text
stringlengths
14
6.51M
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcTCPServerUtils.pas } { File version: 5.03 } { Description: TCP server utilities. } { } { Copyright: Copyright (c) 2007-2021, David J Butler } { All rights reserved. } { This file is licensed under the BSD License. } { See http://www.opensource.org/licenses/bsd-license.php } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2020/07/13 5.01 Initial development: Accept process, Poll process. } { 2020/07/14 5.02 Spin process. } { 2020/07/15 5.03 Test poll and spin processes. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$INCLUDE flcTCP.inc} unit flcTCPServerUtils; interface uses SysUtils, Classes, SyncObjs, flcStdTypes, flcSocketLibSys, flcSocketLib, flcSocket, flcTCPUtils, flcTCPConnection; { TCP Server Error } type ETCPServerError = class(Exception); { TCP Server Thread } type TTCPServerThreadBase = class(TTCPThread) public end; { TCP Server Accept Process } type TTCPServerAcceptProcessSocketEvent = procedure ( const ASocketHandle: TSocket; const AAddr: TSocketAddr; var AAcceptSocket: Boolean) of object; TTCPServerAcceptProcessEvent = procedure of object; TTCPServerAcceptProcess = class private FLock : TCriticalSection; FReadyEvent : TSimpleEvent; FAcceptPaused : Boolean; procedure Lock; procedure Unlock; function GetAcceptPaused: Boolean; procedure SetAcceptPaused(const AAcceptPaused: Boolean); public constructor Create; destructor Destroy; override; procedure Finalise; property AcceptPaused: Boolean read FAcceptPaused write SetAcceptPaused; procedure Execute( const AThread: TTCPServerThreadBase; const AServerSocketHandle: TSocket; const AAcceptSocketProc: TTCPServerAcceptProcessSocketEvent; const AWaitTime: Int32 = 2000); end; { TCP Server Client Base } type TTCPServerClientBase = class private FListPrev : TTCPServerClientBase; FListNext : TTCPServerClientBase; FSocketHandle : TSocketHandle; //FConnection : TTCPConnection; public constructor Create(const ASocketHandle: TSocketHandle); procedure Finalise; virtual; property ListPrev: TTCPServerClientBase read FListPrev write FListPrev; property ListNext: TTCPServerClientBase read FListNext write FListNext; //property Connection: TTCPConnection read FConnection; end; TTCPServerClientBaseArray = array of TTCPServerClientBase; { TCP Server Client List } type TTCPServerClientList = class private FCount : Int32; FFirst : TTCPServerClientBase; FLast : TTCPServerClientBase; public destructor Destroy; override; procedure Finalise; procedure Add(const AClient: TTCPServerClientBase); procedure Remove(const AClient: TTCPServerClientBase); property First: TTCPServerClientBase read FFirst write FFirst; property Last: TTCPServerClientBase read FLast write FLast; property Count: Int32 read FCount; end; { TCP Server Poll List } { Poll list maintains poll buffer used in call to Poll. } type TTCPServerPollList = class private FListLen : Int32; FListUsed : Int32; FListCount : Int32; FFDList : packed array of TPollfd; FClientList : array of TTCPServerClientBase; public constructor Create; destructor Destroy; override; procedure Finalise; function Add(const AClient: TTCPServerClientBase; const ASocketHandle: TSocket): Int32; procedure Remove(const AIdx: Int32); property ClientCount: Integer read FListCount; function GetClientByIndex(const AIdx: Int32): TTCPServerClientBase; {$IFDEF UseInline}inline;{$ENDIF} procedure GetPollBuffer(out APollBufPtr: Pointer; out AItemCount: Int32); {$IFDEF UseInline}inline;{$ENDIF} end; { TCP Server Poll Process } type TTCPServerPollProcessClientPollEvent = procedure ( const AClient: TTCPServerClientBase; var AEventRead, AEventWrite: Boolean) of object; TTCPServerPollProcessClientProcessEvent = procedure ( const AClient: TTCPServerClientBase; const AEventRead, AEventWrite, AEventError: Boolean; out AClientTerminated: Boolean) of object; TTCPServerPollProcessEvent = procedure of object; TTCPServerPollProcess = class private FPollList : TTCPServerPollList; FReadyEvent : TSimpleEvent; procedure RemoveClient(const AIdx: Int32); public constructor Create; destructor Destroy; override; procedure Finalise; procedure Terminate; procedure Execute( const AThread: TTCPServerThreadBase; const APollProcessStartProc: TTCPServerPollProcessEvent; const AClientPollEventProc: TTCPServerPollProcessClientPollEvent; const AClientProcessEventProc: TTCPServerPollProcessClientProcessEvent; const APollProcessCompleteProc: TTCPServerPollProcessEvent; const AWaitTimeMs: Int32); function GetClientCount: Int32; function AddClient(const AClient: TTCPServerClientBase): Int32; end; { TCP Server Spin Process } type TTCPServerSpinProcessClientPollEvent = procedure ( const AClient: TTCPServerClientBase; var AEventRead, AEventWrite: Boolean) of object; TTCPServerSpinProcessClientProcessEvent = procedure ( const AClient: TTCPServerClientBase; const AEventRead, AEventWrite, AEventError: Boolean; out AClientTerminated: Boolean) of object; TTCPServerSpinProcess = class private FLock : TCriticalSection; FReadyEvent : TSimpleEvent; FClientCount : Int32; FClientList : TTCPServerClientBaseArray; FProcessBusy : Boolean; FRemoveAllWait : Boolean; procedure Lock; procedure Unlock; procedure RemoveClient(const AIdx: Int32); public constructor Create; destructor Destroy; override; procedure Terminate; procedure Execute( const AThread: TTCPServerThreadBase; const AClientPollEventProc: TTCPServerSpinProcessClientPollEvent; const AClientProcessEventProc: TTCPServerSpinProcessClientProcessEvent); function GetClientCount: Int32; function AddClient(const AClient: TTCPServerClientBase): Int32; function RemoveClients: TTCPServerClientBaseArray; end; implementation { TTCPServerAcceptProcess } constructor TTCPServerAcceptProcess.Create; begin inherited Create; FLock := TCriticalSection.Create; FReadyEvent := TSimpleEvent.Create; FAcceptPaused := False; FReadyEvent.SetEvent; end; destructor TTCPServerAcceptProcess.Destroy; begin if Assigned(FReadyEvent) then FReadyEvent.SetEvent; FreeAndNil(FReadyEvent); FreeAndNil(FLock); inherited Destroy; end; procedure TTCPServerAcceptProcess.Lock; begin FLock.Acquire; end; procedure TTCPServerAcceptProcess.Unlock; begin FLock.Release; end; procedure TTCPServerAcceptProcess.Finalise; begin Lock; try FAcceptPaused := False; FReadyEvent.SetEvent; finally Unlock; end; end; function TTCPServerAcceptProcess.GetAcceptPaused: Boolean; begin Lock; try Result := FAcceptPaused; finally Unlock; end; end; procedure TTCPServerAcceptProcess.SetAcceptPaused(const AAcceptPaused: Boolean); begin Lock; try if FAcceptPaused = AAcceptPaused then exit; FAcceptPaused := AAcceptPaused; if AAcceptPaused then FReadyEvent.ResetEvent else FReadyEvent.SetEvent; finally Unlock; end; end; procedure TTCPServerAcceptProcess.Execute( const AThread: TTCPServerThreadBase; const AServerSocketHandle: TSocket; const AAcceptSocketProc: TTCPServerAcceptProcessSocketEvent; const AWaitTime: Int32); function IsTerminated: Boolean; begin Result := AThread.Terminated; end; var LEvent : TSimpleEvent; LReady : Boolean; LSelRd : Boolean; LSelWr : Boolean; LSelEr : Boolean; LRetSel : NativeInt; LAccAdr : TSocketAddr; LAccSoc : TSocketHandle; LAccept : Boolean; begin if IsTerminated then exit; LEvent := FReadyEvent; repeat if IsTerminated then exit; LReady := False; case LEvent.WaitFor(AWaitTime) of wrSignaled : LReady := True; wrTimeout : ; wrAbandoned : exit; wrError : if IsTerminated then exit else if not AThread.SleepUnterminated(2000) then exit; end; if IsTerminated then exit; if LReady then begin LSelRd := True; LSelWr := False; LSelEr := True; LRetSel := SocketSelect(AServerSocketHandle, LSelRd, LSelWr, LSelEr, AWaitTime); if IsTerminated then exit; if LRetSel < 0 then begin if not AThread.SleepUnterminated(2000) then exit; end else if (LRetSel = 1) and LSelRd then repeat LAccSoc := SocketAccept(AServerSocketHandle, LAccAdr); if LAccSoc = INVALID_SOCKETHANDLE then break; if IsTerminated then begin SocketClose(LAccSoc); exit; end; LAccept := True; AAcceptSocketProc(LAccSoc, LAccAdr, LAccept); if not LAccept then SocketClose(LAccSoc); if IsTerminated then exit; if GetAcceptPaused then break; if IsTerminated then exit; until False; end; until false; end; { TTCPServerClientBase } constructor TTCPServerClientBase.Create(const ASocketHandle: TSocketHandle); begin inherited Create; FSocketHandle := ASocketHandle; end; procedure TTCPServerClientBase.Finalise; begin FListNext := nil; FListPrev := nil; end; { } { TCP Server Client List } { } { This implementation uses a linked list to avoid any heap operations. } { } destructor TTCPServerClientList.Destroy; begin inherited Destroy; end; procedure TTCPServerClientList.Finalise; begin end; procedure TTCPServerClientList.Add(const AClient: TTCPServerClientBase); var Last : TTCPServerClientBase; begin Assert(Assigned(AClient)); Last := FLast; AClient.FListNext := nil; AClient.FListPrev := Last; if Assigned(Last) then Last.FListNext := AClient else FFirst := AClient; FLast := AClient; Inc(FCount); end; procedure TTCPServerClientList.Remove(const AClient: TTCPServerClientBase); var LPrev, LNext : TTCPServerClientBase; begin Assert(Assigned(AClient)); Assert(FCount > 0); LPrev := AClient.FListPrev; LNext := AClient.FListNext; if Assigned(LPrev) then begin LPrev.FListNext := LNext; AClient.FListPrev := nil; end else begin Assert(FFirst = AClient); FFirst := LNext; end; if Assigned(LNext) then begin LNext.FListPrev := LPrev; AClient.FListNext := nil; end else begin Assert(FLast = AClient); FLast := LPrev; end; Dec(FCount); end; { } { TCP Server Poll List } { } { This implementation aims to: } { - Keep a populated buffer ready for use in calls to Poll (one entry for } { every active client). } { - Avoid heap operations for calls to frequently used operations Add } { and Remove. } { } constructor TTCPServerPollList.Create; begin inherited Create; end; destructor TTCPServerPollList.Destroy; begin inherited Destroy; end; procedure TTCPServerPollList.Finalise; begin FFDList := nil; FClientList := nil; end; function TTCPServerPollList.Add(const AClient: TTCPServerClientBase; const ASocketHandle: TSocket): Int32; var Idx, I, N, L : Int32; begin if FListCount < FListUsed then begin Idx := -1; for I := 0 to FListUsed - 1 do if not Assigned(FClientList[I]) then begin Idx := I; break; end; if Idx < 0 then raise ETCPServerError.Create('Internal error'); end else if FListUsed < FListLen then begin Idx := FListUsed; Inc(FListUsed); end else begin N := FListLen; L := N; if L < 16 then L := 16 else L := L * 2; SetLength(FFDList, L); SetLength(FClientList, L); for I := N to L - 1 do begin FFDList[I].fd := INVALID_SOCKET; FFDList[I].events := 0; FFDList[I].revents := 0; FClientList[I] := nil; end; FListLen := L; Idx := FListUsed; Inc(FListUsed); end; FClientList[Idx] := AClient; FFDList[Idx].fd := ASocketHandle; FFDList[Idx].events := POLLIN or POLLOUT; FFDList[Idx].revents := 0; Inc(FListCount); Result := Idx; end; procedure TTCPServerPollList.Remove(const AIdx: Int32); begin if (AIdx < 0) or (AIdx >= FListUsed) or not Assigned(FClientList[AIdx]) then raise ETCPServerError.Create('Invalid index'); FClientList[AIdx] := nil; FFDList[AIdx].fd := INVALID_SOCKET; FFDList[AIdx].events := 0; FFDList[AIdx].revents := 0; Dec(FListCount); if AIdx = FListUsed - 1 then while (FListUsed > 0) and not Assigned(FClientList[FListUsed - 1]) do Dec(FListUsed); end; function TTCPServerPollList.GetClientByIndex(const AIdx: Int32): TTCPServerClientBase; begin Assert(AIdx >= 0); Assert(AIdx < FListUsed); Result := FClientList[AIdx]; end; procedure TTCPServerPollList.GetPollBuffer(out APollBufPtr: Pointer; out AItemCount: Int32); begin APollBufPtr := Pointer(FFDList); AItemCount := FListUsed; end; { TTCPServerPollProcess } constructor TTCPServerPollProcess.Create; begin inherited Create; FPollList := TTCPServerPollList.Create; FReadyEvent := TSimpleEvent.Create; FReadyEvent.ResetEvent; end; destructor TTCPServerPollProcess.Destroy; begin if Assigned(FReadyEvent) then FReadyEvent.SetEvent; FreeAndNil(FReadyEvent); FreeAndNil(FPollList); inherited Destroy; end; procedure TTCPServerPollProcess.Finalise; begin FPollList.Finalise; end; procedure TTCPServerPollProcess.Terminate; begin FReadyEvent.SetEvent; end; procedure TTCPServerPollProcess.Execute( const AThread: TTCPServerThreadBase; const APollProcessStartProc: TTCPServerPollProcessEvent; const AClientPollEventProc: TTCPServerPollProcessClientPollEvent; const AClientProcessEventProc: TTCPServerPollProcessClientProcessEvent; const APollProcessCompleteProc: TTCPServerPollProcessEvent; const AWaitTimeMs: Int32); function IsTerminated: Boolean; begin Result := AThread.Terminated; end; var LReady : Boolean; LEvent : TSimpleEvent; LPolBuf : Pointer; LPolCnt : Int32; LPolItmP : PPollfd; LPolIdx : Int32; LPolRet : Int32; {$IFDEF OS_WIN32} LPolRep : Int32; {$ENDIF} LCl : TTCPServerClientBase; LClRd : Boolean; LClWr : Boolean; LClEr : Boolean; LClTerm : Boolean; LEvCo : Int16; begin if IsTerminated then exit; LEvent := FReadyEvent; repeat LReady := False; case LEvent.WaitFor(AWaitTimeMs) of wrSignaled : LReady := True; wrTimeout : ; wrAbandoned : raise ETCPServerError.Create('Process abandoned'); wrError : if IsTerminated then exit else if not AThread.SleepUnterminated(2000) then exit; end; if IsTerminated then exit; if LReady then begin APollProcessStartProc; if IsTerminated then exit; FPollList.GetPollBuffer(LPolBuf, LPolCnt); LPolItmP := LPolBuf; for LPolIdx := 0 to LPolCnt - 1 do begin LCl := FPollList.FClientList[LPolIdx]; if not Assigned(LCl) then begin LPolItmP^.fd := INVALID_SOCKET; LPolItmP^.events := 0; LPolItmP^.revents := 0; end else begin LClRd := False; LClWr := False; AClientPollEventProc(LCl, LClRd, LClWr); LEvCo := 0; if LClRd then LEvCo := LEvCo or POLLIN; if LClWr then LEvCo := LEvCo or POLLOUT; LPolItmP^.events := LEvCo; LPolItmP^.revents := 0; if LPolItmP^.fd = INVALID_SOCKET then LPolItmP^.fd := LCl.FSocketHandle; end; Inc(LPolItmP); end; if IsTerminated then exit; {$IFDEF OS_WIN32} // under Win32, WinSock blocks Socket.Write() if Socket.Poll() is active // use loop to reduce write latency LPolRet := 0; for LPolRep := 1 to AWaitTimeMs div 25 do begin LPolRet := SocketsPoll(LPolBuf, LPolCnt, 25); // 25 milliseconds if IsTerminated then exit; if LPolRet <> 0 then break; end; {$ELSE} LPolRet := SocketsPoll(LPolBuf, LPolCnt, AWaitTimeMs); {$ENDIF} if IsTerminated then exit; //// if LPolRet < 0 then //// Check error: log error/warn/alter/critial if LPolRet > 0 then begin LPolItmP := LPolBuf; for LPolIdx := 0 to LPolCnt - 1 do begin LEvCo := LPolItmP^.revents; if (LEvCo <> 0) and (LPolItmP^.fd <> INVALID_SOCKET) then begin LCl := FPollList.FClientList[LPolIdx]; if Assigned(LCl) then begin LClRd := LEvCo and (POLLIN or POLLHUP or POLLERR) <> 0; LClWr := LEvCo and (POLLOUT or POLLHUP or POLLERR) <> 0; LClEr := LEvCo and (POLLHUP or POLLERR) <> 0; AClientProcessEventProc(LCl, LClRd, LClWr, LClEr, LClTerm); if LClTerm then RemoveClient(LPolIdx); if IsTerminated then exit; end; end; Inc(LPolItmP); end; end; APollProcessCompleteProc; if IsTerminated then exit; end; until False; end; function TTCPServerPollProcess.GetClientCount: Int32; begin Result := FPollList.FListCount; end; function TTCPServerPollProcess.AddClient(const AClient: TTCPServerClientBase): Int32; begin Assert(Assigned(AClient)); Result := FPollList.Add(AClient, AClient.FSocketHandle); if FPollList.FListCount = 1 then FReadyEvent.SetEvent; end; procedure TTCPServerPollProcess.RemoveClient(const AIdx: Int32); begin FPollList.Remove(AIdx); if FPollList.FListCount = 0 then FReadyEvent.ResetEvent; end; { TTCPServerSpinProcess } constructor TTCPServerSpinProcess.Create; begin inherited Create; FLock := TCriticalSection.Create; FReadyEvent := TSimpleEvent.Create; FReadyEvent.ResetEvent; FClientCount := 0; end; destructor TTCPServerSpinProcess.Destroy; begin if Assigned(FReadyEvent) then FReadyEvent.SetEvent; FreeAndNil(FReadyEvent); FreeAndNil(FLock); inherited Destroy; end; procedure TTCPServerSpinProcess.Terminate; begin FReadyEvent.SetEvent; end; procedure TTCPServerSpinProcess.Lock; begin FLock.Acquire; end; procedure TTCPServerSpinProcess.Unlock; begin FLock.Release; end; procedure TTCPServerSpinProcess.Execute( const AThread: TTCPServerThreadBase; const AClientPollEventProc: TTCPServerSpinProcessClientPollEvent; const AClientProcessEventProc: TTCPServerSpinProcessClientProcessEvent); function IsTerminated: Boolean; begin Result := AThread.Terminated; end; var LReady : Boolean; LEvent : TSimpleEvent; LSpinIdleCount : Int32; LSpinIdle : Boolean; LSpinIdx : Int32; LClient : TTCPServerClientBase; LSelRet : Int32; LSelRd : Boolean; LSelWr : Boolean; LSelEr : Boolean; LSelTerm : Boolean; LProcCl : Boolean; LRemWait : Boolean; begin if IsTerminated then exit; LReady := False; LEvent := FReadyEvent; repeat // wait until client list not empty case LEvent.WaitFor(2000) of wrSignaled : LReady := True; wrTimeout : ; wrAbandoned : raise ETCPServerError.Create('Process abandoned'); wrError : if IsTerminated then exit else if not AThread.SleepUnterminated(2000) then exit; end; if IsTerminated then exit; if LReady then begin // process until client list empty LSpinIdleCount := 0; repeat Lock; try if IsTerminated then exit; if FClientCount = 0 then break; FProcessBusy := True; finally Unlock; end; try // process clients in client list if Select indidcates event LSpinIdle := True; LSpinIdx := 0; repeat Lock; try if IsTerminated then exit; ////if FRemoveAllWait then ////break; if LSpinIdx >= Length(FClientList) then break; LClient := FClientList[LSpinIdx]; finally Unlock; end; LSelTerm := False; LProcCl := False; if Assigned(LClient) then // 2020/07/15: outside lock begin LSelRd := True; LSelWr := True; LSelEr := True; AClientPollEventProc(LClient, LSelRd, LSelWr); if IsTerminated then exit; LSelRet := SocketSelect(LClient.FSocketHandle, LSelRd, LSelWr, LSelEr, 0); if IsTerminated then exit; LProcCl := (LSelRet = 1) and (LSelRd or LSelWr); end; if LProcCl then // 2020/07/15: outside lock begin LSpinIdle := False; AClientProcessEventProc(LClient, LSelRd, LSelWr, LSelEr, LSelTerm); if IsTerminated then exit; if LSelTerm then RemoveClient(LSpinIdx); end; ////TThread.Yield; // yield for lock to be acquired by other thread if IsTerminated then exit; Inc(LSpinIdx); until False; finally Lock; FProcessBusy := False; LRemWait := FRemoveAllWait; Unlock; end; if LRemWait then begin // 2020/07/25: // yield for lock to be acquired by thread calling RemoveAll {$IFDEF DELPHIXE2_UP} TThread.Yield; {$ENDIF} Sleep(0); if IsTerminated then exit; break; end else // idle spin if LSpinIdle then begin Inc(LSpinIdleCount); if LSpinIdleCount >= 16 then begin {$IFDEF DELPHIXE2_UP} TThread.Yield; {$ENDIF} Sleep(0); end {$IFDEF DELPHIXE2_UP} else if LSpinIdleCount >= 8 then TThread.SpinWait(LSpinIdleCount) {$ENDIF}; if IsTerminated then exit; end else LSpinIdleCount := 0; if IsTerminated then exit; until False; end; until False; end; function TTCPServerSpinProcess.GetClientCount: Int32; begin Lock; try Result := FClientCount; finally Unlock; end; end; function TTCPServerSpinProcess.AddClient(const AClient: TTCPServerClientBase): Int32; var I : Int32; L : Int32; begin Lock; try L := Length(FClientList); I := FClientCount; if L <= I then begin SetLength(FClientList, I + 1); FClientList[I] := AClient; FClientCount := I + 1; Result := I; end else begin Result := -1; for I := 0 to L - 1 do if not Assigned(FClientList[I]) then begin FClientList[I] := AClient; Inc(FClientCount); Result := I; break; end; Assert(Result >= 0); end; if FClientCount = 1 then FReadyEvent.SetEvent; finally Unlock; end; end; function TTCPServerSpinProcess.RemoveClients: TTCPServerClientBaseArray; begin repeat Lock; try if not FProcessBusy then begin FRemoveAllWait := False; if FClientCount = 0 then begin Result := nil; exit; end; Result := FClientList; FClientList := nil; FReadyEvent.ResetEvent; FClientCount := 0; exit; end; FRemoveAllWait := True; finally Unlock; end; {$IFDEF DELPHIXE2_UP} TThread.Yield; {$ENDIF} until False; end; procedure TTCPServerSpinProcess.RemoveClient(const AIdx: Int32); begin Lock; try Assert(AIdx >= 0); Assert(AIdx < FClientCount); Assert(Assigned(FClientList[AIdx])); FClientList[AIdx] := nil; Dec(FClientCount); if FClientCount = 0 then FReadyEvent.ResetEvent; finally Unlock; 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 ClpSecP256K1Field; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpNat256, ClpBigInteger, ClpCryptoLibTypes; type // 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 TSecP256K1Field = class sealed(TObject) strict private const P7 = UInt32($FFFFFFFF); PExt15 = UInt32($FFFFFFFF); PInv33 = UInt32($3D1); class var FP, FPExt, FPExtInv: TCryptoLibUInt32Array; class function GetP: TCryptoLibUInt32Array; static; inline; class constructor SecP256K1Field(); public class procedure Add(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure AddExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure AddOne(const x, z: TCryptoLibUInt32Array); static; inline; class function FromBigInteger(const x: TBigInteger): TCryptoLibUInt32Array; static; inline; class procedure Half(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Multiply(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure MultiplyAddToExt(const x, y, zz: TCryptoLibUInt32Array); static; inline; class procedure Negate(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Reduce(const xx, z: TCryptoLibUInt32Array); static; inline; class procedure Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); static; inline; class procedure Square(const x, z: TCryptoLibUInt32Array); static; inline; class procedure SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); static; inline; class procedure Subtract(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure Twice(const x, z: TCryptoLibUInt32Array); static; inline; class property P: TCryptoLibUInt32Array read GetP; end; implementation { TSecP256K1Field } class constructor TSecP256K1Field.SecP256K1Field; begin FP := TCryptoLibUInt32Array.Create($FFFFFC2F, $FFFFFFFE, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF); FPExt := TCryptoLibUInt32Array.Create($000E90A1, $000007A2, $00000001, $00000000, $00000000, $00000000, $00000000, $00000000, $FFFFF85E, $FFFFFFFD, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF); FPExtInv := TCryptoLibUInt32Array.Create($FFF16F5F, $FFFFF85D, $FFFFFFFE, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $000007A1, $00000002); end; class function TSecP256K1Field.GetP: TCryptoLibUInt32Array; begin result := FP; end; class procedure TSecP256K1Field.Add(const x, y, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat256.Add(x, y, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin TNat.Add33To(8, PInv33, z); end; end; class procedure TSecP256K1Field.AddExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Add(16, xx, yy, zz); if ((c <> 0) or ((zz[15] = PExt15) and (TNat.Gte(16, zz, FPExt)))) then begin if (TNat.AddTo(System.Length(FPExtInv), FPExtInv, zz) <> 0) then begin TNat.IncAt(16, zz, System.Length(FPExtInv)); end; end; end; class procedure TSecP256K1Field.AddOne(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Inc(8, x, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin TNat.Add33To(8, PInv33, z); end; end; class function TSecP256K1Field.FromBigInteger(const x: TBigInteger) : TCryptoLibUInt32Array; var z: TCryptoLibUInt32Array; begin z := TNat256.FromBigInteger(x); if ((z[7] = P7) and (TNat256.Gte(z, FP))) then begin TNat256.SubFrom(FP, z); end; result := z; end; class procedure TSecP256K1Field.Half(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin if ((x[0] and 1) = 0) then begin TNat.ShiftDownBit(8, x, 0, z); end else begin c := TNat256.Add(x, FP, z); TNat.ShiftDownBit(8, z, c); end; end; class procedure TSecP256K1Field.Reduce(const xx, z: TCryptoLibUInt32Array); var cc: UInt64; c: UInt32; begin cc := TNat256.Mul33Add(PInv33, xx, 8, xx, 0, z, 0); c := TNat256.Mul33DWordAdd(PInv33, cc, z, 0); {$IFDEF DEBUG} System.Assert((c = 0) or (c = 1)); {$ENDIF DEBUG} if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin TNat.Add33To(8, PInv33, z); end; end; class procedure TSecP256K1Field.Multiply(const x, y, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat256.CreateExt(); TNat256.Mul(x, y, tt); Reduce(tt, z); end; class procedure TSecP256K1Field.MultiplyAddToExt(const x, y, zz: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat256.MulAddTo(x, y, zz); if ((c <> 0) or ((zz[15] = PExt15) and (TNat.Gte(16, zz, FPExt)))) then begin if (TNat.AddTo(System.Length(FPExtInv), FPExtInv, zz) <> 0) then begin TNat.IncAt(16, zz, System.Length(FPExtInv)); end; end; end; class procedure TSecP256K1Field.Negate(const x, z: TCryptoLibUInt32Array); begin if (TNat256.IsZero(x)) then begin TNat256.Zero(z); end else begin TNat256.Sub(FP, x, z); end; end; class procedure TSecP256K1Field.Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); begin if (((x <> 0) and (TNat256.Mul33WordAdd(PInv33, x, z, 0) <> 0)) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin TNat.Add33To(8, PInv33, z); end; end; class procedure TSecP256K1Field.Square(const x, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat256.CreateExt(); TNat256.Square(x, tt); Reduce(tt, z); end; class procedure TSecP256K1Field.SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin {$IFDEF DEBUG} System.Assert(n > 0); {$ENDIF DEBUG} tt := TNat256.CreateExt(); TNat256.Square(x, tt); Reduce(tt, z); System.Dec(n); while (n > 0) do begin TNat256.Square(z, tt); Reduce(tt, z); System.Dec(n); end; end; class procedure TSecP256K1Field.Subtract(const x, y, z: TCryptoLibUInt32Array); var c: Int32; begin c := TNat256.Sub(x, y, z); if (c <> 0) then begin TNat.Sub33From(8, PInv33, z); end; end; class procedure TSecP256K1Field.SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: Int32; begin c := TNat.Sub(16, xx, yy, zz); if (c <> 0) then begin if (TNat.SubFrom(System.Length(FPExtInv), FPExtInv, zz) <> 0) then begin TNat.DecAt(16, zz, System.Length(FPExtInv)); end; end; end; class procedure TSecP256K1Field.Twice(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.ShiftUpBit(8, x, 0, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin TNat.Add33To(8, PInv33, z); end; end; end.
program LoliBlink; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes { you can add units after this }, GPIO, Crt, SysUtils; var BinaryOut: TBinaryOutput; Status: Boolean; x: Char; begin BinaryOut := TBinaryOutput.Create(nil); try BinaryOut.Address := 17; Status := False; x := #0; WriteLn('A LED at GPIO port 17 should blink now with about 1 Hz'); WriteLn('Press "q" to exit!'); repeat if KeyPressed then x := ReadKey; Status := not Status; BinaryOut.Value := Status; Sleep(500) until x = 'q'; finally BinaryOut.Value := False; BinaryOut.Free end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Core.Blackboard; interface uses System.Rtti, System.Generics.Collections, System.Generics.Defaults; type TB3BlackboardMemory = class(TObjectDictionary<String, TValue>) public destructor Destroy; override; end; (** * The Blackboard is the memory structure required by `BehaviorTree` and its * nodes. It only have 2 public methods: `set` and `get`. These methods works * in 3 different contexts: global, per tree, and per node per tree. * * Suppose you have two different trees controlling a single object with a * single blackboard, then: * * - In the global context, all nodes will access the stored information. * - In per tree context, only nodes sharing the same tree share the stored * information. * - In per node per tree context, the information stored in the blackboard * can only be accessed by the same node that wrote the data. * * The context is selected indirectly by the parameters provided to these * methods, for example: * * // getting/setting variable in global context * blackboard.set('testKey', 'value'); * var value = blackboard.get('testKey'); * * // getting/setting variable in per tree context * blackboard.set('testKey', 'value', tree.id); * var value = blackboard.get('testKey', tree.id); * * // getting/setting variable in per node per tree context * blackboard.set('testKey', 'value', tree.id, node.id); * var value = blackboard.get('testKey', tree.id, node.id); * * Note: Internally, the blackboard store these memories in different * objects, being the global on `_baseMemory`, the per tree on `_treeMemory` * and the per node per tree dynamically create inside the per tree memory * (it is accessed via `_treeMemory[id].nodeMemory`). Avoid to use these * variables manually, use `get` and `set` instead. * * @module b3 * @class Blackboard **) TB3Blackboard = class(TObject) private protected _BaseMemory: TB3BlackboardMemory; _TreeMemory: TB3BlackboardMemory; (** * Internal method to retrieve the tree context memory. If the memory does * not exist, this method creates it. * * @method _getTreeMemory * @param {string} treeScope The id of the tree in scope. * @return {Object} The tree memory. * @protected **) function _getTreeMemory(const TreeScope: String): TB3BlackboardMemory; (** * Internal method to retrieve the node context memory, given the tree * memory. If the memory does not exist, this method creates is. * * @method _getNodeMemory * @param {String} treeMemory the tree memory. * @param {String} nodeScope The id of the node in scope. * @return {Object} The node memory. * @protected **) function _getNodeMemory(const TreeMemory: TB3BlackboardMemory; const NodeScope: String): TB3BlackboardMemory; (** * Internal method to retrieve the context memory. If treeScope and * nodeScope are provided, this method returns the per node per tree * memory. If only the treeScope is provided, it returns the per tree * memory. If no parameter is provided, it returns the global memory. * Notice that, if only nodeScope is provided, this method will still * return the global memory. * * @method _getMemory * @param {String} treeScope The id of the tree scope. * @param {String} nodeScope The id of the node scope. * @return {Object} A memory object. * @protected **) function _getMemory(const TreeScope, NodeScope: String): TB3BlackboardMemory; public (** * Initialization method. * @method initialize * @constructor **) constructor Create; virtual; destructor Destroy; override; (** * Stores a value in the blackboard. If treeScope and nodeScope are * provided, this method will save the value into the per node per tree * memory. If only the treeScope is provided, it will save the value into * the per tree memory. If no parameter is provided, this method will save * the value into the global memory. Notice that, if only nodeScope is * provided (but treeScope not), this method will still save the value into * the global memory. * * @method set * @param {String} key The key to be stored. * @param {String} value The value to be stored. * @param {String} treeScope The tree id if accessing the tree or node * memory. * @param {String} nodeScope The node id if accessing the node memory. **) procedure &Set(const Key: String; Value: TValue; TreeScope: String = ''; NodeScope: String = ''); (** * Retrieves a value in the blackboard. If treeScope and nodeScope are * provided, this method will retrieve the value from the per node per tree * memory. If only the treeScope is provided, it will retrieve the value * from the per tree memory. If no parameter is provided, this method will * retrieve from the global memory. If only nodeScope is provided (but * treeScope not), this method will still try to retrieve from the global * memory. * * @method get * @param {String} key The key to be retrieved. * @param {String} treeScope The tree id if accessing the tree or node * memory. * @param {String} nodeScope The node id if accessing the node memory. * @return {Object} The value stored or undefined. **) function Get(const Key: String; TreeScope: String = ''; NodeScope: String =''): TValue; end; implementation { TB3Blackboard } uses System.SysUtils, Behavior3.Core.BaseNode; constructor TB3Blackboard.Create; begin inherited; _BaseMemory := TB3BlackboardMemory.Create; _TreeMemory := TB3BlackboardMemory.Create; end; destructor TB3Blackboard.Destroy; begin _TreeMemory.Free; _BaseMemory.Free; inherited; end; function TB3Blackboard._GetTreeMemory(const TreeScope: String): TB3BlackboardMemory; var Memory: TB3BlackboardMemory; Value: TValue; begin if not _TreeMemory.TryGetValue(TreeScope, Value) then begin Memory := TB3BlackboardMemory.Create; Memory.Add('openNodes', TB3BaseNodeList.Create(False)); Memory.Add('nodeMemory', TB3BlackboardMemory.Create); _TreeMemory.Add(TreeScope, Memory); end else Memory := Value.AsObject as TB3BlackboardMemory; Result := Memory; end; function TB3Blackboard._GetNodeMemory(const TreeMemory: TB3BlackboardMemory; const NodeScope: String): TB3BlackboardMemory; var NodeMemory, Memory: TB3BlackboardMemory; Value: TValue; begin NodeMemory := TreeMemory['nodeMemory'].AsObject as TB3BlackboardMemory; if not NodeMemory.TryGetValue(NodeScope, Value) then begin Memory := TB3BlackboardMemory.Create; NodeMemory.Add(NodeScope, Memory); end else Memory := Value.AsObject as TB3BlackboardMemory; Result := Memory; end; function TB3Blackboard._GetMemory(const TreeScope, NodeScope: String): TB3BlackboardMemory; var Memory: TB3BlackboardMemory; begin Memory := _BaseMemory; if not TreeScope.IsEmpty then begin Memory := _GetTreeMemory(TreeScope); if not NodeScope.IsEmpty then Memory := _GetNodememory(Memory, NodeScope); end; Result := Memory; end; procedure TB3Blackboard.&Set(const Key: String; Value: TValue; TreeScope: String = ''; NodeScope: String = ''); var Memory: TB3BlackboardMemory; begin Memory := _GetMemory(TreeScope, NodeScope); Memory.AddOrSetValue(Key, Value); end; function TB3Blackboard.Get(const Key: String; TreeScope: String = ''; NodeScope: String = ''): TValue; var Memory: TB3BlackboardMemory; begin Memory := _GetMemory(TreeScope, NodeScope); Memory.TryGetValue(Key, Result); end; { TB3BlackboardMemory } destructor TB3BlackboardMemory.Destroy; var Item: TPair<String, TValue>; begin for Item in Self do if (Item.Value.IsObject) and (Item.Value.AsObject.InheritsFrom(TB3BlackboardMemory)) then Item.Value.AsObject.Free; inherited; end; end.
unit UnitMain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TfrmMain } TfrmMain = class(TForm) btnSubmit: TButton; edMin: TEdit; edHour: TEdit; Label1: TLabel; Label2: TLabel; lblCorrect: TLabel; procedure btnSubmitClick(Sender: TObject); procedure edHourKeyPress(Sender: TObject; var Key: char); procedure edMinKeyPress(Sender: TObject; var Key: char); procedure FormPaint(Sender: TObject); private { private declarations } public { public declarations } hour: integer; min: integer; correct: integer; question: integer; procedure CheckAnswer; procedure DrawClock; procedure GetHourMin; end; var frmMain: TfrmMain; implementation {$R *.lfm} { TfrmMain } procedure TfrmMain.CheckAnswer; begin if (hour = StrToInt(edHour.Text)) and (min = StrToInt(edMin.Text)) then begin correct := correct + 1; end else begin if min = 0 then ShowMessage('The Time is: ' + IntToStr(hour) + ':00') else if min = 5 then ShowMessage('The Time is: ' + IntToStr(hour) + ':05') else ShowMessage('The Time is: ' + IntToStr(hour) + ':' + IntToStr(min)); end; question := question + 1; lblCorrect.Caption := 'Correct: ' + IntToStr(correct) + '/' + IntToStr(question); edMin.Clear; edHour.Clear; edHour.SetFocus; refresh; end; procedure TfrmMain.DrawClock; var AdjHours: real; const Pie = 3.14; begin { draw empty clock } Canvas.Pen.Color := clBlack; Canvas.Pen.Width := 10; Canvas.Brush.Color := clLtGray; Canvas.Ellipse(50,50,500,500); Canvas.Font.Size := 30; Canvas.TextOut(254, 59, '12'); Canvas.TextOut(362, 83, '1'); Canvas.TextOut(425, 153, '2'); Canvas.TextOut(457, 250, '3'); Canvas.TextOut(425, 347, '4'); Canvas.TextOut(362, 417, '5'); Canvas.TextOut(260, 440, '6'); Canvas.TextOut(165, 417, '7'); Canvas.TextOut(95, 347, '8'); Canvas.TextOut(70, 250, '9'); Canvas.TextOut(95, 153, '10'); Canvas.TextOut(165, 83, '11'); { draw hour hand } AdjHours := hour + min / 60; Canvas.Pen.Color := clRed; Canvas.Pen.Width := 25; Canvas.Line(275, 275, trunc(130 * cos((Pi) / 180 * (30 * AdjHours - 90)) + 275), trunc(135 * sin((Pi) / 180 * (30 * AdjHours - 90)) + 275)); { draw minute hand } Canvas.Pen.Color := clGreen; Canvas.Pen.Width := 10; Canvas.Line(275, 275, trunc(175 * cos((Pi) / 180 * (6 * min - 90)) + 275), trunc(160 * sin((Pi) / 180 * (6 * min - 90)) + 275)); { draw cirle in middle } Canvas.Pen.Color := clBlack; Canvas.Pen.Width := 20; Canvas.Ellipse(265, 265, 285, 285); end; procedure TfrmMain.GetHourMin; begin randomize; hour := random(12) + 1; randomize; repeat min := random(60); until min mod 5 = 0; end; procedure TfrmMain.btnSubmitClick(Sender: TObject); begin if (edHour.Text <> '') and (edMin.Text <> '') then CheckAnswer; refresh; end; procedure TfrmMain.edHourKeyPress(Sender: TObject; var Key: char); begin if (edHour.Text <> '') and (edMin.Text <> '') and (Key = Chr(13)) then begin Key := ' '; CheckAnswer; end; end; procedure TfrmMain.edMinKeyPress(Sender: TObject; var Key: char); begin if (edHour.Text <> '') and (edMin.Text <> '') and (Key = Chr(13)) then begin Key := ' '; CheckAnswer; end; end; procedure TfrmMain.FormPaint(Sender: TObject); begin GetHourMin; DrawClock; end; end.
unit Math; interface (* ---------------------- *) (* --------------------------- *) (* MATH FUNCTIONS TP-UNIT *) (* LOGARITHM, POWERS AND ROOTS *) (* ---------------------- *) (* --------------------------- *) function Power (x,y:real):real; (* x to the power of y *) function Root (x,y:real):real; (* the y'th root of x *) function Log (x:real):real; (* Logarithm of x with base 10 *) function Antilog (x:real):real; (* 10^x *) function LogBase (x,y:real):real; (* Logarithm of x with base y *) (* --------------------------- *) (* TRIGONOMETRIC FUNCTIONS *) (* --------------------------- *) function D2R (x:real):real; (* Degrees to radians *) function R2D (x:real):real; (* Radians to degrees *) function Tan (x:real):real; (* Tangent of x *) function ArcSin (x:real):real; (* Arc sine of x *) function ArcCos (x:real):real; (* Arc cosine of x *) (* --------------------------- *) (* HYPERBOLIC FUNCTIONS *) (* --------------------------- *) function Sinh (x:real):real; (* Sine hyperbolic of x *) function Cosh (x:real):real; (* Cosine hyperbolic of x *) function Tanh (x:real):real; (* Tangent hyperbolic of x *) function ArSinh (x:real):real; (* Ar sine hyperbolic of x *) function ArCosh (x:real):real; (* Ar cosine hyperbolic of x *) function ArTanh (x:real):real; (* Ar tangent hyperbolic of x *) (* --------------------------- *) (* OTHER FUNCTIONS *) (* --------------------------- *) function Fac (n:integer):real; (* Factorial of n (n!) *) function Frac (x:real):real; (* Fraction of x *) function Sgn (x:real):integer; (* Sign of x <0=-1 0=0 >0=1 *) implementation function Power; begin if x=0.0 then Power:=1.0 else Power:=exp(y*ln(abs(x))); if (x<0.0) and (frac(abs(y))=0.0) and (odd(round(y))) then Power:=-exp(y*ln(-x)); end; function Root; begin Root:=exp(1.0/y*ln(abs(x))); end; function Log; begin Log:=ln(x)/ln(10.0); end; function Antilog; begin if x=0.0 then Antilog:=1.0 else Antilog:=exp(x*ln(10.0)); end; function LogBase; begin LogBase:=ln(x)/ln(y); end; function D2R; begin D2R:=x*pi/180.0; end; function R2D; begin R2D:=x*180.0/pi; end; function Tan; begin tan:=sin(x)/cos(x); end; function ArcSin; begin if abs(x)=1.0 then ArcSin:=pi/2.0 else ArcSin:=arctan(x/sqrt(1.0-x*x)); end; function ArcCos; begin if x=0.0 then ArcCos:=pi/2.0; if x>0.0 then ArcCos:=arctan(sqrt(1.0-x*x)/x); if x<0.0 then ArcCos:=arctan(sqrt(1.0-x*x)/x)+pi; end; function Sinh; begin Sinh:=(exp(x)-exp(-x))/2.0; end; function Cosh; begin Cosh:=(exp(x)+exp(-x))/2.0; end; function Tanh; begin Tanh:=(exp(x)-exp(-x))/(exp(x)+exp(-x)); end; function ArSinh; begin ArSinh:=ln(x+sqrt(x*x+1.0)); end; function ArCosh; begin ArCosh:=ln(x+sqrt(x*x-1.0)); end; function ArTanh; begin ArTanh:=ln((x+1.0)/(1.0-x))/2.0; end; function Fac; var hlpvar : integer; hlpvarr : real; begin hlpvarr:=1.0; for hlpvar:=2 to n do hlpvarr:=hlpvarr*hlpvar; fac:=hlpvarr; end; function Frac; begin Frac:=x-int(x); end; function Sgn; begin Sgn:=0; if x>0.0 then Sgn:=1; if x<0.0 then Sgn:=-1; end; end.
unit UpdateRoutesCustomFieldsUnit; interface uses SysUtils, BaseExampleUnit, CommonTypesUnit; type TUpdateRoutesCustomFields = class(TBaseExample) public procedure Execute(RouteId: String; RouteDestinationId: integer); end; implementation procedure TUpdateRoutesCustomFields.Execute(RouteId: String; RouteDestinationId: integer); var ErrorString: String; CustomFields: TListStringPair; begin CustomFields := TListStringPair.Create; try CustomFields.Add(TStringPair.Create('animal', 'lion')); CustomFields.Add(TStringPair.Create('form', 'rectangle')); Route4MeManager.Route.UpdateCustomFields(RouteId, RouteDestinationId, CustomFields, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('UpdateCustomFields executed successfully'); WriteLn(Format('Route ID: %s', [RouteId])); end else WriteLn(Format('UpdateCustomFields error: %s', [ErrorString])); finally FreeAndNil(CustomFields); end; end; end.
unit RemoveAddressBookContactsRequestUnit; interface uses REST.Json.Types, System.Generics.Collections, GenericParametersUnit; type TRemoveAddressBookContactsRequest = class(TGenericParameters) private [JSONName('address_ids')] FAddressIds: TArray<integer>; public property AddressIds: TArray<integer> read FAddressIds write FAddressIds; end; implementation end.
unit uSceneMenu; interface uses uScene, Graphics, uGraph, uButton, uSceneAbout, uResFont, uSceneConfig, uSceneHelp; type TMenuItem = (miNone, miTavern, miHelp, miConfig, miAbout, miQuit); const MenuCaption: array [miTavern..miQuit] of string = ('Таверна', 'Справка', 'Опции', 'Авторы', 'Выход'); type TSceneMenu = class(TSceneCustom) private FButton: array [miTavern..miQuit] of TButton; FMenuPos: TMenuItem; FLogo: TBitmap; FResFont: TResFont; FBack: TBitmap; FGraph, FGUI: TGraph; FIsLoad: Boolean; FSceneAbout: TSceneAbout; FSceneConfig: TSceneConfig; procedure Load; procedure Use(I: TMenuItem); procedure DrawMenuButtons; public //** Конструктор. constructor Create; destructor Destroy; override; procedure Draw(); override; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; procedure Start(); end; var SceneMenu: TSceneMenu; implementation uses Windows, SysUtils, uMain, uSCR, uUtils, uSaveLoad, uSounds, uGUIBorder, uSceneSellect, uSceneRace, uIni, uMusicMenu, uVars; { TMenuScene } procedure TSceneMenu.Use(I: TMenuItem); var k: integer; begin Sound.PlayClick(); FMenuPos := I; case FMenuPos of miTavern: Start(); miHelp: begin IsHelp := True; SceneManager.SetScene(SceneHelp); end; miConfig: begin if not Assigned(FSceneConfig) then FSceneConfig := TSceneConfig.Create; SceneManager.SetScene(FSceneConfig); end; miAbout: begin if not Assigned(FSceneAbout) then FSceneAbout := TSceneAbout.Create; SceneManager.SetScene(FSceneAbout); end; miQuit: fMain.Close; end; end; function TSceneMenu.Click(Button: TMouseBtn): Boolean; var I: TMenuItem; begin Result := True; for I := miTavern to miQuit do if FButton[I].MouseOver then Use(I); end; constructor TSceneMenu.Create; begin FIsLoad := False; FMenuPos := miTavern; FGUI := TGraph.Create(Path + 'Data\Images\GUI\'); FGraph := TGraph.Create(Path + 'Data\Images\Screens\'); FResFont := TResFont.Create; FResFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); end; procedure TSceneMenu.Draw; begin IsMenu := True; if not FIsLoad then Load; DrawMenuButtons; SCR.BG.Canvas.Draw(0, 0, FLogo); end; function TSceneMenu.Keys(var Key: Word): Boolean; begin TransKeys(Key); Result := True; case Key of 13: Use(FMenuPos); 27: if IsGame then begin IsMenu := False; Sound.PlayClick; SceneManager.Clear; fMain.RefreshBox; end; 38, 40: begin Inc(FMenuPos, Key - 39); if (FMenuPos < miTavern) then FMenuPos := miQuit; if (FMenuPos > miQuit) then FMenuPos := miTavern; DrawMenuButtons; SceneManager.Draw; Sound.PlayClick(4); end; end; end; destructor TSceneMenu.Destroy; var I: TMenuItem; begin for I := miTavern to miQuit do FButton[I].Free; FreeAndNil(FSceneConfig); FreeAndNil(FSceneAbout); FResFont.Free; FGraph.Free; FLogo.Free; FBack.Free; FGUI.Free; inherited; end; procedure TSceneMenu.Load; var I: TMenuItem; P: Integer; begin FIsLoad := True; FLogo := Graphics.TBitmap.Create; FGraph.LoadImage('Menu.jpg', FLogo); GUIBorder.Make(FLogo); FLogo.Canvas.Brush.Style := bsClear; FBack := Graphics.TBitmap.Create; FGUI.LoadImage('BG.bmp', FBack); FBack.Height := (Ord(miQuit) - 1) * 60 + 90; FBack.Width := 240; GUIBorder.Make(FBack); P := 300 - (FBack.Height div 2); FLogo.Canvas.Draw(530, P, FBack); FGraph.DrawText('v.' + HoDVersion, FLogo, 15, 570, FResFont.FontName, 12, $0028485B); for I := miTavern to miQuit do FButton[I] := TButton.Create(550, P + 20 + ((Ord(I) - 1) * 60), FLogo.Canvas, MenuCaption[I]); end; function TSceneMenu.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; var I: TMenuItem; begin Result := False; for I := miTavern to miQuit do FButton[I].MouseDown(X, Y); SceneManager.Draw; end; function TSceneMenu.MouseMove(X, Y: Integer): Boolean; var I: TMenuItem; begin Result := False; for I := miTavern to miQuit do FButton[I].Draw; SceneManager.Draw; end; procedure TSceneMenu.DrawMenuButtons; var I: TMenuItem; begin for I := miTavern to miQuit do begin FButton[I].Sellected := (I = FMenuPos); FButton[I].Draw; end; end; procedure TSceneMenu.Start; begin PCName := ''; SceneSellect.LoadMenu; if (GetSavePCCount = 0) then SceneManager.SetScene(SceneRace) else SceneManager.SetScene(SceneSellect); end; initialization SceneMenu := TSceneMenu.Create; finalization SceneMenu.Free; end.
{******************************************************************************* * * * TksSpeedButton - TSpeedButton with iOS style badge * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksSpeedButton; interface {$I ksComponents.inc} uses Classes, FMX.StdCtrls, FMX.Graphics, ksControlBadge, ksTypes; type [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksSpeedButton = class(TksBaseSpeedButton) private FBadge: TksControlBadge; procedure SetBadge(Value: TksBadgeProperties); function GetBadge: TksBadgeProperties; protected procedure Resize; override; function GetDefaultStyleLookupName: string; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Badge: TksBadgeProperties read GetBadge write SetBadge; end; procedure Register; implementation uses Math; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksSpeedButton]); end; { TksSpeedButton } constructor TksSpeedButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FBadge := TksControlBadge.Create(Self); //StyledSettings := []; AddObject(FBadge); end; destructor TksSpeedButton.Destroy; begin {$IFDEF NEXTGEN} FBadge.DisposeOf; {$ELSE} FBadge.Free; {$ENDIF} inherited; end; function TksSpeedButton.GetBadge: TksBadgeProperties; begin Result := FBadge.Properties; end; procedure TksSpeedButton.Resize; begin inherited; FBadge.Position.X := (Width - FBadge.Width) - (Width * 0.1); end; function TksSpeedButton.GetDefaultStyleLookupName: string; begin Result := GenerateStyleName(TSpeedButton.ClassName); end; procedure TksSpeedButton.SetBadge(Value: TksBadgeProperties); begin FBadge.Properties.Assign(Value); end; initialization Classes.RegisterClass(TksSpeedButton); end.
Program ProgramaVector; Const DimF = 10; Type vector = Array [ 1..DimF] of integer; procedure crearvector(var v:vector; dimf:integer); var i:integer; begin randomize; for i:=1 to dimf do begin V[i]:=random(100); end; end; procedure imprimirvector (V:vector; diml:integer); var i:integer; begin writeln('Nros almacenados'); writeln('----------------------------------------------------------'); for i:=1 to diml do begin write( '| ', v[i], ' |'); end; writeln(' '); writeln('----------------------------------------------------------'); end; Procedure BorrarElemento (var v:vector; var dimL:integer; valor: integer; var exito: boolean); var pos: integer; i:integer; begin exito:= false; pos:=1; while (v[pos] <> valor) and (pos<DimL) do begin pos:=pos+1; end; if pos<DimL then begin exito:= true; for i:=pos to (dimL-1) do v[i]:= v[i+1]; dimL:= dimL - 1; end; end; Procedure AGREGAR (var v: vector; var dimL:integer; elem: integer; var exito : boolean); Begin If (dimL < dimF) then begin dimL:= dimL+1; v [dimL]:= elem; exito := true end else exito := false; end; procedure insercion (diml: integer; var v:vector); var i:integer; j: integer; aux:integer; begin for i:=2 to diml do begin aux:=v[i]; j:= i-1; while(j > 0) and (v[j] > aux) do begin v[j+1]:= v[j]; j:= j - 1 ; end; v[j+1]:=aux; end; end; var vector1: vector; Dimlogica: integer; x:integer; exito:boolean; Begin crearvector(vector1, DimF); Dimlogica:=DimF; imprimirvector(vector1,Dimlogica); insercion (Dimlogica,vector1); imprimirvector(vector1,Dimlogica); writeln('ingrese numero a borrar del vector '); read(x); BorrarElemento (vector1, Dimlogica, x , exito); imprimirvector(vector1,Dimlogica); readln; read(x); End.
unit QuickView; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Win95FileViewers, WinEnum, DragDrop; type TQuickView = class( TCustomControl ) published property Align; property Enabled; property ParentShowHint; property ShowHint; property Visible; protected fFileName : string; procedure SetFileName( aFileName : string ); published property FileName : string read fFileName write SetFileName; private fFileViewer : IFileViewer; fTimeOut : integer; procedure SetTimeOut( aTimeOut : integer ); public property FileViewer : IFileViewer read fFileViewer; property TimeOut : integer read fTimeOut write SetTimeOut; public constructor Create( aOwner : TComponent ); override; destructor Destroy; override; private ViewerSite : IFileViewerSite; WinHandle : HWND; WinClass : string; WinMenu : HMENU; ViewHandle : HWND; ViewRect : TRect; ViewParent : HWND; ShowInfo : TFileViewerShowInfo; procedure ReleaseFileViewer; function QuickViewWindow : HWND; procedure PatchQuickViewWindow; procedure WMSize( var Message : TWMSize ); message WM_SIZE; end; // Component registration procedure Register; implementation function FillShowInfo( Control : TWinControl; var ShowInfo : TFileViewerShowInfo ) : PFileViewerShowInfo; begin with ShowInfo do begin Size := sizeof(ShowInfo ); Owner := Control.Handle; Show := SW_HIDE; Flags := FVSIF_CANVIEWIT or FVSIF_PINNED; with Control do begin ShowInfo.Rect.TopLeft := ClientToScreen( Point( 0, 0 ) ); ShowInfo.Rect.BottomRight := ClientToScreen( Point( Width, Height ) ); end; UnkRel := nil; end; Result := @ShowInfo; end; procedure ShowViewer( var FileViewer : IFileViewer; ShowInfo : PFileViewerShowInfo ); begin if FileViewer <> nil then begin FileViewer.Show( ShowInfo ); FileViewer.Release; FileViewer := nil; end; end; // TQuickView procedure TQuickView.WMSize( var Message : TWMSize ); begin inherited; if not (csLoading in ComponentState ) then with Message do SetWindowPos( ViewHandle, HWND_TOP, 0, 0, Width, Height, SWP_NOACTIVATE ); end; constructor TQuickView.Create( aOwner : TComponent ); begin inherited; Width := 60; Height := 60; Caption := ''; TimeOut := 60 * 1000; end; destructor TQuickView.Destroy; begin ReleaseFileViewer; inherited; end; procedure TQuickView.ReleaseFileViewer; var ThreadId : integer; begin if fFileViewer <> nil then begin Windows.SetParent( ViewHandle, ViewParent ); with ViewRect do SetWindowPos( ViewHandle, HWND_TOP, Left, Top, Right, Bottom, SWP_NOREDRAW ); SetMenu( WinHandle, WinMenu ); ThreadId := GetWindowThreadProcessId( WinHandle, nil ); if WinClass <> 'FileViewer' then PostThreadMessage( ThreadId, WM_QUIT, 0, 0 ); fFileViewer.Release; fFileViewer := nil; end; end; procedure TQuickView.SetTimeOut( aTimeOut : integer ); const MinTimeOut = 30 * 1000; begin if aTimeOut > MinTimeOut then fTimeOut := aTimeOut else fTimeOut := MinTimeOut; end; function TQuickView.QuickViewWindow : HWND; var StartTime : integer; begin //Result := ViewerSite.WinHandle; Result := FindWindowByCaption( FileName, ['FileViewer'], WinClass ); if Result = 0 then begin ShowViewer( fFileViewer, FillShowInfo( Self, ShowInfo ) ); StartTime := GetTickCount; repeat Result := FindWindowByCaption( FileName, ['OIWin95Frame'], WinClass ); until (Result <> 0 ) or (GetTickCount - StartTime > TimeOut ); end; end; procedure TQuickView.PatchQuickViewWindow; const StyleHidden = WS_CLIPSIBLINGS or WS_GROUP; StyleShown = StyleHidden or WS_VISIBLE or WS_CHILDWINDOW; ExStyle = WS_EX_LEFT or WS_EX_LTRREADING or WS_EX_RIGHTSCROLLBAR; begin SetWindowLong( WinHandle, GWL_STYLE, StyleHidden ); SetWindowLong( WinHandle, GWL_EXSTYLE, ExStyle ); WinMenu := GetMenu( WinHandle ); SetMenu( WinHandle, 0 ); ViewHandle := FindViewerClient( WinHandle ); GetWindowRect( ViewHandle, ViewRect ); ViewParent := Windows.GetParent( ViewHandle ); Windows.SetParent( ViewHandle, Handle ); SetWindowLong( ViewHandle, GWL_STYLE, StyleShown ); SetWindowPos( ViewHandle, HWND_TOP, 0, 0, ClientWidth, ClientHeight, SWP_NOACTIVATE ); Windows.ShowWindow( WinHandle, SW_HIDE ); end; procedure TQuickView.SetFileName( aFileName : string ); begin fFileName := ExpandFileName( aFileName ); if fFileName = '' then ReleaseFileViewer else if ( FileViewer = nil ) or ( WinHandle = 0 ) or ( not DropFile( WinHandle, fFileName ) ) // Fake a drag&drop on QuickView Window then // Create file viewer begin ReleaseFileViewer; //if ViewerSite = nil // then ViewerSite := IFileViewerSite.Create(TForm(Owner ).Handle ); fFileViewer := GetFileViewer( FileName, ViewerSite ); if fFileViewer <> nil then begin WinHandle := QuickViewWindow; if WinHandle <> 0 then PatchQuickViewWindow else Caption := 'Could not attach to QuickView window'; end else Caption := 'Could not find a viewer for ''' + FileName + ''''; end; end; // Registration procedure Register; begin RegisterComponents('Merchise', [TQuickView] ); end; end.
program unisciFile; uses sysUtils,crt; const PATHFONE='fileOne.txt'; PATHFTWO='fileTwo.txt'; DMAX = 50; type Tfile = text; Tpila = record corpo:array[1..DMAX] of integer; top:integer; end; var fileOne,fileTwo:Tfile; pila:Tpila; procedure initFile(var fileOne:Tfile; var fileTwo:Tfile); begin assign(fileOne,PATHFONE); assign(fileTwo,PATHFTWO); if not fileExists(PATHFONE) then begin rewrite(fileOne); close(fileOne); end; if not fileExists(PATHFTWO) then begin rewrite(fileTwo); close(fileTwo); end; end; procedure push(var pila:Tpila; num:integer); begin pila.top:=pila.top+1; pila.corpo[pila.top] := num; end; procedure unisci(var fileOne:Tfile; var fileTwo:Tfile; var pila:Tpila); var numa, numb: integer; begin reset(fileOne); reset(fileTwo); pila.top:=0; readln(fileOne, numa); readln(fileTwo, numb); while not eof(fileOne) and not eof(fileTwo) do begin if numa > numb then push(pila, numb) else push(pila, numa); end; writeln('asa'); if eof(fileOne) then while not eof(fileTwo) do begin readln(fileTwo, numb); push(pila, numb); end else while not eof(fileOne) do begin readln(fileOne, numa); push(pila, numa); end; close(fileOne); close(fileTwo); end; procedure stampa(pila:Tpila); var i:byte; begin for i:=pila.top downto 1 do write(pila.corpo[i], ' '); end; begin writeln('Inizio...'); initFile(fileOne,fileTwo); writeln('Ho sistemato i file...'); unisci(fileOne,fileTwo,pila); writeln('Ho unito in una pila i file...'); writeln('Ecco la pila: '); stampa(pila); end.
unit Rule_AVEDEV; interface uses BaseRule, BaseRuleData; (*// AVEDEV 平均绝对偏差 Mean absolute deviation, MAD AVEDEV 含义:平均绝对偏差。 用法:AVEDEV(X,N) 这个指标 没有前向指标做参考 可以 使用 倒推的方法 //*) type TRule_AVEDEV = class(TBaseRule) protected fParamN: Word; fFloatRet: PArrayDouble; function Get_AVEDEV_ValueF(AIndex: integer): double; function GetParamN: Word; procedure SetParamN(const Value: Word); procedure ComputeFloat; public constructor Create(ADataType: TRuleDataType = dtDouble); override; destructor Destroy; override; procedure Execute; override; procedure Clear; override; property ValueF[AIndex: integer]: double read Get_AVEDEV_ValueF; property ParamN: Word read GetParamN write SetParamN; end; implementation { TRule_AVEDEV } constructor TRule_AVEDEV.Create(ADataType: TRuleDataType = dtDouble); begin inherited; fParamN := 20; fFloatRet := nil; end; destructor TRule_AVEDEV.Destroy; begin Clear; inherited; end; procedure TRule_AVEDEV.Execute; begin Clear; if Assigned(OnGetDataLength) then begin fBaseRuleData.DataLength := OnGetDataLength; if fBaseRuleData.DataLength > 0 then begin case fBaseRuleData.DataType of dtDouble: begin ComputeFloat; end; end; end; end; end; procedure TRule_AVEDEV.Clear; begin CheckInArrayDouble(fFloatRet); fBaseRuleData.DataLength := 0; end; procedure TRule_AVEDEV.ComputeFloat; var tmpFloat_Origin: array of double; tmpFloat_Mean: array of double; //tmpInt64_Origin: array of int64; //tmpInt64_Mean: array of double; i: integer; tmpCounter: integer; tmpDouble: Double; begin (*// Mean = Average(Price, Length); For i = 0 to Length - 1 { SumValue = SumValue + Abs(Price[i] - Mean); } Return SumValue / Length; //*) if Assigned(OnGetDataF) then begin if fFloatRet = nil then fFloatRet := CheckOutArrayDouble; SetArrayDoubleLength(fFloatRet, fBaseRuleData.DataLength); SetLength(tmpFloat_Origin, fBaseRuleData.DataLength); SetLength(tmpFloat_Mean, fBaseRuleData.DataLength); for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpFloat_Origin[i] := OnGetDataF(i); tmpDouble := tmpFloat_Origin[i]; tmpCounter := fParamN - 1; while tmpCounter > 0 do begin if i > tmpCounter - 1 then begin tmpDouble := tmpDouble + tmpFloat_Origin[i - tmpCounter]; end; Dec(tmpCounter); end; if fParamN > 1 then begin if i > fParamN - 1 then begin tmpDouble := tmpDouble / fParamN; end else begin tmpDouble := tmpDouble / (i + 1); end; end; tmpFloat_Mean[i] := tmpDouble; // ========================================== tmpCounter := fParamN - 1; tmpDouble := 0; while tmpCounter > 0 do begin if i > tmpCounter - 1 then begin tmpDouble := tmpDouble + Abs(tmpFloat_Origin[i - tmpCounter] - tmpFloat_Mean[i]); end; Dec(tmpCounter); end; if 1 < fParamN then begin if i > fParamN - 1 then begin tmpDouble := tmpDouble / fParamN; end else begin tmpDouble := tmpDouble / (i + 1); end; end; // ========================================== SetArrayDoubleValue(fFloatRet, i, tmpDouble); end; end; end; function TRule_AVEDEV.GetParamN: Word; begin Result := fParamN; end; procedure TRule_AVEDEV.SetParamN(const Value: Word); begin if Value > 0 then fParamN := Value; end; function TRule_AVEDEV.Get_AVEDEV_ValueF(AIndex: integer): double; begin Result := 0; if fBaseRuleData.DataType = dtDouble then begin if fFloatRet <> nil then begin Result := GetArrayDoubleValue(fFloatRet, AIndex); end; end; end; end.
//Exercicio 21:Faça um algoritmo que leia o ano de nascimento de uma pessoa, calcule e mostre sua idade e, também, //verifique e mostre se ela já tem idade para votar (16 anos ou mais) e para obter a carteira de habilitação //(18 anos ou mais). { Solução em Portugol Algoritmo Exercicio 21; Const ano_atual = 2020; Var ano_nascimento,idade: inteiro; Inicio exiba("Programa que determina se a pessoa pode dirigir e/ou votar."); exiba("Digite o seu ano de nascimento: "); leia(ano_nascimento); idade <- ano_atual - ano_nascimento; exiba("Você tem ",idade," anos."); se(idade < 16) então exiba("Você não pode votar.") senão exiba("Você já pode votar."); fimse; se(idade < 18) então exiba("Você não pode obter a carteira de habilitação.") senão exiba("Você pode obter a carteira de habilitação."); fimse; Fim. } // Solução em Pascal Program Exercicio21; uses crt; const ano_atual = 2020; var ano_nascimento,idade: integer; begin clrscr; writeln('Programa que determina se a pessoa pode dirigir e/ou votar.'); writeln('Digite o seu ano de nascimento: '); readln(ano_nascimento); idade := ano_atual - ano_nascimento; writeln('Você tem ',idade,' anos.'); if(idade < 16) then writeln('Você não pode votar.') else writeln('Você já pode votar.'); if(idade < 18) then writeln('Você não pode obter a carteira de habilitação.') else writeln('Você pode obter a carteira de habilitação.'); repeat until keypressed; end.
unit Model.PlanilhaRoteirosExpressas; interface uses Generics.Collections, System.Classes, System.SysUtils; type TPlanilhaRoteiroExpressas = class private FLogradouro: String; FZona: String; FBairro: String; FPrazo: String; FCEPFinal: String; FCEPInicial: String; FCCEP5: String; FTipo: integer; FMensagem: String; FPlanilha: TObjectList<TPlanilhaRoteiroExpressas>; public property CEPInicial: String read FCEPInicial write FCEPInicial; property CEPFinal: String read FCEPFinal write FCEPFinal; property Prazo: String read FPrazo write FPrazo; property Zona: String read FZona write FZona; property Logradouro: String read FLogradouro write FLogradouro; property Bairro: String read FBairro write FBairro; property CCEP5: String read FCCEP5 write FCCEP5; property Tipo: Integer read FTipo write FTipo; property Planilha: TObjectList<TPlanilhaRoteiroExpressas> read FPlanilha write FPlanilha; property Mensagem: String read FMensagem write FMensagem; function GetPlanilha(sFile: String): Boolean; end; implementation { TPlanilhaRoteiroExpressas } function TPlanilhaRoteiroExpressas.GetPlanilha(sFile: String): Boolean; var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; i, iTipo : Integer; sValor : String; begin try Result := False; FPlanilha := TObjectList<TPlanilhaRoteiroExpressas>.Create; AssignFile(ArquivoCSV, sFile); if sFile.IsEmpty then Exit; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; if Pos('CEP INICIAL',sLinha) = 0 then begin FMensagem := 'Arquivo informado não foi identificado como a Planilha de CEP para Roteiros de Expressas!'; Exit; end; i := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; if StrToIntDef(sDetalhe[0], 0) > 0 then begin sValor := '0'; FPlanilha.Add(TPlanilhaRoteiroExpressas.Create); i := FPlanilha.Count - 1; FPlanilha[i].CEPInicial := sDetalhe[0]; FPlanilha[i].CEPFinal := sDetalhe[1]; FPlanilha[i].Prazo := sDetalhe[2]; FPlanilha[i].Zona := Copy(sDetalhe[3],1,1); FPlanilha[i].Logradouro := sDetalhe[5]; FPlanilha[i].Bairro := sDetalhe[6]; FPlanilha[i].CCEP5 := '000'; if sDetalhe[4] = 'ABRANG. LEVE e PESADO' then begin iTipo := 3; end else if sDetalhe[4] = 'NÃO FAZ' then begin iTipo := 0; end else if Pos('FAZ PESADO', sDetalhe[4]) > 0 then begin iTipo := 2; end else if sDetalhe[4] = 'SÓ FAZ LEVE' then begin iTipo := 1; end; FPlanilha[i].Tipo := iTipo; end; end; if FPlanilha.Count = 0 then begin FMensagem := 'Nenhuma informação foi importada da planilha!'; Exit; end; Result := True; finally CloseFile(ArquivoCSV); end; end; end.
unit GetConfigValueUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TGetConfigValue = class(TBaseExample) public procedure Execute(Key: String); end; implementation uses CommonTypesUnit, NullableBasicTypesUnit; procedure TGetConfigValue.Execute(Key: String); var ErrorString: String; Value: NullableString; begin Value := Route4MeManager.User.GetConfigValue(Key, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if Value.IsNotNull then WriteLn( Format('GetConfigValue successfully. Key="%s", Value="%s"', [Key, Value.Value])) else WriteLn('GetConfigValue error'); WriteLn(''); end else WriteLn(Format('GetConfigValue error: "%s"', [ErrorString])); end; end.
unit MapStringToObject; interface uses Classes; const HashTableSize = 256; type TMapMode = (mmUse, mmOwn); TMapStringToObject = class public constructor Create(aMode : TMapMode); destructor Destroy; override; private HashTable : array[0..pred(HashTableSize)] of TStringList; private fMode : TMapMode; function GetCount : integer; function GetIndexes(pos : integer) : string; function GetItems(index : string) : TObject; procedure SetItems(index : string; Item : TObject); public property Count : integer read GetCount; property Indexes[pos : integer] : string read GetIndexes; property Mode : TMapMode read fMode; property Items[index : string] : TObject read GetItems write SetItems; default; end; implementation uses SysUtils, MathUtils; function HashValue(const s : string) : cardinal; var i : integer; begin {$Q-} Result := 0; for i := 1 to min(5, length(s)) do Result := (Result shl 5) + Result + ord(s[i]); {$Q+} end; constructor TMapStringToObject.Create(aMode : TMapMode); begin inherited Create; fMode := aMode; end; destructor TMapStringToObject.Destroy; procedure FreeList(aList : TStringList); var i : integer; begin if aList <> nil then begin for i := 0 to pred(aList.Count) do aList.Objects[i].Free; aList.Free; end; end; var i : integer; begin if fMode = mmUse then for i := low(HashTable) to high(HashTable) do HashTable[i].Free else for i := low(HashTable) to high(HashTable) do FreeList(HashTable[i]); inherited; end; function TMapStringToObject.GetCount : integer; var i : integer; begin Result := 0; for i := low(HashTable) to high(HashTable) do if HashTable[i] <> nil then inc(Result, HashTable[i].Count); end; function TMapStringToObject.GetIndexes(pos : integer) : string; var i : integer; c : integer; Found : boolean; begin c := 0; i := low(HashTable); Found := false; repeat if HashTable[i] <> nil then if pos < c + HashTable[i].count then Found := true else begin inc(c, HashTable[i].count); inc(i); end else inc(i); until Found or (i = high(HashTable)); if Found then Result := HashTable[i][pos - c] else raise Exception.Create('Index out of bounds'); end; function TMapStringToObject.GetItems(index : string) : TObject; var hash : integer; ndx : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] <> nil then with HashTable[hash] do begin ndx := IndexOf(index); if ndx >= 0 then Result := Objects[ndx] else Result := nil; end else Result := nil; end; procedure TMapStringToObject.SetItems(index : string; Item : TObject); var hash : integer; begin hash := HashValue(index) mod HashTableSize; if HashTable[hash] = nil then begin HashTable[hash] := TStringList.Create; HashTable[hash].Sorted := true; HashTable[hash].Duplicates := dupError; end; HashTable[hash].AddObject(index, Item); end; end.
unit osUtils; interface uses sysutils, classes, dbtables, typinfo, contnrs, forms, db; type // Restrições a usuario TRestricaoUsuario = class IdRestricao: integer; Id: variant; Texto: String; end; // Registro TosClassRef = class(TObject) private FClassRef: TPersistentClass; public constructor Create(PClass: TPersistentClass); property ClassRef: TPersistentClass read FClassRef; end; TosClassReg = class(TStringList) private public constructor Create; destructor Destroy; override; procedure AddClass(PClass: TPersistentClass); function GetClass(const PClassName: string): TPersistentClass; end; var OSClassReg: TosClassReg; procedure OSRegisterClass(PClass: TPersistentClass); function OSGetClass(const PClassName: string): TPersistentClass; // String function GetWord(const PStr: string; PIndex: integer; PSeparator: char): string; procedure ReplaceConstraintChars(var PStr: string); // Parâmetros function ExtractParam(const PName: string): string; {** Checa se as globais de empresa e estabelecimento estão setadas e caso não estejam seta seus valores.} procedure CheckDefaultParams; // String to Component function GetDatamoduleByName(const PName: string): TDatamodule; function GetFormByName(const PName: string): TForm; function GetComponentByName(POwner: TComponent; const PName: string; PClass: TClass ): TComponent; function IsFieldEmpty(PField: TField): boolean; overload; function IsFieldEmpty(PDataset: TDataset; const PFieldName: string): boolean; overload; function getRestricaoUsuario(PId: integer): TRestricaoUsuario; // Globais var GlobalEmpresa, GlobalEstabelecimento: string; var GlobalExtractParams: boolean = True; var GlobalListaRestricoesUsuario: TList = nil; implementation function GetWord(const PStr: string; PIndex: integer; PSeparator: char): string; var iNumWord, i, iLen, iIni: integer; begin iLen := Length(PStr); iNumWord := 1; iIni := 1; for i:=1 to iLen do if (PStr[i] = PSeparator) then if iNumWord = PIndex then break else begin iIni := i + 1; Inc(iNumWord); end; if iNumWord = PIndex then Result := Trim(Copy(PStr, iIni, i - iIni)) else Result := ''; end; procedure ReplaceConstraintChars(var PStr: string); var i, iLen: integer; begin iLen := Length(PStr); for i:=1 to iLen do if PStr[i] = '*' then PStr[i] := '%'; end; // Extração de parâmetros function ExtractParam(const PName: string): string; var i, iPos: Integer; sAux: string; begin Result := ''; for i:=1 to ParamCount do begin sAux := ParamStr(i); iPos := Pos('=', sAux); if (iPos <> 0) and (CompareText(Copy(sAux, 1, iPos-1), PName) = 0) then begin Result := StringReplace(Copy(sAux, iPos + 1, Length(sAux) - iPos),'_', ' ', [rfReplaceAll]); break; end; end; end; procedure CheckDefaultParams; begin if GlobalExtractParams then begin GlobalEmpresa := ExtractParam('empresa'); GlobalEstabelecimento := ExtractParam('estab'); if GlobalEmpresa = '' then GlobalEmpresa := '1'; if GlobalEstabelecimento = '' then GlobalEstabelecimento := '1'; GlobalExtractParams := False; end; end; function GetDatamoduleByName(const PName: string): TDatamodule; var i: integer; begin Result := nil; for i:=0 to Application.Componentcount - 1 do begin if (Application.Components[i] is TDatamodule) and (Application.Components[i].Name = PName) then begin Result := TDatamodule(Application.Components[i]); break; end; end; end; function GetFormByName(const PName: string): TForm; var i: integer; begin Result := nil; for i:=0 to Application.Componentcount - 1 do begin if (Application.Components[i] is TForm) and (Application.Components[i].Name = PName) then begin Result := TForm(Application.Components[i]); break; end; end; end; function GetComponentByName(POwner: TComponent; const PName: string; PClass: TClass ): TComponent; var i: integer; begin Result := nil; if assigned(POwner) then begin for i:=0 to POwner.Componentcount - 1 do begin if (POwner.Components[i] is PClass) and (POwner.Components[i].Name = PName) then begin Result := POwner.Components[i]; break; end; end; end; end; function IsFieldEmpty(PField: TField): boolean; begin Result := ((PField.IsNull) or (Trim(PField.AsString) = '')); end; function IsFieldEmpty(PDataset: TDataset; const PFieldName: string): boolean; begin Result := IsFieldEmpty(PDataset.FieldByName(PFieldName)); end; { TosClassReg } procedure TosClassReg.AddClass(PClass: TPersistentClass); begin AddObject(PClass.ClassName, TOsClassRef.Create(PClass)); end; constructor TosClassReg.Create; begin inherited; Sorted := True; end; destructor TosClassReg.Destroy; var i: integer; begin for i:=0 to Count - 1 do Objects[i].Free; inherited; end; function TosClassReg.GetClass(const PClassName: string): TPersistentClass; var i: integer; begin i := IndexOf(PClassName); if i <> -1 then Result := TosClassRef(Objects[i]).ClassRef else Result := nil; end; procedure OSRegisterClass(PClass: TPersistentClass); begin OSClassReg.AddClass(PClass); end; function OSGetClass(const PClassName: string): TPersistentClass; begin Result := OSClassReg.GetClass(PClassName); end; { TosClassRef } constructor TosClassRef.Create(PClass: TPersistentClass); begin FClassRef := PClass; end; function getRestricaoUsuario(PId: integer): TRestricaoUsuario; var i: integer; begin result := nil; if GlobalListaRestricoesUsuario=nil then exit; for i := 0 to GlobalListaRestricoesUsuario.Count-1 do begin if TRestricaoUsuario(GlobalListaRestricoesUsuario.Items[i]).IdRestricao = PId then result := GlobalListaRestricoesUsuario.Items[i]; end; end; initialization OSClassReg := TosClassReg.Create; finalization OSClassReg.Free; end.
unit ImageCache; interface uses Windows, Classes, GameTypes, LanderTypes, MapTypes; const cBasicZoomRes : TZoomRes = zr32x64; cBasicRotation : TRotation = drNorth; type TLandImages = array[idLand] of TGameImage; type TCacheImager = class(TInterfacedObject, IImager) private constructor Create(const view : IGameView); public destructor Destroy; override; private // IImager fLandImages : TLandImages; fSpareImage : TGameImage; fShadeImage : TGameImage; fRedShadeImage : TGameImage; fBlackShadeImage : TGameImage; function GetLandImage(id : integer) : TGameImage; virtual; abstract; function GetSpareImage : TGameImage; virtual; abstract; function GetShadeImage : TGameImage; virtual; abstract; function GetRedShadeImage : TGameImage; virtual; abstract; function GetBlackShadeImage : TGameImage; virtual; abstract; private fZoom : TZoomRes; fRotation : TRotation; fViews : TList; private procedure AttachView(const which : IGameView); procedure DetachView(const which : IGameView); end; type TImageCache = class public constructor Create(const Manager : ILocalCacheManager); destructor Destroy; override; public function GetImager(const view : IGameView) : IImager; private fManager : ILocalCacheManager; fImagers : array[TRotation, TZoomRes] of TCacheImager; procedure CheckDeletableImager; end; implementation uses Shutdown, AxlDebug, SysUtils, LocalCacheManager, ColorTableMgr, GDI, SpriteUtils; type TBasicImager = class(TCacheImager) private constructor Create(const view : IGameView; const Manager : ILocalCacheManager); destructor Destroy; override; private function GetLandImage(id : integer) : TGameImage; override; function GetSpareImage : TGameImage; override; function GetShadeImage : TGameImage; override; function GetRedShadeImage : TGameImage; override; function GetBlackShadeImage : TGameImage; override; private fManager : ILocalCacheManager; end; type TTransformImager = class(TCacheImager) private constructor Create(const view : IGameView; BasicImager : TBasicImager); destructor Destroy; override; private function GetLandImage(id : integer) : TGameImage; override; function GetSpareImage : TGameImage; override; function GetShadeImage : TGameImage; override; function GetRedShadeImage : TGameImage; override; function GetBlackShadeImage : TGameImage; override; private fBasicImager : TBasicImager; fZoomFactor : single; end; // Utils procedure FreeObject(var which); begin TObject(which).Free; TObject(which) := nil; end; // TCacheImager constructor TCacheImager.Create(const view : IGameView); begin inherited Create; fZoom := TZoomRes(view.ZoomLevel); fRotation := view.Rotation; fViews := TList.Create; _AddRef; end; destructor TCacheImager.Destroy; var i : integer; begin fBlackShadeImage.Free; fRedShadeImage.Free; fShadeImage.Free; fSpareImage.Free; for i := low(fLandImages) to high(fLandImages) do fLandImages[i].Free; fViews.Free; // <<>> finalize them inherited; end; procedure TCacheImager.AttachView(const which : IGameView); // >> begin fViews.Add(pointer(which)); which._AddRef; end; procedure TCacheImager.DetachView(const which : IGameView); // >> begin fViews.Remove(pointer(which)); which._Release; end; // TBasicImager constructor TBasicImager.Create(const view : IGameView; const Manager : ILocalCacheManager); var i : integer; begin inherited Create(view); fManager := Manager; fViews := TList.Create; for i := low(fLandImages) to high(fLandImages) do fLandImages[i] := fManager.GetLandImage(fZoom, i); fSpareImage := fManager.GetSpareImage(fZoom); fShadeImage := fManager.GetShadeImage(fZoom); fRedShadeImage := fManager.GetRedShadeImage(fZoom); fBlackShadeImage := fManager.GetBlackShadeImage(fZoom); end; destructor TBasicImager.Destroy; begin inherited; end; function TBasicImager.GetLandImage(id : integer) : TGameImage; const tickDownloading = -1; var mask : integer; begin mask := id and idMask; id := id and $FFFF; if mask = idLandMask then begin assert((id >= low(idLand)) and (id <= high(idLand))); Result := {GetRGBImage(0, 155, 0, 1)}fLandImages[id]; end else Result := nil; end; function TBasicImager.GetSpareImage : TGameImage; begin Result := fSpareImage; end; function TBasicImager.GetShadeImage : TGameImage; begin Result := fShadeImage; end; function TBasicImager.GetRedShadeImage : TGameImage; begin Result := fRedShadeImage; end; function TBasicImager.GetBlackShadeImage : TGameImage; begin Result := fBlackShadeImage; end; // TTransformImager constructor TTransformImager.Create(const view : IGameView; BasicImager : TBasicImager); var ZoomDif : integer; begin inherited Create(view); fBasicImager := BasicImager; ZoomDif := ord(fBasicImager.fZoom) - ord(fZoom); if ZoomDif >= 0 then fZoomFactor := 1/(1 shl ZoomDif) else fZoomFactor := 1 shl -ZoomDif; end; destructor TTransformImager.Destroy; begin inherited; end; function TTransformImager.GetLandImage(id : integer) : TGameImage; var mask : integer; SrcImg : TGameImage; TransfImg : TGameImage; begin mask := id and idMask; id := id and $FFFF; if mask = idLandMask then begin assert((id >= low(idLand)) and (id <= high(idLand))); if fLandImages[id] = nil then begin SrcImg := fBasicImager.GetLandImage(mask or id); if SrcImg <> nil then begin TransfImg := SpriteStretch(SrcImg, round(SrcImg.Width*fZoomFactor), round(SrcImg.Height*fZoomFactor)); TransfImg.PaletteInfo := SrcImg.PaletteInfo; fLandImages[id] := TransfImg; end; end; Result := fLandImages[id]; end else Result := nil; end; function TTransformImager.GetSpareImage : TGameImage; var SrcImg : TGameImage; TransfImg : TGameImage; begin if fSpareImage = nil then begin SrcImg := fBasicImager.GetSpareImage; if SrcImg <> nil then begin TransfImg := SpriteStretch(SrcImg, round(SrcImg.Width*fZoomFactor), round(SrcImg.Height*fZoomFactor)); TransfImg.PaletteInfo := SrcImg.PaletteInfo; fSpareImage := TransfImg; end; end; Result := fSpareImage; end; function TTransformImager.GetShadeImage : TGameImage; var SrcImg : TGameImage; TransfImg : TGameImage; begin if fShadeImage = nil then begin SrcImg := fBasicImager.GetShadeImage; if SrcImg <> nil then begin TransfImg := SpriteStretch(SrcImg, round(SrcImg.Width*fZoomFactor), round(SrcImg.Height*fZoomFactor)); TransfImg.PaletteInfo := SrcImg.PaletteInfo; fShadeImage := TransfImg; end; end; Result := fShadeImage; end; function TTransformImager.GetRedShadeImage : TGameImage; var SrcImg : TGameImage; TransfImg : TGameImage; begin if fRedShadeImage = nil then begin SrcImg := fBasicImager.GetRedShadeImage; if SrcImg <> nil then begin TransfImg := SpriteStretch(SrcImg, round(SrcImg.Width*fZoomFactor), round(SrcImg.Height*fZoomFactor)); TransfImg.PaletteInfo := SrcImg.PaletteInfo; fRedShadeImage := TransfImg; end; end; Result := fRedShadeImage; end; function TTransformImager.GetBlackShadeImage : TGameImage; var SrcImg : TGameImage; TransfImg : TGameImage; begin if fBlackShadeImage = nil then begin SrcImg := fBasicImager.GetBlackShadeImage; if SrcImg <> nil then begin TransfImg := SpriteStretch(SrcImg, round(SrcImg.Width*fZoomFactor), round(SrcImg.Height*fZoomFactor)); TransfImg.PaletteInfo := SrcImg.PaletteInfo; fBlackShadeImage := TransfImg; end; end; Result := fBlackShadeImage; end; // TImageCache constructor TImageCache.Create(const Manager : ILocalCacheManager); begin inherited Create; fManager := Manager; end; destructor TImageCache.Destroy; var r : TRotation; z : TZoomRes; begin for r := low(r) to high(r) do for z := low(z) to high(z) do fImagers[r, z].Free; inherited; end; function TImageCache.GetImager(const view : IGameView) : IImager; var r : TRotation; z : TZoomRes; begin assert((view.ZoomLevel >= ord(low(TZoomRes))) and (view.ZoomLevel <= ord(high(TZoomRes)))); for r := low(r) to high(r) do for z := low(z) to high(z) do if (fImagers[r, z] <> nil) and (fImagers[r, z].fViews.IndexOf(pointer(view)) <> -1) then fImagers[r, z].DetachView(view); r := view.Rotation; z := TZoomRes(view.ZoomLevel); if fImagers[r, z] = nil then if (r = cBasicRotation) and (z = cBasicZoomRes) then fImagers[r, z] := TBasicImager.Create(view, fManager) else fImagers[r, z] := TTransformImager.Create(view, TBasicImager(fImagers[cBasicRotation, cBasicZoomRes])); fImagers[r, z].AttachView(view); CheckDeletableImager; Result := fImagers[r, z]; end; procedure TImageCache.CheckDeletableImager; var r : TRotation; z : TZoomRes; begin for r := low(r) to high(r) do for z := low(z) to high(z) do if (fImagers[r, z] <> nil) and (fImagers[r, z].fViews.Count = 0) and (r <> cBasicRotation) and (z <> cBasicZoomRes) then begin fImagers[r, z].Free; fImagers[r, z] := nil; end; end; end.
unit uAccessEvent; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ToolPanels, ComCtrls, AdvPageControl, Shader, StdCtrls, AdvEdit, AdvEdBtn, PlannerDatePicker, AdvCombo, Grids, BaseGrid, AdvGrid, AdvPanel, Buttons, uSubForm, CommandArray, RzGrids, AdvObj; type TfmAccessEvent = class(TfmASubForm) AdvPanel1: TAdvPanel; AdvPanel2: TAdvPanel; AdvStringGrid1: TAdvStringGrid; btn_stop: TSpeedButton; btn_start: TSpeedButton; btn_Clear: TSpeedButton; btn_FileSave: TSpeedButton; SaveDialog1: TSaveDialog; SearchTimer: TTimer; lb_ECUID: TLabel; ed_ecuid: TEdit; procedure FormCreate(Sender: TObject); procedure CommandArrayCommandsTCommand0Execute(Command: TCommand; Params: TStringList); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure StringGrideResize(Gride:TStringGrid); procedure AdvStringGrid1Resize(Sender: TObject); procedure StringGrideDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure FormActivate(Sender: TObject); procedure btn_ClearClick(Sender: TObject); procedure btn_FileSaveClick(Sender: TObject); procedure btn_startClick(Sender: TObject); procedure btn_stopClick(Sender: TObject); procedure CommandArrayCommandsTCommand1Execute(Command: TCommand; Params: TStringList); procedure SearchTimerTimer(Sender: TObject); private { Private declarations } DisplayList : TStringList; bClear : Boolean; bStart : Boolean; procedure BatchDisplay(aData: string); public { Public declarations } procedure DisplayStringGrid(aCmd,aTxRx,aIP,aECUID,aData:string); procedure CloseForm; procedure RecvCardAccessEvent(aECUID, aDoorNo, aReaderNo, aInOut, aTime, aCardMode, aDoorMode, aChangeState, aAccessResult, aDoorState, aATButton, aCardNo:string); procedure RcvExitButtonEvent(aECUID, aDoorNo, aReaderNo, aInOut, aTime, aCardMode, aDoorMode, aChangeState, aAccessResult, aDoorState, aATButton, aCardNo:string); end; var fmAccessEvent: TfmAccessEvent; implementation uses uCommon, dllFunction, uUtil; {$R *.dfm} procedure TfmAccessEvent.FormCreate(Sender: TObject); begin Self.ModuleID := 'CURRENTSTATE'; DisplayList := TStringList.Create; SearchTimer.Enabled := True; end; procedure TfmAccessEvent.CommandArrayCommandsTCommand0Execute( Command: TCommand; Params: TStringList); var stCmd : string; stData : string; stTxRx : string; stIP : string; stECUID : string; begin stCmd := Params.Values['Cmd']; stData := Params.Values['Data']; stTxRx := Params.Values['TxRx']; stIP := Params.Values['IP']; stECUID := Params.Values['ECUID']; DisplayStringGrid(stCmd,stTxRx,stIP,stECUID,stData); end; procedure TfmAccessEvent.FormClose(Sender: TObject; var Action: TCloseAction); begin SearchTimer.Enabled := False; if G_bApplicationTerminate then Exit; self.FindSubForm('Main').FindCommand('ACCESSEVENT').Params.Values['VALUE'] := 'FALSE'; self.FindSubForm('Main').FindCommand('ACCESSEVENT').Execute; Action := caFree; DisplayList.Clear; DisplayList.Free; SearchTimer.Free; end; procedure TfmAccessEvent.FormShow(Sender: TObject); begin self.FindSubForm('Main').FindCommand('ACCESSEVENT').Params.Values['VALUE'] := 'TRUE'; self.FindSubForm('Main').FindCommand('ACCESSEVENT').Execute; // StringGrideResize(AdvStringGrid1); btn_ClearClick(Self); btn_StartClick(Self); end; procedure TfmAccessEvent.StringGrideResize(Gride:TStringGrid); var nTotWidth,nColCnt,nColWidth : integer; i : integer; begin with Gride do begin ColCount := 6; nTotWidth := Width - 20; ColWidths[0] := 100; ColWidths[1] := 50; ColWidths[2] := 50; ColWidths[3] := 100; ColWidths[4] := 50; ColWidths[5] := nTotWidth - 370; end; end; procedure TfmAccessEvent.AdvStringGrid1Resize(Sender: TObject); begin // StringGrideResize(AdvStringGrid1); end; procedure TfmAccessEvent.StringGrideDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var DataInCell : string; nLeft,nTop : integer; begin if (AROW < (Sender as TStringGrid).FixedRows) then begin DataInCell := (Sender as TStringGrid).Cells[Acol,Arow]; with (Sender as TStringGrid).Canvas do begin FillRect(Rect); //켄버스를 칠한다.(기본값은 흰색) if DataInCell <> '' then begin nLeft := ((Rect.Right-Rect.Left) - TextWidth(DataInCell)) div 2; nTop := ((Rect.Bottom-Rect.Top) - TextHeight(DataInCell)) div 2; TextRect(Rect, Rect.Left + nLeft, Rect.Top + nTop, DataInCell); //문자를 뿌려준다.. 기본은 검정색 end; End; End else if Acol <> 5 then begin DataInCell := (Sender as TStringGrid).Cells[Acol,Arow]; with (Sender as TStringGrid).Canvas do begin FillRect(Rect); //켄버스를 칠한다.(기본값은 흰색) if DataInCell <> '' then begin nLeft := ((Rect.Right-Rect.Left) - TextWidth(DataInCell)) div 2; nTop := ((Rect.Bottom-Rect.Top) - TextHeight(DataInCell)) div 2; TextRect(Rect, Rect.Left + nLeft, Rect.Top + nTop, DataInCell); //문자를 뿌려준다.. 기본은 검정색 end; End; end; end; procedure TfmAccessEvent.FormActivate(Sender: TObject); begin // AdvStringGrid1.OnDrawCell:=StringGrideDrawCell; end; procedure TfmAccessEvent.btn_ClearClick(Sender: TObject); var i:integer; begin bClear := True; GridInitialize(AdvStringGrid1); end; procedure TfmAccessEvent.DisplayStringGrid(aCmd, aTxRx,aIP,aECUID, aData: string); var stDisplay : string; begin if Not bStart then Exit; end; procedure TfmAccessEvent.btn_FileSaveClick(Sender: TObject); var aFileName: String; sDate: String; eDate: String; begin Screen.Cursor:= crHourGlass; aFileName:='출입현황 조회(' + FormatDateTime('yyyy-mm-dd',now) + ')'; SaveDialog1.FileName := aFileName; if SaveDialog1.Execute then begin AdvStringGrid1.SaveToCSV(SaveDialog1.FileName); end; Screen.Cursor:= crDefault; end; procedure TfmAccessEvent.btn_startClick(Sender: TObject); begin bStart := True; btn_start.Enabled := False; btn_stop.Enabled := True; end; procedure TfmAccessEvent.btn_stopClick(Sender: TObject); begin bStart := False; btn_start.Enabled := True; btn_stop.Enabled := False; end; procedure TfmAccessEvent.CommandArrayCommandsTCommand1Execute( Command: TCommand; Params: TStringList); begin Close; end; procedure TfmAccessEvent.CloseForm; begin Close; end; procedure TfmAccessEvent.SearchTimerTimer(Sender: TObject); begin SearchTimer.Enabled := False; if DisplayList.Count > 0 then begin BatchDisplay(DisplayList.Strings[0]); DisplayList.Delete(0); end; SearchTimer.Enabled := True; end; procedure TfmAccessEvent.BatchDisplay(aData:string); var stECUID, stDoorNo, stReaderNo:string; stInOut, stTime, stCardMode, stDoorMode, stChangeState, stAccessResult:string; stDoorState, stATButton, stCardNo : string; stAccessResultName,stInOutName,stCardModeName : string; stDoorModeName,stChangeStateName,stDoorStateName : string; nPos : integer; stButtonName : string; begin nPos := PosIndex(';',aData,1); stECUID := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stDoorNo := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stReaderNo := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stInOut := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stTime := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stCardMode := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stDoorMode := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stChangeState := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stAccessResult := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stDoorState := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stATButton := copy(aData,1,nPos - 1); Delete(aData,1,nPos); nPos := PosIndex(';',aData,1); stCardNo := copy(aData,1,nPos - 1); Delete(aData,1,nPos); //여기에서 화면에 뿌려주자. with AdvStringGrid1 do begin if Trim(ed_ecuid.Text) <> '' then begin if pos(stEcuID,ed_ecuid.Text) = 0 then Exit; end; if RowCount >= 10000 then rowCount := 9999; if Not bClear then InsertRows(1,1); bClear := False; Cells[0,1] := strToTimeFormat(stTime); Cells[1,1] := stEcuID ; Cells[2,1] := stDoorNo ; Cells[3,1] := stReaderNo ; Cells[4,1] := stCardNo ; case stAccessResult[1] of #$30: stAccessResultName := '해당사항없음'; #$31: stAccessResultName := '출입승인'; #$32: stAccessResultName := '방범카드조작'; //방범카드조작(*) #$33: stAccessResultName := '방범경계승인'; //방범카드조작(*) #$34: stAccessResultName := '방범해제승인'; //방범카드조작(*) #$41: stAccessResultName := '미등록카드'; #$42: stAccessResultName := '출입불가'; #$43: stAccessResultName := '방범불가'; //미등록카드(*) #$44: stAccessResultName := '경계모드출입불가'; #$45: stAccessResultName := '출입제한시간'; #$46: stAccessResultName := '유효기간만료'; else stAccessResultName := stAccessResult; end; Cells[5,1] := stAccessResultName ; stButtonName := Ascii2Hex(stATButton) ; if stButtonName = '30' then stButtonName := '퇴실' else if stButtonName = '31' then stButtonName := '출근' else if stButtonName = '32' then stButtonName := '퇴근' else if stButtonName = '34' then stButtonName := '외출' else if stButtonName = '35' then stButtonName := '복귀' else if stButtonName = '61' then stButtonName := '경해' else if stButtonName = '63' then stButtonName := '재중' else if stButtonName = '7F' then stButtonName := ''; Cells[6,1] := stButtonName ; case stInOut[1] of '0' : stInOutName := '내부'; '1' : stInOutName := '외부'; else stInOutName := '내부'; end; Cells[7,1] := stInOutName ; case stCardMode[1] of '0': stCardModeName := 'Positive'; '1': stCardModeName := 'Negative'; '2': stCardModeName := 'Positive(2)'; '3': stCardModeName := 'Negative(3)'; else stCardModeName := stCardMode; end; Cells[8,1] := stCardModeName ; case stDoorMode[1] of '0': stDoorModeName := '운영모드'; '1': stDoorModeName := '개방모드'; '2': stDoorModeName := '폐쇄모드'; else stDoorModeName := stDoorMode; end; Cells[9,1] := stDoorModeName ; case stChangeState[1] of 'C': stChangeStateName := '카드'; 'P': stChangeStateName := '전화'; 'R': stChangeStateName := '원격제어'; 'B': stChangeStateName := '버튼'; 'S': stChangeStateName := '스케쥴'; else stChangeStateName := stChangeState; end; Cells[10,1] := stChangeStateName ; case stDoorState[1]of 'C': stDoorStateName := '닫힘'; 'O': stDoorStateName := '열림'; else stDoorStateName := stDoorState; end; Cells[11,1] := stDoorStateName ; if Not isDigit(stAccessResult) then RowColor[1] := clYellow; end; end; procedure TfmAccessEvent.RecvCardAccessEvent(aECUID, aDoorNo, aReaderNo, aInOut, aTime, aCardMode, aDoorMode, aChangeState, aAccessResult, aDoorState, aATButton, aCardNo:string); var stDisplay : string; begin if Not bStart then Exit; stDisplay := aECUID + ';'; stDisplay := stDisplay + aDoorNo + ';'; stDisplay := stDisplay + aReaderNo + ';'; stDisplay := stDisplay + aInOut + ';'; stDisplay := stDisplay + aTime + ';'; stDisplay := stDisplay + aCardMode + ';'; stDisplay := stDisplay + aDoorMode + ';'; stDisplay := stDisplay + aChangeState + ';'; stDisplay := stDisplay + aAccessResult + ';'; stDisplay := stDisplay + aDoorState + ';'; stDisplay := stDisplay + aATButton + ';'; stDisplay := stDisplay + aCardNo + ';'; DisplayList.Add(stDisplay); end; procedure TfmAccessEvent.RcvExitButtonEvent(aECUID, aDoorNo, aReaderNo, aInOut, aTime, aCardMode, aDoorMode, aChangeState, aAccessResult, aDoorState, aATButton, aCardNo: string); var stDisplay : string; begin if Not bStart then Exit; stDisplay := aECUID + ';'; stDisplay := stDisplay + aDoorNo + ';'; stDisplay := stDisplay + aReaderNo + ';'; stDisplay := stDisplay + aInOut + ';'; stDisplay := stDisplay + aTime + ';'; stDisplay := stDisplay + aCardMode + ';'; stDisplay := stDisplay + aDoorMode + ';'; stDisplay := stDisplay + aChangeState + ';'; stDisplay := stDisplay + aAccessResult + ';'; stDisplay := stDisplay + aDoorState + ';'; stDisplay := stDisplay + aATButton + ';'; stDisplay := stDisplay + '퇴실버튼' + ';'; DisplayList.Add(stDisplay); end; initialization RegisterClass(TfmAccessEvent); Finalization UnRegisterClass(TfmAccessEvent); end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Bytecode definition unit bytecode; interface uses typedefs, variable; const // ==================================================== // opcodes // ==================================================== // STOP: stop the execution of the program // args: n/a // result: n/a OP_STOP = $00; // PUSH: push variable onto the stack // args: index of the variable to read from and put on the stack // result: the variable is on the top of the stack OP_PUSH = $01; // POP: pop variable off the stack // args: index of the variable to write the value off the stack to // result: the top-most variable is removed from the stack OP_POP = $02; // ADD: addition of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_ADD = $03; // ADD: subtraction of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_SUB = $04; // MUL: multiplication of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_MUL = $05; // DIV: division of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_DIV = $06; // MOD: modulo of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_MOD = $07; // MIN: minimum of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_MIN = $08; // MAX: maximum of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_MAX = $09; // AND: boolean AND of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_AND = $0A; // OR: boolean OR of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_OR = $0B; // XOR: boolean XOR of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_XOR = $0C; // EQ: equality check of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_EQ = $0D; // NEQ: inequality check of the two top-most variables on the stack // args: n/a // result: pops the two top-most variables and pushes the operation result OP_NEQ = $0E; // NEG: boolean negation of the top-most stack variable // args: n/a // result: pops the top-most variable and pushes the operation result OP_NEG = $0F; // CONCAT: concatenates two top-most strings on the stack (will cast if // necessary) // args: n/a // result: pops the two top-most variables and pushes the operation result OP_CONCAT = $10; // JMP: unconditional jump // args: address of the instruction to jump to // result: corresponding pointer arithmetic on the interpreter's instruction // pointer OP_JMP = $11; // CNDJMP: conditional jump (if the implicit "IT" variable is *false*) // args: address of the instruction to jump to // result: corresponding pointer arithmetic on the interpreter's instruction // pointer OP_CNDJMP = $12; // CALL: call a function (defined in LOLCODE); assumes that parameters are // on the stack (stdcall convention) // args: function index // result: function's return value on top of the stack OP_CALL = $13; // RETURN: return control from a function // args: n/a // result: control is returned to higher-level code block OP_RETURN = $14; // PRINT: prints the top of the stack to stdio // args: n/a // result: n/a OP_PRINT = $15; // READ: reads a string from stdin onto the top of the stack // args: n/a // result: n/a OP_READ = $16; // CAST: casts the value on the top of the stack to a given type // args: ID of the type to cast to // result: n/a OP_CAST = $17; // INCR: increments (arg = 1) or decrements (arg = 0) the value of the top // of the stack // args: 0 for decrementation, 1 for incrementation // result: n/a OP_INCR = $18; // ==================================================== // special arguments // ==================================================== // NULL argument // PUSH behaviour: push an empty variable onto the stack // POP behaviour: just pop the stack without writing the value to a variable ARG_NULL = $00000000; type // single instruction with the argument islip_inst = record inst : byte; arg : size_t; end; islip_bytecode = array of islip_inst; pislip_bytecode = ^islip_bytecode; islip_data = array of islip_var; pislip_data = ^islip_data; implementation end.
program TESTDEC ( OUTPUT ) ; const CONST1 = 1234.56 ; type DEC72 = DECIMAL ( 7 , 2 ) ; DEC152 = DECIMAL ( 15 , 2 ) ; PERSON = record VORNAME : CHAR ( 20 ) ; NACHNAME : CHAR ( 20 ) ; ALTER : INTEGER ; GROESSE : DECIMAL ( 3 , 2 ) ; GEWICHT : DECIMAL ( 6 , 3 ) ; end ; var D1 : DECIMAL ( 7 ) ; D2 : DECIMAL ( 15 , 2 ) ; D3 : DEC72 ; D4 : DECIMAL ( 25 , 4 ) ; P : PERSON ; function BRUTTO ( X : DECIMAL ( 15 , 2 ) ) : DEC152 ; begin (* BRUTTO *) BRUTTO := ROUNDX ( X * 1.19 , - 2 ) ; end (* BRUTTO *) ; function BRUTTO2 ( X : DECIMAL ( 15 , 2 ) ) : DECIMAL ( 15 , 2 ) ; begin (* BRUTTO2 *) BRUTTO2 := ROUNDX ( X * 1.19 , - 2 ) ; end (* BRUTTO2 *) ; function NEXTCHAR ( C : CHAR ) : CHAR ( 1 ) ; begin (* NEXTCHAR *) NEXTCHAR := SUCC ( C ) ; end (* NEXTCHAR *) ; procedure PRINT_PERSON ( var X : PERSON ) ; begin (* PRINT_PERSON *) WRITELN ( 'print_person: vorname = ' , X . VORNAME ) ; WRITELN ( 'print_person: nachname = ' , X . NACHNAME ) ; WRITELN ( 'print_person: alter = ' , X . ALTER ) ; WRITELN ( 'print_person: groesse = ' , X . GROESSE ) ; WRITELN ( 'print_person: gewicht = ' , X . GEWICHT ) ; end (* PRINT_PERSON *) ; begin (* HAUPTPROGRAMM *) WRITELN ( '=====================================================' ) ; WRITELN ( 'Show different results of digitsof and precisionof' ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'digitsof (const) = ' , DIGITSOF ( 1234 ) ) ; WRITELN ( 'precisionof (const) = ' , PRECISIONOF ( 1234 ) ) ; WRITELN ( 'digitsof (const) = ' , DIGITSOF ( 1234.56 ) ) ; WRITELN ( 'precisionof (const) = ' , PRECISIONOF ( 1234.56 ) ) ; WRITELN ( 'sizeof (type) = ' , SIZEOF ( DEC72 ) ) ; WRITELN ( 'digitsof (type) = ' , DIGITSOF ( DEC72 ) ) ; WRITELN ( 'precisionof (type) = ' , PRECISIONOF ( DEC72 ) ) ; WRITELN ( 'sizeof (d3) = ' , SIZEOF ( D3 ) ) ; WRITELN ( 'digitsof (d3) = ' , DIGITSOF ( D3 ) ) ; WRITELN ( 'precisionof (d3) = ' , PRECISIONOF ( D3 ) ) ; WRITELN ( 'sizeof (d4) = ' , SIZEOF ( D4 ) ) ; WRITELN ( 'digitsof (d4) = ' , DIGITSOF ( D4 ) ) ; WRITELN ( 'precisionof (d4) = ' , PRECISIONOF ( D4 ) ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'Test output of decimal variables using implicit width' ) ; WRITELN ( '=====================================================' ) ; D3 := 1234.56 ; D3 := D3 + 1234 ; WRITELN ( 'd3 = ' , D3 ) ; D2 := D3 ; WRITELN ( 'd2 = ' , D2 ) ; D4 := D3 ; WRITELN ( 'd4 = ' , D4 ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'Do some computations using decimal variables' ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'compute d4 * 1.19' ) ; D4 := D3 * 1.19 ; WRITELN ( 'd4 = ' , D4 ) ; WRITELN ( 'compute d4 * 1.19 and round to 2nd digit' ) ; D4 := ROUNDX ( D3 * 1.19 , - 2 ) ; WRITELN ( 'd4 = ' , D4 ) ; WRITELN ( 'compute d4 * 1.19 using function brutto' ) ; D4 := D3 ; WRITELN ( 'brutto = ' , BRUTTO ( D4 ) ) ; WRITELN ( 'compute d4 * 1.19 using function brutto2' ) ; D4 := D3 ; WRITELN ( 'brutto2 = ' , BRUTTO2 ( D4 ) ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'output decimal constants' ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'const = ' , 1234.56 ) ; WRITELN ( 'const1 = ' , CONST1 ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'use a record variable including the new types' ) ; WRITELN ( '=====================================================' ) ; WRITELN ( 'sizeof (p) = ' , SIZEOF ( P ) ) ; P . VORNAME := 'Bernd' ; P . NACHNAME := 'Oppolzer' ; P . ALTER := 58 ; P . GROESSE := 1.85 ; P . GEWICHT := 87.125 ; PRINT_PERSON ( P ) ; end (* HAUPTPROGRAMM *) .
unit Unit2; interface uses System.SysUtils, System.Classes, IPPeerClient, REST.OpenSSL, REST.Backend.KinveyProvider, REST.Backend.ParseProvider; {$REGION 'My Secret Keys'} const KINVEY_App_Key = '---'; KINVEY_App_Secret = '---'; KINVEY_Master_Secret = '---'; PARSE_App_Id = '---'; PARSE_RESTApi_Key = '---'; PARSE_Master_Key = '---'; {$ENDREGION} type TDataModule2 = class(TDataModule) ParseProvider1: TParseProvider; KinveyProvider1: TKinveyProvider; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var DataModule2: TDataModule2; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDataModule2.DataModuleCreate(Sender: TObject); begin /// prepare the client-component for usage KinveyProvider1.AppKey := KINVEY_App_Key; KinveyProvider1.AppSecret := KINVEY_App_Secret; KinveyProvider1.MasterSecret := KINVEY_Master_Secret; ParseProvider1.ApplicationID := PARSE_App_Id; ParseProvider1.RestApiKey := PARSE_RESTApi_Key; ParseProvider1.MasterKey := PARSE_Master_Key; end; end.
program runden (input, output); {Zahl wird auf das nächstgelegene Vielfache von 100 auf- oder abgerundet.} var Z: integer; {einzugebene Zahl} modZ: integer; {Ergebnis von Z mod 100} roundZ: integer; {gerundete Zahl} begin writeln ('Gib die zu rundende Zahl ein.'); read (Z); modZ := Z mod 100; if modZ < 50 then roundZ := (Z - modZ) else roundZ := (Z + modZ); writeln ('Die gerundete Zahl lautet ', roundZ,'.'); end.
{ Exercício 36: Elabore um algoritmo que receba o valor de dois números inteiros e a operação aritmética desejada. Calcule e exiba, então, a resposta adequada. Utilize os símbolos da tabela abaixo para ler qual a operação aritmética escolhida. Símbolo Operação + Adição - Subtração * Multiplicação / Divisão } { Solução em Portugol Algoritmo Exercicio 36; Var numero1,numero2: real; operacao: caracter; Inicio exiba("Calculadora com as 4 operações básicas."); exiba("Digite o primeiro número: "); leia(numero1); exiba("Digite a operação que você deseja realizar: "); leia(operacao); exiba("Digite o segundo número: "); leia(numero2); caso(operacao)de "+": exiba("A soma dos dois números é: ", numero1 + numero2); "-": exiba("A subtração dos dois números é: ", numero1 - numero2); "*": exiba("A multiplicação dos dois números é: ", numero1 * numero2); "/": exiba("A divisão dos dois números é: ", numero1 / numero2); senão exiba("Reinicie o programa e digite uma operação válida."); fimcaso; Fim. } // Solução em Pascal Program Exercicio36; uses crt; var numero1,numero2: real; operacao: char; begin clrscr; writeln('Calculadora com as 4 operações básicas.'); writeln('Digite o primeiro número: '); readln(numero1); writeln('Digite a operação que você deseja realizar: '); readln(operacao); writeln('Digite o segundo número: '); readln(numero2); case(operacao)of '+': writeln('A soma dos dois números é: ', (numero1 + numero2):0:2); '-': writeln('A subtração dos dois números é:', (numero1 - numero2):0:2); '*': writeln('A multiplicação dos dois números é:', (numero1 * numero2):0:2); '/': writeln('A divisão dos dois números é:', (numero1 / numero2):0:2); else writeln('Reinicie o programa e digite uma operação válida.'); End; repeat until keypressed; end.
// defines a stack and a stackstack for the code formatter based on a pseudo template // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) // Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features unit GX_CodeFormatterStack; {$I GX_CondDefine.inc} interface uses GX_CodeFormatterTypes; type PStackRec = ^TStackRec; TStackRec = record RT: TReservedType; nInd: Integer; end; const MaxStack = 150; type TStackArray = array[0..MaxStack] of TStackRec; type TCodeFormatterSegment = class private FStack: TStackArray; FStackPtr: Integer; FNIndent: Integer; FProcLevel: Integer; FGenericsElement: Boolean; function TopRec: PStackRec; procedure SetGenericsElement(_Value: Boolean); public constructor Create; destructor Destroy; override; {: returns the topmost item from the stack without removing it } function GetTopType: TReservedType; function GetTopIndent: Integer; {: like GetTopType, but takes an index, Idx = 0 is equivalent to GetTopType, Idx=1 returns the next etc. } function GetType(_Idx: Integer): TReservedType; {: Check whether _Type is somewhere on the stack } function HasType(_Type: TReservedType): Boolean; function Pop: TReservedType; procedure Push(_Type: TReservedType; _IncIndent: Integer); {: returns True if the stack is empty } function IsEmpty: Boolean; {: clears the stack and returns the number of items that were left } function Clear: Integer; function Depth: Integer; function Clone: TCodeFormatterSegment; property NIndent: Integer read FNIndent write FNIndent; property ProcLevel: Integer read FProcLevel write FProcLevel; property GenericsElement: Boolean read FGenericsElement write SetGenericsElement; end; {$DEFINE STACK_TEMPLATE} type _STACK_ITEM_ = TCodeFormatterSegment; const _MAX_DEPTH_ = 150; {$INCLUDE DelforStackTemplate.tpl} type TCodeFormatterStack = class(_STACK_) end; implementation { TCodeFormatterSegment } constructor TCodeFormatterSegment.Create; begin inherited Create; FStackPtr := -1; FNIndent := 0; FProcLevel := 0; FGenericsElement := False; end; destructor TCodeFormatterSegment.Destroy; begin inherited; end; function TCodeFormatterSegment.GetTopType: TReservedType; begin if FStackPtr >= 0 then Result := TopRec.RT else Result := rtNothing; end; function TCodeFormatterSegment.GetType(_Idx: Integer): TReservedType; begin if FStackPtr >= _Idx then Result := FStack[FStackPtr - _Idx].RT else Result := rtNothing; end; procedure TCodeFormatterSegment.Push(_Type: TReservedType; _IncIndent: Integer); begin Inc(FStackPtr); if FStackPtr > MaxStack then raise EFormatException.Create('Stack overflow'); TopRec.RT := _Type; TopRec.nInd := FNIndent; FNIndent := FNIndent + _IncIndent; end; procedure TCodeFormatterSegment.SetGenericsElement(_Value: Boolean); begin FGenericsElement := _Value; end; function TCodeFormatterSegment.HasType(_Type: TReservedType): Boolean; var I: Integer; begin Result := False; for I := 0 to FStackPtr do if FStack[I].RT = _Type then begin Result := True; Exit; end; end; function TCodeFormatterSegment.Pop: TReservedType; begin if FStackPtr >= 0 then begin FNIndent := TopRec.nInd; if (TopRec.RT = rtProcedure) and (FProcLevel > 0) then Dec(FProcLevel); Result := TopRec^.RT; Dec(FStackPtr); end else begin FNIndent := 0; FProcLevel := 0; Result := rtNothing; end; end; function TCodeFormatterSegment.TopRec: PStackRec; begin Result := @FStack[FStackPtr]; end; function TCodeFormatterSegment.GetTopIndent: Integer; begin if not IsEmpty then begin Result := TopRec.nInd; NIndent := Result; end else Result := NIndent; end; function TCodeFormatterSegment.IsEmpty: Boolean; begin Result := FStackPtr < 0; end; function TCodeFormatterSegment.Clear: Integer; begin Result := Depth; FStackPtr := -1; FNIndent := 0; FProcLevel := 0; end; function TCodeFormatterSegment.Depth: Integer; begin Result := FStackPtr + 1; end; function TCodeFormatterSegment.Clone: TCodeFormatterSegment; begin Result := TCodeFormatterSegment.Create; Result.FStack := FStack; Result.FStackPtr := FStackPtr; Result.FNIndent := FNIndent; Result.FProcLevel := FProcLevel; end; { TCodeFormatterStack } {$INCLUDE DelforStackTemplate.tpl} end.
unit StockIndexData_Get_Sina; interface uses BaseApp, Sysutils, UtilsHttp, win.iobuffer, define_dealitem, StockDayDataAccess; type TDealDayDataHeadName_Sina = ( headNone, // 0 headDay, // 1 日期, headPrice_Open, // 7开盘价, headPrice_High, // 5最高价, headPrice_Close, // 4收盘价, headPrice_Low, // 6最低价, headDeal_Volume, // 12成交量, headDeal_Amount, // 13成交金额, headDeal_WeightFactor ); // 15流通市值); PRT_DealDayData_HeaderSina = ^TRT_DealDayData_HeaderSina; TRT_DealDayData_HeaderSina = record HeadNameIndex : array[TDealDayDataHeadName_Sina] of SmallInt; end; const DealDayDataHeadNames_Sina: array[TDealDayDataHeadName_Sina] of string = ( '', '日期', '开盘价', '最高价', '收盘价', '最低价', '交易量(股)', '交易金额(元)', '复权因子' ); const BaseSinaIndexDayUrl1 = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/'; (*// 新浪没找到 搜狐倒是找到了 http://q.stock.sohu.com/zs/000001/cjmx.shtml 上证指数 http://q.stock.sohu.com/zs/000300/cjmx.shtml 沪深 300 http://www.cnindex.com.cn/ //*) (*// // 上证指数 // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml?year=2015&jidu=1 深圳成分 http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/399001/type/S.phtml 沪深 300 http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000300/type/S.phtml //*) var DateFormat_Sina: Sysutils.TFormatSettings;(*// =( CurrencyString: ''; DateSeparator: '-'; TimeSeparator: ':'; ListSeparator: ';'; ShortDateFormat : 'yyyy-mm-dd'; LongDateFormat : 'yyyy-mm-dd'; );//*) function GetStockIndexData_Sina(App: TBaseApp; AStockItem: PRT_DealItem; AIsWeight: Boolean; ANetSession: PHttpClientSession): Boolean; implementation uses Classes, Windows, define_price, Define_DataSrc, define_stock_quotes, UtilsHtmlParser, UtilsDateTime, UtilsLog, StockDayData_Load, StockDayData_Save; function GetStockIndexData_Sina(App: TBaseApp; AStockItem: PRT_DealItem; AIsWeight: Boolean; ANetSession: PHttpClientSession): Boolean; begin Result := false; end; initialization FillChar(DateFormat_Sina, SizeOf(DateFormat_Sina), 0); DateFormat_Sina.DateSeparator := '-'; DateFormat_Sina.TimeSeparator := ':'; DateFormat_Sina.ListSeparator := ';'; DateFormat_Sina.ShortDateFormat := 'yyyy-mm-dd'; DateFormat_Sina.LongDateFormat := 'yyyy-mm-dd'; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StTxtDat.pas 4.04 *} {*********************************************************} {* SysTools: Formatted Text Data Handling *} {*********************************************************} {$include StDefine.inc} unit StTxtDat; interface uses SysUtils, Classes, TypInfo, StConst, StBase, StStrms, StStrL; const StDefaultDelim = ','; StDefaultQuote = '"'; StDefaultComment = ';'; StDefaultFixedSep = ' '; {!!.01} StDefaultLineTerm = #13#10; St_WhiteSpace = #8#9#10#13' '; {page feed, tab, LF, CR, space} {!!.01} type TStSchemaLayoutType = (ltUnknown, ltFixed, ltVarying); TStSchemaFieldType = (sftUnknown, sftChar, sftFloat, sftNumber, sftBool, sftLongInt, sftDate, sftTime, sftTimeStamp); TStOnQuoteFieldEvent = procedure (Sender : TObject; var Field : String) of object; { Text Data Layout descriptors (Schemas)} TStDataField = class protected {private} FFieldDecimals: Integer; FFieldLen: Integer; FFieldName: String; FFieldOffset: Integer; FFieldType: TStSchemaFieldType; function GetAsString: String; procedure SetFieldDecimals(const Value: Integer); procedure SetFieldLen(const Value: Integer); procedure SetFieldName(const Value: String); procedure SetFieldOffset(const Value: Integer); procedure SetFieldType(const Value: TStSchemaFieldType); public { properties } property AsString : String read GetAsString; property FieldDecimals: Integer read FFieldDecimals write SetFieldDecimals; property FieldLen: Integer read FFieldLen write SetFieldLen; property FieldName : String read FFieldName write SetFieldName; property FieldOffset: Integer read FFieldOffset write SetFieldOffset; property FieldType: TStSchemaFieldType read FFieldType write SetFieldType; end; TStDataFieldList = class private FList : TStringList; protected {private} function GetCount: Integer; function GetField(Index: Integer): TStDataField; function GetFieldByName(const FieldName: String): TStDataField; procedure SetField(Index: Integer; const Value: TStDataField); procedure SetFieldByName(const FieldName: String; const Value: TStDataField); public constructor Create; destructor Destroy; override; { Access and Update Methods } procedure AddField(const FieldName: String; FieldType: TStSchemaFieldType; FieldLen, FieldDecimals, FieldOffset: Integer); procedure AddFieldStr(const FieldDef : String); procedure Clear; procedure RemoveField(const FieldName: String); { properties } property Count : Integer read GetCount; property Fields[Index : Integer] : TStDataField read GetField write SetField; default; property FieldByName[const FieldName: String] : TStDataField read GetFieldByName write SetFieldByName; end; TStTextDataSchema = class private FCommentDelimiter: Char; FFieldDelimiter: Char; FLayoutType: TStSchemaLayoutType; FLineTermChar : Char; FLineTerminator : TStLineTerminator; FQuoteDelimiter: Char; FFixedSeparator : Char; {!!.01} FSchema: TStrings; FSchemaName: String; dsFieldList : TStDataFieldList; protected {private} function GetCaptions: TStrings; function GetField(Index: Integer): TStDataField; function GetFieldByName(const FieldName: String): TStDataField; function GetFieldCount: Integer; function GetSchema: TStrings; procedure SetCommentDelimiter(const Value: Char); procedure SetField(Index: Integer; const Value: TStDataField); procedure SetFieldByName(const FieldName: String; const Value: TStDataField); procedure SetFieldDelimiter(const Value: Char); procedure SetLayoutType(const Value: TStSchemaLayoutType); procedure SetQuoteDelimiter(const Value: Char); procedure SetFixedSeparator(const Value: Char); {!!.01} procedure SetSchema(const Value: TStrings); procedure SetSchemaName(const Value: String); public constructor Create; destructor Destroy; override; procedure Assign(ASchema : TStTextDataSchema); { Access and Update Methods } procedure AddField(const FieldName : String; FieldType : TStSchemaFieldType; FieldLen, FieldDecimals : Integer); function IndexOf(const FieldName : String) : Integer; procedure RemoveField(const FieldName: String); procedure Update(AList : TStrings); {!!.01} procedure ClearFields; {!!.01} procedure BuildSchema(AList: TStrings); {!!.01} { Persistence and streaming methods } procedure LoadFromFile(const AFileName : TFileName); procedure LoadFromStream(AStream : TStream); procedure SaveToFile(const AFileName : TFileName); procedure SaveToStream(AStream : TStream); { properties } property Captions : TStrings read GetCaptions; property CommentDelimiter : Char read FCommentDelimiter write SetCommentDelimiter default StDefaultComment; property FieldByName[const FieldName: String] : TStDataField read GetFieldByName write SetFieldByName; property FieldCount : Integer read GetFieldCount; property FieldDelimiter : Char read FFieldDelimiter write SetFieldDelimiter default StDefaultDelim; property Fields[Index : Integer] : TStDataField read GetField write SetField; default; property LayoutType : TStSchemaLayoutType read FLayoutType write SetLayoutType; property LineTermChar : Char read FLineTermChar write FLineTermChar default #0; property LineTerminator : TStLineTerminator read FLineTerminator write FLineTerminator default ltCRLF; property QuoteDelimiter : Char read FQuoteDelimiter write SetQuoteDelimiter default StDefaultQuote; property FixedSeparator : Char {!!.01} read FFixedSeparator write SetFixedSeparator default StDefaultFixedSep; {!!.01} property Schema : TStrings read GetSchema write SetSchema; property SchemaName : String read FSchemaName write SetSchemaName; end; { Text Data Records and Data Sets } TStTextDataRecord = class private FFieldList: TStrings; FQuoteAlways: Boolean; FQuoteIfSpaces: Boolean; FSchema: TStTextDataSchema; FValue : String; FOnQuoteField : TStOnQuoteFieldEvent; protected {private} function GetField(Index: Integer): String; function GetFieldCount: Integer; function GetFieldByName(const FieldName: String): String; function GetFieldList: TStrings; function GetValues: TStrings; procedure SetField(Index: Integer; const NewValue: String); procedure SetFieldByName(const FieldName: String; const NewValue: String); procedure SetQuoteAlways(const Value: Boolean); procedure SetQuoteIfSpaces(const Value: Boolean); procedure SetSchema(const Value: TStTextDataSchema); public constructor Create; destructor Destroy; override; { Access and Update Methods } procedure BuildRecord(Values: TStrings; var NewRecord: String); virtual; function GetRecord : String; {!!.02} procedure DoQuote(var Value: String); virtual; procedure FillRecordFromArray(Values: array of const); procedure FillRecordFromList(Items: TStrings); procedure FillRecordFromValues(Values: TStrings); procedure MakeEmpty; virtual; { properties } property AsString : String {!!.02} // read FValue {write SetValue}; {!!.02} read GetRecord; property FieldByName[const FieldName : String] : String read GetFieldByName write SetFieldByName; property FieldCount : Integer read GetFieldCount; property FieldList : TStrings read GetFieldList; property Fields[Index : Integer] : String read GetField write SetField; property QuoteAlways : Boolean read FQuoteAlways write SetQuoteAlways default False; property QuoteIfSpaces : Boolean read FQuoteIfSpaces write SetQuoteIfSpaces default False; property Schema : TStTextDataSchema read FSchema write SetSchema; property Values : TStrings read GetValues; { events } property OnQuoteField : TStOnQuoteFieldEvent read FOnQuoteField write FOnQuoteField; end; TStTextDataRecordSet = class private FActive: Boolean; FCurrentIndex : Integer; FIsDirty: Boolean; FRecords: TList; FSchema: TStTextDataSchema; FAtEndOfFile : Boolean; {!!.01} FIgnoreStartingLines : Integer; {!!.02} protected {private} function GetCount: Integer; function GetCurrentRecord: TStTextDataRecord; function GetRecord(Index: Integer): TStTextDataRecord; function GetSchema: TStTextDataSchema; procedure SetActive(const Value: Boolean); procedure SetCurrentRecord(const Value: TStTextDataRecord); procedure SetRecord(Index: Integer; const Value: TStTextDataRecord); procedure SetSchema(const Value: TStTextDataSchema); public constructor Create; destructor Destroy; override; { Access and Update Methods } procedure Append; procedure AppendArray(Values : array of const); procedure AppendList(Items : TStrings); procedure AppendValues(Values : TStrings); procedure Clear; procedure Delete; procedure Insert(Index : Integer); procedure InsertArray(Index: Integer; Values : array of const); procedure InsertList(Index : Integer; Items : TStrings); procedure InsertValues(Index : Integer; Values : TStrings); { navigation methods } function BOF : Boolean; function EOF : Boolean; procedure First; procedure Last; function Next : Boolean; function Prior : Boolean; { Persistence and streaming methods } procedure LoadFromFile(const AFile : TFileName); procedure LoadFromStream(AStream : TStream); procedure SaveToFile(const AFile : TFileName); procedure SaveToStream(AStream : TStream); { properties } property Active : Boolean read FActive write SetActive; property Count : Integer read GetCount; property CurrentRecord : TStTextDataRecord read GetCurrentRecord write SetCurrentRecord; property IsDirty : Boolean read FIsDirty; property Records[Index : Integer] : TStTextDataRecord read GetRecord write SetRecord; property Schema : TStTextDataSchema read GetSchema write SetSchema; property IgnoreStartingLines : Integer {!!.02} read FIgnoreStartingLines write FIgnoreStartingLines default 0; {!!.02} end; procedure StParseLine(const Data : String; Schema : TStTextDataSchema; Result : TStrings); function StFieldTypeToStr(FieldType : TStSchemaFieldType) : String; function StStrToFieldType(const S : String) : TStSchemaFieldType; function StDeEscape(const EscStr : String): Char; function StDoEscape(Delim : Char): String; function StTrimTrailingChars(const S : String; Trailer : Char) : String; {!!.01} implementation procedure StParseLine(const Data : String; Schema : TStTextDataSchema; Result : TStrings); { split a line of delimited data according to provided schema into <name>=<value> pairs into Result } var DataLine : TStTextDataRecord; ownSchema : Boolean; begin { need a valid TStrings to work with } if not Assigned(Result) then Exit; ownSchema := False; { if no Schema to use passed in, create a default schema } if not Assigned(Schema) then begin Schema := TStTextDataSchema.Create; ownSchema := True; { we made it we, s have to free it } end; DataLine := TStTextDataRecord.Create; try DataLine.Schema := Schema; DataLine.FValue := Data; Result.Assign(DataLine.FieldList); finally DataLine.Free; { free the Schema if needed } if ownSchema then Schema.Free; end; end; { TStDataField } function StFieldTypeToStr(FieldType : TStSchemaFieldType) : String; { convert TStSchemaFieldType enum into matching string for BDE schema } begin Result := ''; case FieldType of sftChar : Result := 'CHAR'; sftFloat : Result := 'FLOAT'; sftNumber : Result := 'NUMBER'; sftBool : Result := 'BOOL'; sftLongInt : Result := 'LONGINT'; sftDate : Result := 'DATE'; sftTime : Result := 'TIME'; sftTimeStamp : Result := 'TIMESTAMP'; else Result := ''; end; end; function StStrToFieldType(const S : String) : TStSchemaFieldType; { convert string to TStSchemaFieldType constant } var Value : Integer; begin Value := GetEnumValue(TypeInfo(TStSchemaFieldType), S); if Value > -1 then Result := TStSchemaFieldType(Value) else Result := sftUnknown; end; {!!.01 - Added} function StTrimTrailingChars(const S : String; Trailer : Char) : String; { Return a string with specified trailing character removed, useful for cleanup of fixed data records } var Len : Integer; begin Result := S; Len := Length(S); while (Len > 0) and (Result[Len] = Trailer) do Dec(Len); SetLength(Result, Len); end; {!!.01 - End Added} function TStDataField.GetAsString: String; { build string representation of field to match BDE style } { Format : <name>,<type>,<width>,<decimals>,<offset> } begin Result := FFieldName + ',' + StFieldTypeToStr(FFieldType) + ',' + { zero pad width, decimals, and offset to at least two places to match BDE Schema formatting } Format('%.2d,%.2d,%.2d', [FFieldLen, FFieldDecimals, FFieldOffset]); end; procedure TStDataField.SetFieldDecimals(const Value: Integer); begin FFieldDecimals := Value; end; procedure TStDataField.SetFieldLen(const Value: Integer); begin FFieldLen := Value; end; procedure TStDataField.SetFieldName(const Value: String); begin FFieldName := Value; end; procedure TStDataField.SetFieldOffset(const Value: Integer); begin FFieldOffset := Value; end; procedure TStDataField.SetFieldType(const Value: TStSchemaFieldType); begin FFieldType := Value; end; { TStDataFieldList } function CharPosIdx(C: Char; const S : String; Idx: Integer): Integer; { Find leftmost occurrence of character C in string S past location Idx } { If C not found returns 0 } var Len : Integer; begin Len := Length(S); if (Idx > Len) or (Idx < 1) then begin Result := 0; Exit; end; Result := Idx; while (Result <= Len) and (S[Result] <> C) do Inc(Result); if Result > Len then Result := 0; end; procedure SplitFieldStr(const Source: String; var Name: String; var FieldType: TStSchemaFieldType; var ValLen, Decimals, Offset: Integer); { split field description string according to BDE Schema layout } { Format : <name>,<type>,<width>,<decimals>,<offset> } var CommaPos, LastPos : Cardinal; TempS : String; begin CommaPos := 1; LastPos := CommaPos; CommaPos := CharPosIdx(',', Source, CommaPos); if CommaPos = 0 then CommaPos := Length(Source) + 1; Name := Copy(Source, LastPos, CommaPos - LastPos); Inc(CommaPos); LastPos := CommaPos; CommaPos := CharPosIdx(',', Source, CommaPos); if CommaPos = 0 then CommaPos := Length(Source) + 1; TempS := Copy(Source, LastPos, CommaPos - LastPos); FieldType := StStrToFieldType('sft' + TempS); Inc(CommaPos); LastPos := CommaPos; CommaPos := CharPosIdx(',', Source, CommaPos); if CommaPos = 0 then CommaPos := Length(Source) + 1; ValLen := StrToInt(Copy(Source, LastPos, CommaPos - LastPos)); Inc(CommaPos); LastPos := CommaPos; CommaPos := CharPosIdx(',', Source, CommaPos); if CommaPos = 0 then CommaPos := Length(Source) + 1; Decimals := StrToInt(Copy(Source, LastPos, CommaPos - LastPos)); Inc(CommaPos); LastPos := CommaPos; CommaPos := CharPosIdx(',', Source, CommaPos); if CommaPos = 0 then CommaPos := Length(Source) + 1; Offset := StrToInt(Copy(Source, LastPos, CommaPos - LastPos)); end; constructor TStDataFieldList.Create; begin inherited Create; FList := TStringList.Create; end; destructor TStDataFieldList.Destroy; begin FList.Free; inherited Destroy; end; procedure TStDataFieldList.AddField(const FieldName: String; FieldType: TStSchemaFieldType; FieldLen, FieldDecimals, FieldOffset: Integer); var Item : TStDataField; Idx : Integer; begin { see if another field with the name exists } Idx := FList.IndexOf(FieldName); if (Idx > -1) then raise EStException.CreateResTP(stscTxtDatUniqueNameRequired, 0); { build new item } Item := TStDataField.Create; try Item.FieldName := FieldName; Item.FieldType := FieldType; Item.FieldLen := FieldLen; Item.FieldDecimals := FieldDecimals; Item.FieldOffset := FieldOffset; { add to list } FList.AddObject(FieldName, Item); except Item.Free; end; end; procedure TStDataFieldList.AddFieldStr(const FieldDef: String); var Name: String; FieldType: TStSchemaFieldType; ValLen, Decimals, Offset: Integer; begin SplitFieldStr(FieldDef, Name, FieldType, ValLen, Decimals, Offset); AddField(Name, FieldType, ValLen, Decimals, Offset); end; procedure TStDataFieldList.Clear; var Idx : Integer; begin for Idx := Pred(FList.Count) downto 0 do begin { Free associated object and then delete the StringList entry } FList.Objects[Idx].Free; FList.Delete(Idx); end; end; procedure TStDataFieldList.RemoveField(const FieldName: String); var Idx : Integer; begin { locate field } Idx := FList.IndexOf(FieldName); { if it exists } if Idx > -1 then begin { Free associated object and then delete the StringList entry } FList.Objects[Idx].Free; FList.Delete(Idx); end else { no such field, complain... } raise EStException.CreateResTP(stscTxtDatNoSuchField, 0); end; function TStDataFieldList.GetFieldByName( const FieldName: String): TStDataField; var Idx : Integer; begin { locate field } Idx := FList.IndexOf(FieldName); { if it exists } if Idx > -1 then begin { return associated object } Result := TStDataField(FList.Objects[Idx]); end else { no such field, complain... } raise EStException.CreateResTP(stscTxtDatNoSuchField, 0); end; function TStDataFieldList.GetField(Index: Integer): TStDataField; { return requested field if in range } begin if (Index > -1) and (Index < FList.Count) then Result := TStDataField(FList.Objects[Index]) else { no such field, complain... } raise EStException.CreateResTP(stscBadIndex, 0); end; procedure TStDataFieldList.SetFieldByName(const FieldName: String; const Value: TStDataField); var Idx : Integer; begin { see if another field with the name exists } Idx := FList.IndexOf(FieldName); { delete field at that index replace with new field } if (Idx > -1) then begin FList.Objects[Idx].Free; FList.Objects[Idx] := Value; end else { no such field, complain... } raise EStException.CreateResTP(stscTxtDatNoSuchField, 0); end; procedure TStDataFieldList.SetField(Index: Integer; const Value: TStDataField); var Idx : Integer; begin { see if another field with the name exists } Idx := FList.IndexOf(Value.FieldName); if (Idx > -1) and (Idx <> Index) then raise EStException.CreateResTP(stscTxtDatUniqueNameRequired, 0); { delete field at that index replace with new field } if (Index > -1) and (Index < FList.Count) then begin RemoveField(FList[Index]); FList.InsertObject(Index, Value.FieldName, Value); end else { no such field, complain... } raise EStException.CreateResTP(stscBadIndex, 0); end; function TStDataFieldList.GetCount: Integer; { return count of maintained Field Items } begin Result := FList.Count; end; { TStTextDataSchema } constructor TStTextDataSchema.Create; begin inherited Create; { set default values } FFieldDelimiter := StDefaultDelim; FQuoteDelimiter := StDefaultQuote; FCommentDelimiter := StDefaultComment; FFixedSeparator := StDefaultFixedSep; {!!.01} FLineTermChar := #0; FLineTerminator := ltCRLF; FLayoutType := ltUnknown; { create internal instances } dsFieldList := TStDataFieldList.Create; FSchema := TStringList.Create; end; destructor TStTextDataSchema.Destroy; begin { clean up the fields list } dsFieldList.Clear; { free internal instances } dsFieldList.Free; FSchema.Free; inherited Destroy; end; procedure TStTextDataSchema.AddField(const FieldName : String; FieldType : TStSchemaFieldType; FieldLen, FieldDecimals : Integer); { add new field with requested characteristics } var Offset : Integer; LastField : TStDataField; begin { calculate the offset based on the length and offset of previous fields } if dsFieldList.Count > 0 then begin LastField := dsFieldList.Fields[Pred(dsFieldList.Count)]; Offset := LastField.FieldOffset + LastField.FieldLen; end else Offset := 0; dsFieldList.AddField(FieldName, FieldType, FieldLen, FieldDecimals, Offset); end; procedure TStTextDataSchema.Assign(ASchema: TStTextDataSchema); { deep copy another schema } var i : Integer; begin if not Assigned(ASchema) then Exit; { copy properties } FLayoutType := ASchema.LayoutType; FFieldDelimiter := ASchema.FieldDelimiter; FCommentDelimiter := ASchema.CommentDelimiter; FQuoteDelimiter := ASchema.QuoteDelimiter; FSchemaName := ASchema.SchemaName; FLineTermChar := ASchema.LineTermChar; FLineTerminator := ASchema.LineTerminator; { copy fields } dsFieldList.Clear; for i := 0 to Pred(ASchema.FieldCount) do dsFieldList.AddFieldStr(ASchema.Fields[i].AsString); end; {!!.01 -- Added } procedure TStTextDataSchema.BuildSchema(AList : TStrings); var i : Integer; Field : TStDataField; begin { put schema name in brackets } AList.Add('[' + FSchemaName + ']'); { layout type } if FLayoutType = ltVarying then begin AList.Add('FileType=VARYING'); AList.Add('Separator=' + StDoEscape(FFieldDelimiter)); end else begin AList.Add('FileType=FIXED'); AList.Add('Separator=' + StDoEscape(FFixedSeparator)); end; { other parameters } AList.Add('Delimiter=' + StDoEscape(FQuoteDelimiter)); AList.Add('Comment=' + StDoEscape(FCommentDelimiter)); AList.Add('CharSet=ASCII'); { write fields } for i := 0 to Pred(dsFieldList.Count) do begin Field := dsFieldList.Fields[i]; AList.Add('Field' + IntToStr(i + 1) + '=' + Field.AsString); end; end; {!!.01 -- End Added } {!!.01 -- Added } procedure TStTextDataSchema.ClearFields; { remove field definitions from schema } var i : Integer; begin dsFieldList.Clear; for i := Pred(FSchema.Count) downto 0 do if Pos('Field', Trim(FSchema[i])) = 1 then FSchema.Delete(i); end; {!!.01 -- End Added } function TStTextDataSchema.GetCaptions: TStrings; begin Result := dsFieldList.FList; end; function TStTextDataSchema.GetFieldByName(const FieldName: String): TStDataField; begin Result := dsFieldList.FieldByName[FieldName]; end; function TStTextDataSchema.GetFieldCount: Integer; begin Result := dsFieldList.Count; end; function TStTextDataSchema.GetField(Index: Integer): TStDataField; begin Result := dsFieldList.Fields[Index]; end; {!!.01 -- Added } function TStTextDataSchema.GetSchema: TStrings; begin FSchema.Clear; BuildSchema(FSchema); Result := FSchema; end; {!!.01 -- End Added } function TStTextDataSchema.IndexOf(const FieldName : String): Integer; { return index of field with provided name, returns -1 if no such field is found } begin Result := 0; while (Result < dsFieldList.Count) and // (dsFieldList.Fields[Result].FieldName <> FieldName) do {!!.01} (AnsiCompareText(dsFieldList.Fields[Result].FieldName, {!!.01} FieldName) <> 0) {!!.01} do {!!.01} Inc(Result); if Result >= dsFieldList.Count then Result := -1; { not found } end; procedure TStTextDataSchema.LoadFromFile(const AFileName: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try LoadFromStream(FS); finally FS.Free; end; end; function StDoEscape(Delim : Char): String; { Escapes non-printable characters to Borlandish Pascal "#nnn" constants } begin if CharInSet(Delim, [#33..#126, #128..#255]) then Result := Delim else Result := '#' + IntToStr(Ord(Delim)); end; function StDeEscape(const EscStr : String): Char; { converts "escaped" strings of the forms: "#nn" Borlandish Pascal numeric character constants ^l Borlandish Pascal control character constants into equivalent characters, "##" is treated as the '#' character alone if the string doesn't constitute such an escape sequence, the first character is returned } var S : String; C : Char; ChrVal : Byte; begin S := Trim(EscStr); { if string doesn't start with escape or it's only one character long just return first character } if (Length(S) = 1) or ((S[1] <> '#') and (S[1] <> '^')) then begin Result := S[1]; Exit; end; { treat '##' as escape for '#' and '^^' as escape for '^' } if ((S[1] = '#') and (S[2] = '#')) or ((S[1] = '^') and (S[2] = '^')) then begin Result := '#'; Exit; end; { otherwise try to handle escaped character } case S[1] of '#':begin ChrVal := StrToIntDef(Copy(S, 2,Length(S)-1), Ord(StDefaultDelim)); if CharInSet(Chr(ChrVal), [#1..#126]) then Result := Chr(ChrVal) else Result := StDefaultDelim; end; '^': begin { control character format } C := Chr(Ord(S[2]) - $40); if CharInSet(C, [^A..^_]) then Result := C else Result := StDefaultDelim; end; else Result := S[1]; end; {case} end; procedure TStTextDataSchema.LoadFromStream(AStream: TStream); var TS : TStAnsiTextStream; begin TS := TStAnsiTextStream.Create(AStream); try FSchema.Clear; {!!.01} while not TS.AtEndOfStream do FSchema.Add(string(TS.ReadLine)); { code to extract Schema properties moved to Update routine } {!!.01} Update(FSchema); {!!.01} finally TS.Free; end; end; procedure TStTextDataSchema.RemoveField(const FieldName: String); begin dsFieldList.RemoveField(FieldName); end; procedure TStTextDataSchema.SaveToFile(const AFileName: TFileName); var FS : TFileStream; begin if not FileExists(AFileName) then begin FS := TFileStream.Create(AFileName, fmCreate); FS.Free; end; if FSchemaName = '' then FSchemaName := JustNameL(AFileName); FS := TFileStream.Create(AFileName, fmOpenWrite or fmShareDenyNone); try SaveToStream(FS); finally FS.Free; end; end; { General format of a Schema file, based on BDE ASCII driver schema files: ; this is a comment [NAME] Filetype=<VARYING>|<FIXED> Separator=char (default = ',' comma) Delimiter=char (default = '"' double quote) FieldN=<FieldName>,<FieldType>,<FieldWidth>,<FieldDecimals>,<FieldOffset> ; example fields: Field1=Name,CHAR,20,00,00 Field2=Rating,CHAR,2,00,20 Field3=Date,DATE,10,00,22 Field4=Weight,Float,7,2,32 } {!!.01 -- Rewritten} procedure TStTextDataSchema.SaveToStream(AStream: TStream); var TS : TStAnsiTextStream; i : Integer; SL : TStringList; begin SL := nil; TS := nil; try SL := TStringList.Create; BuildSchema(SL); TS := TStAnsiTextStream.Create(AStream); for i := 0 to Pred(SL.Count) do TS.WriteLine(SL[i]); finally TS.Free; SL.Free; end; end; {!!.01 -- End Rewritten} procedure TStTextDataSchema.SetCommentDelimiter(const Value: Char); begin FCommentDelimiter := Value; end; procedure TStTextDataSchema.SetFieldByName(const FieldName: String; const Value: TStDataField); begin dsFieldList.FieldByName[FieldName] := Value; end; procedure TStTextDataSchema.SetFieldDelimiter(const Value: Char); begin FFieldDelimiter := Value; end; procedure TStTextDataSchema.SetField(Index: Integer; const Value: TStDataField); begin dsFieldList.Fields[Index] := Value; end; {!!.01 -- Added } procedure TStTextDataSchema.SetFixedSeparator(const Value: Char); begin FFixedSeparator := Value; end; {!!.01 -- End Added } procedure TStTextDataSchema.SetLayoutType(const Value: TStSchemaLayoutType); begin FLayoutType := Value; end; procedure TStTextDataSchema.SetQuoteDelimiter(const Value: Char); begin FQuoteDelimiter := Value; end; procedure TStTextDataSchema.SetSchema(const Value: TStrings); begin FSchema.Assign(Value); {!!.01} Update(FSchema); {!!.01} end; procedure TStTextDataSchema.SetSchemaName(const Value: String); begin FSchemaName := Value; end; {!!.01 -- Added } procedure TStTextDataSchema.Update(AList : TStrings); var ValStr : String; Idx : Integer; begin for Idx := 0 to Pred(AList.Count) do begin ValStr := AList[Idx]; { if line isn't blank } if ValStr <> '' then begin { assume it's the schema name } if (ValStr[1] = '[') and (ValStr[Length(ValStr)] = ']') then SchemaName := Copy(ValStr, 2, Length(ValStr) - 2) else { assume the line is a comment } if ValStr[1] = FCommentDelimiter {';'} then { ignore it }; { else, it's blank, so skip it } end; end; { extract other Schema Info } { get layout type } ValStr := AList.Values['Filetype']; if UpperCase(ValStr) = 'VARYING' then FLayoutType := ltVarying else if UpperCase(ValStr) = 'FIXED' then FLayoutType := ltFixed else FLayoutType := ltUnknown; { get field separator for schema } ValStr := AList.Values['Separator']; if Length(ValStr) > 0 then FFieldDelimiter := StDeEscape(ValStr) else case FLayoutType of {!!.01} ltFixed : FFieldDelimiter := StDefaultFixedSep; {!!.01} ltVarying: FFieldDelimiter := StDefaultDelim; {!!.01} end; {!!.01} { get quote delimiter for schema } ValStr := AList.Values['Delimiter']; if Length(ValStr) > 0 then FQuoteDelimiter := StDeEscape(ValStr) else FQuoteDelimiter := StDefaultQuote; { get quote delimiter for schema } ValStr := AList.Values['Comment']; if Length(ValStr) > 0 then FCommentDelimiter := StDeEscape(ValStr) else FCommentDelimiter := StDefaultQuote; { build fields list } Idx := 1; dsFieldList.Clear; ValStr := AList.Values['Field' + IntToStr(Idx)]; while ValStr <> '' do begin dsFieldList.AddFieldStr(ValStr); Inc(Idx); ValStr := AList.Values['Field' + IntToStr(Idx)]; end; end; {!!.01 -- End Added } { TStTextDataRecord } constructor TStTextDataRecord.Create; begin inherited Create; { set default values } FValue := ''; FQuoteAlways := False; FQuoteIfSpaces := False; { create internal instances } FFieldList := TStringList.Create; end; destructor TStTextDataRecord.Destroy; begin { free internal instances } FFieldList.Free; inherited Destroy; end; procedure TStTextDataRecord.BuildRecord(Values : TStrings; var NewRecord : String); { re-construct record structure from list of field values } var i : Integer; Temp : String; begin NewRecord := ''; for i := 0 to Pred(Values.Count) do begin Temp := Values[i]; { re-quote value if needed } DoQuote(Temp); { add value onto record } if i = 0 then NewRecord := Temp else NewRecord := NewRecord + FSchema.FieldDelimiter + Temp; end; end; procedure TStTextDataRecord.DoQuote(var Value : String); { quote field string if needed or desired } var QuoteIt : Boolean; begin { fire event if available } if Assigned(FOnQuoteField) then begin FOnQuoteField(self, Value); end else begin { use default quoting policy } QuoteIt := False; if FQuoteAlways then QuoteIt := True else if ((Pos(' ', Value) > 0) and FQuoteIfSpaces) or (Pos(FSchema.FieldDelimiter, Value) > 0) then QuoteIt := True; if QuoteIt then Value := FSchema.QuoteDelimiter + Value + FSchema.QuoteDelimiter; end; end; function ConvertValue(Value : TVarRec) : String; { convert variant record to equivalent string } const BoolChars: array[Boolean] of Char = ('F', 'T'); begin case Value.VType of vtAnsiString: Result := string(Value.VAnsiString); vtUnicodeString: Result := string(Value.VUnicodeString); vtWideString: Result := WideString(Value.VWideString); vtBoolean: Result := BoolChars[Value.VBoolean]; vtChar: Result := string(Value.VChar); vtCurrency: Result := CurrToStr(Value.VCurrency^); vtExtended: Result := FloatToStr(Value.VExtended^); vtInteger: Result := IntToStr(Value.VInteger); vtPChar: Result := string(Value.VPChar); vtString: Result := string(Value.VString^); vtInt64: Result := IntToStr(Value.VInt64^); else raise EStException.CreateResTP(stscTxtDatUnhandledVariant, 0); end; end; procedure TStTextDataRecord.FillRecordFromArray(Values : array of const); { supply field values from a variant open array } var i, j : Integer; begin if Length(Values) > 0 then begin i := 0; j := Low(Values); while (j <= High(Values)) and (i < Schema.FieldCount) do begin SetField(i, ConvertValue(Values[j])); Inc(i); Inc(j); end; end; end; procedure TStTextDataRecord.FillRecordFromList(Items : TStrings); { supply field values from <name>=<value> pairs } { Fields filled from pairs provided in TStrings <NAME> entries in Items that don't match Field Names are ignored Fields with Names having no corresponding entry in Items are left empty } var i : Integer; FN : String; begin if Assigned(Items) then begin for i := 0 to Pred(Schema.FieldCount) do begin FN := Schema.Fields[i].FieldName; FieldByName[FN] := Items.Values[FN]; end; end; end; procedure TStTextDataRecord.FillRecordFromValues(Values : TStrings); { supply field values from a list of values } { Fields filled from Values provided in TStrings if more Values than Fields, extras are ignored if fewer Values than Fields, remaining Fields are left empty } var i : Integer; begin if Assigned(Values) then begin i := 0; while (i < Values.Count) and (i < Schema.FieldCount) do begin SetField(i, Values[i]); Inc(i); end; end; end; function TStTextDataRecord.GetFieldByName(const FieldName: String): String; { retrieve value of field in current record with given name } var Idx : Integer; begin Result := ''; Idx := FSchema.IndexOf(FieldName); if Idx > -1 then Result := GetField(Idx) else raise EStException.CreateResTP(stscTxtDatNoSuchField, 0); end; function TStTextDataRecord.GetField(Index: Integer): String; { retrieve value of field in current record at given index } var Len, Offset: Integer; DataField : TStDataField; Fields : TStringList; begin if (Index < -1) or (Index > Pred(FSchema.FieldCount)) then raise EStException.CreateResTP(stscBadIndex, 0); { get characteristics of the field of interest } DataField := FSchema.Fields[Index]; Len := DataField.FieldLen; { Decimals := DataField.FieldDecimals; } Offset := DataField.FFieldOffset; { extract field data from record } case FSchema.LayoutType of ltFixed : begin { note: Offset is zero based, strings are 1 based } {!!.01} Result := Copy(FValue, Offset + 1, Len); {!!.01} end; ltVarying : begin Fields := TStringList.Create; try ExtractTokensL(FValue, FSchema.FieldDelimiter, FSchema.QuoteDelimiter, True, Fields); Result := Fields[Index]; finally Fields.Free; end; end; ltUnknown : begin raise EStException.CreateResTP(stscTxtDatInvalidSchema, 0); end; end; {case} end; function TStTextDataRecord.GetFieldCount: Integer; begin GetFieldList; {!!.02} Result := FFieldList.Count; end; function TStTextDataRecord.GetFieldList: TStrings; { convert fields of current record into TStrings collection of <name>=<value> pairs } var i : Integer; FN : String; begin FFieldList.Clear; for i := 0 to Pred(FSchema.FieldCount) do begin FN := FSchema.Fields[i].FieldName; FFieldList.Add(FN + '=' + FieldByName[FN]); end; Result := FFieldList; end; function TStTextDataRecord.GetValues: TStrings; var i : Integer; FN : String; begin FFieldList.Clear; for i := 0 to Pred(FSchema.FieldCount) do begin FN := FSchema.Fields[i].FieldName; FFieldList.Add(FieldByName[FN]); end; Result := FFieldList; end; procedure TStTextDataRecord.MakeEmpty; { create an empty record according to schema layout } var i, Width, FieldPos : Integer; begin case FSchema.LayoutType of { string of spaces, length equal to total record width } ltFixed: begin Width := 0; for i := 0 to Pred(FSchema.FieldCount) do begin {!!.01} FieldPos := FSchema.Fields[i].FieldLen + {!!.01} FSchema.Fields[i].FieldOffset + 1; {!!.01} if Width < FieldPos then {!!.01} Width := FieldPos; {!!.01} end; {!!.01} FValue := StringOfChar(FSchema.FixedSeparator, Width); {!!.01} end; { string of field separators, length equal to one less than no. of fields } ltVarying: begin FValue := StringOfChar(FSchema.FieldDelimiter, Pred(FSchema.FieldCount)); end; ltUnknown : begin raise EStException.CreateResTP(stscTxtDatInvalidSchema, 0); end; end; end; procedure TStTextDataRecord.SetFieldByName(const FieldName: String; const NewValue: String); { set value of field in current record with given name } var Idx : Integer; begin Idx := FSchema.IndexOf(FieldName); if Idx > -1 then SetField(Idx, NewValue) else raise EStException.CreateResTP(stscTxtDatNoSuchField, 0); end; procedure TStTextDataRecord.SetField(Index: Integer; const NewValue: String); { set value of field in current record at given index } var Len, Offset: Integer; Temp, FieldVal : String; Fields : TStringList; Idx : Integer; DataField : TStDataField; begin if (Index < -1) or (Index > Pred(FSchema.FieldCount)) then raise EStException.CreateResTP(stscBadIndex, 0); { get characteristics of the field of interest } DataField := FSchema.Fields[Index]; Len := DataField.FieldLen; Offset := DataField.FFieldOffset; Temp := ''; case FSchema.LayoutType of ltFixed : begin for Idx := 0 to Pred(FSchema.FieldCount) do begin if Idx = Index then begin { replace field with Value right buffered or trimmed to to fit field length } if Length(NewValue) < Len then FieldVal := PadChL(NewValue, FSchema.FFixedSeparator, Len) {!!.01} else FieldVal := Copy(NewValue, 1, Len); { note: Offset is zero based, strings are 1 based } Move(FieldVal[1], FValue[Offset + 1], Len * SizeOf(Char)); end; end; end; ltVarying : begin Fields := TStringList.Create; try { parse out the field values } ExtractTokensL(FValue, FSchema.FFieldDelimiter, {!!.01} FSchema.QuoteDelimiter, True, Fields); {!!.01} {!!.02 - rewritten } // { find field of interest } // for Idx := 0 to Pred(FSchema.FieldCount) do begin // if Idx = Index then // { set the new value } // Fields[Idx] := NewValue; { set field of interest } Fields[Index] := NewValue; { reconstruct the record } BuildRecord(Fields, FValue); // end; {!!.02 - rewritten end } finally Fields.Free; end; end; ltUnknown : begin raise EStException.CreateResTP(stscTxtDatInvalidSchema, 0); end; end; {case} end; procedure TStTextDataRecord.SetQuoteAlways(const Value: Boolean); begin FQuoteAlways := Value; end; procedure TStTextDataRecord.SetQuoteIfSpaces(const Value: Boolean); begin FQuoteIfSpaces := Value; end; procedure TStTextDataRecord.SetSchema(const Value: TStTextDataSchema); begin FSchema := Value; end; {!!.02 - Added } function TStTextDataRecord.GetRecord: String; var Idx : Integer; Field : String; begin Result := ''; for Idx := 0 to (FSchema.FieldCount - 2) do begin Field := self.Fields[Idx]; DoQuote(Field); Result := Result + Field + FSchema.FFieldDelimiter; end; Field := self.Fields[FSchema.FieldCount-1]; DoQuote(Field); Result := Result + Field; end; {!!.02 - End Added } { TStTextDataRecordSet } (* TStLineTerminator = ( {possible line terminators...} ltNone, {..no terminator, ie fixed length lines} ltCR, {..carriage return (#13)} ltLF, {..line feed (#10)} ltCRLF, {..carriage return/line feed (#13/#10)} ltOther); {..another character} *) constructor TStTextDataRecordSet.Create; begin inherited Create; FCurrentIndex := 0; FRecords := TList.Create; FIsDirty := False; FAtEndOfFile := False; {!!.01} FIgnoreStartingLines := 0; {!!.02} end; destructor TStTextDataRecordSet.Destroy; begin FRecords.Free; inherited Destroy; end; procedure TStTextDataRecordSet.Append; { append new empty record to dataset } var Rec : TStTextDataRecord; begin Rec := TStTextDataRecord.Create; Rec.Schema := Schema; Rec.MakeEmpty; FRecords.Add(Rec); FIsDirty := True; Last; end; procedure TStTextDataRecordSet.AppendArray(Values : array of const); { append new record to dataset, set field values from a variant open array } begin Append; CurrentRecord.FillRecordFromArray(Values); end; procedure TStTextDataRecordSet.AppendList(Items: TStrings); { append new record to dataset, set field values from <NAME>=<VALUE> pairs} begin Append; CurrentRecord.FillRecordFromList(Items); end; procedure TStTextDataRecordSet.AppendValues(Values: TStrings); { append new record to dataset, set field values from TStrings} begin Append; CurrentRecord.FillRecordFromValues(Values); end; function TStTextDataRecordSet.BOF: Boolean; { test if at beginning of record set } begin Result := (FCurrentIndex = 0); end; procedure TStTextDataRecordSet.Clear; { empty record set } var i : Integer; begin for i := 0 to Pred(FRecords.Count) do TStTextDataRecord(FRecords[i]).Free; FRecords.Clear; FIsDirty := False; end; procedure TStTextDataRecordSet.Delete; { delete record at current position } begin TStTextDataRecord(FRecords[FCurrentIndex]).Free; FRecords.Delete(FCurrentIndex); FIsDirty := True; Next; end; function TStTextDataRecordSet.EOF: Boolean; { test if at end of record set } begin if FAtEndOfFile then {!!.01} FAtEndOfFile := FCurrentIndex = Pred(FRecords.Count); {!!.01} Result := FAtEndOfFile {!!.01} end; procedure TStTextDataRecordSet.First; { make first record in set current } begin FCurrentIndex := 0; end; function TStTextDataRecordSet.GetCount: Integer; { return count of records in set } begin Result := FRecords.Count; end; function TStTextDataRecordSet.GetRecord(Index: Integer): TStTextDataRecord; { return particular record by index } begin if (Index > -1) and (Index < FRecords.Count) then Result := FRecords[Index] else raise EStException.CreateResTP(stscBadIndex, 0); end; function TStTextDataRecordSet.GetCurrentRecord: TStTextDataRecord; { return current record } begin Result := FRecords[FCurrentIndex]; end; function TStTextDataRecordSet.GetSchema: TStTextDataSchema; { return reference to associated schema, create default one if needed } begin if not Assigned(FSchema) then FSchema := TStTextDataSchema.Create; Result := FSchema; end; procedure TStTextDataRecordSet.Insert(Index: Integer); { insert new empty record into dataset at specified location, shifts the record set down one } var Rec : TStTextDataRecord; begin Rec := TStTextDataRecord.Create; Rec.Schema := Schema; Rec.MakeEmpty; FRecords.Insert(Index, Rec); FIsDirty := True; FCurrentIndex := Index; end; procedure TStTextDataRecordSet.InsertArray(Index: Integer; Values : array of const); { insert new record into dataset dataset at specified location, shifts the record set down one, set field values from a variant open array } begin Insert(Index); CurrentRecord.FillRecordFromArray(Values); end; procedure TStTextDataRecordSet.InsertList(Index: Integer; Items: TStrings); { insert new record into dataset dataset at specified location, shifts the record set down one, set field values from <NAME>=<VALUE> pairs} begin Insert(Index); CurrentRecord.FillRecordFromList(Items); end; procedure TStTextDataRecordSet.InsertValues(Index: Integer; Values: TStrings); { insert new record into dataset dataset at specified location, shifts the record set down one, set field values from TStrings} begin Insert(Index); CurrentRecord.FillRecordFromValues(Values); end; procedure TStTextDataRecordSet.Last; { make final record in set current } begin FCurrentIndex := Pred(FRecords.Count); end; procedure TStTextDataRecordSet.LoadFromFile(const AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmOpenRead or fmShareDenyNone); try LoadFromStream(FS); finally FS.Free; end; end; procedure TStTextDataRecordSet.LoadFromStream(AStream: TStream); var TS : TStAnsiTextStream; NewRec : TStTextDataRecord; i, Len : Integer; {!!.02} begin if FActive then raise EStException.CreateResTP(stscTxtDatRecordSetOpen, 0); Clear; TS := TStAnsiTextStream.Create(AStream); { match Ansi Stream terminator to schema's } TS.LineTermChar := AnsiChar(Schema.LineTermChar); TS.LineTerminator := Schema.LineTerminator; {!!.02 - added } { calculate length of fixed record } if Schema.LayoutType = ltFixed then begin Len := 0; for i := 0 to Pred(Schema.FieldCount) do Len := Len + Schema.Fields[i].FieldLen; TS.FixedLineLength := Len; end; {!!.02 - added end } try {!!.02 - added } { ignore starting lines } for i := 1 to FIgnoreStartingLines do TS.ReadLine; {!!.02 - added end } while not TS.AtEndOfStream do begin { new record } NewRec := TStTextDataRecord.Create; { set record data } NewRec.FValue := string(TS.ReadLine); {!!.01 - Rewritten } if TrimCharsL(NewRec.FValue, St_WhiteSpace) <> '' then begin { set the schema to match } NewRec.Schema := Schema; { append new record } FRecords.Add(NewRec); end else {ignore blank lines} NewRec.Free; {!!.01 - End Rewritten } end; FActive := True; FIsDirty := False; finally TS.Free; end; end; function TStTextDataRecordSet.Next : Boolean; { make next record in set current } begin Result := True; { if already on last record, stay there } if FCurrentIndex = Pred(FRecords.Count) then begin {!!.01} FAtEndOfFile := True; { yep, we're at the end } {!!.01} Result := False; {!!.01} end {!!.01} else {!!.01} Inc(FCurrentIndex); {!!.01} end; function TStTextDataRecordSet.Prior : Boolean; { make previous record in set current } begin Result := True; Dec(FCurrentIndex); { if already on first record, stay there } if FCurrentIndex < 0 then begin FCurrentIndex := 0; Result := False; end; end; procedure TStTextDataRecordSet.SaveToFile(const AFile: TFileName); var FS : TFileStream; begin if not FileExists(AFile) then begin FS := TFileStream.Create(AFile, fmCreate); FS.Free; end; FS := TFileStream.Create(AFile, fmOpenWrite or fmShareDenyNone); try SaveToStream(FS); finally FS.Free; end; end; procedure TStTextDataRecordSet.SaveToStream(AStream: TStream); var TS : TStAnsiTextStream; i : Integer; begin TS := TStAnsiTextStream.Create(AStream); { match Ansi Stream terminator to schema's } TS.LineTermChar := AnsiChar(Schema.LineTermChar); TS.LineTerminator := Schema.LineTerminator; { write the records } try for i := 0 to Pred(FRecords.Count) do TS.WriteLine(TStTextDataRecord(FRecords[i]).AsString); FIsDirty := False; finally TS.Free; end; end; procedure TStTextDataRecordSet.SetActive(const Value: Boolean); { activate or close record set } begin FActive := Value; if not FActive then begin Clear; FSchema := nil; end; end; procedure TStTextDataRecordSet.SetCurrentRecord( const Value: TStTextDataRecord); begin TStTextDataRecord(FRecords[FCurrentIndex]).Free; FRecords.Insert(FCurrentIndex, Value); FIsDirty := True; end; procedure TStTextDataRecordSet.SetRecord(Index: Integer; const Value: TStTextDataRecord); begin TStTextDataRecord(FRecords[Index]).Free; FRecords.Insert(Index, Value); FIsDirty := True; end; procedure TStTextDataRecordSet.SetSchema(const Value: TStTextDataSchema); { assign new schema, only works on inactive record set } begin if not FActive then begin if Assigned(FSchema) then FSchema.Free; FSchema := Value; end else raise EStException.CreateResTP(stscTxtDatRecordSetOpen, 0); end; end.
unit ParentKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Parent } // Модуль: "w:\common\components\gui\Garant\VCM\View\ParentAndChild\Forms\ParentKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ParentKeywordsPack" MUID: (4F6B66CB0200_Pack) {$Include w:\common\components\gui\f1LikeAppDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , Parent_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4F6B66CB0200_Packimpl_uses* //#UC END# *4F6B66CB0200_Packimpl_uses* ; type TkwParentFormParentZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TParentForm.ParentZone } private function ParentZone(const aCtx: TtfwContext; aParentForm: TParentForm): TvtPanel; {* Реализация слова скрипта .TParentForm.ParentZone } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwParentFormParentZone Tkw_Form_Parent = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Parent ---- *Пример использования*: [code]форма::Parent TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Parent Tkw_Parent_Control_ParentZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ParentZone ---- *Пример использования*: [code]контрол::ParentZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Parent_Control_ParentZone Tkw_Parent_Control_ParentZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ParentZone ---- *Пример использования*: [code]контрол::ParentZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Parent_Control_ParentZone_Push function TkwParentFormParentZone.ParentZone(const aCtx: TtfwContext; aParentForm: TParentForm): TvtPanel; {* Реализация слова скрипта .TParentForm.ParentZone } begin Result := aParentForm.ParentZone; end;//TkwParentFormParentZone.ParentZone class function TkwParentFormParentZone.GetWordNameForRegister: AnsiString; begin Result := '.TParentForm.ParentZone'; end;//TkwParentFormParentZone.GetWordNameForRegister function TkwParentFormParentZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwParentFormParentZone.GetResultTypeInfo function TkwParentFormParentZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwParentFormParentZone.GetAllParamsCount function TkwParentFormParentZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TParentForm)]); end;//TkwParentFormParentZone.ParamsTypes procedure TkwParentFormParentZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ParentZone', aCtx); end;//TkwParentFormParentZone.SetValuePrim procedure TkwParentFormParentZone.DoDoIt(const aCtx: TtfwContext); var l_aParentForm: TParentForm; begin try l_aParentForm := TParentForm(aCtx.rEngine.PopObjAs(TParentForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aParentForm: TParentForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ParentZone(aCtx, l_aParentForm)); end;//TkwParentFormParentZone.DoDoIt function Tkw_Form_Parent.GetString: AnsiString; begin Result := 'ParentForm'; end;//Tkw_Form_Parent.GetString class procedure Tkw_Form_Parent.RegisterInEngine; begin inherited; TtfwClassRef.Register(TParentForm); end;//Tkw_Form_Parent.RegisterInEngine class function Tkw_Form_Parent.GetWordNameForRegister: AnsiString; begin Result := 'форма::Parent'; end;//Tkw_Form_Parent.GetWordNameForRegister function Tkw_Parent_Control_ParentZone.GetString: AnsiString; begin Result := 'ParentZone'; end;//Tkw_Parent_Control_ParentZone.GetString class procedure Tkw_Parent_Control_ParentZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_Parent_Control_ParentZone.RegisterInEngine class function Tkw_Parent_Control_ParentZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone'; end;//Tkw_Parent_Control_ParentZone.GetWordNameForRegister procedure Tkw_Parent_Control_ParentZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ParentZone'); inherited; end;//Tkw_Parent_Control_ParentZone_Push.DoDoIt class function Tkw_Parent_Control_ParentZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone:push'; end;//Tkw_Parent_Control_ParentZone_Push.GetWordNameForRegister initialization TkwParentFormParentZone.RegisterInEngine; {* Регистрация ParentForm_ParentZone } Tkw_Form_Parent.RegisterInEngine; {* Регистрация Tkw_Form_Parent } Tkw_Parent_Control_ParentZone.RegisterInEngine; {* Регистрация Tkw_Parent_Control_ParentZone } Tkw_Parent_Control_ParentZone_Push.RegisterInEngine; {* Регистрация Tkw_Parent_Control_ParentZone_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TParentForm)); {* Регистрация типа TParentForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit firetrap_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m6502,mcs51,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine,ym_3812,msm5205; function iniciar_firetrap:boolean; implementation const firetrap_rom:array[0..2] of tipo_roms=( (n:'di-02.4a';l:$8000;p:0;crc:$3d1e4bf7),(n:'di-01.3a';l:$8000;p:$8000;crc:$9bbae38b), (n:'di-00-a.2a';l:$8000;p:$10000;crc:$f39e2cf4)); firetrap_snd:array[0..1] of tipo_roms=( (n:'di-17.10j';l:$8000;p:0;crc:$8605f6b9),(n:'di-18.12j';l:$8000;p:$8000;crc:$49508c93)); firetrap_mcu:tipo_roms=(n:'di-12.16h';l:$1000;p:0;crc:$6340a4d7); firetrap_char:tipo_roms=(n:'di-03.17c';l:$2000;p:0;crc:$46721930); firetrap_tiles:array[0..3] of tipo_roms=( (n:'di-06.3e';l:$8000;p:$0;crc:$441d9154),(n:'di-04.2e';l:$8000;p:$8000;crc:$8e6e7eec), (n:'di-07.6e';l:$8000;p:$10000;crc:$ef0a7e23),(n:'di-05.4e';l:$8000;p:$18000;crc:$ec080082)); firetrap_tiles2:array[0..3] of tipo_roms=( (n:'di-09.3j';l:$8000;p:$0;crc:$d11e28e8),(n:'di-08.2j';l:$8000;p:$8000;crc:$c32a21d8), (n:'di-11.6j';l:$8000;p:$10000;crc:$6424d5c3),(n:'di-10.4j';l:$8000;p:$18000;crc:$9b89300a)); firetrap_sprites:array[0..3] of tipo_roms=( (n:'di-16.17h';l:$8000;p:$0;crc:$0de055d7),(n:'di-13.13h';l:$8000;p:$8000;crc:$869219da), (n:'di-14.14h';l:$8000;p:$10000;crc:$6b65812e),(n:'di-15.15h';l:$8000;p:$18000;crc:$3e27f77d)); firetrap_pal:array[0..2] of tipo_roms=( (n:'firetrap.3b';l:$100;p:$0;crc:$8bb45337),(n:'firetrap.4b';l:$100;p:$100;crc:$d5abfc64), (n:'firetrap.1a';l:$100;p:$200;crc:$d67f3514)); //DIP firetrap_dip_a:array [0..5] of def_dip=( (mask:$7;name:'Coin A';number:5;dip:((dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$3;dip_name:'1C 4C'),(dip_val:$4;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$18;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$20;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Demo Sound';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); firetrap_dip_b:array [0..4] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'2'),(dip_val:$c;dip_name:'3'),(dip_val:$8;dip_name:'4'),(dip_val:$4;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$10;dip_name:'30K 70K'),(dip_val:$0;dip_name:'50K 100K'),(dip_val:$30;dip_name:'30K'),(dip_val:$20;dip_name:'50K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$40;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); CPU_SYNC=8; var main_bank,snd_bank,sound_latch,mcu_to_maincpu,maincpu_to_mcu,mcu_p3,vblank,coins,msm5205_data,msm5205_toggle:byte; main_rom:array[0..3,0..$3fff] of byte; snd_rom:array[0..1,0..$3fff] of byte; sound_irq_enable,nmi_enable:boolean; bg1_scrollx,bg1_scrolly,bg2_scrollx,bg2_scrolly:word; procedure update_video_firetrap; var f,nchar,pos:word; color,attr,x,y:byte; flipx,flipy:boolean; procedure draw_sprites; var f,x,y,nchar,attr,attr2,color:byte; flipx,flipy:boolean; begin for f:=$7 downto 0 do begin x:=memoria[$9883+(f*4)]+1; y:=240-memoria[$9882+(f*4)]; attr:=memoria[(f*4)+$9881]; attr2:=memoria[(f*4)+$9880]; nchar:=((attr and $10) shl 3) or ((attr and $20) shl 1) or (attr2 and $3f); color:=(attr and $0f) shl 2; flipx:=(attr2 and $40)<>0; flipy:=(attr2 and $80)<>0; put_gfx_sprite_mask(nchar,color,flipx,flipy,1,0,3); actualiza_gfx_sprite(x,y,3,1); end; end; begin for f:=0 to $3ff do begin //Fondo x:=f div 32; y:=f mod 32; pos:=(y xor $1f)+(x shl 5); if gfx[0].buffer[pos] then begin attr:=memoria[pos+$e400]; color:=(attr and $f0) shr 2; nchar:=memoria[pos+$e000] or ((attr and 1) shl 8); put_gfx_trans(x*8,y*8,nchar,color,1,0); gfx[0].buffer[pos]:=false; end; pos:=((y and $0f) xor $0f) or ((x and $0f) shl 4) or ((y and $10) shl 5) or ((x and $10) shl 6); if gfx[1].buffer[pos] then begin attr:=memoria[pos+$d100]; color:=attr and $30; nchar:=memoria[$d000+pos] or ((attr and 3) shl 8); put_gfx_trans_flip(x*16,y*16,nchar,color+$80,2,1,(attr and 8)<>0,(attr and 4)<>0); gfx[1].buffer[pos]:=false; end; if gfx[2].buffer[pos] then begin attr:=memoria[pos+$d900]; color:=attr and $30; nchar:=memoria[$d800+pos] or ((attr and 3) shl 8); put_gfx_flip(x*16,y*16,nchar,color+$c0,3,2,(attr and 8)<>0,(attr and 4)<>0); gfx[2].buffer[pos]:=false; end; end; scroll_x_y(3,4,bg2_scrollx,512-bg2_scrolly); scroll_x_y(2,4,bg1_scrollx,512-bg1_scrolly); for f:=0 to $5f do begin x:=memoria[$e802+(f*4)]; y:=memoria[$e800+(f*4)]; attr:=memoria[(f*4)+$e801]; nchar:=memoria[(f*4)+$e803]+((attr and $c0) shl 2); color:=(((attr and $08) shr 2) or (attr and $01)) shl 4; flipx:=(attr and $04)<>0; flipy:=(attr and $02)<>0; if (attr and $10)<>0 then begin //doble if flipy then begin put_gfx_sprite_diff(nchar and $ffe,$40+color,flipx,flipy,3,0,0); put_gfx_sprite_diff(nchar or 1,$40+color,flipx,flipy,3,0,16); end else begin put_gfx_sprite_diff(nchar and $ffe,$40+color,flipx,flipy,3,0,16); put_gfx_sprite_diff(nchar or 1,$40+color,flipx,flipy,3,0,0); end; actualiza_gfx_sprite_size(x,y,4,16,32); end else begin put_gfx_sprite(nchar,color+$40,flipx,flipy,3); actualiza_gfx_sprite(x,y,4,3); end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,4); actualiza_trozo_final(0,8,256,240,4); end; procedure eventos_firetrap; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); //SYSTEM if arcade_input.but0[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); //COIN if arcade_input.coin[0] then coins:=(coins and $fb) else coins:=(coins or $4); if arcade_input.coin[1] then coins:=(coins and $f7) else coins:=(coins or $8); end; end; procedure firetrap_principal; var f:word; frame_m,frame_s,frame_mcu:single; h:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=m6502_0.tframes; frame_mcu:=mcs51_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 271 do begin for h:=1 to CPU_SYNC do begin //main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound m6502_0.run(frame_s); frame_s:=frame_s+m6502_0.tframes-m6502_0.contador; //MCU mcs51_0.run(frame_mcu); frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador; end; case f of 8:begin mcs51_0.change_irq1(CLEAR_LINE); vblank:=0; end; 247:begin update_video_firetrap; vblank:=$80; if nmi_enable then z80_0.change_nmi(ASSERT_LINE); mcs51_0.change_irq1(ASSERT_LINE); end; end; end; eventos_firetrap; video_sync; end; end; function firetrap_getbyte(direccion:word):byte; begin case direccion of $0..$7fff,$c000..$e97f:firetrap_getbyte:=memoria[direccion]; $8000..$bfff:firetrap_getbyte:=main_rom[main_bank,direccion and $3fff]; $f010:firetrap_getbyte:=marcade.in0; //in0 $f011:firetrap_getbyte:=marcade.in1; //in1 $f012:firetrap_getbyte:=marcade.in2 or vblank; //in2 $f013:firetrap_getbyte:=marcade.dswa; //dsw0 $f014:firetrap_getbyte:=marcade.dswb; //dsw1 $f016:firetrap_getbyte:=mcu_to_maincpu; //mcu_r end; end; procedure firetrap_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; //ROM $c000..$cfff,$e800..$e97f:memoria[direccion]:=valor; $d000..$d7ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[1].buffer[direccion and $6ff]:=true; end; $d800..$dfff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[2].buffer[direccion and $6ff]:=true; end; $e000..$e7ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $f000:z80_0.change_irq(CLEAR_LINE); //firetrap_state::irqack_w $f001:begin sound_latch:=valor; m6502_0.change_nmi(PULSE_LINE); end; $f002:main_bank:=valor and 3; //firetrap_bankselect_w $f003:; //flip_screen_w $f004:begin //nmi_disable_w nmi_enable:=(valor and 1)=0; if not(nmi_enable) then z80_0.change_nmi(CLEAR_LINE); end; $f005:begin //mcu_w maincpu_to_mcu:=valor; mcs51_0.change_irq0(ASSERT_LINE); end; $f008:bg1_scrollx:=(bg1_scrollx and $ff00) or valor; $f009:bg1_scrollx:=(bg1_scrollx and $ff) or (valor shl 8); $f00a:bg1_scrolly:=(bg1_scrolly and $ff00) or valor; $f00b:bg1_scrolly:=(bg1_scrolly and $ff) or (valor shl 8); $f00c:bg2_scrollx:=(bg2_scrollx and $ff00) or valor; $f00d:bg2_scrollx:=(bg2_scrollx and $ff) or (valor shl 8); $f00e:bg2_scrolly:=(bg2_scrolly and $ff00) or valor; $f00f:bg2_scrolly:=(bg2_scrolly and $ff) or (valor shl 8); end; end; function firetrap_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7ff,$8000..$ffff:firetrap_snd_getbyte:=mem_snd[direccion]; $3400:firetrap_snd_getbyte:=sound_latch; $4000..$7fff:firetrap_snd_getbyte:=snd_rom[snd_bank,direccion and $3fff]; end; end; procedure firetrap_snd_putbyte(direccion:word;valor:byte); begin case direccion of $0..$7ff:mem_snd[direccion]:=valor; $1000:ym3812_0.control(valor); $1001:ym3812_0.write(valor); $2000:begin //adpcm_data_w m6502_0.change_irq(CLEAR_LINE); msm5205_data:=valor; end; $2400:begin //sound_flip_flop_w msm5205_0.reset_w((not(valor) and 1)); sound_irq_enable:=(valor and 2)<>0; if not(sound_irq_enable) then m6502_0.change_irq(CLEAR_LINE); end; $2800:snd_bank:=valor and 1; //sound_bankselect_w $4000..$ffff:; end; end; procedure snd_adpcm; begin msm5205_0.data_w(msm5205_data shr 4); msm5205_data:=msm5205_data shl 4; msm5205_toggle:=msm5205_toggle xor 1; if (sound_irq_enable and (msm5205_toggle=1)) then m6502_0.change_irq(ASSERT_LINE); end; function in_port0:byte; var inserted:byte; begin inserted:=byte((coins and $e)=$e); in_port0:=(coins and $e) or inserted; end; procedure out_port1(valor:byte); begin mcu_to_maincpu:=valor; end; function in_port2:byte; begin in_port2:=maincpu_to_mcu; end; procedure out_port3(valor:byte); begin if (((mcu_p3 and 1)<>0) and ((valor and 1)=0)) then z80_0.change_irq(ASSERT_LINE); if (((mcu_p3 and 2)<>0) and ((valor and 2)=0)) then mcs51_0.change_irq0(CLEAR_LINE); mcu_p3:=valor; end; procedure firetrap_sound_update; begin ym3812_0.update; end; //Main procedure reset_firetrap; begin z80_0.reset; m6502_0.reset; mcs51_0.reset; ym3812_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$7f; main_bank:=0; snd_bank:=0; sound_latch:=0; mcu_to_maincpu:=0; maincpu_to_mcu:=0; msm5205_toggle:=0; mcu_p3:=0; vblank:=$80; coins:=$ff; nmi_enable:=false; sound_irq_enable:=false; bg1_scrollx:=0; bg1_scrolly:=0; bg2_scrollx:=0; bg2_scrolly:=0; end; function iniciar_firetrap:boolean; var colores:tpaleta; f:word; memoria_temp,ptemp:array[0..$1ffff] of byte; bit0,bit1,bit2,bit3:byte; const pc_x:array[0..7] of dword=(3, 2, 1, 0, $200*8*8+3, $200*8*8+2, $200*8*8+1, $200*8*8+0); pt_x:array[0..15] of dword=(3, 2, 1, 0, $400*32*8+3, $400*32*8+2, $400*32*8+1, $400*32*8+0, 16*8+3, 16*8+2, 16*8+1, 16*8+0, $400*32*8+16*8+3, $400*32*8+16*8+2, $400*32*8+16*8+1, $400*32*8+16*8+0); ps_x:array[0..15] of dword=(7, 6, 5, 4, 3, 2, 1, 0, 16*8+7, 16*8+6, 16*8+5, 16*8+4, 16*8+3, 16*8+2, 16*8+1, 16*8+0); ps_y:array[0..15] of dword=(15*8, 14*8, 13*8, 12*8, 11*8, 10*8, 9*8, 8*8, 7*8, 6*8, 5*8, 4*8, 3*8, 2*8, 1*8, 0*8); procedure convert_tiles(num:byte); begin copymemory(@memoria_temp[0],@ptemp[0],$2000); copymemory(@memoria_temp[$8000],@ptemp[$2000],$2000); copymemory(@memoria_temp[$2000],@ptemp[$4000],$2000); copymemory(@memoria_temp[$a000],@ptemp[$6000],$2000); copymemory(@memoria_temp[$4000],@ptemp[$8000],$2000); copymemory(@memoria_temp[$c000],@ptemp[$a000],$2000); copymemory(@memoria_temp[$6000],@ptemp[$c000],$2000); copymemory(@memoria_temp[$e000],@ptemp[$e000],$2000); copymemory(@memoria_temp[$10000],@ptemp[$10000],$2000); copymemory(@memoria_temp[$18000],@ptemp[$12000],$2000); copymemory(@memoria_temp[$12000],@ptemp[$14000],$2000); copymemory(@memoria_temp[$1a000],@ptemp[$16000],$2000); copymemory(@memoria_temp[$14000],@ptemp[$18000],$2000); copymemory(@memoria_temp[$1c000],@ptemp[$1a000],$2000); copymemory(@memoria_temp[$16000],@ptemp[$1c000],$2000); copymemory(@memoria_temp[$1e000],@ptemp[$1e000],$2000); init_gfx(num,16,16,$400); gfx_set_desc_data(4,0,32*8,0,4,$800*32*8+0,$800*32*8+4); convert_gfx(num,0,@memoria_temp,@pt_x,@ps_y,false,false); end; begin llamadas_maquina.bucle_general:=firetrap_principal; llamadas_maquina.reset:=reset_firetrap; iniciar_firetrap:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,512,512,true); screen_mod_scroll(2,512,512,511,512,512,511); screen_init(3,512,512); screen_mod_scroll(3,512,512,511,512,512,511); screen_init(4,512,512,false,true); main_screen.rot90_screen:=true; iniciar_video(256,240); //Main CPU z80_0:=cpu_z80.create(12000000 div 2,272*CPU_SYNC); z80_0.change_ram_calls(firetrap_getbyte,firetrap_putbyte); if not(roms_load(@memoria_temp,firetrap_rom)) then exit; copymemory(@memoria[0],@memoria_temp[0],$8000); for f:=0 to 3 do copymemory(@main_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000); //Sound CPU m6502_0:=cpu_m6502.create(12000000 div 8,272*CPU_SYNC,TCPU_M6502); m6502_0.change_ram_calls(firetrap_snd_getbyte,firetrap_snd_putbyte); m6502_0.init_sound(firetrap_sound_update); if not(roms_load(@memoria_temp,firetrap_snd)) then exit; copymemory(@mem_snd[$8000],@memoria_temp[0],$8000); for f:=0 to 1 do copymemory(@snd_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000); //MCU mcs51_0:=cpu_mcs51.create(8000000,272*CPU_SYNC); mcs51_0.change_io_calls(in_port0,nil,in_port2,nil,nil,out_port1,nil,out_port3); if not(roms_load(mcs51_0.get_rom_addr,firetrap_mcu)) then exit; //Sound Chips ym3812_0:=ym3812_chip.create(YM3526_FM,3000000); msm5205_0:=MSM5205_chip.create(12000000 div 32,MSM5205_S48_4B,0.3,snd_adpcm); //convertir chars if not(roms_load(@memoria_temp,firetrap_char)) then exit; init_gfx(0,8,8,$200); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y[8],false,false); //convertir bg if not(roms_load(@ptemp,firetrap_tiles)) then exit; convert_tiles(1); if not(roms_load(@ptemp,firetrap_tiles2)) then exit; convert_tiles(2); //convertir sprites if not(roms_load(@memoria_temp,firetrap_sprites)) then exit; init_gfx(3,16,16,$400); gfx[3].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0,$400*32*8,$800*32*8,$c00*32*8); convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,false); //poner la paleta if not(roms_load(@memoria_temp,firetrap_pal)) then exit; for f:=0 to $ff do begin // red component */ bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; bit3:=(memoria_temp[f] shr 3) and $01; colores[f].r:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; // green component */ bit0:=(memoria_temp[f] shr 4) and $01; bit1:=(memoria_temp[f] shr 5) and $01; bit2:=(memoria_temp[f] shr 6) and $01; bit3:=(memoria_temp[f] shr 7) and $01; colores[f].g:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; // blue component */ bit0:=(memoria_temp[f+$100] shr 0) and $01; bit1:=(memoria_temp[f+$100] shr 1) and $01; bit2:=(memoria_temp[f+$100] shr 2) and $01; bit3:=(memoria_temp[f+$100] shr 3) and $01; colores[f].b:=$0e*bit0+$1f*bit1+$43*bit2+$8f*bit3; end; set_pal(colores,$100); //DIP marcade.dswa:=$df; marcade.dswb:=$ff; marcade.dswa_val:=@firetrap_dip_a; marcade.dswb_val:=@firetrap_dip_b; //final reset_firetrap; iniciar_firetrap:=true; end; end.
unit jsvarhelper; //create by swish interface uses classes, sysutils, types, dcef3_ceflib, dcefb_Browser, syncobjs, variants; type TJsVars = class protected FEvent: TEvent; FValue: Variant; FBrowser: TDcefBrowser; procedure SetReady; inline; function Wait(ATimeout: Cardinal = INFINITE): TWaitResult; function GetAsBoolean(AName: String): Boolean; function GetAsFloat(AName: String): Double; function GetAsInteger(AName: String): Int64; function GetAsString(AName: String): String; procedure SetAsBoolean(AName: String; const Value: Boolean); procedure SetAsFloat(AName: String; const Value: Double); procedure SetAsInteger(AName: String; const Value: Int64); procedure SetAsString(AName: String; const Value: String); function GetDefined(AName: String): Boolean; public constructor Create(ABrowser: TDcefBrowser); overload; destructor Destroy; override; procedure ExecuteScript(const AScript, AUrl: String; AFromLine: Integer = 0); overload; function ExecuteScript(const AScript: String): Variant; overload; property Defined[AName: String]: Boolean read GetDefined; property AsBoolean[AName: String]: Boolean read GetAsBoolean write SetAsBoolean; property AsInteger[AName: String]: Int64 read GetAsInteger write SetAsInteger; property AsFloat[AName: String]: Double read GetAsFloat write SetAsFloat; property AsString[AName: String]: String read GetAsString write SetAsString; property Browser: TDcefBrowser read FBrowser write FBrowser; end; implementation uses windows; var VarHelper: TJsVars; resourcestring SCantToVariant = '指定的JavaScript变量无法转换为 Variant'; SJSException = '执行脚本时发生异常:'#13#10'信息:%s'#13#10'位置:第 %d 行 %d 列'#13#10'脚本:'#13#10'%s'; SVarTypeMismatch = '变量 %s 不存在或类型不匹配'; function ToVariant(V: Icefv8Value): Variant; var i: Integer; procedure AsObject; var AList: TStringList; AVal: Icefv8Value; i, t, c: Integer; AValues: array of Variant; begin AList := TStringList.Create; try V.GetKeys(AList); SetLength(AValues, AList.Count shl 1); c := 0; for i := 0 to AList.Count do begin AVal := V.GetValueByIndex(i); if not AVal.IsFunction then begin t := c shl 1; AValues[t] := AList[i]; AValues[t + 1] := ToVariant(AVal); Inc(c); end; end; SetLength(AValues, c shl 1); Result := VarArrayOf(AValues); finally FreeAndNil(AList); end; end; begin if V.IsString then Result := V.GetStringValue else if V.IsBool then Result := V.GetBoolValue else if V.IsInt then Result := V.GetIntValue else if V.IsUInt then Result := V.GetUIntValue else if V.IsDouble then Result := V.GetDoubleValue else if V.IsUndefined then Result := Unassigned else if V.IsNull then Result := Null else if V.IsFunction then Result := V.GetFunctionName else if V.IsArray then begin Result := VarArrayCreate([0, V.GetArrayLength], varVariant); for i := 0 to V.GetArrayLength - 1 do begin Result[i] := ToVariant(V.GetValueByIndex(i)); end; end else if V.IsObject then begin AsObject; end else raise Exception.Create(SCantToVariant); end; { TJsVars } constructor TJsVars.Create(ABrowser: TDcefBrowser); begin inherited Create; FBrowser := ABrowser; FEvent := TEvent.Create(nil, false, false, ''); end; destructor TJsVars.Destroy; begin FreeAndNil(FEvent); inherited; end; function TJsVars.ExecuteScript(const AScript: String): Variant; var AExcept: Exception; begin VarHelper := Self; AExcept := nil; VarClear(Result); FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) var AResult: Icefv8Value; AException: ICefv8Exception; begin try if Assigned(AContext) and AContext.Enter then begin if not AContext.Eval(AScript, AResult, AException) then begin AExcept := Exception.CreateFmt(SJSException, [AException.Message, AException.LineNumber, AException.StartColumn, AException.SourceLine]); end else PVariant(AData)^ := ToVariant(AResult); AContext.Exit; end; finally VarHelper.SetReady; end; end, @Result); Wait; if AExcept <> nil then raise AExcept; end; procedure TJsVars.ExecuteScript(const AScript, AUrl: String; AFromLine: Integer); var S: String; begin VarHelper := Self; S := S + #13#10 + 'TJsDHelper.SetReady();'; FBrowser.ExecuteJavaScript(S); Wait; end; function TJsVars.GetAsBoolean(AName: String): Boolean; begin Result := false; VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) var AValue: Icefv8Value; AException: ICefv8Exception; begin try if Assigned(AContext) and AContext.Enter then begin AValue := AContext.Global.GetValueByKey(AName); if AValue.IsValid then begin if AValue.IsUndefined then begin if AContext.Eval(AName, AValue, AException) then PBoolean(AData)^ := ToVariant(AValue) else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end else PBoolean(AData)^ := ToVariant(AValue) end else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end; finally VarHelper.SetReady; end; end, @Result); Wait; end; function TJsVars.GetAsFloat(AName: String): Double; begin Result := 0; VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) var AValue: Icefv8Value; AException: ICefv8Exception; begin try if Assigned(AContext) and AContext.Enter then begin AValue := AContext.Global.GetValueByKey(AName); if AValue.IsValid then begin if AValue.IsUndefined then begin if AContext.Eval(AName, AValue, AException) then PDouble(AData)^ := ToVariant(AValue) else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end else PDouble(AData)^ := ToVariant(AValue) end else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end; finally VarHelper.SetReady; end; end, @Result); Wait; end; function TJsVars.GetAsInteger(AName: String): Int64; begin Result := 0; VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) var AValue: Icefv8Value; AException: ICefv8Exception; begin try if Assigned(AContext) and AContext.Enter then begin AValue := AContext.Global.GetValueByKey(AName); if AValue.IsValid then begin if AValue.IsUndefined then begin if AContext.Eval(AName, AValue, AException) then PInteger(AData)^ := ToVariant(AValue) else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end else PInteger(AData)^ := ToVariant(AValue) end else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end; finally VarHelper.SetReady; end; end, @Result); Wait; end; function TJsVars.GetAsString(AName: String): String; begin Result := ''; VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) var AValue: Icefv8Value; AException: ICefv8Exception; begin try if Assigned(AContext) and AContext.Enter then begin AValue := AContext.Global.GetValueByKey(AName); if AValue.IsValid then begin if AValue.IsUndefined then begin if AContext.Eval(AName, AValue, AException) then PString(AData)^ := ToVariant(AValue) else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end else PString(AData)^ := ToVariant(AValue) end else raise Exception.CreateFmt(SVarTypeMismatch, [AName]); end; finally VarHelper.SetReady; end; end, @Result); Wait; end; function TJsVars.GetDefined(AName: String): Boolean; begin Result := false; VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) begin if Assigned(AContext) then begin if AContext.Enter then begin PBoolean(AData)^ := AContext.Global.HasValueByKey(AName); AContext.Exit; end; end; VarHelper.SetReady; end, @Result); Wait; end; procedure TJsVars.SetAsBoolean(AName: String; const Value: Boolean); begin VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) begin try if Assigned(AContext) and AContext.Enter then begin AContext.Global.SetValueByKey(AName, TCefv8ValueRef.NewBool(Value), []); AContext.Exit; end; finally VarHelper.SetReady; end; end, nil); Wait; end; procedure TJsVars.SetAsFloat(AName: String; const Value: Double); begin VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) begin try if Assigned(AContext) and AContext.Enter then begin AContext.Global.SetValueByKey(AName, TCefv8ValueRef.NewDouble(Value), []); AContext.Exit; end; finally VarHelper.SetReady; end; end, nil); Wait; end; procedure TJsVars.SetAsInteger(AName: String; const Value: Int64); begin VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) begin try if Assigned(AContext) and AContext.Enter then begin AContext.Global.SetValueByKey(AName, TCefv8ValueRef.NewInt(Value), []); AContext.Exit; end; finally VarHelper.SetReady; end; end, nil); Wait; end; procedure TJsVars.SetAsString(AName: String; const Value: String); begin VarHelper := Self; FBrowser.ActivePage.RunInRenderProcess( procedure(ASender: TBrowserPage; AContext: ICefv8Context; AData: Pointer) begin try if Assigned(AContext) and AContext.Enter then begin AContext.Global.SetValueByKey(AName, TCefv8ValueRef.NewString(Value), []); AContext.Exit; end; finally VarHelper.SetReady; end; end, nil); Wait; end; procedure TJsVars.SetReady; begin FEvent.SetEvent; end; function TJsVars.Wait(ATimeout: Cardinal): TWaitResult; begin Result := FEvent.WaitFor(INFINITE); end; end.
Unit HmrcRestClient; (* **************************************************************************** * HMRC API REST Client Unit * ****************************************************************************** * This unit contains new class definitions which inherit from TRESTClient * * and add the necessary data and processes to connect to the HMRC API. It * * was originally developed as a part of the UK-DevGroup collaborative * * attempt to access the HMRC API using OAuth2 in Nov/Dec 2018. * * * * It was originally developed to work with the v1.0 beta version of the * * API and HMRC warn that there are likely to be breaking changes during * * the development of their API services, so you should ensure that you are * * using an up to date version of these components. * * * * There are 3 classes of authorisation: none, application and user. These * * seem to be a standard set for REST with JSON over HTTP, which is what * * this is about. The user based process uses an OAuth2 authorisation to get * * an access token from a target url, which will be on the gov/hmrc site. * * All of the API services appear to require OAuth2, except for the create * * (test) user processess, which require application authorisation and 2 of * * the "hello" connection tests. These are all handled in the * * THmrcTestClient class. * * * * HMRC have added an extra level to the process as "scope" and everything * * happens within a given scope. Access tokens relate to a particular scope * * and must be both aquired and used within that scope. Each API resource / * * endpoint has a scope assigned, which must be used in all calls to it. * * * * The connection details and application/client key/id and secret are * * supplied by the application, being stored and loaded as appropriate. * * * * The headers required for requests and submissions to the HMRC API are * * listed on the HMRC website, which, at the time this was created, was here * * * They depend to a certain extent on the type of application, so the * * programmer is responsible for ensuring that the correct values are used * * and for checking that the requirements have not changed over time. * * * * All calls are made in the name of a "user" on the HMRC system. They have * * a UserId as a string, which uniquely identifies them to HMRC. The classes * * here have a single value, FUID, to hold this and the application will * * pass the appropriate values. For the NI API, this will be the NINo, for * * VAT it will be the VRN, etc. * * * * Valid calls which return no data are returned with a 404 NOT FOUND error. * * Why is known only to HMRC, but it means that if 404 is returned, it is * * necessary to check the text that goes with it, to see whether there is * * actually a problem, or just no data. * * * * This was written in 10.2.3 (Tokyo) and should work in some recent * * earlier versions. It uses units from the REST set which should be found * * in C:\Program Files (x86)\Embarcadero\Studio\19.0\source\data\rest or * * whatever the corresponding location would be on the machine used to * * run this code. * * * * Anyone is welcome to bend this for their own purposes, but no liability * * can be accepted by the author for any loss of or damage to hardware, * * software, data, finance, income or reputation resulting from the use of * * this code, howsoever caused. In any event, maximum liability shall not * * exceed the amount paid by the user for the code. * * * * created 21/11/18 from the initial test case. * * * * version 0.8.1 beta released 12/01/19 to include the api versions * * available at that time. * * * * original copyright Ian Hamilton 2018/19. * * License : GPL * * * **************************************************************************** *) Interface (* ************************************************************************** *) Uses System.Classes, System.SysUtils, System.UITypes, System.Variants, IPPeerClient, REST.Types, REST.Client, REST.Authenticator.OAuth, System.JSON, HmrcRestSupport; (* ************************************************************************** *) Type (* ************************************************************************** ** Base REST Client for the HMRC REST API service ** ** ** ** This handles authentication and connections, but should not be used ** ** directly. ** ** ** ** In general, the relevant User Id and scope should be set before ** ** making any calls to the API. ** ** Headers can be added one at a time using the AddaHeader method, or ** ** supplied as a list using SetHeaderList. ** ** By default, IzTest is set to false, so it will automatically target ** ** the LIVE API service. If using it for testing please remember to set ** ** IzTest to true to target the TEST API. ** ** ** ** All methods will return a result as an integer. This can have 1 of 4 ** ** values: ** ** 0 : Nothing - this should not be returned ** ** 1 : Success - get the JSON Value returned by the API from LastValue ** ** 2 : Failure - get the error messages from LastError and LastMsg ** ** 3 : Exception - get the exception message from LastError ** ** ** ************************************************************************** *) THMRCRestClient = Class(TRESTClient) Strict private class var FResetCount: Integer; Private FStoreFolder: String; // PROPERTY METHODS SECTION Function GetLastCode: integer; Function GetLastError: String; Function GetLastMsg: String; Function GetLastValue: TJSONValue; Procedure SetApiVersion(Const Value: String); Procedure SetAuthMode(Const Value: THmrcAuthMode); Procedure SetAuthScope(Const Value: String); Procedure SetCallbackUrl(Const Value: String); Procedure SetIzTest(Const Value: boolean); Procedure SetUID(Const Value: String); // virtual; Protected FApiVersion: String; // the version of the api to target FAuthMode: THmrcAuthMode; // the level of authentication required FAuthScope: String; // the scope of the authorisation FBaseResource: String; // base element of the service resource FCallbackPort: String; // call back port for authentication process FCallbackUrl: String; // call back url for authentication process FClientId: String; // application/client key for login FClientSecret: String; // application/client secret for login FIzTest: boolean; // test or production api FLastCode: integer; // the response code of the last http call or error value FLastError: String; // the last error/failure message FLastMsg: String; // the last http response status text FLastValue: TJSONValue; // the last api response as a json value FOwnsHeaders: boolean; // does it own the header list, it will need to free the list if true FServerToken: String; // token for application login FTokenState: THmrcTokenState; // status of current hmrc access tokens FUID: String; // unique ID for this user/customer for this service LAccessTokens: THmrcAccessTokens; // a list of user access tokens from the authentication process LHeaderList: TStringList; // a list for the header values required by hmrc LScopeList: TScopeArray; // list of relevant scopes OAccessToken: THmrcAccessToken; // the current access token ORequest: TRESTRequest; // Rest client component // NEW ACCESS TOKEN (NAT) SECTION Function NAT_BildAuthUrl: String; // build the OAuth2 login url Function NAT_CheckReady: boolean; // check the initial values have been loaded/set Procedure NAT_SetOAuth2; // set authentication parameters to get a new access token Procedure NAT_TryForToken(Const aUrl: String; Var DoCloseWebView: boolean); // a TOAuth2WebFormRedirectEvent to handle part 2 to get the access token Procedure NAT_WebFormClose(Sender: TObject; Var Action: TCloseAction); // the WebForm OnClose event - close the login form // REFRESH ACCESS TOKEN (RAT) SECTION Function RAT_RefreshToken: integer; // get a new access token using the current refresh token Procedure RAT_SetOAuth2; // set authentication parameters to refresh an access token // REQUEST (REQ) SECTION Function REQ_BildAccept: String; // build the accept parameter string Function REQ_CheckToken: boolean; // check whether there is a token and whether it is current. Try to refresh. Procedure REQ_ClearLast; // clear the last response values Function REQ_DateFormat(Const Value: TDateTime): String; // convert date to HMRC compatible date string Procedure REQ_Reset; // reset request to defaults Procedure REQ_LoadHeaders; // RPW added 21/02/2020 Public OnTokenChange: THmrcTokenEvent; // pointer to method to save / update saved token Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure AddaHeader(Const aName, aValue: String; Const NoEncode: boolean = False); Procedure RemoveaHeader(Const aName: String); Procedure AddaToken(Const uid, scp, atn, rtn: String; Const exp, tmo: TDateTime); // add a token to the tokens list Function ListScopes: String; // return list of relevant scopes as a comma separated list Function NewAccessToken: boolean; // (NAT) try to login and authenticate with a user Procedure SetHeaderList(Const Value: TStringList; OwnsList: boolean = true); // set a list of header values Function SetHmrcID(Const Value: String): integer; Virtual; // set HMRC "User" ID class procedure InitialiseClassVars; Property LastCode: integer Read GetLastCode; Property LastError: String Read GetLastError; Property LastMsg: String Read GetLastMsg; Property LastValue: TJSONValue Read GetLastValue; Published Property ApiVersion: String Read FApiVersion Write SetApiVersion; Property AuthMode: THmrcAuthMode Read FAuthMode Write SetAuthMode; Property AuthScope: String Read FAuthScope Write SetAuthScope; Property BaseResource: String Read FBaseResource Write FBaseResource; Property CallbackPort: String Read FCallbackPort Write FCallbackPort; Property CallbackUrl: String Read FCallbackUrl Write SetCallbackUrl; Property ClientId: String Read FClientId Write FClientId; Property ClientSecret: String Read FClientSecret Write FClientSecret; Property IzTest: boolean Read FIzTest Write SetIzTest; Property ServerToken: String Read FServerToken Write FServerToken; Property uid: String Read FUID Write SetUID; // RPW Property StoreFolder: String Read FStoreFolder Write FStoreFolder; Property HeaderList: TStringList Read LHeaderList; End; (* ************************************************************************** ** Test REST Client for the HMRC REST API service ** ** ** ** This handles the "hello" test endpoints provided by the API service ** ** and also sets up test users. ** ** At some point the API may stop supporting some or all of these. ** ** API Version 1.0 ** ** ** ** The user id is the value of "userId" for the test user. ** ************************************************************************** *) THmrcTestClient = Class(THMRCRestClient) Private Protected // NEW USER (NUS) SECTION Function NUS_CheckReady: boolean; // check the initial values have been loaded/set Public Constructor Create(AOwner: TComponent); Override; Function AddAgent: integer; // call the user api to add a new user as an agent Function AddCompany: integer; // call the user api to add a new user as a business Function AddPerson: integer; // call the user api to add a new user as an individual Function TestHelloApplication: String; // call the hello application end point Function TestHelloUser: String; // call the hello user end point Function TestHelloWorld: String; // call the hello world end point Function TestFraudHeaders: integer; // call to test the fraud headers End; (* ************************************************************************** ** NI REST Client for the HMRC REST API service ** ** ** ** This handles NI services provided by the API service. ** ** ** ** The user id is the UTR. (10 digits) ** ** Resource = /national-insurance/sa/{utr}/annual-summary/{taxYear} ** ** Tax year in the format YYYY-YY ** ************************************************************************** *) THmrcNIClient = Class(THMRCRestClient) Private Protected Public Constructor Create(AOwner: TComponent); Override; End; (* ************************************************************************** ** PAYE REST Client for the HMRC REST API service ** ** ** ** This handles PAYE services provided by the API service. ** ** ** ** The user id is the UTR. (10 digits) ** ** Resource = /national-insurance/sa/{utr}/annual-summary/{taxYear} ** ** Tax year in the format YYYY-YY ** ************************************************************************** *) THmrcPAYEClient = Class(THMRCRestClient) Private Protected Public Constructor Create(AOwner: TComponent); Override; End; (* ************************************************************************** ** SA REST Client for the HMRC REST API service ** ** ** ** This handles Self Assessment services provided by the API service. ** ** ** ** The user id is the UTR. (10 digits) ** ** Resource = /national-insurance/sa/{utr}/annual-summary/{taxYear} ** ** Tax year in the format YYYY-YY ** ************************************************************************** *) THmrcSAClient = Class(THMRCRestClient) Private Protected Public Constructor Create(AOwner: TComponent); Override; End; (* ************************************************************************** ** VAT REST Client for the HMRC REST API service ** ** ** ** This handles VAT services provided by the API service. ** ** ** ** The user id is the VRN. ** ** Search dates in the format YYYY-MM-DD ** ** Base resource = organisations/vat/{VRN}/ ** ** API Version 1.0 ** ** ** ** There are 5 end points, 4 GET and 1 POST. ** ** Liabilities - GET - (Date From + Date To) ** ** Obligations - GET - (Date From + Date To) ** ** Payments - GET - (Date From + Date To) ** ** Returns - GET - (Period ID) ** ** SubmitReturns - POST - (List of values) ** ** ** ** There are some basic sanity checks run on the parameters supplied for ** ** the GET calls and on the data to be submitted. Other checks are ** ** performed by HMRC, which may cause the call to fail. ** ** ** ** The calls to Liabilities, Obligations and Payments are identical, ** ** except for the final part of the url. These calls are handled by the ** ** SearchLOP method, which accepts the name as a parameter, along with ** ** the start and end dates for the search. ** ** ** ** The Returns call takes a single VAT period id as a Resource Suffix. ** ** ** ** The Submit Returns method takes a vat period, a list of values and a ** ** finalised (true/false) value. If successful it will return the ** ** receipt/confirmation details in a list. ** ** ** ** According to HMRC documentation, all apps must access the Obligations ** ** and SubmitReturns end points. The others are optional. ** ** ** ************************************************************************** *) THmrcVATClient = Class(THMRCRestClient) Private Protected FDateFrom: String; // start date for search FDateTo: String; // end date for search Function API_SearchLP(Const aType: String; Const FromDate, ToDate: TDateTime): integer; // search liabilities / obligations / payments Function PRM_CheckDates(Const dtFrom, dtTo: TDateTime): boolean; // basic checks on dates supplied Function PRM_CheckPeriod(Const Value: String): boolean; // basic checks on period format Function PRM_CheckValues(Const Values: TStringList): boolean; // check the list of values for submission Public Constructor Create(AOwner: TComponent); Override; Function GetLiabilities(Const FromDate, ToDate: TDateTime): integer; // search liabilities for a date range Function GetObligations(Const FromDate, ToDate: TDateTime; aStatus: String = ''): integer; // search obligations for a date range Function GetPayments(Const FromDate, ToDate: TDateTime): integer; // search payments for a date range Function GetReturn(Const aPeriod: String; Var ACorrelationId: String): integer; Function SubmitReturn(Const aPeriod: String; Const Values: TStringList; Const IzFinal: boolean; Var Confirm: String) : integer; // submit a return Function SetHmrcID(Const Value: String): integer; Override; // override to apply some kind of validation End; Procedure Register; (* ************************************************************************** *) Implementation (* ************************************************************************** *) Uses REST.Utils, FMX.Dialogs, System.IOUtils, Systematic.OAuth.WebForm.FMX; // VCL.Dialogs, REST.Authenticator.OAuth.WebForm.Win; Procedure Register; Begin RegisterComponents('HmrcRestClient', [THmrcTestClient]); RegisterComponents('HmrcRestClient', [THmrcVATClient]); End; (* **************************************************************************** * HMRC REST CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THMRCRestClient.Create(AOwner: TComponent); Begin Inherited; ContentType := csApJson; FApiVersion := '1.0'; FAuthMode := amNone; FAuthScope := ''; FBaseResource := ''; FClientId := ''; FClientSecret := ''; BaseUrl := HmrcProdUrl; FCallbackUrl := ''; FCallbackPort := ''; FIzTest := False; FOwnsHeaders := true; FServerToken := ''; FTokenState := tsNone; FUID := ''; REQ_ClearLast; OnTokenChange := Nil; Setlength(LScopeList, 0); // The base class has an FAuthenticator defined as a TCustomAuthenticator Authenticator := TOAuth2Authenticator.Create(Self); LAccessTokens := THmrcAccessTokens.Create; OAccessToken := Nil; LHeaderList := TStringList.Create; ORequest := TRESTRequest.Create(Nil); ORequest.Client := Self; ORequest.Accept := REQ_BildAccept; ContentType := csApJson; End; (* **************************************************************************** * Free request. * **************************************************************************** *) Destructor THMRCRestClient.Destroy; Begin ORequest.DisposeOf; If (Assigned(LAccessTokens)) Then LAccessTokens.Free; If (Assigned(LHeaderList)) And (FOwnsHeaders) Then LHeaderList.Free; Inherited; End; (* **************************************************************************** * PUBLIC METHODS SECTION * ****************************************************************************** * Add a name and value to the headers list. * **************************************************************************** *) Procedure THMRCRestClient.AddaHeader(Const aName, aValue: String; Const NoEncode: boolean = False); Const _dont_encode: Array [boolean] Of String = ('encode', 'noencode'); Begin LHeaderList.Add(aName + '|' + aValue + '|' + _dont_encode[NoEncode]); End; (* **************************************************************************** * Add a new token to the tokens list. * **************************************************************************** *) Procedure THMRCRestClient.AddaToken(Const uid, scp, atn, rtn: String; Const exp, tmo: TDateTime); Begin LAccessTokens.AddToken(uid, scp, atn, rtn, exp, tmo); End; (* **************************************************************************** * Return the list of relevant scopes. * **************************************************************************** *) Function THMRCRestClient.ListScopes: String; Var idx: integer; Begin Result := ''; If (Length(LScopeList) > 0) Then For idx := 0 To Length(LScopeList) - 1 Do Begin If (idx > 0) Then Result := Result + ','; Result := Result + LScopeList[idx]; End; End; (* **************************************************************************** * Set User ID for HMRC user login. * **************************************************************************** *) Function THMRCRestClient.SetHmrcID(Const Value: String): integer; Begin REQ_ClearLast; If (Value <> '') Then Begin uid := Value; Result := RESULT_OK End Else Begin FLastCode := ERR_NO_USER_ID; FLastError := csMsgNoUserId; Result := RESULT_FAIL; End; End; (* **************************************************************************** * NEW ACCESS TOKEN (NAT) SECTION * ****************************************************************************** * Build the login part of the initial url for authentication. * **************************************************************************** *) Function THMRCRestClient.NAT_BildAuthUrl: String; Begin Result := BaseUrl + csAuthorize; Result := Result + '?' + csClientId + '=' + FClientId; Result := Result + '&' + csRedirectUri + '=' + URIEncode(FCallbackUrl); Result := Result + '&' + csResponseType + '=' + csCode; Result := Result + '&' + csScope + '=' + FAuthScope; End; (* **************************************************************************** * Check whether any required key/secret and urls are set. * **************************************************************************** *) Function THMRCRestClient.NAT_CheckReady: boolean; Begin Result := False; If (FClientId = '') Then Begin FLastCode := ERR_NO_CLIENT_ID; FLastError := csMsgNoClient; End Else If (FClientSecret = '') Then Begin FLastCode := ERR_NO_CLIENT_SECRET; FLastError := csMsgNoClient; End Else If (BaseUrl = '') Then Begin FLastCode := ERR_NO_TARGET_URL; FLastError := csMsgNoUri; End Else If (FCallbackUrl = '') Then Begin FLastCode := ERR_NO_CALLBACK_URL; FLastError := csMsgNoUri; End Else If (FCallbackPort = '') Or (StrToIntDef(FCallbackPort, 0) = 0) Then Begin FLastCode := ERR_NO_CALLBACK_PORT; FLastError := csMsgNoPort; End Else Begin Result := true; End; End; (* **************************************************************************** * Set OAuth2 params for HMRC user login. * **************************************************************************** *) Procedure THMRCRestClient.NAT_SetOAuth2; Begin (Authenticator As TOAuth2Authenticator).AccessToken := ''; (Authenticator As TOAuth2Authenticator).RefreshToken := ''; (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).ResponseType := TOAuth2ResponseType.rtTOKEN; (Authenticator As TOAuth2Authenticator).AccessTokenParamName := csAccessToken; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; (Authenticator As TOAuth2Authenticator).Scope := FAuthScope; (Authenticator As TOAuth2Authenticator).AuthorizationEndpoint := BaseUrl + csAuthToken; (Authenticator As TOAuth2Authenticator).RedirectionEndpoint := FCallbackUrl; End; (* **************************************************************************** * Got a code, so now change that for an access token. * **************************************************************************** *) Procedure THMRCRestClient.NAT_TryForToken(Const aUrl: String; Var DoCloseWebView: boolean); Var lvPos: integer; lvCode: String; lvToken: String; Begin lvCode := ''; lvToken := ''; // look for the parameter in the response url lvPos := Pos('code=', aUrl); If (lvPos > 0) Then Begin lvCode := Copy(aUrl, lvPos + 5, Length(aUrl)); If (Pos('&', lvCode) > 0) Then Begin lvCode := Copy(lvCode, 1, Pos('&', lvCode) - 1); End; If (lvCode = '') Then Exit; // so it will close the login form DoCloseWebView := true; // clear the request ORequest.ResetToDefaults; ORequest.Client := Self; ORequest.Accept := REQ_BildAccept; // was set in create event, but has just been cleared // check and initialise the authenticator If (Not Assigned(Authenticator)) Then Authenticator := TOAuth2Authenticator.Create(Self); NAT_SetOAuth2; (Authenticator As TOAuth2Authenticator).AuthCode := lvCode; // now rebuild the request to get the access token ORequest.Method := TRESTRequestMethod.rmPOST; ORequest.Resource := csAuthToken; ORequest.Params.AddItem(csGrantType, csAuthCode, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csCode, URIEncode(lvCode), TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csClientId, FClientId, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csClientSecret, FClientSecret, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csRedirectUri, FCallbackUrl, TRESTRequestParameterKind.pkGETorPOST); ORequest.Execute; // see what happened If (ORequest.Response.Status.Success) Then Begin // lvJson := ORequest.Response.JSONValue; If ORequest.Response.GetSimpleValue(csAccessToken, lvToken) Then Begin // check it has an access token object If (Not Assigned(OAccessToken)) Then OAccessToken := LAccessTokens.FindToken(FUID, FAuthScope); If (OAccessToken.Access <> lvToken) Then Begin OAccessToken.Access := lvToken; // new access token If ORequest.Response.GetSimpleValue(csExpiresIn, lvToken) Then // during testing the expiry time was always 14400 - which is 4 hours in seconds. 86400 seconds in a day. OAccessToken.TimeOut := Now + (StrToIntDef(lvToken, 14400) / 86400) Else OAccessToken.TimeOut := Now + 0.166; // lasts for 4 hours If ORequest.Response.GetSimpleValue(csRefreshToken, lvToken) Then OAccessToken.Refresh := lvToken; // new refresh token OAccessToken.Expires := Date + 547; // can refresh for up to 18 months // this token now needs to be saved, but that is for the owner application // set the new access token in the authenticator (Authenticator As TOAuth2Authenticator).AccessToken := OAccessToken.Access; // check whether we can save the changes If (Assigned(@OnTokenChange)) Then Begin OnTokenChange(Self, FUID, FAuthScope, OAccessToken.Access, OAccessToken.Refresh, OAccessToken.Expires, OAccessToken.TimeOut); FTokenState := tsOK; End Else FTokenState := tsUpdated; End; End // if token Else Begin Raise Exception.Create(csMsgNoTokenRtn); End; End // if success Else Begin Raise Exception.Create(csMsgBadResponse); End; End; // if pos > 0 End; (* **************************************************************************** * Close the login form - fired as an event. * **************************************************************************** *) Procedure THMRCRestClient.NAT_WebFormClose(Sender: TObject; Var Action: TCloseAction); Var lvForm: TOAuthWebForm; Begin lvForm := Sender AS TOAuthWebForm; If (lvForm <> Nil) Then Begin lvForm.OnAfterRedirect := Nil; lvForm.Release; End; End; (* **************************************************************************** * Try to login and get a new user access token. * **************************************************************************** *) Function THMRCRestClient.NewAccessToken: boolean; Var lvForm: TOAuthWebForm; lURL: String; Begin Result := False; If (NAT_CheckReady) Then Begin lURL := NAT_BildAuthUrl; lvForm := TOAuthWebForm.Create(Owner); // lvForm.Width := 550; lvForm.OnAfterRedirect := NAT_TryForToken; // possibly use OnBeforeRedirect on Android/Mobile ?? lvForm.Caption := csHmrcLogin; lvForm.OnClose := NAT_WebFormClose; lvForm.ShowWithURL(NAT_BildAuthUrl); // do we know the outcome here ? Result := true; // at least there were no errors up to this point End Else Raise Exception.Create(FLastError); End; (* **************************************************************************** * REFRESH ACCESS TOKEN (RAT) SECTION * ****************************************************************************** * Get a new access token using the current refresh token. * **************************************************************************** *) Function THMRCRestClient.RAT_RefreshToken: integer; Var lvToken: String; Begin Result := RESULT_NONE; Try REQ_ClearLast; REQ_Reset; RAT_SetOAuth2; // now rebuild the request to get the new access token ORequest.Method := TRESTRequestMethod.rmPOST; ORequest.Resource := csAuthToken; ORequest.Params.AddItem(csGrantType, csRefreshToken, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csRefreshToken, OAccessToken.Refresh, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csClientId, FClientId, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csClientSecret, FClientSecret, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csRedirectUri, FCallbackUrl, TRESTRequestParameterKind.pkGETorPOST); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; // see what happened If (ORequest.Response.Status.Success) Then Begin If ORequest.Response.GetSimpleValue(csAccessToken, lvToken) Then Begin If (OAccessToken.Access <> lvToken) Then Begin // access token for scope OAccessToken.Access := lvToken; If ORequest.Response.GetSimpleValue(csExpiresIn, lvToken) Then // during testing the expiry time was always 14400 - which is 4 hours in seconds. 86400 seconds in a day. OAccessToken.TimeOut := Now + (StrToIntDef(lvToken, 14400) / 86400) Else // access token expiry is in 4 hours OAccessToken.TimeOut := Now + 0.166; // get the new refresh token If ORequest.Response.GetSimpleValue(csRefreshToken, lvToken) Then Begin OAccessToken.Refresh := lvToken; End; // set the new access token in the authenticator (Authenticator As TOAuth2Authenticator).AccessToken := OAccessToken.Access; // check whether we can save the changes If (Assigned(@OnTokenChange)) Then Begin OnTokenChange(Self, FUID, FAuthScope, OAccessToken.Access, OAccessToken.Refresh, OAccessToken.Expires, OAccessToken.TimeOut); FTokenState := tsOK; End Else FTokenState := tsUpdated; Result := RESULT_OK; End; End Else Begin FLastCode := ERR_NO_ACCESS_TOKEN; FLastError := csMsgNoTokenFnd + ORequest.Response.Content; End; End // if success Else Begin FLastCode := ERR_NO_ACCESS_TOKEN; FLastError := csMsgBadResponse + ' : ' + ORequest.Response.Content; End; Except On e: Exception Do Begin FLastCode := ERR_NO_ACCESS_TOKEN; FLastError := csMsgRefreshErr + e.Message; Result := RESULT_FAIL; End; End; End; (* **************************************************************************** * Set OAuth2 params for HMRC access token refresh. * * Assumes that there is a current access token to refresh. * **************************************************************************** *) Procedure THMRCRestClient.RAT_SetOAuth2; Begin (Authenticator As TOAuth2Authenticator).AccessToken := ''; (Authenticator As TOAuth2Authenticator).RefreshToken := OAccessToken.Refresh; (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).ResponseType := TOAuth2ResponseType.rtTOKEN; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; (Authenticator As TOAuth2Authenticator).Scope := FAuthScope; (Authenticator As TOAuth2Authenticator).AuthorizationEndpoint := BaseUrl + csAuthToken; (Authenticator As TOAuth2Authenticator).RedirectionEndpoint := FCallbackUrl; End; Procedure THMRCRestClient.RemoveaHeader(Const aName: String); Var I: integer; Begin For I := 0 To LHeaderList.Count - 1 Do Begin If LHeaderList[I].StartsWith(aName) Then Begin LHeaderList.Delete(I); Exit; End; End; End; (* **************************************************************************** * REQUEST SETTING SECTION * ****************************************************************************** * Create the accept header for the request with the current api version. * **************************************************************************** *) Function THMRCRestClient.REQ_BildAccept: String; Begin Result := csApVnd + FApiVersion + csWithJson; End; (* **************************************************************************** * Check whether there is a token, it is current and can be refreshed. * **************************************************************************** *) Function THMRCRestClient.REQ_CheckToken: boolean; Begin Result := true; FTokenState := tsNone; // no authorisation required, so it must be ok // if (FAuthMode = amNone) then // Exit // Application authorisation requires a server token If (FAuthMode = amApplication) Then Begin If (FServerToken = '') Then Begin // this is a failure and the process cannot connect FLastError := csMsgNoSvrToken; FLastCode := ERR_NO_SERVER_TOKEN; Result := False; End Else Begin // assumes the token it has is correct - there is no way to validate it FTokenState := tsOK; End; End Else If (FAuthMode = amUser) Then Begin // is there an access token object ? if not, then it will need to get a new token If (Assigned(OAccessToken)) Then Begin // does it have an access token ? // no token should be an error condition, but just get a new access token - not failed yet If (OAccessToken.Access <> '') Then Begin // has it expired ? If (OAccessToken.Expires < Date) Then Begin FTokenState := tsExpired; FLastError := csMsgTokenExp; FLastCode := ERR_TOKEN_EXPIRED; Result := False; End // if expired Else Begin // has it timed out ? If (OAccessToken.TimeOut < Now) Then Begin // does it have a refresh token If (OAccessToken.Refresh <> '') Then Begin // try to refresh the access token If (RAT_RefreshToken <> RESULT_OK) Then Begin // ??? // set token state to expired FTokenState := tsExpired; FLastError := csMsgTokenExp; FLastCode := ERR_TOKEN_EXPIRED; Result := False; End; End Else Begin // cannot refresh, so set as expired FTokenState := tsExpired; FLastError := csMsgTokenExp; FLastCode := ERR_TOKEN_EXPIRED; Result := False; End; End // if timed out Else Begin FTokenState := tsOK; End; // else ok End; // else not expired End // if not empty Else Begin FLastError := csMsgNoTokenFnd; FLastCode := ERR_NO_ACCESS_TOKEN; Result := False; End; // else no token value End // if has access token Else Begin FLastError := csMsgNoTokenFnd; FLastCode := ERR_NO_ACCESS_TOKEN; Result := False; End; // else no token object End; End; (* **************************************************************************** * Clear the last response values. * **************************************************************************** *) Procedure THMRCRestClient.REQ_ClearLast; Begin FLastCode := 0; FLastError := ''; FLastMsg := ''; FLastValue := Nil; End; (* **************************************************************************** * convert date to HMRC compatible date string. * **************************************************************************** *) Function THMRCRestClient.REQ_DateFormat(Const Value: TDateTime): String; Begin Result := FormatDateTime('YYYY-MM-DD', Value); End; Procedure THMRCRestClient.REQ_LoadHeaders; Var ix1: integer; Vals: TArray<String>; Begin If (Assigned(LHeaderList)) And (LHeaderList.Count > 0) Then Begin For ix1 := 0 To LHeaderList.Count - 1 Do Begin Vals := LHeaderList[ix1].Split(['|']); If (Length(Vals) = 3) And (Vals[2] = 'noencode') Then Begin ORequest.Params.AddHeader(Vals[0], Vals[1]).Options := [poDoNotEncode]; End Else Begin // don't think we need to encode here as it could result in double encoding, which is not pretty ORequest.Params.AddHeader(Vals[0], Vals[1]); // ORequest.Params.AddHeader(Vals[0], UriEncode(Vals[1])); End; End; End; End; (* **************************************************************************** * Reset the request parameters to defaults and rebuild headers. * **************************************************************************** *) Procedure THMRCRestClient.REQ_Reset; Var tmp: String; Vals: TArray<String>; Begin if FResetCount > 0 then ORequest.ResetToDefaults; Inc(FResetCount); // because we did reset defaults ORequest.Method := TRESTRequestMethod.rmGET; ORequest.Client := Self; ORequest.Accept := REQ_BildAccept; // was set in create event, but has just been cleared ORequest.Params.AddHeader(csAuthorization, csUBearer + ' ' + OAccessToken.Access); // add gov and vendor headers if supplied REQ_LoadHeaders; ORequest.Params.AddItem(csAccessToken, OAccessToken.Access, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csTokenType, csLBearer, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csScope, FAuthScope, TRESTRequestParameterKind.pkGETorPOST); (Authenticator As TOAuth2Authenticator).AccessToken := OAccessToken.Access; (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; (Authenticator As TOAuth2Authenticator).Scope := FAuthScope; End; (* **************************************************************************** * PROPERTY METHODS SECTION * ****************************************************************************** * Get the last http status code. * **************************************************************************** *) Function THMRCRestClient.GetLastCode: integer; Begin Result := FLastCode; End; (* **************************************************************************** * Get the last error/failure message. * **************************************************************************** *) Function THMRCRestClient.GetLastError: String; Begin Result := FLastError; End; (* **************************************************************************** * Get the last http status message. * **************************************************************************** *) Function THMRCRestClient.GetLastMsg: String; Begin Result := FLastMsg; End; (* **************************************************************************** * Get the last response json value. * **************************************************************************** *) Function THMRCRestClient.GetLastValue: TJSONValue; Begin Result := FLastValue; End; class procedure THMRCRestClient.InitialiseClassVars; begin FResetCount := 0; end; (* **************************************************************************** * Reset the accept parameters with the new api version. * **************************************************************************** *) Procedure THMRCRestClient.SetApiVersion(Const Value: String); Begin If (Not AnsiSametext(Value, FApiVersion)) Then Begin FApiVersion := Value; ORequest.Accept := REQ_BildAccept; Self.Accept := REQ_BildAccept; End; End; (* **************************************************************************** * Set OAuth2 params for HMRC user login. * **************************************************************************** *) Procedure THMRCRestClient.SetAuthMode(Const Value: THmrcAuthMode); Begin FAuthMode := Value; End; (* **************************************************************************** * Set OAuth2 params for HMRC user login and try to find the access token. * **************************************************************************** *) Procedure THMRCRestClient.SetAuthScope(Const Value: String); Begin FAuthScope := Value; OAccessToken := LAccessTokens.GetAccessToken(FUID, FAuthScope); End; (* **************************************************************************** * Set OAuth2 params for HMRC user login. * **************************************************************************** *) Procedure THMRCRestClient.SetCallbackUrl(Const Value: String); Begin FCallbackUrl := Value; End; (* **************************************************************************** * Set the header list. * **************************************************************************** *) Procedure THMRCRestClient.SetHeaderList(Const Value: TStringList; OwnsList: boolean); Begin If (Assigned(Value)) Then Begin If (Assigned(LHeaderList)) And (FOwnsHeaders) Then LHeaderList.Free; LHeaderList := Value; FOwnsHeaders := OwnsList; End; End; (* **************************************************************************** * Set the test status - changes the base url. * **************************************************************************** *) Procedure THMRCRestClient.SetIzTest(Const Value: boolean); Begin If (FIzTest <> Value) Then Begin FIzTest := Value; If (FIzTest) Then BaseUrl := HmrcTestUrl Else BaseUrl := HmrcProdUrl; End; End; (* **************************************************************************** * Set User ID for HMRC user login and try to find the access token. * **************************************************************************** *) Procedure THMRCRestClient.SetUID(Const Value: String); Begin FUID := Value; OAccessToken := LAccessTokens.GetAccessToken(FUID, FAuthScope); End; { THmrcTestClient } (* **************************************************************************** * HMRC REST CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THmrcTestClient.Create(AOwner: TComponent); Begin Inherited; BaseUrl := HmrcTestUrl; BaseResource := csHello; ORequest.Resource := csHello; Setlength(LScopeList, 1); LScopeList[0] := csHello; End; (* **************************************************************************** * ADD USERS SECTION * ****************************************************************************** ****************************************************************************** * Create a new agent and return the details. * **************************************************************************** *) Function THmrcTestClient.AddAgent: integer; Begin Result := RESULT_NONE; REQ_ClearLast; If (NUS_CheckReady) Then Begin BaseUrl := HmrcTestUrl; ORequest.Resource := 'create-test-user/agents'; // this is described as an option, but does not appear to work. I have left it in anyway ORequest.Params.AddHeader(csAuthorization, csUBearer + ' ' + FServerToken); // It requires the server token to be set as the access token in the OAuth2 thingy (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).AccessToken := FServerToken; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; ORequest.Method := TRESTRequestMethod.rmPOST; // hard-coded json string - this is the only option allowed ORequest.Body.Add('{"serviceNames": ["agent-services"]}', ctAPPLICATION_JSON); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := RESULT_FAIL; End; End Else Begin Result := RESULT_ERROR; End; End; (* **************************************************************************** * Create a new company and return the details. * **************************************************************************** *) Function THmrcTestClient.AddCompany: integer; Begin Result := RESULT_NONE; REQ_ClearLast; If (NUS_CheckReady) Then Begin BaseUrl := HmrcTestUrl; ORequest.Resource := 'create-test-user/organisations'; // this is described as an option, but does not appear to work. I have left it in anyway ORequest.Params.AddHeader(csAuthorization, csUBearer + ' ' + FServerToken); // It requires the server token to be set as the access token in the OAuth2 thingy (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).AccessToken := FServerToken; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; ORequest.Method := TRESTRequestMethod.rmPOST; // hard-coded json string - there are some other options available - see HMRC website ORequest.Body.Add('{"serviceNames": ["paye-for-employers", "submit-vat-returns", ' + '"national-insurance", "self-assessment", "mtd-income-tax", "mtd-vat"]}', ctAPPLICATION_JSON); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := RESULT_FAIL; End; End Else Begin Result := RESULT_ERROR; End; End; (* **************************************************************************** * Create a new individual and return the details. * **************************************************************************** *) Function THmrcTestClient.AddPerson: integer; Begin Result := RESULT_NONE; REQ_ClearLast; If (NUS_CheckReady) Then Begin BaseUrl := HmrcTestUrl; ORequest.Resource := 'create-test-user/individuals'; ORequest.Params.AddHeader(csAuthorization, csUBearer + ' ' + FServerToken); // It requires the server token to be set as the access token in the OAuth2 thingy (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).AccessToken := FServerToken; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; ORequest.Method := TRESTRequestMethod.rmPOST; // hard-coded json string - - these are the only options allowed ORequest.Body.Add ('{"serviceNames": ["national-insurance", "self-assessment", "mtd-income-tax", "customs-services"]}', ctAPPLICATION_JSON); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := RESULT_FAIL; End; End Else Begin Result := RESULT_ERROR; End; End; (* **************************************************************************** * Check details for an application level api call. * **************************************************************************** *) Function THmrcTestClient.NUS_CheckReady: boolean; Begin Result := NAT_CheckReady; If (Result) Then Begin If (FServerToken = '') Then Begin FLastError := csMsgNoSvrToken; FLastCode := ERR_NO_SERVER_TOKEN; Result := False; End; End; End; (* **************************************************************************** * Call the hello application resource / end point. Uses the server token. * **************************************************************************** *) Function THmrcTestClient.TestFraudHeaders: integer; Begin Result := RESULT_NONE; REQ_ClearLast; If (NUS_CheckReady) Then Begin REQ_LoadHeaders; BaseUrl := HmrcTestUrl; ORequest.Resource := 'test/fraud-prevention-headers/validate'; // this is described as an option, but does not appear to work. I have left it in anyway ORequest.Params.AddHeader(csAuthorization, csUBearer + ' ' + FServerToken); // It requires the server token to be set as the access token in the OAuth2 thingy (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).AccessToken := FServerToken; (Authenticator As TOAuth2Authenticator).ClientId := FClientId; (Authenticator As TOAuth2Authenticator).ClientSecret := FClientSecret; ORequest.Method := TRESTRequestMethod.rmGET; ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := RESULT_FAIL; End; End Else Begin Result := RESULT_ERROR; End; End; Function THmrcTestClient.TestHelloApplication: String; Begin Result := ''; REQ_ClearLast; FAuthMode := amApplication; If (NUS_CheckReady) Then Begin ORequest.ResetToDefaults; // should it do this every time ? // because we did reset defaults ORequest.Method := TRESTRequestMethod.rmGET; ORequest.Client := Self; ORequest.Accept := REQ_BildAccept; // was set in create event, but has just been cleared ORequest.Resource := csHello; ORequest.ResourceSuffix := 'application'; // It requires the server token to be set as the access token in the OAuth2 thingy If (Not Assigned(Authenticator)) Then Authenticator := TOAuth2Authenticator.Create(Self); (Authenticator As TOAuth2Authenticator).TokenType := TOAuth2TokenType.ttBEARER; (Authenticator As TOAuth2Authenticator).AccessToken := FServerToken; ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := FLastValue.GetValue<String>(csMessage); End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := FLastError; End; End Else Begin Result := FLastError; End; End; (* **************************************************************************** * Call the hello user resource / end point. Requires OAuth2 access token. * * If there is no token, it will call the get new access token method and * * when it is finished, it needs to be run again to caal the api. * **************************************************************************** *) Function THmrcTestClient.TestHelloUser: String; Begin Result := ''; Try FAuthMode := amUser; FAuthScope := csHello; If (REQ_CheckToken) Then Begin REQ_ClearLast; REQ_Reset; // hello user specific ORequest.Resource := 'hello/user'; ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.Status.Success) Then Begin FLastValue := ORequest.Response.JSONValue; Result := FLastValue.GetValue<String>(csMessage); End Else Begin FLastError := IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := FLastError; End; End Else Begin // tell the user that there is no access token and to try again Result := FLastError; // create the new access token that will be used when they try again NewAccessToken; End; Except On e: Exception Do Begin FLastError := csMsgTestUsrErr + e.Message; Result := FLastError; End; End; End; (* **************************************************************************** * Call the hello world resource / end point. No security or validation. * **************************************************************************** *) Function THmrcTestClient.TestHelloWorld: String; Begin Result := ''; REQ_ClearLast; FAuthMode := amNone; If (NAT_CheckReady) Then Begin ORequest.ResetToDefaults; // because we did reset defaults ORequest.Method := TRESTRequestMethod.rmGET; ORequest.Client := Self; ORequest.Accept := REQ_BildAccept; // was set in create event, but has just been cleared ORequest.Resource := csHello; ORequest.ResourceSuffix := 'world'; ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.StatusCode < 400) Then Begin FLastValue := ORequest.Response.JSONValue; Result := FLastValue.GetValue<String>(csMessage); End Else Begin FLastError := csError + IntToStr(ORequest.Response.StatusCode) + ' ' + ORequest.Response.Content; Result := FLastError; End; End Else Result := FLastError; End; { THmrcNIClient } (* **************************************************************************** * HMRC NI CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THmrcNIClient.Create(AOwner: TComponent); Begin Inherited; End; { THmrcPAYEClient } (* **************************************************************************** * HMRC PAYE CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THmrcPAYEClient.Create(AOwner: TComponent); Begin Inherited; End; { THmrcSAClient } (* **************************************************************************** * HMRC SA CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THmrcSAClient.Create(AOwner: TComponent); Begin Inherited; End; { THmrcVATClient } (* **************************************************************************** * HMRC VAT CLIENT * ****************************************************************************** * INIT SECTION * ****************************************************************************** * Init. * **************************************************************************** *) Constructor THmrcVATClient.Create(AOwner: TComponent); Begin Inherited; FAuthMode := amUser; // always user authentication FAuthScope := csReadVat; // change this if submitting returns Setlength(LScopeList, 2); LScopeList[0] := csReadVat; LScopeList[1] := csRiteVat; End; (* **************************************************************************** * API METHODS SECTION * ****************************************************************************** * Call VAT Liabilities / Obligations / Payments for a date range. The only * * difference is the last element of the resource. * **************************************************************************** *) Function THmrcVATClient.API_SearchLP(Const aType: String; Const FromDate, ToDate: TDateTime): integer; Begin Result := RESULT_NONE; Try REQ_ClearLast; If (FUID <> '') Then Begin If (PRM_CheckDates(FromDate, ToDate)) Then Begin AuthScope := csReadVat; If (REQ_CheckToken) Then Begin REQ_ClearLast; REQ_Reset; // search specific ORequest.Resource := csOrgsVat + FUID + '/' + aType; ORequest.Params.AddItem(csFrom, FDateFrom, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csTo, FDateTo, TRESTRequestParameterKind.pkGETorPOST); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.Status.Success) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := ORequest.Response.Content; Result := RESULT_FAIL; End; // else failed End // if token Else Begin // error message set in CheckToken Result := RESULT_FAIL; End; End // if dates Else Begin // error message set in check dates Result := RESULT_FAIL; End; End // if uid Else Begin FLastCode := ERR_NO_USER_ID; FLastMsg := csMsgNoUserId; Result := RESULT_FAIL; End; Except On e: Exception Do Begin FLastError := e.Message; Result := RESULT_ERROR; End; End; End; (* **************************************************************************** * Get VAT liabilities details for a given date range. * **************************************************************************** *) Function THmrcVATClient.GetLiabilities(Const FromDate, ToDate: TDateTime): integer; Begin Result := API_SearchLP(csLiabilities, FromDate, ToDate); End; (* **************************************************************************** * Get VAT obkigations details for a given date range. * **************************************************************************** *) Function THmrcVATClient.GetObligations(Const FromDate, ToDate: TDateTime; aStatus: String = ''): integer; Begin Result := RESULT_NONE; Try REQ_ClearLast; If (FUID <> '') Then Begin If (PRM_CheckDates(FromDate, ToDate)) Then Begin AuthScope := csReadVat; If (REQ_CheckToken) Then Begin REQ_ClearLast; REQ_Reset; // search specific ORequest.Resource := csOrgsVat + FUID + '/' + csObligations; ORequest.Params.AddItem(csFrom, FDateFrom, TRESTRequestParameterKind.pkGETorPOST); ORequest.Params.AddItem(csTo, FDateTo, TRESTRequestParameterKind.pkGETorPOST); If (aStatus = 'F') Or (aStatus = 'O') Then ORequest.Params.AddItem(csStatus, aStatus, TRESTRequestParameterKind.pkGETorPOST); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.Status.Success) Then Begin FLastValue := ORequest.Response.JSONValue; Result := RESULT_OK; End Else Begin FLastError := ORequest.Response.Content; Result := RESULT_FAIL; End; // else failed End // if token Else Begin // error message set in CheckToken Result := RESULT_FAIL; End; End // if dates Else Begin // error message set in check dates Result := RESULT_FAIL; End; End // if uid Else Begin FLastCode := ERR_NO_USER_ID; FLastMsg := csMsgNoUserId; Result := RESULT_FAIL; End; Except On e: Exception Do Begin FLastError := e.Message; Result := RESULT_ERROR; End; End; End; (* **************************************************************************** * Get VAT payments details for a given date range. * **************************************************************************** *) Function THmrcVATClient.GetPayments(Const FromDate, ToDate: TDateTime): integer; Begin Result := API_SearchLP(csPayments, FromDate, ToDate); End; (* **************************************************************************** * Get VAT Returns details for a given period. * **************************************************************************** *) Function THmrcVATClient.GetReturn(Const aPeriod: String; Var ACorrelationId: String): integer; Begin Result := RESULT_NONE; Try REQ_ClearLast; If (FUID <> '') Then Begin If (PRM_CheckPeriod(aPeriod)) Then Begin AuthScope := csReadVat; If (REQ_CheckToken) Then Begin REQ_ClearLast; REQ_Reset; // view returns specific ORequest.Resource := csOrgsVat + FUID + '/' + csReturns; ORequest.ResourceSuffix := URIEncode(aPeriod); ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.Status.Success) Then Begin FLastValue := ORequest.Response.JSONValue; ACorrelationId := ORequest.Response.Headers.Values['X-Correlationid']; Result := RESULT_OK; End Else Begin FLastError := ORequest.Response.Content; Result := RESULT_FAIL; End; // else failed End // if token Else Begin // error message set in CheckToken Result := RESULT_FAIL; End; End // if dates Else Begin // error message set in check period Result := RESULT_FAIL; End; End // if uid Else Begin FLastCode := ERR_NO_USER_ID; FLastMsg := csMsgNoUserId; Result := RESULT_FAIL; End; Except On e: Exception Do Begin FLastError := e.Message; Result := RESULT_ERROR; End; End; End; (* **************************************************************************** * Submit VAT Returns details for a given period. Parse the confirmation * * details into a string list. * **************************************************************************** *) Function THmrcVATClient.SubmitReturn(Const aPeriod: String; Const Values: TStringList; Const IzFinal: boolean; Var Confirm: String): integer; Var S, lLogName, lCorrelation, lCorrelationId, lReceipt, lReceiptId, lJSON: String; lVal: TArray<String>; Begin Result := RESULT_NONE; Confirm := ''; Try REQ_ClearLast; If (FUID <> '') Then Begin If (PRM_CheckPeriod(aPeriod)) Then Begin If (PRM_CheckValues(Values)) Then Begin AuthScope := csRiteVat; If (REQ_CheckToken) Then Begin REQ_ClearLast; REQ_Reset; // that set it to GET, so change it ORequest.Method := TRESTRequestMethod.rmPOST; // submit returns specific ORequest.Resource := csOrgsVat + FUID + '/' + csReturns; // the json is accepted if created like this using the JSONWriter element of the request ORequest.Body.JSONWriter.WriteStartObject; // add period ORequest.Body.JSONWriter.WritePropertyname('periodKey'); ORequest.Body.JSONWriter.WriteValue(aPeriod); // add the list of numeric values ORequest.Body.JSONWriter.WritePropertyname(Values.Names[0]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[0])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[1]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[1])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[2]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[2])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[3]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[3])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[4]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[4])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[5]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[5])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[6]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[6])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[7]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[7])); ORequest.Body.JSONWriter.WritePropertyname(Values.Names[8]); ORequest.Body.JSONWriter.WriteValue(StrToFloat(Values.ValueFromIndex[8])); // add the finalised state ORequest.Body.JSONWriter.WritePropertyname('finalised'); ORequest.Body.JSONWriter.WriteValue(IzFinal); // and close ORequest.Body.JSONWriter.WriteEndObject; ORequest.Execute; FLastCode := ORequest.Response.StatusCode; FLastMsg := ORequest.Response.StatusText; If (ORequest.Response.Status.Success) Then Begin lLogName := aPeriod + '_' + FormatDateTime('yyyymmddhhnnss', Now) + '.json'; lLogName := TPath.Combine(StoreFolder, lLogName); lCorrelation := ORequest.Response.Headers[ORequest.Response.Headers.IndexOfName(csXCorrelationid)]; Try lVal := lCorrelation.Split(['=']); lCorrelationId := lVal[1]; Except lCorrelationId := 'unknown'; lCorrelation := csXCorrelationid + '=' + lCorrelationId; End; lReceipt := ORequest.Response.Headers[ORequest.Response.Headers.IndexOfName(csReceiptId)]; Try lVal := lReceipt.Split(['=']); lReceiptId := lVal[1]; Except lReceiptId := 'unknown'; lReceipt := csReceiptId + '=' + lReceiptId; End; lJSON := '{' + sLineBreak + ' "correlation-id":"$",'.Replace('$', lCorrelationId) + sLineBreak + ' "receipt-id":"$",'.Replace('$', lReceiptId); TFile.WriteAllText(lLogName, ORequest.Response.JSONText.Replace('{', lJSON)); FLastValue := ORequest.Response.JSONValue; // we actually need to extract values from the response headers Confirm := lCorrelation + ';' + lReceipt; // ORequest.Response.Headers[ORequest.Response.Headers.IndexOfName(csXCorrelationid)]; // Confirm := Confirm + ';' + ORequest.Response.Headers[ORequest.Response.Headers.IndexOfName(csReceiptId)]; // and for convenience add them to the stringlist data Try If FLastValue.TryGetValue<String>(csProcessingdate, S) Then Confirm := Confirm + ';' + csProcessingdate + '=' + S; If FLastValue.TryGetValue<String>(csPaymentIndicator, S) Then Confirm := Confirm + ';' + csPaymentIndicator + '=' + S; If FLastValue.TryGetValue<String>(csFormBundleNumber, S) Then Confirm := Confirm + ';' + csFormBundleNumber + '=' + S; If FLastValue.TryGetValue<String>(csChargeRefNumber, S) Then Confirm := Confirm + ';' + csChargeRefNumber + '=' + S; Except // let's not fail just because of an error here End; Result := RESULT_OK; End Else Begin FLastError := ORequest.Response.Content; Result := RESULT_FAIL; End; // else failed End // if token Else Begin // error message set in CheckToken Result := RESULT_FAIL; End; End // if values Else Begin FLastCode := ERR_INVALID_DATA; FLastMsg := csMsgBadData; Result := RESULT_FAIL; End; End // if dates Else Begin // error message set in check period Result := RESULT_FAIL; End; End // if uid Else Begin FLastCode := ERR_NO_USER_ID; FLastMsg := csMsgNoUserId; Result := RESULT_FAIL; End; Except On e: Exception Do Begin FLastError := e.Message; Result := RESULT_ERROR; End; End; End; (* **************************************************************************** * VALIDATION METHODS SECTION * ****************************************************************************** * Check the vat search parameters are valid date ranges. * **************************************************************************** *) Function THmrcVATClient.PRM_CheckDates(Const dtFrom, dtTo: TDateTime): boolean; Begin Result := true; If (dtFrom > dtTo) Then Begin FLastCode := ERR_DATE_ERROR; FLastError := csMsgDateError; Result := False; End Else If ((dtTo - dtFrom) > 365) Then Begin FLastCode := ERR_DATE_RANGE; FLastError := csMsgDateRange; Result := False; End Else If (dtFrom < 1) Then Begin FLastCode := ERR_DATE_LOW; FLastError := csMsgDateLow; Result := False; End Else If (dtFrom > (Date + 365)) Then Begin FLastCode := ERR_DATE_HIGH; FLastError := csMsgDateHigh; Result := False; End Else Begin FDateFrom := REQ_DateFormat(dtFrom); FDateTo := REQ_DateFormat(dtTo); End; End; (* **************************************************************************** * Check the vat period is sort of sensible. * **************************************************************************** *) Function THmrcVATClient.PRM_CheckPeriod(Const Value: String): boolean; Begin Result := true; If (Length(Value) <> 4) Then Begin FLastCode := ERR_INVALID_PERIOD; FLastError := csMsgBadPeriod; Result := False; End; End; (* **************************************************************************** * Check the values supplied for submission are valid. Are there 9 and are * * they all numeric. It does not check for sign and decimal places. * **************************************************************************** *) Function THmrcVATClient.PRM_CheckValues(Const Values: TStringList): boolean; Var idx: integer; Begin Result := true; If (Values = Nil) Then Begin FLastCode := ERR_NO_DATA; FLastError := csMsgNoData; Result := False; End Else If (Values.Count <> 9) Then Begin FLastCode := ERR_INVALID_DATA; FLastError := csMsgBadData; Result := False; End Else Begin For idx := 0 To Values.Count - 1 Do Begin If (Values.ValueFromIndex[idx] = '') Then Begin FLastCode := ERR_INVALID_DATA; FLastError := csMsgBadData; Result := False; Break; End Else If (StrToFloatDef(Values.ValueFromIndex[idx], 0) = 0) And (StrToFloatDef(Values.ValueFromIndex[idx], 10) = 10) Then Begin FLastCode := ERR_INVALID_DATA; FLastError := csMsgBadData; Result := False; Break; End; End; // for idx End; End; (* **************************************************************************** * Perform basic checks on the user id as a VRN. * **************************************************************************** *) Function THmrcVATClient.SetHmrcID(Const Value: String): integer; Var lvUid: String; Begin Result := RESULT_OK; lvUid := Trim(Value); // check it is not empty If (lvUid = '') Then Begin FLastCode := ERR_NO_USER_ID; FLastError := csMsgNoUserId; Result := RESULT_FAIL; End // check length is sensible Else If (Length(lvUid) <> 9) Then Begin FLastCode := ERR_INVALID_USER_ID; FLastError := csMsgBadUserId; Result := RESULT_FAIL; End // check it is a number Else If (StrToInt64Def(lvUid, 0) = 0) Then Begin FLastCode := ERR_INVALID_USER_ID; FLastError := csMsgBadUserId; Result := RESULT_FAIL; End // no problem so set it as the current user id Else Begin FUID := lvUid; End; End; initialization THMRCRestClient.InitialiseClassVars; End.
//**************************************************************** // // Inventory Control // // Copyright (c) 2002-2003 Failproof Manufacturing Systems. // //**************************************************************** // // Change History // // 03/10/2003 David Verespey Create Form // unit ForecastBreakdownF; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, History, Datamodule,ADOdb,ComObj,strutils,dateutils; type TWeekData = record WeekNumber :integer; WeekDate :string; WeekCount :integer; end; TEntryRec = record Supplier :string; Partnumber :string; KanbanNumber :string; Skip :boolean; Weeks :array[1..14] of TWeekData; end; TForecastBreakdown_Form = class(TForm) Hist: THistory; OKButton: TButton; procedure OKButtonClick(Sender: TObject); private { Private declarations } fFilename:string; fEntries:array of TEntryRec; fSupplierCode:string; fFirstWeekNumber:integer; fFirstWeekDate:string; fHistDate:string; fFileKind: TFileKind; fClosed:boolean; function ScanLine(line:string;count:integer):boolean; function ScanPartnumber:boolean; procedure UpdateForecast; procedure UpdateUsage; procedure DoPartNumberForecast(PN,WeekDate:string;FCCount,WeekNumber:integer); function HistoryForecast(partno:string):integer; procedure DeleteBreakdown(partnum:string); public { Public declarations } function Execute:boolean; published property filename:string read fFilename write fFilename; property SupplierCode:string read fSupplierCode write fSupplierCode; end; const SUPPLIER_OFF=1; SUPPLIER_SIZE=5; PARTNUMBER_OFF=6; PARTNUMBER_SIZE=12; KANBAN_OFF=18; KANBAN_SIZE=4; FORECASTW1_OFF=22; FORECASTW2_OFF=36; FORECASTW3_OFF=50; FORECASTW4_OFF=64; FORECASTW5_OFF=78; FORECASTW6_OFF=92; FORECASTW7_OFF=106; FORECASTW8_OFF=120; FORECASTW9_OFF=134; FORECASTW10_OFF=148; FORECASTW11_OFF=162; FORECASTW12_OFF=176; FORECASTW13_OFF=190; FORECASTW14_OFF=204; WEEKNUMBER_SIZE=2; WEEKDATE_SIZE=6; WEEKCOUNT_SIZE=6; var ForecastBreakdown_Form: TForecastBreakdown_Form; implementation uses ForecastCamexreport; {$R *.dfm} procedure TForecastBreakdown_Form.DeleteBreakdown(partnum:string); begin With Data_Module.Inv_StoredProc do Begin Close; ProcedureName := 'dbo.DELETE_ForecastInfo;1'; Parameters.Clear; Parameters.AddParameter.Name := '@WeekDate'; Parameters.ParamValues['@WeekDate'] := '20'+fFirstWeekDate; Parameters.AddParameter.Name := '@HistWeekDate'; Parameters.ParamValues['@HistWeekDate'] := fHistDate; Parameters.AddParameter.Name := '@PartNumber'; Parameters.ParamValues['@PartNumber'] := partnum; ExecProc; End; //With end; function TForecastBreakdown_Form.Execute:boolean; var fcf,tcf,taf:Textfile; fcl,tcl,fn,data:string; fopen:boolean; count,counter:integer; excel: variant; lastsupplier: string; i: integer; mySheet: variant; sendsite: boolean; EDIfile: boolean; EDILine: string; EDIcount,EDIdate,EDIweek: string; ForecastReport: TForecastCAMEXReport; begin result:=TRUE; count:=0; counter:=0; lastsupplier:=''; fclosed:=False; OKButton.Visible:=False; sendsite:=FALSE; //open file try AssignFile(fcf, fFileName); Reset(fcf); //determine file type // // Set EDI flag if EDI 830 file // Readln(fcf, fcl); if pos('ISA',fcl) > 0 then begin Readln(fcf, fcl); Readln(fcf, fcl); data:=copy(fcl,4,3); if data='830' then EDIfile:=TRUE else begin Hist.Append('EDI file type='+data+', expected type=830. Import fail.'); Data_Module.LogActLog('FORECAST','EDI file type='+data+', expected type=830. Import fail.'); exit; end; end else EDIfile:=FALSE; Reset(fcf); //count records while not Seekeof(fcf) do begin Readln(fcf, fcl); if EDIfile then begin //if EDI then LIN identifier indicates a partnumber loop data:=copy(fcl,1,3); if data='LIN' then INC(count); end else INC(count); end; reset(fcf); SetLength(fEntries,count); //get all records, check for bad records on the fly try if EDIfile then begin while true do begin while (data <> 'LIN') and (data <> 'CTT') do begin Readln(fcf, fcl); data:=copy(fcl,1,3); end; if data = 'CTT' then begin // end of records break; end; // 5 digit supplier + 12 digit assy part number + 4 digit bogus kanban number EDILine:=Data_Module.fiSupplierCode.AsString+copy(fcl,9,12)+copy(fcl,25,4); // Build the old style line // // Point to data line data:=''; while data <> 'FST' do begin Readln(fcf, fcl); data:=copy(fcl,1,3); end; // Get all data points while data = 'FST' do begin // Get count fcl:=copy(fcl,pos('*',fcl)+1,length(fcl)); //strip line header EDICount:=format('%.6d',[StrToInt(copy(fcl,1,pos('*',fcl)-1))]); fcl:=copy(fcl,pos('*',fcl)+1,length(fcl)); //strip count fcl:=copy(fcl,5,length(fcl)); //strip more characters EDIdate:=copy(fcl,3,6); EDIweek:=copy(fcl,26,2); EDILine:=EDILine+EDIWeek+EDIDate+EDICount; // Get next line Readln(fcf, fcl); data:=copy(fcl,1,3); end; if ScanLine(EDILine,counter) then begin INC(counter); end; end; end else begin while not Seekeof(fcf) do begin // Non-EDI pass the line and parse it out Readln(fcf, fcl); if ScanLine(fcl,counter) then begin INC(counter); end; end; end; //scan for all suppliers, partnumbers and kanbannumber are in our database Hist.Append(IntToStr(counter)+' total records to process'); Data_Module.LogActLog('FORECAST',IntToStr(counter)+' total records to process'); SetLength(fEntries,counter); fHistDate:=formatdatetime('yyyymmdd',now-(data_module.fiHistoricalForecast.AsInteger*7)); if ScanPartnumber then begin for i:=0 to High(fEntries) do begin if (not fEntries[i].Skip) then begin // Delete data that will be forecast this time and clear history, keep anything that isn't forecast this time DeleteBreakdown(fEntries[i].PartNumber); end; end; //add to forecast table UpdateForecast; // Update Usage in Size Master UpdateUsage; // // Produce output files to send to suppliers // try with Data_Module.Inv_DataSet do begin // Get week number only process files for the next week out Data_Module.Inv_DataSet.Close; Filter:=''; Filtered:=FALSE; Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_ForecastSupplier;1'; Parameters.Clear; Parameters.AddParameter.Name := '@WeekDate'; Parameters.ParamValues['@WeekDate'] := formatdatetime('yyyymmdd',now); Open; // // Change to select file output type based on Supplier selection // // // Init both file types; excel:=Unassigned; fopen:=False; while not eof do begin if fieldbyname('VC_SUPPLIER_CODE').AsString <> lastsupplier then begin try if not VarIsEmpty(excel) then begin // Create file in directory specified for each supplier // Use supplier name+WeekDate for filename try if FileExists(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast') then DeleteFile(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); excel.ActiveWorkbook.SaveAs(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'/'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); except on e:exception do begin Data_Module.LogActLog('ERROR','Failed on delete and save excel files, '+e.message+', for supplier('+Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'+')'); Hist.Append('Failed on delete and save excel files, '+e.message+', for supplier('+Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'+')'); end; end; excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end; if fopen then begin CloseFile(tcf); if Data_Module.fiLocalFTP.AsBoolean then begin CloseFile(taf) end; fOpen:=FALSE; end; except on e:exception do begin Data_Module.LogActLog('ERROR','Failed on close output files, '+e.message+', for supplier('+fieldbyname('VC_SUPPLIER_CODE').AsString+')'); Hist.Append('Failed on close output files, '+e.message+', for supplier('+fieldbyname('VC_SUPPLIER_CODE').AsString+')'); if not VarIsEmpty(excel) then begin excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end; end; end; lastsupplier:=fieldbyname('VC_SUPPLIER_CODE').AsString; // // Get FileKind from SUPPLIER table // With Data_Module.Inv_StoredProc do Begin Close; ProcedureName := 'dbo.SELECT_SupplierInfo;1'; Parameters.Clear; Parameters.AddParameter.Name := '@SupCode'; Parameters.ParamValues['@SupCode'] := lastsupplier; Open; if FieldByName('Output File Type').AsString = 'TEXT' then fFileKind := fText else if FieldByName('Output File Type').AsString = 'EXCEL' then fFileKind := fExcel else fFileKind := fBoth; sendsite:=fieldbyname('Site Number in Order').AsBoolean; End; //With if (fFileKind = fExcel) or (fFileKind = fBoth) then begin excel := createOleObject('Excel.Application'); excel.visible := False; excel.DisplayAlerts := False; excel.workbooks.open(Data_Module.TemplateDir+'ForecastTemplate.xls'); mysheet := excel.workSheets[1]; Hist.Append('Create excel file for supplier, '+lastsupplier); Data_Module.LogActLog('FORECAST','Create excel file for supplier, '+lastsupplier); i:=2; end; if (fFileKind = fText) or (fFileKind = fBoth) then begin fn:=Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'.frc'; AssignFile(tcf,Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'.frc'); Data_Module.LogActLog('FORECAST','Create text file :'+Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'.frc'); Rewrite(tcf); if Data_Module.fiLocalFTP.AsBoolean then begin AssignFile(taf,Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\Archive\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+formatdatetime('yyyymmdd',now)+'.frc'); Data_Module.LogActLog('FORECAST','Create archive text file :'+Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\Archive\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+formatdatetime('yyyymmdd',now)+'.frc'); Rewrite(taf); end; fopen:=true; Hist.Append('Create text file for supplier, '+lastsupplier); Data_Module.LogActLog('FORECAST','Create text file for supplier, '+lastsupplier); end; end; if (fFileKind = fExcel) or (fFileKind = fBoth) then begin mysheet.Cells[i,1].value := fieldbyname('VC_SIZE_CODE').AsString; mysheet.Cells[i,2].value := fieldbyname('VC_PART_NUMBER').AsString; mysheet.Cells[i,3].value := fieldbyname('VC_WEEK_DATE').AsString; mysheet.Cells[i,4].value := fieldbyname('IN_WEEK_NUMBER').AsString; mysheet.Cells[i,5].value := fieldbyname('IN_QTY1').AsString; mysheet.Cells[i,6].value := fieldbyname('IN_QTY2').AsString; mysheet.Cells[i,7].value := fieldbyname('IN_QTY3').AsString; mysheet.Cells[i,8].value := fieldbyname('IN_QTY4').AsString; mysheet.Cells[i,9].value := fieldbyname('IN_QTY5').AsString; mysheet.Cells[i,10].value := fieldbyname('IN_QTY6').AsString; mysheet.Cells[i,11].value := fieldbyname('IN_QTY7').AsString; INC(i); end; if (fFileKind = fText) or (fFileKind = fBoth) then begin tcl:=''; if sendsite then // Mod to add site supplier begin tcl:=Data_Module.fiSupplierCode.AsString; tcl:=tcl+fieldbyname('VC_SUPPLIER_CODE').AsString; end else begin tcl:=fieldbyname('VC_SUPPLIER_CODE').AsString; end; tcl:=tcl+fieldbyname('VC_PART_NUMBER').AsString; tcl:=tcl+fieldbyname('VC_WEEK_DATE').AsString; tcl:=tcl+Format('%.2d',[fieldbyname('IN_WEEK_NUMBER').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY1').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY2').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY3').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY4').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY5').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY6').AsInteger]); tcl:=tcl+Format('%.5d',[fieldbyname('IN_QTY7').AsInteger]); Writeln(tcf,tcl); if Data_Module.fiLocalFTP.AsBoolean then begin Writeln(taf,tcl); end; end; next; end; if not VarIsEmpty(excel) then begin // Create file in directory specified for each supplier // Use supplier name+WeekDate for filename if FileExists(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'/'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast') then DeleteFile(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'/'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); excel.ActiveWorkbook.SaveAs(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'/'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); if Data_Module.fiLocalFTP.AsBoolean then begin if FileExists(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\Archive\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast') then DeleteFile(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\Archive\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); //Archive excel.ActiveWorkbook.SaveAs(Data_Module.Inv_StoredProc.FieldbyName('Directory').AsString+'\Archive\'+ANSIReplaceStr(Data_Module.Inv_StoredProc.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_StoredProc.fieldbyname('Supplier Code').AsString+'-'+'Forecast'); end; excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end else if fopen then begin CloseFile(tcf); if Data_Module.fiLocalFTP.AsBoolean then begin CloseFile(taf); end; end; // // End new file selection code // // end; except on e:exception do begin Data_Module.LogActLog('ERROR','Unable to create forecast output files, '+e.message+', for supplier('+lastsupplier+')'); Hist.Append('Unable to create forecast output files, '+e.message+', for supplier('+lastsupplier+')'); result:=false; if not VarIsEmpty(excel) then begin excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end; end; end; ForecastReport := TForecastCAMEXReport.Create(); if not ForecastReport.Execute then begin Data_Module.LogActLog('FORECAST','Failed on Camex forecast report'); Hist.Append('Camex forecast excel file create failed'); end else Hist.Append('Camex forecast excel create complete'); Data_Module.LogActLog('FORECAST','Forecast processing complete'); Hist.Append('Forecast processing complete, Press OK to continue'); end //DEBUG else result:=FALSE; //DEBUG except on e:exception do begin Data_Module.LogActLog('ERROR','Unable to load forecast, '+e.message); Hist.Append('Unable to load forecast, '+e.Message); result:=false; end; end; finally CloseFile(fcf); end; OKButton.Visible:=True; while not fclosed do begin application.ProcessMessages; sleep(500); end; //put data into forecast table end; function TForecastBreakdown_Form.ScanLine(line:string;count:integer):boolean; begin result:=TRUE; try if copy(line,SUPPLIER_OFF,SUPPLIER_SIZE) = fSupplierCode then begin fEntries[count].Supplier:=copy(line,SUPPLIER_OFF,SUPPLIER_SIZE); fEntries[count].Partnumber:=copy(line,PARTNUMBER_OFF,PARTNUMBER_SIZE); fEntries[count].KanbanNumber:=copy(line,KANBAN_OFF,KANBAN_SIZE); fEntries[count].Skip:=False; fEntries[count].Weeks[1].WeekNumber:=StrToInt(copy(line,FORECASTW1_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[1].WeekDate:=copy(line,FORECASTW1_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); fFirstWeekNumber:=StrToInt(copy(line,FORECASTW1_OFF,WEEKNUMBER_SIZE)); fFirstWeekDate:=copy(line,FORECASTW1_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW1_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[1].WeekCount:=StrToInt(copy(line,FORECASTW1_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[1].WeekCount:=0; fEntries[count].Weeks[2].WeekNumber:=StrToInt(copy(line,FORECASTW2_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[2].WeekDate:=copy(line,FORECASTW2_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW2_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[2].WeekCount:=StrToInt(copy(line,FORECASTW2_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[2].WeekCount:=0; fEntries[count].Weeks[3].WeekNumber:=StrToInt(copy(line,FORECASTW3_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[3].WeekDate:=copy(line,FORECASTW3_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW3_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[3].WeekCount:=StrToInt(copy(line,FORECASTW3_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[3].WeekCount:=0; fEntries[count].Weeks[4].WeekNumber:=StrToInt(copy(line,FORECASTW4_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[4].WeekDate:=copy(line,FORECASTW4_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW4_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[4].WeekCount:=StrToInt(copy(line,FORECASTW4_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[4].WeekCount:=0; fEntries[count].Weeks[5].WeekNumber:=StrToInt(copy(line,FORECASTW5_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[5].WeekDate:=copy(line,FORECASTW5_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW5_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[5].WeekCount:=StrToInt(copy(line,FORECASTW5_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[5].WeekCount:=0; fEntries[count].Weeks[6].WeekNumber:=StrToInt(copy(line,FORECASTW6_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[6].WeekDate:=copy(line,FORECASTW6_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW6_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[6].WeekCount:=StrToInt(copy(line,FORECASTW6_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[6].WeekCount:=0; fEntries[count].Weeks[7].WeekNumber:=StrToInt(copy(line,FORECASTW7_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[7].WeekDate:=copy(line,FORECASTW7_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW7_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[7].WeekCount:=StrToInt(copy(line,FORECASTW7_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[7].WeekCount:=0; fEntries[count].Weeks[8].WeekNumber:=StrToInt(copy(line,FORECASTW8_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[8].WeekDate:=copy(line,FORECASTW8_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW8_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[8].WeekCount:=StrToInt(copy(line,FORECASTW8_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[8].WeekCount:=0; fEntries[count].Weeks[9].WeekNumber:=StrToInt(copy(line,FORECASTW9_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[9].WeekDate:=copy(line,FORECASTW9_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW9_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[9].WeekCount:=StrToInt(copy(line,FORECASTW9_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[9].WeekCount:=0; fEntries[count].Weeks[10].WeekNumber:=StrToInt(copy(line,FORECASTW10_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[10].WeekDate:=copy(line,FORECASTW10_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW10_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[10].WeekCount:=StrToInt(copy(line,FORECASTW10_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[10].WeekCount:=0; fEntries[count].Weeks[11].WeekNumber:=StrToInt(copy(line,FORECASTW11_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[11].WeekDate:=copy(line,FORECASTW11_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW11_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[11].WeekCount:=StrToInt(copy(line,FORECASTW11_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[11].WeekCount:=0; fEntries[count].Weeks[12].WeekNumber:=StrToInt(copy(line,FORECASTW12_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[12].WeekDate:=copy(line,FORECASTW12_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW12_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[12].WeekCount:=StrToInt(copy(line,FORECASTW12_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[12].WeekCount:=0; fEntries[count].Weeks[13].WeekNumber:=StrToInt(copy(line,FORECASTW13_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[13].WeekDate:=copy(line,FORECASTW13_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW13_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[13].WeekCount:=StrToInt(copy(line,FORECASTW13_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[13].WeekCount:=0; if Data_Module.fiAssemblerName.AsString='WQS' then begin fEntries[count].Weeks[14].WeekNumber:=StrToInt(copy(line,FORECASTW14_OFF,WEEKNUMBER_SIZE)); fEntries[count].Weeks[14].WeekDate:=copy(line,FORECASTW14_OFF+WEEKNUMBER_SIZE,WEEKDATE_SIZE); if copy(line,FORECASTW14_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE) <> ' -' then fEntries[count].Weeks[14].WeekCount:=StrToInt(copy(line,FORECASTW14_OFF+WEEKNUMBER_SIZE+WEEKDATE_SIZE,WEEKCOUNT_SIZE)) else fEntries[count].Weeks[14].WeekCount:=0; end; end else result:=false; except on e:exception do begin Showmessage('File read error, '+e.Message+', import failed'); Data_Module.LogActLog('ERROR','File read error, '+e.Message+', import failed'); Raise; end; end; end; function TForecastBreakdown_Form.ScanPartnumber:boolean; var i,x,z,y,skip:integer; excel,mysheet:variant; dbmissing:TStringList; foundx:boolean; begin result:=true; skip:=0; dbmissing:=TSTringList.Create; Hist.Append('Scan part number list'); Data_Module.LogActLog('FORECAST','Scan part number list'); with Data_Module.Inv_DataSet do begin try for i:=0 to High(fEntries) do begin Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_ForecastDetail;1'; Parameters.Clear; Parameters.AddParameter.Name := '@AssyCode'; Parameters.ParamValues['@AssyCode'] := fEntries[i].PArtNumber; Open; if recordcount = 0 then //IsEmpty then// not Locate('Assembly part number Code',fEntries[i].PArtNumber,[]) then begin // Partnumber does not exist, skip Hist.Append('Part Number not found in DB, '+fEntries[i].PartNumber); Data_Module.LogActLog('FORECAST','Part Number not found in DB, '+fEntries[i].PartNumber); fEntries[i].Skip:=True; INC(skip); end; end; Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_ForecastDetail;1'; Parameters.Clear; Parameters.AddParameter.Name := '@AssyCode'; Parameters.ParamValues['@AssyCode'] := ''; Parameters.AddParameter.Name := '@ForecastNotZero'; Parameters.ParamValues['@ForecastNotZero'] := 1; Parameters.AddParameter.Name := '@EffectiveMonth'; Parameters.ParamValues['@EffectiveMonth'] := formatdatetime('yyyy/mm',now); Open; while not eof do begin foundx:=False; for i:=0 to High(fEntries) do begin if fEntries[i].Partnumber = fieldbyname('Assembly Part Number Code').AsString then begin foundx:=true; break; end; end; if not foundx then begin dbmissing.Add(fieldbyname('Assembly Part Number Code').AsString); Hist.Append('Part Number not found in Forecast, '+fieldbyname('Assembly Part Number Code').AsString); Data_Module.LogActLog('FORECAST','Part Number not found in Forecast, '+fieldbyname('Assembly Part Number Code').AsString); end; next; end; except on e:exception do begin ShowMessage('Error on INV_FORECAST_DETAIL_INF table access, '+e.Message); Data_Module.LogActLog('ERROR','FORECAST: Error on INV_FORECAST_DETAIL_INF table access, '+e.Message); result:=false; end; end; end; // // Forecast report // try excel := createOleObject('Excel.Application'); excel.visible := False; excel.DisplayAlerts := False; //excel.workbooks.add; excel.workbooks.open(Data_Module.TemplateDir+'ReportTemplate.xls'); mysheet := excel.workSheets[1]; mysheet.cells[1,1].value:='Forecast Part Numbers'; z:=4; if Data_Module.fiAssemblerName.AsString='WQS' then begin for y:=1 to 14 do begin mysheet.Cells[z-1,Y+1].value := 'Week '+IntToStr(fEntries[1].Weeks[y].WeekNumber); end; for x:=0 to high(fEntries) do begin mysheet.Cells[z,1].value := fEntries[x].Partnumber; for y:=1 to 14 do begin mysheet.Cells[z,Y+1].value := fEntries[x].Weeks[y].WeekCount; end; INC(z); end; end else begin for y:=1 to 13 do begin mysheet.Cells[z-1,Y+1].value := 'Week '+IntToStr(fEntries[1].Weeks[y].WeekNumber); end; for x:=0 to high(fEntries) do begin mysheet.Cells[z,1].value := fEntries[x].Partnumber; for y:=1 to 13 do begin mysheet.Cells[z,Y+1].value := fEntries[x].Weeks[y].WeekCount; end; INC(z); end; end; excel.ActiveWorkbook.SaveAs(Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'); excel.Workbooks.Close; excel.Quit; excel:=Unassigned; except on e:exception do begin Showmessage('Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); Data_Module.LogActLog('ERROR','Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); //raise; end; end; // // record in database and not in forecast // try if dbmissing.Count > 0 then begin if messagedlg('There are '+IntToStr(dbMissing.count)+', in the database and not in the forecast. Continue processing?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin result:=False; exit; end; hist.append('Create skipped database report, '+IntToStr(skip)+' records'); Data_Module.LogActLog('FORECAST','Create skipped database report, '+IntToStr(skip)+' records'); // create error xls form excel := createOleObject('Excel.Application'); excel.visible := False; excel.DisplayAlerts := False; excel.workbooks.open(Data_Module.TemplateDir+'ReportTemplate.xls'); mysheet := excel.workSheets[1]; mysheet.cells[1,1].value:='Forecast Part Numbers not in forecast'; z:=4; for x:=0 to dbmissing.Count-1 do begin mysheet.Cells[z,1].value := dbmissing[x]; INC(z); end; excel.ActiveWorkbook.SaveAs(Data_Module.fiReportsOutputDir.AsString+'\ForecastDBError'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'); excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end; dbmissing.Free; except on e:exception do begin Showmessage('Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); Data_Module.LogActLog('ERROR','Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); end; end; // // record in forecast and not in database // try if skip <> 0 then begin if messagedlg('There are '+IntToStr(skip)+', forecast records not in the database. Continue processing?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin result:=False; exit; end; hist.append('Create skipped records report, '+IntToStr(skip)+' records'); Data_Module.LogActLog('FORECAST','Create skipped records report, '+IntToStr(skip)+' records'); // create error xls form excel := createOleObject('Excel.Application'); excel.visible := False; excel.DisplayAlerts := False; //excel.workbooks.add; excel.workbooks.open(Data_Module.TemplateDir+'ReportTemplate.xls'); mysheet := excel.workSheets[1]; mysheet.cells[1,1].value:='Forecast Part Numbers not in database'; z:=4; for x:=0 to high(fEntries) do begin if fEntries[x].Skip then begin mysheet.Cells[z,1].value := fEntries[x].Partnumber; INC(z); end; end; excel.ActiveWorkbook.SaveAs(Data_Module.fiReportsOutputDir.AsString+'\ForecastRecError'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'); excel.Workbooks.Close; excel.Quit; excel:=Unassigned; end; except on e:exception do begin Showmessage('Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); Data_Module.LogActLog('ERROR','Cannot save excel report template('+Data_Module.fiReportsOutputDir.AsString+'\ForecastReport'+formatdatetime('yyyymmddhhmmss00',now)+'.xls'+'), '+e.Message); //raise; end; end; Hist.append(IntToStr(high(fEntries)-skip)+' forecast records to be added'); Data_Module.LogActLog('FORECAST',IntToStr(high(fEntries)-skip)+' forecast records to be added'); end; procedure TForecastBreakdown_Form.UpdateUsage; var lastsize:string; usage:integer; begin Hist.Append('Update usage DB'); Data_Module.LogActLog('FORECAST','Update usage DB'); application.ProcessMessages; try With Data_Module.INV_DataSet do Begin Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_SizeUsage;1'; Parameters.Clear; Open; lastsize:=fieldbyname('VC_SIZE_CODE').AsString; usage:=0; while not EOF do begin if (lastsize <> fieldbyname('VC_SIZE_CODE').AsString) then begin // Update last size with Data_Module.Inv_StoredProc do begin //Get ratio data if usage <> 0 then begin Close; ProcedureName := 'dbo.UPDATE_SizeUsage;1'; Parameters.Clear; Parameters.AddParameter.Name := '@SizeCode'; Parameters.ParamValues['@SizeCode'] := lastsize; Parameters.AddParameter.Name := '@Usage'; Parameters.ParamValues['@Usage'] := usage; ExecProc; end; end; // Set next lastsize:=fieldbyname('VC_SIZE_CODE').AsString; usage:=0; end; // Get week forecast usage:=usage+HistoryForecast(fieldbyname('VC_PART_NUMBER').AsString); next; if eof then begin // do last with Data_Module.Inv_StoredProc do begin //Get ratio data if usage <> 0 then begin Close; ProcedureName := 'dbo.UPDATE_SizeUsage;1'; Parameters.Clear; Parameters.AddParameter.Name := '@SizeCode'; Parameters.ParamValues['@SizeCode'] := lastsize; Parameters.AddParameter.Name := '@Usage'; Parameters.ParamValues['@Usage'] := usage; ExecProc; end; end; end; end; end; except on e:exception do begin Hist.append('Failed to update usage in INV_SIZE_MST,'+e.message); Data_Module.LogActLog('ERROR','FORECAST: Failed to update usage in INV_SIZE_MST,'+e.message); end; end; Hist.Append('Finished update usage DB'); Data_Module.LogActLog('FORECAST','Finished update usage DB'); end; function TForecastBreakdown_Form.HistoryForecast(partno:string):integer; var x,z,y,total:integer; begin // // Change to 7 days instead of 30 // x:=0; total:=0; try with data_module.INV_Forecast_DataSet do begin for z:=0 to Data_Module.fiUsageUpdateCompare.AsInteger do begin for y:=0 to 7 do begin Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_ForecastPartNumberWeek;1'; Parameters.Clear; Parameters.AddParameter.Name := '@WeekNo'; Parameters.ParamValues['@WeekNo'] := WeekOfTheYear(now+z); Parameters.AddParameter.Name := '@DayNo'; Parameters.ParamValues['@DayNo'] := DayOfTheWeek(now+y); Parameters.AddParameter.Name := '@PartNo'; Parameters.ParamValues['@PartNo'] := partno; Open; if (not FieldByName('Qty').IsNull) and (FieldByName('Qty').Value <> 0) then begin total:=total+FieldByName('Qty').Value; INC(x); end; end; end; end; if x<>0 then result:=total div x else result:=0; except on e:exception do begin Data_Module.LogActLog('ERROR','Unable to get usage forecast, '+e.Message); ShowMessage('Unable to get usage forecast, '+e.Message); raise; end; end; end; procedure TForecastBreakdown_Form.UpdateForecast; var i,j,count,tirecount,wheelcount,weekcount,wheelratio,tireratio,forecastratio:integer; wm,tm:string; bd:boolean; begin Hist.Append('Update forecast DB'); Data_Module.LogActLog('FORECAST','Update forecast DB'); if Data_Module.fiAssemblerName.AsString = 'WQS' then count:=14 else count:=13; for i:=0 to High(fEntries) do begin if (not fEntries[i].Skip) then begin //insert or update record try for j:=1 to count do With Data_Module.Inv_StoredProc do Begin begin Close; ProcedureName := 'dbo.INSERTUPDATE_ForecastInfo;1'; Parameters.Clear; Parameters.AddParameter.Name := '@Supplier'; Parameters.ParamValues['@Supplier'] := fEntries[i].Supplier; Parameters.AddParameter.Name := '@PartNumber'; Parameters.ParamValues['@PartNumber'] := fEntries[i].Partnumber; Parameters.AddParameter.Name := '@Kanban'; Parameters.ParamValues['@Kanban'] := fEntries[i].KanbanNumber; Parameters.AddParameter.Name := '@WeekNumber'; Parameters.ParamValues['@WeekNumber'] := fEntries[i].Weeks[j].WeekNumber; Parameters.AddParameter.Name := '@WeekDate'; Parameters.ParamValues['@WeekDate'] := '20'+fEntries[i].Weeks[j].WeekDate; Parameters.AddParameter.Name := '@Count'; Parameters.ParamValues['@Count'] := fEntries[i].Weeks[j].WeekCount; ExecProc; End; //With try with Data_Module.INV_DataSet do begin //Get ratio data Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_ForecastDetail;1'; Parameters.Clear; Parameters.AddParameter.Name := '@AssyCode'; Parameters.ParamValues['@AssyCode'] := fEntries[i].PartNumber; Parameters.AddParameter.Name := '@ForecastNotZero'; Parameters.ParamValues['@ForecastNotZero'] := 1; Open; // // Add adjustment for ratio here // // Date rule: // Record with a blank effective date is the default // Record the contains an effective month overrides if that is the month of the current data // if No blank record and no effective month for this time period, set value to zero for this time // tirecount:=0; // init everything wheelcount:=0; tireratio:=0; wheelratio:=0; forecastratio:=0; weekcount:=fEntries[i].Weeks[j].WeekCount; // for reading purposes bd:=FALSE; // flag for warning while not eof do begin if (FieldByName('Active Date').AsString = '') or (FieldByName('Active Date').AsString = ' ') then begin // calculate default wheelratio:=FieldByName('Wheel Ratio').AsInteger; tireratio:=FieldByName('Tire Ratio').AsInteger; forecastratio:=FieldByName('Forecast Ratio').AsInteger; bd:=TRUE; end else begin tm:=copy(FieldByName('Active Date').AsString,3,2)+copy(FieldByName('Active Date').AsString,6,2); wm:=copy(fEntries[i].Weeks[j].WeekDate,1,4); if tm = wm then begin // Month record match wheelratio:=FieldByName('Wheel Ratio').AsInteger; tireratio:=FieldByName('Tire Ratio').AsInteger; forecastratio:=FieldByName('Forecast Ratio').AsInteger; bd:=TRUE; break; end; end; next; end; if not bd then begin Data_Module.LogActLog('ERROR','No breakdown for part number('+fEntries[i].PartNumber+') on week('+fEntries[i].Weeks[j].WeekDate+') with count('+IntToStr(weekcount)+')'); //ShowMessage('No breakdown for part number('+fEntries[i].PartNumber+') on week('+fEntries[i].Weeks[j].WeekDate+') with count('+IntToStr(weekcount)+'), count will be ignored.'); Hist.Append('No breakdown for part number('+fEntries[i].PartNumber+') on week('+fEntries[i].Weeks[j].WeekDate+') with count('+IntToStr(weekcount)+'), count will be ignored.'); end; // If any ratio is zero the total is zero if (forecastratio <> 0) and (tireratio <> 0) and (wheelratio <> 0) then begin // Changes to reflect ratios over 100 percent // // Added to support non-production values shifted to // other suppliers // if (tireratio <> 100) and (wheelratio <> 100) then begin tirecount:=((((WeekCount div 2) * forecastratio) div 100) * tireratio) div 100; wheelcount:=((((WeekCount div 2) * forecastratio) div 100) * wheelratio) div 100; end else if tireratio <> 100 then begin tirecount:=(((WeekCount * forecastratio) div 100) * tireratio) div 100; wheelcount:=(((WeekCount div 2) * forecastratio) div 100); end else if wheelratio <> 100 then begin tirecount:=(((WeekCount div 2) * forecastratio) div 100); wheelcount:=(((WeekCount * forecastratio) div 100) * wheelratio) div 100; end else //everything 100 begin tirecount:=((WeekCount * forecastratio) div 100); wheelcount:=((WeekCount * forecastratio) div 100); end end; // scan through the part numbers for this assembly code and assign if length(FieldByName('Tire Part Number Code').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Tire Part Number Code').AsString, fEntries[i].Weeks[j].WeekDate, tirecount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Wheel Part Number Code').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Wheel Part Number Code').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Valve Part Number').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Valve Part Number').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Film Part Number').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Film Part Number').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Label Part Number').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Label Part Number').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Misc1 Part Number').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Misc1 Part Number').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; if length(FieldByName('Misc2 Part Number').AsString) = 12 then begin DoPartNumberForecast( FieldByName('Misc2 Part Number').AsString, fEntries[i].Weeks[j].WeekDate, wheelcount,//fEntries[i].Weeks[j].WeekCount, fEntries[i].Weeks[j].WeekNumber); end; end; except on e:exception do begin ShowMessage('Error on INV_FORECAST_DETAIL_INF table access, '+e.Message); Data_Module.LogActLog('ERROR','FORECAST: Error on INV_FORECAST_DETAIL_INF table access, '+e.Message); break; end end; Data_Module.LogActLog('FORECAST','Insert/Update forecast information for part number, '+fEntries[i].Partnumber); end; except on e:exception do Begin Data_Module.LogActLog('ERROR', 'FAILED Insert/Update forecast information for part number, '+fEntries[i].Partnumber + '. Err Msg: ' + E.Message + ' Err: ' + E.ClassName, 0); exit; End; //Except end; //process breakdown end; end; Hist.Append('Finished update forecast'); Data_Module.LogActLog('FORECAST','Finished update forecast'); end; procedure TForecastBreakdown_Form.DoPartNumberForecast(PN,WeekDate:string;FCCount,Weeknumber:integer); var workday: array[1..7] of boolean; dayforecast: array[1..7] of integer; line,supplier,size:string; days,ratiocount,leftover,i, checkweeknumber:integer; begin workday[1]:=true; workday[2]:=true; workday[3]:=true; workday[4]:=true; workday[5]:=true; workday[6]:=false; workday[7]:=false; days:=5; try // Get PartMaster Information with Data_Module.INV_Forecast_DataSet do begin // // Get assembly line // Close; CommandType := CmdStoredProc; CommandText := 'dbo.SELECT_PartsStockInfo;1'; Parameters.Clear; Parameters.AddParameter.Name := '@PartNum'; Parameters.ParamValues['@PartNum'] := PN; Open; if FieldByName('Line Name').AsString <> '' then line:=FieldByName('Line Name').AsString else line := 'ALL LINES'; supplier:=FieldByName('Supplier Code').AsString; size:=FieldByName('Size Code').AsString; Close; // // Modify the week number based on using the first production day // week number value // // checkweeknumber:=WeekNumber; with data_module.Inv_StoredProc do begin if data_module.fiUseFirstProductionDay.AsBoolean then begin Close; ProcedureName := 'dbo.SELECT_FirstProductionDay;1'; Parameters.Clear; Parameters.AddParameter.Name := '@ProdYear'; Parameters.ParamValues['@ProdYear'] := '20'+copy(weekdate,1,2);// formatdatetime('yyyy',EventDate_NUMMIBmDateEdit.date); Open; if FieldByName('First Week Number').AsInteger <> 1 then begin // Go in the opposite direction to get to julian date if first week is greater than production week WeekNumber := WeekNumber + FieldByName('First Week Number').AsInteger - 1; end; end; end; // // Find any changes to a normal weekly schedule // with Data_Module.ALC_DataSet do begin Close; CommandType := CmdStoredProc; CommandText := 'dbo.AD_GetSpecialDateWeek'; Parameters.Clear; Parameters.AddParameter.Name := '@Week'; Parameters.ParamValues['@Week'] := WeekNumber; Parameters.AddParameter.Name := '@Line'; Parameters.ParamValues['@Line'] := Line; Open; if recordCount > 0 then begin while not eof do begin if (trim(fieldByName('Date Status Abrv').AsString) = 'H') or (trim(fieldByName('Date Status Abrv').AsString) = 'X') then begin workday[FieldByName('Day Number').AsInteger]:=False; DEC(days); end else begin workday[FieldByName('Day Number').AsInteger]:=True; INC(days); end; next; end; end; Close; end; if days > 0 then begin ratiocount:=FCCount div days; leftover:= FCCount mod days; end else begin ratiocount := 0; leftover:=0; end; for i:=1 to 7 do begin if workday[i] then begin dayforecast[i]:=ratiocount+leftover; // add any extra to the first day and then reset leftover:=0; end else dayforecast[i]:=0; end; end; // // Insert/Update record for this partnumber on this week // With Data_Module.Inv_StoredProc do Begin Close; ProcedureName := 'dbo.INSERTUPDATE_BreakdownForecastInfo;1'; Parameters.Clear; Parameters.AddParameter.Name := '@WeekNumber'; Parameters.ParamValues['@WeekNumber'] := checkweeknumber;//WeekNumber; Parameters.AddParameter.Name := '@WeekDate'; Parameters.ParamValues['@WeekDate'] := '20'+WeekDate; Parameters.AddParameter.Name := '@Supplier'; Parameters.ParamValues['@Supplier'] := Supplier; Parameters.AddParameter.Name := '@PartNumber'; Parameters.ParamValues['@PartNumber'] := PN; Parameters.AddParameter.Name := '@SizeCode'; Parameters.ParamValues['@SizeCode'] := size; Parameters.AddParameter.Name := '@Qty1'; Parameters.ParamValues['@Qty1'] := dayforecast[1]; Parameters.AddParameter.Name := '@Qty2'; Parameters.ParamValues['@Qty2'] := dayforecast[2]; Parameters.AddParameter.Name := '@Qty3'; Parameters.ParamValues['@Qty3'] := dayforecast[3]; Parameters.AddParameter.Name := '@Qty4'; Parameters.ParamValues['@Qty4'] := dayforecast[4]; Parameters.AddParameter.Name := '@Qty5'; Parameters.ParamValues['@Qty5'] := dayforecast[5]; Parameters.AddParameter.Name := '@Qty6'; Parameters.ParamValues['@Qty6'] := dayforecast[6]; Parameters.AddParameter.Name := '@Qty7'; Parameters.ParamValues['@Qty7'] := dayforecast[7]; ExecProc; End; except on e:exception do begin Data_Module.LogActLog('ERROR','Failure on partnumber forecast update/insert PN('+PN+') '+e.Message); Hist.Append('Failed on Part Number Update PN('+PN+'), '+e.Message); Raise; end end; end; procedure TForecastBreakdown_Form.OKButtonClick(Sender: TObject); begin fclosed:=true; end; end.
unit udmLayouts; interface uses Windows, System.UITypes, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmLayouts = class(TdmPadrao) qryManutencaoIDLAYOUT: TIntegerField; qryManutencaoFILIAL: TStringField; qryManutencaoNOME: TStringField; qryManutencaoATIVO: TStringField; qryManutencaoTIPO: TIntegerField; qryManutencaoOPERADOR: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoIDLAYOUT: TIntegerField; qryLocalizacaoFILIAL: TStringField; qryLocalizacaoNOME: TStringField; qryLocalizacaoATIVO: TStringField; qryLocalizacaoTIPO: TIntegerField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; procedure qryManutencaoBeforePost(DataSet: TDataSet); protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FNome: string; FFilial: string; public property Nome: string read FNome write FNome; property Filial: string read FFilial write FFilial; end; const SQL_DEFAULT = 'SELECT ' + ' IDLAYOUT, ' + ' FILIAL, ' + ' NOME, ' + ' ATIVO, ' + ' TIPO, ' + ' OPERADOR, ' + ' DT_ALTERACAO ' + 'FROM LAYOUTS '; var dmLayouts: TdmLayouts; implementation uses udmPrincipal; {$R *.dfm} { TdmLayouts } procedure TdmLayouts.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE NOME = :NOME'); SQL.Add(' AND FILIAL = :FILIAL'); SQL.Add('ORDER BY NOME'); ParamByName('NOME').AsString := FNome; ParamByName('FILIAL').AsString := FFilial; end; end; procedure TdmLayouts.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY NOME'); end; end; procedure TdmLayouts.qryManutencaoBeforePost(DataSet: TDataSet); begin inherited; if (qryManutencaoIDLAYOUT.isNull) or (qryManutencaoIDLAYOUT.AsInteger = 0) then qryManutencaoIDLAYOUT.AsFloat := dmPrincipal.GeraGenerator('GEN_LAYOUTS'); end; end.
unit Containers; interface uses SysUtils, Classes, HashTables; const DEFAULTBUFSIZE = 1024; type // Forward declarations TItemReader = class; TItemWriter = class; // The item type TItem = class protected constructor Read(Reader: TItemReader); virtual; procedure Write(Writer: TItemWriter); virtual; public procedure Associate(AObject: TObject); virtual; procedure Dissociate(AObject: TObject); virtual; end; TItemClass = class of TItem; // Abstract base class for all types of containers TContainer = class(TItem) private FHost: TItem; FOwnsItems: Boolean; protected constructor Read(Reader: TItemReader); override; procedure Write(Writer: TItemWriter); override; function GetCount: Integer; virtual; abstract; public constructor Create(AHost: TItem; AOwnsItems: Boolean = false); virtual; destructor Destroy; override; procedure Assign(Source: TContainer); virtual; procedure Clear; virtual; abstract; function First: TItem; virtual; abstract; function Next: TItem; virtual; abstract; property Count: Integer read GetCount; property Host: TItem read FHost; property OwnsItems: Boolean read FOwnsItems write FOwnsItems; end; // Ordered, random access list of items TSequence = class(TContainer) private FList: TList; FIndex: Integer; protected constructor Read(Reader: TItemReader); override; procedure Write(Writer: TItemWriter); override; function GetCount: Integer; override; function GetItems(Index: Integer): TItem; public constructor Create(AHost: TItem; AOwnsItems: Boolean = false); override; destructor Destroy; override; procedure Assign(Source: TContainer); override; function Add(Item: TItem): Integer; procedure Clear; override; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); function First: TItem; override; function Next: TItem; override; function IndexOf(Item: TItem): Integer; procedure Insert(Index: Integer; Item: TItem); procedure Move(CurIndex, NewIndex: Integer); function Remove(Item: TItem): Integer; property Items[Index: Integer]: TItem read GetItems; default; end; // Generic set container TSet = class(TContainer) private FTable: THashTable; protected constructor Read(Reader: TItemReader); override; procedure Write(Writer: TItemWriter); override; function GetCount: Integer; override; public constructor Create(AHost: TItem; AOwnsItems: Boolean = false); override; destructor Destroy; override; procedure Assign(Source: TContainer); override; procedure Clear; override; function First: TItem; override; function Next: TItem; override; function Belongs(Item: TItem): Boolean; procedure Insert(Item: TItem); procedure Intersection(Other: TSet); function Remove(Item: TItem): Boolean; procedure Subtract(Other: TSet); procedure Union(Other: TSet); end; // Dictionary with string key as a key type TDictionary = class(TContainer) private FTable: TStringTable; protected constructor Read(Reader: TItemReader); override; procedure Write(Writer: TItemWriter); override; function GetCount: Integer; override; function GetItems(const Key: string): TItem; public constructor Create(AHost: TItem; AOwnsItems: Boolean = false); override; destructor Destroy; override; procedure Assign(Source: TDictionary); reintroduce; procedure Clear; override; function First: TItem; override; function Next: TItem; override; procedure Insert(const Key: string; Item: TItem); function Remove(const Key: string): TItem; property Items[const Key: string]: TItem read GetItems; default; end; // Call back procedure that is called by the TItemReader when // a reference is resolved TResolveCallBack = procedure(Item: TItem) of object; // Node corresponding to a call back reference TCallBackNode = record CallBack: TResolveCallBack; Reference: Integer; end; PCallBackNode = ^TCallBackNode; // TItemReader class extends Delphi's TReader class to handle object // serialization TItemReader = class(TReader) private FClasses: THashTable; FItems: THashTable; FReferences: TList; FCallBackRefs: TList; public constructor Create(Stream: TStream); destructor Destroy; override; procedure ReadClassTable; function ReadItem: TItem; procedure ReadReference(var AReference: TItem); procedure ReadRefCallBack(CallBack: TResolveCallBack); procedure ResolveReferences; end; TItemWriter = class(TWriter) public constructor Create(Stream: TStream); procedure WriteClassTable; procedure WriteItem(AItem: TItem); procedure WriteReference(AReference: TItem); end; EContainerError = class(Exception); procedure RegisterItemClass(AClass: TItemClass); procedure RegisterItemClasses(AClasses: array of TItemClass); function FindItemClass(const AClassName: string): TItemClass; function LoadItemFromStream(Stream: TStream): TItem; procedure SaveItemToStream(Item: TItem; Stream: TStream); function LoadItemFromFile(const FileName: string): TItem; procedure SaveItemToFile(Item: TItem; const FileName: string); implementation var ItemClassList: TList; // General object management procedure ContainerError(const Msg: string); begin raise EContainerError.Create(Msg); end; procedure RegisterItemClass(AClass: TItemClass); begin if ItemClassList.IndexOf(AClass) >= 0 then ContainerError(Format('Class %s is already registered', [AClass.ClassName])); ItemClassList.Add(AClass); end; procedure RegisterItemClasses(AClasses: array of TItemClass); var i: Integer; begin for i := Low(AClasses) to High(AClasses) do RegisterItemClass(AClasses[i]); end; function FindItemClass(const AClassName: string): TItemClass; var i: Integer; begin Result := nil; i := ItemClassList.Count - 1; while (i >= 0) and (TItemClass(ItemClassList[i]).ClassName <> AClassName) do Dec(i); if i >= 0 then Result := TItemClass(ItemClassList[i]) else ContainerError(Format('Class %s is not registered', [AClassName])); end; // Serialization routines function LoadItemFromStream(Stream: TStream): TItem; var Reader: TItemReader; begin Reader := TItemReader.Create(Stream); try Reader.ReadClassTable; Result := Reader.ReadItem; Reader.ResolveReferences; finally Reader.Free; end; end; procedure SaveItemToStream(Item: TItem; Stream: TStream); var Writer: TItemWriter; begin Writer := TItemWriter.Create(Stream); try Writer.WriteClassTable; Writer.WriteItem(Item); finally Writer.Free; end; end; function LoadItemFromFile(const FileName: string): TItem; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := LoadItemFromStream(Stream); finally Stream.Free; end; end; procedure SaveItemToFile(Item: TItem; const FileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveItemToStream(Item, Stream); finally Stream.Free; end; end; { TItem } procedure TItem.Associate(AObject: TObject); begin // Empty declaration end; procedure TItem.Dissociate(AObject: TObject); begin // Empty declaration end; constructor TItem.Read(Reader: TItemReader); begin // Empty declaration end; procedure TItem.Write(Writer: TItemWriter); begin // Empty declaration end; { TContainer } procedure TContainer.Assign(Source: TContainer); begin //Empty declaration end; constructor TContainer.Create(AHost: TItem; AOwnsItems: Boolean); begin FOwnsItems := AOwnsItems; FHost := AHost; end; destructor TContainer.Destroy; var it: TItem; begin it := First; while it <> nil do begin it.Dissociate(self); it := Next; end; Clear; end; constructor TContainer.Read(Reader: TItemReader); begin with Reader do begin ReadReference(FHost); FOwnsItems := ReadBoolean; end; end; procedure TContainer.Write(Writer: TItemWriter); begin with Writer do begin WriteReference(FHost); WriteBoolean(FOwnsItems); end; end; { TSequence } function TSequence.Add(Item: TItem): Integer; begin Result := FList.Add(Item); Item.Associate(self); end; procedure TSequence.Assign(Source: TContainer); var it: TItem; begin Clear; it := Source.First; while it <> nil do begin FList.Add(it); it := Source.Next; end; end; procedure TSequence.Clear; var i: Integer; begin if OwnsItems then for i := 0 to FList.Count - 1 do TItem(FList[i]).Free; FList.Clear; end; constructor TSequence.Create(AHost: TItem; AOwnsItems: Boolean); begin inherited Create(AHost, AOwnsItems); FList := TList.Create; end; procedure TSequence.Delete(Index: Integer); begin if OwnsItems then TItem(FList[Index]).Free else TItem(FList[Index]).Dissociate(self); FList.Delete(Index); end; destructor TSequence.Destroy; begin inherited Destroy; FList.Free; end; procedure TSequence.Exchange(Index1, Index2: Integer); begin FList.Exchange(Index1, Index2); end; function TSequence.First: TItem; begin FIndex := 0; if FList.Count > 0 then Result := TItem(FList.First) else Result := nil; end; function TSequence.GetCount: Integer; begin Result := FList.Count; end; function TSequence.GetItems(Index: Integer): TItem; begin Result := TItem(FList[Index]); end; function TSequence.IndexOf(Item: TItem): Integer; begin Result := FList.IndexOf(Item); end; procedure TSequence.Insert(Index: Integer; Item: TItem); begin FList.Insert(Index, Item); Item.Associate(self); end; procedure TSequence.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); end; function TSequence.Next: TItem; begin if FIndex < (FList.Count - 1) then begin Inc(FIndex); Result := FList[FIndex]; end else Result := nil; end; constructor TSequence.Read(Reader: TItemReader); begin inherited Read(Reader); FList := TList.Create; with Reader do begin FList.Capacity := ReadInteger; ReadListBegin; while not EndOfList do if OwnsItems then Add(ReadItem) else begin FList.Add(nil); ReadReference(TItem(FList.List[FList.Count - 1])); end; ReadListEnd; end; end; function TSequence.Remove(Item: TItem): Integer; begin Result := FList.Remove(Item); if OwnsItems then Item.Free else Item.Dissociate(self); end; procedure TSequence.Write(Writer: TItemWriter); var i: Integer; begin inherited Write(Writer); with Writer do begin WriteInteger(Count); WriteListBegin; for i := 0 to FList.Count - 1 do if OwnsItems then WriteItem(Items[i]) else WriteReference(Items[i]); WriteListEnd; end; end; { TDictionary } procedure TDictionary.Assign(Source: TDictionary); var pt: Pointer; begin Clear; pt := (Source as TDictionary).FTable.First; while pt <> nil do begin FTable.Insert((Source as TDictionary).FTable.CurrentKey, pt); pt := (Source as TDictionary).FTable.Next; end; end; procedure TDictionary.Clear; var it: TItem; begin if OwnsItems then begin it := FTable.First as TItem; while it <> nil do begin it.Free; it := FTable.Next as TItem; end; end; FTable.Clear; end; constructor TDictionary.Create(AHost: TItem; AOwnsItems: Boolean); begin inherited Create(AHost, AOwnsItems); FTable := TStringTable.Create; end; destructor TDictionary.Destroy; begin inherited Destroy; FTable.Free; end; function TDictionary.First: TItem; begin Result := FTable.First as TItem; end; function TDictionary.GetCount: Integer; begin Result := FTable.Count; end; function TDictionary.GetItems(const Key: string): TItem; begin Result := FTable[Key] as TItem; end; procedure TDictionary.Insert(const Key: string; Item: TItem); begin FTable.Insert(Key, Item); Item.Associate(self); end; function TDictionary.Next: TItem; begin Result := FTable.Next as TItem; end; constructor TDictionary.Read(Reader: TItemReader); var key: string; begin inherited Read(Reader); FTable := TStringTable.Create; with Reader do begin FTable.Capacity := ReadInteger; ReadListBegin; while not EndOfList do begin key := ReadString; if OwnsItems then Insert(key, ReadItem) else ReadReference(TItem(FTable.Insert(key, nil)^)); end; ReadListEnd; end; end; function TDictionary.Remove(const Key: string): TItem; begin Result := FTable.Remove(Key) as TItem; if Result <> nil then begin if OwnsItems then Result.Free else Result.Dissociate(self); end; end; procedure TDictionary.Write(Writer: TItemWriter); var it: TItem; begin inherited Write(Writer); with Writer do begin WriteInteger(Count); WriteListBegin; it := First; while it <> nil do begin WriteString(FTable.CurrentKey); if OwnsItems then WriteItem(it) else WriteReference(it); it := Next; end; WriteListEnd; end; end; { TSet } procedure TSet.Assign(Source: TContainer); var it: TItem; begin Clear; it := Source.First; while it <> nil do begin FTable.Insert(Integer(it), it); it := Source.Next; end; end; function TSet.Belongs(Item: TItem): Boolean; begin Result := (FTable[Integer(Item)] <> nil); end; procedure TSet.Clear; var it: TItem; begin if OwnsItems then begin it := TItem(FTable.First); while it <> nil do begin it.Free; it := TItem(FTable.Next); end; end; FTable.Clear; end; constructor TSet.Create(AHost: TItem; AOwnsItems: Boolean); begin inherited Create(AHost, AOwnsItems); FTable := THashTable.Create; end; destructor TSet.Destroy; begin inherited Destroy; FTable.Free; end; function TSet.First: TItem; begin Result := TItem(FTable.First); end; function TSet.GetCount: Integer; begin Result := FTable.Count; end; procedure TSet.Insert(Item: TItem); begin FTable[Integer(Item)] := Item; Item.Associate(self); end; procedure TSet.Intersection(Other: TSet); var pt: Pointer; begin pt := FTable.First; while pt <> nil do begin if Other.FTable[Integer(pt)] = nil then FTable.DeleteCurrent; pt := FTable.Next; end; end; function TSet.Next: TItem; begin Result := TItem(FTable.Next); end; constructor TSet.Read(Reader: TItemReader); begin inherited Read(Reader); FTable := THashTable.Create; with Reader do begin FTable.Capacity := ReadInteger; ReadListBegin; while not EndOfList do begin if OwnsItems then Insert(ReadItem) else ReadRefCallBack(Insert); end; ReadListEnd; end; end; function TSet.Remove(Item: TItem): Boolean; begin Result := (FTable.Remove(Integer(Item)) <> nil); if Result then begin if OwnsItems then Item.Free else Item.Dissociate(self); end; end; procedure TSet.Subtract(Other: TSet); var pt: Pointer; begin pt := FTable.First; while pt <> nil do begin if Other.FTable[Integer(pt)] <> nil then FTable.DeleteCurrent; pt := FTable.Next; end; end; procedure TSet.Union(Other: TSet); var pt: Pointer; begin pt := Other.FTable.First; while pt <> nil do begin if FTable[Integer(pt)] = nil then FTable.Insert(Integer(pt), pt); pt := Other.FTable.Next; end; end; procedure TSet.Write(Writer: TItemWriter); var it: TItem; begin inherited Write(Writer); with Writer do begin WriteInteger(Count); WriteListBegin; it := First; while it <> nil do begin if OwnsItems then WriteItem(it) else WriteReference(it); it := Next; end; WriteListEnd; end; end; { TItemReader } constructor TItemReader.Create(Stream: TStream); begin inherited Create(Stream, DEFAULTBUFSIZE); FClasses := THashTable.Create; FItems := THashTable.Create; FReferences := TList.Create; FCallBackRefs := TList.Create; end; destructor TItemReader.Destroy; var i: Integer; begin FClasses.Free; FItems.Free; FReferences.Free; for i := 0 to FCallBackRefs.Count - 1 do if FCallBackRefs[i] <> nil then Dispose(PCallBackNode(FCallBackRefs[i])); FCallBackRefs.Free; inherited Destroy; end; procedure TItemReader.ReadClassTable; var key: Integer; begin ReadListBegin; while not EndOfList do begin key := ReadInteger; FClasses.Insert(key, FindItemClass(ReadString)); end; ReadListEnd; end; function TItemReader.ReadItem: TItem; var ic: TItemClass; key: Integer; begin ic := TItemClass(FClasses[ReadInteger]); key := ReadInteger; Result := ic.Read(self); FItems.Insert(key, Result); end; procedure TItemReader.ReadRefCallBack(CallBack: TResolveCallBack); var cbn: PCallBackNode; begin New(cbn); cbn^.CallBack := CallBack; cbn^.Reference := ReadInteger; FCallBackRefs.Add(cbn); end; procedure TItemReader.ReadReference(var AReference: TItem); var pt: Pointer; begin pt := Pointer(ReadInteger); if pt = nil then AReference := nil else begin FReferences.Add(@AReference); FReferences.Add(pt); end; end; procedure TItemReader.ResolveReferences; var i: Integer; it: TItem; cbn: PCallBackNode; begin i := 0; while i < FReferences.Count do begin it := TItem(FItems[Integer(FReferences[i + 1])]); if it = nil then ContainerError('Could not resolve references'); TItem(FReferences[i]^) := it; Inc(i, 2); end; FReferences.Clear; for i := 0 to FCallBackRefs.Count - 1 do begin cbn := FCallBackRefs[i]; if cbn^.Reference = 0 then cbn^.CallBack(nil) else begin it := TItem(FItems[cbn^.Reference]); if it = nil then ContainerError('Could not resolve references'); cbn^.CallBack(it); end; Dispose(cbn); FCallBackRefs[i] := nil; end; FCallBackRefs.Clear; FItems.Clear; FClasses.Clear; end; { TItemWriter } constructor TItemWriter.Create(Stream: TStream); begin inherited Create(Stream, DEFAULTBUFSIZE); end; procedure TItemWriter.WriteClassTable; var i: Integer; begin WriteListBegin; for i := 0 to ItemClassList.Count - 1 do begin WriteInteger(Integer(ItemClassList[i])); WriteString(TItemClass(ItemClassList[i]).ClassName); end; WriteListEnd; end; procedure TItemWriter.WriteItem(AItem: TItem); begin if ItemClassList.IndexOf(AItem.ClassType) < 0 then ContainerError(Format('Class %s is not registered', [AItem.ClassName])); WriteInteger(Integer(AItem.ClassType)); WriteInteger(Integer(AItem)); AItem.Write(self); end; procedure TItemWriter.WriteReference(AReference: TItem); begin WriteInteger(Integer(AReference)); end; initialization ItemClassList := TList.Create; RegisterItemClasses([TSequence, TSet, TDictionary]); finalization ItemClassList.Free; end.
unit mcCompileIntercept; interface uses Classes, InterceptIntf; type TTestInterceptor = class(TInterfacedObject, ICompileInterceptor) public {ICompileInterceptor} { GetOptions() returns the interceptor's options. } function GetOptions: TCompileInterceptOptions; stdcall; { GetVirtualFile() is called when the compiler wants to open a file. If the returned value is not NIL the compiler will operate on the virtual stream. In this case AlterFile is not called. CIO_VIRTUALFILE must be set. } function GetVirtualFile(Filename: PWideChar): IVirtualStream; stdcall; { AlterFile() is called when the file is no virtual file and CIO_ALTERFILE is set. FileDate is obsolete and always 0. } function AlterFile(Filename: PWideChar; Content: PByte; FileDate, FileSize: Integer): IVirtualStream; stdcall; { InspectFilename() is called when a file is opened or created and CIO_INSPECTFILENAMES is set. } procedure InspectFilename(Filename: PWideChar; FileMode: TInspectFileMode); stdcall; { AlterMessage() is called when the compiler wants to display a message. The method must return True if it has changed one of the parameters. } function AlterMessage(IsCompilerMessage: Boolean; var MsgKind: TMsgKind; var Code: Integer; const Filename: IWideString; var Line, Column: Integer; const Msg: IWideString): Boolean; stdcall; { CompileProject is called before the specified project is compiled. } procedure CompileProject(ProjectFilename, UnitPaths, SourcePaths, DcuOutputDir: PWideChar; IsCodeInsight: Boolean; var Cancel: Boolean); stdcall; end; TTestStream = class(TInterfacedObject, IVirtualStream) protected FFileName: string; FFileDate: Integer; FStream: TMemoryStream; FStrData: TStrings; //my custom code! procedure ChangeCustomPascal; public constructor Create(const aFileName: string); destructor Destroy; override; procedure AfterConstruction;override; {IVirtualStream} function Seek(Offset: Integer; Origin: Integer): Integer; stdcall; function Read(var Buffer; Size: Integer): Integer; stdcall; procedure FileStatus(out FileDate: Integer; out FileSize: Integer); stdcall; end; implementation uses DbugIntf, SysUtils, Dialogs, TypInfo, Windows, StrUtils; var CompileInterceptorServices: TGetCompileInterceptorServices; { TTestInterceptor } function TTestInterceptor.AlterFile(Filename: PWideChar; Content: PByte; FileDate, FileSize: Integer): IVirtualStream; begin Result := nil; try DbugIntf.SendDebugEx(Format('INTERCEPT: AlterFile( Filename="%s", Content=%p, FileDate=%d, FileSize=%d )', [string(Filename), Content, FileDate, FileSize]), mtInformation ); except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: AlterFile error: %s: %s', [e.ClassName, e.Message]), mtError ); end; end; function TTestInterceptor.AlterMessage(IsCompilerMessage: Boolean; var MsgKind: TMsgKind; var Code: Integer; const Filename: IWideString; var Line, Column: Integer; const Msg: IWideString): Boolean; begin Result := False; try DbugIntf.SendDebugEx(Format('INTERCEPT: AlterMessage( IsCompilerMessage=%s, MsgKind=%s, Code=%d, Filename=%s, Line=%d, Column=%d, Msg="%s" )', [BoolToStr(IsCompilerMessage, True), TypInfo.GetEnumName(TypeInfo(TMsgKind), Ord(MsgKind)), Code, string(Filename.Value), Line, Column, string(Msg.Value)]), mtInformation ); except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: AlterMessage error: %s: %s', [e.ClassName, e.Message]), mtError ); end; end; procedure TTestInterceptor.CompileProject(ProjectFilename, UnitPaths, SourcePaths, DcuOutputDir: PWideChar; IsCodeInsight: Boolean; var Cancel: Boolean); begin Cancel := False; try DbugIntf.SendDebugEx(Format('INTERCEPT: CompileProject( ProjectFilename="%s", UnitPaths="%s", SourcePaths="%s", DcuOutputDir="%s", IsCodeInsight=%s )', [string(ProjectFilename), string(UnitPaths), string(SourcePaths), string(DcuOutputDir), BoolToStr(IsCodeInsight, True)]), mtInformation ); except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: CompileProject error: %s: %s', [e.ClassName, e.Message]), mtError ); end; end; function TTestInterceptor.GetOptions: TCompileInterceptOptions; begin Result := CIO_ALTERFILES or // The interceptor supports the AlterFile() method CIO_VIRTUALFILES or // The interceptor supports the VirtrualFile() method CIO_INSPECTFILENAMES or // The interceptor supports the InspectFilename() method CIO_ALTERMESSAGES or // The interceptor supports the AlterMessage() method CIO_COMPILEPROJECTS; // The interceptor supports the CompileProject() method DbugIntf.SendDebugEx(Format('INTERCEPT: GetOptions', []), mtInformation ); end; function TTestInterceptor.GetVirtualFile(Filename: PWideChar): IVirtualStream; begin Result := nil; try DbugIntf.SendDebugEx(Format('INTERCEPT: GetVirtualFile(Filename="%s")', [string(Filename)]), mtInformation ); if StartsText('my', ExtractFileName(Filename)) then // if ExtractFileName(Filename) = 'Unit7.pas' then // if Filename = 'Unit7.pas' then begin Result := TTestStream.Create(Filename); DbugIntf.SendDebugEx('INTERCEPT: GetVirtualFile: custom file created', mtInformation ); end; except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: GetVirtualFile error: %s: %s', [e.ClassName, e.Message]), mtError ); end; end; procedure TTestInterceptor.InspectFilename(Filename: PWideChar; FileMode: TInspectFileMode); begin try DbugIntf.SendDebugEx(Format('INTERCEPT: InspectFilename(Filename="%s", FileMode=%s)', [string(Filename), TypInfo.GetEnumName(TypeInfo(TInspectFileMode), Ord(FileMode))]), mtInformation ); except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: InspectFilename error: %s: %s', [e.ClassName, e.Message]), mtError ); end; end; { TTestStream } procedure TTestStream.AfterConstruction; begin inherited; end; procedure TTestStream.ChangeCustomPascal; var sData, sCustom: string; iPos: Integer; begin sData := FStrData.Text; iPos := Pos('%message%', sData); if iPos <= 0 then Exit; sCustom := 'MessageDlg(''test from file: %s'', mtInformation, [mbOK], 0);'; sCustom := Format(sCustom, [Self.FFileName]); sData := StringReplace(sData, '%message%', sCustom,[]); DbugIntf.SendDebugEx('INTERCEPT: ChangeCustomPascal: custom message added', mtInformation ); FStrData.Text := sData; FStream.Clear; FStrData.SaveToStream(FStream); end; constructor TTestStream.Create(const aFileName: string); begin inherited Create; FFileName := aFileName; FFileDate := DateTimeToFileDate(Now); FStream := TMemoryStream.Create; FStream.LoadFromFile(FFileName); FStrData := TStringList.Create; FStrData.LoadFromStream(FStream); ChangeCustomPascal; FStream.Position := 0; end; destructor TTestStream.Destroy; begin FStream.Free; inherited; end; procedure TTestStream.FileStatus(out FileDate, FileSize: Integer); begin FileDate := FFileDate; FileSize := FStream.Size; end; function TTestStream.Read(var Buffer; Size: Integer): Integer; begin Result := FStream.Read(Buffer, Size); end; function TTestStream.Seek(Offset, Origin: Integer): Integer; begin Result := FStream.Seek(Offset, Origin); end; var hfile: THandle; iRegIdx: Integer = -1; initialization try hfile := LoadLibrary('CompileInterceptorW.dll');//'c:\Users\Public\AppData\Roaming\DDevExtensions\CompileInterceptorW.dll'); if hfile <> 0 then CompileInterceptorServices := GetProcAddress(hfile, 'GetCompileInterceptorServices') else CompileInterceptorServices := nil; if Assigned(CompileInterceptorServices) then iRegIdx := CompileInterceptorServices.RegisterInterceptor( TTestInterceptor.Create ); except on e:Exception do DbugIntf.SendDebugEx(Format('INTERCEPT: initialization error: %s: %s', [e.ClassName, e.Message]), mtError ); end; finalization if Assigned(CompileInterceptorServices) then CompileInterceptorServices.UnregisterInterceptor( iRegIdx ); CompileInterceptorServices := nil; FreeLibrary(hfile); end.
{$OPTIMIZATION ON} {$RANGECHECKS OFF} unit DblGraphics; interface uses Windows,Classes,Graphics,Misc; const BMP256InfoStatSize=SizeOf(TDblPoint); type TCanvasWrapper=class(TObject) protected FCanvas:TCanvas; FDstShift:TPoint; FSrcShift:TDblPoint; FSrcScale:TDblPoint; private function GetBrush: TBrush; function GetFont: TFont; function GetPen: TPen; procedure SetPenWidth(const Value: float); procedure SetFontHeight(const Value: float); function GetOptScale: float; public procedure SetConversion(const Src:TDblRect; const Dst:TRect);virtual; procedure Convert(const Src:TDblPoint; var Dst:TPoint);overload; procedure Convert(const Src:TPoint; var Dst:TDblPoint);overload; procedure ConvertToFix(const Src:TDblPoint; var Dst:TPoint);overload; constructor Create(Canvas:TCanvas); procedure FillRect(const R: TDblRect); procedure FrameRect(const R: TDblRect); procedure LineTo(const P:TDblPoint); procedure MoveTo(const P:TDblPoint); procedure Rectangle(const R: TDblRect); procedure StretchDraw(const R: TDblRect; Graphic: TGraphic); function TextExtent(const Text: string): TDblPoint; procedure TextOut(const P:TDblPoint; const Text: string); public property DstShift:TPoint read FDstShift; property SrcShift:TDblPoint read FSrcShift; property SrcScale:TDblPoint read FSrcScale; property Brush:TBrush read GetBrush; property Pen:TPen read GetPen; property PenWidth:float write SetPenWidth; property Font:TFont read GetFont; property FontHeight:float write SetFontHeight; property OptScale:float read GetOptScale; end; TByteArray = packed array[0..MaxInt-1] of Byte; PByteArray = ^TByteArray; PBMP256Info = ^TBMP256Info; TBMP256Info = packed record Limit:TPoint; L:array[0..(MaxInt-BMP256InfoStatSize) div SizeOf(Pointer)-1] of PByteArray; end; TBMP256CanvasWrapper=class(TCanvasWrapper) private PenPos:TPoint; BI:PBMP256Info; function GetPenIntPos: TPoint; public property PenIntPos:TPoint read GetPenIntPos; constructor Create(BM:TBitmap); procedure AAMoveTo(const P:TDblPoint); procedure AALineTo(const P:TDblPoint); destructor Destroy;override; end; TPalEntry=packed record R,G,B,Flags:Byte; end; TPalette=packed record Ver,Num:word; Entry:array[0..255] of TPalEntry; end; PPalette=^TPalette; function CreateBMP256Info(BM:TBitmap):PBMP256Info; procedure FreeBMP256Info(BI:PBMP256Info); type TColorMixTbl=packed array[0..3,0..255] of Byte; var MixTbl:array[0..255] of TColorMixTbl; implementation type fix=Integer; TAntiAliasCoeffTbl=packed array[-1..1] of Byte; TLineTripTbl=array[0..3] of TAntiAliasCoeffTbl; var TripTbl:array[-3..3] of TLineTripTbl; function float_fix(const x:Single):fix; const max:single=+32767; min:single=-32767; begin if x<min then Result:=-MaxInt else if max<x then Result:=+MaxInt else Result:=Trunc(x*65536); end; function fix_float(x:fix):Float; const Coeff=1/65536; begin Result:=x*Coeff; end; function int_fix(x:Integer):Integer; begin Result:=x shl 16; end; function fix_cint(x:fix):Integer;register; asm add eax,65535 sar eax,16 end; function fix_int(x:fix):Integer;register; asm sar eax,16 end; function fix_fint(x:fix):Integer;register; asm dec eax sar eax,16 end; procedure AntiAliazedLine(const BI:TBMP256Info; p1,p2:TPoint; Color:Byte); var i,ei,iv,ivLimit:Integer; v,dv:fix; fdv:Single; fv:Byte; TmpP:TPoint; LTT:^TLineTripTbl; AAC:^TAntiAliasCoeffTbl; ColorMix:^TColorMixTbl; begin ColorMix:=@(MixTbl[Color]); if Abs(p1.x-p2.x)>Abs(p1.y-p2.y) then begin if p1.x>p2.x then begin TmpP:=p1; p1:=p2; p2:=TmpP; end; i:=fix_cint(p1.x); if BI.Limit.x<i then exit else if i<0 then i:=0; ei:=fix_fint(p2.x); if ei<0 then exit else if BI.Limit.x<ei then ei:=BI.Limit.x; if p1.x<p2.x then fdv:=(p1.y-p2.y)/(p1.x-p2.x) else fdv:=0; dv:=float_fix(fdv); LTT:=@(TripTbl[Round(fdv*3)]); v:=p1.y+trunc(dv*fix_float(int_fix(i)-p1.x)); ivLimit:=BI.Limit.y; while i<=ei do begin iv:=fix_int(v); fv:=v shr 14 and 3; AAC:=@(LTT[fv]); if (0<=iv) and (iv<=ivLimit) then begin if 0<iv then BI.L[iv-1][i]:=ColorMix[ AAC[-1], BI.L[iv-1][i] ]; BI.L[iv][i]:=ColorMix[ AAC[0], BI.L[iv][i] ]; if iv<ivLimit then BI.L[iv+1][i]:=ColorMix[ AAC[+1], BI.L[iv+1][i] ]; end; inc(v,dv); inc(i); end; end else begin if p1.y>p2.y then begin TmpP:=p1; p1:=p2; p2:=TmpP; end; i:=fix_cint(p1.y); if BI.Limit.y<i then exit else if i<0 then i:=0; ei:=fix_fint(p2.y); if ei<0 then exit else if BI.Limit.y<ei then ei:=BI.Limit.y; if p1.y<p2.y then fdv:=(p1.x-p2.x)/(p1.y-p2.y) else fdv:=0; dv:=float_fix(fdv); LTT:=@(TripTbl[Round(fdv*3)]); v:=p1.x+trunc(dv*fix_float(int_fix(i)-p1.y)); ivLimit:=BI.Limit.x; while i<=ei do begin iv:=fix_int(v); fv:=v shr 14 and 3; AAC:=@(LTT[fv]); if (0<=iv) and (iv<=ivLimit) then begin if 0<iv then BI.L[i][iv-1]:=ColorMix[ AAC[-1], BI.L[i][iv-1] ]; BI.L[i][iv]:=ColorMix[ AAC[0], BI.L[i][iv] ]; if iv<ivLimit then BI.L[i][iv+1]:=ColorMix[ AAC[+1], BI.L[i][iv+1] ]; end; inc(v,dv); inc(i); end; end; end; function CreateBMP256Info(BM:TBitmap):PBMP256Info; var i:Integer; begin GetMem(Result,BMP256InfoStatSize+BM.Height*SizeOf(Pointer)); Result.Limit.x:=BM.Width-1; Result.Limit.y:=BM.Height-1; for i:=0 to BM.Height-1 do Result.L[i]:=BM.ScanLine[i]; end; procedure FreeBMP256Info(BI:PBMP256Info); begin FreeMem(BI,BMP256InfoStatSize+(BI.Limit.Y+1)*SizeOf(Pointer)); end; { TCanvasWrapper } procedure TCanvasWrapper.Convert(const Src: TDblPoint; var Dst: TPoint); begin Dst.x:=Trunc((Src.x+SrcShift.x)*SrcScale.x)+DstShift.x; Dst.y:=Trunc((Src.y+SrcShift.y)*SrcScale.y)+DstShift.y; end; procedure TCanvasWrapper.Convert(const Src: TPoint; var Dst: TDblPoint); begin Dst.x:=(Src.x-DstShift.x)/SrcScale.x-SrcShift.x; Dst.y:=(Src.y-DstShift.y)/SrcScale.y-SrcShift.y; end; procedure TCanvasWrapper.ConvertToFix(const Src: TDblPoint; var Dst: TPoint); begin Dst.x:=float_fix((Src.x+SrcShift.x)*SrcScale.x)+int_fix(DstShift.x); Dst.y:=float_fix((Src.y+SrcShift.y)*SrcScale.y)+int_fix(DstShift.y); end; constructor TCanvasWrapper.Create(Canvas: TCanvas); begin inherited Create; FCanvas:=Canvas; FSrcScale.x:=1.0; FSrcScale.y:=1.0; end; procedure TCanvasWrapper.FillRect(const R: TDblRect); var DR:TRect; begin Convert(R.P1,DR.TopLeft); Convert(R.P2,DR.BottomRight); FCanvas.FillRect(DR); end; procedure TCanvasWrapper.FrameRect(const R: TDblRect); var DR:TRect; begin Convert(R.P1,DR.TopLeft); Convert(R.P2,DR.BottomRight); FCanvas.FrameRect(DR); end; function TCanvasWrapper.GetBrush: TBrush; begin Result:=FCanvas.Brush; end; function TCanvasWrapper.GetFont: TFont; begin Result:=FCanvas.Font; end; function TCanvasWrapper.GetOptScale: float; begin if SrcScale.x<SrcScale.y then Result:=SrcScale.x else Result:=SrcScale.y; // Result:=(SrcScale.x+SrcScale.y)*0.5; end; function TCanvasWrapper.GetPen: TPen; begin Result:=FCanvas.Pen; end; procedure TCanvasWrapper.LineTo(const P: TDblPoint); var DP:TPoint; begin Convert(P,DP); FCanvas.LineTo(DP.x,DP.y); end; procedure TCanvasWrapper.MoveTo(const P: TDblPoint); var DP:TPoint; begin Convert(P,DP); FCanvas.MoveTo(DP.x,DP.y); end; procedure TCanvasWrapper.Rectangle(const R: TDblRect); var DR:TRect; begin Convert(R.P1,DR.TopLeft); Convert(R.P2,DR.BottomRight); FCanvas.Rectangle(DR); end; procedure TCanvasWrapper.SetConversion(const Src: TDblRect; const Dst: TRect); begin FSrcShift.x:=-Src.P1.x; FSrcShift.y:=-Src.P1.y; FDstShift:=Dst.TopLeft; FSrcScale.x:=(Dst.Right-Dst.Left)/(Src.x2-Src.x1); FSrcScale.y:=(Dst.Bottom-Dst.Top)/(Src.y2-Src.y1); end; procedure TCanvasWrapper.SetFontHeight(const Value: float); var h:Integer; begin h:=Round(Value*OptScale); if h<1 then h:=1; FCanvas.Font.Height:=h; end; procedure TCanvasWrapper.SetPenWidth(const Value: float); var w:Integer; begin w:=Round(Value*OptScale); if w<1 then w:=1; FCanvas.Pen.Width:=w end; procedure TCanvasWrapper.StretchDraw(const R: TDblRect; Graphic: TGraphic); var DR:TRect; begin Convert(R.P1,DR.TopLeft); Convert(R.P2,DR.BottomRight); FCanvas.StretchDraw(DR,Graphic); end; function TCanvasWrapper.TextExtent(const Text: string): TDblPoint; var S:TSize; P:TPoint; begin S:=FCanvas.TextExtent(Text); P.x:=S.cx; P.y:=S.cy; Convert(P,Result); end; procedure TCanvasWrapper.TextOut(const P: TDblPoint; const Text: string); var DP:TPoint; begin Convert(P,DP); FCanvas.TextOut(DP.x,DP.y,Text); end; { TBMP256CanvasWrapper } constructor TBMP256CanvasWrapper.Create(BM: TBitmap); begin inherited Create(BM.Canvas); BI:=CreateBMP256Info(BM); end; destructor TBMP256CanvasWrapper.Destroy; begin FreeBMP256Info(BI); inherited; end; procedure TBMP256CanvasWrapper.AALineTo(const P: TDblPoint); var NewPos:TPoint; begin ConvertToFix(P,NewPos); AntiAliazedLine(BI^,PenPos,NewPos,Pen.Color and $FF); PenPos:=NewPos; end; procedure TBMP256CanvasWrapper.AAMoveTo(const P: TDblPoint); begin ConvertToFix(P,PenPos); end; function TBMP256CanvasWrapper.GetPenIntPos: TPoint; begin Result.x:=fix_int(PenPos.x); Result.y:=fix_int(PenPos.y); end; procedure Initialize; const Inv3=1/3; Inv9=1/9; var i,j,k:Integer; CA:^TAntiAliasCoeffTbl; fill,fj:Single; begin for i:=0 to 3 do begin fill:=(Sqrt(1+Inv9*i*i)-1)*0.5+0.17; for j:=0 to 3 do begin CA:=@(TripTbl[i,j]); fj:=j*Inv3; if fj<fill then begin CA[-1]:=Round(fill*3); CA[ 0]:=3; end else begin CA[-1]:=0; CA[ 0]:=Round((1-fj+fill)*3); end; CA[+1]:=Round((fj+fill)*3); end; end; for i:=0 to 3 do for j:=0 to 3 do for k:=-1 to 1 do if TripTbl[i,j,k]>3 then TripTbl[i,j,k]:=3; for i:=-3 to -1 do TripTbl[i]:=TripTbl[-i]; // mix tbl for i:=0 to 255 do for j:=0 to 3 do for k:=0 to 255 do MixTbl[i,j,k]:=Trunc((i*j+k*(3-j))*Inv3); end; initialization Initialize; end.
unit uClienteEmailController; interface uses System.SysUtils, uDMClienteEmail, uRegras, uDM, Data.DB, uEnumerador, uFuncoesSIDomper; type TClienteEmailController = class private FModel: TDMClienteEmail; public procedure LocalizarCodigo(ACodigo: integer); procedure Post; procedure Excluir; procedure Cancelar; procedure Novo; property Model: TDMClienteEmail read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TClienteEmailController } procedure TClienteEmailController.Cancelar; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Cancel; end; constructor TClienteEmailController.Create; begin inherited Create; FModel := TDMClienteEmail.Create(nil); end; destructor TClienteEmailController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TClienteEmailController.Excluir; begin if FModel.CDSConsulta.IsEmpty then raise Exception.Create('Não há Registro para Excluir.'); FModel.CDSConsulta.Delete; end; procedure TClienteEmailController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.LocalizarCodigo(CClienteEmailPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEmailController.Novo; begin FModel.CDSConsulta.Append; end; procedure TClienteEmailController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; 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.13 9/8/2004 8:55:46 PM JPMugaas Fix for compile problem where a char is being compared with an incompatible type in some compilers. Rev 1.12 02/07/2004 21:59:28 CCostelloe Bug fix Rev 1.11 17/06/2004 14:19:00 CCostelloe Bug fix for long subject lines that have characters needing CharSet encoding Rev 1.10 23/04/2004 20:33:04 CCostelloe Minor change to support From headers holding multiple addresses Rev 1.9 2004.02.03 5:44:58 PM czhower Name changes Rev 1.8 24/01/2004 19:08:14 CCostelloe Cleaned up warnings Rev 1.7 1/22/2004 3:56:38 PM SPerry fixed set problems Rev 1.6 2004.01.22 2:34:58 PM czhower TextIsSame + D8 bug workaround Rev 1.5 10/16/2003 11:11:02 PM DSiders Added localization comments. Rev 1.4 10/8/2003 9:49:36 PM GGrieve Use IdDelete Rev 1.3 6/10/2003 5:48:46 PM SGrobety DotNet updates Rev 1.2 04/09/2003 20:35:28 CCostelloe Parameter AUseAddressForNameIfNameMissing (defaulting to False to preserve existing code) added to EncodeAddressItem Rev 1.1 2003.06.23 9:46:52 AM czhower Russian, Ukranian support for headers. Rev 1.0 11/14/2002 02:14:46 PM JPMugaas } unit IdCoderHeader; //refer http://www.faqs.org/rfcs/rfc2047.html //TODO: Optimize and restructure code //TODO: Redo this unit to fit with the new coders and use the exisiting MIME stuff { 2002-08-21 JM Berg - brought in line with the RFC regarding whitespace between encoded words - added logic so that lines that already seem encoded are really encoded again (so that if a user types =?iso8859-1?Q?======?= its really encoded again and displayed like that on the other side) 2001-Nov-18 Peter Mee - Fixed multiple QP decoding in single header. 11-10-2001 - J. Peter Mugaas - tiny fix for 8bit header encoding suggested by Andrew P.Rybin } interface {$i IdCompilerDefines.inc} uses Classes, IdComponent, IdEMailAddress, IdHeaderCoderBase; // Procs function EncodeAddressItem(EmailAddr: TIdEmailAddressItem; const HeaderEncoding: Char; const MimeCharSet: string; AUseAddressForNameIfNameMissing: Boolean = False): string; function EncodeHeader(const Header: string; Specials: String; const HeaderEncoding: Char; const MimeCharSet: string): string; function EncodeAddress(EmailAddr: TIdEMailAddressList; const HeaderEncoding: Char; const MimeCharSet: string; AUseAddressForNameIfNameMissing: Boolean = False): string; function DecodeHeader(const Header: string): string; procedure DecodeAddress(EMailAddr: TIdEmailAddressItem); procedure DecodeAddresses(AEMails: String; EMailAddr: TIdEmailAddressList); implementation uses IdException, IdGlobal, IdGlobalProtocols, IdAllHeaderCoders, SysUtils; const csAddressSpecials: String = '()[]<>:;.,@\"'; {Do not Localize} base64_tbl: array [0..63] of Char = ( 'A','B','C','D','E','F','G','H', {Do not Localize} 'I','J','K','L','M','N','O','P', {Do not Localize} 'Q','R','S','T','U','V','W','X', {Do not Localize} 'Y','Z','a','b','c','d','e','f', {Do not Localize} 'g','h','i','j','k','l','m','n', {Do not Localize} 'o','p','q','r','s','t','u','v', {Do not Localize} 'w','x','y','z','0','1','2','3', {Do not Localize} '4','5','6','7','8','9','+','/'); {Do not Localize} function EncodeAddressItem(EmailAddr: TIdEmailAddressItem; const HeaderEncoding: Char; const MimeCharSet: string; AUseAddressForNameIfNameMissing: Boolean = False): string; var S : string; I : Integer; NeedEncode : Boolean; begin if AUseAddressForNameIfNameMissing and (EmailAddr.Name = '') then begin {CC: Use Address as Name...} EmailAddr.Name := EmailAddr.Address; end; if EmailAddr.Name <> '' then {Do not Localize} begin NeedEncode := False; for I := 1 to Length(EmailAddr.Name) do begin if (EmailAddr.Name[I] < #32) or (EmailAddr.Name[I] >= #127) then begin NeedEncode := True; Break; end; end; if NeedEncode then begin S := EncodeHeader(EmailAddr.Name, csAddressSpecials, HeaderEncoding, MimeCharSet); end else begin { quoted string } S := '"'; {Do not Localize} for I := 1 to Length(EmailAddr.Name) do begin { quote special characters } if (EmailAddr.Name[I] = '\') or (EmailAddr.Name[I] = '"') then begin S := S + '\'; {Do not Localize} end; S := S + EmailAddr.Name[I]; end; S := S + '"'; {Do not Localize} end; Result := IndyFormat('%s <%s>', [S, EmailAddr.Address]) {Do not Localize} end else begin Result := IndyFormat('%s', [EmailAddr.Address]); {Do not Localize} end; end; function B64(AChar: Char): Byte; //TODO: Make this use the more efficient MIME Coder begin for Result := Low(base64_tbl) to High(base64_tbl) do begin if AChar = base64_tbl[Result] then begin Exit; end; end; Result := 0; end; function DecodeHeader(const Header: string): string; var HeaderCharSet, HeaderEncoding, HeaderData, S: string; LDecoded: Boolean; LStartPos, LLength, LEncodingStartPos, LEncodingEndPos, LLastStartPos: Integer; LLastWordWasEncoded: Boolean; Buf: TIdBytes; function ExtractEncoding(const AHeader: string; const AStartPos: Integer; var VStartPos, VEndPos: Integer; var VCharSet, VEncoding, VData: String): Boolean; var LCharSet, LEncoding, LData, LDataEnd: Integer; begin Result := False; //we need a '=? followed by 2 question marks followed by a '?='. {Do not Localize} //to find the end of the substring, we can't just search for '?=', {Do not Localize} //example: '=?ISO-8859-1?Q?=E4?=' {Do not Localize} LCharSet := PosIdx('=?', AHeader, AStartPos); {Do not Localize} if (LCharSet = 0) or (LCharSet > VEndPos) then begin Exit; end; Inc(LCharSet, 2); LEncoding := PosIdx('?', AHeader, LCharSet); {Do not Localize} if (LEncoding = 0) or (LEncoding > VEndPos) then begin Exit; end; Inc(LEncoding); LData := PosIdx('?', AHeader, LEncoding); {Do not Localize} if (LData = 0) or (LData > VEndPos) then begin Exit; end; Inc(LData); LDataEnd := PosIdx('?=', AHeader, LData); {Do not Localize} if (LDataEnd = 0) or (LDataEnd > VEndPos) then begin Exit; end; Inc(LDataEnd); VStartPos := LCharSet-2; VEndPos := LDataEnd; VCharSet := Copy(AHeader, LCharSet, LEncoding-LCharSet-1); VEncoding := Copy(AHeader, LEncoding, LData-LEncoding-1); VData := Copy(AHeader, LData, LDataEnd-LData-1); Result := True; end; // TODO: use TIdCoderQuotedPrintable and TIdCoderMIME instead function ExtractEncodedData(const AEncoding, AData: String; var VDecoded: TIdBytes): Boolean; var I, J: Integer; a3: TIdBytes; a4: array [0..3] of Byte; begin Result := False; SetLength(VDecoded, 0); case PosInStrArray(AEncoding, ['Q', 'B', '8'], False) of {Do not Localize} 0: begin // quoted-printable I := 1; while I <= Length(AData) do begin if AData[i] = '_' then begin {Do not Localize} AppendByte(VDecoded, Ord(' ')); {Do not Localize} end else if (AData[i] = '=') and (Length(AData) >= (i+2)) then begin //make sure we can access i+2 AppendByte(VDecoded, IndyStrToInt('$' + Copy(AData, i+1, 2), 32)); {Do not Localize} Inc(I, 2); end else begin AppendByte(VDecoded, Ord(AData[i])); end; Inc(I); end; Result := True; end; 1: begin // base64 J := Length(AData) div 4; if J > 0 then begin SetLength(a3, 3); for I := 0 to J-1 do begin a4[0] := B64(AData[(I*4)+1]); a4[1] := B64(AData[(I*4)+2]); a4[2] := B64(AData[(I*4)+3]); a4[3] := B64(AData[(I*4)+4]); a3[0] := Byte((a4[0] shl 2) or (a4[1] shr 4)); a3[1] := Byte((a4[1] shl 4) or (a4[2] shr 2)); a3[2] := Byte((a4[2] shl 6) or (a4[3] shr 0)); if AData[(I*4)+4] = '=' then begin if AData[(I*4)+3] = '=' then begin AppendByte(VDecoded, a3[0]); end else begin AppendBytes(VDecoded, a3, 0, 2); end; Break; end else begin AppendBytes(VDecoded, a3, 0, 3); end; end; end; Result := True; end; 2: begin // 8-bit {$IFDEF STRING_IS_ANSI} if AData <> '' then begin VDecoded := RawToBytes(AData[1], Length(AData)); end; {$ELSE} VDecoded := Indy8BitEncoding.GetBytes(AData); {$ENDIF} Result := True; end; end; end; begin Result := Header; LStartPos := 1; LLength := Length(Result); LLastWordWasEncoded := False; LLastStartPos := LStartPos; while LStartPos <= LLength do begin // valid encoded words can not contain spaces // if the user types something *almost* like an encoded word, // and its sent as-is, we need to find this!! LStartPos := FindFirstNotOf(LWS, Result, LLength, LStartPos); if LStartPos = 0 then begin Break; end; LEncodingEndPos := FindFirstOf(LWS, Result, LLength, LStartPos); if LEncodingEndPos <> 0 then begin Dec(LEncodingEndPos); end else begin LEncodingEndPos := LLength; end; if ExtractEncoding(Result, LStartPos, LEncodingStartPos, LEncodingEndPos, HeaderCharSet, HeaderEncoding, HeaderData) then begin LDecoded := False; if ExtractEncodedData(HeaderEncoding, HeaderData, Buf) then begin LDecoded := DecodeHeaderData(HeaderCharSet, Buf, S); end; if LDecoded then begin //replace old substring in header with decoded string, // ignoring whitespace that separates encoded words: if LLastWordWasEncoded then begin Result := Copy(Result, 1, LLastStartPos - 1) + S + Copy(Result, LEncodingEndPos + 1, MaxInt); LStartPos := LLastStartPos + Length(S); end else begin Result := Copy(Result, 1, LEncodingStartPos - 1) + S + Copy(Result, LEncodingEndPos + 1, MaxInt); LStartPos := LEncodingStartPos + Length(S); end; end else begin // could not decode the data, so preserve it in case the user // wants to do it manually. Though, they really should use the // IdHeaderCoderBase.GHeaderDecodingNeeded hook for that instead... LStartPos := LEncodingEndPos + 1; end; LLength := Length(Result); LLastWordWasEncoded := True; LLastStartPos := LStartPos; end else begin LStartPos := FindFirstOf(LWS, Result, LLength, LStartPos); if LStartPos = 0 then begin Break; end; LLastWordWasEncoded := False; end; end; end; procedure DecodeAddress(EMailAddr : TIdEmailAddressItem); begin EMailAddr.Name := UnquotedStr(DecodeHeader(EMailAddr.Name)); end; procedure DecodeAddresses(AEMails : String; EMailAddr: TIdEmailAddressList); var idx : Integer; begin EMailAddr.EMailAddresses := AEMails; for idx := 0 to EMailAddr.Count-1 do begin DecodeAddress(EMailAddr[idx]); end; end; function EncodeAddress(EmailAddr: TIdEMailAddressList; const HeaderEncoding: Char; const MimeCharSet: string; AUseAddressForNameIfNameMissing: Boolean = False): string; var idx : Integer; begin if EmailAddr.Count > 0 then begin Result := EncodeAddressItem(EMailAddr[0], HeaderEncoding, MimeCharSet, AUseAddressForNameIfNameMissing); for idx := 1 to EmailAddr.Count-1 do begin Result := Result + ', ' + {Do not Localize} EncodeAddressItem(EMailAddr[idx], HeaderEncoding, MimeCharSet, AUseAddressForNameIfNameMissing); end; end else begin Result := ''; {Do not Localize} end; end; { encode a header field if non-ASCII characters are used } function EncodeHeader(const Header: string; Specials: String; const HeaderEncoding: Char; const MimeCharSet: string): string; const SPACES = [Ord(' '), 9, 13, 10]; {Do not Localize} var T: string; Buf: TIdBytes; L, P, Q, R: Integer; B0, B1, B2: Integer; InEncode: Integer; NeedEncode: Boolean; csNoEncode, csNoReqQuote, csSpecials: TIdBytes; BeginEncode, EndEncode: string; procedure EncodeWord(AP: Integer); const MaxEncLen = 75; var LQ: Integer; EncLen: Integer; Enc1: string; begin T := T + BeginEncode; if L < AP then AP := L + 1; LQ := InEncode; InEncode := -1; EncLen := Length(BeginEncode) + 2; case PosInStrArray(HeaderEncoding, ['Q', 'B'], False) of {Do not Localize} 0: begin { quoted-printable } while LQ < AP do begin if Buf[LQ] = Ord(' ') then begin {Do not Localize} Enc1 := '_'; {Do not Localize} end else if (not ByteIsInSet(Buf, LQ, csNoReqQuote)) or ByteIsInSet(Buf, LQ, csSpecials) then begin Enc1 := '=' + IntToHex(Buf[LQ], 2); {Do not Localize} end else begin Enc1 := Char(Buf[LQ]); end; if (EncLen + Length(Enc1)) > MaxEncLen then begin //T := T + EndEncode + #13#10#9 + BeginEncode; //CC: The #13#10#9 above caused the subsequent call to FoldWrapText to //insert an extra #13#10 which, being a blank line in the headers, //was interpreted by email clients, etc., as the end of the headers //and the start of the message body. FoldWrapText seems to look for //and treat correctly the sequence #13#10 + ' ' however... T := T + EndEncode + EOL + ' ' + BeginEncode; EncLen := Length(BeginEncode) + 2; end; T := T + Enc1; Inc(EncLen, Length(Enc1)); Inc(LQ); end; end; 1: begin { base64 } while LQ < AP do begin if (EncLen + 4) > MaxEncLen then begin //T := T + EndEncode + #13#10#9 + BeginEncode; //CC: The #13#10#9 above caused the subsequent call to FoldWrapText to //insert an extra #13#10 which, being a blank line in the headers, //was interpreted by email clients, etc., as the end of the headers //and the start of the message body. FoldWrapText seems to look for //and treat correctly the sequence #13#10 + ' ' however... T := T + EndEncode + EOL + ' ' + BeginEncode; EncLen := Length(BeginEncode) + 2; end; B0 := Buf[LQ]; case AP - LQ of 1: begin T := T + base64_tbl[B0 shr 2] + base64_tbl[B0 and $03 shl 4] + '=='; {Do not Localize} end; 2: begin B1 := Buf[LQ + 1]; T := T + base64_tbl[B0 shr 2] + base64_tbl[B0 and $03 shl 4 + B1 shr 4] + base64_tbl[B1 and $0F shl 2] + '='; {Do not Localize} end; else begin B1 := Buf[LQ + 1]; B2 := Buf[LQ + 2]; T := T + base64_tbl[B0 shr 2] + base64_tbl[B0 and $03 shl 4 + B1 shr 4] + base64_tbl[B1 and $0F shl 2 + B2 shr 6] + base64_tbl[B2 and $3F]; end; end; Inc(EncLen, 4); Inc(LQ, 3); end; end; end; T := T + EndEncode; end; function CreateEncodeRange(AStart, AEnd: Byte): TIdBytes; var I: Integer; begin SetLength(Result, AEnd-AStart+1); for I := 0 to Length(Result)-1 do begin Result[I] := AStart+I; end; end; begin if Header = '' then begin Result := ''; Exit; end; Buf := EncodeHeaderData(MimeCharSet, Header); {Suggested by Andrew P.Rybin for easy 8bit support} if HeaderEncoding = '8' then begin {Do not Localize} Result := BytesToStringRaw(Buf); Exit; end;//if // RLebeau 1/7/09: using Char() for #128-#255 because in D2009, the compiler // may change characters >= #128 from their Ansi codepage value to their true // Unicode codepoint value, depending on the codepage used for the source code. // For instance, #128 may become #$20AC... // RLebeau 2/12/09: changed the logic to use "no-encode" sets instead, so // that words containing codeunits outside the ASCII range are always // encoded. This is easier to manage when Unicode data is involved. csNoEncode := CreateEncodeRange(32, 126); csNoReqQuote := CreateEncodeRange(33, 60); AppendByte(csNoReqQuote, 62); AppendBytes(csNoReqQuote, CreateEncodeRange(64, 94)); AppendBytes(csNoReqQuote, CreateEncodeRange(96, 126)); csSpecials := ToBytes(Specials, Indy8BitEncoding); BeginEncode := '=?' + MimeCharSet + '?' + HeaderEncoding + '?'; {Do not Localize} EndEncode := '?='; {Do not Localize} // JMBERG: We want to encode stuff that the user typed // as if it already is encoded!! if DecodeHeader(Header) <> Header then begin RemoveBytes(csNoEncode, 1, ByteIndex(Ord('='), csNoEncode)); end; L := Length(Buf); P := 0; T := ''; {Do not Localize} InEncode := -1; while P < L do begin Q := P; while (P < L) and (Buf[P] in SPACES) do begin Inc(P); end; R := P; NeedEncode := False; while (P < L) and (not (Buf[P] in SPACES)) do begin if (not ByteIsInSet(Buf, P, csNoEncode)) or ByteIsInSet(Buf, P, csSpecials) then begin NeedEncode := True; end; Inc(P); end; if NeedEncode then begin if InEncode = -1 then begin T := T + BytesToString(Buf, Q, R - Q); InEncode := R; end; end else begin if InEncode <> -1 then begin EncodeWord(Q); end; T := T + BytesToString(Buf, Q, P - Q); end; end; if InEncode <> -1 then begin EncodeWord(P); end; Result := T; end; end.
unit TestExceptionHandler; interface uses TestFramework, Should ; implementation initialization Should.RegisterExceptionHandler( procedure (evalResult: TEvalResult) begin case (evalResult.Status) of TEvalResult.TEvalStatus.Falure: raise TestFramework.ETestFailure.Create(evalResult.Message); TEvalResult.TEvalStatus.Fatal: raise TestFramework.EDunitException.Create(evalResult.Message); end; end); end.
unit unCidadeModel; interface type TCidadeModel = class private FCidadeID: Integer; FNome: String; FCodigo_ibge: Integer; FDensidade: Real; FGentilico: String; FArea: Real; FPopulacao: Integer; FEstadoID: Integer; procedure SetArea(const Value: Real); procedure SetCodigo_ibge(const Value: Integer); procedure SetDensidade(const Value: Real); procedure SetGentilico(const Value: String); procedure SetNome(const Value: String); procedure SetPopulacao(const Value: Integer); procedure SetCidadeID(const Value: Integer); procedure SetEstadoID(const Value: Integer); public constructor Create(cCidadeId : Integer; cNome: String; cCodigo_ibge : Integer; cDensidade : Real; cGentilico : String; cArea : Real; cPopulacao : Integer; cEstadoId : Integer); published property CidadeID : Integer read FCidadeID write SetCidadeID; property Nome : String read FNome write SetNome; property Codigo_ibge : Integer read FCodigo_ibge write SetCodigo_ibge; property Populacao : Integer read FPopulacao write SetPopulacao; property Densidade : Real read FDensidade write SetDensidade; property Gentilico : String read FGentilico write SetGentilico; property Area : Real read FArea write SetArea; property EstadoID : Integer read FEstadoID write SetEstadoID; end; { criei um tipo de array, pois não é possível transformar um array em JsonObject pela funcao TObjectToJson. Poderia ter usado o TObjectList<T>, mas retorna muita sujeira no Json } type TArrayCidade = array of TCidadeModel; type TListaCidade = class private mCidades : TArrayCidade; function GetLength : Integer; public procedure Add(VCidade: TCidadeModel); published property Cidades : TArrayCidade read mCidades write mCidades; end; implementation { TCidadeModel } constructor TCidadeModel.Create(cCidadeId : Integer; cNome: String; cCodigo_ibge : Integer; cDensidade : Real; cGentilico : String ;cArea : Real; cPopulacao : Integer; cEstadoID : Integer); begin FCidadeID := cCidadeId; FCodigo_ibge := cCodigo_ibge; FDensidade := cDensidade; FArea := cArea; FPopulacao := cPopulacao; FGentilico := cGentilico; FNome := cNome; FEstadoID := cEstadoId; end; procedure TCidadeModel.SetArea(const Value: Real); begin FArea := Value; end; procedure TCidadeModel.SetCidadeID(const Value: Integer); begin FCidadeID := Value; end; procedure TCidadeModel.SetCodigo_ibge(const Value: Integer); begin FCodigo_ibge := Value; end; procedure TCidadeModel.SetDensidade(const Value: Real); begin FDensidade := Value; end; procedure TCidadeModel.SetEstadoID(const Value: Integer); begin FEstadoID := Value; end; procedure TCidadeModel.SetGentilico(const Value: String); begin FGentilico := Value; end; procedure TCidadeModel.SetNome(const Value: String); begin FNome := Value; end; procedure TCidadeModel.SetPopulacao(const Value: Integer); begin FPopulacao := Value; end; { TListaCidade } procedure TListaCidade.Add(VCidade : TCidadeModel); begin SetLength(mCidades,GetLength + 1);//muda o tamanho da array pegando o tamanho atual dela e incrementando 1. mCidades[High(mCidades)] := VCidade;// adiciona um TCidades na ultima posição da array end; function TListaCidade.GetLength: Integer; begin Result := Length(mCidades); //retorna o tamanha da array end; end.
{***************************************************************} { } { Delphi XML Data Binding } { } { Generated on: 6/4/2001 6:44:51 PM } { Generated from: C:\md6code\23\XmlInterface\Sample.xml } { } {***************************************************************} unit XmlIntfDefinition; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLBooksType = interface; IXMLBookType = interface; IXMLBookTypeList = interface; IXMLEbookType = interface; IXMLEbookTypeList = interface; IXMLString_List = interface; { IXMLBooksType } IXMLBooksType = interface(IXMLNode) ['{C9A9FB63-47ED-4F27-8ABA-E71F30BA7F11}'] { Property Accessors } function Get_Text: WideString; function Get_Book: IXMLBookTypeList; function Get_Ebook: IXMLEbookTypeList; procedure Set_Text(Value: WideString); { Methods & Properties } property Text: WideString read Get_Text write Set_Text; property Book: IXMLBookTypeList read Get_Book; property Ebook: IXMLEbookTypeList read Get_Ebook; end; { IXMLBookType } IXMLBookType = interface(IXMLNode) ['{26BF5C51-9247-4D1A-8584-24AE68969935}'] { Property Accessors } function Get_Title: WideString; function Get_Author: IXMLString_List; procedure Set_Title(Value: WideString); { Methods & Properties } property Title: WideString read Get_Title write Set_Title; property Author: IXMLString_List read Get_Author; end; { IXMLBookTypeList } IXMLBookTypeList = interface(IXMLNodeCollection) ['{3449E8C4-3222-47B8-B2B2-38EE504790B6}'] { Methods & Properties } function Add: IXMLBookType; function Insert(const Index: Integer): IXMLBookType; function Get_Item(Index: Integer): IXMLBookType; property Items[Index: Integer]: IXMLBookType read Get_Item; default; end; { IXMLEbookType } IXMLEbookType = interface(IXMLNode) ['{79F0237E-3596-40DD-ADBE-954AA7F6304F}'] { Property Accessors } function Get_Title: WideString; function Get_Url: WideString; function Get_Author: WideString; procedure Set_Title(Value: WideString); procedure Set_Url(Value: WideString); procedure Set_Author(Value: WideString); { Methods & Properties } property Title: WideString read Get_Title write Set_Title; property Url: WideString read Get_Url write Set_Url; property Author: WideString read Get_Author write Set_Author; end; { IXMLEbookTypeList } IXMLEbookTypeList = interface(IXMLNodeCollection) ['{9713B729-340C-40EB-91AB-635FEF553EA5}'] { Methods & Properties } function Add: IXMLEbookType; function Insert(const Index: Integer): IXMLEbookType; function Get_Item(Index: Integer): IXMLEbookType; property Items[Index: Integer]: IXMLEbookType read Get_Item; default; end; { IXMLString_List } IXMLString_List = interface(IXMLNodeCollection) ['{5DE9DF5D-9DE0-4654-B0D6-0CF330280950}'] { Methods & Properties } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; property Items[Index: Integer]: WideString read Get_Item; default; end; { Forward Decls } TXMLBooksType = class; TXMLBookType = class; TXMLBookTypeList = class; TXMLEbookType = class; TXMLEbookTypeList = class; TXMLString_List = class; { TXMLBooksType } TXMLBooksType = class(TXMLNode, IXMLBooksType) private FBook: IXMLBookTypeList; FEbook: IXMLEbookTypeList; protected { IXMLBooksType } function Get_Text: WideString; function Get_Book: IXMLBookTypeList; function Get_Ebook: IXMLEbookTypeList; procedure Set_Text(Value: WideString); public procedure AfterConstruction; override; end; { TXMLBookType } TXMLBookType = class(TXMLNode, IXMLBookType) private FAuthor: IXMLString_List; protected { IXMLBookType } function Get_Title: WideString; function Get_Author: IXMLString_List; procedure Set_Title(Value: WideString); public procedure AfterConstruction; override; end; { TXMLBookTypeList } TXMLBookTypeList = class(TXMLNodeCollection, IXMLBookTypeList) protected { IXMLBookTypeList } function Add: IXMLBookType; function Insert(const Index: Integer): IXMLBookType; function Get_Item(Index: Integer): IXMLBookType; end; { TXMLEbookType } TXMLEbookType = class(TXMLNode, IXMLEbookType) protected { IXMLEbookType } function Get_Title: WideString; function Get_Url: WideString; function Get_Author: WideString; procedure Set_Title(Value: WideString); procedure Set_Url(Value: WideString); procedure Set_Author(Value: WideString); end; { TXMLEbookTypeList } TXMLEbookTypeList = class(TXMLNodeCollection, IXMLEbookTypeList) protected { IXMLEbookTypeList } function Add: IXMLEbookType; function Insert(const Index: Integer): IXMLEbookType; function Get_Item(Index: Integer): IXMLEbookType; end; { TXMLString_List } TXMLString_List = class(TXMLNodeCollection, IXMLString_List) protected { IXMLString_List } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; end; { Global Functions } function Getbooks(Doc: IXMLDocument): IXMLBooksType; function Loadbooks(const FileName: WideString): IXMLBooksType; function Newbooks: IXMLBooksType; implementation { Global Functions } function Getbooks(Doc: IXMLDocument): IXMLBooksType; begin Result := Doc.GetDocBinding('books', TXMLBooksType) as IXMLBooksType; end; function Loadbooks(const FileName: WideString): IXMLBooksType; begin Result := LoadXMLDocument(FileName).GetDocBinding('books', TXMLBooksType) as IXMLBooksType; end; function Newbooks: IXMLBooksType; begin Result := NewXMLDocument.GetDocBinding('books', TXMLBooksType) as IXMLBooksType; end; { TXMLBooksType } procedure TXMLBooksType.AfterConstruction; begin RegisterChildNode('book', TXMLBookType); RegisterChildNode('ebook', TXMLEbookType); FBook := CreateCollection(TXMLBookTypeList, IXMLBookType, 'book') as IXMLBookTypeList; FEbook := CreateCollection(TXMLEbookTypeList, IXMLEbookType, 'ebook') as IXMLEbookTypeList; inherited; end; function TXMLBooksType.Get_Text: WideString; begin Result := AttributeNodes['text'].Text; end; procedure TXMLBooksType.Set_Text(Value: WideString); begin SetAttribute('text', Value); end; function TXMLBooksType.Get_Book: IXMLBookTypeList; begin Result := FBook; end; function TXMLBooksType.Get_Ebook: IXMLEbookTypeList; begin Result := FEbook; end; { TXMLBookType } procedure TXMLBookType.AfterConstruction; begin FAuthor := CreateCollection(TXMLString_List, IXMLNode, 'author') as IXMLString_List; inherited; end; function TXMLBookType.Get_Title: WideString; begin Result := ChildNodes['title'].Text; end; procedure TXMLBookType.Set_Title(Value: WideString); begin ChildNodes['title'].NodeValue := Value; end; function TXMLBookType.Get_Author: IXMLString_List; begin Result := FAuthor; end; { TXMLBookTypeList } function TXMLBookTypeList.Add: IXMLBookType; begin Result := AddItem(-1) as IXMLBookType; end; function TXMLBookTypeList.Insert(const Index: Integer): IXMLBookType; begin Result := AddItem(Index) as IXMLBookType; end; function TXMLBookTypeList.Get_Item(Index: Integer): IXMLBookType; begin Result := List[Index] as IXMLBookType; end; { TXMLEbookType } function TXMLEbookType.Get_Title: WideString; begin Result := ChildNodes['title'].Text; end; procedure TXMLEbookType.Set_Title(Value: WideString); begin ChildNodes['title'].NodeValue := Value; end; function TXMLEbookType.Get_Url: WideString; begin Result := ChildNodes['url'].Text; end; procedure TXMLEbookType.Set_Url(Value: WideString); begin ChildNodes['url'].NodeValue := Value; end; function TXMLEbookType.Get_Author: WideString; begin Result := ChildNodes['author'].Text; end; procedure TXMLEbookType.Set_Author(Value: WideString); begin ChildNodes['author'].NodeValue := Value; end; { TXMLEbookTypeList } function TXMLEbookTypeList.Add: IXMLEbookType; begin Result := AddItem(-1) as IXMLEbookType; end; function TXMLEbookTypeList.Insert(const Index: Integer): IXMLEbookType; begin Result := AddItem(Index) as IXMLEbookType; end; function TXMLEbookTypeList.Get_Item(Index: Integer): IXMLEbookType; begin Result := List[Index] as IXMLEbookType; end; { TXMLString_List } function TXMLString_List.Add(const Value: WideString): IXMLNode; begin Result := AddItem(-1); Result.NodeValue := Value; end; function TXMLString_List.Insert(const Index: Integer; const Value: WideString): IXMLNode; begin Result := AddItem(Index); Result.NodeValue := Value; end; function TXMLString_List.Get_Item(Index: Integer): WideString; begin Result := List[Index].NodeValue; end; end.
unit UWaveFormComputer; interface uses Windows, Misc; type TWaveP2Calculator=object tf1,Int1:Double; tf2,Int2:Double; Alpha1,Alpha2:Double; function iCalcP2(const t,P1: Double): Double; function CalcP2(const t,P1:Double):Double; end; TWaveFormComputer=object protected D1,A2,D2:PSingle; Data1,Appr2,Data2:TArrayOfSingle; Size:Integer; public P2C:TWaveP2Calculator; FilterShoulder:Integer; NeedAdvInfo:Boolean; AdvInfo:String; procedure Init( const MaxTimeDelta, TimeDelta: Double; const Src1,Src2:TArrayOfSingle; i1,i2,ASize:Integer); procedure CalcSimilarity(Sim1,Sim2:PDouble); procedure GetDrawData(var dA2,dD2:TArrayOfSingle); public property pA2:PSingle read A2; property pD2:PSingle read D2; end; function LinearCompensatedDistance(D1,D2:PSingle; n:Integer):Double; function ShiftCompensatedDistance(D1,D2:PSingle; n:Integer):Double; procedure ExtractImpulse(Src,Dst:PSingle; n:Integer); function SpecCorr(D1,D2:PSingle; n:Integer):Double; function LinearCompensatedSpecCorr(D1,D2:PSingle; n:Integer):Double; procedure MakeHorizontal(pY:PSingle; n:Integer); procedure DifferenceFromLine(Data:PSingle; n:Integer; LMean,RMean,Max:PDouble); procedure CalcP2(tf1,tf2:Integer; P1,P2:PSingle; Len:Integer); implementation uses UFFT; function GetAlpha(n:Integer):Double; begin Result:=Exp(-4.60517/n); end; { Based on sample program for the book NUMERICAL RECIPES IN PASCAL: THE ART OF SCIENTIFIC COMPUTING by William H. Press, Saul A. Teukolsky, Brian P. Flannery, and William T. Vetterling Cambridge University Press, New York, 1989. } FUNCTION BesselI1(x: Double): Double; CONST KA01=1/2.; KA03=1/16.; KA05=1/384.; KA07=1/18432.; KA09=1/1474560.; KA11=1/176947200.; KA13=1/29727129600.; KA15=1/6658877030400.; VAR ax: double; y: double; BEGIN IF (abs(x) < 3.75) THEN BEGIN y:=x*x; Result:=x*(KA01+y*(KA03+y*(KA05+y*(KA07+y*(KA09+y*(KA11+y*(KA13+y*KA15))))))); END ELSE BEGIN ax := abs(x); y := 3.75/ax; Result := exp(ax)/sqrt(ax) * ( 0.39894228 + y*(-0.3988024e-1 + y*(-0.362018e-2 + y*( 0.163801e-2 + y*(-0.1031555e-1 + y*(0.2282967e-1 + y*( -0.2895312e-1 + y*(0.1787654e-1 - y*0.420059e-2) ))))))); IF (x<0.0) THEN Result:=-Result END; END; function Correl(D1,D2:PSingle; n:Integer):Double; var S1,M1,S2,M2:Double; begin CalcMuSigma(D1,n,M1,S1); CalcMuSigma(D2,n,M2,S2); if (S1>0) and (S2>0) then Result:=Cov(D1,D2,M1,M2,n)/(S1*S2) else Result:=0; end; procedure GetMinMax(Data:PSingle; n:Integer; pMin,pMax:PDouble); var Min,Max:Double; begin Min:=Data^; Max:=Data^; Inc(Data); Dec(n); while n>0 do begin if Data^<Min then Min:=Data^ else if Max<Data^ then Max:=Data^; Inc(Data); Dec(n); end; if pMin<>nil then pMin^:=Min; if pMax<>nil then pMax^:=Max; end; procedure DifferenceFromLine(Data:PSingle; n:Integer; LMean,RMean,Max:PDouble); var K,B,Sum,Mx,Tmp:Double; i,i1:Integer; begin i1:=(n+1) shr 1; CalcKB(Data,0,i1,@K,@B); Sum:=0; for i:=0 to i1 do begin Sum:=Sum+Abs(K*i+B-Data^); Inc(Data); end; if LMean<>nil then LMean^:=Sum/(i1+1); Sum:=0; Mx:=0; for i:=i1+1 to n-1 do begin Tmp:=Abs(K*i+B-Data^); if Mx<Tmp then Mx:=Tmp; Sum:=Sum+Tmp; Inc(Data); end; if RMean<>nil then RMean^:=Sum/(n-i1-1); if Max<>nil then Max^:=Mx; end; procedure GetDiff(Src,Dst:PSingle; n:Integer); var PS1,PS2:PSingle; begin Dst^:=0; Inc(Dst); PS2:=Src; Inc(Src); PS1:=Src; Inc(Src); Dec(n,2); while n>0 do begin Dst^:=Src^-PS2^; PS2:=PS1; PS1:=Src; Inc(Src); Inc(Dst); Dec(n); end; Dst^:=0; end; function LinearCompensatedSpecCorr(D1,D2:PSingle; n:Integer):Double; var i:Integer; SumA,SumB,A,B:Double; K1,B1,T1,K2,B2,T2:Double; begin CalcKB(D1,0,n-1,@K1,@B1); CalcKB(D2,0,n-1,@K2,@B2); SumA:=0; SumB:=0; for i:=0 to n-1 do begin T1:=D1^-(K1*i+B1); T2:=D2^-(K2*i+B2); A:=Sqr(T1-T2); B:=Sqr(T1+T2); SumA:=SumA+A; SumB:=SumB+B; Inc(D1); Inc(D2); end; // SumA:=Sqrt(SumA); SumB:=Sqrt(SumB); Result:=SumA+SumB; if Result>1e-66 then Result:=(SumB-SumA)/Result else Result:=0; end; function SpecCorr(D1,D2:PSingle; n:Integer):Double; var i:Integer; SumA,SumB,A,B:Double; begin SumA:=0; SumB:=0; i:=n-1; while i>=0 do begin A:=Sqr(D1^-D2^); B:=Sqr(D1^+D2^); SumA:=SumA+A; SumB:=SumB+B; dec(i); Inc(D1); Inc(D2); end; // SumA:=Sqrt(SumA); SumB:=Sqrt(SumB); Result:=SumA+SumB; if Result>1e-66 then Result:=(SumB-SumA)/Result else Result:=0; end; function ShiftCompensatedDistance(D1,D2:PSingle; n:Integer):Double; var i:Integer; B:Double; DD:array[0..511] of Single; begin B:=0; for i:=0 to n-1 do begin DD[i]:=D1^-D2^; B:=B+DD[i]; Inc(D1); Inc(D2); end; B:=B/n; Result:=0; for i:=0 to n-1 do Result:=Result+Sqr(DD[i]-B); Result:=Sqrt(Result); end; function ScaleCompensatedDistance(D1,D2:PSingle; n:Integer):Double; var i:Integer; K:Double; DD:array[0..511] of Single; begin for i:=0 to n-1 do begin DD[i]:=D1^-D2^; Inc(D1); Inc(D2); end; CalcK(@DD[0],0,n-1,@K); Result:=0; for i:=0 to n-1 do Result:=Result+Sqr(K*i-DD[i]); Result:=Sqrt(Result); end; function LinearCompensatedDistance(D1,D2:PSingle; n:Integer):Double; var i,i1,i2:Integer; K,B:Double; DD:array[0..511] of Single; begin for i:=0 to n-1 do begin DD[i]:=D1^-D2^; Inc(D1); Inc(D2); end; i1:=-(n shr 1); i2:=n+i1-1; CalcKB(@DD[0],i1,i2,@K,@B); Result:=0; for i:=0 to n-1 do Result:=Result+Sqr(K*(i1+i)+B-DD[i]); Result:=Sqrt(Result); end; function InvDistance(D1,D2:PSingle; n:Integer):Double; begin Result:=LinearCompensatedDistance(D1,D2,n); if Result>1e-4 then Result:=1/Result else Result:=1e+4; end; function Similarity(S1,S2:PSingle; n:Integer):Double; var i:Integer; P1,P2:PSingle; DD:array[0..511] of Single; begin P1:=S1; P2:=S2; for i:=0 to n-1 do begin DD[i]:=P2^-P1^; Inc(P1); Inc(P2); end; Result:=SpecCorr(S1,@DD[0],n); end; procedure MakeHorizontal(pY:PSingle; n:Integer); var K,B:Double; i:Integer; begin if CalcKB(pY,0,n-1,@K,@B) then begin for i:=0 to n-1 do begin pY^:=pY^-(K*i+B); Inc(pY); end; end; end; procedure DifferencesFromLine(const K,B:Double; Src,Dst:PSingle; i0,i1:Integer); var i:Integer; begin for i:=i0 to i1 do begin Dst^:=Src^-(K*i+B); Inc(Dst); Inc(Src); end; end; procedure ExtractImpulse(Src,Dst:PSingle; n:Integer); var P0:Single; iSrc:Cardinal absolute Src; // A:Double; // K,B:Double; begin // CalcKB(Src,0,n shr 1,@K,@B); // DifferenceFromLine(K,B,Src,Dst,0,n-1); //{ // A:=GetAlpha(n); P0:=Src^; while n>0 do begin Dst^:=Src^-P0; // P0:=P0*A+Src^*(1-A); Inc(Src); Inc(Dst); Dec(n); end; //} end; procedure TWaveFormComputer.CalcSimilarity(Sim1,Sim2:PDouble); const nCutOff=10; var t:Double; PU,PV:PSingle; n:Integer; Tmp:TArrayOfSingle; begin // Calculate A2 waveform PU:=D1; PV:=A2; n:=Size; t:=0; //(* CalcP2(Round(P2C.tf1),Round(P2C.tf2),PU,PV,Size); {*) while n>0 do begin PV^:=P2C.CalcP2(t,PU^); t:=t+1.0; inc(PV); inc(PU); dec(n); end; //} // Compute similarity :-) MakeHorizontal(A2,Size); MakeHorizontal(D2,Size); Tmp:=nil; n:=Size; { SetLength(Tmp,n); MyFFT(@Appr2[0],@Tmp[0],n,nCutOff); Move(Tmp[0],Appr2[0],n*4); MyFFT(@Data2[0],@Tmp[0],n,nCutOff); Move(Tmp[0],Data2[0],n*4); //} if FilterShoulder>0 then begin SetLength(Tmp,n); DataAvgFilter(Appr2,Tmp,FilterShoulder); Move(Tmp[0],Appr2[0],n*4); DataAvgFilter(Data2,Tmp,FilterShoulder); Move(Tmp[0],Data2[0],n*4); end; // if Sim1<>nil then Sim1^:=Similarity(A2,D2,Size); if Sim1<>nil then Sim1^:=LinearCompensatedSpecCorr(A2,D2,Size); // if Sim1<>nil then Sim1^:=SpecCorr(A2,D2,Size); if Sim2<>nil then Sim2^:=InvDistance(A2,D2,Size); // if Sim2<>nil then Sim2^:=InvDistance(A2,D2,Size); end; procedure TWaveFormComputer.Init( const MaxTimeDelta, TimeDelta: Double; const Src1,Src2:TArrayOfSingle; i1,i2,ASize:Integer); var K,B:Double; Len,SL,SR:Integer; begin P2C.tf2:=(TimeDelta + MaxTimeDelta)*0.5; if P2C.tf2<0 then P2C.tf2:=0; P2C.tf1:=MaxTimeDelta - P2C.tf2; if P2C.tf1<0 then P2C.tf1:=0; Size:=ASize; //Inc(ASize); SetLength(Data1,ASize); D1:=@(Data1[0]); SetLength(Data2,ASize); D2:=@(Data2[0]); SetLength(Appr2,ASize); A2:=@(Appr2[0]); SL:=Size shr 1; SR:=Size-SL-1; { Len:=ASize*3 shr 1; CalcKB(@Src1[i1-Len],i1-Len,i1,@K,@B); DifferenceFromLine(K,B,@Src1[i1-SL],D1,i1-SL,i1+SR); CalcKB(@Src2[i2-Len],i2-Len,i2,@K,@B); DifferenceFromLine(K,B,@Src2[i2-SL],D2,i2-SL,i2+SR); //} //{ ExtractImpulse(@(Src1[i1-SL]),D1,ASize); ExtractImpulse(@(Src2[i2-SL]),D2,ASize); //} end; procedure TWaveFormComputer.GetDrawData(var dA2, dD2: TArrayOfSingle); var i:Integer; p1,p2:PSingle; begin // MakeHorizontal(A2,Size); // MakeHorizontal(D2,Size); SetLength(dA2,Size); SetLength(dD2,Size); p1:=A2; p2:=D2; for i:=0 to Size-1 do begin dA2[i]:=p1^; dD2[i]:=p2^; Inc(p1); Inc(p2); end; end; { TWaveP2Calculator } type TCoeffArray = array[0..255,0..1] of Double; var //[itf,t,...] CoeffsCache:array[0..255] of TCoeffArray; ExpTfCache:array[0..255] of Double; procedure InitCoeffsCache(const Alpha:Double); var st,step:Double; it,itf:Integer; begin for itf:=0 to High(CoeffsCache) do begin ExpTfCache[itf]:=exp(-Alpha*itf); for it:=1 to High(CoeffsCache[0]) do begin st:=sqrt(2.*itf*it+it*it); step:=Alpha*itf * exp(-Alpha*(itf+it)) * BesselI1(Alpha*st) / st; CoeffsCache[itf,it,0]:=1/(exp(-Alpha*itf)+step); CoeffsCache[itf,it,1]:=step; end; end; end; procedure CalcP2(tf1,tf2:Integer; P1,P2:PSingle; Len:Integer); var Int1,Int2,P0,kE:Double; FP1:Single; t:Integer; Coeff1,Coeff2:^TCoeffArray; begin Coeff1:=@CoeffsCache[tf1]; Int1:=0; Coeff2:=@CoeffsCache[tf2]; Int2:=0; kE:=ExpTfCache[tf2]; FP1:=P1^; P2^:=0; for t:=1 to Len-1 do begin Inc(P1); Inc(P2); P0:=(P1^-FP1-Int1)*Coeff1[t,0]; Int1:=Int1+P0*Coeff1[t,1]; Int2:=Int2+P0*Coeff2[t,1]; P2^:=P0*kE+Int2; end; end; function TWaveP2Calculator.iCalcP2(const t, P1: Double): Double; var st,step,P0:Double; it,itf1,itf2:Integer; begin it:=Round(t); itf1:=Round(tf1); itf2:=Round(tf2); if it=0 then begin Int1:=0; Int2:=0; Result:=P1*exp(Alpha2*itf1 - Alpha1*itf2); end else begin P0:=(P1-Int1)*CoeffsCache[itf1,it,0]; Int1:=Int1+P0*CoeffsCache[itf1,it,1]; // Int2:=Int2+P0*CoeffsCache[itf2,it,1]; Result:=P0*ExpTfCache[itf2] + Int2; end; end; function TWaveP2Calculator.CalcP2(const t, P1: Double): Double; var st,step,P0:Double; begin if t=0 then begin Int1:=0; Int2:=0; Result:=P1*exp(Alpha2*tf1 - Alpha1*tf2); end else begin st:=sqrt(2.*tf1*t+t*t); step:=Alpha2*tf1 * exp(-Alpha2*(tf1+t)) * BesselI1(Alpha2*st) / st; P0:=(P1-Int1)/(exp(-Alpha2*tf1)+step); Int1:=Int1+step*P0; // st:=sqrt(2.*tf2*t+t*t); step:=Alpha1*tf2 * exp(-Alpha1*(tf2+t)) * BesselI1(Alpha1*st) / st; Int2:=Int2+step*P0; Result:=P0*exp(-Alpha1*tf2) + Int2; end; end; //*) initialization InitCoeffsCache(0.018); end.
unit IPGeoLocation.Providers.IPStack; interface uses IPGeoLocation.Interfaces, IPGeoLocation.Core, System.Net.HttpClient; type {$REGION 'TIPGeoLocationProviderIPStack'} TIPGeoLocationProviderIPStack = class sealed(TIPGeoLocationProviderCustom) private { private declarations } protected { protected declarations } function GetRequest: IIPGeoLocationRequest; override; public { public declarations } constructor Create(pParent: IIPGeoLocation; const pIP: string); override; end; {$ENDREGION} {$REGION 'TIPGeoLocationResponseIPStack'} TIPGeoLocationResponseIPStack = class sealed(TIPGeoLocationResponseCustom) private { private declarations } protected { protected declarations } procedure Parse; override; public { public declarations } end; {$ENDREGION} {$REGION 'TIPGeoLocationRequestIPStack'} TIPGeoLocationRequestIPStack = class sealed(TIPGeoLocationRequestCustom) private { private declarations } protected { protected declarations } function InternalExecute: IHTTPResponse; override; function GetResponse(pIHTTPResponse: IHTTPResponse): IGeoLocation; override; public { public declarations } constructor Create(pParent: IIPGeoLocationProvider; const pIP: string); override; end; {$ENDREGION} implementation uses System.JSON, System.SysUtils, System.Net.URLClient, IPGeoLocation.Types; {$I APIKey.inc} {$REGION 'TIPGeoLocationProviderIPStack'} constructor TIPGeoLocationProviderIPStack.Create(pParent: IIPGeoLocation; const pIP: string); begin inherited Create(pParent, pIP); FID := '#IPSTACK'; FURL := 'http://api.ipstack.com'; FAPIKey := APIKey_IPStack; //TOKEN FROM APIKey.inc end; function TIPGeoLocationProviderIPStack.GetRequest: IIPGeoLocationRequest; begin Result := TIPGeoLocationRequestIPStack.Create(Self, FIP); end; {$ENDREGION} {$REGION 'TIPGeoLocationResponseIPStack'} procedure TIPGeoLocationResponseIPStack.Parse; var lJSONObject: TJSONObject; begin lJSONObject := nil; try lJSONObject := TJSONObject.ParseJSONValue(FJSON) as TJSONObject; if not Assigned(lJSONObject) then Exit; lJSONObject.TryGetValue('hostname', FHostName); lJSONObject.TryGetValue('country_code', FCountryCode); lJSONObject.GetValue('location').TryGetValue('country_flag', FCountryFlag); lJSONObject.TryGetValue('country_name', FCountryName); lJSONObject.TryGetValue('region_name', FState); lJSONObject.TryGetValue('city', FCity); lJSONObject.TryGetValue('zip', FZipCode); lJSONObject.TryGetValue('isp', FISP); lJSONObject.TryGetValue('latitude', FLatitude); lJSONObject.TryGetValue('longitude', FLongitude); finally lJSONObject.Free; end; end; {$ENDREGION} {$REGION 'TIPGeoLocationRequestIPStack'} constructor TIPGeoLocationRequestIPStack.Create(pParent: IIPGeoLocationProvider; const pIP: string); begin inherited Create(pParent, pIP); FResponseLanguageCode := 'en'; //English/US end; function TIPGeoLocationRequestIPStack.GetResponse( pIHTTPResponse: IHTTPResponse): IGeoLocation; begin Result := TIPGeoLocationResponseIPStack.Create(pIHTTPResponse.ContentAsString, FIP, FProvider); end; function TIPGeoLocationRequestIPStack.InternalExecute: IHTTPResponse; var lURL: TURI; lJSONObject: TJSONObject; lRequestSuccessAPI: Boolean; begin //CONFORME A DOCUMENTAÇÃO DA API lURL := TURI.Create(Format('%s/%s', [FIPGeoLocationProvider.URL, FIP])); lURL.AddParameter('access_key', FIPGeoLocationProvider.APIKey); lURL.AddParameter('language', FResponseLanguageCode); lURL.AddParameter('output', 'json'); lURL.AddParameter('hostname', '1'); FHttpRequest.URL := lURL.ToString; //REQUISIÇÃO Result := inherited InternalExecute; lJSONObject := nil; try lJSONObject := TJSONObject.ParseJSONValue(Result.ContentAsString) as TJSONObject; //CONFORME A DOCUMENTAÇÃO DA API if not lJSONObject.TryGetValue('success', lRequestSuccessAPI) then Exit; if (lRequestSuccessAPI = False) then begin if Assigned(lJSONObject.GetValue('error')) then raise EIPGeoLocationException.Create(TIPGeoLocationExceptionKind.EXCEPTION_API, FIP, FProvider, Now(), lJSONObject.GetValue('error').ToJSON); end; finally lJSONObject.Free; end; end; {$ENDREGION} end.
{ $Id } { svnsync-like utility written with freepascal fpsvnsync synchronizes two svn repositories without the need to set revision properties. Copyright (C) 2007 Vincent Snijders (vincents@freepascal.org) This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } program fpsvnsync; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, FileUtil, SvnClasses, SvnCommand; type { TSvnMirrorApp } TSvnMirrorApp = class(TCustomApplication) private FSourceWC: string; FDestWC: string; function GetRevision(Directory: string): integer; function GetRepositoryRoot(Directory: string): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Run; end; { TSvnMirrorApp } function TSvnMirrorApp.GetRevision(Directory: string): integer; var SvnInfo: TSvnInfo; begin SvnInfo := TSvnInfo.Create(Directory); Result := SvnInfo.Entry.Revision; SvnInfo.Free; end; function TSvnMirrorApp.GetRepositoryRoot(Directory: string): string; var SvnInfo: TSvnInfo; begin SvnInfo := TSvnInfo.Create(Directory); Result := SvnInfo.Entry.Repository.Root; SvnInfo.Free; end; procedure TSvnMirrorApp.Run; var SourceHead: integer; Revision: integer; XmlOutput: TMemoryStream; //SvnResult: LongInt; SvnLog: TSvnLog; SubPath: string; DestRoot: string; procedure GetLog; var Command: string; begin writeln('Getting log message for revision ', Revision); Command := Format('log --xml -v -r%d %s', [Revision,FSourceWC]); SvnLog.LoadFromCommand(command); SvnLog.LogEntry[0].SortPaths; SubPath := SvnLog.LogEntry[0].CommonPath; writeln('Finding common path from log messages: ', SubPath); end; procedure UpdateWC(const WorkingDir, SubPath: string; Revision: integer); var Command: string; UpdatePath: string; RevisionStr: string; begin UpdatePath := WorkingDir+SubPath; if Revision > 0 then RevisionStr := IntToStr(Revision) else RevisionStr := 'HEAD'; writeln(format('Updating %s to revision %s', [UpdatePath, RevisionStr])); Command := Format('up -r%s %s', [RevisionStr, UpdatePath]); writeln('svn ', Command); writeln('Result: ', ExecuteSvnCommand(Command)); end; procedure GetDiff; var Command: string; Diff: TStrings; begin writeln('Getting diffs between revision ', Revision-1,' and ', Revision); Command := Format('diff -c%d %s', [Revision, FSourceWC+SubPath]); writeln('svn ', Command); XmlOutput.Clear; ExecuteSvnCommand(Command, XmlOutput); XmlOutput.Position := 0; Diff := TStringList.Create; Diff.LoadFromStream(XmlOutput); writeln('Diff contains ', Diff.Count, ' lines'); if pos('Property changes on', Diff.Text)>0 then begin writeln('Properties changed'); writeln(Diff.Text); Diff.Free; halt(1); end; Diff.Free; end; procedure DeleteFiles; var LogEntry: TLogEntry; LogPath: TLogPath; i: integer; DestFile: string; begin LogEntry := SvnLog.LogEntry[0]; for i := 0 to LogEntry.PathCount-1 do begin LogPath := LogEntry.Path[i]; if LogPath.Action=caDelete then begin DestFile := FDestWC + LogPath.Path; writeln('Deleting ', DestFile); ExecuteSvnCommand('delete '+DestFile); end; end; end; procedure CopyChanges; var LogEntry: TLogEntry; LogPath: TLogPath; i: integer; SourceFile, DestFile, Command: string; begin LogEntry := SvnLog.LogEntry[0]; for i := 0 to LogEntry.PathCount-1 do begin LogPath := LogEntry.Path[i]; DestFile := FDestWC + LogPath.Path; if LogPath.Action in [caModify, caAdd] then begin SourceFile := FSourceWC + LogPath.Path; if LogPath.CopyFromPath<>'' then begin if ExtractFileName(LogPath.CopyFromPath)=ExtractFileName(DestFile) then // to prevent that svn complains that the target is not a directory Command := format('copy "%1:s%2:s@%0:d" "%3:s"', [LogPath.CopyFromRevision, DestRoot, LogPath.CopyFromPath, ExtractFileDir(DestFile)]) else Command := format('copy "%1:s%2:s@%0:d" "%3:s"', [LogPath.CopyFromRevision, DestRoot, LogPath.CopyFromPath, DestFile]); writeln('svn '+ Command); ExecuteSvnCommand(Command); end; writeln('Copy ', SourceFile, ' to ', DestFile); if DirectoryExists(SourceFile) then ForceDirectory(DestFile) else CopyFile(SourceFile, DestFile, true); if LogPath.Action=caAdd then begin Command := format('add "%s"', [DestFile]); writeln(Command); writeln('Result: ',ExecuteSvnCommand(Command)); end; end; end; end; procedure ApplyPropChanges; var Files: TStrings; SourcePropInfo: TSvnPropInfo; DestPropInfo: TSvnPropInfo; SourceFileName: string; SourceFileProp: TSvnFileProp; DestFileName: string; DestFileProp: TSvnFileProp; i: Integer; function CreatePropInfo(const BaseDir: string): TSvnPropInfo; begin Result := TSvnPropInfo.Create; Files := SvnLog.LogEntry[0].GetFileList(BaseDir); Result.LoadForFiles(Files); Files.Free; end; procedure CopyFileProp(SourceProp, DestProp: TSvnFileProp); var j, pass: integer; IsSvnEolProp: boolean; Command: string; begin if SourceProp.Properties.Text=DestProp.Properties.Text then exit; writeln('Properties changed for ', DestProp.FileName); writeln('Source properties'); writeln(SourceProp.Properties.Text); writeln('Destination properties'); writeln(DestProp.Properties.Text); for j:=0 to DestProp.Properties.Count-1 do begin Command := format('propdel %s "%s"', [DestProp.Properties.Names[j], DestProp.FileName]); writeln('svn ', Command); writeln('svn result: ', ExecuteSvnCommand(Command)); end; // first pass set svn:eolstyle, later it might not be possible // because of the mime style is non-text. for pass := 1 to 2 do begin for j:=0 to SourceProp.Properties.Count-1 do begin // if there is no value, don't set the property if (SourceProp.Properties.ValueFromIndex[j]='') then continue; IsSvnEolProp := SourceProp.Properties.Names[j]='svn:eol-style'; if ((pass=1) and (IsSvnEolProp=true)) or ((pass=2) and (IsSvnEolProp=false)) then begin Command := format('propset %s "%s" "%s"', [SourceProp.Properties.Names[j], SourceProp.Properties.ValueFromIndex[j], DestProp.FileName]); writeln('svn ', Command); writeln('svn result: ', ExecuteSvnCommand(Command)); end; end; end; end; begin SourcePropInfo := CreatePropInfo(FSourceWC); DestPropInfo := CreatePropInfo(FDestWC); Files := SvnLog.LogEntry[0].GetFileList(''); if SourcePropInfo.FileCount<>Files.Count then begin writeln('Source FileName number mismatch: ', SourcePropInfo.FileCount, '<>', Files.Count); for i := 0 to SourcePropInfo.FileCount - 1 do writeln('Source ',i ,': ',SourcePropInfo.FileItem[i].FileName); halt(2); end; if DestPropInfo.FileCount<>Files.Count then begin writeln('Destination FileName number mismatch: ', DestPropInfo.FileCount, '<>', Files.Count); for i := 0 to DestPropInfo.FileCount - 1 do writeln('Dest ',i ,': ',DestPropInfo.FileItem[i].FileName); halt(2); end; for i := 0 to Files.Count-1 do begin SourceFileName := FSourceWC + Files[i]; DestFileName := FDestWC + Files[i]; SourceFileProp := SourcePropInfo.GetFileItem(SourceFileName); DestFileProp := DestPropInfo.GetFileItem(DestFileName); if SourceFileProp=nil then begin writeln('Missing source file properties for ', SourceFileName); halt(3); end; if DestFileProp=nil then begin writeln('Missing destination file properties for ', DestFileName); halt(3); end; CopyFileProp(SourceFileProp, DestFileProp); end; Files.Free; SourcePropInfo.Free; DestPropInfo.Free; end; procedure CommitChanges; var Command: string; MessageFile: string; Message: TStrings; LogEntry: TLogEntry; begin writeln('Commit to destination'); LogEntry := SvnLog.LogEntry[0]; MessageFile := SysUtils.GetTempFileName; Message := TStringList.Create; Message.Add(SvnLog.LogEntry[0].Message); Message.Add( Format('Commited by %s at %s', [LogEntry.Author, LogEntry.DisplayDate])); Message.SaveToFile(MessageFile); writeln(Message.Text); Message.Free; Command := Format('commit -F "%s" "%s"', [MessageFile, FDestWC+LogEntry.CommonPath]); writeln('svn ', Command); writeln('svn commit result: ', ExecuteSvnCommand(Command)); DeleteFile(MessageFile); end; begin try SourceHead := GetRevision('-rHEAD '+FSourceWC); writeln(FSourceWC, ' HEAD at revision ', SourceHead); Revision := GetRevision('-rHEAD '+FDestWC); writeln(FDestWC, ' HEAD at revision ', Revision); DestRoot := GetRepositoryRoot(FDestWC); writeln('------'); except on E: Exception do begin writeln(E.Message); halt(9); end; end; XmlOutput := TMemoryStream.Create; SvnLog := TSvnLog.Create; while (Revision<SourceHead) do begin inc(Revision); GetLog; UpdateWC(FDestWC, SvnLog.LogEntry[0].CommonPath, Revision-1); UpdateWC(FSourceWC, SvnLog.LogEntry[0].CommonPath, Revision); writeln('Doing adds/deletes'); DeleteFiles; CopyChanges; //GetDiff; ApplyPropChanges; CommitChanges; writeln; end; XmlOutput.Free; SvnLog.Free; end; constructor TSvnMirrorApp.Create(AOwner: TComponent); begin inherited Create(AOwner); if ParamCount=2 then begin FSourceWC := ParamStr(1); FDestWC := ParamStr(2); end else begin FSourceWC := 'd:\lazarus\lazmirror\source'; FDestWC := 'd:\lazarus\lazmirror\dest'; FSourceWC := 'C:\lazarus\lazmirror\source'; FDestWC := 'C:\lazarus\lazmirror\dest'; end; end; destructor TSvnMirrorApp.Destroy; begin inherited Destroy; end; var SvnMirrorApp: TSvnMirrorApp; begin SvnMirrorApp := TSvnMirrorApp.Create(nil); try SvnMirrorApp.Run; finally SvnMirrorApp.Free; end; end.
unit vcmBaseCollectionItem; // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Components\vcmBaseCollectionItem.pas" // Стереотип: "SimpleClass" // Элемент модели: "TvcmBaseCollectionItem" MUID: (4FFC3347011F) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM)} uses l3IntfUses , vcmPrimCollectionItem , Classes //#UC START# *4FFC3347011Fintf_uses* //#UC END# *4FFC3347011Fintf_uses* ; type TvcmBaseCollectionItemPrim = class(TvcmPrimCollectionItem) private f_Name: AnsiString; f_Caption: AnsiString; protected function pm_GetName: AnsiString; procedure pm_SetName(const aValue: AnsiString); function pm_GetCaption: AnsiString; virtual; procedure pm_SetCaption(const aValue: AnsiString); virtual; procedure SetCaptionFromName(const aName: AnsiString); virtual; procedure NameChanged; virtual; procedure DoSetCaption(const aName: AnsiString); procedure ChangeName(const anOld: AnsiString; const aNew: AnsiString); virtual; procedure ChangeCaption(const anOld: AnsiString; const aNew: AnsiString); virtual; procedure CaptionChanged; virtual; function GetCaptionStored: Boolean; virtual; function CaptionStored: Boolean; {* Функция определяющая, что свойство Caption сохраняется } procedure BeforeAddToCache; override; {* функция, вызываемая перед добавлением объекта в кэш повторного использования. } function GetDisplayName: String; override; function GetNamePath: String; override; procedure ClearFields; override; public function MakeID(const aName: AnsiString): Integer; virtual; function GetID: Integer; virtual; procedure Assign(Source: TPersistent); override; public property Name: AnsiString read pm_GetName write pm_SetName; property Caption: AnsiString read pm_GetCaption write pm_SetCaption stored CaptionStored; end;//TvcmBaseCollectionItemPrim //#UC START# *4FFC3347011Fci* //#UC END# *4FFC3347011Fci* //#UC START# *4FFC3347011Fcit* //#UC END# *4FFC3347011Fcit* TvcmBaseCollectionItem = class(TvcmBaseCollectionItemPrim) //#UC START# *4FFC3347011Fpubl* published property Caption; property Name; //#UC END# *4FFC3347011Fpubl* end;//TvcmBaseCollectionItem {$IfEnd} // NOT Defined(NoVCM) implementation {$If NOT Defined(NoVCM)} uses l3ImplUses , vcmBaseCollection {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *4FFC3347011Fimpl_uses* , SysUtils , RTLConsts //#UC END# *4FFC3347011Fimpl_uses* ; function TvcmBaseCollectionItemPrim.pm_GetName: AnsiString; //#UC START# *55CCB8960010_55D076150061get_var* //#UC END# *55CCB8960010_55D076150061get_var* begin //#UC START# *55CCB8960010_55D076150061get_impl* Result := f_Name; //#UC END# *55CCB8960010_55D076150061get_impl* end;//TvcmBaseCollectionItemPrim.pm_GetName procedure TvcmBaseCollectionItemPrim.pm_SetName(const aValue: AnsiString); //#UC START# *55CCB8960010_55D076150061set_var* //#UC END# *55CCB8960010_55D076150061set_var* begin //#UC START# *55CCB8960010_55D076150061set_impl* if (f_Name <> aValue) then begin {$IfDef DesignTimeLibrary} if (aValue <> '') and not IsValidIdent(aValue) then raise EComponentError.CreateResFmt(@SInvalidName, [aValue]); {$EndIf DesignTimeLibrary} ChangeName(f_Name, aValue); SetCaptionFromName(aValue); f_Name := aValue; NameChanged; end;//f_Name <> aName //#UC END# *55CCB8960010_55D076150061set_impl* end;//TvcmBaseCollectionItemPrim.pm_SetName function TvcmBaseCollectionItemPrim.pm_GetCaption: AnsiString; //#UC START# *55CCB95D0197_55D076150061get_var* //#UC END# *55CCB95D0197_55D076150061get_var* begin //#UC START# *55CCB95D0197_55D076150061get_impl* Result := f_Caption; //#UC END# *55CCB95D0197_55D076150061get_impl* end;//TvcmBaseCollectionItemPrim.pm_GetCaption procedure TvcmBaseCollectionItemPrim.pm_SetCaption(const aValue: AnsiString); //#UC START# *55CCB95D0197_55D076150061set_var* //#UC END# *55CCB95D0197_55D076150061set_var* begin //#UC START# *55CCB95D0197_55D076150061set_impl* if (Caption <> aValue) then DoSetCaption(aValue); //#UC END# *55CCB95D0197_55D076150061set_impl* end;//TvcmBaseCollectionItemPrim.pm_SetCaption procedure TvcmBaseCollectionItemPrim.SetCaptionFromName(const aName: AnsiString); //#UC START# *55CCB9830041_55D076150061_var* //#UC END# *55CCB9830041_55D076150061_var* begin //#UC START# *55CCB9830041_55D076150061_impl* if (Name = Caption) then Caption := aName; //#UC END# *55CCB9830041_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.SetCaptionFromName procedure TvcmBaseCollectionItemPrim.NameChanged; //#UC START# *55CCBA65014E_55D076150061_var* //#UC END# *55CCBA65014E_55D076150061_var* begin //#UC START# *55CCBA65014E_55D076150061_impl* //#UC END# *55CCBA65014E_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.NameChanged procedure TvcmBaseCollectionItemPrim.DoSetCaption(const aName: AnsiString); //#UC START# *55CCB9A30160_55D076150061_var* //#UC END# *55CCB9A30160_55D076150061_var* begin //#UC START# *55CCB9A30160_55D076150061_impl* ChangeCaption(Caption, aName); f_Caption := aName; CaptionChanged; //#UC END# *55CCB9A30160_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.DoSetCaption procedure TvcmBaseCollectionItemPrim.ChangeName(const anOld: AnsiString; const aNew: AnsiString); //#UC START# *55CCBA3C0190_55D076150061_var* //#UC END# *55CCBA3C0190_55D076150061_var* begin //#UC START# *55CCBA3C0190_55D076150061_impl* //#UC END# *55CCBA3C0190_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.ChangeName function TvcmBaseCollectionItemPrim.MakeID(const aName: AnsiString): Integer; //#UC START# *55CCBAAB00F4_55D076150061_var* //#UC END# *55CCBAAB00F4_55D076150061_var* begin //#UC START# *55CCBAAB00F4_55D076150061_impl* Assert(false, 'Данная коллекция не поддерживает поиска элемента по идентификатору'); Result := -1; //#UC END# *55CCBAAB00F4_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.MakeID function TvcmBaseCollectionItemPrim.GetID: Integer; //#UC START# *55CCBAC800F0_55D076150061_var* //#UC END# *55CCBAC800F0_55D076150061_var* begin //#UC START# *55CCBAC800F0_55D076150061_impl* Assert(false, 'Данная коллекция не поддерживает поиска элемента по идентификатору'); Result := -1; //#UC END# *55CCBAC800F0_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.GetID procedure TvcmBaseCollectionItemPrim.ChangeCaption(const anOld: AnsiString; const aNew: AnsiString); //#UC START# *55CCBA8003C7_55D076150061_var* //#UC END# *55CCBA8003C7_55D076150061_var* begin //#UC START# *55CCBA8003C7_55D076150061_impl* //#UC END# *55CCBA8003C7_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.ChangeCaption procedure TvcmBaseCollectionItemPrim.CaptionChanged; //#UC START# *55CCBA910119_55D076150061_var* //#UC END# *55CCBA910119_55D076150061_var* begin //#UC START# *55CCBA910119_55D076150061_impl* if Assigned(Collection) then TvcmBaseCollection(Collection).CaptionChanged(Self); //#UC END# *55CCBA910119_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.CaptionChanged function TvcmBaseCollectionItemPrim.GetCaptionStored: Boolean; //#UC START# *55CCBA0103DE_55D076150061_var* //#UC END# *55CCBA0103DE_55D076150061_var* begin //#UC START# *55CCBA0103DE_55D076150061_impl* Result := (Caption <> Name); //#UC END# *55CCBA0103DE_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.GetCaptionStored function TvcmBaseCollectionItemPrim.CaptionStored: Boolean; {* Функция определяющая, что свойство Caption сохраняется } //#UC START# *55CCB95D0197Stored_55D076150061_var* //#UC END# *55CCB95D0197Stored_55D076150061_var* begin //#UC START# *55CCB95D0197Stored_55D076150061_impl* Result := GetCaptionStored; //#UC END# *55CCB95D0197Stored_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.CaptionStored procedure TvcmBaseCollectionItemPrim.Assign(Source: TPersistent); //#UC START# *478CF34E02CE_55D076150061_var* //#UC END# *478CF34E02CE_55D076150061_var* begin //#UC START# *478CF34E02CE_55D076150061_impl* if (Source is TvcmBaseCollectionItem) then begin Name := TvcmBaseCollectionItem(Source).Name; Caption := TvcmBaseCollectionItem(Source).Caption; end//P is TvcmBaseCollectionItem else inherited; //#UC END# *478CF34E02CE_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.Assign procedure TvcmBaseCollectionItemPrim.BeforeAddToCache; {* функция, вызываемая перед добавлением объекта в кэш повторного использования. } //#UC START# *479F2B3302C1_55D076150061_var* //#UC END# *479F2B3302C1_55D076150061_var* begin //#UC START# *479F2B3302C1_55D076150061_impl* inherited; f_Name := ''; f_Caption := ''; //#UC END# *479F2B3302C1_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.BeforeAddToCache function TvcmBaseCollectionItemPrim.GetDisplayName: String; //#UC START# *55CCBB5A01E5_55D076150061_var* //#UC END# *55CCBB5A01E5_55D076150061_var* begin //#UC START# *55CCBB5A01E5_55D076150061_impl* Result := Caption; //#UC END# *55CCBB5A01E5_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.GetDisplayName function TvcmBaseCollectionItemPrim.GetNamePath: String; //#UC START# *55CCBC12038F_55D076150061_var* var l_Owner: TPersistent; //#UC END# *55CCBC12038F_55D076150061_var* begin //#UC START# *55CCBC12038F_55D076150061_impl* if (Name = '') then Result := inherited GetNamePath else begin Result := Name; if (Collection <> nil) then begin l_Owner := Collection.Owner; if (l_Owner is TvcmBaseCollectionItem) then Result := TvcmBaseCollectionItem(l_Owner).Name + '.' + Result else if (l_Owner is TComponent) then Result := TComponent(l_Owner).Name + '.' + Result else Result := Collection.GetNamePath + '.' + Result; end;//Collection <> nil end;//Name = '' //#UC END# *55CCBC12038F_55D076150061_impl* end;//TvcmBaseCollectionItemPrim.GetNamePath procedure TvcmBaseCollectionItemPrim.ClearFields; begin Name := ''; Caption := ''; inherited; end;//TvcmBaseCollectionItemPrim.ClearFields //#UC START# *4FFC3347011Fimpl* //#UC END# *4FFC3347011Fimpl* initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TvcmBaseCollectionItemPrim); {* Регистрация TvcmBaseCollectionItemPrim } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TvcmBaseCollectionItem); {* Регистрация TvcmBaseCollectionItem } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // NOT Defined(NoVCM) end.
{ ********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ******************************************************************** } unit FGX.Toasts.iOS; interface uses System.UITypes, System.Generics.Collections, System.TypInfo, Macapi.ObjectiveC, iOSapi.UIKit, iOSapi.Foundation, FGX.Toasts; type TfgiOSToast = class; IFGXToastsQueue = interface(NSObject) ['{D5FBE77D-447D-47E5-A4C4-D3D81EAEAF47}'] procedure ShouldHide; cdecl; procedure ToastDisappeared; cdecl; end; TiOSToastsQueue = class(TOCLocal) private FToasts: TObjectList<TfgiOSToast>; FShowingToast: Boolean; [Weak] FActiveToast: TfgiOSToast; protected function GetObjectiveCClass: PTypeInfo; override; public constructor Create; destructor Destroy; override; procedure EnqueueToast(const AToast: TfgiOSToast); procedure DequeueToast(const AToast: TfgiOSToast); procedure ShowNextToast; { IFGXToastsQueue } procedure ShouldHide; cdecl; procedure ToastDisappeared; cdecl; end; { TfgiOSToast } TfgiOSToast = class(TfgToast) public const DefaultMessageFontSize = 13; DefaultCornerRadius = 3; private FBackgroundView: UIView; FIconView: UIImageView; FMessageView: UILabel; protected procedure Realign; { inherited } procedure DoBackgroundColorChanged; override; procedure DoMessageChanged; override; procedure DoMessageColorChanged; override; procedure DoIconChanged; override; public constructor Create(const AMessage: string; const ADuration: TfgToastDuration); destructor Destroy; override; property ToastView: UIView read FBackgroundView; property MessageView: UILabel read FMessageView; property IconView: UIImageView read FIconView; end; { TfgiOSToastService } TfgiOSToastService = class(TInterfacedObject, IFGXToastService) public { IFGXToastService } function CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; procedure Show(const AToast: TfgToast); procedure Cancel(const AToast: TfgToast); end; TfgToastDurationHelper = record helper for TfgToastDuration public function ToDuration: Single; // secs end; procedure RegisterService; procedure UnregisterService; implementation uses System.SysUtils, System.Types, iOSapi.CoreGraphics, Macapi.ObjCRuntime, Macapi.Helpers, FMX.Forms, FMX.Platform, FMX.Helpers.iOS, FGX.Asserts, FGX.Helpers.iOS; var ToastsQueue: TiOSToastsQueue; procedure RegisterService; begin ToastsQueue := TiOSToastsQueue.Create; TPlatformServices.Current.AddPlatformService(IFGXToastService, TfgiOSToastService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXToastService); FreeAndNil(ToastsQueue); end; { TfgiOSToastService } procedure TfgiOSToastService.Cancel(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgiOSToast); ToastsQueue.DequeueToast(TfgiOSToast(AToast)); end; function TfgiOSToastService.CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; begin Result := TfgiOSToast.Create(AMessage, ADuration); end; procedure TfgiOSToastService.Show(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgiOSToast); ToastsQueue.EnqueueToast(TfgiOSToast(AToast)); end; { TfgToastDurationHelper } function TfgToastDurationHelper.ToDuration: Single; begin case Self of TfgToastDuration.Short: Result := 3; TfgToastDuration.Long: Result := 5; else Result := 3; end; end; { TfgiOSToast } constructor TfgiOSToast.Create(const AMessage: string; const ADuration: TfgToastDuration); begin inherited Create; FBackgroundView := TUIView.Create; FBackgroundView.addSubview(FIconView); FBackgroundView.setBackgroundColor(AlphaColorToUIColor(TfgToast.DefaultBackgroundColor)); FBackgroundView.setOpaque(True); FBackgroundView.setAlpha(0); FBackgroundView.layer.setCornerRadius(DefaultCornerRadius); FIconView := TUIImageView.Create; FBackgroundView.addSubview(FIconView); FMessageView := TUILabel.Create; FMessageView.setText(StrToNSStr(AMessage)); FMessageView.setFont(FMessageView.font.fontWithSize(DefaultMessageFontSize)); FMessageView.setTextColor(AlphaColorToUIColor(TfgToast.DefaultMessageColor)); FBackgroundView.addSubview(FMessageView); // Adding Shadow to application SharedApplication.keyWindow.rootViewController.view.AddSubview(FBackgroundView); Realign; Duration := ADuration; end; destructor TfgiOSToast.Destroy; begin FBackgroundView.removeFromSuperview; inherited; end; procedure TfgiOSToast.DoBackgroundColorChanged; begin AssertIsNotNil(FBackgroundView); inherited; FBackgroundView.setBackgroundColor(AlphaColorToUIColor(BackgroundColor)); end; procedure TfgiOSToast.DoIconChanged; begin AssertIsNotNil(FIconView); AssertIsNotNil(Icon); inherited; FIconView.setImage(BitmapToUIImage(Icon)); Realign; end; procedure TfgiOSToast.DoMessageChanged; begin AssertIsNotNil(FMessageView); inherited; FMessageView.setText(StrToNSStr(Message)); end; procedure TfgiOSToast.DoMessageColorChanged; begin AssertIsNotNil(FMessageView); inherited; FMessageView.setTextColor(AlphaColorToUIColor(MessageColor)); end; procedure TfgiOSToast.Realign; const ToastMargins = 30; IconMargins = 5; var BackgroundRect: TRectF; begin AssertIsNotNil(FMessageView); AssertIsNotNil(FBackgroundView); AssertIsNotNil(FIconView); FMessageView.sizeToFit; { Background View } BackgroundRect := TRectF.Create(TPointF.Zero, FMessageView.bounds.Width, FMessageView.bounds.Height); if HasIcon then BackgroundRect.Width := BackgroundRect.Width + BackgroundRect.Height + IconMargins; BackgroundRect.Inflate(TfgToast.DefaultPadding.Left, TfgToast.DefaultPadding.Top, TfgToast.DefaultPadding.Right, TfgToast.DefaultPadding.Bottom); BackgroundRect.SetLocation(Screen.Size.Width / 2 - BackgroundRect.Width / 2, Screen.Size.Height - BackgroundRect.Height - ToastMargins); FBackgroundView.setFrame(CGRectFromRect(BackgroundRect)); { Icon View } if HasIcon then begin FIconView.setFrame(CGRectMake(TfgToast.DefaultPadding.Left, TfgToast.DefaultPadding.Top, FMessageView.bounds.Height, FMessageView.bounds.Height)); FMessageView.setFrame(CGRectMake(FIconView.frame.origin.x + FIconView.frame.size.width + IconMargins, TfgToast.DefaultPadding.Top, FMessageView.bounds.Width, FMessageView.bounds.Height)); end else begin FIconView.setFrame(CGRectMake(TfgToast.DefaultPadding.Left, TfgToast.DefaultPadding.Top, 0, 0)); FMessageView.setFrame(CGRectMake(TfgToast.DefaultPadding.Left, TfgToast.DefaultPadding.Top, FMessageView.bounds.Width, FMessageView.bounds.Height)); end; end; { TiOSToastStack } procedure TiOSToastsQueue.EnqueueToast(const AToast: TfgiOSToast); begin AssertIsNotNil(AToast); FToasts.Add(AToast); ShowNextToast; end; constructor TiOSToastsQueue.Create; begin inherited; FToasts := TObjectList<TfgiOSToast>.Create; FShowingToast := False; end; destructor TiOSToastsQueue.Destroy; begin FreeAndNil(FToasts); inherited; end; procedure TiOSToastsQueue.ShouldHide; begin AssertIsNotNil(FActiveToast); DequeueToast(FActiveToast); end; function TiOSToastsQueue.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IFGXToastsQueue); end; procedure TiOSToastsQueue.DequeueToast(const AToast: TfgiOSToast); begin AssertIsNotNil(AToast); // if toast is already displayed, we hide it. if AToast = FActiveToast then begin FShowingToast := False; FadeOut(AToast.ToastView, DEFAULT_ANIMATION_DURATION, GetObjectID, 'ToastDisappeared'); end else FToasts.Remove(FActiveToast); end; procedure TiOSToastsQueue.ShowNextToast; begin if (FToasts.Count > 0) and not FShowingToast then begin FShowingToast := True; FActiveToast := FToasts[0]; FadeIn(FActiveToast.ToastView); NSObject(Super).performSelector(sel_getUid('ShouldHide'), GetObjectID, FActiveToast.Duration.ToDuration + DEFAULT_ANIMATION_DURATION); end; end; procedure TiOSToastsQueue.ToastDisappeared; begin AssertIsNotNil(FActiveToast); FToasts.Remove(FActiveToast); FActiveToast := nil; ShowNextToast; end; end.
{******************************************************************************* Author: Pavel Skuratovich (aka Chupaka), Minsk, Belarus Description: Implementation of MikroTik RouterOS API Client Version: 1.3 E-Mail: chupaka@gmail.com Support: http://forum.mikrotik.com/viewtopic.php?t=31555 Dependencies: Uses Ararat Synapse Library (http://synapse.ararat.cz/) Legal issues: Copyright © by Pavel Skuratovich This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ******************************************************************************** API over TLS notes: Added in RouterOS v6.1. Only TLS without certificate is currently supported. Add 'ssl_openssl' to your project uses (http://synapse.ararat.cz/doku.php/public:howto:sslplugin) and then call TRosApiClient.SSLConnect() instead of TRosApiClient.Connect() ******************************************************************************** Version history: 1.3 June 04, 2018 Added support for RouterOS 6.43+ API login method 1.2 June 12, 2013 Added basic support for API over TLS 1.1 November 5, 2009 Delphi 2009 compatibility (thanks to Anton Ekermans for testing) Requires Synapse Release 39 1.0 May 1, 2009 First public release 0.1 April 18, 2009 Unit was rewritten to implement database-like interface 0.0 May 10, 2008 The beginning *******************************************************************************} unit RouterOSAPI; interface uses SysUtils, Classes, StrUtils, blcksock, synautil, synsock, synacode; type TRosApiWord = record Name, Value: AnsiString; end; TRosApiSentence = array of TROSAPIWord; TRosApiClient = class; TRosApiResult = class private Client: TROSAPIClient; Tag: AnsiString; Sentences: array of TRosApiSentence; FTrap: Boolean; FTrapMessage: AnsiString; FDone: Boolean; constructor Create; function GetValueByName(const Name: AnsiString): AnsiString; function GetValues: TRosApiSentence; function GetEof: Boolean; function GetRowsCount: Integer; public property ValueByName[const Name: AnsiString]: AnsiString read GetValueByName; default; property Values: TRosApiSentence read GetValues; function GetOne(const Wait: Boolean): Boolean; function GetAll: Boolean; property RowsCount: Integer read GetRowsCount; property Eof: Boolean read GetEof; property Trap: Boolean read FTrap; property Done: Boolean read FDone; procedure Next; procedure Cancel; end; TRosApiClient = class private FNextTag: Cardinal; FSock: TTCPBlockSocket; FTimeout: Integer; FLastError: AnsiString; Sentences: array of TRosApiSentence; function SockRecvByte(out b: Byte; const Wait: Boolean = True): Boolean; function SockRecvBufferStr(Length: Cardinal): AnsiString; procedure SendWord(s: AnsiString); function RecvWord(const Wait: Boolean; out w: AnsiString): Boolean; function RecvSentence(const Wait: Boolean; out se: TROSAPISentence): Boolean; function GetSentenceWithTag(const Tag: AnsiString; const Wait: Boolean; out Sentence: TROSAPISentence): Boolean; procedure ClearSentenceTag(var Sentence: TRosApiSentence); function DoLogin(const Username, Password: AnsiString): Boolean; public function Connect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8728'): Boolean; function SSLConnect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8729'): Boolean; function Query(const Request: array of AnsiString; const GetAllAfterQuery: Boolean): TROSAPIResult; function Execute(const Request: array of AnsiString): Boolean; property Timeout: Integer read FTimeout write FTimeout; property LastError: AnsiString read FLastError; constructor Create; destructor Destroy; override; procedure Disconnect; function GetWordValueByName(Sentence: TROSAPISentence; Name: AnsiString; RaiseErrorIfNotFound: Boolean = False): AnsiString; end; implementation {******************************************************************************} function HexToStr(hex: AnsiString): AnsiString; const Convert: array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); var i: Integer; begin Result := ''; if Length(hex) mod 2 <> 0 then raise Exception.Create('Invalid hex value') at @HexToStr; SetLength(Result, Length(hex) div 2); for i := 1 to Length(hex) div 2 do begin if not (hex[i * 2 - 1] in ['0'..'9', 'a'..'f']) or not (hex[i * 2] in ['0'..'9', 'a'..'f']) then raise Exception.Create('Invalid hex value') at @HexToStr; Result[i] := AnsiChar((Convert[hex[i * 2 - 1]] shl 4) + Convert[hex[i * 2]]); end; end; {******************************************************************************} constructor TRosApiResult.Create; begin inherited Create; FTrap := False; FTrapMessage := ''; FDone := False; SetLength(Sentences, 0); end; {******************************************************************************} constructor TRosApiClient.Create; begin inherited Create; FNextTag := 1; FTimeout := 30000; FLastError := ''; FSock := TTCPBlockSocket.Create; end; {******************************************************************************} destructor TRosApiClient.Destroy; begin FSock.Free; inherited Destroy; end; {******************************************************************************} function TRosApiClient.Connect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8728'): Boolean; begin FLastError := ''; FSock.CloseSocket; FSock.LineBuffer := ''; FSock.Connect(Hostname, Port); Result := FSock.LastError = 0; FLastError := FSock.LastErrorDesc; if not Result then Exit; Result := DoLogin(Username, Password); end; {******************************************************************************} function TRosApiClient.SSLConnect(const Hostname, Username, Password: AnsiString; const Port: AnsiString = '8729'): Boolean; begin if FSock.SSL.LibName = 'ssl_none' then begin FLastError := 'No SSL/TLS support compiled'; Result := False; Exit; end; FLastError := ''; FSock.CloseSocket; FSock.LineBuffer := ''; FSock.Connect(Hostname, Port); Result := FSock.LastError = 0; FLastError := FSock.LastErrorDesc; if not Result then Exit; FSock.SSL.Ciphers := 'ADH'; FSock.SSL.SSLType := LT_TLSv1; FSock.SSLDoConnect; Result := FSock.LastError = 0; FLastError := FSock.LastErrorDesc; if not Result then Exit; Result := DoLogin(Username, Password); end; {******************************************************************************} function TRosApiClient.DoLogin(const Username, Password: AnsiString): Boolean; var Res, Res2: TRosApiResult; begin Result := False; // post-6.43 login method Res := Query(['/login', '=name=' + Username, '=password=' + Password], True); if Res.Trap then // login error FSock.CloseSocket else if Res.Done then begin if High(Res.Sentences) <> -1 then begin // fallback to pre-6.43 login method Res2 := Query(['/login', '=name=' + Username, '=response=00' + StrToHex(MD5(#0 + Password + HexToStr(Res['=ret'])))], True); if Res2.Trap then FSock.CloseSocket else Result := True; Res2.Free; end else Result := True; end else raise Exception.Create('Invalid response: ''' + Res.Values[0].Name + ''', expected ''!done'''); Res.Free; end; {******************************************************************************} procedure TRosApiClient.Disconnect; begin FSock.CloseSocket; FSock.LineBuffer := ''; end; {******************************************************************************} function TRosApiClient.SockRecvByte(out b: Byte; const Wait: Boolean = True): Boolean; begin Result := True; if Wait then b := FSock.RecvByte(FTimeout) else b := FSock.RecvByte(0); if (FSock.LastError = WSAETIMEDOUT) and (not Wait) then Result := False; if (FSock.LastError = WSAETIMEDOUT) and Wait then raise Exception.Create('Socket recv timeout in SockRecvByte'); end; {******************************************************************************} function TRosApiClient.SockRecvBufferStr(Length: Cardinal): AnsiString; begin Result := FSock.RecvBufferStr(Length, FTimeout); if FSock.LastError = WSAETIMEDOUT then begin Result := ''; raise Exception.Create('Socket recv timeout in SockRecvBufferStr'); end; end; {******************************************************************************} procedure TRosApiClient.SendWord(s: AnsiString); var l: Cardinal; begin l := Length(s); if l < $80 then FSock.SendByte(l) else if l < $4000 then begin l := l or $8000; FSock.SendByte((l shr 8) and $ff); FSock.SendByte(l and $ff); end else if l < $200000 then begin l := l or $c00000; FSock.SendByte((l shr 16) and $ff); FSock.SendByte((l shr 8) and $ff); FSock.SendByte(l and $ff); end else if l < $10000000 then begin l := l or $e0000000; FSock.SendByte((l shr 24) and $ff); FSock.SendByte((l shr 16) and $ff); FSock.SendByte((l shr 8) and $ff); FSock.SendByte(l and $ff); end else begin FSock.SendByte($f0); FSock.SendByte((l shr 24) and $ff); FSock.SendByte((l shr 16) and $ff); FSock.SendByte((l shr 8) and $ff); FSock.SendByte(l and $ff); end; FSock.SendString(s); end; {******************************************************************************} function TRosApiClient.Query(const Request: array of AnsiString; const GetAllAfterQuery: Boolean): TROSAPIResult; var i: Integer; begin FLastError := ''; //Result := nil; // if not FSock.Connected then Exit; Result := TRosApiResult.Create; Result.Client := Self; Result.Tag := IntToHex(FNextTag, 4); Inc(FNextTag); for i := 0 to High(Request) do SendWord(Request[i]); SendWord('.tag=' + Result.Tag); SendWord(''); if GetAllAfterQuery then if not Result.GetAll then raise Exception.Create('Cannot GetAll: ' + LastError); end; {******************************************************************************} function TRosApiClient.RecvWord(const Wait: Boolean; out w: AnsiString): Boolean; var l: Cardinal; b: Byte; begin Result := False; if not SockRecvByte(b, Wait) then Exit; Result := True; l := b; if l >= $f8 then raise Exception.Create('Reserved control byte received, cannot proceed') else if (l and $80) = 0 then else if (l and $c0) = $80 then begin l := (l and not $c0) shl 8; SockRecvByte(b); l := l + b; end else if (l and $e0) = $c0 then begin l := (l and not $e0) shl 8; SockRecvByte(b); l := (l + b) shl 8; SockRecvByte(b); l := l + b; end else if (l and $f0) = $e0 then begin l := (l and not $f0) shl 8; SockRecvByte(b); l := (l + b) shl 8; SockRecvByte(b); l := (l + b) shl 8; SockRecvByte(b); l := l + b; end else if (l and $f8) = $f0 then begin SockRecvByte(b); l := b shl 8; SockRecvByte(b); l := (l + b) shl 8; SockRecvByte(b); l := (l + b) shl 8; SockRecvByte(b); l := l + b; end; w := SockRecvBufferStr(l); end; {******************************************************************************} function TRosApiClient.RecvSentence(const Wait: Boolean; out se: TROSAPISentence): Boolean; var p: Integer; w: AnsiString; begin repeat if RecvWord(Wait, w) then begin SetLength(se, 1); se[0].Name := w; end else begin Result := False; Exit; end; until w <> ''; repeat if RecvWord(True, w) then begin if w = '' then begin Result := True; Exit; end else begin SetLength(se, High(se) + 2); p := PosEx('=', w, 2); if p = 0 then se[High(se)].Name := w else begin se[High(se)].Name := Copy(w, 1, p - 1); se[High(se)].Value := Copy(w, p + 1, Length(w) - p); end; end; end else begin Result := False; Exit; end; until False; end; {******************************************************************************} function TRosApiClient.GetSentenceWithTag(const Tag: AnsiString; const Wait: Boolean; out Sentence: TROSAPISentence): Boolean; var i, j: Integer; se: TRosApiSentence; begin Result := False; for i := 0 to High(Sentences) do begin if GetWordValueByName(Sentences[i], '.tag') = Tag then begin Sentence := Sentences[i]; ClearSentenceTag(Sentence); for j := i to High(Sentences) - 1 do Sentences[j] := Sentences[j + 1]; SetLength(Sentences, High(Sentences)); Result := True; Exit; end; end; repeat if RecvSentence(Wait, se) then begin if GetWordValueByName(se, '.tag', True) = Tag then begin Sentence := se; ClearSentenceTag(Sentence); Result := True; Exit; end; SetLength(Sentences, High(Sentences) + 2); Sentences[High(Sentences)] := se; end else Exit; until False; end; {******************************************************************************} procedure TRosApiClient.ClearSentenceTag(var Sentence: TRosApiSentence); var i, j: Integer; begin for i := High(Sentence) downto 0 do if Sentence[i].Name = '.tag' then begin for j := i to High(Sentence) - 1 do Sentence[j] := Sentence[j + 1]; SetLength(Sentence, High(Sentence)); end; end; {******************************************************************************} function TRosApiClient.GetWordValueByName(Sentence: TROSAPISentence; Name: AnsiString; RaiseErrorIfNotFound: Boolean = False): AnsiString; var i: Integer; begin Result := ''; for i := 1 to High(Sentence) do if (Sentence[i].Name = '=' + Name) or (Sentence[i].Name = Name) then begin Result := Sentence[i].Value; Exit; end; if RaiseErrorIfNotFound then raise Exception.Create('API Word ''' + Name + ''' not found in sentence'); end; {******************************************************************************} function TRosApiResult.GetValueByName(const Name: AnsiString): AnsiString; begin if High(Sentences) = -1 then raise Exception.Create('No values - use Get* first?') else Result := Client.GetWordValueByName(Sentences[0], Name); end; {******************************************************************************} function TRosApiResult.GetValues: TRosApiSentence; begin if High(Sentences) = -1 then raise Exception.Create('No values - use Get* first?') else Result := Sentences[0]; end; {******************************************************************************} function TRosApiResult.GetOne(const Wait: Boolean): Boolean; begin Client.FLastError := ''; FTrap := False; SetLength(Sentences, 1); Result := Client.GetSentenceWithTag(Tag, Wait, Sentences[0]); if not Result then Exit; if Sentences[0][0].Name = '!trap' then begin FTrap := True; Client.FLastError := Self['=message']; end; FDone := Sentences[0][0].Name = '!done'; end; {******************************************************************************} function TRosApiResult.GetAll: Boolean; var se: TRosApiSentence; begin Client.FLastError := ''; FTrap := False; repeat Result := Client.GetSentenceWithTag(Tag, True, se); if Result then begin if se[0].Name = '!trap' then begin FTrap := True; if Client.FLastError <> '' then Client.FLastError := Client.FLastError + '; '; Client.FLastError := Client.FLastError + Client.GetWordValueByName(se, '=message'); end else if se[0].Name = '!done' then begin FDone := True; if High(se) > 0 then begin SetLength(Sentences, High(Sentences) + 2); Sentences[High(Sentences)] := se; end; Exit; end else begin SetLength(Sentences, High(Sentences) + 2); Sentences[High(Sentences)] := se; end; end; until False; end; {******************************************************************************} function TRosApiResult.GetEof: Boolean; begin Result := High(Sentences) = -1; end; {******************************************************************************} function TRosApiResult.GetRowsCount: Integer; begin Result := Length(Sentences); end; {******************************************************************************} procedure TRosApiResult.Next; var i: Integer; begin Client.FLastError := ''; for i := 0 to High(Sentences) - 1 do Sentences[i] := Sentences[i + 1]; SetLength(Sentences, High(Sentences)); end; {******************************************************************************} procedure TRosApiResult.Cancel; begin if not Client.Execute(['/cancel', '=tag=' + Tag]) then raise Exception.Create('Cannot cancel: ' + Client.LastError); end; {******************************************************************************} function TRosApiClient.Execute(const Request: array of AnsiString): Boolean; var Res: TRosApiResult; begin Res := Query(Request, True); Result := not Res.Trap; Res.Free; end; {******************************************************************************} end.
unit Receptor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, DB, ComCtrls, DBCtrls, DBTables, Grids, DBGrids, NxColumnClasses, NxColumns, NxScrollControl, NxCustomGridControl, NxCustomGrid, NxGrid, Buttons, ExtCtrls, FMTBcd, SqlExpr, gtroSearchTreeview; type TfrmReceptor = class(TForm) Panel1: TPanel; cmdModificar: TBitBtn; cmdAgregar: TBitBtn; cmdCerrar: TBitBtn; lista: TNextGrid; codigoban: TNxTextColumn; nombreban: TNxTextColumn; estadoban: TNxTextColumn; cmdEliminar: TBitBtn; padre: TNxTextColumn; nivel: TNxTextColumn; tipo: TNxTextColumn; Label1: TLabel; elpapa: TLabel; trigonivel: TLabel; Panel2: TPanel; elrece2: TLabel; el_item: TLabel; tv: TGtroSearchTreeview; SearchBox: TEdit; Label3: TLabel; Button1: TButton; procedure cmdAgregarClick(Sender: TObject); procedure cmdModificarClick(Sender: TObject); procedure cmdCerrarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cmdEliminarClick(Sender: TObject); procedure tvCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); procedure tvLeafNodeChecked(Sender: TObject; Node: TTreeNode); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } expan:integer; codigoba:string; procedure Rellenao(); procedure Cuento(); end; var frmReceptor: TfrmReceptor; QUEHACE: integer; implementation uses Data, Porcentajes2, Menu,Maximos, RPTListas, ModifiRece, Listadorece, Arbol, SeleRece2, No_conexion; {$R *.dfm} {procedure TfrmReceptor.FormClose(Sender: TObject; var Action: TCloseAction); begin frmData.Datos_Banca.Close; end;} procedure TfrmReceptor.Button1Click(Sender: TObject); begin if expan=0 then begin tv.FullExpand; button1.Caption:='Contraer Arbol'; expan:=1; end else begin tv.FullCollapse; button1.Caption:='Expandir Arbol'; expan:=0; end; tv.Items[0].MakeVisible; //11-06-2019 end; procedure TfrmReceptor.cmdAgregarClick(Sender: TObject); begin label1.Caption:='N'; frmmodifirece.MISION:=1; frmmodifirece.ShowModal; if label1.Caption='S' then begin cuento; rellenao; end; end; procedure TfrmReceptor.cmdModificarClick(Sender: TObject); var voyen: integer; modes: TTreeNode; begin codigoba:=elrece2.Caption; QUEHACE:=2; frmmodifirece.MISION:=2; frmmodifirece.cCodigo.Text:=codigoba; label1.Caption:='N'; frmmodifirece.ShowModal; { if label1.Caption='S' then begin //cuento; rellenao; end; } end; procedure TfrmReceptor.cmdCerrarClick(Sender: TObject); begin if FileExists(GetCurrentDir+'\Arbol.txt') then DeleteFile(GetCurrentDir+'\Arbol.txt'); frmReceptor.Close; end; procedure TfrmReceptor.FormShow(Sender: TObject); begin SearchBox.Text:=''; label1.Caption:='N'; el_item.Caption:=''; rellenao(); cmdModificar.Enabled:=false; cmdEliminar.Enabled:=false; expan:=1; button1.Caption:='Contraer Arbol'; end; procedure TfrmReceptor.Rellenao(); var SQL: string; hijo: TTreeNode; modes: TTreeNode; nivo: integer; S,xtado: String; SS: TStrings; // nuevo 06-05-2019 begin SS := TStringList.Create(); // nuevo 06-05-2019 elpapa.Caption:=elpapa.Caption; frmdata.Query.Close; frmdata.Query.SQL.Clear; SQL:=''; SQL:='SELECT b_niv_rec('+quotedstr(frmdata.Bdbanca)+') as xx'; frmdata.Query.SQL.Add(SQL); ///// CONEXION NUEVA /////////////// if not frmdata.Ejecutar(frmdata.Query) then begin if frmno_conexion.Visible=False then frmNo_conexion.ShowModal; exit; end; ////////////////////////////////////// nivo:=strtoint(frmdata.Query.FieldValues['xx'])+1; frmdata.Query.Close; frmdata.Query.SQL.Clear; SQL:=''; if frmdata.BDBANCA='0001' then begin SQL:='SELECT codigo_ban,nombre_ban,codigo_pad,b_niv_rec(codigo_ban) as niv,estado_ban as tado from datos_banca'+ ' ORDER by tipo_ban,niv,codigo_ban'; nivo:=1; end else begin SQL:='SELECT codigo_ban,nombre_ban,codigo_pad,b_niv_rec(codigo_ban) as niv,estado_ban as tado from datos_banca'+ ' where EsMiRec(codigo_ban,'+quotedstr(frmdata.BDBANCA)+')='+quotedstr('SI')+' ORDER by tipo_ban,niv,codigo_ban'; end; frmdata.Query.SQL.Add(SQL); ///// CONEXION NUEVA /////////////// if not frmdata.Ejecutar(frmdata.Query) then begin if frmno_conexion.Visible=False then frmNo_conexion.ShowModal; exit; end; ////////////////////////////////////// tv.Items.Clear; while not frmdata.Query.Eof do begin if frmdata.Query.FieldByName('niv').AsString = inttostr(nivo) then begin if frmdata.Query.fieldbyname('tado').asString='A' then xtado:='ACTIVO' else xtado:='DESACTIVO'; tv.Items.Add(nil, frmdata.Query.fieldbyname('codigo_ban').asString+' - '+frmdata.Query.fieldbyname('nombre_ban').AsString+ ' *'+xtado+' /'+frmdata.Query.FieldByName('niv').AsString+' +'+frmdata.Query.fieldbyname('codigo_pad').asString); end else begin hijo := tv.Items.GetFirstNode; while hijo <> nil do begin S:=Copy(hijo.text,1,pos('-',hijo.text)-2); if S = frmdata.Query.fieldbyname('codigo_pad').asString then begin if frmdata.Query.fieldbyname('tado').asString='A' then xtado:='ACTIVO' else xtado:='DESACTIVO'; tv.Items.AddChild(hijo, frmdata.Query.fieldbyname('codigo_ban').asString+' - '+frmdata.Query.fieldbyname('nombre_ban').AsString+ ' *'+xtado+' /'+frmdata.Query.FieldByName('niv').AsString+' +'+frmdata.Query.fieldbyname('codigo_pad').asString); end; hijo:= hijo.GetNext; end; end; frmdata.Query.Next; end; ///Nuevo Arbol /// tv.FullExpand; cuento; //tv.SaveToFile(GetCurrentDir+'\Arbol.txt'); ///Nuevo 06-05-2019 // tv.SaveTreeToList ; SS:=tv.TreeviewStorage; SS.SaveToFile(GetCurrentDir+'\Arbol.txt',TEncoding.Unicode); ///////////////////// tv.Items.Clear; tv.LoadFromFile(GetCurrentDir+'\Arbol.txt'); tv.FullExpand; ////////////////// if el_item.Caption='' then tv.Items[0].MakeVisible else begin tv.Items[strtoint(el_item.Caption)].MakeVisible; tv.Select(tv.Items[strtoint(el_item.Caption)]); end; end; procedure TfrmReceptor.cmdEliminarClick(Sender: TObject); var A,cp1,SQL,ajo:string; begin if elrece2.Caption<>'' then begin A:='Esta seguro de eliminar: '+ #13 +'-El Receptor:'+ elrece2.Caption+ #13 +' Sera Borrada la Toda la informacion de este Receptor'; 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 Cualbanca(cod_agencia)='+quotedstr(elrece2.Caption)+' and anulado='+quotedstr('N'); frmdata.Query1.SQL.Add(SQL); //frmData.Ejecutar(frmdata.Query1); ///// CONEXION NUEVA /////////////// if not frmdata.Ejecutar(frmdata.Query1) then begin if frmno_conexion.Visible=False then frmNo_conexion.ShowModal; exit; end; ////////////////////////////////////// if frmdata.Query1.FieldValues['v']<>0 then begin showmessage('Tiene jugada para el dia de hoy y no podra ser eliminado...'); exit; end; ajo:=elrece2.Caption; frmdata.Query.Close; frmdata.Query.SQL.Clear; frmdata.Query.SQL.Add('CALL b_rec_eli('+quotedStr(elrece2.Caption)+')'); frmdata.Llamar(frmdata.Query); frmdata.Query.Close; // Auditoria cp1:=('Elimino El receptor -> '+ajo+' a pesar de que se le advirtio') ; if tv.selected<> nil then tv.selected.Delete; frmRPTListas.elmiron(cp1); // end; //Rellenao; end; end; procedure TfrmReceptor.tvCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); begin If (Not tv.Focused) And (cdsSelected in state) Then begin tv.Canvas.Brush.Color := clRed; TV.Canvas.Font.Color := clWhite; end; end; procedure TfrmReceptor.tvLeafNodeChecked(Sender: TObject; Node: TTreeNode); var x1:string; begin elrece2.Caption:=Copy(Node.Text,1,pos(' ',Node.text)); x1:= Copy(Node.Text,pos('+',Node.text)+1,10); if (frmdata.sicrea='1') or (frmdata.BDBANCA='0001') then begin cmdModificar.Enabled:=true; cmdEliminar.Enabled:=true; end; if frmdata.sicrea='2' then if uppercase(x1)<>uppercase(frmdata.BDBANCA) then begin cmdModificar.Enabled:=true; cmdEliminar.Enabled:=true; end else begin cmdModificar.Enabled:=false; cmdEliminar.Enabled:=false; end; end; procedure TfrmReceptor.Cuento(); var i:integer; begin for i := 0 to tv.Items.Count - 1 do if Copy(tv.Items[i].Text,1,pos(' ',tv.Items[i].text)-1) = elrece2.Caption then el_item.Caption:=inttostr(i); end; end.
unit kwSaveWithOtherExtention; {* *Формат:* расширение SaveWithOtherExtention *Описание:* Сохраняет текущий открытый файл в редакторе под тем же именем, но с другим расширеним, заданынм через параметр "расширение" *Пример:* [code] '.nsr' SaveWithOtherExtention [code] *Результат:* Открытый файл в редакторе будет сохранен с расширением nsr (с преобразованием в формат NSRC, если нужно). } // Модуль: "w:\archi\source\projects\Everest\Lite\7.0\Express\EverestTestSupport\kwSaveWithOtherExtention.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "SaveWithOtherExtention" MUID: (512DD336009D) // Имя типа: "TkwSaveWithOtherExtention" interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type TkwSaveWithOtherExtention = {final} class(TtfwRegisterableWord) {* *Формат:* расширение SaveWithOtherExtention *Описание:* Сохраняет текущий открытый файл в редакторе под тем же именем, но с другим расширеним, заданынм через параметр "расширение" *Пример:* [code] '.nsr' SaveWithOtherExtention [code] *Результат:* Открытый файл в редакторе будет сохранен с расширением nsr (с преобразованием в формат NSRC, если нужно). } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwSaveWithOtherExtention {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , EverestLiteAdapter , SysUtils //#UC START# *512DD336009Dimpl_uses* //#UC END# *512DD336009Dimpl_uses* ; class function TkwSaveWithOtherExtention.GetWordNameForRegister: AnsiString; begin Result := 'SaveWithOtherExtention'; end;//TkwSaveWithOtherExtention.GetWordNameForRegister procedure TkwSaveWithOtherExtention.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_512DD336009D_var* var l_FileExt : String; l_FileName : String; //#UC END# *4DAEEDE10285_512DD336009D_var* begin //#UC START# *4DAEEDE10285_512DD336009D_impl* if aCtx.rEngine.IsTopString then begin l_FileExt := aCtx.rEngine.PopDelphiString; l_FileName := ChangeFileExt(aCtx.rStreamFactory.Filename, l_FileExt); l_FileName := ExtractFileName(l_FileName); l_FileName := aCtx.rCaller.ResolveInputFilePath(l_FileName); SaveDocumentAs(l_FileName); end // if aCtx.rEngine.IsTopString then else Assert(False, 'Не задано новое расширение!'); //#UC END# *4DAEEDE10285_512DD336009D_impl* end;//TkwSaveWithOtherExtention.DoDoIt initialization TkwSaveWithOtherExtention.RegisterInEngine; {* Регистрация SaveWithOtherExtention } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
unit Reading; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fileInOut, LazLogger; procedure openFile(Path: String); procedure LoadFile; procedure GetPointers; procedure GetAllMessages; procedure ReadMessage(I, Loc: Integer; prevByte: Byte = $FF); function ConvertFromHM(Message: array of byte; mIndex: Integer): string; //procedure ReadMessage(Index: SmallInt); type TMsg = record Index: Integer; mText: string; mBytes: array of Byte; mByteStr: string; mBytesUnknown: boolean; end; TMes = record Path: String; NumMsg: SmallInt; MsgCollection: array of TMsg; end; const CharMap: array[$80..$81,$00..$FF] of String = ( {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {A} {B} {C} {D} {E} {F} {80} ({0}'0','1','2','3','4','5','6','7','8','9','-','A','B','C','D','E', {1}'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U', {2}'V','W','X','Y','Z','あ','い','う','え','お','か','き','く','け','こ','さ', {3}'し','す','せ','そ','た','ち','つ','て','と','な','に','ぬ','ね','の','は','ひ', {4}'ふ','へ','ほ','ま','み','む','め','も','や','ゆ','よ','ら','り','る','れ','ろ', {5}'わ','を','ん','ぁ','ぃ','ぅ','ぇ','ぉ','ゃ','ゅ','ょ','っ','が','ぎ','ぐ','げ', {6}'ご','ざ','じ','ず','ぜ','ぞ','だ','ぢ','づ','で','ど','ば','び','ぶ','べ','ぼ', {7}'ぱ','ぴ','ぷ','ぺ','ぽ','ア','イ','ウ','エ','オ','カ','キ','ク','ケ','コ','サ', {8}'シ','ス','セ','ソ','タ','チ','ツ','テ','ト','ナ','ニ','ヌ','ネ','ノ','ハ','ヒ', {9}'フ','ヘ','ホ','マ','ミ','ム','メ','モ','ヤ','ユ','ヨ','ラ','リ','ル','レ','ロ', {A}'ワ','ヲ','ン','ア','イ','ウ','エ','オ','ャ','ュ','ョ','ッ','ガ','ギ','グ','ゲ', {B}'ゴ','ザ','ジ','ズ','ゼ','ゾ','ダ','ヂ','ヅ','デ','ド','バ','ビ','ブ','ベ','ボ', {C}'ヴ','パ','ピ','プ','ペ','ポ','+','×','.','○','?','!','●','♂','♀','·', {D}'—','&"','/','♪','☆','★','♥','%','a','b','c','d','e','f','g','h', {E}'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x', {F}'y','z','''','<','>','(',')','「','」','~','*',' ',' ','ä','ö','ü'), {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {A} {B} {C} {D} {E} {F} {81} ({0}'Ä','Ö','Ü','β','"',',',':','0','0','0','0','0','0','0','0','0', {1}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {2}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {3}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {4}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {5}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {6}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {7}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {8}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {9}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {A}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {B}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {C}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {D}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {E}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0', {F}'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0') ); NameMap: array [$00..$25] of String = ( 'Pete','Tatsuya','Celia','Muffy','Nami','Murrey','Carter', 'Takakura','Romana','Lumina','Sebastian','Wally','Chris', 'Hugh','Grant','Samantha','Kate','Galen','Nina','Daryl', 'Gustafa','Cody','Kassey','Patrick','Tim','Ruby','Rock', 'Griffin','Flora','Vesta','Marlin','Hardy','Nak','Nic', 'Flak','Mukumuku','Van','DUMMY' ); var mesFileStream: TMemoryStream = nil; PointerTable: array of Integer; mes: TMes; implementation procedure ResetMes(); begin mes.Path := ''; mes.NumMsg := 0; SetLength(mes.MsgCollection, 0) end; procedure openFile(Path: String); begin if mes.Path <> '' then ResetMes; mes.Path := Path; mesFileStream := getFile(mes.Path); LoadFile; end; procedure LoadFile; begin // Read the pointer table, then build our arrays GetPointers; GetAllMessages; end; procedure GetPointers; var I: Integer = 0; begin // .mes files graciously tell us the number of MsgContent contained within mesFileStream.Position := $6; mesFileStream.ReadBuffer(Mes.NumMsg,2); // Gamecube uses Big Endian, need to convert that to the system's native Mes.NumMsg := BEToN(Mes.NumMsg); SetLength(PointerTable,Mes.NumMsg); debugLn('Number of messages: ' + IntToStr(Mes.NumMsg)); // Add lines to MessageList to correspond with the MsgContent in the file { for I := 0 to (Mes.NumMsg - 1) do MessageList.AddItem('Message ' + IntToStr(I + 1), nil);} {MessageList.Enabled := True;} // Now we just read the pointers and throw them into the array I := 0; while I < (Mes.NumMsg) do begin // $8 is the location of the first pointer. Four bytes long, Big Endian mesFileStream.Position := $8 + (4 * I); mesFileStream.ReadBuffer(PointerTable[I],4); I := I + 1; end; // debugLn('Size of PointerTable: ' + IntToStr(Length(PointerTable))); end; procedure GetAllMessages; var I: Integer = 0; Loc: Integer = 0; begin // Resize the array of our message records setLength(mes.MsgCollection,mes.NumMsg); for I := 0 to mes.NumMsg - 1 do begin with mes.MsgCollection[I] do begin Loc := BEToN(PointerTable[I]); Index := I; ReadMessage(I, Loc); // debugLn('Msg ' + IntToStr(I) + ': ' + mByteStr); mText := ConvertFromHM(mBytes, I); debugLn('Msg ' + IntToStr(I) + ': ' + mText); end; end; end; // Given a starting location, this will read byte-by-byte until it reaches // a $30 or $00 followed by an $00 byte, at which point it will exit. Recursive. procedure ReadMessage(I, Loc: Integer; prevByte: Byte = $FF); var currByte: Byte; begin mesFileStream.Position := Loc; mesFileStream.ReadBuffer(currByte, 1); with mes.MsgCollection[I] do begin setLength(mBytes, Length(mBytes) + 1); mBytes[Length(mBytes) - 1] := currByte; mByteStr := mByteStr + IntToHex(currByte, 2) + ' '; end; // Messages end either with $0000 or $3000, no exceptions that i can find if (currByte = $00) and ((prevByte = $00) or (prevByte = $30)) then begin //ReadMessage := IntToHex(currByte,2); end else begin //ReadMessage := IntToHex(currByte, 2) + ReadMessage(Loc + 1, currByte); ReadMessage(I, Loc + 1, currByte); end; end; function ConvertFromHM(Message: array of byte; mIndex: Integer): string; var I: Integer = 0; ReadChar: Byte; // Result: String = ''; Append: String = ''; Incre: Integer; begin ConvertFromHM := ''; while I < Length(Message) do begin Append := ''; Incre := 1; if Message[I] in [$80..$81] then // It's a character begin ReadChar := Message[I + 1]; Incre := 2; Append := CharMap[Message[I]][ReadChar]; end else // It's a special marker begin case Message[I] of $00: Append := '{00}'; // Usually a string end marker, when preceded by another 00 or 30 $01: Append := sLineBreak; // Line break $02: Append := ' '; // Space $03: Append := '{ENDPAGE}'; // Page end marker $10..$17: // Colors Append := '{C' + IntToHex(Message[I],2) + '}'; { $14: begin // Farm name? Seems to be various location names. Append := '{LOCATION}'; Incre := 4; end; } $20: begin // People. Pulls from people.mes ReadChar := Message[I + 1]; if Message[I + 1] in [$00..$25] then begin Append := '{' + UpperCase(NameMap[ReadChar]) + '}'; end else Append := '{CHARUNK}'; // Odd case where it's not in the array Incre := 2; end; $21: begin // Previous input? Seems so. Append := '{PREVINPUT}'; Incre := 2; end; $25: begin // Item name from memory. Related to record player and others Append := '{ITEM}'; Incre := 3; end; $27: begin // Seems to be Ordered Items. 3 bytes. Append := '{ORD' + IntToStr(Message[I + 2]) + '}'; Incre := 3; end; $29: begin // Variable marker. 2 bytes //ReadChar := Message[I + 1]; // Apparently texts can be passed variables Append := '{VAR' + IntToStr(Message[I + 1]) + '}'; Incre := 2; end; $2A: begin // Money ** MAYBE NOT. Seems to be anything numeric. 3 bytes Append := '{GOLD}'; Incre := 3; end; $2B: begin // Pulls from structure.mes. 2 bytes. Append := '{STRUC' + IntToStr(Message[I + 1]) + '}'; Incre := 2 end; $30: begin // Pause Append := '{PAUSE}'; end; $32,$34: // Sound. 3 bytes begin Incre := 3; Append := '{S_' + IntToHex(Message[I],2) + IntToHex(Message[I + 1],2) + IntToHex(Message[I + 2],2) + '}'; end; // $35: Incre := 2; // Two bytes. Maybe sound? david.mes $D70 $40: begin // Simple Yes/No choice Append := '{CHOICE Y/N DEF' + IntToStr(Message[I + 1]) + '}'; // Second byte is default choice Incre := 2; end; $41: begin // Custom Player choice ReadChar := Message[I + 1]; // Third byte is default choice Append := '{CHOICE' + IntToStr(Message[I + 1]) + ' DEF' + IntToStr(Message[I + 2]) + '}' + sLineBreak; Incre := 3; end; $50: begin // Semes to change facial expressions? Append := '{FACE?}'; Incre := 4; end; else // Unknown byte begin Append := '{' + IntToHex(Message[I],2) + '}'; Mes.MsgCollection[mIndex].mBytesUnknown := true; end; end; //StatusBar1.Panels[1].Text := Append; end; ConvertFromHM := ConvertFromHM + Append; Inc(I,Incre); end; end; end.
//////////////////////////////////////////////////////////////////////////////// // LibCML.pas // MTB communication library // Main library class. // (c) Jan Horacek (jan.horacek@kmz-brno.cz) //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2016-2018 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: TCML is main library class. It covers all the high-level library principles. } unit LibCML; interface uses MTBusb; type TRCSIPortType = ( iptPlain = 0, iptIR = 1 ); TRCSOPortType = ( optPlain = 0, optSCom = 1 ); TCML = class private procedure MTBOnChange(Sender:TObject); procedure MTBOnInputChanged(Sender: TObject; module: byte); procedure MTBOnOutputChanged(Sender: TObject; module: byte); procedure MTBBeforeOpen(Sender:TObject); procedure MTBAfterOpen(Sender:TObject); procedure MTBBeforeClose(Sender:TObject); procedure MTBAfterClose(Sender:TObject); procedure MTBBeforeStart(Sender:TObject); procedure MTBAfterStart(Sender:TObject); procedure MTBBeforeStop(Sender:TObject); procedure MTBAfterStop(Sender:TObject); procedure MTBOnScanned(Sender:TObject); public api_version: Cardinal; constructor Create(); destructor Destroy(); override; procedure OnError(Sender: TObject; errValue: word; errAddr: byte); procedure OnLog(Sender: TObject; ll:TLogLevel; logValue: string); end; var CML:TCML; MTBdrv: TMTBusb; implementation uses FFormConfig, FFormModule, LibraryEvents; //////////////////////////////////////////////////////////////////////////////// constructor TCML.Create(); begin inherited; MTBdrv.OnError := Self.OnError; MTBdrv.OnLog := Self.OnLog; MTBdrv.OnChange := self.MTBOnChange; MTBdrv.OnInputChange := Self.MTBOnInputChanged; MTBdrv.OnOutputChange := Self.MTBOnOutputChanged; MTBdrv.BeforeOpen := Self.MTBBeforeOpen; MTBdrv.AfterOpen := Self.MTBAfterOpen; MTBdrv.BeforeStart := Self.MTBBeforeStart; MTBdrv.AfterStart := Self.MTBAfterStart; MTBdrv.BeforeStop := Self.MTBBeforeStop; MTBdrv.AfterStop := Self.MTBAfterStop; MTBdrv.BeforeClose := Self.MTBBeforeClose; MTBdrv.AfterClose := Self.MTBAfterClose; MTBdrv.OnScanned := Self.MTBOnScanned; end; destructor TCML.Destroy(); begin inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TCML.MTBBeforeOpen(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.BeforeOpen(Sender); if (Assigned(LibEvents.BeforeOpen.event)) then LibEvents.BeforeOpen.event(Self, LibEvents.BeforeOpen.data); end; procedure TCML.MTBAfterOpen(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.AfterOpen(Sender); if (Assigned(LibEvents.AfterOpen.event)) then LibEvents.AfterOpen.event(Self, LibEvents.AfterOpen.data); end; procedure TCML.MTBBeforeClose(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.BeforeClose(Sender); if (Assigned(LibEvents.BeforeClose.event)) then LibEvents.BeforeClose.event(Self, LibEvents.BeforeClose.data); end; procedure TCML.MTBAfterClose(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.AfterClose(Sender); if (Assigned(LibEvents.AfterClose.event)) then LibEvents.AfterClose.event(Self, LibEvents.AfterClose.data); end; procedure TCML.MTBBeforeStart(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.BeforeStart(Sender); if (Assigned(LibEvents.BeforeStart.event)) then LibEvents.BeforeStart.event(Self, LibEvents.BeforeStart.data); end; procedure TCML.MTBAfterStart(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.AfterStart(Sender); if (Assigned(LibEvents.AfterStart.event)) then LibEvents.AfterStart.event(Self, LibEvents.AfterStart.data); if (Assigned(FormModule)) then FormModule.RefreshStates(); end; procedure TCML.MTBBeforeStop(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.BeforeStop(Sender); if (Assigned(LibEvents.BeforeStop.event)) then LibEvents.BeforeStop.event(Self, LibEvents.BeforeStop.data); end; procedure TCML.MTBAfterStop(Sender:TObject); begin if (Assigned(FormConfig)) then FormConfig.AfterStop(Sender); if (Assigned(LibEvents.AfterStop.event)) then LibEvents.AfterStop.event(Self, LibEvents.AfterStop.data); if (Assigned(FormModule)) then FormModule.RefreshStates(); end; procedure TCML.MTBOnChange(Sender:TObject); begin if (Assigned(FormModule)) then FormModule.OnChange(Sender); end; procedure TCML.OnLog(Sender: TObject; ll:TLogLevel; logValue: string); begin if (Assigned(FormConfig)) then FormConfig.OnLog(Sender, ll, logValue); if (Assigned(LibEvents.OnLog.event)) then LibEvents.OnLog.event(Self, LibEvents.OnLog.data, Integer(ll), PChar(logValue)); end; procedure TCML.OnError(Sender: TObject; errValue: word; errAddr: byte); begin if (Assigned(FormConfig)) then FormConfig.OnError(Sender, errValue, errAddr); if (Assigned(LibEvents.OnError.event)) then LibEvents.OnError.event(Self, LibEvents.OnError.data, errValue, errAddr, PChar(MTBdrv.GetErrString(errValue))); end; procedure TCML.MTBOnInputChanged(Sender: TObject; module: byte); begin if (Assigned(LibEvents.OnInputChanged.event)) then LibEvents.OnInputChanged.event(Self, LibEvents.OnInputChanged.data, module); end; procedure TCML.MTBOnOutputChanged(Sender: TObject; module: byte); begin if (Assigned(LibEvents.OnOutputChanged.event)) then LibEvents.OnOutputChanged.event(Self, LibEvents.OnOutputChanged.data, module); end; procedure TCML.MTBOnScanned(Sender:TObject); begin if (Assigned(LibEvents.OnScanned.event)) then LibEvents.OnScanned.event(Self, LibEvents.OnScanned.data); end; //////////////////////////////////////////////////////////////////////////////// initialization MTBDrv := TMTBusb.Create(nil, 'mtb\mtbcfg.ini'); CML := TCML.Create(); finalization MTBdrv.Free(); CML.Free(); end.
unit MFichas.Model.Caixa.Interfaces; interface uses MFichas.Model.Entidade.CAIXA, MFichas.Model.Usuario.Interfaces, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.ObjectSet; type iModelCaixa = interface; iModelCaixaMetodos = interface; iModelCaixaMetodosAbrir = interface; iModelCaixaMetodosFechar = interface; iModelCaixaMetodosSuprimento = interface; iModelCaixaMetodosSangria = interface; iModelCaixa = interface ['{6DAC11A6-61A5-4D9C-B49B-F24EA43C9C53}'] function SetState(AState: iModelCaixaMetodos): iModelCaixa; function Metodos : iModelCaixaMetodos; function Entidade: TCAIXA; overload; function Entidade(ACaixa: TCAIXA): iModelCaixa; overload; function DAO: iContainerObjectSet<TCAIXA>; end; iModelCaixaMetodos = interface ['{CA0C1C52-AE7F-442E-9179-26561D70CD65}'] function Abrir : iModelCaixaMetodosAbrir; function Fechar : iModelCaixaMetodosFechar; function Suprimento: iModelCaixaMetodosSuprimento; function Sangria : iModelCaixaMetodosSangria; function &End : iModelCaixa; end; iModelCaixaMetodosAbrir = interface ['{79CC7128-A775-40E7-A4EA-BC76DFFCA92C}'] function SetValorAbertura(AValue: Currency) : iModelCaixaMetodosAbrir; function SetOperador(AOperador: iModelUsuario): iModelCaixaMetodosAbrir; overload; function SetOperador(AGUUIDFiscal: String) : iModelCaixaMetodosAbrir; overload; function &End : iModelCaixaMetodos; end; iModelCaixaMetodosFechar = interface ['{9AA943CF-5953-4CF9-A660-DBB88249AE3D}'] function SetValorFechamento(AValue: Currency): iModelCaixaMetodosFechar; function SetOperador(AOperador: String) : iModelCaixaMetodosFechar; function &End : iModelCaixaMetodos; end; iModelCaixaMetodosSuprimento = interface ['{FCEA205D-C423-4DBC-A612-64625F9E8F00}'] function SetValorSuprimento(AValue: Currency): iModelCaixaMetodosSuprimento; function SetOperador(AOperador: String) : iModelCaixaMetodosSuprimento; function &End : iModelCaixaMetodos; end; iModelCaixaMetodosSangria = interface ['{94E99810-3DE3-4B97-947E-7A7CA29A1E96}'] function SetValorSangria(AValue: Currency): iModelCaixaMetodosSangria; function SetOperador(AOperador: String) : iModelCaixaMetodosSangria; function &End : iModelCaixaMetodos; end; implementation end.
unit nsDataResetTree; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Data" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Data/Tree/nsDataResetTree.pas" // Начат: 2005/11/21 17:21:06 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::Data::OldTree::TnsDataResetTree // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3Tree_TLB, l3Tree, nsTypes, afwInterfaces ; type _afwApplicationDataUpdate_Parent_ = Tl3Tree; {$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas} TnsDataResetTree = class(_afwApplicationDataUpdate_) private // private fields f_InGetRoot : Boolean; f_BeenReseted : TnsResetTreeStatus; {* Поле для свойства BeenReseted} protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure FinishDataUpdate; override; function Get_CRootNode: Il3RootNode; override; protected // protected methods procedure BeforeReset; virtual; procedure AfterReget; virtual; function RegetRootNode: Il3RootNode; virtual; public // public properties property BeenReseted: TnsResetTreeStatus read f_BeenReseted; end;//TnsDataResetTree implementation uses afwFacade ; {$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas} // start class TnsDataResetTree procedure TnsDataResetTree.BeforeReset; //#UC START# *4908AAED02BD_4908A9240071_var* //#UC END# *4908AAED02BD_4908A9240071_var* begin //#UC START# *4908AAED02BD_4908A9240071_impl* if fRootNode <> nil then f_BeenReseted := rtsRoot else f_BeenReseted := rtsNone; //#UC END# *4908AAED02BD_4908A9240071_impl* end;//TnsDataResetTree.BeforeReset procedure TnsDataResetTree.AfterReget; //#UC START# *4908AAF6015C_4908A9240071_var* //#UC END# *4908AAF6015C_4908A9240071_var* begin //#UC START# *4908AAF6015C_4908A9240071_impl* ; //#UC END# *4908AAF6015C_4908A9240071_impl* end;//TnsDataResetTree.AfterReget function TnsDataResetTree.RegetRootNode: Il3RootNode; //#UC START# *4908AB070319_4908A9240071_var* //#UC END# *4908AB070319_4908A9240071_var* begin //#UC START# *4908AB070319_4908A9240071_impl* Result := inherited Get_CRootNode; //#UC END# *4908AB070319_4908A9240071_impl* end;//TnsDataResetTree.RegetRootNode procedure TnsDataResetTree.Cleanup; //#UC START# *479731C50290_4908A9240071_var* //#UC END# *479731C50290_4908A9240071_var* begin //#UC START# *479731C50290_4908A9240071_impl* f_BeenReseted := rtsNone; f_InGetRoot := False; inherited; //#UC END# *479731C50290_4908A9240071_impl* end;//TnsDataResetTree.Cleanup procedure TnsDataResetTree.FinishDataUpdate; //#UC START# *47EA4E9002C6_4908A9240071_var* //#UC END# *47EA4E9002C6_4908A9240071_var* begin //#UC START# *47EA4E9002C6_4908A9240071_impl* inherited; Changing; try if fRootNode <> nil then begin BeforeReset; RootNode := nil; end;//if fRootNode <> nil then finally Changed; end;//try..finally //#UC END# *47EA4E9002C6_4908A9240071_impl* end;//TnsDataResetTree.FinishDataUpdate function TnsDataResetTree.Get_CRootNode: Il3RootNode; //#UC START# *4FFC1D0502D0_4908A9240071_var* //#UC END# *4FFC1D0502D0_4908A9240071_var* begin //#UC START# *4FFC1D0502D0_4908A9240071_impl* if f_InGetRoot then begin Result := nil; Exit; end; if (f_BeenReseted <> rtsNone) and (fRootNode = nil) then begin f_InGetRoot := True; Changing; try Result := RegetRootNode; finally f_InGetRoot := False; Changed; f_BeenReseted := rtsNone; AfterReget; end; end else Result := inherited Get_CRootNode; //#UC END# *4FFC1D0502D0_4908A9240071_impl* end;//TnsDataResetTree.Get_CRootNode end.
unit udmConfigLayouts; interface uses System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS; type TdmConfigLayouts = class(TdmPadrao) protected procedure MontaSQLBusca(DataSet: TDataSet = nil); virtual; procedure MontaSQLRefresh; virtual; private FLayout: string; FEmissora: string; FNrConh_Fim: real; FNrConh_Inicio: real; FNrConhecimento: real; function DNrConh_Fim: real; function GetSqlDefault: string; { Private declarations } public property Emissora: string read FEmissora write FEmissora; property Layout: string read FLayout write FLayout; property NrConh_Inicio: real read FNrConh_Inicio write FNrConh_Inicio; property NrConh_Fim: real read DNrConh_Fim write FNrConh_Fim; property NrConhecimento: real read FNrConhecimento write FNrConhecimento; property SqlDefault: string read GetSqlDefault; function LocalizarPorConhecimento(DataSet: TDataSet = nil): Boolean; function LocalizarPorNroConhecimento(DataSet: TDataSet = nil): Boolean; function LocalizarPorLayout(DataSet: TDataSet = nil): Boolean; function LocalizarNota(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = 'SELECT' + ' MOV.DOCUMENTO AS MOV_TPDOC,' + ' MOV.FIL_ORIG AS MOV_FILORIG,' + ' MOV.NR_CTO AS MOV_NRCTO,' + ' MOV.DT_EMISSAO,' + ' MOV.CD_OPE,' + ' REM.NOME AS REM_NOME,' + ' REM.ENDERECO AS REM_ENDERECO,' + ' REM.CIDADE AS REM_CIDADE,' + ' REM.ESTADO AS REM_ESTADO,' + ' MOV.CGC_REMET AS REM_CGC,' + ' DEST.NOME AS DEST_NOME,' + ' DEST.ENDERECO AS DEST_ENDERECO,' + ' DEST.CIDADE AS DEST_CIDADE,' + ' DEST.ESTADO AS DEST_ESTADO,' + ' MOV.CGC_DEST AS DEST_CGC,' + ' CONSIG.NOME AS CONSIG_NOME,' + ' CONSIG.ENDERECO AS CONSIG_ENDERECO,' + ' CONSIG.CIDADE AS CONSIG_CIDADE,' + ' CONSIG.ESTADO AS CONSIG_ESTADO,' + ' MOV.CGC_CONSIG AS CONSIG_CGC,' + ' REDESP.NOME AS REDESP_NOME,' + ' REDESP.ENDERECO AS REDESP_ENDERECO,' + ' REDESP.CIDADE AS REDESP_CIDADE,' + ' REDESP.ESTADO AS REDESP_ESTADO,' + ' MOV.CGC_REDESP AS REDESP_CGC,' + ' ENTREGA.ENT_ENDERECO,' + ' ENTREGA.ENT_CIDADE,' + ' ENTREGA.ENT_UF,' + ' VEICULO.MARCA AS VEICULO_MARCA,' + ' VEICULO.PLACA AS VEICULO_PLACA,' + ' VEICULO.UF_VEIC AS VEICULO_UF,' + ' MOV.TIPO_FRT AS TIPO_FRETE,' + ' MOV.CID_DEST,' + ' MOV.VLR_MERC,' + ' MOV.PESO,' + ' MOV.VOLUMES,' + ' MOV.TARIFA,' + ' MOV.FRT_PESO,' + ' MOV.FRT_VALOR,' + ' MOV.CAT,' + ' MOV.ADEME,' + ' MOV.DESPACHO,' + ' MOV.ITR,' + ' MOV.OUTROS,' + ' MOV.TOT_FRETE,' + ' MOV.BASE_CALC,' + ' MOV.ALIQUOTA,' + ' MOV.VLR_ICMS,' + ' MOV.OBS' + ' FROM STWOPETMOV MOV' + ' LEFT JOIN STWOPETCLI REM ON MOV.CGC_REMET = REM.CGC' + ' LEFT JOIN STWOPETCLI DEST ON MOV.CGC_DEST = DEST.CGC' + ' LEFT JOIN STWOPETCLI CONSIG ON MOV.CGC_CONSIG = CONSIG.CGC' + ' LEFT JOIN STWOPETCLI REDESP ON MOV.CGC_REDESP = REDESP.CGC' + ' LEFT JOIN STWOPETVEI VEICULO ON MOV.VEICULO = VEICULO.FROTA' + ' LEFT JOIN STWOPETAUX1 ENTREGA ON (MOV.DOCUMENTO = ENTREGA.CTO_DOCUMENTO AND' + ' MOV.FIL_ORIG = ENTREGA.CTO_FILIAL AND MOV.NR_CTO = ENTREGA.CTO_NUMERO)' ; var dmConfigLayouts: TdmConfigLayouts; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmConfigLayouts } function TdmConfigLayouts.DNrConh_Fim: real; begin Result := FNrConh_Fim; end; function TdmConfigLayouts.GetSqlDefault: string; begin result := SQL_DEFAULT; end; function TdmConfigLayouts.LocalizarNota(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT * FROM STWOPETNOTA'); SQL.Add('WHERE DOCUMENTO = :DOCUMENTO AND FIL_ORIG = :FIL_ORIG'); SQL.Add(' AND NR_CTO = :NR_IMPRESSO'); ParamByName('FIL_ORIG').AsString := FEmissora; ParamByName('DOCUMENTO').AsString := FEmissora; ParamByName('NR_IMPRESSO').AsFloat := FNrConh_Inicio; Open; Result := not IsEmpty; end; end; function TdmConfigLayouts.LocalizarPorConhecimento(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; // Aqui deverá incluir novos campos caso precise para ser impresso utilizando SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE MOV.FIL_ORIG = :FIL_ORIG AND MOV.NR_CTO >= :NR_CTOINI AND MOV.NR_CTO <= :NR_CTOFIN'); // SQL.Add(' AND (STATUS NOT IN ' + QuotedStr('DG ') + ')'); // ( ' + sAspas + 'DG' + sAspas + ' )) ParamByName('FIL_ORIG').AsString := FEmissora; ParamByName('NR_CTOINI').AsFloat := FNrConh_Inicio; ParamByName('NR_CTOFIN').AsFloat := FNrConh_Fim; Open; Result := not IsEmpty; end; end; function TdmConfigLayouts.LocalizarPorLayout(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE FILIAL = :FILIAL AND LAYOUT = :LAYOUT'); ParamByName('FILIAL').AsString := FEmissora; ParamByName('LAYOUT').AsString := FLayout; Open; Result := not IsEmpty; end; end; function TdmConfigLayouts.LocalizarPorNroConhecimento( DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; // Aqui deverá incluir novos campos caso precise para ser impresso utilizando SQL.Clear; // a configuração de Layout´s e deverá atualizar o mesmo no tela de configuração SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE MOV.FIL_ORIG = :FIL_ORIG AND MOV.NR_CTO = :NR_CTO'); // SQL.Add(' AND (STATUS NOT IN ' + QuotedStr('DG ') + ')'); // ( ' + sAspas + 'DG' + sAspas + ' )) ParamByName('FIL_ORIG').AsString := FEmissora; ParamByName('NR_CTO').AsFloat :=FNrConhecimento; Open; Result := not IsEmpty; end; end; procedure TdmConfigLayouts.MontaSQLBusca(DataSet: TDataSet); begin inherited; if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM CONFIGLAYOUT'); SQL.Add(' WHERE FILIAL = :FILIAL AND LAYOUT = :LAYOUT'); SQL.Add(' ORDER BY LINHA, COLUNA'); ParamByName('FILIAL').AsString := FEmissora; ParamByName('LAYOUT').AsString := FLayout; end; end; procedure TdmConfigLayouts.MontaSQLRefresh; begin with qryManutencao do begin Close; SQL.Clear; SQL.Add('SELECT * FROM CONFIGLAYOUT'); SQL.Add(' ORDER BY LINHA, COLUNA'); open; end; end; end.
unit StdEffects; interface uses Effects, Languages; const fxLittering = 1000; fxGraffiti = 1001; fxWantonViolence = 1002; fxNoise = 1003; fxVoyeurism = 1004; fxSabotage = 1005; fxAreaFear = 1006; fxMaintIncrease = 1007; fxUnDesirability = 1008; fxEfficHit = 1009; fxProdQualityHit = 1010; // Effect names const mtidfxName_Littering : TRegMultiString = nil; mtidfxName_Graffiti : TRegMultiString = nil; mtidfxName_WantonViolence : TRegMultiString = nil; mtidfxName_Noise : TRegMultiString = nil; mtidfxName_Voyeurism : TRegMultiString = nil; mtidfxName_Sabotage : TRegMultiString = nil; mtidfxName_AreaFear : TRegMultiString = nil; mtidfxName_MaintIncrease : TRegMultiString = nil; // Effect status reports const mtidEfxStrength : TRegMultiString = nil; // '%s attack strength %d%%.' mtidEfxBeauty : TRegMultiString = nil; // 'Beauty loss of %d points.' mtidEfxCrime : TRegMultiString = nil; // 'Crime increase of %d points.' mtidEfxQOL : TRegMultiString = nil; // 'QOL loss of %d points.' mtidEfxPoll : TRegMultiString = nil; // 'Pollution increase of %d points.' mtidEfxNBHQ : TRegMultiString = nil; // 'Neighborhood quality loss of %d points.' mtidEfxMaintHit : TRegMultiString = nil; // 'Maintenance costs increased %d%%.' procedure InitMLS; implementation procedure InitMLS; begin mtidfxName_Littering := TRegMultiString.Create( 'mtidfxName_Littering', 'Citizens report several suspects were seen dumping waste on the area.' ); mtidfxName_Graffiti := TRegMultiString.Create( 'mtidfxName_Graffiti', 'Citizens report some suspects were seen making signs with spray cans.' ); mtidfxName_WantonViolence := TRegMultiString.Create( 'mtidfxName_WantonViolence', 'Locals report various acts of wanton violence.' ); mtidfxName_Noise := TRegMultiString.Create( 'mtidfxName_Noise', 'Citizes complain about various forms of loud noise.' ); mtidfxName_Voyeurism := TRegMultiString.Create( 'mtidfxName_Voyeurism', 'Local girls reported they have been repeatedly spied upon by undentified persons.' ); mtidfxName_Sabotage := TRegMultiString.Create( 'mtidfxName_Sabotage', 'Property managers report the site was sabotaged.' ); mtidfxName_AreaFear := TRegMultiString.Create( 'mtidfxName_AreaFear', 'Citizens report they are afraid to leave home for their daily tasks.' ); mtidfxName_MaintIncrease := TRegMultiString.Create( 'mtidfxName_MaintIncrease', 'Property managers report an increase of maintenance costs.' ); mtidEfxStrength := TRegMultiString.Create( 'mtidEfxStrength', 'Attack strength %d%%.' ); mtidEfxBeauty := TRegMultiString.Create( 'mtidEfxBeauty', 'Beauty loss of %d points.' ); mtidEfxCrime := TRegMultiString.Create( 'mtidEfxCrime', 'Crime increase of %d points.' ); mtidEfxQOL := TRegMultiString.Create( 'mtidEfxQOL', 'QOL loss of %d points.' ); mtidEfxPoll := TRegMultiString.Create( 'mtidEfxPoll', 'Pollution increase of %d points.' ); mtidEfxNBHQ := TRegMultiString.Create( 'mtidEfxNBHQ', 'Neighborhood quality loss of %d points.' ); mtidEfxMaintHit := TRegMultiString.Create( 'mtidEfxMaintHit', 'Maintenance costs increased %d%%.' ); end; initialization InitMLS; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Cryptography, RemObjects.Elements.EUnit; type MessageDigestTest = public class (Test) public method ComputeHash; method Updatable; method Algorithms; method ToHexString; end; implementation method MessageDigestTest.Algorithms; begin var Data := Encoding.UTF8.GetBytes("These aren't the droids you're looking for"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.MD5).Digest(Data)), "6ECD7F39E50E4C52D4E383133E18AEB3"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.SHA1).Digest(Data)), "1BD44F7B2657CA9C9D7516885FA925D5791D624C"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.SHA256).Digest(Data)), "DBCE3DDA001C46C396653CF6C5435DC9833741FA9257DC031FDFF48B57DAB374"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.SHA384).Digest(Data)), "3729BBA3B503AC182F75586E69B6F4A6AB5B26D88569B65817EE495D4821B8B9831B8F78CD6DB407A59B321509AB9E8D"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.SHA512).Digest(Data)), "B9DF79CE9E94E4C014D21E2B98424FD79665CF224804761BD56164D7E704A6B0C98C4658CD937DABA449892F0A643522BA7F66C3FB7B9116A2961F999BB36463"); end; method MessageDigestTest.ComputeHash; begin var Data := Encoding.UTF8.GetBytes("Test data value"); Assert.AreEqual(new MessageDigest(DigestAlgorithm.SHA256).Digest(Data), [17, 39, 191, 114, 255, 158, 204, 142, 164, 10, 242, 207, 178, 103, 68, 150, 91, 239, 120, 242, 0, 247, 102, 31, 106, 135, 223, 73, 120, 212, 103, 25]); Assert.AreEqual(new MessageDigest(DigestAlgorithm.SHA384).Digest(Data, 4), [123, 143, 70, 84, 7, 107, 128, 235, 150, 57, 17, 241, 156, 250, 209, 170, 244, 40, 94, 212, 142, 130, 111, 108, 222, 27, 1, 167, 154, 167, 63, 173, 181, 68, 110, 102, 127, 196, 249, 4, 23, 120, 44, 145, 39, 5, 64, 243]); Assert.AreEqual(new MessageDigest(DigestAlgorithm.MD5).Digest(Data, 5, 4), [141, 119, 127, 56, 93, 61, 254, 200, 129, 93, 32, 247, 73, 96, 38, 220]); Assert.AreEqual(new MessageDigest(DigestAlgorithm.SHA1).Digest([]), [218, 57, 163, 238, 94, 107, 75, 13, 50, 85, 191, 239, 149, 96, 24, 144, 175, 216, 7, 9]); Assert.Throws(->new MessageDigest(DigestAlgorithm.MD5).Digest(nil, 0, 1 )); Assert.Throws(->new MessageDigest(DigestAlgorithm.SHA1).Digest(Data, -1, 1)); Assert.Throws(->new MessageDigest(DigestAlgorithm.SHA256).Digest(Data, 1, -1)); Assert.Throws(->new MessageDigest(DigestAlgorithm.SHA384).Digest(Data, 55, 1)); Assert.Throws(->new MessageDigest(DigestAlgorithm.MD5).Digest(Data, 1, 55)); var md := new MessageDigest(DigestAlgorithm.SHA1); Assert.AreEqual(Utils.ToHexString(md.Digest([1, 2, 3])), "7037807198C22A7D2B0807371D763779A84FDFCF"); Assert.AreEqual(Utils.ToHexString(md.Digest([4, 5, 6])), "E809C5D1CEA47B45E34701D23F608A9A58034DC9"); Assert.AreEqual(Utils.ToHexString(md.Digest([7, 8, 9])), "B470CF972A0D84FBAEEEDB51A963A902269417E8"); Assert.AreEqual(Utils.ToHexString(MessageDigest.ComputeHash([1, 2, 3], DigestAlgorithm.SHA1)), "7037807198C22A7D2B0807371D763779A84FDFCF"); Assert.AreEqual(Utils.ToHexString(MessageDigest.ComputeHash([4, 5, 6], DigestAlgorithm.SHA1)), "E809C5D1CEA47B45E34701D23F608A9A58034DC9"); Assert.AreEqual(Utils.ToHexString(MessageDigest.ComputeHash([7, 8, 9], DigestAlgorithm.SHA1)), "B470CF972A0D84FBAEEEDB51A963A902269417E8"); end; method MessageDigestTest.ToHexString; begin Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.MD5).Digest([])), "D41D8CD98F00B204E9800998ECF8427E"); Assert.AreEqual(Utils.ToHexString(new MessageDigest(DigestAlgorithm.SHA1).Digest(Encoding.UTF8.GetBytes("Hello"))), "F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0"); Assert.AreEqual(Utils.ToHexString([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 42]), "000102030405060708090A0B0C0D0E0F2A"); end; method MessageDigestTest.Updatable; begin var Expected: array of Byte := [153, 229, 39, 4, 70, 45, 53, 128, 219, 53, 40, 202, 215, 234, 150, 96]; var Digest := new MessageDigest(DigestAlgorithm.MD5); Digest.Update(Encoding.UTF8.GetBytes("Ping")); var Actual := Digest.Digest(Encoding.UTF8.GetBytes("Pong")); Assert.AreEqual(Actual, Expected); Digest := new MessageDigest(DigestAlgorithm.MD5); Assert.Throws(->Digest.Update(nil, 1, 1)); Assert.Throws(->Digest.Update([], -1, 1)); Assert.Throws(->Digest.Update([], 1, -1)); Assert.Throws(->Digest.Update([1], 5, 1)); Assert.Throws(->Digest.Update([1], 0, 5)); Assert.Throws(->Digest.Digest(nil, 1, 1)); Assert.Throws(->Digest.Digest([], -1, 1)); Assert.Throws(->Digest.Digest([], 1, -1)); Assert.Throws(->Digest.Digest([1], 5, 1)); Assert.Throws(->Digest.Digest([1], 0, 5)); end; end.
unit vtHoverButton; interface uses Windows, Controls, Classes, Messages, ImgList; type TvtHoverButtonState = (hbsNormal, hbsHovered, hbsPressed); TvtHoverButton = class(TGraphicControl) private FState: TvtHoverButtonState; FAutoSize: Boolean; FImageList: TCustomImageList; FNormalImageIndex: Integer; FHoveredImageIndex: Integer; FPressedImageIndex: Integer; FOnClick: TNotifyEvent; procedure pm_SetAutoSize(AValue: Boolean); procedure SetState(AState: TvtHoverButtonState); procedure AdjustSize; function GetStateImageIndex: Integer; function NeedPaintImageByIndex: Boolean; procedure pm_SetHoveredImageIndex(AValue: Integer); procedure pm_SetNormalImageIndex(AValue: Integer); procedure pm_SetPressedImageIndex(AValue: Integer); procedure pm_SetImageList(AValue: TCustomImageList); protected procedure Paint; override; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; published property AutoSize: Boolean read FAutoSize write pm_SetAutoSize; property ImageList: TCustomImageList read FImageList write pm_SetImageList; property NormalImageIndex: Integer read FNormalImageIndex write pm_SetNormalImageIndex default -1; property HoveredImageIndex: Integer read FHoveredImageIndex write pm_SetHoveredImageIndex default -1; property PressedImageIndex: Integer read FPressedImageIndex write pm_SetPressedImageIndex default -1; property OnClick read FOnClick write FOnClick; end; implementation uses SysUtils, Graphics; { TvtHoverPngButton } procedure TvtHoverButton.CMMouseEnter(var Message: TMessage); begin inherited; SetState(hbsHovered); end; procedure TvtHoverButton.CMMouseLeave(var Message: TMessage); begin inherited; SetState(hbsNormal); end; procedure TvtHoverButton.WMLButtonDown(var Message: TWMLButtonDown); begin if (FState in [hbsNormal, hbsHovered]) then SetState(hbsPressed); inherited; end; procedure TvtHoverButton.WMLButtonUp(var Message: TWMLButtonUp); begin if Assigned(FOnClick) then FOnClick(Self); if (FState = hbsPressed) then SetState(hbsNormal); end; function TvtHoverButton.GetStateImageIndex: Integer; begin case FState of hbsNormal: Result := FNormalImageIndex; hbsHovered: begin if (FHoveredImageIndex <> -1) then Result := FHoveredImageIndex else Result := FNormalImageIndex; end;//hbsHovered hbsPressed: begin if (FPressedImageIndex <> -1) then Result := FPressedImageIndex else Result := FHoveredImageIndex; end;//hbsPressed end;//case FState end; function TvtHoverButton.NeedPaintImageByIndex: Boolean; begin Result := (FImageList <> nil) and (GetStateImageIndex <> -1); end; procedure TvtHoverButton.Paint; begin if NeedPaintImageByIndex then FImageList.Draw(Canvas, 0, 0, GetStateImageIndex); end; procedure TvtHoverButton.SetState(AState: TvtHoverButtonState); begin if (AState <> FState) then begin FState := AState; Invalidate; end; end; procedure TvtHoverButton.pm_SetAutoSize(AValue: Boolean); begin if (AValue <> FAutoSize) then begin FAutoSize := AValue; AdjustSize; end; end; procedure TvtHoverButton.AdjustSize; begin if (FNormalImageIndex <> -1) and (FImageList <> nil) then begin Height := FImageList.Height; Width := FImageList.Width; end; end; procedure TvtHoverButton.pm_SetHoveredImageIndex(AValue: Integer); begin if (AValue <> FHoveredImageIndex) then begin FHoveredImageIndex := AValue; if (FState = hbsHovered) then Invalidate; end; end; procedure TvtHoverButton.pm_SetNormalImageIndex(AValue: Integer); begin if (AValue <> FNormalImageIndex) then begin FNormalImageIndex := AValue; if (FState = hbsNormal) then Invalidate; end; end; procedure TvtHoverButton.pm_SetPressedImageIndex(AValue: Integer); begin if (AValue <> FPressedImageIndex) then begin FPressedImageIndex := AValue; if (FState = hbsPressed) then Invalidate; end; end; procedure TvtHoverButton.pm_SetImageList(AValue: TCustomImageList); begin if (AValue <> FImageList) then begin FImageList := AValue; if FAutoSize then AdjustSize else Invalidate; end; end; end.
unit WarningBaloonKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы WarningBaloon } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\WarningBaloonKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "WarningBaloonKeywordsPack" MUID: (4EA58A3903B4_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , WarningBaloon_Form , tfwPropertyLike {$If Defined(Nemesis)} , nscEditor {$IfEnd} // Defined(Nemesis) , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4EA58A3903B4_Packimpl_uses* //#UC END# *4EA58A3903B4_Packimpl_uses* ; type TkwWarningBaloonFormViewer = {final} class(TtfwPropertyLike) {* Слово скрипта .TWarningBaloonForm.Viewer } private function Viewer(const aCtx: TtfwContext; aWarningBaloonForm: TWarningBaloonForm): TnscEditor; {* Реализация слова скрипта .TWarningBaloonForm.Viewer } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwWarningBaloonFormViewer Tkw_Form_WarningBaloon = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы WarningBaloon ---- *Пример использования*: [code]форма::WarningBaloon TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_WarningBaloon Tkw_WarningBaloon_Control_Viewer = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Viewer ---- *Пример использования*: [code]контрол::Viewer TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_WarningBaloon_Control_Viewer Tkw_WarningBaloon_Control_Viewer_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола Viewer ---- *Пример использования*: [code]контрол::Viewer:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_WarningBaloon_Control_Viewer_Push function TkwWarningBaloonFormViewer.Viewer(const aCtx: TtfwContext; aWarningBaloonForm: TWarningBaloonForm): TnscEditor; {* Реализация слова скрипта .TWarningBaloonForm.Viewer } begin Result := aWarningBaloonForm.Viewer; end;//TkwWarningBaloonFormViewer.Viewer class function TkwWarningBaloonFormViewer.GetWordNameForRegister: AnsiString; begin Result := '.TWarningBaloonForm.Viewer'; end;//TkwWarningBaloonFormViewer.GetWordNameForRegister function TkwWarningBaloonFormViewer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscEditor); end;//TkwWarningBaloonFormViewer.GetResultTypeInfo function TkwWarningBaloonFormViewer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwWarningBaloonFormViewer.GetAllParamsCount function TkwWarningBaloonFormViewer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TWarningBaloonForm)]); end;//TkwWarningBaloonFormViewer.ParamsTypes procedure TkwWarningBaloonFormViewer.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Viewer', aCtx); end;//TkwWarningBaloonFormViewer.SetValuePrim procedure TkwWarningBaloonFormViewer.DoDoIt(const aCtx: TtfwContext); var l_aWarningBaloonForm: TWarningBaloonForm; begin try l_aWarningBaloonForm := TWarningBaloonForm(aCtx.rEngine.PopObjAs(TWarningBaloonForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWarningBaloonForm: TWarningBaloonForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Viewer(aCtx, l_aWarningBaloonForm)); end;//TkwWarningBaloonFormViewer.DoDoIt function Tkw_Form_WarningBaloon.GetString: AnsiString; begin Result := 'WarningBaloonForm'; end;//Tkw_Form_WarningBaloon.GetString class procedure Tkw_Form_WarningBaloon.RegisterInEngine; begin inherited; TtfwClassRef.Register(TWarningBaloonForm); end;//Tkw_Form_WarningBaloon.RegisterInEngine class function Tkw_Form_WarningBaloon.GetWordNameForRegister: AnsiString; begin Result := 'форма::WarningBaloon'; end;//Tkw_Form_WarningBaloon.GetWordNameForRegister function Tkw_WarningBaloon_Control_Viewer.GetString: AnsiString; begin Result := 'Viewer'; end;//Tkw_WarningBaloon_Control_Viewer.GetString class procedure Tkw_WarningBaloon_Control_Viewer.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscEditor); end;//Tkw_WarningBaloon_Control_Viewer.RegisterInEngine class function Tkw_WarningBaloon_Control_Viewer.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer'; end;//Tkw_WarningBaloon_Control_Viewer.GetWordNameForRegister procedure Tkw_WarningBaloon_Control_Viewer_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Viewer'); inherited; end;//Tkw_WarningBaloon_Control_Viewer_Push.DoDoIt class function Tkw_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer:push'; end;//Tkw_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister initialization TkwWarningBaloonFormViewer.RegisterInEngine; {* Регистрация WarningBaloonForm_Viewer } Tkw_Form_WarningBaloon.RegisterInEngine; {* Регистрация Tkw_Form_WarningBaloon } Tkw_WarningBaloon_Control_Viewer.RegisterInEngine; {* Регистрация Tkw_WarningBaloon_Control_Viewer } Tkw_WarningBaloon_Control_Viewer_Push.RegisterInEngine; {* Регистрация Tkw_WarningBaloon_Control_Viewer_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TWarningBaloonForm)); {* Регистрация типа TWarningBaloonForm } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditor)); {* Регистрация типа TnscEditor } {$IfEnd} // Defined(Nemesis) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) 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 ClpDerGenerator; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpBits, ClpCryptoLibTypes, ClpStreams, ClpStreamHelper, ClpAsn1Tags, ClpAsn1Generator, ClpIDerGenerator; type TDerGenerator = class abstract(TAsn1Generator, IDerGenerator) strict private var F_tagged, F_isExplicit: Boolean; F_tagNo: Int32; class procedure WriteLength(const outStr: TStream; length: Int32); static; strict protected constructor Create(const outStream: TStream); overload; constructor Create(const outStream: TStream; tagNo: Int32; isExplicit: Boolean); overload; public procedure WriteDerEncoded(tag: Int32; const bytes: TCryptoLibByteArray); overload; class procedure WriteDerEncoded(const outStream: TStream; tag: Int32; const bytes: TCryptoLibByteArray); overload; static; class procedure WriteDerEncoded(const outStr: TStream; tag: Int32; const inStr: TStream); overload; static; end; implementation { TDerGenerator } constructor TDerGenerator.Create(const outStream: TStream); begin Inherited Create(outStream); end; constructor TDerGenerator.Create(const outStream: TStream; tagNo: Int32; isExplicit: Boolean); begin Inherited Create(outStream); F_tagged := true; F_isExplicit := isExplicit; F_tagNo := tagNo; end; class procedure TDerGenerator.WriteDerEncoded(const outStream: TStream; tag: Int32; const bytes: TCryptoLibByteArray); begin outStream.WriteByte(Byte(tag)); WriteLength(outStream, System.length(bytes)); outStream.Write(bytes[0], System.length(bytes)); end; procedure TDerGenerator.WriteDerEncoded(tag: Int32; const bytes: TCryptoLibByteArray); var tagNum, newTag: Int32; bOut: TMemoryStream; temp: TCryptoLibByteArray; begin if (F_tagged) then begin tagNum := F_tagNo or TAsn1Tags.Tagged; if (F_isExplicit) then begin newTag := F_tagNo or TAsn1Tags.Constructed or TAsn1Tags.Tagged; bOut := TMemoryStream.Create(); try WriteDerEncoded(bOut, tag, bytes); bOut.Position := 0; System.SetLength(temp, bOut.Size); bOut.Read(temp[0], bOut.Size); WriteDerEncoded(&Out, newTag, temp); finally bOut.Free; end; end else begin if ((tag and TAsn1Tags.Constructed) <> 0) then begin tagNum := tagNum or TAsn1Tags.Constructed; end; WriteDerEncoded(&Out, tagNum, bytes); end; end else begin WriteDerEncoded(&Out, tag, bytes); end; end; class procedure TDerGenerator.WriteDerEncoded(const outStr: TStream; tag: Int32; const inStr: TStream); begin WriteDerEncoded(outStr, tag, TStreams.ReadAll(inStr)); end; class procedure TDerGenerator.WriteLength(const outStr: TStream; length: Int32); var Size, val, i: Int32; begin if (length > 127) then begin Size := 1; val := length; val := TBits.Asr32(val, 8); while (val <> 0) do begin System.Inc(Size); val := TBits.Asr32(val, 8); end; outStr.WriteByte(Byte(Size or $80)); i := (Size - 1) * 8; while i >= 0 do begin outStr.WriteByte(Byte(TBits.Asr32(length, i))); System.Dec(i, 8); end; end else begin outStr.WriteByte(Byte(length)); end; end; end.
unit gTypes; //============================================================================= // gTypes.pas //============================================================================= // // Responsible for declaring the custom types used within the game, as well as // declaring constant values used throughout the application. // //============================================================================= interface uses sgTypes; const SCREEN_WIDTH = 1280; // Screen Width in pixels (default 1280) SCREEN_HEIGHT = 720; // Screen Height in pixels (default 720) MAP_WIDTH = 32; // # of tiles wide the map is MAP_HEIGHT = 32; // # of tiles high the map is TILE_WIDTH = 64; // The width of the tile bitmaps in pixels (default 64) TILE_HEIGHT = 32; // The height of the tile bitmps in pixels (default 32) DEBUG_MODE = false; // Whether debug output is enabled or not DRAW_TILE_NUMBERS = false; // Whether tiles draw their x,y coords CAMERA_SPEED = 5; // How fast the camera moves MOUSE_MOVE_PADDING = 10; // The padding for camera movement START_FULLSCREEN = false; // Whether the program starts in fullscreen APP_NAME = 'Isocity'; // The title of the program SHOW_SPLASHSCREEN = false; // Whether to show SwinGame splashscreen PAY_TIME = 120; // Number of seconds between income pay type TerrainType = (TERRAIN_NORMAL, TERRAIN_NOACCESS, TERRAIN_WATER, TERRAIN_ZONE, TERRAIN_COMZONE, TERRAIN_ROAD, TERRAIN_BUILDING, TERRAIN_REMOVE, TERRAIN_POWER, TERRAIN_PLACEWATER); BuildingType = (NOT_APPLICABLE, RES_SMALL, RES_MEDIUM, RES_LARGE, COM_SMALL, COM_MEDIUM, COM_LARGE, POWER, WATER); MouseStatus = (MOUSE_NORMAL, MOUSE_SELECTED, MOUSE_MOVE); GUIStatus = (MAIN_MENU, IN_GAME, SHUTDOWN); MenuStatus = (MAIN_SCREEN, CITY_NAME); BuildingEntity = record sprite : Sprite; buildingType : BuildingType; // team: TeamType; selected: Boolean; mouseOver: Boolean; hp: Integer; loc: Point2D; timer : Timer; // production_queue: Array of QueueItem; end; TileType = record bitmap : Bitmap; terrainType: TerrainType; end; TileTypes = Array of TileType; Tile = record bitmap : Bitmap; tType : TileType; terrainType: TerrainType; loc : Point2D; // unused for map hasBuilding : Boolean; building: BuildingEntity; end; TileArray = Array of Tile; NodePointer = ^Node; Node = record loc : Point2D; gScore, fCost, hScore : Double; parent : Integer; end; NodeArray = Array of Node; MapData = Array[0..MAP_WIDTH,0..MAP_HEIGHT] of Tile; UnitType = record img : Bitmap; icon : Bitmap; name : String; cost : Integer; requires : BuildingType; damage : Integer; end; Citizen = record home, work : Point2D; firstName, lastName : String; end; Citizens = Array of Citizen; UnitEntity = record bitmap : Bitmap; sprite : Sprite; selected : Boolean; hp: Integer; loc: Point2D; movingTo : Point2D; destination : Point2D; moveSpeed : Single; unitType : UnitType; toDelete : Boolean; mouseOver: Boolean; path: NodeArray; hasPath: Boolean; end; Building = record img : Bitmap; icon : String; name : String; buildingType : BuildingType; // team : TeamType; cost : Integer; requires : BuildingType; end; GameMouseLocation = record startX, startY, endX, endY : Single; hasSelected : Boolean; placingBuilding : Boolean; mouseStatus : MouseStatus; end; DeleteQueue = Array of Integer; GameData = record map : MapData; tileTypes: TileTypes; mouseLoc: GameMouseLocation; unitTypes: Array of UnitType; units : Array of UnitEntity; buildingTypes: Array of Building; buildings: Array of BuildingEntity; power, money : Integer; guiStatus : GUIStatus; menuStatus : MenuStatus; citizens : Citizens; names : Array of String; cityName : String; zoningType: TerrainType; moneyTimer : Timer; expenses : Array of Integer; end; const STARTUP_MODE = MAIN_MENU; // Which mode the game starts in procedure DebugMsg(msg : String); implementation procedure DebugMsg(msg : String); begin if DEBUG_MODE then WriteLn(msg); end; end.
unit FFSDBGrid; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids; type TFFSDBGrid = class(TDBGrid) private FBoolAsBMP: boolean; FImages: TImageList; FOnRecordEdit: TNotifyEvent; FOnRecordInsert: TNotifyEvent; FOnRecordDelete: TNotifyEvent; procedure SetBoolAsBMP(const Value: boolean); procedure SetImages(const Value: TImageList); procedure SetOnRecordDelete(const Value: TNotifyEvent); procedure SetOnRecordEdit(const Value: TNotifyEvent); procedure SetOnRecordInsert(const Value: TNotifyEvent); { Private declarations } protected { Protected declarations } procedure DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); override; procedure KeyPress(var Key:Char);override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public { Public declarations } constructor Create(AOwner:TComponent);override; published { Published declarations } property BoolAsBMP:boolean read FBoolAsBMP write SetBoolAsBMP; property Images:TImageList read FImages write SetImages; property OnRecordInsert:TNotifyEvent read FOnRecordInsert write SetOnRecordInsert; property OnRecordDelete:TNotifyEvent read FOnRecordDelete write SetOnRecordDelete; property OnRecordEdit:TNotifyEvent read FOnRecordEdit write SetOnRecordEdit; end; procedure Register; implementation uses db; procedure Register; begin RegisterComponents('FFS Data Entry', [TFFSDBGrid]); end; { TFFSDBGrid } constructor TFFSDBGrid.Create(AOwner: TComponent); begin inherited; ReadOnly := true; end; procedure TFFSDBGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var mndx : integer; handled : boolean; sl, st : integer; begin //gdSelected The cell is currently selected. //gdFocused The cell has input focus. //gdFixed The cell is in the fixed region of the grid. handled := false; if BoolAsBMP and (Column.Field.DataType = ftBoolean) and (Images.count >= 2) then begin mndx := ord(column.Field.AsBoolean); if gdFocused in state then inc(mndx,2); (*// if (gdSelected in State) and ({not (gdFocused in State) or} // ([dgRowSelect] * Options <> [])) then inc(mndx,2); *) handled := true; while Images.Count < mndx do dec(mndx,2); canvas.FillRect(Rect); sl := Rect.Left + (((Rect.Right - rect.Left) - Images.Width) div 2); st := Rect.Top + 1 + (((Rect.Bottom - rect.Top) - Images.Height) div 2); Images.draw(Canvas, sl, st, mndx) end; inherited; end; procedure TFFSDBGrid.KeyDown(var Key: Word; Shift: TShiftState); begin // insert check if (shift = []) and (key = vk_Insert) and (Assigned(FOnRecordInsert)) then begin key := 0; FOnRecordInsert(self); end; // delete check if (shift = []) and (key = vk_Delete) and (Assigned(FOnRecordDelete)) then begin key := 0; FOnRecordDelete(self); end; // now inherited inherited; end; procedure TFFSDBGrid.KeyPress(var Key: Char); begin if (Key = #13) and (Assigned(FOnRecordEdit)) then begin Key := #0; FOnRecordEdit(self); end; inherited; end; procedure TFFSDBGrid.SetBoolAsBMP(const Value: boolean); begin FBoolAsBMP := Value; end; procedure TFFSDBGrid.SetImages(const Value: TImageList); begin FImages := Value; end; procedure TFFSDBGrid.SetOnRecordDelete(const Value: TNotifyEvent); begin FOnRecordDelete := Value; end; procedure TFFSDBGrid.SetOnRecordEdit(const Value: TNotifyEvent); begin FOnRecordEdit := Value; end; procedure TFFSDBGrid.SetOnRecordInsert(const Value: TNotifyEvent); begin FOnRecordInsert := Value; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, RemObjects.Elements.EUnit; type QueueTest = public class (Test) private Data: Queue<Message>; public method Setup; override; method Contains; method Clear; method Peek; method Enqueue; method Dequeue; method ToArray; method Count; method Enumerator; end; Message = public class public constructor(aData: String; aCode: Integer); method {$IF NOUGAT}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean; override; property Data: String read write; property Code: Integer read write; end; implementation { Message } constructor Message(aData: String; aCode: Integer); begin Data := aData; Code := aCode; end; method Message.{$IF NOUGAT}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean; begin if obj = nil then exit false; if not (obj is Message) then exit false; var Msg := (obj as Message); exit (Data = Msg.Data) and (Code = Msg.Code); end; { QueueTest } method QueueTest.Setup; begin Data := new Queue<Message>; Data.Enqueue(new Message("One", 1)); Data.Enqueue(new Message("Two", 2)); Data.Enqueue(new Message("Three", 3)); end; method QueueTest.Contains; begin Assert.IsTrue(Data.Contains(Data.Peek)); Assert.IsTrue(Data.Contains(new Message("Two", 2))); Assert.IsFalse(Data.Contains(new Message("Two", 3))); Assert.IsFalse(Data.Contains(nil)); end; method QueueTest.Clear; begin Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method QueueTest.Peek; begin Assert.AreEqual(Data.Count, 3); var Actual := Data.Peek; Assert.AreEqual(Data.Count, 3); Assert.IsTrue(new Message("One", 1).Equals(Actual)); Data.Clear; Assert.Throws(->Data.Peek); end; method QueueTest.Enqueue; begin Assert.AreEqual(Data.Count, 3); var Msg := new Message("Four", 4); Data.Enqueue(Msg); Assert.AreEqual(Data.Count, 4); Assert.IsTrue(Data.Contains(Msg)); //must be last Data.Dequeue; Data.Dequeue; Data.Dequeue; Assert.IsTrue(Data.Peek.Equals(Msg)); //allow duplicates Data.Enqueue(Msg); Data.Enqueue(Msg); Assert.AreEqual(Data.Count, 3); Data.Enqueue(nil); Assert.AreEqual(Data.Count, 4); end; method QueueTest.Dequeue; begin var Actual := Data.Dequeue; Assert.IsNotNil(Actual); Assert.IsTrue(Actual.Equals(new Message("One", 1))); Assert.AreEqual(Data.Count, 2); Actual := Data.Dequeue; Assert.IsNotNil(Actual); Assert.AreEqual(Data.Count, 1); Assert.IsTrue(Actual.Equals(new Message("Two", 2))); Actual := Data.Dequeue; Assert.IsNotNil(Actual); Assert.AreEqual(Data.Count, 0); Assert.IsTrue(Actual.Equals(new Message("Three", 3))); Assert.Throws(->Data.Dequeue); Data.Enqueue(nil); Assert.AreEqual(Data.Count, 1); Actual := Data.Dequeue; Assert.IsNil(Actual); Assert.AreEqual(Data.Count, 0); end; method QueueTest.Count; begin Assert.AreEqual(Data.Count, 3); Data.Dequeue; Assert.AreEqual(Data.Count, 2); Data.Enqueue(new Message("", 0)); Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method QueueTest.ToArray; begin var Expected: array of Message := [new Message("One", 1), new Message("Two", 2), new Message("Three", 3)]; var Actual: array of Message := Data.ToArray; Assert.AreEqual(length(Actual), 3); for i: Integer := 0 to length(Expected) - 1 do Assert.IsTrue(Expected[i].Equals(Actual[i])); end; method QueueTest.Enumerator; begin var Expected: array of Message := [new Message("One", 1), new Message("Two", 2), new Message("Three", 3)]; var &Index: Integer := 0; for Item: Message in Data do begin Assert.IsTrue(Expected[&Index].Equals(Item)); inc(&Index); end; Assert.AreEqual(&Index, 3); end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.HttpServer Description : Http Server Author : Kike Pérez Version : 1.8 Created : 30/08/2019 Modified : 12/06/2020 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.HttpServer; {$i QuickLib.inc} interface uses {$IFDEF DEBUG_HTTPSERVER} Quick.Debug.Utils, {$ENDIF} SysUtils, Classes, IdHTTPServer, IdCustomHTTPServer, IdSSLOpenSSL, IdContext, Quick.Commons, Quick.Value, Quick.Logger.Intf, Quick.HttpServer.Types, Quick.HttpServer.Request, Quick.HttpServer.Response; type EHttpProtocolError = class(Exception); TRequestEvent = procedure(aRequest : IHttpRequest; aResponse : IHttpResponse) of object; TOnConnectEvent = procedure of object; TOnDisconnectEvent = procedure of object; TCustomErrorPages = class private fPath : string; fDynamicErrorPage : Boolean; fEnabled : Boolean; public property Path : string read fPath write fPath; property DynamicErrorPage : Boolean read fDynamicErrorPage write fDynamicErrorPage; property Enabled : Boolean read fEnabled write fEnabled; end; IHttpServer = interface ['{3B48198A-49F7-40A5-BBFD-39C78B6FA1EA}'] procedure SetOnRequest(aRequestEvent : TRequestEvent); function GetOnRequest : TRequestEvent; function GetCustomErrorPages: TCustomErrorPages; procedure SetCustomErrorPages(const Value: TCustomErrorPages); function GetLogger : ILogger; procedure SetLogger(const aLogger : ILogger); function GetHost: string; function GetPort: Integer; property OnNewRequest : TRequestEvent read GetOnRequest write SetOnRequest; property CustomErrorPages : TCustomErrorPages read GetCustomErrorPages write SetCustomErrorPages; property Host : string read GetHost; property Port : Integer read GetPort; property Logger : ILogger read GetLogger write SetLogger; procedure Start; procedure Stop; end; TCustomHttpServer = class(TInterfacedObject,IHttpServer) private fLogger : ILogger; fOnConnect : TOnConnectEvent; fOnDisconnect : TOnDisconnectEvent; fCustomErrorPages : TCustomErrorPages; procedure SetOnRequest(aRequestEvent : TRequestEvent); function GetOnRequest : TRequestEvent; function GetCustomErrorPages: TCustomErrorPages; procedure SetCustomErrorPages(const Value: TCustomErrorPages); function GetLogger : ILogger; procedure SetLogger(const aLogger : ILogger); function GetHost: string; function GetPort: Integer; protected fOnRequest : TRequestEvent; fHost : string; fPort : Integer; fSSLSecured : Boolean; procedure GetErrorPage(const aURL : string; aResponse : IHttpResponse); virtual; public constructor Create(const aHost : string; aPort : Integer; aSSLEnabled : Boolean; aLogger : ILogger = nil); virtual; destructor Destroy; override; property Host : string read GetHost; property Port : Integer read GetPort; property CustomErrorPages : TCustomErrorPages read GetCustomErrorPages write SetCustomErrorPages; property OnNewRequest : TRequestEvent read GetOnRequest write SetOnRequest; property OnConnect : TOnConnectEvent read fOnConnect write fOnConnect; property OnDisconnect : TOnDisconnectEvent read fOnDisconnect write fOnDisconnect; property Logger : ILogger read GetLogger write SetLogger; procedure Start; virtual; abstract; procedure Stop; virtual; abstract; end; THttpServer = class(TCustomHttpServer) private fHTTPServer : TidHTTPServer; procedure OnGetRequest(aContext: TIdContext; aRequestInfo: TIdHTTPRequestInfo; aResponseInfo: TIdHTTPResponseInfo); function GetSSLIOHandler : TIdServerIOHandlerSSLOpenSSL; function OnVerifyPeer(aCertificate: TIdX509; aOk: Boolean; aDepth, aError: Integer): Boolean; function GetRequestInfo(aRequestInfo : TIdHTTPRequestInfo) : THttpRequest; procedure SetResponseInfo(aResponseInfo : TIdHTTPResponseInfo; aResponse : IHttpResponse); procedure DoOnQuerySSLPort(aPort: Word; var vUseSSL: Boolean); procedure DoConnect(aContext: TIdContext); procedure DoDisconnect(aContext: TIdContext); protected procedure ProcessRequest(aRequest: IHttpRequest; aResponse: IHttpResponse); virtual; public constructor Create(const aHost : string; aPort : Integer; aSSLEnabled : Boolean; aLogger : ILogger = nil); override; destructor Destroy; override; procedure Start; override; procedure Stop; override; end; implementation { TCustomHttpServer } constructor TCustomHttpServer.Create(const aHost : string; aPort : Integer; aSSLEnabled : Boolean; aLogger : ILogger = nil); begin fCustomErrorPages := TCustomErrorPages.Create; fCustomErrorPages.Path := '.'; fCustomErrorPages.DynamicErrorPage := False; fCustomErrorPages.Enabled := False; if aHost.IsEmpty then fHost := '127.0.0.1' else fHost := aHost; {$IFDEF DELPHILINUX} if fHost = '127.0.0.1' then fHost := '0.0.0.0'; {$ENDIF} fPort := aPort; if aLogger = nil then begin fLogger := TNullLogger.Create; end else fLogger := aLogger; fSSLSecured := aSSLEnabled; end; destructor TCustomHttpServer.Destroy; begin fCustomErrorPages.Free; inherited; end; function TCustomHttpServer.GetCustomErrorPages: TCustomErrorPages; begin Result := fCustomErrorPages; end; procedure TCustomHttpServer.GetErrorPage(const aURL : string; aResponse : IHttpResponse); var filestream : TFileStream; pagestream : TStringStream; pagefilename : string; found : Boolean; content : string; begin content := ''; found := False; if (fCustomErrorPages.Enabled) then begin pagestream := TStringStream.Create; try //get specific error filename pagefilename := Format('%s\%d.html',[fCustomErrorPages.Path,aResponse.StatusCode]); found := FileExists(pagefilename); //get generic error type filanema if not found then begin pagefilename := Format('%s\%sxx.html',[fCustomErrorPages.Path,(aResponse.StatusCode).ToString[Low(string)]]); found := FileExists(pagefilename); end; //get generic error filename if not found then begin pagefilename := Format('%s\error.html',[fCustomErrorPages.Path]); found := FileExists(pagefilename); end; if found then begin filestream := TFileStream.Create(pagefilename,fmShareDenyNone); try pagestream.CopyFrom(filestream,filestream.Size); finally filestream.Free; end; content := pagestream.DataString; if fCustomErrorPages.DynamicErrorPage then begin content := StringReplace(content,'{{URL}}',aURL,[rfReplaceAll,rfIgnoreCase]); content := StringReplace(content,'{{STATUSCODE}}',aResponse.StatusCode.ToString,[rfReplaceAll,rfIgnoreCase]); content := StringReplace(content,'{{STATUSTEXT}}',aResponse.StatusText,[rfReplaceAll,rfIgnoreCase]); content := StringReplace(content,'{{CONTENT}}',aResponse.ContentText,[rfReplaceAll,rfIgnoreCase]); end; end; finally pagestream.Free; end; end; if not found then begin aResponse.ContentText := Format('<h2>%d Error: %s</h2>',[aResponse.StatusCode,aResponse.StatusText]) + Format('<h4>Message: %s</h4>',[aResponse.ContentText]); end else aResponse.ContentText := content; end; function TCustomHttpServer.GetHost: string; begin Result := fHost; end; function TCustomHttpServer.GetLogger: ILogger; begin Result := fLogger; end; function TCustomHttpServer.GetOnRequest: TRequestEvent; begin Result := fOnRequest; end; function TCustomHttpServer.GetPort: Integer; begin Result := fPort; end; procedure TCustomHttpServer.SetCustomErrorPages(const Value: TCustomErrorPages); begin fCustomErrorPages := Value; end; procedure TCustomHttpServer.SetLogger(const aLogger: ILogger); begin fLogger := aLogger; end; procedure TCustomHttpServer.SetOnRequest(aRequestEvent: TRequestEvent); begin fOnRequest := aRequestEvent; end; { THTTPServer } constructor THTTPServer.Create(const aHost : string; aPort : Integer; aSSLEnabled : Boolean; aLogger : ILogger = nil); begin inherited Create(aHost, aPort, aSSLEnabled, aLogger); Logger.Info('HTTPServer: Indy'); fHTTPServer := TIdHTTPServer.Create(nil); fHTTPServer.Bindings.Clear; //make sure there's no other bindings with fHTTPServer.Bindings.Add do begin IP := fHost; Port := fPort; end; if fSSLSecured then fHTTPServer.IOHandler := GetSSLIOHandler; fHTTPServer.OnCommandGet := OnGetRequest; fHTTPServer.OnCommandOther := OnGetRequest; fHTTPServer.OnConnect := DoConnect; fHTTPServer.OnDisconnect := DoDisconnect; //fHTTPServer.OnExecute := DoConnect; fHTTPServer.OnQuerySSLPort := DoOnQuerySSLPort; fHTTPServer.ServerSoftware := 'Quick.HttpServer'; fHTTPServer.MaxConnections := 0; fHTTPServer.AutoStartSession := False; fHTTPServer.KeepAlive := True; fHTTPServer.SessionState := False; fHTTPServer.ParseParams := False; end; destructor THTTPServer.Destroy; begin if Assigned(fHTTPServer) then begin if Assigned(fHTTPServer.IOHandler) then fHTTPServer.IOHandler.Free; fHTTPServer.Free; end; inherited; end; function THTTPServer.GetSSLIOHandler : TIdServerIOHandlerSSLOpenSSL; begin Result := TIdServerIOHandlerSSLOpenSSL.Create(nil); //Result.SSLOptions.RootCertFile := '.\ca.cert.pem'; Result.SSLOptions.CertFile := '.\server.cert.pem'; Result.SSLOptions.KeyFile := '.\server.key.pem'; Result.SSLOptions.Method := sslvSSLv23; Result.SSLOptions.Mode := sslmServer; Result.OnVerifyPeer := OnVerifyPeer; end; function THTTPServer.OnVerifyPeer(aCertificate: TIdX509; aOk: Boolean; aDepth, aError: Integer): Boolean; begin Result := aOk; end; function THttpServer.GetRequestInfo(aRequestInfo: TIdHTTPRequestInfo): THttpRequest; var i : Integer; uhost : TArray<string>; begin Result := THttpRequest.Create; if aRequestInfo.Host.Contains(':') then begin uhost := aRequestInfo.Host.Split([':']); Result.Host := uhost[0]; Result.Port := StrToIntDef(uhost[1],80); end else Result.Host := aRequestInfo.Host; Result.URL := aRequestInfo.URI; Result.ClientIP := aRequestInfo.RemoteIP; Result.UnParsedParams := aRequestInfo.QueryParams; Result.SetMethodFromString(aRequestInfo.Command); Result.UserAgent := aRequestInfo.UserAgent; Result.CacheControl := aRequestInfo.CacheControl; Result.Referer := aRequestInfo.Referer; Result.Content := aRequestInfo.PostStream; Result.ContentType := aRequestInfo.ContentType; Result.ContentEncoding := aRequestInfo.ContentEncoding; Result.ContentLength := aRequestInfo.ContentLength; {$IFDEF DEBUG_HTTPSERVER} TDebugger.Trace(Self,'Request: Headers (%s)',[aRequestInfo.RawHeaders.Text]); {$ENDIF} for i := 0 to aRequestInfo.RawHeaders.Count -1 do begin if not StrInArray(aRequestInfo.RawHeaders.Names[i],['Host','Accept-Encoding','Accept','User-Agent','Connection','Cache-Control']) then begin Result.Headers.Add(aRequestInfo.RawHeaders.Names[i],aRequestInfo.RawHeaders.Values[aRequestInfo.RawHeaders.Names[i]]); end; end; end; procedure THttpServer.SetResponseInfo(aResponseInfo: TIdHTTPResponseInfo; aResponse: IHttpResponse); var pair : TPairItem; begin for pair in aResponse.Headers do begin aResponseInfo.CustomHeaders.AddValue(pair.Name,pair.Value); end; aResponseInfo.ResponseNo := aResponse.StatusCode; aResponseInfo.ResponseText := aResponse.StatusText; aResponseInfo.ContentStream := aResponse.Content; aResponseInfo.ContentText := aResponse.ContentText; aResponseInfo.ContentType := aResponse.ContentType; //delegate stream to responseinfo aResponse.Content := nil; end; procedure THttpServer.ProcessRequest(aRequest: IHttpRequest; aResponse: IHttpResponse); begin if Assigned(fOnRequest) then fOnRequest(aRequest,aResponse); end; procedure THttpServer.DoConnect(aContext: TIdContext); begin {$IFDEF DEBUG_HTTPSERVER} TDebugger.Enter(Self,'DoConnect').TimeIt; {$ENDIF} Logger.Debug('Client connected'); if Assigned(fOnConnect) then fOnConnect; end; procedure THttpServer.DoDisconnect(aContext: TIdContext); begin {$IFDEF DEBUG_HTTPSERVER} TDebugger.Enter(Self,'DoDisconnect').TimeIt; {$ENDIF} Logger.Debug('Client disconnected!'); if Assigned(fOnDisconnect) then fOnDisconnect; end; procedure THTTPServer.DoOnQuerySSLPort(aPort: Word; var vUseSSL: Boolean); begin vUseSSL := (aPort <> 443); end; procedure THTTPServer.OnGetRequest(aContext: TIdContext; aRequestInfo: TIdHTTPRequestInfo; aResponseInfo: TIdHTTPResponseInfo); var request : IHttpRequest; response : IHttpResponse; begin {$IFDEF DEBUG_HTTPSERVER} TDebugger.Enter(Self,Format('OnGetRequest (%s %s)',[aRequestInfo.Command,aRequestInfo.URI])).TimeIt; {$ENDIF} Logger.Debug('Request: %s',[aRequestInfo.RawHTTPCommand]); request := GetRequestInfo(aRequestInfo); response := THttpResponse.Create; //process incoming Request try ProcessRequest(request,response); except on E : Exception do begin //get unexpected exception if E.InheritsFrom(EControlledException) then begin Logger.Error('Request: %s %s [%d %s] %s',[request.GetMethodAsString,request.URL, response.StatusCode, response.StatusText,e.Message]); response.ContentText := response.ContentText + '<BR>' + e.Message; end else begin if response.StatusCode = 200 then begin response.StatusCode := 500; response.StatusText := 'Internal server error'; end; response.ContentText := e.Message; //log error if response.StatusCode = 404 then Logger.Warn('Request: %s %s [%d %s] %s',[request.GetMethodAsString,request.URL, response.StatusCode, response.StatusText,e.Message]) else Logger.Error('Request: %s %s [%d %s] %s',[request.GetMethodAsString,request.URL, response.StatusCode, response.StatusText,e.Message]); end; end; end; //check if need return error page if response.StatusCode > 399 then GetErrorPage(aRequestInfo.URI,response); //return response to client {$IFDEF DEBUG_HTTPSERVER} TDebugger.TimeIt(Self,Format('OnGetRequest (%s)',[aRequestInfo.URI]),'SendResponse'); {$ENDIF} SetResponseInfo(aResponseInfo,response); aResponseInfo.WriteContent; end; procedure THttpServer.Start; begin fHTTPServer.Active := True; end; procedure THttpServer.Stop; begin fHTTPServer.Active := False; end; end.
namespace RemObjects.Train.API; uses RemObjects.Train, System.Threading, RemObjects.Script.EcmaScript, RemObjects.Script.EcmaScript.Internal, System.Text, System.Text.RegularExpressions, System.Xml.Linq, System.Linq, System.IO, System.Runtime.InteropServices; type [PluginRegistration] EBuildPlugin = public class(IPluginRegistration) public method Register(aServices: IApiRegistrationServices); begin //fServices := aServices; var lEBuildObject := aServices.RegisterObjectValue('ebuild'); lEBuildObject.AddValue('runCustomEBuild', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(EBuildPlugin), 'runCustomEBuild')); lEBuildObject.AddValue('runEBuild', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(EBuildPlugin), 'runEBuild')); lEBuildObject.AddValue('build', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(EBuildPlugin), 'build')); lEBuildObject.AddValue('rebuild', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(EBuildPlugin), 'rebuild')); lEBuildObject.AddValue('clean', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(EBuildPlugin), 'clean')); end; [WrapAs('ebuild.runCustomEBuild', SkipDryRun := false)] class method runCustomEBuild(aServices: IApiRegistrationServices; ec: ExecutionContext; aEBuildExe: String; aProject: String; aOtherParameters: String): Boolean; begin aEBuildExe := aServices.ResolveWithBase(ec, aEBuildExe); result := doRunCustomEBuild(aServices, ec, aEBuildExe, aProject, aOtherParameters); end; [WrapAs('ebuild.runEBuild', SkipDryRun := false)] class method runEBuild(aServices: IApiRegistrationServices; ec: ExecutionContext; aProject: String; aOtherParameters: String): Boolean; begin var lEBuildExe := FindEBuildExe(); if not assigned(lEBuildExe) then raise new Exception("EBuild.exe culd not be located."); result := doRunCustomEBuild(aServices, ec, lEBuildExe, aProject, aOtherParameters); end; [WrapAs('ebuild.build', SkipDryRun := false)] class method build(aServices: IApiRegistrationServices; ec: ExecutionContext; aProject: String; aOtherParameters: String): Boolean; begin result := runEBuild(aServices, ec, aProject, ("--build "+coalesce(aOtherParameters, "")).Trim); end; [WrapAs('ebuild.rebuild', SkipDryRun := false)] class method rebuild(aServices: IApiRegistrationServices; ec: ExecutionContext; aProject: String; aOtherParameters: String): Boolean; begin result := runEBuild(aServices, ec, aProject, ("--rebuild --no-cache "+coalesce(aOtherParameters, "")).Trim); end; [WrapAs('ebuild.clean', SkipDryRun := false)] class method clean(aServices: IApiRegistrationServices; ec: ExecutionContext; aProject: String; aOtherParameters: String): Boolean; begin result := runEBuild(aServices, ec, aProject, ("--clean "+coalesce(aOtherParameters, "")).Trim); end; private // cloned from EBuild itself, which we don't want to reference in Ttain class method FindEBuildExe: nullable String; begin if (RemObjects.Elements.RTL.Environment.OS = RemObjects.Elements.RTL.OperatingSystem.macOS) /*or (Environment.OS = OperatingSystem.Linux)*/ then begin var lPath := "/usr/local/bin/ebuild"; if File.Exists(lPath) then begin var lEBuildScript := File.ReadAllText(lPath).Trim(); //mono "/Users/mh/Code/Elements/Bin/EBuild.exe" "$@" if lEBuildScript.StartsWith('mono "') and lEBuildScript.EndsWith('" "$@"') then begin lPath := lEBuildScript.Substring(6, length(lEBuildScript)-12); if File.Exists(lPath) then exit lPath; end; end; end else if defined("ECHOES") and (RemObjects.Elements.RTL.Environment.OS = RemObjects.Elements.RTL.OperatingSystem.Windows) then begin var lKey := Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\RemObjects\Elements"); if assigned(lKey) then begin if assigned(lKey.GetValue("InstallDir"):ToString) then begin var lPath := Path.Combine(lKey.GetValue("InstallDir"):ToString, "Bin", "EBuild.exe"); if assigned(lPath) and File.Exists(lPath) then exit lPath; end; var lPath := lKey.GetValue("EBuild"):ToString; if assigned(lPath) and File.Exists(lPath) then exit lPath; end; lKey := Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\RemObjects\Elements"); if (lKey <> nil) then begin if assigned(lKey.GetValue("InstallDir"):ToString) then begin var lPath := Path.Combine(lKey.GetValue("InstallDir"):ToString, "Bin", "EBuild.exe"); if assigned(lPath) and File.Exists(lPath) then exit lPath; end; var lPath := lKey.GetValue("EBuild"):ToString; if assigned(lPath) and File.Exists(lPath) then exit lPath; end; end; end; class method doRunCustomEBuild(aServices: IApiRegistrationServices; ec: ExecutionContext; aEBuildExe: String; aProject: String; aOtherParameters: String): Boolean; begin var lSuccess := true; var lLogger := new DelayedLogger(); aServices.Engine.Logger.Enter(true,'ebuild', (aProject+" "+aOtherParameters).Trim); try if aServices.Engine.DryRun then begin aServices.Engine.Logger.LogMessage('Dry run.'); exit true; end; var sb := new System.Text.StringBuilder; aProject := aServices.ResolveWithBase(ec, aProject); var lExitCode := Shell.ExecuteProcess(aEBuildExe, '"'+aProject+'" '+aOtherParameters, aServices.Engine.WorkDir, false , a-> begin if assigned(a) then begin locking sb do sb.AppendLine(a); lLogger.LogError(a); if aServices.Engine.LiveOutput then aServices.Engine.Logger.LogLive("(stderr) "+a); end; end, a-> begin if assigned(a) then begin locking sb do sb.AppendLine(a); if a:StartsWith("E:") then lLogger.LogError("Error: "+a); if aServices.Engine.LiveOutput then aServices.Engine.Logger.LogLive(a); end; end, [], nil); lLogger.LogInfo(sb.ToString); if lExitCode ≠ 0 then begin //var lErrors := new System.Text.StringBuilder; //for each l in sb.ToString.Split(#10) do begin //l := l.Trim(); //if l.StartsWith("E:") then //lErrors.AppendLine("Error: "+l.Substring(2).Trim()); //end; lSuccess := false; //aServices.Engine.Logger.LogError(lErrors.ToString); //locking sb do aServices.Engine.Logger.LogMessage('Output: '#13#10+sb.ToString); raise new Exception("EBuild failed with exit code "+lExitCode); end; //locking sb do aServices.Engine.Logger.LogInfo('Output: '#13#10+sb.ToString); //except //on e: Exception do begin //aServices.Engine.Logger.LogError('Error calling Process.Execute: '+e.Message); //writeLn(e.ToString()); //raise new AbortException; //end; finally lLogger.Replay(aServices.Logger); aServices.Engine.Logger.Exit(true,String.Format('ebuild({0})', aProject), if not lSuccess then RemObjects.Train.FailMode.Yes else RemObjects.Train.FailMode.No); end; end; end; end.
unit Model.Menus; interface uses Common.ENum, FireDAC.Comp.Client; type TMenus = class private FCodigo: Integer; FSistema: Integer; Fmodulo: Integer; FDescricao: String; FAcao: TAcao; public property Sistema: Integer read FSistema write FSistema; property Modulo: Integer read Fmodulo write FModulo; property Codigo: Integer read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TMenus } uses DAO.Menus; function TMenus.Gravar: Boolean; var menusDAO : TMenusDAO; begin try Result := False; menusDAO := TMenusDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := menusDAO.Inserir(Self); Common.ENum.tacAlterar: Result := menusDAO.Alterar(Self); Common.ENum.tacExcluir: Result := menusDAO.Excluir(Self); end; finally menusDAO.Free; end; end; function TMenus.Localizar(aParam: array of variant): TFDQuery; var menusDAO : TMenusDAO; begin try menusDAO := TMenusDAO.Create; Result := menusDAO.Pesquisar(aParam); finally menusDAO.Free; end; end; end.
unit functionhandling; {$mode objfpc}{$H+} interface uses Classes, SysUtils, typehandling; procedure RemoveMonster(index: integer); function IntToStr(number: integer): string; implementation //Removes the monster at the specified index procedure RemoveMonster(index: integer); var i: integer; p: PMonster; begin p := level^.monsters[index]; for i := index to (length(level^.monsters) - 1) do begin level^.monsters[i] := level^.monsters[i + 1]; end; setlength(level^.monsters, length(level^.monsters) - 1); dispose(p); end; //converts an integer to a string function IntToStr(number: integer): string; var temp: string; begin while number <> 0 do begin temp := chr(Ord('0') + (number mod 10)) + temp; number := number div 10; end; IntToStr := temp; end; end.
{!DOCTOPIC}{ Type » TPoint } {!DOCREF} { @method: function TPoint.Magnitude(): Extended; @desc: Returns the magnitude/length of the tpoint } function TPoint.Magnitude(): Extended; begin Result := Sqrt(Sqr(Self.x) + Sqr(Self.y)); end; {!DOCREF} { @method: function TPoint.Random(xR,yR: Int32): TPoint; @desc: Adds a random value in the range c'-xR..xR' and c'-yR..yR' to the point. } function TPoint.Random(xR,yR: Int32): TPoint; begin Result.x := Self.x + RandomRange(-xR,xR); Result.y := Self.y + RandomRange(-yR,yR); end; {!DOCREF} { @method: function TPoint.Random(R: Int32): TPoint; @desc: Adds a random value in the range c'-R..R' to the point. } function TPoint.Random(R: Int32): TPoint; overload; begin Result.x := Self.x + RandomRange(-R,R); Result.y := Self.y + RandomRange(-R,R); end; {!DOCREF} { @method: function TPoint.DistanceTo(Pt:TPoint): Extended; @desc: Returns the Distance from Pt } function TPoint.DistanceTo(Pt:TPoint): Extended; begin Result := Math.DistEuclidean(Self, Pt); end; {!DOCREF} { @method: function TPoint.DistanceToLine(sA, sB:TPoint): Extended; @desc: Returns the Distance from given line segment defined by sA-sB } function TPoint.DistanceToLine(sA, sB:TPoint): Extended; begin Result := Math.DistToLine(Self, sA, sB); end; {!DOCREF} { @method: procedure TPoint.Offset(pt:TPoint); @desc: Moves the point } {$IFNDEF SRL6} procedure TPoint.Offset(pt:TPoint); begin Self.x := Self.x + pt.x; Self.y := Self.y + pt.y; end; {$ENDIF} {!DOCREF} { @method: function TPoint.Rotate(Angle:Extended; cx,cy:Integer): TPoint; @desc: Rotates the point, lazy method (returns a new point). } {$IFNDEF SRL6} function TPoint.Rotate(Angle:Extended; cx,cy:Integer): TPoint; {$ELSE} function TPoint._Rotate(Angle:Extended; cx,cy:Integer): TPoint; {$ENDIF} begin Result := RotatePoint(Self, Angle, cx,cy); end; {!DOCREF} { @method: function TPoint.Flip(): TPoint; @desc: x->y, y->x } function TPoint.Flip(): TPoint; begin Result := Point(Self.y,Self.x); end; {!DOCREF} { @method: function TPoint.EQ(PT:TPoint): Boolean; @desc: Compares "EQual" } function TPoint.EQ(PT:TPoint): Boolean; begin Result := (Self.x = PT.x) and (Self.y = PT.y); end; {!DOCREF} { @method: function TPoint.LT(PT:TPoint): Boolean; @desc: Compares "Less Then" } function TPoint.LT(PT:TPoint): Boolean; begin Result := (Self.X < PT.X) and (Self.Y < PT.Y); end; {!DOCREF} { @method: function TPoint.GT(PT:TPoint): Boolean; @desc: Compares "Greater Then" } function TPoint.GT(PT:TPoint): Boolean; begin Result := not((Self.X <= PT.X) and (Self.Y <= PT.Y)); end; {!DOCREF} { @method: function TPoint.Compare(Pt:TPoint): TComparator; @desc: Compares the two points. Result = (__LT__,__EQ__,__GT__); } function TPoint.Compare(Pt:TPoint): TComparator; begin if (Self.x = PT.x) and (Self.y = PT.y) then Exit(__EQ__); if (Self.X <= PT.X) and (Self.Y <= PT.Y) then Exit(__LT__) else Exit(__GT__); end; {$IFNDEF SRL6} {!DOCREF} { @method: procedure TPoint.Swap(var PT:TPoint); @desc: Swaps the points } procedure TPoint.Swap(var PT:TPoint); var tmp:TPoint; begin tmp := Self; Self := Pt; PT := tmp; end; {$ENDIF} {!DOCREF} { @method: function TPoint.InBox(B:TBox): Boolean; @desc: Checks if the Point is within the given box. } function TPoint.InBox(B:TBox): Boolean; begin Result := InRange(Self.x, B.x1, B.x2) and InRange(Self.y, B.y1, B.y2); end; {$IFNDEF SRL6} {!DOCREF} { @method: function TPoint.RandRange(lo,hi:Int32): TPoint; @desc: Randomizes a point by the given lower and upper bounds. } function TPoint.RandRange(lo,hi:Int32): TPoint; begin Result.x := Self.x + Rand.RandInt(lo,hi); Result.y := Self.y + Rand.RandInt(lo,hi); end; {!DOCREF} { @method: function TPoint.RandRange(x1,y1,x2,y2:Int32): TPoint; overload; @desc: Randomizes a point by the given lower and upper bounds for each axis. } function TPoint.RandRange(x1,y1,x2,y2:Int32): TPoint; overload; begin Result.x := Self.x + Rand.RandInt(x1,x2); Result.y := Self.y + Rand.RandInt(y1,y2); end; {$ENDIF} {!DOCREF} { @method: function TPoint.Gauss(Stddev: Extended): TPoint; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. } function TPoint.Gauss(Stddev: Extended): TPoint; begin {$IFDEF SRL6} Result := Randm.GaussPt(Self,Stddev); {$ELSE} Result := Rand.GaussPt(Self,Stddev); {$ENDIF} end; {!DOCREF} { @method: function TPoint.Gauss(Stddev,MaxDev: Extended): TPoint; overload; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. Takes an extra parameter to encapsule the point within a given range (maxDev). } function TPoint.Gauss(Stddev,MaxDev: Extended): TPoint; overload; begin {$IFDEF SRL6} Result := Randm.GaussPt(Self,StdDev, MaxDev); {$ELSE} Result := Rand.GaussPt(Self,StdDev, MaxDev); {$ENDIF} end; {!DOCREF} { @method: function TPoint.AngleTo(PT: TPoint): Extended; @desc: Computes the angle between c'Self' and c'PT'. } function TPoint.AngleTo(PT: TPoint): Extended; begin Result := ArcTan2(-(PT.y-Self.y), (PT.x-Self.x)); end;
unit BaiduMapAPI.NaviService; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 导航服务 单元 //官方链接:http://lbsyun.baidu.com/ //TBaiduMapNaviService 百度地图 导航服务 interface uses FMX.Platform, BaiduMapAPI.NaviService.CommTypes; type IBaiduMapNaviService = interface ['{505FA6D0-7135-49D8-B964-3921AE206B98}'] procedure initService(AKey:string; ATTSKey:string); procedure startNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); end; TBaiduMapNaviService = class(TInterfacedObject, IBaiduMapNaviService) private FScale:Single; FNaviKey:string; FTTSKey:string; procedure SetVisible(const Value: Boolean); protected procedure DoinitService; virtual; abstract; procedure DostartNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); virtual; abstract; procedure DoSetVisible(const Value: Boolean); virtual; abstract; procedure DoUpdateBaiduNaviFromControl; virtual; abstract; property Scale:Single read FScale; property NaviKey:String read FNaviKey; property TTSKey:String read FTTSKey; public procedure UpdateBaiduNaviFromControl; procedure initService(AKey:string; ATTSKey:string); procedure startNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); property Visible:Boolean write SetVisible; constructor Create; end; TBaiduMapNavi = class(TObject) private FNaviService:TBaiduMapNaviService; public constructor Create; destructor Destroy; override; property NaviService:TBaiduMapNaviService read FNaviService; end; implementation {$IFDEF IOS} uses BaiduMapAPI.NaviService.iOS; {$ENDIF} {$IFDEF ANDROID} uses BaiduMapAPI.NaviService.Android; {$ENDIF ANDROID} { TBaiduMapNaviService } constructor TBaiduMapNaviService.Create; var ScreenSrv:IFMXScreenService; begin inherited Create; if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenSrv) then FScale := ScreenSrv.GetScreenScale else FScale := 1; end; procedure TBaiduMapNaviService.initService(AKey:string; ATTSKey:string); begin FNaviKey:=AKey; FTTSKey:=ATTSKey; DoinitService; end; procedure TBaiduMapNaviService.SetVisible(const Value: Boolean); begin DoSetVisible(Value); end; procedure TBaiduMapNaviService.startNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); begin DostartNaviRoutePlan(RoutePlan); end; procedure TBaiduMapNaviService.UpdateBaiduNaviFromControl; begin DoUpdateBaiduNaviFromControl; end; { TBaiduMapNavi } constructor TBaiduMapNavi.Create; begin inherited Create; {$IFDEF IOS} FNaviService:=TiOSBaiduMapNaviService.Create; {$ENDIF} {$IFDEF ANDROID} FNaviService:=TAndroidBaiduMapNaviService.Create; {$ENDIF ANDROID} FNaviService.Visible:=False; end; destructor TBaiduMapNavi.Destroy; begin FNaviService.Free; inherited; end; end.
unit helper; {$mode objfpc}{$H+} interface uses DwmApi, Forms, Graphics, IdExplicitTLSClientServerBase, IdMessage, IdSMTP, IdSSLOpenSSL, JwaWinGDI, SysUtils, Windows; function ScaleXTo(const SizeX, ToDPI: Integer): Integer; function ScaleYTo(const SizeY, ToDPI: Integer): Integer; function GetWindowRect(Handle: HWND; var lpRect: TRect): Boolean; function CopyDesktop(Image: TPNGImage; MaxWidth, MaxHeight: Int32): Boolean; procedure SaveToFile(Image: TPNGImage; FileName: string); function MakeSMTP(AHost: string; APort: UInt16; AUseTLS: TIdUseTLS; AUsername, APassword: string): TIdSMTP; function Sendmail(AHost: string; APort: UInt16; AUseTLS: TIdUseTLS; AUsername, APassword: string; Message: TIdMessage): Boolean; implementation function ScaleXTo(const SizeX, ToDPI: Integer): Integer; begin Result := MulDiv(SizeX, ToDPI, ScreenInfo.PixelsPerInchX * 100 div 96); end; function ScaleYTo(const SizeY, ToDPI: Integer): Integer; begin Result := MulDiv(SizeY, ToDPI, ScreenInfo.PixelsPerInchY * 100 div 96); end; function GetWindowRect(Handle: HWND; var lpRect: TRect): Boolean; begin Result := (DwmGetWindowAttribute(Handle, DWMWA_EXTENDED_FRAME_BOUNDS, @lpRect, SizeOf(lpRect)) = S_OK); if not Result then begin Result := Windows.GetWindowRect(Handle, lpRect); end; end; function CopyDesktop(Image: TPNGImage; MaxWidth, MaxHeight: Int32): Boolean; var hSubject: HWND; hSubjectDC: HDC; begin if Image = nil then Exit(False); hSubject := GetDesktopWindow; Image.Width := Min(ScaleXTo(Screen.DesktopWidth, 100), MaxWidth); Image.Height := Min(ScaleYTo(Screen.DesktopHeight, 100), MaxHeight); Image.Canvas.FillRect(0, 0, Image.Width, Image.Height); hSubjectDC := GetDC(hSubject); try BitBlt(Image.Canvas.Handle, 0, 0, Image.Width, Image.Height, hSubjectDC, ScaleXTo(Screen.DesktopLeft, 100), ScaleYTo(Screen.DesktopTop, 100), SRCCOPY or CAPTUREBLT); Result := True; finally ReleaseDC(hSubject, hSubjectDC); end; end; procedure SaveToFile(Image: TPNGImage; FileName: string); begin ForceDirectories(ExtractFilePath(FileName)); if Image <> nil then begin Image.SaveToFile(FileName); end else begin FileClose(FileCreate(FileName)); end; end; function MakeSMTP(AHost: string; APort: UInt16; AUseTLS: TIdUseTLS; AUsername, APassword: string): TIdSMTP; begin Result := TIdSMTP.Create(nil); try if AUseTLS <> utNoTLSSupport then begin Result.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Result); end; Result.Host := AHost; Result.Port := APort; Result.UseTLS := AUseTLS; Result.Username := AUsername; Result.Password := APassword; except FreeAndNil(Result); end; end; function Sendmail(AHost: string; APort: UInt16; AUseTLS: TIdUseTLS; AUsername, APassword: string; Message: TIdMessage): Boolean; begin Result := False; with MakeSMTP(AHost, APort, AUseTLS, AUsername, APassword) do try Connect; Send(Message); Result := True; finally Free; end; end; initialization InitDwmLibrary; end.
unit VSM.Rest.Enumeradores; interface type TVSMRestTipoAutenticacao = (tpNoAuth, tpApiKey, tpBearerToken, tpBasicAuth, tpDigestAuth, tpOAuth1, tpOAuth2, tpHawkAuthentication, tpAWSSignature, tpNTLMAuthentication, tpAkamaiEdgeGrid ); // 0-NoAuth, 1-ApiKey, 2-BearerToken, 3-BasicAuth, 4-DigestAuth, // 5-OAuth1, 6-OAuth2, 7-HawkAuthentication, 8-AWSSignature, 9-NTLMAuthentication, 10-AkamaiEdgeGrid implementation end.
unit VCMFormsProcessingPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\VCMFormsProcessingPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "VCMFormsProcessingPack" MUID: (54DCB28C0273) {$Include w:\common\components\rtl\Garant\ScriptEngine\vcmDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCM)} uses l3ImplUses , vcmEntityForm , tfwGlobalKeyWord , tfwScriptingInterfaces , vcmForm , TypInfo , tfwPropertyLike , tfwTypeInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *54DCB28C0273impl_uses* //#UC END# *54DCB28C0273impl_uses* ; type TkwVcmFormManualUpdateActions = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:Form:ManualUpdateActions } private procedure vcm_Form_ManualUpdateActions(const aCtx: TtfwContext; aForm: TvcmForm); {* Реализация слова скрипта vcm:Form:ManualUpdateActions } 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;//TkwVcmFormManualUpdateActions TkwVcmFormReloadToolbars = {final} class(TtfwGlobalKeyWord) {* Слово скрипта vcm:Form:ReloadToolbars } private procedure vcm_Form_ReloadToolbars(const aCtx: TtfwContext; aForm: TvcmEntityForm); {* Реализация слова скрипта vcm:Form:ReloadToolbars } 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;//TkwVcmFormReloadToolbars TkwPopFormIsFloatingStateAndParentNotVisible = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Form:IsFloatingStateAndParentNotVisible } private function IsFloatingStateAndParentNotVisible(const aCtx: TtfwContext; aForm: TvcmEntityForm): Boolean; {* Реализация слова скрипта pop:Form:IsFloatingStateAndParentNotVisible } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopFormIsFloatingStateAndParentNotVisible TkwPopFormIsFloatingState = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Form:IsFloatingState } private function IsFloatingState(const aCtx: TtfwContext; aForm: TvcmEntityForm): Boolean; {* Реализация слова скрипта pop:Form:IsFloatingState } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopFormIsFloatingState TkwPopFormUserType = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Form:UserType } private function UserType(const aCtx: TtfwContext; aForm: TvcmEntityForm): Integer; {* Реализация слова скрипта pop:Form:UserType } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopFormUserType TkwPopFormFormID = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Form:FormID } private function FormID(const aCtx: TtfwContext; aForm: TvcmEntityForm): AnsiString; {* Реализация слова скрипта pop:Form:FormID } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopFormFormID procedure TkwVcmFormManualUpdateActions.vcm_Form_ManualUpdateActions(const aCtx: TtfwContext; aForm: TvcmForm); {* Реализация слова скрипта vcm:Form:ManualUpdateActions } //#UC START# *57BACF5E010C_57BACF5E010C_Word_var* //#UC END# *57BACF5E010C_57BACF5E010C_Word_var* begin //#UC START# *57BACF5E010C_57BACF5E010C_Word_impl* aForm.ManualUpdateActions; //#UC END# *57BACF5E010C_57BACF5E010C_Word_impl* end;//TkwVcmFormManualUpdateActions.vcm_Form_ManualUpdateActions class function TkwVcmFormManualUpdateActions.GetWordNameForRegister: AnsiString; begin Result := 'vcm:Form:ManualUpdateActions'; end;//TkwVcmFormManualUpdateActions.GetWordNameForRegister function TkwVcmFormManualUpdateActions.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmFormManualUpdateActions.GetResultTypeInfo function TkwVcmFormManualUpdateActions.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmFormManualUpdateActions.GetAllParamsCount function TkwVcmFormManualUpdateActions.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmForm)]); end;//TkwVcmFormManualUpdateActions.ParamsTypes procedure TkwVcmFormManualUpdateActions.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmForm; begin try l_aForm := TvcmForm(aCtx.rEngine.PopObjAs(TvcmForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_Form_ManualUpdateActions(aCtx, l_aForm); end;//TkwVcmFormManualUpdateActions.DoDoIt procedure TkwVcmFormReloadToolbars.vcm_Form_ReloadToolbars(const aCtx: TtfwContext; aForm: TvcmEntityForm); {* Реализация слова скрипта vcm:Form:ReloadToolbars } //#UC START# *57F365EB014D_57F365EB014D_Word_var* //#UC END# *57F365EB014D_57F365EB014D_Word_var* begin //#UC START# *57F365EB014D_57F365EB014D_Word_impl* aForm.ReloadToolbars; //#UC END# *57F365EB014D_57F365EB014D_Word_impl* end;//TkwVcmFormReloadToolbars.vcm_Form_ReloadToolbars class function TkwVcmFormReloadToolbars.GetWordNameForRegister: AnsiString; begin Result := 'vcm:Form:ReloadToolbars'; end;//TkwVcmFormReloadToolbars.GetWordNameForRegister function TkwVcmFormReloadToolbars.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwVcmFormReloadToolbars.GetResultTypeInfo function TkwVcmFormReloadToolbars.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwVcmFormReloadToolbars.GetAllParamsCount function TkwVcmFormReloadToolbars.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmEntityForm)]); end;//TkwVcmFormReloadToolbars.ParamsTypes procedure TkwVcmFormReloadToolbars.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmEntityForm; begin try l_aForm := TvcmEntityForm(aCtx.rEngine.PopObjAs(TvcmEntityForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmEntityForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except vcm_Form_ReloadToolbars(aCtx, l_aForm); end;//TkwVcmFormReloadToolbars.DoDoIt function TkwPopFormIsFloatingStateAndParentNotVisible.IsFloatingStateAndParentNotVisible(const aCtx: TtfwContext; aForm: TvcmEntityForm): Boolean; {* Реализация слова скрипта pop:Form:IsFloatingStateAndParentNotVisible } begin Result := aForm.IsFloatingStateAndParentNotVisible; end;//TkwPopFormIsFloatingStateAndParentNotVisible.IsFloatingStateAndParentNotVisible class function TkwPopFormIsFloatingStateAndParentNotVisible.GetWordNameForRegister: AnsiString; begin Result := 'pop:Form:IsFloatingStateAndParentNotVisible'; end;//TkwPopFormIsFloatingStateAndParentNotVisible.GetWordNameForRegister function TkwPopFormIsFloatingStateAndParentNotVisible.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopFormIsFloatingStateAndParentNotVisible.GetResultTypeInfo function TkwPopFormIsFloatingStateAndParentNotVisible.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopFormIsFloatingStateAndParentNotVisible.GetAllParamsCount function TkwPopFormIsFloatingStateAndParentNotVisible.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmEntityForm)]); end;//TkwPopFormIsFloatingStateAndParentNotVisible.ParamsTypes procedure TkwPopFormIsFloatingStateAndParentNotVisible.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsFloatingStateAndParentNotVisible', aCtx); end;//TkwPopFormIsFloatingStateAndParentNotVisible.SetValuePrim procedure TkwPopFormIsFloatingStateAndParentNotVisible.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmEntityForm; begin try l_aForm := TvcmEntityForm(aCtx.rEngine.PopObjAs(TvcmEntityForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmEntityForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsFloatingStateAndParentNotVisible(aCtx, l_aForm)); end;//TkwPopFormIsFloatingStateAndParentNotVisible.DoDoIt function TkwPopFormIsFloatingState.IsFloatingState(const aCtx: TtfwContext; aForm: TvcmEntityForm): Boolean; {* Реализация слова скрипта pop:Form:IsFloatingState } begin Result := aForm.IsFloatingState; end;//TkwPopFormIsFloatingState.IsFloatingState class function TkwPopFormIsFloatingState.GetWordNameForRegister: AnsiString; begin Result := 'pop:Form:IsFloatingState'; end;//TkwPopFormIsFloatingState.GetWordNameForRegister function TkwPopFormIsFloatingState.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopFormIsFloatingState.GetResultTypeInfo function TkwPopFormIsFloatingState.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopFormIsFloatingState.GetAllParamsCount function TkwPopFormIsFloatingState.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmEntityForm)]); end;//TkwPopFormIsFloatingState.ParamsTypes procedure TkwPopFormIsFloatingState.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsFloatingState', aCtx); end;//TkwPopFormIsFloatingState.SetValuePrim procedure TkwPopFormIsFloatingState.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmEntityForm; begin try l_aForm := TvcmEntityForm(aCtx.rEngine.PopObjAs(TvcmEntityForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmEntityForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsFloatingState(aCtx, l_aForm)); end;//TkwPopFormIsFloatingState.DoDoIt function TkwPopFormUserType.UserType(const aCtx: TtfwContext; aForm: TvcmEntityForm): Integer; {* Реализация слова скрипта pop:Form:UserType } begin Result := aForm.UserType; end;//TkwPopFormUserType.UserType class function TkwPopFormUserType.GetWordNameForRegister: AnsiString; begin Result := 'pop:Form:UserType'; end;//TkwPopFormUserType.GetWordNameForRegister function TkwPopFormUserType.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopFormUserType.GetResultTypeInfo function TkwPopFormUserType.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopFormUserType.GetAllParamsCount function TkwPopFormUserType.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmEntityForm)]); end;//TkwPopFormUserType.ParamsTypes procedure TkwPopFormUserType.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству UserType', aCtx); end;//TkwPopFormUserType.SetValuePrim procedure TkwPopFormUserType.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmEntityForm; begin try l_aForm := TvcmEntityForm(aCtx.rEngine.PopObjAs(TvcmEntityForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmEntityForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(UserType(aCtx, l_aForm)); end;//TkwPopFormUserType.DoDoIt function TkwPopFormFormID.FormID(const aCtx: TtfwContext; aForm: TvcmEntityForm): AnsiString; {* Реализация слова скрипта pop:Form:FormID } //#UC START# *55003BED00FC_55003BED00FC_49525B34022A_Word_var* //#UC END# *55003BED00FC_55003BED00FC_49525B34022A_Word_var* begin //#UC START# *55003BED00FC_55003BED00FC_49525B34022A_Word_impl* Result := aForm.FormID.rName; //#UC END# *55003BED00FC_55003BED00FC_49525B34022A_Word_impl* end;//TkwPopFormFormID.FormID class function TkwPopFormFormID.GetWordNameForRegister: AnsiString; begin Result := 'pop:Form:FormID'; end;//TkwPopFormFormID.GetWordNameForRegister function TkwPopFormFormID.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopFormFormID.GetResultTypeInfo function TkwPopFormFormID.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopFormFormID.GetAllParamsCount function TkwPopFormFormID.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvcmEntityForm)]); end;//TkwPopFormFormID.ParamsTypes procedure TkwPopFormFormID.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству FormID', aCtx); end;//TkwPopFormFormID.SetValuePrim procedure TkwPopFormFormID.DoDoIt(const aCtx: TtfwContext); var l_aForm: TvcmEntityForm; begin try l_aForm := TvcmEntityForm(aCtx.rEngine.PopObjAs(TvcmEntityForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aForm: TvcmEntityForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(FormID(aCtx, l_aForm)); end;//TkwPopFormFormID.DoDoIt initialization TkwVcmFormManualUpdateActions.RegisterInEngine; {* Регистрация vcm_Form_ManualUpdateActions } TkwVcmFormReloadToolbars.RegisterInEngine; {* Регистрация vcm_Form_ReloadToolbars } TkwPopFormIsFloatingStateAndParentNotVisible.RegisterInEngine; {* Регистрация pop_Form_IsFloatingStateAndParentNotVisible } TkwPopFormIsFloatingState.RegisterInEngine; {* Регистрация pop_Form_IsFloatingState } TkwPopFormUserType.RegisterInEngine; {* Регистрация pop_Form_UserType } TkwPopFormFormID.RegisterInEngine; {* Регистрация pop_Form_FormID } TtfwTypeRegistrator.RegisterType(TypeInfo(TvcmEntityForm)); {* Регистрация типа TvcmEntityForm } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(TvcmForm)); {* Регистрация типа TvcmForm } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCM) end.
unit AddNewUserUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit, UserParametersUnit; type TAddNewUser = class(TBaseExample) public function Execute(Parameters: TUserParameters): NullableInteger; end; implementation function TAddNewUser.Execute(Parameters: TUserParameters): NullableInteger; var ErrorString: String; begin Result := Route4MeManager.User.AddNewUser(Parameters, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn(Format('New user added successfully, MemberId = %d', [Result.Value])); WriteLn(''); end else WriteLn(Format('AddNewUser error: "%s"', [ErrorString])); end; end.
unit clLancamentos; interface uses clConexao; type TLancamentos = Class(TObject) private function getCodigo: Integer; function getData: TDateTime; function getDescnto: TDateTime; function getDescontado: String; function getDescricao: String; function getEntregador: Integer; function getTipo: String; function getValor: Double; procedure setCodigo(const Value: Integer); procedure setData(const Value: TDateTime); procedure setDescontado(const Value: String); procedure setDesconto(const Value: TDateTime); procedure setDescricao(const Value: String); procedure setEntregador(const Value: Integer); procedure setTipo(const Value: String); procedure setValor(const Value: Double); function getExtrato: String; procedure setExtrato(const Value: String); function getPersistir: String; procedure setPersistir(const Value: String); constructor Create; destructor Destroy; protected _codigo: Integer; _descricao: String; _data: TDateTime; _entregador: Integer; _tipo: String; _valor: Double; _descontado: String; _desconto: TDateTime; _extrato: String; _persistir: String; _conexao: TConexao; public property Codigo: Integer read getCodigo write setCodigo; property Descricao: String read getDescricao write setDescricao; property Data: TDateTime read getData write setData; property Entregador: Integer read getEntregador write setEntregador; property Tipo: String read getTipo write setTipo; property Valor: Double read getValor write setValor; property Descontado: String read getDescontado write setDescontado; property Desconto: TDateTime read getDescnto write setDesconto; property Extrato: String read getExtrato write setExtrato; property Persistir: String read getPersistir write setPersistir; procedure MaxSeq; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getField(campo, coluna: String): String; function getObjects(): Boolean; function Merge(): Boolean; function Totalizacao(sdtInicial, sdtFinal, sEntregador, filtro: String): Double; function Periodo(sdtInicial, sdtFinal, sEntregador, filtro: String) : Boolean; function Fechar(sdtInicial, sdtFinal, sdtDesconto, sNumero, sEntregador, filtro: String): Boolean; function Persistecia(): Boolean; function ConsolidaLancamentos(sInicio: String; sFinal: String): Boolean; function EncontraLancamentos(sFinal: String; sTipo: String): Boolean; end; const TABLENAME = 'TBLANCAMENTOS'; implementation { TLancamentos } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB; constructor TLancamentos.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TLancamentos.Destroy; begin _conexao.Free; end; function TLancamentos.getCodigo: Integer; begin Result := _codigo; end; function TLancamentos.getData: TDateTime; begin Result := _data; end; function TLancamentos.getDescnto: TDateTime; begin Result := _desconto; end; function TLancamentos.getDescontado: String; begin Result := _descontado; end; function TLancamentos.getDescricao: String; begin Result := _descricao; end; function TLancamentos.getEntregador: Integer; begin Result := _entregador; end; function TLancamentos.getTipo: String; begin Result := _tipo; end; function TLancamentos.getValor: Double; begin Result := _valor; end; procedure TLancamentos.MaxSeq; begin Try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(COD_LANCAMENTO) AS CODIGO FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Codigo := (dm.QryGetObject.FieldByName('CODIGO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Validar(): Boolean; begin try Result := False; if Self.Descontado = 'S' then begin MessageDlg('Lançamento já descontado. Alteração não é permitida!', mtWarning, [mbOK], 0); Exit; end; if Self.Persistir = 'N' then begin if not(TUtil.Empty(Self.Extrato)) then begin if Self.Extrato <> '0' then begin Self.Descontado := 'S'; end; end; end; if TUtil.Empty(Self.Descricao) then begin MessageDlg('Informe a Descrição do Lançamento!', mtWarning, [mbOK], 0); Exit; end; if Self.Entregador = 0 then begin MessageDlg('Informe o Código do Entregador!', mtWarning, [mbOK], 0); Exit; end; if Self.Valor = 0 then begin MessageDlg('Informe o Valor do Lançamento!', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_LANCAMENTO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if filtro = 'EXTRATO' then begin SQL.Add('WHERE NUM_EXTRATO = :EXTRATO'); ParamByName('EXTRATO').AsString := Self.Extrato; end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.getObject(id, filtro: String): Boolean; begin try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_LANCAMENTO = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); end else if filtro = 'EXTRATO' then begin SQL.Add('WHERE NUM_EXTRATO = :EXTRATO'); ParamByName('EXTRATO').AsString := id; end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; Self.Codigo := FieldByName('COD_LANCAMENTO').AsInteger; Self.Descricao := FieldByName('DES_LANCAMENTO').AsString; Self.Data := FieldByName('DAT_LANCAMENTO').AsDateTime; Self.Entregador := FieldByName('COD_ENTREGADOR').AsInteger; Self.Tipo := FieldByName('DES_TIPO').AsString; Self.Valor := FieldByName('VAL_LANCAMENTO').AsFloat; Self.Descontado := FieldByName('DOM_DESCONTO').AsString; Self.Desconto := FieldByName('DAT_DESCONTO').AsDateTime; Self.Extrato := FieldByName('NUM_EXTRATO').AsString; Self.Persistir := FieldByName('DOM_PERSISTIR').AsString; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_LANCAMENTO, ' + 'DES_LANCAMENTO, ' + 'DAT_LANCAMENTO, ' + 'COD_ENTREGADOR, ' + 'DES_TIPO, ' + 'VAL_LANCAMENTO, ' + 'DOM_DESCONTO, ' + 'DAT_DESCONTO, ' + 'NUM_EXTRATO, ' + 'DOM_PERSISTIR) ' + 'VALUES (' + ':CODIGO, ' + ':DESCRICAO, ' + ':DATA, ' + ':ENTREGADOR, ' + ':TIPO, ' + ':VALOR, ' + ':DESCONTADO, ' + ':DESCONTO, ' + ':EXTRATO, ' + ':PERSISTIR)'; MaxSeq; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('DATA').AsDate := Self.Data; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('TIPO').AsString := Self.Tipo; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('DESCONTADO').AsString := Self.Descontado; ParamByName('DESCONTO').AsDate := Self.Desconto; ParamByName('EXTRATO').AsString := Self.Extrato; ParamByName('PERSISTIR').AsString := Self.Persistir; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_LANCAMENTO = :DESCRICAO, ' + 'DAT_LANCAMENTO = :DATA, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'DES_TIPO = :TIPO, ' + 'VAL_LANCAMENTO = :VALOR, ' + 'DOM_DESCONTO = :DESCONTADO, ' + 'DAT_DESCONTO = :DESCONTO, ' + 'NUM_EXTRATO = :EXTRATO, ' + 'DOM_PERSISTIR = :PERSISTIR ' + 'WHERE ' + 'COD_LANCAMENTO = :CODIGO'; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('DATA').AsDate := Self.Data; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('TIPO').AsString := Self.Tipo; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('DESCONTADO').AsString := Self.Descontado; ParamByName('DESCONTO').AsDate := Self.Desconto; ParamByName('EXTRATO').AsString := Self.Extrato; ParamByName('PERSISTIR').AsString := Self.Persistir; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.getField(campo, coluna: String): String; begin Try Result := ''; with dm.qryFields do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_LANCAMENTO =:CODIGO '); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if coluna = 'DESCRICAO' then begin SQL.Add(' WHERE DES_LANCAMENTO =:DESCRICAO '); ParamByName('DESCRICAO').AsString := Self.Descricao; end else if coluna = 'ENTREGADOR' then begin SQL.Add(' WHERE COD_ENTREGADOR = :ENTREGADOR '); ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.qryFields.RecordCount > 0 then Result := dm.qryFields.FieldByName(campo).AsString; dm.qryFields.Close; dm.QryCRUD.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.getObjects(): Boolean; begin Try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT * FROM ' + TABLENAME + ' ORDER BY COD_LANCAMENTO'; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Merge(): Boolean; begin try Result := False; if Self.Codigo = 0 then Result := Insert() else Result := Update(); Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Totalizacao(sdtInicial, sdtFinal, sEntregador, filtro: String): Double; var iAgente: Integer; begin Try Result := 0; if TUtil.Empty(sdtInicial) then Exit; if TUtil.Empty(sdtFinal) then Exit; with dm.qryCalculo do begin Close; SQL.Clear; SQL.Add('SELECT COD_ENTREGADOR, SUM(VAL_LANCAMENTO) VALOR FROM ' + TABLENAME); SQL.Add(' WHERE DES_TIPO = :TIPO AND DAT_LANCAMENTO <= :TERMINO AND DOM_DESCONTO <> :DESCONTO'); SQL.Add(' AND COD_ENTREGADOR = :ENTREGADOR'); SQL.Add(' GROUP BY COD_ENTREGADOR'); ParamByName('TERMINO').AsDate := StrToDate(sdtFinal); ParamByName('DESCONTO').AsString := 'S'; ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); if filtro = 'CREDITO' then begin ParamByName('TIPO').AsString := 'CRÉDITO'; end; if filtro = 'DEBITO' then begin ParamByName('TIPO').AsString := 'DÉBITO'; end; dm.ZConn.PingServer; Open; end; if not(dm.qryCalculo.IsEmpty) then Result := dm.qryCalculo.FieldByName('VALOR').AsCurrency; dm.qryCalculo.Close; dm.qryCalculo.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Periodo(sdtInicial, sdtFinal, sEntregador, filtro: String): Boolean; var iAgente: Integer; begin Try Result := False; if TUtil.Empty(sdtInicial) then Exit; if TUtil.Empty(sdtFinal) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add(' WHERE DES_TIPO = :TIPO AND DAT_LANCAMENTO <= :TERMINO AND DOM_DESCONTO <> :DESCONTO'); SQL.Add(' AND COD_ENTREGADOR = :ENTREGADOR'); ParamByName('INICIO').AsDate := StrToDate(sdtInicial); ParamByName('TERMINO').AsDate := StrToDate(sdtFinal); ParamByName('DESCONTO').AsString := 'S'; ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); if filtro = 'CREDITO' then begin ParamByName('TIPO').AsString := 'CRÉDITO'; end; if filtro = 'DEBITO' then begin ParamByName('TIPO').AsString := 'DÉBITO'; end; dm.ZConn.PingServer; Open; end; if not(dm.QryGetObject.IsEmpty) then Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Fechar(sdtInicial, sdtFinal, sdtDesconto, sNumero, sEntregador, filtro: String): Boolean; begin Try Result := False; if TUtil.Empty(sdtInicial) then Exit; if TUtil.Empty(sdtFinal) then Exit; if TUtil.Empty(sdtDesconto) then Exit; if TUtil.Empty(sNumero) then Exit; if TUtil.Empty(sEntregador) then Exit; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('UPDATE ' + TABLENAME); SQL.Add('SET DOM_DESCONTO = :DESCONTO, DAT_DESCONTO = :DATA '); if filtro = 'FECHAR' then begin SQL.Add(', NUM_EXTRATO = :NUMERO'); SQL.Add('WHERE DAT_LANCAMENTO <= :TERMINO AND COD_ENTREGADOR = :ENTREGADOR AND DOM_DESCONTO <> :DESCONTO'); ParamByName('TERMINO').AsDate := StrToDate(sdtFinal); ParamByName('ENTREGADOR').AsInteger := StrToInt(sEntregador); ParamByName('DESCONTO').AsString := 'S'; ParamByName('DATA').AsDate := StrToDate(sdtDesconto); ParamByName('NUMERO').AsString := sNumero; end else begin SQL.Add(', NUM_EXTRATO = "0"'); SQL.Add('WHERE NUM_EXTRATO = :NUMERO'); ParamByName('DESCONTO').AsString := 'N'; ParamByName('DATA').AsDate := 0; ParamByName('NUMERO').AsString := sNumero; end; dm.ZConn.PingServer; ExecSQL; end; Result := True; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TLancamentos.Persistecia(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('UPDATE ' + TABLENAME); SQL.Add('SET DOM_DESCONTO = :DESCONTO '); SQL.Add('WHERE DOM_PERSISTIR = :PERSISTIR'); ParamByName('DESCONTO').AsString := 'N'; ParamByName('PERSISTIR').AsString := 'S'; dm.ZConn.PingServer; ExecSQL; end; Result := True; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TLancamentos.setCodigo(const Value: Integer); begin _codigo := Value; end; procedure TLancamentos.setData(const Value: TDateTime); begin _data := Value; end; procedure TLancamentos.setDescontado(const Value: String); begin _descontado := Value; end; procedure TLancamentos.setDesconto(const Value: TDateTime); begin _desconto := Value; end; procedure TLancamentos.setDescricao(const Value: String); begin _descricao := Value; end; procedure TLancamentos.setEntregador(const Value: Integer); begin _entregador := Value; end; procedure TLancamentos.setTipo(const Value: String); begin _tipo := Value; end; procedure TLancamentos.setValor(const Value: Double); begin _valor := Value; end; function TLancamentos.getExtrato: String; begin Result := _extrato; end; procedure TLancamentos.setExtrato(const Value: String); begin _extrato := Value; end; function TLancamentos.getPersistir: String; begin Result := _persistir; end; procedure TLancamentos.setPersistir(const Value: String); begin _persistir := Value; end; function TLancamentos.ConsolidaLancamentos(sInicio: String; sFinal: String): Boolean; begin Result := False; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; dm.qryPesquisa.SQL.Text := 'SELECT ' + 'TBLANCAMENTOS.COD_ENTREGADOR, ' + 'TBLANCAMENTOS.DES_TIPO, ' + 'SUM(TBLANCAMENTOS.VAL_LANCAMENTO) AS VAL_LANCAMENTO, ' + 'CONCAT(CAST(TBLANCAMENTOS.COD_ENTREGADOR AS CHAR(6)),TBLANCAMENTOS.DES_TIPO) AS CHAVE ' + 'FROM ' + TABLENAME + ' WHERE DAT_LANCAMENTO <= :TERMINO AND DOM_DESCONTO <> :DESCONTO ' + 'GROUP BY TBLANCAMENTOS.COD_ENTREGADOR, TBLANCAMENTOS.DES_TIPO;'; // dm.qryPesquisa.ParamByName('INICIO').AsDate := StrToDate(sInicio); dm.qryPesquisa.ParamByName('TERMINO').AsDate := StrToDate(sFinal); dm.qryPesquisa.ParamByName('DESCONTO').AsString := 'S'; dm.ZConn.PingServer; dm.qryPesquisa.Open; if dm.qryPesquisa.IsEmpty then begin dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; Exit; end; dm.qryPesquisa.First; Result := True; end; function TLancamentos.EncontraLancamentos(sFinal: String; sTipo: String): Boolean; begin Result := False; dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; dm.qryPesquisa.SQL.Text := 'SELECT ' + 'TBLANCAMENTOS.COD_ENTREGADOR, ' + 'TBLANCAMENTOS.DES_TIPO, ' + 'SUM(TBLANCAMENTOS.VAL_LANCAMENTO) AS VAL_LANCAMENTO, ' + 'CONCAT(CAST(TBLANCAMENTOS.COD_ENTREGADOR AS CHAR(6)),TBLANCAMENTOS.DES_TIPO) AS CHAVE ' + 'FROM ' + TABLENAME + ' WHERE DAT_LANCAMENTO <= :TERMINO AND DOM_DESCONTO <> :DESCONTO ' + 'AND DES_TIPO = :TIPO ' + 'GROUP BY TBLANCAMENTOS.COD_ENTREGADOR;'; dm.qryPesquisa.ParamByName('TIPO').AsString := sTipo; dm.qryPesquisa.ParamByName('TERMINO').AsDate := StrToDate(sFinal); dm.qryPesquisa.ParamByName('DESCONTO').AsString := 'S'; dm.ZConn.PingServer; dm.qryPesquisa.Open; if dm.qryPesquisa.IsEmpty then begin dm.qryPesquisa.Close; dm.qryPesquisa.SQL.Clear; Exit; end; dm.qryPesquisa.First; Result := True; end; end.
unit Animation; interface uses Frame, Contnrs, PositionRecord; type TAnimation = class fFramesTotalSeconds : Double; fFrames : TObjectList; constructor Create(); destructor Destroy(); procedure AddFrame(aFrame : TFrame); function GetCurrentFrame(totalElapsedSeconds : double) : TFrame; end; implementation procedure TAnimation.AddFrame(aFrame: TFrame); begin fFrames.Add(aFrame); fFramesTotalSeconds := fFramesTotalSeconds + aFrame.GetLengthSeconds(); end; constructor TAnimation.Create; begin fFrames := TObjectList.Create(); fFramesTotalSeconds := 0; end; destructor TAnimation.Destroy; begin fFrames.Free(); end; function TAnimation.GetCurrentFrame(totalElapsedSeconds : double): TFrame; var i : Integer; sumFrameSecondsStart : Double; sumFrameSecondsEnd : Double; modElapsedSeconds : Double; function Modulus(x,y : double) : Double; begin result := x - int(x/y) * y; end; begin // if fElapsedSeconds > fFramesTotalSeconds then // fElapsedSeconds := fElapsedSeconds - fFramesTotalSeconds; modElapsedSeconds := Modulus(totalElapsedSeconds, fFramesTotalSeconds); sumFrameSecondsStart := 0; sumFrameSecondsEnd := 0; for i := 0 to Pred(fFrames.Count) do begin sumFrameSecondsStart := sumFrameSecondsEnd; sumFrameSecondsEnd := sumFrameSecondsEnd + (fFrames[i] as TFrame).GetLengthSeconds(); if(modElapsedSeconds >= sumFrameSecondsStart) and (modElapsedSeconds < sumFrameSecondsEnd) then begin Result := fFrames[i] as TFrame; Break; end; end; end; end.
Program Random_Numbers; const Digits = 30; {长整数的最大长度} O = 10000; {长整数权值} MaxN = 200; {N最大值为200} MaxM = 200; {M最大值为200} type Long = record {自定义长整数类型} D: Integer; {长整数长度(以log10O位为单位)} Num: array[0..Digits] of Word; {存储长整数(每位权为O)} end; function Max(a, b: Integer): Integer; {返回a和b两者的最大值} begin if a < b then Max := b else Max := a end; { 自定义长整数运算 } procedure SetInt(var a: Long; x: Integer); {设置长整数a的值为x(x<O)} begin a.D := 0; a.Num[0] := x; {x<=65535,直接保存到最低位即可} end; procedure Add(var x, y, res: Long); {长整数加法:res=x+y} var carry: Word; {进位标志} i: Integer; begin carry := 0; i := 0; {进位标志carry置零} repeat if i <= x.D then carry:=carry+x.Num[i]; {对应位相加} if i <= y.D then carry:=carry+y.Num[i]; res.Num[i] := carry mod O; {计算第i位数字} carry := carry div O; {计算进位} i:=i+1; {计算更高位} until (carry = 0) and (i > x.D) and (i > y.D); {从低到高,逐位相加} res.D := i - 1; {设结果的位数} end; procedure Sub(var x, y, res: Long); {长整数加法:res=x-y(x≥y)} var carry: Word; {借位标志} i: Integer; begin carry := 1; i := 0; {进位标志carry置1} repeat if i <= x.D then carry:=carry+x.Num[i]; {对应位相减} if i <= y.D then carry:=carry+(O - 1 - y.Num[i]) else carry:=carry+(O - 1); res.Num[i] := carry mod O; carry := carry div O; {借位} i:=i+1; {计算更高位} until (carry = 1) and (i > x.D) and (i > y.D); {从低到高,逐位相减} i:=i-1; while (i > 0) and (res.Num[i] = 0) do i:=i-1; {调整掉前面多余的零} res.D := i; {设结果的位数} end; procedure Div2(var a, res: Long); {长整数除2:res=a div 2} var i: Integer; carry: Word; begin carry := 0; {高位除2的余数} for i := a.D downto 0 do {从高到低,逐位试商} begin carry := carry * O + a.Num[i]; res.Num[i] := carry div 2; {上商} carry := carry mod 2 {计算当前余数} end; i := a.D; while (i > 0) and (res.Num[i] = 0) do i:=i-1; {调整掉前面多余的零} res.D := i; {设结果的位数} end; function Cmp(var x, y: Long): Integer; { 1 若x>y} var {长整数比较函数。Cmp = 0 若x=y} i: Integer; { -1 若x<y} begin if x.D > y.D then Cmp := 1 {若x的长度比y长则x>y} else if x.D < y.D then Cmp := -1 {若x的长度比y短则x<y} else begin {否则按字典序比较} for i := x.D downto 0 do {从高位到底位,逐一比较} if x.Num[i] > y.Num[i] then begin Cmp := 1; exit end else if x.Num[i] < y.Num[i] then begin Cmp := -1; exit end; Cmp := 0; {数字都相同,则两个数相等} end; end; var Bellman: array[1..MaxM] of Long; {存储Bellman数组} M, N: Integer; Long1, A, B, T, Number, Sum: Long; {Number=G(1,T,0.b1b2…bp)} cur, i, j: Integer; c: char; begin Assign(Input, 'random.in'); Reset(Input); {指定输入输出文件} Assign(Output, 'random.out'); Rewrite(Output); Readln(M, N); SetInt(Long1, 1); {设置常数1} for j := N to M do SetInt(Bellman[j], 1); {顺推Bellman数组} for i := N - 1 downto 1 do begin SetInt(Bellman[i], 0); for j := M - 1 downto i do {Bellman[M]恒等于1} Add(Bellman[j], Bellman[j + 1], Bellman[j]); {计算递推式:Bellman[i-1,j] := Bellman[i,j] + Bellman[i,j+1]} end; SetInt(T, 0); for j := 1 to M do Add(T, Bellman[j], T); {通过Bellman数组计算T} SetInt(A, 1); {计算G(1,T,0.b1b2…bp)} SetInt(B, 0); Add(B, T, B); {A=1,B=T} repeat Read(c); until c = '.'; Read(c); {跳过小数点} while ((c = '0') or (c = '1')) and (Cmp(A, B) <> 0) do {模拟二分法} begin {c是当前的小数位} if c = '0' then begin Add(A, B, B); Div2(B, B) end {得到区间 (A, (A+B) div 2) } else begin Add(A, B, A); Div2(A, A); Add(A, Long1, A) end; {得到区间 ((A+B) div 2+1, B) } Read(c) end; SetInt(Number, 0); Add(Number, A, Number); {Number=G(1,T,0.b1b2…bp)} {Number就是最后的下标} {下面求Number对应的u序列} cur := 1; for i := 1 to N do begin SetInt(Sum, 0); {累加和初始化} cur:=cur-1; while Cmp(Number, Sum) = 1 do {求第i位的数字} begin cur:=cur+1; Add(Sum, Bellman[cur], Sum) {累加Bellman数组} end; if i > 1 then Write(' '); {输出u序列的第i位数字cur} Write(cur); Sub(Sum, Bellman[cur], Sum); {求下一个数字的位置} Sub(Number, Sum, Number); {逆推Bellman数组,恢复到上一阶段的Bellman数组} for j := i to M - 1 do Sub(Bellman[j], Bellman[j + 1], Bellman[j]); end; Writeln; Close(Input); Close(Output); {关闭文件} end.
unit TickServMidware; interface uses System.Types, System.Classes, OverbyteApServer, OverbyteRBroker, OverbyteApSrvCli, FFSRequestBroker, TTSDaapiObjects; type /// <summary>Class managing the Midware AppServer and Request broker, that handle /// the communication with the thin client. It initializes the broker objects and /// exposes client connection eventsSeveral</summary> TTickMidwareServer = class private fRequestBroker: TFFSRequestBroker; fAppServer: TAppServer; fClientCount: Integer; fBrokerObjectCount: Integer; fOnClientClosed: TClientEvent; fOnClientConnected: TClientEvent; fOnObjCreate: TInstanciationEvent; fOnObjDestroy: TInstanciationEvent; procedure InitRequestBrokerObjects; procedure DoClientConnected(Sender: TObject; CliWSocket: TClientWSocket); procedure DoClientClosed(Sender: TObject; CliWSocket: TClientWSocket); procedure DoBrokerObjCreate(Sender: TObject; ServerObject: TServerObject); procedure DoBrokerObjDestroy(Sender: TObject; ServerObject: TServerObject); function GetAddress: String; function GetBanner: String; function GetOnAfterProcessRequest: TProcessRequestEvent; function GetOnBeforeProcessRequest: TProcessRequestEvent; function GetPort: String; procedure SetAddress(const Value: String); procedure SetBanner(const Value: String); procedure SetOnAfterProcessRequest(const Value: TProcessRequestEvent); procedure SetOnBeforeProcessRequest(const Value: TProcessRequestEvent); procedure SetPort(const Value: String); public constructor Create(aBrokerUserData: Integer; aServerBanner: String); destructor Destroy; override; procedure DisconnectAll; procedure Start; procedure Stop; property Address: String read GetAddress write SetAddress; property Banner: String read GetBanner write SetBanner; property BrokerObjectCount: Integer read fBrokerObjectCount; property ClientCount: Integer read fClientCount; property Port: String read GetPort write SetPort; property OnAfterProcessRequest: TProcessRequestEvent read GetOnAfterProcessRequest write SetOnAfterProcessRequest; property OnBeforeProcessRequest: TProcessRequestEvent read GetOnBeforeProcessRequest write SetOnBeforeProcessRequest; property OnClientClosed: TClientEvent read fOnClientClosed write fOnClientClosed; property OnClientConnected: TClientEvent read fOnClientConnected write fOnClientConnected; property OnObjCreate: TInstanciationEvent read fOnObjCreate write fOnObjCreate; property OnObjDestroy: TInstanciationEvent read fOnObjDestroy write fOnObjDestroy; end; implementation procedure TTickMidwareServer.InitRequestBrokerObjects; begin { Initialize RequestBroker object } // setup fRequestBroker.AddServerObject(TServerObjectGetSetupRecord1); fRequestBroker.AddServerObject(TServerObjectSetSetupRecord1); fRequestBroker.AddServerObject(TServerObjectSystemSetOption); // lender fRequestBroker.AddServerObject(TServerObjectLendExists); fRequestBroker.AddServerObject(TServerObjectLendGetRecord); fRequestBroker.AddServerObject(TServerObjectLendUpdateRecord); fRequestBroker.AddServerObject(TServerObjectLendAddRecord); fRequestBroker.AddServerObject(TServerObjectLendDelete); fRequestBroker.AddServerObject(TServerObjectLendGetSelectList); fRequestBroker.AddServerObject(TServerObjectLendGetMaintList); fRequestBroker.AddServerObject(TServerObjectLendSetOption); fRequestBroker.AddServerObject(TServerObjectGetLenderInfo); // Reports fRequestBroker.AddServerObject(TServerObjectGetRunReportOptions); fRequestBroker.AddServerObject(TServerObjectGetReportHistory); fRequestBroker.AddServerObject(TServerObjectGetSavedReportList); fRequestBroker.AddServerObject(TServerObjectGetSavedReport); fRequestBroker.AddServerObject(TServerObjectSaveReportSettings); fRequestBroker.AddServerObject(TServerObjectDeleteReportSettings); fRequestBroker.AddServerObject(TServerObjectRemoveOldReports); fRequestBroker.AddServerObject(TServerObjectSaveModifiedReportRun); fRequestBroker.AddServerObject(TServerObjectSaveReportRun); fRequestBroker.AddServerObject(TServerObjectReportRun); fRequestBroker.AddServerObject(TServerObjectNoticeScanUndo); fRequestBroker.AddServerObject(TServerObjectFixCifColNum); // misc fRequestBroker.AddServerObject(TServerObjectLoanGetLoanCount); fRequestBroker.AddServerObject(TServerObjectUTLGetUTLCount); fRequestBroker.AddServerObject(TServerObjectCopyLender); fRequestBroker.AddServerObject(TServerObjectcopyLendcodes); fRequestBroker.AddServerObject(TServerObjectcopytables); fRequestBroker.AddServerObject(TServerObjectGetReportFile); // datacaddy fRequestBroker.AddServerObject(TServerObjectDCProcessTTSFile); fRequestBroker.AddServerObject(TServerObjectDCTTSFileExists); fRequestBroker.AddServerObject(TServerObjectDCGetUnprocessedList); fRequestBroker.AddServerObject(TServerObjectDCGetReview); fRequestBroker.AddServerObject(TServerObjectDCPerform); fRequestBroker.AddServerObject(TServerObjectDCGetRecord); fRequestBroker.AddServerObject(TServerObjectDCStart); fRequestBroker.AddServerObject(TServerObjectDCStop); fRequestBroker.AddServerObject(TServerObjectDCAddLender); fRequestBroker.AddServerObject(TServerObjectDCProcessRecord); fRequestBroker.AddServerObject(TServerObjectDCStartReport); fRequestBroker.AddServerObject(TServerObjectDCProduceReport); fRequestBroker.AddServerObject(TServerObjectDCUpdateControl); fRequestBroker.AddServerObject(TServerObjectDCGetControl); // DCNEW fRequestBroker.AddServerObject(TServerObjectDCProcessRecordNew); // Version fRequestBroker.AddServerObject(TServerObjectGetDatabaseVersion); fRequestBroker.AddServerObject(TServerObjectSetDatabaseVersion); // Loan fRequestBroker.AddServerObject(TServerObjectLoanGetRecord); fRequestBroker.AddServerObject(TServerObjectLoanAddRecord); fRequestBroker.AddServerObject(TServerObjectLoanUpdateRecord); fRequestBroker.AddServerObject(TServerObjectLoanDelete); fRequestBroker.AddServerObject(TServerObjectLoanChangeNumber); fRequestBroker.AddServerObject(TServerObjectLoanCollCodeInUse); fRequestBroker.AddServerObject(TServerObjectLoanExists); fRequestBroker.AddServerObject(TServerObjectLoanCheckBranch); fRequestBroker.AddServerObject(TServerObjectLoanGetNotes); fRequestBroker.AddServerObject(TServerObjectLoanUpdateNotes); fRequestBroker.AddServerObject(TServerObjectLoanGetModCount); fRequestBroker.AddServerObject(TServerObjectLoanGetCollList); fRequestBroker.AddServerObject(TServerObjectLoanGetBlock); fRequestBroker.AddServerObject(TServerObjectLoanHasNotes); fRequestBroker.AddServerObject(TServerObjectLoanPurge); // Cif fRequestBroker.AddServerObject(TServerObjectCifGetRecord); fRequestBroker.AddServerObject(TServerObjectCifAddRecord); fRequestBroker.AddServerObject(TServerObjectCifUpdateRecord); fRequestBroker.AddServerObject(TServerObjectCifDelete); fRequestBroker.AddServerObject(TServerObjectCifChangeNumber); fRequestBroker.AddServerObject(TServerObjectCifExists); fRequestBroker.AddServerObject(TServerObjectCifGetLoanList); fRequestBroker.AddServerObject(TServerObjectCifExportCifToLoans); fRequestBroker.AddServerObject(TServerObjectCifGetNotes); fRequestBroker.AddServerObject(TServerObjectCifUpdateNotes); fRequestBroker.AddServerObject(TServerObjectCifGetModCount); fRequestBroker.AddServerObject(TServerObjectCifGetBlock); fRequestBroker.AddServerObject(TServerObjectCifHasNotes); // UTL fRequestBroker.AddServerObject(TServerObjectUTLAddRecord); fRequestBroker.AddServerObject(TServerObjectUTLUpdateRecord); fRequestBroker.AddServerObject(TServerObjectUTLGetRecord); fRequestBroker.AddServerObject(TServerObjectUTLGetBlock); fRequestBroker.AddServerObject(TServerObjectUTLDelete); fRequestBroker.AddServerObject(TServerObjectUTLGetRunList); fRequestBroker.AddServerObject(TServerObjectUTLSetProcessVersion); fRequestBroker.AddServerObject(TServerObjectUTLGetProcessVersion); fRequestBroker.AddServerObject(TServerObjectUTLRemovePaidOutLoans); fRequestBroker.AddServerObject(TServerObjectUTLNoMatchAddRecord); // Collateral fRequestBroker.AddServerObject(TServerObjectNcolGetCount); fRequestBroker.AddServerObject(TServerObjectNcolGetRecord); fRequestBroker.AddServerObject(TServerObjectNColGetMoreDesc); fRequestBroker.AddServerObject(TServerObjectNcolUpdateRecord); fRequestBroker.AddServerObject(TServerObjectNcolAddRecord); fRequestBroker.AddServerObject(TServerObjectNcolDeleteRecord); fRequestBroker.AddServerObject(TServerObjectNcolGetCsvRecords); // Coll Codes fRequestBroker.AddServerObject(TServerObjectCollCheckIndivid); fRequestBroker.AddServerObject(TServerObjectCollGetCodeCount); fRequestBroker.AddServerObject(TServerObjectCollCheckCodes); fRequestBroker.AddServerObject(TServerObjectCollGetDesc); fRequestBroker.AddServerObject(TServerObjectCollGetList); fRequestBroker.AddServerObject(TServerObjectCollGetMaintList); fRequestBroker.AddServerObject(TServerObjectCollAddRecord); fRequestBroker.AddServerObject(TServerObjectCollGetCodeDescList); fRequestBroker.AddServerObject(TServerObjectCollGetRecord); fRequestBroker.AddServerObject(TServerObjectCollGetItemList); fRequestBroker.AddServerObject(TServerObjectCollSetItemList); fRequestBroker.AddServerObject(TServerObjectCollDeleteCode); fRequestBroker.AddServerObject(TServerObjectCollUpdateRate); fRequestBroker.AddServerObject(TServerObjectCollGetTable); // misc fRequestBroker.AddServerObject(TServerObjectGetCifPODate); fRequestBroker.AddServerObject(TServerObjectUpdateCifBal); fRequestBroker.AddServerObject(TServerObjectInsertNameSearch); fRequestBroker.AddServerObject(TServerObjectNMSRRebuild); fRequestBroker.AddServerObject(TServerObjectListLoad); // Guar fRequestBroker.AddServerObject(TServerObjectGuarDeleteGuarantor); fRequestBroker.AddServerObject(TServerObjectGuarAddGuarantor); fRequestBroker.AddServerObject(TServerObjectGuarGetGuarantorList); fRequestBroker.AddServerObject(TServerObjectGuarGetLoanList); fRequestBroker.AddServerObject(TServerObjectGuarGetCsvRecs); fRequestBroker.AddServerObject(TServerObjectGuarGetTable); // Citm fRequestBroker.AddServerObject(TServerObjectCitmRequiredItem); // Titm fRequestBroker.AddServerObject(TServerObjectTitmDeleteCategory); fRequestBroker.AddServerObject(TServerObjectTitmGetModCount); fRequestBroker.AddServerObject(TServerObjectTitmGetList); fRequestBroker.AddServerObject(TServerObjectTitmItemExists); fRequestBroker.AddServerObject(TServerObjectTitmAddRecord); fRequestBroker.AddServerObject(TServerObjectTitmGetRecord); fRequestBroker.AddServerObject(TServerObjectTitmUpdateRecord); fRequestBroker.AddServerObject(TServerObjectTitmDelete); fRequestBroker.AddServerObject(TServerObjectTitmGetNotes); fRequestBroker.AddServerObject(TServerObjectTitmUpdateNote); fRequestBroker.AddServerObject(TServerObjectTitmChangeAllCats); fRequestBroker.AddServerObject(TServerObjectTitmCatInUse); fRequestBroker.AddServerObject(TServerObjectTitmGetCsvRecs); fRequestBroker.AddServerObject(TServerObjectTitmAddCsvRecs); fRequestBroker.AddServerObject(TServerObjectTitmNColGetCsvRecs); fRequestBroker.AddServerObject(TServerObjectTitmGetBlock); fRequestBroker.AddServerObject(TServerObjectTitmGetBlockForScan); fRequestBroker.AddServerObject(TServerObjectTitmGetCatBlock); fRequestBroker.AddServerObject(TServerObjectTitmGetCatBlockForScan); fRequestBroker.AddServerObject(TServerObjectHitmGetCsvRecs); fRequestBroker.AddServerObject(TServerObjectTitmGetIntoWktitm); fRequestBroker.AddServerObject(TServerObjectHitmGetIntoWkHitm); fRequestBroker.AddServerObject(TServerObjectUTLGetIntoWkUTL); fRequestBroker.AddServerObject(TServerObjectHitmPND); // TDoc fRequestBroker.AddServerObject(TServerObjectTDocGetItems); fRequestBroker.AddServerObject(TServerObjectTDocGetRecord); fRequestBroker.AddServerObject(TServerObjectTDocDeleteRecord); fRequestBroker.AddServerObject(TServerObjectTDocSetRecord); fRequestBroker.AddServerObject(TServerObjectTDocGetImage); // Trak fRequestBroker.AddServerObject(TServerObjectTrakGetCodeCount); fRequestBroker.AddServerObject(TServerObjectTrakAddRecord); fRequestBroker.AddServerObject(TServerObjectTrakGetRecord); fRequestBroker.AddServerObject(TServerObjectTrakGetTemplate); fRequestBroker.AddServerObject(TServerObjectTrakTallyItems); fRequestBroker.AddServerObject(TServerObjectTrakGetCodeDescList); fRequestBroker.AddServerObject(TServerObjectTrakGetCodeList); fRequestBroker.AddServerObject(TServerObjectTrakGetCodeListbyRisk); fRequestBroker.AddServerObject(TServerObjectTrakGetMaintList); fRequestBroker.AddServerObject(TServerObjectTrakCatExists); fRequestBroker.AddServerObject(TServerObjectTrakDelCat); fRequestBroker.AddServerObject(TServerObjectTrakGetNoticeList); fRequestBroker.AddServerObject(TServerObjectTrakCodeGetTable); // LDoc fRequestBroker.AddServerObject(TServerObjectLDocGetList); fRequestBroker.AddServerObject(TServerObjectLDocGetImage); fRequestBroker.AddServerObject(TServerObjectLDocAddImage); fRequestBroker.AddServerObject(TServerObjectLDocDeleteImage); fRequestBroker.AddServerObject(TServerObjectLDocUpdateDesc); // Code fRequestBroker.AddServerObject(TServerObjectCodeAddRecord); fRequestBroker.AddServerObject(TServerObjectCodeGetCodeDescList); fRequestBroker.AddServerObject(TServerObjectCodeGetFullCodeDescList); fRequestBroker.AddServerObject(TServerObjectCodeExists); fRequestBroker.AddServerObject(TServerObjectCodeGetRecord); fRequestBroker.AddServerObject(TServerObjectCodeDelete); fRequestBroker.AddServerObject(TServerObjectCodeGetCodeList); fRequestBroker.AddServerObject(TServerObjectCodeGetMaintList); fRequestBroker.AddServerObject(TServerObjectCodeGetTable); // Notc fRequestBroker.AddServerObject(TServerObjectNoteGetNoticeText); fRequestBroker.AddServerObject(TServerObjectNoteAddUpdtNoticeText); fRequestBroker.AddServerObject(TServerObjectNoteAddCombHeaderText); fRequestBroker.AddServerObject(TServerObjectNoteAddCombFooterText); fRequestBroker.AddServerObject(TServerObjectNoteGetCombHeaderText); fRequestBroker.AddServerObject(TServerObjectNoteGetCombFooterText); fRequestBroker.AddServerObject(TServerObjectNoteAddUpdtRecord); fRequestBroker.AddServerObject(TServerObjectNoteGetRecord); fRequestBroker.AddServerObject(TServerObjectNoteDelete); // Other fRequestBroker.AddServerObject(TServerObjectRepair_DATE); fRequestBroker.AddServerObject(TServerObjectCIFBal); fRequestBroker.AddServerObject(TServerObjectNoNot); fRequestBroker.AddServerObject(TServerObjectDoRefresh); // search fRequestBroker.AddServerObject(TServerObjectSearchIt); fRequestBroker.AddServerObject(TServerObjectSearchGet); // version fRequestBroker.AddServerObject(TServerObjectCheckApplicationVersion); fRequestBroker.AddServerObject(TServerObjectSetApplicationVersion); // Pledge fRequestBroker.AddServerObject(TServerObjectPldgAddRecord); fRequestBroker.AddServerObject(TServerObjectPldgGetLoanList); fRequestBroker.AddServerObject(TServerObjectPldgGetLoanCollList); fRequestBroker.AddServerObject(TServerObjectPldgDeleteRecord); fRequestBroker.AddServerObject(TServerObjectPldgDeleteAllRecords); fRequestBroker.AddServerObject(TServerObjectPldgGetTable); fRequestBroker.AddServerObject(TServerObjectPldgGetCsvRecords); fRequestBroker.AddServerObject(TServerObjectNcolPldgGetCsvRecords); // Other fRequestBroker.AddServerObject(TServerObjectThreadCount); // Processes fRequestBroker.AddServerObject(TServerObjectProcCifBalScan); fRequestBroker.AddServerObject(TServerObjectProcRemoveNoticeScan); fRequestBroker.AddServerObject(TServerObjectProcLoanChangeOffr); fRequestBroker.AddServerObject(TServerObjectProcCIFChangeOffr); fRequestBroker.AddServerObject(TServerObjectProcDelCat); fRequestBroker.AddServerObject(TServerObjectProcNMSRScan); fRequestBroker.AddServerObject(TServerObjectProcCifFixCol); fRequestBroker.AddServerObject(TServerObjectProcNoNot); fRequestBroker.AddServerObject(TServerObjectLendGetHeaderFooters); fRequestBroker.AddServerObject(TServerObjectTrakUpdRecord); fRequestBroker.AddServerObject(TServerObjectNoteGetNotice); fRequestBroker.AddServerObject(TServerObjectHitmAddRecord); fRequestBroker.AddServerObject(TServerObjectTitmUpdNotice); // User Sirisha fRequestBroker.AddServerObject(TServerObjectUserNameIsUser); fRequestBroker.AddServerObject(TServerObjectUserGetUserID); fRequestBroker.AddServerObject(TServerObjectSecureGetNumberOfUsers); fRequestBroker.AddServerObject(TServerObjectLogGetAll); // Corelink search fRequestBroker.AddServerObject(TServerObjectCoreLinkSearch); // PasswordOptions fRequestBroker.AddServerObject(TServerObjectPasswordOptionsGetRecord); fRequestBroker.AddServerObject(TServerObjectPasswordOptionsAddRecord); fRequestBroker.AddServerObject(TServerObjectPasswordOptionsUpdateRecord); fRequestBroker.AddServerObject(TServerObjectPasswordOptionsDelete); // Job fRequestBroker.AddServerObject(TServerObjectSaveJobRun); fRequestBroker.AddServerObject(TServerObjectGetJobHistory); fRequestBroker.AddServerObject(TServerObjectJobAddRecord); fRequestBroker.AddServerObject(TServerObjectSaveModifiedJobRun); fRequestBroker.AddServerObject(TServerObjectSavePeriodicJobRun); fRequestBroker.AddServerObject(TServerObjectRunJobs); // server fRequestBroker.AddServerObject(TServerObjectGetServerPrinters); // cache Names ,cif, loan 3, Coll, Ref fRequestBroker.AddServerObject(TServerObjectCacheNames); fRequestBroker.AddServerObject(TServerObjectCacheLoan); fRequestBroker.AddServerObject(TServerObjectCacheCIF); fRequestBroker.AddServerObject(TServerObjectCacheColl); fRequestBroker.AddServerObject(TServerObjectCacheRef); fRequestBroker.AddServerObject(TServerObjectCacheALL); end; procedure TTickMidwareServer.DoClientConnected(Sender: TObject; CliWSocket: TClientWSocket); begin fClientCount := fAppServer.ClientCount; if Assigned(fOnClientConnected) then fOnClientConnected(Sender, CliWSocket); end; procedure TTickMidwareServer.DoClientClosed(Sender: TObject; CliWSocket: TClientWSocket); begin fClientCount := fAppServer.ClientCount - 1; // Because the count in fAppServer is decremented after the event if Assigned(fOnClientClosed) then fOnClientClosed(Sender, CliWSocket); end; procedure TTickMidwareServer.DoBrokerObjCreate(Sender: TObject; ServerObject: TServerObject); begin fBrokerObjectCount := fRequestBroker.ObjectCount; if Assigned(fOnObjCreate) then fOnObjCreate(Sender, ServerObject); end; procedure TTickMidwareServer.DoBrokerObjDestroy(Sender: TObject; ServerObject: TServerObject); begin fBrokerObjectCount := fRequestBroker.ObjectCount - 1; // Because the count in fRequestBroker is decremented after the event if Assigned(fOnObjDestroy) then fOnObjDestroy(Sender, ServerObject); end; function TTickMidwareServer.GetAddress: String; begin Result := fAppServer.Addr; end; function TTickMidwareServer.GetBanner: String; begin Result := fAppServer.Banner; end; function TTickMidwareServer.GetOnAfterProcessRequest: TProcessRequestEvent; begin Result := fAppServer.OnAfterProcessRequest; end; function TTickMidwareServer.GetOnBeforeProcessRequest: TProcessRequestEvent; begin Result := fAppServer.OnBeforeProcessRequest; end; function TTickMidwareServer.GetPort: String; begin Result := fAppServer.Port; end; procedure TTickMidwareServer.SetAddress(const Value: String); begin fAppServer.Addr := Value; end; procedure TTickMidwareServer.SetBanner(const Value: String); begin fAppServer.Banner := Value; end; procedure TTickMidwareServer.SetOnAfterProcessRequest(const Value: TProcessRequestEvent); begin fAppServer.OnAfterProcessRequest := Value; end; procedure TTickMidwareServer.SetOnBeforeProcessRequest(const Value: TProcessRequestEvent); begin fAppServer.OnBeforeProcessRequest := Value; end; procedure TTickMidwareServer.SetPort(const Value: String); begin fAppServer.Port := Value; end; constructor TTickMidwareServer.Create(aBrokerUserData: Integer; aServerBanner: String); begin inherited Create; fRequestBroker := TFFSRequestBroker.Create(nil); fRequestBroker.Options := [rboDisplayObjectCount]; fRequestBroker.UserData := aBrokerUserData; fRequestBroker.OnObjCreate := DoBrokerObjCreate; fRequestBroker.OnObjDestroy := DoBrokerObjDestroy; InitRequestBrokerObjects; fAppServer := TAppServer.Create(nil); fAppServer.RequestBroker := fRequestBroker; fAppServer.Options := [asoDisplayCommands, asoDisplayClientCount]; fAppServer.Banner := aServerBanner; fAppServer.ClientTimeout := 30; fAppServer.TimeoutInterval := 1800; fAppServer.ListenBacklog := 50; fAppServer.OnClientClosed := DoClientClosed; fAppServer.OnClientConnected := DoClientConnected; end; destructor TTickMidwareServer.Destroy; begin fAppServer.Free; fRequestBroker.Free; inherited; end; procedure TTickMidwareServer.DisconnectAll; begin fAppServer.DisconnectAll; end; procedure TTickMidwareServer.Start; begin fAppServer.Start; end; procedure TTickMidwareServer.Stop; begin fAppServer.DisconnectAll; fAppServer.Stop; end; end.
unit JPGtoBMP; interface uses Windows, Graphics; procedure LoadJPGToBMP( filename : string; DestBMP : TBitmap ); procedure CopyJPGToBMP( filename : string; DestBMP : TBitmap ); procedure TVFilter( DestBMP : TBitmap; Color : TColor ); procedure DarkImage( DestBMP : TBitmap; perc : integer ); implementation uses jpeg, Classes; procedure LoadJPGToBMP( filename : string; DestBMP : TBitmap ); var jpg : TJPEGImage; begin jpg := TJPEGImage.Create; try jpg.PixelFormat := jf24Bit; jpg.LoadFromFile( filename ); //DestBMP.Assign( jpg ); DestBMP.Canvas.StretchDraw( Rect(0, 0, DestBMP.Width, DestBMP.Height), jpg ); finally jpg.Free; end; end; procedure CopyJPGToBMP( filename : string; DestBMP : TBitmap ); var jpg : TJPEGImage; begin jpg := TJPEGImage.Create; try jpg.PixelFormat := jf24Bit; jpg.LoadFromFile( filename ); DestBMP.Width := jpg.Width; DestBMP.Height := jpg.Height; DestBMP.Canvas.StretchDraw( Rect(0, 0, DestBMP.Width, DestBMP.Height), jpg ); finally jpg.Free; end; end; procedure TVFilter( DestBMP : TBitmap; Color : TColor ); var i : integer; begin with DestBMP.Canvas do begin Pen.Color := Color;//$00243940;//$00343924;//clGray; Pen.Style := psSolid; Pen.Width := 1; for i := 0 to pred(DestBMP.Height) div 2 do begin MoveTo( 0, 2*i ); LineTo( DestBMP.Width, 2*i ); end; end; end; procedure DarkImage( DestBMP : TBitmap; perc : integer ); type TRGB = packed record x, b, g, r : byte; end; var x, y : integer; c : TRGB; begin for y := 0 to pred(DestBMP.Height) do for x := 0 to pred(DestBMP.Width) do begin c := TRGB(DestBMP.Canvas.Pixels[x,y]); c.r := perc*c.r div 100; c.g := perc*c.g div 100; c.b := perc*c.b div 100; c.x := perc*c.x div 100; DestBMP.Canvas.Pixels[x,y] := TColor(c); end; end; end.
unit QuickExportSetup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,save_rtf_dialog; type TQuickExportSetupForm = class(TForm) SkipImages: TCheckBox; Button1: TButton; Button2: TButton; SkipCover: TCheckBox; SkipDescr: TCheckBox; EncCompat: TCheckBox; ImgCompat: TCheckBox; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure SkipImagesClick(Sender: TObject); procedure SkipImagesKeyPress(Sender: TObject; var Key: Char); private { Private declarations } ParentHandle:THandle; Key:String; public { Public declarations } constructor CreateWithForeighnParent(AParent:THandle;AKey:String); procedure CreateParams(var Params: TCreateParams); override; end; var QuickExportSetupForm: TQuickExportSetupForm; const QuickSetupKey=RegistryKey+'\quick\'; implementation uses Registry; {$R *.dfm} constructor TQuickExportSetupForm.CreateWithForeighnParent; Begin ParentHandle:=AParent; Key:=QuickSetupKey+AKey; create(Nil); end; procedure TQuickExportSetupForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := ParentHandle; end; procedure TQuickExportSetupForm.FormCreate(Sender: TObject); Var Reg:TRegistry; begin Reg:=TRegistry.Create(KEY_READ); Try Try if Reg.OpenKeyReadOnly(Key) then Begin SkipImages.Checked:=Reg.ReadBool('Skip images'); SkipCover.Checked:=Reg.ReadBool('Skip cover'); SkipDescr.Checked:=Reg.ReadBool('Skip description'); EncCompat.Checked:=Reg.ReadBool('Encoding compat'); ImgCompat.Checked:=Reg.ReadBool('Image compat'); SkipImagesClick(Nil); end; Finally Reg.Free; end; Except end; end; procedure TQuickExportSetupForm.Button1Click(Sender: TObject); Var Reg:TRegistry; begin Reg:=TRegistry.Create(KEY_ALL_ACCESS); Try if Reg.OpenKey(Key,True) then Begin Reg.WriteBool('Skip images',SkipImages.Checked); Reg.WriteBool('Skip cover',SkipCover.Checked); Reg.WriteBool('Skip description',SkipDescr.Checked); Reg.WriteBool('Encoding compat',EncCompat.Checked); Reg.WriteBool('Image compat',ImgCompat.Checked); end; Finally Reg.Free; end; end; procedure TQuickExportSetupForm.SkipImagesClick(Sender: TObject); begin SkipCover.Enabled:=not SkipImages.Checked; end; procedure TQuickExportSetupForm.SkipImagesKeyPress(Sender: TObject; var Key: Char); begin SkipImagesClick(self); end; end.
unit MergeSocket; interface uses Classes, SyncObjs, SplitSocket, SysUtils, windows; type TMergeSocketNewPacket = procedure(Sender: TObject; Socket: TSplitSocket) of object; TMergeSocket = class(TObject) private FSocketList: TList; ASocketPos: Integer; PacketsAvailable: TEvent; procedure SocketOnNewPacket_ReadThread(Sender: TObject); procedure SocketOnDestroy(Sender: TObject); function GetSocket(nr: integer): TSplitSocket; public OnNewPacket_ReadThread: TMergeSocketNewPacket; OnNewSocket: TMergeSocketNewPacket; OnRemoveSocket: TMergeSocketNewPacket; property Sockets[nr: Integer]: TSplitSocket read GetSocket; procedure AddSocket(Socket: TSplitSocket); procedure RemoveSocket(Socket: TSplitSocket); constructor Create; destructor Destroy; override; procedure RecvPacket(var Data: pointer; var Size: Word; var Socket: TSplitSocket;const TimeOut: Cardinal = High(Cardinal)); function GetPacket(var Data: pointer; var Size: Word; var Socket: TSplitSocket): Boolean; procedure SendPacket(var Data; const Size: Word; SkipSocket: TSplitSocket = nil); function Count: Integer; end; TMergeSocketComponent = class(TComponent) private FOnNewPacket_ReadThread: TMergeSocketNewPacket; FOnNewSocket: TMergeSocketNewPacket; FOnRemoveSocket: TMergeSocketNewPacket; procedure SetFOnNewPacket_ReadThread(proc: TMergeSocketNewPacket); procedure SetFOnNewSocket(proc: TMergeSocketNewPacket); procedure SetFOnRemoveSocket(proc: TMergeSocketNewPacket); public MergeSocket: TMergeSocket; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnNewPacket_ReadThread: TMergeSocketNewPacket read FOnNewPacket_ReadThread write SetFOnNewPacket_ReadThread; property OnNewSocket: TMergeSocketNewPacket read FOnNewSocket write SetFOnNewSocket; property OnRemoveSocket: TMergeSocketNewPacket read FOnRemoveSocket write SetFOnRemoveSocket; end; procedure Register; implementation procedure TMergeSocket.AddSocket(Socket: TSplitSocket); begin If Assigned(OnNewSocket) then OnNewSocket(Self,Socket); FSocketList.Add(Socket); Socket.OnDestroy := {$ifdef Lazarus}@{$endif}SocketOnDestroy; Socket.OnNewPacket_ReadThread := {$ifdef Lazarus}@{$endif}SocketOnNewPacket_ReadThread; //Da vor dem adden schon packete angekommen sein könnten: SocketOnNewPacket_ReadThread(Socket); end; function TMergeSocket.Count: Integer; begin Result := FSocketList.Count; end; constructor TMergeSocket.Create; begin inherited; FSocketList := TList.Create; ASocketPos := 0; PacketsAvailable := TEvent.Create(nil,True,False,''); OnNewSocket := nil; OnNewPacket_ReadThread := nil; OnNewPacket_ReadThread := nil; end; destructor TMergeSocket.Destroy; begin while (Count > 0) do begin RemoveSocket(Sockets[0]); end; FSocketList.Free; inherited; end; {############################################################################### TMergeSocket.GetPacket Liest, falls vorhanden, das nächste Packet. Wenn kein Packet mehr im "Buffer" ist, gibt die Funktion False zurück! Diese Funktion Blockiert nicht! Hinweis zur Technik: Ich starte NICHT jedesmal wieder am Anfang der Liste, damit bei viel Datenverkehr auf der "Leitung0" auch die "Leitungen1,2,3..." Ausgelesen werden! Deswegen der Aufwand mit ASocketPos. ###############################################################################} function TMergeSocket.GetPacket(var Data: pointer; var Size: Word; var Socket: TSplitSocket): Boolean; var stop: Integer; begin Result := False; stop := ASocketPos; if ASocketPos >= Count then ASocketPos := 0; //Könnte vorkommen, wenn Socket schließen, // und aus der Liste gelöscht werden! if Count > 0 then //Wenn es garkeine Sockets in der Liste gibt, // würde es einen Crash geben! repeat Socket := Sockets[ASocketPos]; Result := Socket.GetPacket(Data,Size); inc(ASocketPos); if ASocketPos >= Count then ASocketPos := 0; until (stop = ASocketPos) or Result; end; function TMergeSocket.GetSocket(nr: integer): TSplitSocket; begin if (nr >= 0)and(nr < Count) then Result := TSplitSocket(FSocketList[nr]) else raise Exception.Create('TMergeSocket.GetSocket: Fehler bei Bereichsüberprüfung'); end; {############################################################################### TMergeSocket.RecvPacket Liest das nächste Packet. Wenn nötig wird solange blockiert bis ein Packet vorhanden ist! Ist quasi der Blockierende Socketaufruf. ###############################################################################} procedure TMergeSocket.RecvPacket(var Data: pointer; var Size: Word; var Socket: TSplitSocket; const TimeOut: Cardinal = High(Cardinal)); var success: Boolean; begin repeat case PacketsAvailable.WaitFor(TimeOut) of wrSignaled: begin success := GetPacket(Data, Size, Socket); if not success then PacketsAvailable.ResetEvent; //alle sockets durch und kein Packet gelesen!! // -> keine da, nochmal bis timeout warten! end; wrTimeout: raise ETimeOut.Create('TMergeSocket.RecvPacket: TimeOut while waiting for PacketsAvailable'); else raise Exception.Create('TMergeSocket.RecvPacket: Error while waiting for PacketsAvailable'); end; until success; //bis entweder ein timeout auftritt, // oder erfolgreich gelesen wurde! end; procedure TMergeSocket.RemoveSocket(Socket: TSplitSocket); begin Socket.OnDestroy := nil; Socket.OnNewPacket_ReadThread := nil; FSocketList.Remove(Socket); if Assigned(OnRemoveSocket) then OnRemoveSocket(Self,Socket); end; procedure TMergeSocket.SendPacket(var Data; const Size: Word; SkipSocket: TSplitSocket = nil); var i: integer; begin for i := 0 to Count-1 do begin if Sockets[i] <> SkipSocket then with Sockets[i] do begin try SendPacket(Data,Size); except end; end; end; end; procedure TMergeSocket.SocketOnDestroy(Sender: TObject); begin RemoveSocket(TSplitSocket(Sender)); end; procedure TMergeSocket.SocketOnNewPacket_ReadThread(Sender: TObject); begin PacketsAvailable.SetEvent; if Assigned(OnNewPacket_ReadThread) then OnNewPacket_ReadThread(Self,TSplitSocket(Sender)); end; procedure Register; begin RegisterComponents('nice things', [TMergeSocketComponent]); end; constructor TMergeSocketComponent.Create(AOwner: TComponent); begin inherited; MergeSocket := TMergeSocket.Create; end; destructor TMergeSocketComponent.Destroy; begin MergeSocket.Free; inherited; end; procedure TMergeSocketComponent.SetFOnNewPacket_ReadThread( proc: TMergeSocketNewPacket); begin MergeSocket.OnNewPacket_ReadThread := proc; FOnNewPacket_ReadThread := proc; end; procedure TMergeSocketComponent.SetFOnNewSocket( proc: TMergeSocketNewPacket); begin FOnNewSocket := proc; MergeSocket.OnNewSocket := proc; end; procedure TMergeSocketComponent.SetFOnRemoveSocket( proc: TMergeSocketNewPacket); begin FOnRemoveSocket := proc; MergeSocket.OnRemoveSocket := proc; end; end.
unit scan; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EnImgScr, StdCtrls, JvFormPlacement, JvComponentBase, JvAppStorage, JvAppIniStorage, Vcl.ImgList; type TFScan = class(TForm) btnok: TButton; JvAppIniFileStorage1: TJvAppIniFileStorage; JvFormPlacement1: TJvFormStorage; btnGrabar: TButton; SaveDialog: TSaveDialog; cb: TComboBox; Label1: TLabel; Button1: TButton; Button2: TButton; btnSelScanner: TButton; ImageScrollBox: TImageScrollBox; img: TImageList; procedure btnokClick(Sender: TObject); procedure btnGrabarClick(Sender: TObject); procedure cbChange(Sender: TObject); procedure btnSelScannerClick(Sender: TObject); private { Private declarations } Filename: Ansistring; procedure grabarImagen; public { Public declarations } procedure grabar( const Archivo: string ); procedure adquirir( const DibHandle : THandle; const XDpi : Word; const YDpi : Word; const CallBackData : LongInt ); end; var FScan: TFScan; implementation uses EnScan, { for Scanner } EnOverviewForm, { for TOverviewForm } EnDiGrph, { for TDibGraphic } EnTransf, { for TImageTransform } EnTifGr, { for TTifGraphic } EnPdfGr, { for TPdfGraphic } EnPngGr, { for TPngGraphic } EnPcxGr; {$R *.dfm} procedure TFScan.adquirir( const DibHandle : THandle; const XDpi : Word; const YDpi : Word; const CallBackData : LongInt ); var Graphic : TDibGraphic; begin {$WARNINGS OFF} Graphic := TDibGraphic.Create; try Graphic.AssignFromDIBHandle(DibHandle); Graphic.XDotsPerInch := XDpi; Graphic.YDotsPerInch := YDpi; ImageScrollBox.Graphic := Graphic; // grabarImagen; finally Graphic.Free; end; {$WARNINGS ON} end; procedure TFScan.btnGrabarClick(Sender: TObject); begin // grabarimagen; end; procedure TFScan.btnokClick(Sender: TObject); begin if not Scanner.IsConfigured then begin ShowMessage('Lo siento, no hay scanner configurado en este equipo.'); Exit; end; Self.Enabled := False; try { to hide the user interface and set parameters Scanner.ShowUI := False; Scanner.RequestedXDpi := 200; Scanner.RequestedYDpi := 200; Scanner.RequestedImageFormat := ifBlackWhite; } Scanner.OpenSource; try Scanner.AcquireWithSourceOpen( adquirir, 0); finally Scanner.CloseSource; end; // Other method of scanner, without using OpenSource, CloseSource // Scanner.Acquire(adquirir, 0); //} finally Self.Enabled := True; end; end; procedure TFScan.btnSelScannerClick(Sender: TObject); begin Scanner.SelectScanner; end; procedure TFScan.cbChange(Sender: TObject); begin case cb.ItemIndex of 0: Imagescrollbox.Zoommode := zmFitHeight; 1: Imagescrollbox.Zoommode := zmFitToPage; 2: Imagescrollbox.Zoommode := zmFitWidth; 3: Imagescrollbox.Zoommode := zmFullPage; 4: Imagescrollbox.Zoommode := zmOriginalSize; end; end; procedure TFScan.grabar( const Archivo: string ); begin if ImageScrollBox.Graphic = nil then Exit; ImageScrollBox.SaveToFile(Archivo); end; procedure TFScan.grabarImagen; begin SaveDialog.Filter := GraphicFilter(TDibGraphic); SaveDialog.DefaultExt := 'jpg'; if SaveDialog.Execute then begin FileName := AnsiString(SaveDialog.FileName); if FileExists(FileName) and (MessageDlg( 'Archivo ' + FileName + ' ya existe.'#13 + ' Lo sobre-escribe ?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes) then Abort; grabar( FileName ); Caption := FileName; end; end; end.
unit uFileUtils; interface uses SysUtils; procedure DeleteFileUTF8(const AFileName : string); function FileExistsUTF8(const AFileName: string) : Boolean; function FindFirstUTF8(const APath: string; AAttribute: Integer; var ARecord: TSearchRec): Integer; function DirectoryExistsUTF8(const APath: string): Boolean; function FindNextUTF8(var ARecord: TSearchRec): Integer; function CreateDirUTF8(const AFolder: string) : Boolean; procedure FindCloseUTF8(var ARecord: TSearchRec); implementation procedure DeleteFileUTF8(const AFileName: string); begin DeleteFile(AFileName); end; function FileExistsUTF8(const AFileName: string) : Boolean; begin Result := FileExists(AFileName); end; function FindFirstUTF8(const APath: string; AAttribute: Integer; var ARecord: TSearchRec): Integer; begin Result := FindFirst(APath,AAttribute,ARecord); end; function CreateDirUTF8(const AFolder: string) : Boolean; begin Result := CreateDir(AFolder); end; function DirectoryExistsUTF8(const APath: string): Boolean; begin Result := DirectoryExists(APath); end; function FindNextUTF8(var ARecord: TSearchRec): Integer; begin Result := FindNext(ARecord); end; procedure FindCloseUTF8(var ARecord: TSearchRec); begin FindClose(ARecord); end; end.
unit old_properties_commands; interface uses command_class_lib,classes,typInfo; type TChangePropertiesCommand=class(TAbstractTreeCommand) protected instance: TPersistent; fPropInfo: PPropInfo; procedure _getPropInfo(propPath: string); end; TChangeFloatProperty=class(TChangePropertiesCommand) private fPropPath: string; fBackUp,fVal: Real; procedure ReadPath(reader: TReader); procedure WritePath(writer: TWriter); procedure ReadValue(reader: TReader); procedure WriteValue(writer: TWriter); procedure ReadBackup(reader: TReader); procedure WriteBackup(writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(aPropPath: string; value: Real);reintroduce; overload; function Execute: Boolean; override; function Undo: boolean; override; function caption: string; override; end; TChangeIntegerProperty=class(TChangePropertiesCommand) private fPropPath: string; fBackUp,fVal: Integer; // fCaptionFormat: TChIntCaptionFormat; fCaption: string; procedure ReadPath(reader: TReader); procedure WritePath(writer: TWriter); procedure ReadValue(reader: TReader); procedure WriteValue(writer: TWriter); procedure ReadBackup(reader: TReader); procedure WriteBackup(writer: TWriter); procedure ReadCaption(reader: TReader); procedure WriteCaption(writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(aPropPath: string; value: Integer; aCaption: string=''); reintroduce; overload; function Execute: Boolean; override; function Undo: Boolean; override; function Caption: string; override; end; TChangeStringProperty=class(TChangePropertiesCommand) private fPropPath: string; fVal: string; fBackUp: string; procedure ReadPath(reader: TReader); procedure WritePath(writer: TWriter); procedure ReadValue(reader: TReader); procedure WriteValue(writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(aPropPath: string; value: string); reintroduce; overload; function Execute: Boolean; override; function Undo: Boolean; override; function Caption: string; override; end; TChangeEnumProperty=class(TChangePropertiesCommand) private fPropPath:string; fValName: string; procedure ReadPath(reader: TReader); procedure WritePath(writer: TWriter); procedure ReadValName(reader: TReader); procedure WriteValName(writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(aPropPath: string; valName: string); reintroduce; overload; function Execute: Boolean; override; function Undo: Boolean; override; function Caption: string; override; end; TChangeBoolProperty=class(TChangePropertiesCommand) private fPropPath: string; fVal: Boolean; procedure ReadPath(reader: TReader); procedure WritePath(writer: TWriter); procedure ReadValue(reader: TReader); procedure WriteValue(writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(aPropPath: string;value: Boolean); reintroduce; overload; function Execute: Boolean; override; function Undo: Boolean; override; function Caption: string; override; end; implementation uses SysUtils; (* TChangePropertiesCommand *) procedure TChangePropertiesCommand._getPropInfo(propPath: string); begin myGetPropInfo(propPath,instance,fPropInfo); end; (* TChangeFloatCommand *) constructor TChangeFloatProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); fImageIndex:=13; end; constructor TChangeFloatProperty.Create(aPropPath: string; value: Real); begin Create(nil); fPropPath:=aPropPath; fVal:=value; end; function TChangeFloatProperty.Execute: boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkFloat then Raise Exception.Create('error: property is not float number'); //вот теперь уж все получится) //но надо еще проверить, изменилось ли свойство от наших действий fBackUp:=GetFloatProp(instance,fPropInfo); if fBackUp=fVal then result:=false else begin SetFloatProp(instance,fPropInfo,fVal); Result:=true; end; end; function TChangeFloatProperty.Undo: Boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkFloat then Raise Exception.Create('error: property is not float number'); SetFloatProp(instance,fPropInfo,fBackup); fBackUp:=0; //чтобы места не занимал Result:=true; end; function TChangeFloatProperty.caption: string; begin Result:=fPropPath+'='+FloatToStr(fVal); end; procedure TChangeFloatProperty.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('Path',ReadPath,WritePath,true); //не будем жадничать, путь всегда ненулевой! Filer.DefineProperty('value',ReadValue,WriteValue,(fVal<>0)); Filer.DefineProperty('backup',ReadBackup,WriteBackup,(fBackup<>0)); end; procedure TChangeFloatProperty.ReadPath(reader: TReader); begin fPropPath:=reader.ReadString; end; procedure TChangeFloatProperty.WritePath(writer: TWriter); begin writer.WriteString(fPropPath); end; procedure TChangeFloatProperty.ReadValue(reader: TReader); begin fVal:=reader.ReadFloat; end; procedure TChangeFloatProperty.WriteValue(writer: TWriter); begin writer.WriteFloat(fVal); end; procedure TChangeFloatProperty.ReadBackup(reader: TReader); begin fBackup:=reader.ReadFloat; end; procedure TChangeFloatProperty.WriteBackup(writer: TWriter); begin writer.WriteFloat(fBackup); end; (* TChangeIntegerProperty *) constructor TChangeIntegerProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); fImageIndex:=13; end; constructor TChangeIntegerProperty.Create(aPropPath: string; value: Integer; aCaption: string=''); begin Create(nil); fPropPath:=aPropPath; fVal:=value; fCaption:=aCaption; end; function TChangeIntegerProperty.Execute: boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkInteger then Raise Exception.Create('error: property is not integer'); //вот теперь уж все получится) //но надо еще проверить, изменилось ли свойство от наших действий fBackUp:=GetOrdProp(instance,fPropInfo); if fBackUp=fVal then result:=false else begin SetOrdProp(instance,fPropInfo,fVal); Result:=true; end; end; function TChangeIntegerProperty.Undo: Boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkInteger then Raise Exception.Create('error: property is not integer'); SetOrdProp(instance,fPropInfo,fBackup); fBackup:=0; Result:=true; end; function TChangeIntegerProperty.caption: string; begin if fCaption='' then Result:=fPropPath+'='+IntToStr(fVal) else Result:=fCaption; end; procedure TChangeIntegerProperty.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('Path',ReadPath,WritePath,true); //не будем жадничать, путь всегда ненулевой! Filer.DefineProperty('value',ReadValue,WriteValue,(fVal<>0)); Filer.DefineProperty('backup',ReadBackup,WriteBackup,(fBackup<>0)); Filer.DefineProperty('caption',ReadCaption,WriteCaption,(fCaption<>'')); end; procedure TChangeIntegerProperty.ReadPath(reader: TReader); begin fPropPath:=reader.ReadString; end; procedure TChangeIntegerProperty.WritePath(writer: TWriter); begin writer.WriteString(fPropPath); end; procedure TChangeIntegerProperty.ReadValue(reader: TReader); begin fVal:=reader.ReadInteger; end; procedure TChangeIntegerProperty.WriteValue(writer: TWriter); begin writer.WriteInteger(fVal); end; procedure TChangeIntegerProperty.ReadBackup(reader: TReader); begin fBackup:=reader.ReadInteger; end; procedure TChangeIntegerProperty.WriteBackup(writer: TWriter); begin writer.WriteInteger(fBackup); end; procedure TChangeIntegerProperty.ReadCaption(reader: TReader); begin fCaption:=reader.ReadString; end; procedure TChangeIntegerProperty.WriteCaption(writer: TWriter); begin writer.WriteString(fCaption); end; (* TChangeEnumProperty *) constructor TChangeEnumProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); fImageIndex:=13; end; constructor TChangeEnumProperty.Create(aPropPath: string; valName: string); begin Create(nil); fPropPath:=aPropPath; fValName:=valName; end; procedure TChangeEnumProperty.DefineProperties(Filer: TFiler); begin filer.DefineProperty('Path',ReadPath,WritePath,true); filer.DefineProperty('ValName',ReadValName,WriteValName,true); end; procedure TChangeEnumProperty.ReadPath(reader: TReader); begin fPropPath:=reader.ReadString; end; procedure TChangeEnumProperty.WritePath(writer: TWriter); begin writer.WriteString(fPropPath); end; procedure TChangeEnumProperty.ReadValName(reader: TReader); begin fValName:=reader.ReadString; end; procedure TChangeEnumProperty.WriteValName(writer: TWriter); begin writer.WriteString(fValName); end; function TChangeEnumProperty.Caption: string; begin Result:=fPropPath+'='+fValName; end; function TChangeEnumProperty.Execute: Boolean; var tmp: string; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.Create('error: property is not enumeration'); tmp:=GetEnumProp(instance,fPropInfo); if fValName=tmp then result:=false else begin SetEnumProp(instance,fPropInfo,fValName); Result:=true; end; end; function TChangeEnumProperty.Undo: Boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.Create('error: property is not enumeration'); SetEnumProp(instance,fPropInfo,fValName); Result:=true; end; (* TChangeStringProperty *) constructor TChangeStringProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); fImageIndex:=13; end; constructor TChangeStringProperty.Create(aPropPath: string; value: String); begin Create(nil); fVal:=value; fPropPath:=aPropPath; end; procedure TChangeStringProperty.ReadPath(reader: TReader); begin fPropPath:=reader.ReadString; end; procedure TChangeStringProperty.ReadValue(reader: TReader); begin fVal:=reader.ReadString; end; procedure TChangeStringProperty.WritePath(writer: TWriter); begin writer.WriteString(fPropPath); end; procedure TChangeStringProperty.WriteValue(writer: TWriter); begin writer.WriteString(fVal); end; procedure TChangeStringProperty.DefineProperties(Filer: TFiler); begin filer.DefineProperty('path',ReadPath,WritePath,true); filer.DefineProperty('value',ReadValue,WriteValue,Length(fval)>0); end; function TChangeStringProperty.Caption: string; begin result:=fPropPath+'='+fVal; end; function TChangeStringProperty.Execute: Boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if not (fPropInfo.PropType^.Kind in [tkString,tkLstring,tkWstring]) then Raise Exception.Create('error: property is not string'); //вот теперь уж все получится) //но надо еще проверить, изменилось ли свойство от наших действий fBackUp:=GetStrProp(instance,fPropInfo); // GetFloatProp(instance,fPropInfo); if fBackUp=fVal then result:=false else begin SetStrProp(instance,fPropInfo,fVal); Result:=true; end; end; function TChangeStringProperty.Undo: Boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if not (fPropInfo.PropType^.Kind in [tkString,tkLstring,tkWstring]) then Raise Exception.Create('error: property is not string'); SetStrProp(instance,fPropInfo,fBackup); fBackUp:=''; //чтобы места не занимал Result:=true; end; (* TChangeBoolProperty *) constructor TChangeBoolProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); fImageIndex:=13; end; constructor TChangeBoolProperty.Create(aPropPath: string; value: Boolean); begin Create(nil); fpropPath:=aPropPath; fVal:=value; end; function TChangeBoolProperty.Execute: boolean; var res: LongInt; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.Create('error: property is not boolean'); res:=GetOrdProp(instance,fPropInfo); if fVal=Boolean(res) then result:=false else begin SetOrdProp(instance,fPropInfo,Integer(fVal)); Result:=true; end; end; function TChangeBoolProperty.Undo: boolean; begin _getPropInfo(fPropPath); if fPropInfo.SetProc=nil then Raise Exception.Create('error: write to read-only property'); if fPropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.Create('error: property is not float number'); SetOrdProp(instance,fPropInfo,Integer(not fVal)); Result:=true; end; function TChangeBoolProperty.Caption: string; begin Result:=fPropPath+'='+BoolToStr(fVal,true); end; procedure TChangeBoolProperty.ReadPath(reader: TReader); begin fPropPath:=reader.ReadString; end; procedure TChangeBoolProperty.WritePath(writer: TWriter); begin writer.WriteString(fPropPath); end; procedure TChangeBoolProperty.ReadValue(reader: TReader); begin fVal:=reader.ReadBoolean; end; procedure TChangeBoolProperty.WriteValue(writer: TWriter); begin writer.WriteBoolean(fVal); end; procedure TChangeBoolProperty.DefineProperties(Filer: TFiler); begin filer.DefineProperty('Path',ReadPath,WritePath,true); filer.DefineProperty('Value',ReadValue,WriteValue,true); end; initialization RegisterClasses([TChangeBoolProperty,TChangeEnumProperty,TChangeFloatProperty, TChangeIntegerProperty,TChangeStringProperty]); end.
{ Subroutine SST_R_SYN_ITEM (JTARG) * * Process ITEM syntax. } module sst_r_syn_item; define sst_r_syn_item; %include 'sst_r_syn.ins.pas'; procedure sst_r_syn_item ( {process ITEM syntax} in out jtarg: jump_targets_t); {execution block jump targets info} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var tag: sys_int_machine_t; {tag from syntax tree} jt: jump_targets_t; {jump targets for nested routines} itag: sys_int_machine_t; {tag value if item is tagged} token: string_var32_t; {scratch token for number conversion} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; label trerr; begin token.max := sizeof(token.str); {init local var string} if not syn_trav_next_down (syn_p^) {down into ITEM syntax} then goto trerr; { * Temporarily skip over UNTAGGED_ITEM that always starts the item, and get the * next tag. That determines the format of the overall item, and thereby * whether to create a tag or not. } syn_trav_push (syn_p^); {save current syntax tree position} if syn_trav_next(syn_p^) <> syn_tent_sub_k {go to UNTAGGED_ITEM tree entry} then goto trerr; tag := syn_trav_next_tag (syn_p^); {get tag after UNTAGGED_ITEM} { * TAG is the next tag after UNTAGGED_ITEM. The syntax tree position is at the * tag, but the position before UNTAGGED_ITEM is on the stack. } case tag of {is the item tagged or not ?} { ************************************** * * Item is tagged. } 1: begin syn_trav_tag_string (syn_p^, token); {get the tagged string} string_t_int (token, itag, stat); {make tag value in ITAG} if sys_error(stat) then begin sys_msg_parm_vstr (msg_parm[1], token); syn_error_bomb (syn_p^, stat, 'sst_syn_read', 'tag_string_bad', msg_parm, 1); end; if itag < 1 then begin {invalid tag value ?} sys_msg_parm_int (msg_parm[1], itag); syn_error_bomb (syn_p^, stat, 'sst_syn_read', 'tag_val_bad', msg_parm, 1); end; syn_trav_pop (syn_p^); {restore position to UNTAGGED_ITEM} sst_call (sym_tag_start_p^); {write call to start tag} sst_r_syn_arg_syn; {add SYN argument} sst_call_arg_int (sst_opc_p^, itag); {pass the tag value} sst_r_syn_jtarg_sub ( {make subordinate jump targets for UNTAGGED_ITEM} jtarg, {parent jump targets} jt, {new subordinate targets} lab_fall_k, {fall thru on YES} lab_fall_k); {fall thru on NO} sst_r_syn_utitem (jt); {process UNTAGGED_ITEM syntax} sst_r_syn_jtarg_here (jt); {define jump target labels here} sst_call (sym_tag_end_p^); {write call to end tag} sst_r_syn_arg_syn; {add SYN argument} sst_r_syn_arg_match; {pass MATCH} sst_r_syn_jtarg_goto (jtarg, [jtarg_yes_k, jtarg_no_k]); end; { ************************************** * * Item is untagged. * * All other unexpected tag values are also processed here. Unexpected tags * are most likely due to a syntax error that caused the ITEM type tag not to * be created. Continuing with the UNTAGGED_ITEM will allow processing up to * the error end of the syntax tree, which results in the best possible error * message. } otherwise syn_trav_pop (syn_p^); {restore position to UNTAGGED_ITEM} sst_r_syn_utitem (jtarg); {ITEM resolves to just this UNTAGGED_ITEM} end; { ************************************** } if not syn_trav_up(syn_p^) {back up from UNTAGGED_ITEM syntax} then goto trerr; return; { * The syntax tree is not as expected. We assume this is due to a syntax * error. } trerr: sys_message ('sst_syn_read', 'syerr_item'); syn_parse_err_show (syn_p^); sys_bomb; end;
unit CRCUnit; interface uses Windows, SysUtils, StdCtrls, Math; type TCRC= record bit:byte; Poly:DWord; Init,XorOut:Dword; ReflIn,ReflOut:boolean; end; TCRCType = (crcUserType, crc16Modbus, crc16CCIT_FFFF, crc16CCIT_XModem, crc16CCIT_Kermit, crc16ModbusLSB, crc24PLCI); TCRCCreator = class private FCRCType : TCRCType; T : TCRC; TableCRC : array of DWORD; public constructor Create (crctype : TCRCType); overload; constructor Create (var CRCINIT : TCRC); overload; function GetCRC (var ABuffer; Len : Integer) : DWord; property CRCType : TCRCType read FCRCType write FCRCType; end; function GetCRC32(p:pointer;length:integer):DWord; function GetCRC16(p:pointer;length:integer):Word; function CRC(bit:byte;Poly:DWord; Init,XorOut:Dword;ReflIn,ReflOut:boolean):TCRC; procedure CreatTableCRC(T:TCRC; var Tabel : array of DWORD); function GetCRC(t:TCRC;p:pointer;length:integer;Tabel:Pointer):DWord; implementation var test:array [0..8] of char=('1','2','3','4','5','6','7','8','9'); test2:array [0..3]of byte=($11,$22,$33,$44); testCRC16:Word=$BB3D; testCRC16CCITT:Word=$29B1; testCRC16CCITTG:Word=$E5CC; {init=1D0F} testCRC32:DWord=$CBF43926; tabelCRC16:array [0..$FF] of Word = ($0000,$C0C1,$C181,$0140,$C301,$03C0,$0280,$C241 ,$C601,$06C0,$0780,$C741,$0500,$C5C1,$C481,$0440 ,$CC01,$0CC0,$0D80,$CD41,$0F00,$CFC1,$CE81,$0E40 ,$0A00,$CAC1,$CB81,$0B40,$C901,$09C0,$0880,$C841 ,$D801,$18C0,$1980,$D941,$1B00,$DBC1,$DA81,$1A40 ,$1E00,$DEC1,$DF81,$1F40,$DD01,$1DC0,$1C80,$DC41 ,$1400,$D4C1,$D581,$1540,$D701,$17C0,$1680,$D641 ,$D201,$12C0,$1380,$D341,$1100,$D1C1,$D081,$1040 ,$F001,$30C0,$3180,$F141,$3300,$F3C1,$F281,$3240 ,$3600,$F6C1,$F781,$3740,$F501,$35C0,$3480,$F441 ,$3C00,$FCC1,$FD81,$3D40,$FF01,$3FC0,$3E80,$FE41 ,$FA01,$3AC0,$3B80,$FB41,$3900,$F9C1,$F881,$3840 ,$2800,$E8C1,$E981,$2940,$EB01,$2BC0,$2A80,$EA41 ,$EE01,$2EC0,$2F80,$EF41,$2D00,$EDC1,$EC81,$2C40 ,$E401,$24C0,$2580,$E541,$2700,$E7C1,$E681,$2640 ,$2200,$E2C1,$E381,$2340,$E101,$21C0,$2080,$E041 ,$A001,$60C0,$6180,$A141,$6300,$A3C1,$A281,$6240 ,$6600,$A6C1,$A781,$6740,$A501,$65C0,$6480,$A441 ,$6C00,$ACC1,$AD81,$6D40,$AF01,$6FC0,$6E80,$AE41 ,$AA01,$6AC0,$6B80,$AB41,$6900,$A9C1,$A881,$6840 ,$7800,$B8C1,$B981,$7940,$BB01,$7BC0,$7A80,$BA41 ,$BE01,$7EC0,$7F80,$BF41,$7D00,$BDC1,$BC81,$7C40 ,$B401,$74C0,$7580,$B541,$7700,$B7C1,$B681,$7640 ,$7200,$B2C1,$B381,$7340,$B101,$71C0,$7080,$B041 ,$5000,$90C1,$9181,$5140,$9301,$53C0,$5280,$9241 ,$9601,$56C0,$5780,$9741,$5500,$95C1,$9481,$5440 ,$9C01,$5CC0,$5D80,$9D41,$5F00,$9FC1,$9E81,$5E40 ,$5A00,$9AC1,$9B81,$5B40,$9901,$59C0,$5880,$9841 ,$8801,$48C0,$4980,$8941,$4B00,$8BC1,$8A81,$4A40 ,$4E00,$8EC1,$8F81,$4F40,$8D01,$4DC0,$4C80,$8C41 ,$4400,$84C1,$8581,$4540,$8701,$47C0,$4680,$8641 ,$8201,$42C0,$4380,$8341,$4100,$81C1,$8081,$4040); tabelCRC32:array [0..$FF] of DWord = ($00000000,$77073096,$EE0E612C,$990951BA ,$076DC419,$706AF48F,$E963A535,$9E6495A3 ,$0EDB8832,$79DCB8A4,$E0D5E91E,$97D2D988 ,$09B64C2B,$7EB17CBD,$E7B82D07,$90BF1D91 ,$1DB71064,$6AB020F2,$F3B97148,$84BE41DE ,$1ADAD47D,$6DDDE4EB,$F4D4B551,$83D385C7 ,$136C9856,$646BA8C0,$FD62F97A,$8A65C9EC ,$14015C4F,$63066CD9,$FA0F3D63,$8D080DF5 ,$3B6E20C8,$4C69105E,$D56041E4,$A2677172 ,$3C03E4D1,$4B04D447,$D20D85FD,$A50AB56B ,$35B5A8FA,$42B2986C,$DBBBC9D6,$ACBCF940 ,$32D86CE3,$45DF5C75,$DCD60DCF,$ABD13D59 ,$26D930AC,$51DE003A,$C8D75180,$BFD06116 ,$21B4F4B5,$56B3C423,$CFBA9599,$B8BDA50F ,$2802B89E,$5F058808,$C60CD9B2,$B10BE924 ,$2F6F7C87,$58684C11,$C1611DAB,$B6662D3D ,$76DC4190,$01DB7106,$98D220BC,$EFD5102A ,$71B18589,$06B6B51F,$9FBFE4A5,$E8B8D433 ,$7807C9A2,$0F00F934,$9609A88E,$E10E9818 ,$7F6A0DBB,$086D3D2D,$91646C97,$E6635C01 ,$6B6B51F4,$1C6C6162,$856530D8,$F262004E ,$6C0695ED,$1B01A57B,$8208F4C1,$F50FC457 ,$65B0D9C6,$12B7E950,$8BBEB8EA,$FCB9887C ,$62DD1DDF,$15DA2D49,$8CD37CF3,$FBD44C65 ,$4DB26158,$3AB551CE,$A3BC0074,$D4BB30E2 ,$4ADFA541,$3DD895D7,$A4D1C46D,$D3D6F4FB ,$4369E96A,$346ED9FC,$AD678846,$DA60B8D0 ,$44042D73,$33031DE5,$AA0A4C5F,$DD0D7CC9 ,$5005713C,$270241AA,$BE0B1010,$C90C2086 ,$5768B525,$206F85B3,$B966D409,$CE61E49F ,$5EDEF90E,$29D9C998,$B0D09822,$C7D7A8B4 ,$59B33D17,$2EB40D81,$B7BD5C3B,$C0BA6CAD ,$EDB88320,$9ABFB3B6,$03B6E20C,$74B1D29A ,$EAD54739,$9DD277AF,$04DB2615,$73DC1683 ,$E3630B12,$94643B84,$0D6D6A3E,$7A6A5AA8 ,$E40ECF0B,$9309FF9D,$0A00AE27,$7D079EB1 ,$F00F9344,$8708A3D2,$1E01F268,$6906C2FE ,$F762575D,$806567CB,$196C3671,$6E6B06E7 ,$FED41B76,$89D32BE0,$10DA7A5A,$67DD4ACC ,$F9B9DF6F,$8EBEEFF9,$17B7BE43,$60B08ED5 ,$D6D6A3E8,$A1D1937E,$38D8C2C4,$4FDFF252 ,$D1BB67F1,$A6BC5767,$3FB506DD,$48B2364B ,$D80D2BDA,$AF0A1B4C,$36034AF6,$41047A60 ,$DF60EFC3,$A867DF55,$316E8EEF,$4669BE79 ,$CB61B38C,$BC66831A,$256FD2A0,$5268E236 ,$CC0C7795,$BB0B4703,$220216B9,$5505262F ,$C5BA3BBE,$B2BD0B28,$2BB45A92,$5CB36A04 ,$C2D7FFA7,$B5D0CF31,$2CD99E8B,$5BDEAE1D ,$9B64C2B0,$EC63F226,$756AA39C,$026D930A ,$9C0906A9,$EB0E363F,$72076785,$05005713 ,$95BF4A82,$E2B87A14,$7BB12BAE,$0CB61B38 ,$92D28E9B,$E5D5BE0D,$7CDCEFB7,$0BDBDF21 ,$86D3D2D4,$F1D4E242,$68DDB3F8,$1FDA836E ,$81BE16CD,$F6B9265B,$6FB077E1,$18B74777 ,$88085AE6,$FF0F6A70,$66063BCA,$11010B5C ,$8F659EFF,$F862AE69,$616BFFD3,$166CCF45 ,$A00AE278,$D70DD2EE,$4E048354,$3903B3C2 ,$A7672661,$D06016F7,$4969474D,$3E6E77DB ,$AED16A4A,$D9D65ADC,$40DF0B66,$37D83BF0 ,$A9BCAE53,$DEBB9EC5,$47B2CF7F,$30B5FFE9 ,$BDBDF21C,$CABAC28A,$53B39330,$24B4A3A6 ,$BAD03605,$CDD70693,$54DE5729,$23D967BF ,$B3667A2E,$C4614AB8,$5D681B02,$2A6F2B94 ,$B40BBE37,$C30C8EA1,$5A05DF1B,$2D02EF8D); function revers(w:DWord; j:integer):DWord; var i:integer; p:DWord; begin p:=0; for i:=1 to j do begin if w and 1<>0 then p:=(p shl 1) or 1 else p:=(p shl 1); w:=w shr 1; end; revers:=p; end; function GetCRC32(p:pointer;length:integer):DWord; var crc:DWord; i:integer; begin CRC:=$FFFFFFFF; for i:=0 to length-1 do begin CRC:= (CRC shr 8) xor TabelCRC32[byte(CRC) xor Byte(PByte(p)[i])]; end; CRC:=CRC xor $FFFFFFFF; GetCRC32:=CRC; end; function GetCRC16(p:pointer;length:integer):Word; var crc:Word; i:integer; begin CRC:=0; for i:=0 to length-1 do begin CRC:= (CRC shr 8) xor TabelCRC16[byte(CRC) xor Byte(PByte(p)[i])]; end; CRC:=CRC xor $0; GetCRC16:=CRC; end; function GetCRC(t:TCRC;p:pointer;length:integer;Tabel:Pointer):DWord; type TTable=array [0..0] of DWord; PTable=^TTable; var crc:DWord; i:integer; begin CRC:=t.Init; if (t.ReflIn) then for i:=0 to length-1 do CRC:= (CRC shr 8) xor PTable(Tabel)[byte(CRC) xor Byte(PByte(p)[i])] else begin for i:=0 to length-1 do CRC:= (CRC shl 8) xor PTable(Tabel)[byte(CRC shr (t.bit-8)) xor Byte(PByte(p)[i])]; end; CRC:=CRC xor t.XorOut; if (t.ReflOut xor t.ReflIn) then CRC:=revers(CRC,t.bit); GetCRC:=CRC shl (32-t.bit) shr (32-t.bit); end; function CRC(bit:byte;Poly:DWord; Init,XorOut:Dword;ReflIn,ReflOut:boolean):TCRC; begin Result.Init:=Init; Result.XorOut:=XorOut; Result.Poly:=Poly; Result.bit:=bit; Result.ReflIn:=ReflIn; Result.ReflOut:=ReflOut; end; procedure CreatTableCRC(T:TCRC; var Tabel : array of DWORD); var i, j: Word; crc: DWord; begin if (t.ReflIn) then begin t.Poly:=revers(t.Poly,t.bit); for i := 0 to 255 do begin crc := i; for j := 0 to 7 do if (crc and 1) <> 0 then crc := (crc shr 1) xor t.Poly else crc := (crc shr 1); Tabel [i] := crc; end; end else begin for i := 0 to 255 do begin crc := i shl (t.bit-8); for j := 0 to 7 do if (crc and (1 shl (t.bit-1))) <> 0 then crc := (crc shl 1) xor t.Poly else crc := (crc shl 1); Tabel [i] := crc mod (1 shl t.bit); end; end; end; { TCRCCreator } constructor TCRCCreator.Create(crctype: TCRCType); begin inherited Create; SetLength (TableCRC, 512); FCRCType := crctype; case crctype of crcUserType : begin T.bit := 8; T.Poly := 0; T.Init := 0; T.XorOut := 0; T.ReflIn := false; T.ReflOut := false; end; crc16Modbus, crc16ModbusLSB : begin T.bit := 16; T.Poly := $8005; T.Init := $FFFF; T.XorOut := 0; T.ReflIn := true; T.ReflOut := true; end; crc16CCIT_FFFF : begin T.bit := 16; T.Poly := $1021; T.Init := $FFFF; T.XorOut := 0; T.ReflIn := false; T.ReflOut := false; end; crc16CCIT_XModem : begin T.bit := 16; T.Poly := $1021; T.Init := 0; T.XorOut := 0; T.ReflIn := false; T.ReflOut := false; end; crc16CCIT_Kermit : begin T.bit := 16; T.Poly := $1021; T.Init := 0; T.XorOut := 0; T.ReflIn := true; T.ReflOut := true; end; crc24PLCI : begin T.bit := 24; T.Poly := $01864CFB; T.Init := $00b704ce; T.XorOut := 0; T.ReflIn := false; T.ReflOut := false; end; end; CreatTableCRC (T,TableCRC[0]); end; constructor TCRCCreator.Create(var CRCINIT: TCRC); begin inherited Create; SetLength (TableCRC, 512); T := CRCINIT; CreatTableCRC (T,TableCRC); FCRCType := crcUserType; end; function TCRCCreator.GetCRC(var ABuffer; Len: Integer): DWord; var crc:DWord; i:integer; begin CRC:=t.Init; if (t.ReflIn) then for i:=0 to Len-1 do CRC:= (CRC shr 8) xor TableCRC[byte(CRC) xor Byte(PByte(ABuffer)[i])] else begin for i:=0 to Len-1 do CRC:= (CRC shl 8) xor TableCRC[byte(CRC shr (t.bit-8)) xor Byte(PByte(ABuffer)[i])]; end; CRC:=CRC xor t.XorOut; if (t.ReflOut xor t.ReflIn) then CRC:=revers(CRC,t.bit); Result :=CRC shl (32-t.bit) shr (32-t.bit); if FCRCType = crc16CCIT_Kermit then begin CRC := Lo (Result) shl 8 + Hi (Result); Result := crc; end; end; end.
unit TTSCAPTIONTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCAPTIONRecord = record PLenderNum: String[4]; PLoan: String[20]; PCIF: String[20]; PLender: String[20]; PBorrower: String[20]; PBoldLoan: String[20]; PBranch: String[20]; PDivision: String[20]; PCollateral: String[20]; PCoMaker: String[20]; End; TTTSCAPTIONBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCAPTIONRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCAPTION = (TTSCAPTIONPrimaryKey); TTTSCAPTIONTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFLoan: TStringField; FDFCIF: TStringField; FDFLender: TStringField; FDFBorrower: TStringField; FDFBoldLoan: TStringField; FDFBranch: TStringField; FDFDivision: TStringField; FDFCollateral: TStringField; FDFCoMaker: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPLoan(const Value: String); function GetPLoan:String; procedure SetPCIF(const Value: String); function GetPCIF:String; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPBorrower(const Value: String); function GetPBorrower:String; procedure SetPBoldLoan(const Value: String); function GetPBoldLoan:String; procedure SetPBranch(const Value: String); function GetPBranch:String; procedure SetPDivision(const Value: String); function GetPDivision:String; procedure SetPCollateral(const Value: String); function GetPCollateral:String; procedure SetPCoMaker(const Value: String); function GetPCoMaker:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSCAPTION); function GetEnumIndex: TEITTSCAPTION; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCAPTIONRecord; procedure StoreDataBuffer(ABuffer:TTTSCAPTIONRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFLoan: TStringField read FDFLoan; property DFCIF: TStringField read FDFCIF; property DFLender: TStringField read FDFLender; property DFBorrower: TStringField read FDFBorrower; property DFBoldLoan: TStringField read FDFBoldLoan; property DFBranch: TStringField read FDFBranch; property DFDivision: TStringField read FDFDivision; property DFCollateral: TStringField read FDFCollateral; property DFCoMaker: TStringField read FDFCoMaker; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PLoan: String read GetPLoan write SetPLoan; property PCIF: String read GetPCIF write SetPCIF; property PLender: String read GetPLender write SetPLender; property PBorrower: String read GetPBorrower write SetPBorrower; property PBoldLoan: String read GetPBoldLoan write SetPBoldLoan; property PBranch: String read GetPBranch write SetPBranch; property PDivision: String read GetPDivision write SetPDivision; property PCollateral: String read GetPCollateral write SetPCollateral; property PCoMaker: String read GetPCoMaker write SetPCoMaker; published property Active write SetActive; property EnumIndex: TEITTSCAPTION read GetEnumIndex write SetEnumIndex; end; { TTTSCAPTIONTable } procedure Register; implementation function TTTSCAPTIONTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSCAPTIONTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSCAPTIONTable.GenerateNewFieldName } function TTTSCAPTIONTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSCAPTIONTable.CreateField } procedure TTTSCAPTIONTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFLoan := CreateField( 'Loan' ) as TStringField; FDFCIF := CreateField( 'CIF' ) as TStringField; FDFLender := CreateField( 'Lender' ) as TStringField; FDFBorrower := CreateField( 'Borrower' ) as TStringField; FDFBoldLoan := CreateField( 'BoldLoan' ) as TStringField; FDFBranch := CreateField( 'Branch' ) as TStringField; FDFDivision := CreateField( 'Division' ) as TStringField; FDFCollateral := CreateField( 'Collateral' ) as TStringField; FDFCoMaker := CreateField( 'CoMaker' ) as TStringField; end; { TTTSCAPTIONTable.CreateFields } procedure TTTSCAPTIONTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCAPTIONTable.SetActive } procedure TTTSCAPTIONTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCAPTIONTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCAPTIONTable.SetPLoan(const Value: String); begin DFLoan.Value := Value; end; function TTTSCAPTIONTable.GetPLoan:String; begin result := DFLoan.Value; end; procedure TTTSCAPTIONTable.SetPCIF(const Value: String); begin DFCIF.Value := Value; end; function TTTSCAPTIONTable.GetPCIF:String; begin result := DFCIF.Value; end; procedure TTTSCAPTIONTable.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TTTSCAPTIONTable.GetPLender:String; begin result := DFLender.Value; end; procedure TTTSCAPTIONTable.SetPBorrower(const Value: String); begin DFBorrower.Value := Value; end; function TTTSCAPTIONTable.GetPBorrower:String; begin result := DFBorrower.Value; end; procedure TTTSCAPTIONTable.SetPBoldLoan(const Value: String); begin DFBoldLoan.Value := Value; end; function TTTSCAPTIONTable.GetPBoldLoan:String; begin result := DFBoldLoan.Value; end; procedure TTTSCAPTIONTable.SetPBranch(const Value: String); begin DFBranch.Value := Value; end; function TTTSCAPTIONTable.GetPBranch:String; begin result := DFBranch.Value; end; procedure TTTSCAPTIONTable.SetPDivision(const Value: String); begin DFDivision.Value := Value; end; function TTTSCAPTIONTable.GetPDivision:String; begin result := DFDivision.Value; end; procedure TTTSCAPTIONTable.SetPCollateral(const Value: String); begin DFCollateral.Value := Value; end; function TTTSCAPTIONTable.GetPCollateral:String; begin result := DFCollateral.Value; end; procedure TTTSCAPTIONTable.SetPCoMaker(const Value: String); begin DFCoMaker.Value := Value; end; function TTTSCAPTIONTable.GetPCoMaker:String; begin result := DFCoMaker.Value; end; procedure TTTSCAPTIONTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('Loan, String, 20, N'); Add('CIF, String, 20, N'); Add('Lender, String, 20, N'); Add('Borrower, String, 20, N'); Add('BoldLoan, String, 20, N'); Add('Branch, String, 20, N'); Add('Division, String, 20, N'); Add('Collateral, String, 20, N'); Add('CoMaker, String, 20, N'); end; end; procedure TTTSCAPTIONTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum, Y, Y, N, N'); end; end; procedure TTTSCAPTIONTable.SetEnumIndex(Value: TEITTSCAPTION); begin case Value of TTSCAPTIONPrimaryKey : IndexName := ''; end; end; function TTTSCAPTIONTable.GetDataBuffer:TTTSCAPTIONRecord; var buf: TTTSCAPTIONRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PLoan := DFLoan.Value; buf.PCIF := DFCIF.Value; buf.PLender := DFLender.Value; buf.PBorrower := DFBorrower.Value; buf.PBoldLoan := DFBoldLoan.Value; buf.PBranch := DFBranch.Value; buf.PDivision := DFDivision.Value; buf.PCollateral := DFCollateral.Value; buf.PCoMaker := DFCoMaker.Value; result := buf; end; procedure TTTSCAPTIONTable.StoreDataBuffer(ABuffer:TTTSCAPTIONRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFLoan.Value := ABuffer.PLoan; DFCIF.Value := ABuffer.PCIF; DFLender.Value := ABuffer.PLender; DFBorrower.Value := ABuffer.PBorrower; DFBoldLoan.Value := ABuffer.PBoldLoan; DFBranch.Value := ABuffer.PBranch; DFDivision.Value := ABuffer.PDivision; DFCollateral.Value := ABuffer.PCollateral; DFCoMaker.Value := ABuffer.PCoMaker; end; function TTTSCAPTIONTable.GetEnumIndex: TEITTSCAPTION; var iname : string; begin result := TTSCAPTIONPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCAPTIONPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCAPTIONTable, TTTSCAPTIONBuffer ] ); end; { Register } function TTTSCAPTIONBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..10] of string = ('LENDERNUM','LOAN','CIF','LENDER','BORROWER','BOLDLOAN' ,'BRANCH','DIVISION','COLLATERAL','COMAKER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 10) and (flist[x] <> s) do inc(x); if x <= 10 then result := x else result := 0; end; function TTTSCAPTIONBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; end; end; function TTTSCAPTIONBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PLoan; 3 : result := @Data.PCIF; 4 : result := @Data.PLender; 5 : result := @Data.PBorrower; 6 : result := @Data.PBoldLoan; 7 : result := @Data.PBranch; 8 : result := @Data.PDivision; 9 : result := @Data.PCollateral; 10 : result := @Data.PCoMaker; end; end; end.
{ Here should be a description ----- } unit ConfigureImtired; uses mteFunctions, uselesscore; const SOURCE_FILE_NAME = 'imtired2.esp'; SHIELD_L_LOW_ATTACK_DAMAGE = 10.0; // -n% lower attack damage SHIELD_L_LOW_SPEED = 10.0; // -n% lower speed SHIELD_H_LOW_ATTACK_DAMAGE = 20.0; // -n% lower attack damage SHIELD_H_LOW_SPEED = 15.0; // -n% lower speed BOW_L_LOW_SPEED = 5.0; BOW_H_LOW_SPEED = 10.0; ARMOR_LIGHT = 1.0; // cloth ARMOR_MID = -8.0; // light ARMOR_HIGHT = -15.0; // heavy BOW_LH_BORDER = 10.0; BOW_L_DMG = 10.0; BOW_H_DMG = 20.0; STAMINARATE_A = 0.646248; STAMINARATE_B = 9.920867; STAMINARATE_COMBATMULT = 0.5; function Initialize: integer; begin ScriptProcessElements := [etFile]; end; function findrec(id:string):IInterface; begin result := findRecord(SOURCE_FILE_NAME, id); end; function Finalize(): Integer; var e, f:IInterface; begin f := filebyname(SOURCE_FILE_NAME); // f314IM_ShieldPerk_H e := findrec('01A277'); seev(e, 'Effects\[1]\Function Parameters\EPFD\Float', (100.0 - SHIELD_H_LOW_ATTACK_DAMAGE) / 100.0); // f314IM_ShieldPerk_L e := findrec('02E694'); seev(e, 'Effects\[1]\Function Parameters\EPFD\Float', (100.0 - SHIELD_L_LOW_ATTACK_DAMAGE) / 100.0); // f314IM_Shield_SpeedSpell_H e := findrec('02447C'); seev(e, 'Effects\[0]\EFIT\Magnitude', -SHIELD_H_LOW_SPEED); // f314IM_Shield_SpeedSpell_L e := findrec('02E693'); seev(e, 'Effects\[0]\EFIT\Magnitude', -SHIELD_L_LOW_SPEED); // f314IM_ArmorSpeedSpell[1, 2, 3] seev(findrec('02E680'), 'Effects\[0]\EFIT\Magnitude', ARMOR_LIGHT); seev(findrec('02E681'), 'Effects\[0]\EFIT\Magnitude', ARMOR_MID); seev(findrec('02E682'), 'Effects\[0]\EFIT\Magnitude', ARMOR_HIGHT); // f314IM_BowStamina e := findrec('02E68F'); seev(e, 'Effects\[0]\EFIT\Magnitude', BOW_L_DMG); seev(e, 'Effects\[1]\EFIT\Magnitude', BOW_H_DMG); seev(e, 'Effects\[0]\Conditions\[2]\CTDA\Comparison Value - Float', BOW_LH_BORDER); seev(e, 'Effects\[1]\Conditions\[2]\CTDA\Comparison Value - Float', BOW_LH_BORDER); // f314IM_NPControl e := findrec('000D69'); seev(e, 'Effects\[0]\EFIT\Magnitude', (BOW_L_DMG + BOW_H_DMG) / 2.0); // f314IM_PlayerStaminaRegenControl e := findrec('02E68E'); seev(e, 'VMAD\Scripts\[0]\Properties\[0]\Float', STAMINARATE_A); seev(e, 'VMAD\Scripts\[0]\Properties\[1]\Float', STAMINARATE_B); // fCombatStaminaRegenRateMult e := RecordByFormID(f, strtoint('$0002DD34'), false); seev(e, 'DATA\Float', STAMINARATE_COMBATMULT); // f314IM_Bow_SpeedSpell_H e := findrec('02E6B2'); seev(e, 'Effects\[0]\EFIT\Magnitude', -BOW_H_LOW_SPEED); // f314IM_Bow_SpeedSpell_L e := findrec('02E6B1'); seev(e, 'Effects\[0]\EFIT\Magnitude', -BOW_L_LOW_SPEED); end; end.
unit KM_CommonUtils; interface uses MMSystem; function TimeGet: Cardinal; function GetTimeSince(aTime: Cardinal): Cardinal; implementation function TimeGet: Cardinal; begin Result := TimeGetTime; // Return milliseconds with ~1ms precision end; function GetTimeSince(aTime: Cardinal): Cardinal; begin // TimeGet will loop back to zero after ~49 days since system start Result := (Int64(TimeGet) - Int64(aTime) + Int64(High(Cardinal))) mod Int64(High(Cardinal)); end; end.
unit Classe.Animal; interface type TAnimal = class function Voz : String; virtual; abstract; end; TCachorro = class(TAnimal) function Voz : String; override; end; TGato = class(TAnimal) function Voz : String; override; end; TDinossauro = class (TAnimal) function Voz : String; override; end; TTiranossauro = class sealed (TDinossauro) function Voz : String; override; end; implementation { TCachorro } function TCachorro.Voz: String; begin Result := 'Au Au'; end; { TGato } function TGato.Voz: String; begin Result := 'Miau'; end; { TDinossauro } function TDinossauro.Voz: String; begin Result := 'Gruhhhh'; end; { TTiranossauro } function TTiranossauro.Voz: String; begin Result := 'Gruhhhhhhhhhhhh'; end; end.
unit Usuario; interface type TUsuario = class private FNome: string; FSenha: integer; FLogin: string; procedure SetNome(const Value: string); procedure SetLogin(const Value: string); procedure SetSenha(const Value: integer); public procedure Logar(); property Nome:string read FNome write SetNome; property Login:string read FLogin write SetLogin; property Senha:integer read FSenha write SetSenha; end; implementation uses System.SysUtils; { TUsuario } procedure TUsuario.Logar; begin if (FNome <> 'GABRIEL') or (FSenha <> 123) then begin raise Exception.Create('Erro'); end; end; procedure TUsuario.SetLogin(const Value: string); begin FLogin := Value; end; procedure TUsuario.SetNome(const Value: string); begin FNome := Value; end; procedure TUsuario.SetSenha(const Value: integer); begin FSenha := Value; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Franšois PIETTE Description: ClientWSocket component. It handle the client connection for the application server. Do not confuse TClientWSocket with TAppSrvClient which is the client application side. TClientWSocket is used on the server side to handle client connections, TAppSrvClient is used on the client side to connect to the application server. Both components are talking to each other. Creation: February 17, 1998 Version: 7.00 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list midware@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1998-2010 by Franšois PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software and or any derived or altered versions for any purpose, excluding commercial applications. You can use this software for personal use only. You may distribute it freely untouched. The following restrictions applies: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation and displayed on screen is required. The text must be: "This product is based on MidWare. Freeware source code is available at http://www.overbyte.be." 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution and must be added to the product documentation. Updates: Mar 27, 1998 V1.01 Added a ConnectedSince and LastCommand properties Added a Banner property, must be a single line Apr 10, 1998 V1.01 Removed aSocket from StartConnection. May 18, 1998 V1.03 Implemented command timeout to disconnect an inactive user after a period of inactivity (30 minutes by default). The CheckCommandTimeOut has to be called to make this feature work. It's the server component who do it. Using a TTimer here would consume too much resources. Jun 01, 1998 V1.04 Removed beta status. Changed "legal stuff" to prohibe commercial applications whithout an agreement. Jun 07, 1998 V1.05 Added ReplyHeader, ReplyHeaderLen, ReplyBody, ReplyBodyLen, and SendReply to allow easy encryption and compression implementation. Jul 08, 1998 V1.06 Adapted for Delphi 4 Jul 13, 1998 V1.07 Corrected properties declaration order which prevented BCB to compile this unit, terminating on an internal error ! Functions and procedure must be declared before any property. Added a register procedure to register the component. Aug 17, 1998 V1.08 Added dynamic RcvBuf allocation, OnOverflow event and RcvBuf, RcvSizeInc and RcvSizeMax properties. Dec 12, 1998 V1.09 Added background exception handling Mar 24, 2002 V1.10 Reset RcvBuf to default size when command is executed and receive buffer emptyed. Apr 09, 2002 V1.11 Implemented Datagram types and datagrams from server to client. Aug 13, 2002 V1.12 added ServerObject property. Oct 02, 2002 V1.13 In TClientWSocket.TriggerDataAvailable, checked if FRcvBuf is nul. This occurs when async TServerObject is used and client disconnect prematurely. Aug 28, 2004 V1.14 Use MWDefs.inc Jun 18, 2005 V1.15 TAppServer now use TWSocketServer. That's why TClientWSocket now derive from TWSocketClient instead of TCustomWSocket. Sep 24, 2005 V1.16 Optimized DataAvailable handler to search for EOL only from the point where data has been received. Thanks to Bj°rnar Nielsen <bjornar@sentinel.no> Oct 08, 2005 V1.17 Uwe Schuster <jedivcs@bitcommander.de> implemented dynamic buffer allocation. If you set RcvSizeInc property to 0, then the component will increase the buffer by 25% instead of a fixed value. Oct 23, 2005 V1.18 Updated for Delphi 2006 and BCB 2006 Nov 05, 2005 V1.19 Uwe Schuster <jedivcs@bitcommander.de> updated the timeout detection mechanism to avoid timeout while still transmitting Aug 01, 2008 V7.00 Update for ICS-V7 and Delphi 2009. Warning: Unicode not really supported. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteApSrvCli; interface {$I OverbyteMwDefs.inc} uses Windows, Messages, Classes, SysUtils, OverbyteIcsWinsock, OverbyteIcsWSocket, OverbyteIcsWSockBuf, OverbyteIcsWSocketS; const ApSrvCliVersion = 700; CopyRight : String = ' TClientWSocket (c) 1998-2008 F. Piette V7.00 '; DefaultRcvSize = 65536; // USc 08/10/2005 zero means dynamic buffer increase(+ 1/4) -> see TriggerDataAvailable DefaultRcvSizeInc = 0; DefaultRcvSizeMinInc = 65536; DefaultRcvSizeMax = 0; { Unlimited size } // WM_ABORT_REQUEST = WM_USER + 10; type ClientWSocketException = class(Exception); TDisplayEvent = procedure (Sender : TObject; const Msg : String) of object; TCommandEvent = procedure (Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer) of object; TTimeoutEvent = procedure (Sender : TObject; var CanClose : Boolean) of object; TOverflowEvent = procedure (Sender : TObject; var CanAbort : Boolean) of object; TDatagramAvailableEvent = procedure (Sender : TObject; const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer) of object; {:TClientWSocket is a specialized TWSocket which handle a single client connected to the application server. TAppServer component instanciate a new TClientWSocket for each new client connecting to the server. } TClientWSocket = class(TWSocketClient) protected FRcvBuf : PAnsiChar; FRcvCnt : Integer; FRcvSize : Integer; FRcvSizeInc : Integer; FRcvSizeMax : Integer; FBusy : Boolean; FConnectedSince : TDateTime; FLastCommandRXTime : TDateTime; FLastCommandTime : TDateTime; FLastCommandTXTime : TDateTime; FCommandCount : LongInt; FCommandTimeOut : TDateTime; FBanner : String; FPeerAddr : String; FReplyHeader : PAnsiChar; FReplyHeaderLen : Integer; FReplyBody : PAnsiChar; FReplyBodyLen : Integer; FUserData : LongInt; FAbortRequest : Boolean; FDatagramInBuffer : PAnsiChar; FDatagramInBufferSize : Integer; FDatagramOutBuffer : PAnsiChar; FDatagramOutBufferSize : Integer; FServerObject : TObject; FMsg_WM_ABORT_REQUEST : UINT; FOnDisplay : TDisplayEvent; FOnCommand : TCommandEvent; FOnTimeout : TTimeoutEvent; FOnOverflow : TOverflowEvent; FOnDatagramAvailable : TDatagramAvailableEvent; procedure TriggerSessionConnected(Error : Word); override; function TriggerDataAvailable(Error : Word) : boolean; override; procedure TriggerCommand(CmdBuf : PAnsiChar; CmdLen : Integer); virtual; procedure TriggerTimeout(var CanClose : Boolean); virtual; procedure TriggerOverflow(var CanAbort : Boolean); virtual; procedure TriggerDatagramAvailable(const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer); virtual; function RealSend(var Data : TWSocketData; Len : Integer) : Integer; override; procedure SetRcvSize(newValue : Integer); procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; function MsgHandlersCount: Integer; override; procedure WndProc(var MsgRec: TMessage); override; procedure WMAbortRequest(var msg: TMessage); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {:First method to be invoked on client connection. It initializes internal working and send the banner to the client. } procedure StartConnection; override; {:Procedure used by TAppServer to check for inactivity timeout. } procedure CheckCommandTimeout; virtual; procedure SendReply; virtual; procedure Dup(newHSocket : TSocket); override; function GetPeerAddr: String; override; procedure DatagramIn(const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer; EscChar : AnsiChar); virtual; {:Store the client's IP address. The value is cached. } property PeerAddr : String read GetPeerAddr; {:Gives the time when the client connected. } property ConnectedSince : TDateTime read FConnectedSince; {:Gives the time of the last command request data received. Use for timeout. } property LastCommandRXTime : TDateTime read FLastCommandRXTime; {:Gives the time of the last command received. Use for timeout. } property LastCommandTime : TDateTime read FLastCommandTime; {:Gives the time of the last command response data transmission. Use for timeout. } property LastCommandTXTime : TDateTime read FLastCommandTXTime; {:Number of commands issued by the client. } property CommandCount : LongInt read FCommandCount; {:Timeout value. If the client stay inactive for this period of time, the server will disconnect it. } property CommandTimeOut : TDateTime read FCommandTimeOut write FCommandTimeout; {:The actual buffer used to store incomming data } property RcvBuf : PAnsiChar read FRcvBuf; {:Inherited property giving the number of bytes received. } property RcvdCount; {:ReplyHeader point to the header built by the AppServer based on reply status. } property ReplyHeader : PAnsiChar read FReplyHeader write FReplyHeader; {:ReplyHeaderLen is the length in byte for the header. } property ReplyHeaderLen : Integer read FReplyHeaderLen write FReplyHeaderLen; {:ReplyBody point to the answer to be sent to the client. } property ReplyBody : PAnsiChar read FReplyBody write FReplyBody; {:ReplyBodyLen is the length in bytes for the answer. } property ReplyBodyLen : Integer read FReplyBodyLen write FReplyBodyLen; property LocalPort; property OnDatagramAvailable : TDatagramAvailableEvent read FOnDatagramAvailable write FOnDatagramAvailable; property DatagramInBuffer : PAnsiChar read FDatagramInBuffer write FDatagramInBuffer; property DatagramInBufferSize : Integer read FDatagramInBufferSize write FDatagramInBufferSize; property DatagramOutBuffer : PAnsiChar read FDatagramOutBuffer write FDatagramOutBuffer; property DatagramOutBufferSize : Integer read FDatagramOutBufferSize write FDatagramOutBufferSize; property ServerObject : TObject read FServerObject write FServerObject; published {:The banner to be sent to the client upon connection. } property Banner : String read FBanner write FBanner; {:Size of buffer used to receive commands (requests). } property RcvSize : integer read FRcvSize write SetRcvSize; {:When RcvSize is too small, the buffer will be enlarged by RcvSizeInc bytes automatically until RcvSizeMax is reached } property RcvSizeInc : Integer read FRcvSizeInc write FRcvSizeInc; {:Maximum size allowed for the RcvBuf } property RcvSizeMax : Integer read FRcvSizeMax write FRcvSizeMax; {:Tells if the previous request is still executing. } property Busy : Boolean read FBusy write FBusy; {:UserData is not user by middleware, it is left for the application programmer use. } property UserData : LongInt read FUserData write FUserData; {:Triggered when the component wants to display something on the user interface. } property OnDisplay : TDisplayEvent read FOnDisplay write FOnDisplay; {:Triggered when a client request (command) is received. } property OnCommand : TCommandEvent read FOnCommand write FOnCommand; {:Triggered when the client timedout as is about to be disconnected by TAppServer. } property OnTimeout : TTimeoutEvent read FOnTimeout write FOnTimeout; {:Triggered when the input buffer is overflowed and can't be enlarged } property OnOverflow : TOverflowEvent read FOnOverflow write FOnOverflow; {:Inherited event triggered when the client disconnect. } property OnSessionClosed; {:Inherited event triggered when an exception occurs in the background } property OnBgException; property OnDataSent; {:Inherited property giving the winsock handle. } property HSocket; end; //procedure Register; implementation const DefaultBanner = 'Hello from middleware Server'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* procedure Register; begin RegisterComponents('FPiette', [TClientWSocket]); end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TClientWSocket.Create(AOwner: TComponent); begin inherited Create(AOwner); FBanner := DefaultBanner; FCommandTimeOut := EncodeTime(0, 30, 0, 0); { 30 minutes } FRcvSizeMax := DefaultRcvSizeMax; FRcvSizeInc := DefaultRcvSizeInc; if (DefaultRcvSizeMax <> 0) and (FRcvSizeMax < DefaultRcvSize) then SetRcvSize(DefaultRcvSizeMax) else SetRcvSize(DefaultRcvSize); FDatagramInBufferSize := 2048; FDatagramInBuffer := nil; FDatagramOutBufferSize := 2048; FDatagramOutBuffer := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TClientWSocket.Destroy; begin FRcvCnt := 0; { Cancel received data } SetRcvSize(0); { Free the buffer } if Assigned(FDatagramInBuffer) then begin FreeMem(FDatagramInBuffer, FDatagramInBufferSize); FDatagramInBuffer := nil; end; if Assigned(FDatagramOutBuffer) then begin FreeMem(FDatagramOutBuffer, FDatagramOutBufferSize); FDatagramOutBuffer := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TClientWSocket.MsgHandlersCount : Integer; begin Result := 1 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_ABORT_REQUEST := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.FreeMsgHandlers; begin if Assigned(FWndHandler) then begin FWndHandler.UnregisterMessage(FMsg_WM_ABORT_REQUEST); end; inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.WndProc(var MsgRec: TMessage); begin with MsgRec do begin if Msg = FMsg_WM_ABORT_REQUEST then begin try WMAbortRequest(MsgRec) except on E:Exception do HandleBackGroundException(E); end; end else inherited WndProc(MsgRec); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.WMAbortRequest(var msg: TMessage); begin { Verify that the socket handle is ours handle } if msg.wParam <> HSocket then Exit; FAbortRequest := FALSE; Abort; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TClientWSocket.RealSend(var Data : TWSocketData; Len : Integer) : Integer; begin Result := inherited RealSend(Data, Len); FLastCommandTXTime := Now; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.SetRcvSize(newValue : Integer); begin if FRcvSize < 0 then FRcvSize := 0; if FRcvSize = newValue then Exit; { No change, nothing to do } if (FRcvSizeMax > 0) and (newValue > FRcvSizeMax) then raise ClientWSocketException.Create( 'Can''t expand receive buffer, max size (' + IntToStr(FRcvSizeMax) + ' bytes) has been reached'); if newValue < FRcvCnt then raise ClientWSocketException.Create( 'Can''t reduce buffer size now because data ' + 'will not fit in new size'); FRcvSize := newValue; ReallocMem(FRcvBuf, newValue); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.StartConnection; begin FConnectedSince := Now; FLastCommandRXTime := 0; FLastCommandTime := Now; FLastCommandTXTime := 0; FCommandCount := 0; inherited StartConnection; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TClientWSocket.GetPeerAddr: String; // 20060729 Not needed: already done in the base class ? begin Result := FPeerAddr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.Dup(newHSocket : TSocket); begin inherited Dup(newHSocket); FPeerAddr := inherited GetPeerAddr; // 20060729 Not needed: already done in the base class ? end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.TriggerSessionConnected(Error : Word); begin FAbortRequest := FALSE; FPeerAddr := inherited GetPeerAddr; inherited TriggerSessionConnected(Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.CheckCommandTimeout; var CanClose : Boolean; MostRecentLastCommandTimeStamp: TDateTime; begin if (State <> wsConnected) or (FCommandTimeOut <= 0) then Exit; MostRecentLastCommandTimeStamp := FLastCommandTXTime; if FLastCommandTime > MostRecentLastCommandTimeStamp then MostRecentLastCommandTimeStamp := FLastCommandTime; if FLastCommandRXTime > MostRecentLastCommandTimeStamp then MostRecentLastCommandTimeStamp := FLastCommandRXTime; if Now > (MostRecentLastCommandTimeStamp + FCommandTimeOut) then begin CanClose := TRUE; TriggerTimeout(CanClose); if CanClose then Close; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.TriggerCommand(CmdBuf : PAnsiChar; CmdLen : Integer); begin if Assigned(FOnCommand) then FOnCommand(Self, CmdBuf, CmdLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.DatagramIn( const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer; EscChar : AnsiChar); var I, J : Integer; begin // Allocate memory for the buffer if not already done if not Assigned(FDatagramInBuffer) then begin if DataLen >= FDatagramInBufferSize then FDatagramInBufferSize := DataLen + 2048; GetMem(FDatagramInBuffer, FDatagramInBufferSize); end else if FDatagramInBufferSize < DataLen then begin // Need to enlarge buffer (2KB increment) FDatagramInBufferSize := DataLen + 2048; ReallocMem(FDatagramInBuffer, FDatagramInBufferSize); end; I := 0; J := 0; while I < DataLen do begin if Data[I] <> EscChar then FDatagramInBuffer[J] := Data[I] else begin Inc(I); case Data[I] of 'C': FDatagramInBuffer[J] := #13; 'L': FDatagramInBuffer[J] := #10; 'N': FDatagramInBuffer[J] := #0; else if Data[I] = EscChar then FDatagramInBuffer[J] := EscChar else FDatagramInBuffer[J] := Data[I]; end; end; Inc(I); Inc(J); end; FDatagramInBuffer[J] := #0; // Just easier to debug when nul termintated TriggerDatagramAvailable(DGramType, FDatagramInBuffer, J); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.TriggerDatagramAvailable( const DGramType : AnsiString; Data : PAnsiChar; DataLen : Integer); begin if Assigned(FOnDatagramAvailable) then FOnDatagramAvailable(Self, DGramType, Data, DataLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.TriggerTimeout(var CanClose : Boolean); begin if Assigned(FOnTimeout) then FOnTimeout(Self, CanClose); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.TriggerOverflow(var CanAbort : Boolean); begin if Assigned(FOnOverflow) then FOnOverflow(Self, CanAbort); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TClientWSocket.TriggerDataAvailable(Error : Word) : Boolean; var Len : Integer; I : Integer; CanAbort : Boolean; AllowedInc : Integer; CurrentRcvSizeInc : Integer; begin if FAbortRequest then begin Result := FALSE; Exit; end; Result := TRUE; { We read data } { check space in buffer } if (FRcvSize - FRcvCnt - 1) <= 0 then begin { No space left, enlarge the buffer } try CurrentRcvSizeInc := FRcvSizeInc; if CurrentRcvSizeInc = 0 then begin // USc 08/10/2005 dynamic buffer increase CurrentRcvSizeInc := FRcvSize div 4; if CurrentRcvSizeInc < DefaultRcvSizeMinInc then CurrentRcvSizeInc := DefaultRcvSizeMinInc; end; if FRcvSizeMax > 0 then begin AllowedInc := FRcvSizeMax - FRcvSize; if AllowedInc <= 0 then raise ClientWSocketException.Create(''); if AllowedInc > CurrentRcvSizeInc then SetRcvSize(FRcvSize + CurrentRcvSizeInc) else SetRcvSize(FRcvSize + AllowedInc); end else SetRcvSize(FRcvSize + CurrentRcvSizeInc); except CanAbort := TRUE; TriggerOverflow(CanAbort); if CanAbort then begin FAbortRequest := TRUE; PostMessage(Handle, FMsg_WM_ABORT_REQUEST, HSocket, 0); end; { Buffer cannot be enlarged, cancel actual content } FRcvCnt := 0; Result := FALSE; Exit; end; end; Len := Receive(@FRcvBuf[FRcvCnt], FRcvSize - FRcvCnt - 1); FLastCommandRXTime := Now; if Len <= 0 then Exit; FRcvCnt := FRcvCnt + Len; FRcvBuf[FRcvCnt] := #0; I := FRcvCnt - Len; // 24/09/2005 Optimize eol search while TRUE do begin // I := 0; // 24/09/2005 Optimize eol search while (I < FRcvCnt) and (FRcvBuf[I] <> #10) do Inc(I); if I >= FRcvCnt then Exit; FRcvBuf[I] := #0; FLastCommandTime := Now; Inc(FCommandCount); if (I > 1) and (FRcvBuf[I - 1] = #13) then begin FRcvBuf[I - 1] := #0; TriggerCommand(FRcvBuf, I - 1); if FRcvBuf = nil then // Disconnected ! break; FRcvBuf[I - 1] := #13; end else begin FRcvBuf[0] := #0; // May 19, 2003. Clear #13 TriggerCommand(FRcvBuf, I); end; FRcvBuf[I] := #10; if I >= (FRcvCnt - 1) then begin FRcvCnt := 0; FRcvBuf[0] := #0; SetRcvSize(DefaultRcvSize); // Reset rcv buffer to default size break; end; Move(FRcvBuf[I + 1], FRcvBuf^, FRcvCnt - I); FRcvCnt := FRcvCnt - I - 1; I := 0; end; // 24/09/2005 Optimize eol search end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TClientWSocket.SendReply; begin PutDataInSendBuffer(ReplyHeader, ReplyHeaderLen); PutDataInSendBuffer(ReplyBody, ReplyBodyLen); PutStringInSendBuffer(#13+#10); Send(nil, 0); FBusy := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
//** Вспомогательные функции и процедуры. unit uUtils; interface uses Windows, Graphics, SysUtils, Classes, Types, Math; //** Удержать целую переменную в диапазоне. function Clamp(Value, AMin, AMax: Integer): Integer; //** Является ли строка числом. function IsNumber(S: string): Boolean; //** Ширина графической шкалы (например, здоровье). function BarWidth(CX, MX: Integer): Integer; //** Изменить размер картинки. procedure ScaleBmp(Bitmap: TBitmap; CX, CY: Integer); //** Добавить текст в несколько строк. function AddMultiLineText(aText: string; Canv: TCanvas; aRect: TRect): Integer; //** Принадлежит ли точка плоскости. function PointInRect(X, Y: Integer; RX, RY, RW, RH: Integer): Boolean; //** Принадлежит ли плоскость плоскости. function RectInRect(X, Y, W, H, AX, AY, AW, AH: Integer): Boolean; //** Находитися ли курсор мыши в плоскости. function IsMouseInRect(X1, Y1, X2, Y2: Integer): Boolean; //** Отразить изображение по горизонтали. procedure flip_horizontal(Quelle, Ziel: TBitMap); //** Отразить изображение по вертикали. procedure flip_vertikal(Quelle, Ziel: TBitMap); //** Нахождение последнего вхождения подстроки в строку. function LastPos(SubStr, S: string): Integer; //** Возвращает расширение файла. function FileExt(const FileName: string): string; //** Дистанция в тайлах. function GetDist(x1, y1, x2, y2: Single): Word; //** Случайное целое число из диапазона. function Rand(A, B: Integer): Integer; //** Версия игры. function HoDVersion: string; //** Поменять местами значения. procedure Swap(var A, B: Word); //** Получить символ от нажатой клавиши. function GetCharFromVirtualKey(Key: Word): string; //** Изменить размер изображения. procedure ResizeBitmap(imgo, imgd: TBitmap; nw, nh: Integer); //** Разбить изображение (тайлсет) на фрагменты (тайлы). procedure SplitBMP(var Bmps: array of TBitmap; Path: string; StartIndex: Integer = 0); //** Узнать, попадает ли число в диапазон. function InRange(A, Min, Max: Integer): Boolean; //** Дополнительные клавиши управления. procedure TransKeys(var Key: Word); //** Расстояние между двумя точками. function MaxPointDistance(P1, P2: TPoint): Integer; //** Генератор имен персонажей. function GenName(GenderID: Integer): string; function GetByte(val: integer; place: byte): Byte; function GetWord(val: integer; place: byte): Word; function PostInc(var Value: Integer; Addition: Integer = 1): Integer; var //** Путь к базе игры. Path, //** Путь к последнему изображению. LastImageFileName: string; //** Оконный режим. IsWindowMode: Boolean = False; //** Показывать миникарту. IsShowMinimap: Boolean = True; //** Уровень лога. ShowLogLevel: Byte = 1; //** Главный скриптовый файл. MainScript: string = 'Main.pas'; //** Игрок открыл игровые сцены. IsGame: Boolean = False; //** Игрок открыл меню игры. IsMenu: Boolean = False; //** Доп. сцена справки. IsHelp: Boolean = False; //** Позиция X курсора мыши MouseX: Integer; //** Позиция Y курсора мыши MouseY: Integer; const //** Размер тайла. CellSize = 32; implementation uses uBox, uIni; function Clamp(Value, AMin, AMax: Integer): Integer; begin Result := Value; if Value < AMin then Result := AMin; if Value > AMax then Result := AMax; end; function MaxPointDistance(P1, P2: TPoint): Integer; begin Result := Max(Abs(P1.X - P2.X), Abs(P1.Y - P2.Y)); end; function IsNumber(S: string): Boolean; var I, V: integer; begin Val(S, V, I); IsNumber := (I = 0); end; function BarWidth(CX, MX: Integer): Integer; var i: Integer; begin if (CX = MX) and (CX = 0) then begin Result := 0; Exit; end; if (MX <= 0) then MX := 1; i := (CX * 118) div MX; if i <= 0 then i := 0; if (CX >= MX) then i := 118; Result := i; end; procedure ScaleBmp(Bitmap: Graphics.TBitmap; CX, CY: Integer); var TmpBmp: Graphics.TBitmap; ARect: TRect; begin TmpBmp := Graphics.TBitmap.Create; try TmpBmp.Width := CX; TmpBmp.Height := CY; ARect := Rect(0, 0, CX, CY); TmpBmp.Canvas.StretchDraw(ARect, Bitmap); Bitmap.Assign(TmpBmp); finally TmpBmp.Free; end; end; function AddMultiLineText(aText: string; Canv: TCanvas; aRect: TRect): Integer; var i, c, res: Word; SL: TStringList; s: string; TH: Integer; function AddRow(astr: string): Boolean; begin Canv.TextOut(aRect.Left, res * TH + aRect.Top, astr); end; function Addline(astr, aword: string): Boolean; begin Result := Canv.TextWidth(astr + aword) >= aRect.Right; if Result then begin AddRow(astr); inc(res) end; end; procedure WordDivider; begin SL := TStringList.Create; StringReplace(atext, ' ', ' ', [rfReplaceAll]); // kill all double-space SL.Delimiter := ' '; SL.DelimitedText := aText; // divide all Text into words end; begin WordDivider; Res := 0; s := ''; TH := Canv.TextHeight('1') - 10; c := SL.Count - 1; for i := 0 to c do begin if Addline(s, sl[i]) then // if string fits then inscribe it s := ''; // and Clear it s := s + sl[i] + ' '; // and Add a word if (i = c) and (s <> '') then // if needed Add last string begin AddRow(s); inc(res); end; end; Result := res; FreeAndNil(SL); end; function PointInRect(X, Y: Integer; RX, RY, RW, RH: Integer): Boolean; begin Result := (X > RX) and (X < RX + RW) and (Y > RY) and (Y < RY + RH); end; function RectInRect(X, Y, W, H, AX, AY, AW, AH: Integer): Boolean; begin Result := (X < AW) and (W > AX) and (Y < AH) and (H > AY) or (AX < W) and (AW > X) and (AY < H) and (AH > Y); end; function IsMouseInRect(X1, Y1, X2, Y2: Integer): Boolean; begin Result := (MouseX >= X1) and (MouseX <= X2) and (MouseY >= Y1) and (MouseY <= Y2); end; procedure SplitBMP(var Bmps: array of TBitmap; Path: string; StartIndex: Integer = 0); var B: TBitmap; u, i, j: Integer; begin B := TBitmap.Create; try B.LoadFromFile(Path); U := StartIndex; for j := 0 to (B.Height div CellSize) - 1 do for i := 0 to (B.Width div CellSize) - 1 do begin if not Assigned(Bmps[U]) then Bmps[U] := TBitmap.Create(); with Bmps[U] do begin Width := CellSize; Height := CellSize; PixelFormat := pf24Bit; Canvas.CopyRect(Bounds(0, 0, CellSize, CellSize), B.Canvas, Bounds(i * CellSize, j * CellSize, CellSize, CellSize)); inc(U); end; end; finally B.Free; end; end; function GetCharFromVirtualKey(Key: Word): string; var kbState: TKeyboardState; asciiResult: Integer; begin GetKeyboardState(kbState); SetLength(Result, 2); asciiResult := ToAscii(key, MapVirtualKey(key, 0), kbState, @Result[1], 0); case asciiResult of 0: Result := ''; 1: SetLength(Result, 1); 2: ; else Result := ''; end; end; function LastPos(SubStr, S: string): Integer; var Found, Len, Pos: Integer; begin Pos := Length(S); Len := Length(SubStr); Found := 0; while (Pos > 0) and (Found = 0) do begin if Copy(S, Pos, Len) = SubStr then Found := Pos; Dec(Pos); end; Result := Found; end; function FileExt(const FileName: string): string; begin Result := Copy(FileName, LastPos('.', LowerCase(FileName)), Length(FileName)); end; function GetDist(x1, y1, x2, y2: Single): Word; begin Result := Round(SQRT(SQR(x2 - x1) + SQR(y2 - y1))); end; function Rand(A, B: Integer): Integer; begin Result := Round(Random(B - A + 1) + A); end; procedure Swap(var A, B: Word); var T: Word; begin T := A; A := B; B := T; end; function HoDVersion: string; var szName: array[0..255] of Char; P: Pointer; Value: Pointer; Len: UINT; GetTranslationString:string; FFileName: PChar; FValid:boolean; FSize: DWORD; FHandle: DWORD; FBuffer: PChar; begin try FFileName := StrPCopy(StrAlloc(Length(ParamStr(0)) + 1), ParamStr(0)); FValid := False; FSize := GetFileVersionInfoSize(FFileName, FHandle); if FSize > 0 then try GetMem(FBuffer, FSize); FValid := GetFileVersionInfo(FFileName, FHandle, FSize, FBuffer); except FValid := False; raise; end; Result := ''; if FValid then VerQueryValue(FBuffer, '\VarFileInfo\Translation', p, Len) else p := nil; if P <> nil then GetTranslationString := IntToHex(MakeLong(HiWord(Longint(P^)), LoWord(Longint(P^))), 8); if FValid then begin StrPCopy(szName, '\StringFileInfo\' + GetTranslationString + '\FileVersion'); if VerQueryValue(FBuffer, szName, Value, Len) then Result := StrPas(PChar(Value)); end; finally try if FBuffer <> nil then FreeMem(FBuffer, FSize); except end; try StrDispose(FFileName); except end; end; end; procedure ResizeBitmap(imgo, imgd: TBitmap; nw, nh: Integer); var xini, xfi, yini, yfi, saltx, salty: single; x, y, px, py, tpix: integer; PixelColor: TColor; r, g, b: longint; function MyRound(const X: Double): Integer; begin Result := Trunc(x); if Frac(x) >= 0.5 then if x >= 0 then Result := Result + 1 else Result := Result - 1; // Result := Trunc(X + (-2 * Ord(X < 0) + 1) * 0.5); end; begin // Set target size imgd.Width := nw; imgd.Height := nh; // Calcs width & height of every area of pixels of the source bitmap saltx := imgo.Width / nw; salty := imgo.Height / nh; yfi := 0; for y := 0 to nh - 1 do begin // Set the initial and final Y coordinate of a pixel area yini := yfi; yfi := yini + salty; if yfi >= imgo.Height then yfi := imgo.Height - 1; xfi := 0; for x := 0 to nw - 1 do begin // Set the inital and final X coordinate of a pixel area xini := xfi; xfi := xini + saltx; if xfi >= imgo.Width then xfi := imgo.Width - 1; // This loop calcs del average result color of a pixel area // of the imaginary grid r := 0; g := 0; b := 0; tpix := 0; for py := MyRound(yini) to MyRound(yfi) do begin for px := MyRound(xini) to MyRound(xfi) do begin Inc(tpix); PixelColor := ColorToRGB(imgo.Canvas.Pixels[px, py]); r := r + GetRValue(PixelColor); g := g + GetGValue(PixelColor); b := b + GetBValue(PixelColor); end; end; // Draws the result pixel imgd.Canvas.Pixels[x, y] := rgb(MyRound(r / tpix), MyRound(g / tpix), MyRound(b / tpix) ); end; end; end; procedure flip_horizontal(Quelle, Ziel: TBitMap); begin Ziel.Assign(nil); Ziel.Width := Quelle.Width; Ziel.Height := Quelle.Height; StretchBlt(Ziel.Canvas.Handle, 0, 0, Ziel.Width, Ziel.Height, Quelle.Canvas.Handle, 0, Quelle.Height, Quelle.Width, Quelle.Height, srccopy); end; procedure flip_vertikal(Quelle, Ziel: TBitMap); begin Ziel.Assign(nil); Ziel.Width := Quelle.Width; Ziel.Height := Quelle.Height; StretchBlt(Ziel.Canvas.Handle, 0, 0, Ziel.Width, Ziel.Height, Quelle.Canvas.Handle, Quelle.Width, 0, Quelle.Width, Quelle.Height, srccopy); end; function InRange(A, Min, Max: Integer): Boolean; begin Result := (A >= Min) and (A <= Max) end; procedure TransKeys(var Key: Word); begin if (Key = 100) then Key := 37; if (Key = 104) then Key := 38; if (Key = 102) then Key := 39; if (Key = 98) then Key := 40; end; function GenName(GenderID: Integer): string; const Mx = 3; var S: array [0..Mx] of TStringList; I, F: 0..Mx; begin for I := 0 to Mx do S[I] := TStringList.Create; try S[0].DelimitedText := '"Ab","Ac","Ad","Af","Agr","Ast","As","Al","Adw",' + '"Adr","Ar","B","Br","C","Cr","Ch","Cad","D","Dr","Dw","Ed","Eth",' + '"Et","Er","El","Eow","F","Fr","G","Gr","Gw","Gal","Gl","H","Ha",'+ '"Ib","Jer","K","Ka","Ked","L","Loth","Lar","Leg","M","Mir","N",' + '"Nyd","Ol","Oc","On","P","Pr","R","Rh","S","Sev","T","Tr","Th","V",'+ '"Y","Z","Zor","Zar","W","Wic","Wid"'; S[1].DelimitedText := '"a","ae","au","ao","are","ale","ali","ay","ardo",' + '"e","ei","ea","eri","era","ela","eli","enda","erra","i","ia","ie",' + '"ire","ira","ila","ili","ira","igo","o","oa","oi","oe","ore","u","y"'; S[2].DelimitedText := '"and","b","bwyn","baen","bard","c","ctred",' + '"cred","ch","can","d","dan","don","der","dric","dfrid","dus","f","g",' + '"gord","gan","l","li","lgrin","lin","lith","lath","loth","ld","ldric",' + '"ldan","m","mas","mos","mar","mond","n","nydd","nidd","nnon","nwan",' + '"nyth","nad","nn","nnor","nd","p","r","ron","rd","s","sh","seth",' + '"sean","t","th","thak","tlan","trem","tram","v","vudd","w","wan","win",' + '"wyf","wyn","wyr","wys","wyth"'; S[3].DelimitedText := '"a","ya","ea"'; if (GenderID = 0) then F := Mx else F := Mx - 1; Result := ''; for I := 0 to F do Result := Result + S[I][Random(S[I].Count - 1)]; finally for I := 0 to Mx do S[I].Free; end; end; function GetByte(val: Integer; place: Byte): Byte; begin Result := val shr (place * 8) and $FF; end; function GetWord(val: Integer; place: Byte): Word; begin Result := val shr (place * 16) and $FFFF; end; function PostInc(var Value: Integer; Addition: Integer = 1): Integer; begin Result := Value; Inc(Value, Addition); end; initialization Path := ExtractFilePath(ParamStr(0)); LastImageFileName := ''; finalization end.
unit K609132323; {* [Requestlink:609132323] } // Модуль: "w:\common\components\rtl\Garant\Daily\K609132323.pas" // Стереотип: "TestCase" // Элемент модели: "K609132323" MUID: (5628F8C0018F) // Имя типа: "TK609132323" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK609132323 = class(TRTFtoEVDWriterTest) {* [Requestlink:609132323] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK609132323 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *5628F8C0018Fimpl_uses* //#UC END# *5628F8C0018Fimpl_uses* ; function TK609132323.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK609132323.GetFolder function TK609132323.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '5628F8C0018F'; end;//TK609132323.GetModelElementGUID initialization TestFramework.RegisterTest(TK609132323.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit playlist; {$mode objfpc}{$H+} interface uses Classes, SysUtils, mediacol, debug; { TPlaylistitemClass } type TPlaylistitemClass = class Artist, Title, Path, Album: string; LengthMS, id: longint; Played: boolean; constructor Create; destructor Destroy; procedure update(MedFileObj: TMediaFileClass); end; PPlaylistItemClass = ^TPlaylistitemClass; type //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { TPlaylistClass } TPlaylistClass = class(TList) private function GetItems(index: integer): TPlaylistitemClass; public CurrentTrack: integer; property Items[index: integer]: TPlaylistitemClass read GetItems; constructor Create; destructor Destroy; function TotalPlayTime: int64; function TotalPlayTimeStr: string; procedure move(dest, target: integer); procedure remove(index: integer); procedure Clear; override; function add(filepath: string): integer; //Read track info out of file at path function add(MedFileObj: TMediaFileClass): integer; //Get track info from FileObj procedure insert(index: integer; MedFileObj: TMediaFileClass); function update(index: integer; filepath: string): integer; //update track info out of file at path function update(index: integer; MedFileObj: TMediaFileClass): integer; //update track info from FileObj function RandomIndex: integer; procedure reset_random; function ItemCount: integer; function LoadFromFile(path: string): byte; function SaveToFile(path: string): byte; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ implementation //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { TPlaylistitemClass } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TPlaylistitemClass.Create; begin played := False; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ destructor TPlaylistitemClass.Destroy; begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistitemClass.update(MedFileObj: TMediaFileClass); begin Artist := MedFileObj.Artist; Title := MedFileObj.Title; Album := MedFileObj.Album; ID := MedFileObj.ID; LengthMS := MedFileObj.Playlength; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { TPlaylistClass } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.GetItems(index: integer): TPlaylistitemClass; begin if (index >= 0) and (index < Count) then Result := (TPlaylistitemClass(inherited Items[Index])); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TPlaylistClass.Create; begin inherited Create; end; destructor TPlaylistClass.Destroy; begin Clear; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.TotalPlayTime: int64; // returns total playtime of playlist in milliseconds var i: integer; PPlaylistItem: PPlaylistItemClass; begin Result := 0; for i := 0 to Count - 1 do begin Result := Result + Items[i].LengthMS; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.TotalPlayTimeStr: string; // returns total playtime of playlist in string // format. i.e. '2h 20min' var s1, s2: string; i: int64; begin i := TotalPlayTime; s2 := IntToStr((i div 60) mod 60); s1 := IntToStr((i div 60) div 60); Result := s1 + 'h ' + s2 + 'min'; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistClass.move(dest, target: integer); var current_track_tmp: integer; begin if (dest < ItemCount) and (target < ItemCount) and (dest >= 0) and (target >= 0) then begin inherited Move(dest, target); current_track_tmp := CurrentTrack; if (CurrentTrack > dest) and (CurrentTrack <= target + 1) then Dec(current_track_tmp); if (CurrentTrack < dest) and (CurrentTrack >= target) then Inc(current_track_tmp); if (CurrentTrack = dest) then begin current_track_tmp := target; // if dest<target then current_track_tmp:=target+1 else current_track_tmp:=target; end; CurrentTrack := current_track_tmp; DebugOutLn(Format('dest=%d target=%d curtrack_before=%d', [dest, target, CurrentTrack]), 0); end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistClass.remove(index: integer); begin if (index >= 0) and (index < Count) then begin Items[index].Free; inherited Delete(index); if CurrentTrack > index then Dec(CurrentTrack); end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistClass.Clear; begin while Count > 0 do remove(0); CurrentTrack := -1; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.add(filepath: string): integer; begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.add(MedFileObj: TMediaFileClass): integer; var Playlistitem: TPlaylistitemClass; index: integer; begin index := (inherited Add(TPlaylistitemClass.Create)); Items[index].Path := MedFileObj.path; Items[index].Artist := MedFileObj.Artist; Items[index].Title := MedFileObj.Title; Items[index].Album := MedFileObj.Album; Items[index].ID := MedFileObj.ID; Items[index].LengthMS := MedFileObj.Playlength; Result := index; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistClass.insert(index: integer; MedFileObj: TMediaFileClass); begin inherited insert(index, TPlaylistitemClass.Create); Items[index].Path := MedFileObj.path; Items[index].Artist := MedFileObj.Artist; Items[index].Title := MedFileObj.Title; Items[index].Album := MedFileObj.Album; Items[index].ID := MedFileObj.ID; Items[index].LengthMS := MedFileObj.Playlength; if index < CurrentTrack then Inc(CurrentTrack); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.update(index: integer; filepath: string): integer; begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.update(index: integer; MedFileObj: TMediaFileClass): integer; begin if (index >= 0) and (index < Count) then begin Items[index].update(MedFileObj); end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.RandomIndex: integer; // Returns a random index of playlist entry that has not been played yet. -1 if all has been played. // reset_random resets it var x, i: integer; s: boolean; begin s := False; for i := 0 to Count - 1 do if Items[i].played = False then s := True; randomize; if s then begin i := 0; repeat begin x := random(Count - 1); Inc(i); end; until (Items[x].played = False) or (i > 4096); // i is for timeout to prevent an endless loop if i > 4096 then begin x := -1; repeat Inc(x) until Items[x].played = False; end; Result := x; end else begin Result := -1; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TPlaylistClass.reset_random; var i: integer; begin for i := 0 to Count - 1 do Items[i].played := False; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.ItemCount: integer; begin Result := inherited Count; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.LoadFromFile(path: string): byte; //Load .m3u Playlist var s, tmps, fpath, fartist, ftitle: string; pos1, pos2, i, lengthS: integer; PlaylistItem: TPlaylistItemClass; fileobj: TMediaFileClass; filehandle: Text; begin try system.Assign(Filehandle, path); Reset(filehandle); readln(filehandle, tmps); if pos('#EXTM3U', tmps) <> 0 then begin repeat begin repeat readln(filehandle, tmps) until ((pos('#EXTINF', tmps) <> 0) or EOF(filehandle)); pos1 := pos(':', tmps) + 1; pos2 := pos(',', tmps); s := copy(tmps, pos1, pos2 - pos1); val(s, LengthS); pos1 := pos2 + 1; pos2 := pos(' - ', tmps); fartist := copy(tmps, pos1, pos2 - pos1); pos2 := pos2 + 3; ftitle := copy(tmps, pos2, (length(tmps)) - pos2 + 1); readln(filehandle, fpath); i := (inherited Add(TPlaylistitemClass.Create)); Items[i].Title := ftitle; Items[i].Artist := fartist; Items[i].Path := fpath; Items[i].LengthMS := lengthS * 1000; end; until EOF(filehandle); end else debugoutln(path + ' is not a valid m3u playlist', 4); Close(filehandle); Result := 0; except Result := 1; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TPlaylistClass.SaveToFile(path: string): byte; var i: integer; temps: string; filehandle: Text; begin try system.Assign(Filehandle, path); Rewrite(filehandle); writeln(Filehandle, '#EXTM3U'); for i := 0 to Count - 1 do begin str(Items[i].LengthMS div 1000, temps); writeln(filehandle, '#EXTINF:' + temps + ',' + Items[i].artist + ' - ' + Items[i].title); writeln(filehandle, Items[i].path); end; Close(filehandle); Result := 0; except Result := 1; end; end; end.
unit ssDBGrid; interface uses Windows, SysUtils, Classes, Controls, dxCntner6, dxTL6, dxDBTL6, dxDBCtrl6, dxDBGrid6, Forms, Variants, xLngManager, Messages, dialogs; const WM_OK_NEEDADJUST = WM_USER + 100; type TssDBGridGetTitleEvent = procedure (Sender: TObject; var AText: string; var ImgList: TImageList; var AIndex: Integer) of object; TssDBGridGetGroupNodeAddText = procedure (Sender: TObject; Node: TdxTreeListNode; var AText: string) of object; //---------------------------------------------------------------------- TssDBGridColumn = class(TdxDBGridColumn) public function GetGroupText(const Value: string): string; override; end; //---------------------------------------------------------------------- TssDBGrid = class(TdxDBGrid) private FCurrCol, FCurrHeader: TdxDBTreeListColumn; FCurrNode: TdxTreeListNode; FLangManager: TxLngManager; FOnNeedAdjust: TNotifyEvent; FOnGetOptionsTitle: TssDBGridGetTitleEvent; FAutoHideGroupPanel: Boolean; FOnGetGroupNodeAddText: TssDBGridGetGroupNodeAddText; FAllowGrouping: Boolean; FblockGNS: Boolean; // blocks looping in getNodestring event calling procedure SetLangManager(const Value: TxLngManager); procedure WMOKNeedAdjust(var M: TMessage); message WM_OK_NEEDADJUST; procedure SetAutoHideGroupPanel(const Value: Boolean); protected procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure StartDragHeader(AbsoluteIndex: Integer); override; procedure EndDragHeader(Flag: Boolean); override; procedure ReLoadGroupList; override; function GetNodeString(Node: TdxTreeListNode; Column: Integer): string; override; procedure DoEndDragHeader(P: TPoint; AbsoluteIndex: Integer; var NewPosInfo: TdxHeaderPosInfo; var Accept: Boolean); override; public FImgList: TImagelist; FImgIndex: Integer; procedure ShowColOptions; function GetTitle: string; procedure AutoHideBands; constructor Create(AOwner: TComponent); override; procedure LoadFromRegistry(const ARegPath: string); override; procedure SaveToRegistry(const ARegPath: string); override; procedure Adjust(ACol: TdxDBTreeListColumn; NACols: array of const); published property AllowGrouping: Boolean read FAllowGrouping write FAllowGrouping default False; property AutoHideGroupPanel: Boolean read FAutoHideGroupPanel write SetAutoHideGroupPanel default True; property LangManager: TxLngManager read FLangManager write SetLangManager; property OnNeedAdjust: TNotifyEvent read FOnNeedAdjust write FOnNeedAdjust; property OnGetOptionsTitle: TssDBGridGetTitleEvent read FOnGetOptionsTitle write FOnGetOptionsTitle; property OnGetGroupNodeAddText: TssDBGridGetGroupNodeAddText read FOnGetGroupNodeAddText write FOnGetGroupNodeAddText; end; //---------------------------------------------------------------------- TssDBTreeList = class(TdxDBTreeList) private FCurrCol, FCurrHeader: TdxDBTreeListColumn; FCurrNode: TdxTreeListNode; FLangManager: TxLngManager; FOnNeedAdjust: TNotifyEvent; FOnGetOptionsTitle: TssDBGridGetTitleEvent; procedure SetLangManager(const Value: TxLngManager); procedure WMOKNeedAdjust(var M: TMessage); message WM_OK_NEEDADJUST; protected procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; public FImgList: TImagelist; FImgIndex: Integer; procedure ShowColOptions; function GetTitle: string; published property LangManager: TxLngManager read FLangManager write SetLangManager; property OnNeedAdjust: TNotifyEvent read FOnNeedAdjust write FOnNeedAdjust; property OnGetOptionsTitle: TssDBGridGetTitleEvent read FOnGetOptionsTitle write FOnGetOptionsTitle; end; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses {$IFNDEF PKG} fColOptions, {$ENDIF} ssRegUtils; //============================================================================================== procedure TssDBGrid.Adjust(ACol: TdxDBTreeListColumn; NACols: array of const); var AStyle: Integer; Offset, W, i: integer; function ItemInArr(AItem: Pointer; AArr: array of const): Boolean; var i: Integer; begin Result := False; for i := 0 to Length(AArr) - 1 do if AArr[i].VPointer = AItem then begin Result := True; Exit; end; end; begin AStyle := GetWindowLong(Self.Handle, GWL_STYLE); if AStyle and WS_VSCROLL = WS_VSCROLL then Offset := 19 else Offset := 2; W := Self.Width - Offset; if ACol = nil then begin for i := 0 to Self.VisibleColumnCount - 1 do if not ItemInArr(Pointer(Self.VisibleColumns[i]), NACols) then begin ACol := Self.VisibleColumns[i]; Break; end; end; for i := 0 to Self.VisibleColumnCount - 1 do if Self.VisibleColumns[i] <> ACol then W := W - Self.VisibleColumns[i].Width; ACol.Width := W; end; //============================================================================================== procedure TssDBGrid.AutoHideBands; {var i, j: Integer; FVis: Boolean; } begin {for j := 0 to Bands.Count - 1 do begin FVis := False; for i := 1 to ColumnCount - 1 do if Columns[i].Visible and (Columns[i].BandIndex = j) then FVis := True; Bands.Items[j].Visible := FVis; end; Adjust(nil, []); } end; //============================================================================================== constructor TssDBGrid.Create(AOwner: TComponent); begin inherited; FAutoHideGroupPanel := True; FblockGNS := False; end; //============================================================================================== procedure TssDBGrid.DoEndDragHeader(P: TPoint; AbsoluteIndex: Integer; var NewPosInfo: TdxHeaderPosInfo; var Accept: Boolean); begin inherited; AutoHideBands; end; //============================================================================================== procedure TssDBGrid.EndDragHeader(Flag: Boolean); begin inherited; if FAllowGrouping and FAutoHideGroupPanel and (GroupColumnCount = 0) then ShowGroupPanel := False; end; //============================================================================================== function TssDBGrid.GetNodeString(Node: TdxTreeListNode; Column: Integer): string; var DrawColumn: TdxDBGridColumn; AddText: string; begin Result := ''; if Node.HasChildren then begin DrawColumn := GroupColumns[Node.Level]; // FblockGNS prevents looping if not FblockGNS and Assigned(OnGetGroupNodeAddText) then OnGetGroupNodeAddText(Self, Node, AddText); if not FblockGNS and Assigned(DrawColumn.OnGetText) then begin FblockGNS := True; DrawColumn.OnGetText(DrawColumn, Node, Result); FblockGNS := False; Result := DrawColumn.Caption + ' : ' + Result + ' ' + AddText; end else Result := TssDBGridColumn(DrawColumn).GetGroupText(inherited GetNodeString(Node, DrawColumn.Index)) + ' ' + AddText; end else Result := inherited GetNodeString(Node, Column); end; //============================================================================================== function TssDBGrid.GetTitle: string; begin Result := ''; FImgList := nil; if Assigned(FOnGetOptionsTitle) then FOnGetOptionsTitle(Self, Result, FImgList, FImgIndex); end; //============================================================================================== procedure TssDBGrid.MouseMove(Shift: TShiftState; X, Y: Integer); var FCol, FHeader: TdxDBTreeListColumn; FNode: TdxTreeListNode; begin FHeader := Self.GetHeaderColumnAt(X, Y); FCol := Self.GetColumnAt(X, Y); FNode := Self.GetNodeAt(X, Y); if ((FCol <> nil) and (FNode <> nil)) or (FHeader <> nil) then begin if (FCol <> FCurrCol) or (FNode <> FCurrNode) or (FHeader <> FCurrHeader) then begin Application.CancelHint; if FNode <> nil then begin try if Self.Canvas.TextWidth(VarToStr(FNode.Values[FCol.Index])) > FCol.Width then Self.Hint := VarToStr(FNode.Values[FCol.Index]) else Self.Hint := ''; except end; end else if FHeader <> nil then begin Self.Hint := FHeader.Caption; end; FCurrCol := FCol; FCurrNode := FNode; FCurrHeader := FHeader; end; end else begin Self.Hint := ''; FCurrCol := nil; FCurrNode := nil; Application.CancelHint; end; inherited; end; //============================================================================================== procedure TssDBGrid.ReLoadGroupList; begin inherited; if FAllowGrouping and FAutoHideGroupPanel then ShowGroupPanel := not (GroupColumnCount = 0); end; //============================================================================================== procedure TssDBGrid.LoadFromRegistry(const ARegPath: string); {$IFNDEF PKG} var intTmp: Integer; {$ENDIF} begin inherited; {$IFNDEF PKG} if ReadFromRegInt(ARegPath, 'AutoHideGroupPanel', intTmp) then FAutoHideGroupPanel := (intTmp = 1); {$ENDIF} end; //============================================================================================== procedure TssDBGrid.SaveToRegistry(const ARegPath: string); begin inherited; {$IFNDEF PKG} WriteToRegInt(ARegPath, 'AutoHideGroupPanel', Integer(FAutoHideGroupPanel)); {$ENDIF} end; //============================================================================================== procedure TssDBGrid.SetAutoHideGroupPanel(const Value: Boolean); begin FAutoHideGroupPanel := Value; if Value and (GroupColumnCount > 0) then ShowGroupPanel := True; end; //============================================================================================== procedure TssDBGrid.SetLangManager(const Value: TxLngManager); begin if Value = FLangManager then Exit; FLangManager := Value; try if Assigned(Value) then Value.FreeNotification(Self); except end; end; //============================================================================================== procedure TssDBGrid.ShowColOptions; begin {$IFNDEF PKG} with TfrmColOptions.Create(nil) do try SetCaptions(Self.FLangManager); Grid := Self; ShowModal; finally Free; end; {$ENDIF} end; //============================================================================================== procedure TssDBGrid.StartDragHeader(AbsoluteIndex: Integer); begin if FAllowGrouping and FAutoHideGroupPanel and not ShowGroupPanel then ShowGroupPanel := True; inherited; end; //============================================================================================== procedure TssDBGrid.WMOKNeedAdjust(var M: TMessage); begin if Assigned(FOnNeedAdjust) then FOnNeedAdjust(Self); end; //============================================================================================== //============================================================================================== //============================================================================================== // TssDBTreeList //============================================================================================== //============================================================================================== //============================================================================================== function TssDBTreeList.GetTitle: string; begin Result := ''; FImgList := nil; if Assigned(FOnGetOptionsTitle) then FOnGetOptionsTitle(Self, Result, FImgList, FImgIndex); end; //============================================================================================== procedure TssDBTreeList.MouseMove(Shift: TShiftState; X, Y: Integer); var FCol, FHeader: TdxDBTreeListColumn; FNode: TdxTreeListNode; begin FHeader := Self.GetHeaderColumnAt(X, Y); FCol := Self.GetColumnAt(X, Y); FNode := Self.GetNodeAt(X, Y); if ((FCol <> nil) and (FNode <> nil)) or (FHeader <> nil) then begin if (FCol <> FCurrCol) or (FNode <> FCurrNode) or (FHeader <> FCurrHeader) then begin Application.CancelHint; if FNode <> nil then begin if Self.Canvas.TextWidth(VarToStr(FNode.Values[FCol.Index])) > FCol.Width then Self.Hint := VarToStr(FNode.Values[FCol.Index]) else Self.Hint := ''; end else if FHeader <> nil then Self.Hint := FHeader.Caption; FCurrCol := FCol; FCurrNode := FNode; FCurrHeader := FHeader; end; end else begin Self.Hint := ''; FCurrCol := nil; FCurrNode := nil; Application.CancelHint; end; inherited; end; //============================================================================================== procedure TssDBTreeList.SetLangManager(const Value: TxLngManager); begin if Value = FLangManager then Exit; FLangManager := Value; try if Assigned(Value) then Value.FreeNotification(Self); except end; end; //============================================================================================== procedure TssDBTreeList.ShowColOptions; begin {$IFNDEF PKG} with TfrmColOptions.Create(nil) do try SetCaptions(Self.FLangManager); Grid := Self as TCustomdxDBTreeListControl; ShowModal; finally Free; end; {$ENDIF} end; //============================================================================================== procedure TssDBTreeList.WMOKNeedAdjust(var M: TMessage); begin if Assigned(FOnNeedAdjust) then FOnNeedAdjust(Self); end; //============================================================================================== //============================================================================================== //============================================================================================== // TssDBGridColumn //============================================================================================== //============================================================================================== //============================================================================================== function TssDBGridColumn.GetGroupText(const Value: string): string; begin Result := inherited GetGroupText(Value); end; end.
unit ImageLoaders; // Copyright (c) 1998 Jorge Romero Gomez, Merchise interface uses Classes, Windows, Dibs, ListUtils; type TImageData = class; CImageData = class of TImageData; CImages = class of TImages; TImages = class protected fStream : TStream; fFirstHeaderStreamPos : integer; fWidth : integer; fHeight : integer; fBitCount : integer; fDibHeader : PDib; fImageCount : integer; fImages : TObjectList; function GetImageClass : CImageData; virtual; abstract; function GetImageCount : integer; virtual; abstract; function GetDibHeader : PDib; virtual; abstract; function GetImage( Indx : integer ) : TImageData; virtual; function GetHeaderStreamPos( Indx : integer ) : integer; virtual; function GetImageStreamPos( Indx : integer ) : integer; virtual; public constructor Create; destructor Destroy; override; public // NOTE: It's responsibility of this method to fill the fWidth, fHeight, fBitCount & fImageCount fields procedure LoadFromStream( aStream : TStream ); virtual; procedure LoadImages; virtual; public property Width : integer read fWidth; property Height : integer read fHeight; property BitCount : integer read fBitCount; property DibHeader : PDib read GetDibHeader; property ImageCount : integer read GetImageCount; property Image[ Indx : integer ] : TImageData read GetImage; default; property Stream : TStream read fStream; property HeaderStreamPos[ Indx : integer ] : integer read GetHeaderStreamPos; property ImageStreamPos[ Indx : integer ] : integer read GetImageStreamPos; end; TImageData = class protected fOwner : TImages; fImageStreamPos : integer; fNextHeaderStreamPos : integer; fStream : TStream; fDibHeader : PDib; fWidth : integer; fHeight : integer; fBitCount : integer; fLocalPalette : boolean; function GetDibHeader : PDib; virtual; abstract; function GetOrigin : TPoint; virtual; abstract; function GetDelay : integer; virtual; abstract; function GetTransparent : integer; virtual; abstract; function GetDisposal : integer; virtual; abstract; public property NextHeaderStreamPos : integer read fNextHeaderStreamPos; property ImageStreamPos : integer read fImageStreamPos; public procedure Decode( Dest : pointer; DestWidth : integer ); virtual; abstract; constructor Create( anOwner : TImages ); virtual; public property Owner : TImages read fOwner; property Stream : TStream read fStream; property Origin : TPoint read GetOrigin; property Width : integer read fWidth; property Height : integer read fHeight; property BitCount : integer read fBitCount; property LocalPalette : boolean read fLocalPalette; property DibHeader : PDib read GetDibHeader; property Delay : integer read GetDelay; property Transparent : integer read GetTransparent; property Disposal : integer read GetDisposal; end; // This is the guy we all must call: ============================================= function GetImageLoader( aStream : TStream; Info : pointer ) : TImages; // Registration stuff: type TGetImageLoader = function( aStream : TStream; Info : pointer ) : TImages; // The list of image loaders is sorted by overhead index, so that loaders with less overhead are // checked first. You should also register the most used image loaders with a smaller index // // Ex. If GIF is the main image format of your application you should do something like this: // RegisterLoader( GetGifLoader, ovLoadSignature + 10 ); // RegisterLoader( GetBmpLoader, ovLoadSignature + 20 ); // const // Basic overhead indices ovLoadSignature = $0000; // By simple signature inspection, correct image loader can be determined ovLoadHeader = $1000; // The whole header has to be read ovLoadFirstImage = $5000; // The first image ovLoadFullData = $a000; // All data needs to be loaded procedure RegisterLoader( aGetImageLoader : TGetImageLoader; Overhead : integer ); implementation uses MemUtils; constructor TImages.Create; begin inherited; fImages := TObjectList.Create; fImageCount := -1; end; destructor TImages.Destroy; begin fImages.Free; inherited; end; procedure TImages.LoadFromStream( aStream : TStream ); begin fStream := aStream; end; procedure TImages.LoadImages; // !!! Esto hay que arreglarlo begin fImageCount := 0; while Image[fImageCount] <> nil do ; end; function TImages.GetHeaderStreamPos( Indx : integer ) : integer; begin case Indx of 0 : Result := fFirstHeaderStreamPos; else Result := Image[Indx - 1].NextHeaderStreamPos; end; end; function TImages.GetImageStreamPos( Indx : integer ) : integer; begin Result := Image[Indx].ImageStreamPos; end; function TImages.GetImage( Indx : integer ) : TImageData; var i, j : integer; Image : TImageData; begin assert( ( fImageCount < 0 ) or ( Indx <= fImageCount ), 'Indx out of range in TImages.GetImage!!' ); if ( fImageCount <= Indx ) then fImages.AssertCapacity( Indx + 1 ); if fImages[Indx] = nil then begin i := Indx; while (i >= 0) and not Assigned( fImages[i] ) do dec( i ); for j := i + 1 to Indx do begin fImages.AssertCapacity( fImages.Count + 1 ); Stream.Position := HeaderStreamPos[j]; try Image := GetImageClass.Create( Self ); except Image := nil; end; if (Image <> nil) and (Image.BitCount = 0) // !!! Esto es un parche, el constructor debia fallar... then FreeObject( Image ); fImages[j] := Image; if Image = nil // No more frames? then begin fImageCount := j; //fImages.Capacity := j; end else if ImageCount <= j // A new frame was just loaded? then fImageCount := j + 1; end; end; Result := TImageData( fImages[Indx] ); end; // constructor TImageData.Create( anOwner : TImages ); begin inherited Create; fOwner := anOwner; fStream := anOwner.fStream; end; // var ImgLoaders : TPointerList; function GetImageLoader( aStream : TStream; Info : pointer ) : TImages; var i : integer; StartingPos : integer; begin i := 0; Result := nil; StartingPos := aStream.Position; while ( i < ImgLoaders.Count ) and ( Result = nil ) do begin aStream.Position := StartingPos; Result := TGetImageLoader( ImgLoaders[i] )( aStream, Info ); inc(i); end; end; procedure RegisterLoader( aGetImageLoader : TGetImageLoader; Overhead : integer ); begin ImgLoaders.Add( @aGetImageLoader ); // end; procedure UnregisterAll; begin ImgLoaders.Free; end; initialization ImgLoaders := TPointerList.Create; ImgLoaders.ItemsOwned := false; finalization UnregisterAll; end.
{hint: save all files to location: C:\adt32\eclipse\workspace\AppTFPNoGUIGraphicsBridgeDemo2\jni\ } library controls; //[by Lamw: Lazarus Android Module Wizard: 12/9/2015 22:43:08] {$mode delphi} uses Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls, Laz_And_Controls_Events, unit1; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnScreenStyle Signature: ()I } function pAppOnScreenStyle(PEnv: PJNIEnv; this: JObject): JInt; cdecl; begin Result:=Java_Event_pAppOnScreenStyle(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnCreate Signature: (Landroid/content/Context;Landroid/widget/RelativeLayout;)V } procedure pAppOnCreate(PEnv: PJNIEnv; this: JObject; context: JObject; layout: JObject); cdecl; begin gApp.Init(PEnv, this, context, layout); AndroidModule1.Init(gApp); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnNewIntent Signature: ()V } procedure pAppOnNewIntent(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnNewIntent(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnDestroy Signature: ()V } procedure pAppOnDestroy(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnDestroy(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnPause Signature: ()V } procedure pAppOnPause(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnPause(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnRestart Signature: ()V } procedure pAppOnRestart(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnRestart(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnResume Signature: ()V } procedure pAppOnResume(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnResume(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnStart Signature: ()V } procedure pAppOnStart(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnStart(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnStop Signature: ()V } procedure pAppOnStop(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnStop(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnBackPressed Signature: ()V } procedure pAppOnBackPressed(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnBackPressed(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnRotate Signature: (I)I } function pAppOnRotate(PEnv: PJNIEnv; this: JObject; rotate: JInt): JInt; cdecl; begin Result:=Java_Event_pAppOnRotate(PEnv, this, rotate); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnConfigurationChanged Signature: ()V } procedure pAppOnConfigurationChanged(PEnv: PJNIEnv; this: JObject); cdecl; begin Java_Event_pAppOnConfigurationChanged(PEnv, this); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnActivityResult Signature: (IILandroid/content/Intent;)V } procedure pAppOnActivityResult(PEnv: PJNIEnv; this: JObject; requestCode: JInt; resultCode: JInt; data: JObject); cdecl; begin Java_Event_pAppOnActivityResult(PEnv, this, requestCode, resultCode, data); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnCreateOptionsMenu Signature: (Landroid/view/Menu;)V } procedure pAppOnCreateOptionsMenu(PEnv: PJNIEnv; this: JObject; menu: JObject); cdecl; begin Java_Event_pAppOnCreateOptionsMenu(PEnv, this, menu); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnClickOptionMenuItem Signature: (Landroid/view/MenuItem;ILjava/lang/String;Z)V } procedure pAppOnClickOptionMenuItem(PEnv: PJNIEnv; this: JObject; menuItem: JObject; itemID: JInt; itemCaption: JString; checked: JBoolean); cdecl; begin Java_Event_pAppOnClickOptionMenuItem(PEnv, this, menuItem, itemID, itemCaption, Boolean(checked)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnPrepareOptionsMenu Signature: (Landroid/view/Menu;I)Z } function pAppOnPrepareOptionsMenu(PEnv: PJNIEnv; this: JObject; menu: JObject; menuSize: JInt): JBoolean; cdecl; begin Result:=Java_Event_pAppOnPrepareOptionsMenu(PEnv, this, menu, menuSize); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnPrepareOptionsMenuItem Signature: (Landroid/view/Menu;Landroid/view/MenuItem;I)Z } function pAppOnPrepareOptionsMenuItem(PEnv: PJNIEnv; this: JObject; menu: JObject; menuItem: JObject; itemIndex: JInt): JBoolean; cdecl; begin Result:=Java_Event_pAppOnPrepareOptionsMenuItem(PEnv, this, menu, menuItem, itemIndex); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnCreateContextMenu Signature: (Landroid/view/ContextMenu;)V } procedure pAppOnCreateContextMenu(PEnv: PJNIEnv; this: JObject; menu: JObject); cdecl; begin Java_Event_pAppOnCreateContextMenu(PEnv, this, menu); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnClickContextMenuItem Signature: (Landroid/view/MenuItem;ILjava/lang/String;Z)V } procedure pAppOnClickContextMenuItem(PEnv: PJNIEnv; this: JObject; menuItem: JObject; itemID: JInt; itemCaption: JString; checked: JBoolean); cdecl; begin Java_Event_pAppOnClickContextMenuItem(PEnv, this, menuItem, itemID, itemCaption, Boolean(checked)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClick Signature: (JI)V } procedure pOnClick(PEnv: PJNIEnv; this: JObject; pasobj: JLong; value: JInt); cdecl; begin Java_Event_pOnClick(PEnv, this, TObject(pasobj), value); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnChange Signature: (JLjava/lang/String;I)V } procedure pOnChange(PEnv: PJNIEnv; this: JObject; pasobj: JLong; txt: JString; count: JInt); cdecl; begin Java_Event_pOnChange(PEnv, this, TObject(pasobj), txt, count); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnChanged Signature: (JLjava/lang/String;I)V } procedure pOnChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; txt: JString; count: JInt); cdecl; begin Java_Event_pOnChanged(PEnv, this, TObject(pasobj), txt, count); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnEnter Signature: (J)V } procedure pOnEnter(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnEnter(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnTimer Signature: (J)V } procedure pOnTimer(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnTimer(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnDraw Signature: (JLandroid/graphics/Canvas;)V } procedure pOnDraw(PEnv: PJNIEnv; this: JObject; pasobj: JLong; canvas: JObject ); cdecl; begin Java_Event_pOnDraw(PEnv, this, TObject(pasobj), canvas); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnTouch Signature: (JIIFFFF)V } procedure pOnTouch(PEnv: PJNIEnv; this: JObject; pasobj: JLong; act: JInt; cnt: JInt; x1: JFloat; y1: JFloat; x2: JFloat; y2: JFloat); cdecl; begin Java_Event_pOnTouch(PEnv, this, TObject(pasobj), act, cnt, x1, y1, x2, y2); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnGLRenderer Signature: (JIII)V } procedure pOnGLRenderer(PEnv: PJNIEnv; this: JObject; pasobj: JLong; EventType: JInt; w: JInt; h: JInt); cdecl; begin Java_Event_pOnGLRenderer(PEnv, this, TObject(pasobj), EventType, w, h); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClose Signature: (J)V } procedure pOnClose(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnClose(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnWebViewStatus Signature: (JILjava/lang/String;)I } function pOnWebViewStatus(PEnv: PJNIEnv; this: JObject; pasobj: JLong; EventType: JInt; url: JString): JInt; cdecl; begin Result:=Java_Event_pOnWebViewStatus(PEnv, this, TObject(pasobj), EventType, url); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnAsyncEventDoInBackground Signature: (JI)Z } function pOnAsyncEventDoInBackground(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt): JBoolean; cdecl; begin Result:=Java_Event_pOnAsyncEventDoInBackground(PEnv, this, TObject(pasobj), progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnAsyncEventProgressUpdate Signature: (JI)I } function pOnAsyncEventProgressUpdate(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt): JInt; cdecl; begin Result:=Java_Event_pOnAsyncEventProgressUpdate(PEnv, this, TObject(pasobj), progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnAsyncEventPreExecute Signature: (J)I } function pOnAsyncEventPreExecute(PEnv: PJNIEnv; this: JObject; pasobj: JLong ): JInt; cdecl; begin Result:=Java_Event_pOnAsyncEventPreExecute(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnAsyncEventPostExecute Signature: (JI)V } procedure pOnAsyncEventPostExecute(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt); cdecl; begin Java_Event_pOnAsyncEventPostExecute(PEnv, this, TObject(pasobj), progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClickWidgetItem Signature: (JIZ)V } procedure pOnClickWidgetItem(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; checked: JBoolean); cdecl; begin Java_Event_pOnClickWidgetItem(PEnv, this, TObject(pasobj), position, Boolean( checked)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClickCaptionItem Signature: (JILjava/lang/String;)V } procedure pOnClickCaptionItem(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString); cdecl; begin Java_Event_pOnClickCaptionItem(PEnv, this, TObject(pasobj), position, caption ); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnListViewLongClickCaptionItem Signature: (JILjava/lang/String;)V } procedure pOnListViewLongClickCaptionItem(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString); cdecl; begin Java_Event_pOnListViewLongClickCaptionItem(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnListViewDrawItemCaptionColor Signature: (JILjava/lang/String;)I } function pOnListViewDrawItemCaptionColor(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString): JInt; cdecl; begin Result:=Java_Event_pOnListViewDrawItemCaptionColor(PEnv, this, TObject(pasobj ), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnListViewDrawItemBitmap Signature: (JILjava/lang/String;)Landroid/graphics/Bitmap; } function pOnListViewDrawItemBitmap(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString): JObject; cdecl; begin Result:=Java_Event_pOnListViewDrawItemBitmap(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothEnabled Signature: (J)V } procedure pOnBluetoothEnabled(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnBluetoothEnabled(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothDisabled Signature: (J)V } procedure pOnBluetoothDisabled(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnBluetoothDisabled(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothDeviceFound Signature: (JLjava/lang/String;Ljava/lang/String;)V } procedure pOnBluetoothDeviceFound(PEnv: PJNIEnv; this: JObject; pasobj: JLong; deviceName: JString; deviceAddress: JString); cdecl; begin Java_Event_pOnBluetoothDeviceFound(PEnv, this, TObject(pasobj), deviceName, deviceAddress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothDiscoveryStarted Signature: (J)V } procedure pOnBluetoothDiscoveryStarted(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnBluetoothDiscoveryStarted(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothDiscoveryFinished Signature: (JII)V } procedure pOnBluetoothDiscoveryFinished(PEnv: PJNIEnv; this: JObject; pasobj: JLong; countFoundedDevices: JInt; countPairedDevices: JInt); cdecl; begin Java_Event_pOnBluetoothDiscoveryFinished(PEnv, this, TObject(pasobj), countFoundedDevices, countPairedDevices); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothDeviceBondStateChanged Signature: (JILjava/lang/String;Ljava/lang/String;)V } procedure pOnBluetoothDeviceBondStateChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; state: JInt; deviceName: JString; deviceAddress: JString); cdecl; begin Java_Event_pOnBluetoothDeviceBondStateChanged(PEnv, this, TObject(pasobj), state, deviceName, deviceAddress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothClientSocketConnected Signature: (JLjava/lang/String;Ljava/lang/String;)V } procedure pOnBluetoothClientSocketConnected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; deviceName: JString; deviceAddress: JString); cdecl; begin Java_Event_pOnBluetoothClientSocketConnected(PEnv, this, TObject(pasobj), deviceName, deviceAddress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothClientSocketIncomingData Signature: (J[B[B)V } procedure pOnBluetoothClientSocketIncomingData(PEnv: PJNIEnv; this: JObject; pasobj: JLong; byteArrayContent: JByteArray; byteArrayHeader: JByteArray); cdecl; begin Java_Event_pOnBluetoothClientSocketIncomingData(PEnv, this, TObject(pasobj), byteArrayContent, byteArrayHeader); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothClientSocketDisconnected Signature: (J)V } procedure pOnBluetoothClientSocketDisconnected(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnBluetoothClientSocketDisconnected(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothServerSocketConnected Signature: (JLjava/lang/String;Ljava/lang/String;)Z } function pOnBluetoothServerSocketConnected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; deviceName: JString; deviceAddress: JString): JBoolean; cdecl; begin Result:=Java_Event_pOnBluetoothServerSocketConnected(PEnv, this, TObject( pasobj), deviceName, deviceAddress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothServerSocketIncomingData Signature: (J[B[B)Z } function pOnBluetoothServerSocketIncomingData(PEnv: PJNIEnv; this: JObject; pasobj: JLong; byteArrayContent: JByteArray; byteArrayHeader: JByteArray ): JBoolean; cdecl; begin Result:=Java_Event_pOnBluetoothServerSocketIncomingData(PEnv, this, TObject( pasobj), byteArrayContent, byteArrayHeader); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothServerSocketListen Signature: (JLjava/lang/String;Ljava/lang/String;)V } procedure pOnBluetoothServerSocketListen(PEnv: PJNIEnv; this: JObject; pasobj: JLong; serverName: JString; strUUID: JString); cdecl; begin Java_Event_pOnBluetoothServerSocketListen(PEnv, this, TObject(pasobj), serverName, strUUID); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBluetoothServerSocketAcceptTimeout Signature: (J)V } procedure pOnBluetoothServerSocketAcceptTimeout(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnBluetoothServerSocketAcceptTimeout(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSpinnerItemSeleceted Signature: (JILjava/lang/String;)V } procedure pOnSpinnerItemSeleceted(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString); cdecl; begin Java_Event_pOnSpinnerItemSeleceted(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnLocationChanged Signature: (JDDDLjava/lang/String;)V } procedure pOnLocationChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; latitude: JDouble; longitude: JDouble; altitude: JDouble; address: JString); cdecl; begin Java_Event_pOnLocationChanged(PEnv, this, TObject(pasobj), latitude, longitude, altitude, address); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnLocationStatusChanged Signature: (JILjava/lang/String;Ljava/lang/String;)V } procedure pOnLocationStatusChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; status: JInt; provider: JString; msgStatus: JString); cdecl; begin Java_Event_pOnLocationStatusChanged(PEnv, this, TObject(pasobj), status, provider, msgStatus); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnLocationProviderEnabled Signature: (JLjava/lang/String;)V } procedure pOnLocationProviderEnabled(PEnv: PJNIEnv; this: JObject; pasobj: JLong; provider: JString); cdecl; begin Java_Event_pOnLocationProviderEnabled(PEnv, this, TObject(pasobj), provider); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnLocationProviderDisabled Signature: (JLjava/lang/String;)V } procedure pOnLocationProviderDisabled(PEnv: PJNIEnv; this: JObject; pasobj: JLong; provider: JString); cdecl; begin Java_Event_pOnLocationProviderDisabled(PEnv, this, TObject(pasobj), provider); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnViewClick Signature: (Landroid/view/View;I)V } procedure pAppOnViewClick(PEnv: PJNIEnv; this: JObject; view: JObject; id: JInt ); cdecl; begin Java_Event_pAppOnViewClick(PEnv, this, view, id); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pAppOnListItemClick Signature: (Landroid/widget/AdapterView;Landroid/view/View;II)V } procedure pAppOnListItemClick(PEnv: PJNIEnv; this: JObject; adapter: JObject; view: JObject; position: JInt; id: JInt); cdecl; begin Java_Event_pAppOnListItemClick(PEnv, this, adapter, view, position, id); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnActionBarTabSelected Signature: (JLandroid/view/View;Ljava/lang/String;)V } procedure pOnActionBarTabSelected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; view: JObject; title: JString); cdecl; begin Java_Event_pOnActionBarTabSelected(PEnv, this, TObject(pasobj), view, title); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnActionBarTabUnSelected Signature: (JLandroid/view/View;Ljava/lang/String;)V } procedure pOnActionBarTabUnSelected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; view: JObject; title: JString); cdecl; begin Java_Event_pOnActionBarTabUnSelected(PEnv, this, TObject(pasobj), view, title ); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnCustomDialogShow Signature: (JLandroid/app/Dialog;Ljava/lang/String;)V } procedure pOnCustomDialogShow(PEnv: PJNIEnv; this: JObject; pasobj: JLong; dialog: JObject; title: JString); cdecl; begin Java_Event_pOnCustomDialogShow(PEnv, this, TObject(pasobj), dialog, title); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnCustomDialogBackKeyPressed Signature: (JLjava/lang/String;)V } procedure pOnCustomDialogBackKeyPressed(PEnv: PJNIEnv; this: JObject; pasobj: JLong; title: JString); cdecl; begin Java_Event_pOnCustomDialogBackKeyPressed(PEnv, this, TObject(pasobj), title); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClickToggleButton Signature: (JZ)V } procedure pOnClickToggleButton(PEnv: PJNIEnv; this: JObject; pasobj: JLong; state: JBoolean); cdecl; begin Java_Event_pOnClickToggleButton(PEnv, this, TObject(pasobj), Boolean(state)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnChangeSwitchButton Signature: (JZ)V } procedure pOnChangeSwitchButton(PEnv: PJNIEnv; this: JObject; pasobj: JLong; state: JBoolean); cdecl; begin Java_Event_pOnChangeSwitchButton(PEnv, this, TObject(pasobj), Boolean(state)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnClickGridItem Signature: (JILjava/lang/String;)V } procedure pOnClickGridItem(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString); cdecl; begin Java_Event_pOnClickGridItem(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnLongClickGridItem Signature: (JILjava/lang/String;)V } procedure pOnLongClickGridItem(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString); cdecl; begin Java_Event_pOnLongClickGridItem(PEnv, this, TObject(pasobj), position, caption ); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnGridDrawItemCaptionColor Signature: (JILjava/lang/String;)I } function pOnGridDrawItemCaptionColor(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString): JInt; cdecl; begin Result:=Java_Event_pOnGridDrawItemCaptionColor(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnGridDrawItemBitmap Signature: (JILjava/lang/String;)Landroid/graphics/Bitmap; } function pOnGridDrawItemBitmap(PEnv: PJNIEnv; this: JObject; pasobj: JLong; position: JInt; caption: JString): JObject; cdecl; begin Result:=Java_Event_pOnGridDrawItemBitmap(PEnv, this, TObject(pasobj), position, caption); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnChangedSensor Signature: (JLandroid/hardware/Sensor;I[FJ)V } procedure pOnChangedSensor(PEnv: PJNIEnv; this: JObject; pasobj: JLong; sensor: JObject; sensorType: JInt; values: JFloatArray; timestamp: JLong); cdecl; begin Java_Event_pOnChangedSensor(PEnv, this, TObject(pasobj), sensor, sensorType, values, timestamp); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnListeningSensor Signature: (JLandroid/hardware/Sensor;I)V } procedure pOnListeningSensor(PEnv: PJNIEnv; this: JObject; pasobj: JLong; sensor: JObject; sensorType: JInt); cdecl; begin Java_Event_pOnListeningSensor(PEnv, this, TObject(pasobj), sensor, sensorType ); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnUnregisterListeningSensor Signature: (JILjava/lang/String;)V } procedure pOnUnregisterListeningSensor(PEnv: PJNIEnv; this: JObject; pasobj: JLong; sensorType: JInt; sensorName: JString); cdecl; begin Java_Event_pOnUnregisterListeningSensor(PEnv, this, TObject(pasobj), sensorType, sensorName); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnBroadcastReceiver Signature: (JLandroid/content/Intent;)V } procedure pOnBroadcastReceiver(PEnv: PJNIEnv; this: JObject; pasobj: JLong; intent: JObject); cdecl; begin Java_Event_pOnBroadcastReceiver(PEnv, this, TObject(pasobj), intent); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnTimePicker Signature: (JII)V } procedure pOnTimePicker(PEnv: PJNIEnv; this: JObject; pasobj: JLong; hourOfDay: JInt; minute: JInt); cdecl; begin Java_Event_pOnTimePicker(PEnv, this, TObject(pasobj), hourOfDay, minute); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnDatePicker Signature: (JIII)V } procedure pOnDatePicker(PEnv: PJNIEnv; this: JObject; pasobj: JLong; year: JInt; monthOfYear: JInt; dayOfMonth: JInt); cdecl; begin Java_Event_pOnDatePicker(PEnv, this, TObject(pasobj), year, monthOfYear, dayOfMonth); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnFlingGestureDetected Signature: (JI)V } procedure pOnFlingGestureDetected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; direction: JInt); cdecl; begin Java_Event_pOnFlingGestureDetected(PEnv, this, TObject(pasobj), direction); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnPinchZoomGestureDetected Signature: (JFI)V } procedure pOnPinchZoomGestureDetected(PEnv: PJNIEnv; this: JObject; pasobj: JLong; scaleFactor: JFloat; state: JInt); cdecl; begin Java_Event_pOnPinchZoomGestureDetected(PEnv, this, TObject(pasobj), scaleFactor, state); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnShellCommandExecuted Signature: (JLjava/lang/String;)V } procedure pOnShellCommandExecuted(PEnv: PJNIEnv; this: JObject; pasobj: JLong; cmdResult: JString); cdecl; begin Java_Event_pOnShellCommandExecuted(PEnv, this, TObject(pasobj), cmdResult); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnTCPSocketClientMessageReceived Signature: (J[Ljava/lang/String;)V } procedure pOnTCPSocketClientMessageReceived(PEnv: PJNIEnv; this: JObject; pasobj: JLong; messagesReceived: JStringArray); cdecl; begin Java_Event_pOnTCPSocketClientMessageReceived(PEnv, this, TObject(pasobj), messagesReceived); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnTCPSocketClientConnected Signature: (J)V } procedure pOnTCPSocketClientConnected(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl; begin Java_Event_pOnTCPSocketClientConnected(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnHttpClientContentResult Signature: (JLjava/lang/String;)V } procedure pOnHttpClientContentResult(PEnv: PJNIEnv; this: JObject; pasobj: JLong; content: JString); cdecl; begin Java_Event_pOnHttpClientContentResult(PEnv, this, TObject(pasobj), content); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnHttpClientCodeResult Signature: (JI)V } procedure pOnHttpClientCodeResult(PEnv: PJNIEnv; this: JObject; pasobj: JLong; code: JInt); cdecl; begin Java_Event_pOnHttpClientCodeResult(PEnv, this, TObject(pasobj), code); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewCreated Signature: (JLandroid/view/SurfaceHolder;)V } procedure pOnSurfaceViewCreated(PEnv: PJNIEnv; this: JObject; pasobj: JLong; surfaceHolder: JObject); cdecl; begin Java_Event_pOnSurfaceViewCreated(PEnv, this, TObject(pasobj), surfaceHolder); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewDraw Signature: (JLandroid/graphics/Canvas;)V } procedure pOnSurfaceViewDraw(PEnv: PJNIEnv; this: JObject; pasobj: JLong; canvas: JObject); cdecl; begin Java_Event_pOnSurfaceViewDraw(PEnv, this, TObject(pasobj), canvas); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewChanged Signature: (JII)V } procedure pOnSurfaceViewChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; width: JInt; height: JInt); cdecl; begin Java_Event_pOnSurfaceViewChanged(PEnv, this, TObject(pasobj), width, height); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnMediaPlayerPrepared Signature: (JII)V } procedure pOnMediaPlayerPrepared(PEnv: PJNIEnv; this: JObject; pasobj: JLong; videoWidth: JInt; videoHeigh: JInt); cdecl; begin Java_Event_pOnMediaPlayerPrepared(PEnv, this, TObject(pasobj), videoWidth, videoHeigh); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnMediaPlayerVideoSizeChanged Signature: (JII)V } procedure pOnMediaPlayerVideoSizeChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; videoWidth: JInt; videoHeight: JInt); cdecl; begin Java_Event_pOnMediaPlayerVideoSizeChanged(PEnv, this, TObject(pasobj), videoWidth, videoHeight); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnMediaPlayerCompletion Signature: (J)V } procedure pOnMediaPlayerCompletion(PEnv: PJNIEnv; this: JObject; pasobj: JLong ); cdecl; begin Java_Event_pOnMediaPlayerCompletion(PEnv, this, TObject(pasobj)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnMediaPlayerTimedText Signature: (JLjava/lang/String;)V } procedure pOnMediaPlayerTimedText(PEnv: PJNIEnv; this: JObject; pasobj: JLong; timedText: JString); cdecl; begin Java_Event_pOnMediaPlayerTimedText(PEnv, this, TObject(pasobj), timedText); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewTouch Signature: (JIIFFFF)V } procedure pOnSurfaceViewTouch(PEnv: PJNIEnv; this: JObject; pasobj: JLong; act: JInt; cnt: JInt; x1: JFloat; y1: JFloat; x2: JFloat; y2: JFloat); cdecl; begin Java_Event_pOnSurfaceViewTouch(PEnv, this, TObject(pasobj), act, cnt, x1, y1, x2, y2); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewDrawingInBackground Signature: (JF)Z } function pOnSurfaceViewDrawingInBackground(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JFloat): JBoolean; cdecl; begin Result:=Java_Event_pOnSurfaceViewDrawingInBackground(PEnv, this, TObject( pasobj), progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSurfaceViewDrawingPostExecute Signature: (JF)V } procedure pOnSurfaceViewDrawingPostExecute(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JFloat); cdecl; begin Java_Event_pOnSurfaceViewDrawingPostExecute(PEnv, this, TObject(pasobj), progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnContactManagerContactsExecuted Signature: (JI)V } procedure pOnContactManagerContactsExecuted(PEnv: PJNIEnv; this: JObject; pasobj: JLong; count: JInt); cdecl; begin Java_Event_pOnContactManagerContactsExecuted(PEnv, this, TObject(pasobj), count); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnContactManagerContactsProgress Signature: (JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Bitmap;I)Z } function pOnContactManagerContactsProgress(PEnv: PJNIEnv; this: JObject; pasobj: JLong; contactInfo: JString; contactShortInfo: JString; contactPhotoUriAsString: JString; contactPhoto: JObject; progress: JInt ): JBoolean; cdecl; begin Result:=Java_Event_pOnContactManagerContactsProgress(PEnv, this, TObject( pasobj), contactInfo, contactShortInfo, contactPhotoUriAsString, contactPhoto, progress); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSeekBarProgressChanged Signature: (JIZ)V } procedure pOnSeekBarProgressChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt; fromUser: JBoolean); cdecl; begin Java_Event_pOnSeekBarProgressChanged(PEnv, this, TObject(pasobj), progress, Boolean(fromUser)); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSeekBarStartTrackingTouch Signature: (JI)V } procedure pOnSeekBarStartTrackingTouch(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt); cdecl; begin Java_Event_pOnSeekBarStartTrackingTouch(PEnv, this, TObject(pasobj), progress ); end; { Class: com_example_apptfpnoguigraphicsbridgedemo2_Controls Method: pOnSeekBarStopTrackingTouch Signature: (JI)V } procedure pOnSeekBarStopTrackingTouch(PEnv: PJNIEnv; this: JObject; pasobj: JLong; progress: JInt); cdecl; begin Java_Event_pOnSeekBarStopTrackingTouch(PEnv, this, TObject(pasobj), progress); end; const NativeMethods: array[0..95] of JNINativeMethod = ( (name: 'pAppOnScreenStyle'; signature: '()I'; fnPtr: @pAppOnScreenStyle; ), (name: 'pAppOnCreate'; signature: '(Landroid/content/Context;Landroid/widget/RelativeLayout;)V'; fnPtr: @pAppOnCreate; ), (name: 'pAppOnNewIntent'; signature: '()V'; fnPtr: @pAppOnNewIntent; ), (name: 'pAppOnDestroy'; signature: '()V'; fnPtr: @pAppOnDestroy; ), (name: 'pAppOnPause'; signature: '()V'; fnPtr: @pAppOnPause; ), (name: 'pAppOnRestart'; signature: '()V'; fnPtr: @pAppOnRestart; ), (name: 'pAppOnResume'; signature: '()V'; fnPtr: @pAppOnResume; ), (name: 'pAppOnStart'; signature: '()V'; fnPtr: @pAppOnStart; ), (name: 'pAppOnStop'; signature: '()V'; fnPtr: @pAppOnStop; ), (name: 'pAppOnBackPressed'; signature: '()V'; fnPtr: @pAppOnBackPressed; ), (name: 'pAppOnRotate'; signature: '(I)I'; fnPtr: @pAppOnRotate; ), (name: 'pAppOnConfigurationChanged'; signature: '()V'; fnPtr: @pAppOnConfigurationChanged; ), (name: 'pAppOnActivityResult'; signature: '(IILandroid/content/Intent;)V'; fnPtr: @pAppOnActivityResult; ), (name: 'pAppOnCreateOptionsMenu'; signature: '(Landroid/view/Menu;)V'; fnPtr: @pAppOnCreateOptionsMenu; ), (name: 'pAppOnClickOptionMenuItem'; signature: '(Landroid/view/MenuItem;ILjava/lang/String;Z)V'; fnPtr: @pAppOnClickOptionMenuItem; ), (name: 'pAppOnPrepareOptionsMenu'; signature: '(Landroid/view/Menu;I)Z'; fnPtr: @pAppOnPrepareOptionsMenu; ), (name: 'pAppOnPrepareOptionsMenuItem'; signature: '(Landroid/view/Menu;Landroid/view/MenuItem;I)Z'; fnPtr: @pAppOnPrepareOptionsMenuItem; ), (name: 'pAppOnCreateContextMenu'; signature: '(Landroid/view/ContextMenu;)V'; fnPtr: @pAppOnCreateContextMenu; ), (name: 'pAppOnClickContextMenuItem'; signature: '(Landroid/view/MenuItem;ILjava/lang/String;Z)V'; fnPtr: @pAppOnClickContextMenuItem; ), (name: 'pOnClick'; signature: '(JI)V'; fnPtr: @pOnClick; ), (name: 'pOnChange'; signature: '(JLjava/lang/String;I)V'; fnPtr: @pOnChange; ), (name: 'pOnChanged'; signature: '(JLjava/lang/String;I)V'; fnPtr: @pOnChanged; ), (name: 'pOnEnter'; signature: '(J)V'; fnPtr: @pOnEnter; ), (name: 'pOnTimer'; signature: '(J)V'; fnPtr: @pOnTimer; ), (name: 'pOnDraw'; signature: '(JLandroid/graphics/Canvas;)V'; fnPtr: @pOnDraw; ), (name: 'pOnTouch'; signature: '(JIIFFFF)V'; fnPtr: @pOnTouch; ), (name: 'pOnGLRenderer'; signature: '(JIII)V'; fnPtr: @pOnGLRenderer; ), (name: 'pOnClose'; signature: '(J)V'; fnPtr: @pOnClose; ), (name: 'pOnWebViewStatus'; signature: '(JILjava/lang/String;)I'; fnPtr: @pOnWebViewStatus; ), (name: 'pOnAsyncEventDoInBackground'; signature: '(JI)Z'; fnPtr: @pOnAsyncEventDoInBackground; ), (name: 'pOnAsyncEventProgressUpdate'; signature: '(JI)I'; fnPtr: @pOnAsyncEventProgressUpdate; ), (name: 'pOnAsyncEventPreExecute'; signature: '(J)I'; fnPtr: @pOnAsyncEventPreExecute; ), (name: 'pOnAsyncEventPostExecute'; signature: '(JI)V'; fnPtr: @pOnAsyncEventPostExecute; ), (name: 'pOnClickWidgetItem'; signature: '(JIZ)V'; fnPtr: @pOnClickWidgetItem; ), (name: 'pOnClickCaptionItem'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnClickCaptionItem; ), (name: 'pOnListViewLongClickCaptionItem'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnListViewLongClickCaptionItem; ), (name: 'pOnListViewDrawItemCaptionColor'; signature: '(JILjava/lang/String;)I'; fnPtr: @pOnListViewDrawItemCaptionColor; ), (name: 'pOnListViewDrawItemBitmap'; signature: '(JILjava/lang/String;)Landroid/graphics/Bitmap;'; fnPtr: @pOnListViewDrawItemBitmap; ), (name: 'pOnBluetoothEnabled'; signature: '(J)V'; fnPtr: @pOnBluetoothEnabled; ), (name: 'pOnBluetoothDisabled'; signature: '(J)V'; fnPtr: @pOnBluetoothDisabled; ), (name: 'pOnBluetoothDeviceFound'; signature: '(JLjava/lang/String;Ljava/lang/String;)V'; fnPtr: @pOnBluetoothDeviceFound; ), (name: 'pOnBluetoothDiscoveryStarted'; signature: '(J)V'; fnPtr: @pOnBluetoothDiscoveryStarted; ), (name: 'pOnBluetoothDiscoveryFinished'; signature: '(JII)V'; fnPtr: @pOnBluetoothDiscoveryFinished; ), (name: 'pOnBluetoothDeviceBondStateChanged'; signature: '(JILjava/lang/String;Ljava/lang/String;)V'; fnPtr: @pOnBluetoothDeviceBondStateChanged; ), (name: 'pOnBluetoothClientSocketConnected'; signature: '(JLjava/lang/String;Ljava/lang/String;)V'; fnPtr: @pOnBluetoothClientSocketConnected; ), (name: 'pOnBluetoothClientSocketIncomingData'; signature: '(J[B[B)V'; fnPtr: @pOnBluetoothClientSocketIncomingData; ), (name: 'pOnBluetoothClientSocketDisconnected'; signature: '(J)V'; fnPtr: @pOnBluetoothClientSocketDisconnected; ), (name: 'pOnBluetoothServerSocketConnected'; signature: '(JLjava/lang/String;Ljava/lang/String;)Z'; fnPtr: @pOnBluetoothServerSocketConnected; ), (name: 'pOnBluetoothServerSocketIncomingData'; signature: '(J[B[B)Z'; fnPtr: @pOnBluetoothServerSocketIncomingData; ), (name: 'pOnBluetoothServerSocketListen'; signature: '(JLjava/lang/String;Ljava/lang/String;)V'; fnPtr: @pOnBluetoothServerSocketListen; ), (name: 'pOnBluetoothServerSocketAcceptTimeout'; signature: '(J)V'; fnPtr: @pOnBluetoothServerSocketAcceptTimeout; ), (name: 'pOnSpinnerItemSeleceted'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnSpinnerItemSeleceted; ), (name: 'pOnLocationChanged'; signature: '(JDDDLjava/lang/String;)V'; fnPtr: @pOnLocationChanged; ), (name: 'pOnLocationStatusChanged'; signature: '(JILjava/lang/String;Ljava/lang/String;)V'; fnPtr: @pOnLocationStatusChanged; ), (name: 'pOnLocationProviderEnabled'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnLocationProviderEnabled; ), (name: 'pOnLocationProviderDisabled'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnLocationProviderDisabled; ), (name: 'pAppOnViewClick'; signature: '(Landroid/view/View;I)V'; fnPtr: @pAppOnViewClick; ), (name: 'pAppOnListItemClick'; signature: '(Landroid/widget/AdapterView;Landroid/view/View;II)V'; fnPtr: @pAppOnListItemClick; ), (name: 'pOnActionBarTabSelected'; signature: '(JLandroid/view/View;Ljava/lang/String;)V'; fnPtr: @pOnActionBarTabSelected; ), (name: 'pOnActionBarTabUnSelected'; signature: '(JLandroid/view/View;Ljava/lang/String;)V'; fnPtr: @pOnActionBarTabUnSelected; ), (name: 'pOnCustomDialogShow'; signature: '(JLandroid/app/Dialog;Ljava/lang/String;)V'; fnPtr: @pOnCustomDialogShow; ), (name: 'pOnCustomDialogBackKeyPressed'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnCustomDialogBackKeyPressed; ), (name: 'pOnClickToggleButton'; signature: '(JZ)V'; fnPtr: @pOnClickToggleButton; ), (name: 'pOnChangeSwitchButton'; signature: '(JZ)V'; fnPtr: @pOnChangeSwitchButton; ), (name: 'pOnClickGridItem'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnClickGridItem; ), (name: 'pOnLongClickGridItem'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnLongClickGridItem; ), (name: 'pOnGridDrawItemCaptionColor'; signature: '(JILjava/lang/String;)I'; fnPtr: @pOnGridDrawItemCaptionColor; ), (name: 'pOnGridDrawItemBitmap'; signature: '(JILjava/lang/String;)Landroid/graphics/Bitmap;'; fnPtr: @pOnGridDrawItemBitmap; ), (name: 'pOnChangedSensor'; signature: '(JLandroid/hardware/Sensor;I[FJ)V'; fnPtr: @pOnChangedSensor; ), (name: 'pOnListeningSensor'; signature: '(JLandroid/hardware/Sensor;I)V'; fnPtr: @pOnListeningSensor; ), (name: 'pOnUnregisterListeningSensor'; signature: '(JILjava/lang/String;)V'; fnPtr: @pOnUnregisterListeningSensor; ), (name: 'pOnBroadcastReceiver'; signature: '(JLandroid/content/Intent;)V'; fnPtr: @pOnBroadcastReceiver; ), (name: 'pOnTimePicker'; signature: '(JII)V'; fnPtr: @pOnTimePicker; ), (name: 'pOnDatePicker'; signature: '(JIII)V'; fnPtr: @pOnDatePicker; ), (name: 'pOnFlingGestureDetected'; signature: '(JI)V'; fnPtr: @pOnFlingGestureDetected; ), (name: 'pOnPinchZoomGestureDetected'; signature: '(JFI)V'; fnPtr: @pOnPinchZoomGestureDetected; ), (name: 'pOnShellCommandExecuted'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnShellCommandExecuted; ), (name: 'pOnTCPSocketClientMessageReceived'; signature: '(J[Ljava/lang/String;)V'; fnPtr: @pOnTCPSocketClientMessageReceived; ), (name: 'pOnTCPSocketClientConnected'; signature: '(J)V'; fnPtr: @pOnTCPSocketClientConnected; ), (name: 'pOnHttpClientContentResult'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnHttpClientContentResult; ), (name: 'pOnHttpClientCodeResult'; signature: '(JI)V'; fnPtr: @pOnHttpClientCodeResult; ), (name: 'pOnSurfaceViewCreated'; signature: '(JLandroid/view/SurfaceHolder;)V'; fnPtr: @pOnSurfaceViewCreated; ), (name: 'pOnSurfaceViewDraw'; signature: '(JLandroid/graphics/Canvas;)V'; fnPtr: @pOnSurfaceViewDraw; ), (name: 'pOnSurfaceViewChanged'; signature: '(JII)V'; fnPtr: @pOnSurfaceViewChanged; ), (name: 'pOnMediaPlayerPrepared'; signature: '(JII)V'; fnPtr: @pOnMediaPlayerPrepared; ), (name: 'pOnMediaPlayerVideoSizeChanged'; signature: '(JII)V'; fnPtr: @pOnMediaPlayerVideoSizeChanged; ), (name: 'pOnMediaPlayerCompletion'; signature: '(J)V'; fnPtr: @pOnMediaPlayerCompletion; ), (name: 'pOnMediaPlayerTimedText'; signature: '(JLjava/lang/String;)V'; fnPtr: @pOnMediaPlayerTimedText; ), (name: 'pOnSurfaceViewTouch'; signature: '(JIIFFFF)V'; fnPtr: @pOnSurfaceViewTouch; ), (name: 'pOnSurfaceViewDrawingInBackground'; signature: '(JF)Z'; fnPtr: @pOnSurfaceViewDrawingInBackground; ), (name: 'pOnSurfaceViewDrawingPostExecute'; signature: '(JF)V'; fnPtr: @pOnSurfaceViewDrawingPostExecute; ), (name: 'pOnContactManagerContactsExecuted'; signature: '(JI)V'; fnPtr: @pOnContactManagerContactsExecuted; ), (name: 'pOnContactManagerContactsProgress'; signature: '(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;' +'Landroid/graphics/Bitmap;I)Z'; fnPtr: @pOnContactManagerContactsProgress; ), (name: 'pOnSeekBarProgressChanged'; signature: '(JIZ)V'; fnPtr: @pOnSeekBarProgressChanged; ), (name: 'pOnSeekBarStartTrackingTouch'; signature: '(JI)V'; fnPtr: @pOnSeekBarStartTrackingTouch; ), (name: 'pOnSeekBarStopTrackingTouch'; signature: '(JI)V'; fnPtr: @pOnSeekBarStopTrackingTouch; ) ); function RegisterNativeMethodsArray(PEnv: PJNIEnv; className: PChar; methods: PJNINativeMethod; countMethods: integer): integer; var curClass: jClass; begin Result:= JNI_FALSE; curClass:= (PEnv^).FindClass(PEnv, className); if curClass <> nil then begin if (PEnv^).RegisterNatives(PEnv, curClass, methods, countMethods) > 0 then Result:= JNI_TRUE; end; end; function RegisterNativeMethods(PEnv: PJNIEnv; className: PChar): integer; begin Result:= RegisterNativeMethodsArray(PEnv, className, @NativeMethods[0], Length (NativeMethods)); end; function JNI_OnLoad(VM: PJavaVM; reserved: pointer): JInt; cdecl; var PEnv: PPointer; curEnv: PJNIEnv; begin PEnv:= nil; Result:= JNI_VERSION_1_6; (VM^).GetEnv(VM, @PEnv, Result); if PEnv <> nil then begin curEnv:= PJNIEnv(PEnv); RegisterNativeMethods(curEnv, 'com/example/apptfpnoguigraphicsbridgedemo2' +'/Controls'); end; gVM:= VM; {AndroidWidget.pas} end; procedure JNI_OnUnload(VM: PJavaVM; reserved: pointer); cdecl; var PEnv: PPointer; curEnv: PJNIEnv; begin PEnv:= nil; (VM^).GetEnv(VM, @PEnv, JNI_VERSION_1_6); if PEnv <> nil then begin curEnv:= PJNIEnv(PEnv); (curEnv^).DeleteGlobalRef(curEnv, gjClass); gjClass:= nil; {AndroidWidget.pas} gVM:= nil; {AndroidWidget.pas} end; gApp.Terminate; FreeAndNil(gApp); end; exports JNI_OnLoad name 'JNI_OnLoad', JNI_OnUnload name 'JNI_OnUnload', pAppOnScreenStyle name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnScreenStyle', pAppOnCreate name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnCreate', pAppOnNewIntent name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnNewIntent', pAppOnDestroy name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls' +'_pAppOnDestroy', pAppOnPause name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnPause', pAppOnRestart name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls' +'_pAppOnRestart', pAppOnResume name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnResume', pAppOnStart name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnStart', pAppOnStop name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnStop', pAppOnBackPressed name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnBackPressed', pAppOnRotate name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pAppOnRotate', pAppOnConfigurationChanged name 'Java_com_example_apptfpnoguigraphicsbridgede' +'mo2_Controls_pAppOnConfigurationChanged', pAppOnActivityResult name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnActivityResult', pAppOnCreateOptionsMenu name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pAppOnCreateOptionsMenu', pAppOnClickOptionMenuItem name 'Java_com_example_apptfpnoguigraphicsbridgedem' +'o2_Controls_pAppOnClickOptionMenuItem', pAppOnPrepareOptionsMenu name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pAppOnPrepareOptionsMenu', pAppOnPrepareOptionsMenuItem name 'Java_com_example_apptfpnoguigraphicsbridge' +'demo2_Controls_pAppOnPrepareOptionsMenuItem', pAppOnCreateContextMenu name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pAppOnCreateContextMenu', pAppOnClickContextMenuItem name 'Java_com_example_apptfpnoguigraphicsbridgede' +'mo2_Controls_pAppOnClickContextMenuItem', pOnClick name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnClick', pOnChange name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnChange', pOnChanged name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnChanged', pOnEnter name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnEnter', pOnTimer name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnTimer', pOnDraw name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnDraw', pOnTouch name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnTouch', pOnGLRenderer name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls' +'_pOnGLRenderer', pOnClose name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnClose', pOnWebViewStatus name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnWebViewStatus', pOnAsyncEventDoInBackground name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnAsyncEventDoInBackground', pOnAsyncEventProgressUpdate name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnAsyncEventProgressUpdate', pOnAsyncEventPreExecute name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnAsyncEventPreExecute', pOnAsyncEventPostExecute name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnAsyncEventPostExecute', pOnClickWidgetItem name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnClickWidgetItem', pOnClickCaptionItem name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnClickCaptionItem', pOnListViewLongClickCaptionItem name 'Java_com_example_apptfpnoguigraphicsbri' +'dgedemo2_Controls_pOnListViewLongClickCaptionItem', pOnListViewDrawItemCaptionColor name 'Java_com_example_apptfpnoguigraphicsbri' +'dgedemo2_Controls_pOnListViewDrawItemCaptionColor', pOnListViewDrawItemBitmap name 'Java_com_example_apptfpnoguigraphicsbridgedem' +'o2_Controls_pOnListViewDrawItemBitmap', pOnBluetoothEnabled name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnBluetoothEnabled', pOnBluetoothDisabled name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnBluetoothDisabled', pOnBluetoothDeviceFound name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnBluetoothDeviceFound', pOnBluetoothDiscoveryStarted name 'Java_com_example_apptfpnoguigraphicsbridge' +'demo2_Controls_pOnBluetoothDiscoveryStarted', pOnBluetoothDiscoveryFinished name 'Java_com_example_apptfpnoguigraphicsbridg' +'edemo2_Controls_pOnBluetoothDiscoveryFinished', pOnBluetoothDeviceBondStateChanged name 'Java_com_example_apptfpnoguigraphics' +'bridgedemo2_Controls_pOnBluetoothDeviceBondStateChanged', pOnBluetoothClientSocketConnected name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnBluetoothClientSocketConnected', pOnBluetoothClientSocketIncomingData name 'Java_com_example_' +'apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnBluetoothClientSocketIncomingData', pOnBluetoothClientSocketDisconnected name 'Java_com_example_' +'apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnBluetoothClientSocketDisconnected', pOnBluetoothServerSocketConnected name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnBluetoothServerSocketConnected', pOnBluetoothServerSocketIncomingData name 'Java_com_example_' +'apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnBluetoothServerSocketIncomingData', pOnBluetoothServerSocketListen name 'Java_com_example_apptfpnoguigraphicsbrid' +'gedemo2_Controls_pOnBluetoothServerSocketListen', pOnBluetoothServerSocketAcceptTimeout name 'Java_com_example_' +'apptfpnoguigraphicsbridgedemo2_Controls_' +'pOnBluetoothServerSocketAcceptTimeout', pOnSpinnerItemSeleceted name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnSpinnerItemSeleceted', pOnLocationChanged name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnLocationChanged', pOnLocationStatusChanged name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnLocationStatusChanged', pOnLocationProviderEnabled name 'Java_com_example_apptfpnoguigraphicsbridgede' +'mo2_Controls_pOnLocationProviderEnabled', pOnLocationProviderDisabled name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnLocationProviderDisabled', pAppOnViewClick name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnViewClick', pAppOnListItemClick name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pAppOnListItemClick', pOnActionBarTabSelected name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnActionBarTabSelected', pOnActionBarTabUnSelected name 'Java_com_example_apptfpnoguigraphicsbridgedem' +'o2_Controls_pOnActionBarTabUnSelected', pOnCustomDialogShow name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnCustomDialogShow', pOnCustomDialogBackKeyPressed name 'Java_com_example_apptfpnoguigraphicsbridg' +'edemo2_Controls_pOnCustomDialogBackKeyPressed', pOnClickToggleButton name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnClickToggleButton', pOnChangeSwitchButton name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnChangeSwitchButton', pOnClickGridItem name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnClickGridItem', pOnLongClickGridItem name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnLongClickGridItem', pOnGridDrawItemCaptionColor name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnGridDrawItemCaptionColor', pOnGridDrawItemBitmap name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnGridDrawItemBitmap', pOnChangedSensor name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnChangedSensor', pOnListeningSensor name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnListeningSensor', pOnUnregisterListeningSensor name 'Java_com_example_apptfpnoguigraphicsbridge' +'demo2_Controls_pOnUnregisterListeningSensor', pOnBroadcastReceiver name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnBroadcastReceiver', pOnTimePicker name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls' +'_pOnTimePicker', pOnDatePicker name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_Controls' +'_pOnDatePicker', pOnFlingGestureDetected name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnFlingGestureDetected', pOnPinchZoomGestureDetected name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnPinchZoomGestureDetected', pOnShellCommandExecuted name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnShellCommandExecuted', pOnTCPSocketClientMessageReceived name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnTCPSocketClientMessageReceived', pOnTCPSocketClientConnected name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnTCPSocketClientConnected', pOnHttpClientContentResult name 'Java_com_example_apptfpnoguigraphicsbridgede' +'mo2_Controls_pOnHttpClientContentResult', pOnHttpClientCodeResult name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnHttpClientCodeResult', pOnSurfaceViewCreated name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnSurfaceViewCreated', pOnSurfaceViewDraw name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnSurfaceViewDraw', pOnSurfaceViewChanged name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnSurfaceViewChanged', pOnMediaPlayerPrepared name 'Java_com_example_apptfpnoguigraphicsbridgedemo2' +'_Controls_pOnMediaPlayerPrepared', pOnMediaPlayerVideoSizeChanged name 'Java_com_example_apptfpnoguigraphicsbrid' +'gedemo2_Controls_pOnMediaPlayerVideoSizeChanged', pOnMediaPlayerCompletion name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnMediaPlayerCompletion', pOnMediaPlayerTimedText name 'Java_com_example_apptfpnoguigraphicsbridgedemo' +'2_Controls_pOnMediaPlayerTimedText', pOnSurfaceViewTouch name 'Java_com_example_apptfpnoguigraphicsbridgedemo2_' +'Controls_pOnSurfaceViewTouch', pOnSurfaceViewDrawingInBackground name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnSurfaceViewDrawingInBackground', pOnSurfaceViewDrawingPostExecute name 'Java_com_example_apptfpnoguigraphicsbr' +'idgedemo2_Controls_pOnSurfaceViewDrawingPostExecute', pOnContactManagerContactsExecuted name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnContactManagerContactsExecuted', pOnContactManagerContactsProgress name 'Java_com_example_apptfpnoguigraphicsb' +'ridgedemo2_Controls_pOnContactManagerContactsProgress', pOnSeekBarProgressChanged name 'Java_com_example_apptfpnoguigraphicsbridgedem' +'o2_Controls_pOnSeekBarProgressChanged', pOnSeekBarStartTrackingTouch name 'Java_com_example_apptfpnoguigraphicsbridge' +'demo2_Controls_pOnSeekBarStartTrackingTouch', pOnSeekBarStopTrackingTouch name 'Java_com_example_apptfpnoguigraphicsbridged' +'emo2_Controls_pOnSeekBarStopTrackingTouch'; begin gApp:= jApp.Create(nil); gApp.Title:= 'JNI Android Bridges Library'; gjAppName:= 'com.example.apptfpnoguigraphicsbridgedemo2'; gjClassName:= 'com/example/apptfpnoguigraphicsbridgedemo2/Controls'; gApp.AppName:=gjAppName; gApp.ClassName:=gjClassName; gApp.Initialize; gApp.CreateForm(TAndroidModule1, AndroidModule1); 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 ClpNumberStyles; {$I ..\Include\CryptoLib.inc} interface type {$SCOPEDENUMS ON} TNumberStyles = (None = 0, AllowLeadingWhite = 1, AllowTrailingWhite = 2, AllowLeadingSign = 4, Integer = 4 or 2 or 1, AllowTrailingSign = 8, AllowParentheses = 16, AllowDecimalPoint = 32, AllowThousands = 64, AllowExponent = 128, AllowCurrencySymbol = 256, AllowHexSpecifier = 512); {$SCOPEDENUMS OFF} implementation end.
{*******************************************************} { Проект: Repository } { Модуль: uCheckAccessParameters.pas } { Описание: Параметр события OnCheckAccess службы безопасности} { Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) } { } { Распространяется по лицензии GPLv3 } {*******************************************************} unit uCheckAccessParameters; interface uses uServices; type TCheckAccessParameters = class(TObject) private FAccessGranted: Boolean; FAccessType: TAccessType; FAppUser: IAppUser; FContext: IInterface; FTokenName: string; procedure SetAccessGranted(Value: Boolean); public constructor Create(const ATokenName: string; AAccessType: TAccessType; const AContext: IInterface; const AAppUser: IAppUser); property AccessGranted: Boolean read FAccessGranted write SetAccessGranted; property AccessType: TAccessType read FAccessType; property AppUser: IAppUser read FAppUser; property Context: IInterface read FContext; property TokenName: string read FTokenName; end; implementation { **************************** TCheckAccessParameters **************************** } constructor TCheckAccessParameters.Create(const ATokenName: string; AAccessType: TAccessType; const AContext: IInterface; const AAppUser: IAppUser); begin inherited Create; FTokenName := ATokenName; FAccessType := AAccessType; FContext := AContext; FAppUser := AAppUser; end; procedure TCheckAccessParameters.SetAccessGranted(Value: Boolean); begin if FAccessGranted <> Value then begin FAccessGranted := Value; end; end; end.