text
stringlengths
14
6.51M
unit gl2PSUnit; interface uses OpenGl, classes; Const GL2PS_PS = 0; GL2PS_EPS = 1; GL2PS_TEX = 2; GL2PS_PDF = 3; GL2PS_SVG = 4; GL2PS_PGF = 5; // Sorting algorithms GL2PS_NO_SORT = 1; GL2PS_SIMPLE_SORT = 2; GL2PS_BSP_SORT = 3; // Message levels and error codes GL2PS_SUCCESS = 0; GL2PS_INFO = 1; GL2PS_WARNING = 2; GL2PS_ERROR = 3; GL2PS_NO_FEEDBACK = 4; GL2PS_OVERFLOW = 5; GL2PS_UNINITIALIZED = 6; // Options for gl2psBeginPage GL2PS_NONE = 0; GL2PS_DRAW_BACKGROUND = (1 shl 0); GL2PS_SIMPLE_LINE_OFFSET = (1 shl 1); GL2PS_SILENT = (1 shl 2); GL2PS_BEST_ROOT = (1 shl 3); GL2PS_OCCLUSION_CULL = (1 shl 4); GL2PS_NO_TEXT = (1 shl 5); GL2PS_LANDSCAPE = (1 shl 6); GL2PS_NO_PS3_SHADING = (1 shl 7); GL2PS_NO_PIXMAP = (1 shl 8); GL2PS_USE_CURRENT_VIEWPORT = (1 shl 9); GL2PS_COMPRESS = (1 shl 10); GL2PS_NO_BLENDING = (1 shl 11); GL2PS_TIGHT_BOUNDING_BOX = (1 shl 12); // Arguments for gl2psEnable/gl2psDisable GL2PS_POLYGON_OFFSET_FILL = 1; GL2PS_POLYGON_BOUNDARY = 2; GL2PS_LINE_STIPPLE = 3; GL2PS_BLEND = 4; // Text alignment (o=raster position; default mode is BL): // +---+ +---+ +---+ +---+ +---+ +---+ +-o-+ o---+ +---o // | o | o | | o | | | | | | | | | | | | // +---+ +---+ +---+ +-o-+ o---+ +---o +---+ +---+ +---+ // C CL CR B BL BR T TL TR */ GL2PS_TEXT_C = 1; GL2PS_TEXT_CL = 2; GL2PS_TEXT_CR = 3; GL2PS_TEXT_B = 4; GL2PS_TEXT_BL = 5; GL2PS_TEXT_BR = 6; GL2PS_TEXT_T = 7; GL2PS_TEXT_TL = 8; GL2PS_TEXT_TR = 9; type GL2PSrgba = array[0..3] of GLfloat; GLVWarray = array[0..3] of GLInt; PGL2PSrgba = ^GL2PSrgba; PGLVWarray = ^GLVWArray; procedure gl2psCreateStream(filename: AnsiString); cdecl; external 'gl2ps.dll'; procedure gl2psDestroyStream(); cdecl; external 'gl2ps.dll'; function gl2psBeginPage(title: AnsiString; producer: AnsiString; viewport: PGLVWarray; format,sort,options,colormode,colorsize: GLInt; colormap: PGL2PSrgba; nr, ng, nb, buffersize: GLInt; filename: AnsiString): GLInt; cdecl; external 'gl2ps.dll'; function gl2psEndPage(): GLInt; cdecl; external 'gl2ps.dll'; function gl2psSetOptions(options: GLInt): GLInt; cdecl; external 'gl2ps.dll'; //function gl2psGetOptions(GLint *options): GLInt; stdcall; external 'gl2ps.dll'; function gl2psBeginViewport(viewport: PGLVWarray): GLInt; stdcall; external 'gl2ps.dll'; function gl2psEndViewport(): GLInt; cdecl; external 'gl2ps.dll'; function gl2psText(const str: AnsiString; const fontname: AnsiString; fontsize: GLshort): GLInt; cdecl; external 'gl2ps.dll'; function gl2psTextOpt(const str: AnsiString; const fontname: AnsiString; fontsize: GLshort; align: GLint; angle: GLfloat): GLInt; cdecl; external 'gl2ps.dll'; function gl2psSpecial(format: GLint; const str: AnsiString): GLInt; cdecl; external 'gl2ps.dll'; //function gl2psDrawPixels(width, height: GLsizei; xorig, yorig: GLint; // format, Atype: GLenum; const void *pixels): GLInt; // stdcall; external 'gl2ps.dll'; function gl2psEnable(mode: GLInt): GLInt; cdecl; external 'gl2ps.dll'; function gl2psDisable(mode: GLInt): GLInt; cdecl; external 'gl2ps.dll'; function gl2psPointSize(value: GLFloat): GLInt; cdecl; external 'gl2ps.dll'; function gl2psLineWidth(value: GLFloat): GLInt; cdecl; external 'gl2ps.dll'; function gl2psBlendFunc(sfactor, dfactor: GLenum): GLInt; cdecl; external 'gl2ps.dll'; implementation end.
// // Generated by JavaToPas v1.5 20160510 - 150222 //////////////////////////////////////////////////////////////////////////////// unit android.bluetooth.BluetoothGatt; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.bluetooth.BluetoothDevice, android.bluetooth.BluetoothGattCharacteristic; type JBluetoothGatt = interface; JBluetoothGattClass = interface(JObjectClass) ['{423253E9-269B-4DD5-B3C2-F7674B482379}'] function _GetCONNECTION_PRIORITY_BALANCED : Integer; cdecl; // A: $19 function _GetCONNECTION_PRIORITY_HIGH : Integer; cdecl; // A: $19 function _GetCONNECTION_PRIORITY_LOW_POWER : Integer; cdecl; // A: $19 function _GetGATT_CONNECTION_CONGESTED : Integer; cdecl; // A: $19 function _GetGATT_FAILURE : Integer; cdecl; // A: $19 function _GetGATT_INSUFFICIENT_AUTHENTICATION : Integer; cdecl; // A: $19 function _GetGATT_INSUFFICIENT_ENCRYPTION : Integer; cdecl; // A: $19 function _GetGATT_INVALID_ATTRIBUTE_LENGTH : Integer; cdecl; // A: $19 function _GetGATT_INVALID_OFFSET : Integer; cdecl; // A: $19 function _GetGATT_READ_NOT_PERMITTED : Integer; cdecl; // A: $19 function _GetGATT_REQUEST_NOT_SUPPORTED : Integer; cdecl; // A: $19 function _GetGATT_SUCCESS : Integer; cdecl; // A: $19 function _GetGATT_WRITE_NOT_PERMITTED : Integer; cdecl; // A: $19 function beginReliableWrite : boolean; cdecl; // ()Z A: $1 function connect : boolean; cdecl; // ()Z A: $1 function discoverServices : boolean; cdecl; // ()Z A: $1 function executeReliableWrite : boolean; cdecl; // ()Z A: $1 function getConnectedDevices : JList; cdecl; // ()Ljava/util/List; A: $1 function getConnectionState(device : JBluetoothDevice) : Integer; cdecl; // (Landroid/bluetooth/BluetoothDevice;)I A: $1 function getDevice : JBluetoothDevice; cdecl; // ()Landroid/bluetooth/BluetoothDevice; A: $1 function getDevicesMatchingConnectionStates(states : TJavaArray<Integer>) : JList; cdecl;// ([I)Ljava/util/List; A: $1 function getService(uuid : JUUID) : JBluetoothGattService; cdecl; // (Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService; A: $1 function getServices : JList; cdecl; // ()Ljava/util/List; A: $1 function readCharacteristic(characteristic : JBluetoothGattCharacteristic) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;)Z A: $1 function readDescriptor(descriptor : JBluetoothGattDescriptor) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattDescriptor;)Z A: $1 function readRemoteRssi : boolean; cdecl; // ()Z A: $1 function requestConnectionPriority(connectionPriority : Integer) : boolean; cdecl;// (I)Z A: $1 function requestMtu(mtu : Integer) : boolean; cdecl; // (I)Z A: $1 function setCharacteristicNotification(characteristic : JBluetoothGattCharacteristic; enable : boolean) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z A: $1 function writeCharacteristic(characteristic : JBluetoothGattCharacteristic) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;)Z A: $1 function writeDescriptor(descriptor : JBluetoothGattDescriptor) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattDescriptor;)Z A: $1 procedure abortReliableWrite ; cdecl; overload; // ()V A: $1 procedure abortReliableWrite(mDevice : JBluetoothDevice) ; deprecated; cdecl; overload;// (Landroid/bluetooth/BluetoothDevice;)V A: $1 procedure close ; cdecl; // ()V A: $1 procedure disconnect ; cdecl; // ()V A: $1 property CONNECTION_PRIORITY_BALANCED : Integer read _GetCONNECTION_PRIORITY_BALANCED;// I A: $19 property CONNECTION_PRIORITY_HIGH : Integer read _GetCONNECTION_PRIORITY_HIGH;// I A: $19 property CONNECTION_PRIORITY_LOW_POWER : Integer read _GetCONNECTION_PRIORITY_LOW_POWER;// I A: $19 property GATT_CONNECTION_CONGESTED : Integer read _GetGATT_CONNECTION_CONGESTED;// I A: $19 property GATT_FAILURE : Integer read _GetGATT_FAILURE; // I A: $19 property GATT_INSUFFICIENT_AUTHENTICATION : Integer read _GetGATT_INSUFFICIENT_AUTHENTICATION;// I A: $19 property GATT_INSUFFICIENT_ENCRYPTION : Integer read _GetGATT_INSUFFICIENT_ENCRYPTION;// I A: $19 property GATT_INVALID_ATTRIBUTE_LENGTH : Integer read _GetGATT_INVALID_ATTRIBUTE_LENGTH;// I A: $19 property GATT_INVALID_OFFSET : Integer read _GetGATT_INVALID_OFFSET; // I A: $19 property GATT_READ_NOT_PERMITTED : Integer read _GetGATT_READ_NOT_PERMITTED;// I A: $19 property GATT_REQUEST_NOT_SUPPORTED : Integer read _GetGATT_REQUEST_NOT_SUPPORTED;// I A: $19 property GATT_SUCCESS : Integer read _GetGATT_SUCCESS; // I A: $19 property GATT_WRITE_NOT_PERMITTED : Integer read _GetGATT_WRITE_NOT_PERMITTED;// I A: $19 end; [JavaSignature('android/bluetooth/BluetoothGatt')] JBluetoothGatt = interface(JObject) ['{B670CCCD-EBBA-4CA6-83F6-2BDE5EEE8F25}'] function beginReliableWrite : boolean; cdecl; // ()Z A: $1 function connect : boolean; cdecl; // ()Z A: $1 function discoverServices : boolean; cdecl; // ()Z A: $1 function executeReliableWrite : boolean; cdecl; // ()Z A: $1 function getConnectedDevices : JList; cdecl; // ()Ljava/util/List; A: $1 function getConnectionState(device : JBluetoothDevice) : Integer; cdecl; // (Landroid/bluetooth/BluetoothDevice;)I A: $1 function getDevice : JBluetoothDevice; cdecl; // ()Landroid/bluetooth/BluetoothDevice; A: $1 function getDevicesMatchingConnectionStates(states : TJavaArray<Integer>) : JList; cdecl;// ([I)Ljava/util/List; A: $1 function getService(uuid : JUUID) : JBluetoothGattService; cdecl; // (Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService; A: $1 function getServices : JList; cdecl; // ()Ljava/util/List; A: $1 function readCharacteristic(characteristic : JBluetoothGattCharacteristic) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;)Z A: $1 function readDescriptor(descriptor : JBluetoothGattDescriptor) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattDescriptor;)Z A: $1 function readRemoteRssi : boolean; cdecl; // ()Z A: $1 function requestConnectionPriority(connectionPriority : Integer) : boolean; cdecl;// (I)Z A: $1 function requestMtu(mtu : Integer) : boolean; cdecl; // (I)Z A: $1 function setCharacteristicNotification(characteristic : JBluetoothGattCharacteristic; enable : boolean) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z A: $1 function writeCharacteristic(characteristic : JBluetoothGattCharacteristic) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattCharacteristic;)Z A: $1 function writeDescriptor(descriptor : JBluetoothGattDescriptor) : boolean; cdecl;// (Landroid/bluetooth/BluetoothGattDescriptor;)Z A: $1 procedure abortReliableWrite ; cdecl; overload; // ()V A: $1 procedure abortReliableWrite(mDevice : JBluetoothDevice) ; deprecated; cdecl; overload;// (Landroid/bluetooth/BluetoothDevice;)V A: $1 procedure close ; cdecl; // ()V A: $1 procedure disconnect ; cdecl; // ()V A: $1 end; TJBluetoothGatt = class(TJavaGenericImport<JBluetoothGattClass, JBluetoothGatt>) end; const TJBluetoothGattCONNECTION_PRIORITY_BALANCED = 0; TJBluetoothGattCONNECTION_PRIORITY_HIGH = 1; TJBluetoothGattCONNECTION_PRIORITY_LOW_POWER = 2; TJBluetoothGattGATT_CONNECTION_CONGESTED = 143; TJBluetoothGattGATT_FAILURE = 257; TJBluetoothGattGATT_INSUFFICIENT_AUTHENTICATION = 5; TJBluetoothGattGATT_INSUFFICIENT_ENCRYPTION = 15; TJBluetoothGattGATT_INVALID_ATTRIBUTE_LENGTH = 13; TJBluetoothGattGATT_INVALID_OFFSET = 7; TJBluetoothGattGATT_READ_NOT_PERMITTED = 2; TJBluetoothGattGATT_REQUEST_NOT_SUPPORTED = 6; TJBluetoothGattGATT_SUCCESS = 0; TJBluetoothGattGATT_WRITE_NOT_PERMITTED = 3; implementation end.
program TestUDPNetworking; uses sgNetworking, sgTypes, sgUtils; const LISTEN_PORTB = 49876; LISTEN_PORTA = LISTEN_PORTB + 1; procedure Pause(); begin Write('Press enter to continue.'); ReadLn(); // Delay(1000); end; procedure Main(); var svr: ServerSocket; toSvr: Connection = nil; toClient: Connection = nil; lReceivedMsg : Boolean; msg: Message; begin WriteLn('Listening for UDP connections on port ', LISTEN_PORTB); svr := CreateServer('MyServer', LISTEN_PORTB, UDP); Pause(); WriteLn('Creating connection to send data to server'); toSvr := OpenConnection('toSvr', '127.0.0.1', LISTEN_PORTB, UDP); Pause(); WriteLn('Sending message to server'); SendMessageTo('Hello UDP', toSvr); Pause(); WriteLn('Checking activity'); CheckNetworkActivity(); WriteLn('Server got message: ', HasMessages(svr)); msg := ReadMessage(svr); WriteLn('Message ', MessageData(msg)); Pause(); WriteLn('Sending message to client ', MessageHost(msg), ':', MessagePort(msg)); toClient := OpenConnection('toClient', MessageHost(msg), MessagePort(msg), UDP); CloseMessage(msg); WriteLn('Connection created ', Assigned(toClient)); SendMessageTo('Hello Client', toClient); Delay(100); CheckNetworkActivity(); WriteLn('Client got message ', HasMessages('toSvr')); WriteLn('Message ', ReadMessageData(toSvr)); CloseConnection(toSvr); WriteLn('Closing UDP socket on port ', LISTEN_PORTB); CloseServer(svr); WriteLn('Close all'); CloseAllConnections(); CloseAllServers(); end; begin Main(); end.
{******************************************************************************} { } { Delphi PnHttpSysServer } { } { Copyright (c) 2018 pony,光明(7180001@qq.com) } { } { Homepage: https://github.com/pony5551/PnHttpSysServer } { } {******************************************************************************} unit uPnHttpSys.Comm; interface uses System.SysUtils, Winapi.Windows, uPnHttpSys.Api, SynZip; {$I PnDefs.inc} type {$ifdef UNICODE} /// define the fastest Unicode string type of the compiler SynUnicode = UnicodeString; /// define a raw 8-bit storage string type, used for data buffer management SockString = type RawByteString; {$else} /// define the fastest 16-bit Unicode string type of the compiler SynUnicode = WideString; {$ifdef HASCODEPAGE} // FPC may expect a CP, e.g. to compare two string constants SockString = type RawByteString; {$else} /// define a 8-bit raw storage string type, used for data buffer management SockString = type AnsiString; {$endif} {$endif} /// points to a 8-bit raw storage variable, used for data buffer management PSockString = ^SockString; /// defines a dynamic array of SockString TSockStringDynArray = array of SockString; {$ifdef DELPHI5OROLDER} // not defined in Delphi 5 or older PPointer = ^Pointer; TTextLineBreakStyle = (tlbsLF, tlbsCRLF); UTF8String = AnsiString; UTF8Encode = AnsiString; {$endif} {$ifndef FPC} /// FPC 64-bit compatibility integer type {$ifdef CPU64} PtrInt = NativeInt; PtrUInt = NativeUInt; {$else} PtrInt = integer; PtrUInt = cardinal; {$endif} /// FPC 64-bit compatibility pointer type PPtrInt = ^PtrInt; PPtrUInt = ^PtrUInt; {$endif FPC} const //http头要求16kb大小 RequestBufferLen = 16*1024 + SizeOf(HTTP_REQUEST); /// the running Operating System XPOWEREDOS = {$ifdef MSWINDOWS} 'Windows' {$else} {$ifdef LINUXNOTBSD} 'Linux' {$else} 'Posix' {$endif LINUXNOTBSD} {$endif MSWINDOWS}; XSERVERNAME = 'PnHttpSysServer'; XPOWEREDPROGRAM = XSERVERNAME + ' 1.0.0.0'; XPOWEREDNAME = 'X-Powered-By'; XPOWEREDVALUE = XPOWEREDPROGRAM + ' '; //HTTP Status Code const /// HTTP Status Code for "Success" STATUS_SUCCESS = 200; /// HTTP Status Code for "Created" STATUS_CREATED = 201; /// HTTP Status Code for "Accepted" STATUS_ACCEPTED = 202; /// HTTP Status Code for "No Content" STATUS_NOCONTENT = 204; /// HTTP Status Code for "Partial Content" STATUS_PARTIALCONTENT = 206; /// HTTP Status Code for "Not Modified" STATUS_NOTMODIFIED = 304; /// HTTP Status Code for "Bad Request" STATUS_BADREQUEST = 400; /// HTTP Status Code for "Unauthorized" STATUS_UNAUTHORIZED = 401; /// HTTP Status Code for "Forbidden" STATUS_FORBIDDEN = 403; /// HTTP Status Code for "Not Found" STATUS_NOTFOUND = 404; /// HTTP Status Code for "Not Acceptable" STATUS_NOTACCEPTABLE = 406; /// HTTP Status Code for "Payload Too Large" STATUS_PAYLOADTOOLARGE = 413; /// HTTP Status Code for "Internal Server Error" STATUS_SERVERERROR = 500; /// HTTP Status Code for "Not Implemented" STATUS_NOTIMPLEMENTED = 501; HTTP_RESP_STATICFILE = '!STATICFILE'; HTTP_RESP_NORESPONSE = '!NORESPONSE'; type /// event used to compress or uncompress some data during HTTP protocol // - should always return the protocol name for ACCEPT-ENCODING: header // e.g. 'gzip' or 'deflate' for standard HTTP format, but you can add // your own (like 'synlzo' or 'synlz') // - the data is compressed (if Compress=TRUE) or uncompressed (if // Compress=FALSE) in the Data variable (i.e. it is modified in-place) // - to be used with THttpSocket.RegisterCompress method // - DataRawByteStringtype should be a generic AnsiString/RawByteString, which // should be in practice a SockString or a RawByteString THttpSocketCompress = function(var DataRawByteString; Compress: boolean): AnsiString; /// used to maintain a list of known compression algorithms THttpSocketCompressRec = record /// the compression name, as in ACCEPT-ENCODING: header (gzip,deflate,synlz) Name: SockString; /// the function handling compression and decompression Func: THttpSocketCompress; /// the size in bytes after which compress will take place // - will be 1024 e.g. for 'zip' or 'deflate' // - could be 0 e.g. when encrypting the content, meaning "always compress" CompressMinSize: integer; end; /// list of known compression algorithms THttpSocketCompressRecDynArray = array of THttpSocketCompressRec; /// identify some items in a list of known compression algorithms THttpSocketCompressSet = set of 0..31; /// http.sys API 2.0 logging option flags // - used to alter the default logging behavior // - hlfLocalTimeRollover would force the log file rollovers by local time, // instead of the default GMT time // - hlfUseUTF8Conversion will use UTF-8 instead of default local code page // - only one of hlfLogErrorsOnly and hlfLogSuccessOnly flag could be set // at a time: if neither of them are present, both errors and success will // be logged, otherwise mutually exclusive flags could be set to force only // errors or success logging // - match low-level HTTP_LOGGING_FLAG_* constants as defined in HTTP 2.0 API THttpApiLoggingFlags = set of ( hlfLocalTimeRollover, hlfUseUTF8Conversion, hlfLogErrorsOnly, hlfLogSuccessOnly); /// http.sys API 2.0 fields used for W3C logging // - match low-level HTTP_LOG_FIELD_* constants as defined in HTTP 2.0 API THttpApiLogFields = set of ( hlfDate, hlfTime, hlfClientIP, hlfUserName, hlfSiteName, hlfComputerName, hlfServerIP, hlfMethod, hlfURIStem, hlfURIQuery, hlfStatus, hlfWIN32Status, hlfBytesSent, hlfBytesRecv, hlfTimeTaken, hlfServerPort, hlfUserAgent, hlfCookie, hlfReferer, hlfVersion, hlfHost, hlfSubStatus); { functions } function CompressDeflateEx(var DataRawByteString; Compress: boolean): AnsiString; function RetrieveHeaders(const Request: HTTP_REQUEST; const RemoteIPHeadUp: SockString; out RemoteIP: SockString): SockString; function RetrieveRemoteAddr(const Request: HTTP_REQUEST): SockString; function ComputeContentEncoding(const Compress: THttpSocketCompressRecDynArray; P: PAnsiChar): THttpSocketCompressSet; function RegisterCompressFunc(var Compress: THttpSocketCompressRecDynArray; aFunction: THttpSocketCompress; var aAcceptEncoding: SockString; aCompressMinSize: integer): SockString; function CompressDataAndGetHeaders(Accepted: THttpSocketCompressSet; const Handled: THttpSocketCompressRecDynArray; const OutContentType: SockString; var OutContent: SockString): SockString; procedure GetDomainUserNameFromToken(UserToken: THandle; var result: SockString); function GetCardinal(P: PAnsiChar): cardinal; overload; function GetCardinal(P,PEnd: PAnsiChar): cardinal; overload; function StatusCodeToReason(Code: Cardinal): SockString; function IdemPChar(p, up: pAnsiChar): Boolean; function IdemPCharArray(p: PAnsiChar; const upArray: array of PAnsiChar): integer; function HtmlEncode(const s: SockString): SockString; function GetNextItemUInt64(var P: PAnsiChar): ULONGLONG; procedure AppendI64(value: Int64; var dest: shortstring); procedure AppendChar(chr: AnsiChar; var dest: shortstring); function DateTimeToGMTRFC822(const DateTime: TDateTime): string; function GMTRFC822ToDateTime(const pSour: AnsiString): TDateTime; implementation uses System.Classes, SynWinSock, //Winapi.Winsock2, System.DateUtils; const HTTP_LEVEL = 1; // 6 is standard, but 1 is enough and faster procedure CompressInternal(var Data: SockString; Compress, ZLib: boolean); var tmp: ZipString; DataLen: integer; LStream: TMemoryStream; begin tmp := Data; DataLen := Length(Data); if Compress then begin LStream := TMemoryStream.Create; try CompressStream(pointer(tmp),DataLen,LStream,HTTP_LEVEL,ZLib,0); LStream.Position := 0; SetLength(Data, LStream.Size); LStream.Read(PAnsiChar(Data)^, LStream.Size); finally LStream.Free; end; end else begin LStream := TMemoryStream.Create; try UnCompressStream(pointer(tmp),DataLen,LStream,nil,ZLib,0); LStream.Position := 0; SetLength(Data, LStream.Size); LStream.Read(PAnsiChar(Data)^, LStream.Size); finally LStream.Free; end; end; end; function CompressDeflateEx(var DataRawByteString; Compress: boolean): AnsiString; var Data: SockString absolute DataRawByteString; begin CompressInternal(Data,Compress,false); result := 'deflate'; end; { functions } function GetSinIP(const Sin: TVarSin): AnsiString; var p: PAnsiChar; host: array[0..NI_MAXHOST] of AnsiChar; serv: array[0..NI_MAXSERV] of AnsiChar; hostlen, servlen: integer; r: integer; begin result := ''; if not IsNewApi(Sin.AddressFamily) then begin p := inet_ntoa(Sin.sin_addr); if p <> nil then result := p; end else begin hostlen := NI_MAXHOST; servlen := NI_MAXSERV; r := getnameinfo(@Sin, SizeOfVarSin(Sin), host, hostlen, serv, servlen, NI_NUMERICHOST + NI_NUMERICSERV); if r = 0 then result := host; end; end; procedure IP4Text(const ip4addr; var result: SockString); var b: array[0..3] of byte absolute ip4addr; begin if cardinal(ip4addr)=0 then result := '' else if cardinal(ip4addr)=$0100007f then result := '127.0.0.1' else result := SockString(Format('%d.%d.%d.%d',[b[0],b[1],b[2],b[3]])) end; procedure GetSinIPFromCache(const sin: TVarSin; var result: SockString); begin if sin.sin_family=AF_INET then IP4Text(sin.sin_addr,result) else begin result := GetSinIP(sin); // AF_INET6 may be optimized in a future revision if result='::1' then result := '127.0.0.1'; // IP6 localhost loopback benefits of matching IP4 end; end; const REMOTEIP_HEADERLEN = 10; REMOTEIP_HEADER: string[REMOTEIP_HEADERLEN] = 'RemoteIP: '; KNOWNHEADERS: array[HttpHeaderCacheControl..HttpHeaderUserAgent] of string[19] = ( 'Cache-Control','Connection','Date','Keep-Alive','Pragma','Trailer', 'Transfer-Encoding','Upgrade','Via','Warning','Allow','Content-Length', 'Content-Type','Content-Encoding','Content-Language','Content-Location', 'Content-MD5','Content-Range','Expires','Last-Modified','Accept', 'Accept-Charset','Accept-Encoding','Accept-Language','Authorization', 'Cookie','Expect','From','Host','If-Match','If-Modified-Since', 'If-None-Match','If-Range','If-Unmodified-Since','Max-Forwards', 'Proxy-Authorization','Referer','Range','TE','Translate','User-Agent'); function RetrieveHeaders(const Request: HTTP_REQUEST; const RemoteIPHeadUp: SockString; out RemoteIP: SockString): SockString; var i, L, Lip: integer; H: HTTP_HEADER_ID; P: PHTTP_UNKNOWN_HEADER; D: PAnsiChar; begin assert(low(KNOWNHEADERS)=low(Request.Headers.KnownHeaders)); assert(high(KNOWNHEADERS)=high(Request.Headers.KnownHeaders)); // compute remote IP L := length(RemoteIPHeadUp); if L<>0 then begin P := Request.Headers.pUnknownHeaders; if P<>nil then for i := 1 to Request.Headers.UnknownHeaderCount do if (P^.NameLength=L) and IdemPChar(PUTF8Char(P^.pName),Pointer(RemoteIPHeadUp)) then begin SetString(RemoteIP,p^.pRawValue,p^.RawValueLength); break; end else inc(P); end; if (RemoteIP='') and (Request.Address.pRemoteAddress<>nil) then GetSinIPFromCache(PVarSin(Request.Address.pRemoteAddress)^,RemoteIP); // compute headers length Lip := Length(RemoteIP); if Lip<>0 then L := (REMOTEIP_HEADERLEN+2)+Lip else L := 0; for H := low(KNOWNHEADERS) to high(KNOWNHEADERS) do if Request.Headers.KnownHeaders[h].RawValueLength<>0 then inc(L,Request.Headers.KnownHeaders[h].RawValueLength+ord(KNOWNHEADERS[h][0])+4); P := Request.Headers.pUnknownHeaders; if P<>nil then for i := 1 to Request.Headers.UnknownHeaderCount do begin inc(L,P^.NameLength+P^.RawValueLength+4); // +4 for each ': '+#13#10 inc(P); end; // set headers content SetString(result,nil,L); D := pointer(result); for H := low(KNOWNHEADERS) to high(KNOWNHEADERS) do if Request.Headers.KnownHeaders[h].RawValueLength<>0 then begin move(KNOWNHEADERS[h][1],D^,ord(KNOWNHEADERS[h][0])); inc(D,ord(KNOWNHEADERS[h][0])); PWord(D)^ := ord(':')+ord(' ')shl 8; inc(D,2); move(Request.Headers.KnownHeaders[h].pRawValue^,D^, Request.Headers.KnownHeaders[h].RawValueLength); inc(D,Request.Headers.KnownHeaders[h].RawValueLength); PWord(D)^ := 13+10 shl 8; inc(D,2); end; P := Request.Headers.pUnknownHeaders; if P<>nil then for i := 1 to Request.Headers.UnknownHeaderCount do begin move(P^.pName^,D^,P^.NameLength); inc(D,P^.NameLength); PWord(D)^ := ord(':')+ord(' ')shl 8; inc(D,2); move(P^.pRawValue^,D^,P^.RawValueLength); inc(D,P^.RawValueLength); inc(P); PWord(D)^ := 13+10 shl 8; inc(D,2); end; if Lip<>0 then begin move(REMOTEIP_HEADER[1],D^,REMOTEIP_HEADERLEN); inc(D,REMOTEIP_HEADERLEN); move(pointer(RemoteIP)^,D^,Lip); inc(D,Lip); PWord(D)^ := 13+10 shl 8; {$ifopt C+} inc(D,2); end; assert(D-pointer(result)=L); {$else} end; {$endif} end; function RetrieveRemoteAddr(const Request: HTTP_REQUEST): SockString; begin if (Request.Address.pRemoteAddress<>nil) then GetSinIPFromCache(PVarSin(Request.Address.pRemoteAddress)^, Result) else Result := ''; end; procedure GetDomainUserNameFromToken(UserToken: THandle; var result: SockString); var Buffer: array[0..511] of byte; BufferSize, UserSize, DomainSize: DWORD; UserInfo: PSIDAndAttributes; NameUse: {$ifdef FPC}SID_NAME_USE{$else}Cardinal{$endif}; tmp: SynUnicode; P: PWideChar; begin if not GetTokenInformation(UserToken,TokenUser,@Buffer,SizeOf(Buffer),BufferSize) then exit; UserInfo := @Buffer; UserSize := 0; DomainSize := 0; LookupAccountSidW(nil,UserInfo^.Sid,nil,UserSize,nil,DomainSize,NameUse); if (UserSize=0) or (DomainSize=0) then exit; SetLength(tmp,UserSize+DomainSize-1); P := pointer(tmp); if not LookupAccountSidW(nil,UserInfo^.Sid,P+DomainSize,UserSize,P,DomainSize,NameUse) then exit; P[DomainSize] := '\'; result := {$ifdef UNICODE}UTF8String{$else}UTF8Encode{$endif}(tmp); end; function GetCardinal(P: PAnsiChar): cardinal; overload; var c: cardinal; begin if P=nil then begin result := 0; exit; end; if P^=' ' then repeat inc(P) until P^<>' '; c := byte(P^)-48; if c>9 then result := 0 else begin result := c; inc(P); repeat c := byte(P^)-48; if c>9 then break else result := result*10+c; inc(P); until false; end; end; function GetCardinal(P,PEnd: PAnsiChar): cardinal; overload; var c: cardinal; begin result := 0; if (P=nil) or (P>=PEnd) then exit; if P^=' ' then repeat inc(P); if P=PEnd then exit; until P^<>' '; c := byte(P^)-48; if c>9 then exit; result := c; inc(P); while P<PEnd do begin c := byte(P^)-48; if c>9 then break else result := result*10+c; inc(P); end; end; var ReasonCache: array[1..5,0..8] of SockString; // avoid memory allocation function StatusCodeToReasonInternal(Code: cardinal): SockString; begin case Code of 100: result := 'Continue'; 101: result := 'Switching Protocols'; 200: result := 'OK'; 201: result := 'Created'; 202: result := 'Accepted'; 203: result := 'Non-Authoritative Information'; 204: result := 'No Content'; 205: result := 'Reset Content'; 206: result := 'Partial Content'; 207: result := 'Multi-Status'; 300: result := 'Multiple Choices'; 301: result := 'Moved Permanently'; 302: result := 'Found'; 303: result := 'See Other'; 304: result := 'Not Modified'; 305: result := 'Use Proxy'; 307: result := 'Temporary Redirect'; 308: result := 'Permanent Redirect'; 400: result := 'Bad Request'; 401: result := 'Unauthorized'; 403: result := 'Forbidden'; 404: result := 'Not Found'; 405: result := 'Method Not Allowed'; 406: result := 'Not Acceptable'; 407: result := 'Proxy Authentication Required'; 408: result := 'Request Timeout'; 409: result := 'Conflict'; 410: result := 'Gone'; 411: result := 'Length Required'; 412: result := 'Precondition Failed'; 413: result := 'Payload Too Large'; 414: result := 'URI Too Long'; 415: result := 'Unsupported Media Type'; 416: result := 'Requested Range Not Satisfiable'; 426: result := 'Upgrade Required'; 500: result := 'Internal Server Error'; 501: result := 'Not Implemented'; 502: result := 'Bad Gateway'; 503: result := 'Service Unavailable'; 504: result := 'Gateway Timeout'; 505: result := 'HTTP Version Not Supported'; 511: result := 'Network Authentication Required'; else result := 'Invalid Request'; end; end; function StatusCodeToReason(Code: Cardinal): SockString; var Hi,Lo: cardinal; begin if Code=200 then begin // optimistic approach :) Hi := 2; Lo := 0; end else begin Hi := Code div 100; Lo := Code-Hi*100; if not ((Hi in [1..5]) and (Lo in [0..8])) then begin result := StatusCodeToReasonInternal(Code); exit; end; end; result := ReasonCache[Hi,Lo]; if result<>'' then exit; result := StatusCodeToReasonInternal(Code); ReasonCache[Hi,Lo] := result; end; function IdemPChar(p, up: pAnsiChar): Boolean; // if the beginning of p^ is same as up^ (ignore case - up^ must be already Upper) var c: AnsiChar; begin result := false; if p=nil then exit; if (up<>nil) and (up^<>#0) then repeat c := p^; if up^<>c then if c in ['a'..'z'] then begin dec(c,32); if up^<>c then exit; end else exit; inc(up); inc(p); until up^=#0; result := true; end; function IdemPCharArray(p: PAnsiChar; const upArray: array of PAnsiChar): integer; var w: word; begin if p<>nil then begin w := ord(p[0])+ord(p[1])shl 8; if p[0] in ['a'..'z'] then dec(w,32); if p[1] in ['a'..'z'] then dec(w,32 shl 8); for result := 0 to high(upArray) do if (PWord(upArray[result])^=w) and IdemPChar(p+2,upArray[result]+2) then exit; end; result := -1; end; /// decode 'CONTENT-ENCODING: ' parameter from registered compression list function ComputeContentEncoding(const Compress: THttpSocketCompressRecDynArray; P: PAnsiChar): THttpSocketCompressSet; var i: integer; aName: SockString; Beg: PAnsiChar; begin integer(result) := 0; if P<>nil then repeat while P^ in [' ',','] do inc(P); Beg := P; // 'gzip;q=1.0, deflate' -> aName='gzip' then 'deflate' while not (P^ in [';',',',#0]) do inc(P); SetString(aName,Beg,P-Beg); for i := 0 to high(Compress) do if aName=Compress[i].Name then include(result,i); while not (P^ in [',',#0]) do inc(P); until P^=#0; end; function RegisterCompressFunc(var Compress: THttpSocketCompressRecDynArray; aFunction: THttpSocketCompress; var aAcceptEncoding: SockString; aCompressMinSize: integer): SockString; var i, n: integer; dummy: SockString; aName: SockString; begin result := ''; if @aFunction=nil then exit; n := length(Compress); aName := aFunction(dummy,true); for i := 0 to n-1 do with Compress[i] do if Name=aName then begin // already set if @Func=@aFunction then // update min. compress size value CompressMinSize := aCompressMinSize; exit; end; if n=sizeof(integer)*8 then exit; // fCompressHeader is 0..31 (casted as integer) SetLength(Compress,n+1); with Compress[n] do begin Name := aName; @Func := @aFunction; CompressMinSize := aCompressMinSize; end; if aAcceptEncoding='' then aAcceptEncoding := 'Accept-Encoding: '+aName else aAcceptEncoding := aAcceptEncoding+','+aName; result := aName; end; function CompressDataAndGetHeaders(Accepted: THttpSocketCompressSet; const Handled: THttpSocketCompressRecDynArray; const OutContentType: SockString; var OutContent: SockString): SockString; var i, OutContentLen: integer; compressible: boolean; OutContentTypeP: PAnsiChar absolute OutContentType; begin if (integer(Accepted)<>0) and (OutContentType<>'') and (Handled<>nil) then begin OutContentLen := Length(OutContent); case IdemPCharArray(OutContentTypeP,['TEXT/','IMAGE/','APPLICATION/']) of 0: compressible := true; 1: compressible := IdemPCharArray(OutContentTypeP+6,['SVG','X-ICO'])>=0; 2: compressible := IdemPCharArray(OutContentTypeP+12,['JSON','XML','JAVASCRIPT'])>=0; else compressible := false; end; for i := 0 to high(Handled) do if i in Accepted then with Handled[i] do if (CompressMinSize=0) or // 0 here means "always" (e.g. for encryption) (compressible and (OutContentLen>=CompressMinSize)) then begin // compression of the OutContent + update header result := Func(OutContent,true); exit; // first in fCompress[] is prefered end; end; result := ''; end; function HtmlEncode(const s: SockString): SockString; var i: integer; begin // not very fast, but working result := ''; for i := 1 to length(s) do case s[i] of '<': result := result+'&lt;'; '>': result := result+'&gt;'; '&': result := result+'&amp;'; '"': result := result+'&quot;'; else result := result+s[i]; end; end; function GetNextItemUInt64(var P: PAnsiChar): ULONGLONG; var c: PtrUInt; begin result := 0; if P<>nil then repeat c := byte(P^)-48; if c>9 then break else result := result*10+ULONGLONG(c); inc(P); until false; end; // P^ will point to the first non digit char procedure AppendI64(value: Int64; var dest: shortstring); var temp: shortstring; begin str(value,temp); dest := dest+temp; end; procedure AppendChar(chr: AnsiChar; var dest: shortstring); begin inc(dest[0]); dest[ord(dest[0])] := chr; end; //form http://blog.qdac.cc/?p=2573 const Convert: array[0..255] of Integer = ( -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,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 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,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ); function PCharToIntDef(const S: PAnsichar; Len: Integer; def: Integer = 0): Integer; var I: Integer; v: Integer; begin Result := 0; for I := 0 to len-1 do begin V := Convert[ord(s[i])]; if V<0 then begin Result := def; Exit; end; result := (result * 10) + V; end; end; function LocalTimeZoneBias: Integer; {$IFDEF LINUX} var TV: TTimeval; TZ: TTimezone; begin gettimeofday(TV, TZ); Result := TZ.tz_minuteswest; end; {$ELSE} var TimeZoneInformation: TTimeZoneInformation; Bias: Longint; begin case GetTimeZoneInformation(TimeZoneInformation) of TIME_ZONE_ID_STANDARD: Bias := TimeZoneInformation.Bias + TimeZoneInformation.StandardBias; TIME_ZONE_ID_DAYLIGHT: Bias := TimeZoneInformation.Bias + ((TimeZoneInformation.DaylightBias div 60) * -100); else Bias := TimeZoneInformation.Bias; end; Result := Bias; end; {$ENDIF} var DLocalTimeZoneBias: Double = 0; function DateTimeToGMT(const DT: TDateTime): TDateTime; inline; begin Result := DT + DLocalTimeZoneBias; end; function GMTToDateTime(const DT: TDateTime): TDateTime; inline; begin Result := DT - DLocalTimeZoneBias; end; function DateTimeToGMTRFC822(const DateTime: TDateTime): string; const WEEK: array[1..7] of string = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); STR_ENGLISH_M: array[1..12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); var wWeek, wYear, wMonth, wDay, wHour, wMin, wSec, wMilliSec: Word; begin DecodeDateTime(DateTimeToGMT(DateTime), wYear, wMonth, wDay, wHour, wMin, wSec, wMilliSec); wWeek := DayOfWeek(DateTimeToGMT(DateTime)); Result := Format('%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT', [WEEK[wWeek], wDay, STR_ENGLISH_M[wMonth], wYear, wHour, wMin, wSec]); end; function GMTRFC822ToDateTime(const pSour: AnsiString): TDateTime; function GetMonthDig(const Value: PAnsiChar): Integer; const STR_ENGLISH_M: array[1..12] of PAnsiChar = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); begin for Result := Low(STR_ENGLISH_M) to High(STR_ENGLISH_M) do begin if StrLIComp(Value, STR_ENGLISH_M[Result], 3) = 0 then Exit; end; Result := 0; end; var P1, P2, PMax: PAnsiChar; wDay, wMonth, wYear, wHour, wMinute, wSec: SmallInt; begin Result := 0; if Length(pSour) < 25 then Exit; P1 := Pointer(pSour); P2 := P1; PMax := P1 + Length(pSour); while (P1 < PMax) and (P1^ <> ',') do Inc(P1); Inc(P1); if (P1^ <> #32) and (P1 - P2 < 4) then Exit; Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> #32) do Inc(P1); if (P1^ <> #32) then Exit; wDay := PCharToIntDef(P2, P1 - P2); if wDay = 0 then Exit; Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> #32) do Inc(P1); if (P1^ <> #32) and (P1 - P2 < 3) then Exit; wMonth := GetMonthDig(P2); Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> #32) do Inc(P1); if (P1^ <> #32) then Exit; wYear := PCharToIntDef(P2, P1 - P2); if wYear = 0 then Exit; Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> ':') do Inc(P1); if (P1^ <> ':') then Exit; wHour := PCharToIntDef(P2, P1 - P2); if wHour = 0 then Exit; Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> ':') do Inc(P1); if (P1^ <> ':') then Exit; wMinute := PCharToIntDef(P2, P1 - P2); if wMinute = 0 then Exit; Inc(P1); P2 := P1; while (P1 < PMax) and (P1^ <> #32) do Inc(P1); if (P1^ <> #32) then Exit; wSec := PCharToIntDef(P2, P1 - P2); if wSec = 0 then Exit; Result := GMTToDateTime(EnCodeDateTime(wYear, wMonth, wDay, wHour, wMinute, wSec, 0)); end; initialization DLocalTimeZoneBias := LocalTimeZoneBias / 1440; end.
unit HttpDownloader; {$mode delphi} interface uses curl; type FZDownloaderThread = class; { FZFileDownloader } FZDownloadResult = ( DOWNLOAD_SUCCESS, DOWNLOAD_ERROR ); FZFileDownloader = class public constructor Create(url:string; filename:string; compression_type:cardinal; thread:FZDownloaderThread ); destructor Destroy; override; function IsDownloading():boolean; virtual; abstract; function IsBusy():boolean; function GetUrl:string; function GetFilename:string; function GetCompressionType:cardinal; function StartAsyncDownload():boolean; function StartSyncDownload():boolean; function DownloadedBytes():cardinal; function IsSuccessful():boolean; function RequestStop():boolean; procedure Flush(); virtual; abstract; private _lock:TRTLCriticalSection; _request:uintptr; _url:string; _filename:string; _downloaded_bytes:cardinal; _compression_type:cardinal; _status:FZDownloadResult; _acquires_count:integer; _thread:FZDownloaderThread; _filesize:cardinal; procedure SetRequestId(id:uintptr); function GetRequestId():uintptr; procedure Acquire(); procedure Release(); procedure Lock(); procedure Unlock(); procedure SetStatus(status:FZDownloadResult); procedure SetFileSize(filesize:cardinal); procedure SetDownloadedBytesCount(count:cardinal); end; { FZGameSpyFileDownloader } FZGameSpyFileDownloader = class(FZFileDownloader) public constructor Create(url: string; filename: string; compression_type: cardinal; thread:FZDownloaderThread); function IsDownloading():boolean; override; procedure Flush(); override; end; { FZCurlFileDownloader } FZCurlFileDownloader = class(FZFileDownloader) _file_hndl:THandle; public constructor Create(url: string; filename: string; compression_type: cardinal; thread:FZDownloaderThread); function IsDownloading():boolean; override; destructor Destroy; override; procedure Flush(); override; end; FZDownloaderThreadCmdType = (FZDownloaderAdd, FZDownloaderStop); { FZDownloaderThreadInfo } FZDownloaderThreadCmd = record cmd:FZDownloaderThreadCmdType; downloader:FZFileDownloader; end; { FZDownloaderThreadInfoQueue } FZDownloaderThreadInfoQueue = class public constructor Create; destructor Destroy; override; function Add(item:FZDownloaderThreadCmd):boolean; procedure Flush(); function Count(): integer; function Capacity(): integer; function Get(i:integer):FZDownloaderThreadCmd; private _queue:array of FZDownloaderThreadCmd; _cur_items_cnt:integer; end; { FZDownloaderThread } FZDownloaderThread = class public constructor Create; function AddCommand(cmd:FZDownloaderThreadCmd):boolean; function CreateDownloader(url:string; filename:string; compression_type:cardinal ):FZFileDownloader; virtual; abstract; function StartDownload(dl:FZFileDownloader): boolean; virtual; abstract; function ProcessDownloads():boolean; virtual; abstract; function CancelDownload(dl:FZFileDownloader): boolean; virtual; abstract; destructor Destroy; override; private _lock:TRTLCriticalSection; _commands_queue:FZDownloaderThreadInfoQueue; _downloaders:array of FZFileDownloader; _need_terminate:boolean; _thread_active:boolean; _good:boolean; procedure _WaitForThreadTermination(); function _FindDownloader(dl:FZFileDownloader):integer; procedure _ProcessCommands(); end; { FZGameSpyDownloaderThread } FZGameSpyDownloaderThread = class(FZDownloaderThread) private _dll_handle:THandle; _xrGS_ghttpStartup:procedure(); cdecl; _xrGS_ghttpCleanup:procedure(); cdecl; _xrGS_ghttpThink:procedure(); cdecl; _xrGS_ghttpSave:function( url:PAnsiChar; filename:PAnsiChar; blocking:cardinal; completedCallback:pointer; param:pointer ):cardinal; cdecl; _xrGS_ghttpSaveEx:function( url:PAnsiChar; filename:PAnsiChar; headers:PAnsiChar; post:pointer; throttle:cardinal; blocking:cardinal; progressCallback:pointer; completedCallback:pointer; param:pointer ):cardinal; cdecl; _xrGS_ghttpCancelRequest:procedure( request:cardinal ); cdecl; public constructor Create; destructor Destroy; override; function CreateDownloader(url:string; filename:string; compression_type:cardinal ):FZFileDownloader; override; function StartDownload(dl:FZFileDownloader): boolean; override; function ProcessDownloads(): boolean; override; function CancelDownload(dl:FZFileDownloader): boolean; override; end; { FZCurlDownloaderThread } FZCurlDownloaderThread = class(FZDownloaderThread) _multi_handle:pTCURLM; public constructor Create; destructor Destroy; override; function CreateDownloader(url:string; filename:string; compression_type:cardinal ):FZFileDownloader; override; function StartDownload(dl:FZFileDownloader): boolean; override; function ProcessDownloads(): boolean; override; function CancelDownload(dl:FZFileDownloader): boolean; override; end; implementation uses abstractions, windows, LogMgr, sysutils, Decompressor, CommonHelper; const GHTTPSuccess:cardinal=0; GHTTPRequestError:cardinal=$FFFFFFFF; TH_LBL:string='[TH]'; DL_LBL:string='[DL]'; CB_LBL:string='[CB]'; QUEUE_LBL:string='[Q]'; { Thread functions & Callbacks } procedure CreateThreadedFun(proc:pointer; param:pointer); begin VersionAbstraction().ThreadSpawn(FZCommonHelper.PtrToUint(proc), FZCommonHelper.PtrToUint(param)); end; procedure DownloaderThreadBody(th:FZDownloaderThread); stdcall; var need_stop:boolean; i,last:integer; immediate_call:boolean; begin FZLogMgr.Get.Write(TH_LBL+'DL thread started', FZ_LOG_INFO); need_stop:=false; while (not need_stop) do begin th._ProcessCommands(); immediate_call:=false; windows.EnterCriticalSection(th._lock); try for i:=length(th._downloaders)-1 downto 0 do begin if not th._downloaders[i].IsDownloading() then begin FZLogMgr.Get.Write(TH_LBL+'Removing from active list DL '+th._downloaders[i].GetFilename(), FZ_LOG_INFO); th._downloaders[i].Release(); last:=length(th._downloaders)-1; if i<last then begin th._downloaders[i]:=th._downloaders[last]; end; setlength(th._downloaders, last); FZLogMgr.Get.Write(TH_LBL+'Active downloaders count '+inttostr(length(th._downloaders)), FZ_LOG_INFO); end; end; if length(th._downloaders)>0 then begin immediate_call:=th.ProcessDownloads(); end; need_stop:=th._need_terminate and (length(th._downloaders)=0); finally windows.LeaveCriticalSection(th._lock); end; if not immediate_call then begin Sleep(1); end; end; FZLogMgr.Get.Write(TH_LBL+'DL thread finished', FZ_LOG_INFO); th._thread_active:=false; end; procedure DownloaderThreadBodyWrapper(); cdecl; asm pushad push ebx call DownloaderThreadBody popad end; procedure UnpackerThreadBody(downloader:FZFileDownloader); stdcall; var size:cardinal; begin FZLogMgr.Get.Write(CB_LBL+'Unpacker thread started', FZ_LOG_INFO); if (downloader.GetCompressionType()<>0) then begin size:=DecompressFile(downloader.GetFilename(), downloader.GetCompressionType()); if size=0 then begin downloader.SetStatus(DOWNLOAD_ERROR); end else begin downloader.SetFileSize(size); downloader.SetDownloadedBytesCount(size); end; end; downloader.Release(); FZLogMgr.Get.Write(CB_LBL+'Unpacker thread finished', FZ_LOG_INFO); end; procedure UnpackerThreadBodyWrapper(); cdecl; asm pushad push ebx call UnpackerThreadBody popad end; procedure OnDownloadInProgress(downloader:FZFileDownloader; filesize:cardinal; downloaded:cardinal); begin downloader.Lock(); downloader.SetDownloadedBytesCount(downloaded); downloader.SetFileSize(filesize); downloader.Unlock(); end; procedure OnDownloadFinished(downloader:FZFileDownloader; dlresult:FZDownloadResult); begin downloader.Lock(); FZLogMgr.Get.Write(CB_LBL+'Download finished for '+downloader.GetFileName()+' with result '+inttostr(cardinal(dlresult)), FZ_LOG_INFO); downloader.SetStatus(dlresult); if (dlresult=DOWNLOAD_SUCCESS) and (downloader.GetCompressionType()<>0) then begin downloader.Acquire(); CreateThreadedFun(@UnpackerThreadBodyWrapper, downloader); end; downloader.Unlock(); end; { FZCurlDownloaderThread } constructor FZCurlDownloaderThread.Create; begin inherited; _multi_handle:=curl_multi_init(); if _multi_handle = nil then begin FZLogMgr.Get.Write(TH_LBL+'Cannot create multy handle!', FZ_LOG_ERROR); _good:=false; end; end; destructor FZCurlDownloaderThread.Destroy; begin if _good then begin curl_multi_cleanup(_multi_handle); end; inherited Destroy; end; function FZCurlDownloaderThread.CreateDownloader(url: string; filename: string; compression_type: cardinal): FZFileDownloader; begin result:=FZCurlFileDownloader.Create(url, filename, compression_type, self); end; function CurlWriteCb(ptr:PChar; size:cardinal; nitems:Cardinal; userdata:pointer):cardinal; cdecl; var res:cardinal; dl:FZFileDownloader; begin res:=0; dl:=userdata; if (FZCurlFileDownloader(dl)._file_hndl<>INVALID_HANDLE_VALUE) then begin WriteFile(FZCurlFileDownloader(dl)._file_hndl, ptr[0], nitems*size, res, nil); end; result:=nitems*size; end; function CurlProgressCb(clientp:pointer; dltotal:int64; dlnow:int64; {%H-}ultotal:int64; {%H-}ulnow:int64):integer; cdecl; var downloader:FZFileDownloader; begin downloader:=clientp; OnDownloadInProgress(downloader, dltotal, dlnow); result:=CURLE_OK; end; function FZCurlDownloaderThread.StartDownload(dl: FZFileDownloader): boolean; var purl:pTCURL; dl_i:integer; fname:PAnsiChar; useragent:PAnsiChar; begin dl.Lock(); result:=false; try if not _good then begin FZLogMgr.Get.Write(TH_LBL+'Thread is not in a good state', FZ_LOG_ERROR); dl.SetRequestId(0); end else if _FindDownloader(dl)<0 then begin fname:=PAnsiChar(dl.GetFilename()); FZLogMgr.Get.Write(TH_LBL+'Opening file '+fname, FZ_LOG_INFO); FZCurlFileDownloader(dl)._file_hndl:=CreateFile(fname, GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if FZCurlFileDownloader(dl)._file_hndl = INVALID_HANDLE_VALUE then begin FZLogMgr.Get.Write(TH_LBL+'File creation failed for '+dl.GetFilename(), FZ_LOG_ERROR); exit; end; FZLogMgr.Get.Write(TH_LBL+'File '+fname+' opened, handle is '+inttostr(FZCurlFileDownloader(dl)._file_hndl), FZ_LOG_INFO); FZLogMgr.Get.Write(TH_LBL+'Setting up DL handle', FZ_LOG_INFO); purl:=curl_easy_init(); if purl = nil then begin FZLogMgr.Get.Write(TH_LBL+'Failed to create dl handle!', FZ_LOG_ERROR ); exit; end; useragent:=PAnsiChar('FreeZone Curl-Downloader, build '+{$INCLUDE %DATE}); curl_easy_setopt(purl, CURLOPT_URL, FZCommonHelper.PtrToUint(PAnsiChar(dl.GetUrl()))); curl_easy_setopt(purl, CURLOPT_WRITEFUNCTION, FZCommonHelper.PtrToUint(@CurlWriteCb) ); curl_easy_setopt(purl, CURLOPT_WRITEDATA, FZCommonHelper.PtrToUint(dl)); curl_easy_setopt(purl, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(purl, CURLOPT_FAILONERROR, 1); curl_easy_setopt(purl, CURLOPT_USERAGENT, FZCommonHelper.PtrToUint(useragent)); curl_easy_setopt(purl, CURLOPT_XFERINFODATA, FZCommonHelper.PtrToUint(dl)); curl_easy_setopt(purl, CURLOPT_XFERINFOFUNCTION, FZCommonHelper.PtrToUint(@CurlProgressCb)); curl_easy_setopt(purl, CURLOPT_FOLLOWLOCATION, 1); dl.SetRequestId(FZCommonHelper.PtrToUint(purl)); curl_multi_add_handle(_multi_handle, purl); FZLogMgr.Get.Write(TH_LBL+'Download started for dl '+inttostr(FZCommonHelper.PtrToUint(dl))+', handle '+inttostr(FZCommonHelper.PtrToUint(purl)), FZ_LOG_INFO); dl_i:=length(_downloaders); setlength(_downloaders, dl_i+1); _downloaders[dl_i]:=dl; result:=true; end; finally dl.Unlock(); end; end; function FZCurlDownloaderThread.ProcessDownloads():boolean; var cnt, inprogress, i:integer; msg:pCURLMsg; dl:FZFileDownloader; dl_result:CURLcode; dl_handle:pTCURL; begin result:=curl_multi_perform(_multi_handle, @inprogress) = CURLM_CALL_MULTI_PERFORM; repeat msg :=curl_multi_info_read(_multi_handle, @cnt); if (msg<>nil) then begin if (msg.msg = CURLMSG_DONE) then begin dl:=nil; for i:=length(_downloaders)-1 downto 0 do begin if _downloaders[i].GetRequestId() = FZCommonHelper.PtrToUint(msg.easy_handle) then begin dl:=_downloaders[i]; break; end; end; //Скопируем статус закачки и хендл (после закрытия хендла доступ к ним пропадет) dl_result:=msg.data.result; dl_handle:=msg.easy_handle; //Оптимизация - закрываем соединение, дабы оно не "висело" во время распаковки curl_multi_remove_handle(_multi_handle, msg.easy_handle); curl_easy_cleanup(msg.easy_handle); if dl<>nil then begin if (FZCurlFileDownloader(dl)<>nil) and (INVALID_HANDLE_VALUE<>FZCurlFileDownloader(dl)._file_hndl) then begin FZLogMgr.Get.Write(TH_LBL+'Close file handle '+inttostr(FZCurlFileDownloader(dl)._file_hndl), FZ_LOG_INFO); CloseHandle(FZCurlFileDownloader(dl)._file_hndl); FZCurlFileDownloader(dl)._file_hndl:=INVALID_HANDLE_VALUE; end; if dl_result = CURLE_OK then begin OnDownloadFinished(dl, DOWNLOAD_SUCCESS); end else begin FZLogMgr.Get.Write(TH_LBL+'Curl Download Error ('+inttostr(dl_result)+')', FZ_LOG_ERROR); OnDownloadFinished(dl, DOWNLOAD_ERROR); end; dl.SetRequestId(0); end else begin FZLogMgr.Get.Write(TH_LBL+'Downloader not found for handle '+inttostr(FZCommonHelper.PtrToUint(dl_handle)), FZ_LOG_ERROR); end; end; end; until cnt = 0 ; end; function FZCurlDownloaderThread.CancelDownload(dl: FZFileDownloader): boolean; var purl:pTCURL; dl_i:integer; code:CURLMcode; begin result:=false; dl_i:=_FindDownloader(dl); if dl_i>=0 then begin try dl.Lock(); purl:=FZCommonHelper.UintToPtr(dl.GetRequestId()); if purl<>nil then begin FZLogMgr.Get.Write(TH_LBL+'Cancelling request '+inttostr(FZCommonHelper.PtrToUint(purl)), FZ_LOG_INFO); if (FZCurlFileDownloader(dl)<>nil) and (INVALID_HANDLE_VALUE<>FZCurlFileDownloader(dl)._file_hndl) then begin CloseHandle(FZCurlFileDownloader(dl)._file_hndl); FZCurlFileDownloader(dl)._file_hndl:=INVALID_HANDLE_VALUE; end; OnDownloadFinished(dl, DOWNLOAD_ERROR); code:=curl_multi_remove_handle(_multi_handle, purl); if code = CURLM_OK then begin curl_easy_cleanup(purl); end else begin FZLogMgr.Get.Write(TH_LBL+'Fail to remove from multi handle ('+inttostr(code)+')', FZ_LOG_ERROR); end; dl.SetRequestId(0); result:=true; end; finally dl.Unlock(); end; end else begin FZLogMgr.Get.Write(TH_LBL+'Downloader not found', FZ_LOG_INFO); end; end; { FZCurlFileDownloader } constructor FZCurlFileDownloader.Create(url: string; filename: string; compression_type: cardinal; thread: FZDownloaderThread); begin inherited; _request := 0; _file_hndl:=INVALID_HANDLE_VALUE; end; function FZCurlFileDownloader.IsDownloading: boolean; begin Lock(); result:=(_request<>0); Unlock(); end; destructor FZCurlFileDownloader.Destroy; begin inherited Destroy; end; procedure FZCurlFileDownloader.Flush; begin Lock(); if _file_hndl<>INVALID_HANDLE_VALUE then begin FZLogMgr.Get.Write(DL_LBL+'Flushing file '+_filename+' ('+inttostr(_file_hndl)+')', FZ_LOG_INFO); FlushFileBuffers(_file_hndl); end; Unlock(); end; { FZGameSpyFileDownloader } constructor FZGameSpyFileDownloader.Create(url: string; filename: string; compression_type: cardinal; thread: FZDownloaderThread); begin inherited; _request:=GHTTPRequestError; end; function FZGameSpyFileDownloader.IsDownloading: boolean; begin Lock(); result:=(_request<>GHTTPRequestError); Unlock(); end; procedure FZGameSpyFileDownloader.Flush; begin FZLogMgr.Get.Write(DL_LBL+'Flush request for '+_filename, FZ_LOG_INFO); end; { FZGameSpyDownloaderThread } constructor FZGameSpyDownloaderThread.Create; begin inherited; _dll_handle := LoadLibrary('xrGameSpy.dll'); _xrGS_ghttpStartup:=GetProcAddress( _dll_handle, 'xrGS_ghttpStartup'); _xrGS_ghttpCleanup:=GetProcAddress( _dll_handle, 'xrGS_ghttpCleanup'); _xrGS_ghttpThink:=GetProcAddress( _dll_handle, 'xrGS_ghttpThink'); _xrGS_ghttpSave:=GetProcAddress( _dll_handle, 'xrGS_ghttpSave'); _xrGS_ghttpSaveEx:=GetProcAddress( _dll_handle, 'xrGS_ghttpSaveEx'); _xrGS_ghttpCancelRequest:=GetProcAddress( _dll_handle, 'xrGS_ghttpCancelRequest'); if ( @_xrGS_ghttpStartup<>nil ) and ( @_xrGS_ghttpCleanup<>nil ) and ( @_xrGS_ghttpThink<>nil ) and ( @_xrGS_ghttpSave<>nil ) and ( @_xrGS_ghttpSaveEx<>nil ) and ( @_xrGS_ghttpCancelRequest<>nil ) then begin _xrGS_ghttpStartup(); end else begin _good:=false; FZLogMgr.Get.Write(TH_LBL+'Downloader thread in a bad state', FZ_LOG_ERROR); end; end; destructor FZGameSpyDownloaderThread.Destroy; begin FZLogMgr.Get.Write(TH_LBL+'Destroying GS downloader thread', FZ_LOG_INFO); windows.EnterCriticalSection(_lock); _need_terminate:=true; windows.LeaveCriticalSection(_lock); _WaitForThreadTermination(); if _good then begin FZLogMgr.Get.Write(TH_LBL+'Turn off GS service', FZ_LOG_INFO); _xrGS_ghttpCleanup(); end; FreeLibrary(_dll_handle); inherited Destroy; end; procedure OnGameSpyDownloadInProgress({%H-}request: cardinal; {%H-}state:cardinal; {%H-}buffer:PAnsiChar; {%H-}bufferLen_low: cardinal; {%H-}bufferLen_high: cardinal; bytesReceived_low: cardinal; {%H-}bytesReceived_high: cardinal; totalSize_low: cardinal; {%H-}totalSize_high: cardinal; param:pointer ); cdecl; var downloader:FZFileDownloader; begin downloader:=param; OnDownloadInProgress(downloader, totalSize_low, bytesReceived_low); end; function OnGamespyDownloadFinished({%H-}request: cardinal; requestResult: cardinal; {%H-}buffer: PAnsiChar; bufferLen_low: cardinal; {%H-}bufferLen_high: cardinal; param: pointer): cardinal; cdecl; var downloader:FZFileDownloader; begin downloader:=param; if requestResult = GHTTPSuccess then begin FZLogMgr.Get.Write(CB_LBL+'OnGamespyDownloadFinished ('+inttostr(requestResult)+')', FZ_LOG_INFO); end else begin FZLogMgr.Get.Write(CB_LBL+'OnGamespyDownloadFinished ('+inttostr(requestResult)+')', FZ_LOG_ERROR); end; downloader.Lock(); downloader.SetDownloadedBytesCount(bufferLen_low); downloader.SetFileSize(bufferLen_low); downloader.SetRequestId(GHTTPRequestError); //Not downloading now if (requestResult=GHTTPSuccess) then begin OnDownloadFinished(downloader, DOWNLOAD_SUCCESS); end else begin OnDownloadFinished(downloader, DOWNLOAD_ERROR); end; downloader.Unlock(); result:=1; end; function FZGameSpyDownloaderThread.CreateDownloader(url: string; filename: string; compression_type: cardinal): FZFileDownloader; begin result:=FZGameSpyFileDownloader.Create(url, filename, compression_type, self); end; function FZGameSpyDownloaderThread.StartDownload(dl: FZFileDownloader): boolean; var request:cardinal; progresscb, finishcb:pointer; dl_i:integer; begin progresscb:=@OnGameSpyDownloadInProgress; finishcb:=@OnGamespyDownloadFinished; result:=false; dl.Lock(); try if not _good then begin FZLogMgr.Get.Write(TH_LBL+'Thread is not in a good state', FZ_LOG_ERROR); dl.SetRequestId(GHTTPRequestError); end else if _FindDownloader(dl)<0 then begin request:=_xrGS_ghttpSaveEx(PAnsiChar(dl.GetUrl()), PAnsiChar(dl.GetFilename()), nil, nil,0, 0, progresscb, finishcb, dl); if request<>GHTTPRequestError then begin FZLogMgr.Get.Write(TH_LBL+'Download started, request '+inttostr(request), FZ_LOG_INFO); dl_i:=length(_downloaders); setlength(_downloaders, dl_i+1); _downloaders[dl_i]:=dl; result:=true; end else begin FZLogMgr.Get.Write(TH_LBL+'Failed to start download', FZ_LOG_INFO); end; dl.SetRequestId(request); end; finally dl.Unlock(); end; end; function FZGameSpyDownloaderThread.ProcessDownloads:boolean; begin _xrGS_ghttpThink(); result:=false; //Don't call immediately end; function FZGameSpyDownloaderThread.CancelDownload(dl: FZFileDownloader): boolean; var dl_i:integer; request:cardinal; begin result:=false; dl_i:=_FindDownloader(dl); if dl_i>=0 then begin dl.Lock(); request:=dl.GetRequestId(); //Несмотря на то, что пока очередь не очищена, удаления не произойдет - все равно защитим от этого на всякий dl.Acquire(); //Анлок необходим тут, так как во время работы функции отмены реквеста может начать работу колбэк прогресса (из потока мейнменю) и зависнуть на получении мьютекса - дедлок dl.Unlock(); if request<>GHTTPRequestError then begin FZLogMgr.Get.Write(TH_LBL+'Cancelling request '+inttostr(request), FZ_LOG_INFO); _xrGS_ghttpCancelRequest(request); //Автоматически не вызывается при отмене - приходится вручную OnGamespyDownloadFinished(GHTTPRequestError, GHTTPRequestError, nil, 0, 0, dl); end; dl.Release(); result:=true; end else begin FZLogMgr.Get.Write(TH_LBL+'Downloader not found', FZ_LOG_INFO); end; end; { FZDownloaderThreadInfoQueue } constructor FZDownloaderThreadInfoQueue.Create; begin inherited; setlength(_queue, 0); _cur_items_cnt:=0; end; destructor FZDownloaderThreadInfoQueue.Destroy; begin Flush(); inherited; end; function FZDownloaderThreadInfoQueue.Add(item: FZDownloaderThreadCmd): boolean; var i, cap:integer; begin result:=true; item.downloader.Acquire(); item.downloader.Lock(); FZLogMgr.Get.Write(QUEUE_LBL+'Put command '+inttostr(cardinal(item.cmd))+' into DL queue for '+item.downloader.GetFilename(), FZ_LOG_INFO); cap:=Capacity(); i:=Count(); if (i+1>=cap) then begin setlength(_queue, i+1); end; _queue[i]:=item; _cur_items_cnt:=_cur_items_cnt+1; FZLogMgr.Get.Write(QUEUE_LBL+'Command in queue, count='+inttostr(_cur_items_cnt)+', capacity='+inttostr(length(_queue)), FZ_LOG_INFO); item.downloader.Unlock(); end; procedure FZDownloaderThreadInfoQueue.Flush; var i, cnt:integer; begin cnt:=Count(); FZLogMgr.Get.Write(QUEUE_LBL+'Flush commands', FZ_LOG_INFO); if cnt > 0 then begin for i:=0 to cnt-1 do begin _queue[i].downloader.Release(); end; _cur_items_cnt:=0; end; end; function FZDownloaderThreadInfoQueue.Count: integer; begin result:=_cur_items_cnt; end; function FZDownloaderThreadInfoQueue.Capacity: integer; begin result:=length(_queue); end; function FZDownloaderThreadInfoQueue.Get(i: integer): FZDownloaderThreadCmd; begin assert(i<Count(), QUEUE_LBL+'Invalid item index'); result:=_queue[i]; end; { FZFileDownloader } constructor FZFileDownloader.Create(url: string; filename: string; compression_type: cardinal; thread:FZDownloaderThread); begin windows.InitializeCriticalSection(_lock); _url:=url; _filename:=filename; _compression_type:=compression_type; _downloaded_bytes:=0; _status:=DOWNLOAD_SUCCESS; _acquires_count:=0; _thread:=thread; FZLogMgr.Get.Write(DL_LBL+'Created downloader for '+_filename+' from '+url+', compression '+inttostr(_compression_type), FZ_LOG_INFO); end; destructor FZFileDownloader.Destroy; begin FZLogMgr.Get.Write(DL_LBL+'Wait for DL finished for '+_filename, FZ_LOG_INFO); while IsBusy() do begin sleep(100); end; FZLogMgr.Get.Write(DL_LBL+'Destroying downloader for '+_filename, FZ_LOG_INFO); windows.DeleteCriticalSection(_lock); inherited Destroy; end; function FZFileDownloader.IsBusy: boolean; begin Lock(); result:=(_acquires_count > 0) or IsDownloading(); Unlock(); end; function FZFileDownloader.GetUrl: string; begin Lock(); result:=_url; Unlock(); end; function FZFileDownloader.GetFilename: string; begin Lock(); result:=_filename; Unlock(); end; function FZFileDownloader.GetCompressionType: cardinal; begin Lock(); result:=_compression_type; Unlock(); end; function FZFileDownloader.StartAsyncDownload():boolean; var info:FZDownloaderThreadCmd; begin result:=false; Lock(); if IsBusy() then begin FZLogMgr.Get.Write(DL_LBL+'Downloader is busy - cannot start async DL of '+_filename, FZ_LOG_INFO); Unlock(); exit; end; FZLogMgr.Get.Write(DL_LBL+'Start async DL of '+_filename, FZ_LOG_INFO); Acquire(); //вызов показывает, что даунлоадер приписан к треду, тред зарелизит его перед удалением из списка try info.downloader:=self; info.cmd:=FZDownloaderAdd; result:=_thread.AddCommand(info); finally Unlock(); if not result then Release(); end; end; function FZFileDownloader.StartSyncDownload: boolean; begin FZLogMgr.Get.Write(DL_LBL+'Start sync DL of '+_filename, FZ_LOG_INFO); result:=StartAsyncDownload(); if result then begin FZLogMgr.Get.Write(DL_LBL+'Waiting for DL finished '+_filename, FZ_LOG_INFO); while(IsBusy()) do begin Sleep(100); end; result:= IsSuccessful(); end; end; function FZFileDownloader.DownloadedBytes: cardinal; begin Lock(); result:=_downloaded_bytes; Unlock(); end; function FZFileDownloader.IsSuccessful: boolean; begin Lock(); result:= _status=DOWNLOAD_SUCCESS; Unlock(); end; function FZFileDownloader.RequestStop():boolean; var info:FZDownloaderThreadCmd; begin result:=true; Lock(); FZLogMgr.Get.Write(DL_LBL+'RequestStop for downloader '+GetFilename()+', request='+inttostr(self._request), FZ_LOG_INFO); Acquire(); //To avoid removing before command is sent info.downloader:=self; info.cmd:=FZDownloaderStop; Unlock(); //Unlock to avoid deadlock between downloader's and thread's mutexes result:=_thread.AddCommand(info); Release(); end; procedure FZFileDownloader.SetRequestId(id: uintptr); begin Lock(); FZLogMgr.Get.Write(DL_LBL+'Set request id='+inttostr(id)+' for '+GetFileName(), FZ_LOG_INFO); _request:=id; Unlock(); end; function FZFileDownloader.GetRequestId: uintptr; begin Lock(); result:=_request; Unlock(); end; procedure FZFileDownloader.Acquire; var i:cardinal; begin i:=InterlockedIncrement(_acquires_count); FZLogMgr.Get.Write(DL_LBL+'Downloader acquired (cnt='+inttostr(i)+') '+GetFileName(), FZ_LOG_INFO); end; procedure FZFileDownloader.Release; var i:cardinal; name:string; begin name:=GetFileName(); i:=InterlockedDecrement(_acquires_count); FZLogMgr.Get.Write(DL_LBL+'Downloader released (cnt='+inttostr(i)+') '+name, FZ_LOG_INFO); end; procedure FZFileDownloader.Lock; begin windows.EnterCriticalSection(_lock); end; procedure FZFileDownloader.Unlock; begin windows.LeaveCriticalSection(_lock); end; procedure FZFileDownloader.SetStatus(status: FZDownloadResult); begin Lock(); _status:=status; Unlock(); end; procedure FZFileDownloader.SetFileSize(filesize:cardinal); begin Lock(); _filesize:=filesize; Unlock(); end; procedure FZFileDownloader.SetDownloadedBytesCount(count:cardinal); begin Lock(); _downloaded_bytes:=count; Unlock(); end; { FZDownloaderThread } constructor FZDownloaderThread.Create; begin inherited Create(); windows.InitializeCriticalSection(_lock); _commands_queue:= FZDownloaderThreadInfoQueue.Create(); _need_terminate:=false; _thread_active:=false; _good:=true; FZLogMgr.Get.Write(TH_LBL+'Creating downloader thread fun', FZ_LOG_INFO); _thread_active:=true; CreateThreadedFun(@DownloaderThreadBodyWrapper, self); end; function FZDownloaderThread.AddCommand(cmd: FZDownloaderThreadCmd):boolean; begin result:=false; windows.EnterCriticalSection(_lock); try if not _good then exit; result:=_commands_queue.Add(cmd); finally windows.LeaveCriticalSection(_lock); end; end; destructor FZDownloaderThread.Destroy; begin FZLogMgr.Get.Write(TH_LBL+'Destroying base downloader thread', FZ_LOG_INFO); //Make sure that thread is terminated windows.EnterCriticalSection(_lock); _need_terminate:=true; windows.LeaveCriticalSection(_lock); _WaitForThreadTermination(); _commands_queue.Free(); windows.DeleteCriticalSection(_lock); inherited Destroy; end; procedure FZDownloaderThread._WaitForThreadTermination; var active:boolean; begin active:=true; FZLogMgr.Get.Write(TH_LBL+'Waiting for DL thread termination', FZ_LOG_INFO); while(active) do begin windows.EnterCriticalSection(_lock); active:=_thread_active; windows.LeaveCriticalSection(_lock); end; end; function FZDownloaderThread._FindDownloader(dl: FZFileDownloader): integer; var i:integer; begin result:=-1; windows.EnterCriticalSection(_lock); for i:=length(_downloaders)-1 downto 0 do begin if dl = _downloaders[i] then begin result:=i; break; end; end; windows.LeaveCriticalSection(_lock); end; procedure FZDownloaderThread._ProcessCommands; var i:integer; queue_cnt:integer; command:FZDownloaderThreadCmd; begin windows.EnterCriticalSection(_lock); queue_cnt:=_commands_queue.Count(); if queue_cnt>0 then begin FZLogMgr.Get.Write(TH_LBL+'Start processing commands ('+inttostr(queue_cnt)+')', FZ_LOG_INFO); for i:=0 to queue_cnt-1 do begin command:=_commands_queue.Get(i); case command.cmd of FZDownloaderAdd:begin FZLogMgr.Get.Write(TH_LBL+'Command "Add" for downloader '+command.downloader.GetFilename(), FZ_LOG_INFO); if not StartDownload(command.downloader) then begin FZLogMgr.Get.Write(TH_LBL+'Couldn''t start download for '+command.downloader.GetFilename(), FZ_LOG_ERROR); command.downloader.Release(); end; end; FZDownloaderStop: begin FZLogMgr.Get.Write(TH_LBL+'Command "Stop" for downloader '+command.downloader.GetFilename(), FZ_LOG_INFO); CancelDownload(command.downloader); end; else begin FZLogMgr.Get.Write(TH_LBL+'Unknown command!', FZ_LOG_ERROR); end; end; FZLogMgr.Get.Write(TH_LBL+'Command processed, active downloaders count '+inttostr(length(_downloaders)), FZ_LOG_INFO); end; _commands_queue.Flush(); FZLogMgr.Get.Write(TH_LBL+'Processing commands finished', FZ_LOG_INFO); end; windows.LeaveCriticalSection(_lock); end; end.
{..............................................................................} { Summary Checks for valid pins of symbols in a library. } { } { Copyright (c) 2004 by Altium Limited } {..............................................................................} {..............................................................................} Var ReportInfo : TStringList; {..............................................................................} {..............................................................................} Procedure GenerateReport(Dummy : Integer = 0); Var Document : IServerDocument; Begin ReportInfo.Insert(0,'Schematic Library Pin Names Check'); ReportInfo.Insert(1,'---------------------------------'); ReportInfo.SaveToFile('c:\SchPinsReport.txt'); Document := Client.OpenDocument('Text','c:\SchPinsReport.txt'); If Document <> Nil Then Client.ShowDocument(Document); End; {..............................................................................} {..............................................................................} Procedure CheckSchLibraryFilePinNames; Var DocType : WideString; SchComponent : ISch_Component; SchLib : ISch_Lib; SchDoc : ISCh_Doc; SchIterator : ISch_Iterator; Pin : ISch_Pin; LibName : TDynamicString; PinName : TDynamicString; PinDesignator : TDynamicString; PinIterator : ISch_Iterator; LPinName : Integer; LDesignator : Integer; Begin If SchServer = Nil Then Exit; // Obtain the Client interface so can get the Kind property. DocType := UpperCase(Client.CurrentView.OwnerDocument.Kind); If DocType <> 'SCHLIB' Then Begin ShowWarning('This is not a Library document!'); Exit; End; SchLib := SchServer.GetCurrentSchDocument; If SchLib = Nil Then Exit; // Create a TStringList object to store Pin data ReportInfo := TStringList.Create; ReportInfo.Clear; LibName := SchLib.DocumentName; LibName := ExtractFileName(LibName); ReportInfo.Add(LibName); // Create an iterator to look for components only SchIterator := SchLib.SchLibIterator_Create; SchIterator.AddFilter_ObjectSet(MkSet(eSchComponent)); Try SchComponent := SchIterator.FirstSchObject; While SchComponent <> Nil Do Begin // Look for Pins associated with this component. PinIterator := SchComponent.SchIterator_Create; PinIterator.AddFilter_ObjectSet(MkSet(ePin)); ReportInfo.Add(SchComponent.LibReference); Try Pin := PinIterator.FirstSchObject; While Pin <> Nil Do Begin ReportInfo.Add(' The Pin Designator: ' + Pin.Designator); PinName := Pin.Name; PinDesignator := Pin.Designator; LPinName := Length(Pin.Name); LDesignator := Length(Pin.Designator); If PinName = '' Then ReportInfo.Add(' Pin Name is a blank') Else If PinDesignator = '' Then ReportInfo.Add(' Pin Designator is a blank') Else If (PinName[1] = #32) Then ReportInfo.Add(' ' + Pin.Name + ',' + 'The first character of the Pin Name is a blank') Else If (PinDesignator[1] = #32) Then ReportInfo.Add(' ' + Pin.Designator + ',' + 'The first character of the Pin Designator is a blank') Else If (PinName[LPinName] = #32) Then ReportInfo.Add(' ' + Pin.Name + ',' + 'The last character of the Pin Name is a blank') Else If (PinDesignator[LDesignator] = #32) Then ReportInfo.Add(' ' + Pin.Designator + ',' + 'The last character of the Pin Designator is a blank'); Pin := PinIterator.NextSchObject; End; Finally SchComponent.SchIterator_Destroy(PinIterator); End; ReportInfo.Add(''); SchComponent := SchIterator.NextSchObject; End; Finally SchLib.SchIterator_Destroy(SchIterator); End; GenerateReport; ReportInfo.Free; End; {..............................................................................} {..............................................................................}
unit U_FrmConversation; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.pngimage, U_User, U_StoredProceduresInterface, Data.Win.ADODB, U_Central_Unit; type Tfrm_Conversation = class(TForm) mm_Message: TMemo; e_message: TEdit; btn_Send: TButton; lbl_Contact: TLabel; img_ContactAvatar: TImage; Timer1: TTimer; procedure btn_SendClick(Sender: TObject); procedure e_messageKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } Index: integer; end; var frm_Conversation: Tfrm_Conversation; implementation {$R *.dfm} procedure Tfrm_Conversation.btn_SendClick(Sender: TObject); begin mm_Message.Lines.Add(e_message.Text); InsertMessage(DelphiChat.UsedConnection, DelphiChat.User.UserId, Self.Index, e_message.Text); e_message.Text:=''; e_message.SetFocus; end; procedure Tfrm_Conversation.e_messageKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then //Enter begin btn_Send.Click; end; end; procedure Tfrm_Conversation.FormShow(Sender: TObject); var aux: TMessageList; iCount: Integer; begin aux:= TMessageList.Create; mm_Message.Clear; aux:= GetAllMessageEx(DelphiChat.UsedConnection, DelphiChat.User.UserId, Self.Index); for iCount := 0 to aux.Count-1 do begin if TMessageInfo(aux.Items[iCount]).Sender=DelphiChat.User.UserId then mm_Message.Lines.Add (DelphiChat.User.Nick+' dice: '+TMessageInfo(aux.Items[iCount]).Line) else mm_Message.Lines.Add (self.lbl_Contact.Caption+' dice: '+TMessageInfo(aux.Items[iCount]).Line) end; end; end.
PROGRAM HelloDelphi; {$APPTYPE CONSOLE} VAR MSG: STRING; BEGIN MSG := 'HELLO DELPHI!!'; Writeln(MSG); END.
unit mainform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, ShellCtrls, FileCtrl, StdCtrls, EditBtn, ComCtrls, SynEdit; type { TForm1 } TForm1 = class(TForm) edDirectory: TDirectoryEdit; lbFiles: TFileListBox; cbFilter: TFilterComboBox; ImageList1: TImageList; MainMenu1: TMainMenu; miTextView: TMenuItem; miQuit: TMenuItem; miOptions: TMenuItem; miConvert: TMenuItem; miHelp: TMenuItem; miAbout: TMenuItem; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; tvDirectories: TShellTreeView; Splitter1: TSplitter; Splitter2: TSplitter; seText: TSynEdit; ToolBar1: TToolBar; tbDecrease: TToolButton; tbIncrease: TToolButton; tbQuit: TToolButton; tbNewInstance: TToolButton; procedure edDirectoryChange(Sender: TObject); procedure lbFilesClick(Sender: TObject); procedure cbFilterChange(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure miQuitClick(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure tvDirectoriesChange(Sender: TObject; Node: TTreeNode); procedure tbDecreaseClick(Sender: TObject); procedure tbIncreaseClick(Sender: TObject); procedure tbNewInstanceClick(Sender: TObject); private FLastFileLoaded: TFileName; procedure ChangeDirectory(const ADirectory: string); procedure LoadFirstItem; procedure LoadFile(const AFileName: TFileName); public end; var Form1: TForm1; implementation {$R *.lfm} uses Settings, {$ifdef mswindows} WinDirs, {$endif} LazLogger, LConvEncoding, AboutForm; { TForm1 } procedure TForm1.FormActivate(Sender: TObject); var LDirectory, LFilter: string; LItemIndex, LFontHeight: integer; begin DebugLn('FormActivate'); DebugLn(Format('ParamStr(0) = %s', [ParamStr(0)])); DebugLn(Format('Application.ExeName = %s', [Application.ExeName])); FLastFileLoaded := ''; Caption := 'TextView ' + {$I version.inc}; Splitter1.Height := Self.ClientHeight - 2 * 8 - ToolBar1.Height; LoadSettings(LDirectory, LFilter, LItemIndex, LFontHeight); if DirectoryExists(LDirectory) then edDirectory.Directory := LDirectory else edDirectory.Directory := {$ifdef mswindows} string(GetWindowsSpecialDir(CSIDL_PERSONAL, FALSE)) {$else} GetEnvironmentVariable('HOME') {$endif} ; if Length(LFilter) > 0 then cbFilter.Filter := LFilter; if LItemIndex >= 0 then begin cbFilter.ItemIndex := LItemIndex; cbFilterChange(Sender); end; seText.Font.Height := LFontHeight; end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin DebugLn('FormClose'); SaveSettings(edDirectory.Directory, cbFilter.Filter, cbFilter.ItemIndex, seText.Font.Height); end; procedure TForm1.miQuitClick(Sender: TObject); begin Close; end; procedure TForm1.miAboutClick(Sender: TObject); var LForm: TAboutForm; begin LForm := TAboutForm.Create(nil); try LForm.ShowModal; finally LForm.Free; end; end; procedure TForm1.tvDirectoriesChange(Sender: TObject; Node: TTreeNode); begin DebugLn('ShellTreeView1Change'); ChangeDirectory(ExcludeTrailingPathDelimiter(tvDirectories.Path)); end; procedure TForm1.tbDecreaseClick(Sender: TObject); begin if seText.Font.Height > 13 then seText.Font.Height := Pred(seText.Font.Height); end; procedure TForm1.tbIncreaseClick(Sender: TObject); begin if seText.Font.Height < 18 then seText.Font.Height := Succ(seText.Font.Height); end; procedure TForm1.tbNewInstanceClick(Sender: TObject); begin try ExecuteProcess(Application.ExeName, [], []); except on E: EOSError do DebugLn(Format('Error %d: %s', [E.ErrorCode, E.Message])); end; end; procedure TForm1.ChangeDirectory(const ADirectory: string); begin DebugLn(Format('ChangeDirectory(%s)', [ADirectory])); if edDirectory.Directory <> ADirectory then edDirectory.Directory := ADirectory; if ExcludeTrailingPathDelimiter(tvDirectories.Path) <> ADirectory then tvDirectories.Path := IncludeTrailingPathDelimiter(ADirectory); if lbFiles.Directory <> ADirectory then begin lbFiles.Directory := ADirectory; LoadFirstItem; end; end; procedure TForm1.LoadFirstItem; begin DebugLn('LoadFirstItem'); if lbFiles.Items.Count > 0 then begin lbFiles.ItemIndex := 0; lbFiles.Click; lbFiles.SetFocus; end else seText.Clear; end; procedure TForm1.LoadFile(const AFileName: TFileName); var LList: TStringList; LEncoding: string; begin DebugLn(Format('LoadFile(%s)', [AFileName])); if AFileName = FLastFileLoaded then begin DebugLn('Exit'); Exit; end else FLastFileLoaded := AFileName; if miConvert.Checked then begin LList := TStringList.Create; LList.LoadFromFile(AFileName); LEncoding := GuessEncoding(LList.Text); if LEncoding = 'utf8' then seText.Lines.Text := LList.Text else begin DebugLn(Format('Converting to UTF-8: %s', [AFileName])); DebugLn(Format('File encoding: %s', [LEncoding])); seText.Lines.Text := ConvertEncoding(LList.Text, LEncoding, EncodingUTF8); end; LList.Free; end else seText.Lines.LoadFromFile(AFileName); end; procedure TForm1.cbFilterChange(Sender: TObject); begin DebugLn('FilterComboBox1Change'); lbFiles.Mask := cbFilter.Mask; lbFiles.Refresh; LoadFirstItem; end; procedure TForm1.lbFilesClick(Sender: TObject); begin DebugLn('FileListBox1Click'); LoadFile(lbFiles.FileName); Caption := lbFiles.FileName; end; procedure TForm1.edDirectoryChange(Sender: TObject); begin DebugLn('DirectoryEdit1Change'); Hint := edDirectory.Directory; ChangeDirectory(edDirectory.Directory); end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.Controls.Presentation, FMX.ListView, FMX.Objects, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Edit; type TFormMain = class(TForm) btnColorizer: TButton; btnHorizontal: TButton; Label1: TLabel; btnColumns: TButton; Label2: TLabel; btnParameters: TButton; btnTransparent: TButton; btnScroll: TButton; procedure btnColorizerClick(Sender: TObject); procedure btnHorizontalClick(Sender: TObject); procedure btnColumnsClick(Sender: TObject); procedure btnParametersClick(Sender: TObject); procedure btnTransparentClick(Sender: TObject); procedure btnScrollClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses uForm1, uForm2, uForm3, uForm4, uForm5, uForm6; procedure TFormMain.btnColorizerClick(Sender: TObject); begin Form1.Show; end; procedure TFormMain.btnHorizontalClick(Sender: TObject); begin Form2.Show; end; procedure TFormMain.btnColumnsClick(Sender: TObject); begin Form3.Show; end; procedure TFormMain.btnParametersClick(Sender: TObject); begin Form4.Show; end; procedure TFormMain.btnScrollClick(Sender: TObject); begin Form6.Show; end; procedure TFormMain.btnTransparentClick(Sender: TObject); begin Form5.Show; end; end.
unit MainPromoClass; interface uses PromoConfigClass, dbClient, uSaleItem, PromoClass, PromoSaleClass, PromoFactoryClass, PromoItemClass, uSystemConst; type TMainPromo = class private fSaleItem: TSaleItem; promoItem: TPromoItem; promoFactory: TPromoFactory; promo: TPromo; fCoupon: String; fIsLoyalty: Boolean; fSubtotalSale: Double; fDiscountValue: Double; procedure performPromo(arg_promoLine: TClientDataset; arg_item: TPromoItem); procedure insertPromoInCashRegisger(); public procedure setSaleItem(arg_saleItem: TSaleItem); procedure setCoupon(arg_coupon: String); procedure setIsLoyalty(arg_isLoyalty: Boolean); procedure setSubtotal(arg_subtotal: Double); procedure start(); function getDiscount(): Double; end; implementation uses uDM; { TMainPromo } function TMainPromo.getDiscount: Double; begin result := fDiscountValue; end; procedure TMainPromo.insertPromoInCashRegisger; var i, j: Integer; promoItemInList: TPromoItem; begin // X items for i:= 0 to promo.ItemsPromoXList.Count - 1 do begin promoItemInList := TPromoItem(promo.itemsPromoXList.items[i]); // deleta os itens da caixa // insere itens da promo // Y items for J := 0 to promoItemInList.fListModelY.Count - 1 do begin // deleta os itens da caixa // insere os itens da promo end; end; end; procedure TMainPromo.performPromo(arg_promoLine: TClientDataset; arg_item: TPromoItem); begin promo := promoFactory.createPromo(arg_item); // final result of discount to promo fDiscountValue := promo.getPromoDiscount(arg_item); end; procedure TMainPromo.setCoupon(arg_coupon: String); begin fCoupon := arg_coupon; end; procedure TMainPromo.setIsLoyalty(arg_isLoyalty: Boolean); begin fIsLoyalty := arg_isLoyalty; end; procedure TMainPromo.setSaleItem(arg_saleItem: TSaleItem); begin fSaleItem := arg_saleItem end; procedure TMainPromo.setSubtotal(arg_subtotal: Double); begin fSubtotalSale := arg_subtotal; end; procedure TMainPromo.start; var promoConfig: TPromoConfig; promoConfigLines: TClientDataset; customerDiscount: Double; begin // Settings to Promotions promoConfig := TPromoConfig.getPromoConfigSingleton; promoConfigLines := promoConfig.loadValidPromos(fSaleItem.PreSaleDate); // settings to Customer discount customerDiscount := dm.getCustomerDiscount(fsaleItem.IDCustomer); while ( not promoConfigLines.Eof ) do begin // idmodel was found in promolist if ( fSaleItem.IDModel = promoConfigLines.fieldByName('idmodel').AsInteger ) then begin promoItem := TPromoItem.create(promoConfigLines, fSaleItem, customerDiscount); case ( promoConfigLines.FieldByName('promoType').asInteger ) of PROMO_COUPON_TYPE: performPromo(promoConfigLines, promoItem); PROMO_FREQBUYER_TYPE: performPromo(promoConfigLines, promoItem); PROMO_LOYALTY_TYPE: performPromo(promoConfigLines, promoItem); PROMO_SALE_TYPE: performPromo(promoConfigLines, promoItem); end; end; promoConfigLines.Next; end; end; end.
//============================================================================= // sgWeb.pas //============================================================================= /// SwinGame Web code allows you to create and access web resources. You can create a simple web server /// or access web pages and applications. /// /// @module Web /// @static unit sgWeb; interface uses sgTypes; /// Converts the body of an HttpResponse to a string. /// /// @lib function HttpResponseBodyAsString(httpData: HttpResponse): String; // /// Returns the host name of a given ip address. // /// // /// @lib // function HostName(const address: String): String; // /// Returns the ip address of a given host. // /// // /// @lib // function HostIP(const name: String): String; /// Perform a get request for the resourse at the specified host, path and port. /// /// @lib function HttpGet(const url: String; port: Word): HttpResponse; /// Perform a post request to the specified host, with the supplied body. /// /// @lib function HttpPost(const url: String; port: Word; const body: String): HttpResponse; /// Free the resources used by the HttpResponse. /// /// @lib /// /// @class HttpResponse /// @dispose procedure FreeHttpResponse(var response: HttpResponse); implementation uses sgDriverWeb, sgDriverSDL2Types, sgBackendTypes, sgShared; function HttpResponseBodyAsString(httpData: HttpResponse): String; var i: Integer; response: HttpResponsePtr; begin response := ToHttpResponsePtr(httpData); // WriteLn(response^.data.size); result := ''; if not Assigned(response) then exit; for i := 0 to response^.data.size do begin // WriteLn(response^.data.data[i]); result += Char(response^.data.data[i]); end; end; //---------------------------------------------------------------------------- // Http //---------------------------------------------------------------------------- // function HostName(const address: String): String; // var // host: THostEntry; // host6: THostEntry6; // begin // result := ''; // if GetHostbyAddr(in_addr(StrToHostAddr(address)), host) // or ResolveHostbyAddr(in_addr(StrToHostAddr(address)), host) then // result := host.Name // else if ResolveHostbyAddr6(StrToHostAddr6(address), host6) then // result := host6.Name; // end; // function HostIP(const name: String): String; // var // host: THostEntry; // host6: THostEntry6; // begin // result := ''; // if GetHostByName(name, host) or ResolveHostByName(name, host) then // result := NetAddrToStr(host.Addr) // else if ResolveHostByName6(name, host6) then // result := NetAddrToStr6(host6.Addr); // end; function HttpGet(const url: String; port: Word): HttpResponse; var response : HttpResponsePtr; begin New(response); response^.id := HTTP_RESPONSE_PTR; response^.data := MakeRequest(HTTP_GET, url, port, ''); result := HttpResponse(response); end; function HttpPost(const url: String; port: Word; const body: String): HttpResponse; var response : HttpResponsePtr; begin New(response); response^.id := HTTP_RESPONSE_PTR; response^.data := MakeRequest(HTTP_POST, url, port, body); result := HttpResponse(response); end; procedure FreeHttpResponse(var response: HttpResponse); var toFree: HttpResponsePtr; begin toFree := ToHttpResponsePtr(response); if Assigned(toFree) then Dispose(toFree); response := nil; end; initialization begin InitialiseSwinGame(); end; end.
unit StockDetailDataAccess; interface uses define_DealItem, define_datasrc, BaseDataSet, QuickList_int, define_stock_quotes; type TStockDetailDataAccess = class(TBaseDataSetAccess) protected fStockItem: PRT_DealItem; fDetailDealData: TALIntegerList; fDataSource: TDealDataSource; fFirstDealDate: Word; fLastDealDate: Word; function GetFirstDealDate: Word; procedure SetFirstDealDate(const Value: Word); function GetLastDealDate: Word; procedure SetLastDealDate(const Value: Word); procedure SetStockItem(AStockItem: PRT_DealItem); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); destructor Destroy; override; function FindRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; function CheckOutRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; function NewRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; procedure Sort; override; procedure Clear; override; property FirstDealDate: Word read GetFirstDealDate write SetFirstDealDate; property LastDealDate: Word read GetLastDealDate write SetLastDealDate; property StockItem: PRT_DealItem read fStockItem write SetStockItem; property DataSource: TDealDataSource read fDataSource write fDataSource; end; function GetDetailTimeIndex(ADetailTime: string): Word; function DecodeTimeIndex(ADetailTime: Word; var AHour: integer; var AMinute: integer; var ASecond: integer): Boolean; implementation uses SysUtils, QuickSortList; function DecodeTimeIndex(ADetailTime: Word; var AHour: integer; var AMinute: integer; var ASecond: integer): Boolean; begin Result := false; if 0 < ADetailTime then begin AHour := Trunc(ADetailTime div 3600); ASecond := ADetailTime - AHour * 3600; AMinute := Trunc(ASecond div 60); ASecond := ASecond - AMinute * 60; AHour := AHour + 9; if AHour < 16 then begin if AMinute < 61 then begin Result := true; end; end; end; end; function GetDetailTimeIndex(ADetailTime: string): Word; var tmpHour: integer; tmpMinute: integer; tmpSecond: integer; tmpPos: integer; begin Result := 0; tmpPos := Pos(':', ADetailTime); if 0 < tmpPos then begin tmpHour := StrToIntDef(Copy(ADetailTime, 1, tmpPos - 1), 0); if (8 < tmpHour) and (16 > tmpHour) then begin ADetailTime := Copy(ADetailTime, tmpPos + 1, maxint); tmpPos := Pos(':', ADetailTime); if 0 < tmpPos then begin tmpMinute := StrToIntDef(Copy(ADetailTime, 1, tmpPos - 1), 0); if (61 > tmpMinute) and (-1 < tmpMinute) then begin tmpSecond := StrToIntDef(Copy(ADetailTime, tmpPos + 1, maxint), 0); Result := (tmpHour - 9) * 60 * 60 + tmpMinute * 60 + tmpSecond; end; end; end; end; end; { TStockDetailDataAccess } constructor TStockDetailDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); begin fStockItem := AStockItem; fDetailDealData := TALIntegerList.Create; fDetailDealData.Duplicates := lstDupAccept; fDataSource := ADataSrc; end; destructor TStockDetailDataAccess.Destroy; begin Clear; FreeAndNil(fDetailDealData); inherited; end; procedure TStockDetailDataAccess.SetStockItem(AStockItem: PRT_DealItem); begin if nil <> AStockItem then begin if fStockItem <> AStockItem then begin Self.Clear; end; end; fStockItem := AStockItem; if nil <> fStockItem then begin end; end; function TStockDetailDataAccess.GetFirstDealDate: Word; begin Result := fFirstDealDate; end; procedure TStockDetailDataAccess.SetFirstDealDate(const Value: Word); begin fFirstDealDate := Value; end; function TStockDetailDataAccess.GetLastDealDate: Word; begin Result := fLastDealDate; end; procedure TStockDetailDataAccess.SetLastDealDate(const Value: Word); begin fLastDealDate := Value; end; function TStockDetailDataAccess.GetRecordCount: Integer; begin Result := fDetailDealData.Count; end; function TStockDetailDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := nil; if AIndex < fDetailDealData.Count then begin Result := fDetailDealData.Objects[AIndex]; end else begin if AIndex > 0 then begin end; end; end; procedure TStockDetailDataAccess.Sort; begin if nil <> fDetailDealData then fDetailDealData.Sort; end; procedure TStockDetailDataAccess.Clear; var i: integer; tmpQuote: PRT_Quote_Detail; begin inherited; if nil <> fDetailDealData then begin for i := fDetailDealData.Count - 1 downto 0 do begin tmpQuote := PRT_Quote_Detail(fDetailDealData.Objects[i]); FreeMem(tmpQuote); end; fDetailDealData.Clear; end; end; function TStockDetailDataAccess.NewRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; var tmpIndex: integer; begin Result := System.New(PRT_Quote_Detail); FillChar(Result^, SizeOf(TRT_Quote_Detail), 0); Result.DealDateTime.DateValue := ADealDay; Result.DealDateTime.TimeValue := ADealTime; tmpIndex := Integer(Result.DealDateTime); fDetailDealData.AddObject(tmpIndex, TObject(Result)); end; function TStockDetailDataAccess.CheckOutRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; begin Result := nil; if ADealTime < 1 then exit; Result := FindRecord(ADealDay, ADealTime); if nil = Result then begin Result := NewRecord(ADealDay, ADealTime); end; end; function TStockDetailDataAccess.FindRecord(ADealDay: Word; ADealTime: Word): PRT_Quote_Detail; var tmpPos: integer; tmpDealDateTime: TRT_DateTimePack; tmpIndex: integer; begin Result := nil; tmpPos := fDetailDealData.IndexOf(ADealTime); if 0 > tmpPos then begin tmpDealDateTime.DateValue := ADealDay; tmpDealDateTime.TimeValue := ADealTime; tmpIndex := Integer(tmpDealDateTime); tmpPos := fDetailDealData.IndexOf(tmpIndex); end; if 0 <= tmpPos then Result := PRT_Quote_Detail(fDetailDealData.Objects[tmpPos]); end; end.
unit uBase128; { Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. } interface uses System.SysUtils, uBase; function Encode(data: TBytes): String; function Decode(data: String): TBytes; Const DefaultAlphabet: Array [0 .. 127] of String = ('!', '#', '$', '%', '(', ')', '*', ',', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '-', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', ']', '^', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '®', '¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î'); DefaultSpecial = '='; implementation function Encode(data: TBytes): String; var dataLength, i, length7, tempInt: Integer; tempResult: TStringBuilder; x1, x2: Byte; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; dataLength := Length(data); tempResult := TStringBuilder.Create; tempResult.Clear; try length7 := (dataLength div 7) * 7; i := 0; while i < length7 do begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); x1 := data[i + 2]; tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60) or (x1 shr 3)]); x2 := data[i + 3]; tempResult.Append(DefaultAlphabet[((x1 shl 4) and $70) or (x2 shr 4)]); x1 := data[i + 4]; tempResult.Append(DefaultAlphabet[((x2 shl 3) and $78) or (x1 shr 5)]); x2 := data[i + 5]; tempResult.Append(DefaultAlphabet[((x1 shl 2) and $7C) or (x2 shr 6)]); x1 := data[i + 6]; tempResult.Append(DefaultAlphabet[((x2 shl 1) and $7E) or (x1 shr 7)]); tempResult.Append(DefaultAlphabet[x1 and $7F]); inc(i, 7); end; tempInt := dataLength - length7; Case tempInt of 1: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); tempResult.Append(DefaultAlphabet[(x1 shl 6) and $40]); tempResult.Append(DefaultSpecial, 6); end; 2: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60)]); tempResult.Append(DefaultSpecial, 5); end; 3: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); x1 := data[i + 2]; tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60) or (x1 shr 3)]); tempResult.Append(DefaultAlphabet[(x1 shl 4) and $70]); tempResult.Append(DefaultSpecial, 4); end; 4: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); x1 := data[i + 2]; tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60) or (x1 shr 3)]); x2 := data[i + 3]; tempResult.Append(DefaultAlphabet[((x1 shl 4) and $70) or (x2 shr 4)]); tempResult.Append(DefaultAlphabet[(x2 shl 3) and $78]); tempResult.Append(DefaultSpecial, 3); end; 5: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); x1 := data[i + 2]; tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60) or (x1 shr 3)]); x2 := data[i + 3]; tempResult.Append(DefaultAlphabet[((x1 shl 4) and $70) or (x2 shr 4)]); x1 := data[i + 4]; tempResult.Append(DefaultAlphabet[((x2 shl 3) and $78) or (x1 shr 5)]); tempResult.Append(DefaultAlphabet[(x1 shl 2) and $7C]); tempResult.Append(DefaultSpecial, 2); end; 6: begin x1 := data[i]; tempResult.Append(DefaultAlphabet[x1 shr 1]); x2 := data[i + 1]; tempResult.Append(DefaultAlphabet[((x1 shl 6) and $40) or (x2 shr 2)]); x1 := data[i + 2]; tempResult.Append(DefaultAlphabet[((x2 shl 5) and $60) or (x1 shr 3)]); x2 := data[i + 3]; tempResult.Append(DefaultAlphabet[((x1 shl 4) and $70) or (x2 shr 4)]); x1 := data[i + 4]; tempResult.Append(DefaultAlphabet[((x2 shl 3) and $78) or (x1 shr 5)]); x2 := data[i + 5]; tempResult.Append(DefaultAlphabet[((x1 shl 2) and $7C) or (x2 shr 6)]); tempResult.Append(DefaultAlphabet[(x2 shl 1) and $7E]); tempResult.Append(DefaultSpecial); end; end; result := tempResult.ToString; finally tempResult.Free; end; end; function Decode(data: String): TBytes; var lastSpecialInd, tailLength, x1, x2, length7, i, srcInd: Integer; begin if isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; lastSpecialInd := Length(data); while (data[lastSpecialInd] = DefaultSpecial) do begin dec(lastSpecialInd); end; tailLength := Length(data) - lastSpecialInd; SetLength(result, (Length(data) + 7) div 8 * 7 - tailLength); length7 := Length(result) div 7 * 7; i := 0; srcInd := 0; Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial); while i < length7 do begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 2] := Byte((x1 shl 3) or ((x2 shr 4) and $07)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 3] := Byte((x2 shl 4) or ((x1 shr 3) and $0F)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 4] := Byte((x1 shl 5) or ((x2 shr 2) and $1F)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 5] := Byte((x2 shl 6) or ((x1 shr 1) and $3F)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 6] := Byte((x1 shl 7) or (x2 and $7F)); inc(i, 7); end; case tailLength of 6: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); end; 5: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); end; 4: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 2] := Byte((x1 shl 3) or ((x2 shr 4) and $07)); end; 3: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 2] := Byte((x1 shl 3) or ((x2 shr 4) and $07)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 3] := Byte((x2 shl 4) or ((x1 shr 3) and $0F)); end; 2: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 2] := Byte((x1 shl 3) or ((x2 shr 4) and $07)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 3] := Byte((x2 shl 4) or ((x1 shr 3) and $0F)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 4] := Byte((x1 shl 5) or ((x2 shr 2) and $1F)); end; 1: begin inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 1) or ((x2 shr 6) and $01)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 1] := Byte((x2 shl 2) or ((x1 shr 5) and $03)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 2] := Byte((x1 shl 3) or ((x2 shr 4) and $07)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 3] := Byte((x2 shl 4) or ((x1 shr 3) and $0F)); inc(srcInd); x2 := InvAlphabet[Ord(data[srcInd])]; result[i + 4] := Byte((x1 shl 5) or ((x2 shr 2) and $1F)); inc(srcInd); x1 := InvAlphabet[Ord(data[srcInd])]; result[i + 5] := Byte((x2 shl 6) or ((x1 shr 1) and $3F)); end; end; end; end.
{..............................................................................} { Summary Demo how to create a new symbol in the library } { Copyright (c) 2004 by Altium Limited } {..............................................................................} {..............................................................................} Procedure CreateALibComponent; Var CurrentLib : ISch_Lib; SchComponent : ISch_Component; R : ISch_Rectangle; P1, P2 : ISch_Pin; Begin If SchServer = Nil Then Exit; CurrentLib := SchServer.GetCurrentSchDocument; If CurrentLib = Nil Then Exit; // Check if the document is a Schematic Libary document first If CurrentLib.ObjectID <> eSchLib Then Begin ShowError('Please open schematic library.'); Exit; End; // Create a library component (a page of the library is created). SchComponent := SchServer.SchObjectFactory(eSchComponent, eCreate_Default); If SchComponent = Nil Then Exit; // Set up parameters for the library component. SchComponent.CurrentPartID := 1; SchComponent.DisplayMode := 0; // Define the LibReference and add the component to the library. SchComponent.LibReference := 'Custom'; // Create a rectangle object for the new library component. R := SchServer.SchObjectFactory(eRectangle, eCreate_Default); If R = Nil Then Exit; // Define the rectangle parameters. R.LineWidth := eSmall; R.Location := Point(MilsToCoord(390), MilsToCoord(90)); R.Corner := Point(MilsToCoord(790), MilsToCoord(860)); R.Color := $00FFFF; // YELLOW R.AreaColor := $000000; // BLACK R.IsSolid := True; R.OwnerPartId := CurrentLib.CurrentSchComponent.CurrentPartID; R.OwnerPartDisplayMode := CurrentLib.CurrentSchComponent.DisplayMode; // Create two pin objects for the new library component. P1 := SchServer.SchObjectFactory(ePin, eCreate_Default); If P1 = Nil Then Exit; // Define the pin parameters. P1.Location := Point(MilsToCoord(400), MilsToCoord(330)); P1.Color := $000000; // YELLOW P1.Orientation := eRotate180; P1.Designator := '0'; P1.Name := '0'; P1.OwnerPartId := CurrentLib.CurrentSchComponent.CurrentPartID; P1.OwnerPartDisplayMode := CurrentLib.CurrentSchComponent.DisplayMode; P2 := SchServer.SchObjectFactory(ePin, eCreate_Default); If P2 = Nil Then Exit; // Define the pin parameters. P2.Location := Point(MilsToCoord(400), MilsToCoord(750)); P2.Color := $000000; // YELLOW P2.Orientation := eRotate180; P2.Designator := '1'; P2.Name := '1'; P2.OwnerPartId := CurrentLib.CurrentSchComponent.CurrentPartID; P2.OwnerPartDisplayMode := CurrentLib.CurrentSchComponent.DisplayMode; // Add the rectangle and the pins to the component (the new page of library component). SchComponent.AddSchObject(P1); SchComponent.AddSchObject(P2); SchComponent.AddSchObject(R); SchComponent.Designator.Text := 'U'; SchComponent.ComponentDescription := 'Custom IC'; CurrentLib.AddSchComponent(SchComponent); // Send a system notification that a new component has been added to the library. SchServer.RobotManager.SendMessage(nil, c_BroadCast, SCHM_PrimitiveRegistration, SCHComponent.I_ObjectAddress); CurrentLib.CurrentSchComponent := SchComponent; // Refresh library. CurrentLib.GraphicallyInvalidate; End; {..............................................................................} {..............................................................................}
unit uNewModelReceipt; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, StdCtrls, siComp, siLangRT, Buttons, ExtCtrls; type TNewModelReceipt = class(TFrmParentAll) lblReceiptText: TLabel; mmReceiptText: TMemo; btOK: TButton; procedure btOKClick(Sender: TObject); private fIDModel : Integer; procedure InsertModelReceipt; function ValidadeReceiptText: Boolean; public function Start(IDModel: Integer):Boolean; end; implementation uses uDM, uSystemConst, uMsgConstant, uMsgBox; {$R *.dfm} { TNewModelReceipt } procedure TNewModelReceipt.InsertModelReceipt; var sSQL: String; begin sSQL := 'INSERT Inv_ModelReceipt (IDModelReceipt, IDModel, ReceiptText)' + 'VALUES (' + IntToStr(DM.GetNextID(MR_MODEL_RECEIPT_ID)) + ',' + IntToStr(fIDModel) + ',' + QuotedStr(mmReceiptText.Text) + ' )'; DM.RunSQL(sSQL); end; function TNewModelReceipt.Start(IDModel: Integer): Boolean; begin fIDModel := IDModel; Result := True; ShowModal; end; procedure TNewModelReceipt.btOKClick(Sender: TObject); begin inherited; if ValidadeReceiptText then InsertModelReceipt else ModalResult := mrNone; end; function TNewModelReceipt.ValidadeReceiptText: Boolean; begin Result := True; if mmReceiptText.Text = '' then begin MsgBox(MSG_CRT_NO_RECEIPT_TEXT, vbInformation + vbOkOnly); mmReceiptText.SetFocus; Result := False; Exit; end; end; end.
unit Main; {$mode objfpc}{$H+} //======================================================================================== // // Unit : Main.pas // // Description : // // Called By : ManufacturerDB : TfrmManufacturerDB.FormShow // AppInit : Initialize // // Calls : AppFinal : Finalize // AppInit : Initialize // AppSettings : frmSettings.ShowModal // SuppliersTable : frmSuppliersTable.CreateSuppliersTable // frmSuppliersTable.ShowModal // // Ver. : 1.0.0 // // Date : 22 Dec 2019 // //======================================================================================== interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus, ComCtrls, // Application Units AppFinal, AppInit, AppSettings, Logbook, RVData, SuppliersTable // HULibrary Units ; type { TfrmMain } TfrmMain = class(TForm) mnuLogbooksSaveLogbook: TMenuItem; mnuSettingsApplicationDatabase: TMenuItem; mnuSettings: TMenuItem; muLogbooksSep2: TMenuItem; mnuLogbooksPrint: TMenuItem; mnuLogbooksPrinterSetup: TMenuItem; mnuLogbooksSep1: TMenuItem; mnuLogbooksDeleteLogbook: TMenuItem; mnuLogbooksOpenLogbook: TMenuItem; mnuLogbooksNewLogbook: TMenuItem; mnuLogbooksExit: TMenuItem; mnuLogbooks: TMenuItem; mnuMain: TMainMenu; StatusBar1: TStatusBar; ToolBar1: TToolBar; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure mnuLogbooksNewLogbookClick(Sender: TObject); procedure mnuLogbooksExitClick(Sender: TObject); procedure mnuLogbooksOpenLogbookClick(Sender: TObject); procedure mnuLogbooksPrintClick(Sender: TObject); procedure mnuLogbooksPrinterSetupClick(Sender: TObject); procedure mnuLogbooksDeleteLogbookClick(Sender: TObject); procedure mnuLogbooksSaveClick(Sender: TObject); procedure mnuSettingsApplicationDatabaseClick(Sender: TObject); private public end;// TfrmMain = class(TForm) var frmMain: TfrmMain; procedure TerminateApp; implementation {$R *.lfm} //======================================================================================== // PRIVATE CONSTANTS //======================================================================================== //======================================================================================== // PUBLIC CONSTANTS //======================================================================================== //======================================================================================== // PRIVATE VARIABLES //======================================================================================== //======================================================================================== // PUBLIC VARIABLES //======================================================================================== //======================================================================================== // PRIVATE ROUTINES //======================================================================================== //======================================================================================== // PUBLIC ROUTINES //======================================================================================== procedure TerminateApp; begin showmessage('Terminating Application'); Halt; end;// procedure TerminateApp //======================================================================================== // PROPERTY ROUTINES //======================================================================================== //======================================================================================== // MENU ROUTINES //======================================================================================== //========== // mnuLogbooksClick //========== procedure TfrmMain.mnuLogbooksNewLogbookClick(Sender: TObject); begin frmLogbook.ShowModal; end;// procedure TfrmMain.mnuLogbooksNewClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksOpenLogbookClick(Sender: TObject); begin showmessage('Open Logbook'); end;// procedure TfrmMain.mnuLogbooksOpenLogbookClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksSaveClick(Sender: TObject); begin showmessage('Save Logbook'); end;// procedure TfrmMain.mnuLogbooksSaveClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksDeleteLogbookClick(Sender: TObject); begin showmessage('Delete Logbook'); end;// procedure TfrmMain.mnuLogbooksDeleteClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksPrinterSetupClick(Sender: TObject); begin showmessage('Printer Setup'); end;// procedure TfrmMain.mnuLogbooksPrinterSetupClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksPrintClick(Sender: TObject); begin showmessage('Print'); end;// procedure TfrmMain.mnuLogbooksPrintClick //---------------------------------------------------------------------------------------- procedure TfrmMain.mnuLogbooksExitClick(Sender: TObject); begin showmessage('Exit'); Close; end;// procedure TfrmMain.mnuFileExitClick //======================================================================================== //========== // mnuSettingsClick //========== procedure TfrmMain.mnuSettingsApplicationDatabaseClick(Sender: TObject); begin frmSettings.ShowModal; end;// procedure TfrmMain.mnuSettingsApplicationDatabaseClick //======================================================================================== // COMMAND BUTTON ROUTINES //======================================================================================== //======================================================================================== // CONTROL ROUTINES //======================================================================================== //======================================================================================== // FILE ROUTINES //======================================================================================== //======================================================================================== // FORM ROUTINES //======================================================================================== procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin showmessage('On Close'); Finalize; end;// procedure TfrmMain.FormClose //======================================================================================== procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin showmessage('On Close Query') end;// procedure TfrmMain.FormCloseQuery //======================================================================================== procedure TfrmMain.FormCreate(Sender: TObject); begin end;// procedure TfrmMain.FormCreate //======================================================================================== procedure TfrmMain.FormShow(Sender: TObject); begin Initialize; end;// procedure TfrmMain.FormShow(Sender: TObject); //======================================================================================== end.// unit Main
unit LODPostProcessing; interface {$INCLUDE source/Global_Conditionals.inc} uses LOD; type TLODPostProcessing = class private FQuality: integer; public constructor Create(_Quality: integer); procedure Execute(var _LOD: TLOD); end; implementation uses GLConstants, MeshSmoothSBGames, DistanceFormulas, MeshConvertQuadsToTris, MeshConvertQuadsTo48Tris, MeshRecalculateNormals, MeshSetVertexNormals, MeshSetVertexColours; constructor TLODPostProcessing.Create(_Quality: Integer); begin FQuality := _Quality; end; procedure TLODPostProcessing.Execute(var _LOD: TLOD); var MeshSmooth: TMeshSmoothSBGAMES2010; MeshConvertQuadsToTris: TMeshConvertQuadsToTris; MeshConvertQuadsTo48Tris: TMeshConvertQuadsTo48Tris; MeshRecalculateNormals: TMeshRecalculateNormals; MeshSetVertexNormals : TMeshSetVertexNormals; MeshSetVertexColours : TMeshSetVertexColours; begin case (FQuality) of C_QUALITY_LANCZOS_QUADS: begin MeshSmooth := TMeshSmoothSBGAMES2010.Create(_LOD); MeshSmooth.DistanceFunction := GetLanczosInvACDistance; MeshSmooth.Execute; MeshSmooth.Free; end; C_QUALITY_2LANCZOS_4TRIS: begin MeshSmooth := TMeshSmoothSBGAMES2010.Create(_LOD); MeshSmooth.DistanceFunction := GetLanczosInvACDistance; MeshSmooth.Execute; MeshSmooth.Free; MeshRecalculateNormals := TMeshRecalculateNormals.Create(_LOD); MeshRecalculateNormals.Execute; MeshRecalculateNormals.Free; MeshSetVertexNormals := TMeshSetVertexNormals.Create(_LOD); MeshSetVertexNormals.Execute; MeshSetVertexNormals.Free; MeshSetVertexColours := TMeshSetVertexColours.Create(_LOD); MeshSetVertexColours.Execute; MeshSetVertexColours.Free; MeshConvertQuadsTo48Tris := TMeshConvertQuadsTo48Tris.Create(_LOD); MeshConvertQuadsTo48Tris.Execute; MeshConvertQuadsTo48Tris.Free; end; C_QUALITY_LANCZOS_TRIS: begin MeshSmooth := TMeshSmoothSBGAMES2010.Create(_LOD); MeshSmooth.DistanceFunction := GetLanczosInvACDistance; MeshSmooth.Execute; MeshSmooth.Free; MeshConvertQuadsToTris := TMeshConvertQuadsToTris.Create(_LOD); MeshConvertQuadsToTris.Execute; MeshConvertQuadsToTris.Free; MeshRecalculateNormals := TMeshRecalculateNormals.Create(_LOD); MeshRecalculateNormals.Execute; MeshRecalculateNormals.Free; MeshSetVertexNormals := TMeshSetVertexNormals.Create(_LOD); MeshSetVertexNormals.Execute; MeshSetVertexNormals.Free; MeshSetVertexColours := TMeshSetVertexColours.Create(_LOD); MeshSetVertexColours.Execute; MeshSetVertexColours.Free; end; C_QUALITY_SMOOTH_MANIFOLD: begin MeshSetVertexNormals := TMeshSetVertexNormals.Create(_LOD); MeshSetVertexNormals.Execute; MeshSetVertexNormals.Free; MeshSetVertexColours := TMeshSetVertexColours.Create(_LOD); MeshSetVertexColours.Execute; MeshSetVertexColours.Free; end; end; end; end.
unit uRemoteAccessDemoMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, apiRemote; const sCaption = 'Remote Access Demo'; sCaptionWithVersion = 'Remote Access Demo - AIMP v%s Build %d is running'; type { TfrmRemoteAccessDemo } TfrmRemoteAccessDemo = class(TForm) btnNext: TButton; btnPause: TButton; btnPlay: TButton; btnPrev: TButton; btnStop: TButton; imAlbumArt: TImage; lbDetails: TLabel; lbTitle: TLabel; pnlInfo: TPanel; tbSeekBar: TTrackBar; tmUpdate: TTimer; lbPlayerState: TLabel; procedure btnNextClick(Sender: TObject); procedure btnPauseClick(Sender: TObject); procedure btnPlayClick(Sender: TObject); procedure btnPrevClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tmUpdateTimer(Sender: TObject); procedure tbSeekBarChange(Sender: TObject); private FAIMPRemoteHandle: HWND; FChangeLockCount: Integer; procedure SetAIMPRemoteHandle(const Value: HWND); protected procedure WMAIMPNotify(var Message: TMessage); message WM_AIMP_NOTIFY; procedure WMCopyData(var Message: TWMCopyData); message WM_COPYDATA; public procedure AIMPExecuteCommand(ACommand: Integer); function AIMPGetPropertyValue(APropertyID: Integer): Integer; function AIMPSetPropertyValue(APropertyID, AValue: Integer): Boolean; procedure UpdatePlayerState; procedure UpdateTrackInfo; procedure UpdateTrackPositionInfo; procedure UpdateVersionInfo; // property AIMPRemoteHandle: HWND read FAIMPRemoteHandle write SetAIMPRemoteHandle; end; var frmRemoteAccessDemo: TfrmRemoteAccessDemo; implementation uses // Built-in in D2010 or newer // For old Delphi versions you can download it from: http://pngdelphi.sourceforge.net/ PngImage; {$R *.dfm} { TfrmRemoteAccessDemo } function TfrmRemoteAccessDemo.AIMPGetPropertyValue(APropertyID: Integer): Integer; begin if AIMPRemoteHandle <> 0 then Result := SendMessage(AIMPRemoteHandle, WM_AIMP_PROPERTY, APropertyID or AIMP_RA_PROPVALUE_GET, 0) else Result := 0; end; function TfrmRemoteAccessDemo.AIMPSetPropertyValue(APropertyID, AValue: Integer): Boolean; begin if AIMPRemoteHandle <> 0 then Result := SendMessage(AIMPRemoteHandle, WM_AIMP_PROPERTY, APropertyID or AIMP_RA_PROPVALUE_SET, AValue) <> 0 else Result := False end; procedure TfrmRemoteAccessDemo.AIMPExecuteCommand(ACommand: Integer); begin if AIMPRemoteHandle <> 0 then SendMessage(AIMPRemoteHandle, WM_AIMP_COMMAND, ACommand, 0); end; procedure TfrmRemoteAccessDemo.SetAIMPRemoteHandle(const Value: HWND); begin if FAIMPRemoteHandle <> Value then begin if FAIMPRemoteHandle <> 0 then begin // Unregister notification listener from old window SendMessage(FAIMPRemoteHandle, WM_AIMP_COMMAND, AIMP_RA_CMD_UNREGISTER_NOTIFY, Handle); FAIMPRemoteHandle := 0; end; if Value <> 0then begin FAIMPRemoteHandle := Value; // Register notification listener to new window SendMessage(FAIMPRemoteHandle, WM_AIMP_COMMAND, AIMP_RA_CMD_REGISTER_NOTIFY, Handle); end; UpdatePlayerState; UpdateTrackInfo; UpdateTrackPositionInfo; UpdateVersionInfo; end; end; procedure TfrmRemoteAccessDemo.FormDestroy(Sender: TObject); begin AIMPRemoteHandle := 0; // unregister end; procedure TfrmRemoteAccessDemo.UpdatePlayerState; begin case AIMPGetPropertyValue(AIMP_RA_PROPERTY_PLAYER_STATE) of 0: lbPlayerState.Caption := 'Stopped'; 1: lbPlayerState.Caption := 'Paused'; 2: lbPlayerState.Caption := ''; end; end; procedure TfrmRemoteAccessDemo.UpdateTrackInfo; function ExtractString(var B: PByte; ALength: Integer): WideString; begin SetString(Result, PWideChar(B), ALength); Inc(B, SizeOf(WideChar) * ALength); end; var AAlbum: WideString; AArtist: WideString; ABuffer: PByte; ADate: WideString; AFile: THandle; AFileName: WideString; AGenre: WideString; AInfo: PAIMPRemoteFileInfo; ATitle: WideString; begin lbTitle.Caption := ''; lbDetails.Caption := ''; // Load info about playable file from shared memory-mapped file AFile := OpenFileMapping(FILE_MAP_READ, True, AIMPRemoteAccessClass); try AInfo := MapViewOfFile(AFile, FILE_MAP_READ, 0, 0, AIMPRemoteAccessMapFileSize); if AInfo <> nil then try if AInfo <> nil then begin ABuffer := Pointer(NativeUInt(AInfo) + SizeOf(TAIMPRemoteFileInfo)); // Extract data from the buffer AAlbum := ExtractString(ABuffer, AInfo^.AlbumLength); AArtist := ExtractString(ABuffer, AInfo^.ArtistLength); ADate := ExtractString(ABuffer, AInfo^.DateLength); AFileName := ExtractString(ABuffer, AInfo^.FileNameLength); AGenre := ExtractString(ABuffer, AInfo^.GenreLength); ATitle := ExtractString(ABuffer, AInfo^.TitleLength); // Show the information lbTitle.Caption := ATitle; lbDetails.Caption := AAlbum + #13#10 + AArtist + #13#10 + ADate + #13#10 + AGenre + #13#10 + Format('%d Hz, %d kbps, %d chans', [AInfo^.SampleRate, AInfo^.BitRate, AInfo^.Channels]) + #13#10 + Format('%d seconds, %d bytes', [AInfo^.Duration div 1000, AInfo^.FileSize]); end; finally UnmapViewOfFile(AInfo); end; finally CloseHandle(AFile); end; // Send request for AlbumArt image, answer will be send in WM_COPYDATA if SendMessage(AIMPRemoteHandle, WM_AIMP_COMMAND, AIMP_RA_CMD_GET_ALBUMART, Handle) = 0 then imAlbumArt.Picture.Graphic := nil; end; procedure TfrmRemoteAccessDemo.UpdateTrackPositionInfo; begin Inc(FChangeLockCount); try tbSeekBar.Max := AIMPGetPropertyValue(AIMP_RA_PROPERTY_PLAYER_DURATION) div 1000; tbSeekBar.Position := AIMPGetPropertyValue(AIMP_RA_PROPERTY_PLAYER_POSITION) div 1000; finally Dec(FChangeLockCount); end; end; procedure TfrmRemoteAccessDemo.UpdateVersionInfo; var AVersion: Cardinal; begin AVersion := AIMPGetPropertyValue(AIMP_RA_PROPERTY_VERSION); if AVersion <> 0 then Caption := Format(sCaptionWithVersion, [FormatFloat('0.00', HiWord(AVersion) / 100), LoWord(AVersion)]) else Caption := sCaption; end; procedure TfrmRemoteAccessDemo.WMAIMPNotify(var Message: TMessage); begin case Message.WParam of AIMP_RA_NOTIFY_TRACK_INFO: UpdateTrackInfo; AIMP_RA_NOTIFY_PROPERTY: case Message.LParam of AIMP_RA_PROPERTY_PLAYER_STATE: UpdatePlayerState; AIMP_RA_PROPERTY_PLAYER_POSITION, AIMP_RA_PROPERTY_PLAYER_DURATION: UpdateTrackPositionInfo; end; end; end; procedure TfrmRemoteAccessDemo.WMCopyData(var Message: TWMCopyData); var AImage: TPngImage; AStream: TMemoryStream; begin if Message.CopyDataStruct^.dwData = WM_AIMP_COPYDATA_ALBUMART_ID then begin AStream := TMemoryStream.Create; try AStream.WriteBuffer(Message.CopyDataStruct^.lpData^, Message.CopyDataStruct^.cbData); AStream.Position := 0; AImage := TPngImage.Create; try AImage.LoadFromStream(AStream); imAlbumArt.Picture.Graphic := AImage; except imAlbumArt.Picture.Graphic := nil; AImage.Free; end; finally AStream.Free; end; end; end; procedure TfrmRemoteAccessDemo.tbSeekBarChange(Sender: TObject); begin if FChangeLockCount = 0 then AIMPSetPropertyValue(AIMP_RA_PROPERTY_PLAYER_POSITION, tbSeekBar.Position * 1000); end; procedure TfrmRemoteAccessDemo.tmUpdateTimer(Sender: TObject); begin // Update AIMP Handle AIMPRemoteHandle := FindWindow(AIMPRemoteAccessClass, AIMPRemoteAccessClass); end; procedure TfrmRemoteAccessDemo.btnNextClick(Sender: TObject); begin AIMPExecuteCommand(AIMP_RA_CMD_NEXT); end; procedure TfrmRemoteAccessDemo.btnPauseClick(Sender: TObject); begin AIMPExecuteCommand(AIMP_RA_CMD_PAUSE); end; procedure TfrmRemoteAccessDemo.btnPlayClick(Sender: TObject); begin AIMPExecuteCommand(AIMP_RA_CMD_PLAY); end; procedure TfrmRemoteAccessDemo.btnPrevClick(Sender: TObject); begin AIMPExecuteCommand(AIMP_RA_CMD_PREV); end; procedure TfrmRemoteAccessDemo.btnStopClick(Sender: TObject); begin AIMPExecuteCommand(AIMP_RA_CMD_STOP); end; end.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit EquipmentItem *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2007/10/25] Helios - RaX ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ EquipmentItem - Any sort of item that can be equipped to a character/pet/etc. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2007/10/25] RaX - Created. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit EquipmentItem; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} Item, ItemTypes, GameTypes {Third Party} //none ; type (*= CLASS =====================================================================* TItem *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* Equipment Item - any item that can be equipped. *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/10/25] RaX - Created. [2007/10/26] RaX - Added numerous equipment related properties. *=============================================================================*) TEquipmentItem = class(TItem) protected fViewID : LongWord; //The view id, for the client to show the correct sprite. fEquipmentType : TEquipTypes;//The equipment type(IE::Sword, Armor) fEquipmentLocation : TEquipLocations; //What equipment locations this item resides in fAttack : Word; //this item's attack fDefense : Word; //This item's defense fRange : Word; //The range of this item. fSlots : Byte; //The number of slots this item has. fJob : LongWord; //The required job. fGender : TGenders; //The required gender, if applicable. fMinimumLevel : Word;//The minimum base level required to equip this item fWeaponLevel : Byte; //The weapon level of an item. fOnEquip : String;//Script function, executes when the item is equipped. fOnDisarm : String;//Script Function, executes when the item is unequipped. fOnAttack : String;//Script function, executes when an Item is used to attack fOnDefend : String;//Script function, executes when an Item is used to defend. public Refineable : Boolean; Property ViewID : LongWord Read fViewID Write fViewID; Property EquipmentType: TEquipTypes Read fEquipmentType write fEquipmentType; Property EquipmentLocation: TEquipLocations Read fEquipmentLocation write fEquipmentLocation; Property Slots : Byte Read fSlots Write fSlots; Property Attack : Word Read fAttack Write fAttack; Property Defense : Word Read fDefense Write fDefense; Property Range : Word Read fRange Write fRange; Property Job : LongWord Read fJob Write fJob; Property Gender : TGenders Read fGender Write fGender; Property MinimumLevel : Word Read fMinimumLevel Write fMinimumLevel; Property WeaponLevel : Byte Read fWeaponLevel Write fWeaponLevel; Property OnEquip : String Read fOnEquip Write fOnEquip; Property OnDisarm : String Read fOnDisarm Write fOnDisarm; Property OnAttack : String Read fOnAttack Write fOnAttack; Property OnDefend : String Read fOnDefend Write fOnDefend; Constructor Create; Destructor Destroy;override; End;(* TItem *== CLASS ====================================================================*) implementation //uses {RTL/VCL} {Project} {Third Party} //none (*- Cons ----------------------------------------------------------------------* TEquipmentItem.Create -------------------------------------------------------------------------------- Overview: -- Creates our TEquipmentItem. -- Post: -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/10/23] RaX - Created. *-----------------------------------------------------------------------------*) Constructor TEquipmentItem.Create; begin inherited; End; (* Cons TEquipmentItem.Create *-----------------------------------------------------------------------------*) (*- Dest ----------------------------------------------------------------------* TEquipmentItem.Destroy -- Overview: -- Destroys our TEquipmentItem -- Pre: Post: -- Revisions: -- [2007/10/25] RaX - Created. *-----------------------------------------------------------------------------*) Destructor TEquipmentItem.Destroy; Begin //Pre //-- //Always clean up your owned objects/memory first, then call ancestor. inherited; End;(* Dest TEquipmentItem.Destroy *-----------------------------------------------------------------------------*) end.
unit DataAccess.Base; interface uses Data.DB, System.SysUtils; type TDAOConfig = class strict private FAutoOpenDataSet: Boolean; public property AutoOpenDataSet: Boolean read FAutoOpenDataSet write FAutoOpenDataSet; end; TBaseDAO = class(TInterfacedObject) strict private FConfig: TDAOConfig; strict protected FDataSet: TDataSet; FDataSetReady: Boolean; procedure BindDataSetFields(); virtual; abstract; public procedure VerifyIsStateValid; constructor Create(); destructor Destroy; override; function GetConfig: TDAOConfig; procedure LinkDataSet(dataset: TDataSet; isOpen: Boolean); function Next: Boolean; end; implementation constructor TBaseDAO.Create; begin inherited; FConfig := TDAOConfig.Create(); end; destructor TBaseDAO.Destroy; begin FConfig.Free; inherited; end; function TBaseDAO.GetConfig: TDAOConfig; begin Result := FConfig; end; procedure TBaseDAO.VerifyIsStateValid; begin if not FDataSetReady then raise Exception.Create ('DAO Object isnt linked with dataset. Please call LinkDataSet method in advance.') else if not(FDataSet.Active) then raise Exception.Create ('Dataset is closed. Cant manipulate on the closed dataset using DAO object'); end; procedure TBaseDAO.LinkDataSet(dataset: TDataSet; isOpen: Boolean); begin FDataSet := dataset; if isOpen and not(dataset.Active) then dataset.Open; BindDataSetFields(); FDataSetReady := true; end; function TBaseDAO.Next: Boolean; begin VerifyIsStateValid; FDataSet.Next; Result := not FDataSet.Eof; end; end.
unit LrDocument; interface uses SysUtils, Classes, Controls, ActnList, Contnrs, Dialogs; type TLrDocumentManager = class; TLrDocumentAction = TAction; // TLrController = class(TComponent) public procedure Activate; virtual; procedure Deactivate; virtual; procedure LazyUpdate; virtual; end; // TLrDocument = class private FManager: TLrDocumentManager; FModified: Boolean; FPath: string; FReadOnly: Boolean; FUntitled: Boolean; FController: TLrController; protected function GetActive: Boolean; function GetDisplayName: string; virtual; function GetExtension: string; virtual; function GetFileName: string; function GetFilter: string; virtual; function GetPath: string; virtual; procedure SetActive(const Value: Boolean); procedure SetModified(const Value: Boolean); virtual; procedure SetPath(const Value: string); virtual; procedure SetReadOnly(const Value: Boolean); virtual; procedure SetUntitled(const Value: Boolean); virtual; protected procedure Change; virtual; procedure CloseItem; public constructor Create(inManager: TLrDocumentManager; const inPath: string = ''); virtual; destructor Destroy; override; function CanClose: Boolean; virtual; function EnableSave: Boolean; virtual; function EnableSaveAs: Boolean; virtual; function SaveAs: Boolean; virtual; procedure Activate; virtual; procedure ChangeEvent(inSender: TObject); virtual; procedure Close; virtual; procedure Deactivate; virtual; procedure DisEnableAction(inAction: TLrDocumentAction); virtual; procedure LazyUpdate; virtual; procedure Open; virtual; procedure PerformAction(inAction: TLrDocumentAction); virtual; procedure Save; virtual; public property Active: Boolean read GetActive write SetActive; property Controller: TLrController read FController write FController; property DisplayName: string read GetDisplayName; property Extension: string read GetExtension; property FileName: string read GetFileName; property Filter: string read GetFilter; property Manager: TLrDocumentManager read FManager write FManager; property Modified: Boolean read FModified write SetModified; property Path: string read GetPath write SetPath; property ReadOnly: Boolean read FReadOnly write SetReadOnly; property Untitled: Boolean read FUntitled write SetUntitled; end; // TLrDocumentClass = class of TLrDocument; TLrOpenDocumentEvent = function(inManager: TLrDocumentManager; const inPath: string): TLrDocument of object; TLrSaveAsDocumentEvent = procedure(inSender: TObject; inDocument: TLrDocument; const inOldPath, inNewPath: string) of object; TLrDocumentEvent = procedure(inSender: TObject; inDocument: TLrDocument) of object; // TLrDocumentProfile = class DocumentClass: TLrDocumentClass; Extensions: array of string; end; // TLrDocumentManager = class private { Private declarations } FCurrent: TLrDocument; FDefaultPath: string; FDocumentTypes: TStringList; FItems: TObjectList; FOnAfterOpen: TLrDocumentEvent; FOnClose: TNotifyEvent; FOnCreateController: TLrDocumentEvent; FOnCurrentChanged: TNotifyEvent; FOnCurrentChanging: TNotifyEvent; FOnOpen: TLrOpenDocumentEvent; FOnSaveAs: TLrSaveAsDocumentEvent; FOnUpdateDocument: TLrDocumentEvent; FSaveDialog: TSaveDialog; FUpdate: Integer; protected function GetCount: Integer; function GetItems(inIndex: Integer): TLrDocument; procedure SetCurrent(const Value: TLrDocument); procedure SetDefaultPath(const Value: string); procedure SetItems(inIndex: Integer; const Value: TLrDocument); protected function GetFileFilter: string; function NewName: string; function OpenItem(const inPath: string): TLrDocument; function UntitledCount: Integer; procedure CloseItem(inItem: TLrDocument); procedure CloseUntitled; procedure CurrentChanged; procedure CurrentChanging; procedure CurrentClosing; procedure Select(inItem: TLrDocument); procedure ValidateCurrent(inPivot: Integer); public { Public declarations } constructor Create; destructor Destroy; override; function CloseAll: Boolean; function DocumentClassFromExtension(const inExt: string): TLrDocumentClass; function EnableClose: Boolean; function EnableSave: Boolean; virtual; function EnableSaveAs: Boolean; virtual; function Find(const inPath: string): Integer; function Open(const inPath: string): Boolean; procedure BeginUpdate; procedure Close(inItem: TLrDocument); procedure DisEnableAction(inAction: TLrDocumentAction); virtual; procedure DocumentChanged(inItem: TLrDocument); procedure EndUpdate; procedure New(inClass: TLrDocumentClass); procedure PerformAction(inAction: TLrDocumentAction); virtual; procedure RegisterExtension(const inExt: string; inDocumentClass: TLrDocumentClass); overload; procedure RegisterExtensions(const inExts: array of string; inDocumentClass: TLrDocumentClass); overload; procedure Save(inItem: TLrDocument = nil); procedure SaveAs(inItem: TLrDocument = nil); procedure UpdateDocument(inDocument: TLrDocument); public NilDocument: TLrDocument; property Count: Integer read GetCount; property Current: TLrDocument read FCurrent write SetCurrent; property DefaultPath: string read FDefaultPath write SetDefaultPath; property DocumentTypes: TStringList read FDocumentTypes; property Items[inIndex: Integer]: TLrDocument read GetItems write SetItems; default; property OnClose: TNotifyEvent read FOnClose write FOnClose; property OnCreateController: TLrDocumentEvent read FOnCreateController write FOnCreateController; property OnCurrentChanged: TNotifyEvent read FOnCurrentChanged write FOnCurrentChanged; property OnCurrentChanging: TNotifyEvent read FOnCurrentChanging write FOnCurrentChanging; property OnOpen: TLrOpenDocumentEvent read FOnOpen write FOnOpen; property OnAfterOpen: TLrDocumentEvent read FOnAfterOpen write FOnAfterOpen; property OnSaveAs: TLrSaveAsDocumentEvent read FOnSaveAs write FOnSaveAs; property OnUpdateDocument: TLrDocumentEvent read FOnUpdateDocument write FOnUpdateDocument; property SaveDialog: TSaveDialog read FSaveDialog; end; implementation { TLrController } procedure TLrController.Activate; begin // end; procedure TLrController.Deactivate; begin // end; procedure TLrController.LazyUpdate; begin // end; { TLrDocument } constructor TLrDocument.Create(inManager: TLrDocumentManager; const inPath: string); begin FManager := inManager; FPath := inPath; end; destructor TLrDocument.Destroy; begin Controller.Free; inherited; end; procedure TLrDocument.Change; begin Modified := true; end; procedure TLrDocument.ChangeEvent(inSender: TObject); begin Change; end; procedure TLrDocument.Activate; begin if Controller <> nil then Controller.Activate; end; procedure TLrDocument.Deactivate; begin if Controller <> nil then Controller.Deactivate; end; function TLrDocument.GetActive: Boolean; begin Result := Manager.Current = Self; end; procedure TLrDocument.SetActive(const Value: Boolean); begin if Value and not Active then Manager.Select(Self); end; procedure TLrDocument.LazyUpdate; begin if Active and (Controller <> nil) then Controller.LazyUpdate; end; procedure TLrDocument.Open; begin // end; function TLrDocument.CanClose: Boolean; var mr: TModalResult; begin Result := true; if Modified then begin mr := MessageDlg('Save changes to "' + DisplayName + '" before closing?', mtConfirmation, mbYesNoCancel, 0); if mr = mrCancel then Result := false else if mr = mrYes then begin if Untitled then Result := SaveAs else Save; end; end; end; procedure TLrDocument.CloseItem; begin Deactivate; FManager.CloseItem(Self); end; procedure TLrDocument.Close; begin Deactivate; FManager.Close(Self); end; function TLrDocument.GetFileName: string; begin Result := ExtractFileName(Path); end; function TLrDocument.GetDisplayName: string; begin Result := ChangeFileExt(FileName, ''); end; procedure TLrDocument.SetPath(const Value: string); begin FPath := Value; Change; end; procedure TLrDocument.DisEnableAction(inAction: TLrDocumentAction); begin inAction.Enabled := false; end; procedure TLrDocument.PerformAction(inAction: TLrDocumentAction); begin // end; procedure TLrDocument.SetUntitled(const Value: Boolean); begin FUntitled := Value; end; procedure TLrDocument.SetModified(const Value: Boolean); begin FModified := Value; end; function TLrDocument.EnableSaveAs: Boolean; begin Result := not ReadOnly; end; function TLrDocument.EnableSave: Boolean; begin Result := EnableSaveAs and Modified; end; procedure TLrDocument.Save; begin LazyUpdate; Modified := false; end; function TLrDocument.SaveAs: Boolean; begin //LazyUpdate; with Manager.SaveDialog do begin FileName := Path; DefaultExt := Extension; Filter := Self.Filter; Result := Execute; if Result then begin Untitled := false; Path := FileName; Save; end; end; end; procedure TLrDocument.SetReadOnly(const Value: Boolean); begin FReadOnly := Value; end; function TLrDocument.GetPath: string; begin Result := FPath; end; function TLrDocument.GetExtension: string; begin Result := ExtractFileExt(Path); end; function TLrDocument.GetFilter: string; begin if GetExtension = '' then Result := 'Any File (*.*)|*.*' else Result := Format('Document File (*.%s)|*.%0:s', [ GetExtension ]); end; { TLrDocumentManager } constructor TLrDocumentManager.Create; begin FSaveDialog := TSaveDialog.Create(nil); FItems := TObjectList.Create; NilDocument := TLrDocument.Create(Self, ''); NilDocument.ReadOnly := true; FCurrent := NilDocument; FDocumentTypes := TStringList.Create; //DefaultPath := HomeFolder; end; destructor TLrDocumentManager.Destroy; begin FDocumentTypes.Free; FItems.Free; FSaveDialog.Free; inherited; end; procedure TLrDocumentManager.RegisterExtension(const inExt: string; inDocumentClass: TLrDocumentClass); begin DocumentTypes.AddObject(inExt, TObject(inDocumentClass)); end; procedure TLrDocumentManager.RegisterExtensions(const inExts: array of string; inDocumentClass: TLrDocumentClass); var i: Integer; begin for i := 0 to Pred(Length(inExts)) do RegisterExtension(inExts[i], inDocumentClass); end; function TLrDocumentManager.GetFileFilter: string; var i: Integer; s0, s1: string; begin for i := 0 to Pred(DocumentTypes.Count) do begin if i <> 0 then begin s0 := s0 + ', '; s1 := s1 + '; '; end; s0 := s0 + '*' + DocumentTypes[i]; s1 := s1 + '*' + DocumentTypes[i]; end; Result := '(' + s0 + ')|' + s1; end; function TLrDocumentManager.DocumentClassFromExtension( const inExt: string): TLrDocumentClass; var i: Integer; begin for i := 0 to Pred(DocumentTypes.Count) do if DocumentTypes[i] = inExt then begin Result := TLrDocumentClass(DocumentTypes.Objects[i]); exit; end; Result := nil; end; procedure TLrDocumentManager.SetDefaultPath(const Value: string); begin if Value = '' then FDefaultPath := '' else FDefaultPath := IncludeTrailingPathDelimiter(Value); SaveDialog.InitialDir := FDefaultPath; end; function TLrDocumentManager.GetCount: Integer; begin Result := FItems.Count; end; function TLrDocumentManager.GetItems(inIndex: Integer): TLrDocument; begin Result := TLrDocument(FItems[inIndex]); end; procedure TLrDocumentManager.SetItems(inIndex: Integer; const Value: TLrDocument); begin FItems[inIndex] := Value; end; function TLrDocumentManager.Find(const inPath: string): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do if Items[i].Path = inPath then begin Result := i; break; end; end; procedure TLrDocumentManager.CurrentChanging; begin if Assigned(OnCurrentChanging) then OnCurrentChanging(Self); end; procedure TLrDocumentManager.CurrentChanged; begin if Assigned(OnCurrentChanged) then OnCurrentChanged(Self); end; procedure TLrDocumentManager.CurrentClosing; begin if Assigned(OnClose) then OnClose(Self); end; procedure TLrDocumentManager.CloseUntitled; begin if FCurrent.Untitled and not FCurrent.Modified then begin CurrentClosing; FItems.Extract(FCurrent); FCurrent.Free; end; end; procedure TLrDocumentManager.Select(inItem: TLrDocument); begin // if (inItem <> FCurrent) then // begin CurrentChanging; FCurrent.Deactivate; if inItem = nil then inItem := NilDocument; if inItem <> NilDocument then CloseUntitled; FCurrent := inItem; CurrentChanged; FCurrent.Activate; // end; end; function TLrDocumentManager.UntitledCount: Integer; var i: Integer; begin Result := 0; for i := 0 to Count - 1 do if Items[i].Untitled then Inc(Result); end; function TLrDocumentManager.NewName: string; begin Result := DefaultPath + 'Untitled' + IntToStr(UntitledCount + 1) end; procedure TLrDocumentManager.New(inClass: TLrDocumentClass); var item: TLrDocument; begin item := inClass.Create(Self, NewName); item.Untitled := true; item.Open; //item.Modified := true; FItems.Add(item); Select(item); end; function TLrDocumentManager.Open(const inPath: string): Boolean; var i: Integer; item: TLrDocument; begin Result := true; i := Find(inPath); if (i >= 0) then Select(Items[i]) else begin item := OpenItem(inPath); if item = nil then Result := false else begin FItems.Add(item); Select(item); end; end; end; function TLrDocumentManager.OpenItem(const inPath: string): TLrDocument; var dc: TLrDocumentClass; begin if not Assigned(FOnOpen) then Result := nil else Result := FOnOpen(Self, inPath); if Result = nil then begin dc := DocumentClassFromExtension(ExtractFileExt(inPath)); if (dc <> nil) then Result := dc.Create(Self, inPath); end; if Result <> nil then begin Result.Open; if Assigned(FOnAfterOpen) then FOnAfterOpen(Self, Result); end; end; procedure TLrDocumentManager.ValidateCurrent(inPivot: Integer); begin FCurrent := NilDocument; if (inPivot >= 0) and (inPivot < Count) then Current := Items[inPivot] else if (inPivot > 0) and (inPivot - 1 < Count) then Current := Items[inPivot-1]; end; procedure TLrDocumentManager.CloseItem(inItem: TLrDocument); begin FItems.Extract(inItem); inItem.Free; end; procedure TLrDocumentManager.Close(inItem: TLrDocument); var i: Integer; begin i := FItems.IndexOf(inItem); CloseItem(inItem); if FCurrent = inItem then ValidateCurrent(i); CurrentChanged; end; procedure TLrDocumentManager.DocumentChanged(inItem: TLrDocument); begin // end; procedure TLrDocumentManager.DisEnableAction(inAction: TLrDocumentAction); begin Current.DisEnableAction(inAction); end; procedure TLrDocumentManager.PerformAction(inAction: TLrDocumentAction); begin Current.PerformAction(inAction); end; procedure TLrDocumentManager.Save(inItem: TLrDocument = nil); begin if inItem = nil then inItem := Current; if inItem.Untitled then SaveAs(inItem) else inItem.Save; end; procedure TLrDocumentManager.SaveAs(inItem: TLrDocument = nil); var oldName: string; begin if inItem = nil then inItem := Current; if inItem <> NilDocument then begin oldName := inItem.Path; if inItem.SaveAs then begin if Assigned(OnSaveAs) then OnSaveAs(Self, inItem, oldName, inItem.Path); CurrentChanged; end; end; end; procedure TLrDocumentManager.SetCurrent(const Value: TLrDocument); begin if (Value <> Current) then Select(Value); end; function TLrDocumentManager.EnableClose: Boolean; begin Result := Current <> NilDocument; end; function TLrDocumentManager.EnableSave: Boolean; begin Result := Current.EnableSave; end; function TLrDocumentManager.EnableSaveAs: Boolean; begin Result := Current.EnableSaveAs; end; function TLrDocumentManager.CloseAll: Boolean; begin Result := true; FCurrent := NilDocument; while Count > 0 do if not Items[0].CanClose then begin Result := false; break; end else Items[0].CloseItem; Select(NilDocument); end; procedure TLrDocumentManager.UpdateDocument(inDocument: TLrDocument); begin if Assigned(OnUpdateDocument) then OnUpdateDocument(Self, inDocument); end; procedure TLrDocumentManager.BeginUpdate; begin Inc(FUpdate); end; procedure TLrDocumentManager.EndUpdate; begin Dec(FUpdate); if FUpdate = 0 then ValidateCurrent(0); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls; type TCaption = string; TForm1 = class(TForm) Table: TStringGrid; Label1: TLabel; Label2: TLabel; Label3: TLabel; Xwin: TLabel; Owin: TLabel; Button1: TButton; Label4: TLabel; Turn: TLabel; restart: TButton; procedure TableSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure Button1Click(Sender: TObject); procedure restartClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses Unit2; procedure CleanField(field:TStringGrid); //Очистка поля var i,j:integer; begin for i:=0 to 2 do for j:=0 to 2 do field.Cells[i,j]:= ''; end; {$R *.dfm} procedure TForm1.TableSelectCell(Sender: TObject; ACol, //Нажатие на поле ARow: Integer; var CanSelect: Boolean); function CheckForWin(field:TStringGrid;cturn:string):Boolean; //Проверка на победу var i:integer; begin for i:= 0 to 2 do begin if (field.Cells[i,0]+field.Cells[i,1]+field.Cells[i,2]) = (cturn + cturn + cturn) then CheckForWin := True; if (field.Cells[0,i]+field.Cells[1,i]+field.Cells[2,i]) = (cturn + cturn + cturn) then CheckForWin := True; end; if (field.Cells[0,0]+field.Cells[1,1]+field.Cells[2,2]) = (cturn + cturn + cturn) then CheckForWin := True; if (field.Cells[0,2]+field.Cells[1,1]+field.Cells[2,0]) = (cturn + cturn + cturn) then CheckForWin := True; end; function CheckIfFull(field:TStringGrid):Boolean; //Проверка заполненности var i,j:integer; begin for i:=0 to 2 do for j:=0 to 2 do if field.Cells[i,j] = '' then begin CheckIfFull:= False; abort; end; CheckIfFull:= True; end; begin if Table.Cells[ACol,ARow] <> '' then //Выход, если ячейка уже заполнена exit; if turn.Caption = 'X' then turn.Caption:= 'O' else turn.Caption:= 'X'; Table.Cells[ACol,ARow]:= turn.caption; //Заполнение ячейки if CheckForWin(Table,Turn.caption) = True then begin if turn.caption = 'X' then begin ShowMessage('X победил!'); Xwin.caption:= IntToStr(StrToInt(Xwin.caption) + 1); CleanField(Table); end; if turn.caption = 'O' then begin ShowMessage('O победил!'); Owin.caption:= IntToStr(StrToInt(Owin.caption) + 1); CleanField(Table); end; end; if CheckIfFull(Table) = True then begin ShowMessage('Ничья'); CleanField(Table); end; end; procedure TForm1.Button1Click(Sender: TObject); begin Owin.caption:= '0'; Xwin.caption:= '0'; CleanField(table); turn.Caption:= ''; Form1.close; Form2.visible:=True; end; procedure TForm1.restartClick(Sender: TObject); begin Owin.caption:= '0'; Xwin.caption:= '0'; CleanField(table); turn.Caption:= ''; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) MaleLabel: TLabel; FemaleLabel: TLabel; NeutralLabel: TLabel; MaleInfo: TLabel; FemaleInfo: TLabel; NeutralInfo: TLabel; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateValues; end; var Form1: TForm1; implementation {$R *.dfm} uses NtBase, NtPattern, NtLanguageDlg; procedure TForm1.UpdateValues; resourcestring // Contains only one pattern: neutral. SMessageGender = '{gender, neutral {%s tuo polkupyöränsä}}'; //loc 0: Name of the person procedure Process(gender: TGender; const name: String; messageLabel, infoLabel: TLabel); var actualGender: TGender; begin // Update message label messageLabel.Caption := TMultiPattern.Format(SMessageGender, gender, [name]); // Update info label actualGender := TMultiPattern.GetGender(SMessageGender, gender); if actualGender <> gender then infoLabel.Font.Style := [fsBold] else infoLabel.Font.Style := []; infoLabel.Caption := TMultiPattern.GetGenderName(actualGender); end; resourcestring SJoku = 'Joku'; begin Process(geMale, 'Jussi', MaleLabel, MaleInfo); Process(geFemale, 'Jaana', FemaleLabel, FemaleInfo); Process(geNeutral, SJoku, NeutralLabel, NeutralInfo); end; procedure TForm1.FormCreate(Sender: TObject); begin UpdateValues; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select('fi') then UpdateValues; end; initialization DefaultLocale := 'fi'; end.
unit Win11CornersMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.TitleBarCtrls, Vcl.ExtCtrls; type TWin11CornersForm = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; TitleBarPanel1: TTitleBarPanel; CheckBox1: TCheckBox; Panel1: TPanel; procedure Button1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Win11CornersForm: TWin11CornersForm; implementation {$R *.dfm} uses Winapi.Dwmapi; const // More information: // https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/apply-rounded-corners // https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute // https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/nf-dwmapi-dwmsetwindowattribute // Let the system decide whether or not to round window corners DWMWCP_DEFAULT = 0; // Never round window corners DWMWCP_DONOTROUND = 1; // Round the corners if appropriate DWMWCP_ROUND = 2; // Round the corners if appropriate, with a small radius DWMWCP_ROUNDSMALL = 3; // [set] WINDOW_CORNER_PREFERENCE, Controls the policy that rounds top-level window corners DWMWA_WINDOW_CORNER_PREFERENCE = 33; procedure TWin11CornersForm.Button1Click(Sender: TObject); begin var DWM_WINDOW_CORNER_PREFERENCE: Cardinal; case TComponent(Sender).Tag of 0: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_DONOTROUND; 1: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_ROUND; 2: DWM_WINDOW_CORNER_PREFERENCE := DWMWCP_ROUNDSMALL; end; Winapi.Dwmapi.DwmSetWindowAttribute(self.Handle, DWMWA_WINDOW_CORNER_PREFERENCE, @DWM_WINDOW_CORNER_PREFERENCE, sizeof(DWM_WINDOW_CORNER_PREFERENCE)); end; procedure TWin11CornersForm.CheckBox1Click(Sender: TObject); begin Self.CustomTitleBar.Enabled := CheckBox1.Checked; end; end.
unit HCCompiler; interface uses Classes, SysUtils, Vcl.Dialogs, Generics.Collections, PaxCompiler, PaxProgram, PaxRunner, HCSynEdit, SynEditTypes, PaxRegister, PaxJavaScriptLanguage, IMPORT_Classes, IMPORT_SysUtils, IMPORT_Dialogs, IMPORT_Variants; const ProposalCommColor = '$00A00000'; type TProposalInfo = class(TObject) public TypeID: Integer; ClassNameEx: string; Keyword: string; procedure Init; end; TCplVariable = class(TObject) /// <summary> 变量类型ID </summary> TypeID: Integer; /// <summary> 变量内存地址 </summary> Address: Pointer; /// <summary> 变量名 </summary> FullName: string; /// <summary> 配合SynEdit的代码提示,如var \column{}\style{+B}BLL\style{-B}: TBLLObj; // 业务处理对象 </summary> Proposal: string; end; TCplVariables = class(TObjectList<TCplVariable>) public function New(const ATypeID: Integer; const AAddress: Pointer; const AFullName, AProposal: string): Integer; function NameOf(const AName: string): Integer; end; TCplConvert = class(TObject) public /// <summary> 是否为常量 </summary> Constant: Boolean; /// <summary> 是否为重新封装的(不是原始类中的方法) </summary> Fake: Boolean; /// <summary> 第几个重载 </summary> OverIndex: Byte; /// <summary> 实例内存地址 </summary> Address: Pointer; /// <summary> 全名,如function RunScript(const ACode: string): Boolean; </summary> FullName: string; /// <summary> 配合SynEdit的代码提示,如 procedure \column{}\style{+B}Commit\style{-B}(const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 提交 </summary> Proposal: string; /// <summary> 名称,如RunScript </summary> SimpleName: string; /// <summary> 单元名,如HCCompiler </summary> UnitName: string; /// <summary> 路径,如HCCompiler.TCplConvert </summary> //FullPath: string; /// <summary> 所属类的名称,如TCplConvert </summary> ClassNameEx: string; end; TCplConverts = class(TObjectList<TCplConvert>) public function New(const AFullName, AProposal, ASimpleName, AUnitName, AClassName: string; const AAddress: Pointer; const AFake: Boolean = False; const AOverIndex: Byte = 0): Integer; function AddressOf(const AAddress: Pointer): TCplConvert; function ProcOf(const APath: string; const AOverIndex: Byte): TCplConvert; end; TScriptType = (stpNone, stpPascal, stpJavaScript); TCompilerExceptionEvnet = procedure(const E: Exception; const AModuleName: String; ASourceLine: Integer) of object; THCCompiler = class(TPaxCompiler) private FHasError: Boolean; FPaxProgram: TPaxProgram; FPaxLanguage: TPaxCompilerLanguage; FScriptType: TScriptType; FLastProposal: TProposalInfo; FOnException: TCompilerExceptionEvnet; procedure SetScriptType(const Value: TScriptType); protected FCompilerVariables: TCplVariables; FCompilerConverts: TCplConverts; // 运行bin文件时关联类、函数、变量相关的方法 procedure DoMapTableNamespace(Sender: TPaxRunner; const FullName: string; Global: Boolean); procedure DoMapTableVarAddress(Sender: TPaxRunner; const FullName: string; Global: Boolean; var Address: Pointer); procedure DoMapTableProcAddress(Sender: TPaxRunner; const FullName: string; OverCount: Byte; Global: Boolean; var Address: Pointer); procedure DoMapTableClassRef(Sender: TPaxRunner; const FullName: string; Global: Boolean; var ClassRef: TClass); procedure DoProgException(Sender: TPaxRunner; E: Exception; const ModuleName: String; SourceLineNumber: Integer); procedure DoProgUnhandledException(Sender: TPaxRunner; E: Exception; const ModuleName: String; SourceLineNumber: Integer); public constructor CreateByScriptType(AOwner: TComponent; const AScriptType: TScriptType = stpPascal); virtual; destructor Destroy; override; procedure ResetRegister; virtual; /// <summary> 设置代码提示 </summary> procedure Proposal(const AWord: string; const AInsertList, AItemList: TStrings); /// <summary> 代码提示回车后上屏时触发的事件 </summary> procedure CodeCompletion(Sender: TObject; var Value: UnicodeString; Shift: TShiftState; Index: Integer; EndToken: WideChar); /// <summary> 查找指定名称的变量是否已经注册过 </summary> function FindRegisterVariable(const ATypeID: Integer; const AVarName: string): Boolean; function RunScript(const ACode: string): Boolean; function RunScriptBin(const AStream: TStream): Boolean; function CompileScript(const ACode: string): Boolean; procedure SaveToStream(const AStream: TStream); procedure LoadFromStream(const AStream: TStream); property ScriptType: TScriptType read FScriptType write SetScriptType; property OnException: TCompilerExceptionEvnet read FOnException write FOnException; end; implementation uses PAXCOMP_KERNEL, PAXCOMP_SYMBOL_REC, PAXCOMP_BASERUNNER, PAXCOMP_SYS; { THCCompiler } procedure THCCompiler.CodeCompletion(Sender: TObject; var Value: UnicodeString; Shift: TShiftState; Index: Integer; EndToken: WideChar); var vSynEdit: THCSynEdit; i, vID, vTypeID, vOwnerID: Integer; vKernel: TKernel; vSymbolRec: TSymbolRec; vClassName: string; begin vSynEdit := Sender as THCSynEdit; if FCompilerVariables.NameOf(Value) >= 0 then // 是全局变量,掩掉前面的“." begin vSynEdit.BlockBegin := BufferCoord(vSynEdit.BlockBegin.Char - 1, vSynEdit.BlockBegin.Line); vSynEdit.BlockEnd := BufferCoord(vSynEdit.CaretX, vSynEdit.CaretY); Exit; end; // 动态查找方法、事件、属性、局部变量 vID := Self.LookupId(Value); // 变量ID if vID > 0 then // 动态里有 begin vKernel := Self.GetKernelPtr; vTypeID := vKernel.SymbolTable[vID].TypeId; if vTypeID = 0 then begin vOwnerID := vKernel.SymbolTable[vID].OwnerId; if vOwnerID > 0 then vTypeID := vKernel.SymbolTable[vOwnerID].TypeId; end; for i := vTypeID + 1 to vKernel.SymbolTable.Card do begin vSymbolRec := vKernel.SymbolTable[I]; if vSymbolRec = vKernel.SymbolTable.SR0 then Break; if vSymbolRec.Kind = kindNAMESPACE then Break; if vSymbolRec.Level <> vTypeID then Continue; if CompareStr(vSymbolRec.Name, Value) = 0 then begin if vKernel.SymbolTable.IsProcedure(vTypeID, i) or vKernel.SymbolTable.IsFunction(vTypeID, i) then begin if vSymbolRec.Count > 0 then // 有参数 Value := Value + '()'; Exit; end; end; end; if vKernel.SymbolTable[vID].Kind = kindVAR then // 局部变量 begin vSynEdit.BlockBegin := BufferCoord(vSynEdit.BlockBegin.Char - 1, vSynEdit.BlockBegin.Line); vSynEdit.BlockEnd := BufferCoord(vSynEdit.CaretX, vSynEdit.CaretY); Exit; end; end; // 动态没找到 if FLastProposal.TypeID > 0 then begin vKernel := Self.GetKernelPtr; for i := FLastProposal.TypeID + 1 to vKernel.SymbolTable.Card do begin vSymbolRec := vKernel.SymbolTable[I]; if vSymbolRec = vKernel.SymbolTable.SR0 then Break; if vSymbolRec.Kind = kindNAMESPACE then Break; if vSymbolRec.Level <> FLastProposal.TypeID then Continue; if CompareStr(vSymbolRec.Name, Value) = 0 then begin if vKernel.SymbolTable.IsProcedure(FLastProposal.TypeID, i) or vKernel.SymbolTable.IsFunction(FLastProposal.TypeID, i) then begin if vSymbolRec.Count > 0 then // 有参数 Value := Value + '()'; Exit; end; end; end; end; end; function THCCompiler.CompileScript(const ACode: string): Boolean; begin Result := False; AddCode('main', ACode); if Compile(FPaxProgram) then Result := True; end; constructor THCCompiler.CreateByScriptType(AOwner: TComponent; const AScriptType: TScriptType = stpPascal); begin inherited Create(AOwner); FHasError := False; FLastProposal := TProposalInfo.Create; FCompilerConverts := TCplConverts.Create; FCompilerVariables := TCplVariables.Create; FScriptType := stpNone; FPaxProgram := TPaxProgram.Create(nil); FPaxProgram.OnMapTableNamespace := DoMapTableNamespace; FPaxProgram.OnMapTableVarAddress := DoMapTableVarAddress; FPaxProgram.OnMapTableProcAddress := DoMapTableProcAddress; FPaxProgram.OnMapTableClassRef := DoMapTableClassRef; FPaxProgram.OnException := DoProgException; FPaxProgram.OnUnhandledException := DoProgUnhandledException; SetScriptType(AScriptType); end; destructor THCCompiler.Destroy; begin FreeAndNil(FPaxProgram); if Assigned(FPaxLanguage) then FPaxLanguage.Free; FreeAndNil(FLastProposal); FreeAndNil(FCompilerConverts); FreeAndNil(FCompilerVariables); inherited Destroy; end; procedure THCCompiler.DoMapTableClassRef(Sender: TPaxRunner; const FullName: string; Global: Boolean; var ClassRef: TClass); var vName: string; vTypeID, vPos: Integer; begin vName := UpperCase(FullName); // 取出类名称 vPos := Pos('.', vName); while vPos > 0 do begin vName := Copy(vName, vPos + 1, Length(vName) - vPos); vPos := Pos('.', vName); end; vTypeID := Self.LookupTypeId(vName); if vTypeID > 0 then ClassRef := TKernel(Self.GetKernelPtr).SymbolTable[vTypeID].PClass; end; procedure THCCompiler.DoMapTableNamespace(Sender: TPaxRunner; const FullName: string; Global: Boolean); begin //vName := LowerCase(FullName) //if FullName = 'emr_MsgPack' then end; procedure THCCompiler.DoMapTableProcAddress(Sender: TPaxRunner; const FullName: string; OverCount: Byte; Global: Boolean; var Address: Pointer); var //vPath: string; vConvert: TCplConvert; vID, vTypeID, vOwnerID: Integer; vKernel: TKernel; begin vConvert := FCompilerConverts.ProcOf(FullName, OverCount); if Assigned(vConvert) then begin Address := vConvert.Address; Exit; end; vID := Self.LookupId(FullName); if vID > 0 then begin vKernel := Self.GetKernelPtr; Address := vKernel.SymbolTable[vID].Address; Exit; end; {vPath := LowerCase(FullName); if vPath = 'classes.tmemorystream.create' then Address := @System.Classes.TMemoryStream.Create else if vPath = 'sysutils.quotedstr' then Address := @System.SysUtils.QuotedStr else if vPath = 'sysutils.format' then Address := @System.SysUtils.Format else if vPath = 'sysutils.formatdatetime' then Address := @System.SysUtils.FormatDateTime else if vPath = 'sysutils.inttostr' then Address := @System.SysUtils.IntToStr else if vPath = 'dialogs.showmessage' then Address := @Vcl.Dialogs.ShowMessage;} end; procedure THCCompiler.DoMapTableVarAddress(Sender: TPaxRunner; const FullName: string; Global: Boolean; var Address: Pointer); var i: Integer; begin for i := 0 to FCompilerVariables.Count - 1 do begin if CompareText(FCompilerVariables[i].FullName, FullName) = 0 then begin Address := FCompilerVariables[i].Address; Break; end; end; end; procedure THCCompiler.DoProgException(Sender: TPaxRunner; E: Exception; const ModuleName: String; SourceLineNumber: Integer); begin FHasError := True; //vStackCount := Sender.GetProgPtr.GetCallStackCount; if Assigned(FOnException) then FOnException(E, ModuleName, SourceLineNumber); end; procedure THCCompiler.DoProgUnhandledException(Sender: TPaxRunner; E: Exception; const ModuleName: String; SourceLineNumber: Integer); begin FHasError := True; if Assigned(FOnException) then FOnException(E, ModuleName, SourceLineNumber); end; function THCCompiler.FindRegisterVariable(const ATypeID: Integer; const AVarName: string): Boolean; var vKernel: TKernel; vSymbolRec: TSymbolRec; i: Integer; begin Result := False; vKernel := TKernel(Self.GetKernelPtr); for i := FirstLocalId + 1 to vKernel.SymbolTable.Card do begin vSymbolRec := vKernel.SymbolTable[i]; if (vSymbolRec.Kind = KindVAR) and (CompareStr(vSymbolRec.Name, AVarName) = 0) then // 注册过了 begin Result := True; Break; end; end; end; procedure THCCompiler.LoadFromStream(const AStream: TStream); begin FPaxProgram.LoadFromStream(AStream); end; procedure THCCompiler.Proposal(const AWord: string; const AInsertList, AItemList: TStrings); var i, vID, vTypeID: Integer; vKernel: TKernel; vClassName: string; vConvert: TCplConvert; vVariable: TCplVariable; vSymbolRec: TSymbolRec; begin FLastProposal.Init; FLastProposal.Keyword := AWord; if AWord = '.' then // 提示全部可用的变量 begin vKernel := Self.GetKernelPtr; for i := 0 to FCompilerVariables.Count - 1 do // 注册的全局变量 begin vVariable := FCompilerVariables[i]; AInsertList.Add(vVariable.FullName); if vKernel.SymbolTable[vVariable.TypeID].TypeID = 0 then // 基本类型 vClassName := vKernel.SymbolTable[vVariable.TypeID].Name else vClassName := vKernel.SymbolTable[vVariable.TypeID].PClass.ClassName; // 变量类型名 {if vClassName = 'UNICODESTRING' then vClassName := 'string';} AItemList.Add('\image{0} \column{} var \column{}\style{+B}' + vVariable.FullName + '\style{-B}: ' + vClassName + ' // ' + vVariable.Proposal); end; for i := FirstLocalId + 1 to vKernel.SymbolTable.Card do begin vSymbolRec := vKernel.SymbolTable[i]; if (not vSymbolRec.Host) and (vSymbolRec.Kind = KindVAR) then // 脚本内部的变量 begin if vKernel.SymbolTable[vSymbolRec.TypeID].TypeID = 0 then // 基本类型 vClassName := vKernel.SymbolTable[vSymbolRec.TypeID].Name else vClassName := vKernel.SymbolTable[vSymbolRec.TypeID].PClass.ClassName; // 变量类型名 AInsertList.Add(vSymbolRec.Name); AItemList.Add('\image{0} \column{} var \column{}\style{+B}' + vSymbolRec.Name + '\style{-B}: ' + vClassName + ' // 局部变量'); end; end; end else begin vTypeID := Self.LookupTypeId(AWord); // 先判断写的直接类型名 如 TDeProp if vTypeID > 0 then begin vKernel := TKernel(Self.GetKernelPtr); if vKernel.SymbolTable[vTypeID].TypeID = 0 then // 基本类型 vClassName := vKernel.SymbolTable[vTypeID].Name else vClassName := vKernel.SymbolTable[vTypeID].PClass.ClassName; // 变量类型名 FLastProposal.TypeID := vTypeID; FLastProposal.ClassNameEx := vClassName; for i := 0 to FCompilerConverts.Count - 1 do begin vConvert := FCompilerConverts[i]; if {(not vConvert.Fake) and 重载的方法出不来了} (CompareStr(vConvert.ClassNameEx, vClassName) = 0) then begin AInsertList.Add(vConvert.SimpleName); AItemList.Add(vConvert.Proposal); end; end; Exit; end; vID := Self.LookupId(AWord); // 根据名称获取对象ID if vID > 0 then begin vKernel := TKernel(Self.GetKernelPtr); // 先判断是不是类型名或某类型的变量 vSymbolRec := vKernel.SymbolTable[vID]; if Assigned(vSymbolRec) then // AWord就是类型名,或者是某类型变量 begin vTypeID := vKernel.SymbolTable[vID].TypeID; // 取类型 if vTypeID > 0 then // 有类型 vClassName := vKernel.SymbolTable[vTypeID].Name else // 无类型:方法、函数 vClassName := '';//vKernel.SymbolTable[vTypeID].PClass.ClassName; // 所属类型名称 end else // 还会走到下面吗? begin vTypeID := vKernel.GetTypeMapRec(vID).TypeId; // 所属类型ID if vKernel.SymbolTable[vTypeID].TypeID = 0 then // 基本类型 vClassName := vKernel.SymbolTable[vTypeID].Name else vClassName := vKernel.SymbolTable[vTypeID].PClass.ClassName; // 所属类型名称 vSymbolRec := vKernel.SymbolTable[vID]; end; FLastProposal.TypeID := vTypeID; FLastProposal.ClassNameEx := vClassName; if vSymbolRec.Kind = kindVAR then // 是变量,为啥方法或属性也会满足这个条件呢? begin for i := 0 to FCompilerConverts.Count - 1 do begin vConvert := FCompilerConverts[i]; if {(not vConvert.Fake) and 重载的方法出不来了} (CompareStr(vConvert.ClassNameEx, vClassName) = 0) then begin AInsertList.Add(vConvert.SimpleName); AItemList.Add(vConvert.Proposal); end; end; end; end; end; end; procedure THCCompiler.ResetRegister; begin FCompilerVariables.Clear; Reset; RegisterLanguage(FPaxLanguage); AddModule('main', FPaxLanguage.LanguageName); end; function THCCompiler.RunScript(const ACode: string): Boolean; begin Result := False; FHasError := False; AddCode('main', ACode); //FPaxProgram.GetProgPtr.RootExceptionIsAvailableForHostApplication := True; // 响应try finally中的异常 if Compile(FPaxProgram) then begin FPaxProgram.Run; if not FHasError then // FPaxProgram.GetProgPtr.HasError ExceptionRec Result := True; end; end; function THCCompiler.RunScriptBin(const AStream: TStream): Boolean; var vRun: TBaseRunner; begin Result := False; FHasError := False; AStream.Position := 0; //FPaxProgram.GetProgPtr.RootExceptionIsAvailableForHostApplication := True; // 响应try finally中的异常 FPaxProgram.LoadFromStream(AStream); FPaxProgram.MapGlobal; FPaxProgram.MapLocal; FPaxProgram.Run; if not FHasError then // FPaxProgram.GetProgPtr.HasError ExceptionRec Result := True; end; procedure THCCompiler.SaveToStream(const AStream: TStream); begin FPaxProgram.SaveToStream(AStream); end; procedure THCCompiler.SetScriptType(const Value: TScriptType); begin if FScriptType <> Value then begin if Assigned(FPaxLanguage) then FPaxLanguage.Free; FScriptType := Value; case FScriptType of stpPascal: FPaxLanguage := TPaxPascalLanguage.Create(nil); stpJavaScript: FPaxLanguage := TPaxJavaScriptLanguage.Create(nil); end; ResetRegister; end; end; { TCplConverts } function TCplConverts.AddressOf(const AAddress: Pointer): TCplConvert; var i: Integer; begin Result := nil; for i := 0 to Self.Count - 1 do begin if Self[i].Address = AAddress then begin Result := Self[i]; Break; end; end; end; function TCplConverts.New(const AFullName, AProposal, ASimpleName, AUnitName, AClassName: string; const AAddress: Pointer; const AFake: Boolean = False; const AOverIndex: Byte = 0): Integer; var vConvert: TCplConvert; begin vConvert := TCplConvert.Create; vConvert.FullName := AFullName; vConvert.Proposal := AProposal; vConvert.SimpleName := ASimpleName; vConvert.UnitName := AUnitName; vConvert.ClassNameEx := AClassName; vConvert.Address := AAddress; vConvert.OverIndex := AOverIndex; vConvert.Fake := AFake; vConvert.Constant := False; Result := Self.Add(vConvert); end; function TCplConverts.ProcOf(const APath: string; const AOverIndex: Byte): TCplConvert; var i: Integer; vConvert: TCplConvert; vPath: string; begin Result := nil; for i := 0 to Self.Count - 1 do begin vConvert := Self[i]; if vConvert.OverIndex = AOverIndex then begin vPath := vConvert.ClassNameEx + '.' + vConvert.SimpleName; if CompareText(APath, vPath) = 0 then begin Result := Self[i]; Exit; end; vPath := vConvert.UnitName + '.' + vPath; if CompareText(APath, vPath) = 0 then begin Result := Self[i]; Exit; end; end; end; end; { TCplVariables } function TCplVariables.NameOf(const AName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to Self.Count - 1 do begin if CompareStr(Self[i].FullName, AName) = 0 then begin Result := i; Break; end; end; end; function TCplVariables.New(const ATypeID: Integer; const AAddress: Pointer; const AFullName, AProposal: string): Integer; var vVariable: TCplVariable; begin Result := -1; vVariable := TCplVariable.Create; vVariable.TypeID := ATypeID; vVariable.Address := AAddress; vVariable.FullName := AFullName; vVariable.Proposal := AProposal; Result := Self.Add(vVariable); end; { TProposalInfo } procedure TProposalInfo.Init; begin TypeID := 0; ClassNameEx := '';; Keyword := ''; end; procedure RegisterImportClass; begin IMPORT_Classes.Register_Classes; IMPORT_SysUtils.Register_SysUtils; IMPORT_Dialogs.Register_Dialogs; IMPORT_Variants.Register_Variants; end; initialization RegisterImportClass; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // 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. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // 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 COPYRIGHT OWNER 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. unit uEditorFileHandler; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Forms, Dialogs, Controls, uCommon, uFileHist, FileCtrl, uMultiLanguage, SynEditTextBuffer, SynEditTypes, JclFileUtils; type TEditorFileHandler = class private fEditor: TObject; fSavedMemoCaret: TBufferCoord; fSavedMemoFirstLine: integer; fSavedMemoLeftChar: integer; function GetBackupFilename: string; procedure RememberMemoPositions; procedure RestoreMemoPositions; public constructor Create(Editor: TObject); // todo: move to private function SaveInFormat(Source: TStrings; Format: TTextFormat; FileName: string): boolean; function PrepareForSave(var NewFileName:string; const ChangeName:boolean = FALSE):boolean; function BackupFile: boolean; function Rename(NewFileName: string): boolean; function RenameEnabled: boolean; function RevertToSavedEnabled: boolean; function RevertToBackupEnabled: boolean; procedure RevertToSaved; procedure RevertToBackup; procedure CopyTo; end; implementation uses fEditor, uEnvOptions; //////////////////////////////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function TEditorFileHandler.GetBackupFilename: string; var path: string; bak_fname: string; fname: string; begin fname:=TfmEditor(fEditor).FileName; if (Length(EnvOptions.BackupDir)>0) then path:=PathAddSeparator(EnvOptions.BackupDir) else path:=ExtractFilePath(fname); bak_fname:=ExtractFileName(fname); if EnvOptions.BackupDOSFileName then SetLength(bak_fname, Length(bak_fname)-Length(ExtractFileExt(bak_fname))); result:=path+bak_fname+'.bak'; end; //------------------------------------------------------------------------------------------ procedure TEditorFileHandler.RememberMemoPositions; begin with TfmEditor(fEditor).memo do begin fSavedMemoCaret:=CaretXY; fSavedMemoFirstLine:=TopLine; fSavedMemoLeftChar:=LeftChar; end; end; //------------------------------------------------------------------------------------------ procedure TEditorFileHandler.RestoreMemoPositions; begin with TfmEditor(fEditor).memo do begin CaretXY:=fSavedMemoCaret; TopLine:=fSavedMemoFirstLine; LeftChar:=fSavedMemoLeftChar; end; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.BackupFile: boolean; var bak_fname: string; bak_path: string; ok: boolean; attr: word; fname: string; begin ok:=TRUE; fname:=TfmEditor(fEditor).FileName; if EnvOptions.BackupFile and FileExists(fname) then begin bak_fname:=GetBackupFilename; bak_path:=ExtractFilePath(bak_fname); if (Length(EnvOptions.BackupDir)>0) then ForceDirectories(bak_path); if FileExists(bak_fname) then begin attr:=FileGetAttr(bak_fname); FileSetAttr(bak_fname, attr and not faReadOnly); DeleteFile(bak_fname); end; ok:=CopyFile(PChar(fname), PChar(bak_fname), FALSE); if not ok then MessageDlg(Format(mlStr(ML_EDIT_ERR_SAVING_BACKUP,'Error creating backup file: ''%s'''),[bak_fname]), mtError,[mbOK],0); end; result:=ok; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.RenameEnabled: boolean; var Editor: TfmEditor; begin Editor:=TfmEditor(fEditor); result:=not (Editor.NewFile or Editor.Unnamed); end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.Rename(NewFileName: string): boolean; var old_fname: string; old_path: string; new_path: string; Editor: TfmEditor; begin Editor:=TfmEditor(fEditor); old_fname:=Editor.FileName; old_path:=ExtractFilePath(Editor.FileName); new_path:=ExtractFilePath(NewFileName); Delete(NewFileName, 1, Length(new_path)); if (Length(new_path)=0) then new_path:=old_path; NewFileName:=new_path+NewFileName; if (not FileExists(NewFileName)) or (UpperCase(NewFileName)=UpperCase(Editor.FileName)) then begin result:=RenameFile(Editor.FileName, NewFileName); if not result then MessageDlg(Format(mlStr(ML_RENAME_FILE_ERROR, 'Error renaming file ''%s'' to ''%s''.'), [Editor.FileName, NewFileName]), mtError, [mbOK], 0); end else begin MessageDlg(mlStr(ML_RENAME_FILE_ERR_EXISTS, 'File already exists!'), mtError, [mbOK], 0); result:=FALSE; end; if result then Editor.FileName:=NewFileName; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.RevertToBackupEnabled: boolean; begin result:=EnvOptions.BackupFile and FileExists(GetBackupFilename); end; //------------------------------------------------------------------------------------------ procedure TEditorFileHandler.RevertToBackup; var OldFileName: string; Editor: TfmEditor; begin if (MessageDlg(Format(mlStr(ML_REVERT_TO_BACKUP_QUERY, 'Revert to backup file ''%s''?'), [GetBackupFilename]), mtWarning, [mbOK, mbCancel], 0)=mrOK) then begin Editor:=TfmEditor(fEditor); OldFileName:=Editor.FileName; RememberMemoPositions; Editor.Open(GetBackupFilename, FALSE); RestoreMemoPositions; Editor.FileName:=OldFileName; Editor.Modified:=TRUE; end; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.RevertToSavedEnabled: boolean; var Editor: TfmEditor; begin Editor:=TfmEditor(fEditor); result:=Editor.Modified and not (Editor.NewFile or Editor.Unnamed); end; //------------------------------------------------------------------------------------------ procedure TEditorFileHandler.RevertToSaved; var Editor: TfmEditor; begin Editor:=TfmEditor(fEditor); if (MessageDlg(Format(mlStr(ML_REVERT_TO_SAVED_QUERY, 'Revert ''%s'' to saved?'), [Editor.FileName]), mtWarning, [mbOK, mbCancel], 0)=mrOK) then begin RememberMemoPositions; Editor.Open(Editor.FileName, FALSE); RestoreMemoPositions; end; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.SaveInFormat(Source: TStrings; Format: TTextFormat; FileName: string): boolean; var buff :pChar; buff_size :integer; p, pp :pChar; s :string; i :integer; F :file; ok :boolean; begin ok:=TRUE; try case format of tfNormal: begin TSynEditStringList(Source).FileFormat:=sffDos; Source.SaveToFile(FileName); ok:=TRUE; end; tfUnix: begin TSynEditStringList(Source).FileFormat:=sffUnix; Source.SaveToFile(FileName); ok:=TRUE; end; tfMac: begin TSynEditStringList(Source).FileFormat:=sffMac; Source.SaveToFile(FileName); ok:=TRUE; end; tfUnicode, tfUnicodeBigEndian, tfUTF8: begin buff:=nil; case format of tfUnicode: begin buff_size:=2+Length(Source.Text)*2; GetMem(buff,buff_size); p:=buff; p^:=#$FF; (p+1)^:=#$FE; inc(p,2); s:=Source.Text; for i:=1 to Length(s) do begin p^:=s[i]; (p+1)^:=#00; inc(p,2); end; end; tfUnicodeBigEndian: begin buff_size:=2+Length(Source.Text)*2; GetMem(buff,buff_size); p:=buff; p^:=#$FE; (p+1)^:=#$FF; inc(p,2); s:=Source.Text; for i:=1 to Length(s) do begin p^:=#00; (p+1)^:=s[i]; inc(p,2); end; end; tfUTF8: begin buff_size:=3+Length(Source.Text); GetMem(buff,buff_size); p:=buff; p^:=#$EF; (p+1)^:=#$BB; (p+2)^:=#$BF; inc(p,3); pp:=@Source.Text[1]; Move(pp^, p^, Length(Source.Text)); end; end; AssignFile(F, FileName); {$I-} Rewrite(F,1); {$I+} ok:=(IOResult=0); if ok then begin BlockWrite(F, buff^,buff_size); System.CloseFile(F); end; if Assigned(buff) then FreeMem(buff); end; end; except ok:=FALSE; end; result:=ok; end; //------------------------------------------------------------------------------------------ function TEditorFileHandler.PrepareForSave(var NewFileName:string; const ChangeName:boolean = FALSE):boolean; var canceled: boolean; dlg: TSaveDialog; s: string; OldExt: string; OldFilterIndex: integer; attr: integer; Editor: TfmEditor; label EXECUTE_DIALOG; function FirstMask_From_NewFilter:string; begin result:=GetDefaultExtForFilterIndex(dlg.Filter, dlg.FilterIndex); end; begin Editor:=TfmEditor(fEditor); canceled:=FALSE; NewFileName:=Editor.FileName; dlg:=TSaveDialog.Create(nil); try dlg.Options:=[ofHideReadOnly,ofEnableSizing]; if (Length(Editor.FileName)=0) or ChangeName or (Editor.NewFile and Editor.Unnamed) then begin PrepareOpenDlgForFileType(dlg, Editor); if not Editor.NewFile then begin s:=ExtractFileExt(Editor.FileName); dlg.FileName:=Copy(Editor.FileName,1, Length(Editor.FileName)-Length(s)); if (Length(s)>0) and (s[1]='.') then Delete(s,1,1); OldExt:=s; end else begin dlg.FileName:=''; OldExt:=''; end; dlg.DefaultExt:=''; OldFilterIndex:=dlg.FilterIndex; BringEditorToFront(Editor); EXECUTE_DIALOG: canceled:=not dlg.Execute; if not canceled then begin s:=dlg.FileName; if (Pos('.',ExtractFileName(dlg.FileName))=0) then begin if (OldExt<>'') and (OldFilterIndex=dlg.FilterIndex) then s:=s+'.'+OldExt else if (dlg.FilterIndex<>1) then s:=s+'.'+FirstMask_From_NewFilter; end; if DlgReplaceFile(s) then NewFileName:=s else goto EXECUTE_DIALOG; end; end; finally dlg.Free; end; if not canceled then begin attr:=FileGetAttr(NewFileName); if (attr<>-1) and ((attr and faReadOnly)>0) then begin canceled:=MessageDlg(Format(mlStr(ML_EDIT_READ_ONLY_WARNING, 'File ''%s'' is read-only. Save file anyway?'), [NewFileName]), mtWarning, [mbOK, mbCancel], 0)=mrCancel; if not canceled then FileSetAttr(NewFileName, attr and not faReadOnly); end; end; result:=not canceled; end; //------------------------------------------------------------------------------------------ procedure TEditorFileHandler.CopyTo; var fname: string; Editor: TfmEditor; begin Editor:=TfmEditor(fEditor); if PrepareForSave(fname, TRUE) then begin if not SaveInFormat(Editor.memo.Lines, Editor.TextFormat, fname) then DlgErrorSaveFile(fname); end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Constructor, destructor //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TEditorFileHandler.Create(Editor: TObject); begin fEditor:=Editor; end; //------------------------------------------------------------------------------------------ end.
unit Classes.Box; interface uses Interfaces.Box, Vcl.ExtCtrls, System.Classes, System.Types, Vcl.Imaging.pngimage, Vcl.Controls; type TBox = class(TInterfacedObject, IBox) strict private var FPosition: TPoint; FImage: TImage; FOwner: TGridPanel; png: TPngImage; FKey: Integer; public class function New(const AOwner: TGridPanel): IBox; destructor Destroy; override; function Position(const Value: TPoint): IBox; overload; function Position: TPoint; overload; function Owner(const Value: TGridPanel): IBox; overload; function Owner: TGridPanel; overload; function Key(const Value: Integer): IBox; overload; function Key: Integer; overload; function CreateImages: IBox; function ChangeParent: IBox; end; implementation uses System.SysUtils; { TBox } function TBox.ChangeParent: IBox; var Panel: TWinControl; begin Result := Self; Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]); FImage.Parent := Panel; end; function TBox.CreateImages: IBox; begin Result := Self; FImage := TImage.Create(nil); FImage.Parent := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]); FImage.Align := alClient; if Assigned(png) then FreeAndNil(png); png := TPngImage.Create; png.LoadFromResourceName(HInstance, 'box'); FImage.Picture.Graphic := png; end; destructor TBox.Destroy; begin FOwner.ControlCollection.RemoveControl(FImage); FreeAndNil(FImage); if Assigned(png) then FreeAndNil(png); inherited; end; function TBox.Key: Integer; begin Result := FKey; end; function TBox.Key(const Value: Integer): IBox; begin Result := Self; FKey := Value; end; class function TBox.New(const AOwner: TGridPanel): IBox; begin Result := Self.Create; Result.Owner(AOwner); end; function TBox.Owner: TGridPanel; begin Result := FOwner; end; function TBox.Owner(const Value: TGridPanel): IBox; begin Result := Self; FOwner := Value; end; function TBox.Position(const Value: TPoint): IBox; begin Result := Self; FPosition := Value; end; function TBox.Position: TPoint; begin Result := FPosition; end; end.
(* ---------------------------------------------------------------------------- Module: ADSI Searching in Delphi Author: Marc Scheuner Date: July 17, 2000 Changes: Description: constructor Create(aOwner : TComponent); override; Creates a new instance of component destructor Destroy; override; Frees instance of component function CheckIfExists() : Boolean; Checks to see if the object described in the properties exists or not TRUE: Object exists, FALSE: object does not exist procedure Search; Launches the ADSI search - use GetFirstRow and GetNextRow to retrieve information function GetFirstRow() : TWideStringList; function GetNextRow() : TWideStringList; Returns the first row / next row of the result set, as a WideStringList. The values are stored in the string list as a <name>=<value> pair, so you can access the values via the FWideStringList.Values['name'] construct. Multivalued attributes are returned as one per line, in an array index manner: objectClass[0]=top objectClass[1]=Person objectClass[2]=organizationalPerson objectClass[3]=user and so forth. The index is zero-based. If there are no (more) rows, the return value will be NIL. It's up to the receiver to free the string list when no longer needed. property Attributes : WideString Defines the attributes you want to retrieve from the object. If you leave this empty, all available attributes will be returned. You can specify multiple attributes separated by comma: cn,distinguishedName,name,ADsPath will therefore retrieve these four attributes for all the objects returned in the search (if the attributes exist). property BaseIADs : IADs If you already have an interface to an IADs object, you can reuse it here by setting it to the BaseIADs property - in this case, ADSISearch can skip the step of binding to the ADSI object and will be executing faster. property BasePath : WideString LDAP base path for the search - the further down in the LDAP tree you start searching, the smaller the namespace to search and the quicker the search will return what you're looking for. LDAP://cn=Users,dc=stmaarten,dc=qc,dc=rnd is the well-known LDAP path for the Users container in the stmaarten.qc.rnd domain. property ChaseReferrals : Boolean If set to TRUE, the search might need to connect to other domain controllers and naming contexts, which is very time consuming. Set this property to FALSE to limit it to the current naming context, thus speeding up searches significantly. property DirSrchIntf : IDirectorySearch Provides access to the basic Directory Search interface, in case you need to do some low-level tweaking property Filter : WideString LDAP filter expression to search for. It will be ANDed together with a (objectClass=<ObjectClass>) filter to form the full search filter. It can be anything that is a valid LDAP search filter - see the appropriate books or online help files for details. It can be (among many other things): cn=Marc* badPwdCount>=0 countryCode=49 givenName=Steve and multiple conditions can be ANDed or ORed together using the LDAP syntax. property MaxRows : Integer Maximum rows of the result set you want to retrieve. Default is 0 which means all rows. property PageSize : Integer Maximum number of elements to be returned in a paged search. If you set this to 0, the search will *not* be "paged", e.g. IDirectorySearch will return all elements found in one big gulp, but there's a limit at 1'000 elements. With paged searching, you can search and find any number of AD objects. Default is set to 100 elements. No special need on the side of the developer / user to use paged searches - just set the PageSize to something non-zero. property ObjectClass: WideString ObjectClass of the ADSI object you are searching for. This allows you to specify e.g. just users, only computers etc. Be aware that ObjectClass is a multivalued attribute in LDAP, and sometimes has unexpected hierarchies (e.g."computer" descends from "user" and will therefore show up if you search for object class "user"). This property will be included in the LDAP search filter passed to the search engine. If you don't want to limit the objects returned, just leave it at the default value of * property SearchScope Limits the scope of the search. scBase: search only the base object (as specified by the LDAP path) - not very useful..... scOneLevel: search only object immediately contained by the specified base object (does not include baes object) - limits the depth of the search scSubtree: no limit on how "deep" the search goes, below the specified base object - this is the default. ---------------------------------------------------------------------------- *) unit ADSISearch; interface uses ActiveX, ActiveDs_TLB, Classes, SysUtils; type EADSISearchException = class(Exception); TSearchScope = (scBase, scOneLevel, scSubtree); TADSISearch = class private FBaseIADs : IADs; FDirSrchIntf : IDirectorySearch; FSearchHandle : ADS_SEARCH_HANDLE; FAttributes, FFilter, FBasePath, FObjectClass : Widestring; FResult : HRESULT; FChaseReferrals, FSearchExecuted : Boolean; FMaxRows, FPageSize : Integer; FSearchScope : TSearchScope; procedure EnumerateColumns(aStrList : TStringList); function GetStringValue(oSrchColumn : ads_search_column; Index : Integer) : WideString; procedure SetBaseIADs(const Value: IADs); procedure SetBasePath(const Value: WideString); procedure SetFilter(const Value: WideString); procedure SetObjectClass(const Value: Widestring); procedure SetMaxRows(const Value: Integer); procedure SetPageSize(const Value: Integer); procedure SetAttributes(const Value: WideString); procedure SetChaseReferrals(const Value: Boolean); public constructor Create; destructor Destroy; override; function CheckIfExists() : Boolean; procedure Search; function GetFirstRow() : TStringList; function GetNextRow() : TStringList; // list of attributes to return - empty string equals all attributes property Attributes : WideString read FAttributes write SetAttributes; // search base - both as an IADs interface, as well as a LDAP path property BaseIADs : IADs read FBaseIADs write SetBaseIADs stored False; property BasePath : WideString read FBasePath write SetBasePath; // chase possible referrals to other domain controllers? property ChaseReferrals : Boolean read FChaseReferrals write SetChaseReferrals default False; // "raw" search interface - for any low-level tweaking necessary property DirSrchIntf : IDirectorySearch read FDirSrchIntf; // LDAP filter to limit the search property Filter : WideString read FFilter write SetFilter; // maximum number of rows to return - 0 = all rows (no limit) property MaxRows : Integer read FMaxRows write SetMaxRows default 0; property ObjectClass : Widestring read FObjectClass write SetObjectClass; property PageSize : Integer read FPageSize write SetPageSize default 100; property SearchScope : TSearchScope read FSearchScope write FSearchScope default scSubtree; end; const // ADSI success codes S_ADS_ERRORSOCCURRED = $00005011; S_ADS_NOMORE_ROWS = $00005012; S_ADS_NOMORE_COLUMNS = $00005013; // ADSI error codes E_ADS_BAD_PATHNAME = $80005000; E_ADS_INVALID_DOMAIN_OBJECT = $80005001; E_ADS_INVALID_USER_OBJECT = $80005002; E_ADS_INVALID_COMPUTER_OBJECT = $80005003; E_ADS_UNKNOWN_OBJECT = $80005004; E_ADS_PROPERTY_NOT_SET = $80005005; E_ADS_PROPERTY_NOT_SUPPORTED = $80005006; E_ADS_PROPERTY_INVALID = $80005007; E_ADS_BAD_PARAMETER = $80005008; E_ADS_OBJECT_UNBOUND = $80005009; E_ADS_PROPERTY_NOT_MODIFIED = $8000500A; E_ADS_PROPERTY_MODIFIED = $8000500B; E_ADS_CANT_CONVERT_DATATYPE = $8000500C; E_ADS_PROPERTY_NOT_FOUND = $8000500D; E_ADS_OBJECT_EXISTS = $8000500E; E_ADS_SCHEMA_VIOLATION = $8000500F; E_ADS_COLUMN_NOT_SET = $80005010; E_ADS_INVALID_FILTER = $80005014; (*============================================================================*) (* IMPLEMENTATION *) (*============================================================================*) implementation uses Windows; var ActiveDSHandle : THandle; gADsGetObject: function(pwcPathName: PWideChar; const xRIID: TGUID; out pVoid): HResult; stdcall; gFreeADsMem : function(aPtr : Pointer) : BOOL; stdcall; // Active Directory API helper functions - implemented in ActiveDs.DLL and // dynamically loaded at time of initialization of this module function ADsGetObject(pwcPathName: PWideChar; const xRIID: TGUID; var pVoid): HResult; begin Result := gADsGetObject(pwcPathName, xRIID, pVoid); end; function FreeADsMem(aPtr : Pointer) : BOOL; begin Result := gFreeADsMem(aPtr); end; // resource strings for all messages - makes localization so much easier! resourcestring rc_CannotLoadActiveDS = 'Cannot load ActiveDS.DLL'; rc_CannotGetProcAddress = 'Cannot GetProcAddress of '; rc_CouldNotBind = 'Could not bind to object %s (%x)'; rc_CouldNotFreeSH = 'Could not free search handle (%x)'; rc_CouldNotGetIDS = 'Could not obtain IDirectorySearch interface for %s (%x)'; rc_GetFirstFailed = 'GetFirstRow failed (%x)'; rc_GetNextFailed = 'GetNextRow failed (%x)'; rc_SearchFailed = 'Search in ADSI failed (result code %x)'; rc_SearchNotExec = 'Search has not been executed yet'; rc_SetSrchPrefFailed = 'Setting the max row limit failed (%x)'; rc_UnknownDataType = '(unknown data type %d)'; // --------------------------------------------------------------------------- // Constructor and destructor // --------------------------------------------------------------------------- constructor TADSISearch.Create; begin inherited Create; FBaseIADs := nil; FDirSrchIntf := nil; FAttributes := ''; FBasePath := ''; FFilter := ''; FObjectClass := '*'; FMaxRows := 0; FPageSize := 100; FChaseReferrals := False; FSearchScope := scSubtree; FSearchExecuted := False; end; destructor TADSISearch.Destroy; begin if (FSearchHandle <> 0) then FResult := FDirSrchIntf.CloseSearchHandle(FSearchHandle); FBaseIADs := nil; FDirSrchIntf := nil; inherited; end; // --------------------------------------------------------------------------- // Set and Get methods // --------------------------------------------------------------------------- procedure TADSISearch.SetAttributes(const Value: WideString); begin if (FAttributes <> Value) then begin FAttributes := Value; end; end; // the methods to set the search base always need to update the other property // as well, in order to make sure the base IADs interface and the BasePath // property stay in sync // setting the search base will require a new search // therefore set internal flag FSearchExecuted to false procedure TADSISearch.SetBaseIADs(const Value: IADs); begin if (FBaseIADs <> Value) then begin FBaseIADs := Value; FBasePath := FBaseIADs.ADsPath; FSearchExecuted := False; end; end; procedure TADSISearch.SetBasePath(const Value: WideString); begin if (FBasePath <> Value) then begin FBasePath := Value; FBaseIADs := nil; FSearchExecuted := False; end; end; procedure TADSISearch.SetChaseReferrals(const Value: Boolean); begin if (FChaseReferrals <> Value) then begin FChaseReferrals := Value; end; end; // setting the filter will require a new search // therefore set internal flag FSearchExecuted to false procedure TADSISearch.SetFilter(const Value: WideString); begin if (FFilter <> Value) then begin FFilter := Value; FSearchExecuted := False; end; end; procedure TADSISearch.SetMaxRows(const Value: Integer); begin if (Value >= 0) and (Value <> FMaxRows) then begin FMaxRows := Value; end; end; procedure TADSISearch.SetPageSize(const Value: Integer); begin if (Value >= 0) and (Value <> FPageSize) then begin FPageSize := Value; end; end; // setting the object category will require a new search // therefore set internal flag FSearchExecuted to false procedure TADSISearch.SetObjectClass(const Value: Widestring); begin if (FObjectClass <> Value) then begin if (Value = '') then FObjectClass := '*' else FObjectClass := Value; FSearchExecuted := False; end; end; // --------------------------------------------------------------------------- // Private helper methods // --------------------------------------------------------------------------- // EnumerateColumns iterates through all the columns in the current row of // the search results and builds the string list of results procedure TADSISearch.EnumerateColumns(aStrList: TStringList); var ix : Integer; bMultiple : Boolean; pwColName : PWideChar; oSrchColumn : ads_search_column; wsColName, wsValue : WideString; begin // determine name of next column to fetch FResult := FDirSrchIntf.GetNextColumnName(FSearchHandle, pwColName); // as long as no error occured and we still do have columns.... while Succeeded(FResult) and (FResult <> S_ADS_NOMORE_COLUMNS) do begin // get the column from the result set FResult := FDirSrchIntf.GetColumn(FSearchHandle, pwColName, oSrchColumn); if Succeeded(FResult) then begin // check if it's a multi-valued attribute bMultiple := (oSrchColumn.dwNumValues > 1); if bMultiple then begin // if it's a multi-valued attribute, iterate through the values for ix := 0 to oSrchColumn.dwNumValues-1 do begin wsColName := Format('%s[%d]', [oSrchColumn.pszAttrName, ix]); wsValue := GetStringValue(oSrchColumn, ix); aStrList.Add(wsColName + '=' + wsValue); end; end else begin // single valued attributes are quite straightforward wsColName := oSrchColumn.pszAttrName; wsValue := GetStringValue(oSrchColumn, 0); aStrList.Add(wsColName + '=' + wsValue); end; end; // free the memory associated with the search column, and the column name FDirSrchIntf.FreeColumn(oSrchColumn); FreeADsMem(pwColName); // get next column name FResult := FDirSrchIntf.GetNextColumnName(FSearchHandle, pwColName); end; end; // Get string value will turn the supported types of data into a string representation // for inclusion in the resulting string list // For a complete list of possible values, see the ADSTYPE_xxx constants in the // ActiveDs_TLB.pas file function TADSISearch.GetStringValue(oSrchColumn: ads_search_column; Index: Integer): WideString; var wrkPointer : PADSValue; oSysTime : _SYSTEMTIME; dtDate, dtTime : TDateTime; begin Result := ''; // advance the value pointer to the correct one of the potentially multiple // values in the "array of values" for this attribute wrkPointer := oSrchColumn.pADsValues; Inc(wrkPointer, Index); // depending on the type of the value, turning it into a string is more // or less straightforward case oSrchColumn.dwADsType of ADSTYPE_CASE_EXACT_STRING : Result := wrkPointer^.__MIDL_0010.CaseExactString; ADSTYPE_CASE_IGNORE_STRING : Result := wrkPointer^.__MIDL_0010.CaseIgnoreString; ADSTYPE_DN_STRING : Result := wrkPointer^.__MIDL_0010.DNString; ADSTYPE_OBJECT_CLASS : Result := wrkPointer^.__MIDL_0010.ClassName; ADSTYPE_PRINTABLE_STRING : Result := wrkPointer^.__MIDL_0010.PrintableString; ADSTYPE_NUMERIC_STRING : Result := wrkPointer^.__MIDL_0010.NumericString; ADSTYPE_BOOLEAN : Result := IntToStr(wrkPointer^.__MIDL_0010.Boolean); ADSTYPE_INTEGER : Result := IntToStr(wrkPointer^.__MIDL_0010.Integer); ADSTYPE_LARGE_INTEGER : Result := IntToStr(wrkPointer^.__MIDL_0010.LargeInteger); ADSTYPE_UTC_TIME: begin // ADS_UTC_TIME maps to a _SYSTEMTIME structure Move(wrkPointer^.__MIDL_0010.UTCTime, oSysTime, SizeOf(oSysTime)); // create two TDateTime values for the date and the time dtDate := EncodeDate(oSysTime.wYear, oSysTime.wMonth, oSysTime.wDay); dtTime := EncodeTime(oSysTime.wHour, oSysTime.wMinute, oSysTime.wSecond, oSysTime.wMilliseconds); // add the two TDateTime's (really only a Float), and turn into a string Result := DateTimeToStr(dtDate+dtTime); end; else Result := Format(rc_UnknownDataType, [oSrchColumn.dwADsType]); end; end; // --------------------------------------------------------------------------- // Public methods // --------------------------------------------------------------------------- // Check if any object matching the criteria as defined in the properties exists function TADSISearch.CheckIfExists(): Boolean; var slTemp : TStringList; iOldMaxRows : Integer; wsOldAttributes : WideString; begin Result := False; // save the settings of the MaxRows and Attributes properties iOldMaxRows := FMaxRows; wsOldAttributes := FAttributes; try // set the attributes to return just one row (that's good enough for // making sure it exists), and the Attribute of instanceType which is // one attribute that must exist for any of the ADSI objects FMaxRows := 1; FAttributes := 'instanceType'; try Search; // did we get any results?? If so, at least one object exists! slTemp := GetFirstRow(); Result := (slTemp <> nil); slTemp.Free; except on EADSISearchException do ; end; finally // restore the attributes to what they were before FMaxRows := iOldMaxRows; FAttributes := wsOldAttributes; end; end; function TADSISearch.GetFirstRow(): TStringList; var slTemp : TStringList; begin slTemp := nil; try if FSearchExecuted then begin // get the first row of the result set FResult := FDirSrchIntf.GetFirstRow(FSearchHandle); // did we succeed? ATTENTION: if we don't have any more rows, // we still get a "success" value back from ADSI!! if Succeeded(FResult) then begin // any more rows in the result set? if (FResult <> S_ADS_NOMORE_ROWS) then begin // create a string list slTemp := TStringList.Create; // enumerate all columns into that resulting string list EnumerateColumns(slTemp); end; end else begin raise EADSISearchException.CreateFmt(rc_GetFirstFailed, [FResult]); end; end else begin raise EADSISearchException.Create(rc_SearchNotExec); end; finally Result := slTemp; end; end; function TADSISearch.GetNextRow(): TStringList; var slTemp : TStringList; begin slTemp := nil; try if FSearchExecuted then begin // get the next row of the result set FResult := FDirSrchIntf.GetNextRow(FSearchHandle); // did we succeed? ATTENTION: if we don't have any more rows, // we still get a "success" value back from ADSI!! if Succeeded(FResult) then begin // any more rows in the result set? if (FResult <> S_ADS_NOMORE_ROWS) then begin // create result string list slTemp := TStringList.Create; // enumerate all columns in result set EnumerateColumns(slTemp); end; end else begin raise EADSISearchException.CreateFmt(rc_GetNextFailed, [FResult]); end; end else begin raise EADSISearchException.Create(rc_SearchNotExec); end; finally Result := slTemp; end; end; // this is the core piece of the component - the actual search method procedure TADSISearch.Search; var ix : Integer; wsFilter : WideString; slTemp : TStringList; AttrCount : Cardinal; AttrArray : array of WideString; SrchPrefInfo : array of ads_searchpref_info; begin // check to see if we have assigned an IADs, if not, bind to it if (FBaseIADs = nil) then begin FResult := ADsGetObject(@FBasePath[1], IID_IADs, FBaseIADs); if not Succeeded(FResult) then begin raise EADSISearchException.CreateFmt(rc_CouldNotBind, [FBasePath, FResult]); end; end; // get the IDirectorySearch interface from the base object FDirSrchIntf := (FBaseIADs as IDirectorySearch); if (FDirSrchIntf = nil) then begin raise EADSISearchException.CreateFmt(rc_CouldNotGetIDS, [FBasePath, FResult]); end; // if we still have a valid search handle => close it if (FSearchHandle <> 0) then begin FResult := FDirSrchIntf.CloseSearchHandle(FSearchHandle); if not Succeeded(FResult) then begin raise EADSISearchException.CreateFmt(rc_CouldNotFreeSH, [FResult]); end; end; // we are currently setting 3 search preferences // for a complete list of possible search preferences, please check // the ADS_SEARCHPREF_xxx values in ActiveDs_TLB.pas SetLength(SrchPrefInfo, 4); // Set maximum number of rows to be what is defined in the MaxRows property SrchPrefInfo[0].dwSearchPref := ADS_SEARCHPREF_SIZE_LIMIT; SrchPrefInfo[0].vValue.dwType := ADSTYPE_INTEGER; SrchPrefInfo[0].vValue.__MIDL_0010.Integer := FMaxRows; // set the "chase referrals" search preference SrchPrefInfo[1].dwSearchPref := ADS_SEARCHPREF_CHASE_REFERRALS; SrchPrefInfo[1].vValue.dwType := ADSTYPE_BOOLEAN; SrchPrefInfo[1].vValue.__MIDL_0010.Boolean := Ord(FChaseReferrals); // set the "search scope" search preference SrchPrefInfo[2].dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE; SrchPrefInfo[2].vValue.dwType := ADSTYPE_INTEGER; SrchPrefInfo[2].vValue.__MIDL_0010.Integer := Ord(FSearchScope); // set the "page size " search preference SrchPrefInfo[3].dwSearchPref := ADS_SEARCHPREF_PAGESIZE; SrchPrefInfo[3].vValue.dwType := ADSTYPE_INTEGER; SrchPrefInfo[3].vValue.__MIDL_0010.Integer := FPageSize; // set the search preferences of our directory search interface FResult := FDirSrchIntf.SetSearchPreference(Pointer(SrchPrefInfo), Length(SrchPrefInfo)); if not Succeeded(FResult) then begin raise EADSISearchException.CreateFmt(rc_SetSrchPrefFailed, [FResult]); end; // hack together the filter if (FFilter = '') then wsFilter := Format('(objectClass=%s)', [FObjectClass]) else wsFilter := Format('(&(objectClass=%s)(%s))', [FObjectClass, FFilter]); // get attributes if (FAttributes <> '') then begin slTemp := TStringList.Create; // we support a list of attributes, separated by comma, so assigning the // string to the .CommaText property of the string list will load the // string list with all the values slTemp.CommaText := Attributes; // how many attributes did we specify? We need to size our array accordingly AttrCount := slTemp.Count; SetLength(AttrArray, AttrCount); // assign the values to the attribute array for ix := 0 to AttrCount-1 do begin AttrArray[ix] := slTemp[ix]; end; slTemp.Free; end else begin // we did not specify any attributes - set the count to -1 and the array to nil AttrCount := Cardinal(-1); AttrArray := nil; end; // execute search FResult := FDirSrchIntf.ExecuteSearch(@wsFilter[1], AttrArray, AttrCount, FSearchHandle); if not Succeeded(FResult) then begin raise EADSISearchException.CreateFmt(rc_SearchFailed, [FResult]); end; FSearchExecuted := True; end; initialization // try to load the ActiveDs.DLL library - should be in your system32 directory ActiveDSHandle := LoadLibrary('ActiveDS.dll'); if (ActiveDSHandle = 0) then raise Exception.Create(rc_CannotLoadActiveDS); // bind the ADsGetObject helper function gADsGetObject := GetProcAddress(ActiveDSHandle, 'ADsGetObject'); if not Assigned(gADsGetObject) then raise Exception.Create(rc_CannotGetProcAddress + 'ADsGetObject'); // bind the FreeADsMem helper function gFreeADsMem := GetProcAddress(ActiveDSHandle, 'FreeADsMem'); if not Assigned(gFreeADsMem) then raise Exception.Create(rc_CannotGetProcAddress + 'FreeADsMem'); finalization // if we had loaded an instance of ActiveDs.DLL, release it if (ActiveDSHandle <> 0) then FreeLibrary(ActiveDSHandle); end.
unit uGrantRulesAdd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxButtonEdit, StdCtrls, cxButtons, cxMemo, cxMaskEdit, cxDropDownEdit, cxCalendar, cxTextEdit, cxControls, cxContainer, cxEdit, cxLabel, ibase, ucs_types,uCs_loader, cxCurrencyEdit, ActnList, Menus; type TfmGrantRulesAdd = class(TForm) LabelSubType: TcxLabel; cxLabel2: TcxLabel; cxLabel3: TcxLabel; cxLabel4: TcxLabel; DateEditBeg: TcxDateEdit; DateEditEnd: TcxDateEdit; MemoNote: TcxMemo; OkButton: TcxButton; CancelButton: TcxButton; Labelkoef: TcxLabel; LabelAddSum: TcxLabel; ButtonEditSubType: TcxButtonEdit; LabelMinGrant: TcxLabel; ButtonEditMinGrant: TcxButtonEdit; cxLabel1: TcxLabel; TextEditKoef: TcxCurrencyEdit; TextEditAddSum: TcxCurrencyEdit; ActionList1: TActionList; ActionSave: TAction; ActionExit: TAction; TextEditAllSum: TcxCurrencyEdit; procedure CancelButtonClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure ButtonEditSubTypePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure ButtonEditMinGrantPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure TextEditKoefExit(Sender: TObject); procedure TextEditKoefKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public id_min_sum, id_grant_subType : variant; id_grant_rules : variant; DB_handle : TISC_DB_HANDLE; constructor Create(AOwner:TComponent);reintroduce; end; {var fmGrantRulesAdd: TfmGrantRulesAdd; } implementation uses DM_GrantRules; {$R *.dfm} constructor TfmGrantRulesAdd.Create(AOwner:TComponent); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); Screen.Cursor:=crDefault; end; procedure TfmGrantRulesAdd.CancelButtonClick(Sender: TObject); begin close; end; procedure TfmGrantRulesAdd.OkButtonClick(Sender: TObject); begin if (id_grant_subType= null) then Begin ShowMessage('Необхідно вибрати тип стипендії!'); ButtonEditSubType.SetFocus; Exit; end; if (id_min_sum = null) then Begin ShowMessage('Необхідно вибрати розмір мінімальної стипендії!'); ButtonEditSubType.SetFocus; Exit; end; if (TextEditKoef.Text = '') then Begin ShowMessage('Необхідно заповнити коефіцієнт!'); TextEditKoef.SetFocus; Exit; end; if (TextEditAddSum.Text = '') then Begin ShowMessage('Необхідно заповнити додаткову суму!'); TextEditAddSum.SetFocus; Exit; end; if (DateEditBeg.Text = '') then Begin ShowMessage('Необхідно заповнити дату початку!'); DateEditBeg.SetFocus; Exit; end; if (DateEditEnd.Text = '') then Begin ShowMessage('Необхідно заповнити дату кінця!'); DateEditEnd.SetFocus; Exit; end; if (DateEditBeg.Date > DateEditEnd.Date) then Begin ShowMessage('Дата початку не може перевищувати дату кінця!'); DateEditBeg.SetFocus; Exit; end; ModalResult := mrok; end; procedure TfmGrantRulesAdd.ButtonEditSubTypePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var AParameter: TcsParamPacks; res : variant; begin AParameter := TcsParamPacks.Create; AParameter.Owner := self; AParameter.Db_Handle := dm.Db.Handle; AParameter.Formstyle := fsNormal; res := DoFunctionFromPackage(AParameter, ['Contingent_Student\CS_SubTypeGrant.bpl', 'ShowGrantSubType']); AParameter.Free; if VarArrayDimCount(res)>0 then begin id_grant_subType := res[0]; ButtonEditSubType.Text:= vartostr(res[1]); end; end; procedure TfmGrantRulesAdd.ButtonEditMinGrantPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var AParameter: TcsParamPacks; res : variant; begin AParameter := TcsParamPacks.Create; AParameter.Owner := self; AParameter.Db_Handle := dm.Db.Handle; AParameter.Formstyle := fsNormal; res := DoFunctionFromPackage(AParameter, ['Contingent_Student\CS_SpMinGrant.bpl', 'ShowSpGrantMin']); AParameter.Free; if VarArrayDimCount(res)>0 then begin id_min_sum := res[0]; ButtonEditMinGrant.Text:= currtostr(res[1]); TextEditKoefExit(self); end; end; procedure TfmGrantRulesAdd.TextEditKoefExit(Sender: TObject); var summa_all, min_grant : currency; begin if(TextEditKoef.Text= '') then TextEditKoef.Text := '1,0000'; if(ButtonEditMinGrant.Text= '') then min_grant := 0 else min_grant := strtocurr(ButtonEditMinGrant.Text); if(TextEditAddSum.Text= '') then TextEditAddSum.Text := '0,00'; summa_all := min_grant*strtocurr(TextEditKoef.Text)+ strtocurr(TextEditAddSum.Text); TextEditAllSum.Text := currtostr(summa_all); end; procedure TfmGrantRulesAdd.TextEditKoefKeyPress(Sender: TObject; var Key: Char); begin if (Key = '-') then Key := Chr(0); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Project.Interfaces; interface uses Spring.Collections, System.Generics.Defaults, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Dependency.Interfaces, DPM.Core.Package.Interfaces; {$SCOPEDENUMS ON} type IProjectConfiguration = interface ['{2A251BA1-1D1E-4D0A-95B0-BD0036A14D94}'] function GetPlatform : TDPMPlatform; function GetName : string; function GetOutputDir : string; function GetUsesRuntimePackages : boolean; function GetPackages : IList<string>; property Platform : TDPMPlatform read GetPlatform; property Name : string read GetName; property OutputDir : string read GetOutputDir; property UsesRuntimePackages : boolean read GetUsesRuntimePackages; property Packages : IList<string> read GetPackages; end; TAppType = (Application, Package,Lib, Unknown); TProjectElement = (ProjectVersion,MainSource, AppType, Platforms, Configs, PackageRefs, All); TProjectElements = set of TProjectElement; //used by the package installer IProjectEditor = interface ['{CFF241F9-8B5B-44FC-95FC-6C1A015637E9}'] function GetCompilerVersion : TCompilerVersion; function GetPlatforms : TDPMPlatforms; function GetProjectVersion : string; function GetAppType : TAppType; function GetHasPackages : boolean; function GetProjectFile : string; procedure SetCompiler(const value : TCompilerVersion); function LoadProject(const filename : string; const elements : TProjectElements = [TProjectElement.All]) : boolean; procedure Reset; procedure RemoveFromSearchPath(const platform : TDPMPlatform; const packageId : string); function AddSearchPaths(const platform : TDPMPlatform; const searchPaths : IList<string>; const packageCacheLocation : string) : boolean; procedure UpdatePackageReferences(const dependencyGraph : IPackageReference; const platform : TDPMPlatform); function GetPackageReferences(const platform : TDPMPlatform) : IPackageReference; function GetProjectConfiguration(const name : string; const platform : TDPMPlatform) : IProjectConfiguration; function GetConfigNames : IReadOnlyList<string>; function SaveProject(const fileName : string = '') : boolean; property CompilerVersion : TCompilerVersion read GetCompilerVersion write SetCompiler; property ProjectVersion : string read GetProjectVersion; property Platforms : TDPMPlatforms read GetPlatforms; property AppType : TAppType read GetAppType; property HasPackages : boolean read GetHasPackages; property ProjectFile : string read GetProjectFile; end; IGroupProjectReader = interface ['{D7E07C8A-A9C1-44B3-9306-F00EDFB9825D}'] function LoadGroupProj(const groupProjFile : string) : boolean; procedure Close; function ExtractProjects(const list : IList<string>) : boolean; end; // //just compares id's, not version! // TPackageRefenceComparer = class(TInterfacedObject,IEqualityComparer<IPackageReference>) // protected // function Equals(const Left, Right: IPackageReference): Boolean;reintroduce; // function GetHashCode(const Value: IPackageReference): Integer; reintroduce; // end; implementation //// For Delphi XE3 and up: //{$IF CompilerVersion >= 24.0 } // {$LEGACYIFEND ON} //{$IFEND} //uses // {$IF CompilerVersion >= 29.0} // System.Hash, // {$IFEND} // System.SysUtils; //{ TPackageRefenceComparer } // //function TPackageRefenceComparer.Equals(const Left, Right: IPackageReference): Boolean; //begin // result := SameText(Left.Id, Right.Id); //end; // //function TPackageRefenceComparer.GetHashCode(const Value: IPackageReference): Integer; //var // s : string; //begin // s := Value.Id; // {$IF CompilerVersion >= 29.0} // Result := System.Hash.THashBobJenkins.GetHashValue(s); // {$ELSE} // Result := BobJenkinsHash(PChar(s)^, SizeOf(Char) * Length(s), 0); // {$IFEND} //end; end.
unit uLogController; interface uses SysUtils, uPadraoDAO, dialogs, FireDAC.Comp.Client, uDmAcessaBanco, uUsuarioModel; type TLogController = class private FUsuario: TUsuarioModel; FQuery: TFDQuery; procedure SetUsuario(const Value: TUsuarioModel); function RetornaPrimaryKey(ACampoCodigo, ATabela: String): Integer; public property Usuario: TUsuarioModel read FUsuario write SetUsuario; procedure GravaLog(ADescricao: String); constructor Create; destructor Destroy; override; end; implementation { TLogController } constructor TLogController.Create; begin FQuery := TFDQuery.Create(nil); FQuery.Connection := DmAcessaBanco.fdcLYS; end; destructor TLogController.Destroy; begin FreeAndNil(FQuery); inherited; end; procedure TLogController.GravaLog(ADescricao: String); var LCodigo: Integer; begin LCodigo := RetornaPrimaryKey('CODIGO','LOG'); if FQuery.Active then FQuery.Close; FQuery.SQL.Text := 'INSERT INTO LOG VALUES (:codigo, :usuario_codigo, :descricao, :horario)'; FQuery.ParamByName('codigo').AsInteger := LCodigo; FQuery.ParamByName('usuario_codigo').AsInteger := FUsuario.Codigo; FQuery.ParamByName('descricao').AsString := ADescricao; FQuery.ParamByName('horario').AsDateTime := Now; FQuery.ExecSQL; end; function TLogController.RetornaPrimaryKey(ACampoCodigo, ATabela: String): Integer; begin FQuery.SQL.Text := 'SELECT MAX(' + ACampoCodigo + ') CODIGO FROM ' + ATabela; FQuery.Open; try Result := FQuery.FieldByName('CODIGO').AsInteger + 1; finally FQuery.Close; end; end; procedure TLogController.SetUsuario(const Value: TUsuarioModel); begin FUsuario := Value; end; end.
unit TestStudentEditDialog; interface uses Controls, uStudentEditDialog, FutureWindows; implementation uses Windows, Messages, SysUtils, TestFramework, TestCaseBase, uModel, Forms; type TStudentEditDialogTestCase = class(TTestCaseBase) published procedure TestEditCadastro1; procedure TestEditCadastro2; procedure TestCloseForm; end; TEditStudentFutureWindowAction = class(TAbstractWindowAction) strict private FName: string; FEmail: string; FDate: TDate; protected procedure Execute(const AWindow: IWindow); override; public constructor Create(const AName, AEmail: string; ADate: TDate); end; { TStudentEditDialogTestCase } procedure TStudentEditDialogTestCase.TestCloseForm; var student: IStudent; futureWindow: IFutureWindow; begin student := TModel.CreateStudent(); futureWindow := TFutureWindows.Expect(TStudentEditDialog.ClassName) .ExecPauseAction(0.5, Application.ProcessMessages) .ExecCloseWindow() ; CheckFalse(TStudentEditDialog.Edit(student)); end; procedure TStudentEditDialogTestCase.TestEditCadastro1; var student: IStudent; futureWindow: IFutureWindow; dateOfBirth: TDate; const NAME = 'Joćo da Silva'; EMAIL = 'joao@dasilva.com'; begin dateOfBirth := EncodeDate(1980, 1, 1); student := TModel.CreateStudent(); futureWindow := TFutureWindows.Expect(TStudentEditDialog.ClassName); futureWindow.ExecAction(TEditStudentFutureWindowAction.Create( NAME, EMAIL, dateOfBirth )); Check(TStudentEditDialog.Edit(student)); Check(futureWindow.WindowFound, 'window not found: ' + futureWindow.Description); CheckEquals(NAME, student.Name); CheckEquals(EMAIL, student.Email); CheckEquals(dateOfBirth, student.DateOfBirth, 0.1); end; procedure TStudentEditDialogTestCase.TestEditCadastro2; var student: IStudent; futureWindow: IFutureWindow; dateOfBirth: TDate; const NAME = 'Leonardo Gregianin'; EMAIL = 'leogregianin@gmail.com'; begin dateOfBirth := EncodeDate(1980, 1, 1); student := TModel.CreateStudent(); futureWindow := TFutureWindows.Expect(TStudentEditDialog.ClassName); futureWindow.ExecAction(TEditStudentFutureWindowAction.Create( NAME, EMAIL, dateOfBirth )); Check(TStudentEditDialog.Edit(student)); Check(futureWindow.WindowFound, 'window not found: ' + futureWindow.Description); CheckEquals(NAME, student.Email, 'Campo nome'); CheckEquals(EMAIL, student.Email, 'Campo email'); CheckEquals(dateOfBirth, student.DateOfBirth, 0.1); end; { TTestEditAction } constructor TEditStudentFutureWindowAction.Create(const AName, AEmail: string; ADate: TDate); begin FName := AName; FEmail := AEmail; FDate := ADate; end; procedure TEditStudentFutureWindowAction.Execute(const AWindow: IWindow); var dlg: TStudentEditDialog; begin Assert(AWindow.AsControl is TStudentEditDialog); dlg := AWindow.AsControl as TStudentEditDialog; dlg.edName.Text := FName; dlg.edEmail.Text := FEmail; dlg.dtpDateOfBirth.Date := FDate; // let us see the changes TTestCaseBase.ProcessMessages(0); dlg.OKBtn.Click; end; initialization RegisterTest(TStudentEditDialogTestCase.Suite); end.
unit ModuleOperationsUnit; interface uses System.Types, Winapi.Windows, System.SysUtils, SplashScreenUnit, System.Classes, TypInfo; const ProcCountPerModule = 21; ControlCodeMarker = '>'; StartAll = -1; type TModuleType = (input_and_output, only_input, only_output, no_input_and_no_output, parser, undetermined, erroneous_or_empty); TWindowState = (closed, opened, window_does_not_exist); TModuleState = (working, sleeping, module_cant_sleep); TModuleTypeRussian = (ввод_и_вывод, только_ввод, только_вывод, без_ввода_и_без_вывода, парсер, неопределён, ошибочен_или_пуст); TWindowStateRussian = (закрыто, открыто, окно_не_существует); TModuleStateRussian = (работает, спит, модуль_не_может_спать); TModuleStatistics = record Empty: boolean; TimesLoaded: Integer; end; TModule = record Handle: THandle; Name, FileName, ControlCode, ControlCodeFormated: String; MType: TModuleType; WindowState: TWindowState; ModuleState: TModuleState; HelpTopicID: Integer; Statistics: TModuleStatistics; SetLanguage: function(Language: PChar): boolean; stdcall; SendLanguageData: function(Data: array of PChar): boolean; stdcall; GetName: function: PChar; stdcall; GetHelp: function: PChar; stdcall; Start: procedure; stdcall; Sleep: function: boolean; stdcall; WakeUp: procedure; stdcall; OpenWindow: procedure; stdcall; CloseWindow: procedure; stdcall; SetVirtual: procedure(Name: PChar); stdcall; SaveData: procedure; stdcall; LoadData: procedure; stdcall; Reset: procedure; stdcall; SetNewMainWindow: procedure(Position, Size: TPoint); stdcall; GetTimerInterval: function: Integer; stdcall; SendData: procedure(Data: PChar); stdcall; GetData: function: PChar; stdcall; SetSource: procedure(SourcePath: PChar); stdcall; NextData: function: PChar; stdcall; Progress: function: Real; stdcall; RestartParsing: procedure; stdcall; end; TModules = array of TModule; var Module, ModuleSelected: TModules; ProgessFloat: Single; ProgressInt: Int64; ProgressSteps: Int64; PathToModules: String; procedure FindModules(Path: String); procedure LoadModules; function LoadModule(var M: TModule): boolean; procedure AddNewModule(FileName: String); procedure FreeModules; procedure FreeModule(var M: TModule); function DetermineModuleType(var M: TModule): TModuleType; procedure IncAndUpdateProgress(val: Int64 = 1); function FindModuleByFileName(FN: String): TModule; function FindModuleIDByFileName(FN: String): Integer; procedure AddModulesHelpToMainProgramHelp; procedure ChangeModulesLanguageToProgramLanguage; function GetInfoAbout(M: TModule): TStrings; function GetStatisticsSummary(M: TModule): TStrings; procedure ToogleModuleWindow(ID: Integer); procedure ToogleModuleSleepMode(ID: Integer); procedure StartModule(ID: Integer); procedure StartSelectedModules(IDs: array of Integer); procedure StartAllModules; procedure CloseAllWindows; function AreWindowsClosed: boolean; procedure SaveAllData; implementation uses MainWindowUnit, HelpWindowUnit; procedure FindModules(Path: String); var R: Integer; SR: TSearchRec; begin SetLength(Module, 0); SetCurrentDir(Path); R := FindFirst('*.dll', 0, SR); while R = 0 do begin SetLength(Module, Length(Module) + 1); Module[Length(Module) - 1].FileName := SR.Name; Module[Length(Module) - 1].Handle := 0; R := FindNext(SR); end; FindClose(SR); PathToModules := Path; ProgressSteps := Length(Module) * ProcCountPerModule; ProgressInt := 0; end; procedure LoadModules; var i: Integer; begin for i := 0 to Length(Module) - 1 do begin if Module[i].Handle > 0 then FreeModule(Module[i]); if LoadModule(Module[i]) then DetermineModuleType(Module[i]); end; end; function LoadModule(var M: TModule): boolean; procedure LoadStatistics; begin M.Statistics.Empty := true; end; function FormatControlCode(Code: String): String; var i: Integer; R: String; begin R := ''; for i := 1 to Length(Code) do R := R + '#' + IntToStr(Ord(Code[i])); Result := R; end; var B: String; C: Integer; begin with M do begin Handle := LoadLibrary(PWideChar(FileName)); if Handle > 0 then begin @SetLanguage := GetProcAddress(Handle, 'SetLanguage'); IncAndUpdateProgress; @SendLanguageData := GetProcAddress(Handle, 'SendLanguageData'); IncAndUpdateProgress; @GetName := GetProcAddress(Handle, 'GetName'); IncAndUpdateProgress; @GetHelp := GetProcAddress(Handle, 'GetHelp'); IncAndUpdateProgress; @Start := GetProcAddress(Handle, 'Start'); IncAndUpdateProgress; @Sleep := GetProcAddress(Handle, 'Sleep'); IncAndUpdateProgress; @WakeUp := GetProcAddress(Handle, 'WakeUp'); IncAndUpdateProgress; @OpenWindow := GetProcAddress(Handle, 'OpenWindow'); IncAndUpdateProgress; @CloseWindow := GetProcAddress(Handle, 'CloseWindow'); IncAndUpdateProgress; @SetVirtual := GetProcAddress(Handle, 'SetVirtual'); IncAndUpdateProgress; @SaveData := GetProcAddress(Handle, 'SaveData'); IncAndUpdateProgress; @LoadData := GetProcAddress(Handle, 'LoadData'); IncAndUpdateProgress; @Reset := GetProcAddress(Handle, 'Reset'); IncAndUpdateProgress; @SetNewMainWindow := GetProcAddress(Handle, 'SetNewMainWindow'); IncAndUpdateProgress; @GetTimerInterval := GetProcAddress(Handle, 'GetTimerInterval'); IncAndUpdateProgress; @SendData := GetProcAddress(Handle, 'SendData'); IncAndUpdateProgress; @GetData := GetProcAddress(Handle, 'GetData'); IncAndUpdateProgress; @SetSource := GetProcAddress(Handle, 'SetSource'); IncAndUpdateProgress; @NextData := GetProcAddress(Handle, 'NextData'); IncAndUpdateProgress; @Progress := GetProcAddress(Handle, 'Progress'); IncAndUpdateProgress; @RestartParsing := GetProcAddress(Handle, 'RestartParsing'); IncAndUpdateProgress; if @GetName <> nil then begin B := GetName; C := Pos(ControlCodeMarker, B); if C > 0 then begin Name := Copy(B, C + 1, Length(B)); ControlCode := Copy(B, 1, C - 1); ControlCodeFormated := FormatControlCode(ControlCode); end else begin Name := B; ControlCode := MainForm.LanguageData[133]; end; end else begin Name := MainForm.LanguageData[114]; ControlCode := MainForm.LanguageData[133]; end; if (@OpenWindow <> nil) and (@CloseWindow <> nil) then WindowState := closed else WindowState := window_does_not_exist; if (@Sleep <> nil) and (@WakeUp <> nil) then ModuleState := working else ModuleState := module_cant_sleep; LoadStatistics; Result := true; end else Result := false; end; end; procedure AddNewModule(FileName: String); begin SetLength(Module, Length(Module) + 1); Module[Length(Module) - 1].FileName := FileName; LoadModule(Module[Length(Module) - 1]); end; procedure FreeModules; var i: Integer; begin for i := 0 to Length(Module) - 1 do FreeModule(Module[i]); SetLength(Module, 0); end; procedure FreeModule(var M: TModule); begin with M do begin FreeLibrary(Handle); Name := ''; FileName := ''; MType := undetermined; WindowState := window_does_not_exist; ModuleState := module_cant_sleep; HelpTopicID := 0; @SetLanguage := nil; @SendLanguageData := nil; @GetName := nil; @GetHelp := nil; @Start := nil; @Sleep := nil; @WakeUp := nil; @OpenWindow := nil; @CloseWindow := nil; @SetVirtual := nil; @SaveData := nil; @LoadData := nil; @Reset := nil; @SetNewMainWindow := nil; @GetTimerInterval := nil; @SendData := nil; @GetData := nil; @SetSource := nil; @NextData := nil; @Progress := nil; @RestartParsing := nil; end; end; function DetermineModuleType(var M: TModule): TModuleType; begin with M do begin MType := undetermined; if (@SetLanguage = nil) and (@SendLanguageData = nil) and (@GetName = nil) and (@GetHelp = nil) and (@Start = nil) and (@Sleep = nil) and (@WakeUp = nil) and (@OpenWindow = nil) and (@CloseWindow = nil) and (@SetVirtual = nil) and (@SaveData = nil) and (@LoadData = nil) and (@Reset = nil) and (@SetNewMainWindow = nil) and (@GetTimerInterval = nil) and (@SendData = nil) and (@GetData = nil) and (@SetSource = nil) and (@NextData = nil) and (@Progress = nil) and (@RestartParsing = nil) then MType := erroneous_or_empty else begin if (@SetSource <> nil) or (@NextData <> nil) or (@Progress <> nil) or (@RestartParsing <> nil) then MType := parser else begin if (@GetData <> nil) and (@SendData <> nil) then MType := input_and_output else if (@GetData <> nil) and (@SendData = nil) then MType := only_input else if (@GetData = nil) and (@SendData <> nil) then MType := only_output else if (@GetData = nil) and (@SendData = nil) then MType := no_input_and_no_output; end; end; Result := MType; end; end; procedure IncAndUpdateProgress(val: Int64 = 1); procedure ShowProgess; begin ProgessFloat := ProgressInt / ProgressSteps * 100; SplashScreen.SetProgress(ProgessFloat); end; begin inc(ProgressInt, val); case MainForm.SavedSplashScreenState of 0: ShowProgess; 1: if ProgressInt mod ProcCountPerModule = 0 then ShowProgess; 2: ; end; end; function FindModuleByFileName(FN: String): TModule; var M: TModule; begin for M in Module do if M.FileName = FN then Result := M; end; function FindModuleIDByFileName(FN: String): Integer; var i: Integer; begin Result := -1; for i := 0 to Length(Module) - 1 do if Module[i].FileName = FN then Result := i; end; procedure AddModulesHelpToMainProgramHelp; function GetStrings(ID: Integer): TStrings; function Slice(var S: String; C: Char): String; var P: Integer; begin P := Pos(C, S); if P > 0 then begin Result := Copy(S, 1, P - 1); Delete(S, 1, P); end else begin Result := S; S := ''; end; end; var HT: String; begin Result := TStringList.Create; HT := String(Module[ID].GetHelp); while HT <> '' do Result.Add(Slice(HT, #13)); end; var i: Integer; begin for i := 0 to Length(Module) - 1 do if @Module[i].GetHelp <> nil then Module[i].HelpTopicID := HelpForm.AddTopic(MainForm.LanguageData[69] + ' "' + Module[i].Name + '"', GetStrings(i)); end; procedure ChangeModulesLanguageToProgramLanguage; var M: TModule; begin for M in Module do if @M.SetLanguage <> nil then M.SetLanguage(PChar(MainForm.LanguageData[0])) else if @M.SendLanguageData <> nil then M.SendLanguageData(PChar(MainForm.LanguageData)); end; function GetInfoAbout(M: TModule): TStrings; function UnderlineToSpace(str: String): String; var n: Integer; S: String; begin S := str; n := Pos('_', S); while n > 0 do begin S[n] := #32; n := Pos('_', S); end; Result := S; end; begin Result := TStringList.Create; with Result, M, MainForm do begin Add(LanguageData[119] + #32 + IntToStr(M.Handle)); Add(LanguageData[120] + #32 + M.Name); Add(LanguageData[121] + #32 + FileName); Add(LanguageData[132] + #32 + ControlCodeFormated); if LanguageData[0] = 'Russian' then begin Add(LanguageData[122] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TModuleTypeRussian), Ord(MType)))); Add(LanguageData[123] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TWindowStateRussian), Ord(M.WindowState)))); Add(LanguageData[124] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TModuleStateRussian), Ord(ModuleState)))); end else begin Add(LanguageData[122] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TModuleType), Ord(MType)))); Add(LanguageData[123] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TWindowState), Ord(M.WindowState)))); Add(LanguageData[124] + #32 + UnderlineToSpace (GetEnumName(TypeInfo(TModuleState), Ord(ModuleState)))); end; Add(LanguageData[125] + #32 + IntToStr(HelpTopicID)); if Statistics.Empty then Add(LanguageData[126]) else Add(LanguageData[127]); Add(''); Add(LanguageData[128]); if @SetLanguage <> nil then Add('SetLanguage'); if @SendLanguageData <> nil then Add('SendLanguageData'); if @GetName <> nil then Add('GetName'); if @GetHelp <> nil then Add('GetHelp'); if @Start <> nil then Add('Start'); if @Sleep <> nil then Add('Sleep'); if @WakeUp <> nil then Add('WakeUp'); if @OpenWindow <> nil then Add('OpenWindow'); if @CloseWindow <> nil then Add('CloseWindow'); if @SetVirtual <> nil then Add('SetVirtual'); if @SaveData <> nil then Add('SaveData'); if @LoadData <> nil then Add('LoadData'); if @Reset <> nil then Add('Reset'); if @SetNewMainWindow <> nil then Add('SetNewMainWindow'); if @GetTimerInterval <> nil then Add('GetTimerInterval'); if @SendData <> nil then Add('SendData'); if @GetData <> nil then Add('GetData'); if @SetSource <> nil then Add('SetSource'); if @NextData <> nil then Add('NextData'); if @Progress <> nil then Add('Progress'); if @RestartParsing <> nil then Add('RestartParsing'); end; end; function GetStatisticsSummary(M: TModule): TStrings; begin Result := TStringList.Create; with Result, M, MainForm do begin if Statistics.Empty then Add(LanguageData[126]) else begin Add(LanguageData[106] + ': '); end; end; end; procedure ToogleModuleWindow(ID: Integer); begin with Module[ID] do case WindowState of closed: begin OpenWindow; WindowState := opened; end; opened: begin CloseWindow; WindowState := closed; end; window_does_not_exist: ; end; end; procedure ToogleModuleSleepMode(ID: Integer); begin with Module[ID] do case ModuleState of working: begin ModuleState := sleeping; Sleep; end; sleeping: begin ModuleState := working; WakeUp; end; module_cant_sleep: ; end; end; procedure StartModule(ID: Integer); begin with Module[ID] do if @Start <> nil then begin Start; if WindowState = closed then ToogleModuleWindow(ID); if @SetVirtual <> nil then SetVirtual(PChar(MainForm.AVirtual.Name)); if @LoadData <> nil then LoadData; end; end; procedure StartSelectedModules(IDs: array of Integer); function Selected(ID: Integer): boolean; var i: Integer; begin Result := false; for i := 0 to Length(IDs) - 1 do if IDs[i] = ID then begin Result := true; exit; end; end; var i: Integer; begin for i := 0 to Length(Module) - 1 do if Selected(i) or (IDs[0] = StartAll) then StartModule(i); end; procedure StartAllModules; begin StartSelectedModules([StartAll]); end; procedure CloseAllWindows; var i: Integer; begin for i := 0 to Length(Module) - 1 do if Module[i].WindowState = opened then ToogleModuleWindow(i); end; function AreWindowsClosed: boolean; var M: TModule; begin Result := true; for M in Module do if M.WindowState = opened then begin Result := false; exit; end; end; procedure SaveAllData; var M: TModule; begin for M in ModuleSelected do if @M.SaveData <> nil then M.SaveData; end; end.
program example; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads}cthreads,{$ENDIF}{$ENDIF} Classes, SysUtils, Math, FGL, NamedPipes; const ServerInstances = 5; ClientInstances = 20; ClientDelayMin = 100; ClientDelayMax = 500; ClientNumMessages = 3; ServerIdleTimeout = 5000; UniquePipeName = 'EDA5A83C-C5CA-42C6-B07E-F1DBF12CBDD2'; function GetInstanceInfo: String; begin Result := Format('$%x:$%x', [GetProcessID, GetThreadID]); end; procedure PerformTest; var Server: TNamedPipeServerStream; Client: TNamedPipeClientStream; begin Server := TNamedPipeServerStream.Create(UniquePipeName); try Server.Open; Client := TNamedPipeClientStream.Create(UniquePipeName); try Client.Open; Client.WriteAnsiString('Test message at ' + DateTimeToStr(Now)); WriteLn(Server.ReadAnsiString); finally Client.Free; end; finally Server.Free; end; WriteLn('Finished. Press enter key...'); ReadLn; end; procedure PerformServer; var Server: TNamedPipeServerStream; InstanceInfo, Message: String; begin InstanceInfo := GetInstanceInfo; WriteLn(Format('Creating server pipe %s.', [InstanceInfo])); Server := TNamedPipeServerStream.Create(UniquePipeName, pdIn); try Server.MaxInstances := ServerInstances; Server.Open; while True do begin // Wait for connection from clients if not Server.WaitForConnection(ServerIdleTimeout) then begin WriteLn(Format('No connections for %s. Exiting.', [InstanceInfo])); Break; end; // Read all data try while True do begin Message := Server.ReadAnsiString; WriteLn(Format('Message recieved by %s: %s', [InstanceInfo, Message])); end; except // Assume client pipe has closed end; // Disconnect client Server.Disconnect; end; Server.Close; finally Server.Free; end; end; procedure PerformClient; var Client: TNamedPipeClientStream; InstanceInfo, Message: String; MessageCount: Integer; begin InstanceInfo := GetInstanceInfo; WriteLn(Format('Creating client pipe %s.', [InstanceInfo])); Client := TNamedPipeClientStream.Create(UniquePipeName, pdOut); try while not Client.Open(-1) do ; // wait until connects for MessageCount := 1 to ClientNumMessages do begin Sleep(RandomRange(ClientDelayMin, ClientDelayMax)); Message := Format('Hello #%d from client %s at %s.', [MessageCount, InstanceInfo, DateTimeToStr(Now)]); Client.WriteAnsiString(Message); WriteLn(Format('Message sent by %s: %s', [InstanceInfo, Message])); end; Client.Flush; Client.Close; finally Client.Free; end; end; type TThreadList = specialize TFPGObjectList<TThread>; procedure PerformThreads(ThreadProc: TProcedure; CountInstances: Integer); var Index: Integer; Thread: TThread; Threads: TThreadList; begin Threads := TThreadList.Create(True); try for Index := 1 to CountInstances do Threads.Add(TThread.CreateAnonymousThread(ThreadProc)); for Thread in Threads do begin Thread.FreeOnTerminate := False; Thread.Start; end; for Thread in Threads do Thread.WaitFor; finally Threads.Free; end; end; var Action: String; begin Randomize; Action := ParamStr(1); case Action of 'server' : PerformServer; 'client' : PerformClient; 'servers' : PerformThreads(@PerformServer, ServerInstances); 'clients' : PerformThreads(@PerformClient, ClientInstances); 'test' : PerformTest; else WriteLn(Format('Usage: %s [servers|clients|server|client|test]', [ExtractFileName(ParamStr(0))])); end; end.
{ ******************************************************* } { * {* uSeriesTracker.pas {* Delphi Implementation of the Class SeriesTracker {* Generated by Enterprise Architect {* Created on: 09-févr.-2015 11:42:14 {* Original author: Labelleg OK {* {******************************************************* } unit xmltvdb.SeriesTracker; interface uses System.Generics.Collections, System.Classes; type ISeriesTracker = Interface procedure addFail; procedure addSuccess; // order more successful first // function CompareTo(Other: ISeriesTracker): Integer; function getFail: Integer; function getPercentSuccessful: double; function getSeries: String; function getSucess: Integer; function getTotal: Integer; end; TSeriesTracker = class(TInterfacedObject, ISeriesTracker) strict private Ffail: Integer; Fseries: String; Fsucess: Integer; public procedure addFail; procedure addSuccess; // order more successful first // function CompareTo(Other: TSeriesTracker): Integer; function getFail: Integer; function getPercentSuccessful: double; function getSeries: String; function getSucess: Integer; function getTotal: Integer; constructor Create(series: String); destructor Destroy; override; end; TSeriesTrackerHashColl = Class(TObjectDictionary<string, ISeriesTracker>) public constructor Create(); destructor Destroy; override; function Get(const lestring:string):ISeriesTracker ; function IsExist(const lestring:string):Boolean; // procedure Sort; overload; End; ISeriesTrackerColl = interface(IInterfaceListEx) ['{32A73DA8-E34C-4D4C-ABD6-CBCF22B0B59D}'] function Add(const lestring:string;const obj : ISeriesTracker) : integer; function Get(const lestring:string):ISeriesTracker ; function IsExist(const lestring:string):Boolean; end; // TSeriesTrackerHashColl = Class(TInterfaceList, ISeriesTrackerColl) // strict private // FDict : TDictionary<string , ISeriesTracker>; // public // constructor Create(); // destructor Destroy; override; // // function Add(const lestring:string;const obj : ISeriesTracker) : integer; // function Get(const lestring:string):ISeriesTracker ; // function IsExist(const lestring:string):Boolean; // // End; TSeriesTrackerColl = class(TList<ISeriesTracker>) public procedure Sort; overload; end; implementation uses System.Generics.Defaults; procedure TSeriesTracker.addFail; begin inc(Ffail); end; procedure TSeriesTracker.addSuccess; begin inc(Fsucess); end; //function TSeriesTracker.CompareTo(Other: TSeriesTracker): Integer; //begin // // // if Self.getPercentSuccessful > Other.getPercentSuccessful then // begin // Result := -1; // end // else if Self.getPercentSuccessful < Other.getPercentSuccessful then // begin // Result := 1 // end // else // begin // Result := 0; // end; // //end; constructor TSeriesTracker.Create(series: String); begin inherited Create; Ffail := 0; Fsucess := 0; Self.Fseries := series; end; destructor TSeriesTracker.Destroy; begin inherited Destroy; end; function TSeriesTracker.getFail: Integer; begin Result := Ffail; end; function TSeriesTracker.getPercentSuccessful: double; begin if Self.getTotal = 0 then begin Result := 0 end else begin Result := 100.0 * (getSucess() / getTotal()); end; end; function TSeriesTracker.getSeries: String; begin Result := Fseries; end; function TSeriesTracker.getSucess: Integer; begin Result := Fsucess; end; function TSeriesTracker.getTotal: Integer; begin Result := getSucess + getFail; end; { TSeriesTracker } { TSeriesTrackerColl } //function TSeriesTrackerHashColl.Add(const lestring:string;const obj : ISeriesTracker) : integer; //begin // Result := inherited Add(obj); // FDict.Add(lestring,obj); //end; //constructor TSeriesTrackerHashColl.Create; //begin //// inherited Create([doOwnsValues]); // inherited Create; // // FDict := TDictionary<string , ISeriesTracker>.Create ; // //end; //destructor TSeriesTrackerHashColl.Destroy; //begin // FDict.Free; // inherited; //end; //function TSeriesTrackerHashColl.Get(const lestring:string): ISeriesTracker; //begin // Result := FDict[lestring]; //end; // //function TSeriesTrackerHashColl.IsExist(const lestring: string): Boolean; //begin // Result := FDict.ContainsKey(lestring); //end; { TSeriesTrackerColl } procedure TSeriesTrackerColl.Sort; begin Self.Sort( TComparer<ISeriesTracker>.Construct( function(const Item1,Item2:ISeriesTracker): Integer begin // Result := 1;//CompareValue( Ord( Item1.Getaccuracy) ,Ord(Item2.Getaccuracy)); if Item1.getPercentSuccessful > Item2.getPercentSuccessful then begin Result := -1; end else if Item1.getPercentSuccessful < Item2.getPercentSuccessful then begin Result := 1 end else begin Result := 0; end; end)); end; { TSeriesTrackerHashColl } constructor TSeriesTrackerHashColl.Create; begin // inherited Create([doOwnsValues]); inherited Create; end; destructor TSeriesTrackerHashColl.Destroy; begin inherited destroy; end; function TSeriesTrackerHashColl.Get(const lestring: string): ISeriesTracker; begin Result := Self[lestring]; end; function TSeriesTrackerHashColl.IsExist(const lestring: string): Boolean; begin Result:= Self.ContainsKey(lestring); end; end.
// // Generated by JavaToPas v1.5 20140918 - 132003 //////////////////////////////////////////////////////////////////////////////// unit android.widget.SeekBar; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Util, android.view.accessibility.AccessibilityEvent, android.view.accessibility.AccessibilityNodeInfo; type JSeekBar_OnSeekBarChangeListener = interface; // merged JSeekBar = interface; JSeekBarClass = interface(JObjectClass) ['{89B16FFF-E0B7-4D2F-AB15-58DFABAA9A76}'] function init(context : JContext) : JSeekBar; cdecl; overload; // (Landroid/content/Context;)V A: $1 function init(context : JContext; attrs : JAttributeSet) : JSeekBar; cdecl; overload;// (Landroid/content/Context;Landroid/util/AttributeSet;)V A: $1 function init(context : JContext; attrs : JAttributeSet; defStyle : Integer) : JSeekBar; cdecl; overload;// (Landroid/content/Context;Landroid/util/AttributeSet;I)V A: $1 procedure onInitializeAccessibilityEvent(event : JAccessibilityEvent) ; cdecl;// (Landroid/view/accessibility/AccessibilityEvent;)V A: $1 procedure onInitializeAccessibilityNodeInfo(info : JAccessibilityNodeInfo) ; cdecl;// (Landroid/view/accessibility/AccessibilityNodeInfo;)V A: $1 procedure setOnSeekBarChangeListener(l : JSeekBar_OnSeekBarChangeListener) ; cdecl;// (Landroid/widget/SeekBar$OnSeekBarChangeListener;)V A: $1 end; [JavaSignature('android/widget/SeekBar$OnSeekBarChangeListener')] JSeekBar = interface(JObject) ['{74D68489-C2AB-4B8D-A26E-8CB94242F0BD}'] procedure onInitializeAccessibilityEvent(event : JAccessibilityEvent) ; cdecl;// (Landroid/view/accessibility/AccessibilityEvent;)V A: $1 procedure onInitializeAccessibilityNodeInfo(info : JAccessibilityNodeInfo) ; cdecl;// (Landroid/view/accessibility/AccessibilityNodeInfo;)V A: $1 procedure setOnSeekBarChangeListener(l : JSeekBar_OnSeekBarChangeListener) ; cdecl;// (Landroid/widget/SeekBar$OnSeekBarChangeListener;)V A: $1 end; TJSeekBar = class(TJavaGenericImport<JSeekBarClass, JSeekBar>) end; // Merged from: .\android-19\android.widget.SeekBar_OnSeekBarChangeListener.pas JSeekBar_OnSeekBarChangeListenerClass = interface(JObjectClass) ['{56A8FE9F-889B-4E08-B7E2-C33D81BF225D}'] procedure onProgressChanged(JSeekBarparam0 : JSeekBar; Integerparam1 : Integer; booleanparam2 : boolean) ; cdecl;// (Landroid/widget/SeekBar;IZ)V A: $401 procedure onStartTrackingTouch(JSeekBarparam0 : JSeekBar) ; cdecl; // (Landroid/widget/SeekBar;)V A: $401 procedure onStopTrackingTouch(JSeekBarparam0 : JSeekBar) ; cdecl; // (Landroid/widget/SeekBar;)V A: $401 end; [JavaSignature('android/widget/SeekBar_OnSeekBarChangeListener')] JSeekBar_OnSeekBarChangeListener = interface(JObject) ['{FA6F423F-D8EE-4769-8728-E5ABDD58BE96}'] procedure onProgressChanged(JSeekBarparam0 : JSeekBar; Integerparam1 : Integer; booleanparam2 : boolean) ; cdecl;// (Landroid/widget/SeekBar;IZ)V A: $401 procedure onStartTrackingTouch(JSeekBarparam0 : JSeekBar) ; cdecl; // (Landroid/widget/SeekBar;)V A: $401 procedure onStopTrackingTouch(JSeekBarparam0 : JSeekBar) ; cdecl; // (Landroid/widget/SeekBar;)V A: $401 end; TJSeekBar_OnSeekBarChangeListener = class(TJavaGenericImport<JSeekBar_OnSeekBarChangeListenerClass, JSeekBar_OnSeekBarChangeListener>) end; implementation end.
unit DSA.Sorts.SelectionSort; interface uses Classes, SysUtils, DSA.Interfaces.Comparer, DSA.Interfaces.DataStructure, DSA.Utils; type { TSelectionSort } TSelectionSort<T> = class private type TArray_T = TArray<T>; ICmp_T = IComparer<T>; var class procedure __swap(var a, b: T); public class procedure Sort(var arr: TArray_T; Comparer: ICmp_T); end; procedure Main; implementation type TStudent = class type { TComparer } TComparer = class(TInterfacedObject, IComparer<TStudent>) public constructor Default; function Compare(const Left, Right: TStudent): integer; end; var Name: string; Score: integer; constructor Create(newName: string; newScore: integer); function ToString: string; override; end; TSelectionSort_int = TSelectionSort<integer>; TSelectionSort_TStudent = TSelectionSort<TStudent>; TArr_student = TArray<TStudent>; procedure Main; var n: integer; arr: TArray_int; studentArr: TArr_student; ts1: TSortTestHelper_int; i: integer; begin n := 100000; ts1 := TSortTestHelper_int.Create; arr := ts1.GenerateRandomArray(n, n); //ts1.TestSort('SelectionSort', arr, TSelectionSort_int.Sort); SetLength(studentArr, 4); studentArr := [TStudent.Create('D', 90), TStudent.Create('C', 100), TStudent.Create('B', 95), TStudent.Create('A', 95)]; TSelectionSort_TStudent.Sort(studentArr, TStudent.TComparer.Default); for i := 0 to Length(studentArr) - 1 do writeLn(studentArr[i].ToString, ' '); end; { TSelectionSort<T> } class procedure TSelectionSort<T>.Sort(var arr: TArray_T; Comparer: ICmp_T); var i, j, minIndex, bool: integer; begin for i := 0 to Length(arr) - 1 do begin minIndex := i; for j := i + 1 to Length(arr) - 1 do begin bool := Comparer.Compare(arr[minIndex], arr[j]); if bool > 0 then minIndex := j; end; __swap(arr[i], arr[minIndex]); end; end; class procedure TSelectionSort<T>.__swap(var a, b: T); var tmp: T; begin tmp := a; a := b; b := tmp; end; { TStudent.TComparer } function TStudent.TComparer.Compare(const Left, Right: TStudent): integer; var bool: integer; begin if Left.Score = Right.Score then bool := 0 else if Left.Score < Right.Score then bool := 1 else bool := -1; Result := bool; end; constructor TStudent.TComparer.Default; begin inherited Create; end; { TStudent } constructor TStudent.Create(newName: string; newScore: integer); begin name := newName; Score := newScore; end; function TStudent.ToString: string; var sb: TStringBuilder; begin sb := TStringBuilder.Create; sb.Append('Student: ').Append(name).Append(' ').Append(Score); Result := sb.ToString; end; end.
(* Category: SWAG Title: SEARCH/FIND/REPLACE ROUTINES Original name: 0012.PAS Description: STRPOS.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:46 *) (* Hi, Andy: ...Just for fun I also threw together a "PosSearch" routine that uses the built-in TP "POS" function. It actually performs better than I thought it would, as it takes a string longer than 15 characters before it starts to become slower than the Boyer- Moore function I just posted. (ie: PosSearch is faster than the Boyer-Moore routine for strings that are smaller than 16 chars) Here's a demo program of the "PosSearch" search routine I put together. *Remember* to turn-off "range-checking" {$R-} in your finished program, otherwise the PosSearch will take longer than it should to execute. *) (* Public-domain Search routine, using the standard TP *) (* POS function. Guy McLoughlin - May 1, 1993. *) program DemoPosSearch; (***** PosSearch function. Returns 0 if string is not found. *) (* Returns 65,535 if BufferSize is too large. *) (* ie: Greater than 65,520 bytes. *) (* *) function PosSearch({input } var Buffer; BuffSize : word; Pattern : string) : {output} word; type arwo_2 = array[1..2] of word; arch_255 = array[1..255] of char; var po_Buffer : ^arch_255; by_Temp, by_IncSize : byte; wo_Index : word; begin if (BuffSize > 65520) then begin PosSearch := $FFFF; exit end; wo_Index := 0; by_IncSize := (255 - pred(length(Pattern))); po_Buffer := addr(Buffer); repeat by_Temp := pos(Pattern, po_Buffer^); if (by_Temp = 0) then begin inc(wo_Index, by_IncSize); inc(arwo_2(po_Buffer)[1], by_IncSize) end else inc(wo_Index, by_Temp) until (by_Temp <> 0) or (wo_Index > BuffSize); if (by_Temp = 0) then PosSearch := 0 else PosSearch := wo_Index end; (* PosSearch. *) type arby_64K = array[1..65520] of byte; var Index : word; st_Temp : string[20]; Buffer : ^arby_64K; BEGIN new(Buffer); fillchar(Buffer^, sizeof(Buffer^), 0); st_Temp := '12345678901234567890'; move(st_Temp[1], Buffer^[65501], length(st_Temp)); Index := PosSearch(Buffer^, sizeof(Buffer^), st_Temp); writeln(st_Temp, ' found at offset ', Index) END. (* - Guy --- ■ DeLuxe²/386 1.25 #5060 ■ * Rose Media, Toronto, Canada : 416-733-2285 * PostLink(tm) v1.04 ROSE (#1047) : RelayNet(tm) *)
unit Mixi; interface uses IdHttp, MD5, SysUtils, Classes, superxmlparser, superobject, IdSSLOpenSSL, HttpLib, Crypt; const AUTH_ENDPOINT = 'https://mixi.jp/connect_authorize.pl'; TOKEN_ENDPOINT = 'https://secure.mixi-platform.com/2/token'; API_DESC = 'This is the test project for mixi Graph API'; HTTP_TIMEOUT = 10000; type TAPIToken = class; TAPIToken = class private FConsumerKey: String; FConsumerSecret: String; FRedirectUrl: String; FCode: String; FAccessToken: String; FRefreshToken: String; FExpire: TDateTime; public constructor Create(key, secret, redirect: String); procedure Authorize(code: String); function Refresh: Boolean; function isExpired: Boolean; procedure SaveToFile(Path: String); procedure LoadFromFile(Path: String); property Code: String read FCode write FCode; property AccessToken: String read FAccessToken write FAccessToken; property RefreshToken: String read FRefreshToken write FRefreshToken; property Expire: TDateTime read FExpire write FExpire; end; function AuthorizeUUID: String; function AuthorizeUrl(key: String; scopes: array of String): String; implementation function AuthorizeUUID: String; var buf: String; begin Randomize; buf := DateTimeToStr(Now) + IntToStr(Random($7FFFFFFF)); Result := CalcMD5(PByte(buf), Length(buf)); end; function AuthorizeUrl(key: String; scopes: array of String): String; var i, mx: Integer; scope: String; begin mx := High(scopes); scope := ''; for i := 0 to mx do begin scope := scope + scopes[i]; if i < mx then scope := scope + ' '; end; Result := AUTH_ENDPOINT + '?client_id=' + key + '&response_type=code' + '&scope=' + scope + '&display=pc'; end; constructor TAPIToken.Create(key: string; secret: string; redirect: string); begin FConsumerKey := key; FConsumerSecret := secret; FRedirectUrl := redirect; end; procedure TAPIToken.Authorize(code: string); var req, res: TStringList; ms: TMemoryStream; json: ISuperObject; function CalcExpire(exp: Integer): TDateTime; var hh, mm, ss: Integer; begin ss := exp mod 60; mm := (exp div 60) mod 60; hh := (exp div 3600) mod 24; Result := Now + EncodeTime(hh, mm, ss, 0) end; begin req := TStringList.Create; res := TStringList.Create; ms := TMemoryStream.Create; try req.Values['grant_type'] := 'authorization_code'; req.Values['client_id'] := FConsumerKey; req.Values['client_secret'] := FConsumerSecret; req.Values['code'] := code; req.Values['redirect_uri'] := FRedirectUrl; try //Self.Post(TOKEN_ENDPOINT, req, ms); UserAgent.Post(TOKEN_ENDPOINT, req, ms); except end; ms.Position := 0; res.LoadFromStream(ms); json := SO(res.Text); res.SaveToFile('json.txt'); FCode := code; FAccessToken := json['access_token'].AsString; FRefreshToken := json['refresh_token'].AsString; FExpire := CalcExpire(json['expires_in'].AsInteger); finally req.Free; res.Free; ms.Free; end; end; function TAPIToken.Refresh: Boolean; var req, res: TStringList; ms: TMemoryStream; json: ISuperObject; begin req := TStringList.Create; res := TStringList.Create; ms := TMemoryStream.Create; try req.Values['grant_type'] := 'refresh_token'; req.Values['client_id'] := FConsumerKey; req.Values['client_secret'] := FConsumerSecret; req.Values['refresh_token'] := FRefreshToken; //Self.Post(TOKEN_ENDPOINT, req, ms); UserAgent.Post(TOKEN_ENDPOINT, req, ms); ms.Position := 0; res.LoadFromStream(ms); json := SO(res.Text); FCode := code; FAccessToken := json['access_token'].AsString; FRefreshToken := json['refresh_token'].AsString; FExpire := Now + EncodeTime(0, 0, 0, json['expires_in'].AsInteger); finally req.Free; res.Free; ms.Free; end; Result := True; end; function TAPIToken.isExpired: Boolean; begin Result := FExpire < Now; end; procedure TAPIToken.SaveToFile(Path: String); var SL: TStringList; begin SL := TStringList.Create; try SL.Add(Encrypt( CryptData(FAccessToken, API_DESC) )); SL.Add(Encrypt( CryptData(FRefreshToken, API_DESC) )); SL.Add(DateTimeToStr(FExpire)); SL.SaveToFile(Path); finally SL.Free; end; end; procedure TAPIToken.LoadFromFile(Path: String); var SL: TStringList; cd: TCryptData; begin SL := TStringList.Create; try SL.LoadFromFile(Path); if SL.Count < 3 then raise Exception.Create('Invalid File'); cd := Decrypt(SL[0]); if Not( cd.Description = API_DESC ) then raise Exception.Create('Invalid Access Token'); FAccessToken := cd.Data; cd := Decrypt(SL[1]); if Not( cd.Description = API_DESC ) then raise Exception.Create('Invalid Refresh Token'); FRefreshToken := cd.Data; FExpire := StrToDateTime(SL[2]); finally SL.Free; end; end; end.
unit USettings; interface type TSettings = record public Persist: boolean; MasterFolder: string; GeneratedFolder: string; GenerateIPhone: boolean; GenerateIPad: boolean; GenerateAndroid: boolean; OnlyGenerateRequired: boolean; CreateNewFiles: boolean; OptimizePng: boolean; OutputPattern: string; OutputPatternOnDisk: string; ImgBackColor: integer; CmdOptimizer: string; CmdResizer: string; constructor Create(const initialize: boolean); procedure SaveToDisk(const Filename: string; const forced: boolean); procedure LoadFromDisk(const Filename: string; const DefaultSettings: TSettings); end; implementation uses System.IniFiles, IOUtils, SysUtils; const StrFolders = 'Folders'; StrMasterFolder = 'MasterFolder'; StrGeneratedFolder = 'GeneratedFolder'; StrGenerate = 'Generate'; StrIPhone = 'iPhone'; StrIPad = 'iPad'; StrAndroid = 'Android'; StrOnlyRequired = 'OnlyRequired'; StrCreateNewFiles = 'CreateNewFiles'; StrOptions = 'Options'; StrOptimizePng = 'OptimizePng'; StrPattern = 'Pattern'; StrOutputPattern = 'OutputPattern'; StrOutputPatternOnDisk = 'OutputPatternOnDisk'; StrImgBackColor = 'ImageBackColor'; { TSettings } procedure TSettings.SaveToDisk(const Filename: string; const forced: boolean); var s: TIniFile; begin if not Persist then exit; if (not forced) and (not TFile.Exists(Filename)) then exit; s := TIniFile.Create(Filename); try s.WriteString(StrFolders, StrMasterFolder, MasterFolder); s.WriteString(StrFolders, StrGeneratedFolder, GeneratedFolder); s.WriteBool(StrGenerate, StrIPhone, GenerateIPhone); s.WriteBool(StrGenerate, StrIPad, GenerateIPad); s.WriteBool(StrGenerate, StrAndroid, GenerateAndroid); s.WriteBool(StrGenerate, StrOnlyRequired, OnlyGenerateRequired); s.WriteBool(StrGenerate, StrCreateNewFiles, CreateNewFiles); s.WriteBool(StrOptions, StrOptimizePng, OptimizePng); s.WriteString(StrPattern, StrOutputPattern, OutputPattern); s.WriteString(StrPattern, StrOutputPatternOnDisk, OutputPatternOnDisk); s.WriteInteger(StrOptions, StrImgBackColor, ImgBackColor); finally s.Free; end; end; constructor TSettings.Create(const initialize: boolean); begin Persist := true; MasterFolder := 'master_icons'; GeneratedFolder := 'icons'; GenerateIPhone := true; GenerateIPad := true; GenerateAndroid := true; OnlyGenerateRequired := false; CreateNewFiles := true; OptimizePng := true; OutputPattern := '%4:s_%0:dx%1:d.png'; OutputPatternOnDisk := '%4:s_%5:s.png'; ImgBackColor := 0; CmdOptimizer := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'lib/truepng.exe'); CmdResizer := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'lib/convert.exe'); end; procedure TSettings.LoadFromDisk(const Filename: string; const DefaultSettings: TSettings); var s: TIniFile; begin s := TIniFile.Create(Filename); try MasterFolder := s.ReadString(StrFolders, StrMasterFolder, DefaultSettings.MasterFolder); GeneratedFolder := s.ReadString(StrFolders, StrGeneratedFolder, DefaultSettings.GeneratedFolder); GenerateIPhone := s.ReadBool(StrGenerate, StrIPhone, DefaultSettings.GenerateIPhone); GenerateIPad := s.ReadBool(StrGenerate, StrIPad, DefaultSettings.GenerateIPad); GenerateAndroid := s.ReadBool(StrGenerate, StrAndroid, DefaultSettings.GenerateAndroid); OnlyGenerateRequired := s.ReadBool(StrGenerate, StrOnlyRequired, DefaultSettings.OnlyGenerateRequired); CreateNewFiles := s.ReadBool(StrGenerate, StrCreateNewFiles, DefaultSettings.CreateNewFiles); OptimizePng := s.ReadBool(StrOptions, StrOptimizePng, DefaultSettings.OptimizePng); OutputPattern := s.ReadString(StroutputPattern, StrOutputPattern, DefaultSettings.OutputPattern); OutputPatternOnDisk := s.ReadString(StroutputPattern, StrOutputPatternOnDisk, DefaultSettings.OutputPatternOnDisk); ImgBackColor := s.ReadInteger(StrOptions, StrImgBackColor, DefaultSettings.ImgBackColor); finally s.Free; end; end; end.
unit uMachMask; // © Alexandr Petrovich Sysoev interface uses Classes; /// ////////////////////////////////////////////////// Работа со списком шаблонов // Функции предназначены для сопоставления текстов (имен файлов) на // соответствие заданному шаблону или списку шаблонов. // Обычно используется для посторения простых фильтров, например аналогичных // файловым фильтрам программы Total Commander. // // Каждый шаблон аналогичен шаблону имен файлов в MS-DOS и MS Windows, // т.е. может включать "шаблонные" символы '*' и '?' и не может включать // символ '|'. // Любой шаблон может быть заключен в двойные кавычки ('''), при этом двойные // кавычки имеющиеся в шаблоне должны быть удвоены. Если шаблон включает // символы ';' или ' ' (пробел) то он обязательно должен быть заключен в // двойные кавычки. // В списке, шаблоны разделяются символом ';'. // За первым списком шаблонов, может следовать символ '|', за которым может // следовать второй список. // Текст (имя файла) будет считаться соответствующим списку шаблонов только // если он соответствует хотя бы одному шаблону из первого списка, // и не соответствует ни одному шаблону из второго списка. // Если первый список пуст, то подразумевается '*' // // Формальное описание синтаксиса списка шаблонов: // // Полный список шаблонов :: [<список включаемых шаблонов>]['|'<список исключаемых шаблонов>] // список включаемых шаблонов :: <список шаблонов> // список исключаемых шаблонов :: <список шаблонов> // список шаблонов :: <шаблон>[';'<шаблон>] // шаблон :: шаблон аналогичный шаблону имен файлов в // MS-DOS и MS Windows, т.е. может включать // "шаблонные" символы '*' и '?' и не может // включать символ '|'. Шаблон может быть // заключен в двойные кавычки (''') при этом // двойные кавычки имеющиеся в шаблоне должны // быть удвоены. Если шаблон включает символы // ';' или ' ' (пробел) то он // обязательно должен быть заключен в двойные // кавычки. // // Например: // '*.ini;*.wav' - соответствует любым файлам с расшиениями 'ini' // или 'wav' // '*.*|*.exe' - соответствует любым файлам, кроме файлов с // расширением 'EXE' // '*.mp3;*.wav|?.*;??.*' - соответствует любым файлам с расшиениями 'mp3' // и 'wav' за исключением файлов у которых имя // состоит из одного или двух символов. // '|awString.*' - соответствует любым файлам за исключением файлов // с именем awString и любым расширением. // function IsMatchWhiteSpaceMask(AText, AMask: string): Boolean; function IsMatchMask(AText, AMask: PChar): Boolean; overload; function IsMatchMask(AText, AMask: string; AFileNameMode: Boolean = True): Boolean; overload; // Выполняют сопоставление текста aText с одним шаблоном aMask. // Возвращает True если сопоставление выполнено успешно, т.е. текст // aText соответствует шаблону aMask. // Если aFileNameModd=True, то объект используется для сопоставления // имен файлов с шаблоном. А именно, в этом случае, если aText не // содержит символа '.' то он добавляется в конец. Это необходимо для // того, чтобы файлы без расширений соответствовали например шаблону '*.*' function IsMatchMaskList(AText, AMaskList: string; AFileNameMode: Boolean = True): Boolean; // Выполняет сопоставление текста aText со списком шаблонов aMaskList. // Возвращает True если сопоставление выполнено успешно, т.е. текст // aText соответствует списку шаблонов aMaskList. // Если aFileNameModd=True, то объект используется для сопоставления // имен файлов с шаблоном. А именно, в этом случае, если aText не // содержит символа '.' то он добавляется в конец. Это необходимо для // того, чтобы файлы без расширений соответствовали например шаблону '*.*' // // Замечание, если требуется проверка сопоставления нескольких строк одному // списку шаблонов, эффективнее будет воспользоваться объектом tMatchMaskList. type TMatchMaskList = class(TObject) private FMaskList: string; FCaseSensitive: Boolean; FFileNameMode: Boolean; FPrepared: Boolean; FIncludeMasks: TStringList; FExcludeMasks: TStringList; procedure SetMaskList(V: string); procedure SetCaseSensitive(V: Boolean); public constructor Create(const AMaskList: string = ''); // Создает объект. Если задан параметр aMaskList, то он присваивается // свойству MaskList. destructor Destroy; override; // Разрушает объект procedure PrepareMasks; // Осуществляет компиляцию списка шаблонов во внутреннюю структуру // используемую при сопоставлении текста. // Вызов данного метода не является обязательным и при необходимости // будет вызван автоматически. function IsMatch(AText: string): Boolean; // Выполняет сопоставление текста aText со списком шаблонов MaskList. // Возвращает True если сопоставление выполнено успешно, т.е. текст // aText соответствует списку шаблонов MaskList. property MaskList: string read FMaskList write SetMaskList; // Списко шаблонов используемый для сопоставления с текстом property CaseSensitive: Boolean read FCaseSensitive write SetCaseSensitive default False; // Если False (по умолчанию), то при сопоставлении текста будет // регистр символов не будет учитываться. // Иначе, если True, сопоставление будет проводиться с учетом регистра. property FileNameMode: Boolean read FFileNameMode write FFileNameMode default True; // Если True (по умолчанию), то объект используется для сопоставления // имен файлов с шаблоном. А именно, в этом случае, если aText не // содержит символа '.' то он добавляется в конец. Это необходимо для // того, чтобы файлы без расширений соответствовали например шаблону '*.*' end; implementation uses SysUtils; function IsMatchMask(AText, AMask: PChar): Boolean; overload; begin Result := False; while True do begin case AMask^ of '*': // соответствует любому числу любых символов кроме конца строки begin // переместиться на очередной символ шаблона, при этом, подряд // идущие '*' эквивалентны одному, поэтому пропуск всех '*' repeat Inc(AMask); until (AMask^ <> '*'); // если за '*' следует любой символ кроме '?' то он должен совпасть // с символом в тексте. т.е. нужно пропустить все не совпадающие, // но не далее конца строки if AMask^ <> '?' then while (AText^ <> #0) and (AText^ <> AMask^) do Inc(AText); if AText^ <> #0 then begin // не конец строки, значит совпал символ // '*' 'жадный' шаблон поэтому попробуем отдать совпавший символ // ему. т.е. проверить совпадение продолжения строки с шаблоном, // начиная с того-же '*'. если продолжение совпадает, то if IsMatchMask(AText + 1, AMask - 1) then Break; // это СОВПАДЕНИЕ // продолжение не совпало, значит считаем что здесь закончилось // соответствие '*'. Продолжим сопоставление со следующего // символа шаблона Inc(AMask); Inc(AText); // иначе переходим к следующему символу end else if (AMask^ = #0) then // конец строки и конец шаблона Break // это СОВПАДЕНИЕ else // конец строки но не конец шаблона Exit // это НЕ СОВПАДЕНИЕ end; '?': // соответствует любому кроме конца строки if (AText^ = #0) then // конец строки Exit // это НЕ СОВПАДЕНИЕ else begin // иначе Inc(AMask); Inc(AText); // иначе переходим к следующему символу end; else // символ в шаблоне должен совпасть с символом в строке if AMask^ <> AText^ then // символы не совпали - Exit // это НЕ СОВПАДЕНИЕ else begin // совпал очередной символ if (AMask^ = #0) then // совпавший символ последний - Break; // это СОВПАДЕНИЕ Inc(AMask); Inc(AText); // иначе переходим к следующему символу end; end; end; Result := True; end; function IsMatchMask(AText, AMask: string; AFileNameMode: Boolean = True): Boolean; overload; begin if AFileNameMode and (Pos('.', AText) = 0) then AText := AText + '.'; Result := IsMatchMask(PChar(AText), PChar(AMask)); end; function IsMatchMaskList(AText, AMaskList: string; AFileNameMode: Boolean = True): Boolean; begin with TMatchMaskList.Create(AMaskList) do try FileNameMode := AFileNameMode; Result := IsMatch(AText); finally Free; end; end; /// //////////////////////////////////////////////////////// tFileMask procedure TMatchMaskList.SetMaskList(V: string); begin if FMaskList = V then Exit; FMaskList := V; FPrepared := False; end; procedure TMatchMaskList.SetCaseSensitive(V: Boolean); begin if FCaseSensitive = V then Exit; FCaseSensitive := V; FPrepared := False; end; constructor TMatchMaskList.Create(const AMaskList: string); begin MaskList := AMaskList; FFileNameMode := True; FIncludeMasks := TStringList.Create; with FIncludeMasks do begin Delimiter := ';'; // Sorted := True; // Duplicates := dupIgnore; end; FExcludeMasks := TStringList.Create; with FExcludeMasks do begin Delimiter := ';'; // Sorted := True; // Duplicates := dupIgnore; end; end; destructor TMatchMaskList.Destroy; begin FIncludeMasks.Free; FExcludeMasks.Free; end; procedure TMatchMaskList.PrepareMasks; procedure CleanList(L: TStrings); var I: Integer; begin for I := L.Count - 1 downto 0 do if L[I] = '' then L.Delete(I); end; var S: string; I: Integer; begin if FPrepared then Exit; if CaseSensitive then S := MaskList else S := UpperCase(MaskList); I := Pos('|', S); if I = 0 then begin FIncludeMasks.DelimitedText := S; FExcludeMasks.DelimitedText := ''; end else begin FIncludeMasks.DelimitedText := Copy(S, 1, I - 1); FExcludeMasks.DelimitedText := Copy(S, I + 1, MaxInt); end; CleanList(FIncludeMasks); CleanList(FExcludeMasks); // если список включаемых шаблонов пуст а // список исключаемых шаблонов не пуст, то // имеется ввиду что список включаемых шаблонов равен <все файлы> if (FIncludeMasks.Count = 0) and (FExcludeMasks.Count <> 0) then FIncludeMasks.Add('*'); FPrepared := True; end; function TMatchMaskList.IsMatch(AText: string): Boolean; var I: Integer; begin Result := False; if AText = '' then Exit; if not CaseSensitive then AText := UpperCase(AText); if FileNameMode and (Pos('.', AText) = 0) then AText := AText + '.'; if not FPrepared then PrepareMasks; // поиск в списке "включаемых" масок до первого совпадения for I := 0 to FIncludeMasks.Count - 1 do if IsMatchMask(PChar(AText), PChar(FIncludeMasks[I])) then begin Result := True; Break; end; // если совпадение найдено, надо проверить по списку "исключаемых" if Result then for I := 0 to FExcludeMasks.Count - 1 do if IsMatchMask(PChar(AText), PChar(FExcludeMasks[I])) then begin Result := False; Break; end; end; function IsMatchWhiteSpaceMask(AText, AMask: string): Boolean; var I: Integer; MaskParts: TArray<string>; begin MaskParts := AMask.Split([' '], TStringSplitOptions.ExcludeEmpty); Result := True; for I := 0 to Length(MaskParts) - 1 do if Pos(MaskParts[I], AText) = 0 then Exit(False); end; end.
unit ThImageList; interface uses SysUtils, Classes, Controls, Graphics, ThComponent; type TThImageList = class(TThComponent) private FImageList: TImageList; protected function GetJpegStream(inIndex: Integer): TStream; procedure SetImageList(const Value: TImageList); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; function GetImageUrl(inIndex: Integer): string; virtual; abstract; published property ImageList: TImageList read FImageList write SetImageList; //property Url; end; implementation uses ThGraphicUtils; { TThImageList } constructor TThImageList.Create(inOwner: TComponent); begin inherited; FImageList := TImageList.Create(Self); FImageList.SetSubComponent(true); end; destructor TThImageList.Destroy; begin FImageList.Free; inherited; end; procedure TThImageList.SetImageList(const Value: TImageList); begin //FImageList := Value; end; function TThImageList.GetJpegStream(inIndex: Integer): TStream; var b: TBitmap; begin Result := TMemoryStream.Create; b := TBitmap.Create; try ImageList.GetBitmap(inIndex, b); ThBitmapToJpgStream(b, Result); finally b.Free; end; end; { procedure TThImageList.Fulfill(inAction: TThAction); var ii: Integer; begin if ImageList <> nil then begin ii := StrToIntDef(Copy(inAction.Document, 2, MAXINT), 0); inAction.ServeStream(GetJpegStream(ii), 'image/jpg'); end; end; function TThImageList.GetImageUrl(inIndex: Integer): string; begin Result := Format('%s/%d', [ Url, inIndex ]); end; } end.
program questao12; { Autor: Hugo Deiró Data: 03/06/2012 - Este programa calcula o salário líquido de uma pessoa através do número de horas trabalhadas no mês e do valor da hora de trabalho } var horas_trabalhadas : integer; valor_hora : real; begin write('Insira o valor da hora de trabalho: '); readln(valor_hora); if(valor_hora > 0)then begin write('Insira o número de horas trabalhadas: '); readln(horas_trabalhadas); if(horas_trabalhadas > 0)then begin writeln; if((horas_trabalhadas*valor_hora) <= 900)then begin writeln('Salário Bruto = ',(horas_trabalhadas*valor_hora):6:2); writeln('IR = ISENTO'); writeln('INSS = ',(horas_trabalhadas*valor_hora)*0.1:6:2); writeln('FGTS = ',(horas_trabalhadas*valor_hora)*0.11:6:2); writeln('Total Descontos = ',(horas_trabalhadas*valor_hora)*0.21:6:2); writeln('Salário Líquido = ',(horas_trabalhadas*valor_hora) - (horas_trabalhadas*valor_hora)*0.21:6:2); end; if((horas_trabalhadas*valor_hora) > 900) and ((horas_trabalhadas*valor_hora) <= 1500)then begin writeln('Salário Bruto = ',(horas_trabalhadas*valor_hora):6:2); writeln('IR = ',(horas_trabalhadas*valor_hora)*0.05:6:2); writeln('INSS = ',(horas_trabalhadas*valor_hora)*0.1:6:2); writeln('FGTS = ',(horas_trabalhadas*valor_hora)*0.11:6:2); writeln('Total Descontos = ',(horas_trabalhadas*valor_hora)*0.26:6:2); writeln('Salário Líquido = ',(horas_trabalhadas*valor_hora) - (horas_trabalhadas*valor_hora)*0.26:6:2); end; if((horas_trabalhadas*valor_hora) > 1500) and ((horas_trabalhadas*valor_hora) <= 2500)then begin writeln('Salário Bruto = ',(horas_trabalhadas*valor_hora):6:2); writeln('IR = ',(horas_trabalhadas*valor_hora)*0.1:6:2); writeln('INSS = ',(horas_trabalhadas*valor_hora)*0.1:6:2); writeln('FGTS = ',(horas_trabalhadas*valor_hora)*0.11:6:2); writeln('Total Descontos = ',(horas_trabalhadas*valor_hora)*0.31:6:2); writeln('Salário Líquido = ',(horas_trabalhadas*valor_hora) - (horas_trabalhadas*valor_hora)*0.31:6:2); end; if((horas_trabalhadas*valor_hora) > 2500)then begin writeln('Salário Bruto = ',(horas_trabalhadas*valor_hora):6:2); writeln('IR = 2',(horas_trabalhadas*valor_hora)*0.2:6:2); writeln('INSS = ',(horas_trabalhadas*valor_hora)*0.1:6:2); writeln('FGTS = ',(horas_trabalhadas*valor_hora)*0.11:6:2); writeln('Total Descontos = ',(horas_trabalhadas*valor_hora)*0.41:6:2); writeln('Salário Líquido = ',(horas_trabalhadas*valor_hora) - (horas_trabalhadas*valor_hora)*0.41:6:2); end; end else writeln('Número de Horas Trabalhadas Inválido!'); end else writeln('Valor da Hora de Trabalho Inválido!'); end.
unit InflatablesList_ItemShop_Base; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses AuxTypes, AuxClasses{for TNotifyEvent}, InflatablesList_Types, InflatablesList_ItemShopParsingSettings; type TILItemShopUpdateFlag = (ilisufClearSelected,ilisufOverviewUpdate,ilisufShopListItemUpdate, ilisufValuesUpdate,ilisufAvailHistUpdate,ilisufPriceHistUpdate); TILItemShopUpdateFlags = set of TILItemShopUpdateFlag; TILItemShop_Base = class(TObject) protected // internals fStaticSettings: TILStaticManagerSettings; fRequiredCount: UInt32; // used internally in updates, ignored otherwise fUpdateCounter: Integer; // transient (not copied in copy constructor) fUpdated: TILItemShopUpdateFlags; // transient // internal events fOnClearSelected: TNotifyEvent; // all events are transient fOnOverviewUpdate: TNotifyEvent; fOnShopListItemUpdate: TNotifyEvent; fOnValuesUpdate: TNotifyEvent; fOnAvailHistUpdate: TNotifyEvent; fOnPriceHistUpdate: TNotifyEvent; // data fSelected: Boolean; fUntracked: Boolean; fAltDownMethod: Boolean; fName: String; fShopURL: String; fItemURL: String; fAvailable: Int32; fPrice: UInt32; fAvailHistory: TILItemShopHistory; fPriceHistory: TILItemShopHistory; fNotes: String; // parsing stuff fParsingSettings: TILItemShopParsingSettings; fLastUpdateRes: TILItemShopUpdateResult; fLastUpdateMsg: String; fLastUpdateTime: TDateTime; procedure SetRequiredCount(Value: UInt32); virtual; procedure SetStaticSettings(Value: TILStaticManagerSettings); virtual; // data getters and setters procedure SetSelected(Value: Boolean); virtual; procedure SetUntracked(Value: Boolean); virtual; procedure SetAltDownMethod(Value: Boolean); virtual; procedure SetName(const Value: String); virtual; procedure SetShopURL(const Value: String); virtual; procedure SetItemURL(const Value: String); virtual; procedure SetAvailable(Value: Int32); virtual; procedure SetPrice(Value: UInt32); virtual; Function GetAvailHistoryEntryCount: Integer; virtual; Function GetAvailHistoryEntry(Index: Integer): TILItemShopHistoryEntry; virtual; Function GetPriceHistoryEntryCount: Integer; virtual; Function GetPriceHistoryEntry(Index: Integer): TILItemShopHistoryEntry; virtual; procedure SetNotes(const Value: String); virtual; procedure SetLastUpdateRes(Value: TILItemShopUpdateResult); virtual; procedure SetLastUpdateMsg(const Value: String); virtual; procedure SetLastUpdateTime(Value: TDateTime); virtual; // event callers procedure ClearSelected; virtual; procedure UpdateOverview; virtual; procedure UpdateShopListItem; virtual; procedure UpdateValues; virtual; procedure UpdateAvailHistory; virtual; procedure UpdatePriceHistory; virtual; // other protected methods procedure InitializeData; virtual; procedure FinalizeData; virtual; procedure Initialize; virtual; procedure Finalize; virtual; public constructor Create; overload; constructor CreateAsCopy(Source: TILItemShop_Base; UniqueCopy: Boolean); overload; destructor Destroy; override; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; // history Function AvailHistoryAdd: Integer; virtual; procedure AvailHistoryDelete(Index: Integer); virtual; procedure AvailHistoryClear; virtual; Function PriceHistoryAdd: Integer; virtual; procedure PriceHistoryDelete(Index: Integer); virtual; procedure PriceHistoryClear; virtual; procedure AvailAndPriceHistoryAdd; virtual; procedure UpdateAvailAndPriceHistory; virtual; // other methods procedure SetValues(const Msg: String; Res: TILItemShopUpdateResult; Avail: Int32; Price: UInt32); procedure ReplaceParsingSettings(Source: TILItemShopParsingSettings); virtual; Function IsAvailableHere(HonorCount: Boolean): Boolean; virtual; procedure AssignInternalEvents( ClearSelected, OverviewUpdate, ShopListItemUpdate, ValuesUpdate, AvailHistUpdate, PriceHistUpdate: TNotifyEvent); virtual; procedure ClearInternalEvents; virtual; // properties property StaticSettings: TILStaticManagerSettings read fStaticSettings write SetStaticSettings; property RequiredCount: UInt32 read fRequiredCount write SetRequiredCount; // data property Selected: Boolean read fSelected write SetSelected; property Untracked: Boolean read fUntracked write SetUntracked; property AltDownMethod: Boolean read fAltDownMethod write SetAltDownMethod; property Name: String read fName write SetName; property ShopURL: String read fShopURL write SetShopURL; property ItemURL: String read fItemURL write SetItemURL; property Available: Int32 read fAvailable write SetAvailable; property Price: UInt32 read fPrice write SetPrice; property AvailHistoryEntryCount: Integer read GetAvailHistoryEntryCount; property AvailHistoryEntries[Index: Integer]: TILItemShopHistoryEntry read GetAvailHistoryEntry; property PriceHistoryEntryCount: Integer read GetPriceHistoryEntryCount; property PriceHistoryEntries[Index: Integer]: TILItemShopHistoryEntry read GetPriceHistoryEntry; property Notes: String read fNotes write SetNotes; property ParsingSettings: TILItemShopParsingSettings read fParsingSettings; property LastUpdateRes: TILItemShopUpdateResult read fLastUpdateRes write SetLastUpdateRes; property LastUpdateMsg: String read fLastUpdateMsg write SetLastUpdateMsg; property LastUpdateTime: TDateTime read fLastUpdateTime write SetLastUpdateTime; end; implementation uses SysUtils, InflatablesList_Utils; procedure TILItemShop_Base.SetStaticSettings(Value: TILStaticManagerSettings); begin fStaticSettings := IL_ThreadSafeCopy(Value); fParsingSettings.StaticSettings := Value; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetRequiredCount(Value: UInt32); begin fRequiredCount := Value; fParsingSettings.RequiredCount := Value; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetSelected(Value: Boolean); begin If fSelected <> Value then begin ClearSelected; fSelected := Value; UpdateOverview; UpdateShopListItem; UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetUntracked(Value: Boolean); begin If fUntracked <> Value then begin fUntracked := Value; UpdateShopListItem; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetAltDownMethod(Value: Boolean); begin If fAltDownMethod <> Value then begin fAltDownMethod := Value; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetName(const Value: String); begin If not IL_SameStr(fName,Value) then begin fName := Value; UniqueString(fName); UpdateOverview; UpdateShopListItem; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetShopURL(const Value: String); begin If not IL_SameStr(fShopURL,Value) then begin fShopURL := Value; UniqueString(fShopURL); end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetItemURL(const Value: String); begin If not IL_SameStr(fItemURL,Value) then begin fItemURL := Value; UniqueString(fItemURL); UpdateShopListItem; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetAvailable(Value: Int32); begin If fAvailable <> Value then begin fAvailable := Value; UpdateOverview; UpdateShopListItem; UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetPrice(Value: UInt32); begin If fPrice <> Value then begin fPrice := Value; UpdateOverview; UpdateShopListItem; UpdateValues; end; end; //------------------------------------------------------------------------------ Function TILItemShop_Base.GetAvailHistoryEntryCount: Integer; begin Result := Length(fAvailHistory); end; //------------------------------------------------------------------------------ Function TILItemShop_Base.GetAvailHistoryEntry(Index: Integer): TILItemShopHistoryEntry; begin If (Index >= Low(fAvailHistory)) and (Index <= High(fAvailHistory)) then Result := fAvailHistory[Index] else raise Exception.CreateFmt('TILItemShop_Base.GetAvailHistoryItem: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ Function TILItemShop_Base.GetPriceHistoryEntryCount: Integer; begin Result := Length(fPriceHistory); end; //------------------------------------------------------------------------------ Function TILItemShop_Base.GetPriceHistoryEntry(Index: Integer): TILItemShopHistoryEntry; begin If (Index >= Low(fPriceHistory)) and (Index <= High(fPriceHistory)) then Result := fPriceHistory[Index] else raise Exception.CreateFmt('TILItemShop_Base.GetPriceHistoryItem: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetNotes(const Value: String); begin If not IL_SameStr(fNotes,Value) then begin fNotes := Value; UniqueString(fNotes); end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetLastUpdateRes(Value: TILItemShopUpdateResult); begin If fLastUpdateRes <> Value then begin fLastUpdateRes := Value; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetLastUpdateMsg(const Value: String); begin If not IL_SameStr(fLastUpdateMsg,Value) then begin fLastUpdateMsg := Value; UniqueString(fLastUpdateMsg); UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetLastUpdateTime(Value: TDateTime); begin If fLastUpdateTime <> Value then begin fLastUpdateTime := Value; UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.ClearSelected; begin If Assigned(fOnClearSelected) and (fUpdateCounter <= 0) then fOnClearSelected(Self); Include(fUpdated,ilisufClearSelected); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdateOverview; begin If Assigned(fOnOverviewUpdate) and (fUpdateCounter <= 0) then fOnOverviewUpdate(Self); Include(fUpdated,ilisufOverviewUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdateShopListItem; begin If Assigned(fOnShopListItemUpdate) and (fUpdateCounter <= 0) then fOnShopListItemUpdate(Self); Include(fUpdated,ilisufShopListItemUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdateValues; begin If Assigned(fOnValuesUpdate) and (fUpdateCounter <= 0) then fOnValuesUpdate(Self); Include(fUpdated,ilisufValuesUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdateAvailHistory; begin If Assigned(fOnAvailHistUpdate) and (fUpdateCounter <= 0) then fOnAvailHistUpdate(Self); Include(fUpdated,ilisufAvailHistUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdatePriceHistory; begin If Assigned(fOnPriceHistUpdate) and (fUpdateCounter <= 0) then fOnPriceHistUpdate(Self); Include(fUpdated,ilisufPriceHistUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.InitializeData; begin fSelected := False; fUntracked := False; fAltDownMethod := False; fName := ''; fShopURL := ''; fItemURL := ''; fAvailable := 0; fPrice := 0; SetLength(fAvailHistory,0); SetLength(fPriceHistory,0); fNotes := ''; fParsingSettings := TILItemShopParsingSettings.Create; fParsingSettings.StaticSettings := fStaticSettings; fParsingSettings.RequiredCount := fRequiredCount; fLastUpdateRes := ilisurSuccess; fLastUpdateMsg := ''; fLastUpdateTime := 0.0; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.FinalizeData; begin SetLength(fAvailHistory,0); SetLength(fPriceHistory,0); FreeAndNil(fParsingSettings); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.Initialize; begin FillChar(fStaticSettings,SizeOf(TILStaticManagerSettings),0); fRequiredCount := 0; fUpdateCounter := 0; fUpdated := []; InitializeData; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.Finalize; begin FinalizeData; end; //============================================================================== constructor TILItemShop_Base.Create; begin inherited Create; Initialize; end; //------------------------------------------------------------------------------ constructor TILItemShop_Base.CreateAsCopy(Source: TILItemShop_Base; UniqueCopy: Boolean); var i: Integer; begin inherited Create; // do not call initialize fStaticSettings := IL_ThreadSafeCopy(Source.StaticSettings); fRequiredCount := Source.RequiredCount; // copy data... fSelected := Source.Selected; fUntracked := Source.Untracked; fAltDownMethod := Source.AltDownMethod; fName := Source.Name; UniqueString(fName); fShopURL := Source.ShopURL; UniqueString(fShopURL); fItemURL := Source.ItemURL; UniqueString(fItemURL); fAvailable := Source.Available; fPrice := Source.Price; SetLength(fAvailHistory,Source.AvailHistoryEntryCount); For i := Low(fAvailHistory) to High(fAvailHistory) do fAvailHistory[i] := Source.AvailHistoryEntries[i]; // no need to care for thread safety SetLength(fPriceHistory,Source.PriceHistoryEntryCount); For i := Low(fPriceHistory) to High(fPriceHistory) do fPriceHistory[i] := Source.PriceHistoryEntries[i]; fNotes := Source.Notes; UniqueString(fNotes); // parsing stuff fParsingSettings := TILItemShopParsingSettings.CreateAsCopy(Source.ParsingSettings,UniqueCopy); fParsingSettings.RequiredCount := fRequiredCount; fLastUpdateRes := Source.LastUpdateRes; fLastUpdateMsg := Source.LastUpdateMsg; fLastUpdateTime := Source.LastUpdateTime; UniqueString(fLastUpdateMsg); end; //------------------------------------------------------------------------------ destructor TILItemShop_Base.Destroy; begin Finalize; inherited; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.BeginUpdate; begin If fUpdateCounter <= 0 then fUpdated := []; Inc(fUpdateCounter); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.EndUpdate; begin Dec(fUpdateCounter); If fUpdateCounter <= 0 then begin fUpdateCounter := 0; If ilisufClearSelected in fUpdated then ClearSelected; If ilisufOverviewUpdate in fUpdated then UpdateOverview; If ilisufShopListItemUpdate in fUpdated then UpdateShopListItem; If ilisufValuesUpdate in fUpdated then UpdateValues; If ilisufAvailHistUpdate in fUpdated then UpdateAvailHistory; If ilisufPriceHistUpdate in fUpdated then UpdatePriceHistory; fUpdated := []; end; end; //------------------------------------------------------------------------------ Function TILItemShop_Base.AvailHistoryAdd: Integer; begin Result := Length(fAvailHistory); SetLength(fAvailHistory,Result + 1); fAvailHistory[Result].Value := fAvailable; fAvailHistory[Result].Time := Now; UpdateAvailHistory; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.AvailHistoryDelete(Index: Integer); var i: Integer; begin If (Index >= Low(fAvailHistory)) and (Index <= High(fAvailHistory)) then begin For i := Index to Pred(High(fAvailHistory)) do fAvailHistory[i] := fAvailHistory[i + 1]; SetLength(fAvailHistory,Length(fAvailHistory) - 1); UpdateAvailHistory; end else raise Exception.CreateFmt('TILItemShop_Base.AvailHistoryDelete: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.AvailHistoryClear; begin SetLength(fAvailHistory,0); UpdateAvailHistory; end; //------------------------------------------------------------------------------ Function TILItemShop_Base.PriceHistoryAdd: Integer; begin Result := Length(fPriceHistory); SetLength(fPriceHistory,Result + 1); fPriceHistory[Result].Value := fPrice; fPriceHistory[Result].Time := Now; UpdatePriceHistory; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.PriceHistoryDelete(Index: Integer); var i: Integer; begin If (Index >= Low(fPriceHistory)) and (Index <= High(fPriceHistory)) then begin For i := Index to Pred(High(fPriceHistory)) do fPriceHistory[i] := fPriceHistory[i + 1]; SetLength(fPriceHistory,Length(fPriceHistory) - 1); UpdatePriceHistory; end else raise Exception.CreateFmt('TILItemShop_Base.PriceHistoryDelete: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.PriceHistoryClear; begin SetLength(fPriceHistory,0); UpdatePriceHistory; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.AvailAndPriceHistoryAdd; var CurrTime: TDateTime; begin CurrTime := Now; SetLength(fAvailHistory,Length(fAvailHistory) + 1); fAvailHistory[High(fAvailHistory)].Value := fAvailable; fAvailHistory[High(fAvailHistory)].Time := CurrTime; SetLength(fPriceHistory,Length(fPriceHistory) + 1); fPriceHistory[High(fPriceHistory)].Value := fPrice; fPriceHistory[High(fPriceHistory)].Time := CurrTime; UpdateAvailHistory; UpdatePriceHistory; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.UpdateAvailAndPriceHistory; begin If fPrice > 0 then begin // price is nonzero, add only when current price or avail differs from last // entry or there is no prior entry If (Length(fPriceHistory) <= 0) then AvailAndPriceHistoryAdd else If (fAvailHistory[High(fAvailHistory)].Value <> fAvailable) or (fPriceHistory[High(fPriceHistory)].Value <> Int32(fPrice)) then AvailAndPriceHistoryAdd; end else begin // price is zero, add only when there is already a price entry and // current price or avail differs from last entry If (Length(fPriceHistory) > 0) then If ((fAvailHistory[High(fAvailHistory)].Value <> fAvailable) or (fPriceHistory[High(fPriceHistory)].Value <> Int32(fPrice))) then AvailAndPriceHistoryAdd; end; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.SetValues(const Msg: String; Res: TILItemShopUpdateResult; Avail: Int32; Price: UInt32); begin fAvailable := Avail; fPrice := Price; fLastUpdateRes := Res; fLastUpdateMsg := Msg; fLastUpdateTime := Now; UniqueString(fLastUpdateMsg); UpdateOverview; UpdateShopListItem; UpdateValues; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.ReplaceParsingSettings(Source: TILItemShopParsingSettings); var Variables: TILItemShopParsingVariables; i: Integer; begin // keep variables // no need to care for thread safety, strings are cured when assigned to new object Variables := fParsingSettings.VariablesRec; fParsingSettings.Free; fParsingSettings := TILItemShopParsingSettings.CreateAsCopy(Source,True); fParsingSettings.RequiredCount := fRequiredCount; For i := 0 to Pred(fParsingSettings.VariableCount) do fParsingSettings.Variables[i] := Variables.Vars[i]; end; //------------------------------------------------------------------------------ Function TILItemShop_Base.IsAvailableHere(HonorCount: Boolean): Boolean; begin If fPrice > 0 then begin If HonorCount then begin If fAvailable > 0 then Result := UInt32(fAvailable) >= fRequiredCount else Result := UInt32(Abs(fAvailable) * 2) >= fRequiredCount end else Result := fAvailable <> 0; end else Result := False; end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.AssignInternalEvents(ClearSelected,OverviewUpdate, ShopListItemUpdate,ValuesUpdate,AvailHistUpdate,PriceHistUpdate: TNotifyEvent); begin fOnClearSelected := IL_CheckHandler(ClearSelected); fOnOverviewUpdate := IL_CheckHandler(OverviewUpdate); fOnShopListItemUpdate := IL_CheckHandler(ShopListItemUpdate); fOnValuesUpdate := IL_CheckHandler(ValuesUpdate); fOnAvailHistUpdate := IL_CheckHandler(AvailHistUpdate); fOnPriceHistUpdate := IL_CheckHandler(PriceHistUpdate); end; //------------------------------------------------------------------------------ procedure TILItemShop_Base.ClearInternalEvents; begin fOnClearSelected := nil; fOnOverviewUpdate := nil; fOnShopListItemUpdate := nil; fOnValuesUpdate := nil; fOnAvailHistUpdate := nil; fOnPriceHistUpdate := nil; end; end.
unit ControllerObjectList; interface uses ControllerObjectItem, ControllerDataTypes; type TControllerObjectList = class protected FObjects: array of TControllerObjectItem; // Gets function GetItem(_ObjectID: TObjectID): TControllerObjectItem; function GetObject(_ID: integer): TControllerObjectItem; function GetNumItems: integer; // Adds procedure AddItem(_ObjectID: TObjectID); public // Constructors and destructors constructor Create; destructor Destroy; override; procedure Clear; // Adds and Remove procedure RemoveItem(var _Item: TControllerObjectItem); // Properties property NumItems: integer read GetNumItems; property Objects[_ID: integer]: TControllerObjectItem read GetObject; property Item[_ObjectID: TObjectID]: TControllerObjectItem read GetItem; end; implementation // Constructor and Destructors constructor TControllerObjectList.Create; begin SetLength(FObjects, 0); end; destructor TControllerObjectList.Destroy; begin Clear; inherited Destroy; end; procedure TControllerObjectList.Clear; var i: integer; begin for i := Low(FObjects) to High(FObjects) do begin FObjects[i].Free; end; SetLength(FObjects, 0); end; // Gets function TControllerObjectList.GetItem(_ObjectID: TObjectID): TControllerObjectItem; var i: integer; begin for i := Low(FObjects) to High(FObjects) do begin if FObjects[i].ObjectID = _ObjectID then begin Result := FObjects[i]; exit; end; end; AddItem(_ObjectID); Result := FObjects[High(FObjects)]; end; function TControllerObjectList.GetNumItems: integer; begin Result := High(FObjects) + 1; end; function TControllerObjectList.GetObject(_ID: integer): TControllerObjectItem; begin if (_ID >= 0) and (_ID <= High(FObjects)) then begin Result := FObjects[_ID]; end else begin Result := nil; end; end; // Adds & Remove procedure TControllerObjectList.AddItem(_ObjectID: TObjectID); begin SetLength(FObjects, High(FObjects) + 2); FObjects[High(FObjects)] := TControllerObjectItem.Create(_ObjectID); end; procedure TControllerObjectList.RemoveItem(var _Item: TControllerObjectItem); var i: integer; found: boolean; begin i := High(FObjects); found := false; while (not found) and (i >= 0) do begin if FObjects[i].ObjectID = _Item.ObjectID then begin found := true; end else begin dec(i); end; end; while i < High(FObjects) do begin FObjects[i] := FObjects[i+1]; inc(i); end; _Item.Free; SetLength(FObjects, High(FObjects)); end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFRenderHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefRenderHandlerOwn = class(TCefBaseRefCountedOwn, ICefRenderHandler) protected procedure GetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler); virtual; function GetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; virtual; function GetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; virtual; function GetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean; virtual; function GetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean; virtual; procedure OnPopupShow(const browser: ICefBrowser; show: Boolean); virtual; procedure OnPopupSize(const browser: ICefBrowser; const rect: PCefRect); virtual; procedure OnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); virtual; procedure OnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; CursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); virtual; function OnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean; virtual; procedure OnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation); virtual; procedure OnScrollOffsetChanged(const browser: ICefBrowser; x, y: Double); virtual; procedure OnIMECompositionRangeChanged(const browser: ICefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect); virtual; public constructor Create; virtual; end; TCustomRenderHandler = class(TCefRenderHandlerOwn) protected FEvent: IChromiumEvents; procedure GetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler); override; function GetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; override; function GetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; override; function GetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean; override; procedure OnPopupShow(const browser: ICefBrowser; show: Boolean); override; procedure OnPopupSize(const browser: ICefBrowser; const rect: PCefRect); override; procedure OnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); override; procedure OnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); override; function GetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean; override; function OnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean; override; procedure OnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation); override; procedure OnScrollOffsetChanged(const browser: ICefBrowser; x, y: Double); override; procedure OnIMECompositionRangeChanged(const browser: ICefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect); override; public constructor Create(const events: IChromiumEvents); reintroduce; virtual; destructor Destroy; override; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFDragData; function cef_render_handler_get_accessibility_handler(self: PCefRenderHandler): PCefAccessibilityHandler; stdcall; var TempHandler : ICefAccessibilityHandler; begin with TCefRenderHandlerOwn(CefGetObject(self)) do begin TempHandler := nil; GetAccessibilityHandler(TempHandler); if (TempHandler <> nil) then Result := TempHandler.Wrap else Result := nil; end; end; function cef_render_handler_get_root_screen_rect(self: PCefRenderHandler; browser: PCefBrowser; rect: PCefRect): Integer; stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do Result := Ord(GetRootScreenRect(TCefBrowserRef.UnWrap(browser), rect^)); end; function cef_render_handler_get_view_rect(self: PCefRenderHandler; browser: PCefBrowser; rect: PCefRect): Integer; stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do Result := Ord(GetViewRect(TCefBrowserRef.UnWrap(browser), rect^)); end; function cef_render_handler_get_screen_point(self: PCefRenderHandler; browser: PCefBrowser; viewX, viewY: Integer; screenX, screenY: PInteger): Integer; stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do Result := Ord(GetScreenPoint(TCefBrowserRef.UnWrap(browser), viewX, viewY, screenX^, screenY^)); end; function cef_render_handler_get_screen_info(self: PCefRenderHandler; browser: PCefBrowser; screen_info: PCefScreenInfo): Integer; stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do Result := Ord(GetScreenInfo(TCefBrowserRef.UnWrap(browser), screen_info^)); end; procedure cef_render_handler_on_popup_show(self: PCefRenderProcessHandler; browser: PCefBrowser; show: Integer); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnPopupShow(TCefBrowserRef.UnWrap(browser), show <> 0); end; procedure cef_render_handler_on_popup_size(self: PCefRenderProcessHandler; browser: PCefBrowser; const rect: PCefRect); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnPopupSize(TCefBrowserRef.UnWrap(browser), rect); end; procedure cef_render_handler_on_paint(self: PCefRenderProcessHandler; browser: PCefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnPaint(TCefBrowserRef.UnWrap(browser), kind, dirtyRectsCount, dirtyRects, buffer, width, height); end; procedure cef_render_handler_on_cursor_change(self: PCefRenderProcessHandler; browser: PCefBrowser; cursor: TCefCursorHandle; type_: TCefCursorType; const custom_cursor_info: PCefCursorInfo); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnCursorChange(TCefBrowserRef.UnWrap(browser), cursor, type_, custom_cursor_info); end; function cef_render_handler_start_dragging(self: PCefRenderProcessHandler; browser: PCefBrowser; drag_data: PCefDragData; allowed_ops: TCefDragOperations; x, y: Integer): Integer; stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do Result := Ord(OnStartDragging(TCefBrowserRef.UnWrap(browser), TCefDragDataRef.UnWrap(drag_data), allowed_ops, x, y)); end; procedure cef_render_handler_update_drag_cursor(self: PCefRenderProcessHandler; browser: PCefBrowser; operation: TCefDragOperation); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnUpdateDragCursor(TCefBrowserRef.UnWrap(browser), operation); end; procedure cef_render_handler_on_scroll_offset_changed(self: PCefRenderProcessHandler; browser: PCefBrowser; x, y: Double); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnScrollOffsetChanged(TCefBrowserRef.UnWrap(browser), x, y); end; procedure cef_render_handler_on_ime_composition_range_changed(self: PCefRenderProcessHandler; browser: PCefBrowser; const selected_range: PCefRange; character_boundsCount: NativeUInt; const character_bounds: PCefRect); stdcall; begin with TCefRenderHandlerOwn(CefGetObject(self)) do OnIMECompositionRangeChanged(TCefBrowserRef.UnWrap(browser), selected_range, character_boundsCount, character_bounds); end; constructor TCefRenderHandlerOwn.Create; begin CreateData(SizeOf(TCefRenderHandler)); with PCefRenderHandler(FData)^ do begin get_accessibility_handler := cef_render_handler_get_accessibility_handler; get_root_screen_rect := cef_render_handler_get_root_screen_rect; get_view_rect := cef_render_handler_get_view_rect; get_screen_point := cef_render_handler_get_screen_point; get_screen_info := cef_render_handler_get_screen_info; on_popup_show := cef_render_handler_on_popup_show; on_popup_size := cef_render_handler_on_popup_size; on_paint := cef_render_handler_on_paint; on_cursor_change := cef_render_handler_on_cursor_change; start_dragging := cef_render_handler_start_dragging; update_drag_cursor := cef_render_handler_update_drag_cursor; on_scroll_offset_changed := cef_render_handler_on_scroll_offset_changed; on_ime_composition_range_changed := cef_render_handler_on_ime_composition_range_changed; end; end; procedure TCefRenderHandlerOwn.GetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler); begin aAccessibilityHandler := nil; end; function TCefRenderHandlerOwn.GetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; begin Result := False; end; function TCefRenderHandlerOwn.GetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean; begin Result := False; end; function TCefRenderHandlerOwn.GetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean; begin Result := False; end; function TCefRenderHandlerOwn.GetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; begin Result := False; end; procedure TCefRenderHandlerOwn.OnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; CursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); begin end; procedure TCefRenderHandlerOwn.OnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); begin end; procedure TCefRenderHandlerOwn.OnPopupShow(const browser: ICefBrowser; show: Boolean); begin end; procedure TCefRenderHandlerOwn.OnPopupSize(const browser: ICefBrowser; const rect: PCefRect); begin end; procedure TCefRenderHandlerOwn.OnScrollOffsetChanged( const browser: ICefBrowser; x, y: Double); begin end; procedure TCefRenderHandlerOwn.OnIMECompositionRangeChanged(const browser : ICefBrowser; const selected_range : PCefRange; character_boundsCount : NativeUInt; const character_bounds : PCefRect); begin end; function TCefRenderHandlerOwn.OnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean; begin Result := False; end; procedure TCefRenderHandlerOwn.OnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation); begin end; // TCustomRenderHandler constructor TCustomRenderHandler.Create(const events: IChromiumEvents); begin inherited Create; FEvent := events; end; destructor TCustomRenderHandler.Destroy; begin FEvent := nil; inherited Destroy; end; procedure TCustomRenderHandler.GetAccessibilityHandler(var aAccessibilityHandler : ICefAccessibilityHandler); begin if (FEvent <> nil) then FEvent.doOnGetAccessibilityHandler(aAccessibilityHandler); end; function TCustomRenderHandler.GetRootScreenRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnGetRootScreenRect(browser, rect) else Result := inherited GetRootScreenRect(browser, rect); end; function TCustomRenderHandler.GetScreenInfo(const browser: ICefBrowser; var screenInfo: TCefScreenInfo): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnGetScreenInfo(browser, screenInfo) else Result := inherited GetScreenInfo(browser, screenInfo); end; function TCustomRenderHandler.GetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; var screenX, screenY: Integer): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnGetScreenPoint(browser, viewX, viewY, screenX, screenY) else Result := inherited GetScreenPoint(browser, viewX, viewY, screenX, screenY); end; function TCustomRenderHandler.GetViewRect(const browser: ICefBrowser; var rect: TCefRect): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnGetViewRect(browser, rect) else Result := inherited GetViewRect(browser, rect); end; procedure TCustomRenderHandler.OnCursorChange(const browser : ICefBrowser; cursor : TCefCursorHandle; cursorType : TCefCursorType; const customCursorInfo : PCefCursorInfo); begin if (FEvent <> nil) then FEvent.doOnCursorChange(browser, cursor, cursorType, customCursorInfo); end; procedure TCustomRenderHandler.OnPaint(const browser : ICefBrowser; kind : TCefPaintElementType; dirtyRectsCount : NativeUInt; const dirtyRects : PCefRectArray; const buffer : Pointer; width : Integer; height : Integer); begin if (FEvent <> nil) then FEvent.doOnPaint(browser, kind, dirtyRectsCount, dirtyRects, buffer, width, height); end; procedure TCustomRenderHandler.OnPopupShow(const browser: ICefBrowser; show: Boolean); begin if (FEvent <> nil) then FEvent.doOnPopupShow(browser, show); end; procedure TCustomRenderHandler.OnPopupSize(const browser: ICefBrowser; const rect: PCefRect); begin if (FEvent <> nil) then FEvent.doOnPopupSize(browser, rect); end; procedure TCustomRenderHandler.OnScrollOffsetChanged(const browser: ICefBrowser; x, y: Double); begin if (FEvent <> nil) then FEvent.doOnScrollOffsetChanged(browser, x, y); end; procedure TCustomRenderHandler.OnIMECompositionRangeChanged(const browser : ICefBrowser; const selected_range : PCefRange; character_boundsCount : NativeUInt; const character_bounds : PCefRect); begin if (FEvent <> nil) then FEvent.doOnIMECompositionRangeChanged(browser, selected_range, character_boundsCount, character_bounds); end; function TCustomRenderHandler.OnStartDragging(const browser : ICefBrowser; const dragData : ICefDragData; allowedOps : TCefDragOperations; x : Integer; y : Integer): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnStartDragging(browser, dragData, allowedOps, x, y) else Result := inherited OnStartDragging(browser, dragData, allowedOps, x, y); end; procedure TCustomRenderHandler.OnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation); begin if (FEvent <> nil) then FEvent.doOnUpdateDragCursor(browser, operation); end; end.
unit AStar64.LandMark; interface uses SysUtils, Classes, Types, StrUtils, IOUtils, Math, System.Generics.Collections, System.Generics.Defaults, AStar64.Extra, AStar64.FileStructs, JsonDataObjects, Ils.Json.Names, Ils.Json.Utils, Geo.Pos, Geo.Calcs, Geo.Hash, slogsend; const CIndexFileExt = '.idx'; CRecalcFileExt = '.rec'; CDataFileExt = '.dat'; CAreaFile = 'Areas.txt'; type TLandMarkWayKey = packed record v: THashVector; z: UInt64; end; TLandMarkKeyArray = array of TLandMarkWayKey; TLandMarkIdxLenFileRecord = packed record k: TLandMarkWayKey; i: Int64; l: Double; RESERVED: Int64; end; TAreaStateType = (stNoCalc, stPartialCalc, stInCalc, stFullCalc); TWayLen = packed record Way: string; Len: Double; end; TZoneTrackDictionary = TDictionary<UInt64, TWayLen>; TLandMarkDictionary = TDictionary<THashVector, TZoneTrackDictionary>; TLandMarkAreaInfo = record AccountID: Integer; State: TAreaStateType; //состояние рассчитанности маршрутов GeoHashID: string; Name: string; PolygonHash: string; LandMarksHash: string; Polygon: TGeoPosArray; LandMarks: TGeoPosArray; LandMarkDict: TLandMarkDictionary; end; TLandMarkAreaDictionary = class(TDictionary<Integer, TLandMarkAreaInfo>) public function Save(const ARootPath: string; const AAccount: integer): Boolean; end; TGeoWayVectorHash = class(TDictionary<THashVector, Integer>) public function Parse(const AHash: string): Boolean; end; TLandMarkWay = class private FIdx: Integer; FGeoHashString: string; FGeoWayVectorHash: TGeoWayVectorHash; FDistance: Double; FConnectedNodeForward: TNode; FConnectedNodeBackward: TNode; function GetConnectedNode(Idx: TADir): TNode; procedure SetConnectedNode(Idx: TADir; const Value: TNode); function GetHashVector(Idx: Integer): THashVector; public property Idx: Integer read FIdx write FIdx; property ConnectedNode[Idx: TADir]: TNode read GetConnectedNode write SetConnectedNode; property GeoHash: string read FGeoHashString write FGeoHashString; property GeoWayVectorHash: TGeoWayVectorHash read FGeoWayVectorHash; property Distance: Double read FDistance; property HashVector[Idx: Integer]: THashVector read GetHashVector; procedure NewData(const AGeoHash: string; const ADistance: Double); procedure Clear; function IsEmpty: Boolean; constructor Create(const AGeoHash: string; const ADistance: Double); overload; constructor Create(const AIdx: Integer; const AGeoHash: string; const ADistance: Double); overload; destructor Destroy; override; end; TLandMarkMatrix = class(TDictionary<TLandMarkWayKey, TLandMarkWay>) private FIdxFN: string; FRecalcFN: string; FDatFN: string; FAccounts: TIntegerDynArray; FLandMarkWaysChoosen: TList<TLandMarkWayKey>; protected procedure ValueNotify(const Value: TLandMarkWay; Action: TCollectionNotification); override; public constructor Create(const ARootPath: string; const AFileName: string; const AAccounts: TIntegerDynArray; const AResDir: string); overload; constructor Create(const ARootPath: string; const AFileName: string); overload; destructor Destroy; override; function LoadChoosenWays: Integer; function GetAreaTracks(const ARootPath: string; const AAccount: Integer; const AGeoHashID: string): TLandMarkDictionary; function LoadIndex: Boolean; function Save: Integer; function SaveLandMarks(const ARootPath: string; const AAccount: integer; const AGeoHashID: string; ALandMarkDict: TLandMarkDictionary): Boolean; function SaveAreas(const ARootPath: string; const AAccount: integer; const AAreas: TLandMarkAreaDictionary; const ASaveTacks: Boolean): Boolean; function GetKeysForRecalc: TLandMarkKeyArray; procedure CheckAndLoadLandMarks(const AFromLatitude, AFromLongitude, AToLatitude, AToLongitude: Double; const FZones: Int64); function CheckLandmarkWayConnection(const ANode: TNode; const ADir: TADir; var OKey: TLandMarkWayKey): Boolean; property LandMarkWaysChoosen: TList<TLandMarkWayKey> read FLandMarkWaysChoosen; end; TLandMarkPicker = class private FLandMarkMatrix: TLandMarkMatrix; FRootPath: string; public LMNW: Int64; LMSE: Int64; constructor Create(const AAccs: TIntegerDynArray; const ALatiFrom, ALongiFrom, ALatiTo, ALongiTo: Double; const AResDir: string = ''); destructor Destroy; override; property LandMarkMatrix: TLandMarkMatrix read FLandMarkMatrix; end; implementation { TLandMarkMatrix } constructor TLandMarkMatrix.Create(const ARootPath: string; const AFileName: string; const AAccounts: TIntegerDynArray; const AResDir: string); var i: Integer; begin inherited Create; // FLandMarkWaysChoosen := TList<TLandMarkWayKey>.Create; FAccounts := AAccounts; for I := Low(AAccounts) to High(AAccounts) do begin if FileExists(ARootPath + IntToStr(AAccounts[i])+ PathDelim + AFileName + CIndexFileExt) then begin FIdxFN := ARootPath + IntToStr(AAccounts[i])+ PathDelim + AFileName + CIndexFileExt; FDatFN := ARootPath + IntToStr(AAccounts[i])+ PathDelim + AFileName + CDataFileExt; FRecalcFN := ARootPath + IntToStr(AAccounts[i])+ PathDelim + AFileName + CRecalcFileExt; Exit; end; end; if AResDir = '' then begin FIdxFN := ARootPath + IntToStr(AAccounts[0])+ PathDelim + AFileName + CIndexFileExt; FDatFN := ARootPath + IntToStr(AAccounts[0])+ PathDelim + AFileName + CDataFileExt; FRecalcFN := ARootPath + IntToStr(AAccounts[0])+ PathDelim + AFileName + CRecalcFileExt; end else begin FIdxFN := ARootPath + AResDir + PathDelim + AFileName + CIndexFileExt; FDatFN := ARootPath + AResDir + PathDelim + AFileName + CDataFileExt; FRecalcFN := ARootPath + AResDir + PathDelim + AFileName + CRecalcFileExt; end; end; destructor TLandMarkMatrix.Destroy; begin FLandMarkWaysChoosen.Free; Clear; // inherited Destroy; end; function TLandMarkMatrix.GetAreaTracks(const ARootPath: string; const AAccount: Integer; const AGeoHashID: string): TLandMarkDictionary; var LandMarkArr: array of TLandMarkIdxLenFileRecord; IdxFile, DatFile: TFileStream; DatFileReader: TStreamReader; IdxFileName, DatFileName, FileName: string; i: Integer; Way: TWayLen; ZoneTrackDict: TZoneTrackDictionary; begin Result := TDictionary<THashVector, TZoneTrackDictionary>.Create; begin FileName := Copy(AGeoHashID,3,12) + '_' + Copy(AGeoHashID,15,12); IdxFileName := ARootPath + IntToStr(AAccount) + PathDelim + FileName + CIndexFileExt; DatFileName := ARootPath + IntToStr(AAccount) + PathDelim + FileName + CDataFileExt; if not (FileExists(IdxFileName) and FileExists(DatFileName)) then Exit; IdxFile := TFileStream.Create(IdxFileName, fmOpenRead and fmShareDenyNone); DatFile := TFileStream.Create(DatFileName, fmOpenRead and fmShareDenyNone); DatFileReader := TStreamReader.Create(DatFile, TEncoding.ANSI, True); try SetLength(LandMarkArr, IdxFile.Size div SizeOf(TLandMarkIdxLenFileRecord)); IdxFile.ReadBuffer(LandMarkArr[0], IdxFile.Size); for i := Low(LandMarkArr) to High(LandMarkArr) do begin if (LandMarkArr[i].k.v.HashFrom > 0) and (LandMarkArr[i].k.v.HashTo > 0) and (LandMarkArr[i].i < DatFile.Size) then begin DatFileReader.DiscardBufferedData; DatFile.Position := LandMarkArr[i].i; Way.Way := Trim(DatFileReader.ReadLine); Way.Len := 0; if not Result.TryGetValue(LandMarkArr[i].k.v, ZoneTrackDict) then ZoneTrackDict := TDictionary<UInt64, TWayLen>.Create; ZoneTrackDict.AddOrSetValue(LandMarkArr[i].k.z, Way); Result.AddOrSetValue(LandMarkArr[i].k.v, ZoneTrackDict); end; end; finally IdxFile.Free; DatFileReader.Free; DatFile.Free; end; end; end; function TLandMarkMatrix.GetKeysForRecalc: TLandMarkKeyArray; var k: TLandMarkWayKey; begin SetLength(Result, 0); for k in Keys do begin if (Items[k].GeoHash = '') then begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := k; end; end; end; function TLandMarkMatrix.LoadIndex: Boolean; var fsIdx, fsRec, fsDat: TFileStream; ir: TLandMarkIdxLenFileRecord; srDat: TStreamReader; HashStr: string; begin if not FileExists(FIdxFN) then Exit(False); fsIdx := TFileStream.Create(FIdxFN, fmOpenRead + fmShareDenyNone); fsDat := TFileStream.Create(FDatFN, fmOpenRead + fmShareDenyNone); srDat := TStreamReader.Create(fsDat, TEncoding.ANSI, True); fsIdx.Seek(0, soFromBeginning); try while (fsIdx.Read(ir, SizeOf(ir)) = SizeOf(ir)) do begin if (ir.i < fsDat.Size) then begin srDat.DiscardBufferedData; fsDat.Position := ir.i; HashStr := Trim(srDat.ReadLine); end; if not ContainsKey(ir.k) then Add(ir.k, TLandMarkWay.Create(HashStr, ir.l)); end; if FileExists(FRecalcFN) then begin fsRec := TFileStream.Create(FRecalcFN, fmOpenRead + fmShareDenyNone); fsRec.Seek(0, soFromBeginning); try while (fsRec.Read(ir, SizeOf(ir)) = SizeOf(ir)) do if not ContainsKey(ir.k) then begin if ir.RESERVED = 0 then Add(ir.k, TLandMarkWay.Create('',0)) else Add(ir.k, TLandMarkWay.Create('fullcalc',0)); end; finally fsRec.Free; end; end; finally fsIdx.Free; fsDat.Free; srDat.Free; end; Result := True; end; function TLandMarkMatrix.LoadChoosenWays: Integer; var k: TLandMarkWayKey; fsDat: TFileStream; srDat: TStreamReader; begin Result := 0; if not FileExists(FDatFN) then Exit; fsDat := TFileStream.Create(FDatFN, fmOpenRead + fmShareDenyNone); srDat := TStreamReader.Create(fsDat); try for k in FLandMarkWaysChoosen do begin srDat.DiscardBufferedData; fsDat.Position := Items[k].Idx; Items[k].NewData(srDat.ReadLine, Items[k].Distance); Inc(Result); end; finally srDat.Free; fsDat.Free; end; end; function TLandMarkMatrix.Save: Integer; var fsIdx: TFileStream; fsDat: TFileStream; fsRec: TFileStream; swDat: TStreamWriter; ir: TLandMarkIdxLenFileRecord; k: TLandMarkWayKey; begin ir.RESERVED := 0; Result := 0; if FileExists(FDatFN) then DeleteFile(FDatFN); if FileExists(FIdxFN) then DeleteFile(FIdxFN); if FileExists(FRecalcFN) then DeleteFile(FRecalcFN); fsDat := TFileStream.Create(FDatFN, fmCreate + fmOpenReadWrite + fmShareDenyNone); swDat := TStreamWriter.Create(fsDat); fsIdx := TFileStream.Create(FIdxFN, fmCreate + fmOpenReadWrite + fmShareDenyNone); fsRec := TFileStream.Create(FRecalcFN, fmCreate + fmOpenReadWrite + fmShareDenyNone); try fsIdx.Seek(0, soFromBeginning); fsRec.Seek(0, soFromBeginning); fsDat.Seek(0, soFromBeginning); for k in Keys do begin ir.RESERVED := 0; if Items[k].IsEmpty then Continue; if (Items[k].GeoHash = 'error') then begin ir.k := k; ir.i := 0; ir.l := 0; fsRec.Write(ir, SizeOf(ir)); Continue; end; if (Items[k].GeoHash = 'fullcalc') then begin ir.k := k; ir.i := 0; ir.l := 0; ir.RESERVED := 1; fsRec.Write(ir, SizeOf(ir)); Continue; end; ir.k := k; ir.i := fsDat.Position; ir.l := Items[k].Distance; swDat.WriteLine(Items[k].GeoHash); // swDat.WriteLine(IntToStr(k.v.HashFrom)+'-'+IntToStr(k.v.HashTo)+'-'+IntToStr(k.z)+' '+ Items[k].GeoHash); fsIdx.Write(ir, SizeOf(ir)); Inc(Result); end; finally fsDat.Free; fsIdx.Free; fsRec.Free; end; end; function TLandMarkMatrix.SaveAreas(const ARootPath: string; const AAccount: integer; const AAreas: TLandMarkAreaDictionary; const ASaveTacks: Boolean): Boolean; var List: TStringList; ID: Integer; AreaInfo: TLandMarkAreaInfo; RootDir, AccDir: string; Json: TJsonObject; begin Json := TJsonObject.Create; try List := TStringList.Create; try for ID in AAreas.Keys do begin AAreas.TryGetValue(ID, AreaInfo); with Json.A['Areas'].AddObject do begin I['ID'] := ID; S['Name'] := AreaInfo.Name; S['GeoHashID'] := AreaInfo.GeoHashID; I['State'] := Integer(AreaInfo.State); S['Polygon'] := AreaInfo.PolygonHash; S['LandMarks'] := AreaInfo.LandMarksHash; if ASaveTacks and Assigned(AreaInfo.LandMarkDict) and (AreaInfo.LandMarkDict.Count > 0) then SaveLandMarks(ARootPath, AAccount, AreaInfo.GeoHashID, AreaInfo.LandMarkDict); end; end; List.Text := Json.ToString; RootDir := IncludeTrailingPathDelimiter(ExtractFileDir(GetModuleName(HInstance))); AccDir := IntToStr(AAccount) + PathDelim; // каталог ForceDirectories(ARootPath + AccDir); List.SaveToFile(ARootPath + AccDir + CAreaFile, TEncoding.UTF8); Result := True; finally List.Free; Json.Free; end; except Result := False; end; end; function TLandMarkMatrix.SaveLandMarks(const ARootPath: string; const AAccount: integer; const AGeoHashID: string; ALandMarkDict: TLandMarkDictionary): Boolean; var IdxFile, RecalcFile, DatFile: TFileStream; DatFileWriter: TStreamWriter; // RecalcFileName, IdxFileName, DatFileName, FileName: string; Way: TWayLen; HashVector: THashVector; ZoneTrackDict: TZoneTrackDictionary; Zone: UInt64; LandMarkIdx: TLandMarkIdxLenFileRecord; begin // FileName := Copy(AGeoHashID,3,12) + '_' + Copy(AGeoHashID,15,12); // IdxFileName := ARootPath + IntToStr(AAccount) + PathDelim + FileName + '.idx'; // DatFileName := ARootPath + IntToStr(AAccount) + PathDelim + FileName + '.dat'; if FileExists(FIdxFN) then DeleteFile(PChar(FIdxFN)); if FileExists(FDatFN) then DeleteFile(PChar(FDatFN)); if FileExists(FRecalcFN) then DeleteFile(PChar(FRecalcFN)); try IdxFile := TFileStream.Create(FIdxFN, fmCreate + fmOpenReadWrite); DatFile := TFileStream.Create(FDatFN, fmCreate + fmOpenReadWrite); RecalcFile := TFileStream.Create(FRecalcFN, fmCreate + fmOpenReadWrite); DatFileWriter := TStreamWriter.Create(DatFile); try IdxFile.Seek(0, soFromBeginning); RecalcFile.Seek(0, soFromBeginning); DatFile.Seek(0, soFromBeginning); for HashVector in ALandMarkDict.Keys do begin ALandMarkDict.TryGetValue(HashVector,ZoneTrackDict); for Zone in ZoneTrackDict.Keys do begin ZoneTrackDict.TryGetValue(Zone, Way); if Way.Way <> 'error' then begin LandMarkIdx.i := DatFile.Position; LandMarkIdx.k.v := HashVector; LandMarkIdx.k.z := Zone; LandMarkIdx.l := Way.Len;//Items[k].Distance; DatFileWriter.WriteLine(Way.Way); IdxFile.Write(LandMarkIdx, SizeOf(LandMarkIdx)); end else begin LandMarkIdx.i := 0; LandMarkIdx.k.v := HashVector; LandMarkIdx.k.z := Zone; LandMarkIdx.l := 0; RecalcFile.Write(LandMarkIdx, SizeOf(LandMarkIdx)); end; end; end; Result := True; finally IdxFile.Free; RecalcFile.Free; DatFileWriter.Free; DatFile.Free; end; except Result := False; end; end; procedure TLandMarkMatrix.ValueNotify(const Value: TLandMarkWay; Action: TCollectionNotification); begin if (Action = cnRemoved) then Value.Free; end; function TLandMarkMatrix.CheckLandmarkWayConnection(const ANode: TNode; const ADir: TADir; var OKey: TLandMarkWayKey): Boolean; var k: TLandMarkWayKey; HashVector: THashVector; begin Result := False; if (ADir = adForward) then HashVector := ANode.HashVector^ else HashVector := ANode.HashVector^.Reverse; for k in FLandMarkWaysChoosen do begin if Items[k].GeoWayVectorHash.ContainsKey(HashVector) then begin Items[k].ConnectedNode[ADir] := ANode; if Assigned(Items[k].ConnectedNode[ADir]) and Assigned(Items[k].ConnectedNode[Reverse(ADir)]) then begin OKey := k; Exit(True); end; end; end; end; constructor TLandMarkMatrix.Create(const ARootPath, AFileName: string); var Accounts: TIntegerDynArray; begin SetLength(Accounts, 1); Accounts[0] := 1; Create(ARootPath, AFileName, Accounts, ARootPath); end; procedure TLandMarkMatrix.CheckAndLoadLandMarks(const AFromLatitude, AFromLongitude, AToLatitude, AToLongitude: Double; const FZones: Int64); var PathVector: THashVector; WayKey: TLandMarkWayKey; LastVector: THashVector; LastDistance: Double; I: Integer; const CChoosenWaysMax = 8; CAzimuthTolerance = 10; begin LoadIndex(); PathVector.HashFrom := TGeoHash.EncodePointBin(AFromLatitude, AFromLongitude); PathVector.HashTo := TGeoHash.EncodePointBin(AToLatitude, AToLongitude); FLandMarkWaysChoosen.Clear(); for WayKey in Keys do begin if ((WayKey.z and FZones) = 0) then FLandMarkWaysChoosen.Add(WayKey); end; if (FLandMarkWaysChoosen.Count = 0) then Exit; //TODO: в конктно ЭТОЙ реализации нужно сначала отфильтровать по азимуту, а потом всё остальное (для скорости) FLandMarkWaysChoosen.Sort(TComparer<TLandMarkWayKey>.Construct( function(const Left, Right: TLandMarkWayKey): Integer begin if (Left.v.HashFrom < Right.v.HashFrom) then Result := -1 else if (Left.v.HashFrom > Right.v.HashFrom) then Result := 1 else if (Left.v.HashTo < Right.v.HashTo) then Result := -1 else if (Left.v.HashTo > Right.v.HashTo) then Result := 1 else Result := 0; end )); LastVector := FLandMarkWaysChoosen[0].v; LastDistance := Items[FLandMarkWaysChoosen[0]].Distance; I := 1; while (I < FLandMarkWaysChoosen.Count) do begin if (LastVector = FLandMarkWaysChoosen[I].v) then begin if (LastDistance < Items[FLandMarkWaysChoosen[I]].Distance) then FLandMarkWaysChoosen.Delete(I) else begin LastVector := FLandMarkWaysChoosen[I].v; LastDistance := Items[FLandMarkWaysChoosen[I]].Distance; FLandMarkWaysChoosen.Delete(I - 1); end; end else begin LastVector := FLandMarkWaysChoosen[I].v; LastDistance := Items[FLandMarkWaysChoosen[I]].Distance; Inc(I); end; end; FLandMarkWaysChoosen.Sort(TComparer<TLandMarkWayKey>.Construct( function(const Left, Right: TLandMarkWayKey): Integer function CalcDistance1(Key: TLandMarkWayKey): Double; var ds, dt: Double; begin ds := TGeoCalcs.GeoDistancePointToLineDeg( Key.v.PointFrom.Latitude, Key.v.PointFrom.Longitude, AFromLatitude, AFromLongitude, AToLatitude, AToLongitude ); dt := TGeoCalcs.GeoDistancePointToLineDeg( Key.v.PointTo.Latitude, Key.v.PointTo.Longitude, AFromLatitude, AFromLongitude, AToLatitude, AToLongitude ); Result := ds + dt; end; var dl, dr: Double; begin dl := CalcDistance1(Left); dr := CalcDistance1(Right); if (dl < dr) then Result := -1 else if (dl > dr) then Result := 1 else Result := 0; end )); I := 0; while (I < FLandMarkWaysChoosen.Count) do begin if not FLandMarkWaysChoosen[I].v.AzimuthFits(PathVector.Azimuth, CAzimuthTolerance) then FLandMarkWaysChoosen.Delete(I) else Inc(I); end; if (FLandMarkWaysChoosen.Count > CChoosenWaysMax) then FLandMarkWaysChoosen.DeleteRange(CChoosenWaysMax, FLandMarkWaysChoosen.Count - CChoosenWaysMax); LoadChoosenWays(); end; { TLandMarkWay } constructor TLandMarkWay.Create(const AGeoHash: string; const ADistance: Double); begin Create(-1, AGeoHash, ADistance); end; constructor TLandMarkWay.Create(const AIdx: Integer; const AGeoHash: string; const ADistance: Double); begin inherited Create; // FGeoWayVectorHash := TGeoWayVectorHash.Create; FConnectedNodeForward := nil; FConnectedNodeBackward := nil; Idx := AIdx; NewData(AGeoHash, ADistance); end; destructor TLandMarkWay.Destroy; begin FGeoWayVectorHash.Free; // inherited Destroy; end; procedure TLandMarkWay.Clear; begin Idx := -1; FGeoHashString := ''; FDistance := 0; FGeoWayVectorHash.Clear; end; function TLandMarkWay.GetHashVector(Idx: Integer): THashVector; var i: Integer; s1: string; s2: string; begin //LM //ucfq9fqxdkxe - 12 //Z2B0000000000000000 - 19 //ucfq9fmwpur5 - 12 i := 3 + (Idx * (12 + 19)); s1 := Copy(FGeoHashString, i, 12); s2 := Copy(FGeoHashString, i + (12 + 19), 12); Result := THashVector.Create(TGeoHash.DecodePointString(s1), TGeoHash.DecodePointString(s2)); end; function TLandMarkWay.IsEmpty: Boolean; begin Result := FGeoHashString = ''; end; procedure TLandMarkWay.NewData(const AGeoHash: string; const ADistance: Double); begin FDistance := ADistance; FGeoHashString := AGeoHash; FGeoWayVectorHash.Parse(FGeoHashString); end; function TLandMarkWay.GetConnectedNode(Idx: TADir): TNode; begin case Idx of adForward: Result := FConnectedNodeForward; else Result := FConnectedNodeBackward; end; end; procedure TLandMarkWay.SetConnectedNode(Idx: TADir; const Value: TNode); begin case Idx of adForward: if not Assigned(FConnectedNodeForward) then FConnectedNodeForward := Value; else if not Assigned(FConnectedNodeBackward) then FConnectedNodeBackward := Value; end; end; { TGeoWayVectorHash } function TGeoWayVectorHash.Parse(const AHash: string): Boolean; const CLen = 12 + 19 + 12; CFormatIncrement = 12 + 19; var v: THashVector; h1, h2: string; p1, p2: TGeoPos; sPos: Integer; Idx: Integer; begin Clear; if (AHash = '') then Exit(False); Idx := 0; sPos := 3; while ((sPos + CLen) <= Length(AHash)) do begin h1 := Copy(AHash, sPos, 12); h2 := Copy(AHash, sPos + (12 + 19), 12); TGeoHash.DecodePointString(h1, p1.Latitude, p1.Longitude); TGeoHash.DecodePointString(h2, p2.Latitude, p2.Longitude); v := THashVector.Create(p1, p2); if not ContainsKey(v) then Add(v, Idx); Inc(Idx); Inc(sPos, CFormatIncrement); end; Result := True; end; { TLandMarkPicker } function QExcludeFileExt(const AFullName: string): string; var I: Integer; begin for I := Length(AFullName) downto 1 do begin if (AFullName[I] = '.') then Exit(Copy(AFullName, 1, I - 1)); end; Result := AFullName; end; constructor TLandMarkPicker.Create(const AAccs: TIntegerDynArray; const ALatiFrom, ALongiFrom, ALatiTo, ALongiTo: Double; const AResDir: string); var WorkName: string; AccPath: string; LatiNW, LongiNW, LatiSE, LongiSE: Double; CurMinSum, PrevMinSum: Double; FilesList: TStringDynArray; RezIdx: Integer; AccIter: Integer; I: Integer; begin inherited Create; // if (Length(AAccs) = 0) then raise Exception.Create('Массив аккаунтов не должен быть пуст'); FRootPath := ExtractFilePath(GetModuleName(HInstance)); for AccIter in AAccs do begin AccPath := FRootPath + IntToStr(AccIter) + PathDelim; if not DirectoryExists(AccPath) then Continue; FilesList := TDirectory.GetFiles(AccPath, '*.idx'); if (Length(FilesList) = 0) then Continue; RezIdx := -1; PrevMinSum := Infinity; for I := Low(FilesList) to High(FilesList) do begin FilesList[I] := QExcludeFileExt(FilesList[I]); WorkName := ExtractFileName(FilesList[I]); if (Length(WorkName) = 25) and TGeoHash.DecodePointString(Copy(WorkName, 1, 12), LatiNW, LongiNW) and TGeoHash.DecodePointString(Copy(WorkName, 14, 12), LatiSE, LongiSE) then begin if (ALatiFrom > LatiNW) or (ALatiFrom < LatiSE) or (ALatiTo > LatiNW) or (ALatiTo < LatiSE) or (ALongiFrom < LongiNW) or (ALongiFrom > LongiSE) or (ALongiTo < LongiNW) or (ALongiTo > LongiSE) then Continue; CurMinSum := (LatiNW - LatiSE) + (LongiSE - LongiNW); if (PrevMinSum > CurMinSum) then begin LMNW := TGeoHash.ConvertStringToBin(Copy(WorkName, 1, 12)); LMSE := TGeoHash.ConvertStringToBin(Copy(WorkName, 14, 12)); PrevMinSum := CurMinSum; RezIdx := I; end; end; end; if (RezIdx <> -1) then begin FLandMarkMatrix := TLandMarkMatrix.Create(AccPath, WorkName, AAccs, AResDir); Break; end; end; end; destructor TLandMarkPicker.Destroy; begin FLandMarkMatrix.Free; // inherited Destroy; end; { TLandMarkAreaDictionary } function TLandMarkAreaDictionary.Save(const ARootPath: string; const AAccount: integer): Boolean; var List: TStringList; ID: Integer; AreaInfo: TLandMarkAreaInfo; RootDir, AccDir: string; Json: TJsonObject; begin Json := TJsonObject.Create; try List := TStringList.Create; try for ID in Keys do begin AreaInfo := Items[ID]; with Json.A['Areas'].AddObject do begin I['ID'] := ID; S['Name'] := AreaInfo.Name; S['GeoHashID'] := AreaInfo.GeoHashID; I['State'] := Integer(AreaInfo.State); S['Polygon'] := AreaInfo.PolygonHash; S['LandMarks'] := AreaInfo.LandMarksHash; end; end; List.Text := Json.ToString; RootDir := IncludeTrailingPathDelimiter(ExtractFileDir(GetModuleName(HInstance))); AccDir := IntToStr(AAccount) + PathDelim; // каталог ForceDirectories(ARootPath + AccDir); List.SaveToFile(ARootPath + AccDir + CAreaFile, TEncoding.UTF8); Result := True; finally List.Free; Json.Free; end; except Result := False; end; end; end.
unit controller; interface uses System.Classes, class_.util, IdCustomHTTPServer, IdGlobal; type TController = class(TInterfacedPersistent) private class var fCount : Integer; fRequestInfo : TIdHTTPRequestInfo; fResponseInfo: TIdHTTPResponseInfo; function getRequestInfo: TIdHTTPRequestInfo; function getResponseInfo: TIdHTTPResponseInfo; function getRequestBody: String; function getQueryParams:TStrings; protected class function addCount : Integer; public class function getCount : Integer; procedure setRequestInfo(RequestInfo: TIdHTTPRequestInfo); procedure setResponseInfo(ResponseInfo: TIdHTTPResponseInfo); function execMethod(MethodName : String; parametes : TArrayValue) : variant; function QueryParamByName(param : String) : variant; published property RequestInfo : TIdHTTPRequestInfo read getRequestInfo ; property ResponseInfo: TIdHTTPResponseInfo read getResponseInfo; property RequestBody : String read getRequestBody ; property QueryParams : TStrings read getQueryParams ; end; implementation uses Vcl.Dialogs, System.SysUtils, System.Rtti, HTTPServer; { TController } class function TController.addCount: Integer; begin inc(fCount); result := fCount; end; function TController.execMethod(MethodName : String; parametes : TArrayValue) : variant; var ctxRtti : TRttiContext; typeRtti: TRttiType; metRtti : TRttiMethod; begin ctxRtti := TRttiContext.Create; try typeRtti := ctxRtti.GetType(self.ClassType); metRtti := typeRtti.GetMethod(MethodName); if not(Assigned(metRtti)) then begin getResponseInfo.ResponseNo := 500; getResponseInfo.ContentText := 'Metodo '+MethodName+ ' não localizado!'; Exit; end; result := metRtti.Invoke(self, parametes).ToString; finally ctxRtti.Free; end; end; class function TController.getCount: Integer; begin result := fCount; end; function TController.getQueryParams: TStrings; begin result := RequestInfo.Params; end; function TController.getRequestBody: String; begin result := ReadStringFromStream(RequestInfo.PostStream); end; function TController.getRequestInfo: TIdHTTPRequestInfo; begin result := fRequestInfo; //THTTPServer.getInstance.RequestInfo; end; function TController.getResponseInfo: TIdHTTPResponseInfo; begin result := fResponseInfo; //THTTPServer.getInstance.ResponseInfo; end; function TController.QueryParamByName(param: String): variant; var i : integer; v_param : String; begin result := ''; for v_param in QueryParams do begin if (UpperCase(v_param.Split(['='])[0]) = UpperCase(param)) then begin result := v_param.Split(['='])[1]; if (upperCase(result) = upperCase('NULL')) then result := EmptyStr; Break; end; end; end; procedure TController.setRequestInfo(RequestInfo: TIdHTTPRequestInfo); begin fRequestInfo := RequestInfo; end; procedure TController.setResponseInfo(ResponseInfo: TIdHTTPResponseInfo); begin fResponseInfo := ResponseInfo; end; initialization TController.fCount := 0; RegisterClass(TController); finalization UnRegisterClass(TController); end.
unit SuperEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TSuperEdit = class(TEdit) private FAlignment : TAlignment; FOnPressEnter : TNotifyEvent; procedure SetAlignment(Value: TAlignment); protected procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN; {handle esc} procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } published property OnPressEnter : TNotifyEvent read FOnPressEnter write FOnPressEnter; property Alignment: TAlignment read FAlignment write SetAlignment; end; procedure Register; implementation procedure TSuperEdit.CNKeyDown(var Message: TWMKeyDown); begin with Message do // Ambos os casos nao continua a capturar a tecla case charcode of VK_RETURN : begin if Assigned(OnPressEnter) then FOnPressEnter(Self); Exit; end; end; inherited; end; procedure Register; begin RegisterComponents('NewPower', [TSuperEdit]); end; procedure TSuperEdit.CreateParams(var Params: TCreateParams); const Alignments : array[TAlignment] of LongInt = (ES_Left,ES_Right, ES_Center); begin inherited CreateParams(Params); Params.Style := Params.Style or Alignments[FAlignment]; end; procedure TSuperEdit.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; end.
unit Unit1; // ----------------------------------------------------------------------------- // // Random SVG star // // B.J.H. Verhue // // ----------------------------------------------------------------------------- interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, BVE.SVG2Image.VCL; type TForm1 = class(TForm) SVG2Image1: TSVG2Image; Timer1: TTimer; procedure Timer1Timer(Sender: TObject); procedure SVG2Image1Click(Sender: TObject); private FTime: integer; function LFO(const f: single): single; function LFO2(const s, f: single): single; public function StarPath(const aEdgeCount: integer; const aRIn, aROut, aOuterEdge: single): string; procedure Update; end; var Form1: TForm1; implementation uses Vcl.Clipbrd, System.Math; {$R *.dfm} { TForm1 } function TForm1.LFO(const f: single): single; begin // Low frequency oscilator Result := Sin(2* PI * f * FTime / 1000); end; function TForm1.LFO2(const s, f: single): single; begin // Coupled LFO's to simulate randomness Result := LFO(s * LFO(f)); end; function SVGColor(const aR, aG, aB: single): string; begin Result := '#' + IntToHex(Round(255 * Abs(aR)), 2) + IntToHex(Round(255 * Abs(aG)), 2) + IntToHex(Round(255 * Abs(aB)), 2); end; function TForm1.StarPath(const aEdgeCount: integer; const aRIn, aROut, aOuterEdge: single): string; var i: integer; InnerAngle, OuterAngle, X, Y: single; begin // Create starshaped pathdata // aEdgeCount : number of edges or points // aRIn : radius of star core // aROuter : outer radius of star // aOuterEdge : width of star point Result := ''; InnerAngle := 2 * PI / aEdgeCount; OuterAngle := arctan2(aOuterEdge, aROut); for i := 0 to aEdgeCount - 1 do begin X := aRIn * Sin(i * InnerAngle); Y := aRIn * Cos(i * InnerAngle); if i = 0 then Result := Result + Format('M%0:.2f,%1:.2f', [X, Y]) else Result := Result + Format('L%0:.2f,%1:.2f', [X, Y]); X := aROut * Sin((i + 0.5 - OuterAngle) * InnerAngle); Y := aROut * Cos((i + 0.5 - OuterAngle) * InnerAngle); Result := Result + Format('L%0:.2f,%1:.2f', [X, Y]); X := aROut * Sin((i + 0.5 + OuterAngle) * InnerAngle); Y := aROut * Cos((i + 0.5 + OuterAngle) * InnerAngle); Result := Result + Format('L%0:.2f,%1:.2f', [X, Y]); end; Result := Result + 'Z'; end; procedure TForm1.SVG2Image1Click(Sender: TObject); begin Timer1.Enabled := not Timer1.Enabled; // Put SVG on clipboard if paused if not Timer1.Enabled then Clipboard.AsText := SVG2Image1.SVG.Text; end; procedure TForm1.Timer1Timer(Sender: TObject); begin // Timer interval is set to 25ms, FPS=40 Update; Inc(FTime, Timer1.Interval); end; procedure TForm1.Update; begin // Create SVG content and assign to SVG2Image SVG2Image1.SVG.Text := '<svg version="1.1" id="star"' + ' viewBox="-100 -100 200 200"' + ' xmlns="http://www.w3.org/2000/svg">' // Defs section with a random radial gradient + ' <defs>' + ' <radialGradient id="radGrad1">' + ' <stop offset="0%" stop-color="' + SVGColor(LFO2(0.01, 0.02), LFO2(0.015, 0.03), LFO2(0.008, 0.015)) + '" />' + ' <stop offset="100%" stop-color="' + SVGColor(LFO2(0.02, 0.01), LFO2(0.025, 0.015), LFO2(0.03, 0.008)) + '" />' + ' </radialGradient>' + '</defs>' // Path element with random starshape + '<path stroke="pink" fill="url(#radGrad1)" stroke-width="3" d="' + StarPath( Round(19 + 16 * LFO2(0.01, 0.01)), 50 + 30 * LFO2(0.03, 0.005), 80 + 10 * LFO2(0.008, 0.01), 16 + 16 * LFO2(0.01, 0.002)) + '"/>' + '</svg>'; SVG2Image1.Repaint; end; initialization // Set decimal seperator for "Format" function FormatSettings.DecimalSeparator := '.'; end.
unit NetMsg; // ***************************************************************************** // ***************************************************************************** // IMPORTANT! // ***************************************************************************** // ***************************************************************************** // The NetAPI only operates with Windows NT/2000. // If you wish to create an application using this unit, you have a choice // between statically and dynamically linking with NetAPI32.dll. // IF YOUR COMPILED EXECUTABLE IS ONLY EVER GOING TO BE RUN UNDER // WINDOWS NT/2000: // It is recommended that you *statically* link with this DLL. // In order to statically link your executable to this DLL, you must define the // compiler directive "_NETMSG_STATIC". // To do this, goto "Project options", "Directories/Conditionals" tab and // include "_NETMSG_STATIC" in the "Conditional defines" list // Apart from this, all you need do is include this unit in your "uses" clause // IF YOUR COMPILED EXECUTABLE WILL AT ANY TIME BE RUN UNDER WINDOWS 9X/ME: // Your executable must *dynamically* link with this DLL, otherwise you'll get // a DLL error when your program starts up, and it will simply crash and die. // In order to dynamically link your executable to this DLL, you don't need // to do anything other than include this unit in your "uses" clause. interface uses Windows; const NETAPI_DLL = 'NetAPI32.dll'; type NET_API_STATUS = DWORD; // --------------------------------------------------------------------------- // Net API interface function NetMessageNameAdd( servername:PWChar; msgname:PWChar ) : NET_API_STATUS; stdcall; function NetMessageBufferSend( servername :PWChar; msgname :PWChar; fromname :PWChar; buf : PByte; buflen :DWORD ) : NET_API_STATUS; stdcall; function NetMessageNameDel( servername :PWChar; msgname :PWChar ) : NET_API_STATUS; stdcall; function NetMessageNameEnum( servername : PWChar; level : DWORD; bufptr : PByte; prefmaxlen : DWORD; entriesread : LPDWORD; totalentries : LPDWORD; resume_handle : LPDWORD ) : NET_API_STATUS; stdcall; function NetMessageNameGetInfo( servername: PWChar; msgname: PWChar; level : DWORD; bufptr : PByte ) : NET_API_STATUS; stdcall; implementation {$ifdef _NETMSG_STATIC} // ----------------------------------------------------------------------------- // Net API implementation - staticly linked DLL function NetMessageNameAdd; external NETAPI_DLL name 'NetMessageNameAdd'; function NetMessageBufferSend; external NETAPI_DLL name 'NetMessageBufferSend'; function NetMessageNameDel; external NETAPI_DLL name 'NetMessageNameDel'; function NetMessageNameEnum; external NETAPI_DLL name 'NetMessageNameEnum'; function NetMessageNameGetInfo; external NETAPI_DLL name 'NetMessageNameGetInfo'; // ----------------------------------------------------------------------------- {$else} // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Net API implementation - dynamicly linked DLL type TNetMessageNameAdd = function ( servername:PWChar; msgname:PWChar ) : NET_API_STATUS; stdcall; TNetMessageBufferSend = function ( servername :PWChar; msgname :PWChar; fromname :PWChar; buf : PByte; buflen :DWORD ) : NET_API_STATUS; stdcall; TNetMessageNameDel= function ( servername :PWChar; msgname :PWChar ) : NET_API_STATUS; stdcall; TNetMessageNameEnum = function ( servername : PWChar; level : DWORD; bufptr : PByte; prefmaxlen : DWORD; entriesread : LPDWORD; totalentries : LPDWORD; resume_handle : LPDWORD ) : NET_API_STATUS; stdcall; TNetMessageNameGetInfo = function ( servername: PWChar; msgname: PWChar; level : DWORD; bufptr : PByte ) : NET_API_STATUS; stdcall; // ----------------------------------------------------------------------------- function NetMessageNameAdd( servername:PWChar; msgname:PWChar ) : NET_API_STATUS; stdcall; var libHandle: THandle; libFunction: TNetMessageNameAdd; begin libHandle := LoadLibrary(NETAPI_DLL); if libHandle = 0 then begin Result := GetLastError; exit; end; try @libFunction := GetProcAddress(libHandle, 'NetMessageNameAdd'); if @libFunction = nil then begin Result := GetLastError; exit; end; Result := libFunction(servername, msgname); finally FreeLibrary(libHandle); end; end; function NetMessageBufferSend( servername :PWChar; msgname :PWChar; fromname :PWChar; buf : PByte; buflen :DWORD ) : NET_API_STATUS; stdcall; var libHandle: THandle; libFunction: TNetMessageBufferSend; begin libHandle := LoadLibrary(NETAPI_DLL); if libHandle = 0 then begin Result := GetLastError; exit; end; try @libFunction := GetProcAddress(libHandle, 'NetMessageBufferSend'); if @libFunction = nil then begin Result := GetLastError; exit; end; Result := libFunction(servername, msgname, fromname, buf, buflen); finally FreeLibrary(libHandle); end; end; function NetMessageNameDel( servername :PWChar; msgname :PWChar ) : NET_API_STATUS; stdcall; var libHandle: THandle; libFunction: TNetMessageNameDel; begin libHandle := LoadLibrary(NETAPI_DLL); if libHandle = 0 then begin Result := GetLastError; exit; end; try @libFunction := GetProcAddress(libHandle, 'NetMessageNameDel'); if @libFunction = nil then begin Result := GetLastError; exit; end; Result := libFunction(servername, msgname); finally FreeLibrary(libHandle); end; end; function NetMessageNameEnum( servername : PWChar; level : DWORD; bufptr : PByte; prefmaxlen : DWORD; entriesread : LPDWORD; totalentries : LPDWORD; resume_handle : LPDWORD ) : NET_API_STATUS; stdcall; var libHandle: THandle; libFunction: TNetMessageNameEnum; begin libHandle := LoadLibrary(NETAPI_DLL); if libHandle = 0 then begin Result := GetLastError; exit; end; try @libFunction := GetProcAddress(libHandle, 'NetMessageNameEnum'); if @libFunction = nil then begin Result := GetLastError; exit; end; Result := libFunction(servername, level, bufptr, prefmaxlen, entriesread, totalentries, resume_handle); finally FreeLibrary(libHandle); end; end; function NetMessageNameGetInfo( servername: PWChar; msgname: PWChar; level : DWORD; bufptr : PByte ) : NET_API_STATUS; stdcall; var libHandle: THandle; libFunction: TNetMessageNameGetInfo; begin libHandle := LoadLibrary(NETAPI_DLL); if libHandle = 0 then begin Result := GetLastError; exit; end; try @libFunction := GetProcAddress(libHandle, 'NetMessageNameGetInfo'); if @libFunction = nil then begin Result := GetLastError; exit; end; Result := libFunction(servername, msgname, level, bufptr); finally FreeLibrary(libHandle); end; end; {$endif} END.
unit CompareBytes; interface uses Windows, SysUtils, Classes; function CompareFastBytes(const Data1,Data2:Pointer; const DataSize:integer):boolean; function CompareFastBytesEx(const Data1:Pointer; const Size1:integer; const Data2:Pointer; const Size2:integer): Integer; implementation function CompareSlowBytes(Data1,Data2:Pointer; DataSize:integer):boolean; var Loop : integer; pItem1, pItem2 : ^Byte; begin pItem1:= Data1; pItem2:= Data2; Result:= true; for Loop := 1 to DataSize do begin if pItem1^ <> pItem2^ then begin Result:= false; Break; end; Inc(pItem1, 1); Inc(pItem2, 1); end; end; function CompareFastBytes(const Data1,Data2:Pointer; const DataSize:integer):boolean; var Loop : integer; pItem1, pItem2 : ^DWord; begin pItem1:= Data1; pItem2:= Data2; for Loop := 1 to DataSize div 4 do begin if pItem1^ <> pItem2^ then begin Result:= false; Exit; end; Inc(pItem1, 1); Inc(pItem2, 1); end; Result:= CompareSlowBytes(pItem1, pItem2, DataSize mod 4); end; function CompareFastBytesEx(const Data1:Pointer; const Size1:integer; const Data2:Pointer; const Size2:integer): Integer; var Loop, Size : integer; pWord1, pWord2 : ^DWord; pByte1, pByte2 : ^Byte; begin Result := 0; if Size1 > Size2 then Size := Size2 else Size := Size1; pWord1 := Data1; pWord2 := Data2; for Loop := 1 to Size div 4 do begin if pWord1^ <> pWord2^ then begin if pWord1^ > pWord2^ then Result := 1 else Result := -1; Exit; end; Inc(pWord1); Inc(pWord2); end; pByte1 := Pointer(pWord1); pByte2 := Pointer(pWord2); for Loop := 1 to Size mod 4 do begin if pByte1^ <> pByte2^ then begin if pByte1^ > pByte2^ then Result := 1 else Result := -1; Exit; end; Inc(pByte1); Inc(pByte2); end; if Size1 > Size2 then Result := 1 else if Size1 < Size2 then Result := -1; end; {$IFDEF DEBUG} var Item1 : word = $FFFF; Item2 : word = $FFFF; Item3 : word = $1230; Item4 : word = $1234; {$ENDIF} initialization {$IFDEF DEBUG} Assert(CompareFastBytesEx(@Item1, 1, @Item2, 1) = 0, 'CompareFastBytesEx(@Item1, 1, @Item2, 1) = 0'); Assert(CompareFastBytesEx(@Item1, 1, @Item2, 2) = -1, 'CompareFastBytesEx(@Item1, 1, @Item2, 2) = -1'); // 엔디안 문제로 실제 비교는 $3012 vs $3412 가 된다. Assert(CompareFastBytesEx(@Item3, 2, @Item4, 2) = -1, 'CompareFastBytesEx(@Item3, 2, @Item4, 2) = -1'); {$ENDIF} end.
//*****************************************// //*****设置前台POS钱箱,打印机,显示屏*****// //函数接口:ShowSetForm //内部接口:由各DLL组成// //作者: //日期: //***************************************// unit Pform_SetPos; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls ,IniFiles,cxControls, ShellAPI, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, Math; type TPosSet = Record BoxControl, //钱箱控制 BoxPort, //钱箱端口 PrintPort, //打印机端口 PrintModel, //打印机型号 PrintColor, //打印颜色 PrintCut, //切纸方式 ScreenPort, //显示端口 Screentype, PayMode: Integer; Bill_Top, Bill_Bottom: string; Bill_Print, MaxCount, Item1, Item2, Item3, Item4, Item5, Item6: Integer; end; //显示类型 type tSetform = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; Panel1: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; RadioGroup1: TRadioGroup; Label1: TLabel; Label2: TLabel; RadioGroup3: TRadioGroup; Label3: TLabel; Label4: TLabel; inibutton: TButton; OpenButton: TButton; StateButton: TButton; Label5: TLabel; CobType: TComboBox; Label6: TLabel; CobPort: TComboBox; Label7: TLabel; CobColor: TComboBox; Label8: TLabel; EdPage: TEdit; Label9: TLabel; RedText: TRichEdit; Label10: TLabel; Cobcut: TComboBox; Ini: TButton; InPaper: TButton; MicroFeed: TButton; Print: TButton; Cut: TButton; Label11: TLabel; ComboBox1: TComboBox; Label12: TLabel; ComboBox2: TComboBox; RadioGroup4: TRadioGroup; Label13: TLabel; Edit1: TEdit; Button1: TButton; Button2: TButton; Button3: TButton; procedure BitBtn2Click(Sender: TObject); Function CheckSelect(State:String):Integer; procedure IniButtonClick(Sender: TObject); procedure OpenButtonClick(Sender: TObject); procedure StateButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CobTypeChange(Sender: TObject); procedure CobPortChange(Sender: TObject); procedure INIClick(Sender: TObject); procedure InPaperClick(Sender: TObject); procedure MicroFeedClick(Sender: TObject); procedure PrintClick(Sender: TObject); procedure CutClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RadioGroup1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure EdPageKeyPress(Sender: TObject; var Key: Char); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure Edit1Exit(Sender: TObject); procedure EdPageExit(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure RadioGroup4Click(Sender: TObject); procedure aaClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); private FBoxV1: String; FResultI: Integer; FBoxV3: String; FBoxV2: String; FPrnType: Integer; FPrnPort: Integer; FShowText: String; FShowPort: Integer; { Private declarations } public Property BoxV1: String Read FBoxV1 Write FBoxV1;//传递钱箱的三个值及返回值 Property BoxV2: String Read FBoxV2 Write FBoxV2; Property BoxV3: String Read FBoxV3 Write FBoxV3; Property ResultI: Integer Read FResultI Write FResultI; Property PrnPort :Integer Read FPrnPort Write FPrnPort default 1; //打印机端口 Property PrnType :Integer Read FPrnType Write FPrnType default 1; //打印机类型 Property ShowPort :Integer Read FShowPort Write FShowPort default 1 ; //显示屏端口 Property ShowText :String Read FShowText Write FShowText ; { Public declarations } end; var Setform: TSetform; POSSet: TPosSet; //动态链接库函数声明 function Drawer(var1, var2, var3: string): integer; export;stdcall;far;external 'DrawerDll.dll'; //打印机 function HK110D_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK110D_PrnCnEn(iPt: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK110D_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK110D_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HKP600T_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HKP600T_PrnCnEn(iPt: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function HKP600T_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HKP600T_Cut(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function ADP300_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function ADP300_PrnCnEn(iPt, iColor: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function ADP300_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function ADP300_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function ADP300_Cut(iPt, iVal: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK588TP_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK588TP_PrnCnEn(iPt: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK588TP_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function HK588TP_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM300K_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM300K_PrnCnEn(iPt, iColor: integer; sData: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM300K_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM300K_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM300K_Cut(iPt, iVal: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210D_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210D_PrnCnEn(ipt, iColor: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210D_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210D_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210P_Init(iPt: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210P_PrnCnEn(ipt, iColor: integer; str: string): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210P_FeedLines(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; function TM210P_MicroFeed(iPt, iLines: integer): integer; export; stdcall; far; external 'mPrnDll.dll'; //show function lc112_Init(bPt: byte): boolean; export; stdcall; far; external 'lc112dll.dll'; function lc112_DisplayStr(str: string): boolean; export; stdcall; far; external 'lc112dll.dll'; function lc112_ClearScreen: boolean; export; stdcall; far; external 'lc112dll.dll'; function lc112_SetPoint(iPostion: integer): boolean; export; stdcall; far; external 'lc112dll.dll'; function lc112_SendData(bData: byte): boolean; export; stdcall; far; external 'lc112dll.dll'; function lc112_SendStr(str: string): boolean; export; stdcall; far; external 'lc112dll.dll'; function vc108_CLS(bPt: byte): boolean; export; stdcall; far; external 'VC108dll.dll'; function VC108_Trans(bPt, bTransType, bCurrencyType: byte; rAmount: real): boolean; export; stdcall; far; external 'VC108dll.dll'; function Cv20_Init(bPt: byte): boolean; export; stdcall; far; external 'cv20dll.dll'; procedure Cv20_SelfTest; export; stdcall; far; external 'cv20dll.dll'; function Cv20_DisplayStr(str: string): boolean; export; stdcall; far; external 'cv20dll.dll'; function Cv20_ClearScreen: boolean; export; stdcall; far; external 'cv20dll.dll'; function Cv20_SendData(bData: byte): boolean; export; stdcall; far; external 'cv20dll.dll'; function com_init(com: Integer; baud: Dword): Boolean; export; stdcall; far; external 'api_com.dll'; function com_rest: Boolean; export; stdcall; far; external 'api_com.dll'; function com_send(buf: PChar; len: Integer): Boolean; export; stdcall; far; external 'api_com.dll'; //并口打印 Ftype:1、走纸 2、打印 PageNum: 为走纸的行数 pText 打印的内容 Procedure PosPrint(Ftype, PageNum: Integer; pText: String); //串口(Com),并口(Lpt)开钱箱 0, IfIni 是否初始化 Ftype : 1, 通过打印机开 2,通过显示屏开 , PORTNUM打印端口 1-COM1 ... FVALUE 为速率 2400或9600 Procedure PosBox(IfIni, Ftype, PortNum: Integer; Fvalue: Cardinal); //顾客显示屏,FTYPE指显示的项 0: 清屏 1:单价目 2:总计 3:收款 4:找零 CURR指显示的数值 Procedure PosScreen(Port: Byte; Fvalue: Cardinal; FType: Integer; Curr: currency); //初始化显示屏 Procedure PosScreenInit(Port: Byte; Fvalue: Cardinal); //钱箱 function USimpleRoundTo(const AValue: Double; const ADigit: TRoundToRange = -2): Double; Procedure ShowSetForm(IfShow:Boolean); implementation {$R *.DFM} Procedure PosScreenInit(Port:Byte;Fvalue:Cardinal); var Pdstr: string; begin {初始化显示屏} com_rest; if Com_init(Port, Fvalue) then begin Pdstr := chr(27) + chr(64); com_send(pchar(pdstr), length(pdstr)); end; end; Procedure PosScreen(Port: Byte; Fvalue: Cardinal; FType: Integer; Curr: currency); var pdstr: String; Begin Try If FType = 0 Then Begin PDStr := Chr(12); com_send(pchar(pdstr), length(pdstr)); PosScreenInit(Port, Fvalue); End Else Begin PDStr := Chr(27) + Chr(115) + IntToStr(FType) ; com_send(Pchar(PDStr), Length(PDStr)); PDStr := Chr(27) + Chr(81) + Chr(65) + CurrToStr(Curr) + Chr(13); com_send(Pchar(PDStr), Length(PDStr)); End; Finally End; End; Procedure PosBox(IfIni, Ftype, PortNum: Integer; Fvalue: Cardinal); //这里是通过显示屏来打开钱箱 var pdstr: string; F: TextFile; begin Try If IfIni = 1 Then Begin com_rest; Com_init(PortNum, Fvalue); //打开串口 Pdstr := chr(27) + chr(64); com_send(pchar(pdstr), length(pdstr)); //初始化显示屏} End Else Begin Case Ftype of 1:Begin PDStr := Chr(2) + Chr(77);{控制顾客显示屏开钱箱指令} com_send(Pchar(PDStr), Length(PDStr)); End; 2:Begin PDStr := Chr(27) + 'p' + Chr(0) + Chr(60) + Chr(255); {//打印机开钱箱} AssignFile(F, 'LPT1'); Rewrite(F); Write(F, PDStr); CloseFile(F); End; 3:begin ShellExecute(Application.Handle, '', pchar('Open.Com'), Nil, Pchar(ExtractFileDir(Application.ExeName)), SW_HIDE); end; end; End; except end; End; Procedure PosPrint(Ftype,PageNum:Integer;pText:String); Var F: TextFile; PDStr: string; i, Li_i: Integer; Begin Try If Ftype = 1 Then Begin PDStr := char(10); //为空即走纸 Li_i := PageNum; PDStr := '' + chr(10); AssignFile(F, 'LPT1'); Rewrite(F); While Li_i > 0 Do Begin Write(F, PDStr); Li_i := Li_i - 1; End; End Else Begin PDStr := pText + chr(10); Li_i := PageNum; AssignFile(F, 'LPT1'); Rewrite(F); Write(F, PDStr); PDStr := '' + chr(10); While Li_i > 0 Do Begin Write(F, PDStr); Li_i := Li_i - 1; End; End; CloseFile(F); Except End; End; function USimpleRoundTo(const AValue: Double; const ADigit: TRoundToRange = -2): Double; var LFactor: Double; begin LFactor := IntPower(10, ADigit); if AValue > 0 then Result := Trunc((AValue / LFactor) + 0.5) * LFactor else Result := Trunc((AValue / LFactor) - 0.5) * LFactor; end; Procedure ShowSetForm(IfShow:Boolean); Begin If Setform = Nil Then Application.CreateForm(TsetForm,SetForm); If IfShow Then Setform.ShowModal; End; procedure TSetForm.BitBtn2Click(Sender: TObject); begin Close; end; Function TSetForm.CheckSelect(State:String):Integer; Var li_i:Integer; begin case RadioGroup1.ItemIndex of 0: Begin BoxV1 :='MB'; // BoxV2 :=RadioGroup2.Items.Strings[RadioGroup2.itemindex]; End; 1: Begin BoxV1 :='PRN'; // BoxV2 :=RadioGroup3.Items.Strings[RadioGroup3.itemindex]; End; End; BoxV3 :=State; Li_i:=Drawer(BoxV1,BoxV2,BoxV3); Result :=li_i; end; procedure TSetForm.IniButtonClick(Sender: TObject); begin { ResultI:=CheckSelect('I'); Label4.Caption :=IntToStr(ResultI); If ResultI =1 Then Label3.Caption :='初始化成功!' Else Label3.Caption :='初始化失败!';} //这里钱箱是通过显示屏或打印机打开,即初始钱箱就直接初始显示屏 PosBox(1,RadioGroup1.ItemIndex+1,RadioGroup3.ItemIndex+1,2400); end; procedure TSetForm.OpenButtonClick(Sender: TObject); begin { ResultI:=CheckSelect('O'); Label4.Caption :=IntToStr(ResultI); If ResultI =1 Then Label3.Caption :='打开成功!' Else Label3.Caption :='打开失败!';} PosBox(2,RadioGroup1.ItemIndex+1,RadioGroup3.ItemIndex+1,2400); {Led8 2400} end; procedure TSetForm.StateButtonClick(Sender: TObject); begin ResultI:=CheckSelect('C'); Label4.Caption :=IntToStr(ResultI); If ResultI =1 Then Label3.Caption :='关' Else Begin If ResultI =0 Then Label3.Caption :='开' Else Label3.Caption :='失败!'; End; end; ////PAGECONTROL2 procedure TSetForm.FormCreate(Sender: TObject); Var ReadIni:TIniFile; SavePath:String; Pdstr: string; begin SavePath :=ExtractFilePath(Application.ExeName); ReadIni :=TIniFile.Create(SavePath +'SetPos.Ini'); RadioGroup1.ItemIndex:= ReadIni.ReadInteger('钱箱设置','钱箱控制',0); // RadioGroup2.ItemIndex:= ReadIni.ReadInteger('钱箱设置','主板类型',0); RadioGroup3.ItemIndex:= ReadIni.ReadInteger('钱箱设置','打印机端口',0); CobType.ItemIndex:= ReadIni.ReadInteger('打印机设置','打印机型号',0); CobPort.ItemIndex:= ReadIni.ReadInteger('打印机设置','打印机端口',0); CobColor.ItemIndex:= ReadIni.ReadInteger('打印机设置','打印颜色',0); CobCut.ItemIndex:= ReadIni.ReadInteger('打印机设置','切纸方式',0); Combobox1.ItemIndex:= ReadIni.ReadInteger('显示屏设置','显示端口',0); Combobox2.ItemIndex:= ReadIni.ReadInteger('显示屏设置','显示类型',0); ReadIni.Free; {初始化显示屏} com_rest; if Com_init(1,2400) then begin Pdstr :=chr(27)+chr(64); com_send(pchar(pdstr),length(pdstr)); end; PageControl1.ActivePageIndex := 0; end; //打印机类型 procedure TSetForm.CobTypeChange(Sender: TObject); begin PrnType :=CobType.ItemIndex +1; MicroFeed.Enabled:=true; Cut.Enabled:=false; CobCut.enabled:=false; CobCut.text:='部分切纸'; CobColor.enabled:=false; case PrnType of 1: ; //HK110D 2: //HKP600T begin MicroFeed.enabled:=false; Cut.Enabled:=true; end; 3: //ADP300 begin Cut.Enabled:=true; CobCut.enabled:=true; CobColor.enabled:=true; end; 4: ; //HK588TP 5: //TM300K begin Cut.Enabled:=true; CobCut.enabled:=true; CobColor.enabled:=true; end; 6,7: //TM210D CobColor.enabled:=true; end; end; //打印机端口 procedure TSetForm.CobPortChange(Sender: TObject); begin if CobPort.ItemIndex=-1 then PrnPort :=1 else Begin if (CobPort.itemindex>=0) and (CobPort.itemindex<=1) then PrnPort :=CobPort.itemindex+1 //LPT1,LPT2 else PrnPort :=CobPort.itemindex-1; //COM1-4 End; end; //初始化 procedure TSetForm.INIClick(Sender: TObject); begin case PrnType of 1: HK110D_Init(PrnPort); 2: HKP600T_Init(PrnPort); 3: ADP300_Init(PrnPort); 4: HK588TP_Init(PrnPort); 5: TM300K_Init(PrnPort); 6: TM210D_Init(PrnPort); 7: TM210P_Init(PrnPort); end; end; //进纸 procedure TSetForm.InPaperClick(Sender: TObject); var iLines:integer; begin iLines:=strtoint(EdPage.text); { case PrnType of 1: HK110D_FeedLines(PrnPort,iLines); 2: HKP600T_FeedLines(PrnPort,iLines); 3: ADP300_FeedLines(PrnPort,iLines); 4: HK588TP_FeedLines(PrnPort,iLines); 5: TM300K_FeedLines(PrnPort,iLines); 6: TM210D_FeedLines(PrnPort,iLines); 7: TM210P_FeedLines(PrnPort,iLines); end;} PosPrint(1,iLines,' '); end; //微进纸 procedure TSetForm.MicroFeedClick(Sender: TObject); var iLines:integer; begin iLines:=strtoint(EdPage.text); case PrnType of 1: HK110D_MicroFeed(PrnPort,iLines); //HKP600T不能微进纸 3: ADP300_MicroFeed(PrnPort,iLines); 4: HK588TP_MicroFeed(PrnPort,iLines); 5: TM300K_MicroFeed(PrnPort,iLines); 6: TM210D_MicroFeed(PrnPort,iLines); 7: TM210P_MicroFeed(PrnPort,iLines); end; end; //打印 procedure TSetForm.PrintClick(Sender: TObject); var iColor,iLines:integer; begin iLines:=strtoint(EdPage.text); { if CobColor.ItemIndex=-1 then iColor:=1 else iColor:=CobColor.itemindex+1; case PrnType of 1: HK110D_PrnCnEn(PrnPort,RedText.Text); 2: HKP600T_PrnCnEn(PrnPort,RedText.Text); 3: ADP300_PrnCnEn(PrnPort,iColor,RedText.Text); 4: HK588TP_PrnCnEn(PrnPort,RedText.Text); 5: TM300K_PrnCnEn(PrnPort,iColor,RedText.Text); 6: TM210D_PrnCnEn(PrnPort,iColor,RedText.Text); 7: TM210P_PrnCnEn(PrnPort,iColor,RedText.Text); end;} PosPrint(2,iLines,RedText.Text); end; //切纸 procedure TSetForm.CutClick(Sender: TObject); var iCutMode:integer; //切纸方式 begin if CobCut.ItemIndex=-1 then iCutMode:=1 else iCutMode:=CobCut.ItemIndex+1; case PrnType of //HK110D无切纸刀 2: HKP600T_Cut(PrnPort); 3: ADP300_Cut(PrnPort,iCutMode); //HK588TP无切纸刀 5: TM300K_Cut(PrnPort,iCutMode); //TM210D/210P 无切纸刀 end; end; procedure TSetForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TSetForm.RadioGroup1Click(Sender: TObject); Var LB_Flg:Boolean; begin If RadioGroup1.ItemIndex =0 Then LB_Flg :=True Else LB_Flg :=False; // RadioGroup2.Enabled :=LB_Flg; // RadioGroup3.Enabled :=Not LB_Flg; end; procedure tSetform.Button1Click(Sender: TObject); Var Fvalue:Cardinal; Pdstr:String; begin { case ComboBox2.ItemIndex of 0: lc112_Init(ShowPort); //不需要 2: Cv20_Init(showport); End;} ShowPort :=ComboBox1.ItemIndex+1; If ComboBox2.ItemIndex =0 Then Fvalue :=2400 Else Fvalue :=9600; com_rest; If Com_init(ShowPort ,Fvalue) Then Begin Pdstr :=chr(27)+chr(64); com_send(pchar(pdstr),length(pdstr)); End Else MessageBox(Handle, PChar('初始化失败!'), PChar('系统提示'), MB_OK + MB_ICONINFORMATION); end; procedure tSetform.Button2Click(Sender: TObject); Var Pdstr:String; begin PDStr:= Chr(27)+Chr(115)+IntToStr(RadioGroup4.ItemIndex+1) ; com_send(Pchar(PDStr),Length(PDStr)); PDStr:=Chr(27)+Chr(81)+Chr(65)+Edit1.Text+Chr(13); if Not com_send(Pchar(PDStr),Length(PDStr)) then MessageBox(Handle, PChar('发送失败!'), PChar('系统提示'), MB_OK + MB_ICONINFORMATION); { case ComboBox2.ItemIndex of 0: lc112_DisplayStr(RadioGroup4.Items.Strings[RadioGroup4.itemindex]+':'+Edit1.text); 1: VC108_Trans(ShowPort,(RadioGroup4.ItemIndex+1),1,StrToFloat(Edit1.text)); 2: Cv20_DisplayStr(RadioGroup4.Items.Strings[RadioGroup4.itemindex]+':'+Edit1.text); End;} end; procedure tSetform.Button3Click(Sender: TObject); var pdstr:string; begin PDStr:= Chr(12); com_send(pchar(pdstr),length(pdstr)); { case ComboBox2.ItemIndex of 0: lc112_ClearScreen; 1: vc108_CLS(showport); 2: Cv20_ClearScreen; End;} end; procedure tSetform.EdPageKeyPress(Sender: TObject; var Key: Char); begin If Not (Key in ['0','1','2','3','4','5','6','7','8','9','.']) Then Key:=#0; end; procedure tSetform.Edit1KeyPress(Sender: TObject; var Key: Char); begin If Not (Key in ['0','1','2','3','4','5','6','7','8','9','.']) Then Key:=#0; end; procedure tSetform.Edit1Exit(Sender: TObject); begin If Trim(Edit1.Text)='' Then Edit1.Text :='0.00'; end; procedure tSetform.EdPageExit(Sender: TObject); begin If Trim(EdPage.Text)='' Then EdPage.Text :='1'; end; procedure tSetform.BitBtn1Click(Sender: TObject); Var SaveIni:TIniFile; SavePath:String; begin SavePath :=ExtractFilePath(Application.ExeName); SaveIni :=TIniFile.Create(SavePath +'SetPos.Ini'); SaveIni.WriteInteger('钱箱设置','钱箱控制',RadioGroup1.ItemIndex); // SaveIni.WriteInteger('钱箱设置','主板类型',RadioGroup2.ItemIndex); SaveIni.WriteInteger('钱箱设置','打印机端口',RadioGroup3.ItemIndex); SaveIni.WriteInteger('打印机设置','打印机型号',CobType.ItemIndex); SaveIni.WriteInteger('打印机设置','打印机端口',PrnPort); SaveIni.WriteInteger('打印机设置','打印颜色',CobColor.ItemIndex); SaveIni.WriteInteger('打印机设置','切纸方式',CobCut.ItemIndex); SaveIni.WriteInteger('显示屏设置','显示端口',ComboBox1.ItemIndex); SaveIni.WriteInteger('显示屏设置','显示类型',ComboBox2.ItemIndex); SaveIni.Free; PosSet.BoxControl:=RadioGroup1.ItemIndex+1; Posset.BoxPort:=RadioGroup3.ItemIndex+1; PosSet.PrintModel:=CobType.ItemIndex+1; PosSet.PrintPort:=CobPort.ItemIndex+1; PosSet.PrintColor:=CobColor.ItemIndex+1; PosSet.PrintCut:=CobColor.ItemIndex+1; PosSet.ScreenPort:=ComboBox1.ItemIndex+1; PosSet.Screentype:=ComboBox1.ItemIndex+1; end; procedure tSetform.RadioGroup4Click(Sender: TObject); Var pdstr:string; begin PDStr:= Chr(27)+Chr(115)+IntToStr(RadioGroup4.ItemIndex+1); com_send(Pchar(PDStr),Length(PDStr)); end; procedure tSetform.aaClick(Sender: TObject); var pdstr:string; F:TextFile ; begin PDStr:= Chr(27)+'p'+Chr(0)+Chr(60)+Chr(255); {//打印机开钱箱} AssignFile(F, 'LPT1'); Rewrite(F); closeFile(F); end; procedure tSetform.Button4Click(Sender: TObject); begin PosScreen(1,2400,0,0); end; procedure tSetform.Button5Click(Sender: TObject); begin PosScreen(1,2400,1,1); end; procedure tSetform.Button6Click(Sender: TObject); begin PosScreen(1,2400,2,2); end; procedure tSetform.Button7Click(Sender: TObject); begin PosScreen(1,2400,3,3); end; procedure tSetform.Button8Click(Sender: TObject); begin PosScreen(1,2400,4,4); end; end.
unit GLDRingParamsFrame; interface uses Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem, GLDRing, GLDNameAndColorFrame, GLDUpDown; type TGLDRingParamsFrame = class(TFrame) NameAndColor: TGLDNameAndColorFrame; GB_Params: TGroupBox; L_Radius1: TLabel; L_Radius2: TLabel; L_Segments: TLabel; L_Sides: TLabel; L_StartAngle: TLabel; L_SweepAngle: TLabel; E_Radius1: TEdit; E_Radius2: TEdit; E_Segments: TEdit; E_Sides: TEdit; E_StartAngle: TEdit; E_SweepAngle: TEdit; UD_Radius1: TGLDUpDown; UD_Radius2: TGLDUpDown; UD_Segments: TUpDown; UD_Sides: TUpDown; UD_StartAngle: TGLDUpDown; UD_SweepAngle: TGLDUpDown; procedure ParamsChangeUD(Sender: TObject); procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HaveRing: GLboolean; function GetParams: TGLDRingParams; procedure SetParams(const Name: string; const Color: TGLDColor3ub; const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); procedure SetParamsFrom(Ring: TGLDRing); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; procedure Register; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; constructor TGLDRingParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; destructor TGLDRingParamsFrame.Destroy; begin if Assigned(FDrawer) then if FDrawer.IOFrame = Self then FDrawer.IOFrame := nil; inherited Destroy; end; function TGLDRingParamsFrame.HaveRing: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedObject) and (FDrawer.EditedObject is TGLDRing) then Result := True; end; function TGLDRingParamsFrame.GetParams: TGLDRingParams; begin if HaveRing then with TGLDRing(FDrawer.EditedObject) do begin Result.Position := Position.Vector3f; Result.Rotation := Rotation.Params; end else begin Result.Position := GLD_VECTOR3F_ZERO; Result.Rotation := GLD_ROTATION3D_ZERO; end; Result.Color := NameAndColor.ColorParam; Result.InnerRadius := UD_Radius1.Position; Result.OuterRadius := UD_Radius2.Position; Result.Segments := UD_Segments.Position; Result.Sides := UD_Sides.Position; Result.StartAngle := UD_StartAngle.Position; Result.SweepAngle := UD_SweepAngle.Position; end; procedure TGLDRingParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub; const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); begin NameAndColor.NameParam := Name; NameAndColor.ColorParam := Color; UD_Radius1.Position := Radius1; UD_Radius2.Position := Radius2; UD_Segments.Position := Segments; UD_Sides.Position := Sides; UD_StartAngle.Position := StartAngle; UD_SweepAngle.Position := SweepAngle; end; procedure TGLDRingParamsFrame.SetParamsFrom(Ring: TGLDRing); begin if not Assigned(Ring) then Exit; with Ring do SetParams(Name, Color.Color3ub, InnerRadius, OuterRadius, Segments, Sides, StartAngle, SweepAngle); end; procedure TGLDRingParamsFrame.ApplyParams; begin if HaveRing then TGLDRing(FDrawer.EditedObject).Params := GetParams; end; procedure TGLDRingParamsFrame.ParamsChangeUD(Sender: TObject); begin if HaveRing then with TGLDRing(FDrawer.EditedObject) do if Sender = UD_Radius1 then InnerRadius := UD_Radius1.Position else if Sender = UD_Radius2 then OuterRadius := UD_Radius2.Position else if Sender = UD_StartAngle then StartAngle := UD_StartAngle.Position else if Sender = UD_SweepAngle then SweepAngle := UD_SweepAngle.Position; end; procedure TGLDRingParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); begin if HaveRing then with TGLDRing(FDrawer.EditedObject) do if Sender = UD_Segments then Segments := UD_Segments.Position else if Sender = UD_Sides then Sides := UD_Sides.Position; end; procedure TGLDRingParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDRingParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDRingParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; NameAndColor.Drawer := FDrawer; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDRingParamsFrame]); end; end.
{--------------------------------------------------------} { { Simulador de mouse e teclado { { Versăo 2 - năo usa biblioteca externa { { Autor: José Antonio Borges { { Em 11/05/2008 { {--------------------------------------------------------} unit dvmacro; interface uses windows, messages, sysUtils; procedure SendKeyDown(VKey: Byte; NumTimes: Word; GenUpMsg :Boolean); procedure SendKeyUp(VKey: Byte); procedure SendKey(MKey: Word; NumTimes: Word; GenUpMsg: Boolean); procedure keyboardClick (letra: char); procedure keyboardChar (letra: char; delay: integer); procedure keyboardAlt (letra: char; delay: integer); procedure keyboardString (s: string; delay: integer); procedure keyboardVirtKey (key: byte; comControl, comShift, comAlt: boolean; delay: integer); procedure mouseMove (x, y: integer); procedure mouseClick (x, y: integer); procedure mouseRightClick (x, y: integer); procedure mouseDoubleClick (x, y: integer); procedure mouseBeginDrag (x, y: integer); procedure mouseContinueDrag (x, y: integer); procedure mouseEndDrag (x, y: integer); procedure mouseShiftClick (x, y: integer); procedure mouseControlClick (x, y: integer); implementation const ExtendedVKeys : set of byte = [VK_Up, VK_Down, VK_Left, VK_Right, VK_Home, VK_End, VK_Prior, {PgUp} VK_Next, {PgDn} VK_Insert, VK_Delete]; const VKKEYSCANSHIFTON = $01; VKKEYSCANCTRLON = $02; VKKEYSCANALTON = $04; {--------------- simulaçăo de teclado ----------------} function BitSet (BitTable, BitMask: Byte): Boolean; begin Result := ByteBool(BitTable and BitMask); end; procedure SetBit (var BitTable: Byte; BitMask: Byte); begin BitTable := BitTable or Bitmask; end; procedure KeyboardEvent (VKey, ScanCode: Byte; Flags: Longint); var KeyboardMsg : TMsg; begin keybd_event(VKey, ScanCode, Flags,0); While (PeekMessage(KeyboardMsg,0,WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) do begin TranslateMessage(KeyboardMsg); DispatchMessage(KeyboardMsg); end; end; procedure SendKeyDown(VKey: Byte; NumTimes: Word; GenUpMsg :Boolean); var Cnt : Word; ScanCode : Byte; NumState : Boolean; KeyBoardState : TKeyboardState; begin If (VKey=VK_NUMLOCK) then begin NumState:=ByteBool(GetKeyState(VK_NUMLOCK) and 1); GetKeyBoardState(KeyBoardState); If NumState then KeyBoardState[VK_NUMLOCK]:=(KeyBoardState[VK_NUMLOCK] and not 1) else KeyBoardState[VK_NUMLOCK]:=(KeyBoardState[VK_NUMLOCK] or 1); SetKeyBoardState(KeyBoardState); exit; end; ScanCode:=Lo(MapVirtualKey(VKey,0)); For Cnt:=1 to NumTimes do If (VKey in ExtendedVKeys)then begin KeyboardEvent(VKey, ScanCode, KEYEVENTF_EXTENDEDKEY); If (GenUpMsg) then KeyboardEvent(VKey, ScanCode, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP) end else begin KeyboardEvent(VKey, ScanCode, 0); If (GenUpMsg) then KeyboardEvent(VKey, ScanCode, KEYEVENTF_KEYUP); end; end; procedure SendKeyUp(VKey: Byte); var ScanCode : Byte; begin ScanCode:=Lo(MapVirtualKey(VKey,0)); If (VKey in ExtendedVKeys)then KeyboardEvent(VKey, ScanCode, KEYEVENTF_EXTENDEDKEY and KEYEVENTF_KEYUP) else KeyboardEvent(VKey, ScanCode, KEYEVENTF_KEYUP); end; Procedure SendKey(MKey: Word; NumTimes: Word; GenUpMsg: Boolean); begin If (BitSet(Hi(MKey),VKKEYSCANSHIFTON)) then SendKeyDown(VK_SHIFT,1,False); If (BitSet(Hi(MKey),VKKEYSCANCTRLON)) then SendKeyDown(VK_CONTROL,1,False); If (BitSet(Hi(MKey),VKKEYSCANALTON)) then SendKeyDown(VK_MENU,1,False); SendKeyDown(Lo(MKey), NumTimes, GenUpMsg); If (BitSet(Hi(MKey),VKKEYSCANSHIFTON)) then SendKeyUp(VK_SHIFT); If (BitSet(Hi(MKey),VKKEYSCANCTRLON)) then SendKeyUp(VK_CONTROL); If (BitSet(Hi(MKey),VKKEYSCANALTON)) then SendKeyUp(VK_MENU); end; procedure keyboardClick (letra: char); begin if ord (letra) in [32..127] then begin SendKeyDown(vkKeyScan (letra), 1, false); sleep (1); SendKeyUp(vkKeyScan (letra)); sleep (1); end else keyboardChar (letra, 1); end; procedure keyboardChar (letra: char; delay: integer); const tabAcentos: string = '_€__‚_ƒ_„_…_†_‡_ˆ_‰_Š_‹_Œ__Ž_' + '__‘_’_“_”_•_–_—_˜_™_š_›_œ__ž_Ÿ' + '_ _Ą_ą_Ł_€_„_Š_§_š_©_Ș_«_Ź_­_ź_Ż' + '_°_±_Č_ł_Ž_”_¶_·_ž_č_ș_»_Œ_œ_Ÿ_ż' + '`AŽA^A~AšA_Ć_Æ_Ç`EŽE^EšE`IŽI^IšI' + '_Đ~N`OŽO^O~OšO_Ś_Ű`UŽU^UšUŽY_Ț_ß' + '`aŽa^a~aša_ć_æ_ç`eŽe^eše`iŽi^iši' + '_đ~n`oŽo^o~ošo_ś_ű`uŽu^ušuŽy_țšy'; var l1, l2: char; k, p: integer; begin if ord (letra) in [32..127] then SendKey(vkKeyScan (letra), 1, true) else if ord (letra) < 32 then keyboardVirtKey (ord(letra) + $40, true, false, false, delay) else begin p := (ord(letra) - 128) * 2 + 1; l1 := tabAcentos [p]; l2 := tabAcentos [p+1]; if l1 <> '_' then SendKey(vkKeyScan (l1), 1, true); k := vkKeyScan (l2); if k >= 0 then SendKey(vkKeyScan (l2), 1, true) else SendKey(vkKeyScan (' '), 1, true) end; if delay <> 0 then sleep (delay); end; procedure keyboardAlt (letra: char; delay: integer); begin SendKey (word(vkKeyScan (letra)) or (VKKEYSCANALTON shl 8), 1, true); if delay <> 0 then sleep (delay); end; procedure keyboardString (s: string; delay: integer); var i: integer; begin for i := 1 to length (s) do keyboardChar (s[i], delay); end; procedure keyboardVirtKey (key: byte; comControl, comShift, comAlt: boolean; delay: integer); var k: word; begin k := key; if comControl then k := k or (VKKEYSCANCTRLON shl 8); if comShift then k := k or (VKKEYSCANSHIFTON shl 8); if comAlt then k := k or (VKKEYSCANALTON shl 8); SendKey (k, 1, true); if delay <> 0 then sleep (delay); end; {--------------- simulaçăo de mouse ----------------} procedure mouseMove (x, y: integer); begin SetCursorPos(x, y); end; procedure mouseClick (x, y: integer); begin SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; procedure mouseRightClick (x, y: integer); begin SetCursorPos(x, y); mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); end; procedure mouseDoubleClick (x, y: integer); begin SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); GetDoubleClickTime; mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; procedure mouseShiftClick (x, y: integer); begin SetCursorPos(x, y); SendKeyDown(VK_SHIFT, 1, false); sleep (20); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); SendKeyUp(VK_SHIFT); sleep (20); end; procedure mouseControlClick (x, y: integer); begin SetCursorPos(x, y); SendKeyDown(VK_CONTROL, 1, false); sleep (20); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); SendKeyUp(VK_CONTROL); sleep (20); end; procedure mouseBeginDrag (x, y: integer); begin SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); end; procedure mouseContinueDrag (x, y: integer); begin SetCursorPos(x, y); end; procedure mouseEndDrag (x, y: integer); begin SetCursorPos(x, y); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; end.
unit Reg; interface uses windows; type TFun=function(name:string):boolean; procedure AddValue(Root: HKEY; StrPath: pchar; StrValue: pchar; Strdata: pchar; DataType: integer); procedure AddValue2(Root: HKEY; StrPath: pchar; StrValue: pchar; Strdata: pchar); procedure DelValue(Root: HKEY; StrPath: pchar; StrValue: pchar); procedure DelSub(Root: HKEY; StrPath: pchar; StrSub: pchar); function ReadValue(Root: HKEY; StrPath: pchar; StrValue: pchar): string; function ReadValueBinary(Root: HKEY; StrPath: pchar; StrValue: pchar): string; function ValueExists(Root: HKEY; StrPath: pchar; StrValue: pchar): Boolean; function KeyExists(Root: HKEY; StrPath: pchar; StrSub: pchar): Boolean; function GetValueName(Root: HKEY; StrPath: pchar; var Str: string): integer; function GetKeyName(Root: HKEY; StrPath: pchar; var Str: string): integer; procedure GetKeyName2(Root: HKEY; StrPath: pchar; fun:TFun); implementation function CreateKey(Root: HKEY; StrPath: pchar): Hkey; var TempKey: HKey; Disposition: Integer; begin TempKey := 0; RegCreateKeyEx(Root, StrPath, 0, nil, 0, KEY_ALL_ACCESS, nil, TempKey, @Disposition); Result := TempKey; end; function OpenKey(Root: HKEY; StrPath: pchar): Hkey; var TempKey: Hkey; begin TempKey := 0; RegOpenKeyEx(Root, StrPath, 0, KEY_ALL_ACCESS, TempKey); Result := TempKey; end; procedure AddValue(Root: HKEY; StrPath: pchar; StrValue: pchar; Strdata: pchar; DataType: integer); var s: Hkey; begin s := CreateKey(Root, StrPath); RegSetValueEx(s, StrValue, 0, REG_SZ, Strdata, sizeof(Strdata)); RegCloseKey(s); end; function StrLen(const Str: PChar): Cardinal; assembler; asm MOV EDX,EDI MOV EDI,EAX MOV ECX,0FFFFFFFFH XOR AL,AL REPNE SCASB MOV EAX,0FFFFFFFEH SUB EAX,ECX MOV EDI,EDX end; procedure AddValue2(Root: HKEY; StrPath: pchar; StrValue: pchar; Strdata: pchar); var s: Hkey; begin s := CreateKey(Root, StrPath); RegSetValueEx(s, StrValue, 0, REG_SZ, Strdata, strlen(Strdata)); RegCloseKey(s); end; procedure DelValue(Root: HKEY; StrPath: pchar; StrValue: pchar); var s: Hkey; begin s := OpenKey(Root, StrPath); RegDeleteValue(s, StrValue); RegCloseKey(s); end; procedure DelSub(Root: HKEY; StrPath: pchar; StrSub: pchar); var s: Hkey; begin s := OpenKey(Root, StrPath); RegDeleteKey(s, StrSub); RegCloseKey(s); end; function ReadValue(Root: HKEY; StrPath: pchar; StrValue: pchar): string; var s: Hkey; ValueType: DWORD; MyData: array[0..255] of char; dLength: DWORD; begin ValueType := REG_SZ; s := OpenKey(Root, StrPath); dLength := SizeOf(MyData); if RegQueryValueEx(s, StrValue, nil, @ValueType, @MyData[0], @dLength) = 0 then begin Result := MyData; RegCloseKey(s); end else begin Result := ''; RegCloseKey(s); end; end; function ReadValueBinary(Root: HKEY; StrPath: pchar; StrValue: pchar): string; const size=255; var s: Hkey; ValueType: DWORD; dLength: DWORD; begin ValueType := REG_BINARY; s := OpenKey(Root, StrPath); Setlength(Result,size); dLength := size; if RegQueryValueEx(s, StrValue, nil, @ValueType, @result[1], @dLength) = 0 then begin Setlength(result,dLength); RegCloseKey(s); end else begin Result := ''; RegCloseKey(s); end; end; function ValueExists(Root: HKEY; StrPath: pchar; StrValue: pchar): Boolean; var s: Hkey; ValueType: DWORD; begin ValueType := REG_SZ; s := OpenKey(Root, StrPath); Result := RegQueryValueEx(s, StrValue, nil, @ValueType, nil, nil) = 0; RegCloseKey(s); end; function KeyExists(Root: HKEY; StrPath: pchar; StrSub: pchar): Boolean; var s: Hkey; Str: string; begin if StrPath <> nil then Str := Strpath + '\' + StrSub else Str := StrSub; s := OpenKey(Root, pchar(Str)); Result := s <> 0; if s <> 0 then RegCloseKey(s); end; function GetValueName(Root: HKEY; StrPath: pchar; var Str: string): integer; var s: Hkey; Count: integer; ValueName: array[0..100] of char; BufSize, dType, dLength: DWORD; IData: array[0..255] of char; begin str:=''; Count := 0; BufSize := 100; dLength := 254; s := OpenKey(Root, StrPath); if s <> 0 then begin while RegEnumValue(s, Count, @ValueName[0], BufSize, nil, @dType, @iData, @dLength) = 0 do begin BufSize := 100; dLength := 254; Str := Str + ValueName + ','; Count := Count + 1; end; RegCloseKey(s); end; if copy(Str, 1, 1) = ',' then delete(Str, 1, 1); if copy(Str, Length(str), 1) = ',' then delete(Str, Length(str), 1); Result := Count; end; function GetKeyName(Root: HKEY; StrPath: pchar; var Str: string): integer; const size=255; var s: Hkey; Count: integer; BufSize: DWORD; ValueName: array[0..size-1] of char; begin str:=''; Count := 0; BufSize := size; s := OpenKey(Root, StrPath); if s <> 0 then begin while RegEnumKeyEx(s, Count, @ValueName[0], BufSize, nil, nil, nil, nil) = 0 do begin BufSize := size; Str := Str + ValueName + ','; Count := Count + 1; end; RegCloseKey(s); end; if copy(Str, Length(str), 1) = ',' then delete(Str, Length(str), 1); Result := Count; end; procedure GetKeyName2(Root: HKEY; StrPath: pchar; fun:TFun); const size=255; var s: Hkey; Count: integer; BufSize: DWORD; ValueName: array[0..size-1] of char; begin Count := 0; BufSize := size; s := OpenKey(Root, StrPath); if s <> 0 then begin while RegEnumKeyEx(s, Count, @ValueName[0], BufSize, nil, nil, nil, nil) = 0 do begin BufSize := size; if @fun<>nil then if not fun(ValueName) then break; Count := Count + 1; end; RegCloseKey(s); end; end; end.
unit fPlotColors; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.UITypes, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, OpenGLTokens, uGlobal, fFunctions, fDerivativeOptions; type TPlotColorsForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; UpperRed: TTrackBar; UpperGreen: TTrackBar; UpperBlue: TTrackBar; UpperAlpha: TTrackBar; GroupBox2: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; LowerRed: TTrackBar; LowerGreen: TTrackBar; LowerBlue: TTrackBar; LowerAlpha: TTrackBar; UpperLowerLock: TCheckBox; EditBlend: TEdit; Label9: TLabel; Label10: TLabel; EditMove: TEdit; ApplyBtn: TBitBtn; BitBtn1: TBitBtn; procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure UpperRedChange(Sender: TObject); procedure UpperGreenChange(Sender: TObject); procedure UpperBlueChange(Sender: TObject); procedure UpperAlphaChange(Sender: TObject); procedure LowerRedChange(Sender: TObject); procedure LowerGreenChange(Sender: TObject); procedure LowerBlueChange(Sender: TObject); procedure LowerAlphaChange(Sender: TObject); procedure ApplyBtnClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UpperLowerLockClick(Sender: TObject); procedure EditBlendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditBlendKeyPress(Sender: TObject; var Key: Char); procedure EditBlendKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditMoveKeyPress(Sender: TObject; var Key: Char); procedure EditMoveKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public procedure ShowPlotColorData; end; var PlotColorsForm: TPlotColorsForm; //======================================================================= implementation //======================================================================= uses fMain; {$R *.dfm} procedure TPlotColorsForm.ApplyBtnClick(Sender: TObject); begin with FunctionsForm.CheckListBox do TPlotDataObject(Items.Objects[ItemIndex]).Data := PlotData; ViewForm.UpdatePlot; ApplyBtn.Visible := False; Altered := True; end; procedure TPlotColorsForm.BitBtn1Click(Sender: TObject); begin Close; end; procedure TPlotColorsForm.EditBlendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) or (Key = VK_BACK) then ApplyBtn.Visible := True; end; procedure TPlotColorsForm.EditBlendKeyPress(Sender: TObject; var Key: Char); begin if CharInSet(Key, PosFloat) then ApplyBtn.Visible := True else Key := #0; end; procedure TPlotColorsForm.EditBlendKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var x: TGLFloat; begin try x := StrToFloat(EditBlend.Text); except x := 1.0; end; PlotData.ColorBlend := x; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.EditMoveKeyPress(Sender: TObject; var Key: Char); begin if CharInSet(Key, AnyFloat) then ApplyBtn.Visible := True else Key := #0; end; procedure TPlotColorsForm.EditMoveKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var x: TGLFloat; begin try x := StrToFloat(EditMove.Text); except x := 0.0; end; PlotData.ColorMove := x; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ApplyBtn.Visible then begin case MessageDlg('The current graph''s color data has been altered.'+ #13#10'Do you wish to save the alterations ?', mtConfirmation, [mbYes, mbNo, mbCancel], 0) of mrYes: ApplyBtnClick(Sender); mrCancel: begin CanClose := False; Exit; end; end; end; end; procedure TPlotColorsForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TPlotColorsForm.FormShow(Sender: TObject); begin UpperLowerLock.Checked := False; ShowPlotColorData; ApplyBtn.Visible := False; end; procedure TPlotColorsForm.UpperRedChange(Sender: TObject); begin PlotData.UpperColor.X := UpperRed.Position/225; if UpperLowerLock.Checked then LowerRed.Position := UpperRed.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.UpperGreenChange(Sender: TObject); begin PlotData.UpperColor.Y := UpperGreen.Position/225; if UpperLowerLock.Checked then LowerGreen.Position := UpperGreen.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.UpperLowerLockClick(Sender: TObject); begin if UpperLowerLock.Checked then begin LowerRed.Position := UpperRed.Position; LowerGreen.Position := UpperGreen.Position; LowerBlue.Position := UpperBlue.Position; LowerAlpha.Position := UpperAlpha.Position; end; end; procedure TPlotColorsForm.UpperBlueChange(Sender: TObject); begin PlotData.UpperColor.Z := UpperBlue.Position/225; if UpperLowerLock.Checked then LowerBlue.Position := UpperBlue.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.UpperAlphaChange(Sender: TObject); begin PlotData.UpperColor.W := UpperAlpha.Position/1000; if UpperLowerLock.Checked then LowerAlpha.Position := UpperAlpha.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.LowerRedChange(Sender: TObject); begin PlotData.LowerColor.X := LowerRed.Position/225; if UpperLowerLock.Checked then UpperRed.Position := LowerRed.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.LowerGreenChange(Sender: TObject); begin PlotData.LowerColor.Y := LowerGreen.Position/225; if UpperLowerLock.Checked then UpperGreen.Position := LowerGreen.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.LowerBlueChange(Sender: TObject); begin PlotData.LowerColor.Z := LowerBlue.Position/225; if UpperLowerLock.Checked then UpperBlue.Position := LowerBlue.Position; ApplyBtn.Visible := True; end; procedure TPlotColorsForm.LowerAlphaChange(Sender: TObject); begin PlotData.LowerColor.W := LowerAlpha.Position/1000; if UpperLowerLock.Checked then UpperAlpha.Position := LowerAlpha.Position; ApplyBtn.Visible := True; end; { Public declarations } procedure TPlotColorsForm.ShowPlotColorData; begin UpperRed.Position := round(PlotData.UpperColor.X*255); UpperGreen.Position := round(PlotData.UpperColor.Y*255); UpperBlue.Position := round(PlotData.UpperColor.Z*255); UpperAlpha.Position := round(PlotData.UpperColor.W*1000); LowerRed.Position := round(PlotData.LowerColor.X*255); LowerGreen.Position := round(PlotData.LowerColor.Y*255); LowerBlue.Position := round(PlotData.LowerColor.Z*255); LowerAlpha.Position := round(PlotData.LowerColor.W*1000); EditBlend.Text := FloatToStrF(PlotData.ColorBlend, ffGeneral, 7, 4); EditMove.Text := FloatToStrF(Plotdata.ColorMove, ffGeneral, 7, 4); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: ARBProgram<p> Some useful methods for setting up ARB vertex and fragment programs.<p> <b>History : </b><font size=-1><ul> <li>31/03/07 - DaStr - Added $I GLScene.inc <li>11/10/04 - SG - Creation </ul></font> } unit ARBProgram; interface {$I GLScene.inc} uses SysUtils, OpenGL1x, OpenGLTokens; procedure LoadARBProgram(target : GLenum; programText : String; var handle : cardinal); implementation procedure LoadARBProgram(target : GLenum; programText : String; var handle : cardinal); var errPos : Integer; errString : String; begin if (target = GL_VERTEX_PROGRAM_ARB) and not GL_ARB_vertex_program then raise Exception.Create('GL_ARB_vertex_program required!'); if (target = GL_FRAGMENT_PROGRAM_ARB) and not GL_ARB_fragment_program then raise Exception.Create('GL_ARB_fragment_program required!'); glGenProgramsARB(1, @handle); glBindProgramARB(target, handle); glProgramStringARB(target, GL_PROGRAM_FORMAT_ASCII_ARB, Length(programText), PGLChar(TGLString(programText))); glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, @errPos); if errPos>-1 then begin errString:=String(glGetString(GL_PROGRAM_ERROR_STRING_ARB)); raise Exception.CreateFmt('ARB Program Error - [Handle: %d][Pos: %d][Error %s]', [handle, errPos, errString]); end; CheckOpenGLError; end; end.
unit Demo.Trendlines.Exponential; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_Trendlines_Exponential = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_Trendlines_Exponential.GenerateChart; var Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_SCATTER_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Generation'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Descendants') ]); Chart.Data.AddRow([0, 1]); Chart.Data.AddRow([1, 33]); Chart.Data.AddRow([2, 269]); Chart.Data.AddRow([3, 2013]); // Options Chart.Options.Title('Descendants by Generation'); Chart.Options.HAxis('title', 'Generation'); Chart.Options.HAxis('minValue', 0); Chart.Options.HAxis('maxValue', 3); Chart.Options.VAxis('title', 'Descendants'); Chart.Options.VAxis('minValue', 3); Chart.Options.VAxis('maxValue', 2100); Chart.Options.TrendLines(['0: {type: ''exponential'', visibleInLegend: true, color: ''green''}']); // Draw a trendline for data series 0. // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="chart_div" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('chart_div', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_Trendlines_Exponential); end.
unit AArray; interface uses Windows, Classes, Variants, DB, Forms; const AARRAY_NULL_STRING = 'null'; type TAArray = class; TAArray = class private fValue : Variant; fObject : TObject; fNames : array of Variant; fArrays : array of TAArray; function GetValue(Index : Variant) : TAArray; function GetCount: Integer; function GetAsString: string; procedure SetAsString(const Value: string); function GetAsInt64: Int64; function GetASInteger: Integer; procedure SetAsInt64(const Value: Int64); procedure SetAsInteger(const Value: Integer); function GetName(Index: Integer): Variant; procedure ExportArray(sl : TStringList; aName : Variant; a : TAArray; iter : Integer; const space_count : Integer = 4); function ExportArray2(sl : TStringList; const aName : Variant; const a : TAArray; s : string) : string; function ObjectAsString : string; function GetAsCurrency: Currency; procedure SetAsCurrency(const Value: Currency); public constructor Create; destructor Destroy; override; procedure SaveToFile(const FileName : string; const space_count : Integer = 4); procedure SaveToFile2(const FileName : string); procedure LoadFromFile(const FileName, Section : string); procedure View(Owner : TForm); procedure CopyTo(var a : TAArray); property Values[Index : Variant] : TAArray read GetValue; default; property AsVariant : Variant read fValue write fValue; property AsString : string read GetAsString write SetAsString; property AsInteger : Integer read GetASInteger write SetAsInteger; property AsInt64 : Int64 read GetAsInt64 write SetAsInt64; property AsCurrency : Currency read GetAsCurrency write SetAsCurrency; property AsObject : TObject read fObject write fObject; property Names[Index : Integer] : Variant read GetName; property Count : Integer read GetCount; end; procedure FillArrayFromDataSet(a : TAArray; ds : TDataSet); procedure ViewArray(Owner : TForm; a : TAArray); implementation uses SysUtils, frmArrayUnit, inifiles; procedure ViewArray(Owner : TForm; a : TAArray); var frm : TfrmArray; begin frm := TfrmArray.Create(Owner); frm.BuildTree(a); frm.ShowModal; frm.Free; end; procedure FillArrayFromDataSet(a : TAArray; ds : TDataSet); var i : Integer; begin if not ds.Active then Exit; for i := 0 to ds.FieldCount - 1 do begin a[ds.Fields[i].FullName].AsVariant := ds.FieldByName(ds.Fields[i].FullName).Value; end; end; { TAArray } procedure TAArray.CopyTo(var a: TAArray); var i : integer; begin for i := 0 to GetCount - 1 do begin a[fNames[i]].AsVariant := Values[fNames[i]].AsVariant; a[fNames[i]].AsObject := Values[fNames[i]].AsObject; end; end; constructor TAArray.Create; begin inherited; fValue := null; fObject := nil; end; destructor TAArray.Destroy; var i : Integer; begin for i := 0 to Count - 1 do begin fArrays[i].Destroy; fArrays[i] := nil; end; fArrays := nil; fNames := nil; inherited; end; procedure TAArray.ExportArray(sl: TStringList; aName : Variant; a: TAArray; iter: Integer; const space_count: Integer); var s : string; i : Integer; begin s := ''; for i := 0 to iter do s := s + ' '; s := s + VarToStr(aName); if VarType(a.AsVariant) = varString then s := s + ' = ''' + a.AsString + '''' else s := s + ' = ' + a.AsString; sl.Add(s); for i := 0 to a.Count - 1 do ExportArray(sl, a.Names[i], a[a.Names[i]], iter + space_count); end; function TAArray.ExportArray2(sl : TStringList; const aName: Variant; const a: TAArray; s: string) : string; var sName : string; sValue : string; i : integer; begin if VarIsNull(aName) then sName := 'null' else if VarType(aName) = varString then sName := '''' + aName + '''' else sName := aName; if VarType(a.AsVariant) = varString then sValue := '''' + a.AsVariant + '''' else sValue := a.AsString; Result := s + '[' + sName + ']'; if not VarIsNull(a.AsVariant) then sl.Add(Result + '.AsVariant := ' + sValue + ';') else begin if a.fObject <> nil then sl.Add(Result + ' := ' + a.ObjectAsString + ';'); end; for i := 0 to a.Count - 1 do begin ExportArray2(sl, a.fNames[i], a[a.fNames[i]], Result); end; end; function TAArray.GetAsCurrency: Currency; begin Result := fValue; end; function TAArray.GetAsInt64: Int64; begin if not VarIsNull(fValue) then Result := fValue else Result := -1; end; function TAArray.GetASInteger: Integer; begin if not VarIsNull(fValue) then Result := fValue else Result := -1; end; function TAArray.GetAsString: string; begin if VarIsNull(fValue) then begin if fObject = nil then Result := AARRAY_NULL_STRING else Result := ObjectAsString; end else Result := fValue; end; function TAArray.GetCount: Integer; begin Result := Length(fArrays); end; function TAArray.GetName(Index: Integer): Variant; begin Result := fNames[Index]; end; function TAArray.GetValue(Index: Variant): TAArray; var i : Integer; begin Result := nil; if fNames <> nil then begin for i := 0 to Length(fNames) - 1 do begin // check if string if VarIsStr(Index) then begin if VarIsStr(fNames[i]) then begin if AnsiUpperCase(VarToStr(Index)) = AnsiUpperCase(VarToStr(fNames[i])) then begin Result := fArrays[i]; break; end; end; end else//else check equal begin if VarType(Index) = VarType(fNames[i]) then begin if VarCompareValue(Index, fNames[i]) = vrEqual then begin Result := fArrays[i]; break; end; end; end; end; end; if Result = nil then begin SetLength(fArrays, Count + 1); SetLength(fNames, Count); fNames[Count - 1] := Index; fArrays[Count - 1] := TAArray.Create; Result := fArrays[Count - 1]; end; end; procedure TAArray.LoadFromFile(const FileName, Section: string); var f : TMemIniFile; s : TStringList; i : integer; begin f := TMemIniFile.Create(FileName); s := TStringList.Create; f.ReadSection(Section, s); for i := 0 to s.Count - 1 do Values[s.Strings[i]].AsString := f.ReadString(Section, s.Strings[i], ''); s.Free; f.Free; end; function TAArray.ObjectAsString: string; begin if fObject = nil then Result := AARRAY_NULL_STRING else Result := fObject.ClassType.ClassName + '($' + IntToHex(Integer(Addr(fObject)), 2) + ')' end; procedure TAArray.SaveToFile(const FileName: string; const space_count: Integer); var sl : TStringList; i : Integer; ch : Char; begin ch := DecimalSeparator; DecimalSeparator := '.'; sl := TStringList.Create; for i := 0 to Count - 1 do ExportArray(sl, Names[i], fArrays[i], 0, space_count); sl.SaveToFile(FileName); sl.Free; DecimalSeparator := ch; end; procedure TAArray.SaveToFile2(const FileName: string); var sl : TStringList; s : string; i : Integer; ch : char; begin ch := DecimalSeparator; DecimalSeparator := '.'; sl := TStringList.Create; for i := 0 to Count - 1 do begin s := ''; ExportArray2(sl, fNames[i], fArrays[i], s); end; sl.SaveToFile(FileName); sl.Free; DecimalSeparator := ch; end; procedure TAArray.SetAsCurrency(const Value: Currency); begin fValue := Value; end; procedure TAArray.SetAsInt64(const Value: Int64); begin fValue := Value; end; procedure TAArray.SetAsInteger(const Value: Integer); begin fValue := Value; end; procedure TAArray.SetAsString(const Value: string); begin fValue := Value; end; procedure TAArray.View(Owner: TForm); begin ViewArray(Owner, Self); end; end.
unit OpenSSL.CoreTests; interface uses TestFramework, System.SysUtils, System.Classes, OpenSSL.Api_11, OpenSSL.Core; type TSSLCoreTest = class(TTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure TestBase64Encode; procedure TestBytesToHex; end; implementation { TSSLCoreTest } procedure TSSLCoreTest.SetUp; begin inherited; end; procedure TSSLCoreTest.TearDown; begin inherited; end; procedure TSSLCoreTest.TestBase64Encode; var S, T, U: TBytes; begin S := TEncoding.Default.GetBytes('0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'); T := Base64Encode(S); U := Base64Decode(T); CheckEquals(Length(S), Length(U)); CheckEqualsMem(Pointer(S), Pointer(U), Length(S)); S := TEncoding.Default.GetBytes('1234'); T := Base64Encode(S); CheckEquals(TEncoding.Default.GetString(T), 'MTIzNA=='); U := Base64Decode(T); CheckEquals(Length(S), Length(U)); CheckEqualsMem(Pointer(S), Pointer(U), Length(S)); S := TEncoding.Default.GetBytes('123456789'); T := Base64Encode(S); CheckEquals(TEncoding.Default.GetString(T), 'MTIzNDU2Nzg5'); U := Base64Decode(T); CheckEquals(Length(S), Length(U)); CheckEqualsMem(Pointer(S), Pointer(U), Length(S)); S := TEncoding.UTF8.GetBytes('中文测试'); T := Base64Encode(S); CheckEquals(TEncoding.Default.GetString(T), '5Lit5paH5rWL6K+V'); U := Base64Decode(T); CheckEquals(Length(S), Length(U)); CheckEqualsMem(Pointer(S), Pointer(U), Length(S)); S := TEncoding.ANSI.GetBytes('测试中文测试:测试'); T := Base64Encode(S); CheckEquals(TEncoding.Default.GetString(T), 'suLK1NbQzsSy4srUOrLiytQ='); U := Base64Decode(T); CheckEquals(Length(S), Length(U)); CheckEqualsMem(Pointer(S), Pointer(U), Length(S)); end; procedure TSSLCoreTest.TestBytesToHex; var B, C: TBytes; S, T: string; begin S := '1234567890'; B := TEncoding.ANSI.GetBytes(S); T := BytesToHex(B); CheckEquals('31323334353637383930', T); C := HexToBytes(T); CheckEquals(Length(B), Length(C)); CheckEqualsMem(Pointer(B), Pointer(C), Length(B)); S := '测试中文测试:测试'; B := TEncoding.ANSI.GetBytes(S); T := BytesToHex(B, False); CheckEquals('B2E2CAD4D6D0CEC4B2E2CAD43AB2E2CAD4', T); C := HexToBytes(T); CheckEquals(Length(B), Length(C)); CheckEqualsMem(Pointer(B), Pointer(C), Length(B)); end; initialization // Register any test cases with the test runner RegisterTest(TSSLCoreTest.Suite); end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Toon shader : Toon shading also called Cell Shading At this time only one light source is supported } unit VXS.GLSLToonShader; interface //{$I VXScene.inc} uses System.Classes, //VXScene VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x, VXS.Context, VXS.RenderContextInfo, VXS.VectorGeometry, VXS.Coordinates, VXS.TextureFormat, VXS.Color, VXS.Texture, VXS.Material, GLSL.Shader, VXS.CustomShader; //TVXCustomGLSLToonShader // { Custom class for GLSLToonShader. } type TVXCustomGLSLToonShader = class(TVXCustomGLSLShader) private FHighlightColor : TVXColor; FMidColor : TVXColor; FLightenShadowColor : TVXColor; FDarkenShadowColor : TVXColor; FOutlineColor : TVXColor; FHighlightSize : Single; FMidSize : Single; FShadowSize : Single; FOutlineWidth : Single; procedure SetHighLightColor(AValue: TVXColor); procedure SetMidColor(AValue: TVXColor); procedure SetLightenShadowColor(AValue: TVXColor); procedure SetDarkenShadowColor(AValue: TVXColor); procedure SetOutlineColor(AValue: TVXColor); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property HighlightColor : TVXColor read FHighlightColor Write setHighlightColor; property MidColor : TVXColor read FMidColor Write setMidColor; property LightenShadowColor : TVXColor Read FLightenShadowColor Write setLightenShadowColor; property DarkenShadowrColor : TVXColor Read FDarkenShadowColor Write setDarkenShadowColor; property OutlinetColor : TVXColor Read FOutlineColor Write setOutlineColor; property HighlightSize : Single read FHighlightSize write FHighlightSize; property MidSize : Single read FMidSize write FMidSize; property ShadowSize : Single read FShadowSize write FShadowSize; property OutlineWidth : Single read FOutlineWidth write FOutlineWidth; end; type TVXSLToonShader = class(TVXCustomGLSLToonShader) published property HighlightColor; property MidColor; property LightenShadowColor; property DarkenShadowrColor; property OutlinetColor; property HighlightSize; property MidSize; property ShadowSize; property OutlineWidth; end; implementation { TVXCustomGLSLToonShader } constructor TVXCustomGLSLToonShader.Create(AOwner: TComponent); begin inherited; with VertexProgram.Code do begin Clear; Add('varying vec3 vNormal; '); Add('varying vec3 LightVec; '); Add('varying vec3 ViewVec; '); Add(' '); Add('void main() '); Add('{ '); Add(' vec4 lightPos = gl_LightSource[0].position;'); Add(' vec4 vert = gl_ModelViewMatrix * gl_Vertex; '); Add(' vec3 normal = gl_NormalMatrix * gl_Normal; '); Add(' vNormal = normalize(normal); '); Add(' LightVec = vec3(lightPos - vert); '); Add(' ViewVec = -vec3(vert); '); //Add(' gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; '); Add(' gl_Position = ftransform(); '); Add('} '); end; with FragmentProgram.Code do begin Clear; Add('uniform vec4 HighlightColor; '); Add('uniform vec4 MidColor; '); Add('uniform vec4 LightenShadowColor; '); Add('uniform vec4 DarkenShadowColor; '); Add('uniform vec4 OutlineColor; '); Add('uniform float HighlightSize; '); // 0.95 Add('uniform float MidSize; '); // 0.5 Add('uniform float ShadowSize; '); // 0.25 Add('uniform float OutlineWidth; '); Add('varying vec3 vNormal; '); Add('varying vec3 LightVec; '); Add('varying vec3 ViewVec; '); Add('void main() '); Add('{ '); Add(' vec3 n = normalize(vNormal); '); Add(' vec3 l = normalize(LightVec); '); Add(' vec3 v = normalize(ViewVec); '); Add(' float lambert = dot(l,n); '); Add(' vec4 colour = MidColor; '); Add(' if (lambert>HighlightSize) colour = HighlightColor; '); Add(' else if (lambert>MidSize) colour = MidColor; '); Add(' else if (lambert>ShadowSize) colour = LightenShadowColor; '); Add(' else if (lambert<ShadowSize) colour = DarkenShadowColor; '); Add(' if (dot(n,v)<OutlineWidth) colour = OutlineColor; '); Add(' gl_FragColor = colour; '); Add('} '); end; // Initial stuff. FHighLightColor := TVXColor.Create(self); FHighLightColor.SetColor(0.9,0.9,0.9,1.0); FMidColor := TVXColor.Create(self); FMidColor.SetColor(0.75,0.75,0.75,1.0); FLightenShadowColor := TVXColor.Create(self); FLightenShadowColor.SetColor(0.5,0.5,0.5,1.0); FDarkenShadowColor := TVXColor.Create(self); FDarkenShadowColor.SetColor(0.3,0.3,0.3,1.0); FOutlineColor := TVXColor.Create(self); FOutlineColor.SetColor(0,0,0,1.0); FHighlightSize := 0.95; FMidSize := 0.50; FShadowSize := 0.25; FOutlineWidth := 0.25; end; destructor TVXCustomGLSLToonShader.Destroy; begin FHighLightColor.Free; FMidColor.Free; FLightenShadowColor.Free; FDarkenShadowColor.Free; FOutlineColor.Free; inherited; end; procedure TVXCustomGLSLToonShader.DoApply(var rci: TVXRenderContextInfo;Sender: TObject); begin GetGLSLProg.UseProgramObject; param['HighlightColor'].AsVector4f := FHighlightColor.Color; param['MidColor'].AsVector4f := FMidColor.Color; param['LightenShadowColor'].AsVector4f := FLightenShadowColor.Color; param['DarkenShadowColor'].AsVector4f := FDarkenShadowColor.Color; param['OutlineColor'].AsVector4f := FOutlineColor.Color; param['HighlightSize'].AsVector1f := FHighlightSize; param['MidSize'].AsVector1f := FMidSize; param['ShadowSize'].AsVector1f := FShadowSize; param['OutlineWidth'].AsVector1f := FOutlineWidth; end; function TVXCustomGLSLToonShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean; begin GetGLSLProg.EndUseProgramObject; Result := False; end; procedure TVXCustomGLSLToonShader.SetHighlightColor(AValue: TVXColor); begin FHighlightColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLToonShader.SetMidColor(AValue: TVXColor); begin FMidColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLToonShader.SetLightenShadowColor(AValue: TVXColor); begin FLightenShadowColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLToonShader.SetDarkenShadowColor(AValue: TVXColor); begin FDarkenShadowColor.DirectColor := AValue.Color; end; procedure TVXCustomGLSLToonShader.SetOutlineColor(AValue: TVXColor); begin FOutlineColor.DirectColor := AValue.Color; end; end.
unit Demo.Miscellaneous.Formatters; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_Miscellaneous_Formatters = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation uses System.SysUtils, System.DateUtils; procedure TDemo_Miscellaneous_Formatters.GenerateChart; function GetChartArrowFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Department'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Revenues Change') ]); Result.Data.AddRow; Result.Data.SetValue(0, 'Shoes'); Result.Data.SetValue(1, 12, '12.0%'); Result.Data.AddRow; Result.Data.SetValue(0, 'Sports'); Result.Data.SetValue(1, -7.3, '-7.3%'); Result.Data.AddRow; Result.Data.SetValue(0, 'Toys'); Result.Data.SetValue(1, 0, '0%'); Result.Data.AddRow; Result.Data.SetValue(0, 'Electronics'); Result.Data.SetValue(1, -2.1, '-2.1%'); Result.Data.AddRow; Result.Data.SetValue(0, 'Food'); Result.Data.SetValue(1, 22, '22.0%'); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(350); // Formatter Result.ScripCodeBeforeCallDraw := 'var formatter = new google.visualization.ArrowFormat();' + 'formatter.format(data, 1);' ; end; function GetChartBarFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Department'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Revenues') ]); Result.Data.AddRow; Result.Data.SetValue(0, 'Shoes'); Result.Data.SetValue(1, 10700); Result.Data.AddRow; Result.Data.SetValue(0, 'Sports'); Result.Data.SetValue(1, -15400); Result.Data.AddRow; Result.Data.SetValue(0, 'Toys'); Result.Data.SetValue(1, 12500); Result.Data.AddRow; Result.Data.SetValue(0, 'Electronics'); Result.Data.SetValue(1, -2100); Result.Data.AddRow; Result.Data.SetValue(0, 'Food'); Result.Data.SetValue(1, 22600); Result.Data.AddRow; Result.Data.SetValue(0, 'Art'); Result.Data.SetValue(1, 1100); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(350); // Formatter Result.ScripCodeBeforeCallDraw := 'var formatter = new google.visualization.BarFormat({width: 120});' + 'formatter.format(data, 1);' ; end; function GetChartColorFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Department'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Revenues') ]); Result.Data.AddRow; Result.Data.SetValue(0, 'Shoes'); Result.Data.SetValue(1, 10700); Result.Data.AddRow; Result.Data.SetValue(0, 'Sports'); Result.Data.SetValue(1, -15400); Result.Data.AddRow; Result.Data.SetValue(0, 'Toys'); Result.Data.SetValue(1, 12500); Result.Data.AddRow; Result.Data.SetValue(0, 'Electronics'); Result.Data.SetValue(1, -2100); Result.Data.AddRow; Result.Data.SetValue(0, 'Food'); Result.Data.SetValue(1, 22600); Result.Data.AddRow; Result.Data.SetValue(0, 'Art'); Result.Data.SetValue(1, 1100); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(350); // Formatter Result.ScripCodeBeforeCallDraw := 'var formatter = new google.visualization.ColorFormat({width: 120});' + 'formatter.addRange(-20000, 0, ''white'', ''orange'');' + 'formatter.addRange(20000, null, ''red'', ''#33ff33''); ' + 'formatter.format(data, 1);' ; end; function GetChartDateFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Employee Name'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start Date (Long)'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start Date (Medium)'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start Date (Short)') ]); Result.Data.AddRow(['Mike', EncodeDateTime(2008, 2, 28, 0, 31, 26, 0), EncodeDateTime(2008, 2, 28, 0, 31, 26, 0), EncodeDateTime(2008, 2, 28, 0, 31, 26, 0)]); Result.Data.AddRow(['Bob', EncodeDate(2007, 6, 1), EncodeDate(2007, 6, 1), EncodeDate(2007, 6, 1)]); Result.Data.AddRow(['Alice', EncodeDate(2006, 8, 16), EncodeDate(2006, 8, 16), EncodeDate(2006, 8, 16)]); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(550); // Formatter Result.ScripCodeBeforeCallDraw := 'var formatter_long = new google.visualization.DateFormat({formatType: ''long''});' + 'var formatter_medium = new google.visualization.DateFormat({formatType: ''medium''});' + 'var formatter_short = new google.visualization.DateFormat({formatType: ''short''});' + 'formatter_long.format(data, 1);' + 'formatter_medium.format(data, 2);' + 'formatter_short.format(data, 3);' ; end; function GetChartNumberFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Department'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Revenues') ]); Result.Data.AddRow; Result.Data.SetValue(0, 'Shoes'); Result.Data.SetValue(1, 10700); Result.Data.AddRow; Result.Data.SetValue(0, 'Sports'); Result.Data.SetValue(1, -15400); Result.Data.AddRow; Result.Data.SetValue(0, 'Toys'); Result.Data.SetValue(1, 12500); Result.Data.AddRow; Result.Data.SetValue(0, 'Electronics'); Result.Data.SetValue(1, -2100); Result.Data.AddRow; Result.Data.SetValue(0, 'Food'); Result.Data.SetValue(1, 22600); Result.Data.AddRow; Result.Data.SetValue(0, 'Art'); Result.Data.SetValue(1, 1100); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(550); // Formatter Result.ScripCodeBeforeCallDraw := 'var formatter = new google.visualization.NumberFormat({prefix: ''$'', negativeColor: ''red'', negativeParens: true});' + 'formatter.format(data, 1);' ; end; function GetChartPatternFormat: IcfsGChartProducer; begin Result := TcfsGChartProducer.Create; Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART; // Data Result.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Name'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Email') ]); Result.Data.AddRow( ['John Lennon', 'john@beatles.co.uk'] ); Result.Data.AddRow( ['Paul McCartney', 'paul@beatles.co.uk'] ); Result.Data.AddRow( ['George Harrison', 'george@beatles.co.uk'] ); Result.Data.AddRow( ['Ringo Starr', 'ringo@beatles.co.uk'] ); // Options Result.Options.AllowHtml(True); Result.Options.SetAsBoolean('showRowNumber', True); Result.Options.Width(550); // Formatter //Result.UseDataView := True; // <---- ATTENTION: In this formatter example we UseDataView to Hide email column after draw! Result.ScripCodeBeforeCallDraw := 'var formatter = new google.visualization.PatternFormat(''<a href="mailto:{1}">{0}</a>'');' + 'formatter.format(data, [0, 1]);' + 'var view = new google.visualization.DataView(data);' // <-- Create a Data View + 'view.setColumns([0]);'; // Show the first column only (hide email column) ; end; begin // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="display: flex; width: 100%; height: 30%;">' + '<div style="width: 10%; height: 100%;"></div>' + '<div style="width: 40%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Arrow Format<br><br></div>' + '<div id="ChartArrowFormat"></div>' + '</div>' + '<div style="width: 50%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Date Format<br><br></div>' + '<div id="ChartDateFormat"></div>' + '</div>' + '</div>' + '<div style="display: flex; width: 100%; height: 30%;">' + '<div style="width: 10%; height: 100%;"></div>' + '<div style="width: 40%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Bar Format<br><br></div>' + '<div id="ChartBarFormat"></div>' + '</div>' + '<div style="width: 50%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Number Format<br><br></div>' + '<div id="ChartNumberFormat"></div>' + '</div>' + '</div>' + '<div style="display: flex; width: 100%; height: 30%;">' + '<div style="width: 10%; height: 100%;"></div>' + '<div style="width: 40%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Color Format<br><br></div>' + '<div id="ChartColorFormat"></div>' + '</div>' + '<div style="width: 50%; height: 100%;">' + '<div style="font-family: Arial; font-size:12px; font-weight:bold"><br>Pattern Format<br><br></div>' + '<div id="ChartPatternFormat"></div>' + '</div>' + '</div>' + '<div style="display: flex; width: 100%; height: 10%;">' + '<div style="width:100%;font-family: Arial; font-size:14px; text-align: center;"><br><br>Note: click the column headings to sort</div>' + '</div>' ); GChartsFrame.DocumentGenerate('ChartArrowFormat', GetChartArrowFormat); GChartsFrame.DocumentGenerate('ChartBarFormat', GetChartBarFormat); GChartsFrame.DocumentGenerate('ChartColorFormat', GetChartColorFormat); GChartsFrame.DocumentGenerate('ChartDateFormat', GetChartDateFormat); GChartsFrame.DocumentGenerate('ChartNumberFormat', GetChartNumberFormat); GChartsFrame.DocumentGenerate('ChartPatternFormat', GetChartPatternFormat); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_Miscellaneous_Formatters); end.
unit fmeSDUBlocks; // NOTE: When the panel has *no* blocks, the control's Caption will be shown // instead {shows a chart of diff colour blocks eg. for partitions display } { TODO -otdk -cenhance : pos replace with chart component } interface uses Classes, fmeBaseOptions, CommonSettings, Controls, Dialogs, ExtCtrls, Forms, MainSettings, Graphics, Messages, SysUtils, Types , Variants, Windows, Vcl.StdCtrls; type // Note: Both Caption and SubCaption can have CRLFs (e.g. SDUCRLF) in them // to insert newlines TBlock = record Caption: String; SubCaption: String; Percentage: Double; BkColor: TColor; Data: TObject; end; TfmeSDUBlocks = class (TFrame) Label1: TLabel; PROTECTED FLastXY: TPoint; FBlocks: array of TBlock; FBlockRects: array of TRect; FSelected: Integer; FOnChanged: TNotifyEvent; FCanvas :TCanvas; procedure Click; OVERRIDE; procedure MouseMove(Shift: TShiftState; X, Y: Integer); OVERRIDE; procedure WMGetDlgCode(var Message: TWMGetDlgCode); MESSAGE WM_GETDLGCODE; procedure KeyDown(var Key: Word; Shift: TShiftState); OVERRIDE; procedure KeyPress(var Key: Char); OVERRIDE; procedure DoEnter; OVERRIDE; procedure DrawBlock(idx: Integer); procedure RemoveAllBlocks(); procedure SetSelected(idx: Integer); procedure PaintWindow(DC: HDC); OVERRIDE; PUBLIC constructor Create(AOwner: TComponent); OVERRIDE; destructor Destroy(); OVERRIDE; procedure Clear(); VIRTUAL; procedure Add(blk: TBlock); VIRTUAL; function GetItem(idx: Integer): TBlock; VIRTUAL; procedure SetItem(idx: Integer; blk: TBlock); VIRTUAL; function GetCount(): Integer; VIRTUAL; PUBLIC property Item[idx: Integer]: TBlock Read GetItem Write SetItem; procedure SetCaption(cap: String); PUBLISHED property Count: Integer Read GetCount; property Selected: Integer Read FSelected Write SetSelected; property OnChanged: TNotifyEvent Read FOnChanged Write FOnChanged; end; // procedure Register; implementation {$R *.dfm} uses GraphUtil, Math; { this frame has a control on it that isnt used, because that forces PaintWindow to be called, see: http://stackoverflow.com/questions/10681027/what-is-the-most-safe-and-correct-way-to-paint-on-a-tframe-surface cant set DoubleBuffered := true; bc may be overridden } constructor TfmeSDUBlocks.Create(AOwner: TComponent); begin inherited; FLastXY := Point(-1, -1); // Change TPanel default; we accept keypresses TabStop := True; RemoveAllBlocks(); FCanvas := TCanvas.Create(); end; destructor TfmeSDUBlocks.Destroy(); begin FCanvas.Free(); inherited; end; procedure TfmeSDUBlocks.RemoveAllBlocks(); begin SetLength(FBlocks, 0); SetLength(FBlockRects, 0); end; procedure TfmeSDUBlocks.Clear(); begin RemoveAllBlocks(); // Flag as none selected FSelected := -1; end; procedure TfmeSDUBlocks.Add(blk: TBlock); begin SetLength(FBlocks, (length(FBlocks) + 1)); FBlocks[length(FBlocks) - 1] := blk; SetLength(FBlockRects, (length(FBlockRects) + 1)); FBlockRects[length(FBlockRects) - 1] := Rect(0, 0, 0, 0); Invalidate(); end; function TfmeSDUBlocks.GetItem(idx: Integer): TBlock; begin Result := FBlocks[idx]; end; procedure TfmeSDUBlocks.SetCaption(cap: String); begin Caption := cap; end; procedure TfmeSDUBlocks.SetItem(idx: Integer; blk: TBlock); begin FBlocks[idx] := blk; Invalidate(); end; procedure TfmeSDUBlocks.PaintWindow(DC: HDC); var i: Integer; x: Integer; useWidth: Integer; currBlkWidth: Integer; BevelPixels: Integer; useRect: TRect; currRight: Integer; begin inherited; if (length(FBlocks) > 0) then begin BevelPixels := 0; if (BevelInner <> bvNone) then Inc(BevelPixels, BevelWidth); if (BevelOuter <> bvNone) then Inc(BevelPixels, BevelWidth); useRect := Rect(0, 0, ClientWidth, ClientHeight); InflateRect(useRect, -BevelPixels, -BevelPixels); // Purge display FCanvas.Handle := DC; fcanvas.Brush.Color := Color; fcanvas.FillRect(useRect); x := useRect.Left; useWidth := useRect.Right - useRect.Left; for i := low(FBlocks) to high(FBlocks) do begin currBlkWidth := trunc((useWidth / 100) * FBlocks[i].Percentage); // Ensure we don't go over the bevel/edge of the control... currRight := min(x + currBlkWidth, useRect.Right); FBlockRects[i] := Rect(x, useRect.Top, currRight, useRect.Bottom); DrawBlock(i); // +1 to give a slight x := x + currBlkWidth + 1; end; end; end; procedure TfmeSDUBlocks.DrawBlock(idx: Integer); var insideBounds: TRect; textHeight: Integer; blk: TBlock; tmpBounds: TRect; normalFGColor: TColor; normalBKColor: TColor; stlTextLines: TStringList; i: Integer; textTop: Integer; begin inherited; blk := FBLocks[idx]; // Clear any lines on the display // We surround the Canvas blanking with "parent<>nil" to avoid getting // "Control '' has no parent window" errors when the component is dropped // onto a form if (parent <> nil) then begin normalFGColor := Font.Color; normalBKColor := Color; if (blk.BkColor <> clNone) then begin normalBKColor := blk.BkColor; end; fCanvas.Brush.Color := normalBKColor; fCanvas.Brush.Style := bsSolid; insideBounds := FBlockRects[idx]; fCanvas.FillRect(insideBounds); InflateRect(insideBounds, -4, -4); fCanvas.Pen.Color := normalFGColor; fCanvas.Brush.Color := normalBKColor; fCanvas.Brush.Style := bsClear; if (Selected = idx) then begin fCanvas.Pen.Color := GetHighLightColor(normalFGColor); fCanvas.Brush.Color := GetHighLightColor(normalBKColor); // Refill the reduced rect to give highlighted background fCanvas.FillRect(insideBounds); end; fCanvas.Brush.Style := bsClear; fCanvas.Font.Style := Font.Style + [fsBold]; textHeight := fCanvas.TextHeight('X'); // We use a TStringList to split the caption up into separate lines if it's // for SDUCRLF's in it, then TextRect(...) the strings out as TextRect(...) // doesn't honour CRLFs, or "\n" in strings stlTextLines := TStringList.Create(); try stlTextLines.Text := blk.Caption; textTop := insideBounds.top; for i := 0 to (stlTextLines.Count - 1) do begin fCanvas.TextRect( insideBounds, insideBounds.left, textTop, stlTextLines[i] ); textTop := textTop + textHeight; end; fCanvas.Font.Style := Font.Style - [fsBold]; // Changed style could have altered the height of the font textHeight := fCanvas.TextHeight('X'); stlTextLines.Text := blk.SubCaption; // textTop already set appropriately at this point for i := 0 to (stlTextLines.Count - 1) do begin fCanvas.TextRect( insideBounds, insideBounds.left, textTop, stlTextLines[i] ); textTop := textTop + textHeight; end; finally stlTextLines.Free(); end; // Cell frame... fCanvas.Brush.Style := bsSolid; fCanvas.Brush.Color := clBlack; fCanvas.FrameRect(FBlockRects[idx]); // Selected dottec focus rect.. if (Selected = idx) then begin tmpBounds := FBlockRects[idx]; InflateRect(tmpBounds, -1, -1); fCanvas.Brush.Color := color; fCanvas.DrawFocusRect(tmpBounds); end; end; end; procedure TfmeSDUBlocks.Click(); var i: Integer; currBlk: TRect; begin SetFocus(); FSelected := -1; for i := low(FBlockRects) to high(FBlockRects) do begin currBlk := FBlockRects[i]; if ((currBlk.left <= FLastXY.X) and (currBlk.right >= FLastXY.X) and (currBlk.top <= FLastXY.Y) and (currBlk.bottom >= FLastXY.Y)) then begin Selected := i; break; end; end; inherited; end; procedure TfmeSDUBlocks.MouseMove(Shift: TShiftState; X, Y: Integer); begin FLastXY := Point(X, Y); inherited; end; procedure TfmeSDUBlocks.SetSelected(idx: Integer); begin FSelected := idx; Invalidate(); if Assigned(FOnChanged) then begin FOnChanged(self); end; end; function TfmeSDUBlocks.GetCount(): Integer; begin Result := length(FBlocks); end; procedure TfmeSDUBlocks.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if ((Key = VK_LEFT) or (Key = VK_UP)) then begin if (Selected < low(FBlockRects)) then begin // None selected; select first Selected := low(FBlockRects); end else if (Selected = low(FBlockRects)) then begin // Do nothing; 1st one already selected end else begin Selected := Selected - 1; end; end else if ((Key = VK_RIGHT) or (Key = VK_DOWN)) then begin if ((Selected < low(FBlockRects)) or (Selected > high(FBlockRects))) then begin // None selected; select last Selected := high(FBlockRects); end else if (Selected = high(FBlockRects)) then begin // Do nothing; 1st one already selected end else begin Selected := Selected + 1; end; end; end; procedure TfmeSDUBlocks.KeyPress(var Key: Char); begin //ko end; procedure TfmeSDUBlocks.DoEnter; begin if (Selected < low(FBlockRects)) then begin Selected := low(FBlockRects); end; inherited; end; procedure TfmeSDUBlocks.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; Message.Result := Message.Result or DLGC_WANTARROWS; end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) 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/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_HugeCardinal; {.$define profiling} interface uses Classes, uTPLb_IntegerUtils, uTPLb_MemoryStreamPool {$IFDEF profiling} , Generics.Collections {$ENDIF} ; type {$define SI} TCompareResult = (rGreaterThan, rEqualTo, rLessThan); TByteOrder = (LittleEndien, BigEndien); TProgress = procedure ( Sender: TObject; BitsProcessed, TotalBits: int64; var doAbort: boolean) of object; {$if CompilerVersion >= 21.00} THugeCardinal = class sealed {$else} THugeCardinal = class {$ifend} // An instance of this class represents a very large non-negative integer. private FMaxBits: integer; // Maximum number of bits of storage. // For efficiency reasons, we will not allow // re-allocation/resizing. FBits: integer; // Cached value of the bit length of the value; {$IFNDEF SI} FValue: TMemoryStream; // Little-endien. {$ENDIF} procedure CheckBits; class function ComputedNeededSize( RequestedBits: integer): integer; procedure ClearMem( Offset, Length: integer); procedure DividePrimitive( Divisor: THugeCardinal; var Quotient, Remainder: THugeCardinal; RequiresQuotient: boolean); function GetAsHexString: string; procedure MulPower2_OldAlgorithm( ShiftAmnt: integer); procedure MulPower2_NewAlgorithm( ShiftAmnt: integer); procedure MultiplyMod_Old( Factor, Modulus: THugeCardinal); procedure MultiplyMod_New( Factor, Modulus: THugeCardinal); protected function NewMemoryStream( InitBitSize: integer): TMemoryStream; function ValuePntr( ByteIndex: integer): PByte; public {$IFDEF SI} FValue: TMemoryStream; // Little-endien. {$ENDIF} FPool: IMemoryStreamPool; // Life-cycle methods. constructor CreateSimple( Value: uint64); constructor CreateZero( MaxBits1: integer; const Pool1: IMemoryStreamPool); constructor CreateRandom( Bits1, MaxBits1: integer; ExactBitLength: boolean; const Pool1: IMemoryStreamPool); // CreateRandom creates a random number up to Bits1 bits long. // If ExactBitLength is True, then the resultant bit length will be // exactly Bits1 long. Otherwise it may range anywhere down to zero. constructor CreateSmall( Value: uint64; MaxBits1: integer; const Pool1: IMemoryStreamPool); constructor CreateAsClone( Master: THugeCardinal; const Pool1: IMemoryStreamPool); constructor CreateAsSizedClone( MaxBits1: integer; Master: THugeCardinal; const Pool1: IMemoryStreamPool); constructor CreateFromStreamIn( MaxBits1: integer; ByteOrder: TByteOrder; Stream: TStream; const Pool1: IMemoryStreamPool); destructor Destroy; override; function Clone: THugeCardinal; function CloneSized( MaxBits1: integer): THugeCardinal; procedure Resize( NewMaxBit1: integer); procedure Burn; // Size properties. function BitLength: integer; function MaxBits: integer; function CapacityInBits: integer; // Assignment. procedure Assign( Source: THugeCardinal); procedure AssignFromStreamIn( ByteOrder: TByteOrder; Stream: TStream); procedure AssignSmall( Value: uint64); procedure Swap( Peer: THugeCardinal); // Random numbers. procedure Random( UpperBound: THugeCardinal); // ^ Results in a random number x, such that: // 0 <= x < UpperBound. // Requires (UpperBound >= 1) and (UpperBound.BitLength <= MaxBits) procedure RandomBits( BitsOfRandom: integer; ExactBitLength: boolean); // ^ if ExactBitLength = False, results in .... // 0 <= x < (2 ** BitsOfRandom) . // In other words ..... // x.BitLength <= BitsOfRandom // If ExactBitLength = True, results in .... // (2 ** BitsOfRandom-1) <= x < (2 ** BitsOfRandom) . // In other words ..... // x.BitLength = BitsOfRandom // Assumes BitsOfRandom >= 1. // Comparison function Compare( Reference: THugeCardinal): TCompareResult; function CompareSmall( Reference: uint64): TCompareResult; function isZero: boolean; function isOdd: boolean; // Small ops. procedure Zeroise; function isSmall: boolean; function ExtractSmall: uint64; function ModSmall( Modulus: uint64): uint64; // Addition. procedure Add( Addend: THugeCardinal); procedure Increment( Addend: int64); procedure Subtract( Subtractend: THugeCardinal); procedure AddMod( Addend, Modulus: THugeCardinal); // Multiplication. procedure MulSmall( Factor: uint32); function Multiply( Factor: THugeCardinal): THugeCardinal; procedure MultiplyMod( Factor, Modulus: THugeCardinal); procedure SquareMod( Modulus: THugeCardinal); procedure MulPower2( ShiftAmnt: integer); // Division function Modulo( Modulus: THugeCardinal): THugeCardinal; procedure Divide( Divisor: THugeCardinal; var Quotient, Remainder: THugeCardinal); // Exponentiation. function PowerMod( Exponent, Modulus: THugeCardinal; OnProgress: TProgress): boolean; // ^ Return True if not aborted. function PowerMod_WithChineseRemainderAlgorithm( Exponent, // d Modulus: THugeCardinal; // n := p * q FactorP, // p FactorQ, // q ExponentModFactorP, // dp := d mod p-1 ExponentModFactorQ, // dq := d mod q-1 InverseQ : THugeCardinal; // qinv := q ** -1 mod p // result := self ** d mod n OnProgress: TProgress): boolean; // ^ Return True if not aborted. procedure SmallExponent_PowerMod( Exponent: uint64; Modulus: THugeCardinal); procedure SmallExponent_Power( Exponent: uint32); // Only used for unit-test purposes. // Streaming. procedure StreamOut( ByteOrder: TByteOrder; Stream: TStream; SizeToOutput: integer = -1); // ^ Streams the low order SizeToOutput bytes out to the stream. // If SizeToOutput is -1, then this is interpreted as (MaxBits + 7) div 8 property AsHexString: string read GetAsHexString; end; procedure SafeAssign( Destin, Source: THugeCardinal); // Both parameters must pre-exist. procedure SafeAdd( Sum, Addend1, Addend2: THugeCardinal); // All 3 parameters must pre-exist. type TProfileSection = ( proc_Add, proc_Increment, proc_Subtract, proc_AddMod, proc_MulSmall, func_Multiply, proc_MultiplyMod, proc_SquareMod, proc_MulPower2, func_Modulo, proc_Divide, func_PowerMod, proc_SmallExponent_PowerMod); TProfileSectionSet = set of TProfileSection; TProfileSectionResult = record Section: TProfileSection; Sum, Start: Int64; end; var ActiveProfileSections: TProfileSectionSet = [proc_MultiplyMod, proc_SquareMod, proc_MulPower2, func_Modulo]; {$IFDEF profiling} var SectionStack: TStack<TProfileSectionResult> = nil; {$ENDIF} var HugeCardinal_InstanceCount: integer = 0; doUseMulPower2_NewAlgorithm: boolean = True; doUseMultiplyMod_NewAlgorithm: boolean = True; doProfiling: boolean = False; ExecutionTimes: array[ TProfileSection] of Int64; ExecutionPercentages: array[ TProfileSection] of cardinal; procedure InitExecutionTimes; procedure DoneExecutionTimes; procedure CalcExecutionPercentages; implementation uses SysUtils, uTPLb_StreamUtils, Math, uTPlb_Random,uTPLb_I18n, uTPLb_PointerArithmetic, SyncObjs; {$IFDEF profiling} type TProfileSectionHold = class( TInterfacedObject) private doFrame: boolean; public constructor Create( Entry: TProfileSection); destructor Destroy; override; end; {$ENDIF} function EnterProfileSection( Entry: TProfileSection): IInterface; begin {$IFDEF profiling} if Entry in ActiveProfileSections then result := TProfileSectionHold.Create( Entry) else {$ENDIF} {$IFNDEF profiling} result := nil {$ENDIF} end; procedure InitExecutionTimes; var j: TProfileSection; begin for j := Low( TProfileSection) to High( TProfileSection) do ExecutionTimes[j] := 0; {$IFDEF profiling} SectionStack.Free; SectionStack := TStack<TProfileSectionResult>.Create {$ENDIF} end; procedure DoneExecutionTimes; begin {$IFDEF profiling} SectionStack.Free; SectionStack := nil {$ENDIF} end; {$IFDEF profiling} constructor TProfileSectionHold.Create( Entry: TProfileSection); var Now1: Int64; ProfSectRes: TProfileSectionResult; isEmpty: boolean; begin isEmpty := SectionStack.Count = 0; doFrame := isEmpty or (SectionStack.Peek.Section <> Entry); if not doFrame then exit; if not isEmpty then ProfSectRes := SectionStack.Pop; QueryPerformanceCounter( Now1); if (not isEmpty) and (ProfSectRes.Start > 0) then begin ProfSectRes.Sum := ProfSectRes.Sum + (Now1 - ProfSectRes.Start); ProfSectRes.Start := 0; SectionStack.Push( ProfSectRes) end; ProfSectRes.Section := Entry; ProfSectRes.Sum := 0; ProfSectRes.Start := Now1; SectionStack.Push( ProfSectRes) end; destructor TProfileSectionHold.Destroy; var Now1: Int64; ProfSectRes: TProfileSectionResult; isEmpty: boolean; begin if doFrame then begin QueryPerformanceCounter( Now1); ProfSectRes := SectionStack.Pop; if ProfSectRes.Start > 0 then ProfSectRes.Sum := ProfSectRes.Sum + (Now1 - ProfSectRes.Start); ExecutionTimes[ProfSectRes.Section] := ExecutionTimes[ProfSectRes.Section] + ProfSectRes.Sum; if SectionStack.Count > 0 then begin ProfSectRes := SectionStack.Pop; ProfSectRes.Start := Now1; SectionStack.Push( ProfSectRes) end end; inherited end; {$ENDIF} procedure CalcExecutionPercentages; var j: TProfileSection; Sum: Int64; begin Sum := 0; for j := Low( TProfileSection) to High( TProfileSection) do if j in ActiveProfileSections then Sum := Sum + ExecutionTimes[j]; for j := Low( TProfileSection) to High( TProfileSection) do if (Sum = 0) or (ExecutionTimes[j] = 0) or (not (j in ActiveProfileSections)) then ExecutionPercentages[j] := 0 else ExecutionPercentages[j] := Round( (ExecutionTimes[j] / Sum) * 100.0) end; procedure SafeAssign( Destin, Source: THugeCardinal); begin Destin.Zeroise; if Source.BitLength > Destin.MaxBits then Destin.Resize( Source.BitLength); Destin.Assign( Source) end; procedure SafeAdd( Sum, Addend1, Addend2: THugeCardinal); var Tmp: THugeCardinal; begin Tmp := THugeCardinal.CreateAsSizedClone( Max( Addend1.BitLength, Addend2.BitLength) + 1, Addend1, Addend1.FPool); Tmp.Add( Addend2); SafeAssign( Sum, Tmp); Tmp.Free end; { THugeCardinal } procedure SetBit( Number: THugeCardinal; BitIndex: integer); var P: PByte; begin P := MemStrmOffset( Number.FValue, BitIndex div 8); P^ := P^ or (1 shl (BitIndex mod 8)) end; procedure ClearBit( Number: THugeCardinal; BitIndex: integer); var P: PByte; begin P := MemStrmOffset( Number.FValue, BitIndex div 8); P^ := P^ and (not (1 shl (BitIndex mod 8))) end; function TestBit( Number: THugeCardinal; BitIndex: integer): boolean; var P: PByte; begin P := MemStrmOffset( Number.FValue, BitIndex div 8); result := (P^ and (1 shl (BitIndex mod 8))) <> 0 end; class function THugeCardinal.ComputedNeededSize( RequestedBits: integer): integer; begin result := Max( RequestedBits, 64); if (result mod 8) <> 0 then result := result + 8 - (result mod 8) end; constructor THugeCardinal.CreateAsClone( Master: THugeCardinal; const Pool1: IMemoryStreamPool); begin FPool := Pool1; FMaxBits := Master.MaxBits; FBits := Master.FBits; FValue := NewMemoryStream( Master.FValue.Size * 8); Move( Master.FValue.Memory^, FValue.Memory^, FValue.Size); TInterlocked.Increment( HugeCardinal_InstanceCount) end; constructor THugeCardinal.CreateAsSizedClone( MaxBits1: integer; Master: THugeCardinal; const Pool1: IMemoryStreamPool); var DataByteLen: integer; begin FPool := Pool1; FMaxBits := ComputedNeededSize( MaxBits1); if Master.BitLength > FMaxBits then raise Exception.Create( ES_HugeCardinal_CloneOverflow); DataByteLen := (Master.BitLength + 7) div 8; FValue := NewMemoryStream( FMaxBits); if DataByteLen > 0 then Move( Master.FValue.Memory^, FValue.Memory^, DataByteLen); ClearMem( DataByteLen, FValue.Size - DataByteLen); FBits := Master.BitLength; TInterlocked.Increment( HugeCardinal_InstanceCount) end; constructor THugeCardinal.CreateFromStreamIn( MaxBits1: integer; ByteOrder: TByteOrder; Stream: TStream; const Pool1: IMemoryStreamPool); begin FPool := Pool1; FMaxBits := ComputedNeededSize( MaxBits1); FValue := NewMemoryStream( FMaxBits); AssignFromStreamIn( ByteOrder, Stream); TInterlocked.Increment( HugeCardinal_InstanceCount) end; constructor THugeCardinal.CreateRandom( Bits1, MaxBits1: integer; ExactBitLength: boolean; const Pool1: IMemoryStreamPool); begin CreateZero( MaxBits1, Pool1); if Bits1 > FMaxBits then Bits1 := FMaxBits; RandomBits( Bits1, ExactBitLength) end; procedure THugeCardinal.Random( UpperBound: THugeCardinal); begin if not UpperBound.isZero then repeat RandomBits( UpperBound.BitLength, False) until Compare( UpperBound) = rLessThan end; procedure THugeCardinal.RandomBits( BitsOfRandom: integer; ExactBitLength: boolean); var R: TStream; Bits, j: integer; Bytes, OldBytes: integer; HighByte, Mask: byte; begin if BitsOfRandom <= 0 then exit; R := TRandomStream.Instance; CheckBits; Bits := BitsOfRandom; Bytes := ((Bits + 7) div 8) - 1; OldBytes := ((FBits + 7) div 8); FBits := -1; if Bytes > 0 then begin // Determine all the bytes, except the most significant byte. R.Read( FValue.Memory^, Bytes); Dec( Bits, Bytes * 8) end; if Bits > 0 then begin // Determine the most significant byte. R.Read( HighByte, 1); Mask := 1; for j := 2 to Bits do Mask := (Mask shl 1) + 1; HighByte := HighByte and Mask; FValue.Position := Bytes; FValue.Write( HighByte, 1); Inc( Bytes); if ((HighByte shr (Bits - 1)) and $01) = $01 then FBits := BitsOfRandom end; if OldBytes > Bytes then BurnMemory( ValuePntr( Bytes)^, OldBytes - Bytes); if ExactBitLength then begin SetBit( self, BitsOfRandom-1); FBits := BitsOfRandom end end; constructor THugeCardinal.CreateSimple( Value: uint64); begin CreateSmall( Value, 0, nil) end; constructor THugeCardinal.CreateSmall( Value: uint64; MaxBits1: integer; const Pool1: IMemoryStreamPool); begin CreateZero( MaxBits1, Pool1); if Value > 0 then begin FValue.Write( Value, SizeOf( Value)); FBits := BitCount_64( Value) end end; constructor THugeCardinal.CreateZero( MaxBits1: integer; const Pool1: IMemoryStreamPool); begin FPool := Pool1; FMaxBits := ComputedNeededSize( MaxBits1); FBits := 0; FValue := NewMemoryStream( FMaxBits); ZeroFillStream( FValue); TInterlocked.Increment( HugeCardinal_InstanceCount) end; destructor THugeCardinal.Destroy; begin TInterlocked.Increment( HugeCardinal_InstanceCount); FValue.Free; inherited end; function THugeCardinal.ExtractSmall: uint64; begin Move( FValue.Memory^, result, 8) end; function THugeCardinal.GetAsHexString: string; var // Temp: THugeCardinal; ValueByte: byte; Idx: integer; P1: PByte; StrIdx: integer; function CharOfNibble( Nibble: byte): Char; begin if Nibble <= 9 then result := Chr( Ord('0') + Nibble) else result := Chr( Ord('A') + Nibble - 10) end; begin // Temp := Clone; Idx := (BitLength + 7) div 8; SetLength( result, Idx * 2); P1 := ValuePntr( Idx); StrIdx := -1; while Idx > 0 do begin Dec( P1, 1); Dec( Idx); Inc( StrIdx, 2); ValueByte := P1^; result[StrIdx ] := CharOfNibble( ValueByte shr 4); result[StrIdx+1] := CharOfNibble( ValueByte and $0F) end; if (Length( result) > 0) and (result[1] = '0') and (not isZero) then Delete( result, 1, 1); if Length( result) = 0 then result := '0' end; type Puint64 = ^uint64; procedure THugeCardinal.Add( Addend: THugeCardinal); var P1, P2: PByte; I1, D1, D2: integer; Carry: boolean; Sum: uint16; v: uint64; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_AddOverflow) end; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_Add); {$ENDIF} if Addend.isZero then exit; if isZero then begin Assign( Addend); exit end; if Addend.isSmall then begin v := Addend.ExtractSmall; if v <= $7FFFFFFFFFFFFFFF then begin Increment( v); exit end end; if Addend.BitLength > MaxBits then Overflow; P1 := FValue.Memory; // Cursor into the accumulator. I1 := FValue.Size; // Complement of offset into P1. D1 := (BitLength + 7) div 8; // Number of original data bytes in the accumulator. P2 := Addend.FValue.Memory; D2 := (Addend.BitLength + 7) div 8; Carry := False; while (D1 > 0) or (D2 > 0) or Carry do begin if (D1 >= 8) and (D2 >= 8) then begin Puint64( P1)^ := Add_uint64_WithCarry( Puint64( P1)^, Puint64( P2)^, Carry); Inc( P1, 8); Inc( P2, 8); Dec( D1, 8); Dec( D2, 8); Dec( I1, 8) end else begin if D1 > 0 then Sum := P1^ else Sum := 0; if D2 > 0 then Inc( Sum, P2^); if Carry then Inc( Sum); if I1 > 0 then begin P1^ := WordRec( Sum).Lo; Carry := WordRec( Sum).Hi <> 0 end else if Sum = 0 then Carry := False else Overflow; Inc( P1, 1); Inc( P2, 1); Dec( I1, 1); Dec( D1, 1); Dec( D2, 1) end end; FBits := -1 end; procedure THugeCardinal.AddMod( Addend, Modulus: THugeCardinal); var RequiredBits: integer; Sum, Remainder: THugeCardinal; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_AddMod); {$ENDIF} RequiredBits := Max( BitLength, Addend.BitLength) + 1; if RequiredBits < MaxBits then Sum := self else Sum := CloneSized( RequiredBits); try Sum.Add( Addend); Remainder := Sum.Modulo( Modulus); try Assign( Remainder) finally Remainder.Free end finally if Sum <> self then Sum.Free end end; procedure THugeCardinal.Assign( Source: THugeCardinal); var SourceBytes: integer; begin SourceBytes := (Source.BitLength + 7) div 8; if SourceBytes > FValue.Size then raise Exception.Create( ES_CannotAssignHuge_BecauseSourceTooBig); if SourceBytes > 0 then Move( Source.FValue.Memory^, FValue.Memory^, SourceBytes); ClearMem( SourceBytes, FValue.Size - SourceBytes); FBits := Source.BitLength end; procedure THugeCardinal.AssignSmall( Value: uint64); begin if BitLength > 64 then Zeroise; Move( Value, FValue.Memory^, SizeOf( Value)); FBits := -1 end; function THugeCardinal.BitLength: integer; begin CheckBits; result := FBits end; procedure THugeCardinal.Burn; begin BurnMemoryStream( FValue); FBits := 0 end; procedure THugeCardinal.CheckBits; var P32: ^uint32; P8: PByte; LastBits: integer; begin if FBits <> -1 then exit; FBits := FValue.Size * 8; if FBits = 0 then exit; P8 := ValuePntr( FBits div 8); LastBits := 0; while (FBits > 0) and (LastBits = 0) do begin if (FBits >= 32) and isAligned32( P8) then begin Dec( P8, 4); P32 := pointer( P8); LastBits := BitCount_32( P32^); Dec( FBits, 32 - LastBits) end else begin Dec( P8, 1); LastBits := BitCount_8( P8^); Dec( FBits, 8 - LastBits) end end end; procedure THugeCardinal.ClearMem( Offset, Length: integer); begin ClearMemory( FValue, Offset, Length) end; function THugeCardinal.Clone: THugeCardinal; begin result := THugeCardinal.CreateAsClone( self, FPool) end; function THugeCardinal.CloneSized( MaxBits1: integer): THugeCardinal; begin result := THugeCardinal.CreateAsSizedClone( MaxBits1, self, FPool) end; function THugeCardinal.Compare( Reference: THugeCardinal): TCompareResult; var Diff: integer; P1, P2: PByte; Idx: integer; begin Diff := BitLength - Reference.BitLength; if Diff <> 0 then begin if Diff > 0 then result := rGreaterThan else result := rLessThan end else begin result := rEqualTo; if BitLength <> 0 then begin Idx := (BitLength + 7) div 8; P1 := ValuePntr( Idx); P2 := Reference.ValuePntr( Idx); while (Idx > 0) and (result = rEqualTo) do begin Dec( P1, 1); Dec( P2, 1); Dec( Idx); Diff := P1^; Diff := Diff - P2^; if Diff > 0 then result := rGreaterThan else if Diff < 0 then result := rLessThan end end end end; function THugeCardinal.CompareSmall( Reference: uint64): TCompareResult; var V: uint64; begin if isSmall then begin V := ExtractSmall; if V > Reference then result := rGreaterThan else if V < Reference then result := rLessThan else result := rEqualTo end else result := rGreaterThan end; procedure THugeCardinal.Increment( Addend: int64); var P1: PByte; I1, Stop_I1: integer; Carry, Borrow: boolean; Sum: uint16; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_IncrementOverflow) end; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_Increment); {$ENDIF} if Addend = 0 then exit; if MaxBits < 8 then Overflow; P1 := FValue.Memory; I1 := (BitLength + 7) div 8; Stop_I1 := I1 - FValue.Size; // -ve of spare capacity. if Addend > 0 then begin Carry := False; Puint64( P1)^ := Add_uint64_WithCarry( Puint64( P1)^, Addend, Carry); Inc( P1, 8); Dec( I1, 8); while (I1 > 0) or Carry do begin if I1 <= Stop_I1 then Overflow; if I1 > 0 then Sum := P1^ else Sum := 0; if Carry then Inc( Sum); P1^ := WordRec( Sum).Lo; Carry := WordRec( Sum).Hi <> 0; Inc( P1, 1); Dec( I1, 1); end end else begin // -ve case Borrow := False; Puint64( P1)^ := Subtract_uint64_WithBorrow( Puint64( P1)^, -Addend, Borrow); Inc( P1, 8); Dec( I1, 8); while (I1 > 0) or Borrow do begin if I1 <= Stop_I1 then Overflow; if I1 > 0 then Sum := P1^ else Sum := 0; if Borrow then begin if Sum = 0 then Sum := 255 else begin Dec( Sum); Borrow := False end end; P1^ := WordRec( Sum).Lo; Inc( P1, 1); Dec( I1, 1); end end; FBits := -1 end; function THugeCardinal.isOdd: boolean; var LowByte: byte; begin CheckBits; result := FBits > 0; if not result then exit; FValue.Position := 0; FValue.Read( LowByte, 1); result := Odd( LowByte) end; function THugeCardinal.isSmall: boolean; begin result := BitLength <= 64 end; function THugeCardinal.isZero: boolean; begin CheckBits; result := FBits = 0 end; function THugeCardinal.MaxBits: integer; begin result := FMaxBits end; function THugeCardinal.ModSmall( Modulus: uint64): uint64; var Mask, Low64: uint64; Quot, Mod1: THugeCardinal; begin if Modulus <= 1 then result := 0 else if Modulus = 2 then result := Ord( isOdd) else begin Low64 := ExtractSmall; if CountSetBits_64( Modulus) = 1 then // Modulus = 4, 8, 16 etc. begin Mask := Modulus - 1; // Mask = $03, $07, $0F etc. result := Low64 and Mask end else if isSmall and (int64rec( Modulus).Hi = 0) and (int64rec( Low64 ).Hi = 0) then // Pure 32 bit operation. result := int64rec( Low64).Lo mod int64rec( Modulus).Lo // 64-bit mod might be possible, but I dont trust the compiler to // get it right. else begin Mod1 := nil; Quot := nil; try Mod1 := THugeCardinal.CreateSmall( Modulus, 0, FPool); Quot := Modulo( Mod1); result := Quot.ExtractSmall finally Mod1.Free; Quot.Free end end end end; function THugeCardinal.Modulo( Modulus: THugeCardinal): THugeCardinal; var Dummy: THugeCardinal; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( func_Modulo); {$ENDIF} Dummy := nil; DividePrimitive( Modulus, Dummy, result, False); Dummy.Free end; procedure THugeCardinal.Divide( Divisor: THugeCardinal; var Quotient, Remainder: THugeCardinal); begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_Divide); {$ENDIF} DividePrimitive( Divisor, Quotient, Remainder, True) end; procedure THugeCardinal.DividePrimitive( Divisor: THugeCardinal; var Quotient, Remainder: THugeCardinal; RequiresQuotient: boolean); var ShiftedMod: THugeCardinal; ShiftAmnt: integer; RemainderBits, ModulusBits, DiffBits: integer; Compare: TCompareResult; LeftShift: integer; QuotientByte: PByte; Mask: byte; begin QuotientByte := nil; Remainder := CloneSized( BitLength); if RequiresQuotient then Quotient := THugeCardinal.CreateZero( Max( BitLength, Divisor.BitLength), FPool); if BitLength > Divisor.BitLength then ShiftedMod := Divisor.CloneSized( BitLength) else ShiftedMod := Divisor.Clone; try ShiftAmnt := 0; RemainderBits := Remainder.BitLength; ModulusBits := Divisor.BitLength; DiffBits := RemainderBits - ModulusBits; if DiffBits > 0 then Compare := rGreaterThan else if DiffBits < 0 then Compare := rLessThan else Compare := Remainder.Compare( Divisor); while ((Compare in [rGreaterThan, rEqualTo]) or (ShiftAmnt > 0)) and (RemainderBits > 0) do begin LeftShift := DiffBits; if (LeftShift < 0) and ((-LeftShift) > ShiftAmnt) then LeftShift := - ShiftAmnt; if (ShiftAmnt + LeftShift) = 0 then ShiftedMod.Assign( Divisor) else ShiftedMod.MulPower2( LeftShift); Inc( ShiftAmnt, LeftShift); if LeftShift <> 0 then Compare := Remainder.Compare( ShiftedMod); if (Compare = rLessThan) and (ShiftAmnt > 0) then begin if ShiftAmnt = 1 then ShiftedMod.Assign( Divisor) else ShiftedMod.MulPower2( -1); Dec( ShiftAmnt); Compare := rGreaterThan end; if Compare in [rGreaterThan, rEqualTo] then begin Remainder.Subtract( ShiftedMod); RemainderBits := Remainder.BitLength; Compare := rLessThan; // set bit ShiftAmnt of Quotient if RequiresQuotient and (ShiftAmnt > Quotient.MaxBits) then raise Exception.Create( ES_HugeCardinal_DivideOverflow); if RequiresQuotient then QuotientByte := Quotient.ValuePntr( ShiftAmnt div 8); Mask := 1 shl (ShiftAmnt mod 8); if RequiresQuotient then begin Assert( (QuotientByte^ and Mask) = 0, AS_HugeCardinal_DivideLogicFail); QuotientByte^ := QuotientByte^ or Mask end end; DiffBits := RemainderBits - (ModulusBits + ShiftAmnt) end; finally ShiftedMod.Free end; if RequiresQuotient then Quotient.FBits := -1 end; procedure THugeCardinal.MulPower2( ShiftAmnt: integer); begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_MulPower2); {$ENDIF} if doUseMulPower2_NewAlgorithm then MulPower2_NewAlgorithm( ShiftAmnt) else MulPower2_OldAlgorithm( ShiftAmnt) end; procedure THugeCardinal.MulPower2_OldAlgorithm( ShiftAmnt: integer); var P8: PByte; P32: ^uint32; Carry: byte; Remaining, ShiftBytes: integer; b8_1, b8_2: byte; b32_1, b32_2: uint32; DataLen: integer; Idx: integer; // index into data value pointed to by the write pointer P8. InitialBits: integer; InitialShiftAmnt: integer; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_Power2) end; begin if (ShiftAmnt = 0) or isZero then exit; InitialBits := BitLength; if (InitialBits + ShiftAmnt) > MaxBits then Overflow; InitialShiftAmnt := ShiftAmnt; if ShiftAmnt > 0 then ShiftBytes := ShiftAmnt div 8 else ShiftBytes := -((-ShiftAmnt + 7) div 8); Dec( ShiftAmnt, ShiftBytes * 8); DataLen := (FBits + 7) div 8; P8 := FValue.Memory; Idx := 0; Remaining := DataLen; if ShiftBytes >= 1 then begin // Here, we want to shift-left the value data by ShiftBytes (bytes). // Shift-left is equivalent to multiplication by a positive power of 2. // The newly shifted out area must be cleared. // In the context of little-endien byte order, picture data bytes as // laid out from right (offset zero, least signficant), traversing // to left (offset Size-1, most signficant). And picture the bits // within the bytes as bit 0 (LSB) on the right-hand side, traversing // bits horizontally to bit 7 (MSB) of the byte on the left-hand side. // In a big-endien system, bytes would be laid out pictorially in the // reverse order. // ShiftAmnt is now an amount of bits to be shift-left, ranging // from 0 to 7. if (ShiftBytes + DataLen) > FValue.Size then Overflow; P8 := ValuePntr( ShiftBytes); Idx := ShiftBytes; Move( FValue.Memory^, P8^, DataLen); ClearMem( 0, ShiftBytes); Inc( FBits, ShiftBytes * 8) end; Carry := 0; if ShiftBytes <= -1 then begin ShiftBytes := - ShiftBytes; // Here, we want to shift-right the value data by ShiftBytes. if ((ShiftBytes - 1) < DataLen) and (ShiftAmnt > 0) then begin // We shift-right a few bits too far, so save these bits // to be shift-lefted back in later. P8 := ValuePntr( ShiftBytes - 1); Carry := P8^ shr (8 - ShiftAmnt) end; if ShiftBytes < DataLen then begin P8 := ValuePntr( ShiftBytes); Idx := DataLen - ShiftBytes; Move( P8^, FValue.Memory^, Idx); ClearMem( Idx, ShiftBytes); Dec( FBits, ShiftBytes * 8); Dec( Remaining, ShiftBytes) end else begin ClearMem( 0, DataLen); FBits := 0; Remaining := 0 end; P8 := FValue.Memory; Idx := 0 end; if ShiftAmnt = 0 then exit; // Here, we want to shift-left the value data by ShiftAmnt bits, // where ShiftAmnt ranges from 1 to 7. while Remaining > 0 do begin if (Remaining >= 4) and isAligned32( P8) then begin P32 := pointer( P8); b32_1 := P32^ shr (32 - ShiftAmnt); b32_2 := Carry; Carry := LongRec( b32_1).Bytes[0]; b32_1 := P32^ shl ShiftAmnt; P32^ := b32_1 or b32_2; Inc( P8, 4); Dec( Remaining, 4); Inc( Idx, 4) end else begin b8_1 := P8^ shr (8 - ShiftAmnt); b8_2 := Carry; Carry := b8_1; b8_1 := P8^ shl ShiftAmnt; P8^ := b8_1 or b8_2; Inc( P8); Dec( Remaining); Dec( Idx) end; end; if Carry > 0 then // Here, we have shifted all the main data, but we have a few bits // of carry left over. begin if Idx < FValue.Size then P8^ := Carry else Overflow end; FBits := InitialBits + InitialShiftAmnt; if FBits < 0 then FBits := 0 end; procedure THugeCardinal.MulPower2_NewAlgorithm( ShiftAmnt: integer); var LogicalBitCount : integer; LogicalByteCount : integer; PhysicalByteCount: integer; ShiftBytesLeft, ShiftBitsLeft: integer; ShiftBytesRight, ShiftBitsRight: integer; // FinalByteIndex: integer; isLeftShift: boolean; Remaining: integer; P8: PByte; P32: ^uint32; Carry: byte; // ShiftBytes: integer; b8_1, b8_2: byte; b32_1, b32_2: uint32; ShiftComp8, ShiftComp32: integer; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_Power2) end; begin if (ShiftAmnt = 0) or isZero then exit; LogicalBitCount := BitLength; LogicalByteCount := (LogicalBitCount + 7) div 8; PhysicalByteCount := FValue.Size; if ShiftAmnt > 0 then begin ShiftBytesLeft := ShiftAmnt div 8; ShiftBitsLeft := ShiftAmnt mod 8; ShiftBitsRight := 0; // if (ShiftBitsLeft > 0) and ((ShiftBytesLeft + LogicalByteCount) < PhysicalByteCount) then // begin // Inc( ShiftBytesLeft); // ShiftBitsRight := 8 - ShiftBitsLeft; // ShiftBitsLeft := 0 // end; if (ShiftBytesLeft + LogicalByteCount) > PhysicalByteCount then Overflow; if ShiftBytesLeft > 0 then begin Move( FValue.Memory^, ValuePntr( ShiftBytesLeft)^, LogicalByteCount); ClearMem( 0, ShiftBytesLeft); Inc( FBits, ShiftBytesLeft * 8) end; end else begin ShiftAmnt := - ShiftAmnt; ShiftBytesRight := ShiftAmnt div 8; ShiftBitsRight := ShiftAmnt mod 8; ShiftBitsLeft := 0; if ShiftBytesRight >= LogicalByteCount then begin ClearMem( 0, LogicalByteCount); FBits := 0 end else if ShiftBytesRight > 0 then begin Move( ValuePntr( ShiftBytesRight)^, FValue.Memory^, LogicalByteCount - ShiftBytesRight); ClearMem( LogicalByteCount - ShiftBytesRight, ShiftBytesRight); Dec( FBits, ShiftBytesRight * 8) end; end; if ((ShiftBitsLeft + ShiftBitsRight) > 0) and (FBits > 0) then begin isLeftShift := ShiftBitsLeft > 0; Remaining := (FBits + 7) div 8; Carry := 0; if isLeftShift then ShiftAmnt := ShiftBitsLeft else ShiftAmnt := ShiftBitsRight; ShiftComp32 := 32 - ShiftAmnt; ShiftComp8 := 8 - ShiftAmnt; if isLeftShift then begin P8 := ValuePntr( 0); while Remaining > -1 do begin if (Remaining >= 4) and isAligned32( P8) then begin P32 := pointer( P8); b32_1 := P32^ shr ShiftComp32; b32_2 := Carry; Carry := LongRec( b32_1).Bytes[0]; b32_1 := P32^ shl ShiftAmnt; P32^ := b32_1 or b32_2; Inc( P8, 4); Dec( Remaining, 4) end else begin if Remaining > 0 then b8_1 := P8^ shr ShiftComp8 else b8_1 := 0; b8_2 := Carry; Carry := b8_1; b8_1 := P8^ shl ShiftAmnt; P8^ := b8_1 or b8_2; Inc( P8); Dec( Remaining) end end; Inc( FBits, ShiftBitsLeft) end else begin P8 := ValuePntr( Remaining - 1); while Remaining > 0 do begin {$if CompilerVersion >= 21.00} if (Remaining >= 4) and isAligned32( P8 - 3) then {$else} if (Remaining >= 4) and isAligned32( pointer( TrueNativeInt( P8) - 3)) then {$ifend} begin Dec( P8, 3); P32 := pointer( P8); b32_1 := P32^ shl ShiftComp32; b32_2 := 0; LongRec( b32_2).Bytes[3] := Carry; Carry := LongRec( b32_1).Bytes[3]; b32_1 := P32^ shr ShiftAmnt; P32^ := b32_1 or b32_2; Dec( P8); Dec( Remaining, 4) end else begin b8_1 := P8^ shl ShiftComp8; b8_2 := Carry; Carry := b8_1; b8_1 := P8^ shr ShiftAmnt; P8^ := b8_1 or b8_2; Dec( P8); Dec( Remaining) end end; Dec( FBits, ShiftBitsRight); if FBits < 0 then FBits := 0 end; end end; procedure THugeCardinal.MulSmall( Factor: uint32); var Done: boolean; PoweredFactor, Power, iFactor: integer; j: Integer; DataLen, Remaining: integer; P32: ^uint32; Carry, Factor1: uint32; Product: uint64; Idx: integer; FactorBytes: integer; LastBits: integer; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_MulSmallOverflow) end; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_MulSmall); {$ENDIF} if isZero then exit; Done := False; if Factor = 0 then begin Zeroise; Done := True end else if Factor = 1 then Done := True else begin iFactor := Factor; PoweredFactor := 1; for Power := 1 to 10 do begin PoweredFactor := PoweredFactor * 2; if PoweredFactor > iFactor then break; if PoweredFactor < iFactor then continue; MulPower2( Power); Done := True; break end end; if Done then exit; if (BitLength + BitCount_32( Factor) - 1) > MaxBits then Overflow; DataLen := (BitLength + 7) div 8; Remaining := DataLen; P32 := FValue.Memory; Idx := 0; Carry := 0; for j := 0 to (DataLen div 4) - 1 do begin Factor1 := P32^; Product := Factor1; // Widen. Product := Product * Factor + Carry; Factor1 := int64rec( Product).Lo; P32^ := Factor1; Carry := int64rec( Product).Hi; P32 := Offset( P32, 4); Dec( Remaining, 4); Inc( Idx, 4) end; Factor1 := 0; if Remaining > 0 then Move( P32^, Factor1, Remaining); Product := Factor1; // widen. Product := Product * Factor + Carry; if Product <> 0 then begin LastBits := BitCount_64( Product); FactorBytes := (LastBits + 7) div 8; if (Idx + FactorBytes) > FValue.Size then Overflow; Move( Product, P32^, FactorBytes) end; FBits := -1 end; function THugeCardinal.Multiply( Factor: THugeCardinal): THugeCardinal; var Addend: THugeCardinal; Factor2: uint32; j: integer; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( func_Multiply); {$ENDIF} result := THugeCardinal.CreateZero( BitLength + Factor.BitLength + 32, FPool); if isZero then exit; Addend := THugeCardinal.CreateZero( BitLength + Factor.BitLength + 32, FPool); try Factor.FValue.Position := 0; for j := 0 to ((Factor.BitLength + 31) div 32) - 1 do begin Factor2 := 0; Factor.FValue.Read( Factor2, 4); if Factor2 = 0 then continue; Addend.Assign( self); Addend.MulSmall( Factor2); Addend.MulPower2( j * 32); result.Add( Addend) end finally Addend.Free end end; procedure THugeCardinal.MultiplyMod( Factor, Modulus: THugeCardinal); begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_MultiplyMod); {$ENDIF} if doUseMultiplyMod_NewAlgorithm then MultiplyMod_New( Factor, Modulus) else MultiplyMod_Old( Factor, Modulus) end; procedure THugeCardinal.MultiplyMod_Old( Factor, Modulus: THugeCardinal); var Product, Remainder: THugeCardinal; begin Product := Multiply( Factor); try Remainder := Product.Modulo( Modulus); try Assign( Remainder) finally Remainder.Free end finally Product.Free end end; procedure THugeCardinal.MultiplyMod_New( Factor, Modulus: THugeCardinal); var Product{, Remainder}: THugeCardinal; Addend: THugeCardinal; Factor2: uint32; j: integer; LogicalByteCount, PhysicalByteCount, ShiftBytesLeft: integer; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_AddOverflow) end; procedure MakeProductModulo; var Remainder: THugeCardinal; begin Remainder := Product.Modulo( Modulus); try Product.Assign( Remainder) finally Remainder.Free end end; begin if isZero then exit; Product := THugeCardinal.CreateZero( BitLength + Factor.BitLength + 32, FPool); try Addend := THugeCardinal.CreateZero( BitLength + Factor.BitLength + 32, FPool); try Factor.FValue.Position := 0; for j := 0 to ((Factor.BitLength + 31) div 32) - 1 do begin Factor2 := 0; Factor.FValue.Read( Factor2, 4); if Factor2 = 0 then continue; Addend.Assign( self); Addend.MulSmall( Factor2); if j > 0 then with Addend do begin LogicalByteCount := (Addend.BitLength+ 7) div 8; PhysicalByteCount := Addend.FValue.Size; ShiftBytesLeft := j * 4; if (ShiftBytesLeft + LogicalByteCount) > PhysicalByteCount then Overflow; Move( Addend.FValue.Memory^, Addend.ValuePntr( ShiftBytesLeft)^, LogicalByteCount); Addend.ClearMem( 0, ShiftBytesLeft); Inc( Addend.FBits, ShiftBytesLeft * 8) end; Product.Add( Addend); // MakeProductModulo end finally Addend.Free end; MakeProductModulo; Assign( Product) finally Product.Free end end; function THugeCardinal.NewMemoryStream( InitBitSize: integer): TMemoryStream; var InitSize: integer; begin InitSize := InitBitSize div 8; if assigned( FPool) then result := FPool.NewMemoryStream( InitSize) else begin result := TMemoryStream.Create; if InitSize > 0 then result.Size := InitSize end end; procedure THugeCardinal.Resize( NewMaxBit1: integer); var NewMaxBits: integer; NewValue: TMemoryStream; DataBytesLen: integer; begin NewMaxBits := ComputedNeededSize( NewMaxBit1); if NewMaxBits = MaxBits then exit; if BitLength > NewMaxBits then raise Exception.Create( ES_HugeCardinal_ResizeOverflow); NewValue := NewMemoryStream( NewMaxBits); DataBytesLen := (BitLength + 7) div 8; if DataBytesLen > 0 then Move( FValue.Memory^, NewValue.Memory^, DataBytesLen); ClearMemory( NewValue, DataBytesLen, NewValue.Size - DataBytesLen); FValue.Free; FValue := NewValue end; procedure THugeCardinal.SquareMod( Modulus: THugeCardinal); var C: uint64; Remainder: THugeCardinal; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_SquareMod); {$ENDIF} if isZero then exit; if BitLength <= 32 then begin C := ExtractSmall; AssignSmall( C * C); Remainder := Modulo( Modulus); try Assign( Remainder) finally Remainder.Free end end else MultiplyMod( self, Modulus) end; procedure THugeCardinal.SmallExponent_Power( Exponent: uint32); var Odd1: boolean; Base, Product: THugeCardinal; RequiredBits: uint64; procedure Mult( Factor: THugeCardinal); begin Product := Multiply( Factor); try Assign( Product) finally FreeAndNil( Product) end end; begin // First, deal with special cases. if isZero then begin Assert( Exponent <> 0, AS_ZeroToZero); exit end; if Exponent = 0 then begin AssignSmall( 1); exit end; RequiredBits := cardinal( BitLength) * Exponent; if (RequiredBits < Exponent) or (RequiredBits > MaxBits) then raise Exception.Create( ES_HugeCardinal_PowerOverflow); // Russian Peasant Algorithm. Base := THugeCardinal.CreateZero( RequiredBits, FPool); try while Exponent >= 2 do begin Odd1 := Odd( Exponent); if Odd1 then Base.Assign( self); Exponent := Exponent shr 1; Mult( self); if Odd1 then Mult( Base) end finally Base.Free end end; procedure THugeCardinal.SmallExponent_PowerMod( Exponent: uint64; Modulus: THugeCardinal); var Base, Factor: THugeCardinal; begin // First, deal with special cases. if isZero then exit; if Exponent = 0 then begin AssignSmall( 1); exit end; // Russian Peasant Algorithm. Factor := nil; try if Compare( Modulus) <> rLessThan then begin Base := Modulo( Modulus); try Assign( Base) finally Base.Free end end; Base := THugeCardinal.CreateZero( Modulus.BitLength, FPool); try while Exponent >= 2 do begin if Odd( int64Rec( Exponent).Lo) then begin if not assigned( Factor) then Factor := CloneSized( Modulus.BitLength) else Factor.MultiplyMod( self, Modulus) end; Exponent := Exponent shr 1; SquareMod( Modulus) end finally Base.Free end; if assigned( Factor) then MultiplyMod( Factor, Modulus) finally Factor.Free end end; function THugeCardinal.PowerMod( Exponent, Modulus: THugeCardinal; OnProgress: TProgress): boolean; var Base: THugeCardinal; Expo: THugeCardinal; Factor: THugeCardinal; BitsProcessed, TotalBits: int64; doAbort: boolean; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( func_PowerMod); {$ENDIF} Factor := nil; try if not Exponent.isSmall then begin doAbort := False; // Russian Peasant Algorithm. if Compare( Modulus) <> rLessThan then begin Base := Modulo( Modulus); try Assign( Base) finally Base.Free; end end; Base := THugeCardinal.CreateZero( Modulus.BitLength, FPool); Expo := Exponent.CloneSized( Exponent.BitLength); TotalBits := Exponent.BitLength; try while (not Expo.isSmall) and (not doAbort) do begin if Expo.isOdd then begin if not assigned( Factor) then Factor := CloneSized( Modulus.BitLength) else Factor.MultiplyMod( self, Modulus) end; Expo.MulPower2( -1); SquareMod( Modulus); if assigned( OnProgress) then begin BitsProcessed := TotalBits - Expo.BitLength; OnProgress( self, BitsProcessed, TotalBits, doAbort) end end; if not doAbort then SmallExponent_PowerMod( Expo.ExtractSmall, Modulus) finally Base.Free; Expo.Free end end else SmallExponent_PowerMod( Exponent.ExtractSmall, Modulus); result := not doAbort; if result and assigned( Factor) then MultiplyMod( Factor, Modulus) finally Factor.Free end end; function THugeCardinal.PowerMod_WithChineseRemainderAlgorithm( Exponent, // d Modulus: THugeCardinal; // n := p * q FactorP, // p FactorQ, // q ExponentModFactorP, // dp := d mod p-1 ExponentModFactorQ, // dq := d mod q-1 InverseQ : THugeCardinal; // qinv := q ** -1 mod p OnProgress: TProgress ): boolean; // result := self ** d mod n var x2, CRT_Result: THugeCardinal; begin if (not assigned( FactorP)) or (not assigned( FactorQ)) then result := PowerMod( Exponent, Modulus, OnProgress) else begin // With CRT, we can short-cut ... // x := y ** d mod n // as ... // x1 := y ** dp mod p // x2 := y ** dq mod q // if x1 >= x2: // h := qinv * (x1 - x2) mod p // else: // h := qinv * (x1 + p - x2) mod p // x := x2 + h * q x2 := Clone; try result := PowerMod( ExponentModFactorP, FactorP, OnProgress) and x2.PowerMod( ExponentModFactorQ, FactorQ, OnProgress); if result then begin if Compare( x2) = rLessThan then Add( FactorP); Subtract( x2); MultiplyMod( InverseQ, FactorP); CRT_Result := Multiply( FactorQ); CRT_Result.Add( x2); Assign( CRT_Result); CRT_Result.Free end; finally x2.Free end end end; procedure THugeCardinal.Subtract( Subtractend: THugeCardinal); var P1, P2: PByte; Borrow: boolean; Bytes, j, Idx: integer; V1, V2, V3: uint64; SubBytes, D2: integer; procedure Overflow; begin FBits := -1; raise Exception.Create( ES_HugeCardinal_SubractOverflow) end; begin {$IFDEF profiling} if doProfiling then EnterProfileSection( proc_Subtract); {$ENDIF} Bytes := (BitLength + 7) div 8; SubBytes := (Subtractend.BitLength + 7) div 8; if SubBytes > Bytes then Overflow; P1 := FValue.Memory; P2 := Subtractend.FValue.Memory; Borrow := False; Idx := 0; D2 := Subtractend.FValue.Size; FBits := -1; for j := 0 to (Bytes div 8) - 1 do begin V1 := Puint64( P1)^; V2 := 0; if D2 > 0 then Move( P2^, V2, Min( D2, 8)); if (V2 = 0) and (not Borrow) and (Idx >= SubBytes) then exit; V3 := Subtract_uint64_WithBorrow( V1, V2, Borrow); Puint64( P1)^ := V3; Inc( P1, 8); Inc( P2, 8); Inc( Idx, 8); Dec( D2, 8) end; if (Bytes mod 8) <> 0 then begin V1 := 0; Move( P1^, V1, bytes mod 8); V2 := 0; if D2 > 0 then Move( P2^, V2, Min( D2, 8)); V3 := Subtract_uint64_WithBorrow( V1, V2, Borrow); Move( V3, P1^, bytes mod 8) end; if Borrow then Overflow end; procedure THugeCardinal.Swap( Peer: THugeCardinal); var TempMaxBits: integer; TempBits: integer; TempValue: TMemoryStream; begin TempMaxBits := FMaxBits; TempBits := FBits; TempValue := FValue; FMaxBits := Peer.FMaxBits; FBits := Peer.FBits; FValue := Peer.FValue; Peer.FMaxBits := TempMaxBits; Peer.FBits := TempBits; Peer.FValue := TempValue end; function THugeCardinal.ValuePntr( ByteIndex: integer): PByte; begin result := MemStrmOffset( FValue, ByteIndex) end; procedure THugeCardinal.Zeroise; begin CheckBits; if isZero then exit; ClearMem( 0, (FBits + 7) div 8); FBits := 0 end; procedure THugeCardinal.StreamOut( ByteOrder: TByteOrder; Stream: TStream; SizeToOutput: integer = -1); // ^ Streams the low order SizeToOutput bytes out to the stream. // If SizeToOutput is -1, then this is interpreted as (MaxBits + 7) div 8 var P8: PByte; PayloadByte, ZeroByte: byte; j: integer; ZeroFillCount: integer; MaxBytes: cardinal; MSB_Index: cardinal; begin // MaxBytes = (MaxBits = 7) div 8 = N; // Case 1: Little-endien; MaxBytes > SizeToOutput // FValue = X[0](=LSB) X[1] ... X[N-1](=MSB) // Stream := X[0] .. X[SizeToOutput-1] // If any discarded data (X[SizeToOutput]..X[N-1]) is non-zero, this is an error. // Case 2: Little-endien; MaxBytes < SizeToOutput // FValue = X[0](=LSB) X[1] ... X[N](=MSB) // Stream := X[0] .. X[N-1] 0 0 0 0 (0 is repeated SizeToOutput - MaxBytes times). // Case 3: Big-endien; MaxBytes > SizeToOutput // FValue = X[0](=LSB) X[1] ... X[N-1](=MSB) // Stream := X[SizeToOutput-1] .. X[1] X[0] // If any discarded data (X[SizeToOutput]..X[N-1]) is non-zero, this is an error. // Case 4: Big-endien; MaxBytes < SizeToOutput // FValue = X[0](=LSB) X[1] ... X[N](=MSB) // Stream := 0 0 0 0 X[N-1] .. X[0] (At the start, 0 is repeated SizeToOutput - MaxBytes times). MaxBytes := FValue.Size; if SizeToOutput < 0 then SizeToOutput := MaxBytes; // = (MaxBits + 7) div 8 if SizeToOutput = 0 then exit; ZeroFillCount := SizeToOutput - integer( MaxBytes); if SizeToOutput < ((BitLength + 7) div 8) then raise Exception.Create( ES_HugeCardinal_StreamOutOverflow); ZeroByte := 0; MSB_Index := Min( SizeToOutput, MaxBytes); case ByteOrder of LittleEndien: begin Stream.Write( FValue.Memory^, MSB_Index); for j := 0 to ZeroFillCount - 1 do Stream.Write( ZeroByte, 1) end; BigEndien: begin for j := 0 to ZeroFillCount - 1 do Stream.Write( ZeroByte, 1); P8 := ValuePntr( MSB_Index - 1); for j := MSB_Index - 1 downto 0 do begin PayloadByte := P8^; Stream.Write( PayloadByte, 1); Dec( P8) end end end end; procedure THugeCardinal.AssignFromStreamIn( ByteOrder: TByteOrder; Stream: TStream); var P8: PByte; PayloadByte: byte; j: integer; SourceLen, MaxBytes, MSB_Index, ZeroFillCount: integer; procedure CheckDiscardedData; var Ok: boolean; jj: integer; begin if ZeroFillCount >= 0 then exit; // if dont check then do the following instead. // if ZeroFillCount < 0 then // Stream.Seek( -ZeroFillCount, soCurrent); Ok := True; for jj := 0 to (-ZeroFillCount) - 1 do begin Stream.Read( PayloadByte, 1); Ok := PayloadByte = 0; if Ok then continue; Stream.Seek( (-ZeroFillCount) - jj - 1, soCurrent); break end; if not Ok then raise Exception.Create( ES_HugeCardinal_StreamInOverflow) end; begin // MaxBytes = Stream.Size = N; // SizeToInput = Stream.Size - Stream.Position; // Case 1: Little-endien; MaxBytes > SizeToInput // Stream = X[0] .. X[SizeToInput-1] // FValue := X[0](=LSB) X[1] ... X[SizeToInput-1](=MSB) 0 0 0 0 (0 is repeated MaxBytes - SizeToInput times). // Case 2: Little-endien; MaxBytes < SizeToInput // Stream = X[0] .. X[N-1] X[N] X[SizeToInput-1] // ^-------------------^ All this discarded. // FValue := X[0] .. X[N-1] // If any discarded data (X[N]..X[SizeToInput-1]) is non-zero, this is an error. // Case 3: Big-endien; MaxBytes > SizeToInput // Stream = X[SizeToInput-1] .. X[1] X[0] // FValue := X[0](=LSB) X[1] ... X[SizeToInput-1] 0 0 0 0 (0 is repeated MaxBytes - SizeToInput times). // Case 4: Big-endien; MaxBytes < SizeToInput // Stream = X[SizeToInput-1] .. X[N] X[N-1] .. X[0] // ^---------------------^ All this discarded. // FValue := X[0](=LSB) X[1] ... X[N-1](=MSB) // If any discarded data (X[SizeToInput-1]..X[N]) is non-zero, this is an error. SourceLen := Stream.Size - Stream.Position; MaxBytes := FValue.Size; MSB_Index := Min( SourceLen, MaxBytes); ZeroFillCount := MaxBytes - SourceLen; Case ByteOrder of LittleEndien: begin if MSB_Index > 0 then Stream.Read( FValue.Memory^, MSB_Index); if ZeroFillCount > 0 then ClearMemory( FValue, MSB_Index, ZeroFillCount); // case 1 zeros CheckDiscardedData // case 2 discard end; BigEndien: begin CheckDiscardedData; // case 4 discard P8 := ValuePntr( MSB_Index - 1); for j := MSB_Index - 1 downto 0 do begin Stream.Read( PayloadByte, 1); P8^ := PayloadByte; Dec( P8) end; if ZeroFillCount > 0 then ClearMemory( FValue, MSB_Index, ZeroFillCount) // case 3 zeros end end; FBits := -1 end; function THugeCardinal.CapacityInBits: integer; begin result := FValue.Size * 8 end; initialization InitExecutionTimes; finalization DoneExecutionTimes; end.
{===================================================================================== Copyright (C) combit GmbH -------------------------------------------------------------------------------------- File : viewer.pas, viewer.dfm, Llviewer.dpr Module : List & Label Viewer example Descr. : D: Dieses Beispiel demonstriert die Verwendung des Preview-Controls US: This example demonstrates the usage of the preview control ======================================================================================} unit viewer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, Menus, L28, cmbtll28, Registry; type TViewForm = class(TForm) OpenDialog: TOpenDialog; MainMenu: TMainMenu; File1: TMenuItem; Open1: TMenuItem; Exit1: TMenuItem; View1: TMenuItem; FirstPage1: TMenuItem; PreviousPage1: TMenuItem; NextPage1: TMenuItem; LastPage1: TMenuItem; N1: TMenuItem; Zoomin1: TMenuItem; Zoomout1: TMenuItem; FittoPage1: TMenuItem; Saveas1: TMenuItem; N2: TMenuItem; Print1: TMenuItem; CurrentPage1: TMenuItem; MultiplePages1: TMenuItem; LlViewer: TLL28PreviewControl; procedure FormCreate(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure FormResize(Sender: TObject); procedure FirstPage1Click(Sender: TObject); procedure PreviousPage1Click(Sender: TObject); procedure NextPage1Click(Sender: TObject); procedure LastPage1Click(Sender: TObject); procedure Zoomin1Click(Sender: TObject); procedure Zoomout1Click(Sender: TObject); procedure FittoPage1Click(Sender: TObject); procedure Saveas1Click(Sender: TObject); procedure CurrentPage1Click(Sender: TObject); procedure MultiplePages1Click(Sender: TObject); procedure LlViewerPageChanged(Sender: TObject; NewPageIndex: Integer); private { Private declarations } public { Public declarations } end; var ViewForm: TViewForm; implementation {$R *.DFM} procedure TViewForm.FormCreate(Sender: TObject); var registry: TRegistry; var regKeyPath: String; var tmp: String; begin // D: Datenbankpfad auslesen // US: Read database path registry := TRegistry.Create(); registry.RootKey := HKEY_CURRENT_USER; regKeyPath := 'Software\combit\cmbtll\'; if registry.KeyExists(regKeyPath) then begin if registry.OpenKeyReadOnly(regKeyPath) then begin // cmbtll28 tmp := registry.ReadString('LL28SampleDir'); if (tmp[Length(tmp)] = '\') then begin tmp := tmp + 'Delphi\BDE (Legacy)\Samples\Viewer Example\'; end else tmp := tmp + '\Delphi\BDE (Legacy)\Samples\Viewer Example\'; registry.CloseKey(); end; end; registry.Free(); LlViewer.InputFileName := tmp + 'invoice.ll'; end; procedure TViewForm.Open1Click(Sender: TObject); begin if OpenDialog.execute then LlViewer.InputFileName:=OpenDialog.FileName; end; procedure TViewForm.Exit1Click(Sender: TObject); begin ViewForm.close; end; procedure TViewForm.FormResize(Sender: TObject); begin LlViewer.Height:=ViewForm.ClientHeight; LlViewer.Width:=ViewForm.ClientWidth; end; procedure TViewForm.FirstPage1Click(Sender: TObject); begin LlViewer.GotoFirst; end; procedure TViewForm.PreviousPage1Click(Sender: TObject); begin LlViewer.GotoPrevious; end; procedure TViewForm.NextPage1Click(Sender: TObject); begin LlViewer.GotoNext; end; procedure TViewForm.LastPage1Click(Sender: TObject); begin LlViewer.GotoLast; end; procedure TViewForm.Zoomin1Click(Sender: TObject); begin LlViewer.ZoomTimes2; end; procedure TViewForm.Zoomout1Click(Sender: TObject); begin LlViewer.ZoomRevert; end; procedure TViewForm.FittoPage1Click(Sender: TObject); begin LlViewer.ZoomReset; end; procedure TViewForm.Saveas1Click(Sender: TObject); begin LlViewer.SaveAs; end; procedure TViewForm.CurrentPage1Click(Sender: TObject); begin Llviewer.PrintCurrentPage(true); end; procedure TViewForm.MultiplePages1Click(Sender: TObject); begin Llviewer.PrintAllPages(true); end; procedure TViewForm.LlViewerPageChanged(Sender: TObject; NewPageIndex: Integer); begin FirstPage1.enabled:=true; PreviousPage1.enabled:=true; LastPage1.enabled:=true; NextPage1.enabled:=true; If NewPageIndex = 0 then begin FirstPage1.enabled:=false; PreviousPage1.enabled:=false; end; If NewPageIndex = Llviewer.PageCount-1 then begin LastPage1.enabled:=false; NextPage1.enabled:=false; end; end; end.
unit UnitServerSettings; interface uses StrUtils,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UnitMain, ComCtrls, ExtCtrls, UnitConexao; type TFormServerSettings = class(TForm) StatusBar1: TStatusBar; bsSkinPanel1: TPanel; AdvListView1: TListView; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } Servidor: TConexaoNew; LiberarForm: boolean; procedure AtualizarIdioma; procedure InserirSettings(Settings: string); procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA; procedure WMCloseFree(var Message: TMessage); message WM_CLOSEFREE; procedure CreateParams(var Params : TCreateParams); override; public { Public declarations } procedure OnRead(Recebido: String; ConAux: TConexaoNew); overload; constructor Create(aOwner: TComponent; ConAux: TConexaoNew); overload; end; var FormServerSettings: TFormServerSettings; implementation {$R *.dfm} uses UnitConstantes, UnitStrings, UnitConfigs, UnitCommonProcedures; //procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA; procedure TFormServerSettings.WMAtualizarIdioma(var Message: TMessage); begin AtualizarIdioma; end; procedure TFormServerSettings.WMCloseFree(var Message: TMessage); begin LiberarForm := True; Close; end; //Here's the implementation of CreateParams procedure TFormServerSettings.CreateParams(var Params : TCreateParams); begin inherited CreateParams(Params); //Don't ever forget to do this!!! if FormMain.ControlCenter = True then Exit; Params.WndParent := GetDesktopWindow; end; procedure TFormServerSettings.AtualizarIdioma; begin AdvListView1.Groups.Items[0].Header := Traduzidos[24]; AdvListView1.Groups.Items[1].Header := Traduzidos[89]; AdvListView1.Groups.Items[2].Header := Traduzidos[252]; AdvListView1.Column[0].Caption := Traduzidos[20]; AdvListView1.Column[1].Caption := Traduzidos[526]; end; constructor TFormServerSettings.Create(aOwner: TComponent; ConAux: TConexaoNew); begin inherited Create(aOwner); Servidor := ConAux; end; type SArray = array of string; function Split(const Source, Delimiter: String): SArray; var iCount,iPos,iLength: Integer; sTemp: String; aSplit:SArray; begin sTemp := Source; iCount := 0; iLength := Length(Delimiter) - 1; repeat iPos := posex(Delimiter, sTemp); if iPos = 0 then break else begin Inc(iCount); SetLength(aSplit, iCount); aSplit[iCount - 1] := Copy(sTemp, 1, iPos - 1); Delete(sTemp, 1, iPos + iLength); end; until False; if Length(sTemp) > 0 then begin Inc(iCount); SetLength(aSplit, iCount); aSplit[iCount - 1] := sTemp; end; Result := aSplit; end; function BoolToStr(Bool: boolean): string; begin Result := Traduzidos[95]; if Bool = false then Result := Traduzidos[96]; end; function StrToBool(Str: string): boolean; begin if Str = 'TRUE' then result := true else result := false; end; procedure TFormServerSettings.InserirSettings(Settings: string); var Ports: array [0..high(ConfiguracoesServidor.Ports)] of integer; DNS: array [0..high(ConfiguracoesServidor.Ports)] of string; Password: int64; ServerID: string; GroupID: string; CopyServer: boolean; ServerFileName: string; ServerFolder: string; SelectedDir: integer; Melt: boolean; InjectProcess: string; HideServer: boolean; Restart: boolean; HKLMRun: string; HKCURun: string; ActiveX: string; HKLMRunBool: boolean; HKCURunBool: boolean; ActiveXBool: boolean; Persistencia: boolean; Mutex: string; ActiveKeylogger: boolean; USBSpreader: boolean; KeyDelBackspace: boolean; SendFTPLogs: boolean; RecordWords: xArray; FTPAddress: xArray; FTPFolder: xArray; FTPUser: xArray; FTPPass: xArray; FTPFreq: integer; FTPDelLogs: boolean; I: Integer; InstalledServer: string; ProcessoAtual: string; VersaoDoPrograma: string; Item: TListItem; TempStr: string; ServerStarted: string; Config: TConfiguracoes; begin if AdvListView1.Items.Count > 0 then AdvListView1.Items.Clear; CopyMemory(@Config, @Settings[1], SizeOf(TConfiguracoes)); Delete(Settings, 1, SizeOf(TConfiguracoes)); for i := 0 to NUMMAXCONNECTION - 1 do begin DNS[i] := Config.DNS[i]; Ports[i] := Config.Ports[i]; end; Password := Config.Password; ServerID := Config.ServerID; GroupID := Config.GroupID; CopyServer := Config.CopyServer; ServerFileName := Config.ServerFileName; ServerFolder := Config.ServerFolder; SelectedDir := Config.SelectedDir; Melt := Config.Melt; HideServer := Config.HideServer; InjectProcess := Config.InjectProcess; Restart := Config.Restart; HKLMRun := Config.HKLMRun; HKCURun := Config.HKCURun; ActiveX := Config.ActiveX; HKLMRunBool := Config.HKLMRunBool; HKCURunBool := Config.HKCURunBool; ActiveXBool := Config.ActiveXBool; VersaoDoPrograma := Config.Versao; Persistencia := Config.Persistencia; Mutex := Config.Mutex; ActiveKeylogger := Config.ActiveKeylogger; USBSpreader := Config.USBSpreader; KeyDelBackspace := Config.KeyDelBackspace; RecordWords := Config.RecordWords; SendFTPLogs := Config.SendFTPLogs; FTPAddress := Config.FTPAddress; FTPFolder := Config.FTPFolder; FTPUser := Config.FTPUser; FTPPass := Config.FTPPass; FTPFreq := Config.FTPFreq; FTPDelLogs := Config.FTPDelLogs; InstalledServer := Copy(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, length(DelimitadorComandos)); ProcessoAtual := Copy(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, length(DelimitadorComandos)); ServerStarted := Copy(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, posex(DelimitadorComandos, Settings) - 1); Delete(Settings, 1, length(DelimitadorComandos)); AdvListView1.Items.BeginUpdate; for i := 0 to high(ConfiguracoesServidor.Ports) do if (DNS[i] <> '') and (Ports[i] <> 0) then begin Item := AdvListView1.Items.Add; Item.GroupID := 0; Item.ImageIndex := -1; Item.Caption := Traduzidos[527] + '[' + inttostr(i) + ']'; Item.SubItems.Add(DNS[i] + ':' + IntToStr(Ports[i])); end; Item := AdvListView1.Items.Add; Item.GroupID := 0; Item.ImageIndex := -1; Item.Caption := Traduzidos[45]; Item.SubItems.Add({ServerID} Servidor.NomeDoServidor); Item := AdvListView1.Items.Add; Item.GroupID := 0; Item.ImageIndex := -1; Item.Caption := Traduzidos[46]; Item.SubItems.Add({GroupID} Servidor.GroupName); if CopyServer = True then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[48]; Item.SubItems.Add(BoolToStr(CopyServer)); if SelectedDir = 0 then TempStr := '%Windows%\' else if SelectedDir = 1 then TempStr := '%System%\' else if SelectedDir = 2 then TempStr := '%Root%\' else if SelectedDir = 3 then TempStr := Traduzidos[91] + '\' else if SelectedDir = 4 then TempStr := '%AppData%\' else if SelectedDir = 5 then TempStr := '%Temp%\'; Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[51]; Item.SubItems.Add(TempStr + ServerFolder); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[49]; Item.SubItems.Add(ServerFileName); end else begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[48]; Item.SubItems.Add(BoolToStr(CopyServer)); end; Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[52]; Item.SubItems.Add(BoolToStr(Melt)); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[56]; Item.SubItems.Add(BoolToStr(HideServer)); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[66]; Item.SubItems.Add(BoolToStr(ActiveKeylogger)); if ActiveKeylogger then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[91]; Item.SubItems.Add(RecordWords); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[67]; Item.SubItems.Add(BoolToStr(KeyDelBackspace)); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[68]; Item.SubItems.Add(BoolToStr(SendFTPLogs)); if SendFTPLogs then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[69]; Item.SubItems.Add(FTPAddress); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[71]; Item.SubItems.Add(FTPFolder); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[70]; Item.SubItems.Add(FTPUser); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[73]; Item.SubItems.Add(IntToStr((FTPFreq * 5) + 5) + ' ' + Traduzidos[74]); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[92]; Item.SubItems.Add(BoolToStr(FTPDelLogs)); end; end; Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[54]; Item.SubItems.Add(InjectProcess); if Restart = True then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[94]; Item.SubItems.Add(BoolToStr(Restart)); if HKLMRunBool = true then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := 'HKLM\Run'; Item.SubItems.Add(HKLMRun); end; if HKCURunBool = true then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := 'HKCU\Run'; Item.SubItems.Add(HKCURun); end; if ActiveXBool = true then begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := 'ActiveX'; Item.SubItems.Add(ActiveX); end; end else begin Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[94]; Item.SubItems.Add(BoolToStr(Restart)); end; Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[13]; Item.SubItems.Add(VersaoDoPrograma); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[55]; Item.SubItems.Add(BoolToStr(Persistencia)); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := Traduzidos[57]; Item.SubItems.Add(BoolToStr(USBSpreader)); Item := AdvListView1.Items.Add; Item.GroupID := 1; Item.ImageIndex := -1; Item.Caption := 'Mutex'; Item.SubItems.Add(Mutex); Item := AdvListView1.Items.Add; Item.GroupID := 2; Item.ImageIndex := -1; Item.Caption := traduzidos[528]; Item.SubItems.Add(InstalledServer); Item := AdvListView1.Items.Add; Item.GroupID := 2; Item.ImageIndex := -1; Item.Caption := traduzidos[529]; Item.SubItems.Add(ProcessoAtual); Item := AdvListView1.Items.Add; Item.GroupID := 2; Item.ImageIndex := -1; Item.Caption := traduzidos[530]; Item.SubItems.Add(ServerStarted); AdvListView1.Items.EndUpdate; StatusBar1.Panels.Items[0].Text := Traduzidos[373]; end; procedure TFormServerSettings.FormClose(Sender: TObject; var Action: TCloseAction); begin if LiberarForm then Action := caFree; end; procedure TFormServerSettings.FormCreate(Sender: TObject); var LG: TListGroup; begin Self.Left := (screen.width - Self.width) div 2 ; Self.top := (screen.height - Self.height) div 2; if AdvListView1.Items.Count > 0 then AdvListView1.Items.Clear; LiberarForm := False; AdvListView1.GroupView := True; LG := AdvListView1.Groups.Add; LG.Header := 'Conexão'; LG.TitleImage := 101; LG.State := [lgsNormal]; LG.HeaderAlign := taLeftJustify; LG.FooterAlign := taLeftJustify; LG := AdvListView1.Groups.Add; LG.Header := 'Instalação'; LG.TitleImage := 69; LG.State := [lgsNormal]; LG.HeaderAlign := taLeftJustify; LG.FooterAlign := taLeftJustify; LG := AdvListView1.Groups.Add; LG.Header := 'Estado atual'; LG.TitleImage := 77; LG.State := [lgsNormal]; LG.HeaderAlign := taLeftJustify; LG.FooterAlign := taLeftJustify; AdvListView1.GroupHeaderImages := FormMain.ImageListDiversos; end; procedure TFormServerSettings.FormShow(Sender: TObject); var i: integer; Item: TListItem; begin AtualizarIdioma; if AdvListView1.Items.Count > 0 then AdvListView1.Items.Clear; Servidor.EnviarString(GETSERVERSETTINGS + '|'); StatusBar1.Panels.Items[0].Text := Traduzidos[205]; end; procedure TFormServerSettings.OnRead(Recebido: String; ConAux: TConexaoNew); var i: integer; Tempstr: string; Item: TListItem; begin if Copy(Recebido, 1, posex('|', Recebido) - 1) = GETSERVERSETTINGS then begin delete(Recebido, 1, posex('|', Recebido)); InserirSettings(Recebido); end else end; end.
unit ufrmDialogRekening; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, uConn, StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxMaskEdit, cxButtonEdit, cxTextEdit, cxCurrencyEdit, uClientClasses, uModRekening, uDMClient, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, uDbutils, DBClient, Vcl.Samples.Spin, cxSpinEdit, ufraFooterDialog3Button, System.Actions, Vcl.ActnList, uInterface; type TStatusForm = (frNew, frEdit); TfrmDialogRekening = class(TfrmMasterDialog, iCrudable) lbl1: TLabel; lbl2: TLabel; lbl4: TLabel; lbl5: TLabel; chkIsDebet: TCheckBox; chkIsLeaf: TCheckBox; edtRekCode: TEdit; edtRekName: TEdit; edtDescription: TEdit; lbl6: TLabel; lblGroup: TLabel; chkbs: TRadioButton; chkpl: TRadioButton; dbParentCode: TcxExtLookupComboBox; dbAccountGroup: TcxExtLookupComboBox; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtRekCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtRekNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure intedtLevelKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtDescriptionKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure chkIsDebetKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edbParentCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edbParentCodeClickBtn(Sender: TObject); procedure dbAccountGroupKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbParentCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure chkplKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure chkbsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure intedtLevelPropertiesEditValueChanged(Sender: TObject); private FCDS: TClientDataSet; FCDSRekening: tclientDataset; FCDSRekeningGroup: tclientDataset; FCrud: TCrudClient; FDsProvider: TDSProviderClient; FFormMode: TFormMode; FIsProcessSuccesfull: Boolean; FStatusForm: TStatusForm; FKodeGrupRekId: Integer; FModRekening: TModRekening; FRekCode: string; FParentCode: string; function ChekEmptyValue: Boolean; function GetCDSRekening: tclientDataset; function GetCDSRekeningGroup: tclientDataset; function GetCrud: TCrudClient; function GetDsProvider: TDSProviderClient; function GetModRekening: TModRekening; // function SaveDataRekening: Boolean; // function UpdateDataRekening: Boolean; procedure ParseDataRekening; procedure ParseComboGrupRekening; procedure SetFormMode(const Value: TFormMode); procedure SetIsProcessSuccesfull(const Value: Boolean); procedure SetStatusForm(const Value: TStatusForm); procedure SetKodeGrupRekId(const Value: Integer); procedure SetRekCode(const Value: string); procedure SetParentCode(const Value: string); procedure SimpanData; property CDSRekening: tclientDataset read GetCDSRekening write FCDSRekening; property CDSRekeningGroup: tclientDataset read GetCDSRekeningGroup write FCDSRekeningGroup; property Crud: TCrudClient read GetCrud write FCrud; property DsProvider: TDSProviderClient read GetDsProvider write FDsProvider; property ModRekening: TModRekening read GetModRekening write FModRekening; public procedure LoadData(ID: String); property IsProcessSuccesfull: Boolean read FIsProcessSuccesfull write SetIsProcessSuccesfull; property StatusForm: TStatusForm read FStatusForm write SetStatusForm; property KodeGrupRekId: Integer read FKodeGrupRekId write SetKodeGrupRekId; property RekCode: string read FRekCode write SetRekCode; property ParentCode: string read FParentCode write SetParentCode; published property FormMode: TFormMode read FFormMode write SetFormMode; end; var frmDialogRekening: TfrmDialogRekening; implementation uses uConstanta, uTSCommonDlg, uRetnoUnit, DB, StrUtils, uAppUtils, uDXUtils, ufrmProductType; {$R *.dfm} procedure TfrmDialogRekening.actDeleteExecute(Sender: TObject); begin inherited; if not TAppUtils.ConfirmHapus then Exit; Try DMClient.CrudClient.DeleteFromDB(ModRekening); Self.ModalResult := mrOK; TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); Except TAppUtils.Error(ER_DELETE_FAILED); Raise End; Self.Close; end; procedure TfrmDialogRekening.actSaveExecute(Sender: TObject); begin inherited; SimpanData(); end; procedure TfrmDialogRekening.FormCreate(Sender: TObject); begin inherited; dbParentCode.Properties.LoadFromCDS(CDSRekening,'REKENING_ID', 'REK_NAME', ['REKENING_ID', 'REK_LEVEL'] , self); dbParentCode.Properties.SetMultiPurposeLookup; dbAccountGroup.Properties.LoadFromCDS(CDSRekeningGroup,'REF$GRUP_REKENING_ID', 'GROREK_NAME', ['REF$GRUP_REKENING_ID'] , self); dbAccountGroup.Properties.SetMultiPurposeLookup; intedtLevelPropertiesEditValueChanged(Self); self.ClearByTag([0]); end; procedure TfrmDialogRekening.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogRekening.FormDestroy(Sender: TObject); begin inherited; frmDialogRekening := nil; frmDialogRekening.Free; end; procedure TfrmDialogRekening.ParseComboGrupRekening; var s : string; begin s := 'SELECT GROREK_ID, GROREK_NAME FROM REF$GRUP_REKENING' + ' WHERE GROREK_COMP_ID = ' + IntToStr(DialogCompany); // cQueryToComboObject(cmbAccountType, s); end; procedure TfrmDialogRekening.ParseDataRekening; //var // FRekening: TMasterRekening; begin {FRekening := TMasterRekening.Create(nil); try Self.Enabled := False; if FRekening.LoadByKode(RekCode, DialogCompany) then begin edtRekCode.Text := FRekening.REK_CODE; edtRekName.Text := FRekening.REK_NAME; intedtLevel.Value := FRekening.REK_LEVEL; edtDescription.Text := FRekening.REK_DESCRIPTION; cSetItemAtComboObject(cmbAccountType, FRekening.REK_GROREK_ID); edbParentCode.Text := FRekening.REK_PARENT_CODE; if FRekening.REK_IS_DEBET = 0 then chkIsDebet.Checked := False else chkIsDebet.Checked := True; if FRekening.REK_IS_LEAF = 0 then chkIsLeaf.Checked := False else chkIsLeaf.Checked := True; if FRekening.REK_IS_GROUP = 1 then chkBS.Checked := True else if FRekening.REK_IS_GROUP = 2 then chkPL.Checked := True else begin chkbs.Checked := False; chkpl.Checked := False; end; end; finally if FRekening <> nil then FreeAndNil(FRekening); Self.Enabled := True; end; } end; procedure TfrmDialogRekening.SetIsProcessSuccesfull(const Value: Boolean); begin FIsProcessSuccesfull := Value; end; procedure TfrmDialogRekening.SetKodeGrupRekId(const Value: Integer); begin FKodeGrupRekId := Value; end; procedure TfrmDialogRekening.SetRekCode(const Value: string); begin FRekCode := Value; end; procedure TfrmDialogRekening.SetStatusForm(const Value: TStatusForm); begin FStatusForm := Value; end; procedure TfrmDialogRekening.FormShow(Sender: TObject); begin inherited; ParseComboGrupRekening; case StatusForm of frNew: begin RekCode := ''; edtRekCode.SetFocus; end; frEdit: begin ParseDataRekening; edtRekName.SetFocus; end; end; end; procedure TfrmDialogRekening.edtRekCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) and (edtRekCode.Text <> '') then edtRekName.SetFocus; end; procedure TfrmDialogRekening.edtRekNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) and (edtRekName.Text <> '') then edtDescription.SetFocus; end; procedure TfrmDialogRekening.intedtLevelKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then begin edtDescription.SetFocus; end; end; procedure TfrmDialogRekening.intedtLevelPropertiesEditValueChanged( Sender: TObject); var lDS: TClientDataSet; begin inherited; // FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.Rekening_GetDSLookupLvl(intedtLevel.Value), Self); // dbParentCode.Properties.LoadFromCDS(FCDS,'REKENING_ID', 'REK_NAME', ['REKENING_ID', 'REK_LEVEL'] , self); lDS := dbParentCode.CDS; if not Assigned(lDS) then exit; end; procedure TfrmDialogRekening.edtDescriptionKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) and (edtDescription.Text <> '') then dbAccountGroup.SetFocus; end; procedure TfrmDialogRekening.chkbsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then chkIsDebet.SetFocus; end; procedure TfrmDialogRekening.chkIsDebetKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then chkIsLeaf.SetFocus; end; procedure TfrmDialogRekening.chkplKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then chkIsDebet.SetFocus; end; procedure TfrmDialogRekening.dbAccountGroupKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then dbParentCode.SetFocus; end; procedure TfrmDialogRekening.dbParentCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_RETURN) then chkbs.SetFocus; end; function TfrmDialogRekening.ChekEmptyValue: Boolean; begin Result := False; if (edtRekCode.Text = '') then begin TAppUtils.Warning('Account Code Tidak Boleh Kosong'); edtRekCode.SetFocus; Exit; end; if (edtRekName.Text = '') then begin TAppUtils.Warning('Nama Rekening Tidak Boleh Kosong'); edtRekName.SetFocus; Exit; end; if (dbAccountGroup.Text = '') then begin TAppUtils.Warning('Account Group Tidak Boleh Kosong'); dbAccountGroup.SetFocus; Exit; end; if (dbParentCode.Text = '') then begin TAppUtils.Warning('Parent Code Tidak Boleh Kosong'); dbParentCode.SetFocus; Exit; end; Result := True; end; procedure TfrmDialogRekening.SetParentCode(const Value: string); begin FParentCode := Value; end; procedure TfrmDialogRekening.edbParentCodeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_DOWN) OR (Key = VK_F5) then edbParentCodeClickBtn(Self) else if (Key = VK_RETURN) then chkBS.SetFocus; end; procedure TfrmDialogRekening.edbParentCodeClickBtn(Sender: TObject); begin inherited; // if intedtLevel.Value = 0 then exit; //// KodeGrupRekId := cGetIDfromCombo(cmbAccountType, cmbAccountType.ItemIndex); // // s := 'SELECT REK_CODE as KODE, REK_NAME as NAMAREKENING FROM REKENING' // + ' WHERE REK_LEVEL < ' + VarToStr(intedtLevel.EditValue) // + ' AND REK_IS_LEAF = 0' // + ' AND REK_COMP_ID = ' + IntToStr(DialogCompany) // + ' AND REK_GROREK_ID = ' + IntToStr(KodeGrupRekId); //// with clookup('Daftar Rekening', s) do //// begin //// Try //// if Strings[0] = '' then Exit; //// edbParentCode.Text := Strings[0]; //// //// Finally //// Free; //// End; //// end; end; function TfrmDialogRekening.GetCDSRekening: tclientDataset; begin if not assigned(FCDSRekening) then fCDSRekening := Tdbutils.DSToCDS(DsProvider.Rekening_GetDSLookupLvl, self); Result := FCDSRekening; end; function TfrmDialogRekening.GetCDSRekeningGroup: tclientDataset; begin if not assigned(FCDSRekeningGroup) then FCDSRekeningGroup := Tdbutils.DSToCDS(DsProvider.GroupRekening_GetDSLookup, self); Result := FCDSRekeningGroup; end; function TfrmDialogRekening.GetCrud: TCrudClient; begin if not Assigned(FCrud) then fCrud := TCrudClient.Create(DMClient.RestConn, FALSE); Result := FCrud; end; function TfrmDialogRekening.GetDsProvider: TDSProviderClient; begin if not assigned(FDsProvider) then FDsProvider := TDSProviderClient.Create(DmClient.RestConn,False); Result := FDsProvider; end; function TfrmDialogRekening.GetModRekening: TModRekening; begin if not Assigned(FModRekening) then FModRekening := TModRekening.Create(); Result := FModRekening; end; procedure TfrmDialogRekening.LoadData(ID: String); begin if Assigned(fModRekening) then FreeAndNil(fModRekening); fModRekening := Crud.Retrieve(TModRekening.ClassName, ID) as TModRekening; edtRekCode.Text := ModRekening.REK_CODE; edtRekName.Text := ModRekening.REK_NAME; edtDescription.Text := ModRekening.REK_DESCRIPTION; if Assigned(ModRekening.RekeningGroup) then dbAccountGroup.EditValue := ModRekening.RekeningGroup.ID; if Assigned(ModRekening.REK_PARENT) then dbParentCode.EditValue := ModRekening.REK_PARENT.ID; if ModRekening.REK_IS_GROUP = 1 then chkbs.Checked := true else chkpl.Checked := true; if ModRekening.REK_IS_DEBET = 1 then cHKisDebet.Checked := true else cHKisDebet.Checked := false; if ModRekening.REK_IS_LEAF = 1 then cHKisLeaf.Checked := true else cHKisLeaf.Checked := false; end; { TfrmDialogRekening } procedure TfrmDialogRekening.SetFormMode(const Value: TFormMode); begin FFormMode := Value; end; procedure TfrmDialogRekening.SimpanData; var isLeaf : Integer; IsDebet : Integer; IsGroup : Integer; begin try if not ChekEmptyValue then exit; IsProcessSuccesfull := False; Self.Enabled := False; if chkIsDebet.Checked then IsDebet := 1 else IsDebet := 0; if chkIsLeaf.Checked then isLeaf := 1 else isLeaf := 0; IsGroup := 0 ; if chkBS.Checked then IsGroup := 1; if chkPL.Checked then IsGroup := 2; finally Self.Enabled := True; if FIsProcessSuccesfull then Close; end; ModRekening.REK_CODE := edtRekCode.Text; ModRekening.REK_NAME := edtRekName.Text; ModRekening.REK_DESCRIPTION := edtDescription.Text; ModRekening.RekeningGroup := TModRekeningGroup.CreateID(dbAccountGroup.EditValue); ModRekening.REK_PARENT := TModRekening.CreateID(dbParentCode.EditValue); ModRekening.REK_IS_DEBET := isDebet; ModRekening.REK_IS_LEAF := isLeaf; ModRekening.REK_IS_GROUP := isGroup; try Crud.SaveToDB(MODRekening); TAppUtils.Information('Simpan Berhasil.'); ModalResult := mrOK; except TAppUtils.Error('Gagal Menyimpan Data.'); edtRekCode.SetFocus; Raise end; end; end.
unit Main; interface uses Windows, Forms, StdCtrls, jpeg, ExtCtrls, Controls, Classes, Easysize, VistaAltFixUnit, JvExControls, JvFormWallpaper; type TForm1 = class(TForm) XPBtn: TButton; VistaBtn: TButton; SevenBtn: TButton; CmdBtn: TButton; RebootBtn: TButton; CubicBtn: TButton; EightBtn: TButton; VistaAltFix1: TVistaAltFix; BBG: TJvFormWallpaper; procedure XPBtnClick(Sender: TObject); procedure VistaBtnClick(Sender: TObject); procedure SevenBtnClick(Sender: TObject); procedure CmdBtnClick(Sender: TObject); procedure RebootBtnClick(Sender: TObject); procedure CubicBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure EightBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } WinPE : boolean; procedure ChangeSize(newWidth, newHeight: integer); end; var Form1: TForm1; AppDrv : Char; implementation uses SysUtils, ShellAPI, Dialogs; {$R *.dfm} type TOSInfo = class(TObject) public class function IsWOW64: Boolean; end; class function TOSInfo.IsWOW64: Boolean; type TIsWow64Process = function( Handle: THandle; var Res: BOOL ): BOOL; stdcall; var IsWow64Result: BOOL; IsWow64Process: TIsWow64Process; begin IsWow64Process := GetProcAddress( GetModuleHandle('kernel32'), 'IsWow64Process' ); if Assigned(IsWow64Process) then begin if not IsWow64Process(GetCurrentProcess, IsWow64Result) then raise Exception.Create('Bad process handle'); Result := IsWow64Result; end else Result := False; end; function ExpandEnvVars(const Str: string): string; var BufSize: Integer; // size of expanded string begin // Get required buffer size BufSize := ExpandEnvironmentStrings( PChar(Str), nil, 0); if BufSize > 0 then begin // Read expanded string into result string SetLength(Result, BufSize - 1); ExpandEnvironmentStrings(PChar(Str), PChar(Result), BufSize); end else // Trying to expand empty string Result := ''; end; procedure Execute( Command : string; Params : string = ''; StartFolder : string = ''); begin ShellExecute( Form1.Handle, 'open', PChar(Command), PChar(Params), PChar(StartFolder), SW_SHOWNORMAL); end; procedure TForm1.XPBtnClick(Sender: TObject); begin Execute(AppDrv + ':\boot\OSInstall\XP\Setup.exe'); end; procedure TForm1.VistaBtnClick(Sender: TObject); begin Execute(AppDrv + ':\boot\OSInstall\VISTA\Setup.exe'); end; procedure TForm1.SevenBtnClick(Sender: TObject); begin Execute(AppDrv + ':\boot\OSInstall\SEVEN\Setup.exe'); end; procedure TForm1.EightBtnClick(Sender: TObject); begin Execute(AppDrv + ':\boot\OSInstall\EIGHT\Setup.exe'); end; procedure TForm1.CmdBtnClick(Sender: TObject); begin Execute('CMD.exe'); end; procedure TForm1.RebootBtnClick(Sender: TObject); begin Execute('Wpeutil','Reboot'); end; procedure TForm1.CubicBtnClick(Sender: TObject); begin if WinPE then begin if not DirectoryExists( ExpandEnvVars('%SystemRoot%\system32\config\systemprofile\desktop') ) then ForceDirectories( ExpandEnvVars('%SystemRoot%\system32\config\systemprofile\desktop') ); end; Execute(AppDrv + ':\Tech-Tools\CubicExplorer\CubicExplorer.exe'); end; procedure TForm1.ChangeSize(newWidth, newHeight: integer); var i, oldWidth, oldHeight : integer; begin oldWidth:=Width; oldHeight:=Height; for i:=0 to ControlCount-1 do with Controls[i] do begin Width:=Width*newWidth div oldWidth; Height:=Height*newHeight div oldHeight; Left:=Left*newWidth div oldWidth; Top:=Top*newHeight div oldHeight; end; Width:=newWidth; Height:=newHeight; end; procedure TForm1.FormCreate(Sender: TObject); begin AppDrv := ExtractFileDrive(ParamStr(0))[1]; XPBtn.Enabled := FileExists(AppDrv + ':\boot\OSInstall\XP\Setup.exe'); VistaBtn.Enabled := FileExists(AppDrv + ':\boot\OSInstall\VISTA\Setup.exe'); SevenBtn.Enabled := FileExists(AppDrv + ':\boot\OSInstall\SEVEN\Setup.exe'); EightBtn.Enabled := FileExists(AppDrv + ':\boot\OSInstall\EIGHT\Setup.exe'); if FileExists( ExpandEnvVars('%SystemRoot%\system32\wpeutil.exe') ) then begin Left := 0; Top := 0; ChangeSize(Screen.Width,Screen.Height); WinPE := true; end else begin BorderStyle := bsToolWindow; ClientWidth := 800; ClientHeight := 600; Left:=(Screen.Width-Width) div 2; Top:=(Screen.Height-Height) div 2; RebootBtn.Enabled := false; WinPE := false; end; end; end.
unit myclasses2; { 行情数据! 行情数据! 行情数据! 行情数据! 行情数据! 行情数据! 行情数据! 行情数据! 行情数据! } {$mode objfpc}{$H+} interface uses Classes, SysUtils, DateUtils, TplZlibUnit; type //股票列表记录 TMyStockItem = packed record Code:string[6]; Caption:string[20]; Market:string[2]; end; PMyStockItem = ^TMyStockItem; //股票列表管理对象 { TMyStocks } TMyStocks = class(TComponent) private FList:TList; function GetCount: integer; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure Clear; //清除所有数据 procedure LoadFromFile(Afilename:String);//从文件读数据 procedure SaveToFile(AFilename:string);//保存数据到文件 function Add(AValue:TMyStockItem):integer;//增加 function IndexOf(ACode,AMarket:string):integer;//查找 function Item(AIndex:integer):TMyStockItem;//返回数据 procedure Update(AIndex:integer;AValue:TMyStockItem); //更新数据 property Count:integer read GetCount;//记录条数 end; //文件记录对象基类 { TL2DataFile } TL2DataFile = class(TComponent) private FCompress: boolean; FDataType: string; FFilename: string; FFrameInterval: integer; FList:TList;//记录对象 FMarket: string; FSecirityType: string; FSecutityCode: string; function GetCount: integer; public FFrameMap:array of String;//存储Frame目录,数组下标为Frame索引,数组内容为逗号间隔的数据项FList下标 constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear;//清除全部对象 function Add(AValue:Pointer):integer;//增加记录 function Item(AIndex:integer):Pointer;//返回指定下标的对象指针 procedure SaveToStream(AStream:TStream);virtual;//写入流 procedure LoadFromStream(AStream:TStream);virtual;//从流中读入 procedure SaveToFile(AFilename:string);//写入文件 procedure LoadFromFile(AFilename:string);//从文件读入 procedure InitFrameMap;//初始化FFrameMap数据 function CalcFrameIndex(ATime:int32):integer;//根据输入的时间,计算应该属于的FrameMap下标 procedure ReadFrame(AFrameIndex:integer;AStream:TStream);virtual;//按照FrameMap的下标读取帧数据,写入流 property FrameInterval:integer read FFrameInterval write FFrameInterval;//帧间隔时间,单位为秒 property Count:integer read GetCount;//对象个数 property SecutityCode:string read FSecutityCode write FSecutityCode;//股票代码 property SecirityType:string read FSecirityType write FSecirityType;//股票类型(股票、指数) property Market:string read FMarket write FMarket;//所属市场 property DataType:string read FDataType write FDataType;//数据类型 行情快照 盘口 逐笔成交 property Filename:string read FFilename write FFilename;//数据文件名 property Compress:boolean read FCompress write FCompress;//是否使用压缩 end; //指数记录 TL2IndexItem = packed record date:integer;//日期 publish_time:integer;//发布时间 code:string[6];//代码 last_close:double;//前收盘 open:double;//今开盘 high:double;//最高价 low:double;//最低价 close:double;//收盘价 最新价 现价 amount:double;//成交额(暂时没用) volume:int64;//成交量(暂时没用) end; PL2IndexItem = ^TL2IndexItem; TL2IndexItemArray = array of TL2IndexItem; //指数记录文件对象 { TL2IndexDataFile } TL2IndexDataFile = class(TL2DataFile) public function Add(AValue:TL2IndexItem):integer;overload; function Item(AIndex:integer):PL2IndexItem;overload; procedure SaveToStream(AStream:TStream);override; procedure LoadFromStream(AStream:TStream);override; procedure ReadFrame(AFrameIndex:integer;AStream:TStream);override;//按照FrameMap的下标读取帧数据,写入流 procedure ReadFrameToArray(AFrameIndex:integer;var AArray:TL2IndexItemArray); end; //快照记录 TL2SnapItem = packed record date:int32;//日期 publish_time:integer;//发布时间 code:string[6];//代码 last_close:double;//前收盘 open:double;//今开 high:double;//最高 low:double;//最低 close:double;//收盘 volume:int64;//成交量 amount:double;//成交额 end; PL2SnapItem = ^TL2SnapItem; TL2SnapItemArray = array of TL2SnapItem; //快照记录文件 { TL2SnapDataFile } TL2SnapDataFile = class(TL2DataFile) public function Add(AValue:TL2SnapItem):integer;overload; function Item(AIndex:integer):PL2SnapItem;overload; procedure SaveToStream(AStream:TStream);override; procedure LoadFromStream(AStream:TStream);override; procedure ReadFrame(AFrameIndex:integer;AStream:TStream);override;//按照FrameMap的下标读取帧数据,写入流 procedure ReadFrameToArray(AFrameIndex:integer;var AArray:TL2SnapItemArray); end; //盘口报价记录 TL2SnapDWItem = packed record date:integer;//日期 publish_time:integer;//发布时间 code:string[6];//代码 sell_1:double;//卖1价格 sell_2:double;//卖2价格 sell_3:double;//卖3价格 sell_4:double;//卖4价格 sell_5:double;//卖5价格 sell_6:double;//卖6价格 sell_7:double;//卖7价格 sell_8:double;//卖8价格 sell_9:double;//卖9价格 sell_10:double;//卖10价格 buy_1:double;//买1价格 buy_2:double;//买2价格 buy_3:double;//买3价格 buy_4:double;//买4价格 buy_5:double;//买5价格 buy_6:double;//买6价格 buy_7:double;//买7价格 buy_8:double;//买8价格 buy_9:double;//买9价格 buy_10:double;//买10价格 sell_1_vol:integer;//卖1量 sell_2_vol:integer;//卖1量 sell_3_vol:integer;//卖1量 sell_4_vol:integer;//卖1量 sell_5_vol:integer;//卖1量 sell_6_vol:integer;//卖1量 sell_7_vol:integer;//卖1量 sell_8_vol:integer;//卖1量 sell_9_vol:integer;//卖1量 sell_10_vol:integer;//卖1量 buy_1_vol:integer;//买1量 buy_2_vol:integer;//买2量 buy_3_vol:integer;//买3量 buy_4_vol:integer;//买4量 buy_5_vol:integer;//买5量 buy_6_vol:integer;//买6量 buy_7_vol:integer;//买7量 buy_8_vol:integer;//买8量 buy_9_vol:integer;//买9量 buy_10_vol:integer;//买10量 end; PL2SnapDWItem = ^TL2SnapDWItem; TL2SnapDWItemArray = array of TL2SnapDWItem; //盘口报价记录文件 { TL2SnapDWDataFile } TL2SnapDWDataFile = class(TL2DataFile) public function Add(AValue:TL2SnapDWItem):integer;overload; function Item(AIndex:integer):PL2SnapDWItem;overload; procedure SaveToStream(AStream:TStream);override; procedure LoadFromStream(AStream:TStream);override; procedure ReadFrame(AFrameIndex:integer;AStream:TStream);override;//按照FrameMap的下标读取帧数据,写入流 procedure ReadFrameToArray(AFrameIndex:integer;var AArray:TL2SnapDWItemArray); end; implementation //股票列表 { TMyStocks } function TMyStocks.GetCount: integer; begin Result:=FList.Count; end; constructor TMyStocks.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TList.Create; end; destructor TMyStocks.Destroy; begin Clear; FList.Free; inherited Destroy; end; procedure TMyStocks.Clear; var i:integer; begin for i:=0 to FList.Count-1 do begin Dispose(PMyStockItem(FList.Items[i])); end; FList.Clear; end; procedure TMyStocks.LoadFromFile(Afilename: String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TMyStockItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); Clear; mFile.Seek(0,soBeginning); mFile.Read(mcount,sizeof(mcount)); for i:=0 to mCount-1 do begin mFile.Read(mItem,sizeof(mItem)); if strtoint(mItem.Code)<2705 then Add(mItem); //只导入证券,不导入指数 end; mFile.Free; end; procedure TMyStocks.SaveToFile(AFilename: string); var mcount:integer; mFile:TFileStream; i:integer; mItem:TMyStockItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); mCount:=FList.Count; mFile.Seek(0,soBeginning); mFile.Write(mcount,sizeof(mCount)); for i:=0 to mcount-1 do begin mItem:=Self.Item(i); mFile.Write(mItem,sizeof(mItem)); end; mFile.Free; end; function TMyStocks.Add(AValue: TMyStockItem): integer; var m:PMyStockItem; begin new(m); m^.Caption:=AValue.Caption; m^.Code:=AValue.Code; m^.Market:=AValue.Market; Result:=FList.Add(m); end; function TMyStocks.IndexOf(ACode, AMarket: string): integer; var i:integer; mItem:TMyStockItem; begin Result:=-1; for i:=0 to FList.Count-1 do begin mItem:=Self.Item(i); if (mItem.Code=ACode) and (mItem.Market=AMarket) then begin Result:=i; Break; end; end; end; function TMyStocks.Item(AIndex: integer): TMyStockItem; var m:PMyStockItem; begin m:=PMyStockItem(FList.Items[AIndex]); Result.Code:=m^.Code; Result.Caption:=m^.Caption; Result.Market:=m^.Market; end; procedure TMyStocks.Update(AIndex: integer; AValue: TMyStockItem); var m:PMyStockItem; begin if Aindex < Flist.count then begin m:=PMyStockItem(FList.Items[AIndex]); m^.code:=AValue.code; m^.caption:=AValue.caption; m^.market:=AValue.Market; end; end; { TL2SnapDWDataFile } function TL2SnapDWDataFile.Add(AValue: TL2SnapDWItem): integer; var m:PL2SnapDWItem; begin new(m); with m^ do begin date:=AValue.date;//日期 publish_time:=AValue.publish_time;//发布时间 code:=AValue.code;//代码 sell_1:=AValue.sell_1;//卖1价格 sell_2:=AValue.sell_2;//卖2价格 sell_3:=AValue.sell_3;//卖3价格 sell_4:=AValue.sell_4;//卖4价格 sell_5:=AValue.sell_5;//卖5价格 sell_6:=AValue.sell_6;//卖6价格 sell_7:=AValue.sell_7;//卖7价格 sell_8:=AValue.sell_8;//卖8价格 sell_9:=AValue.sell_9;//卖9价格 sell_10:=AValue.sell_10;//卖10价格 buy_1:=AValue.buy_1;//买1价格 buy_2:=AValue.buy_2;//买2价格 buy_3:=AValue.buy_3;//买3价格 buy_4:=AValue.buy_4;//买4价格 buy_5:=AValue.buy_5;//买5价格 buy_6:=AValue.buy_6;//买6价格 buy_7:=AValue.buy_7;//买7价格 buy_8:=AValue.buy_8;//买8价格 buy_9:=AValue.buy_9;//买9价格 buy_10:=AValue.buy_10;//买10价格 sell_1_vol:=AValue.sell_1_vol;//卖1量 sell_2_vol:=AValue.sell_2_vol;//卖1量 sell_3_vol:=AValue.sell_3_vol;//卖1量 sell_4_vol:=AValue.sell_4_vol;//卖1量 sell_5_vol:=AValue.sell_5_vol;//卖1量 sell_6_vol:=AValue.sell_6_vol;//卖1量 sell_7_vol:=AValue.sell_7_vol;//卖1量 sell_8_vol:=AValue.sell_8_vol;//卖1量 sell_9_vol:=AValue.sell_9_vol;//卖1量 sell_10_vol:=AValue.sell_10_vol;//卖1量 buy_1_vol:=AValue.buy_1_vol;//买1量 buy_2_vol:=AValue.buy_2_vol;//买2量 buy_3_vol:=AValue.buy_3_vol;//买3量 buy_4_vol:=AValue.buy_4_vol;//买4量 buy_5_vol:=AValue.buy_5_vol;//买5量 buy_6_vol:=AValue.buy_6_vol;//买6量 buy_7_vol:=AValue.buy_7_vol;//买7量 buy_8_vol:=AValue.buy_8_vol;//买8量 buy_9_vol:=AValue.buy_9_vol;//买9量 buy_10_vol:=AValue.buy_10_vol;//买10量 end; Result:=FList.Add(m); end; function TL2SnapDWDataFile.Item(AIndex: integer): PL2SnapDWItem; begin Result:=nil; if AIndex<Flist.Count then Result:=PL2SnapDWItem(FList.Items[AIndex]); end; procedure TL2SnapDWDataFile.SaveToStream(AStream: TStream); var i:integer; m:PL2SnapDWItem; begin AStream.Seek(0,soBeginning); for i:=0 to FList.Count-1 do begin m:=Self.Item(i); AStream.Write(m^,Sizeof(m^)); end; end; procedure TL2SnapDWDataFile.LoadFromStream(AStream: TStream); var i,mCount:integer; m:TL2SnapDWItem; mIndex,mFrameIndex:integer; begin Self.Clear; mCount:= AStream.Size div sizeof(m); AStream.Seek(0,soBeginning); for i:=0 to mCount-1 do begin AStream.Read(m,sizeof(m)); mIndex:=Self.Add(m); if Length(FFrameMap)>0 then begin //如果Framemap已经初始化,则填充FrampMap数组 mFrameIndex:=Self.CalcFrameIndex(m.publish_time); if (mFrameIndex<Length(FFrameMap)) and (mFrameIndex<>-1) then FFrameMap[mFrameIndex]:=FFrameMap[mFrameIndex]+inttostr(mIndex)+','; end; end; end; procedure TL2SnapDWDataFile.ReadFrame(AFrameIndex: integer; AStream: TStream); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2SnapDWItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; AStream.Write(mCount,sizeof(mCount)); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AStream.Write(mItem^,sizeof(mItem^)); end; end; mTmp.Free; end; procedure TL2SnapDWDataFile.ReadFrameToArray(AFrameIndex: integer; var AArray: TL2SnapDWItemArray); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2SnapDWItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; SetLength(AArray,mCount); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AArray[i].code:=mItem^.code; AArray[i].date:=mItem^.date; AArray[i].publish_time:=mItem^.publish_time; AArray[i].buy_1:=mItem^.buy_1; AArray[i].buy_1_vol:=mItem^.buy_1_vol; AArray[i].buy_2:=mItem^.buy_2; AArray[i].buy_2_vol:=mItem^.buy_2_vol; AArray[i].buy_3:=mItem^.buy_3; AArray[i].buy_3_vol:=mItem^.buy_3_vol; AArray[i].buy_4:=mItem^.buy_4; AArray[i].buy_4_vol:=mItem^.buy_4_vol; AArray[i].buy_5:=mItem^.buy_5; AArray[i].buy_5_vol:=mItem^.buy_5_vol; AArray[i].buy_6:=mItem^.buy_6; AArray[i].buy_6_vol:=mItem^.buy_6_vol; AArray[i].buy_7:=mItem^.buy_7; AArray[i].buy_7_vol:=mItem^.buy_7_vol; AArray[i].buy_8:=mItem^.buy_8; AArray[i].buy_8_vol:=mItem^.buy_8_vol; AArray[i].buy_9:=mItem^.buy_9; AArray[i].buy_9_vol:=mItem^.buy_9_vol; AArray[i].buy_10:=mItem^.buy_10; AArray[i].buy_10_vol:=mItem^.buy_10_vol; AArray[i].sell_1:=mItem^.sell_1; AArray[i].sell_1_vol:=mItem^.sell_1_vol; AArray[i].sell_2:=mItem^.sell_2; AArray[i].sell_2_vol:=mItem^.sell_2_vol; AArray[i].sell_3:=mItem^.sell_3; AArray[i].sell_3_vol:=mItem^.sell_3_vol; AArray[i].sell_4:=mItem^.sell_4; AArray[i].sell_4_vol:=mItem^.sell_4_vol; AArray[i].sell_5:=mItem^.sell_5; AArray[i].sell_5_vol:=mItem^.sell_5_vol; AArray[i].sell_6:=mItem^.sell_6; AArray[i].sell_6_vol:=mItem^.sell_6_vol; AArray[i].sell_7:=mItem^.sell_7; AArray[i].sell_7_vol:=mItem^.sell_7_vol; AArray[i].sell_8:=mItem^.sell_8; AArray[i].sell_8_vol:=mItem^.sell_8_vol; AArray[i].sell_9:=mItem^.sell_9; AArray[i].sell_9_vol:=mItem^.sell_9_vol; AArray[i].sell_10:=mItem^.sell_10; AArray[i].sell_10_vol:=mItem^.sell_10_vol; end; end; mTmp.Free; end; { TL2SnapDataFile } function TL2SnapDataFile.Add(AValue: TL2SnapItem): integer; var m:PL2SnapItem; begin new(m); with m^ do begin date:=AValue.date;//日期 publish_time:=AValue.publish_time;//发布时间 code:=AValue.code;//代码 last_close:=AValue.last_close;//前收盘 open:=AValue.open;//今开 high:=AValue.high;//最高 low:=AValue.low;//最低 close:=AValue.close;//收盘 volume:=AValue.volume;//成交量 amount:=AValue.amount;//成交额 end; Result:=FList.Add(m); end; function TL2SnapDataFile.Item(AIndex: integer): PL2SnapItem; begin Result:=nil; if AIndex < FList.Count then Result:= PL2SnapItem(FList.Items[AIndex]); end; procedure TL2SnapDataFile.SaveToStream(AStream: TStream); var i:integer; m:PL2SnapItem; begin AStream.Seek(0,soBeginning); for i:=0 to FList.Count-1 do begin m:=Self.Item(i); AStream.Write(m^,Sizeof(m^)); end; end; procedure TL2SnapDataFile.LoadFromStream(AStream: TStream); var i,mCount:integer; m:TL2SnapItem; mIndex:integer; mFrameIndex:integer; begin Self.Clear; mCount:= AStream.Size div sizeof(m); AStream.Seek(0,soBeginning); for i:=0 to mCount-1 do begin AStream.Read(m,sizeof(m)); mIndex:=Self.Add(m); if Length(FFrameMap)>0 then begin //如果Framemap已经初始化,则填充FrampMap数组 mFrameIndex:=Self.CalcFrameIndex(m.publish_time); if (mFrameIndex<Length(FFrameMap)) and (mFrameIndex<>-1) then FFrameMap[mFrameIndex]:=FFrameMap[mFrameIndex]+inttostr(mIndex)+','; end; end; end; procedure TL2SnapDataFile.ReadFrame(AFrameIndex: integer; AStream: TStream); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2SnapItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; AStream.Write(mCount,sizeof(mCount)); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AStream.Write(mItem^,sizeof(mItem^)); end; end; mTmp.Free; end; procedure TL2SnapDataFile.ReadFrameToArray(AFrameIndex: integer; var AArray: TL2SnapItemArray); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2SnapItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; SetLength(AArray,mCount); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AArray[i].volume:=mItem^.volume; AArray[i].publish_time:=mItem^.publish_time; AArray[i].open:=mItem^.open; AArray[i].low:=mItem^.low; AArray[i].last_close:=mItem^.last_close; AArray[i].high:=mItem^.high; AArray[i].date:=mItem^.date; AArray[i].code:=mItem^.code; AArray[i].close:=mItem^.close; AArray[i].amount:=mItem^.amount; end; end; mTmp.Free; end; { TL2IndexDataFile } function TL2IndexDataFile.Add(AValue: TL2IndexItem): integer; var m:PL2IndexItem; begin new(m); with m^ do begin date:=AValue.date;//日期 publish_time:=AValue.publish_time;//发布时间 code:=AValue.code;//代码 last_close:=AValue.last_close;//前收盘 open:=AValue.open;//今开盘 high:=AValue.high;//最高价 low:=AValue.low;//最低价 close:=AValue.close;//收盘价 最新价 现价 amount:=AValue.amount;//成交额(暂时没用) volume:=AValue.volume;//成交量(暂时没用) end; Result:=FList.Add(m); end; function TL2IndexDataFile.Item(AIndex: integer): PL2IndexItem; begin Result:=nil; if AIndex < FList.Count then Result:= PL2IndexItem(FList.Items[AIndex]); end; procedure TL2IndexDataFile.SaveToStream(AStream: TStream); var i:integer; m:PL2IndexItem; begin AStream.Seek(0,soBeginning); for i:=0 to FList.Count-1 do begin m:=Self.Item(i); AStream.Write(m^,Sizeof(m^)); end; end; procedure TL2IndexDataFile.LoadFromStream(AStream: TStream); var i,mCount:integer; m:TL2IndexItem; mIndex:integer; mFrameIndex:integer; begin Self.Clear; mCount:= AStream.Size div sizeof(m); AStream.Seek(0,soBeginning); for i:=0 to mCount-1 do begin AStream.Read(m,sizeof(m)); mIndex:=Self.Add(m); if Length(FFrameMap)>0 then begin //如果Framemap已经初始化,则填充FrampMap数组 mFrameIndex:=Self.CalcFrameIndex(m.publish_time); if (mFrameIndex<Length(FFrameMap)) and (mFrameIndex<>-1) then FFrameMap[mFrameIndex]:=FFrameMap[mFrameIndex]+inttostr(mIndex)+','; end; end; end; procedure TL2IndexDataFile.ReadFrame(AFrameIndex: integer; AStream: TStream); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2IndexItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; AStream.Write(mCount,sizeof(mCount)); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AStream.Write(mItem^,sizeof(mItem^)); end; end; mTmp.Free; mCount:=AStream.Size; end; procedure TL2IndexDataFile.ReadFrameToArray(AFrameIndex: integer; var AArray: TL2IndexItemArray); var mTmp:TStrings; mLine:string; mCount:int32; i,mIndex:integer; mItem:PL2IndexItem; begin mLine:=FFrameMap[AFrameIndex]; mTmp:=TStringList.Create; ExtractStrings([','],[],PAnsiChar(mLine),mTmp); if mTmp.Count>1 then begin //清除空行 for i:=mTmp.Count-1 downto 0 do begin if Trim(mTmp.Strings[i])='' then mTmp.Delete(i); end; end; mCount:=mTmp.Count; SetLength(AArray,mCount); if mCount>0 then begin for i:=0 to mTmp.Count-1 do begin mIndex:=strtoint(mTmp.Strings[i]); mItem:=Item(mIndex); AArray[i].amount:=mItem^.amount; AArray[i].close:=mItem^.close; AArray[i].code:=mItem^.code; AArray[i].date:=mItem^.date; AArray[i].high:=mItem^.high; AArray[i].last_close:=mItem^.last_close; AArray[i].low:=mItem^.low; AArray[i].open:=mItem^.open; AArray[i].publish_time:=mItem^.publish_time; AArray[i].volume:=mItem^.volume; end; end; mTmp.Free; end; { TL2DataFile } function TL2DataFile.GetCount: integer; begin Result:=FList.Count; end; constructor TL2DataFile.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TList.Create; FFrameInterval:=3; end; destructor TL2DataFile.Destroy; begin FList.Clear; FList.Free; inherited Destroy; end; procedure TL2DataFile.Clear; var i:integer; begin FList.Clear; for i:=0 to Length(FFrameMap)-1 do begin FFrameMap[i]:=''; end; end; function TL2DataFile.Add(AValue: Pointer): integer; begin Result:=FList.Add(AValue); end; function TL2DataFile.Item(AIndex: integer): Pointer; begin Result:=FList.Items[AIndex]; end; procedure TL2DataFile.SaveToStream(AStream: TStream); begin end; procedure TL2DataFile.LoadFromStream(AStream: TStream); begin end; procedure TL2DataFile.SaveToFile(AFilename: string); var mFile:TFileStream; mMemory:TMemoryStream; begin if Self.Compress then begin //使用压缩 mMemory:=TMemoryStream.Create; Self.SaveToStream(mMemory); mFile:=TFileStream.Create(AFilename,fmCreate); CompressStreamZLib(mMemory,mFile); mFile.Free; mMemory.Free; end else begin //不使用压缩 mFile:=TFileStream.Create(AFilename,fmCreate); Self.SaveToStream(mFile); mFile.Free; end; end; procedure TL2DataFile.LoadFromFile(AFilename: string); var mFile:TFileStream; mMemory:TMemoryStream; begin if Self.Compress then begin //使用压缩 mMemory:=TMemoryStream.Create; mFile:=TFileStream.Create(AFilename,fmOpenRead); ExtractStreamZLib(mFile,mMemory); Self.LoadFromStream(mMemory); mMemory.Free; mFile.Free; end else begin //不使用压缩 mFile:=TFileStream.Create(AFilename,fmOpenRead); Self.LoadFromStream(mFile); mFile.Free; end; end; procedure TL2DataFile.InitFrameMap; var m,i:integer; begin if FFrameInterval=0 then FFrameInterval:=3; m:=15000 div FFrameInterval;//09:25-11:30 13:00-15:05 Setlength(FFrameMap,m); for i:=0 to Length(FFrameMap)-1 do begin FFrameMap[i]:=''; end; end; function TL2DataFile.CalcFrameIndex(ATime: int32): integer; var m1,m2:TDatetime; mH,mM,mS:integer; mSeconds:integer; begin mH:=ATime div 10000; mM:=(ATime - mH*10000) div 100; mS:=ATime - mH*10000 - mM*100; m2:=EncodeTime(mH,mM,mS,0); if ATime<=113000 then begin //上午交易时间 m1:=EncodeTime(9,25,1,0); mSeconds:=SecondsBetween(m1,m2); Result:=mSeconds div FFrameInterval; end else if (ATime>113000) and (ATime<130000) then begin //中午休息时间,跳过 Result:=-1; end else if (ATime>=130000) and (ATime<=150500) then begin //下午交易时间 m1:=EncodeTime(13,0,0,0); mSeconds:=SecondsBetween(m1,m2); Result:=mSeconds div FFrameInterval + 7500 div FFrameInterval; end; end; procedure TL2DataFile.ReadFrame(AFrameIndex: integer; AStream: TStream); begin //虚方法 end; { //股票行情数据 TMyQuoteItem = packed record ADate:integer; ATime:integer; Open:double; High:double; Low:double; Close:double; Vol:integer; end; PMyQuoteItem=^TMyQuoteItem; //单个股票行情管理对象 { TMyQuote } TMyQuote = class(TComponent) private FCaption: string; FCode: string; FList: TList; FMarket: string; function GetCount: integer; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear; procedure LoadFromFile(AFilename:string); procedure SaveToFile(AFilename:String); function Add(AValue:TMyQuoteItem):integer; function IndexOf(ADate,Atime:integer):integer; function Item(AIndex:integer):TMyQuoteItem; property Count:integer read GetCount; property Code:string read FCode write FCode; property Market:string read FMarket write FMarket; property Caption:string read FCaption write FCaption; end; //多个股票的行情总表对象 { TMyQuotes } TMyQuotes = class(TComponent) private FList:TObjectList; //管理对象为TMyQuote的列表 function GetCount: integer; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear; function Add(ACode,ACaption,AMarket:string):integer; function IndexOf(ACode,AMarket:string):integer; function Item(AIndex:integer):TMyQuote; procedure SaveListToFile(AFilename:string);//保存列表到文件 procedure LoadListFromFile(AFilename:String);//读取列表文件 procedure SaveDataToFile(ADir:string);//保存所有数据到各自的文件 procedure LoadDataFromFile(ADir:string);//所有对象读取各自的数据文件 property Count:integer read GetCount; end; //股票盘口数据 {TMyHandicapItem} TMyHAndicapItem = packed record ADate:integer; ATime:integer; ratio:double; //量比 //卖盘 sealprice1:double; //卖一价 sealvolume1:integer; //卖一成交量 sealprice2:double; sealvolume2:integer; sealprice3:double; sealvolume3:integer; sealprice4:double; sealvolume4:integer; sealprice5:double; sealvolume5:integer; sealprice6:double; sealvolume6:integer; sealprice7:double; sealvolume7:integer; sealprice8:double; sealvolume8:integer; sealprice9:double; sealvolume9:integer; sealprice10:double; sealvolume10:integer; //买盘 buyprice1:double; //买一价 buyvolume1:integer; //买一成交量 buyprice2:double; buyvolume2:integer; buyprice3:double; buyvolume3:integer; buyprice4:double; buyvolume4:integer; buyprice5:double; buyvolume5:integer; buyprice6:double; buyvolume6:integer; buyprice7:double; buyvolume7:integer; buyprice8:double; buyvolume8:integer; buyprice9:double; buyvolume9:integer; buyprice10:double; buyvolume10:integer; end; PMyHAndicapItem=^TMyHAndicapItem; //单个股票盘口管理对象 { TMyHandicap } TMyHandicap = class(TComponent) private FCaption: string; FCode: string; FList:TList; FMarket: string; function GetCount: integer; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear; procedure LoadFromFile(AFilename:string); procedure SaveToFile(AFilename:String); function Add(AValue:TMyHandicapItem):integer; function IndexOf(ADate,Atime:integer):integer; function Item(AIndex:integer):TMyHandicapItem; property Count:integer read GetCount; property Code:string read FCode write FCode; property Market:string read FMarket write FMarket; property Caption:string read FCaption write FCaption; end; //多个股票的盘口总表对象 { TMyHandicaps } TMyHandicaps = class(TComponent) private FList:TObjectList; //管理对象为TMyHandicap的列表 function GetCount: integer; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear; function Add(ACode,ACaption,AMarket:string):integer; function IndexOf(ACode,AMarket:string):integer; function Item(AIndex:integer):TMyHandicap; procedure SaveListToFile(AFilename:string);//保存列表到文件 procedure LoadListFromFile(AFilename:String);//读取列表文件 procedure SaveDataToFile(ADir:string);//保存所有数据到各自的文件 procedure LoadDataFromFile(ADir:string);//所有对象读取各自的数据文件 property Count:integer read GetCount; end; implementation //股票行情 { TMyQuote } function TMyQuote.GetCount: integer; begin Result:=FList.Count; end; constructor TMyQuote.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TList.Create; end; destructor TMyQuote.Destroy; begin clear; Flist.Free; inherited Destroy; end; procedure TMyQuote.Clear; begin Flist.clear; end; procedure TMyQuote.LoadFromFile(AFilename: string); var m:TMyStockItem; mFile:TFileStream; mCount,i:integer; mItem:TMyQuoteItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); //将文件中的单股行情,导入mFile Clear; mFile.Seek(0,soBeginning); mFile.Read(m,sizeof(m)); // 读出股票的代码、名称,作为表头信息 FCode:=m.Code; FCaption:=m.Caption; FMarket:=m.Market; mFile.Read(mCount,sizeof(mCount)); //读出一共多少条行情记录 for i:=0 to mCount-1 do begin //循环读出每条行情记录,add到Flist中 mFile.Read(mItem,sizeof(mItem)); Add(mItem); end; mFile.Free; end; procedure TMyQuote.SaveToFile(AFilename: String); var m:TMyStockItem; mFile:TFileStream; mCount,i:integer; mItem:TMyQuoteItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); //创建文件流 mFile.Seek(0,soBeginning); m.Caption:=FCaption; m.Code:=FCode; m.Market:=FMarket; mFile.Write(m,sizeof(m)); //存入股票代码、名称 mCount:=FList.Count; // 存入count mFile.Write(mCount,sizeof(mCount)); for i:=0 to FList.Count-1 do //循环Item函数,将返回的每条QuoteItem写入文件 begin mItem:=Item(i); mFile.Write(mItem,sizeof(mItem)); end; mFile.Free; end; function TMyQuote.Add(AValue: TMyQuoteItem): integer; var m:PMyQuoteItem; begin new(m); //创建新指针m,将Avalue信息依次付给m,最后Flist.add(m) m^.ADate:=AValue.ADate; m^.ATime:=AValue.ATime; m^.Open:=AValue.Open; m^.High:=AValue.High; m^.Low:=AValue.Low; m^.Close:=AValue.Close; m^.Vol:=AValue.vol; Result:=Flist.Add(m); end; function TMyQuote.IndexOf(ADate, Atime: integer): integer; var i:integer; mItem:TMyQuoteItem; begin Result:=-1; for i:=0 to Flist.Count-1 do begin mItem:=self.Item(i); //将循环的每一条QuoteItem赋值给mItem if (mItem.ADate=Adate) and (mItem.ATime=ATime) then //再将mItem和AValue比较 begin result:=i; break; end; end; end; function TMyQuote.Item(AIndex: integer): TMyQuoteItem; var m:PMyQuoteItem; begin m:=PMyQuoteItem(Flist.Items[AIndex]); result.Adate:=m^.ADate; result.ATime:=m^.ATime; result.Open:=m^.Open; result.High:=m^.High; result.Low:=m^.Low; result.Close:=m^.Close; result.Vol:=m^.Vol; end; { TMyQuotes } function TMyQuotes.GetCount: integer; begin Result:=Flist.Count; end; constructor TMyQuotes.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TObjectList.Create(True); end; destructor TMyQuotes.Destroy; begin Clear; FList.Free; inherited Destroy; end; procedure TMyQuotes.Clear; begin FList.Clear; end; function TMyQuotes.Add(ACode, ACaption, AMarket: string): integer; var //增加一只新股票 m:TMyQuote; begin m:=TMyQuote.Create(Self); m.Code:=ACode; m.Caption:=ACaption; m.Market:=AMarket; Result:=FList.Add(m); end; function TMyQuotes.IndexOf(ACode, AMarket: string): integer; var //索引一只股票 i:integer; m:TMyQuote; begin Result:=-1; for i:=0 to FList.Count-1 do begin if ((FList.Items[i] as TMyQuote).Code=ACode) and ((FList.Items[i] as TMyQuote).Market=AMarket) then begin Result:=i; Break; end; end; end; function TMyQuotes.Item(AIndex: integer): TMyQuote; begin Result:=FList.Items[AIndex] as TMyQuote; //等同于强制转换:TMyQuote(FList.Items[AIndex]) end; procedure TMyQuotes.SaveListToFile(AFilename:string); var i:integer; mHeader:TMyStockItem; m:TMyQuote; mFile:TFileStream; mCount:integer; begin mFile:=TFileStream.Create(AFilename,fmCreate); mFile.Seek(0,soBeginning); mCount:=Flist.Count; mFile.Write(mCount,sizeof(mCount)); //保存count for i:=0 to FList.Count-1 do begin m:=Self.Item(i); //依次提取出TMyQuote对象 mHeader.Code:=m.Code; mHeader.Market:=m.Market; //将每个对象的代码、市场和名称作为stockItem结构写入文件 mHeader.Caption:=m.Caption; mFile.Write(mHeader,sizeof(mHeader)); end; mFile.Free; end; procedure TMyQuotes.LoadListFromFile(AFilename: String); var i:integer; mHeader:TMyStockItem; m:TMyQuote; mFile:TFileStream; mCount:integer; begin Clear; mFile:=TFileStream.Create(AFilename,fmOpenRead); mFile.Seek(0,soBeginning); mFile.Read(mCount,sizeof(mCount)); for i:=0 to mCount-1 do begin //依次读取每个StockItem结构 mFile.Read(mHeader,sizeof(mHeader)); Self.Add(mHeader.Code,mHeader.Caption,mHeader.Market); end; //将每个StockItem中的代码、名称作为TMyQuote对象add到Flist中 mFile.Free; end; procedure TMyQuotes.SaveDataToFile(ADir:string); var i:integer; mFilename:string; mItem:TMyQuote; begin for i:=0 to FList.Count-1 do begin //对于list中的每一个TMyQuote对象 mItem:=Item(i); // 自动调用SaveToFile函数,保存到各自的目录下 mFilename:=Adir+'\'+mItem.Market+mItem.Code+'.dat'; mItem.SaveToFile(mFilename); end; end; procedure TMyQuotes.LoadDataFromFile(ADir:string); var i:integer; mFilename:string; mItem:TMyQuote; begin for i:=0 to FList.Count-1 do begin // 每一个TMyQuote对象自动从各自的目录Load mFilename:=Adir+'\'+mItem.Market+mItem.Code+'.dat'; mItem:=Item(i); mItem.LoadFromFile(mFilename); end; end; //盘口 { TMyHandicap } function TMyHandicap.GetCount: integer; begin Result:=Flist.Count; end; constructor TMyHandicap.Create(AOwner: TComponent); begin inherited Create(AOwner); Flist:=TList.Create; end; destructor TMyHandicap.Destroy; begin clear; Flist.Free; inherited Destroy; end; procedure TMyHandicap.Clear; begin Flist.Clear; end; procedure TMyHandicap.LoadFromFile(AFilename: string); var m:TMyStockItem; mFile:TFileStream; mCount,i:integer; mItem:TMyHandicapItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); Clear; mFile.seek(0,soBeginning); mFile.Read(m,sizeof(m)); FCode:=m.Code; FCaption:=m.Caption; FMarket:=m.Market; mFile.Read(mCount,sizeof(mCount)); //读出一共多少条行情记录 for i:=0 to mCount-1 do begin mFile.Read(mItem,sizeof(mItem)); Add(mItem); end; mFile.free; end; procedure TMyHandicap.SaveToFile(AFilename: String); var m:TMyStockItem; mFile:TFileStream; mCount,i:integer; mItem:TMyHandicapItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); mFile.seek(0,soBeginning); m.Code:=FCode; m.Caption:=FCaption; m.Market:=FMarket; mFile.Write(m,sizeof(m)); mCount:=Flist.Count; mFile.Write(mCount,sizeof(mCount)); //读出一共多少条行情记录 for i:=0 to mCount-1 do begin mItem:=Item(i); mFile.Write(mItem,sizeof(mItem)); end; mFile.free; end; function TMyHandicap.Add(AValue: TMyHandicapItem): integer; var m:PMyHandicapItem; begin new(m); m^.ADate:=AValue.ADate; m^.ATime:=AValue.ATime; m^.sealprice1:=AValue.sealprice1; m^.sealvolume1:=AValue.sealvolume1; m^.sealprice2:=AValue.sealprice1; m^.sealvolume2:=AValue.sealvolume1; m^.sealprice3:=AValue.sealprice1; m^.sealvolume3:=AValue.sealvolume1; m^.sealprice4:=AValue.sealprice1; m^.sealvolume4:=AValue.sealvolume1; m^.sealprice5:=AValue.sealprice1; m^.sealvolume5:=AValue.sealvolume1; m^.sealprice6:=AValue.sealprice1; m^.sealvolume6:=AValue.sealvolume1; m^.sealprice7:=AValue.sealprice1; m^.sealvolume7:=AValue.sealvolume1; m^.sealprice8:=AValue.sealprice1; m^.sealvolume8:=AValue.sealvolume1; m^.sealprice9:=AValue.sealprice1; m^.sealvolume9:=AValue.sealvolume1; m^.sealprice10:=AValue.sealprice1; m^.sealvolume10:=AValue.sealvolume1; m^.buyprice1:=AValue.buyprice1; m^.buyvolume1:=AValue.buyvolume1; m^.buyprice2:=AValue.buyprice1; m^.buyvolume2:=AValue.buyvolume1; m^.buyprice3:=AValue.buyprice1; m^.buyvolume3:=AValue.buyvolume1; m^.buyprice4:=AValue.buyprice1; m^.buyvolume4:=AValue.buyvolume1; m^.buyprice5:=AValue.buyprice1; m^.buyvolume5:=AValue.buyvolume1; m^.buyprice6:=AValue.buyprice1; m^.buyvolume6:=AValue.buyvolume1; m^.buyprice7:=AValue.buyprice1; m^.buyvolume7:=AValue.buyvolume1; m^.buyprice8:=AValue.buyprice1; m^.buyvolume8:=AValue.buyvolume1; m^.buyprice9:=AValue.buyprice1; m^.buyvolume9:=AValue.buyvolume1; m^.buyprice10:=AValue.buyprice1; m^.buyvolume10:=AValue.buyvolume1; Result:=Flist.Add(m); end; function TMyHandicap.IndexOf(ADate, Atime: integer): integer; var i:integer; mItem:TMyHandicapItem; begin Result:=-1; for i:=0 to Flist.Count-1 do begin mItem:=Self.Item(i); if (mItem.ADate=ADate) and (mItem.ATime=ATime) then begin result:=i; break; end; end; end; function TMyHandicap.Item(AIndex: integer): TMyHandicapItem; var m:PMyHandicapItem; begin m:=PMyHandicapItem(Flist.Items[AIndex]); result.Adate:=m^.ADate; result.ATime:=m^.ATime; result.sealprice1:=m^.sealprice1; result.sealvolume1:=m^.sealvolume1; result.sealprice2:=m^.sealprice1; result.sealvolume2:=m^.sealvolume1; result.sealprice3:=m^.sealprice1; result.sealvolume3:=m^.sealvolume1; result.sealprice4:=m^.sealprice1; result.sealvolume4:=m^.sealvolume1; result.sealprice5:=m^.sealprice1; result.sealvolume5:=m^.sealvolume1; result.sealprice6:=m^.sealprice1; result.sealvolume6:=m^.sealvolume1; result.sealprice7:=m^.sealprice1; result.sealvolume7:=m^.sealvolume1; result.sealprice8:=m^.sealprice1; result.sealvolume8:=m^.sealvolume1; result.sealprice9:=m^.sealprice1; result.sealvolume9:=m^.sealvolume1; result.sealprice10:=m^.sealprice1; result.sealvolume10:=m^.sealvolume1; result.buyprice1:=m^.buyprice1; result.buyvolume1:=m^.buyvolume1; result.buyprice2:=m^.buyprice1; result.buyvolume2:=m^.buyvolume1; result.buyprice3:=m^.buyprice1; result.buyvolume3:=m^.buyvolume1; result.buyprice4:=m^.buyprice1; result.buyvolume4:=m^.buyvolume1; result.buyprice5:=m^.buyprice1; result.buyvolume5:=m^.buyvolume1; result.buyprice6:=m^.buyprice1; result.buyvolume6:=m^.buyvolume1; result.buyprice7:=m^.buyprice1; result.buyvolume7:=m^.buyvolume1; result.buyprice8:=m^.buyprice1; result.buyvolume8:=m^.buyvolume1; result.buyprice9:=m^.buyprice1; result.buyvolume9:=m^.buyvolume1; result.buyprice10:=m^.buyprice1; result.buyvolume10:=m^.buyvolume1; end; { TMyHandicaps } function TMyHandicaps.GetCount: integer; begin Result:=Flist.Count; end; constructor TMyHandicaps.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TObjectList.Create(True); end; destructor TMyHandicaps.Destroy; begin Clear; Flist.Free; inherited Destroy; end; procedure TMyHandicaps.Clear; begin Flist.Clear; end; function TMyHandicaps.Add(ACode, ACaption, AMarket: string): integer; var m:TMyHandicap; begin m:=TMyHandicap.Create(self); m.Code:=ACode; m.Caption:=ACaption; m.Market:=AMarket; Result:=FList.Add(m); end; function TMyHandicaps.IndexOf(ACode, AMarket: string): integer; var //索引一只股票 i:integer; m:TMyHandicap; begin Result:=-1; for i:=0 to FList.Count-1 do begin if ((FList.Items[i] as TMyHandicap).Code=ACode) and ((FList.Items[i] as TMyHandicap).Market=AMarket) then begin Result:=i; Break; end; end; end; function TMyHandicaps.Item(AIndex: integer): TMyHandicap; begin Result:=Flist.Items[Aindex] as TMyHandicap; end; procedure TMyHandicaps.SaveListToFile(AFilename: string); var i:integer; mHeader:TMyStockItem; m:TMyHandicap; mFile:TFileStream; mCount:integer; begin mFile:=TFileStream.Create(AFilename,fmCreate); mFile.Seek(0,soBeginning); mCount:=Flist.Count; mFile.Write(mCount,sizeof(mCount)); //保存count for i:=0 to FList.Count-1 do begin m:=Self.Item(i); //依次提取出TMyQuote对象 mHeader.Code:=m.Code; mHeader.Market:=m.Market; //将每个对象的代码、市场和名称作为stockItem结构写入文件 mHeader.Caption:=m.Caption; mFile.Write(mHeader,sizeof(mHeader)); end; mFile.Free; end; procedure TMyHandicaps.LoadListFromFile(AFilename: String); var i:integer; mHeader:TMyStockItem; m:TMyHandicap; mFile:TFileStream; mCount:integer; begin Clear; mFile:=TFileStream.Create(AFilename,fmOpenRead); mFile.Seek(0,soBeginning); mFile.Read(mCount,sizeof(mCount)); for i:=0 to mCount-1 do begin //依次读取每个StockItem结构 mFile.Read(mHeader,sizeof(mHeader)); Self.Add(mHeader.Code,mHeader.Caption,mHeader.Market); end; //将每个StockItem中的代码、名称作为TMyQuote对象add到Flist中 mFile.Free; end; procedure TMyHandicaps.SaveDataToFile(ADir: string); var i:integer; mFilename:string; mItem:TMyHandicap; begin for i:=0 to FList.Count-1 do begin //对于list中的每一个TMyQuote对象 mItem:=Item(i); // 自动调用SaveToFile函数,保存到各自的目录下 mFilename:=Adir+'\'+mItem.Market+mItem.Code+'.dat'; mItem.SaveToFile(mFilename); end; end; procedure TMyHandicaps.LoadDataFromFile(ADir: string); var i:integer; mFilename:string; mItem:TMyHandicap; begin for i:=0 to FList.Count-1 do begin // 每一个TMyQuote对象自动从各自的目录Load mFilename:=Adir+'\'+mItem.Market+mItem.Code+'.dat'; mItem:=Item(i); mItem.LoadFromFile(mFilename); end; end; } end.
(**************************************************) (* *) (* Advanced Encryption Standard (AES) *) (* Interface Unit v1.3 *) (* *) (* *) (* Copyright (c) 2002 Jorlen Young *) (* *) (* *) (* *) (*说明: *) (* *) (* 基于 ElASE.pas 单元封装 *) (* *) (* 这是一个 AES 加密算法的标准接口。 *) (* *) (* *) (* 作者:杨泽晖 2004.12.04 *) (* *) (* 支持 128 / 192 / 256 位的密匙 *) (* 默认情况下按照 128 位密匙操作 *) (* *) (**************************************************) unit AES; interface uses SysUtils, Classes, Math, ElAES; type TKeyBit = (kb128, kb192, kb256); function StrToHex(Value: string): string; function HexToStr(Value: string): string; function EncryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; function DecryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; implementation function StrToHex(Value: string): string; var I: Integer; begin Result := ''; for I := 1 to Length(Value) do Result := Result + IntToHex(Ord(Value[I]), 2); end; function HexToStr(Value: string): string; var I: Integer; begin Result := ''; for I := 1 to Length(Value) do begin if ((I mod 2) = 1) then Result := Result + Chr(StrToInt('0x'+ Copy(Value, I, 2))); end; end; { -- 字符串加密函数 默认按照 128 位密匙加密 -- } function EncryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; var SS, DS: TStringStream; Size: Int64; AESKey128: TAESKey128; AESKey192: TAESKey192; AESKey256: TAESKey256; begin Result := ''; SS := TStringStream.Create(Value); DS := TStringStream.Create(''); try Size := SS.Size; DS.WriteBuffer(Size, SizeOf(Size)); { -- 128 位密匙最大长度为 16 个字符 -- } if KeyBit = kb128 then begin FillChar(AESKey128, SizeOf(AESKey128), 0 ); Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key))); EncryptAESStreamECB(SS, 0, AESKey128, DS); end; { -- 192 位密匙最大长度为 24 个字符 -- } if KeyBit = kb192 then begin FillChar(AESKey192, SizeOf(AESKey192), 0 ); Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key))); EncryptAESStreamECB(SS, 0, AESKey192, DS); end; { -- 256 位密匙最大长度为 32 个字符 -- } if KeyBit = kb256 then begin FillChar(AESKey256, SizeOf(AESKey256), 0 ); Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key))); EncryptAESStreamECB(SS, 0, AESKey256, DS); end; Result := StrToHex(DS.DataString); finally SS.Free; DS.Free; end; end; { -- 字符串解密函数 默认按照 128 位密匙解密 -- } function DecryptString(Value: string; Key: string; KeyBit: TKeyBit = kb128): string; var SS, DS: TStringStream; Size: Int64; AESKey128: TAESKey128; AESKey192: TAESKey192; AESKey256: TAESKey256; begin Result := ''; SS := TStringStream.Create(HexToStr(Value)); DS := TStringStream.Create(''); try Size := SS.Size; SS.ReadBuffer(Size, SizeOf(Size)); { -- 128 位密匙最大长度为 16 个字符 -- } if KeyBit = kb128 then begin FillChar(AESKey128, SizeOf(AESKey128), 0 ); Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key))); DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey128, DS); end; { -- 192 位密匙最大长度为 24 个字符 -- } if KeyBit = kb192 then begin FillChar(AESKey192, SizeOf(AESKey192), 0 ); Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key))); DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey192, DS); end; { -- 256 位密匙最大长度为 32 个字符 -- } if KeyBit = kb256 then begin FillChar(AESKey256, SizeOf(AESKey256), 0 ); Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key))); DecryptAESStreamECB(SS, SS.Size - SS.Position, AESKey256, DS); end; Result := DS.DataString; finally SS.Free; DS.Free; end; end; end.
unit UDExportOdbc; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, UCrpe32; type TCrpeOdbcDlg = class(TForm) pnlOdbc: TPanel; lblSource: TLabel; lblUser: TLabel; lblPassword: TLabel; lblTable: TLabel; editSource: TEdit; editUser: TEdit; editPassword: TEdit; editTable: TEdit; btnSelect: TButton; btnOk: TButton; btnCancel: TButton; cbPrompt: TCheckBox; procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSelectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure cbPromptClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeOdbcDlg: TCrpeOdbcDlg; implementation {$R *.DFM} uses UDExportOptions, UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.FormShow(Sender: TObject); begin editSource.Text := Cr.ExportOptions.ODBC.Source; editUser.Text := Cr.ExportOptions.ODBC.User; editPassword.Text := Cr.ExportOptions.ODBC.Password; editTable.Text := Cr.ExportOptions.ODBC.Table; cbPrompt.Checked := Cr.ExportOptions.ODBC.Prompt; end; {------------------------------------------------------------------------------} { cbPromptClick } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.cbPromptClick(Sender: TObject); var OnOff : Boolean; begin OnOff := (cbPrompt.Checked = False); editSource.Enabled := OnOff; editUser.Enabled := OnOff; editPassword.Enabled := OnOff; editTable.Enabled := OnOff; editSource.Color := ColorState(OnOff); editUser.Color := ColorState(OnOff); editPassword.Color := ColorState(OnOff); editTable.Color := ColorState(OnOff); btnSelect.Enabled := OnOff; end; {------------------------------------------------------------------------------} { btnSelectClick } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.btnSelectClick(Sender: TObject); const SQL_SUCCESS = 0; SQL_DRIVER_PROMPT = 2; SQL_SUCCESS_WITH_INFO = 1; SQL_DATA_SOURCE_NAME = 2; type MyUChar = array[0..255] of char; TSQLAllocEnv = function (var henv: Pointer): SmallInt stdcall; TSQLAllocConnect = function (henv: Pointer; var hdbc: Pointer): SmallInt stdcall; TSQLDriverConnect = function (hdbc: Pointer; window: hWnd; szConnStrIn: MyUChar; cbConnStrIn: SmallInt; szConnStrOut: MyUChar; cbConnStrOutMax: SmallInt; var pcbConnStrOut: Pointer; fDriverCompletion: Word ): SmallInt stdcall; TSQLGetInfo = function (hdbc: Pointer; fInfoType: SmallInt; rgbInfoValue: PChar; cbInfoValueMax: SmallInt; var pcbInfoValue: SmallInt): SmallInt stdcall; var henv : Pointer; hdbc : Pointer; ConIn, ConOut : MyUChar; LenIn, LenOut : SmallInt; RetCode : SmallInt; TotOut : Pointer; x : SmallInt; Temp : PChar; hODBC32 : THandle; SQLAllocEnv: TSQLAllocEnv; SQLAllocConnect: TSQLAllocConnect; SQLDriverConnect: TSQLDriverConnect; SQLGetInfo: TSQLGetInfo; begin LenIn := 256; LenOut := 256; henv := Nil; hdbc := Nil; hODBC32 := LoadLibrary('ODBC32.DLL'); if (hODBC32 < HINSTANCE_ERROR) then begin MessageDlg('ODBC32.DLL could not be loaded.', mtError, [mbOk], 0); Exit; end; SQLAllocEnv := GetProcAddress(hODBC32, 'SQLAllocEnv'); if TSQLAllocEnv(SQLAllocEnv)(henv) <> SQL_SUCCESS then begin MessageDlg('ODBC Connect Failed.', mtError, [mbOk], 0); Exit; end; SQLAllocConnect := GetProcAddress(hODBC32, 'SQLAllocConnect'); if TSQLAllocConnect(SQLAllocConnect)(henv, hdbc) <> SQL_SUCCESS then begin MessageDlg('ODBC Connect Failed.', mtError, [mbOk], 0); Exit; end; FillChar(ConIn, 256, ' '); SQLDriverConnect := GetProcAddress(hODBC32, 'SQLDriverConnect'); RetCode := TSQLDriverConnect(SQLDriverConnect)(hdbc, Self.Handle, ConIn, LenIn, ConOut, LenOut, TotOut, SQL_DRIVER_PROMPT); Refresh; if ((Retcode <> SQL_SUCCESS) and (Retcode <> SQL_SUCCESS_WITH_INFO)) then begin MessageDlg('ODBC Connect Failed.', mtError, [mbOk], 0); Exit; end; Temp := StrAlloc(255); SQLGetInfo := GetProcAddress(hODBC32, 'SQLGetInfo'); RetCode := TSQLGetInfo(SQLGetInfo)(hdbc, SQL_DATA_SOURCE_NAME, Temp, 255, x); if (Retcode <> SQL_SUCCESS) AND (RetCode <> SQL_SUCCESS_WITH_INFO) then begin MessageDlg('ODBC Connect Failed.', mtError, [mbOk], 0); StrDispose(Temp); Exit; end; editSource.Text := StrPas(Temp); StrDispose(Temp); end; {------------------------------------------------------------------------------} { btnOKClick } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.btnOKClick(Sender: TObject); begin SaveFormPos(Self); Cr.ExportOptions.ODBC.Source := editSource.Text; Cr.ExportOptions.ODBC.User := editUser.Text; Cr.ExportOptions.ODBC.Password := editPassword.Text; Cr.ExportOptions.ODBC.Table := editTable.Text; Cr.ExportOptions.ODBC.Prompt := cbPrompt.Checked; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeOdbcDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
object FormOptions: TFormOptions Left = 356 Top = 257 BorderStyle = bsDialog Caption = 'FormOptions' ClientHeight = 142 ClientWidth = 389 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poOwnerFormCenter PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 0 Top = 0 Width = 389 Height = 105 Align = alTop Shape = bsFrame end object YesBtn: TcxButton Left = 192 Top = 112 Width = 91 Height = 22 Action = YesAction ParentShowHint = False ShowHint = True TabOrder = 0 LookAndFeel.Kind = lfFlat end object CancelBtn: TcxButton Left = 288 Top = 112 Width = 89 Height = 22 Action = CancelAction ParentShowHint = False ShowHint = True TabOrder = 1 LookAndFeel.Kind = lfFlat end object LabelDateForm: TcxLabel Left = 136 Top = 74 Width = 121 Height = 17 AutoSize = False ParentFont = False Properties.Alignment.Horz = taRightJustify Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clNavy Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 2 Caption = #1044#1072#1090#1072' '#1092#1086#1088#1084#1091#1074#1072#1085#1085#1103':' end object DateEdit: TcxDateEdit Left = 264 Top = 72 Width = 122 Height = 21 ParentFont = False Properties.Alignment.Horz = taRightJustify Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clGreen Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 3 end object LabelMonth: TcxLabel Left = 8 Top = 10 Width = 113 Height = 17 AutoSize = False ParentFont = False Properties.Alignment.Horz = taRightJustify Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clNavy Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 4 Caption = #1052#1110#1089#1103#1094#1100':' end object MonthComboBox: TcxComboBox Left = 128 Top = 8 Width = 257 Height = 21 ParentFont = False Properties.DropDownListStyle = lsFixedList Properties.Items.Strings = ( #1089#1110#1095#1077#1085#1100 #1083#1102#1090#1080#1081 #1073#1077#1088#1077#1079#1077#1085#1100 #1082#1074#1110#1090#1077#1085#1100 #1090#1088#1072#1074#1077#1085#1100 #1095#1077#1088#1074#1077#1085#1100 #1083#1080#1087#1077#1085#1100 #1089#1077#1088#1087#1077#1085#1100 #1074#1077#1088#1077#1089#1077#1085#1100 #1078#1086#1074#1090#1077#1085#1100 #1083#1080#1089#1090#1086#1087#1072#1076 #1075#1088#1091#1076#1077#1085#1100) Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clGreen Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 5 end object cxLabel1: TcxLabel Left = 8 Top = 44 Width = 137 Height = 17 AutoSize = False ParentFont = False Properties.Alignment.Horz = taRightJustify Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clNavy Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 6 Caption = #1055#1110#1076#1089#1090#1072#1074#1072' '#1076#1083#1103' '#1088#1086#1073#1086#1090#1080':' end object WorkComboBox: TcxComboBox Left = 152 Top = 40 Width = 233 Height = 21 ParentFont = False Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clGreen Style.Font.Height = -11 Style.Font.Name = 'MS Sans Serif' Style.Font.Style = [fsBold] TabOrder = 7 Text = #1059#1089#1110 end object ActionList: TActionList Left = 152 Top = 104 object YesAction: TAction Caption = 'YesAction' ShortCut = 16464 OnExecute = YesActionExecute end object CancelAction: TAction Caption = 'CancelAction' ShortCut = 27 OnExecute = CancelActionExecute end object DesRep: TAction Caption = 'DesRep' OnExecute = DesRepExecute end end end
unit Aurelius.Drivers.MyDac; {$I Aurelius.inc} interface uses Classes, DB, Variants, Generics.Collections, DBAccess, Aurelius.Drivers.Base, Aurelius.Drivers.Interfaces; type TMyDacResultSetAdapter = class(TDriverResultSetAdapter<TCustomDADataset>) end; TMyDacStatementAdapter = class(TInterfacedObject, IDBStatement, IDBDatasetStatement) private FQuery: TCustomDADataset; function GetDataset: TDataset; public constructor Create(AQuery: TCustomDADataset); destructor Destroy; override; procedure SetSQLCommand(SQLCommand: string); procedure SetParams(Params: TEnumerable<TDBParam>); function Execute: Integer; function ExecuteQuery: IDBResultSet; end; TMyDacConnectionAdapter = class(TDriverConnectionAdapter<TCustomDAConnection>, IDBConnection) public procedure Connect; procedure Disconnect; function IsConnected: Boolean; function CreateStatement: IDBStatement; function BeginTransaction: IDBTransaction; function RetrieveSqlDialect: string; override; end; TMyDacTransactionAdapter = class(TInterfacedObject, IDBTransaction) private FConnection: TCustomDAConnection; public constructor Create(AConnection: TCustomDAConnection); procedure Commit; procedure Rollback; end; implementation { TMyDacStatementAdapter } uses SysUtils, Bcl.Utils, Aurelius.Drivers.Exceptions, Aurelius.Global.Utils; constructor TMyDacStatementAdapter.Create(AQuery: TCustomDADataset); begin FQuery := AQuery; end; destructor TMyDacStatementAdapter.Destroy; begin FreeObj(FQuery); inherited; end; function TMyDacStatementAdapter.Execute: Integer; begin FQuery.ExecSQL; Result := FQuery.RowsAffected; end; function TMyDacStatementAdapter.ExecuteQuery: IDBResultSet; var ResultSet: TCustomDADataset; I: Integer; begin ResultSet := FQuery.Connection.CreateDataSet; try ResultSet.Connection := FQuery.Connection; ResultSet.SQL := FQuery.SQL; for I := 0 to FQuery.Params.Count - 1 do ResultSet.Params[I].Assign(FQuery.Params[I]); ResultSet.Execute; except FreeObj(ResultSet); raise; end; Result := TMyDacResultSetAdapter.Create(ResultSet); end; function TMyDacStatementAdapter.GetDataset: TDataset; begin Result := FQuery; end; procedure TMyDacStatementAdapter.SetParams(Params: TEnumerable<TDBParam>); var P: TDBParam; Parameter: TDAParam; Bytes: TBytes; I: Integer; begin I := 0; for P in Params do begin if (P.ParamName = '') and (I < FQuery.Params.Count) then Parameter := FQuery.Params[I] else Parameter := FQuery.FindParam(P.ParamName); Inc(I); if not Assigned(Parameter) then Continue; Parameter.DataType := P.ParamType; Parameter.ParamType := ptInput; if P.ParamType in [ftOraBlob, ftOraClob, ftBlob] then begin Bytes := TUtils.VariantToBytes(P.ParamValue); if VarIsNull(P.ParamValue) or (Length(Bytes) = 0) then Parameter.Clear else begin Parameter.DataType := P.ParamType; Parameter.AsBlob := Bytes; end; end else if P.ParamType in [ftMemo, ftWideMemo] then begin if VarIsNull(P.ParamValue) or (Length(VarToStr(P.ParamValue)) = 0) then Parameter.AsMemo := '' else begin Parameter.AsMemo := P.ParamValue; end; end else Parameter.Value := P.ParamValue; end; end; procedure TMyDacStatementAdapter.SetSQLCommand(SQLCommand: string); begin FQuery.SQL.Text := SQLCommand; end; { TMyDacConnectionAdapter } procedure TMyDacConnectionAdapter.Disconnect; begin if Connection <> nil then Connection.Connected := False; end; function TMyDacConnectionAdapter.RetrieveSqlDialect: string; begin if Connection = nil then Exit(''); Result := 'MySQL' end; function TMyDacConnectionAdapter.IsConnected: Boolean; begin if Connection <> nil then Result := Connection.Connected else Result := false; end; function TMyDacConnectionAdapter.CreateStatement: IDBStatement; var Statement: TCustomDADataset; begin if Connection = nil then Exit(nil); Statement := Connection.CreateDataSet; try Statement.Connection := Connection; except FreeObj(Statement); raise; end; Result := TMyDacStatementAdapter.Create(Statement); end; procedure TMyDacConnectionAdapter.Connect; begin if Connection <> nil then Connection.Connected := True; end; function TMyDacConnectionAdapter.BeginTransaction: IDBTransaction; begin if Connection = nil then Exit(nil); Connection.Connected := true; if not Connection.InTransaction then begin Connection.StartTransaction; Result := TMyDacTransactionAdapter.Create(Connection); end else Result := TMyDacTransactionAdapter.Create(nil); end; { TMyDacTransactionAdapter } procedure TMyDacTransactionAdapter.Commit; begin if (FConnection = nil) then Exit; FConnection.Commit; end; constructor TMyDacTransactionAdapter.Create(AConnection: TCustomDAConnection); begin FConnection := AConnection; end; procedure TMyDacTransactionAdapter.Rollback; begin if (FConnection = nil) then Exit; FConnection.Rollback; end; end.
unit FrnEngn; interface uses Windows, Classes, SysUtils, Grobal2, SDK; type TFrontEngine = class(TThread) m_UserCriticalSection: TRTLCriticalSection; m_LoadRcdList: TList; m_SaveRcdList: TList; m_ChangeGoldList: TList; private m_LoadRcdTempList: TList; m_SaveRcdTempList: TList; procedure GetGameTime(); procedure ProcessGameDate(); function LoadHumFromDB(LoadUser: pTLoadDBInfo; var boReTry: Boolean): Boolean; function ChangeUserGoldInDB(GoldChangeInfo: pTGoldChangeInfo): Boolean; procedure Run(); { Private declarations } protected procedure Execute; override; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; function SaveListCount(): Integer; function IsIdle(): Boolean; function IsFull(): Boolean; procedure DeleteHuman(nGateIndex, nSocket: Integer); function InSaveRcdList(sAccount, sChrName: string): Boolean; procedure AddChangeGoldList(sGameMasterName, sGetGoldUserName: string; nGold: Integer); procedure AddToLoadRcdList(sAccount, sChrName, sIPaddr: string; boFlag: Boolean; nSessionID: Integer; nPayMent, nPayMode, nSoftVersionDate, nSocket, nGSocketIdx, nGateIdx: Integer); procedure AddToLoadHeroRcdList(sCharName, sMsg: string; PlayObject: TObject; btLoadType: Byte); procedure AddToSaveRcdList(SaveRcd: pTSaveRcd); function UpDataSaveRcdList(SaveRcd: pTSaveRcd): Boolean; function GetSaveRcd(sAccount, sCharName: string): pTSaveRcd; end; implementation uses M2Share, RunDB, ObjBase, HUtil32; { TFrontEngine } constructor TFrontEngine.Create(CreateSuspended: Boolean); begin inherited; InitializeCriticalSection(m_UserCriticalSection); m_LoadRcdList := TList.Create; m_SaveRcdList := TList.Create; m_ChangeGoldList := TList.Create; m_LoadRcdTempList := TList.Create; m_SaveRcdTempList := TList.Create; //FreeOnTerminate:=True; //AddToProcTable(@TFrontEngine.ProcessGameDate, 'TFrontEngine.ProcessGameDatea'); end; destructor TFrontEngine.Destroy; begin m_LoadRcdList.Free; m_SaveRcdList.Free; m_ChangeGoldList.Free; m_LoadRcdTempList.Free; m_SaveRcdTempList.Free; DeleteCriticalSection(m_UserCriticalSection); inherited; end; procedure TFrontEngine.Execute; begin while not Terminated do begin try Run(); except MainOutMessage('{异常} TFrontEngine::Execute'); end; Sleep(1); end; end; procedure TFrontEngine.GetGameTime; var Hour, Min, Sec, MSec: Word; begin DecodeTime(Time, Hour, Min, Sec, MSec); case Hour of 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22: g_nGameTime := 1; 11, 23: g_nGameTime := 2; 4, 15: g_nGameTime := 0; 0, 1, 2, 3, 12, 13, 14: g_nGameTime := 3; end; end; function TFrontEngine.IsIdle: Boolean; begin Result := False; EnterCriticalSection(m_UserCriticalSection); try if m_SaveRcdList.Count = 0 then Result := True; finally LeaveCriticalSection(m_UserCriticalSection); end; end; function TFrontEngine.SaveListCount: Integer; begin Result := 0; EnterCriticalSection(m_UserCriticalSection); try Result := m_SaveRcdList.Count; finally LeaveCriticalSection(m_UserCriticalSection); end; end; procedure TFrontEngine.ProcessGameDate; var I: Integer; II: Integer; TempList: TList; ChangeGoldList: TList; LoadDBInfo: pTLoadDBInfo; SaveRcd: pTSaveRcd; GoldChangeInfo: pTGoldChangeInfo; boReTryLoadDB: Boolean; boSaveRcd: Boolean; nCode: Byte; resourcestring sExceptionMsg = '{异常} TFrontEngine::ProcessGameDate Code:%d'; sSaveExceptionMsg = '数据库服务器出现异常,请重新启动数据库服务器(DBServer.exe)!!!'; begin nCode := 0; try ChangeGoldList := nil; nCode := 17; if g_nSaveRcdErrorCount >= 10 then begin nCode := 18; if GetTickCount - g_dwShowSaveRcdErrorTick > 5000{1000} then begin//20081224 修改秒触发 nCode := 19; g_dwShowSaveRcdErrorTick := GetTickCount; MainOutMessage(sSaveExceptionMsg); end; end; EnterCriticalSection(m_UserCriticalSection); try nCode := 20; if m_SaveRcdList.Count > 0 then begin//20081008 nCode := 21; for I := 0 to m_SaveRcdList.Count - 1 do begin m_SaveRcdTempList.Add(m_SaveRcdList.Items[I]); end; end; nCode := 1; TempList := m_LoadRcdTempList; nCode := 2; m_LoadRcdTempList := m_LoadRcdList; nCode := 3; m_LoadRcdList := TempList; nCode := 4; if m_ChangeGoldList.Count > 0 then begin nCode := 22; ChangeGoldList := TList.Create; nCode := 23; for I := 0 to m_ChangeGoldList.Count - 1 do begin if m_ChangeGoldList.Items[I] <> nil then//20080808 增加 ChangeGoldList.Add(m_ChangeGoldList.Items[I]); end; end; finally LeaveCriticalSection(m_UserCriticalSection); end; if m_SaveRcdTempList.Count > 0 then begin//20081008 for I := 0 to m_SaveRcdTempList.Count - 1 do begin SaveRcd := m_SaveRcdTempList.Items[I]; if (not DBSocketConnected) or (g_nSaveRcdErrorCount >= 10) then begin //DBS关闭 不保存 if (SaveRcd.PlayObject <> nil) and (not SaveRcd.boIsHero) then begin TPlayObject(SaveRcd.PlayObject).m_boRcdSaved := True; end; EnterCriticalSection(m_UserCriticalSection); try for II := m_SaveRcdList.Count - 1 downto 0 do begin if m_SaveRcdList.Count <= 0 then Break;//20080917 if m_SaveRcdList.Items[II] = SaveRcd then begin m_SaveRcdList.Delete(II); nCode := 5; DisPoseAndNil(SaveRcd); nCode := 6; Break; end; end;//for finally LeaveCriticalSection(m_UserCriticalSection); end; end else begin boSaveRcd := False; if SaveRcd.nReTryCount = 0 then begin boSaveRcd := True; end else if (SaveRcd.nReTryCount < 50) and (GetTickCount - SaveRcd.dwSaveTick > 5000) then begin //保存错误等待5秒后在保存 boSaveRcd := True; end else if SaveRcd.nReTryCount >= 50 then begin //失败50次后不在保存 if (SaveRcd.PlayObject <> nil) and (not SaveRcd.boIsHero) then begin TPlayObject(SaveRcd.PlayObject).m_boRcdSaved := True; end; EnterCriticalSection(m_UserCriticalSection); try for II := m_SaveRcdList.Count - 1 downto 0 do begin if m_SaveRcdList.Count <= 0 then Break;//20080917 if m_SaveRcdList.Items[II] = SaveRcd then begin m_SaveRcdList.Delete(II); nCode := 7; DisPoseAndNil(SaveRcd); nCode := 8; Break; end; end;//for finally LeaveCriticalSection(m_UserCriticalSection); end; end; if boSaveRcd then begin if SaveHumRcdToDB(SaveRcd.sAccount, SaveRcd.sChrName, SaveRcd.nSessionID, SaveRcd.boIsHero, SaveRcd.HumanRcd) then begin if (SaveRcd.PlayObject <> nil) and (not SaveRcd.boIsHero) then begin TPlayObject(SaveRcd.PlayObject).m_boRcdSaved := True; end; EnterCriticalSection(m_UserCriticalSection); try for II := m_SaveRcdList.Count - 1 downto 0 do begin if m_SaveRcdList.Count <= 0 then Break;//20080917 if m_SaveRcdList.Items[II] = SaveRcd then begin m_SaveRcdList.Delete(II); nCode := 9; DisPoseAndNil(SaveRcd); nCode := 10; Break; end; end; finally LeaveCriticalSection(m_UserCriticalSection); end; end else begin //保存失败 Inc(SaveRcd.nReTryCount); SaveRcd.dwSaveTick := GetTickCount; end; end; end; end;//for m_SaveRcdTempList.Clear;//20081008 换地方 nCode := 11; end; if m_LoadRcdTempList.Count > 0 then begin//20080810 增加 nCode := 17; for I := 0 to m_LoadRcdTempList.Count - 1 do begin nCode := 18; LoadDBInfo := m_LoadRcdTempList.Items[I]; nCode := 19; if (not LoadHumFromDB(LoadDBInfo, boReTryLoadDB)) and (not LoadDBInfo.boIsHero) then RunSocket.CloseUser(LoadDBInfo.nGateIdx, LoadDBInfo.nSocket); if not boReTryLoadDB then begin DisPoseAndNil(LoadDBInfo); end else begin //如果读取人物数据失败(数据还没有保存),则重新加入队列 EnterCriticalSection(m_UserCriticalSection); try m_LoadRcdList.Add(LoadDBInfo); finally LeaveCriticalSection(m_UserCriticalSection); end; end; end;//for end; m_LoadRcdTempList.Clear; nCode := 12; if ChangeGoldList <> nil then begin nCode := 121; if ChangeGoldList.Count > 0 then begin//20081008 nCode := 122; for I := 0 to ChangeGoldList.Count - 1 do begin nCode := 123; GoldChangeInfo := ChangeGoldList.Items[I]; nCode := 124; if GoldChangeInfo <> nil then begin//20081204 增加 ChangeUserGoldInDB(GoldChangeInfo); nCode := 13; Dispose(GoldChangeInfo); nCode := 14; end; end; end; nCode := 15; ChangeGoldList.Free; end; except MainOutMessage(Format(sExceptionMsg, [nCode])); end; end; function TFrontEngine.IsFull: Boolean; begin Result := False; EnterCriticalSection(m_UserCriticalSection); try if m_SaveRcdList.Count >= 2000 then begin Result := True; end; finally LeaveCriticalSection(m_UserCriticalSection); end; end; //btLoadType 0-召唤 1-新建 2-删除 3-查询数据 procedure TFrontEngine.AddToLoadHeroRcdList(sCharName, sMsg: string; PlayObject: TObject; btLoadType: Byte); var LoadRcdInfo: pTLoadDBInfo; begin New(LoadRcdInfo); TPlayObject(PlayObject).m_boWaitHeroDate := True; LoadRcdInfo.sAccount := TPlayObject(PlayObject).m_sUserID; LoadRcdInfo.sCharName := sCharName; LoadRcdInfo.sIPaddr := TPlayObject(PlayObject).m_sIPaddr; LoadRcdInfo.boClinetFlag := TPlayObject(PlayObject).m_boClientFlag; LoadRcdInfo.nSessionID := TPlayObject(PlayObject).m_nSessionID; LoadRcdInfo.nSoftVersionDate := TPlayObject(PlayObject).m_nSoftVersionDate; LoadRcdInfo.nPayMent := TPlayObject(PlayObject).m_nPayMent; LoadRcdInfo.nPayMode := TPlayObject(PlayObject).m_nPayMode; LoadRcdInfo.nSocket := TPlayObject(PlayObject).m_nSocket; LoadRcdInfo.nGSocketIdx := TPlayObject(PlayObject).m_nGSocketIdx; LoadRcdInfo.nGateIdx := TPlayObject(PlayObject).m_nGateIdx; LoadRcdInfo.dwNewUserTick := GetTickCount(); LoadRcdInfo.PlayObject := PlayObject; LoadRcdInfo.nReLoadCount := 0; LoadRcdInfo.boIsHero := True; LoadRcdInfo.btLoadDBType := btLoadType; LoadRcdInfo.sMsg := sMsg; EnterCriticalSection(m_UserCriticalSection); try m_LoadRcdList.Add(LoadRcdInfo); finally LeaveCriticalSection(m_UserCriticalSection); end; end; procedure TFrontEngine.AddToLoadRcdList(sAccount, sChrName, sIPaddr: string; boFlag: Boolean; nSessionID, nPayMent, nPayMode, nSoftVersionDate, nSocket, nGSocketIdx, nGateIdx: Integer); var LoadRcdInfo: pTLoadDBInfo; begin New(LoadRcdInfo); LoadRcdInfo.sAccount := sAccount; LoadRcdInfo.sCharName := sChrName; LoadRcdInfo.sIPaddr := sIPaddr; LoadRcdInfo.boClinetFlag := boFlag; LoadRcdInfo.nSessionID := nSessionID; LoadRcdInfo.nSoftVersionDate := nSoftVersionDate; LoadRcdInfo.nPayMent := nPayMent; LoadRcdInfo.nPayMode := nPayMode; LoadRcdInfo.nSocket := nSocket; LoadRcdInfo.nGSocketIdx := nGSocketIdx; LoadRcdInfo.nGateIdx := nGateIdx; LoadRcdInfo.dwNewUserTick := GetTickCount(); LoadRcdInfo.PlayObject := nil; LoadRcdInfo.nReLoadCount := 0; LoadRcdInfo.boIsHero := False; EnterCriticalSection(m_UserCriticalSection); try m_LoadRcdList.Add(LoadRcdInfo); finally LeaveCriticalSection(m_UserCriticalSection); end; end; function TFrontEngine.LoadHumFromDB(LoadUser: pTLoadDBInfo; var boReTry: Boolean): Boolean; //004B4B10 var HumanRcd: THumDataInfo; UserOpenInfo: pTUserOpenInfo; nOpenStatus: Integer; begin Result := False; boReTry := False; if (not LoadUser.boIsHero) or ((LoadUser.boIsHero) and (LoadUser.btLoadDBType = 0)) then begin if InSaveRcdList(LoadUser.sAccount, LoadUser.sCharName) then begin boReTry := True; //反回TRUE,则重新加入队列 Exit; end; end; if not LoadUser.boIsHero then begin if (UserEngine.GetPlayObjectEx(LoadUser.sAccount, LoadUser.sCharName) <> nil) then begin UserEngine.KickPlayObjectEx(LoadUser.sAccount, LoadUser.sCharName); boReTry := True; //反回TRUE,则重新加入队列 Exit; end; end; if not LoadUser.boIsHero then begin if not LoadHumRcdFromDB(LoadUser.sAccount, LoadUser.sCharName, LoadUser.sIPaddr, HumanRcd, LoadUser.nSessionID) then begin RunSocket.SendOutConnectMsg(LoadUser.nGateIdx, LoadUser.nSocket, LoadUser.nGSocketIdx);//强迫用户下线 end else begin New(UserOpenInfo); UserOpenInfo.sAccount := LoadUser.sAccount; UserOpenInfo.sChrName := LoadUser.sCharName; UserOpenInfo.LoadUser := LoadUser^; UserOpenInfo.HumanRcd := HumanRcd; UserEngine.AddUserOpenInfo(UserOpenInfo); Result := True; end; end else begin nOpenStatus := -1; case LoadUser.btLoadDBType of 0: if LoadHeroRcdFromDB(LoadUser.sAccount, LoadUser.sCharName, LoadUser.sIPaddr, HumanRcd, LoadUser.nSessionID) then nOpenStatus := 1; 1: nOpenStatus := NewHeroRcd(LoadUser.sCharName, LoadUser.sMsg); 2: if DelHeroRcd(LoadUser.sAccount, LoadUser.sCharName, LoadUser.sIPaddr, LoadUser.nSessionID) then nOpenStatus := 1; 3: LoadUser.sMsg:= QueryHeroRcdFromDB(LoadUser.sAccount, LoadUser.sCharName, LoadUser.sIPaddr, LoadUser.sMsg, LoadUser.nSessionID);//20080514 else nOpenStatus := 0; end; New(UserOpenInfo); UserOpenInfo.sAccount := LoadUser.sAccount; UserOpenInfo.sChrName := LoadUser.sCharName; UserOpenInfo.LoadUser := LoadUser^; UserOpenInfo.HumanRcd := HumanRcd; UserOpenInfo.nOpenStatus := nOpenStatus; UserEngine.AddUserOpenInfo(UserOpenInfo); Result := True; end; end; function TFrontEngine.InSaveRcdList(sAccount, sChrName: string): Boolean; var I: Integer; begin Result := False; EnterCriticalSection(m_UserCriticalSection); try if m_SaveRcdList.Count > 0 then begin//20081008 for I := 0 to m_SaveRcdList.Count - 1 do begin if (pTSaveRcd(m_SaveRcdList.Items[I]).sAccount = sAccount) and (pTSaveRcd(m_SaveRcdList.Items[I]).sChrName = sChrName) then begin Result := True; Break; end; end; end; finally LeaveCriticalSection(m_UserCriticalSection); end; end; procedure TFrontEngine.AddChangeGoldList(sGameMasterName, sGetGoldUserName: string; nGold: Integer); var GoldInfo: pTGoldChangeInfo; begin New(GoldInfo); GoldInfo.sGameMasterName := sGameMasterName; GoldInfo.sGetGoldUser := sGetGoldUserName; GoldInfo.nGold := nGold; m_ChangeGoldList.Add(GoldInfo); end; procedure TFrontEngine.AddToSaveRcdList(SaveRcd: pTSaveRcd); begin EnterCriticalSection(m_UserCriticalSection); try m_SaveRcdList.Add(SaveRcd); finally LeaveCriticalSection(m_UserCriticalSection); end; end; function TFrontEngine.GetSaveRcd(sAccount, sCharName: string): pTSaveRcd; var I: Integer; SaveRcd: pTSaveRcd; begin Result := nil; EnterCriticalSection(m_UserCriticalSection); try if m_SaveRcdList.Count > 0 then begin for I := 0 to m_SaveRcdList.Count - 1 do begin SaveRcd := pTSaveRcd(m_SaveRcdList.Items[I]); if (SaveRcd.sAccount = sAccount) and (SaveRcd.sChrName = sCharName) then begin Result := SaveRcd; Break; end; end; end; finally LeaveCriticalSection(m_UserCriticalSection); end; end; function TFrontEngine.UpDataSaveRcdList(SaveRcd: pTSaveRcd): Boolean; //2005-11-12 增加 var I: Integer; HumanRcd: pTSaveRcd; begin Result := False; EnterCriticalSection(m_UserCriticalSection); try for I := m_SaveRcdList.Count - 1 downto 0 do begin if m_SaveRcdList.Count <= 0 then Break;//20080917 HumanRcd := pTSaveRcd(m_SaveRcdList.Items[I]); if (HumanRcd.sAccount = SaveRcd.sAccount) and (HumanRcd.sChrName = SaveRcd.sChrName) then begin HumanRcd.HumanRcd := SaveRcd.HumanRcd; Result := True; //清清改 // m_SaveRcdList.Delete(I); //DisPoseAndNil(SaveRcd); Exit; end; end; m_SaveRcdList.Add(SaveRcd); finally LeaveCriticalSection(m_UserCriticalSection); end; end; procedure TFrontEngine.DeleteHuman(nGateIndex, nSocket: Integer); var I: Integer; LoadRcdInfo: pTLoadDBInfo; begin EnterCriticalSection(m_UserCriticalSection); try for I := m_LoadRcdList.Count - 1 downto 0 do begin if m_LoadRcdList.Count <= 0 then Break; LoadRcdInfo := m_LoadRcdList.Items[I]; if (LoadRcdInfo.nGateIdx = nGateIndex) and (LoadRcdInfo.nSocket = nSocket) then begin m_LoadRcdList.Delete(I); Dispose(LoadRcdInfo); Break; end; end; finally LeaveCriticalSection(m_UserCriticalSection); end; end; function TFrontEngine.ChangeUserGoldInDB(GoldChangeInfo: pTGoldChangeInfo): Boolean; var HumanRcd: THumDataInfo; begin Result := False; if LoadHumRcdFromDB('1', GoldChangeInfo.sGetGoldUser, '1', HumanRcd, 1) then begin if ((HumanRcd.Data.nGold + GoldChangeInfo.nGold) > 0) and ((HumanRcd.Data.nGold + GoldChangeInfo.nGold) < 2000000000) then begin Inc(HumanRcd.Data.nGold, GoldChangeInfo.nGold); if SaveHumRcdToDB('1', GoldChangeInfo.sGetGoldUser, 1, False, HumanRcd) then begin UserEngine.sub_4AE514(GoldChangeInfo); Result := True; end; end; end; end; procedure TFrontEngine.Run; begin Try ProcessGameDate(); GetGameTime(); except on E: Exception do begin MainOutMessage('{异常} TFrontEngine.Run'); end; end; end; end.
program HowToDrawSimpleText; uses SwinGame, sgTypes; procedure Main(); begin OpenGraphicsWindow('Drawing Text', 800, 600); ClearScreen(); DrawText('You Win!!!', ColorWhite, 300, 200); RefreshScreen(); Delay(5000); ReleaseAllResources(); end; begin Main(); end.
{****** 单 元:uWord.pas 作 者:刘景威 日 期:2008-3-3 说 明:导出Word文档 更 新: ******} unit uWord; interface uses Windows, Messages, SysUtils, Classes, Variants, ComObj, Forms, Graphics, Quiz, WordXP, OfficeXP; type //显示进度信息之回调函数原型 TWord = class private FOwner: TPublish; FQuizObj: TQuizObj; FWordApp: OleVariant; FDocument: OleVariant; FRange: OleVariant; FTable: OleVariant; //写信息 function BuildInfo: Boolean; //写试题 function BuildQues: Boolean; //创建Word文档 function BuildWord: Boolean; public constructor Create(AOwner: TPublish); destructor Destroy; override; function Execute: Boolean; end; implementation uses uGlobal; { TWord } constructor TWord.Create(AOwner: TPublish); begin FOwner := AOwner; FQuizObj := AOwner.QuizObj; end; destructor TWord.Destroy; begin if not VarIsNull(FWordApp) then begin FWordApp.Quit; FWordApp := Unassigned; end; inherited Destroy; end; function TWord.BuildInfo: Boolean; begin Result := True; if not FQuizObj.QuizProp.ShowInfo then begin with FQuizObj.QuizProp do begin FRange := FDocument.Range; //表格 if QuizID <> '' then begin FTable := FDocument.Tables.Add(FRange, 1, 2); FTable.Columns.Item(1).Width := 302; FTable.Columns.Item(2).Width := 124; end else FTable := FDocument.Tables.Add(FRange, 1, 1); //边框 FTable.Borders.InsideLineStyle := wdLineStyleSingle; FTable.Borders.InsideColor := wdColorGray35; FTable.Borders.OutsideLineStyle := wdLineStyleSingle; FTable.Borders.OutsideColor := wdColorGray35; //标题 FRange := FTable.Cell(1, 1).Range; FRange.Bold := msoTrue; FRange.Text := QuizTopic; //ID if QuizID <> '' then begin FRange := FTable.Cell(1, 2).Range; FRange.Text := QuizID; end; end; Exit; end; //Cell的Row及Col,是从1, 1开始的 //默认宽度为426,不知是什么单位;字号默认为10 try with FQuizObj.QuizProp do begin FRange := FDocument.Range; //表格 if FileExists(QuizImage) then begin FTable := FDocument.Tables.Add(FRange, 1, 2); FTable.Columns.Item(1).Width := 302; FTable.Columns.Item(2).Width := 124; end else FTable := FDocument.Tables.Add(FRange, 1, 1); //边框 FTable.Borders.InsideLineStyle := wdLineStyleSingle; FTable.Borders.InsideColor := wdColorGray35; FTable.Borders.OutsideLineStyle := wdLineStyleSingle; FTable.Borders.OutsideColor := wdColorGray35; //标题 FRange := FTable.Cell(1, 1).Range; FRange.Font.Name := 'Microsoft Sans Serif'; FRange.Bold := msoTrue; FRange.Text := QuizTopic; //简介 FRange.InsertAfter(#13#10); FRange.InsertParagraphAfter; FRange := FRange.Paragraphs.Last.Range; FRange.Bold := False; if Trim(QuizInfo) <> '' then FRange.Text := ' ' + QuizInfo; //出题者 if ShowName or ShowMail then begin //这样再指定一次才行…… FRange := FTable.Cell(1, 1).Range; FRange.InsertAfter(#13#10 + #13#10); FRange.InsertParagraphAfter; FRange := FRange.Paragraphs.Last.Range; if ShowName and ShowMail then FRange.Text := '帐号:__________________ 邮件:__________________' else if ShowName then FRange.Text := '账号:____________________' else FRange.Text := '邮件:____________________'; end; //图片 if FileExists(QuizImage) and DealImage(QuizImage, 160, 120) then FTable.Cell(1, 2).Range.InlineShapes.AddPicture(App.TmpJpg, msoFalse, msoTrue); Result := True; end; except Result := False; end; end; function TWord.BuildQues: Boolean; function GetTypeImage(AType: TQuesType): Boolean; var bmp: TBitmap; begin Result := True; if FileExists(App.TmpPath + IntToStr(Ord(AType)) + '.bmp') then Exit; bmp := TBitmap.Create; try Result := FQuizObj.ImageList.GetBitmap(Ord(AType) + 8, bmp); if Result then bmp.SaveToFile(App.TmpPath + IntToStr(Ord(AType)) + '.bmp'); finally bmp.Free; end; end; type TArray = Array of Integer; function GetRndArray(ALength: Integer): TArray; var sCur: string; sl: TStrings; begin SetLength(Result, ALength); sl := TStringList.Create; try Randomize(); while sl.Count < ALength do begin sCur := IntToStr(Random(ALength)); if sl.IndexOf(sCur) = -1 then begin sl.Append(sCur); Result[sl.Count - 1] := StrToInt(sCur); end; end; finally sl.Free; end; end; const ARR_SIGN: array[0..8] of string = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'); var HasImage: Boolean; sCap, sAns: string; procedure DealQues(AQuesObj: TQuesBase; AIndex: Integer; AQuesIndex: string); procedure AddSignShape(AHotImage: OleVariant; AQuesHot: TQuesHot); const IMG_WIDTH = 377; IMG_HEIGHT = 189; var vSign: OleVariant; pic: TPicture; fFitScale, fScale, fLeft, fTop, fWidth, fHeight: Single; OffsetX, OffsetY: Integer; begin pic := TPicture.Create; try pic.LoadFromFile(AQuesHot.HotImage); if TQuesHot(AQuesObj).ImgFit then begin if (pic.Height / pic.Width) > IMG_HEIGHT / IMG_WIDTH then fFitScale := pic.Height / IMG_HEIGHT else fFitScale := pic.Width / IMG_WIDTH; OffsetX := Round(TQuesHot(AQuesObj).HotRect.Left * fFitScale); OffsetY := Round(TQuesHot(AQuesObj).HotRect.Top * fFitScale); end else begin fFitScale := 1; OffsetX := Round(TQuesHot(AQuesObj).HPos + TQuesHot(AQuesObj).HotRect.Left); OffsetY := Round(TQuesHot(AQuesObj).VPos + TQuesHot(AQuesObj).HotRect.Top); end; if (pic.Width > 320) or (pic.Height > 240) then begin //这里需要换算... if (pic.Height / pic.Width) > 3 / 4 then fScale := 240 / pic.Height else fScale := 320 / pic.Width; end else fScale := 1; //像素->磅 fScale := fScale * 3 / 4; //算位置 fLeft := AHotImage.Range.Information[wdHorizontalPositionRelativeToPage] + OffsetX * fScale; fTop := AHotImage.Range.Information[wdVerticalPositionRelativeToPage] + OffsetY * fScale; fTop := fTop + 4; fWidth := AQuesHot.HotRect.Right * fFitScale * fScale; fHeight := AQuesHot.HotRect.Bottom * fFitScale * fScale; //光标定位到此处,以解决若不再第一页则指示图形位置错误的问题 AHotImage.Select; //画图形 vSign := FDocument.Shapes.AddShape(msoShapeRectangle, fLeft, fTop, fWidth, fHeight); //vSign.Select; vSign.Fill.Visible := msoTrue; vSign.Fill.ForeColor.RGB := RGB(0, 0, 255); vSign.Fill.Transparency := 0.75; vSign.Line.Weight := 0.75; vSign.Line.DashStyle := msoLineDash; vSign.Line.Style := msoLineSingle; vSign.Line.ForeColor.RGB := RGB(255, 0, 0); vSign.Line.Visible := msoTrue; vSign.Line.Visible := msoTrue; finally pic.Free; end; end; var j, AnsIndex: Integer; AddRow: Boolean; slMatch: TStrings; ArrRnd: TArray; QuesRange: OleVariant; QuesTable: OleVariant; HotImage: OleVariant; begin //序号、题目、图片 FTable.Cell(AIndex + 2, 1).Range.Text := AQuesIndex; //题型图 if GetTypeImage(AQuesObj._Type) then begin FTable.Cell(AIndex + 2, 1).Range.InsertParagraphAfter; FTable.Cell(AIndex + 2, 1).Range.Paragraphs.Last.Range.InlineShapes.AddPicture(App.TmpPath + IntToStr(Ord(AQuesObj._Type)) + '.bmp', msoFalse, msoTrue); end; if AQuesObj._Type <> qtScene then FTable.Cell(AIndex + 2, 2).Range.Text := Trim(AQuesObj.Topic) + ' (' + FloatToStr(AQuesObj.Points) + FQuizObj.Player.Texts[5] + ')' else FTable.Cell(AIndex + 2, 2).Range.Text := Trim(AQuesObj.Topic); FTable.Cell(AIndex + 2, 2).Range.Font.Name := 'Microsoft Sans Serif'; FTable.Cell(AIndex + 2, 2).Range.Font.Size := FQuizObj.QuizSet.FontSetT.Size - 1.5; if AQuesObj._Type <> qtScene then FTable.Cell(AIndex + 2, 2).Range.Font.Color := FQuizObj.QuizSet.FontSetT.Color else FTable.Cell(AIndex + 2, 2).Range.Font.Color := $000066FF; FTable.Cell(AIndex + 2, 2).Range.Bold := FQuizObj.QuizSet.FontSetT.Bold; if FileExists(AQuesObj.Image) and DealImage(AQuesObj.Image, 160, 120) then begin FTable.Cell(AIndex + 2, 3).Range.InlineShapes.AddPicture(App.TmpJpg, msoFalse, msoTrue); FTable.Cell(AIndex + 2, 3).Range.Paragraphs.Format.Alignment := wdAlignParagraphCenter; end; FTable.Cell(AIndex + 2, 2).Range.InsertParagraphAfter; QuesRange := FTable.Cell(AIndex + 2, 2).Range.Paragraphs.Last.Range; QuesRange.Bold := msoFalse; QuesRange.Font.Name := 'Microsoft Sans Serif'; QuesRange.Font.Size := FQuizObj.QuizSet.FontSetA.Size - 1.5; if AQuesObj._Type <> qtScene then QuesRange.Font.Color := FQuizObj.QuizSet.FontSetA.Color else QuesRange.Font.Color := $000066FF; QuesRange.Font.Bold := FQuizObj.QuizSet.FontSetA.Bold; if AQuesObj._Type <> qtHotSpot then QuesRange.InsertAfter(#13#10); //创建所需要表格 if AQuesObj._Type in [qtJudge, qtSingle, qtMulti, qtMatch, qtSeque] then //宽度为260.2,先加1行, QuesTable := FTable.Cell(AIndex + 2, 2).Range.Tables.Add(QuesRange, 1, 2); AddRow := False; sCap := '答案'; sAns := ''; //处理每题... case AQuesObj._Type of qtJudge, qtSingle, qtMulti: begin QuesTable.Columns.Item(1).Width := 20; if HasImage then QuesTable.Columns.Item(2).Width := 239 else QuesTable.Columns.Item(2).Width := 363; //填充 SetLength(ArrRnd, 0); if FQuizObj.QuizProp.RndAnswer then ArrRnd := GetRndArray(TQuesObj(AQuesObj).Answers.Count); for j := 0 to TQuesObj(AQuesObj).Answers.Count - 1 do begin if FQuizObj.QuizProp.RndAnswer then begin if Trim(TQuesObj(AQuesObj).Answers.ValueFromIndex[ArrRnd[j]]) = '' then Continue; end else if Trim(TQuesObj(AQuesObj).Answers.ValueFromIndex[j]) = '' then Continue; if AddRow then QuesTable.Rows.Add; AddRow := True; if not FQuizObj.QuizProp.RndAnswer then AnsIndex := j else AnsIndex := ArrRnd[j]; //此段为老方式,模拟控件模样 (*if AQuesObj._Type <> qtMulti then begin if FQuizObj.Publish.ShowAnswer and (TQuesObj(AQuesObj).Answers.Names[AnsIndex] = 'True') then QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := '⊙' else QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := '○'; end else begin if FQuizObj.Publish.ShowAnswer and (TQuesObj(AQuesObj).Answers.Names[AnsIndex] = 'True') then QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := '■' else QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := '□'; end;*) //此段,为新模式 if FQuizObj.Publish.ShowAnswer and (TQuesObj(AQuesObj).Answers.Names[AnsIndex] = 'True') then begin if sAns = '' then sAns := ARR_SIGN[j] else sAns := sAns + ',' + ARR_SIGN[j]; end; QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := ARR_SIGN[j]; if not AQuesObj.FeedAns then QuesTable.Cell(QuesTable.Rows.Count, 2).Range.Text := TQuesObj(AQuesObj).Answers.ValueFromIndex[AnsIndex] else if AQuesObj._Type = qtSingle then QuesTable.Cell(QuesTable.Rows.Count, 2).Range.Text := AQuesObj.GetAnswer(TQuesObj(AQuesObj).Answers.ValueFromIndex[AnsIndex]); end; end; qtBlank: begin QuesRange.Text := '________________________________'; if FQuizObj.Publish.ShowAnswer then begin QuesRange.Text := QuesRange.Text + ''; sCap := '可接受答案'; for j := 0 to TQuesObj(AQuesObj).Answers.Count - 1 do begin if Trim(TQuesObj(AQuesObj).Answers[j]) = '' then Continue; if FQuizObj.Publish.ShowAnswer then begin if sAns = '' then sAns := TQuesObj(AQuesObj).Answers[j] else sAns := sAns + '|' + TQuesObj(AQuesObj).Answers[j]; end; end; end; end; qtMatch: begin if HasImage then begin QuesTable.Columns.Item(1).Width := 129; QuesTable.Columns.Item(2).Width := 129; end else begin QuesTable.Columns.Item(1).Width := 191; QuesTable.Columns.Item(2).Width := 191; end; //因为有答案对应关系,所以特别处理一下 slMatch := TStringList.Create; try for j := 0 to TQuesObj(AQuesObj).Answers.Count - 1 do begin if Trim(TQuesObj(AQuesObj).Answers.ValueFromIndex[j]) = '' then Continue; slMatch.Append(TQuesObj(AQuesObj).Answers[j]); end; ArrRnd := GetRndArray(slMatch.Count); for j := 0 to slMatch.Count - 1 do begin if j > 0 then QuesTable.Rows.Add; QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := StringReplace(slMatch.Names[j], '$+$', '=', [rfReplaceAll]); QuesTable.Cell(QuesTable.Rows.Count, 2).Range.Text := slMatch.ValueFromIndex[ArrRnd[j]]; if FQuizObj.Publish.ShowAnswer then begin if sAns = '' then sAns := StringReplace(slMatch.Names[j], '$+$', '=', [rfReplaceAll]) + '->' + slMatch.ValueFromIndex[j] else sAns := sAns + ',' + StringReplace(slMatch.Names[j], '$+$', '=', [rfReplaceAll]) + '->' + slMatch.ValueFromIndex[j]; end; end; finally slMatch.Free; end; end; qtSeque: begin QuesTable.Columns.Item(1).Width := 20; if HasImage then QuesTable.Columns.Item(2).Width := 239 else QuesTable.Columns.Item(2).Width := 363; //填充 ArrRnd := GetRndArray(TQuesObj(AQuesObj).Answers.Count); for j := 0 to TQuesObj(AQuesObj).Answers.Count - 1 do begin if Trim(TQuesObj(AQuesObj).Answers[ArrRnd[j]]) = '' then Continue; if AddRow then QuesTable.Rows.Add; AddRow := True; QuesTable.Cell(QuesTable.Rows.Count, 1).Range.Text := IntToStr(j + 1); QuesTable.Cell(QuesTable.Rows.Count, 2).Range.Text := TQuesObj(AQuesObj).Answers[ArrRnd[j]]; if FQuizObj.Publish.ShowAnswer then begin if sAns = '' then sAns := IntToStr(ArrRnd[j] + 1) else sAns := sAns + ',' + IntToStr(ArrRnd[j] + 1); end; end; end; qtHotSpot: begin if DealImage(TQuesHot(AQuesObj).HotImage, 320, 240) then begin HotImage := QuesRange.InlineShapes.AddPicture(App.TmpJpg, msoFalse, msoTrue); //显示答案,特别处理 if FQuizObj.Publish.ShowAnswer then begin AddSignShape(HotImage, TQuesHot(AQuesObj)); sAns := '图中的蓝色区域'; end; end; end; qtEssay: begin QuesRange.Text := '_______________________________'; QuesRange.Text := QuesRange.Text + '_______________________________'; QuesRange.Text := QuesRange.Text + '_______________________________'; QuesRange.Text := QuesRange.Text + '_______________________________'; if FQuizObj.Publish.ShowAnswer then begin QuesRange.Text := QuesRange.Text + ''; sCap := '参考答案'; sAns := Trim(TQuesObj(AQuesObj).Answers.Text); end; end; qtScene: QuesRange.Text := Trim(TQuesObj(AQuesObj).Answers.Text); end; if FQuizObj.Publish.ShowAnswer and (AQuesObj._Type <> qtScene) then begin FTable.Cell(AIndex + 2, 2).Range.InsertParagraphAfter; QuesRange := FTable.Cell(AIndex + 2, 2).Range.Paragraphs.Last.Range; QuesRange.Bold := msoFalse; QuesRange.Font.Name := 'Microsoft Sans Serif'; QuesRange.Font.Size := 11; QuesRange.Font.Color := wdColorGreen; QuesRange.Text := sCap + ':' + sAns; end; end; var i, iCur, iQuesCount: Integer; sRndIds: string; QuesObj: TQuesBase; begin Result := False; if FQuizObj.QuesList.Count = 0 then Exit; try //大表格 FDocument.Range.InsertParagraphAfter; FRange := FDocument.Paragraphs.Last.Range; HasImage := False; with FQuizObj, FOwner do begin if QuizProp.RndQues.Enabled and (RndCount > 0) and (RndCount < (QuesList.Count - GetQuesCount(qtScene))) then begin sRndIds := FOwner.RndIds; iQuesCount := FOwner.RndCount; //是否有题存在图片 for i := 0 to QuesList.Count - 1 do begin if Pos(Format(',%d,', [i]), sRndIds) = 0 then Continue; QuesObj := QuesList.Items[i]; if FileExists(QuesObj.Image) then begin HasImage := True; Break; end; end; end else begin iQuesCount := QuesList.Count; //是否有题存在图片 for i := 0 to QuesList.Count - 1 do begin QuesObj := QuesList.Items[i]; if FileExists(QuesObj.Image) then begin HasImage := True; Break; end; end; end; if HasImage then begin FTable := FDocument.Tables.Add(FRange, iQuesCount + 1, 3); FTable.Columns.Item(1).Width := 32; FTable.Columns.Item(2).Width := 270; FTable.Columns.Item(3).Width := 124; FTable.Cell(1, 1).Range.Text := '编号'; FTable.Cell(1, 2).Range.Text := '试题'; FTable.Cell(1, 3).Range.Text := '图片'; end else begin FTable := FDocument.Tables.Add(FRange, iQuesCount + 1, 2); FTable.Columns.Item(1).Width := 32; FTable.Columns.Item(2).Width := 394; FTable.Cell(1, 1).Range.Text := '编号'; FTable.Cell(1, 2).Range.Text := '试题'; end; FTable.Rows.Item(1).Range.Bold := msoTrue; //边框 FTable.Borders.InsideLineStyle := wdLineStyleSingle; FTable.Borders.InsideColor := wdColorGray35; FTable.Borders.OutsideLineStyle := wdLineStyleSingle; FTable.Borders.OutsideColor := wdColorGray35; //第一行背景 FTable.Rows.Item(1).Shading.BackgroundPatternColor := wdColorGray20; //是否随机出题且不是运行期随机,且随机数量不是全部 if QuizProp.RndQues.Enabled and (RndCount > 0) and (RndCount < (QuesList.Count - GetQuesCount(qtScene))) then begin iCur := 0; //每题... for i := 0 to QuesList.Count - 1 do begin //取消转换 if FOwner.Cancel then Abort; if Pos(Format(',%d,', [i]), sRndIds) = 0 then Continue; //进度指示 if Assigned(FOwner.DisProgress) then FOwner.DisProgress(iCur + 1, FOwner.RndCount); DealQues(QuesList[i], iCur, IntToStr(iCur + 1)); Inc(iCur); end; end else begin //为处理场景题型而设置 iCur := 0; for i := 0 to QuesList.Count - 1 do begin //进度指示 if Assigned(FOwner.DisProgress) then FOwner.DisProgress(i + 1, QuesList.Count); if FQuizObj.QuesList.Items[i]._Type <> qtScene then begin DealQues(FQuizObj.QuesList.Items[i], i, IntToStr(iCur + 1)); Inc(iCur); end else DealQues(FQuizObj.QuesList.Items[i], i, ''); end; end; end; Result := True; except Result := False; end; end; function TWord.BuildWord: Boolean; var WordFile: OleVariant; begin Result := False; if not BuildInfo then Exit; if not BuildQues then Exit; //保存 WordFile := FOwner.Folder + FOwner.Title + '.doc'; with FQuizObj.QuizProp.PwdSet do begin if Enabled and (_Type = pstPwd) then FDocument.SaveAs(WordFile, wdFormatDocument, False, Password) else FDocument.SaveAs(WordFile); end; Result := True; end; function TWord.Execute: Boolean; begin Result := False; try FWordApp := GetActiveOleObject('Word.Application'); except try FWordApp := CreateOleObject('Word.Application'); except MessageBox(FOwner.Handle, '创建Word文档失败,您的计算机是安装Microsoft Word了吗?', '提示', MB_OK + MB_ICONINFORMATION); FWordApp := Null; Exit; end; end; //操作其中过程 FWordApp.Caption := FOwner.Title; FDocument := FWordApp.Documents.Add; //作者信息 with FQuizObj.Player do begin FDocument.BuiltInDocumentProperties(wdPropertyAuthor) := AuthorSet.Name; FDocument.BuiltInDocumentProperties(wdPropertyCompany) := 'AWindSoft'; FDocument.BuiltInDocumentProperties(wdPropertyComments) := AuthorSet.Des; FDocument.BuiltInDocumentProperties(wdPropertyHyperlinkBase) := AuthorSet.Url; end; FDocument.Saved := msoTrue; Result := BuildWord; end; end.
unit fct.controller.main; interface Uses fct.Controller.Interfaces,System.sysUtils, Vcl.Dialogs,Registry, Vcl.Forms, Winapi.Windows, Winapi.Messages, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Imaging.jpeg; type TFolderClass = class(TInterfacedObject,iFolderInterface) private FRaiz : String; FProjectName : String; public constructor Create; destructor Destroy;override; class Function New : iFolderInterface; function LocalRaiz(Value : String) : iFolderInterface; function Exec : iFolderInterface; function EnsureShellFolderPopupItem(Value: String) : iFolderInterface; function ProjectName(Value : String) : iFolderInterface; end; implementation { TFolderClass } constructor TFolderClass.Create; begin end; destructor TFolderClass.Destroy; begin inherited; end; function TFolderClass.EnsureShellFolderPopupItem( Value: String): iFolderInterface; begin Result := Self; With TRegistry.Create do Begin try RootKey := HKEY_CLASSES_ROOT; if openKey('Directory\Shell',true) then Begin if OpenKey(Value + '\command',true) then WriteString('','"' + Application.ExeName + '" "%1"'); End; finally Free; end; End; end; function TFolderClass.Exec: iFolderInterface; var Caminho : String; begin if (FRaiz <> '') and (FProjectName <> '') then Begin Caminho := FRaiz + '\' + FProjectName; if (not DirectoryExists(Caminho + '\DCU')) and (not DirectoryExists(Caminho + '\CLASSEs')) and (not DirectoryExists(Caminho + '\EXE')) and (not DirectoryExists(Caminho + '\EXE\DADOS')) and (not DirectoryExists(Caminho + '\FORMs')) and (not DirectoryExists(Caminho + '\IMAGEs')) and (not DirectoryExists(Caminho + '\PROJETO')) then Begin ForceDirectories(Caminho + '\CLASSEs'); ForceDirectories(Caminho + '\DCU'); ForceDirectories(Caminho + '\EXE'); ForceDirectories(Caminho + '\EXE\DADOS'); ForceDirectories(Caminho + '\FORMs'); ForceDirectories(Caminho + '\IMAGEs'); ForceDirectories(Caminho + '\PROJETO'); MessageDlg('Folders Created Successfully' + #13 + 'You need to setup your Delphi Project by going to Menu Project/Options under Delphi Compiler.Change the options OUTPUT DIRECTORY pointing it to EXE folder and UNIT OUTPUT DIRECTORY pointing it to DCU folder',mtWarning,[mbOk],0); End Else Begin MessageDlg('Folders have already been created.',mtWarning,[mbOk],0); End; End; end; function TFolderClass.LocalRaiz(Value: String): iFolderInterface; begin Result := Self; FRaiz := Value; end; class function TFolderClass.New: iFolderInterface; begin Result := Self.Create; end; function TFolderClass.ProjectName(Value: String): iFolderInterface; begin Result := Self; FProjectName := Value; end; end.
unit TreeMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Buttons, Vcl.BaseImageCollection, Vcl.ImageCollection, Vcl.VirtualImageList, Vcl.ExtCtrls; type TForm2 = class(TForm) TreeView1: TTreeView; Button1: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button2: TButton; lstLog: TListBox; Button6: TButton; Button7: TButton; Button8: TButton; Button9: TButton; Button10: TButton; Button11: TButton; Button12: TButton; FDMemTable1: TFDMemTable; FDMemTable1word: TStringField; Label1: TLabel; Button13: TButton; Button14: TButton; SpeedButton1: TSpeedButton; Button15: TButton; Panel1: TPanel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure Button10Click(Sender: TObject); procedure Button11Click(Sender: TObject); procedure Button12Click(Sender: TObject); procedure TreeViewCheckStateChanging(Sender: TCustomTreeView; Node: TTreeNode; NewCheckState, OldCheckState: TNodeCheckState; var AllowChange: Boolean); procedure TreeViewCheckStateChanged(Sender: TCustomTreeView; Node: TTreeNode; CheckState: TNodeCheckState); procedure Button13Click(Sender: TObject); procedure Button14Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button15Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure Log(const Msg: string); overload; procedure Log(const Msg: string; const Args: array of const); overload; procedure AllowAllStyles; public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.Log(const Msg: string); begin lstLog.ItemIndex := lstLog.Items.Add(Msg) end; procedure TForm2.Log(const Msg: string; const Args: array of const); begin Log(Format(Msg, Args)) end; procedure TForm2.SpeedButton1Click(Sender: TObject); begin lstLog.Clear; end; procedure TForm2.FormCreate(Sender: TObject); begin TreeView1.Items.Clear; lstLog.Clear; end; procedure TForm2.FormShow(Sender: TObject); begin FDmemTable1.Open; while fdMemTable1.RecordCount > 0 do begin FDMemTable1.RecNo := random(fdMemTable1.RecordCount); var randomWord := FDMemTable1.Fields[0].AsString; var randomNode: TTreeNode := nil; if TreeView1.Items.Count > 0 then randomNode := TreeView1.Items.Item[random(TreeView1.Items.Count)]; case random(4) of 0 : TreeView1.Items.AddChild(nil, randomWord); 1..2 : TreeView1.Items.AddChild(randomNode, randomWord); 3 : TreeView1.Items.Add(randomNode, randomWord); end; FDMemTable1.Delete; end; end; function CheckStateToStr(CheckState: TNodeCheckState): string; begin case CheckState of ncsNone: Result := 'N/A'; ncsUnchecked: Result := 'unchecked'; ncsChecked : Result := 'checked'; ncsPartial : Result := 'partial'; ncsDimmed : Result := 'dimmed'; ncsExclusion: Result := 'exclusion'; end; end; procedure TForm2.TreeViewCheckStateChanged(Sender: TCustomTreeView; Node: TTreeNode; CheckState: TNodeCheckState); begin Log('Node ''%s'' state changed to %s', [Node.Text, CheckStateToStr(CheckState)]); end; procedure TForm2.TreeViewCheckStateChanging(Sender: TCustomTreeView; Node: TTreeNode; NewCheckState, OldCheckState: TNodeCheckState; var AllowChange: Boolean); begin Log('Node ''%s'' state changing: %s -> %s', [Node.Text, CheckStateToStr(OldCheckState), CheckStateToStr(NewCheckState)]); end; procedure TForm2.Button1Click(Sender: TObject); begin TreeView1.CheckBoxes := not TreeView1.CheckBoxes; if TreeView1.CheckBoxes then Log('CheckBoxes = True') else Log('CheckBoxes = False') end; procedure TForm2.Button2Click(Sender: TObject); begin TreeView1.CheckStyles := []; Log('CheckStyles = []') end; procedure TForm2.Button3Click(Sender: TObject); begin TreeView1.CheckStyles := [csPartial]; Log('CheckStyles = [csPartial]') end; procedure TForm2.Button4Click(Sender: TObject); begin TreeView1.CheckStyles := [csPartial, csDimmed]; Log('CheckStyles = [csPartial, csDimmed]') end; procedure TForm2.Button5Click(Sender: TObject); begin TreeView1.CheckStyles := [csPartial, csExclusion]; Log('CheckStyles = [csPartial, csExclusion]') end; procedure TForm2.Button6Click(Sender: TObject); begin TreeView1.CheckStyles := [csDimmed, csExclusion]; Log('CheckStyles = [csDimmed, csExclusion]') end; procedure TForm2.AllowAllStyles; begin TreeView1.CheckStyles := [csPartial, csDimmed, csExclusion]; Log('CheckStyles = [csPartial, csDimmed, csExclusion]'); end; procedure TForm2.Button7Click(Sender: TObject); begin AllowAllStyles; end; procedure TForm2.Button8Click(Sender: TObject); begin TreeView1.Items[0].CheckState := ncsUnchecked end; procedure TForm2.Button9Click(Sender: TObject); begin TreeView1.Items[0].CheckState := ncsChecked end; procedure TForm2.Button10Click(Sender: TObject); begin TreeView1.Items[0].CheckState := ncsPartial end; procedure TForm2.Button11Click(Sender: TObject); begin TreeView1.Items[0].CheckState := ncsDimmed end; procedure TForm2.Button12Click(Sender: TObject); begin TreeView1.Items[0].CheckState := ncsExclusion end; procedure TForm2.Button13Click(Sender: TObject); begin TreeView1.LockDrawing; try TreeView1.FullExpand; TreeView1.Items.GetFirstNode.MakeVisible; finally TreeView1.UnlockDrawing; end; end; procedure TForm2.Button14Click(Sender: TObject); begin TreeView1.LockDrawing; try TreeView1.FullCollapse; TreeView1.Items.GetFirstNode.MakeVisible; finally TreeView1.UnlockDrawing; end; end; procedure TForm2.Button15Click(Sender: TObject); begin AllowAllStyles; TreeView1.LockDrawing; lstLog.LockDrawing; try for var i := 0 to pred(TreeView1.Items.Count) do begin var state := Succ(TNodeCheckState(random(5))); TreeView1.Items[i].CheckState := state; end; finally TreeView1.UnlockDrawing; lstLog.UnlockDrawing; end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Dependency.Resolver; interface uses Spring.Collections, System.Diagnostics, VSoft.Awaitable, DPM.Core.Types, DPM.Core.Logging, DPM.Core.Package.Interfaces, DPM.Core.Project.Interfaces, DPM.Core.Repository.Interfaces, DPM.Core.Configuration.Interfaces, DPM.Core.Dependency.Interfaces, DPM.Core.Dependency.Version, DPM.Core.Dependency.Context, DPM.Core.Options.Search, DPM.Core.Package.Installer.Interfaces; type TDependencyResolver = class(TInterfacedObject, IDependencyResolver) private FLogger : ILogger; FRepositoryManager : IPackageRepositoryManager; FPackageInstallerContext : IPackageInstallerContext; FStopwatch : TStopWatch; FConfiguration : IConfiguration; protected function Initialize(const config: IConfiguration) : boolean; function ValidateDependencyGraph(const cancellationToken : ICancellationToken; var dependencyGraph : IPackageReference) : boolean; function DoResolve(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const includePrerelease : boolean; const context : IResolverContext) : boolean; function ResolveForInstall(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const projectFile : string; const options : TSearchOptions; const newPackage : IPackageInfo; const projectReferences : IList<TProjectReference>; var dependencyGraph : IPackageReference; out resolved : IList<IPackageInfo>) : boolean; function ResolveForRestore(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const projectFile : string; const options : TSearchOptions; const projectReferences : IList<TProjectReference>; var dependencyGraph : IPackageReference; out resolved : IList<IPackageInfo>) : boolean; public constructor Create(const logger : ILogger; const repositoryManager : IPackageRepositoryManager; const packageInstallerContext : IPackageInstallerContext); end; implementation uses System.SysUtils, Generics.Defaults, DPM.Core.Constants, DPM.Core.Dependency.Graph; { TDependencyResolver } constructor TDependencyResolver.Create(const logger : ILogger; const repositoryManager : IPackageRepositoryManager; const packageInstallerContext : IPackageInstallerContext); begin FLogger := logger; FRepositoryManager := repositoryManager; FStopwatch := TStopwatch.Create; FPackageInstallerContext := packageInstallerContext; end; function SortDependencies(const Left, Right : IPackageDependency) : integer; var w : integer; begin //check the width of the range.. smaller range equals less dep versions //so we can fail faster. w := Left.VersionRange.PatchWidth - Right.VersionRange.PatchWidth; if w = 0 then result := 0 else if w > 0 then result := 1 else result := -1; end; /// This a simple depth first search with backtracking. It records unresolvable paths (nogoods) to avoid searching those again /// When a conflict is found, it tries to resolve that by finding an overlapping dependency version range between the new /// dependency range and the one already resolved. If found then it will undo the previous resolution and push it back on /// the stack to be redone with the overlapping range. If not then we have an unresolvable conflict and exit. /// /// Note that top level (non transitive) dependencies always win out in conflicts with transient dependencies. /// A small optimisation is to sort the dependencies by the width of their dependency version range and /// process them from small to large. The idea there is to fail as early as possible. /// /// In basic testing, this seems to be fast enough, however as the eco system grows and dependencies become /// deeper and more widespread, this simple algorithm may become slow. /// /// The current algorithm is not great at explaining the problem when conflicts are found. /// /// In the future we can implement a better algorithms which provides faster resolution /// /// The PubGrub algorithm used in the dart package manager (pub) looks to be a good contender /// https://medium.com/@nex3/pubgrub-2fb6470504f /// ://github.com/dart-lang/pub/blob/master/doc/solver.md /// If anyone is good math and want's to have a stab at implementing it in Delphi that would be great! function TDependencyResolver.DoResolve(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const includePrerelease : boolean; const context : IResolverContext) : boolean; var currentPackage : IPackageInfo; dependency : IPackageDependency; resolution : IResolution; parentResolution : IResolution; intersectingRange : TVersionRange; versions : IList<IPackageInfo>; version : IPackageInfo; selected : boolean; choices : integer; preRelease : boolean; begin FStopwatch.Reset; FStopwatch.Start; FLogger.Verbose('Starting dependency resolution...'); result := false; while context.AnyOpenRequrements do begin currentPackage := context.PopRequirement; //if the package has no dependencies then we are done with it. if not currentPackage.Dependencies.Any then continue; //if the current package is pre-release then we need to include them in the versions we get below. preRelease := includePrerelease or (not currentPackage.Version.IsStable); //Sort the dependencies by the width of the dependency's versionrange (smaller the better) //the idea is to fail as quickly as possible, the less work we do the better currentPackage.Dependencies.Sort(TComparer<IPackageDependency>.Construct(SortDependencies)); for dependency in currentPackage.Dependencies do begin FLogger.Information('Resolving dependency : ' + currentPackage.Id + '.' + currentPackage.Version.ToStringNoMeta + '->' + dependency.Id + ' ' + dependency.VersionRange.ToString); //first see if we have resolved this package already. That may be in this project, or another project in the group. if context.TryGetResolution(dependency.Id, currentPackage.Id, resolution) then begin //check if the dependency range is satisfied by already resolved version if not dependency.VersionRange.IsSatisfiedBy(resolution.Package.Version) then begin FLogger.Information(' conflict - selected version : ' + dependency.Id + '-' + resolution.Package.Version.ToString + ' does not satisfy ' + dependency.VersionRange.ToString); //Check if the resolution comes from a different project, if so then record a project conflict but carry on? if not SameText(resolution.Project, context.ProjectFile) then begin FLogger.Error('Package project conflict - version : ' + dependency.Id + '-' + resolution.Package.Version.ToString + ' in project : ' + resolution.Project + ' does not satisfy ' + dependency.VersionRange.ToString ); //record conflicts here in the context so we can show the user and then continue.. that way we can show the user rather than bombing on the first go? exit; end else if resolution.IsTopLevel then //if it's a top level package then the version is not negotiable. begin FLogger.Error('Package conflict - selected version : ' + dependency.Id + '-' + resolution.Package.Version.ToString + ' does not satisfy ' + dependency.VersionRange.ToString); exit; end; FLogger.Verbose('Attempting to find overalapping versionrange with dependency and earlier resolution'); //see if we can reduce to an overlapping versionrange that satisfies both if resolution.VersionRange.TryGetIntersectingRange(dependency.VersionRange, intersectingRange) then begin //resolution.Dependency.Version := intersectingRange; dependency.VersionRange := intersectingRange; FLogger.Debug(' overlapping range found : ' + dependency.Id + '-' + intersectingRange.ToString); end else begin //record the resolved version as no good, so we don't try it again context.RecordNoGood(resolution.Package); //backtrack the package/version that got us here in the first place //not 100% sure this is correct here. More testing needed. if context.TryGetResolution(resolution.ParentId, '', parentResolution) then begin context.RecordNoGood(parentResolution.Package); context.PushRequirement(parentResolution.Package); end; end; //unresolve the dependency context.RemoveResolution(dependency.Id); //try the current package again context.PushRequirement(currentPackage); end else begin if resolution.Project <> context.ProjectFile then begin FLogger.Information(' resolved earlier : ' + dependency.Id + '.' + resolution.Package.Version.ToString); end else FLogger.Information(' selected : ' + dependency.Id + '.' + resolution.Package.Version.ToString); //in the case where we are promoting a transitive to a direct dependency, we need a range. //the direct will not have a range so we convert the version to a range. if resolution.VersionRange.IsEmpty then resolution.VersionRange := TVersionRange.Create(resolution.Package.Version); //if the resolution came from another project, then we still need to deal with it's dependencies. if resolution.Package.Dependencies.Any then context.PushRequirement(resolution.Package); end; //we're good.. this is resolved. continue; end else begin //it wasn't resolved before, so get the available versions versions := context.GetPackageVersions(dependency.Id); if versions = nil then begin //passing in the version range to filter the results - not sure if this is valid.. do we need all versions? //I suspect it may result in more failures versions := FRepositoryManager.GetPackageVersionsWithDependencies(cancellationToken, compilerVersion, platform, dependency.Id, dependency.VersionRange, preRelease); if versions.Any then //cache the versions in the context in case we need them again context.AddPackageVersions(dependency.Id, versions); end; selected := false; for version in versions do begin if context.IsNoGood(version) then continue; if dependency.VersionRange.IsSatisfiedBy(version.Version) then begin context.RecordResolution(version, dependency.VersionRange, currentPackage.Id); if version.Dependencies.Any then //no point pushing it if there are no dependencies - see top of loop context.PushRequirement(version); //resolve it's dependencies FLogger.Information(' selected : ' + version.Id + '.' + version.Version.ToStringNoMeta); selected := true; break; end else context.RecordNoGood(version); // so we don't try to use it again. end; if not selected then begin //if we get here we are blocked on this path. //make sure we never try the currentPackage version again context.RecordNoGood(currentPackage); FLogger.Debug(' Unable to satisfy dependency ' + dependency.Id + '-' + dependency.VersionRange.ToString); //try backtrack up to where a different choice could have been made for the current package choices := 0; versions := context.GetPackageVersions(currentPackage.id); if (versions <> nil) and versions.Any then begin //see if there are any other choices for the current version for version in versions do begin if context.IsNoGood(version) then continue; Inc(choices); end; if choices > 0 then begin //get the parent, and backtrack to it. if context.TryGetResolution(currentPackage.Id, currentPackage.Id, resolution) then begin //can't backtrack to a root (direct dependency) if (resolution.ParentId <> cRootNode) and context.TryGetResolution(resolution.ParentId, '', parentResolution) then begin FLogger.Debug('Backtracking to : ' + parentResolution.Package.Id + '-' + parentResolution.Package.Version.ToString); context.RemoveResolution(currentPackage.Id); //shouldn't this be the parentResolution.Pacakage??? context.PushRequirement(parentResolution.Package); break; end; end; end; //if we get here we are unable to continue. //TODO : Context.RecordUnresolvable - and just continue until done. FLogger.Error('Unable to satisfy dependency : ' + currentPackage.Id + ' -> ' + dependency.Id + ' ' + dependency.VersionRange.ToString); exit(false); end; end; end; end; end; result := true; FLogger.Success('Dependency resolution done in [' + IntToStr(FStopwatch.ElapsedMilliseconds) + 'ms]'); FLogger.NewLine; end; function TDependencyResolver.Initialize(const config: IConfiguration) : boolean; begin Assert(config <> nil); FConfiguration := config; result :=FRepositoryManager.Initialize(config); end; function TDependencyResolver.ResolveForInstall(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const projectFile : string; const options : TSearchOptions; const newPackage : IPackageInfo; const projectReferences : IList<TProjectReference>; var dependencyGraph : IPackageReference; out resolved : IList<IPackageInfo>) : boolean; var context : IResolverContext; packageRef : TProjectReference; resolution : IResolution; errorCount : integer; begin Assert(FConfiguration <> nil, 'config is nil, Initialize has not been called'); errorCount := 0; for packageRef in projectReferences do begin resolution := FPackageInstallerContext.FindPackageResolution(projectFile, platform, packageRef.Package.Id); if (resolution <> nil) and (not resolution.VersionRange.IsSatisfiedBy(packageRef.Package.Version)) then begin FLogger.Error('Package project group conflict : ' + packageRef.Package.Id + '-' + resolution.Package.Version.ToString + ' in project : ' + resolution.Project + ' does not satisfy ' + packageRef.Package.Version.ToString ); Inc(errorCount) //exit; end; end; context := TResolverContext.Create(FLogger, FPackageInstallerContext, projectFile, newPackage, projectReferences); result := DoResolve(cancellationToken, compilerVersion, platform, options.Prerelease, context); resolved := context.GetResolvedPackages; dependencyGraph := context.BuildDependencyGraph; //record the resolutions so they can be applied to other projects in the group FPackageInstallerContext.RecordResolutions(projectFile, platform, context.GetResolutions); result := result and (errorCount = 0); end; //This is all wrong. What it should do is just validate the project references and ensure it's correct, not go off and resolve dependencies //which might change the dependecy versions. We only want to change the graph if it's wrong. function TDependencyResolver.ResolveForRestore(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const projectFile : string; const options : TSearchOptions; const projectReferences : IList<TProjectReference>; var dependencyGraph : IPackageReference; out resolved : IList<IPackageInfo>) : boolean; var context : IResolverContext; packageRef : TProjectReference; resolution : IResolution; errorCount : integer; begin Assert(dependencyGraph <> nil, 'nil dependency graph provided to ResolveForRestore'); Assert(FConfiguration <> nil, 'config is nil, Initialize has not been called'); //TODO : First validate that there are no conflicts in the existing graph.. if there are remove them and let the resolver deal with it? errorCount := 0; //first check if the packages are already resolved in the project group. for packageRef in projectReferences do begin resolution := FPackageInstallerContext.FindPackageResolution(projectFile, platform, packageRef.Package.Id); //if resolved, check if they are compatible. if (resolution <> nil) and (not resolution.VersionRange.IsSatisfiedBy(packageRef.Package.Version)) then begin FLogger.Error('Package project group conflict : ' + packageRef.Package.Id + '-' + resolution.Package.Version.ToString + ' in project : ' + resolution.Project + ' does not satisfy ' + packageRef.Package.Version.ToString ); Inc(errorCount) // exit; //don't exit, we still want to resolve what we can. end; end; context := TResolverContext.Create(FLogger, FPackageInstallerContext, projectFile, compilerVersion, platform, projectReferences); result := DoResolve(cancellationToken, compilerVersion, platform, options.Prerelease, context); resolved := context.GetResolvedPackages; dependencyGraph := context.BuildDependencyGraph; //record the resolutions so they can be applied to other projects in the group FPackageInstallerContext.RecordResolutions(projectFile, platform, context.GetResolutions); result := result and (errorCount = 0); end; function TDependencyResolver.ValidateDependencyGraph(const cancellationToken: ICancellationToken; var dependencyGraph: IPackageReference): boolean; var resolvedPackages: IDictionary<string, TPackageVersion>; begin result := true; resolvedPackages := TCollections.CreateDictionary<string, TPackageVersion>; //check for conflicts in the graph. If there are any then log the conflicts and remove them so restore can repair the graph. dependencyGraph.VisitDFS( procedure(const node: IPackageReference) var pkgVersion : TPackageVersion; begin if resolvedPackages.TryGetValue(LowerCase(node.Id), pkgVersion) then begin end else begin end; end); end; end.
unit zViewSheet_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, dxBar, dxBarExtItems, cxSplitter, cxLabel, cxContainer, cxTextEdit, cxMaskEdit, cxDBEdit, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxDockPanel, dxDockControl, Unit_VedView_Consts, cxMemo, FIBQuery, pFIBQuery, ZProc, Dates, ZTypes, gr_CountSheet_Filter, PackageLoad, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, gr_uCommonConsts, gr_uCommonProc, gr_uCommonTypes, gr_dmCommonStyles, gr_uMessage, cxCurrencyEdit, zcxLocateBar; type TFgrCountSheets = class(TForm) BarManager: TdxBarManager; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; DeleteBtn: TdxBarLargeButton; DSource2: TDataSource; DSource1: TDataSource; DataBase: TpFIBDatabase; DSet2: TpFIBDataSet; DSet1: TpFIBDataSet; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; StoredProc: TpFIBStoredProc; dxBarDockControl2: TdxBarDockControl; FilterBtn: TdxBarLargeButton; DockSite: TdxDockSite; dxDockPanelSpisok: TdxDockPanel; dxDockPanelSheet: TdxDockPanel; dxLayoutDockSite2: TdxLayoutDockSite; dxDockPanelData: TdxDockPanel; ContainerDockSite: TdxTabContainerDockSite; dxLayoutDockSite1: TdxLayoutDockSite; Grid1DBTableView1: TcxGridDBTableView; Grid1Level1: TcxGridLevel; Grid1: TcxGrid; Grid3DBTableView1: TcxGridDBTableView; Grid3Level1: TcxGridLevel; Grid3: TcxGrid; Grid2DBTableView1: TcxGridDBTableView; Grid2Level1: TcxGridLevel; Grid2: TcxGrid; Grid3ClNameVidOpl: TcxGridDBColumn; Grid3ClKodVidOpl: TcxGridDBColumn; Grid3ClSumma: TcxGridDBColumn; Grid1ClKodSheet: TcxGridDBColumn; Grid1ClViplata: TcxGridDBColumn; Grid1ClKodSetup: TcxGridDBColumn; Grid2ClTn: TcxGridDBColumn; Grid2ClFIO: TcxGridDBColumn; Grid2ClSumma: TcxGridDBColumn; Grid2ClTin: TcxGridDBColumn; Grid1ClKodSmeta: TcxGridDBColumn; Grid1ClKodDepartment: TcxGridDBColumn; Grid1ClTypePayment: TcxGridDBColumn; BarDockControlLocate: TdxBarDockControl; cxSplitter1: TcxSplitter; Panel1: TPanel; cxDBTextEdit1: TcxDBTextEdit; cxDBTextEdit2: TcxDBTextEdit; cxDBTextEdit3: TcxDBTextEdit; Grid1ClKurs: TcxGridDBColumn; LabelSmeta: TcxLabel; LabelDepartment: TcxLabel; LabelTypeSheet: TcxLabel; DSet3: TpFIBDataSet; DSource3: TDataSource; Grid3ClP1: TcxGridDBColumn; Grid3ClKodSetup3: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ExitBtnClick(Sender: TObject); procedure Panel1Resize(Sender: TObject); procedure ContainerDockSiteActiveChildChanged( Sender: TdxContainerDockSite; Child: TdxCustomDockControl); procedure RefreshBtnClick(Sender: TObject); procedure cxGrid2DBTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure Grid3ClP1GetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure DeleteBtnClick(Sender: TObject); procedure FilterBtnClick(Sender: TObject); private PParameter:UVVedFilter; PMode:TUVTypeViewSheet; PlanguageIndex:byte; pStylesDM:TStylesDM; pTypeForm:TgrUVParam; pLocateBar:TZBarLocate; pSizePanelDopData:integer; public constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE;ATypeView:TgrUVParam;AParameter:UVVedFilter);reintroduce; property Mode:TUVTypeViewSheet read PMode; end; function View_CountSheet(AParameter:TObject):Variant; stdcall; exports View_CountSheet; implementation uses StrUtils, gr_uCommonLoader; {$R *.dfm} function View_CountSheet(AParameter:TObject):Variant; var ViewForm: TFgrCountSheets; Parameter:UVVedFilter; i:integer; f:boolean; begin Parameter.Id_smeta:=0; Parameter.Id_department:=0; Parameter.Kod_Setup:=0; Parameter.Kod:=0; Parameter.Id_man:=0; Parameter.ModalResult := mrYes; F:=True; for i:=Application.MainForm.MDIChildCount-1 downto 0 do if (Application.MainForm.MDIChildren[i].ClassType = TFgrCountSheets) then if (Application.MainForm.MDIChildren[i] as TFgrCountSheets).mode=TgrPriznakSimpleParam(AParameter).Priznak then begin Application.MainForm.MDIChildren[i].BringToFront; F:=False; break; end; if F then begin if TgrPriznakSimpleParam(AParameter).Priznak=uvpFilter then Parameter := ViewFilter(TgrSimpleParam(AParameter).Owner, TgrSimpleParam(AParameter).DB_Handle, Parameter,TgrPriznakSimpleParam(AParameter).Priznak); if Parameter.ModalResult=mrYes then ViewForm := TFgrCountSheets.Create(TgrSimpleParam(AParameter).Owner, TgrSimpleParam(AParameter).DB_Handle, TgrPriznakSimpleParam(AParameter).Priznak, Parameter); end; Result:=NULL; end; constructor TFgrCountSheets.Create(AOwner : TComponent;DB:TISC_DB_HANDLE;ATypeView:TgrUVParam;AParameter:UVVedFilter); begin Inherited Create(AOwner); //------------------------------------------------------------------------------ PlanguageIndex := IndexLanguage; PParameter := AParameter; pStylesDM := TStylesDM.Create(self); pTypeForm := ATypeView; pSizePanelDopData := Panel1.Width - cxDBTextEdit1.Width; //------------------------------------------------------------------------------ case ATypeView of uvpFilter: begin Caption := LocateAndFilter_Text[PLanguageIndex]; DeleteBtn.Visible := ivNever; FilterBtn.Visible := ivAlways; DSet1.SQLs.SelectSQL.text := 'SELECT * FROM GR_UV_SELECT_GRSHEET('+ IFThen(PParameter.Kod_Setup=0,'NULL',IntToStr(PParameter.Kod_Setup))+','+ IfThen(PParameter.Kod=0,'NULL',IntToStr(PParameter.Kod))+','+ IfThen(PParameter.Id_man=0,'NULL',IntToStr(PParameter.Id_man))+','+ IFThen(PParameter.Id_Department=0,'NULL',IntToStr(PParameter.Id_department))+','+ IFThen(PParameter.Id_smeta=0,'NULL',IntToStr(PParameter.Id_smeta))+',0,''T'')'; end; uvpCurrent: begin Caption := PeriodVed_Text[PLanguageIndex]; DeleteBtn.Visible := ivAlways; FilterBtn.Visible := ivAlways; DSet1.SQLs.SelectSQL.text := 'SELECT * FROM GR_UV_SELECT_GRSHEET(NULL,NULL,NULL,NULL,NULL,0,''T'')'; end; uvpNotSaved: begin Caption := ViewVedData_Text[PLanguageIndex]; DeleteBtn.Visible := ivAlways; DeleteBtn.Enabled := True; FilterBtn.Visible := ivAlways; DSet1.SQLs.SelectSQL.text := 'SELECT * FROM GR_UV_SELECT_GRSHEET(NULL,NULL,NULL,NULL,NULL,1,''T'')'; end; end; DSet2.SQLs.SelectSQL.Text := 'SELECT * FROM UV_SHEET_LIST_PEOPLE(:ID_GRSHEET)'; DSet3.SQLs.SelectSQL.Text := 'SELECT * FROM UV_SHEETPRO_SELECTMAN(:ID_SHEET)'; //------------------------------------------------------------------------------ RefreshBtn.Caption := RefreshBtn_Caption[PlanguageIndex]; DeleteBtn.Caption := DeleteBtn_Caption[PlanguageIndex]; FilterBtn.Caption := FilterBtn_Caption[PlanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[PlanguageIndex]; Grid1ClKodSheet.Caption := GridClKod_Caption[PlanguageIndex]; Grid1ClViplata.Caption := GridClViplata_Caption[PlanguageIndex]; Grid1ClKodSetup.Caption := GridClKodSetup_Caption[PlanguageIndex]; Grid1ClKodSmeta.Caption := GridClKodSmeta_Caption[PlanguageIndex]; Grid1ClKodDepartment.Caption := GridClKodDepartment_Caption[PlanguageIndex]; Grid1ClTypePayment.Caption := GridClTypeViplata_Caption[PlanguageIndex]; Grid1ClKurs.Caption := GridClKurs_Caption[PlanguageIndex]; Grid2ClTn.Caption := GridClTn_Caption[PlanguageIndex]; Grid2ClFIO.Caption := GridClFIO_Caption[PlanguageIndex]; Grid2ClSumma.Caption := GridClSumma_Caption[PlanguageIndex]; Grid2ClTin.Caption := GridClTin_Caption[PlanguageIndex]; Grid3ClNameVidOpl.Caption := GridClNameVo_Caption[PlanguageIndex]; Grid3ClKodVidOpl.Caption := GridClKodVo_Caption[PlanguageIndex]; Grid3ClSumma.Caption := GridClSumma_Caption[PlanguageIndex]; Grid3ClKodSetup3.Caption := GridClKodSetup_Caption[PlanguageIndex]; Grid3ClP1.Caption := GridClP1_Caption[PlanguageIndex]; dxDockPanelSpisok.Caption := Spisok_Text[PlanguageIndex]; dxDockPanelSheet.Caption := Sheets_Text[PlanguageIndex]; dxDockPanelData.Caption := Data_Text[PlanguageIndex]; LabelDepartment.Caption := LabelDepartment_Caption[PlanguageIndex]; LabelSmeta.Caption := LabelSmeta_Caption[PlanguageIndex]; LabelTypeSheet.Caption := LabelTypeSheet_Caption[PlanguageIndex]; Grid3DBTableView1.DataController.Summary.FooterSummaryItems[1].Format := Summary_Text[PlanguageIndex]; //------------------------------------------------------------------------------ DataBase.Handle := DB; DSet1.Open; DSet2.Open; //------------------------------------------------------------------------------ SetOptionsGridView(Grid1DBTableView1); SetOptionsGridView(Grid2DBTableView1); SetOptionsGridView(Grid3DBTableView1); SetOptionsBarManager(BarManager); Grid1DBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; Grid2DBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; Grid3DBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; SetOptionsBarManager(BarManager); Grid3DBTableView1.OptionsView.Footer := True; //------------------------------------------------------------------------------ pLocateBar := TZBarLocate.Create(BarManager); pLocateBar.DataSet := DSet2; pLocateBar.AddLocateItem('TIN',Grid2ClTin.Caption,[loCaseInsensitive,loPartialKey]); pLocateBar.AddLocateItem('FIO',Grid2ClFIO.Caption,[loCaseInsensitive,loPartialKey]); pLocateBar.DigitalField := 'TIN'; pLocateBar.DockControl := BarDockControlLocate; pLocateBar.BorderStyle := bbsNone; BarDockControlLocate.SunkenBorder := False; dxBarDockControl2.SunkenBorder := True; //------------------------------------------------------------------------------ WindowState := wsMaximized; //------------------------------------------------------------------------------ end; procedure TFgrCountSheets.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; Action := caFree; end; procedure TFgrCountSheets.ExitBtnClick(Sender: TObject); begin Close; end; procedure TFgrCountSheets.Panel1Resize(Sender: TObject); begin cxDBTextEdit1.Width := Panel1.Width-pSizePanelDopData; cxDBTextEdit2.Width := cxDBTextEdit1.Width; cxDBTextEdit3.Width := cxDBTextEdit1.Width; end; procedure TFgrCountSheets.ContainerDockSiteActiveChildChanged( Sender: TdxContainerDockSite; Child: TdxCustomDockControl); begin if Child=dxDockPanelData then begin if (not DSet3.Active) and (DSet3.SQLs.SelectSQL.Text<>'') then DSet3.Open; end else if (DSet2<>nil) and (DSet3.Active) then DSet3.Close; end; procedure TFgrCountSheets.RefreshBtnClick(Sender: TObject); begin if ContainerDockSite.ActiveChild=dxDockPanelData then if DSet3.Active then DSet3.Close; if DSet2.Active then DSet2.Close; if DSet1.Active then DSet1.Close; DSet1.Open; DSet2.Open; if ContainerDockSite.ActiveChild=dxDockPanelData then DSet3.Open; end; procedure TFgrCountSheets.cxGrid2DBTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var AItem: TcxGridTableSummaryItem; begin AItem := TcxGridTableSummaryItem(Arguments.SummaryItem); if (AItem.Column = Grid3ClSumma) and (AItem.Kind = skSum) and (AItem.Position = spFooter) then begin if (VarToStr(Grid3DBTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F') then OutArguments.Value:=-OutArguments.Value; end; end; procedure TFgrCountSheets.Grid3ClP1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='False' then AText:=GridClP1_Ud_Text[PLanguageIndex]; if AText='True' then AText:=GridClP1_Nar_Text[PLanguageIndex]; end; procedure TFgrCountSheets.Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if Trim(AText)<>'' then AText:=grConvertKodSetupToStrPeriod(StrToInt(AText),kspMonthNumYearShort); end; procedure TFgrCountSheets.DeleteBtnClick(Sender: TObject); begin if VarIsNULL(DSet1['ID_GRSHEET']) then Exit; if grShowMessage(Caption_Delete[PlanguageIndex],DeleteRecordQuestion_Text[PlanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then try StoredProc.StoredProcName := 'UV_DELETE_SHEET'; StoredProc.Transaction.StartTransaction; StoredProc.Prepare; StoredProc.ParamByName('ID_GRSHEET').AsInteger := DSet1['ID_GRSHEET']; StoredProc.ExecProc; StoredProc.Transaction.Commit; DSet1.SQLs.DeleteSQL.Text := 'execute procedure Z_EMPTY_PROC'; DSet1.Delete; DSet1.SQLs.DeleteSQL.Text := ''; except on e:exception do begin StoredProc.Transaction.Rollback; grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOk]); end; end; end; procedure TFgrCountSheets.FilterBtnClick(Sender: TObject); begin PParameter := ViewFilter(self,DataBase.Handle,PParameter,pTypeForm); if PParameter.ModalResult=mrYes then begin if ContainerDockSite.ActiveChild=dxDockPanelData then if DSet3.Active then DSet3.Close; if DSet2.Active then DSet2.Close; if DSet1.Active then DSet1.Close; DSet1.SQLs.SelectSQL.text := 'SELECT * FROM UV_SELECT_GRSHEET('+ IFThen(PParameter.Kod_Setup=0,'NULL',IntToStr(PParameter.Kod_Setup))+','+ IfThen(PParameter.Kod=0,'NULL',IntToStr(PParameter.Kod))+','+ IfThen(PParameter.Id_man=0,'NULL',IntToStr(PParameter.Id_man))+','+ IFThen(PParameter.Id_Department=0,'NULL',IntToStr(PParameter.Id_department))+','+ IFThen(PParameter.Id_smeta=0,'NULL',IntToStr(PParameter.Id_smeta))+','+ ifThen(pTypeForm=uvpNotSaved,'1','0')+')'; DSet1.Open; DSet2.Open; if ContainerDockSite.ActiveChild=dxDockPanelData then DSet3.Open; end; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083239 //////////////////////////////////////////////////////////////////////////////// unit java.nio.file.AccessMode; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JAccessMode = interface; JAccessModeClass = interface(JObjectClass) ['{6F48CC19-8AD8-4693-B242-474D42CC6CD6}'] function _GetEXECUTE : JAccessMode; cdecl; // A: $4019 function _GetREAD : JAccessMode; cdecl; // A: $4019 function _GetWRITE : JAccessMode; cdecl; // A: $4019 function valueOf(&name : JString) : JAccessMode; cdecl; // (Ljava/lang/String;)Ljava/nio/file/AccessMode; A: $9 function values : TJavaArray<JAccessMode>; cdecl; // ()[Ljava/nio/file/AccessMode; A: $9 property &READ : JAccessMode read _GetREAD; // Ljava/nio/file/AccessMode; A: $4019 property &WRITE : JAccessMode read _GetWRITE; // Ljava/nio/file/AccessMode; A: $4019 property EXECUTE : JAccessMode read _GetEXECUTE; // Ljava/nio/file/AccessMode; A: $4019 end; [JavaSignature('java/nio/file/AccessMode')] JAccessMode = interface(JObject) ['{B7F16F32-12D8-4F7E-882E-93ACA2A0BAC9}'] end; TJAccessMode = class(TJavaGenericImport<JAccessModeClass, JAccessMode>) end; implementation end.
{*******************************************************} { } { 软件名称 W.MIS CLIENT MODEL } { 版权所有 (C) 2003, 2004 Esquel.IT } { 单元名称 UVersionInfo.pas } { 创建日期 2004-8-3 14:36:40 } { 创建人员 wuwj } { } {*******************************************************} unit UVersionInfo; {* 获取应用程序版本类单元 } interface uses Windows, Types, SysUtils, Dialogs, uShowMessage; type TExeVersionInfo = class(TObject) private FProductName: string; FProductVersion: string; FFileDescription: string; FLegalCopyright: string; FFileVersion: string; FCompanyName: string; FLegalTradeMarks: string; FInternalName: string; FOriginalFileName: string; FExeFullName: string; protected procedure GetVersionInfo; public Constructor Create(AExeFullName:string); property ProductName: string read FProductName; property ProductVersion: string read FProductVersion; property FileDescription: string read FFileDescription; property LegalCopyright: string read FLegalCopyright; property FileVersion: string read FFileVersion; property CompanyName: string read FCompanyName; property LegalTradeMarks: string read FLegalTradeMarks; property InternalName: string read FInternalName; property OriginalFileName: string read FOriginalFileName; end; implementation constructor TExeVersionInfo.Create(AExeFullName:string); begin FExeFullName:=AExeFullName; GetVersionInfo; end; procedure TExeVersionInfo.GetVersionInfo; const InfoNum = 9; InfoStr: array[1..InfoNum] of string = ( 'ProductName', 'ProductVersion', 'FileDescription', 'LegalCopyright', 'FileVersion', 'CompanyName', 'LegalTradeMarks', 'InternalName', 'OriginalFileName'); var S: string; BufSize, Len: DWORD; Buf: PChar; Value: PChar; begin S := FExeFullName; BufSize := GetFileVersionInfoSize(PChar(S), BufSize); if BufSize > 0 then begin Buf := AllocMem(BufSize); GetFileVersionInfo(PChar(S), 0, BufSize, Buf); if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[1]), Pointer(Value), Len) then FProductName := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[2]), Pointer(Value), Len) then FProductVersion := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[3]), Pointer(Value), Len) then FFileDescription := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[4]), Pointer(Value), Len) then FLegalCopyright := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[5]), Pointer(Value), Len) then FFileVersion := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[6]), Pointer(Value), Len) then FCompanyName := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[7]), Pointer(Value), Len) then FLegalTrademarks := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[8]), Pointer(Value), Len) then FInternalName := Value; if VerQueryValue(Buf, PChar('StringFileInfo\080403A8\' + InfoStr[9]), Pointer(Value), Len) then FOriginalFilename := Value; FreeMem(Buf, BufSize); end else begin TMsgDialog.ShowMsgDialog('获取产品信息时遇到错误,请检查工程文件的选项设置是否包含了版本信息!。', mtError); end; end; end.
unit FreeOTFEDLLHashAPI; // API ported from FreeOTFE4PDAHashAPI.h interface uses OTFEFreeOTFE_DriverHashAPI, Windows; //#define DLLEXPORT_HASH_IDENTIFYDRIVER TEXT("HashIdentifyDriver") //typedef DWORD (* PHashDLLFnIdentifyDriver)( // DIOC_HASH_IDENTIFYDRIVER* // ); const DLLEXPORT_HASH_IDENTIFYDRIVER = 'HashIdentifyDriver'; type PHashDLLFnIdentifyDriver = function(Buffer: PDIOC_HASH_IDENTIFYDRIVER): DWORD; CDECL; //#define DLLEXPORT_HASH_IDENTIFYSUPPORTED TEXT("HashIdentifySupported") //typedef DWORD (* PHashDLLFnIdentifySupported)( // DWORD, // DIOC_HASH_IDENTIFYSUPPORTED* // ); const DLLEXPORT_HASH_IDENTIFYSUPPORTED = 'HashIdentifySupported'; type PHashDLLFnIdentifySupported = function(BufferSize: DWORD; // In bytes Buffer: PDIOC_HASH_IDENTIFYSUPPORTED): DWORD; CDECL; //#define DLLEXPORT_HASH_GETHASHDETAILS TEXT("HashGetHashDetails") //typedef DWORD (* PHashDLLFnGetHashDetails)( // GUID*, // HASH* // ); const DLLEXPORT_HASH_GETHASHDETAILS = 'HashGetHashDetails'; type PHashDLLFnGetHashDetails = function(HashGUID: PGUID; HashDetails: PHASH): DWORD; CDECL; //#define DLLEXPORT_HASH_HASH TEXT("HashHash") //typedef DWORD (* PHashDLLFnHash)( // GUID*, // unsigned int, // FREEOTFEBYTE*, // unsigned int*, // FREEOTFEBYTE* // ); const DLLEXPORT_HASH_HASH = 'HashHash'; type PHashDLLFnHash = function(HashGUID: PGUID; BufferSizeIn: Cardinal; BufferIn: PByte; ptrBufferSizeOut: PCardinal; BufferOut: PByte): DWORD; CDECL; implementation end.
{ ----------------------------------------------------------------------------- Unit Name: LibraryHelperU Author: Tristan Marlow Purpose: Library Helper ---------------------------------------------------------------------------- Copyright (c) 2016 Tristan David Marlow Copyright (c) 2016 Little Earth Solutions All Rights Reserved This product is protected by copyright and distributed under licenses restricting copying, distribution and decompilation ---------------------------------------------------------------------------- History: ----------------------------------------------------------------------------- } unit LibraryHelperU; {$WARN SYMBOL_PLATFORM OFF} interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections, LibraryPathsU; type TDelphiLibrary = (dlAndroid32, dlAndroid64, dlIOS32, dlIOS64, dlIOSimulator, dlOSX32, dlOSX64, dlOSXARM64, dlWin32, dlWin64, dlLinux64); type TEnviromentVariable = class private FName: string; FValue: string; procedure SetName(const Value: string); procedure SetValue(const Value: string); public property Name: string read FName write SetName; property Value: string read FValue write SetValue; end; type TEnviromentVariableList = TObjectList<TEnviromentVariable>; type TEnvironmentVariables = class private FEnviromentVariableList: TEnviromentVariableList; function GetValue(AName: string): string; function GetVariable(AIndex: integer): TEnviromentVariable; procedure SetValue(AName: string; const Value: string); protected public function FindVariable(AName: string): TEnviromentVariable; constructor Create; destructor Destroy; override; function Count: integer; function Add(AName: string; AValue: string): integer; procedure Clear; property Variable[AIndex: integer]: TEnviromentVariable read GetVariable; property Value[AName: string]: string read GetValue write SetValue; end; type TDelphiInstallation = class private FRegistryKey: string; FEnvironmentVariables: TEnvironmentVariables; FSystemEnvironmentVariables: TEnvironmentVariables; FLibraryAndroid32: TLibraryPaths; FLibraryAndroid64: TLibraryPaths; FLibraryIOS32: TLibraryPaths; FLibraryIOS64: TLibraryPaths; FLibraryIOSSimulator: TLibraryPaths; FLibraryOSX32: TLibraryPaths; FLibraryOSX64: TLibraryPaths; FLibraryOSXARM64: TLibraryPaths; FLibraryWin32: TLibraryPaths; FLibraryWin64: TLibraryPaths; FLibraryLinux64: TLibraryPaths; FLibraryPathType: TLibraryPathType; function GetInstalled: boolean; function GetProductName: string; procedure SaveEnvironmentVariables; procedure LoadEnvironmentVariables; procedure LoadSystemEnvironmentVariables; procedure LoadLibraries; procedure SaveLibraries; procedure SetLibraryAndroid32(const Value: string); procedure SetLibraryIOS32(const Value: string); procedure SetLibraryIOS64(const Value: string); procedure SetLibraryIOSSimulator(const Value: string); procedure SetLibraryOSX32(const Value: string); procedure SetLibraryWin32(const Value: string); procedure SetLibraryWin64(const Value: string); function LoadLibrary(ALibrary: string; APathType: TLibraryPathType): string; procedure SaveLibrary(ALibrary: string; AValue: string; APathType: TLibraryPathType); function GetLibraryAndroid32: string; function GetLibraryIOS32: string; function GetLibraryIOS64: string; function GetLibraryIOSSimulator: string; function GetLibraryOSX32: string; function GetLibraryWin32: string; function GetLibraryWin64: string; function GetLibraryLinux64: string; procedure SetLibraryLinux64(const Value: string); function GetRootPath: string; function GetBinPath: string; function GetBDSPublicFolder(AFolder: string): string; function GetBDSUserFolder(AFolder: string): string; function GetLibraryPathAsString(AStrings: TLibraryPaths): string; procedure SetLibraryPathFromString(AString: string; AStrings: TLibraryPaths; ALibrary: TDelphiLibrary); function CreateLibraryPaths: TLibraryPaths; function GetProductVersion: integer; function GetStudioVersion: integer; function ApplyTemplatePaths(ATemplateLibraryPaths: TLibraryPaths; ALibraryPaths: TLibraryPaths): integer; function GetAllEnvironemntVariables(const Vars: TStrings): integer; function GetShellFolderPath(AFolder: integer): string; function GetDocumentFolder: string; function GetPublicDocumentFolder: string; procedure NotifyEnvironmentChanges; procedure SetLibraryPathType(const Value: TLibraryPathType); procedure RemoveInvalidPaths(ALibraryPaths: TLibraryPaths; ALibrary: TDelphiLibrary); function RemoveBrowseFromSearchPaths(ALibraryPaths: TLibraryPaths; ADelphiLibrary: TDelphiLibrary; ASmartEnabled: boolean): integer; procedure FileSearch(const PathName, FileName: string; const Recurse: boolean; FileList: TStrings); function FolderContainsFiles(const PathName: string; FileName: string = '*.*'; const Recurse: boolean = true): boolean; function DeduplicatPaths(ALibraryPaths: TLibraryPaths; ALibrary: TDelphiLibrary): integer; function CopyLibraryPaths(ASourcePaths: TLibraryPaths; ASourcePathType: TLibraryPathType; ADestPaths: TLibraryPaths; ADestPathType: TLibraryPathType; ASkipBDSPaths: boolean = true): integer; function GetLibraryAndroid64: string; function GetLibraryOSX64: string; function GetLibraryOSXARM64: string; procedure SetLibraryAndroid64(const Value: string); procedure SetLibraryOSX64(const Value: string); procedure SetLibraryOSXARM64(const Value: string); public constructor Create(ARegistryKey: string); destructor Destroy; override; procedure Load; procedure Save(ADeduplicate: boolean); procedure Cleanup; procedure CopyBrowseToSearch; procedure CopySearchToBrowse; procedure DeleteAll(APathType: TLibraryPathType = dlpAll); function Deduplicate: integer; function RemoveBrowseFromSearch(ASmartEnabled: boolean): integer; procedure ExportLibrary(AFileName: TFileName); procedure ImportLibrary(AFileName: TFileName); function Apply(ALibraryPathTemplate: TLibraryPathTemplate) : integer; overload; function Apply(AFileName: TFileName): integer; overload; function AddPath(APath: string; ALibrary: TDelphiLibrary; ALibraryPathType: TLibraryPathType = dlpNone): boolean; function OpenFolder(AFolder: string; ALibrary: TDelphiLibrary): boolean; function ExecuteFile(const Operation, FileName, Params, DefaultDir: string; ShowCmd: word): integer; function GetLibraryName(ALibrary: TDelphiLibrary): string; function GetLibraryPlatformName(ALibrary: TDelphiLibrary): string; procedure CopyToClipBoard(APath: string; ALibrary: TDelphiLibrary; AExpand: boolean = true); procedure ForceEnvOptionsUpdate; function ExpandLibraryPath(APath: string; ALibrary: TDelphiLibrary): string; property LibraryPathType: TLibraryPathType read FLibraryPathType write SetLibraryPathType; property Installed: boolean read GetInstalled; property ProductVersion: integer read GetProductVersion; property ProductName: string read GetProductName; property RootPath: string read GetRootPath; property EnvironmentVariables: TEnvironmentVariables read FEnvironmentVariables; property SystemEnvironmentVariables: TEnvironmentVariables read FSystemEnvironmentVariables; procedure LibraryAsStrings(AStrings: TStrings; ADelphiLibrary: TDelphiLibrary); property LibraryWin32: string read GetLibraryWin32 write SetLibraryWin32; property LibraryWin64: string read GetLibraryWin64 write SetLibraryWin64; property LibraryOSX32: string read GetLibraryOSX32 write SetLibraryOSX32; property LibraryOSX64: string read GetLibraryOSX64 write SetLibraryOSX64; property LibraryOSXARM64: string read GetLibraryOSXARM64 write SetLibraryOSXARM64; property LibraryAndroid32: string read GetLibraryAndroid32 write SetLibraryAndroid32; property LibraryAndroid64: string read GetLibraryAndroid64 write SetLibraryAndroid64; property LibraryIOS32: string read GetLibraryIOS32 write SetLibraryIOS32; property LibraryIOS64: string read GetLibraryIOS64 write SetLibraryIOS64; property LibraryIOSSimulator: string read GetLibraryIOSSimulator write SetLibraryIOSSimulator; property LibraryLinux64: string read GetLibraryLinux64 write SetLibraryLinux64; end; type TDelphiInstallationList = TObjectList<TDelphiInstallation>; type TLibraryHelper = class(TObject) private FDelphiInstallationList: TDelphiInstallationList; function GetInstallation(AIndex: integer): TDelphiInstallation; function IsProcessRunning(AFileName: string): boolean; protected procedure GetDelphiInstallations; function FindInstallation(AProductName: string): TDelphiInstallation; public constructor Create; destructor Destroy; override; procedure Load; function Count: integer; function InstalledCount: integer; function IsDelphiRunning: boolean; function GetLibraryName(ADelphiLibrary: TDelphiLibrary): string; function GetLibraryPlatformName(ADelphiLibrary: TDelphiLibrary): string; procedure GetLibraryNames(AStrings: TStrings); property Installations[AIndex: integer]: TDelphiInstallation read GetInstallation; property Installation[AProductName: string]: TDelphiInstallation read FindInstallation; end; implementation uses System.Win.Registry, Winapi.ShellAPI, Vcl.Forms, Winapi.TlHelp32, Clipbrd, Winapi.ShlObj, System.IniFiles, LoggingU, System.StrUtils; constructor TLibraryHelper.Create; begin FDelphiInstallationList := TDelphiInstallationList.Create; end; destructor TLibraryHelper.Destroy; begin try FreeAndNil(FDelphiInstallationList); finally inherited; end; end; function TLibraryHelper.FindInstallation(AProductName: string) : TDelphiInstallation; var LIdx: integer; begin Result := nil; LIdx := 0; while (LIdx < Count) and (Result = nil) do begin if SameText(FDelphiInstallationList.Items[LIdx].ProductName, AProductName) then begin Result := FDelphiInstallationList.Items[LIdx]; end; Inc(LIdx); end; end; procedure TLibraryHelper.GetDelphiInstallations; const BDS_KEY = 'SOFTWARE\Embarcadero\BDS'; var LRegistry: TRegistry; LKeys: TStringList; LKeyIdx: integer; LKeyName: string; begin LRegistry := TRegistry.Create; LKeys := TStringList.Create; try LRegistry.RootKey := HKEY_LOCAL_MACHINE; if LRegistry.OpenKeyReadOnly(BDS_KEY) then begin LRegistry.GetKeyNames(LKeys); for LKeyIdx := 0 to PreD(LKeys.Count) do begin LKeyName := IncludeTrailingBackslash(BDS_KEY) + LKeys[LKeyIdx]; LRegistry.CloseKey; if LRegistry.OpenKeyReadOnly(LKeyName) then begin FDelphiInstallationList.Add(TDelphiInstallation.Create(LKeyName)); LRegistry.CloseKey; end; end; end; finally FreeAndNil(LRegistry); FreeAndNil(LKeys); end; end; function TLibraryHelper.GetInstallation(AIndex: integer): TDelphiInstallation; begin Result := FDelphiInstallationList.Items[AIndex]; end; procedure TLibraryHelper.GetLibraryNames(AStrings: TStrings); var LDelphiLibrary: TDelphiLibrary; begin AStrings.Clear; for LDelphiLibrary := Low(TDelphiLibrary) to High(TDelphiLibrary) do begin AStrings.Add(GetLibraryName(LDelphiLibrary)); end; end; function TLibraryHelper.GetLibraryName(ADelphiLibrary: TDelphiLibrary): string; begin Result := 'Unknown Library (' + IntToStr(integer(ADelphiLibrary)) + ')'; case ADelphiLibrary of dlAndroid32: Result := 'Android32'; dlAndroid64: Result := 'Android64'; dlIOS32: Result := 'iOS32'; dlIOS64: Result := 'iOS64'; dlIOSimulator: Result := 'iOSSimulator'; dlOSX32: Result := 'OSX32'; dlOSX64: Result := 'OSX64'; dlOSXARM64: Result := 'OSXARM64'; dlWin32: Result := 'Win32'; dlWin64: Result := 'Win64'; dlLinux64: Result := 'Linux64'; end; end; function TLibraryHelper.GetLibraryPlatformName(ADelphiLibrary : TDelphiLibrary): string; begin Result := ''; case ADelphiLibrary of dlAndroid32: Result := 'android32'; dlAndroid64: Result := 'android64'; dlIOS32: Result := 'iosdevice32'; dlIOS64: Result := 'iosdevice64'; dlIOSimulator: Result := 'iossimulator'; dlOSX32: Result := 'osx32'; dlOSX64: Result := 'osx64'; dlOSXARM64: Result := 'osxarm64'; dlWin32: Result := 'win32'; dlWin64: Result := 'win64'; dlLinux64: Result := 'linux64'; end; end; function TLibraryHelper.Count: integer; begin Result := FDelphiInstallationList.Count; end; function TLibraryHelper.IsProcessRunning(AFileName: string): boolean; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); Result := False; while integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(AFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(AFileName))) then begin Result := true; end; ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; function TLibraryHelper.InstalledCount: integer; var LIdx: integer; begin Result := 0; for LIdx := 0 to PreD(Count) do begin if Installations[LIdx].Installed then Inc(Result); end; end; function TLibraryHelper.IsDelphiRunning: boolean; begin Result := IsProcessRunning('bds.exe'); Debug('IsDelphiRunning', BoolToStr(Result, true)); end; procedure TLibraryHelper.Load; begin GetDelphiInstallations; end; { TDelphiVersion } function TDelphiInstallation.Apply(ALibraryPathTemplate : TLibraryPathTemplate): integer; begin Result := 0; Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryAndroid32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryAndroid32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Android32, FLibraryAndroid32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryIOS32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryIOS32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.IOS32, FLibraryIOS32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryIOS64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryIOS64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.IOS64, FLibraryIOS64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryIOSSimulator); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryIOSSimulator); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.IOS32, FLibraryIOSSimulator); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryOSX32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryOSX32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.OSX32, FLibraryOSX32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryWin32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryWin32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonVCL, FLibraryWin32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Win32, FLibraryWin32); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryWin64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryWin64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonVCL, FLibraryWin64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Win64, FLibraryWin64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Common, FLibraryLinux64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.CommonFMX, FLibraryLinux64); Result := Result + ApplyTemplatePaths(ALibraryPathTemplate.Linux64, FLibraryLinux64); Log('Template applied %d path(s)', [Result]); end; function TDelphiInstallation.AddPath(APath: string; ALibrary: TDelphiLibrary; ALibraryPathType: TLibraryPathType): boolean; var LPath: string; LLibraryPathType: TLibraryPathType; begin LLibraryPathType := ALibraryPathType; if LLibraryPathType = dlpNone then LLibraryPathType := FLibraryPathType; Result := False; LPath := APath; LPath := ExpandLibraryPath(LPath, ALibrary); if (Trim(LPath) <> '') and (DirectoryExists(LPath)) then begin case ALibrary of dlAndroid32: FLibraryAndroid32.Add(APath, LLibraryPathType); dlAndroid64: FLibraryAndroid64.Add(APath, LLibraryPathType); dlIOS32: FLibraryIOS32.Add(APath, LLibraryPathType); dlIOS64: FLibraryIOS64.Add(APath, LLibraryPathType); dlIOSimulator: FLibraryIOSSimulator.Add(APath, LLibraryPathType); dlOSX32: FLibraryOSX32.Add(APath, LLibraryPathType); dlOSX64: FLibraryOSX64.Add(APath, LLibraryPathType); dlOSXARM64: FLibraryOSXARM64.Add(APath, LLibraryPathType); dlWin32: FLibraryWin32.Add(APath, LLibraryPathType); dlWin64: FLibraryWin64.Add(APath, LLibraryPathType); end; Result := true; end; end; function TDelphiInstallation.Apply(AFileName: TFileName): integer; var LLibraryPathTemplate: TLibraryPathTemplate; begin LLibraryPathTemplate := TLibraryPathTemplate.Create; try LLibraryPathTemplate.Load(AFileName, GetProductVersion); Result := Apply(LLibraryPathTemplate); finally FreeAndNil(LLibraryPathTemplate); end; end; function TDelphiInstallation.ApplyTemplatePaths(ATemplateLibraryPaths : TLibraryPaths; ALibraryPaths: TLibraryPaths): integer; var LPathIdx: integer; LPath: string; LPathType: TLibraryPathType; begin Result := 0; for LPathIdx := 0 to PreD(ATemplateLibraryPaths.Count) do begin LPath := ATemplateLibraryPaths.Path[LPathIdx].Path; LPathType := ATemplateLibraryPaths.Path[LPathIdx].PathType; if ALibraryPaths.Add(LPath, LPathType, true) <> -1 then begin Log('Template path "%s (%s)" has been added.', [LPath, TLibraryPath.PathTypeToString(LPathType)]); Inc(Result); end; end; end; procedure TDelphiInstallation.Cleanup; begin RemoveInvalidPaths(FLibraryAndroid32, dlAndroid32); RemoveInvalidPaths(FLibraryAndroid64, dlAndroid64); RemoveInvalidPaths(FLibraryIOS32, dlIOS32); RemoveInvalidPaths(FLibraryIOS64, dlIOS64); RemoveInvalidPaths(FLibraryIOSSimulator, dlIOSimulator); RemoveInvalidPaths(FLibraryOSX32, dlOSX32); RemoveInvalidPaths(FLibraryOSX64, dlOSX64); RemoveInvalidPaths(FLibraryOSXARM64, dlOSXARM64); RemoveInvalidPaths(FLibraryWin32, dlWin32); RemoveInvalidPaths(FLibraryWin64, dlWin64); RemoveInvalidPaths(FLibraryLinux64, dlLinux64); end; procedure TDelphiInstallation.CopyBrowseToSearch; begin CopyLibraryPaths(FLibraryAndroid32, dlpBrowse, FLibraryAndroid32, dlpSearch); CopyLibraryPaths(FLibraryIOS32, dlpBrowse, FLibraryIOS32, dlpSearch); CopyLibraryPaths(FLibraryIOS64, dlpBrowse, FLibraryIOS64, dlpSearch); CopyLibraryPaths(FLibraryIOSSimulator, dlpBrowse, FLibraryIOSSimulator, dlpSearch); CopyLibraryPaths(FLibraryOSX32, dlpBrowse, FLibraryOSX32, dlpSearch); CopyLibraryPaths(FLibraryWin32, dlpBrowse, FLibraryWin32, dlpSearch); CopyLibraryPaths(FLibraryWin64, dlpBrowse, FLibraryWin64, dlpSearch); CopyLibraryPaths(FLibraryLinux64, dlpBrowse, FLibraryLinux64, dlpSearch); end; function TDelphiInstallation.CopyLibraryPaths(ASourcePaths: TLibraryPaths; ASourcePathType: TLibraryPathType; ADestPaths: TLibraryPaths; ADestPathType: TLibraryPathType; ASkipBDSPaths: boolean): integer; var LSourcePath: TLibraryPath; LAddPath: boolean; LTotal, LIdx: integer; begin Result := 0; LTotal := ASourcePaths.Count; for LIdx := 0 to LTotal do begin LSourcePath := ASourcePaths.Path[LIdx]; if LSourcePath.PathType = ASourcePathType then begin LAddPath := true; if ASkipBDSPaths then begin LAddPath := StartsText('$(BDS', LSourcePath.Path); end; if LAddPath then begin ADestPaths.Add(LSourcePath.Path, ADestPathType); Inc(Result); end; end; end; end; procedure TDelphiInstallation.CopySearchToBrowse; begin CopyLibraryPaths(FLibraryAndroid32, dlpSearch, FLibraryAndroid32, dlpBrowse); CopyLibraryPaths(FLibraryIOS32, dlpSearch, FLibraryIOS32, dlpBrowse); CopyLibraryPaths(FLibraryIOS64, dlpSearch, FLibraryIOS64, dlpBrowse); CopyLibraryPaths(FLibraryIOSSimulator, dlpSearch, FLibraryIOSSimulator, dlpBrowse); CopyLibraryPaths(FLibraryOSX32, dlpSearch, FLibraryOSX32, dlpBrowse); CopyLibraryPaths(FLibraryWin32, dlpSearch, FLibraryWin32, dlpBrowse); CopyLibraryPaths(FLibraryWin64, dlpSearch, FLibraryWin64, dlpBrowse); CopyLibraryPaths(FLibraryLinux64, dlpSearch, FLibraryLinux64, dlpBrowse); end; procedure TDelphiInstallation.CopyToClipBoard(APath: string; ALibrary: TDelphiLibrary; AExpand: boolean); var LPath: string; begin LPath := APath; if AExpand then LPath := ExpandLibraryPath(APath, ALibrary); Clipboard.AsText := LPath; end; constructor TDelphiInstallation.Create(ARegistryKey: string); begin FLibraryPathType := dlpSearch; FRegistryKey := ARegistryKey; FEnvironmentVariables := TEnvironmentVariables.Create; FSystemEnvironmentVariables := TEnvironmentVariables.Create; FLibraryAndroid32 := CreateLibraryPaths; FLibraryAndroid64 := CreateLibraryPaths; FLibraryIOS32 := CreateLibraryPaths; FLibraryIOS64 := CreateLibraryPaths; FLibraryIOSSimulator := CreateLibraryPaths; FLibraryOSX32 := CreateLibraryPaths; FLibraryOSX64 := CreateLibraryPaths; FLibraryOSXARM64 := CreateLibraryPaths; FLibraryWin32 := CreateLibraryPaths; FLibraryWin64 := CreateLibraryPaths; FLibraryLinux64 := CreateLibraryPaths; end; function TDelphiInstallation.CreateLibraryPaths: TLibraryPaths; begin Result := TLibraryPaths.Create; end; function TDelphiInstallation.Deduplicate: integer; begin Result := 0; Result := Result + DeduplicatPaths(FLibraryAndroid32, dlAndroid32); Result := Result + DeduplicatPaths(FLibraryAndroid64, dlAndroid64); Result := Result + DeduplicatPaths(FLibraryIOS32, dlIOS32); Result := Result + DeduplicatPaths(FLibraryIOS64, dlIOS64); Result := Result + DeduplicatPaths(FLibraryIOSSimulator, dlIOSimulator); Result := Result + DeduplicatPaths(FLibraryOSX32, dlOSX32); Result := Result + DeduplicatPaths(FLibraryOSX64, dlOSX64); Result := Result + DeduplicatPaths(FLibraryOSXARM64, dlOSXARM64); Result := Result + DeduplicatPaths(FLibraryWin32, dlWin32); Result := Result + DeduplicatPaths(FLibraryWin64, dlWin64); Result := Result + DeduplicatPaths(FLibraryLinux64, dlLinux64); end; destructor TDelphiInstallation.Destroy; begin try FreeAndNil(FEnvironmentVariables); FreeAndNil(FSystemEnvironmentVariables); FreeAndNil(FLibraryAndroid32); FreeAndNil(FLibraryAndroid64); FreeAndNil(FLibraryIOS32); FreeAndNil(FLibraryIOS64); FreeAndNil(FLibraryIOSSimulator); FreeAndNil(FLibraryOSX32); FreeAndNil(FLibraryOSX64); FreeAndNil(FLibraryOSXARM64); FreeAndNil(FLibraryWin32); FreeAndNil(FLibraryWin64); FreeAndNil(FLibraryLinux64); finally inherited; end; end; function TDelphiInstallation.GetShellFolderPath(AFolder: integer): string; const SHGFP_TYPE_CURRENT = 0; var Path: array [0 .. MAX_PATH] of char; begin if SUCCEEDED(SHGetFolderPath(0, AFolder, 0, SHGFP_TYPE_CURRENT, @Path[0])) then Result := Path else Result := ''; end; function TDelphiInstallation.GetStudioVersion: integer; var LPath: string; begin LPath := GetRootPath; LPath := ExcludeTrailingPathDelimiter(LPath); LPath := ExtractFileName(LPath); LPath := ChangeFileExt(LPath, ''); Result := StrToIntDef(LPath, 0); end; function TDelphiInstallation.GetDocumentFolder: string; begin Result := IncludeTrailingPathDelimiter(GetShellFolderPath(CSIDL_PERSONAL)); end; function TDelphiInstallation.GetPublicDocumentFolder: string; begin Result := IncludeTrailingPathDelimiter (GetShellFolderPath(CSIDL_COMMON_DOCUMENTS)); end; function TDelphiInstallation.ExpandLibraryPath(APath: string; ALibrary: TDelphiLibrary): string; var LVariableIdx: integer; begin Result := APath; Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSBIN)', GetBinPath, [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSCatalogRepositoryAllUsers)', GetBDSPublicFolder('CatalogRepository'), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSCatalogRepository)', GetBDSUserFolder('CatalogRepository'), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSLIB)', GetRootPath + 'lib', [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSINCLUDE)', GetRootPath + 'include', [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSCOMMONDIR)', GetBDSPublicFolder(''), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSPLATFORMSDKDIR)', GetBDSUserFolder('SDKs'), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSPROFILESDIR)', GetBDSUserFolder('Profiles'), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSPROJECTSDIR)', GetBDSUserFolder('Profiles'), [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDSUSERDIR)', GetBDSUserFolder(''), [rfReplaceAll, rfIgnoreCase])); for LVariableIdx := 0 to PreD(FSystemEnvironmentVariables.Count) do begin Result := ExcludeTrailingPathDelimiter(StringReplace(Result, Format('$(%s)', [FSystemEnvironmentVariables.Variable[LVariableIdx].Name] ), FSystemEnvironmentVariables.Variable[LVariableIdx].Value, [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, Format('${%s}', [FSystemEnvironmentVariables.Variable[LVariableIdx].Name] ), FSystemEnvironmentVariables.Variable[LVariableIdx].Value, [rfReplaceAll, rfIgnoreCase])); end; for LVariableIdx := 0 to PreD(FEnvironmentVariables.Count) do begin Result := ExcludeTrailingPathDelimiter(StringReplace(Result, Format('$(%s)', [FEnvironmentVariables.Variable[LVariableIdx].Name]), FEnvironmentVariables.Variable[LVariableIdx].Value, [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, Format('${%s}', [FEnvironmentVariables.Variable[LVariableIdx].Name]), FEnvironmentVariables.Variable[LVariableIdx].Value, [rfReplaceAll, rfIgnoreCase])); end; Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(BDS)', GetRootPath, [rfReplaceAll, rfIgnoreCase])); Result := ExcludeTrailingPathDelimiter(StringReplace(Result, '$(Platform)', GetLibraryPlatformName(ALibrary), [rfReplaceAll, rfIgnoreCase])); Debug('ExpandLibraryPath', '%s => %s', [APath, Result]); end; procedure TDelphiInstallation.ExportLibrary(AFileName: TFileName); var LINIfile: TMemIniFile; LPathType: TLibraryPathType; procedure ExportDelphiLibrary(ALibraryPaths: TLibraryPaths; ADelphiLibrary: TDelphiLibrary); var LLibraryPath: TLibraryPath; LLibraryName: string; LIdx: integer; begin LLibraryName := GetLibraryPlatformName(ADelphiLibrary); for LIdx := 0 to PreD(ALibraryPaths.Count) do begin LLibraryPath := ALibraryPaths.Path[LIdx]; LINIfile.WriteString(LLibraryName, LLibraryPath.Path + ';' + TLibraryPath.PathTypeToString(LLibraryPath.PathType), ''); end; end; begin if FileExists(AFileName) then DeleteFile(AFileName); LINIfile := TMemIniFile.Create(AFileName); try for LPathType := dlpSearch to dlpDebugDCU do begin ExportDelphiLibrary(FLibraryAndroid32, dlAndroid32); ExportDelphiLibrary(FLibraryAndroid64, dlAndroid64); ExportDelphiLibrary(FLibraryIOS32, dlIOS32); ExportDelphiLibrary(FLibraryIOS64, dlIOS64); ExportDelphiLibrary(FLibraryIOSSimulator, dlIOSimulator); ExportDelphiLibrary(FLibraryOSX32, dlOSX32); ExportDelphiLibrary(FLibraryOSX64, dlOSX64); ExportDelphiLibrary(FLibraryOSXARM64, dlOSXARM64); ExportDelphiLibrary(FLibraryWin32, dlWin32); ExportDelphiLibrary(FLibraryWin64, dlWin64); ExportDelphiLibrary(FLibraryLinux64, dlLinux64); end; finally LINIfile.UpdateFile; FreeAndNil(LINIfile); end; end; procedure TDelphiInstallation.ImportLibrary(AFileName: TFileName); var LINIfile: TMemIniFile; procedure ImportDelphiLibrary(ALibrary: TDelphiLibrary); var LLibrary: TStringList; LLibraryName: string; LPath: string; LLibraryPath: TLibraryPathType; LSection: string; begin LLibrary := TStringList.Create; try LLibraryName := GetLibraryName(ALibrary); LINIfile.ReadSection(LLibraryName, LLibrary); for LSection in LLibrary do begin if Pos(';', LSection) > 0 then begin LPath := Copy(LSection, 1, Pos(';', LSection) - 1); LLibraryPath := TLibraryPath.PathTypeFromString (Copy(LSection, Pos(';', LSection) + 1, Length(LSection))); end else begin LPath := LSection; LLibraryPath := dlpNone; end; AddPath(LPath, ALibrary, LLibraryPath); end; finally FreeAndNil(LLibrary); end; end; begin if FileExists(AFileName) then begin LINIfile := TMemIniFile.Create(AFileName); try ImportDelphiLibrary(dlAndroid32); ImportDelphiLibrary(dlAndroid64); ImportDelphiLibrary(dlIOS32); ImportDelphiLibrary(dlIOS64); ImportDelphiLibrary(dlIOSimulator); ImportDelphiLibrary(dlOSX32); ImportDelphiLibrary(dlOSX64); ImportDelphiLibrary(dlOSXARM64); ImportDelphiLibrary(dlWin32); ImportDelphiLibrary(dlWin64); ImportDelphiLibrary(dlLinux64); finally FreeAndNil(LINIfile); end; end; end; procedure TDelphiInstallation.ForceEnvOptionsUpdate; var LRegistry: TRegistry; LRegistryKey: string; begin LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; LRegistryKey := IncludeTrailingBackslash(FRegistryKey); LRegistryKey := IncludeTrailingBackslash(LRegistryKey + 'Globals'); if LRegistry.OpenKey(LRegistryKey, False) then begin LRegistry.WriteInteger('ForceEnvOptionsUpdate', 1); end; finally FreeAndNil(LRegistry); end; end; procedure TDelphiInstallation.NotifyEnvironmentChanges; begin Log('Notify Environment Changes'); SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, NativeInt(PChar('Environment')), SMTO_ABORTIFHUNG, 5000, nil); end; procedure TDelphiInstallation.LibraryAsStrings(AStrings: TStrings; ADelphiLibrary: TDelphiLibrary); begin case ADelphiLibrary of dlAndroid32: AStrings.Text := GetLibraryAndroid32; dlAndroid64: AStrings.Text := GetLibraryAndroid64; dlIOS32: AStrings.Text := GetLibraryIOS32; dlIOS64: AStrings.Text := GetLibraryIOS64; dlIOSimulator: AStrings.Text := GetLibraryIOSSimulator; dlOSX32: AStrings.Text := GetLibraryOSX32; dlOSX64: AStrings.Text := GetLibraryOSX64; dlOSXARM64: AStrings.Text := GetLibraryOSXARM64; dlWin32: AStrings.Text := GetLibraryWin32; dlWin64: AStrings.Text := GetLibraryWin64; dlLinux64: AStrings.Text := GetLibraryLinux64; end; end; procedure TDelphiInstallation.Load; begin LoadSystemEnvironmentVariables; LoadEnvironmentVariables; LoadLibraries; end; procedure TDelphiInstallation.LoadEnvironmentVariables; var LRegistry: TRegistry; LLibraryKey: string; LValues: TStringList; LIdx: integer; LName: string; begin FEnvironmentVariables.Clear; LRegistry := TRegistry.Create; LValues := TStringList.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; LLibraryKey := IncludeTrailingBackslash(FRegistryKey); LLibraryKey := IncludeTrailingBackslash (LLibraryKey + 'Environment Variables'); if LRegistry.OpenKeyReadOnly(LLibraryKey) then begin LRegistry.GetValueNames(LValues); for LIdx := 0 to PreD(LValues.Count) do begin LName := LValues[LIdx]; if Trim(LName) <> '' then begin FEnvironmentVariables.Add(LName, LRegistry.ReadString(LValues[LIdx])); end; end; end; finally FreeAndNil(LRegistry); FreeAndNil(LValues); end; end; procedure TDelphiInstallation.LoadLibraries; var LPathType: TLibraryPathType; begin for LPathType := dlpSearch to dlpDebugDCU do begin FLibraryAndroid32.FromDelimitedString(LoadLibrary('Android32', LPathType), LPathType); FLibraryAndroid64.FromDelimitedString(LoadLibrary('Android64', LPathType), LPathType); FLibraryIOS64.FromDelimitedString(LoadLibrary('iOSDevice64', LPathType), LPathType); FLibraryIOS32.FromDelimitedString(LoadLibrary('iOSDevice32', LPathType), LPathType); FLibraryIOSSimulator.FromDelimitedString(LoadLibrary('iOSSimulator', LPathType), LPathType); FLibraryOSX32.FromDelimitedString(LoadLibrary('OSX32', LPathType), LPathType); FLibraryOSX64.FromDelimitedString(LoadLibrary('OSX64', LPathType), LPathType); FLibraryOSXARM64.FromDelimitedString(LoadLibrary('OSXARM64', LPathType), LPathType); FLibraryWin32.FromDelimitedString(LoadLibrary('Win32', LPathType), LPathType); FLibraryWin64.FromDelimitedString(LoadLibrary('Win64', LPathType), LPathType); FLibraryLinux64.FromDelimitedString(LoadLibrary('Linux64', LPathType), LPathType); end; end; function TDelphiInstallation.GetInstalled: boolean; var LRegistry: TRegistry; LApp: string; begin Result := False; LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; if LRegistry.OpenKeyReadOnly(FRegistryKey) then begin LApp := LRegistry.ReadString('App'); Result := FileExists(LApp); end; finally FreeAndNil(LRegistry); end; end; function TDelphiInstallation.LoadLibrary(ALibrary: string; APathType: TLibraryPathType): string; var LRegistry: TRegistry; LLibraryKey: string; LName: string; begin Result := ''; LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; LLibraryKey := IncludeTrailingBackslash(FRegistryKey); LLibraryKey := IncludeTrailingBackslash(LLibraryKey + 'Library'); LLibraryKey := IncludeTrailingBackslash(LLibraryKey + ALibrary); if LRegistry.OpenKeyReadOnly(LLibraryKey) then begin case APathType of dlpSearch: LName := 'Search Path'; dlpBrowse: LName := 'Browsing Path'; dlpDebugDCU: LName := 'Debug DCU Path'; else LName := ''; end; if LName <> '' then begin Result := LRegistry.ReadString(LName); Debug('LoadLibrary', 'Loading library %s name: %s, value: %s', [LLibraryKey, LName, Result]); end; end; finally FreeAndNil(LRegistry); end; end; function TDelphiInstallation.GetAllEnvironemntVariables (const Vars: TStrings): integer; var PEnvVars: PChar; // pointer to start of environment block PEnvEntry: PChar; // pointer to an env string in block begin // Clear the list if Assigned(Vars) then Vars.Clear; // Get reference to environment block for this process PEnvVars := GetEnvironmentStrings; if PEnvVars <> nil then begin // We have a block: extract strings from it // Env strings are #0 separated and list ends with #0#0 PEnvEntry := PEnvVars; try while PEnvEntry^ <> #0 do begin if Assigned(Vars) then Vars.Add(PEnvEntry); Inc(PEnvEntry, StrLen(PEnvEntry) + 1); end; // Calculate length of block Result := (PEnvEntry - PEnvVars) + 1; finally // Dispose of the memory block FreeEnvironmentStrings(PEnvVars); end; end else // No block => zero length Result := 0; end; function TDelphiInstallation.GetBDSPublicFolder(AFolder: string): string; begin Result := GetPublicDocumentFolder; Result := IncludeTrailingPathDelimiter(Result + 'Embarcadero\Studio'); Result := IncludeTrailingPathDelimiter (Result + IntToStr(GetStudioVersion) + '.0'); if Trim(AFolder) <> '' then Result := IncludeTrailingPathDelimiter(Result + AFolder); Result := ExcludeTrailingPathDelimiter(Result); end; function TDelphiInstallation.GetBDSUserFolder(AFolder: string): string; begin Result := GetDocumentFolder; Result := IncludeTrailingPathDelimiter(Result + 'Embarcadero\Studio'); Result := IncludeTrailingPathDelimiter (Result + IntToStr(GetStudioVersion) + '.0'); if Trim(AFolder) <> '' then Result := IncludeTrailingPathDelimiter(Result + AFolder); Result := ExcludeTrailingPathDelimiter(Result); end; function TDelphiInstallation.GetBinPath: string; var LRegistry: TRegistry; begin Result := ''; LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; if LRegistry.OpenKeyReadOnly(FRegistryKey) then begin Result := IncludeTrailingPathDelimiter (ExtractFilePath(LRegistry.ReadString('App'))); end; finally FreeAndNil(LRegistry); end; end; procedure TDelphiInstallation.LoadSystemEnvironmentVariables; var LVars: TStringList; LVarIdx: integer; LName: string; begin LVars := TStringList.Create; try FSystemEnvironmentVariables.Clear; GetAllEnvironemntVariables(LVars); for LVarIdx := 0 to PreD(LVars.Count) do begin LName := LVars.Names[LVarIdx]; if Trim(LName) <> '' then begin FSystemEnvironmentVariables.Add(LName, LVars.ValueFromIndex[LVarIdx]); end; end; finally FreeAndNil(LVars); end; end; function TDelphiInstallation.OpenFolder(AFolder: string; ALibrary: TDelphiLibrary): boolean; var LFolder: string; begin Result := False; LFolder := AFolder; LFolder := ExpandLibraryPath(LFolder, ALibrary); if DirectoryExists(LFolder) then begin Result := ExecuteFile('open', PChar('explorer.exe'), PChar(LFolder), '', SW_SHOWNORMAL) > 32; end; end; function TDelphiInstallation.FolderContainsFiles(const PathName: string; FileName: string; const Recurse: boolean): boolean; var LFileList: TStringList; begin LFileList := TStringList.Create; try FileSearch(PathName, FileName, Recurse, LFileList); Result := LFileList.Count > 0; finally FreeAndNil(LFileList); end; end; procedure TDelphiInstallation.FileSearch(const PathName, FileName: string; const Recurse: boolean; FileList: TStrings); var Rec: TSearchRec; Path: string; Cancel: boolean; begin Path := IncludeTrailingPathDelimiter(PathName); Cancel := False; if FindFirst(Path + FileName, faAnyFile, Rec) = 0 then try repeat if (Rec.Name <> '.') and (Rec.Name <> '..') then begin FileList.Add(Path + Rec.Name); end; until (FindNext(Rec) <> 0) or (Cancel = true); finally FindClose(Rec); end; if (Recurse) and (Cancel = False) then begin if FindFirst(Path + '*', faDirectory, Rec) = 0 then try repeat if ((Rec.Attr and faDirectory) = faDirectory) and (Rec.Name <> '.') and (Rec.Name <> '..') then begin FileSearch(Path + Rec.Name, FileName, true, FileList); end; until (FindNext(Rec) <> 0) or (Cancel = true); finally FindClose(Rec); end; end; end; function TDelphiInstallation.RemoveBrowseFromSearchPaths(ALibraryPaths : TLibraryPaths; ADelphiLibrary: TDelphiLibrary; ASmartEnabled: boolean): integer; var LSearchFolders, LBrowseFolders: TStringList; LSearchFolder, LBrowseFolder: string; LBrowseFolderIdx, LSearchFolderIdx: integer; LDelete: boolean; begin Result := 0; LSearchFolders := TStringList.Create; LBrowseFolders := TStringList.Create; try LBrowseFolders.Sorted := true; LBrowseFolders.Duplicates := dupIgnore; LSearchFolders.Sorted := true; LSearchFolders.Duplicates := dupIgnore; ALibraryPaths.AsStrings(LSearchFolders, dlpSearch); ALibraryPaths.AsStrings(LBrowseFolders, dlpBrowse); for LBrowseFolderIdx := 0 to PreD(LBrowseFolders.Count) do begin LBrowseFolder := LBrowseFolders[LBrowseFolderIdx]; LBrowseFolder := ExpandLibraryPath(LBrowseFolder, ADelphiLibrary); LSearchFolderIdx := 0; while LSearchFolderIdx < LSearchFolders.Count do begin LSearchFolder := LSearchFolders[LSearchFolderIdx]; LSearchFolder := ExpandLibraryPath(LSearchFolder, ADelphiLibrary); LDelete := False; if SameText(LSearchFolder, LBrowseFolder) then begin Log('Found matching search and browse folder "%s"', [LSearchFolder]); LDelete := true; if ASmartEnabled then begin if LDelete then LDelete := not FolderContainsFiles(LSearchFolder, '*.dfm', False); if LDelete then LDelete := not FolderContainsFiles(LSearchFolder, '*.inc', False); if LDelete then LDelete := not FolderContainsFiles(LSearchFolder, '*.res', False); if not LDelete then begin Log('Skipping folder "%s" as it contains DFM,INC or RES files.', [LSearchFolder]); end; end; end; if LDelete then begin Log('Removing matching search and browse folder "%s"', [LSearchFolder]); Inc(Result); LSearchFolders.Delete(LSearchFolderIdx); end else begin Inc(LSearchFolderIdx); end; end; end; if Result > 0 then begin ALibraryPaths.FromStrings(LSearchFolders, dlpSearch); end; finally FreeAndNil(LSearchFolders); end; end; function TDelphiInstallation.RemoveBrowseFromSearch(ASmartEnabled : boolean): integer; begin Result := 0; Result := Result + RemoveBrowseFromSearchPaths(FLibraryAndroid32, dlAndroid32, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryAndroid64, dlAndroid64, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryIOS32, dlIOS32, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryIOS64, dlIOS64, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryIOSSimulator, dlIOSimulator, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryOSX32, dlOSX32, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryOSX64, dlOSX64, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryOSXARM64, dlOSXARM64, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryWin32, dlWin32, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryWin64, dlWin64, ASmartEnabled); Result := Result + RemoveBrowseFromSearchPaths(FLibraryLinux64, dlLinux64, ASmartEnabled); end; procedure TDelphiInstallation.RemoveInvalidPaths(ALibraryPaths: TLibraryPaths; ALibrary: TDelphiLibrary); var LIdx: integer; LPath: string; LExists: boolean; begin LIdx := 0; while LIdx < ALibraryPaths.Count do begin LExists := true; LPath := ALibraryPaths.Path[LIdx].Path; if not DirectoryExists(LPath) then begin LPath := (ExpandLibraryPath(LPath, ALibrary)); if Pos('$', LPath) = 0 then begin LExists := DirectoryExists(LPath); end; end; if not LExists then begin Log('Removing invalid path "%s"', [LPath]); ALibraryPaths.Delete(LIdx); end else begin Inc(LIdx); end; end; end; function TDelphiInstallation.DeduplicatPaths(ALibraryPaths: TLibraryPaths; ALibrary: TDelphiLibrary): integer; var LExpandedPaths: TLibraryPaths; LIdx: integer; LPath: string; LPathType: TLibraryPathType; LDelete: boolean; begin Result := 0; LExpandedPaths := TLibraryPaths.Create; try LIdx := 0; ALibraryPaths.Sort; while LIdx < ALibraryPaths.Count do begin LDelete := False; LPath := ALibraryPaths.Path[LIdx].Path; LPathType := ALibraryPaths.Path[LIdx].PathType; LPath := (ExpandLibraryPath(LPath, ALibrary)); if Pos('$', LPath) > 0 then begin // expansion incomplete, return to orginal path LPath := ALibraryPaths.Path[LIdx].Path; end; if LExpandedPaths.FindByIndex(LPath, LPathType) = -1 then begin LExpandedPaths.Add(LPath, LPathType); end else begin LDelete := true; end; if LDelete then begin Log('Removing duplicate path: %s, type: %s', [ALibraryPaths.Path[LIdx].Path, TLibraryPath.PathTypeToString(ALibraryPaths.Path[LIdx].PathType)]); ALibraryPaths.Delete(LIdx); Inc(Result); end else begin Inc(LIdx); end; end; finally FreeAndNil(LExpandedPaths); end; end; procedure TDelphiInstallation.DeleteAll(APathType: TLibraryPathType); begin FLibraryAndroid32.Clear(APathType); FLibraryAndroid64.Clear(APathType); FLibraryIOS32.Clear(APathType); FLibraryIOS64.Clear(APathType); FLibraryIOSSimulator.Clear(APathType); FLibraryOSX32.Clear(APathType); FLibraryOSX64.Clear(APathType); FLibraryOSXARM64.Clear(APathType); FLibraryWin32.Clear(APathType); FLibraryWin64.Clear(APathType); FLibraryLinux64.Clear(APathType); end; function TDelphiInstallation.ExecuteFile(const Operation, FileName, Params, DefaultDir: string; ShowCmd: word): integer; var zFileName, zParams, zDir: array [0 .. 255] of char; begin Result := ShellExecute(Application.Handle, PChar(Operation), StrPCopy(zFileName, FileName), StrPCopy(zParams, Params), StrPCopy(zDir, DefaultDir), ShowCmd); end; function TDelphiInstallation.GetLibraryAndroid32: string; begin Result := GetLibraryPathAsString(FLibraryAndroid32); end; function TDelphiInstallation.GetLibraryAndroid64: string; begin Result := GetLibraryPathAsString(FLibraryAndroid64); end; function TDelphiInstallation.GetLibraryIOS32: string; begin Result := GetLibraryPathAsString(FLibraryIOS32); end; function TDelphiInstallation.GetLibraryIOS64: string; begin Result := GetLibraryPathAsString(FLibraryIOS64); end; function TDelphiInstallation.GetLibraryIOSSimulator: string; begin Result := GetLibraryPathAsString(FLibraryIOSSimulator); end; function TDelphiInstallation.GetLibraryLinux64: string; begin Result := GetLibraryPathAsString(FLibraryLinux64); end; function TDelphiInstallation.GetLibraryName(ALibrary: TDelphiLibrary): string; var LLibraryHelper: TLibraryHelper; begin LLibraryHelper := TLibraryHelper.Create; try Result := LLibraryHelper.GetLibraryName(ALibrary); finally FreeAndNil(LLibraryHelper); end; end; function TDelphiInstallation.GetLibraryOSX32: string; begin Result := GetLibraryPathAsString(FLibraryOSX32); end; function TDelphiInstallation.GetLibraryOSX64: string; begin Result := GetLibraryPathAsString(FLibraryOSX64); end; function TDelphiInstallation.GetLibraryOSXARM64: string; begin Result := GetLibraryPathAsString(FLibraryOSXARM64); end; function TDelphiInstallation.GetLibraryPathAsString (AStrings: TLibraryPaths): string; begin Result := AStrings.AsString(FLibraryPathType); end; function TDelphiInstallation.GetLibraryWin32: string; begin Result := GetLibraryPathAsString(FLibraryWin32); end; function TDelphiInstallation.GetLibraryWin64: string; begin Result := GetLibraryPathAsString(FLibraryWin64); end; function TDelphiInstallation.GetProductName: string; var LProductVersion: integer; begin LProductVersion := GetProductVersion; case LProductVersion of 28: Result := 'Delphi Alexandria'; 27: Result := 'Delphi Sydney'; 26: Result := 'Delphi Rio'; 25: Result := 'Delphi Tokyo'; 24: Result := 'Delphi Berlin'; 23: Result := 'Delphi Seattle'; 22: Result := 'Delphi XE8'; 21: Result := 'Delphi XE7'; 20: Result := 'Delphi XE6'; 19: Result := 'Delphi XE5'; 18: Result := 'Delphi XE4'; 17: Result := 'Delphi XE3'; 16: Result := 'Delphi XE2'; 15: Result := 'Delphi XE'; 14: Result := 'Delphi 2010'; 12: Result := 'Delphi 2009'; 11: Result := 'Delphi 2007'; 10: Result := 'Delphi 2006'; 9: Result := 'Delphi 2005'; 8: Result := 'Delphi 8'; 7: Result := 'Delphi 7'; 6: Result := 'Delphi 6'; 5: Result := 'Delphi 5'; 4: Result := 'Delphi 4'; 3: Result := 'Delphi 3'; 2: Result := 'Delphi 2'; 1: Result := 'Delphi 1'; else Result := Format('Unknown Version %d', [LProductVersion]); end; end; function TDelphiInstallation.GetProductVersion: integer; var LRegistry: TRegistry; begin Result := -1; LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; if LRegistry.OpenKeyReadOnly(FRegistryKey) then begin Result := StrToIntDef(LRegistry.ReadString('ProductVersion'), -1); end; finally FreeAndNil(LRegistry); end; end; function TDelphiInstallation.GetRootPath: string; var LRegistry: TRegistry; begin Result := ''; LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; if LRegistry.OpenKeyReadOnly(FRegistryKey) then begin Result := IncludeTrailingPathDelimiter(LRegistry.ReadString('RootDir')); end; finally FreeAndNil(LRegistry); end; end; procedure TDelphiInstallation.Save(ADeduplicate: boolean); begin if ADeduplicate then Deduplicate; SaveEnvironmentVariables; SaveLibraries; // ForceEnvOptionsUpdate; NotifyEnvironmentChanges; end; procedure TDelphiInstallation.SaveEnvironmentVariables; var LRegistry: TRegistry; LLibraryKey: string; LValues: TStringList; LIdx: integer; begin LRegistry := TRegistry.Create; LValues := TStringList.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; LLibraryKey := IncludeTrailingBackslash(FRegistryKey); LLibraryKey := IncludeTrailingBackslash (LLibraryKey + 'Environment Variables'); LRegistry.DeleteKey(LLibraryKey); if LRegistry.OpenKey(LLibraryKey, true) then begin for LIdx := 0 to PreD(FEnvironmentVariables.Count) do begin LRegistry.WriteString(FEnvironmentVariables.Variable[LIdx].Name, FEnvironmentVariables.Variable[LIdx].Value); end; LRegistry.CloseKey; end; finally FreeAndNil(LRegistry); FreeAndNil(LValues); end; end; procedure TDelphiInstallation.SaveLibraries; var LPathType: TLibraryPathType; begin for LPathType := dlpSearch to dlpDebugDCU do begin SaveLibrary('Android32', FLibraryAndroid32.AsDelimitedString(LPathType), LPathType); SaveLibrary('Android64', FLibraryAndroid64.AsDelimitedString(LPathType), LPathType); SaveLibrary('iOSDevice64', FLibraryIOS64.AsDelimitedString(LPathType), LPathType); SaveLibrary('iOSDevice32', FLibraryIOS32.AsDelimitedString(LPathType), LPathType); SaveLibrary('iOSSimulator', FLibraryIOSSimulator.AsDelimitedString (LPathType), LPathType); SaveLibrary('OSX32', FLibraryOSX32.AsDelimitedString(LPathType), LPathType); SaveLibrary('OSX64', FLibraryOSX64.AsDelimitedString(LPathType), LPathType); SaveLibrary('OSXARM64', FLibraryOSXARM64.AsDelimitedString(LPathType), LPathType); SaveLibrary('Win32', FLibraryWin32.AsDelimitedString(LPathType), LPathType); SaveLibrary('Win64', FLibraryWin64.AsDelimitedString(LPathType), LPathType); SaveLibrary('Linux64', FLibraryLinux64.AsDelimitedString(LPathType), LPathType); end; end; procedure TDelphiInstallation.SaveLibrary(ALibrary, AValue: string; APathType: TLibraryPathType); var LRegistry: TRegistry; LLibraryKey: string; LName: string; begin LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_CURRENT_USER; LLibraryKey := IncludeTrailingBackslash(FRegistryKey); LLibraryKey := IncludeTrailingBackslash(LLibraryKey + 'Library'); LLibraryKey := IncludeTrailingBackslash(LLibraryKey + ALibrary); if LRegistry.OpenKey(LLibraryKey, False) then begin case APathType of dlpSearch: LName := 'Search Path'; dlpBrowse: LName := 'Browsing Path'; dlpDebugDCU: LName := 'Debug DCU Path'; else LName := ''; end; if LName <> '' then begin Debug('SaveLibrary', 'Saving library %s name: %s, value: %s', [LLibraryKey, LName, AValue]); LRegistry.WriteString(LName, AValue); end; end; finally FreeAndNil(LRegistry); end; end; procedure TDelphiInstallation.SetLibraryAndroid32(const Value: string); begin SetLibraryPathFromString(Value, FLibraryAndroid32, dlAndroid32); end; procedure TDelphiInstallation.SetLibraryAndroid64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryAndroid64, dlAndroid64); end; procedure TDelphiInstallation.SetLibraryIOS32(const Value: string); begin SetLibraryPathFromString(Value, FLibraryIOS32, dlIOS32); end; procedure TDelphiInstallation.SetLibraryIOS64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryIOS64, dlIOS64); end; procedure TDelphiInstallation.SetLibraryIOSSimulator(const Value: string); begin SetLibraryPathFromString(Value, FLibraryIOSSimulator, dlIOSimulator); end; procedure TDelphiInstallation.SetLibraryLinux64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryLinux64, dlLinux64); end; procedure TDelphiInstallation.SetLibraryOSX32(const Value: string); begin SetLibraryPathFromString(Value, FLibraryOSX32, dlOSX32); end; procedure TDelphiInstallation.SetLibraryOSX64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryOSX64, dlOSX64); end; procedure TDelphiInstallation.SetLibraryOSXARM64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryOSXARM64, dlOSXARM64); end; procedure TDelphiInstallation.SetLibraryPathFromString(AString: string; AStrings: TLibraryPaths; ALibrary: TDelphiLibrary); begin AStrings.FromString(AString, FLibraryPathType); end; procedure TDelphiInstallation.SetLibraryPathType(const Value: TLibraryPathType); begin FLibraryPathType := Value; end; procedure TDelphiInstallation.SetLibraryWin32(const Value: string); begin SetLibraryPathFromString(Value, FLibraryWin32, dlWin32); end; procedure TDelphiInstallation.SetLibraryWin64(const Value: string); begin SetLibraryPathFromString(Value, FLibraryWin64, dlWin64); end; function TDelphiInstallation.GetLibraryPlatformName (ALibrary: TDelphiLibrary): string; var LLibraryHelper: TLibraryHelper; begin LLibraryHelper := TLibraryHelper.Create; try Result := LLibraryHelper.GetLibraryPlatformName(ALibrary); finally FreeAndNil(LLibraryHelper); end; end; { TEnviromentVariable } procedure TEnviromentVariable.SetName(const Value: string); begin FName := Value; end; procedure TEnviromentVariable.SetValue(const Value: string); begin FValue := Value; end; { TEnvironmentVariables } function TEnvironmentVariables.Add(AName: string; AValue: string): integer; var LEnviromentVariable: TEnviromentVariable; begin LEnviromentVariable := FindVariable(AName); if Assigned(LEnviromentVariable) then begin Result := FEnviromentVariableList.IndexOf(LEnviromentVariable); end else begin LEnviromentVariable := TEnviromentVariable.Create; LEnviromentVariable.Name := AName; Result := FEnviromentVariableList.Add(LEnviromentVariable); end; LEnviromentVariable.Value := AValue; end; procedure TEnvironmentVariables.Clear; begin FEnviromentVariableList.Clear; end; function TEnvironmentVariables.Count: integer; begin Result := FEnviromentVariableList.Count; end; constructor TEnvironmentVariables.Create; begin FEnviromentVariableList := TEnviromentVariableList.Create; end; destructor TEnvironmentVariables.Destroy; begin try FreeAndNil(FEnviromentVariableList); finally inherited; end; end; function TEnvironmentVariables.FindVariable(AName: string): TEnviromentVariable; var LIdx: integer; begin Result := nil; LIdx := 0; while (LIdx < Count) and (Result = nil) do begin if SameText(FEnviromentVariableList.Items[LIdx].Name, AName) then begin Result := FEnviromentVariableList.Items[LIdx]; end; Inc(LIdx); end; end; function TEnvironmentVariables.GetValue(AName: string): string; var LEnviromentVariable: TEnviromentVariable; begin Result := ''; LEnviromentVariable := FindVariable(AName); if Assigned(LEnviromentVariable) then begin Result := LEnviromentVariable.Value; end; end; function TEnvironmentVariables.GetVariable(AIndex: integer) : TEnviromentVariable; begin Result := FEnviromentVariableList.Items[AIndex]; end; procedure TEnvironmentVariables.SetValue(AName: string; const Value: string); var LEnviromentVariable: TEnviromentVariable; begin LEnviromentVariable := FindVariable(AName); if Assigned(LEnviromentVariable) then LEnviromentVariable.Value := Value; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMain = class(TForm) ScriptMemo: TMemo; LogMemo: TMemo; ParseBtn: TButton; procedure ParseBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main: TMain; implementation uses System.Math, ExpressionLexer, ExpressionParser; {$R *.dfm} procedure TMain.ParseBtnClick(Sender: TObject); var Lexer: TExpressionLexer; Parser: TExpressionParser; StringStream: TStringStream; begin StringStream := TStringStream.Create(ScriptMemo.Text, TEncoding.UTF8); try Lexer := TExpressionLexer.Create(StringStream); try Parser := TExpressionParser.Create(Lexer); try Parser.Console := LogMemo; Parser.Parse(); finally Parser.Free(); end; finally Lexer.Free(); end; finally StringStream.Free(); end; end; initialization ReportMemoryLeaksOnShutdown := True; end.
program fpmashc; {$mode objfpc}{$H+} uses SysUtils, u_compiler; var cmp: TMashCompiler; tm: QWord; begin writeln('Mash compiler v1.3'); writeln('Author: RoPi0n (Pavel Chernov), (c) from 2018.'); writeln('GitHub: github.com/RoPi0n/mash-lang'); if ParamCount > 1 then try tm := GetTickCount64; cmp := TMashCompiler.Create(ParamStr(1), ParamStr(2)); cmp.Compile(); writeln('Success.'); writeln('Time elapsed: ', Format('%.3f', [(GetTickCount64() - tm) / 1000]), ' sec.'); except on E: Exception do writeln('[Error]: ', E.Message); end else writeln('Using: mashc <source> <dest> [args]'); end.
unit uExeSql; { Функции и процедуры для работы с хранимыми SQL-запросами Создан 30.09.2004 } interface uses uCommonForm, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, MemTable, ExtCtrls, Ora,uOilQuery,uOilStoredProc; function GetExeSqlTextByName(p_SqlName,p_FormName: string): string; function GetExeSqlTextById(p_Id: integer): string; function GetExeSqlIdByName(p_SqlName,p_FormName: string): integer; function GetQHeadValue(p_Q: TOilQuery; p_Name: string): string; procedure LoadExeSql( p_Sql: TStrings; p_SqlName: string = ''; p_FormName: string = ''); procedure LoadSQLByForm(var AForm: TForm); function MakeExeSqlTests(p_Q: TOilQuery; var pp_Msg: string): Boolean; implementation uses ExFunc,OilStd, Main, GetFromGrid, TextFunc, uStart, MoneyFunc,UDbFunc,uTestLaunch; //============================================================================== // получение текста SQL по EXE_SQL.ID //------------------------------------------------------------------------------ function GetExeSqlTextById(p_Id: integer): string; var q: TOilQuery; eos: string; begin result:=''; q:=TOilQuery.Create(nil); q.Session:=frmStart.OraSession1; try q.SQL.Text:= ' select text from exe_sql_data'+ ' where state=''Y'' and sql_id='+IntToStr(p_Id)+ ' order by line'; q.Open; result:=''; if GetSqlValue('select lines_merge from exe_sql where id='+IntToStr(p_Id))='Y' then eos:='' else eos:=#13#10; while not q.Eof do begin result:=result+q.FieldByName('text').AsString+eos; q.Next; end; finally q.Free; end; end; //============================================================================== // получение текста SQL по имени SQL и имени формы //------------------------------------------------------------------------------ function GetExeSqlTextByName(p_SqlName,p_FormName: string): string; var vId: integer; begin vId:=GetExeSqlIdByName(p_SqlName,p_FormName); if vId=0 then raise exception.create(TranslateText('Не найден хранимый запрос с именем ')+p_SqlName+TranslateText(' и именем формы ')+p_FormName); result:=GetExeSqlTextById(vId); end; //============================================================================== function GetExeSqlFieldValue(p_SqlName,p_FormName,p_Field: string): variant; var q: TOilQuery; begin q:=TOilQuery.Create(nil); q.Session:=frmStart.OraSession1; try q.Sql.Text:= ' select sql.'+p_Field+ ' from exe_sql sql,exe_forms frm'+ ' where sql.state=''Y'' and frm.state=''Y'''+ ' and sql.form_id=frm.id'+ ' and lower(sql.name)=lower('''+p_SqlName+''')'+ ' and lower(frm.name)=lower('''+p_FormName+''')'; _OpenQueryOra(q); if q.RecordCount=0 then result:=0 else result:=nvl(q.Fields[0].Value,0); finally q.Free; end; end; //============================================================================== // результат - EXE_SQL.ID хранимого SQL с заданными именем SQL и именем формы // 0 если такого SQL не существует либо он в состоянии STATE=N //------------------------------------------------------------------------------ function GetExeSqlIdByName(p_SqlName,p_FormName: string): integer; begin result:=GetExeSqlFieldValue(p_SqlName,p_FormName,'id'); end; //============================================================================== // проверка существования хранимого SQL с заданными именем SQL и именем формы //------------------------------------------------------------------------------ function ExistsSqlByName(p_SqlName,p_FormName: string): Boolean; begin result:=GetExeSqlIdByName(p_SqlName,p_FormName)>0; end; //============================================================================== // в начале текста SQL могут содержаться псевдокомментарии вида // --$переменная=значение // функция возвращает значение, если оно есть или пустую строку если его нет //------------------------------------------------------------------------------ function GetQHeadValue(p_Q: TOilQuery; p_Name: string): string; var i: integer; s,name,value: string; begin result:=''; for i:=0 to p_Q.SQL.Count-1 do begin if copy(p_Q.Sql[i],1,3)<>'--$' then exit; s:=copy(p_Q.Sql[i],4,length(p_Q.sql[i])); GetNameValue(s,name,value); if lowercase(name)=lowercase(p_Name) then begin result:=value; exit; end; end; end; //============================================================================== // сюда передаются SQL-тексты запросов. // если текст начинается со строки вида --> ИмяЗапроса,ИмяФормы // то происходит подставновка соответствующего хранимого запроса // если вместо --> стоит -->>, то в случае если запрос не будет найден // возникнет ошибка. В случае же --> эта ситуация игнорируется //------------------------------------------------------------------------------ procedure LoadExeSql( p_Sql: TStrings; p_SqlName: string = ''; p_FormName: string = ''); var s,ver,vSqlName,vFormName: string; ErrorIfNoExists: Boolean; begin if (p_Sql.Count=0) or (copy(p_Sql[0],1,3)<>'-->') then if (p_SqlName='') or (p_FormName='') then exit else p_Sql.Insert(0,'--> '+p_SqlName+','+p_FormName); ErrorIfNoExists:=FALSE; s:=copy(p_Sql[0],4,length(p_Sql[0])); if (s<>'') and (s[1]='>') then begin ErrorIfNoExists:=TRUE; s:=copy(s,2,length(s)); end; GetNameValue(s,vSqlName,vFormName,','); if (vSqlName='') or (vFormName='') then raise exception.create( TranslateText('LoadExeSql: неверная ссылка на хранимый запрос')+#13#10+p_Sql[1]); qlog(TranslateText('поиск ')+vSqlName+', '+vFormName); if ExistsSqlByName(vSqlName,vFormName) then begin ver:=GetExeSqlFieldValue(vSqlName,vFormName,'ver_id'); if (ver='') or (ver='0') or not RightVersion(Version.fileversion,ver) then begin p_Sql.Text:=GetExeSqlTextByName(vSqlName,vFormName); qLog(TranslateText('считан успешно')); end end else if ErrorIfNoExists then begin qlog(TranslateText('не найден хранимый запрос!!!')); raise exception.create( TranslateText('LoadExeSql: не найден хранимый запрос (')+vSqlName+','+vFormName+')'); end; end; //============================================================================== procedure LoadSQLByForm(var AForm: TForm); var I: Integer; begin with AForm do for I := 0 to ComponentCount - 1 do begin if (Components[I] is TOilQuery) then LoadExeSQL((Components[I] as TOilQuery).SQL,(Components[I] as TOilQuery).Name,AForm.Name); end; end; //============================================================================== function MakeExeSqlTests(p_Q: TOilQuery; var pp_Msg: string): Boolean; var i,n: integer; s,vFunc: string; //**************************************************************************** function MakeOneTest(p_Args: string): Boolean; var sl: TStringList; q: TOilQuery; i: integer; begin result:=TRUE; sl:=TStringList.Create; q:=TOilQuery.Create(nil); q.Session:=frmStart.OraSession1; try Str2StringList(p_Args,sl,';'); if sl.Count<>4 then raise exception.create( TranslateText('MakeExeSqlTests: неверное число аргументов')+#13#10+ 'TEST('+p_Args+')'); if not ExistsSqlByName(sl[0],sl[1]) then exit; q.Sql.Text:=GetExeSqlTextByName(sl[0],sl[1]); q.Prepare; for i:=0 to q.Params.Count-1 do if p_Q.FindParam(q.Params[i].Name)<>nil then q.Params[i].Value:=p_Q.Params.ParamValues[q.Params[i].Name]; _OpenQueryOra(q); if q.RecordCount=0 then exit; // если нашлись записи if pp_Msg<>'' then pp_Msg:=pp_Msg+#13#10; pp_Msg:=pp_Msg+sl[2]; if sl[3]='ABORT' then begin MessageDlg(sl[2],mtError,[mbOk],0); result:=FALSE; end else if sl[3]='CONTINUE' then begin MessageDlg(sl[2],mtWarning,[mbOk],0); result:=TRUE; end else if sl[3]='ANSWER' then begin result:=MessageDlg(sl[2]+#13#10+TranslateText('Продолжить?'),mtConfirmation,[mbYes,mbNo],0)=mrYes; end; finally sl.Free; q.Free; end; end; //**************************************************************************** begin result:=TRUE; pp_Msg:=''; for i:=0 to p_Q.Sql.Count-1 do begin if copy(p_Q.Sql[i],1,2)<>'--' then exit; if p_Q.Sql[i][3]<>'@' then continue; s:=trim(copy(p_Q.Sql[i],4,length(p_Q.Sql[i]))); n:=pos('(',s); vFunc:=UpperCase(copy(s,1,n-1)); if vFunc<>'TEST' then continue; result:=MakeOneTest(copy(s,n+1,length(s)-n-1)); if not result then exit; end; end; //============================================================================== end.
{======================================================================================================================= SendMessageFrame Unit Raize Components - Demo Program Source Unit Copyright © 1995-2002 by Raize Software, Inc. All Rights Reserved. =======================================================================================================================} {$I RCDemo.inc} unit SendMessageFrame; interface uses Forms, ImgList, Controls, RzShellDialogs, RzSndMsg, Mask, RzEdit, StdCtrls, RzLstBox, RzPanel, RzButton, Classes, RzCommon, RzLabel, ExtCtrls; type TFmeSendMessages = class(TFrame) Msg: TRzSendMessage; RzToolbar1: TRzToolbar; pnlMessage: TRzPanel; EdtMessage: TRzMemo; GrpAttach: TRzPanel; LstFiles: TRzEditListBox; pnlRecipients: TRzPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; EdtTO: TRzMemo; EdtCC: TRzMemo; EdtSubject: TRzEdit; DlgOpen: TRzOpenDialog; BtnSend: TRzToolButton; BtnAttach: TRzToolButton; ImageList1: TImageList; pnlHeader: TRzPanel; RzLabel1: TRzLabel; procedure BtnSendClick(Sender: TObject); procedure BtnAttachClick(Sender: TObject); procedure BtnRemoveClick(Sender: TObject); private { Private declarations } public procedure Init; procedure UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); end; implementation {$R *.dfm} procedure TFmeSendMessages.Init; begin // ParentBackground := False; end; procedure TFmeSendMessages.UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); begin pnlHeader.VisualStyle := VS; pnlHeader.GradientColorStyle := GCS; RzToolbar1.VisualStyle := VS; RzToolbar1.GradientColorStyle := GCS; end; procedure TFmeSendMessages.BtnSendClick(Sender: TObject); begin Msg.Attachments := LstFiles.Items; Msg.ToRecipients := EdtTO.Lines; Msg.CcRecipients := EdtCC.Lines; Msg.Send; { Clear all fields } EdtTo.Clear; EdtCC.Clear; EdtSubject.Clear; EdtMessage.Clear; LstFiles.Clear; end; procedure TFmeSendMessages.BtnAttachClick(Sender: TObject); begin if DlgOpen.Execute then LstFiles.Items.Add( DlgOpen.FileName ); end; procedure TFmeSendMessages.BtnRemoveClick(Sender: TObject); begin if LstFiles.ItemIndex <> -1 then LstFiles.Items.Delete( LstFiles.ItemIndex ); end; end.
unit UModalSelectBroker; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VirtualTrees, SQLiteTable3, UClassDef; type TdlgBrokerSelect = class(TForm) Label2: TLabel; EditBrokerName: TEdit; Label3: TLabel; EditBrokerTel: TEdit; VirtualStringTreeBroker: TVirtualStringTree; ButtonSearch: TButton; ButtonNew: TButton; ButtonOK: TButton; ButtonCancel: TButton; procedure VirtualStringTreeBrokerCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure VirtualStringTreeBrokerFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure FormCreate(Sender: TObject); procedure VirtualStringTreeBrokerGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure ButtonSearchClick(Sender: TObject); procedure EditBrokerNameChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure VirtualStringTreeBrokerChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure EditBrokerTelChange(Sender: TObject); procedure ButtonOKClick(Sender: TObject); procedure ButtonNewClick(Sender: TObject); procedure VirtualStringTreeBrokerDblClick(Sender: TObject); procedure VirtualStringTreeBrokerHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); procedure EditBrokerNameEnter(Sender: TObject); procedure EditBrokerTelEnter(Sender: TObject); private { Private 宣言 } procedure QueryBroker(Filter: string); procedure ClearSelectedBrokerData(); public { Public 宣言 } SelectedBrokerData: TBrokerNodeData; end; var dlgBrokerSelect: TdlgBrokerSelect; implementation uses UMain, UUtils, UDefaultValues; {$R *.dfm} procedure TdlgBrokerSelect.ButtonNewClick(Sender: TObject); var frmInput : TfrmDefaultValues; //i:integer; //objData:TBrokerNodeData; begin inherited; //Changed(); frmInput := TfrmDefaultValues.Create(self); // frmInput.TabSheetTrainLine.TabVisible := false; frmInput.TabSheetTrainStation.TabVisible := false; frmInput.TabSheetLocation.TabVisible := false; //frmInput.TabSheetBroker.TabVisible := true; //frmInput.PopupParent := frmMain; //frmInput.PopupMode := pmExplicit; self.Visible := false; frmInput.ShowModal; self.Visible := true; QueryBroker(''); VirtualStringTreeBroker.SetFocus; //UpdateComboBoxBroker(); end; procedure TdlgBrokerSelect.ButtonOKClick(Sender: TObject); var PNodeData: ^rNodeData; Node: PVirtualNode; begin if not (VirtualStringTreeBroker.RootNodeCount > 0) then begin ClearSelectedBrokerData(); exit; end; Node := VirtualStringTreeBroker.FocusedNode; if Node = nil then exit; if not VirtualStringTreeBroker.Selected[Node] then begin ClearSelectedBrokerData(); exit; end; PNodeData := VirtualStringTreeBroker.GetNodeData(Node); if Assigned(PNodeData) then begin if (PNodeData.NodeData is TBrokerNodeData) then begin SelectedBrokerData.tel := (PNodeData.NodeData as TBrokerNodeData).tel; SelectedBrokerData.Caption := (PNodeData.NodeData as TBrokerNodeData).Caption; SelectedBrokerData.ID := (PNodeData.NodeData as TBrokerNodeData).ID; end; end; end; procedure TdlgBrokerSelect.ClearSelectedBrokerData(); begin SelectedBrokerData.tel := ''; SelectedBrokerData.Caption := ''; SelectedBrokerData.ID := -1; end; procedure TdlgBrokerSelect.ButtonSearchClick(Sender: TObject); var sqlFilter:string; begin // if (EditBrokerName.Text <> '') and (EditBrokerTel.Text <> '') then begin sqlFilter := 'broker LIKE ''%' + EditBrokerName.Text + '%'''; sqlFilter := sqlFilter + 'OR telephone LIKE ''%' + EditBrokerTel.Text + '%'''; end else if EditBrokerName.Text <> '' then begin sqlFilter := 'broker LIKE ''%' + EditBrokerName.Text + '%'''; end else if EditBrokerTel.Text <> '' then begin sqlFilter := 'telephone LIKE ''%' + EditBrokerTel.Text + '%'''; end else begin sqlFilter := ''; end; QueryBroker(sqlFilter); ButtonOK.Enabled := false; if not (VirtualStringTreeBroker.RootNode <> nil) then begin VirtualStringTreeBroker.FocusedNode := VirtualStringTreeBroker.RootNode; if VirtualStringTreeBroker.RootNode.FirstChild <> nil then begin VirtualStringTreeBroker.FocusedNode := VirtualStringTreeBroker.RootNode.FirstChild; VirtualStringTreeBroker.Selected[VirtualStringTreeBroker.RootNode.FirstChild] := true; end; end; VirtualStringTreeBroker.SetFocus; end; procedure TdlgBrokerSelect.EditBrokerNameChange(Sender: TObject); begin ButtonOK.Default := false; ButtonSearch.Default := true; if EditBrokerName.Text <> '' then begin //ButtonSearch.Enabled := true; end else begin //ButtonSearch.Enabled := false; end; end; procedure TdlgBrokerSelect.EditBrokerNameEnter(Sender: TObject); begin //ButtonOK.Enabled := false; ButtonOK.Default := false; ButtonSearch.Default := true; end; procedure TdlgBrokerSelect.EditBrokerTelChange(Sender: TObject); begin ButtonOK.Default := false; ButtonSearch.Default := true; end; procedure TdlgBrokerSelect.EditBrokerTelEnter(Sender: TObject); begin //ButtonOK.Enabled := false; ButtonOK.Default := false; ButtonSearch.Default := true; end; procedure TdlgBrokerSelect.FormCreate(Sender: TObject); begin VirtualStringTreeBroker.NodeDataSize := SizeOf(TNodeData); SelectedBrokerData:= TBrokerNodeData.Create; QueryBroker(''); end; procedure TdlgBrokerSelect.FormDestroy(Sender: TObject); begin SelectedBrokerData.Free; end; procedure TdlgBrokerSelect.QueryBroker(Filter: string); var SQLiteTable: TSQLiteTable; Data: TBrokerNodeData; sql: string; begin VirtualStringTreeBroker.Clear; ClearSelectedBrokerData(); sql := 'SELECT * FROM Brokers'; //引数Filterが空文字以外の場合はWHERE句を追加 if Filter <> '' then sql := sql + ' WHERE ' + Filter; SQLiteTable := frmMain.SQLiteDB.GetTable(UTF8Encode(sql)); with SQLiteTable do begin MoveFirst; while not EOF do begin Data := TBrokerNodeData.Create; Data.Caption := UTF8toString((FieldByName['broker'])); Data.tel := UTF8toString((FieldByName['telephone'])); Data.ID := FieldAsInteger(FieldIndex['ID']); VirtualStringTreeBroker.AddChild(nil,Data); Next; end; end; SQLiteTable.Free; VirtualStringTreeBroker.SortTree(0,sdAscending); end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerChange( Sender: TBaseVirtualTree; Node: PVirtualNode); var PNodeData: ^rNodeData; begin // if VirtualStringTreeBroker.SelectedCount > 0 then begin PNodeData := VirtualStringTreeBroker.GetNodeData(Node); if Assigned(PNodeData) then begin if (PNodeData.NodeData is TBrokerNodeData) then begin SelectedBrokerData.tel := (PNodeData.NodeData as TBrokerNodeData).tel; SelectedBrokerData.Caption := (PNodeData.NodeData as TBrokerNodeData).Caption; SelectedBrokerData.ID := (PNodeData.NodeData as TBrokerNodeData).ID; end; end; ButtonOK.Enabled := true; ButtonSearch.Default := false; ButtonOK.Default := true; end else begin ButtonOK.Enabled := false; ButtonOK.Default := false; ButtonSearch.Default := true; end; end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerCompareNodes( Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: ^rNodeData; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); if (Data1.NodeData is TBrokerNodeData) and (Data2.NodeData is TBrokerNodeData) then begin case Column of 0: Result := AnsiCompareStr(TBrokerNodeData(Data1.NodeData).Caption,TBrokerNodeData(Data2.NodeData).Caption); 1: Result := AnsiCompareStr(TBrokerNodeData(Data1.NodeData).tel,TBrokerNodeData(Data2.NodeData).tel); end; end; end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerDblClick(Sender: TObject); var Node: PVirtualNode; begin Node := VirtualStringTreeBroker.FocusedNode; if Node = nil then exit; if not VirtualStringTreeBroker.Selected[Node] then exit; ButtonOKClick(nil); self.ModalResult := mrOK; //close; end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerFreeNode( Sender: TBaseVirtualTree; Node: PVirtualNode); var PNodeData: ^rNodeData; begin // PNodeData := VirtualStringTreeBroker.GetNodeData(Node); if Assigned(PNodeData) then begin if (PNodeData.NodeData is TNodeData) then begin (PNodeData.NodeData as TNodeData).Free; end; end; end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerGetText( Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var PNodeData: ^rNodeData; begin PNodeData := VirtualStringTreeBroker.GetNodeData(Node); if Assigned(PNodeData) then begin if (PNodeData.NodeData is TBrokerNodeData) then begin case Column of -1, // main column, -1 if columns are hidden, 0 if they are shown 0: CellText := PNodeData.NodeData.Caption; 1: CellText := (PNodeData.NodeData as TBrokerNodeData).tel; end; end; end; end; procedure TdlgBrokerSelect.VirtualStringTreeBrokerHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); begin if HitInfo.Button = mbLeft then begin with Sender, Treeview do begin if SortColumn > NoColumn then Columns[SortColumn].Options := Columns[SortColumn].Options + [coParentColor]; // Do not sort the first column, it contains nothing to sort. if HitInfo.Column >= 2 then SortColumn := NoColumn else begin if (SortColumn = NoColumn) or (SortColumn <> HitInfo.Column) then begin SortColumn := HitInfo.Column; SortDirection := sdAscending; end else if SortDirection = sdAscending then SortDirection := sdDescending else SortDirection := sdAscending; Columns[SortColumn].Color := $F7F7F7; SortTree(SortColumn, SortDirection, False); end; end; end; end; end.
unit JsEditView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExtCtrls, dcstring, dcsystem, dcparser, dccommon, dcmemo, EasyClasses, EasyParser, EasyEditor, EasyEditSource, {EasyEditorActions,} CodeExplorerView, dxDockControl, dxDockPanel, dfsSplitter; type TJsEditForm = class(TForm) Source: TEasyEditSource; JsParser: TEasyEditorParser; ChangeTimer: TTimer; dfsSplitter1: TdfsSplitter; Edit: TEasyEdit; procedure EditSourceChanged(Sender: TObject; State: TEasyEditSourceStates); procedure FormCreate(Sender: TObject); procedure ChangeTimerTimer(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FOnModified: TNotifyEvent; FCodeDesigner: TCodeDesigner; ExplorerForm: TCodeExplorerForm; protected function GetStrings: TStrings; procedure SetCodeDesigner(const Value: TCodeDesigner); procedure SetStrings(const Value: TStrings); protected procedure DoModified; procedure LazyUpdate; public { Public declarations } procedure ShowSource(Sender: TObject; inX, inY: Integer); procedure ValidateMethods(inContainer: TWinControl); public property CodeDesigner: TCodeDesigner read FCodeDesigner write SetCodeDesigner; property Strings: TStrings read GetStrings write SetStrings; property OnModified: TNotifyEvent read FOnModified write FOnModified; end; implementation uses LrUtils, JavaScriptCodeDesigner; {$R *.dfm} procedure TJsEditForm.FormCreate(Sender: TObject); begin Source.Strings.Clear; // CodeDesigner := TJavaScriptCodeDesigner.Create(Self); CodeDesigner.OnShowSource := ShowSource; // AddForm(ExplorerForm, TCodeExplorerForm, Self, alLeft); ExplorerForm.Left := 0; ExplorerForm.EasyEdit := Edit; end; procedure TJsEditForm.FormShow(Sender: TObject); begin LazyUpdate; end; function TJsEditForm.GetStrings: TStrings; begin Result := Source.Strings; end; procedure TJsEditForm.SetStrings(const Value: TStrings); begin Source.Strings.Assign(Value); LazyUpdate; end; procedure TJsEditForm.DoModified; begin if Assigned(OnModified) then OnModified(Self); end; procedure TJsEditForm.EditSourceChanged(Sender: TObject; State: TEasyEditSourceStates); begin if (State <> [csPositionChanged]) then begin ChangeTimer.Enabled := true; if Edit.Modified then DoModified; end; end; procedure TJsEditForm.ChangeTimerTimer(Sender: TObject); begin ChangeTimer.Enabled := false; LazyUpdate; end; procedure TJsEditForm.LazyUpdate; begin if (ExplorerForm <> nil) {and (ExplorerDock.Parent <> nil)} then ExplorerForm.UpdateExplorer; end; procedure TJsEditForm.ShowSource(Sender: TObject; inX, inY: Integer); begin Source.JumpTo(inX, inY); if Edit.CanFocus then Edit.SetFocus; end; procedure TJsEditForm.SetCodeDesigner(const Value: TCodeDesigner); begin FCodeDesigner := Value; FCodeDesigner.Strings := Strings; end; procedure TJsEditForm.ValidateMethods(inContainer: TWinControl); begin with TJavaScriptCodeDesigner(CodeDesigner) do begin DeleteEmptyMethods; ValidateEventProperties(inContainer); end; end; end.
unit DSA.Tree.AVLTreeSet; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DSA.Interfaces.DataStructure, DSA.Tree.AVLTree; type { TAVLTreeSet } generic TAVLTreeSet<T, TKeyCmp> = class(TInterfacedObject, specialize ISet<T>) private type TAVLTree_T_V = specialize TAVLTree<T, TObject, TKeyCmp>; var __alt: TAVLTree_T_V; public constructor Create; destructor Destroy; override; procedure Add(e: T); procedure Remove(e: T); function Contains(e: T): boolean; function GetSize: integer; function IsEmpty: boolean; end; implementation { TAVLTreeSet } constructor TAVLTreeSet.Create; begin __alt := TAVLTree_T_V.Create(); end; procedure TAVLTreeSet.Add(e: T); begin __alt.Add(e, nil); end; function TAVLTreeSet.Contains(e: T): boolean; begin Result := Contains(e); end; destructor TAVLTreeSet.Destroy; begin FreeAndNil(__alt); inherited Destroy; end; function TAVLTreeSet.GetSize: integer; begin Result := __alt.GetSize; end; function TAVLTreeSet.IsEmpty: boolean; begin Result := __alt.IsEmpty; end; procedure TAVLTreeSet.Remove(e: T); begin __alt.Remove(e); end; end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } /// <summary> /// Este é nosso contador de execuções /// </summary> FCount: integer; public { Public declarations } /// <summary> /// Esta função não faz nada sério /// </summary> /// <param name="aValue"> /// aValue recebe uma string qualquer /// </param> /// <returns> /// A mesma string que vc passou! /// </returns> function NadaSerio(aValue: string): string; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin Button1.Caption := NadaSerio('Estamos ao vivo'); end; function TForm1.NadaSerio(aValue: string): string; begin Inc(FCount); Result := aValue + ' #' + FCount.ToString; end; end.
unit uPedidoCab; interface type TPedidoCab = class strict private FPRECO_TOTAL : double ; FCLIENTE_CPF : string ; FSTATUS : string ; FDT_EMISSAO : string ; FNUM_PEDIDO : integer ; procedure SetPRECOTOTAL(val : double); function GetPRECOTOTAL : double; procedure SetCLIENTECPF(val : String); function GetCLIENTECPF : String; procedure SetSTATUS(val : String); function GetSTATUS : String; procedure SetDTEMISSAO(val : String); function GetDTEMISSAO : String; procedure SetNUMPEDIDO(val : integer); function GetNUMPEDIDO : integer; public property PRECOTOTAL : double read FPRECO_TOTAL write FPRECO_TOTAL ; property CLIENTECPF : string read FCLIENTE_CPF write FCLIENTE_CPF ; property STATUS : string read FSTATUS write FSTATUS ; property DTEMISSAO : string read FDT_EMISSAO write FDT_EMISSAO ; property NUMPEDIDO : integer read FNUM_PEDIDO write FNUM_PEDIDO ; constructor Create; destructor Destroy; override; end; implementation { TPedidoCab } constructor TPedidoCab.Create; begin inherited Create; end; destructor TPedidoCab.Destroy; begin inherited Destroy; end; function TPedidoCab.GetCLIENTECPF: String; begin Result:= FCLIENTE_CPF; end; function TPedidoCab.GetDTEMISSAO: String; begin Result:= FDT_EMISSAO; end; function TPedidoCab.GetNUMPEDIDO: integer; begin Result:= FNUM_PEDIDO ; end; function TPedidoCab.GetPRECOTOTAL: double; begin Result:= FPRECO_TOTAL; end; function TPedidoCab.GetSTATUS: String; begin Result:= FSTATUS ; end; procedure TPedidoCab.SetCLIENTECPF(val: String); begin FCLIENTE_CPF := val; end; procedure TPedidoCab.SetDTEMISSAO(val: String); begin FDT_EMISSAO:= val; end; procedure TPedidoCab.SetNUMPEDIDO(val: integer); begin FNUM_PEDIDO:= val; end; procedure TPedidoCab.SetPRECOTOTAL(val: double); begin FPRECO_TOTAL:= val; end; procedure TPedidoCab.SetSTATUS(val: String); begin FSTATUS:= val; end; end.
{*******************************************************} { } { Plugin X versão 1.1 beta - 21/01/2004 } { } { Biblioteca para comunicação entre uma DLL/Aplicação } { e uma aplicação Servidor de Internet } { Glauber Almeida Dantas - glauber@delphix.com.br } { } {*******************************************************} unit PluginX; interface uses Windows, Classes; type { AppInfo Info } TAppInfo = packed record Version : String[30]; Hwnd : HWND; Keep : Boolean; end; PAppInfo = ^TAppInfo; { Plugin Info } TPluginInfo = packed record pVersion, pAuthor, pCopyright, pHome, pFunction, pDescription : PChar; end; PPluginInfo = ^TPluginInfo; { Pacote com informações de um cliente } TClientInfo = packed record cID: Integer; cThread: Integer; cInfo1, cInfo2, cInfo3 : String[255]; end; {** Objeto TClient usado nesse exemplo para guardar info de uma conexão **} PClient = ^TClient; TClient = class(TObject) Nick, IP: String[50]; ClientInfo: TClientInfo; end; { Função executada quando o plugin é carregado } TLoadPlugin = procedure (AppInfo: TAppInfo; PluginInfo: TPluginInfo); stdcall; { Função executada quando o plugin é liberado } TUnloadPlugin = procedure; stdcall; { Função executada quando o servidor receber dados } TOnExecute = function(mWnd: hWnd; eClientThread: Pointer; eCmd, eReturn: PChar; NoPause: Boolean): Integer; stdcall; { Para enviar ao plugin dados de um TClient } TSendClientToPlug = procedure (mWnd: hWnd; sClient: TClient; NoPause: Boolean); stdcall; { Tipo TPlugin para armazenar informações dos plugins carregados } PPLugin = ^TPlugin; TPlugin = packed record DLLName : PChar; DLLHandle : THandle; FLoadPlugin : TLoadPlugin; FUnLoadPlugin : TUnLoadPlugin; FOnExecute : TOnExecute; PluginInfo : TPluginInfo; FSendClientToPlug : TSendClientToPlug; end; { Identificadores das mensagens do plugin para a aplicação } const MSG_BASE = $9000; MSG_ERROR = MSG_BASE + 1; APP_BROADCAST_WRITE = MSG_BASE + 11; APP_CLIENT_WRITE = MSG_BASE + 12; APP_CLIENT_CLOSE = MSG_BASE + 13; APP_CLIENT_GETCLIENT = MSG_BASE + 14; implementation end.
unit FrToolsData; interface uses SysUtils, Classes, frxRich, frxExportRTF, frxExportXML, frxExportXLS, frxExportHTML, frxClass, frxExportBaseDialog, frxExportPDF, frxGradient; type TDataFrTools = class(TDataModule) frxGradientObject1: TfrxGradientObject; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxXMLExport1: TfrxXMLExport; frxRTFExport1: TfrxRTFExport; frxRichObject1: TfrxRichObject; frxPDFExport1: TfrxPDFExport; private { Private declarations } public { Public declarations } procedure MyFrxShow(frxReport: TfrxReport); procedure MyFrxLoad(frxReport: TfrxReport; FRepFile:String); end; function DataFrTools: TDataFrTools; implementation {$R *.dfm} uses UniGUIVars, uniGUIMainModule, MainModule,Main, UrlViewForm, ServerModule, uniGUIApplication, Rcontracts; function DataFrTools: TDataFrTools; begin Result := TDataFrTools(UniMainModule.GetModuleInstance(TDataFrTools)); end; //============================================================================= procedure TDataFrTools.MyFrxShow(frxReport: TfrxReport); var fn:String; FormUrlView1: TFormUrlView; begin // R-041541.563.pdf HHMMSS.zzz fn:= 'R-' +FormatDateTime('hhmmss.zzz', Now()) +'.pdf'; // Create a unique name for report. frxReport.PrintOptions.ShowDialog := False; frxReport.ShowProgress:=false; frxReport.PrintOptions.ShowDialog:=false; frxReport.EngineOptions.SilentMode:=True; frxPDFExport1.Background:=True; frxPDFExport1.ShowProgress:=False; frxPDFExport1.ShowDialog:=False; frxPDFExport1.EmbeddedFonts:=True; frxPDFExport1.FileName := UniServerModule.LocalCachePath +fn; frxPDFExport1.DefaultPath := ''; if Mainform.WebMode then begin frxReport.PrepareReport(); // Create Report frxReport.Export(frxPDFExport1); // Export Report if MainForm.DwnRepoFile then begin UniSession.SendFile(UniServerModule.LocalCachePath +fn, fn); end else begin FormUrlView1:=TFormUrlView.Create(UniApplication); FormUrlView1.URLFrame.URL := UniServerModule.LocalCacheURL +fn; // Displayed on UniURLFrame FormUrlView1.Show; end; end else begin frxReport.ShowReport(); end; end; procedure TDataFrTools.MyFrxLoad(frxReport: TfrxReport; FRepFile: String); begin frxReport.Clear; frxReport.PreviewOptions.AllowEdit:=False; // frxReport.LoadFromFile('.......\'+FRepFile); frxReport.LoadFromFile(UniMainModule.ReportsPath + FRepFile + '.fr3'); frxReport.PrepareReport(true); // frxReport1.LoadFromFile(UniMainModule.ReportsPath + RepName + '.fr3'); // // fn:= 'R-' +FormatDateTime('hhmmss.zzz', Now()) +'.pdf'; // Create a unique name for report. // frxReport.PrintOptions.ShowDialog := False; // frxReport.ShowProgress:=false; // frxReport.PrintOptions.ShowDialog:=false; // frxReport.EngineOptions.SilentMode:=True; // frxPDFExport1.Background:=True; // frxPDFExport1.ShowProgress:=False; // frxPDFExport1.ShowDialog:=False; // frxPDFExport1.FileName := UniServerModule.LocalCachePath +fn; // frxPDFExport1.DefaultPath := ''; // if Mainform.WebMode then begin // frxReport.PrepareReport(); // Create Report // frxReport.Export(frxPDFExport1); // Export Report // if MainForm.DwnRepoFile then begin // UniSession.SendFile(UniServerModule.LocalCachePath +fn, fn); // end else begin // FormUrlView1:=TFormUrlView.Create(UniApplication); // FormUrlView1.URLFrame.URL := UniServerModule.LocalCacheURL +fn; // Displayed on UniURLFrame // FormUrlView1.Show; // end; // end else begin // frxReport.ShowReport(); // end; end; initialization RegisterModuleClass(TDataFrTools); end.
unit WarodaiHeader; { Разбор заголовков статей. } interface uses Warodai; {$INCLUDE 'Warodai.inc'} { Заголовок любой статьи - одна строчка, которая содержит все или некоторые последующие поля: みる【見る・観る】(миру)〔1-603-1-64〕 катакана 【разные・варианты・кандзи】(киридзи)〔ссылка〕 Чтение и ссылка присутствуют обязательно, всё остальное опционально. Также возможная схема с несколькими словами: よもぎ, よもぎな【艾・蓬, 艾采】(ёмоги, ёмогина)〔1-241-2-52〕 イロアききん, イロアしきん【イロア基金・EROA基金, イロア資金・EROA資金】(ироа-кйкин, ироа-сйкин)〔1-277-2-69〕 При этом и кандзи, и киридзи должны присутствовать в стольких же версиях, а кандзи в каждой версии может присутствовать в нескольких вариантах (см. выше). Также возможны флаги прямо в заголовке: アイレ(Айрэ) [геогр.]〔2-595-1-24〕 おおくまざ【大熊座】(о:кумадза) [нов.]〔A-937-3-28〕 Встречаются следующие редкие неприятные моменты. Несколько чтений на один кандзи: わらしべ, わらすべ【藁稭】(варасибэ, варасубэ)〔1-084-1-41〕 --- тогда кандзи копируется Несколько киридзи на одно чтение: です(дэс, дэсў)〔1-231-2-35〕 --- так лишь в двух записях, пока никак не поддерживается, берём первое киридзи } const MaxWords = 4; MaxKanjiVariants = 10; type TEntryWord = record s_reading: string; s_kanji: array[0..MaxKanjiVariants-1] of string; s_kanji_used: integer; s_kiriji: string; end; PEntryWord = ^TEntryWord; TEntryHeader = record s_ref: string; s_flags: string; words: array[0..MaxWords-1] of TEntryWord; words_used: integer; end; PEntryHeader = ^TEntryHeader; procedure DecodeEntryHeader(s: string; hdr: PEntryHeader); { После некоторых чтений и некоторых записей кандзи идёт римская запись номера варианта: みるI みるIV 見るII Нижеследующая функция удаляет эту часть из строки. } function DropVariantIndicator(const s: string): string; overload; implementation uses SysUtils, StrUtils, UniStrUtils; type TBasicEntryHeader = record ref: string; readings: array[0..MaxWords-1] of string; reading_cnt: integer; kiriji: array[0..MaxWords-1] of string; kiriji_cnt: integer; flags: string; kanji: array[0..MaxWords-1] of record variants: array[0..MaxKanjiVariants-1] of string; variant_cnt: integer; end; kanji_cnt: integer; procedure Reset; function AddReading: PString; function AddKiriji: PString; function AddKanji: integer; function AddKanjiVariant(kanji_id: integer): PString; end; PBasicEntryHeader = ^TBasicEntryHeader; procedure TBasicEntryHeader.Reset; begin ref := ''; flags := ''; reading_cnt := 0; kiriji_cnt := 0; kanji_cnt := 0; end; function TBasicEntryHeader.AddReading: PString; begin if reading_cnt>=Length(readings) then raise EParsingException.Create('BasicEntryHeader: cannot add one more reading.'); Inc(reading_cnt); Result := @readings[reading_cnt-1]; Result^ := ''; end; function TBasicEntryHeader.AddKiriji: PString; begin if kiriji_cnt>=Length(kiriji) then raise EParsingException.Create('BasicEntryHeader: cannot add one more kiriji.'); Inc(kiriji_cnt); Result := @kiriji[kiriji_cnt-1]; Result^ := ''; end; function TBasicEntryHeader.AddKanji: integer; begin if kanji_cnt>=Length(kanji) then raise EParsingException.Create('BasicEntryHeader: cannot add one more kanji.'); Inc(kanji_cnt); kanji[kanji_cnt-1].variant_cnt := 0; Result := kanji_cnt-1; end; function TBasicEntryHeader.AddKanjiVariant(kanji_id: integer): PString; begin if kanji[kanji_id].variant_cnt>=Length(kanji[kanji_id].variants) then raise EParsingException.Create('BasicEntryHeader: cannot add one more kanji variant.'); Inc(kanji[kanji_id].variant_cnt); with kanji[kanji_id] do Result := @variants[variant_cnt-1]; Result^ := ''; end; { Раскодирует строку, просто разбирая её структуру - не пытаясь проверить, что строка правильная } procedure DecodeBasicEntryHeader(s: string; bh: PBasicEntryHeader); const //parsing state EH_READING = 0; EH_KANJI = 1; EH_KIRIJI = 2; EH_FLAGS = 3; EH_REF = 4; var state: integer; pc: PChar; state_over: boolean; //if set, we're in state transition (such as "】(") and normal symbols are not expected curreading: PString; curkiriji: PString; curkanjiid: integer; curkanjivariant: PString; procedure SkipSpaces(); begin Inc(pc); while pc^=' ' do Inc(pc); Dec(pc); end; procedure StartKanji; begin state := EH_KANJI; state_over := false; curkanjiid := bh.AddKanji; curkanjivariant := bh.AddKanjiVariant(curkanjiid); end; procedure StartKiriji; begin state := EH_KIRIJI; state_over := false; curkiriji := bh.AddKiriji; end; procedure StartFlags; begin state := EH_FLAGS; state_over := false; end; procedure StartRef; begin state := EH_REF; state_over := false; end; begin state := EH_READING; state_over := false; bh.Reset; curreading := bh.AddReading(); pc := PWideChar(s); while pc^<>#00 do begin //Пока читаем "чтение", составляем таблицу слов (определяем words_used) if (state=EH_READING) and (pc^=',') then begin SkipSpaces; curreading := bh.AddReading; end else if (state=EH_READING) and (pc^='【') then StartKanji else if (state=EH_READING) and (pc^='(') then StartKiriji else if (state=EH_READING) and (pc^='[') then StartFlags else if (state=EH_READING) and (pc^='〔') then StartRef else //Дальшей каждой компоненты должно быть по words_used версий if (state=EH_KANJI) and (pc^='・') then begin curkanjivariant := bh.AddKanjiVariant(curkanjiid); end else if (state=EH_KANJI) and (pc^=',') then begin SkipSpaces; curkanjiid := bh.AddKanji; curkanjivariant := bh.AddKanjiVariant(curkanjiid); end else if (state=EH_KANJI) and (pc^='】') then state_over := true else if (state=EH_KANJI) and state_over and (pc^='(') then StartKiriji else if (state=EH_KANJI) and state_over and (pc^='[') then StartFlags else if (state=EH_KANJI) and state_over and (pc^='〔') then StartRef else if (state=EH_KIRIJI) and (pc^=',') then curkiriji := bh.AddKiriji else if (state=EH_KIRIJI) and (pc^=')') then state_over := true else if (state=EH_KIRIJI) and state_over and (pc^='[') then StartFlags else if (state=EH_KIRIJI) and state_over and (pc^='〔') then StartRef else if (state=EH_FLAGS) and (pc^=']') then state_over := true else if (state=EH_FLAGS) and state_over and (pc^='〔') then StartRef else if (state=EH_REF) and (pc^='〕') then state_over := true else if state_over=true then begin //Лишние символы между скобками //Можно быть добрыми и просто пропускать их, но давайте контролировать ошибки if pc^<>' ' then raise EParsingException.Create('Unexpected characters in state_over.'); end else if (state=EH_READING) then curreading^ := curreading^ + pc^ else if (state=EH_KANJI) then curkanjivariant^ := curkanjivariant^ + pc^ else if (state=EH_KIRIJI) then curkiriji^ := curkiriji^ + pc^ else if (state=EH_FLAGS) then bh.flags := bh.flags + pc^ else if (state=EH_REF) then bh.ref := bh.ref + pc^ else raise EParsingException.Create('DecodeEntryHeader(): Invalid parsing state.'); //this should not happen no matter the input Inc(pc); end; //Контролируем ошибки if (state<>EH_READING) and (state_over<>true) then raise EParsingException.Create('Unclosed part, state='+IntToStr(state)+', state_over='+BoolToStr(state_over, true)); end; procedure DecodeEntryHeader(s: string; hdr: PEntryHeader); var bh: TBasicEntryHeader; i, j: integer; begin DecodeBasicEntryHeader(s, @bh); { Пробуем устранить всякие простые ошибки } //Одно киридзи на несколько чтений - дублируем его каждому чтению if (bh.reading_cnt > 1) and (bh.kiriji_cnt = 1) then begin bh.kiriji_cnt := bh.reading_cnt; for i := 1 to bh.kiriji_cnt - 1 do bh.kiriji[i] := bh.kiriji[0]; end; //Кандзи присутствует только в одной форме - дублируем его каждому чтению if (bh.reading_cnt > 1) and (bh.kanji_cnt = 1) then begin bh.kanji_cnt := bh.reading_cnt; for i := 1 to bh.kanji_cnt - 1 do bh.kanji[i] := bh.kanji[0]; end; {$IFDEF FIX_UNSUPPORTED} if (bh.kiriji_cnt>1) and (bh.reading_cnt = 1) then bh.kiriji_cnt := 1; {$ENDIF} //Проверяем, что все поля совпадают if (bh.kiriji_cnt <> bh.reading_cnt) and (bh.kiriji_cnt <> 0) then raise EParsingException.Create('Kiriji count not equal to reading count.'); if (bh.kanji_cnt <> bh.reading_cnt) and (bh.kanji_cnt <> 0) then raise EParsingException.Create('Kanji count not equal to reading count.'); if bh.ref='' then raise EParsingException.Create('Reference missing'); //Иначе всё совпадает - перекодируем hdr.s_ref := bh.ref; hdr.words_used := bh.reading_cnt; for i := 0 to hdr.words_used - 1 do begin hdr.words[i].s_reading := bh.readings[i]; if bh.kiriji_cnt<>0 then hdr.words[i].s_kiriji := bh.kiriji[i] else hdr.words[i].s_kiriji := ''; if bh.kanji_cnt<>0 then begin hdr.words[i].s_kanji_used := bh.kanji[i].variant_cnt; for j := 0 to hdr.words[i].s_kanji_used - 1 do hdr.words[i].s_kanji[j] := bh.kanji[i].variants[j]; end else hdr.words[i].s_kanji_used := 0; end; end; procedure _DropVariantIndicator(var s: string); var ch: Char; i: integer; begin i := Length(s); if i<=0 then exit; ch := s[i]; while (ch='I') or (ch='V') or (ch='X') or (ch=' ') do begin Dec(i); if i<=0 then break; ch := s[i]; end; delete(s, i+1, Length(s)-i); end; function DropVariantIndicator(const s: string): string; overload; begin Result := s; _DropVariantIndicator(Result); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Options.Restore; interface uses DPM.Core.Types, DPM.Core.Logging, DPM.Core.Options.Search; type TRestoreOptions = class(TSearchOptions) private FProjectPath : string; class var FDefault : TRestoreOptions; protected constructor CreateClone(const original : TRestoreOptions); reintroduce; public class constructor CreateDefault; class property Default : TRestoreOptions read FDefault; constructor Create; override; function Validate(const logger : ILogger) : Boolean; override; function Clone : TRestoreOptions; reintroduce; property ProjectPath : string read FProjectPath write FProjectPath; end; implementation { TRestoreOptions } function TRestoreOptions.Clone : TRestoreOptions; begin result := TRestoreOptions.CreateClone(Self); end; constructor TRestoreOptions.Create; begin inherited; Prerelease := true; end; constructor TRestoreOptions.CreateClone(const original : TRestoreOptions); begin inherited CreateClone(original); FProjectPath := original.ProjectPath; end; class constructor TRestoreOptions.CreateDefault; begin FDefault := TRestoreOptions.Create; end; function TRestoreOptions.Validate(const logger : ILogger) : Boolean; begin //must call inherited result := inherited Validate(logger); if FProjectPath = '' then begin Logger.Error('Project path cannot be empty, must either be a directory or project file.'); result := false; end; end; end.
unit eUsusario.Controller.Factory.Query; interface uses eUsusario.Controller.Factory.Interfaces, eUsusario.View.Conexao.Interfaces; Type TControllerFactoryQuery = class(TInterfacedObject, iFactoryQuery) private public constructor Create; destructor Destroy; override; class function New : iFactoryQuery; function Query(Connection : iConexao) : iQuery; end; implementation uses eUsusario.View.Query.Firedac; { TControllerFactoryQuery } constructor TControllerFactoryQuery.Create; begin end; destructor TControllerFactoryQuery.Destroy; begin inherited; end; class function TControllerFactoryQuery.New: iFactoryQuery; begin Result := Self.Create; end; function TControllerFactoryQuery.Query(Connection : iConexao) : iQuery; begin Result := TModelQueryFiredac.New(Connection); end; end.