text
stringlengths
14
6.51M
unit Interfaces; interface uses System.SysUtils, System.Generics.Collections, DataModels; type IPanelFrame = interface ['{753BD983-6F7C-418F-9D9B-96FFAD37E138}'] end; IBasePresenter = interface ['{D11D3023-FDFF-4146-AF07-491FA2B6E52F}'] procedure Start; end; IBaseView<T> = interface ['{D11D3023-FDFF-4146-AF07-491FA2B6E52F}'] procedure SetPresenter(APresenter: T); end; IMainPresenter = interface(IBasePresenter) ['{2018CC47-FB09-4883-A910-521D9D9D8A8D}'] end; IMainView = interface(IBaseView<IMainPresenter>) ['{062D2FAA-A4AA-46AF-B6EB-92E43F4E47EB}'] procedure CreateMenuPage; procedure OpenFrame(ATitle: string; AProc: TProc<IPanelFrame>); procedure CloseTab(AControl: IPanelFrame); end; IBaseFrameView<T> = interface(IBaseView<T>) ['{7B0AA6F0-3981-4815-B522-6867CDABBF4C}'] procedure SetMainAndPanel(AMain: IMainView; APanel: IPanelFrame); end; IMenuPresenter = interface(IBasePresenter) ['{BBB01FCD-E79C-432A-80AE-AF016A7AA9AA}'] end; IMenuView = interface(IBaseFrameView<IMenuPresenter>) ['{2B04293C-2E7C-4BA6-A2E1-214A1700E53B}'] end; IProductsPresenter = interface(IBasePresenter) ['{323CEBCE-7104-438E-B346-CF71B75C1756}'] procedure LoadData; end; IProductsView = interface(IBaseFrameView<IProductsPresenter>) ['{CBB6BF9D-3F30-40C6-AAB9-292CC3B9249A}'] procedure ShowData(AProducts: TList<TProducts>); end; implementation end.
unit CANLIB; // // Copyright 1995-2018 by KVASER AB // WWW: http://www.kvaser.com // // This software is furnished under a license and may be used and copied // only in accordance with the terms of such license. // // This unit defines an interface for Delphi to CANLIB32.DLL. interface {$IF Defined(WIN32) or Defined(WIN64)} uses Messages, Windows; {$ENDIF} const canINVALID_HANDLE = -1; canOK = 0; canERR_PARAM = -1; // Error in parameter canERR_NOMSG = -2; // No messages available canERR_NOTFOUND = -3; // Specified hw not found canERR_NOMEM = -4; // Out of memory canERR_NOCHANNELS = -5; // No channels avaliable canERR_INTERRUPTED = -6; // Interrupted by signals canERR_TIMEOUT = -7; // Timeout occurred canERR_NOTINITIALIZED = -8; // Lib not initialized canERR_NOHANDLES = -9; // Can't get handle canERR_INVHANDLE = -10; // Handle is invalid canERR_INIFILE = -11; // Error in the ini-file (16-bit only) canERR_DRIVER = -12; // CAN driver type not supported canERR_TXBUFOFL = -13; // Transmit buffer overflow canERR_RESERVED_1 = -14; // canERR_HARDWARE = -15; // Some hardware error has occurred canERR_DYNALOAD = -16; // Can't find requested DLL canERR_DYNALIB = -17; // DLL seems to be wrong version canERR_DYNAINIT = -18; // Error when initializing DLL canERR_NOT_SUPPORTED = -19; // Operation not supported by hardware or firmware canERR_RESERVED_5 = -20; // canERR_RESERVED_6 = -21; // canERR_RESERVED_2 = -22; // canERR_DRIVERLOAD = -23; // Can't find/load driver canERR_DRIVERFAILED = -24; // DeviceIOControl failed; use Win32 GetLastError() canERR_NOCONFIGMGR = -25; // Can't find req'd config s/w (e.g. CS/SS) canERR_NOCARD = -26; // The card was removed or not inserted canERR_RESERVED_7 = -27; // canERR_REGISTRY = -28; // Error in the Registry canERR_LICENSE = -29; // The license is not valid. canERR_INTERNAL = -30; // Internal error in the driver. canERR_NO_ACCESS = -31; // Access denied canERR_NOT_IMPLEMENTED = -32; // Requested function is not implemented canERR_DEVICE_FILE = -33; // An error has occured when trying to access a file on the device. canERR_HOST_FILE = -34; // An error has occured when trying to access a file on the host. canERR_DISK = -35; // A disk error has occurred. Verify that the disk is initialized. canERR_CRC = -36; // The CRC calculation did not match the expected result. canERR_CONFIG = -37; // The configuration is corrupt. canERR_MEMO_FAIL = -38; // Other configuration error. canERR_SCRIPT_FAIL = -39; // A script has failed. canERR_SCRIPT_WRONG_VERSION = -40; // The t script version dosen't match the version(s) that the device firmware supports. canERR__RESERVED = -41; // RESERVED {$IF Defined(WIN32) or Defined(WIN64)} WM__CANLIB = (WM_USER + 16354); // Windows message from Can unit. {$ENDIF} canEVENT_RX = 32000; // Receive event canEVENT_TX = 32001; // Transmit event canEVENT_ERROR = 32002; // Error event canEVENT_STATUS = 32003; // Change-of-status event canEVENT_ENVVAR = 32004; // An envvar changed canEVENT_BUSONOFF = 32005; // Bus on/off status changed canEVENT_REMOVED = 32006; // Device removed // Used in canSetNotify canNOTIFY_NONE = $0000; // Turn notifications off. canNOTIFY_RX = $0001; // Notify on receive canNOTIFY_TX = $0002; // Notify on transmit canNOTIFY_ERROR = $0004; // Notify on error canNOTIFY_STATUS = $0008; // Notify on (some) status change events canNOTIFY_ENVVAR = $0010; // An environment variable was changed by a script canNOTIFY_BUSONOFF = $0020; // Notify on bus on/off status changed canNOTIFY_REMOVED = $0040; // Notify on device removed // Circuit status flags canSTAT_ERROR_PASSIVE = $00000001; // The circuit is error passive canSTAT_BUS_OFF = $00000002; // The circuit is Off Bus canSTAT_ERROR_WARNING = $00000004; // At least one error counter > 96 canSTAT_ERROR_ACTIVE = $00000008; // The circuit is error active. canSTAT_TX_PENDING = $00000010; // There are messages pending transmission canSTAT_RX_PENDING = $00000020; // There are messages in the receive buffer canSTAT_RESERVED_1 = $00000040; // canSTAT_TXERR = $00000080; // There has been at least one TX error canSTAT_RXERR = $00000100; // There has been at least one RX error of some sort canSTAT_HW_OVERRUN = $00000200; // The has been at least one HW buffer overflow canSTAT_SW_OVERRUN = $00000400; // The has been at least one SW buffer overflow // Message information flags canMSG_MASK = $00FF; // Used to mask the non-info bits canMSG_RTR = $0001; // Message is a remote request canMSG_STD = $0002; // Message has a standard ID canMSG_EXT = $0004; // Message has an extended id canMSG_WAKEUP = $0008; // Message is a SWC wakeup frame canMSG_STATUS = $0008; // Obsolete - retained for compatibility canMSG_NERR = $0010; // Message sent/received with TJA1054 (etc.) NERR active canMSG_ERROR_FRAME = $0020; // Message is an error frame canMSG_TXACK = $0040; // Message is a TX ACK (msg is really sent) canMSG_TXRQ = $0080; // Message is a TX REQUEST (msg is transfered to the chip) canMSG_DELAY_MSG = $0100; // Message is NOT sent on the bus. The transmission of messages are delayed. // The dlc specifies the delay in milliseconds // single shot flags: canMSG_SINGLE_SHOT = $1000000; // Message is Single Shot, try to send once, no retransmission (only tx) canMSG_TXNACK = $2000000; // Message is a failed Single Shot, message was not sent (only rx) canMSG_ABL = $4000000; // Only together with canMSG_TXNACK, Single shot message was not sent because arbitration was lost (only rx) // Message error flags, >= $0100 canFDMSG_MASK = $FF0000; // Used to mask the non-info bits canFDMSG_EDL = $010000; // Obsolete, use canFDMSG_FDF instead canFDMSG_FDF = $010000; // Indicate if message is an FD message canFDMSG_BRS = $020000; // Indicate if message should be sent with bit rate switch canFDMSG_ESI = $040000; // Indicate if the sender of this message is in error passive mode // Message error flags, >= $0100 canMSGERR_MASK = $FF00; // Used to mask the non-error bits // $0100 reserved canMSGERR_HW_OVERRUN = $0200; // HW buffer overrun canMSGERR_SW_OVERRUN = $0400; // SW buffer overrun canMSGERR_STUFF = $0800; // Stuff error canMSGERR_FORM = $1000; // Form error canMSGERR_CRC = $2000; // CRC error canMSGERR_BIT0 = $4000; // Sent dom, read rec canMSGERR_BIT1 = $8000; // Sent rec, read dom // Convenience values canMSGERR_OVERRUN = $0600; // Any overrun condition. canMSGERR_BIT = $C000; // Any bit error (note: TWO bits) canMSGERR_BUSERR = $F800; // Any RX error canCIRCUIT_ANY = -1; // Any circuit will do canCARD_ANY = -1; // Any card will do canCHANNEL_ANY = -1; // Any channel will do // Flags for canAccept canFILTER_ACCEPT = 1; canFILTER_REJECT = 2; canFILTER_SET_CODE_STD = 3; canFILTER_SET_MASK_STD = 4; canFILTER_SET_CODE_EXT = 5; canFILTER_SET_MASK_EXT = 6; canFILTER_NULL_MASK = 0; canDRIVER_NORMAL = 4; canDRIVER_SILENT = 1; canDRIVER_SELFRECEPTION = 8; canDRIVER_OFF = 0; // "shortcut" baud rates; use with canBusParams or canTranslateBaud // canBAUD_xxx is obsolete; use canBITRATE_xxx instead canBAUD_1M = -1; canBAUD_500K = -2; canBAUD_250K = -3; canBAUD_125K = -4; canBAUD_100K = -5; canBAUD_62K = -6; canBAUD_50K = -7; canBAUD_83K = -8; canBITRATE_1M = -1; canBITRATE_500K = -2; canBITRATE_250K = -3; canBITRATE_125K = -4; canBITRATE_100K = -5; canBITRATE_62K = -6; canBITRATE_50K = -7; canBITRATE_83K = -8; canBITRATE_10K = -9; canFD_BITRATE_500K_80P = -1000; canFD_BITRATE_1M_80P = -1001; canFD_BITRATE_2M_80P = -1002; canFD_BITRATE_4M_80P = -1003; canFD_BITRATE_8M_60P = -1004; canIOCTL_PREFER_EXT = 1; canIOCTL_PREFER_STD = 2; canIOCTL_RES3 = 3; canIOCTL_RES4 = 4; canIOCTL_CLEAR_ERROR_COUNTERS = 5; canIOCTL_SET_TIMER_SCALE = 6; canIOCTL_SET_TXACK = 7; canIOCTL_GET_RX_BUFFER_LEVEL = 8; canIOCTL_GET_TX_BUFFER_LEVEL = 9; canIOCTL_FLUSH_RX_BUFFER = 10; canIOCTL_FLUSH_TX_BUFFER = 11; canIOCTL_GET_TIMER_SCALE = 12; canIOCTL_SET_TX_REQUESTS = 13; canIOCTL_GET_EVENTHANDLE = 14; canIOCTL_SET_BYPASS_MODE = 15; canIOCTL_SET_WAKEUP = 16; canIOCTL_GET_DRIVERHANDLE = 17; canIOCTL_MAP_RXQUEUE = 18; canIOCTL_GET_WAKEUP = 19; canIOCTL_SET_REPORT_ACCESS_ERRORS = 20; canIOCTL_GET_REPORT_ACCESS_ERRORS = 21; canIOCTL_CONNECT_TO_VIRTUAL_BUS = 22; canIOCTL_DISCONNECT_FROM_VIRTUAL_BUS = 23; canIOCTL_SET_USER_IOPORT = 24; canIOCTL_GET_USER_IOPORT = 25; canIOCTL_SET_BUFFER_WRAPAROUND_MODE = 26; canIOCTL_SET_RX_QUEUE_SIZE = 27; canIOCTL_SET_USB_THROTTLE = 28; canIOCTL_GET_USB_THROTTLE = 29; canIOCTL_SET_BUSON_TIME_AUTO_RESET = 30; canIOCTL_GET_TXACK = 31; canIOCTL_SET_LOCAL_TXECHO = 32; canIOCTL_SET_ERROR_FRAMES_REPORTING = 33; canIOCTL_GET_CHANNEL_QUALITY = 34; canIOCTL_GET_ROUNDTRIP_TIME = 35; canIOCTL_GET_BUS_TYPE = 36; canIOCTL_GET_DEVNAME_ASCII = 37; canIOCTL_GET_TIME_SINCE_LAST_SEEN = 38; canIOCTL_GET_TREF_LIST = 39; canIOCTL_TX_INTERVAL = 40; canIOCTL_SET_THROTTLE_SCALED = 41; canIOCTL_GET_THROTTLE_SCALED = 42; canIOCTL_SET_BRLIMIT = 43; canIOCTL_RESET_OVERRUN_COUNT = 44; // Type of buffer canOBJBUF_TYPE_AUTO_RESPONSE = $01; canOBJBUF_TYPE_PERIODIC_TX = $02; // The buffer responds to RTRs only, not regular messages. canOBJBUF_AUTO_RESPONSE_RTR_ONLY = $01; // Check for specific version(s) of CANLIB. canVERSION_DONT_ACCEPT_LATER = $01; canVERSION_DONT_ACCEPT_BETAS = $02; CANID_METAMSG = (-1); CANID_WILDCARD = (-2); kvENVVAR_TYPE_INT = 1; kvENVVAR_TYPE_FLOAT = 2; kvENVVAR_TYPE_STRING = 3; kvEVENT_TYPE_KEY = 1; kvSCRIPT_STOP_NORMAL = 0; kvSCRIPT_STOP_FORCED = -9; kvDEVICE_MODE_INTERFACE = $00; kvDEVICE_MODE_LOGGER = $01; canVERSION_CANLIB32_VERSION = 0; canVERSION_CANLIB32_PRODVER = 1; canVERSION_CANLIB32_PRODVER32 = 2; canVERSION_CANLIB32_BETA = 3; kvBUSTYPE_NONE = 0; kvBUSTYPE_PCI = 1; kvBUSTYPE_PCMCIA = 2; kvBUSTYPE_USB = 3; kvBUSTYPE_WLAN = 4; kvBUSTYPE_PCI_EXPRESS = 5; kvBUSTYPE_ISA = 6; kvBUSTYPE_VIRTUAL = 7; kvBUSTYPE_PC104_PLUS = 8; kvBUSTYPE_LAN = 9; kvBUSTYPE_GROUP_VIRTUAL = 1; // kvBUSTYPE_VIRTUAL kvBUSTYPE_GROUP_LOCAL = 2; // kvBUSTYPE_USB kvBUSTYPE_GROUP_REMOTE = 3; // kvBUSTYPE_WLAN kvBUSTYPE_GROUP_INTERNAL = 4; // kvBUSTYPE_PCI, kvBUSTYPE_PCMCIA, ... kvSCRIPT_REQUEST_TEXT_UNSUBSCRIBE = 1; kvSCRIPT_REQUEST_TEXT_SUBSCRIBE = 2; kvSCRIPT_REQUEST_TEXT_ALL_SLOTS = 255; kvREMOTE_TYPE_NOT_REMOTE = 0; kvREMOTE_TYPE_WLAN = 1; kvREMOTE_TYPE_LAN = 2; kvLOGGER_TYPE_NOT_A_LOGGER = 0; kvLOGGER_TYPE_V1 = 1; kvLOGGER_TYPE_V2 = 2; type {$IF Defined(WIN32) or Defined(WIN64)} // This one is primarily used by WCANKING TMsgRec = record // This record holds information about a CAN message. envelope: Longint; // The CAN envelope. dlc: Integer; // The data length code. flag: Integer; // The flag have information about remote request and #X Return flags case indexType: Integer of 0: (data: array [0 .. 7] of AnsiChar); // CAN data as char. 1: (shData: array [0 .. 7] of ShortInt); // CAN data as shortint. 2: (bData: array [0 .. 7] of Byte); // CAN data as byte. 3: (iData: array [0 .. 3] of SmallInt); // CAN data as smallint. 4: (lData: array [0 .. 1] of Longint); // CAN data as Longint. 6: (wData: array [0 .. 3] of Word); // CAN data as word. 7: (tData: string[7]); // CAN data as string[7]. 8: (fData: array [0 .. 1] of Single); // CAN data as float. 9: (rData: Real); // CAN data as real. 10: (dData: Double); // CAN data as double. 11: (cData: Comp); // CAN data as comp. end; // This one is primarily used by WCANKING TMsgObj = class(TObject) // A TMsgObj holds a TMsgRec, so it can be used as an object in TStringList. public txm : Boolean; // True if CAN message sent, false if received. time : Longint; // Receive time in milliseconds. count : Integer; // Message number. MsgRec: TMsgRec; // The CAN message. end; canMemoryAllocator = TFarProc; // Memory allocator, if nil malloc is used. canMemoryDeallocator = TFarProc; // Memory deallocator, if nil free is used. canAction = TFarProc; // Currently unsupported. BYTEPTR = PAnsiChar; // Byte pointer. // Can hardware descriptor, holds information about CAN card and CAN circuit used. canHWDescr = record circuitType: Integer; // The CAN circuit. cardType: Integer; channel: Integer; end; // Used in canOpen. Obsolete. canSWDescr = record rxBufSize: Integer; // Requested receive buffer size [1, 32767]. txBufSize: Integer; // Requested transmit buffer size [0, 32767]. alloc: canMemoryAllocator; // Memory allocator. deAlloc: canMemoryDeallocator; // Memory deallocator. end; canSWDescrPointer = ^canSWDescr; TWMCan = record // Type declaration for windows or dos message Msg: Cardinal; case Integer of 0: (WParam: Cardinal; LParam: Longint; Result: Longint); 1: (handle: Cardinal; // CAN handle issuing message. minorMsg: Word; // Message types. status: Word;); // Status. end; {$ENDIF} canStatus = Integer; canHandle = Integer; kvEnvHandle = Int64; canBusStatistics = record stdData: Cardinal; stdRemote: Cardinal; extData: Cardinal; extRemote: Cardinal; errFrame: Cardinal; // Error frames busLoad: Cardinal; // 0 .. 10000 meaning 0.00-100.00% overruns: Cardinal; end; canUserIoPortData = record portNo: Cardinal; portValue: Cardinal; end; {$IF Defined(WIN32) or Defined(WIN64)} TCanInterface = class(TObject) public channel : Integer; eanhi, eanlo: Cardinal; serial : Cardinal; hnd : canHandle; name : string; Constructor create(canChannel: Integer); overload; private end; // ------------------------------------------------------------+ // | End of type definitions. | // +------------------------------------------------------------ function canLocateHardware: canStatus; stdcall; procedure canInitializeLibrary; stdcall; function canUnloadLibrary: Integer; stdcall; procedure SetDllName(s: string); {$ENDIF} type kvCallback_t = procedure(handle: canHandle; context: Pointer; notifyEvent: Cardinal); stdcall; kvStatus = canStatus; kvTimeDomain = Cardinal; // Really a pointer to something kvTimeDomainData = packed record nMagiSyncGroups: Integer; nMagiSyncedMembers: Integer; nNonMagiSyncCards: Integer; nNonMagiSyncedMembers: Integer; end; {$IF Defined(WIN32) or Defined(WIN64)} var canOpen : function(const hwdescr: canHWDescr; swdescr: Pointer; flags: Cardinal): canHandle; stdcall; canClose : function(handle: canHandle): canStatus; stdcall; canBusOn : function(handle: canHandle): canStatus; stdcall; canBusOff : function(handle: canHandle): canStatus; stdcall; canSetBusParams : function(handle: canHandle; freq: Longint; tseg1, tseg2, sjw, noSamp, syncmode: Cardinal): canStatus; stdcall; canGetBusParams : function(handle: canHandle; var freq: Longint; var tseg1, tseg2, sjw, noSamp, syncmode: Cardinal): canStatus; stdcall; canSetBusParamsFd : function(handle: canHandle; freq: Longint; tseg1, tseg2, sjw: Cardinal): canStatus; stdcall; canGetBusParamsFd : function(handle: canHandle; var freq: Longint; var tseg1, tseg2, sjw: Cardinal): canStatus; stdcall; canSetBusOutputControl : function(handle: canHandle; drivertype: Cardinal): canStatus; stdcall; canGetBusOutputControl : function(handle: canHandle; var drivertype: Cardinal): canStatus; stdcall; canAccept : function(handle: canHandle; envelope: Longint; flag: Cardinal): canStatus; stdcall; canReadStatus : function(handle: canHandle; var flags: Cardinal): canStatus; stdcall; canReadErrorCounters : function(handle: canHandle; var txErr, rxErr, ovErr: Cardinal): canStatus; stdcall; canWrite : function(handle: canHandle; id: Longint; Msg: Pointer; dlc: Cardinal; flag: Cardinal): canStatus; stdcall; canWriteSync : function(handle: canHandle; timeout: Cardinal): canStatus; stdcall; canRead : function(handle: canHandle; var id: Longint; Msg: Pointer; var dlc: Cardinal; var flag: Cardinal; var time: Cardinal): canStatus; stdcall; canReadWait : function(handle: canHandle; var id: Longint; Msg: Pointer; var dlc: Cardinal; var flag: Cardinal; var time: Cardinal; timeout: Cardinal): canStatus; stdcall; canReadSpecific : function(handle: canHandle; id: Longint; Msg: Pointer; var dlc: Cardinal; var flag: Cardinal; var time: Cardinal): canStatus; stdcall; canReadSync : function(handle: canHandle; timeout: Cardinal): canStatus; stdcall; canReadSyncSpecific : function(handle: canHandle; id: Longint; timeout: Cardinal): canStatus; stdcall; canReadSpecificSkip : function(handle: canHandle; id: Longint; Msg: Pointer; var dlc: Cardinal; var flag: Cardinal; var time: Cardinal): canStatus; stdcall; canInstallAction : function(handle: canHandle; id: Longint; fn: Pointer): canStatus; stdcall; canUninstallAction : function(handle: canHandle; id: Longint): canStatus; stdcall; canInstallOwnBuffer : function(handle: canHandle; id: Longint; len: Cardinal; buf: Pointer): canStatus; stdcall; canUninstallOwnBuffer : function(handle: canHandle; id: Longint): canStatus; stdcall; canSetNotify : function(handle: canHandle; aHWnd: HWND; aNotifyFlags: Cardinal): canStatus; stdcall; canTranslateBaud : function(var freq: Longint; var tseg1, tseg2, sjw, noSamp, syncmode: Cardinal): canStatus; stdcall; canGetErrorText : function(err: canStatus; buf: PAnsiChar; bufsiz: Cardinal): canStatus; stdcall; canGetVersion : function: Word; stdcall; canIoCtl : function(handle: canHandle; func: Cardinal; buf: Pointer; buflen: Cardinal): canStatus; stdcall; canReadTimer : function(handle: canHandle): Cardinal; stdcall; kvReadTimer : function(handle: canHandle; var time: Cardinal): kvStatus; stdcall; kvReadTimer64 : function(handle: canHandle; var time: Int64): kvStatus; stdcall; canGetNumberOfChannels : function(var channelCount: Integer): canStatus; stdcall; canGetChannelData : function(channel, item: Integer; var buffer; bufsize: size_t): canStatus; stdcall; canOpenChannel : function(channel: Integer; flags: Integer): canHandle; stdcall; canWaitForEvent : function(hnd: canHandle; timeout: Cardinal): canStatus; stdcall; canSetBusParamsC200 : function(hnd: canHandle; btr0, btr1: Byte): canStatus; stdcall; canGetVersionEx : function(itemCode: Cardinal): Cardinal; stdcall; canSetDriverMode : function(hnd: canHandle; lineMode, resNet: Integer): canStatus; stdcall; canGetDriverMode : function(hnd: canHandle; var lineMode: Integer; var resNet: Integer): canStatus; stdcall; canParamGetCount : function(): canStatus; stdcall; canParamCommitChanges : function(): canStatus; stdcall; canParamDeleteEntry : function(index: Integer): canStatus; stdcall; canParamCreateNewEntry : function(): canStatus; stdcall; canParamSwapEntries : function(index1, index2: Integer): canStatus; stdcall; canParamGetName : function(index: Integer; buffer: PAnsiChar; maxlen: Integer): canStatus; stdcall; canParamGetChannelNumber : function(index: Integer): canStatus; stdcall; canParamGetBusParams : function(index: Integer; var bitrate: Longint; var tseg1: Cardinal; var tseg2: Cardinal; var sjw: Cardinal; var noSamp: Cardinal): canStatus; stdcall; canParamSetName : function(index: Integer; buffer: PAnsiChar): canStatus; stdcall; canParamSetChannelNumber : function(index, channel: Integer): canStatus; stdcall; canParamSetBusParams : function(index: Integer; bitrate: Longint; tseq1, tseq2, sjw, noSamp: Cardinal): canStatus; stdcall; canParamFindByName : function(const name: PAnsiChar): canStatus; stdcall; canObjBufFreeAll : function(handle: canHandle): canStatus; stdcall; canObjBufAllocate : function(handle: canHandle; tp: Integer): canStatus; stdcall; canObjBufFree : function(handle: canHandle; idx: Integer): canStatus; stdcall; canObjBufWrite : function(handle: canHandle; idx, id: Integer; var Msg; dlc, flags: Cardinal): canStatus; stdcall; canObjBufSetFilter : function(handle: canHandle; idx: Integer; code, mask: Cardinal): canStatus; stdcall; canObjBufSetFlags : function(handle: canHandle; idx: Integer; flags: Cardinal): canStatus; stdcall; canObjBufEnable : function(handle: canHandle; idx: Integer): canStatus; stdcall; canObjBufDisable : function(handle: canHandle; idx: Integer): canStatus; stdcall; canObjBufSetPeriod : function(handle: canHandle; idx: Integer; period: Cardinal): canStatus; stdcall; canObjBufSetMsgCount : function(handle: canHandle; idx: Integer; count: Cardinal): canStatus; stdcall; canObjBufSendBurst : function(handle: canHandle; idx: Integer; burstLen: Cardinal): canStatus; stdcall; canProbeVersion : function(handle: canHandle; major, minor, oem_id: Integer; flags: Cardinal): Boolean; stdcall; canResetBus : function(handle: canHandle): canStatus; stdcall; canWriteWait : function(handle: canHandle; id: Longint; var Msg; dlc, flag, timeout: Cardinal): canStatus; stdcall; canSetAcceptanceFilter : function(handle: canHandle; code, mask: Cardinal; is_extended: Integer): canStatus; stdcall; canFlushReceiveQueue : function(handle: canHandle): canStatus; stdcall; canFlushTransmitQueue : function(handle: canHandle): canStatus; stdcall; canRequestChipStatus : function(handle: canHandle): canStatus; stdcall; canRequestBusStatistics : function(handle: canHandle): canStatus; stdcall; canGetBusStatistics : function(handle: canHandle; var stat: canBusStatistics; bufsiz: size_t): canStatus; stdcall; kvAnnounceIdentity : function(handle: canHandle; var buf; bufsiz: size_t): canStatus; stdcall; kvAnnounceIdentityEx : function(handle: canHandle; tp: Integer; var buf; bufsiz: size_t): canStatus; stdcall; kvSetNotifyCallback : function(handle: canHandle; callback: kvCallback_t; context: Pointer; notifyFlags: Cardinal): canStatus; stdcall; kvBeep : function(handle: canHandle; freq: Integer; duration: Cardinal): canStatus; stdcall; kvSelfTest : function(handle: canHandle; var presults: Cardinal): canStatus; stdcall; kvFlashLeds : function(handle: canHandle; action: Integer; timeout: Integer): canStatus; stdcall; canSetBitrate : function(handle: canHandle; bitrate: Integer): canStatus; stdcall; canGetHandleData : function(handle: canHandle; item: Integer; var buffer; bufsize: size_t): canStatus; stdcall; kvGetApplicationMapping : function(busType: Integer; appName: PAnsiChar; appChannel: Integer; var resultingChannel: Integer): canStatus; stdcall; kvTimeDomainCreate : function(var domain: kvTimeDomain): kvStatus; stdcall; kvTimeDomainDelete : function(domain: kvTimeDomain): kvStatus; stdcall; kvTimeDomainResetTime : function(domain: kvTimeDomain): kvStatus; stdcall; kvTimeDomainGetData : function(domain: kvTimeDomain; var data: kvTimeDomainData; bufsiz: size_t): kvStatus; stdcall; kvTimeDomainAddHandle : function(domain: kvTimeDomain; handle: canHandle): kvStatus; stdcall; kvTimeDomainRemoveHandle : function(domain: kvTimeDomain; handle: canHandle): kvStatus; stdcall; kvReadDeviceCustomerData : function(hnd: canHandle; userNumber, itemNumber: Integer; var data; bufsize: size_t): kvStatus; stdcall; kvGetSupportedInterfaceInfo: function(index: Integer; hwName: PAnsiChar; nameLen: size_t; var hwType: Integer; var hwBusType: Integer): kvStatus; stdcall; kvScriptStart : function(const hnd: canHandle; slotNo: Integer): kvStatus; stdcall; kvScriptStatus : function(const hnd: canHandle; slotNo: Integer; var status: Cardinal): kvStatus; stdcall; kvScriptStop : function(const hnd: canHandle; slotNo: Integer; mode: Integer): kvStatus; stdcall; kvScriptUnload : function(const hnd: canHandle; slotNo: Integer): kvStatus; stdcall; kvScriptSendEvent : function(const hnd: canHandle; slotNo: Integer; eventType: Integer; eventNo: Integer; data: Cardinal): kvStatus; stdcall; kvScriptEnvvarOpen : function(const hnd: canHandle; envvarName: PAnsiChar; var envvarType: Integer; var envvarSize: Integer): kvEnvHandle; stdcall; kvScriptEnvvarClose : function(const eHnd: kvEnvHandle): kvStatus; stdcall; kvScriptEnvvarSetInt : function(const eHnd: kvEnvHandle; val: Integer): kvStatus; stdcall; kvScriptEnvvarGetInt : function(const eHnd: kvEnvHandle; var val: Integer): kvStatus; stdcall; kvScriptEnvvarSetFloat : function(const eHnd: kvEnvHandle; val: Single): kvStatus; stdcall; kvScriptEnvvarGetFloat : function(const eHnd: kvEnvHandle; var val: Single): kvStatus; stdcall; kvScriptEnvvarSetData : function(const eHnd: kvEnvHandle; var buf; start_index: Integer; data_len: Integer): kvStatus; stdcall; kvScriptEnvvarGetData : function(const eHnd: kvEnvHandle; var buf; start_index: Integer; data_len: Integer): kvStatus; stdcall; kvScriptGetMaxEnvvarSize : function(hnd: canHandle; var envvarSize: Integer): kvStatus; stdcall; kvScriptLoadFileOnDevice : function(hnd: canHandle; slotNo: Integer; localFile: PAnsiChar): kvStatus; stdcall; kvScriptLoadFile : function(hnd: canHandle; slotNo: Integer; filePathOnPC: PAnsiChar): kvStatus; stdcall; kvScriptRequestText : function(hnd: canHandle; slotNo: Cardinal; request: Cardinal): kvStatus; stdcall; kvScriptGetText : function(hnd: canHandle; var slot: Integer; var time: Cardinal; var flags: Cardinal; buf: PAnsiChar; bufsize: size_t): kvStatus; stdcall; kvFileCopyToDevice : function(hnd: canHandle; hostFileName: PAnsiChar; deviceFileName: PAnsiChar): kvStatus; stdcall; kvFileCopyFromDevice : function(hnd: canHandle; deviceFileName: PAnsiChar; hostFileName: PAnsiChar): kvStatus; stdcall; kvFileDelete : function(hnd: canHandle; deviceFileName: PAnsiChar): kvStatus; stdcall; kvFileGetName : function(hnd: canHandle; fileNo: Integer; name: PAnsiChar; nameLen: Integer): kvStatus; stdcall; kvFileGetCount : function(hnd: canHandle; var count: Integer): kvStatus; stdcall; kvFileGetSystemData : function(hnd: canHandle; itemCode: Integer; var Result: Integer): kvStatus; stdcall; kvDeviceSetMode : function(hnd: canHandle; mode: Integer): kvStatus; stdcall; kvDeviceGetMode : function(hnd: canHandle; var mode: Integer): kvStatus; stdcall; kvPingRequest : function(hnd: canHandle; var requestTime: Cardinal): kvStatus; stdcall; kvPingGetLatest : function(hnd: canHandle; var requestTime: Cardinal; var pingTime: Cardinal): kvStatus; stdcall; //I/O Pin Handling kvIoGetNumberOfPins : function(hnd: canHandle; var pinCount: Integer): kvStatus; stdcall; kvIoConfirmConfig : function(hnd: canHandle): kvStatus; stdcall; kvIoPinGetInfo : function(hnd: canHandle; pin: Integer; item: Integer; var buffer; bufsize: size_t): kvStatus; stdcall; kvIoPinSetInfo : function(hnd: canHandle; pin: Integer; item: Integer; var buffer; bufsize: size_t): kvStatus; stdcall; kvIoPinSetDigital : function(hnd: canHandle; pin: Integer; value: cardinal): kvStatus; stdcall; kvIoPinGetDigital : function(hnd: canHandle; pin: Integer; var value: cardinal): kvStatus; stdcall; kvIoPinSetRelay : function(hnd: canHandle; pin: integer; value: cardinal): kvStatus; stdcall; kvIoPinSetAnalog : function(hnd: canHandle; pin: Integer; value: single): kvStatus; stdcall; kvIoPinGetAnalog : function(hnd: canHandle; pin: Integer; var value: single): kvStatus; stdcall; kvIoPinGetOutputAnalog : function(hnd: canHandle; pin: Integer; var value: single): kvStatus; stdcall; kvIoPinGetOutputDigital : function(hnd: canHandle; pin: Integer; var value: cardinal): kvStatus; stdcall; kvIoPinGetOutputRelay : function(hnd: canHandle; pin: Integer; var value: cardinal): kvStatus; stdcall; {$ENDIF} const kvLED_ACTION_ALL_LEDS_ON = 0; kvLED_ACTION_ALL_LEDS_OFF = 1; kvLED_ACTION_LED_0_ON = 2; kvLED_ACTION_LED_0_OFF = 3; kvLED_ACTION_LED_1_ON = 4; kvLED_ACTION_LED_1_OFF = 5; kvLED_ACTION_LED_2_ON = 6; kvLED_ACTION_LED_2_OFF = 7; kvLED_ACTION_LED_3_ON = 8; kvLED_ACTION_LED_3_OFF = 9; canCHANNELDATA_CHANNEL_CAP = 1; canCHANNELDATA_TRANS_CAP = 2; canCHANNELDATA_CHANNEL_FLAGS = 3; // available, etc canCHANNELDATA_CARD_TYPE = 4; // canHWTYPE_xxx canCHANNELDATA_CARD_NUMBER = 5; // Number in machine, 0,1,... canCHANNELDATA_CHAN_NO_ON_CARD = 6; canCHANNELDATA_CARD_SERIAL_NO = 7; canCHANNELDATA_TRANS_SERIAL_NO = 8; canCHANNELDATA_CARD_FIRMWARE_REV = 9; canCHANNELDATA_CARD_HARDWARE_REV = 10; canCHANNELDATA_CARD_UPC_NO = 11; canCHANNELDATA_TRANS_UPC_NO = 12; canCHANNELDATA_CHANNEL_NAME = 13; canCHANNELDATA_DLL_FILE_VERSION = 14; canCHANNELDATA_DLL_PRODUCT_VERSION = 15; canCHANNELDATA_DLL_FILETYPE = 16; canCHANNELDATA_TRANS_TYPE = 17; canCHANNELDATA_DEVICE_PHYSICAL_POSITION = 18; canCHANNELDATA_UI_NUMBER = 19; canCHANNELDATA_TIMESYNC_ENABLED = 20; canCHANNELDATA_DRIVER_FILE_VERSION = 21; canCHANNELDATA_DRIVER_PRODUCT_VERSION = 22; canCHANNELDATA_MFGNAME_UNICODE = 23; canCHANNELDATA_MFGNAME_ASCII = 24; canCHANNELDATA_DEVDESCR_UNICODE = 25; canCHANNELDATA_DEVDESCR_ASCII = 26; canCHANNELDATA_DRIVER_NAME = 27; canCHANNELDATA_CHANNEL_QUALITY = 28; canCHANNELDATA_ROUNDTRIP_TIME = 29; canCHANNELDATA_BUS_TYPE = 30; canCHANNELDATA_DEVNAME_ASCII = 31; canCHANNELDATA_TIME_SINCE_LAST_SEEN = 32; canCHANNELDATA_REMOTE_OPERATIONAL_MODE = 33; canCHANNELDATA_REMOTE_PROFILE_NAME = 34; canCHANNELDATA_REMOTE_HOST_NAME = 35; canCHANNELDATA_REMOTE_MAC = 36; canCHANNELDATA_MAX_BITRATE = 37; canCHANNELDATA_CHANNEL_CAP_MASK = 38; canCHANNELDATA_CUST_CHANNEL_NAME = 39; canCHANNELDATA_IS_REMOTE = 40; canCHANNELDATA_REMOTE_TYPE = 41; canCHANNELDATA_LOGGER_TYPE = 42; canCHANNELDATA_HW_STATUS = 43; canCHANNELDATA_FEATURE_EAN = 44; // channelFlags in canChannelData canCHANNEL_IS_EXCLUSIVE = $0001; canCHANNEL_IS_OPEN = $0002; canCHANNEL_IS_CANFD = $0004; canCHANNEL_IS_LIN = $0010; canCHANNEL_IS_LIN_MASTER = $0020; canCHANNEL_IS_LIN_SLAVE = $0040; // For canOpen(), canOpenChannel() canWANT_EXCLUSIVE = $08; // Don't allow sharing canWANT_EXTENDED = $10; // Extended CAN is required canWANT_VIRTUAL = $0020; canOPEN_EXCLUSIVE = canWANT_EXCLUSIVE; canOPEN_REQUIRE_EXTENDED = canWANT_EXTENDED; canOPEN_ACCEPT_VIRTUAL = canWANT_VIRTUAL; canOPEN_OVERRIDE_EXCLUSIVE = $0040; canOPEN_REQUIRE_INIT_ACCESS = $0080; canOPEN_NO_INIT_ACCESS = $0100; canOPEN_ACCEPT_LARGE_DLC = $0200; canOPEN_CAN_FD = $0400; canOPEN_CAN_FD_NONISO = $0800; canOPEN_LIN = $1000; // Hardware types. canHWTYPE_NONE = 0; // Unknown canHWTYPE_VIRTUAL = 1; // Virtual channel. canHWTYPE_LAPCAN = 2; // LAPcan family canHWTYPE_CANPARI = 3; // CANpari (not supported.) canHWTYPE_PCCAN = 8; // PCcan family canHWTYPE_PCICAN = 9; // PCIcan family canHWTYPE_USBCAN = 11; // USBcan family canHWTYPE_PCICAN_II = 40; canHWTYPE_USBCAN_II = 42; canHWTYPE_SIMULATED = 44; canHWTYPE_ACQUISITOR = 46; canHWTYPE_LEAF = 48; canHWTYPE_PC104_PLUS = 50; // PC104+ canHWTYPE_PCICANX_II = 52; // PCIcanx II canHWTYPE_MEMORATOR_II = 54; // Memorator Professional canHWTYPE_MEMORATOR_PRO = 54; // Memorator Professional canHWTYPE_USBCAN_PRO = 56; // USBcan Professional canHWTYPE_IRIS = 58; // Obsolete name, use canHWTYPE_BLACKBIRD instead canHWTYPE_BLACKBIRD = 58; canHWTYPE_MEMORATOR_LIGHT = 60; // Kvaser Memorator Light canHWTYPE_MINIHYDRA = 62; // Obsolete name, use canHWTYPE_EAGLE instead canHWTYPE_EAGLE = 62; // Kvaser Eagle family canHWTYPE_BAGEL = 64; // Obsolete name, use canHWTYPE_BLACKBIRD_V2 instead canHWTYPE_BLACKBIRD_V2 = 64; // Kvaser BlackBird v2 canHWTYPE_MINIPCIE = 66; // "Mini PCI Express" for now, subject to change. canHWTYPE_USBCAN_KLINE = 68; // USBcan Pro HS/K-Line canHWTYPE_ETHERCAN = 70; // Kvaser Ethercan canHWTYPE_USBCAN_LIGHT = 72; // Kvaser USBcan Light canHWTYPE_USBCAN_PRO2 = 74; // Kvaser USBcan Pro 5xHS canHWTYPE_PCIE_V2 = 76; // PCIe for now canHWTYPE_MEMORATOR_PRO2 = 78; // Kvaser Memorator Pro 5xHS canHWTYPE_LEAF2 = 80; // Kvaser Leaf Pro HS v2 and variants canHWTYPE_MEMORATOR_V2 = 82; // Kvaser Memorator (2nd generation) canHWTYPE_CANLINHYBRID = 84; // Kvaser Hybrid CAN/LIN canHWTYPE_DINRAIL = 86; // Kvaser DIN Rail SE400S and variants canTRANSCEIVER_TYPE_UNKNOWN = 0; canTRANSCEIVER_TYPE_251 = 1; canTRANSCEIVER_TYPE_252 = 2; canTRANSCEIVER_TYPE_DNOPTO = 3; canTRANSCEIVER_TYPE_W210 = 4; canTRANSCEIVER_TYPE_SWC_PROTO = 5; canTRANSCEIVER_TYPE_SWC = 6; canTRANSCEIVER_TYPE_EVA = 7; canTRANSCEIVER_TYPE_FIBER = 8; canTRANSCEIVER_TYPE_K251 = 9; canTRANSCEIVER_TYPE_K = 10; canTRANSCEIVER_TYPE_1054_OPTO = 11; canTRANSCEIVER_TYPE_SWC_OPTO = 12; canTRANSCEIVER_TYPE_TT = 13; canTRANSCEIVER_TYPE_1050 = 14; canTRANSCEIVER_TYPE_1050_OPTO = 15; canTRANSCEIVER_TYPE_1041 = 16; canTRANSCEIVER_TYPE_1041_OPTO = 17; canTRANSCEIVER_TYPE_RS485 = 18; canTRANSCEIVER_TYPE_LIN = 19; canTRANSCEIVER_TYPE_KONE = 20; canTRANSCEIVER_TYPE_CANFD = 22; canTRANSCEIVER_TYPE_CANFD_LIN = 24; canTRANSCEIVER_TYPE_LINX_LIN = 64; canTRANSCEIVER_TYPE_LINX_J1708 = 66; canTRANSCEIVER_TYPE_LINX_K = 68; canTRANSCEIVER_TYPE_LINX_SWC = 70; canTRANSCEIVER_TYPE_LINX_LS = 72; // Channel capabilities. canCHANNEL_CAP_EXTENDED_CAN = $00000001; // Can use extended identifiers canCHANNEL_CAP_BUS_STATISTICS = $00000002; // Can report busload etc canCHANNEL_CAP_ERROR_COUNTERS = $00000004; // Can return error counters canCHANNEL_CAP_CAN_DIAGNOSTICS = $00000008; // Can report CAN diagnostics canCHANNEL_CAP_GENERATE_ERROR = $00000010; // Can send error frames canCHANNEL_CAP_GENERATE_OVERLOAD = $00000020; // Can send CAN overload frame canCHANNEL_CAP_TXREQUEST = $00000040; // Can report when a CAN messsage transmission is initiated canCHANNEL_CAP_TXACKNOWLEDGE = $00000080; // Can report when a CAN messages has been transmitted canCHANNEL_CAP_VIRTUAL = $00010000; // Virtual CAN channel canCHANNEL_CAP_SIMULATED = $00020000; // Simulated CAN channel canCHANNEL_CAP_REMOTE = $00040000; // Remote CAN channel (e.g. BlackBird). canCHANNEL_CAP_CAN_FD = $00080000; // CAN-FD ISO compliant channel canCHANNEL_CAP_CAN_FD_NONISO = $00100000; // CAN-FD NON-ISO compliant channel canCHANNEL_CAP_SILENT_MODE = $00200000; // Channel supports Silent mode canCHANNEL_CAP_SINGLE_SHOT = $00400000; // Channel supports Single Shot messages canCHANNEL_CAP_LOGGER = $00800000; // Channel has logger capabilities. canCHANNEL_CAP_REMOTE_ACCESS = $01000000; // Channel has remote capabilities canCHANNEL_CAP_SCRIPT = $02000000; // Channel has script capabilities. canCHANNEL_CAP_LIN_FLEX = $04000000; // Channel has script capabilities. // Driver (transceiver) capabilities canDRIVER_CAP_HIGHSPEED = $00000001; // I/O Info kvIO_INFO_GET_MODULE_TYPE = 1; kvIO_INFO_GET_DIRECTION = 2; kvIO_INFO_GET_PIN_TYPE = 4; kvIO_INFO_GET_NUMBER_OF_BITS = 5; kvIO_INFO_GET_RANGE_MIN = 6; kvIO_INFO_GET_RANGE_MAX = 7; kvIO_INFO_GET_DI_LOW_HIGH_FILTER = 8; kvIO_INFO_SET_DI_LOW_HIGH_FILTER = 8; kvIO_INFO_GET_DI_HIGH_LOW_FILTER = 9; kvIO_INFO_SET_DI_HIGH_LOW_FILTER = 9; kvIO_INFO_GET_AI_LP_FILTER_ORDER = 10; kvIO_INFO_SET_AI_LP_FILTER_ORDER = 10; kvIO_INFO_GET_AI_HYSTERESIS = 11; kvIO_INFO_SET_AI_HYSTERESIS = 11; kvIO_INFO_GET_MODULE_NUMBER = 14; // I/O Module Type kvIO_MODULE_TYPE_DIGITAL = 1; kvIO_MODULE_TYPE_ANALOG = 2; kvIO_MODULE_TYPE_RELAY = 3; // I/O Pin Type kvIO_PIN_TYPE_DIGITAL = 1; kvIO_PIN_TYPE_ANALOG = 2; kvIO_PIN_TYPE_RELAY = 3; // I/O Pin Direction kvIO_PIN_DIRECTION_IN = 4; kvIO_PIN_DIRECTION_OUT = 8; implementation uses SysUtils; var hDLL : THandle; realCanLocateHardware : function: canStatus; realCanInitializeLibrary: procedure; realCanUnloadLibrary : function: Integer; DLLName : array [0 .. 50] of char = 'CANLIB32.DLL'; {$IF Defined(WIN32) or Defined(WIN64)} Constructor TCanInterface.create(canChannel: Integer)overload; var cname: packed array [0 .. 256] of AnsiChar; begin channel := canChannel; canGetChannelData(channel, canCHANNELDATA_CHANNEL_NAME, cname, 256); // OutputDebugString(PCHAR(inttostr(status))); name := Format('%s', [cname]); // Inherited Create; end; procedure LoadDLL; forward; procedure UnloadDLL; forward; procedure canInitializeLibrary; begin if hDLL <> 0 then Exit; LoadDLL; if hDLL <> 0 then begin realCanInitializeLibrary; end; end; function canLocateHardware: canStatus; begin if hDLL <> 0 then begin Result := canOK; Exit; end; LoadDLL; if hDLL = 0 then begin Result := canERR_DYNALOAD; end else begin Result := realCanLocateHardware; end; end; function canUnloadLibrary: Integer; begin if hDLL = 0 then begin Result := canOK; Exit; end; if Assigned(realCanUnloadLibrary) then realCanUnloadLibrary; UnloadDLL; Result := canOK; end; function GPA(const proc: string): Pointer; var s: array [0 .. 300] of char; begin StrPCopy(s, proc); Result := GetProcAddress(hDLL, s); if Result = nil then begin raise Exception.CreateFmt('CANLIB: function %s not found.', [proc]); end; end; procedure SetDllName(s: string); begin StrPCopy(DLLName, s); end; procedure LoadDLL; var err: Integer; begin hDLL := LoadLibrary(DLLName); err := GetLastError; if hDLL = 0 then begin raise Exception.create(Format('Can not load the CAN driver - is it correctly installed? ' + '(Error 0x%8.8x)', [err])); Exit; end; @realCanLocateHardware := GPA('canLocateHardware'); @realCanInitializeLibrary := GPA('canInitializeLibrary'); @canOpen := GPA('canOpen'); @canClose := GPA('canClose'); @canBusOn := GPA('canBusOn'); @canBusOff := GPA('canBusOff'); @canSetBusParams := GPA('canSetBusParams'); @canGetBusParams := GPA('canGetBusParams'); @canSetBusParamsFd := GPA('canSetBusParamsFd'); @canGetBusParamsFd := GPA('canGetBusParamsFd'); @canSetBusOutputControl := GPA('canSetBusOutputControl'); @canGetBusOutputControl := GPA('canGetBusOutputControl'); @canAccept := GPA('canAccept'); @canReadStatus := GPA('canReadStatus'); @canReadErrorCounters := GPA('canReadErrorCounters'); @canWrite := GPA('canWrite'); @canWriteSync := GPA('canWriteSync'); @canRead := GPA('canRead'); @canReadWait := GPA('canReadWait'); @canReadSpecific := GPA('canReadSpecific'); @canReadSync := GPA('canReadSync'); @canReadSyncSpecific := GPA('canReadSyncSpecific'); @canReadSpecificSkip := GPA('canReadSpecificSkip'); @canInstallAction := nil; @canUninstallAction := nil; @canInstallOwnBuffer := nil; @canUninstallOwnBuffer := nil; @canSetNotify := GPA('canSetNotify'); @canTranslateBaud := GPA('canTranslateBaud'); @canGetErrorText := GPA('canGetErrorText'); @canGetVersion := GPA('canGetVersion'); @canIoCtl := GPA('canIoCtl'); @canReadTimer := GPA('canReadTimer'); @canGetNumberOfChannels := GPA('canGetNumberOfChannels'); @canGetChannelData := GPA('canGetChannelData'); @canOpenChannel := GPA('canOpenChannel'); @canWaitForEvent := GPA('canWaitForEvent'); @canSetBusParamsC200 := GPA('canSetBusParamsC200'); @canGetVersionEx := GPA('canGetVersionEx'); @canSetDriverMode := GPA('canSetDriverMode'); @canGetDriverMode := GPA('canGetDriverMode'); @canParamGetCount := GPA('canParamGetCount'); @canParamCommitChanges := GPA('canParamCommitChanges'); @canParamDeleteEntry := GPA('canParamDeleteEntry'); @canParamCreateNewEntry := GPA('canParamCreateNewEntry'); @canParamSwapEntries := GPA('canParamSwapEntries'); @canParamGetName := GPA('canParamGetName'); @canParamGetChannelNumber := GPA('canParamGetChannelNumber'); @canParamGetBusParams := GPA('canGetBusParams'); @canParamSetName := GPA('canParamSetName'); @canParamSetChannelNumber := GPA('canParamSetChannelNumber'); @canParamSetBusParams := GPA('canParamSetBusParams'); @canParamFindByName := GPA('canParamFindByName'); @canObjBufFreeAll := GPA('canObjBufFreeAll'); @canObjBufAllocate := GPA('canObjBufAllocate'); @canObjBufFree := GPA('canObjBufFree'); @canObjBufWrite := GPA('canObjBufWrite'); @canObjBufSetFilter := GPA('canObjBufSetFilter'); @canObjBufSetFlags := GPA('canObjBufSetFilter'); @canObjBufEnable := GPA('canObjBufEnable'); @canObjBufDisable := GPA('canObjBufDisable'); @canProbeVersion := GPA('canProbeVersion'); @canResetBus := GPA('canResetBus'); @canWriteWait := GPA('canWriteWait'); @canSetAcceptanceFilter := GPA('canSetAcceptanceFilter'); @canRequestChipStatus := GPA('canRequestChipStatus'); @canRequestBusStatistics := GPA('canRequestBusStatistics'); @canGetBusStatistics := GPA('canGetBusStatistics'); @kvAnnounceIdentity := GPA('kvAnnounceIdentity'); @kvSetNotifyCallback := GPA('kvSetNotifyCallback'); @kvBeep := GPA('kvBeep'); @kvSelfTest := GPA('kvSelfTest'); @kvFlashLeds := GPA('kvFlashLeds'); @canSetBitrate := GPA('canSetBitrate'); @canGetHandleData := GPA('canGetHandleData'); @kvTimeDomainCreate := GPA('kvTimeDomainCreate'); @kvTimeDomainDelete := GPA('kvTimeDomainDelete'); @kvTimeDomainResetTime := GPA('kvTimeDomainResetTime'); @kvTimeDomainGetData := GPA('kvTimeDomainGetData'); @kvTimeDomainAddHandle := GPA('kvTimeDomainAddHandle'); @kvTimeDomainRemoveHandle := GPA('kvTimeDomainRemoveHandle'); @kvReadDeviceCustomerData := GPA('kvReadDeviceCustomerData'); @kvReadTimer := GPA('kvReadTimer'); @kvReadTimer64 := GPA('kvReadTimer64'); @canObjBufSetPeriod := GPA('canObjBufSetPeriod'); @canObjBufSetMsgCount := GPA('canObjBufSetMsgCount'); @canObjBufSendBurst := GPA('canObjBufSendBurst'); @canFlushReceiveQueue := GPA('canFlushReceiveQueue'); @canFlushTransmitQueue := GPA('canFlushTransmitQueue'); @kvAnnounceIdentityEx := GPA('kvAnnounceIdentityEx'); @kvGetApplicationMapping := GPA('kvGetApplicationMapping'); @kvGetSupportedInterfaceInfo := GPA('kvGetSupportedInterfaceInfo'); @kvScriptStart := GPA('kvScriptStart'); @kvScriptStatus := GPA('kvScriptStatus'); @kvScriptStop := GPA('kvScriptStop'); @kvScriptUnload := GPA('kvScriptUnload'); @kvScriptSendEvent := GPA('kvScriptSendEvent'); @kvScriptEnvvarOpen := GPA('kvScriptEnvvarOpen'); @kvScriptEnvvarClose := GPA('kvScriptEnvvarClose'); @kvScriptEnvvarSetInt := GPA('kvScriptEnvvarSetInt'); @kvScriptEnvvarGetInt := GPA('kvScriptEnvvarGetInt'); @kvScriptEnvvarSetFloat := GPA('kvScriptEnvvarSetFloat'); @kvScriptEnvvarGetFloat := GPA('kvScriptEnvvarGetFloat'); @kvScriptEnvvarSetData := GPA('kvScriptEnvvarSetData'); @kvScriptEnvvarGetData := GPA('kvScriptEnvvarGetData'); @kvScriptGetMaxEnvvarSize := GPA('kvScriptGetMaxEnvvarSize'); @kvScriptLoadFileOnDevice := GPA('kvScriptLoadFileOnDevice'); @kvScriptLoadFile := GPA('kvScriptLoadFile'); @kvScriptRequestText := GPA('kvScriptRequestText'); @kvScriptGetText := GPA('kvScriptGetText'); @kvFileCopyToDevice := GPA('kvFileCopyToDevice'); @kvFileCopyFromDevice := GPA('kvFileCopyFromDevice'); @kvFileDelete := GPA('kvFileDelete'); @kvFileGetName := GPA('kvFileGetName'); @kvFileGetCount := GPA('kvFileGetCount'); @kvFileGetSystemData := GPA('kvFileGetSystemData'); @kvDeviceSetMode := GPA('kvDeviceSetMode'); @kvDeviceGetMode := GPA('kvDeviceGetMode'); @kvPingRequest := GPA('kvPingRequest'); @kvPingGetLatest := GPA('kvPingGetLatest'); @realCanUnloadLibrary := GPA('canUnloadLibrary'); @kvIoGetNumberOfPins := GPA('kvIoGetNumberOfPins'); @kvIoConfirmConfig := GPA('kvIoConfirmConfig'); @kvIoPinGetInfo := GPA('kvIoPinGetInfo'); @kvIoPinSetInfo := GPA('kvIoPinSetInfo'); @kvIoPinSetDigital := GPA('kvIoPinSetDigital'); @kvIoPinGetDigital := GPA('kvIoPinGetDigital'); @kvIoPinSetRelay := GPA('kvIoPinSetRelay'); @kvIoPinSetAnalog := GPA('kvIoPinSetAnalog'); @kvIoPinGetAnalog := GPA('kvIoPinGetAnalog'); @kvIoPinGetOutputDigital := GPA('kvIoPinGetOutputDigital'); @kvIoPinGetOutputRelay := GPA('kvIoPinGetOutputRelay'); @kvIoPinGetOutputAnalog := GPA('kvIoPinGetOutputAnalog'); end; procedure UnloadDLL; begin if not Assigned(realCanUnloadLibrary) then Exit; realCanUnloadLibrary; FreeLibrary(hDLL); hDLL := 0; end; {$ENDIF} end.
// *************************************************************************** // // cfs.GCharts.uniGUI: uniGUI Google Charts Frame // cfsCharts is a Delphi library of components to generate Charts in uniGUI Framework using the Google Charts API // // Copyright (c) 2021 Josep Pagès // // https://github.com/JosepPages7/Delphi-GCharts // // // *************************************************************************** // // 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 cfs.GCharts.uniGUI; interface uses System.Classes, System.SysUtils, Generics.Collections, Data.DB, uniGUITypes, uniGUIClasses, uniGUIInterfaces, cfs.GCharts; type TuniGChartsFrame = class; TuniGChartsSelectEvent = procedure(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string) of object; TuniGChartsBeforeDocumentPost = procedure(Sender: TComponent; var HTMLDocument: string) of object; TcfsCustomURLFrame = class(TUniCustomContainerPanel) strict private FLoaded: Boolean; FHTMLDocument: string; FOnLoaded : TNotifyEvent; FBeforeDocumentPost: TuniGChartsBeforeDocumentPost; procedure H_OnLoaded(This: TJSObject; EventName: string; Params: TUniStrings); procedure SetHTMLDocument(const Value: string); procedure PostHTMLDocument; protected procedure CreateFrame; virtual; procedure SetOnLoaded(Value: TNotifyEvent); procedure LoadCompleted; override; function VCLControlClassName: string; override; procedure ConfigJSClasses(ALoading: Boolean); override; procedure WebCreate; override; property OnFrameLoaded: TNotifyEvent read FOnLoaded write SetOnLoaded; property BeforeDocumentPost: TuniGChartsBeforeDocumentPost read FBeforeDocumentPost write FBeforeDocumentPost; property HTMLDocument: string write SetHTMLDocument; public constructor Create(AOwner: TComponent); override; end; TuniGChartsFrame = class(TcfsCustomURLFrame) private FScriptCode: TStringBuilder; FListIdCharts: TList<string>; FCSSCode: string; FHTMLCode: string; FOnSelect: TuniGChartsSelectEvent; FAutoResize: Boolean; procedure CheckDocumentInit; function GetHTMLDocument: string; protected procedure DOHandleEvent(EventName: string; Params: TUniStrings); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetHTMLDocument(const Text: string); procedure DocumentInit; procedure DocumentSetCSS(const CSSText: string); procedure DocumentSetBody(const HTMLText: string); procedure DocumentAddScript(const Text: string); procedure DocumentGenerate(const ChartId: string; ChartProducer: TcfsGChartProducer); overload; procedure DocumentGenerate(const ChartId: string; ChartProducer: IcfsGChartProducer); overload; procedure DocumentPost; published property AlignmentControl; property ParentAlignmentControl; property Align; property Anchors; property LayoutConfig; property ScreenMask; property OnAjaxEvent; property TabOrder; property TabStop; property OnFrameLoaded; property BeforeDocumentPost; property AutoResize: Boolean read FAutoResize write FAutoResize default False; property OnSelect: TuniGChartsSelectEvent read FOnSelect write FOnSelect; end; const JS_RESOURCE_GCHARTS_LOADER : string = '<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>'; JS_RESOURCE_JQUERY: string = '<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>'; procedure register; implementation uses UniGUIJSUtils; procedure register; begin RegisterComponents('uniGUI CFS', [TuniGChartsFrame]); end; { TcfsCustomURLFrame } function TcfsCustomURLFrame.VCLControlClassName: string; begin Result:='TVCLURLFrame'; // to be defined end; procedure TcfsCustomURLFrame.ConfigJSClasses(ALoading: Boolean); begin JSObjects.DefaultJSClassName:='Ext.panel.iframe'; end; constructor TcfsCustomURLFrame.Create(AOwner: TComponent); begin inherited; Width := 320; Height := 240; end; procedure TcfsCustomURLFrame.CreateFrame; var FName : string; begin FName := Name+'_'+JSName; JSConfig('ifName', ['name_'+FName]); JSConfig('items', [JSArray('{xtype:"component",'+ 'width:"100%",'+ 'height:"100%",'+ 'autoEl: {tag:"iframe",'+ 'onload:"iframe_load('''+JSId+''')",'+ 'name:"name_'+FName+'",'+ 'title:"title_'+FName+'",'+ 'src:"about:blank",frameborder:"0"}}') ] ); JSCall('initIFrame'); end; procedure TcfsCustomURLFrame.PostHTMLDocument; begin if Assigned(FBeforeDocumentPost) then FBeforeDocumentPost(Self, FHTMLDocument); if FHTMLDocument <>'' then JSCall('setValue', [FHTMLDocument]); FHTMLDocument := ''; // Free Memory; end; procedure TcfsCustomURLFrame.LoadCompleted; begin inherited; CreateFrame; FLoaded := True; if FHTMLDocument <> '' then PostHTMLDocument; end; procedure TcfsCustomURLFrame.WebCreate; begin inherited; BorderStyle := ubsNone; end; procedure TcfsCustomURLFrame.H_OnLoaded(This: TJSObject; EventName: string; Params: TUniStrings); begin if Assigned(FOnLoaded) then FOnLoaded(Self); end; procedure TcfsCustomURLFrame.SetHTMLDocument(const Value: string); begin FHTMLDocument := Value; if FLoaded then PostHTMLDocument; end; procedure TcfsCustomURLFrame.SetOnLoaded(Value: TNotifyEvent); begin FOnLoaded:=Value; if WebMode then begin if Assigned(FOnLoaded) then JSAddEvent('frameload', ['This', '%0.nm', 'Frame', '%1.nm'], H_OnLoaded) else JSRemoveEvent('frameload', H_OnLoaded); end; end; { TuniHTMLFrameGCharts } constructor TuniGChartsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); if Name = '' then Name := 'cfsChart' + Self.JSName; // Important assign a default name! FAutoResize := False; end; destructor TuniGChartsFrame.Destroy; begin if Assigned(FScriptCode) then FreeAndNil(FScriptCode); FreeAndNil(FListIdCharts); inherited; end; procedure TuniGChartsFrame.DOHandleEvent(EventName: string; Params: TUniStrings); begin inherited; if Assigned(FOnSelect) then begin if EventName = 'chartSelect' then FOnSelect(Self, Params.Values['chartId'], Params.Values['itemRow'], Params.Values['itemColumn'], Params.Values['itemValue'], Params.Values['itemCategory']); end; end; procedure TuniGChartsFrame.CheckDocumentInit; begin if not Assigned(FScriptCode) then raise Exception.Create(ClassName + ': Please call DocumentInit before to start'); end; procedure TuniGChartsFrame.DocumentInit; begin if Assigned(FScriptCode) then FreeAndNil(FScriptCode); FScriptCode := TStringBuilder.Create; FHTMLCode := ''; FCSSCode := ''; FListIdCharts := TList<string>.Create; end; procedure TuniGChartsFrame.DocumentPost; var N: string; begin CheckDocumentInit; if FAutoResize and (FListIdCharts.Count > 0) then begin FScriptCode.Append('$(window).resize(function(){'); FScriptCode.Append('if(this.resizeTO) clearTimeout(this.resizeTO);'); FScriptCode.Append('this.resizeTO=setTimeout(function(){'); FScriptCode.Append('$(this).trigger(''resizeEnd'');'); FScriptCode.Append('},500);'); FScriptCode.Append('});'); FScriptCode.Append('$(window).on(''resizeEnd'',function() {'); for N in FListIdCharts do FScriptCode.Append('if (typeof ' + TcfsGChartProducer.PREFIX_DRAW_CHART_FUNCTION_NAME + N + ' === "function") {' + TcfsGChartProducer.PREFIX_DRAW_CHART_FUNCTION_NAME + N + '();}'); FScriptCode.Append('});'); end; if Assigned(FScriptCode) or (FHTMLCode <> '') then HTMLDocument := GetHTMLDocument; end; function TuniGChartsFrame.GetHTMLDocument: string; function GetCSSCode: string; begin Result := FCSSCode; //if Result = '' then //Result := '<style type="text/css">body{margin: 0;padding: 0}</style>'; // remove Margins end; var H: string; const DESACTIVATE_RIGHT_BUTTON = 'document.addEventListener("contextmenu", event => event.preventDefault());'; begin if Assigned(FScriptCode) then begin if FScriptCode.Length <> 0 then begin H := JS_RESOURCE_GCHARTS_LOADER; if AutoResize then H := H + JS_RESOURCE_JQUERY; Result := H + '<script type="text/javascript">' + DESACTIVATE_RIGHT_BUTTON + FScriptCode.ToString + '</script>' + GetCSSCode + FHTMLCode; end else Result := GetCSSCode + FHTMLCode; FreeAndNil(FScriptCode); FreeAndNil(FListIdCharts); end else begin Result := GetCSSCode + FHTMLCode; end; FHTMLCode := ''; FCSSCode := ''; end; procedure TuniGChartsFrame.SetHTMLDocument(const Text: string); begin HTMLDocument := Text; FreeAndNil(FScriptCode); FreeAndNil(FListIdCharts); end; procedure TuniGChartsFrame.DocumentSetBody(const HTMLText: string); begin CheckDocumentInit; if Copy(HTMLText.TrimLeft, 1, 5).ToUpper <> '<BODY' then FHTMLCode := '<body style="padding:0;background-color:#ffffff;">' + HTMLText + '</body>' else FHTMLCode := HTMLText; end; procedure TuniGChartsFrame.DocumentSetCSS(const CSSText: string); begin CheckDocumentInit; if Copy(FHTMLCode.TrimLeft, 1, 7).ToUpper <> '<STYLE>' then FCSSCode := '<style type="text/css">' + CSSText + '</style>' else FCSSCode := CSSText; end; procedure TuniGChartsFrame.DocumentAddScript(const Text: string); begin CheckDocumentInit; FScriptCode.Append(Text); end; procedure TuniGChartsFrame.DocumentGenerate(const ChartId: string; ChartProducer: IcfsGChartProducer); begin DocumentGenerate(ChartId, ChartProducer as TcfsGChartProducer); end; procedure TuniGChartsFrame.DocumentGenerate(const ChartId: string; ChartProducer: TcfsGChartProducer); var Id: string; begin CheckDocumentInit; Id := ChartId.Trim; if not IsValidIdent(Id) then raise Exception.Create(ClassName + ': Invalid Chart Id'); if ChartProducer = nil then raise Exception.Create(ClassName + ': ChartProducer is nil'); FListIdCharts.Add(Id); if Assigned(FOnSelect) then FScriptCode.Append(ChartProducer.GenerateJSCode(Id, True, 'parent.ajaxRequest', 'parent.' + Self.JSName)) else FScriptCode.Append(ChartProducer.GenerateJSCode(Id)); end; end.
{*******************************************************} { } { Tachyon Unit } { Vector Raster Geographic Information Synthesis } { VOICE .. Tracer } { GRIP ICE .. Tongs } { Digital Terrain Mapping } { Image Locatable Holographics } { SOS MAP } { Surreal Object Synthesis Multimedia Analysis Product } { Fractal3D Life MOW } { Copyright (c) 1995,2006 Ivan Lee Herring } { } {*******************************************************} unit fuMathF; interface uses Windows, Messages, SysUtils, Dialogs, Forms, Graphics, Classes, Math; procedure Fra_Mtns(Fune, D: Extended; Intensity: Integer); procedure FractalGrid(Fun, D : Extended); procedure FoldedGlobe( Krypton : Integer); procedure DupliGlobe(Krypton : Integer); procedure Craters(phingphactor:Double; DeptH, Intensity : Integer); procedure Waves( DeptH, Intensity : Integer); procedure Rippled(RadiusG, DeptH, Intensity : Integer); procedure Splattered(RadiusG, DeptH, Intensity : Integer); procedure DLA(Intensity: Integer); procedure DLAC(Intensity: Integer); procedure DLACentroid (Intensity: Integer); {(Freq,F_Dim: Extended;Points,} procedure B_3D_Map(N, L, VA, HA: Integer); procedure FallingColumn; procedure RotatingCube; procedure SinShadow(Plot_Angle, M_x, sign: Integer; View_Angle, Illum_Angle: Extended); procedure CoSinShadow(Plot_Angle, M_x, sign: Integer; View_Angle, Illum_Angle: Extended); implementation uses fUGlobal, fMain, fGMath,fXYZ3D; const radtheta = 1 {degrees} * 3.1415926535 {radians} / 180 {per degrees}; {sin and cos on computers are done in radians.} type tpointr = record {Just a record to hold 3d points} x, y, z: real; end; var box: array[0..7] of tpointr; {The box we will manipulate} const xSize = 512; {90 degrees} ySize = 256; {60 degrees} angleMask = xSize * 4 - 1; {xSize must be power of 2 or and's won't work} mapSize = 256; var sinTab: array of Integer; {sinTab:array[0..angleMask]of integer;} {sin(xyAngle)*$7FFF} tanTab: array of Integer; { array[0..ySize-1]of integer;} {tan(zAngle)*$7FFF} map: array of array of byte; { array[0..mapSize-1,0..mapSize-1]of byte;} type fixed = record case boolean of false: (l: longint); true: (f: word; i: integer); end; (*************************************************************) (*************************************************************) procedure Fra_Mtns(Fune, D: Extended; Intensity: Integer); var TempColor: TColor; MtnRowY, MaxZDo, MaxXDo, ColXF, RowYF,TempMan, maxcolx, maxrowy, N, I, XCount, ZCount, C, Y_Height: Integer; MtnZ, View_Angle, Illum_Angle, X, Z, R, Y, H, HS: Extended; iss, s, ss: string; F_File: file of Smallint; { Integer;} F, A, PH, TH, CS, SN: array[0..16] of Extended; {ColXF} HM: array[0..4096] of Extended; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin {if (iMadeMountains < 3) then } begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; MtnRowY := FileSizeY- 1; for Zcount := 0 to MtnRowY do begin Mainform.ProgressBar1.Position := Round((Zcount / MtnRowY) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Zcount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; Write(F_File, TempMan); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); maxrowy := (FYImageY - 1); case Intensity of 0: begin MtnRowY := 47; MtnZ := 10.0; end; 1: begin MtnRowY := 119; MtnZ := 5.0; end; 2: begin MtnRowY := 479; MtnZ := 1.0; end; end; {Case} FileSizeX := maxcolx + 1;{For maybe next time} FileSizeY := MtnRowY + 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FYImageX, FYImageY); for N := 0 to 16 do begin F[N] := ((EXP(N * ln(Fune))) * 3.14 / maxcolx); A[N] := EXP((D - 2) * ln(F[N])); PH[N] := 6.28 * Random; TH[N] := N + 2 * Random; CS[N] := COS(TH[N]); SN[N] := SIN(TH[N]); end; Z := 0.0; HS := 0.0; for I := 0 to maxcolx do HM[I] := 0.0; {M_x := 20.0; }{ Magnification ratio ... see below } {Plot_Angle := 90.0;}{ >90 makes steep walls of SIN <90 makes shallow} View_Angle := 2.0; {3.0; steep} {2.0 Makes an angle of 30 degrees} Illum_Angle := 0.5; {0.3;} {0.5 Makes an angle of 30 degrees} { V and I would make the plot location need to be changed} { str(View_Angle:5:2,s);str(Illum_Angle:5:2,ss);} str(Fune: 5: 2, s); str(D: 5: 2, ss); {str(Intensity,iss);} { str(A[0]:5:2,s);str(A[16]:5:2,ss);}{str(Intensity,iss);} TextOut(10, 10, 'Fractal "roughness" = ' + s + ',Dimension "range" ' + ss {+ ', Intensity = '+iss}); { LOOP} for Zcount := 0 to MtnRowY {120} do begin X := 0; for Xcount := 0 to maxcolx do begin Y := 0; for N := 1 to 16 do begin Y := Y + PH[N] + (A[N] * SIN(F[N] * (X * CS[N] + Z * SN[N]))); end; {record array} ManMatrix[Xcount, Zcount] := round(Y); H := Y + (Z / View_Angle); HS := HS - Illum_Angle; if H < HS then C := 5 {green} else begin C := 10; {purple} HS := H; end; if Y < -20 then begin c := 1; {blue water} H := (z / View_Angle) - 20; {20; goes with View 2.0, Illum 0.5} end; if H > HM[Xcount] then begin HM[Xcount] := H; {Place on screen } Y_Height := ((maxrowy - round(H))); TempColor := RGB(RGBArray[0, C], RGBArray[1, C], RGBArray[2, C]); Pixels[Xcount, Y_Height] := TempColor; end; X := X + 1.0; end; { NEXT X} HS := 0; Z := Z + MtnZ; {15} end; { NEXT Z} end; end; end; { of Procedure Fra_Mtns(Fun, D : Extended);} (*************************************************************) (*************************************************************) {Tin Mountain} procedure FractalGrid(Fun, D : Extended); var N, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; F_File: file of Smallint; Y: Extended; F, A, PH, TH, CS, SN: array[0..16] of Extended; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FileSizeX, FileSizeY); for N := 0 to 16 do begin F[N] := ((EXP(N * ln(Fun))) * 3.14 / maxcolx); A[N] := EXP({-0.8}(D - 2) * ln(F[N])); PH[N] := 6.28 * Random; TH[N] := N + 2 * Random; CS[N] := COS(TH[N]); SN[N] := SIN(TH[N]); end; { LOOP} for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 50); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Y := 0; for N := 1 to 16 do begin Y := Y + PH[N] + (A[N] * SIN(F[N] * (Xcount * CS[N] + Ycount * SN[N]))); end; {record array} ManMatrix[Xcount, Ycount] := round(Y); end; end; {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := 50+ Round((Ycount / maxrowy) * 50); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) {John Olsson}{johol@lysator.liu.se} {Process to Intensity level Krypton 20000} procedure FoldedGlobe(Krypton : Integer); var F_File: file of Smallint; Twister:Boolean; {XCount2, YCount2,I,}XCount2, Gamma,Omega, Slider,{Slideto,}Quartered,Twisted, MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; SinPI: array of double; Alpha,Beta, TanB, YRangeDiv2, YRangeDivPI,XRangeDiv2, XRangeDivPI: Double; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FileSizeX, FileSizeY); SetLength(SinPI, (2*FileSizeX)); { LOOP} XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} XCount2:=Random(Krypton div (maxrowy*maxcolx)); for Ycount := 0 to maxrowy do for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(XCount2 * (Random -Random)); end; for Xcount := 0 to maxcolx do begin YRangeDiv2:= sin(Xcount*2*PI/FileSizeX ); SinPI[Xcount] := YRangeDiv2; SinPI[Xcount+FileSizeX] := YRangeDiv2; end; YRangeDiv2:= FileSizeY/2; YRangeDivPI:= FileSizeY/PI; XRangeDiv2:= FileSizeX / 2; XRangeDivPI:= FileSizeX/PI; Quartered:=Round((FileSizeX / 4)); XCount2:=Round(FileSizeX / 2); {Process to Intensity level Krypton 20000} For MaxZDo:= 0 to Krypton do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / Krypton) * 100); Application.ProcessMessages; Alpha:= Random*PI; Beta:= Random*PI; Slider:= Random(Quartered); { Slideto:=XCount2+Slider;} Gamma:= Round( (XRangeDiv2)-(XRangeDivPI)*Beta); TanB:= tan(arccos(cos(Alpha)*cos(Beta))); If (random <{random} 0.5) then Twister:=True else Twister:=False; If (random <{random} 0.5) then Twisted:=-1 else Twisted:=1; for Xcount := {Slider to Slideto do }0 to XCount2 do begin Omega:= Round((YRangeDivPI *arctan(SinPI[Gamma-Xcount+FileSizeX{-Slider}] * TanB)) +YRangeDiv2); {If (Omega<0) then showmessage('Omega small'); If (Omega>maxrowy) then showmessage('Omega big');} If ( (Omega>=0) and (Omega <FileSizeY) and (Xcount>=0) and (Xcount <FileSizeX) ) then begin If Twister then begin ManMatrix[Xcount+Slider, Omega] := Round(ManMatrix[Xcount+Slider, Omega]+Twisted); { ManMatrix[Xcount, Omega] := ManMatrix[Xcount, Omega]+1;} end else begin { ManMatrix[Xcount, Omega] := ManMatrix[Xcount, Omega]-1;} { If ( (Xcount+XCount2-1) < FilesizeX) then ManMatrix[(Xcount+XCount2-1), Omega] := Round(ManMatrix[(Xcount+XCount2-1), Omega]+Twisted);} { ManMatrix[Xcount, Omega] := ManMatrix[Xcount, Omega]+Twisted;} { ManMatrix[Xcount, Omega] :=ManMatrix[Xcount, Omega]-1;} (* ManMatrix[Xcount{+Quartered-1}, Omega] := Round(ManMatrix[Xcount{+Quartered-1}, Omega]+Twisted);*) If ((Xcount<Slider))then ManMatrix[(Xcount{-Slider}), Omega] := Round(ManMatrix[(Xcount{-Slider}), Omega]+Twisted); If (((Quartered+Xcount)+Slider)<FileSizex)then ManMatrix[(Quartered+Xcount)+Slider, Omega] := Round(ManMatrix[(Quartered+Xcount)+Slider, Omega]+Twisted); end; end; end; end; {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; SetLength(SinPI, 0); end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) procedure DupliGlobe(Krypton : Integer); var F_File: file of Smallint; Twister:Boolean; XCount2, Gamma, Omega, {Quartered,} MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; Alpha,Beta, TanB, YRangeDiv2, YRangeDivPI, XRangeDiv2, XRangeDivPI: Double; SinPI: array of double; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... } SetLength(ManMatrix, FileSizeX, FileSizeY); SetLength(SinPI, (2*FileSizeX)); XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} XCount2:=Random(Krypton div (maxrowy*maxcolx)); for Ycount := 0 to maxrowy do for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(XCount2 * (Random -Random)); end; for Xcount := 0 to maxcolx do begin YRangeDiv2:= sin(Xcount*2*PI/FileSizeX ); SinPI[Xcount] := YRangeDiv2; SinPI[Xcount+FileSizeX] := YRangeDiv2; end; YRangeDiv2:= FileSizeY/2; YRangeDivPI:= FileSizeY/PI; XRangeDiv2:= FileSizeX / 2; XRangeDivPI:= FileSizeX/PI; { Quartered:=Round((FileSizeX / 4));} XCount2:=Round(FileSizeX / 2); {Process to Intensity level} For MaxZDo:= 0 to Krypton do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / Krypton) * 100); Application.ProcessMessages; Alpha:= Random*PI; Beta:= Random*PI; Gamma:= Round( (XRangeDiv2)-(XRangeDivPI)*Beta); TanB:= tan(arccos(cos(Alpha)*cos(Beta))); If (random <{random} 0.5) then Twister:=True else Twister:=False; for Xcount := 0 to XCount2 do begin Omega:= Round((YRangeDivPI *arctan(SinPI[Gamma-Xcount+FileSizeX] * TanB)) +YRangeDiv2); If ( (Omega>=0) and (Omega <FileSizeY) and (Xcount>=0) and (Xcount <FileSizeX) ) then begin If Twister then begin ManMatrix[Xcount, Omega] := Round(ManMatrix[Xcount, Omega]+1); end else begin ManMatrix[Xcount, Omega] := Round(ManMatrix[Xcount, Omega]-1); end; end; end; end; {Duplicate} XCount2:=Round(FileSizeX / 2); for Ycount := 0 to maxrowy do begin Application.ProcessMessages; for Xcount := 0 to XCount2 do begin If ((Xcount+XCount2>=0) and (Xcount+XCount2 <FileSizeX) ) then ManMatrix[Xcount+XCount2, Ycount] := ManMatrix[Xcount, Ycount]; end; end; {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; SetLength(SinPI, 0); end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) {Random sin..cos wave craters of fractal (random various) sizes from GRIP Filters Rough texture...} {R multiplier of sin..cos cones G width random 3 7 11 rest are little shallow I intensity times file width=repititions} {Process to Intensity level r g i Loop phingphactor:= r 1.4 Gradient DeptH, 9 Intensity,36 :} procedure Craters(phingphactor:Double; DeptH, Intensity : Integer); var UpDown:Boolean; X, Z, MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; Decider, Totaler, R, Y: Extended; F_File: file of Smallint; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.bin'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FileSizeX, FileSizeY); XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} for Ycount := 0 to maxrowy do begin for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(Random(Intensity) * (Random -Random)); end;end; {Process to Intensity level r g i Loop phingphactor:= r 1.4 Gradient DeptH, 9 Intensity,36 :} For MaxZDo:= 0 to maxcolx*Intensity do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / maxcolx*Intensity) * 100); Application.ProcessMessages; Xcount:= random(maxcolx); Ycount:= random(maxrowy); {Place filters here} Decider:=Random(DeptH); If (Random > 0.5)then UpDown:=True else UpDown:=False; Totaler := 0; if (Decider <3) then begin for X := 0 to 8 do begin for Z := 0 to 8 do begin R := SQRT(sqr(X - 4) + sqr(Z - 4)) * phingphactor; if ((X = 4) and (Z = 4)) then Y := 0 else begin If UpDown then Y := (SIN(R) / R) else Y := (COS(R) / R); Totaler := Totaler + Y; end; if (( Xcount < (maxcolx - X)) and (Ycount < (maxrowy - Z))) then Manmatrix[Xcount+X, Ycount+Z] := Manmatrix[Xcount+X, Ycount+Z]+Round(Y); end; end; if (( Xcount < (maxcolx - 4)) and (Ycount < (maxrowy - 4))) then Manmatrix[Xcount+4, Ycount+4]:= Manmatrix[Xcount+4, Ycount+4]+Round(Totaler); end else if (Decider<7) then begin for X := 0 to 6 do begin for Z := 0 to 6 do begin R := SQRT(sqr(X - 3) + sqr(Z - 3)) * phingphactor; if ((X = 3) and (Z = 3)) then Y := 0 else begin If UpDown then Y := (SIN(R) / R) else Y := (COS(R) / R); Totaler := Totaler + Y; end; if (( Xcount < (maxcolx - X)) and (Ycount < (maxrowy - Z))) then Manmatrix[Xcount+X, Ycount+Z] := Manmatrix[Xcount+X, Ycount+Z]+Round(Y); end; end; if (( Xcount < (maxcolx - 3)) and (Ycount < (maxrowy - 3))) then Manmatrix[Xcount+3, Ycount+3]:= Manmatrix[Xcount+3, Ycount+3]+Round(Totaler); end else if (Decider<11) then begin for X := 0 to 4 do begin for Z := 0 to 4 do begin R := SQRT(sqr(X - 2) + sqr(Z - 2)) * phingphactor; if ((X = 2) and (Z = 2)) then Y := 0 else begin If UpDown then Y := (SIN(R) / R) else Y := (COS(R) / R); Totaler := Totaler + Y; end; if (( Xcount < (maxcolx - X)) and (Ycount < (maxrowy - Z))) then Manmatrix[Xcount+X, Ycount+Z] := Manmatrix[Xcount+X, Ycount+Z]+Round(Y); end; end; if (( Xcount < (maxcolx - 2)) and (Ycount < (maxrowy - 2))) then Manmatrix[Xcount+2, Ycount+2]:= Manmatrix[Xcount+2, Ycount+2]+Round(Totaler); end else {9} begin for X := 0 to 2 do begin for Z := 0 to 2 do begin R := SQRT(sqr(X - 1) + sqr(Z - 1)) * phingphactor; if ((X = 1) and (Z = 1)) then Y := 0 else begin If UpDown then Y := (SIN(R) / R) else Y := (COS(R) / R); Totaler := Totaler + Y; end; if (( Xcount < (maxcolx - X)) and (Ycount < (maxrowy - Z))) then Manmatrix[Xcount+X, Ycount+Z] := Manmatrix[Xcount+X, Ycount+Z]+Round(Y); end; end; if (( Xcount < (maxcolx - 1)) and (Ycount < (maxrowy - 1))) then Manmatrix[Xcount+1, Ycount+1]:= Manmatrix[Xcount+1, Ycount+1]+Round(Totaler); end end; {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) {Water Demo Cones Author : Jason Allen Email : jra101@home.com} procedure Waves( DeptH, Intensity : Integer); var F_File: file of Smallint; MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; u, v , sqrx, sqry, sqrw : Integer; Synchronocity:Double; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FileSizeX, FileSizeY); XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} for Ycount := 0 to maxrowy do begin for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(Random(Intensity) * (Random -Random)); end;end; For MaxZDo:= 0 to maxcolx*Intensity do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / (maxcolx*Intensity)) * 100); Application.ProcessMessages; Xcount:= random(maxcolx); Ycount:= random(maxrowy); Synchronocity:=(Random-Random); (* // Name : Water Demo // Author : Jason Allen// Email : jra101@home.com // Name : PutDrop // Purpose : Starts a droplet in the wavemap. //This is done by creating a //"cone" around the x,y coordinates specified. This "cone" is //then averaged every redraw, creating the ripple effect. // Parameters : // x,y - coordinates of the grid point to start to droplet // w - splash height // MulFactor - splash strength // Returns : none procedure PutDrop(x , y, w, MulFactor : Integer); var u, v : Integer; // Loop counters sqrx, sqry, sqrw : Integer; x= Xcount y= Ycount begin*) {Process to Intensity level DeptH, 22 Intensity,10} // w:=DeptH; splash height 22 not his 4 // MulFactor:=Intensity; splash strength Sync used not his -22 { PutDrop(x, y, 4 ,-22);} sqrw := sqr(DeptH); // Create the initial "cone" for v := Ycount - DeptH to Ycount + DeptH do begin sqry := sqr(v - Ycount); for u := Xcount - DeptH to Xcount + DeptH do begin sqrx := sqr(u-Xcount); if (sqrx + sqry) <= sqrw then begin // Boundary checking, make sure we don't try to put //a drop next to an edge if (u > -1) and ( u < (FileSizeX )) and ( v > -1) and (v < (FileSizeY )) then begin ManMatrix[u, v] := (ManMatrix[u, v]+ Round(Synchronocity *(DeptH - sqrt(sqrx + sqry)))); end; end; end; end; end;{of loop} {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) (*************************************************************) procedure Rippled(RadiusG, DeptH, Intensity : Integer); var F_File: file of Smallint; XCount2, YCount2, u, v , sqrx, sqry, sqrw,MaxZDo2,{MaxZDo3,}n, MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; Synchronocity:Double; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1+2; maxrowy := FileSizeY- 1+2; Randomize; {Set up array... 2 larger to hold filter} SetLength(ManMatrix, FileSizeX+2, FileSizeY+2); XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} for Ycount := 0 to maxrowy do begin for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(Random(Intensity) * (Random -Random)); end;end; For MaxZDo:= 0 to maxcolx do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / (maxcolx)) * 100); Application.ProcessMessages; For MaxZDo2:= 0 to Intensity do begin Application.ProcessMessages; Xcount:= random(maxcolx); Ycount:= random(maxrowy); Synchronocity:=(Random-Random);{they got too high?...} {Process to Intensity level DeptH, 22 Intensity,10} // w:=DeptH; splash height // MulFactor:=Intensity; splash strength sqrw := sqr(DeptH); // Create the initial "cone" for v := Ycount - DeptH to Ycount + DeptH do begin sqry := sqr(v - Ycount); for u := Xcount - DeptH to Xcount + DeptH do begin sqrx := sqr(u-Xcount); if (sqrx + sqry) <= sqrw then begin // Boundary checking, make sure we don't try to put //a drop next to an edge if (u > -1) and ( u < (FileSizeX )) and ( v > -1) and (v < (FileSizeY )) then begin ManMatrix[u, v] := (ManMatrix[u, v]+ Round(Synchronocity *(DeptH - sqrt(sqrx + sqry)))); end; end; end; end; end;{loop intnesity} {R smoothers} { For MaxZDo3:= 0 to RadiusG do} If ( Random(100) <= RadiusG)then begin for YCount2 := 1 to maxrowy-1 do begin Application.ProcessMessages; for XCount2 := 1 to maxcolx-1 do begin // Calculate the current cell's new value // based on the surrounding cell's n := ( (ManMatrix[XCount2-1,YCount2] + { ManMatrix[XCount2,YCount2]+} ManMatrix[XCount2+1,YCount2] + { ManMatrix[XCount2-1,YCount2-1] +} ManMatrix[XCount2,YCount2-1]+ { ManMatrix[XCount2+1,YCount2-1] + ManMatrix[XCount2-1,YCount2+1] +} ManMatrix[XCount2,YCount2+1] { + ManMatrix[XCount2+1,YCount2+1]} ) div 2{8}) - ManMatrix[XCount2,YCount2]; // Equivalent to decrementing n by n divided by 2^DAMP, // this decreases the value in the cell, //making the waves fade out by Water damping amount // DAMP = 4; Dec(n,Smallint(n shr 4)); // Set new value into the wavemap ManMatrix[Xcount2, Ycount2] := n; end;end; end;{of loop 2} end;{of loop columns} {Replace matrix to real size, reset variable sizes} for YCount2 := 1 to maxrowy-1 do begin Application.ProcessMessages; for XCount2 := 1 to maxcolx-1 do begin ManMatrix[Xcount2-1, Ycount2-1] := ManMatrix[Xcount2, Ycount2]; end; end; SetLength(ManMatrix, FileSizeX, FileSizeY); {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) (*************************************************************) procedure Splattered(RadiusG, DeptH, Intensity : Integer); var F_File: file of Smallint; MaxZDo, maxcolx, maxrowy, XCount, YCount, TempMan : Integer; u, v , sqrx, sqry, sqrw : Integer; Synchronocity:Double; begin {Save LAST array made to FractalFileName} if (bSaveTheMountains) then begin begin MainForm.HintPanel.Caption := 'Saving Mountains to disk'; Application.ProcessMessages; FractalFileMatrix := ChangeFileExt(FractalFilename, '.BIN'); AssignFile(F_File, FractalFileMatrix); ReWrite(F_File); if IoResult = 0 then begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin Write(F_File, ManMatrix[Xcount, Ycount]); end; end; CloseFile(F_File); if (IoResult <> 0) then DoMessages(30064); end else DoMessages(30065); end; end else begin maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; Randomize; {Set up array... for next one} SetLength(ManMatrix, FileSizeX, FileSizeY); XYZ3DForm.MtnsProgressBar.Position :=10; Application.ProcessMessages; {Fill Array} for Ycount := 0 to maxrowy do begin for Xcount := 0 to maxcolx do begin ManMatrix[Xcount, Ycount] := round(Random(Intensity) * (Random -Random)); end;end; For MaxZDo:= 0 to maxcolx*Intensity do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / (maxcolx*Intensity)) * 100); Application.ProcessMessages; Xcount:= random(maxcolx); Ycount:= random(maxrowy); Synchronocity:=(Random-Random);{they got too high?...} {Process to Intensity level DeptH, 22 Intensity,10} // w:=DeptH; splash height // MulFactor:=Intensity; splash strength sqrw := sqr(DeptH); // Create the initial "cone" for v := Ycount - DeptH to Ycount + DeptH do begin sqry := sqr(v - Ycount); for u := Xcount - DeptH to Xcount + DeptH do begin sqrx := sqr(u-Xcount); if (sqrx + sqry) <= sqrw then begin // Boundary checking, make sure we don't try to put //a drop next to an edge if (u > -1) and ( u < (FileSizeX )) and ( v > -1) and (v < (FileSizeY )) then begin ManMatrix[u, v] := (ManMatrix[u, v]+ Round(Synchronocity *(DeptH - sqrt(sqrx + sqry)))); end; end; end; end; end;{of loop} {R more cones} For MaxZDo:= 0 to RadiusG do begin XYZ3DForm.MtnsProgressBar.Position := Round((MaxZDo / (RadiusG)) * 100); Application.ProcessMessages; Xcount:= random(maxcolx); Ycount:= random(maxrowy); Synchronocity:=RadiusG*(Random-Random);{they got too high?...} sqrw := sqr(DeptH); // Create the initial "cone" for v := Ycount - DeptH to Ycount + DeptH do begin sqry := sqr(v - Ycount); for u := Xcount - DeptH to Xcount + DeptH do begin sqrx := sqr(u-Xcount); if (sqrx + sqry) <= sqrw then begin // Boundary checking, make sure we don't try to put //a drop next to an edge if (u > -1) and ( u < (FileSizeX )) and ( v > -1) and (v < (FileSizeY )) then begin ManMatrix[u, v] := (ManMatrix[u, v]+ Round(Synchronocity *(DeptH - sqrt(sqrx + sqry)))); end; end; end; end; end;{of loop 2} {Gather results} MaximumElevation := -2147483647; MinimumElevation := 2147483646; maxcolx:= FileSizeX- 1; maxrowy := FileSizeY- 1; for Ycount := 0 to maxrowy do begin XYZ3DForm.MtnsProgressBar.Position := Round((Ycount / maxrowy) * 100); Application.ProcessMessages; for Xcount := 0 to maxcolx do begin TempMan:=ManMatrix[Xcount, Ycount]; if (MaximumElevation <= TempMan) then MaximumElevation := TempMan; if (MinimumElevation >= TempMan) then MinimumElevation := TempMan; end; end; end; XYZ3DForm.MtnsProgressBar.Position :=0; Application.ProcessMessages; end; (*************************************************************) (*************************************************************) (*************************************************************) {Grow along bottom of screen} procedure DLA(Intensity: Integer); {(Freq,F_Dim: Extended;Intensity:Integer)} var TempColor: TColor; Contact: Boolean; X, Y, HighestHigh, {CurrentX,CurrentY,} spacer, ICount, maxcolx, maxrowy: Integer; HighS, Xs, Ys: string; begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); maxrowy := (FYImageY - 1); HighestHigh := (FYImageY - 5); { Brush.Color:=FBackGroundColor; Brush.Style:=bsSolid; FillRect(Rect(0,0,FYImageX,FYImageY)); TempColor:=RGB(255-GetRValue(FBackGroundColor), 255-GetGValue(FBackGroundColor), 255-GetBValue(FBackGroundColor)); Pen.Color := TempColor; Font.Color:= TempColor;} {Set up bottom line glue} { Moveto(0,maxrowy); Lineto(maxcolx,maxrowy); } {Set up multi color line} for X := 0 to maxcolx do begin TempColor := RGB(Colors[0, (Random(255) mod 255)], Colors[1, (Random(255) mod 255)], Colors[2, (Random(255) mod 255)]); Pixels[X, maxrowy] := TempColor; end; { MainForm.Show;} Randomize; bRotateImage := False; {in the Drawing...} bRotatingImage := True; maxcolx := (FYImageX - 3); X := random(maxcolx) + 1; Y := HighestHigh; {Start from HighestHigh + 3} str(X, Xs); str(Y, Ys); str(HighestHigh, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; repeat for Spacer := 1 to 100 do begin X := random(maxcolx) + 1; Y := HighestHigh; {Start from HighestHigh + 3} {Y:= (Random((maxrowy-(HighestHigh-2)))+HighestHigh);} if Y > maxrowy then Y := HighestHigh; Contact := True; ICount := 0; while Contact do begin {Drop bombers} if (FBackGroundColor <> Pixels[X + 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X + 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X + 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; X := X + (Random(3) - 1); {Y := Y + (Random(3)-1);}{Keep in bounds} Y := Y + (Random(3)); {Keep in bounds.. always dropping} if X > maxcolx then X := ((maxcolx div 2) - round((random - random) * 100)); if X < 1 then X := ((maxcolx div 2) + round((random - random) * 100)); if Y > maxrowy then Y := HighestHigh; if Y < HighestHigh - 4 then Y := HighestHigh; end; {end of while} end; {of spacer} str(X, Xs); str(Y, Ys); str(HighestHigh, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; until ((bRotateImage = True) or (HighestHigh < 7)); end; end; (*************************************************************) {Grow along bottom of screen} procedure DLAC(Intensity: Integer); var TempColor: TColor; Contact: Boolean; X, Y, HighestHigh, {CurrentX,CurrentY,} Spacer, ICount, maxcolx, maxrowy: Integer; HighS, Xs, Ys: string; begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); maxrowy := (FYImageY - 1); HighestHigh := (FYImageY - 5); { Brush.Color:=FBackGroundColor; Brush.Style:=bsSolid; FillRect(Rect(0,0,FYImageX,FYImageY)); TempColor:=RGB(255-GetRValue(FBackGroundColor), 255-GetGValue(FBackGroundColor), 255-GetBValue(FBackGroundColor)); Pen.Color := TempColor; Font.Color:= TempColor;} {Set up bottom line glue} Moveto(0, maxrowy); Lineto(maxcolx, maxrowy); {Set up multi color line} for X := 0 to maxcolx do begin TempColor := RGB(Colors[0, (Random(255) mod 255)], Colors[1, (Random(255) mod 255)], Colors[2, (Random(255) mod 255)]); Pixels[X, maxrowy] := TempColor; end; { MainForm.Show;} Randomize; bRotateImage := False; {in the Drawing...} bRotatingImage := True; maxcolx := (FYImageX - 3); X := random(maxcolx) + 1; Y := HighestHigh; {Start from HighestHigh + 3} str(X, Xs); str(Y, Ys); str(HighestHigh, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; repeat for Spacer := 1 to 100 do begin X := (X mod 6); if X = 1 then X := ((maxcolx div 2) + round((random - random) * 100)) else X := random(maxcolx) + 1; {X:= (maxcolx div 2);} Y := HighestHigh; {Start from HighestHigh + 3} {Y:= (Random((maxrowy-(HighestHigh-2)))+HighestHigh);} if Y > maxrowy then Y := HighestHigh; Contact := True; ICount := 0; while Contact do begin {Drop bombers} if (FBackGroundColor <> Pixels[X + 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X + 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X + 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X + 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X - 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X - 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; if (FBackGroundColor <> Pixels[X, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then HighestHigh := Y - 3; TempColor := Pixels[X, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; (* If ( {TempColor =} (FBackGroundColor <> Pixels[X+1,Y+1]) or (FBackGroundColor <> Pixels[X-1,Y+1]) or (FBackGroundColor <> Pixels[X,Y+1]) or (FBackGroundColor <> Pixels[X+1,Y]) or (FBackGroundColor <> Pixels[X-1,Y]) or (FBackGroundColor <> Pixels[X+1,Y-1]) or (FBackGroundColor <> Pixels[X-1,Y-1]) or (FBackGroundColor <> Pixels[X,Y-1]) ) then begin {Contacted so accumulate} If Y = HighestHigh Then HighestHigh:=Y-3; Pixels[X,Y]:= TempColor; Contact:= False; end; *) {str(X,Xs);str(Y,Ys); MainForm.HiddenFX.Caption:='FX: '+Xs+', FY: '+Ys; Application.ProcessMessages;} X := X + (Random(3) - 1); {Y := Y + (Random(3)-1);}{Keep in bounds} Y := Y + (Random(3)); {Keep in bounds.. always dropping} {If X > maxcolx Then X := ((maxcolx div 2)- round((random -random) *100)); If X < 1 Then X := ((maxcolx div 2)+ round((random -random) *100));} if X > maxcolx then X := (maxcolx div 2); if X < 1 then X := ((maxcolx div 2)); if Y > maxrowy then Y := HighestHigh; if Y < HighestHigh - 4 then Y := HighestHigh; end; {end of while} end; str(X, Xs); str(Y, Ys); str(HighestHigh, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; until ((bRotateImage = True) or (HighestHigh < 7)); end; end; (*************************************************************) (*************************************************************) {Grow at center of screen... make a box and throw at center} procedure DLACentroid(Intensity: Integer); {(Freq,F_Dim: Extended;Points,Intensity:Integer)} var TempColor: TColor; Contact: Boolean; Spacer, X, Y, HighestHigh, LowestLow, RightSide, LeftSide, Stepcounter, ICount, CenterX, CenterY, Centroid, maxcolx, maxrowy: Integer; HighS, Xs, Ys: string; begin with MainForm.Image2.Canvas do begin { Brush.Color:=FBackGroundColor; Brush.Style:=bsSolid; FillRect(Rect(0,0,FYImageX,FYImageY)); TempColor:=RGB(255-GetRValue(FBackGroundColor), 255-GetGValue(FBackGroundColor), 255-GetBValue(FBackGroundColor)); Pen.Color := TempColor; Font.Color:= TempColor; MainForm.Show;} {Set up bottom line glue} maxcolx := (10); maxrowy := (10); CenterX := (FYImageX div 2); CenterY := (FYImageY div 2); { HighestHigh:=(CenterY+5); LowestLow:=(CenterY-5);} HighestHigh := (CenterY - 5); LowestLow := (CenterY + 5); RightSide := (CenterX + 5); LeftSide := (CenterX - 5); {Set up multi color line} for X := CenterX - 2 to CenterX + 2 do begin for Y := CenterY - 2 to CenterY + 2 do begin TempColor := RGB(Colors[0, (Random(255) mod 255)], Colors[1, (Random(255) mod 255)], Colors[2, (Random(255) mod 255)]); Pixels[X, Y] := TempColor; end; end; Randomize; bRotateImage := False; {in the Drawing...} bRotatingImage := True; X := CenterX; Y := HighestHigh; str(X, Xs); str(Y, Ys); str(HighestHigh, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; repeat for Spacer := 1 to 100 do begin ICount := 0; Centroid := random(4); if Centroid = 0 then {center + (width * random + or -)} begin X := LeftSide; { Y:=(CenterY+ ( (random(maxrowy div 2)) *(random(2) -random(2)) ) );} Y := (CenterY + ((random(maxrowy div 2)) - (random(maxrowy div 2)))); end else if Centroid = 1 then {center + (width * random + or -)} begin X := RightSide; { Y:=(CenterY+ ( (random(maxrowy div 2)) *(random(2) -random(2))));} Y := (CenterY + ((random(maxrowy div 2)) - (random(maxrowy div 2)))); end else if Centroid = 2 then {center + (width * random + or -)} begin { X:=(CenterX + ( (random(maxcolx div 2)) *(random(2) -random(2))));} X := (CenterX + ((random(maxcolx div 2)) - (random(maxcolx div 2)))); Y := HighestHigh; end else if Centroid = 3 then {center + (width * random + or -)} begin X := (CenterX + ((random(maxcolx div 2)) - (random(maxcolx div 2)))); Y := LowestLow; end else ;{center + (width * random + or -)} { showmessage('oops 1');} Stepcounter := 0; Contact := True; while ((Contact) and (Stepcounter < 2000)) do begin {Drop bombers} inc(Stepcounter); case Centroid of {Keep in bounds.. always dropping} 0: begin {Left} X := X + (Random(3) - 1); Y := Y + (Random(3) - 1); { +(Random(2)-Random(2));} end; 1: begin {Right} X := X + (Random(3) - 1); { -(Random(2));} Y := Y + (Random(3) - 1); { +(Random(2)-Random(2));} end; 2: begin {Top} X := X + (Random(3) - 1); Y := Y + (Random(3) - 1); {+(Random(2));} end; 3: begin {Bottom} X := X + (Random(3) - 1); Y := Y + (Random(3) - 1); { -(Random(2));} end; else ;{showmessage('oops');} end; {of case} if (X < (LeftSide - 4)) then X := LeftSide; if (X > (RightSide + 4)) then X := RightSide; if (Y < (HighestHigh - 4)) then Y := HighestHigh; if (Y > (LowestLow + 4)) then Y := LowestLow; { HighestHigh:=(CenterY-5); LowestLow:=(CenterY+5); RightSide:=(CenterX+5); LeftSide:=(CenterX-5);} if (FBackGroundColor <> Pixels[X - 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X - 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X - 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount = Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X - 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X + 1, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X + 1, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X + 1, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X + 1, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X - 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X - 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X + 1, Y]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X + 1, Y]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X, Y + 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X, Y + 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; { else} if (FBackGroundColor <> Pixels[X, Y - 1]) then begin {Contacted so accumulate} inc(ICount); if (ICount >= Intensity) then begin if Y = HighestHigh then begin HighestHigh := Y - 3; inc(maxrowy, 6); end; if Y = LowestLow then begin LowestLow := Y + 3; inc(maxrowy, 6); end; if X = RightSide then begin RightSide := X + 3; inc(maxcolx, 6); end; if X = LeftSide then begin LeftSide := X - 3; inc(maxcolx, 6); end; TempColor := Pixels[X, Y - 1]; Pixels[X, Y] := TempColor; Contact := False; end; end; {str(X,Xs);str(Y,Ys); str(StepCounter,HighS); MainForm.HiddenFX.Caption:='FX: '+Xs+', FY: '+Ys+', Count: '+HighS; Application.ProcessMessages;} end; {end of while} end; {of spacer} str(X, Xs); str(Y, Ys); {str(HighestHigh,HighS);} str(StepCounter, HighS); MainForm.HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys + ', High: ' + HighS; Application.ProcessMessages; until ((bRotateImage = True) or (HighestHigh < 7) or (LowestLow > FYImageY) or (RightSide > FYImageX) or (LeftSide < 7)); end; end; (*************************************************************) (*************************************************************) (*************************************************************) (***************************************************) (***************************************************) procedure init; {turns on graphics and creates a cube. Since the rotation routines rotate around the origin, I have centered the cube on the origin, so that it stays in place and only spins.} begin box[0].x := -75; box[0].y := -75; box[0].z := -75; box[1].x := 75; box[1].y := -75; box[1].z := -75; box[2].x := 75; box[2].y := 75; box[2].z := -75; box[3].x := -75; box[3].y := 75; box[3].z := -75; box[4].x := -75; box[4].y := -75; box[4].z := 75; box[5].x := 75; box[5].y := -75; box[5].z := 75; box[6].x := 75; box[6].y := 75; box[6].z := 75; box[7].x := -75; box[7].y := 75; box[7].z := 75; end; procedure myline(x1, y1, z1, x2, y2, z2: real); {Keeps the draw routine pretty. Pixels are integers, so I round. Since the cube is centered around 0,0 I move it over 200 to put it on screen.} begin {if you think those real mults are slow, here's some rounds too...} {hey, you may wonder, what happened to the stinking z coordinate? Ah, says I, this is the simplest of 3d viewing transforms. You just take the z coord out of things and boom. Looking straight down the z axis on the object. If I get inspired, I will add simple perspective transform to these.} {There, got inspired. Made mistakes. Foley et al are not very good at tutoring perspective and I'm kinda ready to be done and post this.} MainForm.Image2.Canvas.moveto(round(x1) + 200, round(y1) + 200); MainForm.Image2.Canvas.lineto(round(x2) + 200, round(y2) + 200); end; procedure draw; {my model is hard coded. No cool things like vertex and edge and face lists.} begin myline(box[0].x, box[0].y, box[0].z, box[1].x, box[1].y, box[1].z); myline(box[1].x, box[1].y, box[1].z, box[2].x, box[2].y, box[2].z); myline(box[2].x, box[2].y, box[2].z, box[3].x, box[3].y, box[3].z); myline(box[3].x, box[3].y, box[3].z, box[0].x, box[0].y, box[0].z); myline(box[4].x, box[4].y, box[4].z, box[5].x, box[5].y, box[5].z); myline(box[5].x, box[5].y, box[5].z, box[6].x, box[6].y, box[6].z); myline(box[6].x, box[6].y, box[6].z, box[7].x, box[7].y, box[7].z); myline(box[7].x, box[7].y, box[7].z, box[4].x, box[4].y, box[4].z); myline(box[0].x, box[0].y, box[0].z, box[4].x, box[4].y, box[4].z); myline(box[1].x, box[1].y, box[1].z, box[5].x, box[5].y, box[5].z); myline(box[2].x, box[2].y, box[2].z, box[6].x, box[6].y, box[6].z); myline(box[3].x, box[3].y, box[3].z, box[7].x, box[7].y, box[7].z); myline(box[0].x, box[0].y, box[0].z, box[5].x, box[5].y, box[5].z); myline(box[1].x, box[1].y, box[1].z, box[4].x, box[4].y, box[4].z); end; procedure rotx; {if you know your matrix multiplication, the following equations are derived from [x [ 1 0 0 0 [x',y',z',1] y 0 c -s 0 = z 0 s c 0 1] 0 0 0 1]} var i: integer; begin MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); { setcolor(0);} draw; for i := 0 to 7 do begin box[i].x := box[i].x; box[i].y := box[i].y * cos(radTheta) + box[i].z * sin(radTheta); box[i].z := -box[i].y * sin(radTheta) + box[i].z * cos(radTheta); end; { setcolor(15);} MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); draw; end; procedure roty; {if you know your matrix multiplication, the following equations are derived from [x [ c 0 s 0 [x',y',z',1] y 0 1 0 0 = z -s 0 c 0 1] 0 0 0 1]} var i: integer; begin { setcolor(0);} MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); draw; for i := 0 to 7 do begin box[i].x := box[i].x * cos(radTheta) - box[i].z * sin(radTheta); box[i].y := box[i].y; box[i].z := box[i].x * sin(radTheta) + box[i].z * cos(radTheta); end; { setcolor(15); } MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); draw; end; procedure rotz; {if you know your matrix multiplication, the following equations are derived from [x [ c -s 0 0 [x',y',z',1] y s c 0 0 = z 0 0 1 0 1] 0 0 0 1]} var i: integer; begin { setcolor(0);} MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); draw; for i := 0 to 7 do begin box[i].x := box[i].x * cos(radTheta) + box[i].y * sin(radTheta); box[i].y := -box[i].x * sin(radTheta) + box[i].y * cos(radTheta); box[i].z := box[i].z; end; { setcolor(15);} MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 150], Colors[1, 150], Colors[2, 150]); draw; end; procedure RotatingCube; begin MainForm.DoImageStart; init; { setcolor(14);} MainForm.Image2.Canvas.Pen.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); MainForm.Image2.Canvas.Brush.Color := RGB(Colors[0, 0], Colors[1, 0], Colors[2, 0]); draw; bRotateImage := False; {in the Drawing...} bRotatingImage := True; RotatorCuff := 0; repeat begin case RotatorCuff of 0: rotx; 1: roty; 2: rotz; else {who gives a}; end; {case} MainForm.HiddenFX.Caption := 'FX: '; Application.ProcessMessages; end; until (bRotateImage = True); Mainform.DoImageDone; end; (***************************************************) (***************************************************) procedure drawScene(x, y, z, rot: integer); var lastTan, lastAngle, h: integer; mapTan: longint; hstr: string; {var scrn:word;} var {color,} height: byte; var xs, ys, ds: longint; var xp, yp, dp: fixed; begin { fillchar(mem[$A000:0],320*200,0);} for h := 0 to xSize - 1 do begin lastAngle := 0; { scrn:=h+320*(ySize-1);} lastTan := tanTab[lastAngle]; xp.i := x; xp.f := 0; yp.i := y; yp.f := 0; dp.l := 0; xs := longint(sinTab[(h + rot - (xSize shr 1)) and angleMask]) * 2; ys := longint(sinTab[(h + rot - (xSize shr 1) + xSize) and angleMask]) * 2; {cos} ds := $FFFE; inc(xp.l, xs * 16); inc(yp.l, ys * 16); inc(dp.l, ds * 16); str(h, hstr); MainForm.HiddenFX.Caption := 'FX: ' + hstr; Application.ProcessMessages; while lastAngle < ySize do begin inc(xp.l, xs * 2); inc(yp.l, ys * 2); inc(dp.l, ds * 2); inc(xs, xs div 32); inc(ys, ys div 32); inc(ds, ds shr 5); if word(xp.i) > mapSize - 1 then break; if word(yp.i) > mapSize - 1 then break; height := map[xp.i, yp.i]; mapTan := (longint(height - z) * $7FFF) div dp.i; { color:=32+((z-height));}{never changes} while (lastTan <= mapTan) or {and}(lastAngle < ySize) do begin { mem[$A000:scrn]:=color;}{h+20,lastAngle+20} MainForm.Image2.Canvas.Pixels[lastAngle + 120, h] := abs(lastTan); {RGB(Colors[0,(color mod 255)],Colors[1,(color mod 255)],Colors[2,(color mod 255)]);} { dec(scrn,320);} inc(lastAngle); lastTan := tanTab[lastAngle]; { str((z-height),hstr); MainForm.HiddenFX.Caption:='FX angle: '+hstr; Application.ProcessMessages;} end; end; end; end; procedure initTables; var i: integer; r: real; begin for i := 0 to angleMask do sinTab[i] := round(sin(i * pi / 512) * $7FFF); for i := 0 to ySize - 1 do begin r := (i - 64) * pi / (3 * ySize); tanTab[i] := round(sin(r) / cos(r) * $7FFF); end; end; procedure initMap; var x, y: integer; begin for x := 0 to 127 do for y := 0 to 127 do map[x, y] := ((longint(sinTab[(y * 21 - 12) and angleMask]) + sinTab[(x * 31 + 296) and angleMask] div 2) shr 12) + 120; end; procedure FallingColumn; var x, y, z, r {,a}: integer; i: word; begin MainForm.DoImageStart; bRotateImage := False; {in the Drawing...} bRotatingImage := True; if ((RotatorCuff < 0) or (RotatorCuff > 3)) then RotatorCuff := 0; { sinTab:array of Integer;} SetLength(sinTab, angleMask + 1); {:array[0..angleMask]of integer;} {sin(xyAngle)*$7FFF} { tanTab:array of Integer;} SetLength(tanTab, ySize); { array[0..ySize-1]of integer;} {tan(zAngle)*$7FFF} { map:array of array of byte;} { array[0..mapSize-1,0..mapSize-1]of byte;} SetLength(map, mapSize, mapSize); initTables; MainForm.HiddenFX.Caption := 'FX: 22'; Application.ProcessMessages; initMap; randomize; x := 50 + random(29); y := 50 + random(29); z := 125 + random(10); r := random(angleMask); { a:=64;} repeat begin { drawScene(x,y,z,r); } RotatorCuff := random(500); if tanTab[ySize - 1] < 30000 then for i := 0 to ySize - 1 do inc(tanTab[i], RotatorCuff) else if tanTab[0] > -30000 then for i := 0 to ySize - 1 do dec(tanTab[i], RotatorCuff); RotatorCuff := random(4); { inc(RotatorCuff); } if ((RotatorCuff < 0) or (RotatorCuff > 3)) then RotatorCuff := 0; case RotatorCuff of 0: if tanTab[ySize - 1] < 30000 then for i := 0 to ySize - 1 do inc(tanTab[i], 500); 1: if tanTab[0] > -30000 then for i := 0 to ySize - 1 do dec(tanTab[i], 100 {500}); 2: r := (r - 32) and angleMask; 3: r := (r + 32) and angleMask; end; drawScene(x, y, z, r); MainForm.HiddenFX.Caption := 'FX: '; Application.ProcessMessages; end; until (bRotateImage = True); Mainform.DoImageDone; end; (***************************************************) (***************************************************) (*************************************************************) (*************************************************************) (*************************************************************) procedure B_3D_Map(N, L, VA, HA: Integer); {'---- 3-D SURFACE PLOT ---- File: 3DMAP DEF FNF(X,Y) = 80 + (X*Y*(X-Y)) ' Surface to be plotted} var maxcolx, maxrowy, IC, JC: Integer; X0, Y0, XM, YM: Integer; { :'---- Plot limits} I, J, CV, SV, CH, SH, XA, YA, X, X1, DX, DX1, STX, SX, STX1, Y, Y1, Y2, DY, DY1, STY, SY, STY1: Extended; TempColor: TColor; function FNF(A, B: Extended): Extended; begin FNF := (180 {(FYImageY div 2) } + (A * B * (A - B))); {height added + Surface to be plotted} end; begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); maxrowy := (FYImageY - 1); X0 := -4; Y0 := -4; XM := 5; YM := 5; { :'---- Plot limits} STX := (XM - X0) / N; STY := (YM - Y0) / N; {STX1 := STX;STY1 := STY;}{VA=Vertical angle} CV := COS(VA / 57.3); SV := SIN(VA / 57.3); CH := COS(HA / 57.3); {HA = Horiz view angle} SH := SIN(HA / 57.3); {init graphics }{ Start position} SY := 400; SX := 380; {SY := (FYImageY div 2); SX := (FYImageX div 2);} X := SX; X1 := X; DX1 := L * SH * 3; DX := L * CH * 3; Y := SY; Y1 := Y; DY1 := L * SV * CH; DY := L * SV * SH; Moveto(Round(X), Round(Y)); Lineto(Round(X + N * DX1), Round(Y - N * DY1)); I := X0; J := Y0; {STEP STX} { : PSET (X,Y)} for IC := 1 to N + 1 do begin XA := X; YA := Y; for JC := 1 to N + 1 do { STEP STY} begin Y2 := Y1 - CV * FNF(I, J); Moveto(Round(XA), Round(YA)); Lineto(Round(X1), Round(Y2)); XA := X1; YA := Y2; X1 := X1 + DX1; Y1 := Y1 - DY1; STY1 := JC * STY; J := Y0 + STY1; end; {NEXT J } J := Y0; X := X - DX; Y := Y - DY; X1 := X; Y1 := Y; STX1 := IC * STX; I := X0 + STX1; end; { NEXT I } X := SX; Y := SY; Moveto(Round(X), Round(Y)); Lineto(Round(X - N * DX), Round(Y - N * DY)); {STX1 := (XM-X0)/N;STY1 := (YM-Y0)/N; } I := X0; J := Y0; for JC := 1 to N + 1 do begin XA := X; YA := Y; X1 := X; Y1 := Y; for IC := 1 to N + 1 do {STEP STX} begin Y2 := Y1 - CV * FNF(I, J); Moveto(Round(XA), Round(YA)); Lineto(Round(X1), Round(Y2)); XA := X1; YA := Y2; X1 := X1 - DX; Y1 := Y1 - DY; STX1 := IC * STX; I := X0 + STX1; end; { NEXT I} I := X0; X := X + DX1; Y := Y - DY1; STY1 := JC * STY; J := Y0 + STY1; end; end; { NEXT J } end; { of Procedure } { of UNIT B_B3DMAP } (*************************************************************) procedure SinShadow(Plot_Angle, M_x, sign: Integer; View_Angle, Illum_Angle: Extended); var HM: array[0..4095] of Extended; {Plot_Angle, View_Angle, Illum_Angle, M_x,} X, Z, R, Y, H, HS: Extended; InSign, HalfX, HalfY, MiniY, maxcolx {,maxrowy}, I, XCount, ZCount, {C,} Y_Height: Integer; DoColor {,TempColor}: TColor; NS, TextS: string; begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); { maxrowy := (FYImageY-1);} MiniY := ((FYImageY - 1) div 6); HalfX := ((FYImageY - 1) div 2); HalfY := ((FYImageY - 1) div 2); if (sign < 0) then Insign := -1 else Insign := 1; {Brush.Color:=FBackGroundColor; Brush.Style:=bsSolid; FillRect(Rect(0,0,maxcolx,maxrowy)); TempColor:=RGB(255-GetRValue(FBackGroundColor), 255-GetGValue(FBackGroundColor), 255-GetBValue(FBackGroundColor)); Pen.Color := TempColor; Font.Color:= TempColor; Rectangle(0,0,maxcolx,maxrowy); MainForm.Show;} Z := 0.0; HS := 0.0; for I := 0 to maxcolx do HM[I] := 0.0; (* Plot_Angle := 90.0; { >90 makes steep walls of SIN <90 makes shallow} View_Angle := 3.0; {3.0;} {2.0 Makes an angle of 30 degrees} Illum_Angle := 0.3; {0.3;} {0.5 Makes an angle of 30 degrees} M_x := 20.0; { Magnification ratio ... see below } *){ V and I would make the plot location need to be changed} { LOOP} for Zcount := 0 to MiniY {74 479} do {STEP 15} begin X := 0; for Xcount := 0 to maxcolx do begin {R := ( (SQRT( ((POWER((X-320),2.0)) + (POWER((Z-240),2.0))) )) / M_x );} R := SQRT(sqr(X - HalfX) + sqr(Z - HalfY)) / M_x; { ? / Magnification ... how close to the apex } {higher M_x = closer ... less of whole wave is seen } { AT a V_Angle of 3.0 and a I_Angle of 0.3 } { M_x := } { 0.0 is seemingly flat with a vertical line as apex} { 20.0 is ok : the hump and 3 circling waves } { 30.0 is the hump and 2 circling waves } { 40.0 is the hump and its circling wave} { 60.0 is only the inner hump is seen } {GOTOXY(1,1); Writeln('R : ',R:40:20);} Y := Plot_Angle * InSign * (sin(R) / R); { Writeln('Y : ',Y:40:20);} H := Y + (Z / View_Angle); { Writeln('H : ',H:40:20); } { Readln; } HS := HS - Illum_Angle; if H < HS then DoColor := V1Color else begin DoColor := V2Color; HS := H; end; if H > HM[Xcount] then begin HM[Xcount] := H; Y_Height := ((HalfY - round(H)) * 2); Pixels[Xcount, Y_Height] := DoColor; end; X := X + 1.0; (* iF c=2 THEN BEGIN {DO NOTHING}END*); end; { NEXT X} HS := 0; Z := Z + 10.0 {10.0}; {15} end; { NEXT Z} {M_x := 20.0; Plot_Angle := 90.0; View_Angle := 3.0; Illum_Angle := 0.3;} str(Plot_Angle, NS); TextS := 'Plot angle: ' + NS; str(View_Angle: 6: 2, NS); TextS := TextS + ' View angle: ' + NS; str(Illum_Angle: 6: 2, NS); TextS := TextS + ' Illumination angle: ' + NS; str(M_x, NS); TextS := TextS + ' Magnification: ' + NS; TextOut(10, 10, TextS); { TextOut(10,470,'Plot = 90, View = 3, I = .3, M = 20');} end; end; { of procedure SinShadow } (*************************************************************) procedure CoSinShadow(Plot_Angle, M_x, sign: Integer; View_Angle, Illum_Angle: Extended); var HM: array[0..4095] of Extended; {Plot_Angle, View_Angle, Illum_Angle, M_x,} X, Z, R, Y, H, HS: Extended; Insign, HalfX, HalfY, MiniY, maxcolx {,maxrowy}, I, XCount, ZCount, {C,} Y_Height: Integer; DoColor {,TempColor}: TColor; NS, TextS: string; begin with MainForm.Image2.Canvas do begin maxcolx := (FYImageX - 1); { maxrowy := (FYImageY-1); } MiniY := ((FYImageY - 1) div 7); HalfX := ((FYImageY - 1) div 2); HalfY := ((FYImageY - 1) div 2); if (sign < 0) then Insign := -1 else Insign := 1; Z := 0.0; HS := 0.0; for I := 0 to maxcolx do HM[I] := 0.0; (* Plot_Angle := 90.0;{>90 makes steep walls of SIN <90 makes shallow} View_Angle := 3.0; {3.0;} {2.0 Makes an angle of 30 degrees} Illum_Angle := 0.3; {0.3;} {0.5 Makes an angle of 30 degrees} M_x := 20.0; { Magnification ratio ... see below } *){ V and I would make the plot location need to be changed} { LOOP} for Zcount := 0 to MiniY {74 479} do {STEP 15} begin X := 0; for Xcount := 0 to maxcolx do begin {R := ( (SQRT( ((POWER((X-320),2.0)) + (POWER((Z-240),2.0))) )) / M_x );} R := SQRT(sqr(X - HalfX) + sqr(Z - HalfY)) / M_x; { ? / Magnification ... how close to the apex } {higher M_x = closer ... less of whole wave is seen } { AT a V_Angle of 3.0 and a I_Angle of 0.3 } { M_x := } { 0.0 is seemingly flat with a vertical line as apex} { 20.0 is ok : the hump and 3 circling waves } { 30.0 is the hump and 2 circling waves } { 40.0 is the hump and its circling wave} { 60.0 is only the inner hump is seen } {GOTOXY(1,1); Writeln('R : ',R:40:20);} Y := Plot_Angle * Insign * (COS(R) / R); { Writeln('Y : ',Y:40:20);} H := Y + (Z / View_Angle); { Writeln('H : ',H:40:20); } { Readln; } HS := HS - Illum_Angle; if H < HS then DoColor := V1Color else begin DoColor := V2Color; HS := H; end; if H > HM[Xcount] then begin HM[Xcount] := H; Y_Height := ((HalfY - round(H)) * 2); Pixels[Xcount, Y_Height] := DoColor; end; X := X + 1.0; (* iF c=2 THEN BEGIN {DO NOTHING}END*); end; { NEXT X} HS := 0; Z := Z + 10.0 {10.0}; {15} end; { NEXT Z} {M_x := 20.0; Plot_Angle := 90.0; View_Angle := 3.0; Illum_Angle := 0.3;} str(Plot_Angle, NS); TextS := 'Plot angle: ' + NS; str(View_Angle: 6: 2, NS); TextS := TextS + ' View angle: ' + NS; str(Illum_Angle: 6: 2, NS); TextS := TextS + ' Illum angle: ' + NS; str(M_x, NS); TextS := TextS + ' Magnification: ' + NS; TextOut(10, 10, TextS); { TextOut(10,470,'Plot = 90, View = 3, I = .3, M = 20');} end; end; { of procedure CoSinShadow } (**************************************************) (**************************************************) (**************************************************) end.
unit uGameScreen.MainGame; {Главный экран - игровой, "в нем" пользователь играет} interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Contnrs, GLScene, GLObjects, GLWin32Viewer, GLVectorGeometry, GLVectorTypes, GLVectorFileObjects, GLFile3DS, GLFilePNG, GLMaterial, GLTexture, GLHUDObjects, GLRenderContextInfo, GLParticleFX, GLKeyboard, GLSkyDome, uGameScreen, uSpacefighter, uFighterControl.User, uDebugInfo, uAsteroidField, uSimplePhysics, uBulletAccum, uGameObject, uTarget, uFonts, uBoomAccum, uTutorial; const C_SCREEN_NAME = 'Main Game'; C_FADEIN_TIME = 2.5; {+debug} C_JUP_SCALE = 1; {-debug} type TdfMainGame = class (TdfGameScreen) private FRoot: TGLDummyCube; FHUDDummy: TGLDummyCube; FBlankBack: TGLHUDSprite; FDirectOpenGL: TGLDirectOpenGL; FMatLib: TGLMaterialLibrary; FViewerW, FViewerH: Integer; Ft: Double; FInGameMenu, FAlpha: TdfGameScreen; FSkyDome: TGLSkyDome; FPlayer: TdfSpaceFighter; FGameObjects: TObjectList; FUserControl: TdfUserControl; FAsteroidField: TdfAsteroidField; FJupiter: TGLPlane; FParticleRenderer: TGLParticleFXRenderer; FBooms, FBigBooms: TdfBoomAccum; {+debug} FTutorial: TdfTutorialMission; myTmpVec: TAffineVector; // FPlayerPosInd: Integer; //индекс строки дебага с позицией игрока procedure OnCollision(o1, o2: TdfPhys); procedure OnRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure OnGameObjectNotify(aObj: TdfGameObject; aAction: TdfGameObjectNotifyAction); procedure OnMissionEnd(); {-debug} procedure FadeInComplete(); procedure FadeOutComplete(); protected procedure FadeIn(deltaTime: Double); override; procedure FadeOut(deltaTime: Double); override; procedure SetStatus(const aStatus: TdfGameSceneStatus); override; public constructor Create(); override; destructor Destroy; override; procedure Load(); override; procedure Unload(); override; procedure Update(deltaTime: Double; X, Y: Integer); override; procedure SetGameScreens(aInGameMenu, aAlpha: TdfGameScreen); end; //======================================================================= implementation //======================================================================= uses uGLSceneObjects, uGameObjects; { TdfMainGameScreen } constructor TdfMainGame.Create(); var colorMin, colorMax: TVector3b; props: TdfBoomProperties; begin inherited; FName := C_SCREEN_NAME; FRoot := TGLDummyCube.CreateAsChild(dfGLSceneObjects.Scene.Objects); FRoot.Visible := False; FViewerW := dfGLSceneObjects.Viewer.Width; FViewerH := dfGLSceneObjects.Viewer.Height; FMatLib := dfGLSceneObjects.MatLibrary; FGameObjects := TObjectList.Create(False); FHUDDummy := TGLDummyCube.CreateAsChild(FRoot); colorMin.X := 128; colorMin.Y := 128; colorMin.Z := 128; colorMax.X := 255; colorMax.Y := 255; colorMax.Z := 255; FSkyDome := TGLSkyDome.CreateAsChild(FRoot); FSkyDome.Bands.Clear; FSkyDome.Stars.AddRandomStars(2000, colorMin, colorMax, 1.0, 10.0); FParticleRenderer := TGLParticleFXRenderer.CreateAsChild(FRoot); FParticleRenderer.Visible := False; dfGLSceneObjects.EnginesFX[0].Renderer := FParticleRenderer; dfGLSceneObjects.BoomFX[0].Renderer := FParticleRenderer; dfGLSceneObjects.BoomFX[1].Renderer := FParticleRenderer; FDirectOpenGL := TGLDirectOpenGL.CreateAsChild(FRoot); FDirectOpenGL.OnRender := Self.OnRender; FDirectOpenGL.Blend := False; dfPhysics := TdfSimplePhysics.Create(); dfPhysics.OnCollision := OnCollision; FPlayer := TdfSpaceFighter.CreateAsChild(FRoot); FPlayer.LoadFromFile('sfBuran2.ini'); FPlayer.GroupID := C_GROUP_ALLIES; FPlayer.Position.SetPoint(0, 0, 1); FUserControl := TdfUserControl.Create(FPlayer, FHUDDummy); FUserControl.Enabled := True; dfGameObjects.Player := FPlayer; dfGameObjects.UserControl := FUserControl; dfGameObjects.GameObjects := FGameObjects; // FPlayerPosInd := dfDebugInfo.AddNewString('Позиция игрока'); // dfDebugInfo.HideString(FPlayerPosInd); FAsteroidField := TdfAsteroidField.CreateAsChild(FRoot); FAsteroidField.SetMatLib(FMatLib); FAsteroidField.LoadFromFile('af1.ini', True); {+debug} FJupiter := TGLPlane.CreateAsChild(FRoot); FJupiter.Position.SetPoint(0, 0, 700); with FJupiter.Material do begin Texture.Image.LoadFromFile('data\planets\jupiter.png'); Texture.Enabled := True; Texture.TextureMode := tmReplace; BlendingMode := bmTransparency; MaterialOptions := [moNoLighting]; FJupiter.Width := Texture.Image.Width / C_JUP_SCALE; FJupiter.Height := Texture.Image.Height / C_JUP_SCALE; end; FJupiter.Material.DepthProperties.DepthWrite := False; {Рендерим юпитер вручную, так как сцена сортирует его по прозрачности и фактически игнорирует его порядок рендера для него, выводя его последним} FJupiter.Visible := False; FJupiter.Position.AsVector := FPlayer.AbsolutePosition; FJupiter.Position.Z := FJupiter.Position.Z + 700; FJupiter.Direction.AsAffineVector := VectorSubtract(FPlayer.Position.AsAffineVector, FJupiter.Position.AsAffineVector); {-debug} FBooms := TdfBoomAccum.CreateAsChild(FRoot); with props do begin sPositionDispersion := 1.2; sParticleInterval := 0.01; sVelocityDispersion := 10.2; end; FBooms.Init(10, dfGLSceneObjects.BoomFX[0], props); FBigBooms := TdfBoomAccum.CreateAsChild(FRoot); with props do begin sPositionDispersion := 2.5; sParticleInterval := 0.001; sVelocityDispersion := 20.2; end; FBigBooms.Init(5, dfGLSceneObjects.BoomFX[1], props); dfGameObjects.BigBoom := FBigBooms; FHUDDummy.MoveLast; Ft := 0; FInGameMenu := nil; FBlankBack := TGLHUDSprite.CreateAsChild(FRoot); FBlankBack.SetSize(FViewerW, FViewerH); FBlankBack.Position.SetPoint(FViewerW / 2, FViewerH / 2, 0.5); with FBlankBack.Material do begin Texture.Enabled := False; BlendingMode := bmTransparency; MaterialOptions := [moIgnoreFog, moNoLighting]; FrontProperties.Diffuse.SetColor(0, 0, 0, 1); end; FBlankBack.MoveFirst; FTutorial := TdfTutorialMission.Create(FRoot, FHUDDummy, GetFont(C_FONT_1)); FTutorial.OnGameObjectNotify := Self.OnGameObjectNotify; FTutorial.OnMissionEnd := Self.OnMissionEnd; end; destructor TdfMainGame.Destroy; begin FTutorial.Free; FUserControl.Free; FGameObjects.Free; FRoot.Free; dfPhysics.Free; inherited; end; procedure TdfMainGame.FadeIn(deltaTime: Double); begin Ft := Ft + deltaTime; FBlankBack.Material.FrontProperties.Diffuse.Alpha := 1 - Ft / C_FADEIN_TIME; if Ft >= C_FADEIN_TIME then inherited; end; procedure TdfMainGame.FadeInComplete; begin //* FBlankBack.Visible := False; FTutorial.Start; end; procedure TdfMainGame.FadeOut(deltaTime: Double); begin inherited; end; procedure TdfMainGame.FadeOutComplete; begin FRoot.Visible := False; Unload(); end; procedure TdfMainGame.Load; begin inherited; if FLoaded then Exit; dfDebugInfo.Visible := True; FPlayer.ResetParams(); FUserControl.ResetParams(); FParticleRenderer.MoveLast; FHUDDummy.MoveLast; FParticleRenderer.Visible := True; FLoaded := True; end; procedure TdfMainGame.OnCollision(o1, o2: TdfPhys); procedure BulletVSDestroyable(aBullet, aDestr: TdfPhys); var bul: TdfBullet; begin bul := TdfBullet(aBullet.Obj); if bul.Used then begin TdfGameObject(aDestr.Obj).TakeDamage(bul.Damage); FBooms.SetBoom(AffineVectorMake(bul.AbsolutePosition), 0.3); bul.Used := False; end; end; procedure BulletVSAsteroid(aBullet, aAster: TdfPhys); var bul: TdfBullet; begin bul := TdfBullet(aBullet.Obj); if bul.Used then begin bul.Used := False; FBooms.SetBoom(AffineVectorMake(bul.AbsolutePosition), 0.3); end; end; procedure DestrVSDestr(aDestr1, aDestr2: TdfPhys); begin dfPhysics.Bounce(aDestr1, aDestr2); dfPhysics.Bounce(aDestr2, aDestr1); //В альфа-версии не отнимаем здоровье за столкновение //Так как все сделано сферами и большинство столкновений неочевидно end; procedure DestrVSAsteroid(aDestr, aAster: TdfPhys); begin dfPhysics.Bounce(aDestr, aAster); //В альфа-версии не отнимаем здоровье за столкновение //Так как все сделано сферами и большинство столкновений неочевидно end; begin case o1.UserType of C_PHYS_BULLET: case o2.UserType of C_PHYS_BULLET: Exit; C_PHYS_DESTROYABLE: BulletVSDestroyable(o1, o2); C_PHYS_INVINCIBLE: Exit; C_PHYS_ASTEROID: BulletVSAsteroid(o1, o2); end; C_PHYS_DESTROYABLE: case o2.UserType of C_PHYS_BULLET: BulletVSDestroyable(o2, o1); //Удаляем пулю o2, у первого объекта отнимаем жизнь C_PHYS_DESTROYABLE: DestrVSDestr(o1, o2); //Отталкиваемся, отнимаем жизни o1, o2 C_PHYS_INVINCIBLE: Exit; //Ничего C_PHYS_ASTEROID: DestrVSAsteroid(o1, o2); //Отталкиваемся, отнимаем жизнь у o1 end; C_PHYS_INVINCIBLE: Exit; C_PHYS_ASTEROID: case o2.UserType of C_PHYS_BULLET: BulletVSAsteroid(o2, o1); //Уничтожаем пулю C_PHYS_DESTROYABLE: DestrVSAsteroid(o2, o1); //отталкиваем о2, отнимаем жизнь C_PHYS_INVINCIBLE: Exit; //Ничего C_PHYS_ASTEROID: Exit; //Ничего end; end; end; procedure TdfMainGame.OnGameObjectNotify(aObj: TdfGameObject; aAction: TdfGameObjectNotifyAction); begin case aAction of naAdded: FPlayer.ObjectsAround.Add(aObj); naRemoved: FPlayer.ObjectsAround.Remove(aObj); naChanged: ; end; end; procedure TdfMainGame.OnMissionEnd; begin OnNotify(FAlpha, naShowModal); end; procedure TdfMainGame.OnRender(Sender: TObject; var rci: TGLRenderContextInfo); begin FJupiter.Render(rci); end; procedure TdfMainGame.SetGameScreens(aInGameMenu, aAlpha: TdfGameScreen); begin FInGameMenu := aInGameMenu; FAlpha := aAlpha; end; procedure TdfMainGame.SetStatus(const aStatus: TdfGameSceneStatus); begin inherited; case aStatus of gssNone : Exit; gssReady : Exit; gssFadeIn : begin Load(); FRoot.Visible := True; FBlankBack.Visible := True; Ft := 0; end; gssFadeInComplete : FadeInComplete(); gssFadeOut : Ft := 0; gssFadeOutComplete: FadeOutComplete(); gssPaused : Exit; end; end; procedure TdfMainGame.Unload; var i: Integer; begin inherited; if not FLoaded then Exit; // dfDebugInfo.Visible := False; FTutorial.Stop; FParticleRenderer.Visible := False; for i := 0 to FPlayer.WeaponsCount - 1 do FPlayer.Weapons[i].ReleaseAllBullets(); //* FLoaded := False; end; procedure TdfMainGame.Update(deltaTime: Double; X, Y: Integer); begin inherited; case FStatus of gssNone: Exit; gssFadeIn: FadeIn(deltaTime); gssFadeInComplete: Exit; gssFadeOut: FadeOut(deltaTime); gssFadeOutComplete: Exit; gssPaused: Exit; gssReady: begin dfPhysics.Update(deltaTime); FTutorial.Update(deltaTime); // dfDebugInfo.UpdateParam(FPlayerPosInd, FPlayer.Position.AsVector); FPlayer.Update(deltaTime); FUserControl.Update(deltaTime, X, Y); myTmpVec := FPlayer.Up.AsAffineVector; myTmpVec.Z := 0; FDirectOpenGL.Up.AsAffineVector := myTmpVec; FJupiter.Direction.AsAffineVector := VectorSubtract(FPlayer.Position.AsAffineVector, FJupiter.Position.AsAffineVector); FJupiter.Position.AsVector := FPlayer.AbsolutePosition; FJupiter.Position.Z := FJupiter.Position.Z + 700; FAsteroidField.UpdateField(deltaTime); FBooms.Update(deltaTime); FBigBooms.Update(deltaTime); if IsKeyDown(VK_ESCAPE) then OnNotify(FInGameMenu, naShowModal); // if IsKeyDown(VK_RETURN) then // OnNotify(FAlpha, naShowModal); end; end; end; end.
unit UCountSystems; interface uses UTypes; { Переводит число из одной системы счисления во все другие } procedure convertToCountSystems(var number: TNumber; countSystem: TCountSystem); implementation uses SysUtils; const { Таблицы перевода } BIN_HEX_CONVERT: array [1..2, 1..16] of String = (('0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110' ,'1111'), ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')); BIN_OCT_CONVERT: array [1..2, 1..8] of String = (('000', '001', '010', '011', '100', '101', '110', '111'), ('0', '1', '2', '3', '4', '5', '6', '7')); { Переводит двоичное число в шестнадцатеричное } function binToHex(bin: String): String; var i, j: Integer; tempStr: String; begin while length(bin) mod 4 <> 0 do insert('0', bin, 1); i := 1; result := ''; while i <= length(bin) do begin tempStr := copy(bin, i, 4); j := 1; while BIN_HEX_CONVERT[1, j] <> tempStr do inc(j); result := result + BIN_HEX_CONVERT[2, j]; inc(i, 4); end; end; { Переводит двоичное число в десятичное } function binToDec(bin: String): String; var pow, res: int64; i: Integer; begin res := 0; pow := 1; for i := length(bin) downto 1 do begin if bin[i] = '1' then res := res + pow; pow := pow * 2; end; result := IntToStr(res); if result = '0' then result := ''; end; { Переводит двоичное число в восьмеричное } function binToOct(bin: String): String; var i, j: Integer; tempStr: String; begin while length(bin) mod 3 <> 0 do insert('0', bin, 1); i := 1; result := ''; while i <= length(bin) do begin tempStr := copy(bin, i, 3); j := 1; while BIN_OCT_CONVERT[1, j] <> tempStr do inc(j); result := result + BIN_OCT_CONVERT[2, j]; inc(i, 3); end; end; { Переводит шестнадцатеричное число в двоичное } function hexToBin(hex: String): String; var i, j: Integer; begin for i := 1 to length(hex) do begin j := 1; while BIN_HEX_CONVERT[2, j] <> hex[i] do inc(j); result := result + BIN_HEX_CONVERT[1, j]; end; while (length(result) >= 1) and (result[1] = '0') do delete(result, 1, 1); end; { Переводит восьмеричное число в двоичное } function octToBin(oct: String): String; var i, j: Integer; begin for i := 1 to length(oct) do begin j := 1; while BIN_OCT_CONVERT[2, j] <> oct[i] do inc(j); result := result + BIN_OCT_CONVERT[1, j]; end; while (length(result) >= 1) and (result[1] = '0') do delete(result, 1, 1); end; { Переводит десятичное число в двоичное } function decToBin(dec: String): String; var res: int64; begin if length(dec) > 0 then res := StrToInt64(dec) else res := 0; result := ''; while res <> 0 do begin if res mod 2 = 0 then result := '0' + result else result := '1' + result; res := res div 2; end; end; { Переводит число из одной системы счисления во все другие } procedure convertToCountSystems(var number: TNumber; countSystem: TCountSystem); begin case countSystem of csHEX: begin number.bin := hexToBin(number.hex); number.dec := binToDec(number.bin); number.oct := binToOct(number.bin); end; csDEC: begin number.bin := decToBin(number.dec); number.hex := binToHex(number.bin); number.oct := binToOct(number.bin); end; csOCT: begin number.bin := octToBin(number.oct); number.hex := binToHex(number.bin); number.dec := binToDec(number.bin); end; csBIN: begin number.hex := binToHex(number.bin); number.dec := binToDec(number.bin); number.oct := binToOct(number.bin); end; end; end; end.
{ *************************************************************************** } { } { MVCBr é o resultado de esforços de um grupo } { } { Copyright (C) 2017 MVCBr } { } { amarildo lacerda } { http://www.tireideletra.com.br } { } { } { *************************************************************************** } { } { 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. } { } { *************************************************************************** } /// <summary> /// Unit MVCBr.View implementas os objeto Factory para a camada de visualização /// </summary> unit MVCBr.View; interface uses {$ifdef LINUX} {$else} {$IFDEF FMX} FMX.Forms, {$ELSE} VCL.Forms, {$ENDIF}{$endif} system.Classes, system.SysUtils, system.Rtti, MVCBr.Model, MVCBr.Interf, System.JSON; type TViewFactoryClass = class of TViewFactory; /// <summary> /// TViewFactory é um Factory abstrato a ser utilizado com finalidades genericas /// sem ligação direta com um visualizador /// </summary> TViewFactory = class(TMVCFactoryAbstract, IView) private FText: string; FController: IController; FViewModel: IViewModel; procedure SetController(const AController: IController); function GetTitle: String; procedure SetTitle(Const AText: String); protected function Controller(const AController: IController): IView; virtual; function This: TObject; virtual; public procedure Init; virtual; function ViewEvent(AMessage: string;var AHandled: boolean): IView; overload;virtual; function ViewEvent(AMessage: TJsonValue;var AHandled: boolean): IView;overload;virtual; Procedure DoCommand(ACommand: string; const AArgs: array of TValue); virtual; function ShowView(const AProc: TProc<IView>): Integer; overload; virtual; function ShowView(): IView; overload; virtual; function ShowView(const AProc: TProc<IView>; AShowModal: boolean): IView; overload; virtual; function ShowView(const AProcBeforeShow: TProc<IView>; const AProcAfterShow:TProc<IView>) : IView; overload; virtual; function GetViewModel: IViewModel; virtual; procedure SetViewModel(const AViewModel: IViewModel); virtual; function GetModel(AII:TGuid):IModel; function UpdateView: IView; virtual; function GetController: IController; function ViewModel(const AModel: IViewModel): IView; property Text: string read GetTitle write SetTitle; end; implementation { TViewFactory } function TViewFactory.Controller(const AController: IController): IView; begin result := self; SetController(AController); end; procedure TViewFactory.DoCommand(ACommand: string; const AArgs: array of TValue); begin end; function TViewFactory.ViewEvent(AMessage: string;var AHandled: boolean): IView; begin result := self; end; function TViewFactory.GetController: IController; begin result := FController; end; function TViewFactory.GetModel(AII: TGuid): IModel; begin result := FController.GetModel(AII,result); end; function TViewFactory.GetTitle: String; begin result := FText; end; function TViewFactory.GetViewModel: IViewModel; begin result := FViewModel; end; procedure TViewFactory.Init; begin end; function TViewFactory.ViewEvent(AMessage: TJsonValue;var AHandled: boolean): IView; begin end; function TViewFactory.ViewModel(const AModel: IViewModel): IView; begin result := self; FViewModel := AModel; end; { class function TViewFactory.New(AClass: TViewFactoryClass; const AController: IController): IView; var obj:TViewFactory; begin obj := AClass.Create; obj.Controller(AController); supports(obj,IView,result); end; } procedure TViewFactory.SetController(const AController: IController); begin FController := AController; end; procedure TViewFactory.SetTitle(const AText: String); begin FText := AText; end; procedure TViewFactory.SetViewModel(const AViewModel: IViewModel); begin FViewModel := AViewModel; end; function TViewFactory.ShowView(const AProcBeforeShow, AProcAfterShow: TProc<IView>): IView; begin result := self; ShowView(AProcBeforeShow); end; function TViewFactory.ShowView: IView; begin result := self; ShowView(nil); end; function TViewFactory.ShowView(const AProc: TProc<IView>): Integer; begin result := -1; // implements on overrided code if assigned(AProc) then AProc(self); result := 0; end; function TViewFactory.This: TObject; begin result := self; end; function TViewFactory.UpdateView: IView; begin result := self; end; function TViewFactory.ShowView(const AProc: TProc<IView>; AShowModal: boolean): IView; begin result := self; ShowView(AProc); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // unit VXS.FileJPEG; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.VectorGeometry, VXS.Context, VXS.Graphics, VXS.TextureFormat, VXS.ApplicationFileIO; type TVXJPEGImage = class(TVXBaseImage) private FAbortLoading: boolean; FDivScale: longword; FDither: boolean; FSmoothing: boolean; FProgressiveEncoding: boolean; procedure SetSmoothing(const AValue: boolean); public constructor Create; override; class function Capabilities: TVXDataFileCapabilities; override; procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; { Assigns from any Texture. } procedure AssignFromTexture(textureContext: TVXContext; const textureHandle: GLuint; textureTarget: TVXTextureTarget; const CurrentFormat: boolean; const intFormat: TVXInternalFormat); reintroduce; property DivScale: longword read FDivScale write FDivScale; property Dither: boolean read FDither write FDither; property Smoothing: boolean read FSmoothing write SetSmoothing; property ProgressiveEncoding: boolean read FProgressiveEncoding; end; // =================================================================== implementation // =================================================================== // ------------------ // ------------------ TVXJPEGImage ------------------ // ------------------ constructor TVXJPEGImage.Create; begin inherited; FAbortLoading := False; FDivScale := 1; FDither := False; end; procedure TVXJPEGImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(filename) then begin fs := CreateFileStream(filename, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; procedure TVXJPEGImage.SaveToFile(const filename: string); var fs: TStream; begin fs := CreateFileStream(filename, fmOpenWrite or fmCreate); try SaveToStream(fs); finally fs.Free; end; ResourceName := filename; end; procedure TVXJPEGImage.LoadFromStream(stream: TStream); begin // Do nothing end; procedure TVXJPEGImage.SaveToStream(stream: TStream); begin // Do nothing end; procedure TVXJPEGImage.AssignFromTexture(textureContext: TVXContext; const textureHandle: GLuint; textureTarget: TVXTextureTarget; const CurrentFormat: boolean; const intFormat: TVXInternalFormat); begin // end; procedure TVXJPEGImage.SetSmoothing(const AValue: boolean); begin if FSmoothing <> AValue then FSmoothing := AValue; end; class function TVXJPEGImage.Capabilities: TVXDataFileCapabilities; begin Result := [dfcRead { , dfcWrite } ]; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ { Register this Fileformat-Handler } RegisterRasterFormat('jpg', 'Joint Photographic Experts Group Image', TVXJPEGImage); RegisterRasterFormat('jpeg', 'Joint Photographic Experts Group Image', TVXJPEGImage); RegisterRasterFormat('jpe', 'Joint Photographic Experts Group Image', TVXJPEGImage); end.
{******************************************************************************} { } { Delphi OPENSSL Library } { Copyright (c) 2018 Luca Minuti } { https://bitbucket.org/lminuti/delphi-openssl } { } {******************************************************************************} { } { 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 OpenSSL.RandUtils; // https://www.openssl.org/docs/man1.1.0/crypto/RAND_load_file.html // https://www.openssl.org/docs/man1.1.1/man3/RAND_poll.html // https://www.openssl.org/docs/man1.1.0/crypto/RAND_bytes.html interface uses System.SysUtils; type TRandUtil = class(TObject) public // Calling InitPool is not necessary, because the DRBG polls the entropy source automatically class procedure InitPool; // true if the CSPRNG has been seeded with enough data class function Initialized: Boolean; // reads a number of bytes from file filename and adds them to the PRNG // if max_bytes is -1, the complete file is read // returns the number of bytes read class function LoadSeedFromFile(const FileName: string; MaxBytes: Integer = -1): Integer; // writes a number of random bytes (currently 1024) to file filename // which can be used to initialize the PRNG by calling RAND_load_file() in a later session // returns the number of bytes written class function SaveSeedToFile(const FileName: string): Integer; // generates a default path for the random seed file class function GetDefaultSeedFileName: string; // Generate a random number class function GetRandomBytes(const Size: Integer): TBytes; // Generate a cryptographically secure random number class function GetPseudoRandomBytes(const Size: Integer): TBytes; end; implementation uses OpenSSL.Api_11, OpenSSL.Core; { TRandUtil } class function TRandUtil.GetDefaultSeedFileName: string; const MaxLen = 255; var Filename: AnsiString; FilenameP: PAnsiChar; begin SetLength(Filename, MaxLen); FilenameP := RAND_file_name(@Filename[1], MaxLen); if not Assigned(FilenameP) then RaiseOpenSSLError('RAND_file_name error'); Result := string(AnsiString(PAnsiChar(Filename))); end; class function TRandUtil.GetPseudoRandomBytes(const Size: Integer): TBytes; var ErrCode: Integer; begin SetLength(Result, Size); ErrCode := RAND_pseudo_bytes(@Result[0], Size); if ErrCode = -1 then RaiseOpenSSLError('RAND method not supported'); if ErrCode = 0 then RaiseOpenSSLError('RAND_pseudo_bytes error'); end; class function TRandUtil.GetRandomBytes(const Size: Integer): TBytes; var ErrCode: Integer; begin SetLength(Result, Size); ErrCode := RAND_bytes(@Result[0], Size); if ErrCode = -1 then RaiseOpenSSLError('RAND method not supported'); if ErrCode = 0 then RaiseOpenSSLError('RAND_bytes error'); end; class function TRandUtil.Initialized: Boolean; var ErrCode: Integer; begin ErrCode := RAND_status(); Result := ErrCode = 1; end; class procedure TRandUtil.InitPool; var ErrCode: Integer; begin ErrCode := RAND_poll(); if ErrCode <> 1 then RaiseOpenSSLError('RAND_poll error'); end; class function TRandUtil.LoadSeedFromFile(const FileName: string; MaxBytes: Integer): Integer; begin Result := RAND_load_file(@FileName[1], MaxBytes); if Result < 0 then RaiseOpenSSLError('RAND_load_file error'); end; class function TRandUtil.SaveSeedToFile(const FileName: string): Integer; begin Result := RAND_write_file(@FileName[1]); if Result < 0 then RaiseOpenSSLError('RAND_write_file error'); end; end.
unit Unit1; interface uses Windows, Messages, System.SysUtils, System.Variants, System.Math, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GLCadencer, GLWin32Viewer, GLScene, GLObjects, GLVectorGeometry, GLKeyboard, GLTerrainRenderer, GLGeomObjects, GLMultiPolygon, GLExtrusion, GLAsyncTimer, GLHeightData, GLCoordinates, GLCrossPlatform, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; vp: TGLSceneViewer; GLCadencer1: TGLCadencer; cam: TGLCamera; dc_world: TGLDummyCube; dc_player: TGLDummyCube; dc_cam: TGLDummyCube; dc_target: TGLDummyCube; ter: TGLTerrainRenderer; GLCustomHDS1: TGLCustomHDS; GLExtrusionSolid1: TGLExtrusionSolid; targ: TGLSprite; AsyncTimer1: TGLAsyncTimer; GLCamera1: TGLCamera; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure GLCustomHDS1StartPreparingData(heightData: TGLHeightData); procedure AsyncTimer1Timer(Sender: TObject); private public end; var Form1: TForm1; _m: array of array of single; dx, dz: Double; implementation {$R *.dfm} procedure AreaInit; var a1, a2, a3, x, y, d: integer; b1: single; begin SetLength(_m, 256, 256); randomize; // generate landscape [fractal] for a1 := 0 to 7 do for a2 := 0 to 7 do _m[a1 shl 5, a2 shl 5] := (random - 0.5) * 256; for a3 := 0 to 4 do begin d := 16 shr a3; for a1 := 0 to (1 shl (a3 + 3)) - 1 do for a2 := 0 to (1 shl (a3 + 3)) - 1 do begin b1 := (random - 0.5) * (128 shr a3); x := d + a1 shl (5 - a3); y := a2 shl (5 - a3); _m[x, y] := (_m[x - d, y] + _m[(x + d) and 255, y]) / 2 + b1; b1 := (random - 0.5) * (128 shr a3); x := a1 shl (5 - a3); y := d + a2 shl (5 - a3); _m[x, y] := (_m[x, y - d] + _m[x, (y + d) and 255]) / 2 + b1; b1 := (random - 0.5) * (128 shr a3); x := d + a1 shl (5 - a3); y := d + a2 shl (5 - a3); _m[x, y] := (_m[x - d, y - d] + _m[x - d, (y + d) and 255] + _m[(x + d) and 255, y - d] + _m[(x + d) and 255, (y + d) and 255] ) / 4 + b1; end; end; // turn to planet type for a1 := 0 to 255 do for a2 := 0 to 255 do _m[a1, a2] := power(1.011, power((_m[a1, a2] + 384) * 0.101, 1.61)); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin AsyncTimer1.Enabled := false; GLCadencer1.Enabled := false; vp.Free; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var v1: TVector; b1, b2: single; begin // -- Y test -------------------------------------------------------------------- v1 := VectorSubtract(dc_target.AbsolutePosition, VectorScale(dc_target.AbsoluteDirection, 25)); dc_target.Position.y := dc_target.Position.y + (-dc_target.Position.y + 10 + ter.InterpolatedHeight(v1)) * deltaTime; // -- move ---------------------------------------------------------------------- if iskeydown(vk_up) and (dz < 1) then dz := dz + deltaTime / (0.1 + dz * dz) else dz := dz * (1 - deltaTime * 2); dc_target.Move(-dz * deltaTime * 40); // -- turn ---------------------------------------------------------------------- if iskeydown(vk_left) and (dx < 2) then dx := dx + deltaTime / (0.1 + dx * dx / 2); if iskeydown(vk_right) and (dx > -2) then dx := dx - deltaTime / (0.1 + dx * dx / 2); dx := dx * (1 - deltaTime); dc_target.Turn(-dx * deltaTime * 50); dc_player.AbsoluteDirection := dc_target.AbsoluteDirection; dc_player.RollAngle := dx * 45; // -- camera & player correction (blackmagic)------------------------------------ b1 := dc_cam.DistanceTo(dc_target.AbsolutePosition); if abs(b1 - 4) > 0.1 then dc_cam.Position.Translate (VectorScale(VectorSubtract(dc_target.AbsolutePosition, dc_cam.AbsolutePosition), (b1 - 4) * deltaTime)); if abs(dc_cam.Position.y - dc_target.Position.y - 0.5) > 0.1 then dc_cam.Position.y := dc_cam.Position.y - (dc_cam.Position.y - dc_target.Position.y - 0.5) * deltaTime * 10; b1 := dc_player.DistanceTo(dc_target.AbsolutePosition); if abs(b1 - 1) > 0.1 then dc_player.Position.Translate (VectorScale(VectorSubtract(dc_target.AbsolutePosition, dc_player.AbsolutePosition), (b1 - 1) * deltaTime * 2)); dc_cam.PointTo(dc_target.AbsolutePosition, vectormake(0, 1, 0)); // -- update scene -------------------------------------------------------------- vp.Invalidate; // -- close if press Escape ----------------------------------------------------- if iskeydown(vk_escape) then close; end; procedure TForm1.FormCreate(Sender: TObject); begin AreaInit; end; procedure TForm1.GLCustomHDS1StartPreparingData(heightData: TGLHeightData); var a1, a2: integer; ln: PSingleArray; begin heightData.DataState := hdsPreparing; with heightData do begin Allocate(hdtSingle); for a1 := ytop to ytop + size - 1 do begin ln := SingleRaster[a1 - ytop]; for a2 := xleft to xleft + size - 1 do ln[a2 - xleft] := _m[a2 and 255, a1 and 255] * 0.1; end; end; end; procedure TForm1.AsyncTimer1Timer(Sender: TObject); begin caption := vp.FramesPerSecondText(2); vp.ResetPerformanceMonitor; end; end.
unit UDOleObjects; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32; type TCrpeOleObjectsDlg = class(TForm) pnlOleObjects: TPanel; lblNumber: TLabel; lbNumbers: TListBox; editCount: TEdit; lblCount: TLabel; btnOk: TButton; btnClear: TButton; lblOleType: TLabel; lblUpdateType: TLabel; lblLinkSource: TLabel; editLinkSource: TEdit; rgUnits: TRadioGroup; lblTop: TLabel; lblLeft: TLabel; lblWidth: TLabel; lblHeight: TLabel; editTop: TEdit; editLeft: TEdit; editWidth: TEdit; editHeight: TEdit; lblSection: TLabel; cbSection: TComboBox; btnBorder: TButton; btnFormat: TButton; editOleType: TEdit; editUpdateType: TEdit; procedure btnClearClick(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateOleObjects; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure EditSizeEnter(Sender: TObject); procedure EditSizeExit(Sender: TObject); procedure cbSectionChange(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure rgUnitsClick(Sender: TObject); procedure btnFormatClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; OIndex : smallint; PrevSize : string; end; var CrpeOleObjectsDlg: TCrpeOleObjectsDlg; bOleObjects : boolean; implementation {$R *.DFM} uses TypInfo, UCrpeUtl, UDBorder, UDFormat; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.FormCreate(Sender: TObject); begin bOleObjects := True; LoadFormPos(Self); btnOk.Tag := 1; editLinkSource.Tag := 1; editOleType.Tag := 1; editUpdateType.Tag := 1; OIndex := -1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.FormShow(Sender: TObject); begin UpdateOleObjects; end; {------------------------------------------------------------------------------} { UpdateOleObjects } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.UpdateOleObjects; var OnOff : boolean; i : integer; begin OIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin OnOff := (Cr.OleObjects.Count > 0); {Get OleObjects Index} if OnOff then begin if Cr.OleObjects.ItemIndex > -1 then OIndex := Cr.OleObjects.ItemIndex else OIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff then begin {Fill Section ComboBox} cbSection.Clear; cbSection.Items.AddStrings(Cr.SectionFormat.Names); {Fill Numbers ListBox} for i := 0 to Cr.OleObjects.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.OleObjects.Count); lbNumbers.ItemIndex := OIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.lbNumbersClick(Sender: TObject); var OnOff : Boolean; begin OIndex := lbNumbers.ItemIndex; OnOff := (Cr.OleObjects[OIndex].Handle <> 0); btnBorder.Enabled := OnOff; btnFormat.Enabled := OnOff; editLinkSource.Text := Cr.OleObjects.Item.LinkSource; editOleType.Text := GetEnumName(TypeInfo(TCrOleObjectType), Ord(Cr.OleObjects.Item.OleType)); editUpdateType.Text := GetEnumName(TypeInfo(TCrOleUpdateType), Ord(Cr.OleObjects.Item.UpdateType)); cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.OleObjects.Item.Section); rgUnitsClick(Self); end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editTop.Text := TwipsToInchesStr(Cr.OleObjects.Item.Top); editWidth.Text := TwipsToInchesStr(Cr.OleObjects.Item.Width); editLeft.Text := TwipsToInchesStr(Cr.OleObjects.Item.Left); editHeight.Text := TwipsToInchesStr(Cr.OleObjects.Item.Height); end else {twips} begin editTop.Text := IntToStr(Cr.OleObjects.Item.Top); editWidth.Text := IntToStr(Cr.OleObjects.Item.Width); editLeft.Text := IntToStr(Cr.OleObjects.Item.Left); editHeight.Text := IntToStr(Cr.OleObjects.Item.Height); end; end; {------------------------------------------------------------------------------} { editSizeEnter } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.EditSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { EditSizeExit } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.EditSizeExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.OleObjects.Item.Top := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.OleObjects.Item.Width := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.OleObjects.Item.Left := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.OleObjects.Item.Height := InchesStrToTwips(TEdit(Sender).Text); UpdateOleObjects; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.OleObjects.Item.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.OleObjects.Item.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.OleObjects.Item.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.OleObjects.Item.Height := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { cbSectionChange } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.cbSectionChange(Sender: TObject); begin Cr.OleObjects.Item.Section := cbSection.Items[cbSection.ItemIndex]; end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.OleObjects.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.OleObjects.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.btnClearClick(Sender: TObject); begin Cr.OleObjects.Clear; UpdateOleObjects; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateOleObjects call} if (not IsStrEmpty(Cr.ReportName)) and (OIndex > -1) then begin editSizeExit(editTop); editSizeExit(editLeft); editSizeExit(editWidth); editSizeExit(editHeight); end; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeOleObjectsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bOleObjects := False; Release; end; end.
{------------------------------------ 功能说明:实现IDBAccess接口 创建日期:2014/08/04 作者:mx 版权:mx -------------------------------------} unit uDBAccess; interface uses SysUtils, DB, DBClient, Dialogs, uDBIntf, uSvcInfoIntf, uParamObject, WMServer_Intf; type TDBOperation = class(TInterfacedObject, IDBAccess, ISvcInfo) private FWMServer: IWMFBData; protected {IDBOperation} procedure QuerySQL(const ASQLStr: string; AQueryData: TClientDataSet); function OpenSQL(const ASQLStr: AnsiString): Integer; function GetMoudleNoSQL(const AMoudleNo: Integer): string; // 执行一个存储过程, 不返回数据集 function ExecuteProcByName(AProcName: string; AParamName: array of string; AParamValue: array of OleVariant; OutputParams: TParamObject = nil): Integer; overload; function ExecuteProcByName(AProcName: string; AInParam: TParamObject = nil; AOutParams: TParamObject = nil): Integer; overload; // 执行一个存储过程, 回数据集 function ExecuteProcBackData(AProcName: string; AInParam: TParamObject = nil; AOutParams: TParamObject = nil; ABackData: TClientDataSet = nil): Integer; overload; function Login(AUserName, AUserPSW: string; var AMsg: string): Integer; //登陆用户 {ISvcInfo} function GetModuleName: string; function GetTitle: string; function GetVersion: string; function GetComments: string; public constructor Create; destructor Destroy; override; end; implementation uses uSysSvc, uSysFactory, uRDM, uOtherIntf, uPubFun, variants; { TDBOperation } function TDBOperation.GetComments: string; begin Result := '用于数据库操作'; end; function TDBOperation.GetModuleName: string; begin Result := ExtractFileName(SysUtils.GetModuleName(HInstance)); end; function TDBOperation.GetTitle: string; begin Result := '数据库操作接口(IDBAccess)'; end; function TDBOperation.GetVersion: string; begin Result := '20141203.001'; end; procedure TDBOperation.QuerySQL(const ASQLStr: string; AQueryData: TClientDataSet); var aBackDate: OleVariant; begin if Trim(ASQLStr) = EmptyStr then Exit; try FWMServer.QuerySQL(ASQLStr, aBackDate); AQueryData.Data := aBackDate; except raise(SysService as IExManagement).CreateSysEx('执行SQL<' + Trim(ASQLStr) + '>错误'); end; end; constructor TDBOperation.Create; var Obj: TObject; begin DMWMServer := TDMWMServer.Create(nil); FWMServer := DMWMServer.RORemoteService as IWMFBData; end; destructor TDBOperation.Destroy; begin DMWMServer.Free; inherited; end; procedure CreateDBOperation(out anInstance: IInterface); begin anInstance := TDBOperation.Create; end; function TDBOperation.GetMoudleNoSQL(const AMoudleNo: Integer): string; var aSQL: string; begin Result := ''; end; function TDBOperation.ExecuteProcByName(AProcName: string; AParamName: array of string; AParamValue: array of OleVariant; OutputParams: TParamObject): Integer; begin end; function TDBOperation.ExecuteProcByName(AProcName: string; AInParam, AOutParams: TParamObject): Integer; var aInParamJson, aOutParam: OleVariant; aBackParams: TParams; i: Integer; aWriteLogMsg: string; begin try aInParamJson := StrToOleData(PackageToJson(AProcName, ParamObjectToJson(AInParam)).AsString); Result := FWMServer.ExecuteProc(aInParamJson, aOutParam); if Assigned(AOutParams) then begin aBackParams := TParams.Create; try UnpackParams(aOutParam, aBackParams); with aBackParams do begin for i := 0 to Count - 1 do begin AInParam.Add(Items[i].Name, Items[i].Value); end; end; finally FreeAndNil(aBackParams); end; end; except on E: Exception do begin aWriteLogMsg := StringFormat('存储过程[%s],参数[%s],错误信息[%s]', [AProcName, ParamObjectToString(AInParam), E.Message]); raise (SysService as IExManagement).CreateFunEx('执行存储过程出错!', aWriteLogMsg); end; end; end; function TDBOperation.ExecuteProcBackData(AProcName: string; AInParam: TParamObject; AOutParams: TParamObject; ABackData: TClientDataSet): Integer; var aInParamJson, aBackDate: OleVariant; aBackParams: TParams; i: Integer; var aWriteLogMsg: string; begin try aInParamJson := StrToOleData(PackageToJson(AProcName, ParamObjectToJson(AInParam)).AsString); Result := FWMServer.ExecuteProcBackData(aInParamJson, aBackDate, aBackDate); ABackData.Data := aBackDate; if Assigned(AOutParams) then begin aBackParams := TParams.Create; try UnpackParams(aBackDate, aBackParams); with aBackParams do begin for i := 0 to Count - 1 do begin AOutParams.Add(Items[i].Name, Items[i].Value); end; end; finally FreeAndNil(aBackParams); end; end; except on E: Exception do begin aWriteLogMsg := StringFormat('存储过程[%s],参数[%s],错误信息[%s]', [AProcName, ParamObjectToString(AInParam), E.Message]); raise (SysService as IExManagement).CreateFunEx('执行存储过程出错!', aWriteLogMsg); end; end; end; function TDBOperation.OpenSQL(const ASQLStr: AnsiString): Integer; begin Result := -1; if Trim(ASQLStr) = EmptyStr then Exit; try Result := FWMServer.OpenSQL(ASQLStr); except raise(SysService as IExManagement).CreateSysEx('执行SQL<' + Trim(ASQLStr) + '>错误'); end; end; function TDBOperation.Login(AUserName, AUserPSW: string; var AMsg: string): Integer; begin Result := -999; if (Trim(AUserName) = EmptyStr) OR (Trim(AUserPSW) = EmptyStr) then Exit; try Result := FWMServer.Login(AUserName, AUserPSW, AMsg); except raise(SysService as IExManagement).CreateFunEx('登陆账号错误,用户名:' + AUserName); end; end; initialization TSingletonFactory.Create(IDBAccess, @CreateDBOperation); finalization end.
//****************************************************************************** // Пакет для редактирования записи // из таблицы Z_Current - зарплатные текущие выплаты // Параметры: AOwner - компонент от которого создается форма для редактирования // DB_Handle - база для подключения // AZControlFormStyle - тип формы: редактрирование, удаление, добавление, просмотр // AID - если добавление, то RMoving, иначе ID_Current //****************************************************************************** unit Current_Ctrl_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit, cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox, StdCtrls, cxButtons, Registry, PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr, cxDBEdit, cxSpinEdit, cxMemo, Dates, cxCalc, FIBQuery, pFIBQuery, pFIBStoredProc, gr_uMessage, ActnList, gr_uCommonConsts, Current_Ctrl_DM, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxGridTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, Unit_NumericConsts, dxStatusBar, Menus, gr_uCommonProc, cxGridBandedTableView, cxGridDBBandedTableView, ZProc, gr_dmCommonStyles, cxCheckBox; type TFgrCurrentCtrl = class(TForm) YesBtn: TcxButton; CancelBtn: TcxButton; BoxMain: TcxGroupBox; PrikazBox: TcxGroupBox; EditPrikaz: TcxMaskEdit; LabelPrikaz: TcxLabel; LabelPeriod: TcxLabel; MonthesList: TcxComboBox; YearSpinEdit: TcxSpinEdit; LabelSumma: TcxLabel; EditSumma: TcxMaskEdit; Bevel2: TBevel; IdMovingBox: TcxGroupBox; LabelManMoving: TcxLabel; LabelMan: TcxLabel; EditMan: TcxDBButtonEdit; ActionList1: TActionList; Action1: TAction; Grid1Level1: TcxGridLevel; Grid1: TcxGrid; cxStyleRepository1: TcxStyleRepository; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; BoxChild: TcxGroupBox; EditSmeta: TcxButtonEdit; LabelSmeta: TcxLabel; LabelSmetaName: TcxLabel; LabelVidOpl: TcxLabel; EditVidOpl: TcxButtonEdit; LabelVidOplName: TcxLabel; Action2: TAction; dxStatusBar1: TdxStatusBar; Grid1DBBandedTableView1: TcxGridDBBandedTableView; GridClKodDepartment: TcxGridDBBandedColumn; GridClNameDepartment: TcxGridDBBandedColumn; GridClNamePost: TcxGridDBBandedColumn; GridClDateBeg: TcxGridDBBandedColumn; GridClDateEnd: TcxGridDBBandedColumn; GridClKurs: TcxGridDBBandedColumn; CheckBoxMonthFinish: TcxCheckBox; Action3: TAction; procedure CancelBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Action1Execute(Sender: TObject); procedure EditVidOplExit(Sender: TObject); procedure EditSmetaExit(Sender: TObject); procedure MonthesListExit(Sender: TObject); procedure EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditVidOplPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure RestoreFromBuffer(Sender:TObject); procedure Action2Execute(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormResize(Sender: TObject); procedure Action3Execute(Sender: TObject); private Pcfs:TZControlFormStyle; PId_VidOpl:LongWord; PId_Smeta:LongWord; PId_Man:LongWord; PIdStud:int64; PIdCurrent:int64; PResult:Variant; PParameter:TZCurrentParameters; PLanguageIndex:Byte; PKodSetup:integer; DM:TDM; StylesDM:TStylesDM; public constructor Create(AOwner:TComponent);reintroduce; function DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean; function PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean; property result:Variant read PResult; end; implementation uses Math; {$R *.dfm} Var F:boolean; function TFgrCurrentCtrl.DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean; var PLanguageIndex:byte; begin Result:=False; PLanguageIndex := IndexLanguage; if grShowMessage(Caption_Delete[PLanguageIndex], DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbCancel])=mrYes then begin DM := TDM.Create(self); with DM do try Result:=True; DB.Handle:=Db_Handle; StProc.Transaction.StartTransaction; StProc.StoredProcName:='GR_CURRENT_D'; StProc.Prepare; StProc.ParamByName('ID_CURRENT').AsInteger:=Id; StProc.ExecProc; ////////// удаление из спска массовых выплат DSetDelMass.Close; DSetDelMass.SQLs.SelectSQL.Text:='execute procedure GR_MASS_PAYMENT_MAN_DD('''+IntToStr(Id)+''')'; try DSetDelMass.Open; except showmessage('Можливо виникло переповнення протоколу змін'); end; ////////// StProc.Transaction.Commit; except on E:Exception do begin grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]); StProc.Transaction.Rollback; Result:=False; end; end; DM.Destroy; end; end; constructor TFgrCurrentCtrl.Create(AOwner:TComponent); begin inherited Create(AOwner); PLanguageIndex:= IndexLanguage; //****************************************************************************** EditSumma.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+grSystemDecimalSeparator+']\d\d?)?'; //****************************************************************************** LabelMan.Caption := LabelStudent_Caption[PLanguageIndex]; LabelSumma.Caption := LabelSumma_Caption[PLanguageIndex]; LabelVidOpl.Caption := LabelVidOpl_Caption[PLanguageIndex]; LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex]; LabelManMoving.Caption := LabelStudentMoving_Caption[PLanguageIndex]; LabelPeriod.Caption := LabelPeriod_Caption[PLanguageIndex]; LabelPrikaz.Caption := LabelPrikaz_Caption[PLanguageIndex]; CheckBoxMonthFinish.Properties.Caption := LabelMonthFinish_Caption[PLanguageIndex]; MonthesList.Properties.Items.Text := MonthesList_Text[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; //****************************************************************************** dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex]; dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption; dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption; //****************************************************************************** GridClKodDepartment.Caption := LabelKod_Caption[PLanguageIndex]; GridClNameDepartment.Caption := LabelNameDepartment_Caption[PLanguageIndex]; GridClNamePost.Caption := LabelPost_Caption[PLanguageIndex]; GridClDateBeg.Caption := LabelDateBeg_Caption[PLanguageIndex]; GridClDateEnd.Caption := LabelDateEnd_Caption[PLanguageIndex]; GridClKurs.Caption := LabelKurs_Caption[PLanguageIndex]; //****************************************************************************** SetOptionsGridView(Grid1DBBandedTableView1); StylesDM := TStylesDM.Create(self); Grid1DBBandedTableView1.Styles.StyleSheet := StylesDM.GridBandedTableViewStyleSheetDevExpress; //****************************************************************************** PResult := NULL; end; function TFgrCurrentCtrl.PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean; var CurrKodSetup:integer; FieldValue:Variant; begin Result:=False; DM := TDM.Create(self); Pcfs:=fs; DM.DB.Handle := Db_Handle; Grid1DBBandedTableView1.DataController.DataSource := DM.DSourceMoving; case fs of zcfsInsert: try Caption := Caption_Insert[PLanguageIndex]; DM.DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+ IntToStr(Id)+',NULL)'; DM.DSetMoving.Open; DM.StProc.Transaction.StartTransaction; DM.StProc.StoredProcName := 'GR_MAN_BY_ID_STUD'; DM.StProc.Prepare; PIdStud := Id; DM.StProc.ParamByName('ID_STUD').AsInt64 := Id; DM.StProc.ExecProc; EditMan.Text := DM.StProc.ParamByName('FIO').AsString; PId_Man := DM.StProc.ParamByName('ID_MAN').AsInteger; DM.StProc.Transaction.Commit; CurrKodSetup := ValueFieldZSetup(Db_Handle,'GR_KOD_SETUP'); MonthesList.ItemIndex := YearMonthFromKodSetup(CurrKodSetup,False)-1; YearSpinEdit.Value := YearMonthFromKodSetup(CurrKodSetup); PKodSetup := CurrKodSetup; FieldValue := ValueFieldZSetup(Db_Handle,'GR_DEFAULT_SMETA'); if not VarIsNULL(FieldValue) then begin EditSmeta.Text := VarToStr(FieldValue); EditSmetaExit(self); end; Result:=True; except on E:Exception do begin DM.StProc.Transaction.Rollback; grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOk]); Result := False; end; end; zcfsUpdate: try Caption := Caption_Update[PLanguageIndex]; DM.StProc.Transaction.StartTransaction; DM.StProc.StoredProcName := 'GR_CURRENT_S_BY_KEY'; DM.StProc.Prepare; PIdCurrent := Id; DM.StProc.ParamByName('OLD_ID_CURRENT').AsInt64 := Id; DM.StProc.ExecProc; CheckBoxMonthFinish.EditValue := DM.StProc.ParamByName('NOW_PAY').AsString; PId_Man := DM.StProc.ParamByName('ID_MAN').AsInteger; EditMan.Text := DM.StProc.ParamByName('FIO').AsString; PId_VidOpl := DM.StProc.ParamByName('ID_VIDOPL').AsInteger; EditVidOpl.Text := VarToStrDef(DM.StProc.ParamByName('KOD_VIDOPL').AsVariant,''); LabelVidOplName.Caption := VarToStrDef(DM.StProc.ParamByName('NAME_VIDOPL').AsVariant,''); PId_Smeta := DM.StProc.ParamByName('ID_SMETA').AsInt64; EditSmeta.Text := VarToStrDef(DM.StProc.ParamByName('KOD_SMETA').AsVariant,''); LabelSmetaName.Caption := VarToStrDef(DM.StProc.ParamByName('NAME_SMETA').AsVariant,''); EditPrikaz.Text := VarToStrDef(DM.StProc.ParamByName('PRIKAZ').AsVariant,''); EditSumma.Text := FloatToStrF(DM.StProc.ParamByName('SUMMA').AsCurrency,ffFixed,16,2); PKodSetup := DM.StProc.ParamByName('KOD_SETUP').AsInteger; MonthesList.ItemIndex := YearMonthFromKodSetup(PKodSetup,False)-1; YearSpinEdit.Value := YearMonthFromKodSetup(PKodSetup); PIdStud := DM.StProc.ParamByName('ID_STUD').AsInt64; DM.DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+ IntToStr(PIdStud)+','+IntToStr(PKodSetup)+')'; DM.DSetMoving.Open; if not DM.DSetMoving.Locate('ID_STUD_INF',DM.StProc.ParamByName('ID_STUD_INF').AsInt64,[loCaseInsensitive]) then grShowMessage(ECaption[PLanguageIndex],EStudentMovingNotSelect_Text[PLanguageIndex],mtInformation,[mbOK]); DM.StProc.Transaction.Commit; Result:=True; except on E:Exception do begin DM.StProc.Transaction.Rollback; grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOk]); Result := False; end; end; zcfsShowDetails: try Caption := Caption_Detail[PLanguageIndex]; DM.StProc.Transaction.StartTransaction; DM.StProc.StoredProcName := 'GR_CURRENT_S_BY_KEY'; DM.StProc.Prepare; PIdCurrent := Id; DM.StProc.ParamByName('OLD_ID_CURRENT').AsInt64 := Id; DM.StProc.ExecProc; CheckBoxMonthFinish.EditValue := DM.StProc.ParamByName('NOW_PAY').AsString; PId_Man := DM.StProc.ParamByName('ID_MAN').AsInteger; EditMan.Text := DM.StProc.ParamByName('FIO').AsString; PId_VidOpl := DM.StProc.ParamByName('ID_VIDOPL').AsInteger; EditVidOpl.Text := VarToStrDef(DM.StProc.ParamByName('KOD_VIDOPL').AsVariant,''); LabelVidOplName.Caption := VarToStrDef(DM.StProc.ParamByName('NAME_VIDOPL').AsVariant,''); PId_Smeta := DM.StProc.ParamByName('ID_SMETA').AsInt64; EditSmeta.Text := VarToStrDef(DM.StProc.ParamByName('KOD_SMETA').AsVariant,''); LabelSmetaName.Caption := VarToStrDef(DM.StProc.ParamByName('NAME_SMETA').AsVariant,''); EditPrikaz.Text := VarToStrDef(DM.StProc.ParamByName('PRIKAZ').AsVariant,''); EditSumma.Text := FloatToStrF(DM.StProc.ParamByName('SUMMA').AsCurrency,ffFixed,16,2); PKodSetup := DM.StProc.ParamByName('KOD_SETUP').AsInteger; MonthesList.ItemIndex := YearMonthFromKodSetup(PKodSetup,False)-1; YearSpinEdit.Value := YearMonthFromKodSetup(PKodSetup); PIdStud := DM.StProc.ParamByName('ID_STUD').AsInt64; DM.DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+ IntToStr(PIdStud)+','+IntToStr(PKodSetup)+')'; DM.DSetMoving.Open; if not DM.DSetMoving.Locate('ID_STUD_INF',DM.StProc.ParamByName('ID_STUD_INF').AsInt64,[loCaseInsensitive]) then grShowMessage(ECaption[PLanguageIndex],EStudentMovingNotSelect_Text[PLanguageIndex],mtInformation,[mbOK]); DM.StProc.Transaction.Commit; BoxMain.Enabled := False; BoxChild.Enabled := False; PrikazBox.Enabled := False; IdMovingBox.Enabled := False; YesBtn.Visible := False; CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex]; dxStatusBar1.Panels[1].Visible := false; dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption; Result:=True; except on E:Exception do begin DM.StProc.Transaction.Rollback; grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOk]); Result := False; end; end; end; end; procedure TFgrCurrentCtrl.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFgrCurrentCtrl.FormClose(Sender: TObject; var Action: TCloseAction); begin DM.Free; end; procedure TFgrCurrentCtrl.Action1Execute(Sender: TObject); begin if DM.DSetMoving.IsEmpty then begin grShowMessage(ECaption[PLanguageIndex],EStudentMovingNotSelect_Text[PLanguageIndex],mtInformation,[mbOK]); CancelBtn.SetFocus; Exit; end; if EditSumma.Text='' then begin grShowMessage(ECaption[PLanguageIndex],ESummaInput_Text[PLanguageIndex],mtInformation,[mbOK]); EditSumma.SetFocus; Exit; end; if PId_VidOpl=0 then begin grShowMessage(ECaption[PLanguageIndex],EVidOplInput_Text[PLanguageIndex],mtInformation,[mbOK]); EditVidOpl.SetFocus; Exit; end; if PId_Smeta=0 then begin grShowMessage(ECaption[PLanguageIndex],ESmetaInput_Text[PLanguageIndex],mtInformation,[mbOK]); EditSmeta.SetFocus; Exit; end; with DM do try StProc.Transaction.StartTransaction; case Pcfs of zcfsInsert: StProc.StoredProcName:='GR_CURRENT_I'; zcfsUpdate: StProc.StoredProcName:='GR_CURRENT_U'; end; StProc.Prepare; StProc.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); StProc.ParamByName('KOD_SETUP_O1').AsVariant := NULL; StProc.ParamByName('KOD_SETUP_O2').AsVariant := NULL; StProc.ParamByName('ID_MAN').AsVariant := NULL; StProc.ParamByName('SUMMA').AsCurrency := StrToFloat(EditSumma.Text); StProc.ParamByName('ID_CATEGORY').AsVariant := DSetMoving['ID_KAT_STUD']; StProc.ParamByName('ID_POST').AsVariant := NULL; StProc.ParamByName('ID_DEPARTMENT').AsVariant := NULL; StProc.ParamByName('ID_SMETA').AsInt64 := PId_Smeta; StProc.ParamByName('ID_ACCOUNT').AsVariant := NULL; StProc.ParamByName('ID_STUD_INF').AsInt64 := DSetMoving['ID_STUD_INF']; StProc.ParamByName('ID_STUD').AsVariant := NULL; StProc.ParamByName('TAX_TEXT').AsVariant := NULL; StProc.ParamByName('P_OLD').AsString := 'F'; StProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl; StProc.ParamByName('PRIKAZ').AsString := EditPrikaz.Text; StProc.ParamByName('NOW_PAY').AsString := CheckBoxMonthFinish.EditValue; grShowStProcParametersData(StProc); case Pcfs of zcfsUpdate: StProc.ParamByName('ID_CURRENT').AsInt64 := PIdCurrent; end; StProc.ExecProc; if pcfs=zcfsInsert then PResult := StProc.ParamByName('ID_CURRENT').AsInt64 else PResult:=PIdCurrent; ////////// удаление из спска массовых выплат DSetDelMass.Close; DSetDelMass.SQLs.SelectSQL.Text:='execute procedure GR_MASS_PAYMENT_MAN_DD('''+IntToStr(PIdCurrent)+''')'; try DSetDelMass.Open; except showmessage('Можливо виникло переповнення протоколу змін'); end; ////////// StProc.Transaction.Commit; ModalResult:=mrYes; except on e:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]); StProc.Transaction.RollBack; PResult:=NULL; end; end; end; procedure TFgrCurrentCtrl.EditVidOplExit(Sender: TObject); var Vo:variant; begin if EditVidOpl.Text<>'' then begin VO:=VoByKod(StrToInt(EditVidOpl.Text), Date, DM.DB.Handle, ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM'), 0); if not VarIsNull(VO) then begin PId_VidOpl:=VO[0]; LabelVidOplName.Caption:=VarToStr(VO[2]); end else EditVidOpl.SetFocus; end; end; procedure TFgrCurrentCtrl.EditSmetaExit(Sender: TObject); var Smeta:variant; begin if EditSmeta.Text<>'' then begin Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),DM.DB.Handle); if not VarIsNull(Smeta) then begin PId_Smeta:=Smeta[0]; LabelSmetaName.Caption:=VarToStr(Smeta[2]); end else EditSmeta.SetFocus; end end; procedure TFgrCurrentCtrl.MonthesListExit(Sender: TObject); begin if PKodSetup=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1) then Exit else PKodSetup:=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); if DM.DSetMoving.Active then DM.DSetMoving.Close; DM.DSetMoving.SQLs.SelectSQL.Text:='SELECT * FROM GR_CN_DT_STUD_INF_S_BY_STUD_KS('+ IntToStr(PIdStud)+','+IntToStr(PKodSetup)+') order by DATE_END'; DM.DSetMoving.Open; DM.DSetMoving.Last; end; procedure TFgrCurrentCtrl.EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Smeta:Variant; begin Smeta:=GetSmets(self,DM.DB.Handle,Date,psmSmet); if VarArrayDimCount(Smeta)> 0 then If Smeta[0]<>NULL then begin EditSmeta.Text := Smeta[3]; LabelSmetaName.Caption := Smeta[2]; PId_Smeta := Smeta[0]; end; end; procedure TFgrCurrentCtrl.EditVidOplPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var VidOpl:Variant; begin VidOPl:=LoadVidOpl(self, DM.DB.Handle, zfsModal, 0, ValueFieldZSetup(DM.DB.Handle,'GR_ID_SYSTEM')); if VarArrayDimCount(VidOpl)> 0 then if VidOpl[0]<> NULL then begin EditVidOpl.Text := VidOpl[2]; LabelVidOplName.Caption := VidOpl[1]; PId_VidOpl := VidOpl[0]; end; end; procedure TFgrCurrentCtrl.RestoreFromBuffer(Sender:TObject); var reg:TRegistry; Kod:integer; Key:string; begin if (Owner as TForm).Caption = CurrentOperationsData_Text[PLanguageIndex] then Key := '\Software\Grant\CurrentCtrl\Current'; if (Owner as TForm).Caption = DataStud_Caption[PLanguageIndex] then Key := '\Software\Grant\CurrentCtrl\Stud'; reg := TRegistry.Create; reg.RootKey:=HKEY_CURRENT_USER; if not reg.OpenKey(Key,False) then begin reg.free; Exit; end; if reg.ReadString('IsBuffer')<>'1' then begin reg.Free; exit; end; EditSmeta.Text := reg.ReadString('KodSmeta'); EditSmetaExit(sender); EditVidOpl.Text := reg.ReadString('KodVidOpl'); EditVidOplExit(sender); EditPrikaz.Text := reg.ReadString('Prikaz'); CheckBoxMonthFinish.EditValue := reg.ReadString('EndMonth'); Kod := reg.ReadInteger('KodSetup'); if Kod>0 then begin MonthesList.ItemIndex := YearMonthFromKodSetup(Kod,False)-1; YearSpinEdit.Value := YearMonthFromKodSetup(Kod); end; editSumma.SetFocus; Reg.Free; end; procedure TFgrCurrentCtrl.Action2Execute(Sender: TObject); var reg: TRegistry; Key:string; begin CancelBtn.SetFocus; if (Owner as TForm).Caption = CurrentOperationsData_Text[PLanguageIndex] then Key := '\Software\Grant\CurrentCtrl\Current'; if (Owner as TForm).Caption = DataStud_Caption[PLanguageIndex] then Key := '\Software\Grant\CurrentCtrl\Stud'; reg:=TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; reg.OpenKey(Key,True); reg.WriteString('IsBuffer','1'); reg.WriteString('KodSmeta',EditSmeta.Text); reg.WriteString('KodVidOpl',EditVidOpl.Text); reg.WriteInteger('KodSetup',PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)); reg.WriteString('Prikaz',EditPrikaz.Text); reg.WriteString('EndMonth',CheckBoxMonthFinish.EditValue); finally reg.Free; end; end; procedure TFgrCurrentCtrl.FormShow(Sender: TObject); begin if Pcfs=zcfsInsert then RestoreFromBuffer(self); FormResize(sender); F:=False; end; procedure TFgrCurrentCtrl.FormResize(Sender: TObject); var i:integer; begin for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := Width div dxStatusBar1.Panels.Count; end; procedure TFgrCurrentCtrl.Action3Execute(Sender: TObject); begin if (CancelBtn.Focused=False) and (YesBtn.focused=False) and (CheckBoxMonthFinish.Focused=False) and (YearSpinEdit.focused=False) and (MonthesList.focused=False) and (EditSumma.focused=False) and (EditPrikaz.focused=False) and (EditVidOpl.focused=False) and (EditSmeta.focused=False) then F:=True; if CancelBtn.focused=true then close(); if YesBtn.focused=true then Action1.Execute; if F=true then begin YesBtn.SetFocus; F:=False; exit; end; if CheckBoxMonthFinish.Focused=true then begin Grid1.SetFocus; F:=True; exit; end; if YearSpinEdit.focused=true then begin CheckBoxMonthFinish.SetFocus; exit; end; if MonthesList.focused=true then begin YearSpinEdit.SetFocus; exit; end; if EditSumma.focused=true then begin MonthesList.SetFocus; exit; end; if EditPrikaz.focused=true then begin EditSumma.SetFocus; exit; end; if EditVidOpl.focused=true then begin EditPrikaz.SetFocus; exit; end; if EditSmeta.focused=true then begin EditVidOpl.SetFocus; exit; end; //if CancelBtn.focused=true then EditSmeta.SetFocus; end; end.
program Redefinisjon; var x: integer; procedure WriteInt (X: Integer); begin write(X) {Her kaller vi på den originale 'write'.} end; {WriteInt} procedure WriteChar (X: Char); begin write(X) {Det gjoer vi her ogsaa.} end; {WriteChar} procedure write (C: char; V: integer); begin WriteChar(C); WriteChar('='); WriteInt(V); WriteChar(eol) end; {write} begin x := 42; write('x', x) {Her kaller vi på den redefinerte 'write'.} end.
unit eaterFeeds; interface uses Classes, DataLank, eaterReg; type TFeedEatResult=record FeedCount,PostCount:integer; end; TFeedEater=class(TInterfacedObject, IFeedStore, IFeedHandler) private FDB,FDBStats:TDataConnection; FReport:TStringList; FPostID:string; FPostURL:WideString; FPostPubDate:TDateTime; FPostTags:Variant; FPostTagPrefix:string; FFeed:record id,group_id:integer; URL,URL0,URLSkip,Name,Name0,LastMod,LastMod0,Result,Result0:string; Regime,TotalCount:integer; LoadStart,LoadLast:TDateTime; NotModified:boolean; end; FPostsTotal,FPostsNew:integer; FHasReplaces:boolean; OldPostsCutOff:TDateTime; function LoadExternal(const URL,FilePath,LastMod,Accept:string):WideString; function ParseExternalHeader(var content:WideString):WideString; function FeedSkipDisplay(d:TDateTime):string; procedure PerformReplaces(var title,content:WideString); procedure PerformGlobalReplaces(var data:WideString); procedure FeedCombineURL(const url,lbl:string); function FindFeedURL(const data:WideString):boolean; //IFeedStore function CheckLastLoadResultPrefix(const Prefix:string):boolean; //IFeedHandler function CheckNewPost(const PostID:string;const PostURL:WideString; PostPubDate:TDateTime):boolean; procedure UpdateFeedName(const NewName:string); procedure PostTags(const TagPrefix:string;const Tags:Variant); procedure RegisterPost(const PostTitle,PostContent:WideString); procedure ReportSuccess(const Lbl:string); procedure ReportFailure(const Msg:string); public ForceLoadAll,SaveData:boolean; OnFeedURLUpdate:TNotifyEvent; constructor Create; destructor Destroy; override; procedure DoCleanup; procedure DoAutoUnread; function DoUpdateFeeds(SpecificFeedID:integer;const FeedLike:string; PubDateMargin:double):TFeedEatResult; procedure RenderGraphs; end; const Specific_NewFeeds=-111; Specific_AllFeeds=-113; var PGVersion:string; BlackList:TStringList; InstagramLastTC:cardinal; InstagramFailed:TDateTime; const InstagramIntervalMS=30000; InstagramCoolDown=4.0/24.0; implementation uses Windows, SysUtils, Variants, ComObj, eaterUtils, eaterSanitize, MSXML2_TLB, jsonDoc, VBScript_RegExp_55_TLB, eaterGraphs, feedSoundCloud; const FeederIniPath='..\..\feeder.ini'; EaterIniPath='..\..\feeder_eater.ini'; //TODO: from ini? FeedLoadReport='..\Load.html'; AvgPostsDays=500; OldPostsDays=3660; regimesteps=12; regimestep:array[0..regimesteps-1] of integer=(1,2,3,7,14,30,60,90,120,150,200,360); function qrDate(qr:TQueryResult;const Idx:Variant):TDateTime; var v:Variant; begin v:=qr[Idx]; if VarIsNull(v) then Result:=0 else Result:=double(v); end; { TFeedEater } constructor TFeedEater.Create; var sl:TStringList; constr:string; qr:TQueryResult; begin inherited Create; OutLn('Opening databases...'); sl:=TStringList.Create; try sl.LoadFromFile(FeederIniPath); constr:=sl.Text; finally sl.Free; end; FDB:=TDataConnection.Create(constr); FDBStats:=TDataConnection.Create(constr); if PGVersion='' then //? begin qr:=TQueryResult.Create(FDB,'select version()',[]); try if qr.Read then PGVersion:=qr.GetStr(0); finally qr.Free; end; end; FReport:=TStringList.Create; FReport.DefaultEncoding:=TEncoding.UTF8; OldPostsCutOff:=UtcNow-OldPostsDays; ForceLoadAll:=false;//default SaveData:=false;//default OnFeedURLUpdate:=nil; end; destructor TFeedEater.Destroy; begin FDB.Free; FDBStats.Free; inherited; end; procedure TFeedEater.DoCleanup; var qr:TQueryResult; i,j:integer; begin Out0('Clean-up old...'); qr:=TQueryResult.Create(FDBStats,'select id from "Post" where pubdate<$1',[double(OldPostsCutOff)]); try j:=0; while qr.Read do begin i:=qr.GetInt('id'); FDB.BeginTrans; try FDB.Execute('delete from "UserPost" where post_id=$1',[i]); FDB.Execute('delete from "Opinion" where post_id=$1',[i]); FDB.Execute('delete from "Post" where id=$1',[i]); FDB.CommitTrans; except FDB.RollbackTrans; raise; end; inc(j); end; Writeln(' '+IntToStr(j)+' posts cleaned '); finally qr.Free; end; Out0('Clean-up unused...'); qr:=TQueryResult.Create(FDBStats,'select id from "Feed" where id>0'+ ' and not exists (select S.id from "Subscription" S where S.feed_id="Feed".id)',[]); try j:=0; while qr.Read do begin i:=qr.GetInt('id'); Write(#13'... #'+IntToStr(i)+' '); FDB.BeginTrans; try FDB.Execute('delete from "UserPost" where post_id in (select P.id from "Post" P where P.feed_id=$1)',[i]); FDB.Execute('delete from "Opinion" where post_id in (select P.id from "Post" P where P.feed_id=$1)',[i]); FDB.Execute('delete from "Post" where feed_id=$1',[i]); FDB.Execute('delete from "Feed" where id=$1',[i]); FDB.CommitTrans; except FDB.RollbackTrans; raise; end; inc(j); end; Writeln(' '+IntToStr(j)+' feeds cleaned '); finally qr.Free; end; end; procedure TFeedEater.DoAutoUnread; var qr:TQueryResult; i:integer; begin Out0('Auto-unread after...'); qr:=TQueryResult.Create(FDBStats,'select X.id from "Subscription" S' +' inner join "UserPost" X on X.subscription_id=S.id' +' where S.autounread is not null' +' and X.pubdate<$1-S.autounread/24.0 limit 1',[double(UtcNow)]); try if qr.EOF then i:=0 else i:=1; finally qr.Free; end; if i=0 then Writeln(' none') else begin FDB.BeginTrans; try i:=FDB.Execute('delete from "UserPost" where id in (select X.id' +' from "Subscription" S' +' inner join "UserPost" X on X.subscription_id=S.id' +' where S.autounread is not null' +' and X.pubdate<$1-S.autounread/24.0)',[double(UtcNow)]); FDB.CommitTrans; except FDB.RollbackTrans; raise; end; Writeln(' '+IntToStr(i)+' items marked read'); end; end; function TFeedEater.DoUpdateFeeds(SpecificFeedID:integer;const FeedLike:string; PubDateMargin:double):TFeedEatResult; var qr:TQueryResult; ids:array of integer; ids_i,ids_l:integer; d,oldPostDate:TDateTime; sql1,sql2,ss,html1,html2:string; postlast,postavg,f:double; newfeed,doreq,loadext,xres:boolean; r:ServerXMLHTTP60; redirCount,sCount,i,j:integer; handler_i:cardinal; doc:DOMDocument60; FeedData,FeedDataType:WideString; begin FReport.Clear; //TODO: from embedded resource FReport.Add('<style>'); FReport.Add('P{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;}'); FReport.Add('TH{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;white-space:nowrap;border:1px solid #333333;}'); FReport.Add('TD{font-family:"PT Sans","Yu Gothic",Calibri,sans-serif;font-size:0.7em;white-space:nowrap;border:1px solid #CCCCCC;}'); FReport.Add('TD.n{max-width:20em;overflow:hidden;text-overflow:ellipsis;}'); FReport.Add('TD.empty{background-color:#CCCCCC;}'); FReport.Add('DIV.flag{display:inline;padding:2pt;color:#FFCC00;border-radius:4pt;white-space:nowrap;}'); FReport.Add('</style>'); FReport.Add('<table cellspacing="0" cellpadding="4" border="1">'); FReport.Add('<tr><th>&nbsp;</th><th>name</th><th title="subscriptions">#</th>'); FReport.Add('<th>post:avg</th><th>regime</th><th>since</th>'); FReport.Add('<th>load result</th><th>new</th><th>items</th><th>total</th></tr>'); try OutLn('List feeds for loading...'); Result.FeedCount:=0; Result.PostCount:=0; if SpecificFeedID>0 then begin ids_l:=1; SetLength(ids,1); ids[0]:=SpecificFeedID; end else begin if SpecificFeedID=Specific_NewFeeds then qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+ ' and F.created>$1 order by F.id',[UtcNow-1.0]) else if FeedLike<>'' then qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+ ' and F.url like $1'+ ' order by F.id',['%'+FeedLike+'%']) else qr:=TQueryResult.Create(FDB,'select F.id from "Feed" F where F.id>0'+ ' order by F.id',[]); try ids_l:=0; ids_i:=0; while qr.Read do begin if ids_i=ids_l then begin inc(ids_l,$400);//grow step SetLength(ids,ids_l); end; ids[ids_i]:=qr.GetInt('id'); inc(ids_i); end; ids_l:=ids_i; finally qr.Free; end; end; oldPostDate:=UtcNow-AvgPostsDays; ids_i:=0; while ids_i<ids_l do begin FFeed.id:=ids[ids_i]; qr:=TQueryResult.Create(FDB,'select *' +' ,(select count(*) from "Subscription" S where S.feed_id=F.id) as scount' +' from "Feed" F where F.id=$1',[FFeed.id]); try if qr.EOF then raise Exception.Create('No feed found for this id.'); FFeed.group_id:=qr.GetInt('group_id'); FFeed.URL0:=qr.GetStr('url'); FFeed.URLSkip:=qr.GetStr('urlskip'); FFeed.Name0:=qr.GetStr('name'); FFeed.LastMod0:=qr.GetStr('lastmod'); FFeed.Result0:=qr.GetStr('result'); FFeed.Regime:=qr.GetInt('regime'); FFeed.TotalCount:=qr.GetInt('totalcount'); FFeed.LoadStart:=UtcNow; FFeed.LoadLast:=qrDate(qr,'loadlast'); FFeed.URL:=FFeed.URL0; FFeed.Name:=FFeed.Name0; FFeed.LastMod:=FFeed.LastMod0; FFeed.Result:=''; FFeed.NotModified:=false; FPostsTotal:=qr.GetInt('itemcount'); FPostsNew:=qr.GetInt('loadcount'); newfeed:=qr.IsNull('itemcount'); Out0('#'+IntToStr(FFeed.id)+' '+DisplayShortURL(FFeed.URL)); //flags //i:=qr0.GetInt('flags'); //feedglobal:=(i and 1)<>0; //TODO: more? html1:='<td class="n" title="created: ' +FormatDateTime('yyyy-mm-dd hh:nn',qrDate(qr,'created')) +#13#10'check: ' +FormatDateTime('yyyy-mm-dd hh:nn:ss',FFeed.LoadStart) +'">'; if FFeed.group_id<>0 then html1:=html1+'<div class="flag" style="background-color:red;">'+IntToStr(FFeed.group_id)+'</div>&nbsp;'; html2:='<td style="text-align:right;">'+VarToStr(qr['scount'])+'</td>'; finally qr.Free; end; //check feed timing and regime qr:=TQueryResult.Create(FDB, 'select id from "Post" where feed_id=$1 order by 1 desc limit 1 offset 200',[FFeed.id]); try if qr.EOF then begin sql1:=''; sql2:=''; end else begin sql1:=' and P1.id>'+IntToStr(qr.GetInt('id')); sql2:=' and P2.id>'+IntToStr(qr.GetInt('id')); end; finally qr.Free; end; qr:=TQueryResult.Create(FDB,(//UTF8Encode( 'select max(X.pubdate) as postlast, avg(X.pd) as postavg' +', min(X.pm) as postmedian' +' from(' +' select' +' P2.pubdate, min(P2.pubdate-P1.pubdate) as pd' +' ,case when cume_dist()over(order by min(P2.pubdate-P1.pubdate))<0.5 then null else min(P2.pubdate-P1.pubdate) end as pm' +' from "Post" P1' +' inner join "Post" P2 on P2.feed_id=P1.feed_id'+sql2+' and P2.pubdate>P1.pubdate+1.0/1440.0' +' where P1.feed_id=$1'+sql1+' and P1.pubdate>$2' +' group by P2.pubdate' +' ) X') ,[FFeed.id,double(oldPostDate)]); try if qr.EOF then begin postlast:=0.0; postavg:=0.0; end else begin postlast:=qrDate(qr,'postlast'); postavg:=qrDate(qr,'postmedian'); if postavg=0.0 then postavg:=qrDate(qr,'postavg'); end; finally qr.Free; end; if postlast=0.0 then begin if FFeed.LoadLast=0.0 then d:=FFeed.LoadStart-PubDateMargin else d:=FFeed.LoadLast+FFeed.Regime; end else begin d:=postlast+postavg-PubDateMargin; if (FFeed.LoadLast<>0.0) and (d<FFeed.LoadLast) then d:=FFeed.LoadLast+FFeed.Regime-PubDateMargin; end; //proceed with this feed? if (d<FFeed.LoadStart) or ForceLoadAll or (SpecificFeedID>0) then begin //load feed data loadext:=FileExists('feeds\'+Format('%.4d',[FFeed.id])+'.txt'); try //TODO: move these into specific feed handlers if (FFeed.Result0<>'') and (FFeed.Result0[1]='[') then FFeed.Result0:=''; if (FFeed.Result0='') and StartsWith(FFeed.URL,'https://www.youtube.com') then SanitizeYoutubeURL(FFeed.URL); //TODO: move this to feedInstagram.pas if StartsWithX(FFeed.URL,'http://www.instagram.com/',ss) then FFeed.URL:='https://instagram.com'+ss; if StartsWithX(FFeed.URL,'http://instagram.com/',ss) then FFeed.URL:='https://instagram.com'+ss; if (StartsWith(FFeed.URL,'https://www.instagram.com/') or StartsWith(FFeed.URL,'https://instagram.com/')) then begin if (InstagramFailed<>0.0) and (UtcNow>InstagramFailed) then InstagramFailed:=0.0; if InstagramFailed=0.0 then begin r:=CoServerXMLHTTP60.Create; if not(FFeed.URL[Length(FFeed.URL)]='/') then FFeed.URL:=FFeed.URL+'/'; if not StartsWithX(FFeed.Name,'instagram:',ss) then begin Write('?'); r.open('GET',FFeed.URL,false,EmptyParam,EmptyParam); r.send(EmptyParam); if r.status<>200 then raise Exception.Create('[HTTP:'+IntToStr(r.status)+']'+r.statusText); FeedData:=r.responseText; i:=Pos(WideString('"profile_id":"'),FeedData); if i=0 then raise Exception.Create('Instagram: no profile_id found') else begin inc(i,14); j:=i; while (j<=Length(FeedData)) and (FeedData[j]<>'"') do inc(j); //and FeedData[j] in ['0'..'9']? ss:=Copy(FeedData,i,j-i); FFeed.Name:='instagram:'+ss; InstagramLastTC:=GetTickCount-(InstagramLastTC div 2); end; end; //space requests while cardinal(GetTickCount-InstagramLastTC)<InstagramIntervalMS do begin Write(Format(' %.2d"',[(InstagramIntervalMS- cardinal(GetTickCount-InstagramLastTC)+500) div 1000])+#8#8#8#8); Sleep(1000); end; Write('. '#8#8#8); if newfeed then i:=32 else i:=8;//new? r.open('GET','https://www.instagram.com/graphql/query/?query_hash=' +'69cba40317214236af40e7efa697781d&variables=%7B%22id%22%3A%22' +ss+'%22%2C%22first%22%3A'+IntToStr(i)+'%7D' ,false,EmptyParam,EmptyParam); r.setRequestHeader('Accept','application/json'); //r.setRequestHeader('Referer',FFeed.URL);?? r.setRequestHeader('Cookie','csrftoken=r0E0o6p76cxSWJma3DcrEt1EyS40Awdw');//?? r.setRequestHeader('X-CSRFToken','r0E0o6p76cxSWJma3DcrEt1EyS40Awdw'); //'x-ig-app-id'? r.send(EmptyParam); if r.status=200 then begin Write(':'); FeedData:=r.responseText; //FeedDataType:='application/json'; FeedDataType:=r.getResponseHeader('Content-Type'); if SaveData then SaveUTF16('xmls\'+Format('%.4d',[FFeed.id])+'.json',FeedData); end else if r.status=401 then begin InstagramFailed:=UtcNow+InstagramCoolDown; FFeed.Result:='(Instagram '+IntToStr(Round((InstagramFailed-UtcNow)*1440.0))+'''.)'; end else begin FFeed.Result:='[HTTP:'+IntToStr(r.status)+']'+r.statusText; end; r:=nil; InstagramLastTC:=GetTickCount; end else FFeed.Result:='(Instagram '+IntToStr(Round((InstagramFailed-UtcNow)*1440.0))+''')'; end else if loadext then begin FeedData:=LoadExternal(FFeed.URL, 'xmls\'+Format('%.4d',[FFeed.id])+'.xml', FFeed.LastMod, 'application/rss+xml, application/atom+xml, application/xml, application/json, text/xml'); FeedDataType:=ParseExternalHeader(FeedData); end else begin redirCount:=0; doreq:=true; while doreq do begin Write(':'); r:=CoServerXMLHTTP60.Create; handler_i:=0; while (handler_i<RequestProcessorsIndex) and doreq do if RequestProcessors[handler_i].AlternateOpen(FFeed.URL,FFeed.LastMod,r) then doreq:=false else inc(handler_i); if doreq then //if (handler_i=RequestProcessors) then begin doreq:=false; r.open('GET',FFeed.URL,false,EmptyParam,EmptyParam); r.setRequestHeader('Accept','application/rss+xml, application/atom+xml, application/xml, application/json, text/xml'); r.setRequestHeader('User-Agent','FeedEater/1.1'); r.setRequestHeader('Cache-Control','no-cache, no-store, max-age=0'); end; //TODO: ...'/wp/v2/posts' param 'after' last load time? if (FFeed.LastMod<>'') and not(ForceLoadAll) then r.setRequestHeader('If-Modified-Since',FFeed.LastMod); r.send(EmptyParam); if (r.status=301) or (r.status=302) or (r.status=308) then //moved permanently begin FFeed.URL:=r.getResponseHeader('Location'); doreq:=true; inc(redirCount); if redirCount=8 then raise Exception.Create('Maximum number of redirects reached'); end; end; if r.status=200 then begin Write(':'); FeedData:=r.responseText; //:=r.getAllResponseHeaders; FeedDataType:=r.getResponseHeader('Content-Type'); FFeed.LastMod:=r.getResponseHeader('Last-Modified'); r:=nil; if SaveData then SaveUTF16('xmls\'+Format('%.4d',[FFeed.id])+'.xml',FeedData); end else if r.status=304 then FFeed.NotModified:=true else FFeed.Result:='[HTTP:'+IntToStr(r.status)+']'+r.statusText; end; except on e:Exception do begin if e is EAlternateProcessFeed then begin FeedData:=e.Message;//see AlternateOpen FeedDataType:='text/plain'; end else FFeed.Result:='['+e.ClassName+']'+e.Message; if not(loadext) and (e is EOleException) and ((e.Message='A security error occurred') or (e.Message='A connection with the server could not be established')) then //TODO: e.ErrorCode=? SaveUTF16('feeds\'+Format('%.4d',[FFeed.id])+'.txt',''); end; end; //global replaces if FileExists('feeds\'+Format('%.4d',[FFeed.id])+'g.json') then PerformGlobalReplaces(FeedData); //content type missing? (really simple) auto-detect if (FeedDataType='') and (Length(FeedData)>8) then begin i:=1; while (i<=Length(FeedData)) and (FeedData[i]<=' ') do inc(i); if (FeedData<>'') and ((FeedData[i]='{') or (FeedData[i]='[')) then FeedDataType:='application/json' else if StartsWith(FeedData,'<?xml ') then FeedDataType:='application/xml' //parse? xmlns? application/atom+xml? application/rss+xml? else FeedDataType:='text/html';//enables search for <link>s below end; //any new data? if FFeed.NotModified then begin FFeed.Result:=FFeed.Result+' [HTTP 304]'; if not loadext then Writeln(' HTTP 304'); end else begin if (FFeed.Result='') and (FeedData='') then FFeed.Result:='[NoData]'; //process feed data if FFeed.Result='' then try FPostsTotal:=0;//see CheckNewPost FPostsNew:=0;//see RegisterPost SanitizeContentType(FeedDataType); SanitizeUnicode(FeedData); //TODO: "Feed".flags? if FileExists('feeds\'+Format('%.4d',[FFeed.id])+'ws.txt') then begin i:=1; while (i<=Length(FeedData)) and (word(FeedData[i])<=32) do inc(i); if i<>1 then FeedData:=Copy(FeedData,i,Length(FeedData)-i+1); end; FHasReplaces:=FileExists('feeds\'+Format('%.4d',[FFeed.id])+'r.json'); handler_i:=0; while handler_i<FeedProcessorsIndex do if FeedProcessors[handler_i].Determine( Self,FFeed.URL,FeedData,FeedDataType) then begin FeedProcessors[handler_i].ProcessFeed(Self,FeedData); //assert FFeed.Result set by ReportSuccess or ReportFailure handler_i:=FeedProcessorsIndex; end else inc(handler_i); //nothing yet? process as XML if FFeed.Result='' then begin doc:=CoDOMDocument60.Create; doc.async:=false; doc.validateOnParse:=false; doc.resolveExternals:=false; doc.preserveWhiteSpace:=true; doc.setProperty('ProhibitDTD',false); xres:=doc.loadXML(FeedData); //fix Mashable (grr!) if not(xres) then xres:=FixUndeclNSPrefix(doc,FeedData); //fix floating nbsp's if not(xres) and (Pos('''nbsp''',string(doc.parseError.reason))<>0) then FixNBSP(doc,FeedData); if xres then begin handler_i:=0; while handler_i<FeedProcessorsXMLIndex do if FeedProcessorsXML[handler_i].Determine(doc) then begin FeedProcessorsXML[handler_i].ProcessFeed(Self,doc); //assert FFeed.Result set by ReportSuccess or ReportFailure handler_i:=FeedProcessorsXMLIndex; end else inc(handler_i); //still nothing? if FFeed.Result='' then if not((FeedDataType='text/html') and FindFeedURL(FeedData)) then FFeed.Result:='Unkown "'+doc.documentElement.tagName+'" (' +FeedDataType+')'; end else begin if FeedData='' then FFeed.Result:='[No Data]' else //XML parse failed if not((FeedDataType='text/html') and FindFeedURL(FeedData)) then FFeed.Result:='[XML'+IntToStr(doc.parseError.line)+':'+ IntToStr(doc.parseError.linepos)+']'+doc.parseError.Reason; end; // end; inc(Result.FeedCount); inc(Result.PostCount,FPostsNew); inc(FFeed.TotalCount,FPostsNew); except on e:Exception do FFeed.Result:='['+e.ClassName+']'+e.Message; end; //update feed data if any changes if (FFeed.Result<>'') and ((FFeed.Result[1]='[') or (FFeed.Result[1]='(')) then begin ErrLn('!!! '+FFeed.Result); end else begin //stale? update regime if (FPostsNew=0) and (FPostsTotal>FFeed.Regime*2+5) then begin i:=0; if FFeed.Regime>=0 then begin while (i<regimesteps) and (FFeed.Regime>=regimestep[i]) do inc(i); if (i<regimesteps) and ((postlast=0.0) or (postlast+regimestep[i]*2<FFeed.LoadStart)) then begin FFeed.Result:=FFeed.Result+' (stale? r:'+IntToStr(FFeed.Regime)+ '->'+IntToStr(regimestep[i])+')'; FFeed.Regime:=regimestep[i]; end; end; end else begin //not stale: update regime to apparent post average period if FFeed.Regime<>0 then begin i:=regimesteps; while (i<>0) and (postavg<regimestep[i-1]) do dec(i); if i=0 then FFeed.Regime:=0 else FFeed.Regime:=regimestep[i-1]; end; end; Writeln(' '+FFeed.Result); end; FDB.BeginTrans; try if FFeed.Name='' then begin i:=5; while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>':') do inc(i); inc(i); if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i); if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i); FFeed.Name:='['+Copy(FFeed.URL,i,Length(FFeed.URL)-i+1); i:=2; while (i<=Length(FFeed.Name)) and (FFeed.Name[i]<>'/') do inc(i); SetLength(FFeed.Name,i); FFeed.Name[i]:=']'; end; if newfeed or (FFeed.URL<>FFeed.URL0) or (FFeed.Name<>FFeed.Name0) then begin FDB.Update('Feed', ['id',FFeed.id ,'name',Copy(FFeed.Name,1,200) ,'url',FFeed.URL ,'loadlast',double(FFeed.LoadStart) ,'result',FFeed.Result ,'loadcount',FPostsNew ,'itemcount',FPostsTotal ,'totalcount',FFeed.TotalCount ,'regime',FFeed.Regime ]); if (@OnFeedURLUpdate<>nil) and (FFeed.URL<>FFeed.URL0) then OnFeedURLUpdate(Self); end else FDB.Update('Feed', ['id',FFeed.id ,'loadlast',double(FFeed.LoadStart) ,'result',FFeed.Result ,'loadcount',FPostsNew ,'itemcount',FPostsTotal ,'totalcount',FFeed.TotalCount ,'regime',FFeed.Regime ]); if FFeed.LastMod<>FFeed.LastMod0 then FDB.Update('Feed', ['id',FFeed.id ,'lastmod',FFeed.LastMod ]); FDB.CommitTrans; except FDB.RollbackTrans; raise; end; end; end else begin //feed not loaded now Writeln(' Skip '+FeedSkipDisplay(d)); FFeed.Result:=FFeed.Result0; //postsTotal,postsNew see above FFeed.LoadStart:=FFeed.LoadLast; end; FReport.Add('<tr><th>'+IntToStr(FFeed.id)+'</th>'); FReport.Add(html1+'<a href="'+HTMLEncode(FFeed.URL)+'">'+HTMLEncode(FFeed.Name)+'</a></td>'); FReport.Add(html2); ss:='<td title="'; if FFeed.LastMod0<>'' then ss:=ss+'last mod: '+HTMLEncode(FFeed.LastMod0)+#13#10; if postlast<>0.0 then ss:=ss+'post last: '+FormatDateTime('yyyy-mm-dd hh:nn',postlast); ss:=ss+'"'; if postavg=0.0 then FReport.Add(ss+' class="empty">&nbsp;</td>') else if postavg>1.0 then FReport.Add(ss+' style="text-align:right;background-color:#FFFFCC;">'+IntToStr(Round(postavg))+' days</td>') else FReport.Add(ss+' style="text-align:right;">'+IntToStr(Round(postavg*1440.0))+' mins</td>'); if FFeed.Regime=0 then FReport.Add('<td class="empty">&nbsp;</td>') else FReport.Add('<td style="text-align:right;">'+IntToStr(FFeed.Regime)+'</td>'); if FFeed.LoadLast=0.0 then FReport.Add('<td class="empty">&nbsp;</td>') else begin ss:='<td title="load last: '+FormatDateTime('yyyy-mm-dd hh:nn',FFeed.LoadLast) +'" style="text-align:right;'; f:=UtcNow-FFeed.LoadLast; if f>1.0 then FReport.Add(ss+'background-color:#FFFFCC;">'+IntToStr(Round(f))+' days</td>') else FReport.Add(ss+'">'+IntToStr(Round(f*1440.0))+' mins</td>'); end; if (FFeed.Result<>'') and (FFeed.Result[1]='[') then FReport.Add('<td style="color:#CC0000;">'+HTMLEncode(FFeed.Result)+'</td>') else FReport.Add('<td>'+HTMLEncode(FFeed.Result)+'</td>'); FReport.Add('<td style="text-align:right;" title="last mod:' +HTMLEncode(FFeed.LastMod)+'">'+IntToStr(FPostsNew)+'</td>'); if FPostsTotal=0 then FReport.Add('<td class="empty">&nbsp;</td>') else FReport.Add('<td style="text-align:right;">'+IntToStr(FPostsTotal)+'</td>'); FReport.Add('<td style="text-align:right;">'+IntToStr(FFeed.TotalCount)+'</td>'); FReport.Add('</tr>'); inc(ids_i); end; OutLn(Format('Loaded: %d posts from %d feeds (%d)', [Result.PostCount,Result.FeedCount,ids_l])); FReport.Add('</table>'); qr:=TQueryResult.Create(FDBStats, 'select ((select count(*) from "Post")+500)/1000||''K posts, ''' +'||((select count(*) from "UserPost")+500)/1000||''K unread, ''' +'||pg_database_size(''feeder'')/1024000||''MB, ''' +'||version()',[]); try while qr.Read do FReport.Add('<p>'+HTMLEncode(qr.GetStr(0))+'</p>'); finally qr.Free; end; FReport.SaveToFile(FeedLoadReport); except on e:Exception do begin ErrLn('['+e.ClassName+']'+e.Message); ExitCode:=1; end; end; end; function TFeedEater.CheckLastLoadResultPrefix(const Prefix: string): boolean; begin Result:=(FFeed.Result0='') or StartsWith(FFeed.Result0,Prefix); end; function TFeedEater.CheckNewPost(const PostID: string; const PostURL: WideString; PostPubDate: TDateTime): boolean; var qr:TQueryResult; i:integer; s:string; begin FPostID:=PostID; FPostURL:=PostURL; FPostPubDate:=PostPubDate; FPostTags:=Null; FPostTagPrefix:=''; if FPostURL='' then FPostURL:=FPostID; if FPostID='' then FPostID:=FPostURL; if StartsWithX(FPostID,'http://',s) then FPostID:=s else if StartsWithX(FPostID,'https://',s) then FPostID:=s; SanitizePostID(FPostID); if FFeed.URLSkip<>'' then begin i:=Pos(FFeed.URLSkip,FPostID); if i<>0 then FPostID:=Copy(FPostID,1,i-1); end; //TODO: if feed_flag_trim in feed_flags? FPostURL:=SanitizeTrim(FPostURL); //relative url if (FPostURL<>'') and not(StartsWith(FPostURL,'http')) then if FPostURL[1]='/' then begin i:=5; while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>':') do inc(i); inc(i); if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i); if (i<=Length(FFeed.URL)) and (FFeed.URL[i]='/') then inc(i); while (i<=Length(FFeed.URL)) and (FFeed.URL[i]<>'/') do inc(i); FPostURL:=Copy(FFeed.URL,1,i-1)+FPostURL; end else begin i:=Length(FFeed.URL); while (i<>0) and (FFeed.URL[i]<>'/') do dec(i); FPostURL:=Copy(FFeed.URL,1,i)+FPostURL; end; //TODO: switch: allow future posts? if FPostPubDate>FFeed.LoadStart+2.0/24.0 then FPostPubDate:=FFeed.LoadStart; inc(FPostsTotal); //check age, blacklist, already listed Result:=FPostPubDate>=OldPostsCutOff; i:=0; while Result and (i<BlackList.Count) do if (BlackList[i]<>'') and (blacklist[i]=Copy(FPostURL,1,Length(BlackList[i]))) then Result:=false else inc(i); if Result then begin if FFeed.group_id<>0 then qr:=TQueryResult.Create(FDB, 'select P.id from "Post" P' +' inner join "Feed" F on F.id=P.feed_id' +' and F.group_id=$1' +' where P.guid=$2' ,[FFeed.group_id,FPostID]) else qr:=TQueryResult.Create(FDB, 'select id from "Post" where feed_id=$1 and guid=$2' ,[FFeed.id,FPostID]); try Result:=qr.EOF; //TODO: if FFeed.group_id<>0 and P.feed_id>FFeed.id then update? finally qr.Free; end; end; end; procedure TFeedEater.UpdateFeedName(const NewName:string); begin if NewName<>'' then FFeed.Name:=NewName; end; procedure TFeedEater.PostTags(const TagPrefix:string;const Tags: Variant); begin //assert varArray of varString FPostTags:=Tags; FPostTagPrefix:=TagPrefix; //see also RegisterPost end; procedure TFeedEater.RegisterPost(const PostTitle, PostContent: WideString); var title,content:WideString; ti,postid:integer; tsql:string; begin title:=PostTitle; content:=PostContent; inc(FPostsNew); if IsSomethingEmpty(title) then begin title:=StripHTML(content,200); if Length(title)<=8 then title:=#$2039+FPostID+#$203A; end; //content starts with <img>? inject a <br /> SanitizeStartImg(content); if FHasReplaces then PerformReplaces(title,content); //if feedtagprefix<>'' then tsql:=''; if VarIsArray(FPostTags) then //varArray of varStrSomething? for ti:=VarArrayLowBound(FPostTags,1) to VarArrayHighBound(FPostTags,1) do tsql:=tsql+' or B.url='''+StringReplace(FPostTagPrefix+':'+ VarToStr(FPostTags[ti]),'''','''''',[rfReplaceAll])+''''; //list the post FDB.BeginTrans; try postid:=FDB.Insert('Post', ['feed_id',FFeed.id ,'guid',FPostID ,'title',SanitizeTitle(title) ,'content',content ,'url',FPostURL ,'pubdate',double(FPostPubDate) ,'created',double(UtcNow) ],'id'); FDB.Execute('insert into "UserPost" (user_id,post_id,subscription_id,pubdate)'+ ' select S.user_id,$1,S.id,$2 from "Subscription" S'+ ' left outer join "UserBlock" B on B.user_id=S.user_id'+ ' and (B.url=left($3,length(B.url))'+tsql+')'+ ' where S.feed_id=$4 and B.id is null',[postid,double(FPostPubDate), FPostURL,FFeed.id]); FDB.CommitTrans; except FDB.RollbackTrans; raise; end; end; procedure TFeedEater.ReportSuccess(const Lbl: string); begin FFeed.Result:=Format('%s %d/%d',[Lbl,FPostsNew,FPostsTotal]); end; procedure TFeedEater.ReportFailure(const Msg: string); begin FFeed.LastMod:=''; FFeed.Result:=Msg; end; const GatsbyPageDataSuffix='/page-data.json'; function TFeedEater.LoadExternal(const URL, FilePath, LastMod, Accept: string): WideString; var si:TStartupInfo; pi:TProcessInformation; f:TFileStream; s:UTF8String; i:integer; w:word; r,mr:cardinal; cl,ua:string; begin WriteLn(' ->'); DeleteFile(PChar(FilePath));//remove any previous file ua:='FeedEater/1.0'; mr:=8; if StartsWith(URL,'https://www.instagram.com/') then begin mr:=0; //ua:= end; cl:='wget.exe -nv --no-cache --max-redirect='+IntToStr(mr)+ ' --no-http-keep-alive --no-check-certificate'; if not(ForceLoadAll) and (LastMod<>'') then cl:=cl+' --header="If-Modified-Since: '+LastMod+'"'; cl:=cl+ ' --save-headers --content-on-error --header="Accept: '+Accept+'"'; if Copy(URL,Length(URL)- Length(GatsbyPageDataSuffix)+1,Length(GatsbyPageDataSuffix))= GatsbyPageDataSuffix then begin i:=9;//past 'https://' while (i<=Length(URL)) and (URL[i]<>'/') do inc(i); cl:=cl+' --referer="'+Copy(URL,1,i)+'"'; end; cl:=cl+ ' --user-agent="'+ua+'" --compression=auto'+ ' -O "'+FilePath+'" "'+URL+'"'; ZeroMemory(@si,SizeOf(TStartupInfo)); si.cb:=SizeOf(TStartupInfo); if not CreateProcess(nil,PChar(cl),nil,nil,true,0,nil,nil,si,pi) then RaiseLastOSError; CloseHandle(pi.hThread); r:=WaitForSingleObject(pi.hProcess,30000); if r<>WAIT_OBJECT_0 then begin TerminateProcess(pi.hProcess,9); raise Exception.Create('LoadExternal:'+SysErrorMessage(r)); end; CloseHandle(pi.hProcess); f:=TFileStream.Create(FilePath,fmOpenRead); try f.Read(w,2); if w=$FEFF then //UTF16? begin i:=f.Size-2; SetLength(Result,i div 2); f.Read(Result[1],i); end else if w=$BBEF then begin w:=0; f.Read(w,1); if w<>$BF then raise Exception.Create('Unexpected partial UTF8BOM'); i:=f.Size-3; SetLength(s,i); f.Read(s[1],i); Result:=UTF8ToWideString(s); end else begin f.Position:=0; i:=f.Size; SetLength(s,i); f.Read(s[1],i); Result:=UTF8ToWideString(s); end; finally f.Free; end; end; function TFeedEater.ParseExternalHeader(var content: WideString): WideString; var i,j:integer; rh:TStringList; s,t:string; begin i:=1; while (i+4<Length(content)) and not( (content[i]=#13) and (content[i+1]=#10) and (content[i+2]=#13) and (content[i+3]=#10)) do inc(i); Result:='';//default; FFeed.LastMod:='';//default rh:=TStringList.Create; try rh.Text:=Copy(content,1,i); if rh.Count<>0 then begin if StartsWith(rh[0],'HTTP/1.1 304') then FFeed.NotModified:=true else if not StartsWith(rh[0],'HTTP/1.1 200') then FFeed.Result:='['+rh[0]+']'; for j:=1 to rh.Count-1 do begin s:=rh[j]; if StartsWithX(s,'Content-Type: ',t) then Result:=t else if StartsWithX(s,'Last-Modified: ',t) then FFeed.LastMod:=t; end; end; finally rh.Free; end; inc(i,4); content:=Copy(content,i,Length(content)-i+1); end; procedure TFeedEater.PerformReplaces(var title,content: WideString); var sl:TStringList; j,rd:IJSONDocument; rc,rt:IJSONDocArray; i:integer; begin rc:=JSONDocArray; rt:=JSONDocArray; j:=JSON(['r',rc,'t',rt]); sl:=TStringList.Create; try sl.LoadFromFile('feeds\'+Format('%.4d',[FFeed.id])+'r.json'); j.Parse(sl.Text); finally sl.Free; end; rd:=JSON; //replaces: content for i:=0 to rc.Count-1 do begin rc.LoadItem(i,rd); PerformReplace(rd,content); end; //replaces: title for i:=0 to rt.Count-1 do begin rt.LoadItem(i,rd); PerformReplace(rd,title); end; //prefixes if VarIsArray(FPostTags) and //varArray of varStrSomething? (VarArrayDimCount(FPostTags)=1) and (VarArrayHighBound(FPostTags,1)-VarArrayLowBound(FPostTags,1)>0) then begin rd:=JSON(j['p']); if rd<>nil then for i:=VarArrayLowBound(FPostTags,1) to VarArrayHighBound(FPostTags,1) do if not(VarIsNull(rd.Item[FPostTags[i]])) then title:=rd.Item[FPostTags[i]]+title; end; end; procedure TFeedEater.PerformGlobalReplaces(var data: WideString); var sl:TStringList; j,rd:IJSONDocument; r:IJSONDocArray; i:integer; begin r:=JSONDocArray; j:=JSON(['r',r]); sl:=TStringList.Create; try sl.LoadFromFile('feeds\'+Format('%.4d',[FFeed.id])+'g.json'); j.Parse(sl.Text); finally sl.Free; end; rd:=JSON; for i:=0 to r.Count-1 do begin r.LoadItem(i,rd); PerformReplace(rd,data); end; end; function TFeedEater.FeedSkipDisplay(d:TDateTime): string; var i:integer; s:string; begin i:=Round((d-FFeed.LoadStart)*1440.0); if i<0 then s:='('+FFeed.Result0+')' else begin //minutes s:=IntToStr(i mod 60)+''''; i:=i div 60; if i<>0 then begin //hours s:=IntToStr(i mod 24)+'h '+s; i:=i div 24; if i<>0 then begin //days s:=IntToStr(i)+'d '+s; end; end; end; if FFeed.Regime<>0 then s:=s+' Regime:'+IntToStr(FFeed.Regime)+'d'; Result:=s; end; procedure TFeedEater.FeedCombineURL(const url, lbl: string); var i,l:integer; begin if LowerCase(Copy(url,1,4))='http' then FFeed.URL:=url else if (Length(url)>1) and (url[1]='/') then if (Length(url)>2) and (url[2]='/') then begin i:=5; l:=Length(FFeed.URL); while (i<=l) and (FFeed.URL[i]<>'/') do inc(i); FFeed.URL:=Copy(FFeed.URL,1,i-1)+url; end else begin i:=5; l:=Length(FFeed.URL); //"http://" while (i<=l) and (FFeed.URL[i]<>'/') do inc(i); inc(i); while (i<=l) and (FFeed.URL[i]<>'/') do inc(i); inc(i); //then to the next "/" while (i<=l) and (FFeed.URL[i]<>'/') do inc(i); FFeed.URL:=Copy(FFeed.URL,1,i-1)+url; end else begin i:=Length(FFeed.URL); while (i<>0) and (FFeed.URL[i]<>'/') do dec(i); FFeed.URL:=Copy(FFeed.URL,1,i-1)+url; end; FFeed.Result:='Feed URL found in content, updating ('+lbl+')'; FFeed.LastMod:=''; end; function TFeedEater.FindFeedURL(const data: WideString): boolean; var reLink:RegExp; mc:MatchCollection; m:Match; sm:SubMatches; i,s1,s2:integer; begin Result:=false;//default reLink:=CoRegExp.Create; reLink.Global:=true; reLink.IgnoreCase:=true; //search for applicable <link type="" href=""> reLink.Pattern:='<link[^>]+?(rel|type|href)=["'']([^"'']+?)["''][^>]+?(type|href)=["'']([^"'']+?)["'']([^>]+?(type|href)=["'']([^"'']+?)["''])?[^>]*?>'; mc:=reLink.Execute(data) as MatchCollection; if mc.Count=0 then //without quotes? begin reLink.Pattern:='<link[^>]+?(rel|type|href)=([^ >]+)[^>]+?(type|href)=([^ >]+)([^>]+?(type|href)=([^ >]+))?[^>]*?>'; mc:=reLink.Execute(data) as MatchCollection; end; i:=0; while (i<mc.Count) and not(Result) do begin m:=mc[i] as Match; inc(i); sm:=m.SubMatches as SubMatches; if (sm[0]='rel') and (sm[1]='https://api.w.org/') and (sm[2]='href') then begin //TODO: check +'wp/v2/articles'? FeedCombineURL(sm[3]+'wp/v2/posts','WPv2'); //TODO: +'?per_page=32'? //extract title reLink.Pattern:='<title>([^<]+?)</title>'; mc:=reLink.Execute(data) as MatchCollection; if mc.Count>0 then FFeed.Name:=HTMLDecode(((mc[0] as Match).SubMatches as SubMatches)[0]); Result:=true; s1:=0;//disable below s2:=0; end else if (sm[0]='rel') and (sm[1]='alternate') and (sm[2]='type') and (sm[5]='href') then begin s1:=3; s2:=6; end else if (sm[0]='rel') and (sm[1]='alternate') and (sm[2]='href') and (sm[5]='type') then begin s1:=6; s2:=3; end else if (sm[2]='rel') and (sm[4]='alternate') and (sm[0]='type') and (sm[5]='href') then begin s1:=1; s2:=6; end else if (sm[0]='type') and (sm[2]='href') then begin s1:=1; s2:=3; end else if (sm[0]='href') and (sm[2]='type') then begin s1:=3; s2:=1; end else begin s1:=0; s2:=0; end; if s1<>0 then if (sm[s1]='application/rss+xml') or (sm[s1]='text/rss+xml') then begin FeedCombineURL(sm[s2],'RSS'); Result:=true; end else if (sm[s1]='application/atom') or (sm[s1]='application/atom+xml') or (sm[s1]='text/atom') or (sm[s1]='text/atom+xml') then begin FeedCombineURL(sm[s2],'Atom'); Result:=true; end; //TODO if sm[s1]='application/json'? end; //search for <meta http-equiv="refresh"> redirects if not(Result) then begin reLink.Pattern:='<meta[^>]+?http-equiv=["'']?refresh["'']?[^>]+?content=["'']\d+?;url=([^"'']+?)["''][^>]*?>'; mc:=reLink.Execute(data) as MatchCollection; if mc.Count<>0 then begin FeedCombineURL(((mc[0] as Match).SubMatches as SubMatches)[0],'Meta'); Result:=true; end; end; //search for id="__gatsby" if not(Result) then if Pos(WideString('<div id="___gatsby"'),data)<>0 then begin FeedCombineURL('/page-data/index/page-data.json','PageDataIndex'); Result:=true; end; end; procedure TFeedEater.RenderGraphs; begin DoGraphs(FDB); end; initialization PGVersion:=''; BlackList:=TStringList.Create; InstagramLastTC:=GetTickCount-InstagramIntervalMS; InstagramFailed:=0.0; finalization BlackList.Free; end.
unit uThreadBarraProgresso; interface uses System.Classes, Vcl.ComCtrls; type TThreadBarraProgresso = class(TThread) private FBarraProgresso: TProgressBar; FnTempoSleep: integer; FnPosicao: integer; procedure AtualizarProgresso; protected procedure Execute; override; public property BarraProgresso: TProgressBar read FBarraProgresso write FBarraProgresso; property TempoSleep: Integer read FnTempoSleep write FnTempoSleep; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure ThreadBarraProgresso.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { ThreadBarraProgresso } procedure TThreadBarraProgresso.AtualizarProgresso; begin FBarraProgresso.Position := FnPosicao; end; procedure TThreadBarraProgresso.Execute; var nPosicao: integer; begin for nPosicao := 0 to 100 do begin FnPosicao := nPosicao; Sleep(FnTempoSleep); Synchronize(AtualizarProgresso); end; end; end.
{$APPTYPE CONSOLE} unit u_Main; interface uses Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, GLCadencer, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene, GLMaterial, GLObjects, GLCoordinates, GLMesh, GLAsyncTimer, GLKeyboard, GLFBORenderer, GLRenderContextInfo, GLVectorGeometry, GLGeomObjects, GLFileJpeg, uLog, u_Map; type TForm1 = class(TForm) GLScene1: TGLScene; vp: TGLSceneViewer; cad: TGLCadencer; cam: TGLCamera; dc_cam: TGLDummyCube; mesh: TGLMesh; GLCube1: TGLCube; at: TGLAsyncTimer; dc_world: TGLDummyCube; dogl: TGLDirectOpenGL; fbo: TGLFBORenderer; matlib: TGLMaterialLibrary; dc_map: TGLDummyCube; back: TGLPlane; cam_fbo: TGLCamera; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure atTimer(Sender: TObject); procedure cadProgress(Sender: TObject; const deltaTime,newTime: Double); procedure doglRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure fboAfterRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure FormShow(Sender: TObject); public map: c_Map; end; var Form1: TForm1; map_point: TPoint; map_modified: boolean; implementation {$R *.dfm} // // setup // procedure TForm1.FormCreate; begin isConsole := True; SetCurrentDir('data'); log_tick; log('load map:', 10); map_point := point(0,0); map := c_Map.Create(self, 'map.bmp'); resize; log('uploading...', 14); vp.Buffer.Render; log( 'form create:', 10 ); log( format( '%.3f sec', [ log_delta ])); end; // // cadProgress // procedure TForm1.cadProgress; begin // animation with dc_cam.Position do begin if abs(x - map_point.X) > 9 then begin map_point.X := round(x); map_modified := true; end; if abs(Floor(Y) - map_point.Y) > 4 then begin map_point.Y := floor(y); map_modified := true; end; end; dc_cam.Translate(deltatime * 4, deltatime * 2, 0); vp.Invalidate; if iskeydown(vk_escape) then close; end; // // doglRender // procedure TForm1.doglRender; begin // redraw background texture if map_modified then begin map.redraw(mesh, map_point); back.Position.SetPoint(map_point.X, map_point.Y, 0); mesh.AbsolutePosition := dc_cam.AbsolutePosition; fbo.Active := true; end; map_modified := false; end; // // fboAfterRender // procedure TForm1.fboAfterRender; begin fbo.Active := false; end; // // resize // procedure TForm1.FormResize; var c1,c2: cardinal; begin // resize viewport if (clientWidth - 40) / (clientHeight - 40) > 2 then begin c1 := clientHeight - 40; c2 := clientWidth div 2 - c1; vp.BoundsRect := rect(c2, 20, c1 * 2 + c2, c1 + 20); end else begin c1 := (clientWidth - 40) div 2; c2 := clientHeight div 2 - c1 div 2; vp.BoundsRect := rect(20, c2, c1 * 2 + 20, c2 + c1); end; // resize fbo c1 := 1 shl ceil(log2(vp.Width)); if fbo.Width <> c1 then begin fbo.Width := c1; fbo.Height := c1 div 2; map_modified := true; log(format('new FBO size: %d x %d', [fbo.Width, fbo.Height]), 14); end; end; // // timer // procedure TForm1.atTimer; begin caption := 'Tiles: ' + vp.FramesPerSecondText(2); vp.ResetPerformanceMonitor; end; // // show // procedure TForm1.FormShow; begin cad.Enabled := true; end; end.
unit LightControl; interface uses SysUtils, Generics.Collections, Math, Windows; type TLampe = class(TObject) private fR, fG, fB: Integer; // 0..4095 fH, fS, fV: Real; // 0..2*Pi, 0..1, 0..1 fHasChanged: boolean; procedure RGBToHSV; procedure HSVToRGB; function BoundRGB(const aValue: Integer): Integer; function BoundFraction(const aValue: Real): Real; function BoundAngle(const aValue: Real): Real; public property R: Integer read fR; property G: Integer read fG; property B: Integer read fB; property H: Real read fH; property S: Real read fS; property V: Real read fV; property HasChanged: boolean read fHasChanged write fHasChanged; procedure SetColorRGB(aR, aG, aB: Integer); procedure SetColorHSV(aH, aSat, aV: Real); end; TLightControl = class(TObject) private fHelligkeit: Real; fSaettigung: Real; fGeschwindigkeit: Real; fWinkelDifferenz: Real; public fMessageCounter: Integer; fLampen: TList<TLampe>; fStartWinkel: Real; constructor Create(const anzahlLampen: Integer); destructor Destroy; function SetzeHelligkeit(einWert: Real): AnsiString; function SetzeHelligkeitProzent(einWert: Real): AnsiString; function SetzeSaettigung(einWert: Real): AnsiString; function SetzeSaettigungProzent(einWert: Real): AnsiString; function SetzeGeschwindigkeit(deltaPhi: Real): AnsiString; function SetzeGeschwindigkeitGrad(deltaPhi: Real): AnsiString; function StarteMoodlight(startFarbe, farbUnterschied: Real): AnsiString; function StarteMoodlightGrad(startFarbe, farbUnterschied: Real): AnsiString; function SchalteLampe(nummer: Integer; istAn: boolean): AnsiString; function SetzeFarbe(nummer, R, G, B: Integer): AnsiString; property Helligkeit: Real read fHelligkeit; property Saettigung: Real read fSaettigung; property Geschwindigkeit: Real read fGeschwindigkeit; property WinkelDifferenz: Real read fWinkelDifferenz; end; implementation { TLightControl } constructor TLightControl.Create(const anzahlLampen: Integer); var i: Integer; begin inherited Create; fHelligkeit := 0.75; fSaettigung := 0.9; fGeschwindigkeit := 0.01; fWinkelDifferenz := 135; Self.fLampen := TList<TLampe>.Create; for i := 0 to anzahlLampen - 1 do fLampen.Add(TLampe.Create); end; destructor TLightControl.Destroy; var i: Integer; begin for i := 0 to fLampen.Count - 1 do fLampen.Items[i].Free; fLampen.Free; inherited; end; function TLightControl.SchalteLampe(nummer: Integer; istAn: boolean): AnsiString; begin if istAn then Result := '251,' + IntToStr(nummer) + ',1' else Result := '251,' + IntToStr(nummer) + ',0'; Inc(fMessageCounter); end; function TLightControl.SetzeFarbe(nummer, R, G, B: Integer): AnsiString; begin Result := IntToStr(nummer) + ',' + IntToStr(R) + ',' + IntToStr(G) + ',' + IntToStr(B); Inc(fMessageCounter); end; function TLightControl.SetzeGeschwindigkeit(deltaPhi: Real): AnsiString; begin Result := SetzeGeschwindigkeitGrad(deltaPhi * 180 / Pi); end; function TLightControl.SetzeGeschwindigkeitGrad(deltaPhi: Real): AnsiString; begin if (deltaPhi >= 0) and (deltaPhi <= 360) then begin fGeschwindigkeit := deltaPhi; DecimalSeparator := '.'; Result := '252,' + FloatToStr(RoundTo(deltaPhi, -4)); Inc(fMessageCounter); end; end; function TLightControl.SetzeHelligkeit(einWert: Real): AnsiString; var i: Integer; begin if (einWert >= 0) and (einWert <= 1) then begin fHelligkeit := einWert; DecimalSeparator := '.'; Result := '254,' + FloatToStr(RoundTo(einWert, -4)); for i := 0 to fLampen.Count - 1 do begin fLampen.Items[i].fV := einWert; end; Inc(fMessageCounter); end; end; function TLightControl.SetzeHelligkeitProzent(einWert: Real): AnsiString; begin Result := SetzeHelligkeit(einWert / 100); end; function TLightControl.SetzeSaettigung(einWert: Real): AnsiString; var i: Integer; begin if (einWert >= 0) and (einWert <= 1) then begin fSaettigung := einWert; DecimalSeparator := '.'; Result := '253,' + FloatToStr(RoundTo(einWert, -4)); for i := 0 to fLampen.Count - 1 do begin fLampen.Items[i].fS := einWert; end; Inc(fMessageCounter); end; end; function TLightControl.SetzeSaettigungProzent(einWert: Real): AnsiString; begin Result := SetzeSaettigung(einWert / 100); end; function TLightControl.StarteMoodlight(startFarbe, farbUnterschied: Real): AnsiString; begin Result := StarteMoodlightGrad(startFarbe * 180 / Pi, farbUnterschied * 180 / Pi); end; function TLightControl.StarteMoodlightGrad(startFarbe, farbUnterschied: Real): AnsiString; begin if (startFarbe >= 0) and (startFarbe <= 360) and (farbUnterschied >= 0) and (farbUnterschied <= 360) then begin fWinkelDifferenz := farbUnterschied; DecimalSeparator := '.'; Result := '255,' + FloatToStr(RoundTo(startFarbe, -4)) + ',' + FloatToStr(RoundTo(farbUnterschied, -4)); Inc(fMessageCounter); end; end; { TLampe } {* Stellt sicher, dass ein übergebener Winkel in Radians zwischen * 0 und 2*Pi liegt. Bei Winkeln bis -2*Pi bzw. +4*Pi wird entsprechend * auf den gültigen Bereich umgerechnet. Bei allen anderen werten wird * auf 0..2*Pi begrenzt.} function TLampe.BoundAngle(const aValue: Real): Real; begin if (aValue >= 0) and (aValue <= 2*Pi) then Result := aValue else if aValue < 0 then Result := Max(2*Pi + aValue, 0) else Result := Min(aValue - 2*Pi, 2*Pi); end; {* Stellt sicher, dass ein übergebener Wert zwischen 0 und 1 liegt. *} function TLampe.BoundFraction(const aValue: Real): Real; begin if (aValue >= 0) and (aValue <= 1) then Result := aValue else if aValue < 0 then Result := 0 else Result := 1; end; {* Stellt sicher, dass ein übergebener RGB-Wert zwischen 0 und 4095 liegt. *} function TLampe.BoundRGB(const aValue: Integer): Integer; begin if (aValue >= 0) and (aValue <= 4095) then Result := aValue else if aValue < 0 then Result := 0 else Result := 4095; end; procedure TLampe.HSVToRGB; var C, X, m, ht: Real; rs, gs, bs: Real; rm: Real; begin if fS = 0 then // Sonderfall weiß bzw. grau begin fR := Round(fV * 4095); fG := Round(fV * 4095); fB := Round(fV * 4095); end else // Alle anderen fälle begin ht := fH * 180 / Pi; // hue in Grad umrechnen C := fV * fS; rm := ht / 60 - 2 * trunc(ht / 60 / 2); // Modulo Division für Real X := C * (1 - abs(rm - 1)); m := fV - C; if fH < Pi / 3 then begin rs := C; gs := X; bs := 0; end else if fH < 2 * Pi / 3 then begin rs := X; gs := C; bs := 0; end else if fH < Pi then begin rs := 0; gs := C; bs := X; end else if fH < 4 * Pi / 3 then begin rs := 0; gs := X; bs := C; end else if fH < 5 * Pi / 3 then begin rs := X; gs := 0; bs := C; end else begin rs := C; gs := 0; bs := X; end; fR := Round((rs + m) * 4095); fG := Round((gs + m) * 4095); fB := Round((bs + m) * 4095); end; end; procedure TLampe.RGBToHSV; var Maximum, Minimum: Real; Rc, Gc, Bc: Real; begin Maximum := Max(fR, Max(fG, fB)); Minimum := Min(fR, Min(fG, fB)); fV := Maximum / 4095; if Maximum <> 0 then fS := (Maximum - Minimum) / Maximum else fS := 0; if fS = 0 then fH := 0 // arbitrary value else begin Assert(Maximum <> Minimum); Rc := (Maximum - fR) / (Maximum - Minimum); Gc := (Maximum - fG) / (Maximum - Minimum); Bc := (Maximum - fB) / (Maximum - Minimum); if fR = Maximum then fH := Bc - Gc else if fG = Maximum then fH := 2 + Rc - Bc else begin Assert(fB = Maximum); fH := 4 + Gc - Rc; end; fH := fH * Pi / 3; fH := BoundAngle(fH); end; end; procedure TLampe.SetColorHSV(aH, aSat, aV: Real); begin if (fH <> aH) or (fS <> aSat) or (fV <> aV) then begin fH := BoundAngle(aH); fS := BoundFraction(aSat); fV := BoundFraction(aV); HSVToRGB; fHasChanged := true; end; end; procedure TLampe.SetColorRGB(aR, aG, aB: Integer); begin if (fR <> aR) or (fG <> aG) or (fB <> aB) then begin fR := BoundRGB(aR); fG := BoundRGB(aG); fB := BoundRGB(aB); RGBToHSV; fHasChanged := true; end; end; end.
{ Role Receive mouse pointer information - Detect the item of the mouse position - Firing Mouse-event on item 역할을 분담하는 것이 맞는가? DrawObj에 구현하는 것이 맞나? } unit ThCanvasEventProcessor; interface uses System.Classes, GR32, ThTypes, ThItemCollections; type /// 도형 그리기의 마우스 처리 담당 TThShapeDrawMouseProcessor = class private FLastPoint: TFloatPoint; FMouseDowned: Boolean; FDragState: TThShapeDragState; FItemList: TThItemList; FTargetItem: IThSelectableItem; // Mouse가 올라간 Item FTargetConnection: IThConnectableItem; // Mouse가 올라간 연결가능한 Item(dsItemResize 시 할당 됨) FSelectedItems: TThSelectedItems; FShapeId: string; procedure SetDragState(const Value: TThShapeDragState); procedure SetShapeId(const Value: string); public constructor Create(AItemList: TThItemList; ASelectedItems: TThSelectedItems); procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); property DragState: TThShapeDragState read FDragState write SetDragState; property ShapeId: string read FShapeId write SetShapeId; end; implementation uses Vcl.Forms, System.SysUtils, System.UITypes, ThShapeItem, ThItemStyle, ThItemHandle; { TThMouseHandler } constructor TThShapeDrawMouseProcessor.Create(AItemList: TThItemList; ASelectedItems: TThSelectedItems); begin FItemList := AItemList; FSelectedItems := ASelectedItems; end; procedure TThShapeDrawMouseProcessor.MouseDown(const APoint: TFloatPoint; AShift: TShiftState); var PressedShift: Boolean; begin FLastPoint := APoint; FMouseDowned := True; if FDragState = dsItemAdd then begin FTargetItem := TThShapeItemFactory.GetShapeItem(FShapeId, TThShapeStyle.Create); FTargetItem.ResizeItem(FLastPoint, FLastPoint); FItemList.Add(FTargetItem); FSelectedItems.Clear; FSelectedItems.Add(FTargetItem); DragState := dsItemResize; FShapeId := ''; end else if FDragState = dsNone then begin { Click Canvas : Clear Selections Item : Clear selection, Select Item Selected Item : None Item Handle : Start drag Shift + Click Canvas : None Item : Add to selection Selected Item : Remove from selection Item Handle : Don't show } // Select item(Unselect, Multi-select) PressedShift := AShift * [ssShift, ssCtrl] <> []; // Canvas click if not Assigned(FTargetItem) then begin if not PressedShift then FSelectedItems.Clear; end else begin if not FTargetItem.Selected then // Non-selected item click begin if not PressedShift then FSelectedItems.Clear; FSelectedItems.Add(FTargetitem); end else // Selected item click begin if PressedShift then begin FTargetItem.Selected := False; FSelectedItems.Remove(FTargetItem); end; end; end; if Assigned(FTargetItem) and FTargetItem.Selected then begin if Assigned(FTargetItem.Selection.HotHandle) then DragState := dsItemResize else DragState := dsItemMove; end; end; end; procedure TThShapeDrawMouseProcessor.MouseMove(const APoint: TFloatPoint; AShift: TShiftState); var Pt: TFloatPoint; Item: IThSelectableItem; ConnectionItem: IThConnectableItem; MovePoint: TFloatPoint; begin Pt := APoint; Item := FItemList.GetItemAtPoint(APoint); if not FMouseDowned then begin if FTargetItem <> Item then begin if Assigned(FTargetItem) then FTargetItem.MouseLeave(APoint); FTargetItem := Item; if Assigned(FTargetItem) then FTargetItem.MouseEnter(APoint) end; if Assigned(FTargetItem) then FTargetItem.MouseMove(APoint); end else begin case FDragState of dsItemMove: begin MovePoint := APoint - FLastPoint; FSelectedItems.MoveItems(MovePoint); FLastPoint := APoint; end; dsItemResize: begin // 연결선을 변경하는 경우 // 연결 대상 인지 // 대상과 연결 if Supports(FTargetItem, IThConnectorItem) then begin ConnectionItem := FItemList.GetConnectionItem(APoint); if FTargetConnection <> ConnectionItem then begin if Assigned(FTargetConnection) then begin // FTargetConnection.MouseLeave(APoint); // IThSelectableItem과 IThConnectorItem 분리? FTargetConnection.HideConnection; end; FTargetConnection := ConnectionItem; if Assigned(FTargetConnection) then begin // FTargetConnection.MouseEnter(APoint); FTargetConnection.ShowConnection; end; end; if Assigned(FTargetConnection) then begin FTargetConnection.MouseMove(APoint); if Assigned(FTargetConnection.Connection.HotHandle) then Pt := TThItemHandle(FTargetConnection.Connection.HotHandle).Point; end; end; FTargetItem.Selection.ResizeItem(Pt); end; end; end; end; procedure TThShapeDrawMouseProcessor.MouseUp(const APoint: TFloatPoint; AShift: TShiftState); var ConnectorItem: IThConnectorItem; begin FMouseDowned := False; if FDragState = dsItemResize then begin if Assigned(FTargetConnection) then begin if FTargetConnection.IsConnectable and Supports(FTargetItem, IThConnectorItem, ConnectorItem) then begin FTargetConnection.ConnectTo(ConnectorItem); end; end; end; if Assigned(FTargetConnection) then begin FTargetConnection.HideConnection; FTargetConnection := nil; end; DragState := dsNone; end; procedure TThShapeDrawMouseProcessor.SetDragState( const Value: TThShapeDragState); begin FDragState := Value; case FDragState of dsNone: ; dsItemAdd: Screen.Cursor := crCross; dsItemMove: ; dsItemResize: Screen.Cursor := crCross; end; end; procedure TThShapeDrawMouseProcessor.SetShapeId(const Value: string); begin FShapeId := Value; if FShapeId = '' then DragState := dsNone else DragState := dsItemAdd; end; end.
unit Card.Confetti; interface uses W3C.HighResolutionTime, Card.Framework; type TConfetti = class; TConfettiSnippet = class private FOwner: TConfetti; FRotationSpeed: Float; FAngle: Float; FRotation: Float; FOscillationSpeed: Float; FSpeed: TVector2f; FTime: Float; FCorners: array [0..3] of TVector2f; FColors: array [0..1] of String; FPosition: TVector2f; public constructor Create(Owner: TConfetti); procedure Resize; procedure Draw(ElapsedSeconds: Float = 0); end; TConfetti = class(TCanvas2DElement) private FConfettiSnippets: array of TConfettiSnippet; FRunning: Boolean; FRise: Boolean; FAlpha: Float; FAnimHandle: Integer; FPixelRatio: Float; FLastTimeStamp: TDOMHighResTimeStamp; public constructor Create(Owner: IHtmlElementOwner); overload; override; procedure Resize; procedure Draw(TimeStamp: TDOMHighResTimeStamp); procedure Start; procedure Stop; procedure Reset; property Running: Boolean read FRunning; property PixelRatio: Float read FPixelRatio; property Rise: Boolean read FRise; end; implementation uses WHATWG.Console, W3C.HTML5; var GRequestAnimFrame: function(const AMethod: TFrameRequestCallback): Integer; var GCancelAnimFrame: procedure(Handle: Integer); procedure InitAnimationFrameShim; begin asm @GRequestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ return window.setTimeout(callback(50/3), 50/3); }; })(); @GCancelAnimFrame = (function(){ return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame || function( handle ){ window.clearTimeout(handle); }; })(); end; end; function RequestAnimationFrame(const AMethod: TFrameRequestCallback): Integer; begin if not Assigned(GRequestAnimFrame) then InitAnimationFrameShim; Result := GRequestAnimFrame(aMethod); end; procedure CancelAnimationFrame(Handle: Integer); begin if not Assigned(GCancelAnimFrame) then InitAnimationFrameShim; GCancelAnimFrame(handle); end; { TConfettiSnippet } constructor TConfettiSnippet.Create(Owner: TConfetti); const CColors = [ ['#df0049', '#660671'], ['#00e857', '#005291'], ['#2bebbc', '#05798a'], ['#ffd200', '#b06c00'] ]; begin FOwner := Owner; FPosition := TVector2F.Create( Random * FOwner.CanvasElement.Width, Random * FOwner.CanvasElement.Height); FColors := CColors[RandomInt(CColors.Length)]; var PixelRatio := FOwner.PixelRatio; FRotationSpeed := 2 * Pi * (Random + 1); FAngle := Random * 2 * Pi; FRotation := Random * 2 * Pi; FOscillationSpeed := Random * 1.5 + 0.5; FSpeed := TVector2f.Create(PixelRatio * (40), PixelRatio * (Random * 60 + 50)); for var Index := 0 to 3 do FCorners[Index] := TVector2f.Create( Cos(FAngle + Pi * (Index * 0.5 + 0.25)) * 5 * PixelRatio, Sin(FAngle + Pi * (Index * 0.5 + 0.25)) * 5 * PixelRatio); FTime := random; end; procedure TConfettiSnippet.Resize; begin FPosition := TVector2F.Create( Random * FOwner.CanvasElement.Width, Random * FOwner.CanvasElement.Height); end; procedure TConfettiSnippet.Draw(ElapsedSeconds: Float = 0); begin FTime += ElapsedSeconds; FRotation += FRotationSpeed * ElapsedSeconds; var CosZ := Cos(FRotation); FPosition.x += Cos(FTime * FOscillationSpeed) * FSpeed.X * ElapsedSeconds; FPosition.y += FSpeed.Y * ElapsedSeconds; if FPosition.y > FOwner.CanvasElement.Height then begin FPosition.x := Random * FOwner.CanvasElement.Width; FPosition.y := 0; end; var Context := FOwner.Context; if CosZ > 0 then Context.fillStyle := FColors[0] else Context.fillStyle := FColors[1]; Context.beginPath; Context.moveTo( FPosition.x + FCorners[0].x, FPosition.y + FCorners[0].y * CosZ); for var Index := 1 to 3 do Context.LineTo( FPosition.x + FCorners[Index].x, FPosition.y + FCorners[Index].y * CosZ); Context.closePath; Context.fill; end; { TConfetti } constructor TConfetti.Create(Owner: IHtmlElementOwner); begin inherited Create(Owner); // determine pixel ratio FPixelRatio := 1; asm @FPixelRatio = window.devicePixelRatio || 1; end; CanvasElement.width := Round(FPixelRatio * Window.innerWidth); CanvasElement.height := Round(FPixelRatio * Window.innerHeight); Style.display := 'none'; for var i := 0 to 99 do FConfettiSnippets.Add(TConfettiSnippet.Create(Self)); FAlpha := 0; end; procedure TConfetti.Draw(TimeStamp: TDOMHighResTimeStamp); begin // get time between the last frame var ElapsedSeconds := Clamp(0.001 * (TimeStamp - FLastTimeStamp), 0, 0.5); FLastTimeStamp := TimeStamp; Context.clearRect(0, 0, CanvasElement.width, CanvasElement.Height); Context.GlobalAlpha := FAlpha; for var ConfettiSnippet in FConfettiSnippets do ConfettiSnippet.Draw(ElapsedSeconds); Context.GlobalAlpha := 1; if FRise then FAlpha := Min(FAlpha + ElapsedSeconds, 1) else begin FAlpha := FAlpha - ElapsedSeconds; if FAlpha < 0 then begin FAlpha := 0; CancelAnimationFrame(FAnimHandle); Style.display := 'none'; Exit; end; end; FAnimHandle := RequestAnimationFrame(Draw); end; procedure TConfetti.Resize; begin var NewWidth := Round(FPixelRatio * Window.innerWidth); var NewHeight := Round(FPixelRatio * Window.innerHeight); if (CanvasElement.width <> NewWidth) or (CanvasElement.height <> NewHeight) then begin CanvasElement.width := NewWidth; CanvasElement.height := NewHeight; for var ConfettiSnippet in FConfettiSnippets do ConfettiSnippet.Resize; end; end; procedure TConfetti.Start; begin FRise := True; Style.display := 'block'; FLastTimeStamp := Now; FAnimHandle := RequestAnimationFrame(Draw); end; procedure TConfetti.Stop; begin FRise := False; end; procedure TConfetti.Reset; begin FRise := False; end; end.
unit MainFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, Data.Win.ADODB, ppPrnabl, ppClass, ppCtrls, ppBands, ppCache, ppDB, ppDesignLayer, ppParameter, ppProd, ppReport, ppComm, ppRelatv, ppDBPipe, ppVar, ppRichTx, ppStrtch, ppMemo; type TMainForm = class(TForm) Connection1: TADOConnection; DataSource1: TDataSource; Pipeline1: TppDBPipeline; Report1: TppReport; ppParameterList1: TppParameterList; ppDesignLayers1: TppDesignLayers; ppDesignLayer1: TppDesignLayer; ppHeaderBand1: TppHeaderBand; ppDetailBand1: TppDetailBand; ppFooterBand1: TppFooterBand; ppDBText1: TppDBText; PreviewButton: TButton; LanguageButton: TButton; Query1: TADOQuery; ppDBText3: TppDBText; procedure FormCreate(Sender: TObject); procedure PreviewButtonClick(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateItems; end; var MainForm: TMainForm; implementation {$R *.dfm} uses NtBase, NtLocalization, NtLanguageDlg; procedure TMainForm.UpdateItems; function GetLanguageCode: String; begin if LoadedResourceLocale = '' then Result := 'en' else Result := TNtLocale.LocaleToIso639(TNtLocale.ExtensionToLocale(LoadedResourceLocale)); end; begin Connection1.Connected := True; Query1.Close; Query1.SQL.Text := Format('SELECT * FROM Sport WHERE Lang=''%s''', [GetLanguageCode]); Query1.Open; end; procedure TMainForm.FormCreate(Sender: TObject); begin UpdateItems; end; procedure TMainForm.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select('en', '', lnNative, [ldShowErrorIfNoDll], [roSaveLocale]) then UpdateItems; end; procedure TMainForm.PreviewButtonClick(Sender: TObject); begin Report1.Print; end; end.
namespace Basic_WebAssembly_GUI_App; uses RemObjects.Elements.RTL.Delphi, RemObjects.Elements.RTL.Delphi.VCL; type [Export] Program = public class public method HelloWorld; begin Application := new TApplication(nil); Application.Initialize; Application.Run; // Create form var lForm := new TForm(nil); lForm.Width := 800; // we can display the form in an existing div element. If Show parameter is nil, a new div is created lForm.Show(nil); var lTopLabel := new TLabel(lForm); lTopLabel.Left := 1; lTopLabel.Parent := lForm; lTopLabel.Caption := 'Write the item caption on the edit and press Add New button to add to ListBox:'; var lButton := new TButton(lForm); lButton.Left := 50; lButton.Top := 50; lButton.Caption := 'Add New'; lButton.Parent := lForm; var lEdit := new TEdit(lForm); lEdit.Left := 150; lEdit.Top := 50; lEdit.Parent := lForm; var lListBox := new TListBox(lForm); lListBox.Left := 350; lListBox.Top := 50; lListBox.Parent := lForm; lListBox.Width := 250; lListBox.MultiSelect := true; lButton.OnClick := () -> begin lListBox.Items.Add(lEdit.Text); end; var lChangeLabel := new TLabel(lForm); lChangeLabel.Top := 165; lChangeLabel.Parent := lForm; lChangeLabel.Caption := 'Press button to change label font:'; var lChangeButton := new TButton(lForm); lChangeButton.Left := 50; lChangeButton.Top := 200; lChangeButton.Caption := 'Change font'; lChangeButton.Parent := lForm; var lLabel := new TLabel(lForm); lLabel.Left := 150; lLabel.Top := 200; lLabel.Caption := 'Sample text!'; lLabel.Parent := lForm; lChangeButton.OnClick := () -> begin lLabel.Font.Name := 'Verdana'; lLabel.Font.Size := 24; end; var lMemo := new TMemo(lForm); lMemo.Left := 50; lMemo.Top := 300; lMemo.Width := 250; lMemo.Height := 150; lMemo.Parent := lForm; var lMemoButton := new TButton(lForm); lMemoButton.Left := 350; lMemoButton.Top := 325; lMemoButton.Caption := 'Add text'; lMemoButton.Parent := lForm; var lList := TStringList.Create; lList.Add('one line'); lList.Add('another one'); lMemoButton.OnClick := () -> begin lMemo.Lines.AddStrings(lList); end; var lDisplayButton := new TButton(lForm); lDisplayButton.Top := lMemoButton.Top; lDisplayButton.Left := 450; lDisplayButton.Caption := 'Show memo text'; lDisplayButton.Parent := lForm; lDisplayButton.OnClick := ()-> begin ShowMessage(lMemo.Lines.Text); end; end; end; end.
//This event type is for NPC's "OnTouch" property. When a character walks into //the walking field, this executes. unit OnTouchCellEvent; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses NPC, Being, Character; type TOnTouchCellEvent = class protected fScriptNPC : TScriptNPC; public property ScriptNPC : TScriptNPC read fScriptNPC; Constructor Create(AScriptNPC : TScriptNPC); Procedure Execute(ACharacter : TCharacter); end; implementation Constructor TOnTouchCellEvent.Create(AScriptNPC : TScriptNPC); begin inherited Create; fScriptNPC := AScriptNPC; end; //[2007/05/28] Tsusai - Added execution checks. Procedure TOnTouchCellEvent.Execute(ACharacter : TCharacter); begin if (ACharacter.ScriptStatus = SCRIPT_NOTRUNNING) and (ACharacter.BeingState = BeingStanding) then begin ACharacter.ScriptBeing := fScriptNPC; fScriptNPC.OnTouch(ACharacter); end; end; end.
namespace AppBarExample; interface uses System, System.Collections.Generic, System.IO, System.Linq, Windows.ApplicationModel, Windows.ApplicationModel.Activation, Windows.Foundation, Windows.Foundation.Collections, Windows.UI.Xaml, Windows.UI.Xaml.Controls, Windows.UI.Xaml.Controls.Primitives, Windows.UI.Xaml.Data, Windows.UI.Xaml.Input, Windows.UI.Xaml.Media, Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> type App = partial class(Application) private /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> method OnSuspending(sender: System.Object; args: SuspendingEventArgs); protected /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> method OnLaunched(args: LaunchActivatedEventArgs); override; public /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> constructor ; end; implementation constructor App; begin InitializeComponent(); Suspending += OnSuspending; end; method App.OnLaunched(args: LaunchActivatedEventArgs); begin // Do not repeat app initialization when already running, just ensure that // the window is active if args.PreviousExecutionState = ApplicationExecutionState.Running then begin Window.Current.Activate(); exit end; if args.PreviousExecutionState = ApplicationExecutionState.Terminated then begin //TODO: Load state from previously suspended application end; // Create a Frame to act navigation context and navigate to the first page var rootFrame := new Frame(); if not rootFrame.Navigate(typeOf(MainPage)) then begin raise new Exception('Failed to create initial page') end; // Place the frame in the current Window and ensure that it is active Window.Current.Content := rootFrame; Window.Current.Activate() end; method App.OnSuspending(sender: Object; args: SuspendingEventArgs); begin var deferral := args.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete() end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFeedback<p> A scene object encapsulating the OpenGL feedback buffer.<p> This object, when Active, will render it's children using the GL_FEEDBACK render mode. This will render the children into the feedback Buffer rather than into the frame buffer.<p> Mesh data can be extracted from the buffer using the BuildMeshFromBuffer procedure. For custom parsing of the buffer use the Buffer SingleList. The Buffered property will indicate if there is valid data in the buffer.<p> <b>History : </b><font size=-1><ul> <li>05/03/10 - DanB - More state added to TGLStateCache <li>30/03/07 - DaStr - Added $I GLScene.inc <li>28/03/07 - DaStr - Renamed parameters in some methods (thanks Burkhard Carstens) (Bugtracker ID = 1678658) <li>23/07/04 - SG - Creation. </ul></font> } unit GLFeedback; interface {$I GLScene.inc} uses Classes, SysUtils, GLVectorGeometry, GLVectorLists, GLScene, GLVectorFileObjects, GLTexture, GLRenderContextInfo, GLState; type TFeedbackMode = (fm2D, fm3D, fm3DColor, fm3DColorTexture, fm4DColorTexture); // TGLFeedback {: An object encapsulating the OpenGL feedback rendering mode. } TGLFeedback = class(TGLBaseSceneObject) private { Private Declarations } FActive : Boolean; FBuffer : TSingleList; FMaxBufferSize : Cardinal; FBuffered : Boolean; FCorrectionScaling : Single; FMode : TFeedbackMode; protected { Protected Declarations } procedure SetMaxBufferSize(const Value : Cardinal); procedure SetMode(const Value : TFeedbackMode); public { Public Declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure DoRender(var ARci : TRenderContextInfo; ARenderSelf, ARenderChildren : Boolean); override; {: Parse the the feedback buffer for polygon data and build a mesh into the assigned lists. } procedure BuildMeshFromBuffer( Vertices : TAffineVectorList = nil; Normals : TAffineVectorList = nil; TexCoords : TAffineVectorList = nil; VertexIndices : TIntegerList = nil); //: True when there is data in the buffer ready for parsing property Buffered : Boolean read FBuffered; //: The feedback buffer property Buffer : TSingleList read FBuffer; {: Vertex positions in the buffer needs to be scaled by CorrectionScaling to get correct coordinates. } property CorrectionScaling : Single read FCorrectionScaling; published { Published Declarations } //: Maximum size allocated for the feedback buffer property MaxBufferSize : Cardinal read FMaxBufferSize write SetMaxBufferSize; //: Toggles the feedback rendering property Active : Boolean read FActive write FActive; //: The type of data that is collected in the feedback buffer property Mode : TFeedbackMode read FMode write SetMode; property Visible; end; // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- implementation // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- uses OpenGL1x, OpenGLTokens, GLMeshUtils; // ---------- // ---------- TGLFeedback ---------- // ---------- // Create // constructor TGLFeedback.Create(AOwner : TComponent); begin inherited; FMaxBufferSize:=$100000; FBuffer:=TSingleList.Create; FBuffer.Capacity:=FMaxBufferSize div SizeOf(Single); FBuffered:=False; FActive:=False; FMode:=fm3DColorTexture; end; // Destroy // destructor TGLFeedback.Destroy; begin FBuffer.Free; inherited; end; // DoRender // procedure TGLFeedback.DoRender(var ARci : TRenderContextInfo; ARenderSelf, ARenderChildren : Boolean); function RecursChildRadius(obj : TGLBaseSceneObject) : Single; var i : Integer; childRadius : Single; begin childRadius:=0; Result:=obj.BoundingSphereRadius+VectorLength(obj.AbsolutePosition); for i:=0 to obj.Count-1 do childRadius:=RecursChildRadius(obj.Children[i]); if childRadius>Result then Result:=childRadius; end; var i : integer; radius : Single; atype : cardinal; begin FBuffer.Count:=0; try if (csDesigning in ComponentState) or not Active then exit; if not ARenderChildren then exit; FCorrectionScaling:=1.0; for i:=0 to Count-1 do begin radius:=RecursChildRadius(Children[i]); if radius>FCorrectionScaling then FCorrectionScaling:=radius+1e-5; end; case FMode of fm2D : aType:=GL_2D; fm3D : aType:=GL_3D; fm3DColor : aType:=GL_3D_COLOR; fm3DColorTexture : aType:=GL_3D_COLOR_TEXTURE; fm4DColorTexture : aType:=GL_4D_COLOR_TEXTURE; else aType:=GL_3D_COLOR_TEXTURE; end; FBuffer.Count:=FMaxBufferSize div SizeOf(Single); glFeedBackBuffer(FMaxBufferSize, atype, @FBuffer.List[0]); ARci.GLStates.PushAttrib([sttEnable, sttViewport]); ARci.GLStates.Disable(stCullFace); glMatrixMode(GL_PROJECTION); glPushMatrix; glLoadIdentity; glMatrixMode(GL_MODELVIEW); glPushMatrix; glLoadIdentity; glScalef( 1.0/FCorrectionScaling, 1.0/FCorrectionScaling, 1.0/FCorrectionScaling); glViewPort(-1,-1,2,2); glRenderMode(GL_FEEDBACK); Self.RenderChildren(0, Count-1, ARci); FBuffer.Count:=glRenderMode(GL_RENDER); glMatrixMode(GL_MODELVIEW); glPopMatrix; glMatrixMode(GL_PROJECTION); glPopMatrix; glMatrixMode(GL_MODELVIEW); ARci.GLStates.PopAttrib; finally FBuffered:=(FBuffer.Count>0); if ARenderChildren then Self.RenderChildren(0, Count-1, ARci); end; end; // BuildMeshFromBuffer // procedure TGLFeedback.BuildMeshFromBuffer( Vertices : TAffineVectorList = nil; Normals : TAffineVectorList = nil; TexCoords : TAffineVectorList = nil; VertexIndices : TIntegerList = nil); var value : Single; i,j,LCount,skip : Integer; vertex, color, texcoord : TVector; tempVertices, tempNormals, tempTexCoords : TAffineVectorList; tempIndices : TIntegerList; ColorBuffered, TexCoordBuffered : Boolean; begin Assert(FMode<>fm2D, 'Cannot build mesh from fm2D feedback mode.'); tempVertices:=TAffineVectorList.Create; tempTexCoords:=TAffineVectorList.Create; ColorBuffered:= (FMode = fm3DColor) or (FMode = fm3DColorTexture) or (FMode = fm4DColorTexture); TexCoordBuffered:= (FMode = fm3DColorTexture) or (FMode = fm4DColorTexture); i:=0; skip:=3; if FMode = fm4DColorTexture then skip:=skip+1; if ColorBuffered then skip:=skip+4; if TexCoordBuffered then skip:=skip+4; while i<FBuffer.Count-1 do begin value:=FBuffer[i]; if value = GL_POLYGON_TOKEN then begin Inc(i); value:=FBuffer[i]; LCount:=Round(value); Inc(i); if LCount = 3 then begin for j:=0 to 2 do begin vertex[0]:=FBuffer[i]; Inc(i); vertex[1]:=FBuffer[i]; Inc(i); vertex[2]:=FBuffer[i]; Inc(i); if FMode = fm4DColorTexture then Inc(i); if ColorBuffered then begin color[0]:=FBuffer[i]; Inc(i); color[1]:=FBuffer[i]; Inc(i); color[2]:=FBuffer[i]; Inc(i); color[3]:=FBuffer[i]; Inc(i); end; if TexCoordBuffered then begin texcoord[0]:=FBuffer[i]; Inc(i); texcoord[1]:=FBuffer[i]; Inc(i); texcoord[2]:=FBuffer[i]; Inc(i); texcoord[3]:=FBuffer[i]; Inc(i); end; vertex[2]:=2*vertex[2]-1; ScaleVector(vertex, FCorrectionScaling); tempVertices.Add(AffineVectorMake(vertex)); tempTexCoords.Add(AffineVectorMake(texcoord)); end; end else begin Inc(i,skip*LCount); end; end else begin Inc(i); end; end; if Assigned(VertexIndices) then begin tempIndices:=BuildVectorCountOptimizedIndices(tempVertices, nil, nil); RemapAndCleanupReferences(tempVertices, tempIndices); VertexIndices.Assign(tempIndices); end else begin tempIndices:=TIntegerList.Create; tempIndices.AddSerie(0,1,tempVertices.Count); end; tempNormals:=BuildNormals(tempVertices, tempIndices); if Assigned(Vertices) then Vertices.Assign(tempVertices); if Assigned(Normals) then Normals.Assign(tempNormals); if Assigned(TexCoords) and TexCoordBuffered then TexCoords.Assign(tempTexCoords); tempVertices.Free; tempNormals.Free; tempTexCoords.Free; tempIndices.Free; end; // SetMaxBufferSize // procedure TGLFeedback.SetMaxBufferSize(const Value : Cardinal); begin if Value<>FMaxBufferSize then begin FMaxBufferSize:=Value; FBuffered:=False; FBuffer.Count:=0; FBuffer.Capacity:=FMaxBufferSize div SizeOf(Single); end; end; // SetMode // procedure TGLFeedback.SetMode(const Value : TFeedbackMode); begin if Value<>FMode then begin FMode:=Value; FBuffered:=False; FBuffer.Count:=0; end; end; initialization RegisterClasses([TGLFeedback]); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { 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.Base; interface uses DPM.Core.Types, DPM.Core.Options.Common, DPM.Core.Logging; type TOptionsBase = class private FVerbosity : TVerbosity; FConfigFile : string; FNonInteractive : boolean; protected FValidated : boolean; FIsValid : boolean; constructor CreateClone(const original : TOptionsBase); virtual; public constructor Create; virtual; procedure ApplyCommon(const options : TCommonOptions); function Validate(const logger : ILogger) : boolean; virtual; property ConfigFile : string read FConfigFile write FConfigFile; property NonInteractive : boolean read FNonInteractive write FNonInteractive; property Verbosity : TVerbosity read FVerbosity write FVerbosity; property Validated : boolean read FValidated; property IsValid : boolean read FIsValid; end; implementation uses DPM.Core.Constants, DPM.Core.Utils.System, DPM.Core.Utils.Config, System.SysUtils; { TOptionsBase } procedure TOptionsBase.ApplyCommon(const options : TCommonOptions); var sConfigFile : string; begin FVerbosity := options.Verbosity; FConfigFile := options.ConfigFile; FNonInteractive := options.NonInteractive; //check if there is a config file in the curent folder. if FConfigFile = '' then begin //check the current directory sConfigFile := IncludeTrailingPathDelimiter(GetCurrentDir) + cDPMConfigFileName; if FileExists(sConfigFile) then FConfigFile := sConfigFile; //if it's still empty, use the profile default. if FConfigFile = '' then begin //ensure our .dpm folder exists. TConfigUtils.EnsureDefaultConfigDir; FConfigFile := TConfigUtils.GetDefaultConfigFileName; end; end; end; constructor TOptionsBase.Create; begin FVerbosity := TVerbosity.Normal; FValidated := false; FIsValid := false; end; constructor TOptionsBase.CreateClone(const original : TOptionsBase); begin FVerbosity := original.Verbosity; FConfigFile := original.FConfigFile; FNonInteractive := original.FNonInteractive; FValidated := original.FValidated; FIsValid := original.FIsValid; end; function TOptionsBase.Validate(const logger : ILogger) : boolean; begin result := true; FValidated := true; FIsValid := true; end; end.
unit Guia.OpenViewUrl; interface function OpenURL(const URL: string; const DisplayError: Boolean = False): Boolean; implementation uses IdURI, SysUtils, Classes, FMX.Dialogs, {$IFDEF ANDROID} FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes, Androidapi.Helpers; {$ENDIF ANDROID} {$IFDEF IOS} Macapi.Helpers, iOSapi.Foundation, FMX.Helpers.iOS; {$ENDIF IOS} function OpenURL(const URL: string; const DisplayError: Boolean = False): Boolean; {$IFDEF ANDROID} var Intent: JIntent; begin Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW, TJnet_Uri.JavaClass.parse(StringToJString(TIdURI.URLEncode(URL)))); try SharedActivity.startActivity(Intent); exit(true); except on e: Exception do begin if DisplayError then ShowMessage('Erro ao tentar abrir a url "' + URL + '"'); exit(False); end; end; end; {$ENDIF ANDROID} {$IFDEF IOS} var NSU: NSUrl; begin NSU := StrToNSUrl(TIdURI.URLEncode(URL)); if SharedApplication.canOpenURL(NSU) then exit(SharedApplication.OpenURL(NSU)) else begin if DisplayError then ShowMessage('Erro ao tentar abrir a url "' + URL + '"'); exit(False); end; end; {$ENDIF IOS} {$IFDEF MSWINDOWS} begin Try ShellExecute(Handle, 'open', URL, nil, nil, SW_SHOWMAXIMIZED); except if DisplayError then ShowMessage('Erro ao tentar abrir a url "' + URL + '"'); exit(False); end; end; {$ENDIF MSWINDOWS} end.
namespace com.remobjects.actionbar; interface uses java.util, android.app, android.content, android.os, android.util, android.view, android.widget; type MainActivity = public class(Activity) protected method openSearch(); method openSettings(); public method onCreate(savedInstanceState: Bundle); override; method onCreateOptionsMenu(menu: Menu): Boolean; override; method onOptionsItemSelected(item: MenuItem): Boolean; override; end; implementation method MainActivity.onCreate(savedInstanceState: Bundle); begin inherited; // Set our view from the "main" layout resource ContentView := R.layout.main; end; method MainActivity.onCreateOptionsMenu(menu : Menu) : Boolean; begin var inflater := getMenuInflater(); inflater.inflate(R.menu.main_activity_actions, menu); result := inherited onCreateOptionsMenu(menu); end; method MainActivity.onOptionsItemSelected(item: MenuItem): Boolean; begin case item.getItemId() of R.id.action_search: begin self.openSearch(); result := true; end; R.id.action_settings: begin self.openSettings(); result := true; end else result := inherited onOptionsItemSelected(item); end; end; method MainActivity.openSearch(); begin var intent := new Intent(self, typeOf(SearchActivity)); startActivity(intent); end; method MainActivity.openSettings(); begin var intent := new Intent(self, typeOf(SettingsActivity)); startActivity(intent); end; end.
unit ImportarProduto.Controller; interface uses ImportarProduto.Controller.interf, TESTPRODUTO.Entidade.Model, Produto.Model.interf, System.SysUtils; type TImportarProdutoController = class(TInterfacedObject, IImportarProdutoController) private FProdutoModel: IProdutoModel; FRegistro: TTESTPRODUTO; public constructor Create; destructor Destroy; override; class function New: IImportarProdutoController; function localizar(AValue: Integer): IImportarProdutoController; function produtoSelecionado: TTESTPRODUTO; function Importar: IImportarProdutoOperacaoController; end; implementation { TImportarProdutoController } uses FacadeModel, ImportarProdutoOperacao.Controller; constructor TImportarProdutoController.Create; begin FProdutoModel := TFacadeModel.New.ModulosFacadeModel. estoqueFactoryModel.Produto; end; destructor TImportarProdutoController.Destroy; begin inherited; end; function TImportarProdutoController.Importar : IImportarProdutoOperacaoController; begin Result := TImportarProdutoOperacaoController.New.importarProdutoController (Self).produtoModel(FProdutoModel) end; function TImportarProdutoController.localizar(AValue: Integer) : IImportarProdutoController; begin Result := Self; try FRegistro := FProdutoModel.DAO.FindWhere('CODIGO_SINAPI=' + QuotedStr(IntToStr(AValue)), 'DESCRICAO').Items[0]; except on E: Exception do end; end; class function TImportarProdutoController.New: IImportarProdutoController; begin Result := Self.Create; end; function TImportarProdutoController.produtoSelecionado: TTESTPRODUTO; begin Result := FRegistro; end; end.
unit untGlobal; interface uses FMX.Objects, FMX.Forms, System.Classes, FireDAC.Comp.Client, IdFtp, System.NetEncoding, IdHTTP, IdSSLOpenSSL, Guia.Controle, System.Net.HttpClient; function formataCNPJCEP(vDoc,vAcao : String) : String; function SizeImgPx(fImagem : String) : String; function GeraNameFile : String; procedure pLoadImage(pImage : TImage; pImagem : String); procedure fMsg(vForm:TForm; vCaption, vMensagem, vNameImg, vButtons: String); function QueryToLog(Q: TFDQuery): string; function preencheCEP(vCep : String; vForm: TForm) : Boolean; function formataDDD(vDDD: String): String; function FormataFone(vFone, vAcao: String): String; function ExtractText(aText, OpenTag, CloseTag : String) : String; function PintarStatus(S : String) : String; function NomeStatus(S : String) : String; function FinalSemana(vData : TDate) : Boolean; function isNumeric(S : String) : Boolean; procedure LimpaEdit(fForm : TForm); //function ConvertFileToBase64(AInFileName: String): String; function SendFileFtp(File_From, File_To, Dir_To: string) : Boolean; function ReceiveFileFtp(File_From, File_To, Dir_Ftp: string) : Boolean; function SendSMS(vCelular,vMsg : String) : Boolean; function ValidaCelular : String; function GeraSenha : String; function DeleteFileFtp(vDirFtp,vFile: string) : Boolean; function CarregaPosicaoMapa(fEndereco : String) : String; function ApenasNumeros(S: String): String; function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean; function BoolToStrValue(AValue : Boolean) : String; function EnviarPush(ATokenCelular, ATitulo, AMensagem, AImagem, AAnuncio, AIdComercio, ANomeComercio : String) : Integer; function DataAtual: TDateTime; var gPathArquivos : String; vListaErros : TStringList; gIdComercio, gIdContrato : Integer; pNewFile, pOldFile, pNameFile: String; gUpdate : Boolean = False; gLetra, gImgHome, gImgSecao : String; gLimiteFindCep : Integer; gDiasStatus : Integer; gDiasVencto : Integer; gAutorizado : Boolean; gIdUsu : Integer; ALog : TStringlist; const gSenhaSMS : String = 'MFnW289S5pv3XZs'; fIconExclamation : String = 'fIconExclamation'; fIconInterrogation : String = 'fIconInterrogation'; fIconError : String = 'fIconError'; fIconInformation : String = 'fIconInformation'; fIconMais : String = 'fIconMais'; fbtnYesNo : String = 'fbtnYesNo'; fBtnOK : String = 'fBtnOK'; ffmtEnter : String = 'fmtEnter'; ffmtExit : String = 'fmtExit'; gEstados : String = 'AC,AL,AP,AM,BA,CE,DF,ES,GO,MA,MT,MS,MG,PA,PB,PR,PE,PI,RJ,RN,RS,RO,RR,SC,SP,SE,TO'; gLetras : String = 'ABCDEFGHIJKLMNOPQRSTUVXWYZ'; gCorStOnLine : String = '<font color="claMidnightBlue">'; gCorStOffLine : String = '<font color="claDarkGreen">'; gCorStAtrasado : String = '<font color="claFireBrick">'; gCorStPausado : String = '<font color="claGold">'; gCorStFinalizado : String = '<font color="clared"><S>'; gCorStCancelado : String = '<font color="claDimGray"><S>'; gCorStNovo : String = '<font color="claBlack">'; gCorStVencer : String = '<font color="claGoldenrod">'; gCorStPago : String = '<font color="claSeaGreen">'; gCorStVencido : String = '<font color="claRed">'; gCorStAVencer : String = '<font color="claGoldenrod">'; implementation uses FMX.Graphics, System.SysUtils, untDmGeral, System.Types, FMX.StdCtrls, Data.DB, System.AnsiStrings, FMX.Edit, FMX.Memo, FMX.Grid, IdFTPCommon, System.JSON; function getCamposJsonString(json,value:String): String; var LJSONObject: TJSONObject; function TrataObjeto(jObj:TJSONObject):string; var i:integer; jPar: TJSONPair; begin result := ''; for i := 0 to jObj.Size - 1 do begin jPar := jObj.Get(i); if jPar.JsonValue Is TJSONObject then result := TrataObjeto((jPar.JsonValue As TJSONObject)) else if sametext(trim(jPar.JsonString.Value),value) then begin Result := jPar.JsonValue.Value; break; end; if result <> '' then break; end; end; begin try LJSONObject := nil; LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(json),0) as TJSONObject; result := TrataObjeto(LJSONObject); finally LJSONObject.Free; end; end; function DataAtual: TDateTime; var fQueryTmp : TFDQuery; fTSAgora : String; begin Try fQueryTmp := TFDQuery.Create(nil); fQueryTmp.Connection := dmGeral.Conexao; fQueryTmp.Close; fQueryTmp.SQL.Clear; fQueryTmp.SQL.Add('select current_time as hora, current_date as data from rdb$database'); fQueryTmp.Open; fTSAgora := fQueryTmp.FieldByName('data').AsString + ' ' + fQueryTmp.FieldByName('hora').AsString; Result := StrToDateTime(fTSAgora); Finally fQueryTmp.DisposeOf; End; end; function EnviarPush(ATokenCelular, ATitulo, AMensagem, AImagem, AAnuncio, AIdComercio, ANomeComercio : String) : Integer; var client : THTTPClient; v_json : TJSONObject; v_jsondata : TJSONObject; v_data : TStringStream; v_response : TStringStream; url_google : string; begin url_google := 'https://fcm.googleapis.com/fcm/send'; //-------------------------------- v_json := TJSONObject.Create; v_json.AddPair('to', ATokenCelular); v_jsondata := TJSONObject.Create; v_jsondata.AddPair('body', AMensagem); v_jsondata.AddPair('title', ATitulo); v_json.AddPair('notification', v_jsondata); v_jsondata := TJSONObject.Create; v_jsondata.AddPair('Mensagem' ,AMensagem); v_jsondata.AddPair('Titulo' ,ATitulo); v_jsondata.AddPair('Imagem' ,AImagem); v_jsondata.AddPair('Anuncio' ,AAnuncio); v_jsondata.AddPair('IdComercio' ,AIdComercio); v_jsondata.AddPair('NomeComercio' ,ANomeComercio); v_json.AddPair('data', v_jsondata); client := THTTPClient.Create; client.ContentType := 'application/json'; client.CustomHeaders['Authorization'] := 'key=' + ctrKEYPUSH; v_data := TStringStream.Create(v_json.ToString, TEncoding.UTF8); V_data.Position := 0; v_response := TStringStream.Create; client.Post(url_google, v_data, v_response); v_response.Position := 0; Result := getCamposJsonString(v_response.DataString,'failure').ToInteger; end; procedure ConectaFTP(gFTP: TIdFtp); begin if not gFTP.Connected then begin gFTP.Disconnect; gFTP.host := ctrHOSTFTP; // Endereço do servidor FTP gFTP.port := ctrPORTAFTP; gFTP.username := ctrUSUARIOFTP; // Parametro nome usuario servidor FTP gFTP.password := ctrSENHAFTP; // Parametro senha servidor FTP gFTP.Connect(); AssErt(gFTP.Connected); end; end; procedure pLoadImage(pImage : TImage; pImagem : String); var InStream: TResourceStream; begin InStream := TResourceStream.Create(HInstance, pImagem, RT_RCDATA); try pImage.Bitmap.LoadFromStream(InStream); finally InStream.Free; end; end; function ApenasNumeros(S: String): String; var vText: PChar; begin vText := PChar(S); Result := ''; while (vText^ <> #0) do begin {$IFDEF UNICODE} if CharInSet(vText^, ['0' .. '9']) then {$ELSE} if vText^ in ['0' .. '9'] then {$ENDIF} Result := Result + vText^; Inc(vText); end; end; function CarregaPosicaoMapa(fEndereco : String) : String; var xTemp: TStringList; vLat, vLong, S : String; i,j : Integer; vMemo : TMemo; vIdSSL : TIdSSLIOHandlerSocketOpenSSL; vIdHttp : TIdHTTP; AKey : String; begin AKey := 'AIzaSyBEmEFZcMSPDszUa7E-SfDLZPQDVc7XZHE'; vIdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(Application); vIdHttp := TIdHTTP.Create(Application); vMemo := TMemo.Create(Application); vIdSSL.SSLOptions.Method := sslvTLSv1; vIdSSL.SSLOptions.Mode := sslmUnassigned; vIdHttp.IOHandler := vIdSSL; xTemp:= TStringList.Create; vIdHttp.Request.Accept := 'text/html, */*'; vIdHttp.Request.UserAgent := 'Mozilla/3.0 (compatible; IndyLibrary)'; vIdHttp.Request.ContentType := 'application/x-www-form-urlencoded'; vIdHttp.HandleRedirects := True; S := StringReplace(fEndereco,' ','%20',[rfReplaceAll]); xTemp.Text := UTF8Decode(vIdHttp.Get('https://maps.google.com/maps/api/geocode/json?sensor=false&address={'+S+'}&key='+AKey)); vMemo.Lines.Clear; for i := 0 to xTemp.Count - 1 do begin vMemo.Lines.Add('Linha: '+FormatFloat('000',i)+' '+ xTemp.Strings[i]); if Pos('"location"',xTemp.Strings[i]) > 0 then j := i; end; vLat := Copy(Trim(xTemp.Strings[j+1]),8,12); vLong := Copy(Trim(xTemp.Strings[j+2]),8,12); Result := vLat+'|'+vLong; end; function ValidaCelular : String; begin Randomize; Result := FormatFloat('000000',Random(999999)); end; function GeraSenha : String; var R: String; const vChars : String = 'AB0CD1EF2GH3IJ4KL5MN6OP7QR8ST9UVXWYZ'; begin Randomize; R := ''; While Length(R) < 6 do R := Trim(R + vChars[Random(36)]); Result := R; end; function SendSMS(vCelular, vMsg: String): Boolean; var vLista: TStringList; vIdHTTP: TIdHTTP; begin Result := True; vLista := TStringList.Create; vIdHTTP := TIdHTTP.Create(nil); Try Try vLista.Add('metodo=envio'); vLista.Add('usuario=souza@vikmar.com.br'); vLista.Add('senha=Mjs19770'); vLista.Add('celular=' + vCelular); vLista.Add('mensagem=' + vMsg); vIdHTTP.Post ('http://www.iagentesms.com.br/webservices/http.php', vLista); Except Result := False; end; Finally FreeAndNil(vIdHTTP); end; end; function FinalSemana(vData : TDate) : Boolean; begin if (DayOfWeek(vData) = 7) or (DayOfWeek(vData) = 1) then Result := True else Result := False; end; function SendFileFtp(File_From, File_To, Dir_To: string) : Boolean; var ftp: TIdFTP; ms: TMemoryStream; image : TBitmap; TextMemo : TMemo; begin Result := False; image := TBitmap.Create; TextMemo := TMemo.Create(Application); ftp := TIdFTP.Create(Application); ms := TMemoryStream.Create; try try if Pos('.txt', File_From) = 0 then begin image.LoadFromFile(File_From); image.SaveToStream(ms); ms.Position := 0; end else begin TextMemo.Lines.LoadFromFile(File_From); TextMemo.Lines.SaveToStream(ms); ms.Position := 0; end; ConectaFTP(ftp); ftp.ChangeDir(Dir_To); // Definir a pasta no servidor ftp.TransferType := ftBinary; ftp.Put(ms, File_To); Result := True; finally ms.Free; image.Free; ftp.Free; end; except Result := false; end; end; function DeleteFileFtp(vDirFtp,vFile: string) : Boolean; var ftp: TIdFTP; begin Result := False; ftp := TIdFTP.Create(Application); try try ConectaFTP(ftp); ftp.ChangeDir(vDirFtp); // Definir a pasta no servidor ftp.TransferType := ftBinary; ftp.Delete(vFile); Result := True; finally ftp.Free; end; except Result := false; end; end; function ReceiveFileFtp(File_From, File_To, Dir_Ftp: string) : Boolean; var ftp: TIdFTP; begin Result := False; ftp := TIdFTP.Create(Application); try try ConectaFTP(ftp); ftp.ChangeDir(Dir_Ftp); // Definir a pasta no servidor ftp.TransferType := ftBinary; ftp.Get(File_From, File_To,True); Result := True; finally ftp.Free; end; except Result := false; end; end; function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean; begin If AValue = ATrue then Result := True; If AValue = AFalse then Result := False; end; function BoolToStrValue(AValue : Boolean) : String; begin case AValue of True : Result := 'T'; False : Result := 'F'; end; end; {function ConvertFileToBase64(AInFileName: String): String; var inStream: TStream; outStream: TStream; vFile: String; vStringList: TStringList; vPathFile : String; begin vPathFile := gPathArquivos; AInFileName := vPathFile + AInFileName; inStream := TFileStream.Create(AInFileName, fmOpenRead); vStringList := TStringList.Create; try vFile := FormatDateTime('hhmmss', Now); outStream := TFileStream.Create(vFile, fmCreate); try TNetEncoding.Base64.Encode(inStream, outStream); finally outStream.Free; end; vStringList.LoadFromFile(vFile); Result := vStringList.Text; finally DeleteFile(Pchar(vFile)); inStream.Free; end; end; procedure ConvertBase64ToFile(Base64, FileName: string); var inStream: TStream; outStream: TStream; vFiletmp: String; vStringList: TStringList; vDestino : String; begin vStringList := TStringList.Create; try vFiletmp := FormatDateTime('hhmmss', Now); vStringList.Add(Base64); vStringList.SaveToFile(gPathArquivos+'\Tmp\' + vFiletmp); inStream := TFileStream.Create(gPathArquivos+'\Tmp\' + vFiletmp, fmOpenRead); try vDestino := gPathArquivos; outStream := TFileStream.Create(vDestino, fmCreate); try TNetEncoding.Base64.Decode(inStream, outStream); finally outStream.Free; end; finally inStream.Free; end; finally DeleteFile(gPathArquivos+'\Tmp\' + vFiletmp); FreeAndNil(vStringList); end; end; } function PintarStatus(S : String) : String; begin //Status Contrato if S = 'ONLINE' then Result := gCorStOnLine; if S = 'OFFLINE' then Result := gCorStOffLine; if S = 'ATRASADO' then Result := gCorStAtrasado; if S = 'PAUSADO' then Result := gCorStPausado; if S = 'FINALIZADO' then Result := gCorStFinalizado; if S = 'CANCELADO' then Result := gCorStCancelado; //Status Pagamentos if S = 'VENCER' then Result := gCorStVencer; if S = 'PAGO' then Result := gCorStPago; if S = 'VENCIDO' then Result := gCorStVencido; if S = 'AVENCER' then Result := gCorStAVencer; end; function NomeStatus(S : String) : String; begin //Status Contrato if Pos('ONLINE',S) > 0 then Result := 'ONLINE'; if Pos('OFFLINE',S) > 0 then Result := 'OFFLINE'; if Pos('ATRASADO',S) > 0 then Result := 'ATRASADO'; if Pos('PAUSADO',S) > 0 then Result := 'PAUSADO'; if Pos('FINALIZADO',S) > 0 then Result := 'FINALIZADO'; if Pos('CANCELADO',S) > 0 then Result := 'CANCELADO'; if Pos('NOVO',S) > 0 then Result := 'NOVO'; //Status Pagamentos if Pos('VENCER',S) > 0 then Result := 'VENCER'; if Pos('PAGO',S) > 0 then Result := 'PAGO'; if Pos('VENCIDO',S) > 0 then Result := 'VENCIDO'; if Pos('AVENCER',S) > 0 then Result := 'AVENCER'; end; function ExtractText(aText, OpenTag, CloseTag : String) : String; var iAux, kAux : Integer; begin Result := ''; if Pos('/',aText) > 0 then begin if (Pos(CloseTag, aText) <> 0) and (Pos(OpenTag, aText) <> 0) then begin iAux := Pos(OpenTag, aText) + Length(OpenTag); kAux := Pos(CloseTag, aText); Result := Copy(aText, iAux, kAux-iAux); end; end else begin Result := aText; end; end; function FormataFone(vFone, vAcao: String): String; // vAcao 1 = Ao entrar , 2 Ao sair var vRes: String; begin if vAcao = 'ffEnter' then begin if Length(vFone) = 9 then vRes := Copy(vFone, 1, 4) + Copy(vFone, 6, 4); if (Length(vFone) = 10) and (Pos('-', vFone) > 0) then vRes := Copy(vFone, 1, 5) + Copy(vFone, 7, 4); end else begin if Length(vFone) = 8 then vRes := Copy(vFone, 1, 4) + '-' + Copy(vFone, 5, 4); if (Length(vFone) = 9) and (Pos('-', vFone) = 0) then vRes := Copy(vFone, 1, 5) + '-' + Copy(vFone, 6, 4); end; if Length(vRes) > 0 then Result := vRes else Result := vFone; end; function formataDDD(vDDD: String): String; begin if Length(vDDD) = 2 then Result := '0' + vDDD else Result := vDDD; end; procedure LimpaEdit(fForm : TForm); var i : Integer; begin for i := 0 to fForm.ComponentCount - 1 do if fForm.Components[i] is TEdit then TEdit(fForm.Components[i]).Text := ''; end; function preencheCEP(vCep : String; vForm: TForm) : Boolean; begin dmGeral.ConsultaCep(vCep); if dmGeral.fdmemCep.RecordCount > 0 then begin TEdit(vForm.FindComponent('edtLogradouro')).Text := dmGeral.fdmemCeplogradouro.Text; TEdit(vForm.FindComponent('edtBairro')).Text := dmGeral.fdmemCepbairro.Text; TEdit(vForm.FindComponent('edtCidade')).Text := dmGeral.fdmemCeplocalidade.Text; TEdit(vForm.FindComponent('edtUF')).Text := dmGeral.fdmemCepuf.Text; Result := True; end else begin Result := False; end; end; function isNumeric(S : String) : Boolean; begin Result := True; Try StrToInt(S); Except Result := False; end; end; function QueryToLog(Q: TFDQuery): string; var i: Integer; r: string; begin Result := Q.SQL.Text; for i := 0 to Q.Params.Count - 1 do begin case Q.Params.Items[i].DataType of ftString, ftDate, ftDateTime: r := QuotedStr(Q.Params[i].AsString); else r := Q.Params[i].AsString; end; Result := ReplaceText(Result, ':' + Q.Params.Items[i].Name, r); end; end; procedure fMsg(vForm:TForm; vCaption, vMensagem, vNameImg, vButtons: String); begin With vForm do begin if Length(Trim(vCaption)) > 0 then TLabel(vForm.FindComponent('lblCaption')).Text := vCaption; TLabel(vForm.FindComponent('lblMensagem')).Text := vMensagem; pLoadImage(TImage(vForm.FindComponent('imgIcoMsg')), vNameImg); if vButtons = fbtnYesNo then begin TSpeedButton(vForm.FindComponent('sbtnSim')).Visible := True; TSpeedButton(vForm.FindComponent('sbtnNao')).Visible := True; TSpeedButton(vForm.FindComponent('sbtnOK')).Visible := False; end else begin TSpeedButton(vForm.FindComponent('sbtnSim')).Visible := False; TSpeedButton(vForm.FindComponent('sbtnNao')).Visible := False; TSpeedButton(vForm.FindComponent('sbtnOK')).Visible := True; end; TRectangle(vForm.FindComponent('recModal')).Visible := True; end; end; function SizeImgPx(fImagem : String) : String; var vImagem : TBitmap; vLargura, vAltura : Integer; begin vImagem := TBitmap.Create(); vImagem.LoadFromFile(fImagem); vAltura := vImagem.Height; vLargura := vImagem.Width; Result := vLargura.ToString+'x'+vAltura.ToString; end; function GeraNameFile : String; var R: String; fQueryTmp : TFDQuery; Repetido : Boolean; const vChars : String = 'AB0CD1EF2GH3IJ4KL5MN6OP7QR8ST9UVXWYZ'; begin fQueryTmp := TFDQuery.Create(nil); fQueryTmp.Connection := dmGeral.Conexao; Randomize; Repetido := True; While Repetido do begin R := ''; While Length(R) < 12 do R := Trim(R + vChars[Random(36)]); With fQueryTmp do begin Close; Sql.Clear; Sql.Add('SELECT * FROM ALFILES'); Sql.Add('WHERE NOMEFILES LIKE '+''''+R+'%'+''''); Open; if RecordCount = 0 then Repetido := False else Repetido := True; end; end; FreeAndNil(fQueryTmp); Result := R; end; function formataCNPJCEP(vDoc,vAcao : String) : String; var vRes : String; begin //Ao entrar if vAcao = ffmtEnter then begin //Copia as informações sem os pontos, traços ou barras if Length(vDoc) = 9 then vRes := Copy(vDoc,1,5) + Copy(vDoc,7,3); if Length(vDoc) = 14 then vRes := Copy(vDoc,1,3) + Copy(vDoc,5,3) + Copy(vDoc,9,3) + Copy(vDoc,13,2); if Length(vDoc) = 18 then vRes := Copy(vDoc,1,2) + Copy(vDoc,4,3) + Copy(vDoc,8,3) + Copy(vDoc,12,4) + Copy(vDoc,17,2); end else begin //Acrescenta os traçoes, barras ou pontos onde necessário if Length(vDoc) = 8 then vRes := Copy(vDoc,1,5) +'-'+ Copy(vDoc,6,3); if Length(vDoc) = 11 then vRes := Copy(vDoc,1,3) +'.'+ Copy(vDoc,4,3) +'.'+ Copy(vDoc,7,3) +'-'+ Copy(vDoc,10,2); if Length(vDoc) = 14 then vRes := Copy(vDoc,1,2) +'.'+ Copy(vDoc,3,3) +'.'+ Copy(vDoc,6,3) +'/'+ Copy(vDoc,9,4) +'-'+ Copy(vDoc,13,2); end; if Length(vRes) > 0 then Result := vRes else Result := vDoc; end; end.
(* RestObject Simple class to interact with a RESTful Web Service Given a domain, port and user credentials, it is able to retrieve from and post to an address XML strings. Example In your class or unit, declare that: uses RestObject; Then, among your variable declaration: var rest : TRestObject; You can now create the object, with the credentials: rest := TRestObject.Create( 'www.dbunic.cnrs-gif.fr', 443, 'do', 'do' ); Then address a GET request to the Web Service: XMLres := rest.getXML( 'https://www.dbunic.cnrs-gif.fr/brainscales/people/researcher/5?format=xml' ); Once received the XML, you want to destroy the object to free: rest.Destroy; And operate the XML: ReceiveLog.lines.Add( XMLres.DocumentElement.NodeName ); *) unit RestObject; interface uses Windows, SysUtils, Dialogs, Classes, EncdDecd, util1, IdHTTP, IdException, IdStack, IdHeaderList, IdAuthentication, IdSSLOpenSSL, IdIOHandler, IdIOHandlerSocket, IdSSLOpenSSLHeaders, XMLIntf, XMLDoc; //IdSSLOpenSSL requires additional dll: // ssleay32.dll // libeay32.dll // vsinit.dll (* ---------------- START Object --------------- *) type TRestObject = class( TObject ) host : String; port : String; username : String; password : String; ErrorString: AnsiString; private http : TIdHttp; SSLhandler : TIdSSLIOHandlerSocketOpenSSL; Response : String; function getXMLstring( getUrl:String ) : String; public // init communications constructor Create( host:String; port:Integer; username,password : String ); destructor Destroy(); Override; function doGet( getUrl:String ) : IXMLDocument; procedure doPost( postURL:String; doc:IXMLDocument ); procedure doPut( putURL:String; doc:IXMLDocument ); procedure doDelete( deleteUrl:String ); end; implementation // Methods constructor TRestObject.Create( host:String; port:Integer; username,password : String ); begin // create objects http := TIDHttp.Create; SSLhandler := TIdSSLIOHandlerSocketOpenSSL.Create; SSLhandler.SSLOptions.Method := sslvSSLv23; SSLhandler.Host := host; // domain SSLhandler.Port := port; // HTTPS // population http.IOHandler := SSLhandler; http.HandleRedirects := True; // auth http.Request.BasicAuthentication := True; http.Request.Username := username; http.Request.Password := password; // additional http.Request.Host := 'Indy 10'; http.Request.Accept := 'text/xml'; http.Request.ContentType := 'application/xml'; http.ReadTimeout := 10000; http.ConnectTimeout := 10000; //http.Request.Connection := 'close'; //http.Request.ContentEncoding := 'UTF-8'; //http.HTTPOptions := []; //LoadLibrary( 'libeay32.dll' ); //LoadLibrary( 'ssleay32.dll' ); //LoadLibrary( 'vsinit.dll' ); end; destructor TRestObject.Destroy(); begin http.Disconnect; // otherwise: EIdConnClosedGracefully (the connection has been closed in agreement) http.Free; SSLhandler.Free; // remove dll //FreeLibrary( GetModuleHandle('libeay32.dll') ); //FreeLibrary( GetModuleHandle('ssleay32.dll') ); end; // utility functions function TRestObject.getXMLstring( getUrl:String ) : String; begin try ErrorString:=''; Response := http.Get( getUrl ); except on E: EIdConnClosedGracefully do ; on E: EIdHTTPProtocolException do ErrorString := 'Protocol Exception (HTTP status '+ IntToStr(E.ErrorCode) +'): ' + E.Message; on E: EIdSocketError do ErrorString := 'Socket Error ('+ IntToStr(E.LastError) +'): ' + E.Message; on E: EIdException do ErrorString := 'Exception (class '+ E.ClassName +'): ' + E.Message; end; Result := Response; end; // PUBLIC // DELETE // Detete requires a full address to a detail (without format specification): // https://www.dbunic.cnrs-gif.fr/brainscales/people/researcher/12 procedure TRestObject.doDelete( deleteUrl:String ); begin // check address for a detail (although tastypie is checking it as well) try http.Delete( deleteURL ); ShowMessage( http.ResponseText ); except on E: EIdConnClosedGracefully do ; on E: EIdHTTPProtocolException do ShowMessage('Protocol Exception (HTTP status '+ IntToStr(E.ErrorCode) +'): ' + E.Message); on E: EIdSocketError do ShowMessage('Socket Error ('+ IntToStr(E.LastError) +'): ' + E.Message); on E: EIdException do ShowMessage('Exception (class '+ E.ClassName +'): ' + E.Message); end; end; // POST // Post to server should be sent only to base address (the list) not to details procedure TRestObject.doPost( postURL:String; doc:IXMLDocument ); var data : TStringStream; xmlString : String; xmlPayloadStart : Integer; begin xmlString := doc.XML.Text; // remove xml header xmlPayloadStart := Pos('<object', doc.XML.Text); if( xmlPayloadStart > 0 ) then begin xmlString := copy( doc.XML.Text, xmlPayloadStart, length(doc.XML.Text)-xmlPayloadStart ); end; ShowMessage(xmlString); data := TStringStream.Create( xmlString ); try data.Position := 0; http.Post( postURL, data ); except on E: EIdConnClosedGracefully do ; on E: EIdHTTPProtocolException do ShowMessage('Protocol Exception (HTTP status '+ IntToStr(E.ErrorCode) +'): ' + E.Message); on E: EIdSocketError do ShowMessage('Socket Error ('+ IntToStr(E.LastError) +'): ' + E.Message); on E: EIdException do ShowMessage('Exception (class '+ E.ClassName +'): ' + E.Message); end; ShowMessage( http.ResponseText ); data.Free; end; // PUT // Put requires a full resource detail address procedure TRestObject.doPut( putURL:String; doc:IXMLDocument ); var data : TStringStream; xmlString : String; xmlPayloadStart : Integer; begin xmlString := doc.XML.Text; // remove xml header xmlPayloadStart := Pos('<object', doc.XML.Text); if( xmlPayloadStart > 0 ) then begin xmlString := copy( doc.XML.Text, xmlPayloadStart, length(doc.XML.Text)-xmlPayloadStart ); end; ShowMessage(xmlString); data := TStringStream.Create( xmlString ); try data.Position := 0; http.Put( putURL, data ); except on E: EIdConnClosedGracefully do ; on E: EIdHTTPProtocolException do ShowMessage('Protocol Exception (HTTP status '+ IntToStr(E.ErrorCode) +'): ' + E.Message); on E: EIdSocketError do ShowMessage('Socket Error ('+ IntToStr(E.LastError) +'): ' + E.Message); on E: EIdException do ShowMessage('Exception (class '+ E.ClassName +'): ' + E.Message); end; ShowMessage( http.ResponseText ); data.Free; end; // GET // Get works both for detail resource and list function TRestObject.doGet( getUrl:String ) : IXMLDocument; var res, XMLstring : String; //rest : TRestObject; XMLstart : Integer; XMLres : IXMLDocument; begin res := getXMLstring( getUrl ); // parse // continue only if XML is present (search for '<?xml') XMLstart := Pos( res, '<?xml' ); if( XMLstart >= 0 ) then begin // remove all Indy specific headers XMLstring := copy( res, XMLstart, length(res)-XMLstart ); //ReceiveLog.lines.Add( XMLstring ); XMLres := LoadXMLData( XMLstring ); end else begin XMLres:=nil; ErrorString:= 'Internal Error SSL: '+WhichFailedToLoad+ crlf+' Try reloading the resource.' ; end; // return Result := XMLres; end; (* ---------------- END Object --------------- *) end.
unit UserModel; interface uses GlobalTypes; type TUser = class private fId : StringGuid; fFirstName : String40; fLastName : String150; fBirtDate : TDateTime; fActive : Boolean; fPhoneNumber : String12; fUsername : String20; fPassword : String64; public property Id : StringGuid read fId write fId; property FirstName : String40 read fFirstName write fFirstName; property LastName : String150 read fLastName write fLastName; property BirtDate : TDateTime read fBirtDate write fBirtDate; property Active : Boolean read fActive write fActive; property PhoneNumber : String12 read fPhoneNumber write fPhoneNumber; property Username : String20 read fUsername write fUsername; property Password : String64 read fPassword write fPassword; end; implementation end.
{ Datamove - Conversor de Banco de Dados Firebird para Oracle licensed under a APACHE 2.0 Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT. Toda e qualquer alteração deve ser submetida à https://github.com/Arturbarth/Datamove } unit uMoveDados; interface uses FireDAC.Comp.BatchMove, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Comp.BatchMove.SQL, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.Client, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.BatchMove.DataSet, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.Oracle, FireDAC.Phys.OracleDef, FireDAC.Phys.FB, FireDAC.Phys.FBDef, System.Classes, FireDAC.Comp.UI, uConexoes, Vcl.StdCtrls; type IMoveDados = interface ['{5EFE6439-77A9-4A96-A0EF-4FFC1E1ED476}'] procedure MoverDadosTabela(cTabela: String); end; TMoveDados = class(TInterfacedObject, IMoveDados) private FModelFirebird: TModelConexao; FModelOracle: TModelConexao; FDBatchMove1: TFDBatchMove; FDBatchMoveDataSetReader1: TFDBatchMoveDataSetReader; FDBatchMoveDataSetWriter1: TFDBatchMoveDataSetWriter; FDBatchMoveSQLReader1: TFDBatchMoveSQLReader; FDBatchMoveSQLWriter1: TFDBatchMoveSQLWriter; FDMetaInfoQuery1: TFDMetaInfoQuery; FDCommand1: TFDCommand; qryOrigem: TFDQuery; qryDestino: TFDQuery; qryTabelas: TFDQuery; dsTabelas: TDataSource; public FmeLog: TMemo; FmeErros: TMemo; FDConOracle: TFDConnection; FDConFireBird: TFDConnection; class function New(oConOrigem, oConDestino: TFDConnection): IMoveDados; constructor Create(oConOrigem, oConDestino: TFDConnection); overload; destructor Destroy; override; procedure MoverDadosTabela(cTabela: String); procedure ExecuteCommandDestino(cComando: String); procedure AtualizarMigradas(cTabela: String); end; implementation uses uParametrosConexao, uEnum; { TMoveDados } class function TMoveDados.New(oConOrigem, oConDestino: TFDConnection): IMoveDados; begin Result := TMoveDados.Create(oConOrigem, oConDestino); end; constructor TMoveDados.Create(oConOrigem, oConDestino: TFDConnection); begin FDConFirebird := oConOrigem; FDConOracle := oConDestino; // qryOrigem := TFDQuery.Create(nil); // qryDestino := TFDQuery.Create(nil); // qryOrigem.Connection := FDConFirebird; // qryDestino.Connection := FDConOracle; // FDBatchMoveDataSetReader1 := TFDBatchMoveDataSetReader.Create(nil); // FDBatchMoveDataSetWriter1 := TFDBatchMoveDataSetWriter.Create(nil); // FDBatchMoveDataSetReader1.DataSet := qryOrigem; // FDBatchMoveDataSetWriter1.DataSet := qryDestino; FDBatchMove1 := TFDBatchMove.Create(nil); FDBatchMoveSQLReader1 := TFDBatchMoveSQLReader.Create(FDBatchMove1); FDBatchMoveSQLReader1.Connection := FDConFirebird; FDBatchMoveSQLWriter1 := TFDBatchMoveSQLWriter.Create(FDBatchMove1); FDBatchMoveSQLWriter1.Connection := FDConOracle; // FDBatchMove1.CommitCount := 500; // FDBatchMove1.Reader := FDBatchMoveDataSetReader1; FDBatchMove1.Reader := FDBatchMoveSQLReader1; FDBatchMove1.Writer := FDBatchMoveSQLWriter1; end; destructor TMoveDados.Destroy; begin // qryOrigem.Free; // qryDestino.Free; // FDBatchMoveDataSetReader1.Free; // FDBatchMoveDataSetWriter1.Free; FDBatchMoveSQLReader1.Free; FDBatchMove1.Free; inherited; end; procedure TMoveDados.MoverDadosTabela(cTabela: String); begin {if (cTabela = 'VSCONSULTA') then begin ExecuteCommandDestino('DELETE FROM ' + cTabela + ' WHERE SQLID < 0'); end else begin} ExecuteCommandDestino('TRUNCATE TABLE ' + cTabela); {end;} // qryOrigem.SQL.Text := 'SELECT * FROM ' + cTabela; // qryOrigem.Open; FDBatchMoveSQLReader1.TableName := cTabela; FDBatchMoveSQLWriter1.TableName := cTabela; // qryDestino.SQL.Text := 'SELECT * FROM ' + cTabela; // qryDestino.Open; FDBatchMove1.Execute; //FDBatchMove1.OnProgress; AtualizarMigradas(cTabela); end; procedure TMoveDados.AtualizarMigradas(cTabela: String); var qry: TFDQuery; begin try qry := TFDQuery.Create(nil); qry.Connection := FDConFireBird; qry.SQL.Text := 'SELECT * FROM MIGRATABELAS WHERE TABELA = :TABELA'; qry.ParamByName('TABELA').Value := cTabela; qry.Open(); qry.Edit; qry.FieldByName('MIGRADA').Value := 'S'; qry.Post; finally qry.Free; end; end; procedure TMoveDados.ExecuteCommandDestino(cComando: String); begin FDConOracle.ExecSQL(cComando); end; end. { Datamove - Conversor de Banco de Dados Firebird para Oracle licensed under a APACHE 2.0 Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT. Toda e qualquer alteração deve ser submetida à https://github.com/Arturbarth/Datamove }
unit tools; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics; type //types of tools ToolEnum = ( TLPEN, TLERASER, TLLINE, TLRECT, TLELLIPSE, TCFILLER ); //general tool template TTool = class private x1, y1, x2, y2: Integer; PenColor, BrushColor: TColor; Size: Byte; public constructor Create( X, Y: Integer; FColor, BColor: TColor; PenSize: Byte ); procedure Draw( ImgCanvas: TCanvas ); virtual; procedure Update( X, Y: Integer ); end; //mouse-moving tools TLine = class(TTool) procedure Draw( ImgCanvas: TCanvas ); override; end; TPen = class(TLine) procedure Draw( ImgCanvas: TCanvas ); override; end; TRectangle = class(TTool) procedure Draw( ImgCanvas: TCanvas ); override; end; TEllipse = class(TTool) procedure Draw( ImgCanvas: TCanvas ); override; end; //and click tools. so, they are simple procedures and no use TTool procedure FillAtXY( ImgCanvas: TCanvas; X, Y: Integer; Color: TColor ); implementation uses GraphType; { TTool - general class } constructor TTool.Create( X, Y: Integer; FColor, BColor: TColor; PenSize: Byte ); begin x1 := X; y1 := Y; PenColor := FColor; BrushColor := BColor; Size := PenSize; end; procedure TTool.Draw( ImgCanvas: TCanvas ); begin ImgCanvas.Pen.Color := PenColor; ImgCanvas.Pen.Width := Size; if (BrushColor = clNone) then ImgCanvas.Brush.Style := bsClear else begin ImgCanvas.Brush.Style := bsSolid; ImgCanvas.Brush.Color := BrushColor; end; end; procedure TTool.Update( X, Y: Integer ); begin x2 := X; y2 := Y; end; { TLine } procedure TLine.Draw( ImgCanvas: TCanvas ); begin inherited; ImgCanvas.MoveTo( x1, y1 ); ImgCanvas.LineTo( x2, y2 ); end; { TPen } procedure TPen.Draw( ImgCanvas: TCanvas ); begin inherited; x1 := x2; y1 := y2; end; { TRectangle } procedure TRectangle.Draw( ImgCanvas: TCanvas ); begin inherited; ImgCanvas.Rectangle( x1, y1, x2, y2 ); end; { TEllipse } procedure TEllipse.Draw( ImgCanvas: TCanvas ); begin inherited; ImgCanvas.Ellipse( x1, y1, x2, y2 ); end; { CLICK TOOLS ROUTINES } procedure FillAtXY( ImgCanvas: TCanvas; X, Y: Integer; Color: TColor ); begin ImgCanvas.Brush.Color := Color; ImgCanvas.FloodFill( X, Y, ImgCanvas.Pixels[X,Y], fsSurface ); end; end.
unit avrisphw; {$mode objfpc}{$H+} interface uses Classes, SysUtils, basehw, libusb, usbhid, msgstr, utilfunc; type { TUsbAspHardware } TAvrispHardware = class(TBaseHardware) private FDevOpened: boolean; FDevHandle: Pusb_dev_handle; FDeviceDescription: TDeviceDescription; FStrError: string; public constructor Create; destructor Destroy; override; function GetLastError: string; override; function DevOpen: boolean; override; procedure DevClose; override; //spi function SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; override; function SPIInit(speed: integer): boolean; override; procedure SPIDeinit; override; //I2C procedure I2CInit; override; procedure I2CDeinit; override; function I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; override; procedure I2CStart; override; procedure I2CStop; override; function I2CReadByte(ack: boolean): byte; override; function I2CWriteByte(data: byte): boolean; override; //return ack //MICROWIRE function MWInit(speed: integer): boolean; override; procedure MWDeinit; override; function MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; override; function MWIsBusy: boolean; override; end; implementation uses main; const SPI_SPEED_8 = 0; // clock 16MHz = 8MHz SPI, clock 8MHz = 4MHz SPI SPI_SPEED_4 = 1; // 4MHz SPI SPI_SPEED_2 = 2; // 2MHz SPI SPI_SPEED_1 = 3; // 1MHz SPI SPI_SPEED_500 = 4; // 500KHz SPI SPI_SPEED_250 = 5; // 250KHz SPI SPI_SPEED_125 = 6; // 125KHz SPI STATUS_CMD_UNKNOWN = $C9; CMD_ENTER_PROGMODE_SPI25 = $30; CMD_LEAVE_PROGMODE_SPI25 = $31; CMD_SPI25_READ = $32; CMD_SPI25_WRITE = $33; CMD_FIRMWARE_VER = $34; //I2C CMD_I2C_READ = $35; CMD_I2C_WRITE = $36; CMD_I2C_START = $37; CMD_I2C_STOP = $55; CMD_I2C_READBYTE = $56; CMD_I2C_WRITEBYTE = $57; CMD_I2C_INIT = $58; //MW CMD_MW_READ = $38; CMD_MW_WRITE = $39; CMD_MW_BUSY = $40; CMD_MW_INIT = $41; CMD_SET_PARAMETER = $02; CMD_GET_PARAMETER = $03; PARAM_SCK_DURATION = $98; IN_EP = $82; OUT_EP = $02; STREAM_TIMEOUT_MS = 1000; constructor TAvrispHardware.Create; begin FDevHandle := nil; FDeviceDescription.idPRODUCT := $2104; FDeviceDescription.idVENDOR := $03EB; FHardwareName := 'Avrisp'; FHardwareID := CHW_AVRISP; end; destructor TAvrispHardware.Destroy; begin DevClose; end; function TAvrispHardware.GetLastError: string; begin result := usb_strerror; if UpCase(result) = 'NO ERROR' then result := FStrError; end; function TAvrispHardware.DevOpen: boolean; var err: integer; buff : array[0..3] of byte; begin if FDevOpened then DevClose; FDevHandle := nil; FDevOpened := false; err := USBOpenDevice(FDevHandle, FDeviceDescription); if err <> 0 then begin case err of USBOPEN_ERR_ACCESS: FStrError := STR_CONNECTION_ERROR+ FHardwareName +'(Can''t access)'; USBOPEN_ERR_IO: FStrError := STR_CONNECTION_ERROR+ FHardwareName +'(I/O error)'; USBOPEN_ERR_NOTFOUND: FStrError := STR_CONNECTION_ERROR+ FHardwareName +'(Not found)'; end; Exit(false); end; usb_set_configuration(FDevHandle, 1); usb_claim_interface(FDevHandle, 0); //Есть ли в прошивке наши команды buff[0]:= CMD_FIRMWARE_VER; usb_bulk_write(FDevHandle, OUT_EP, buff, 1, STREAM_TIMEOUT_MS); usb_bulk_read(FDevHandle, IN_EP, buff, 2, STREAM_TIMEOUT_MS); if buff[1] = STATUS_CMD_UNKNOWN then begin FStrError := STR_NO_EEPROM_SUPPORT; Exit(false); end; FDevOpened := true; Result := true; end; procedure TAvrispHardware.DevClose; begin if FDevHandle <> nil then begin usb_release_interface(FDevHandle, 0); USB_Close(FDevHandle); FDevHandle := nil; FDevOpened := false; end; end; //SPI___________________________________________________________________________ function TAvrispHardware.SPIInit(speed: integer): boolean; var buffer: array[0..2] of byte; begin if not FDevOpened then Exit(false); result := true; //spi speed buffer[0]:= CMD_SET_PARAMETER; buffer[1]:= PARAM_SCK_DURATION; buffer[2]:= speed; if usb_bulk_write(FDevHandle, OUT_EP, buffer, Length(buffer), STREAM_TIMEOUT_MS) <> Length(buffer) then result := false; if usb_bulk_read(FDevHandle, IN_EP, buffer, 2, STREAM_TIMEOUT_MS) <> 2 then result := false; if buffer[1] <> 0 then begin FStrError := 'STR_SET_SPEED_ERROR'; Exit(false); end; //spi init buffer[0]:= CMD_ENTER_PROGMODE_SPI25; if usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS) <> 1 then result := false; if usb_bulk_read(FDevHandle, IN_EP, buffer, 2, STREAM_TIMEOUT_MS) <> 2 then result := false; if buffer[1] <> 0 then result := false; end; procedure TAvrispHardware.SPIDeinit; var buffer: array[0..1] of byte; begin if not FDevOpened then Exit; buffer[0]:= CMD_LEAVE_PROGMODE_SPI25; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; function TAvrispHardware.SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; var buff: array[0..3] of byte; begin if not FDevOpened then Exit(-1); buff[0] := CMD_SPI25_READ; buff[1] := lo(Word(BufferLen)); buff[2] := hi(Word(BufferLen)); buff[3] := CS; usb_bulk_write(FDevHandle, OUT_EP, buff, Length(buff), STREAM_TIMEOUT_MS); result := usb_bulk_read(FDevHandle, IN_EP, buffer, BufferLen, STREAM_TIMEOUT_MS); end; function TAvrispHardware.SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; const HEADER_SIZE = 4; var full_buffer: array of byte; begin if not FDevOpened then Exit(-1); SetLength(full_buffer, BufferLen+HEADER_SIZE); full_buffer[0] := CMD_SPI25_WRITE; full_buffer[1] := lo(Word(BufferLen)); full_buffer[2] := hi(Word(BufferLen)); full_buffer[3] := CS; Move(buffer, full_buffer[HEADER_SIZE], BufferLen); result := usb_bulk_write(FDevHandle, OUT_EP, full_buffer[0], BufferLen+HEADER_SIZE, STREAM_TIMEOUT_MS) - HEADER_SIZE; end; //i2c___________________________________________________________________________ procedure TAvrispHardware.I2CInit; var buffer: byte; begin if not FDevOpened then Exit; buffer:= CMD_I2C_INIT; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; procedure TAvrispHardware.I2CDeinit; var buffer: array[0..1] of byte; begin if not FDevOpened then Exit; buffer[0]:= CMD_LEAVE_PROGMODE_SPI25; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; function TAvrispHardware.I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; const HEADER_LEN = 5; var StopAfterWrite: byte; buff: array of byte; begin if not FDevOpened then Exit(-1); StopAfterWrite := 1; if WBufferLen > 0 then begin if RBufferLen > 0 then StopAfterWrite := 0; SetLength(buff, WBufferLen+HEADER_LEN); buff[0] := CMD_I2C_WRITE; buff[1] := lo(Word(WBufferLen)); buff[2] := hi(Word(WBufferLen)); buff[3] := DevAddr; buff[4] := StopAfterWrite; Move(WBuffer, buff[HEADER_LEN], WBufferLen); result := usb_bulk_write(FDevHandle, OUT_EP, buff[0], WBufferLen+HEADER_LEN, STREAM_TIMEOUT_MS) - HEADER_LEN; end; if RBufferLen > 0 then begin SetLength(buff, HEADER_LEN); buff[0] := CMD_I2C_READ; buff[1] := lo(Word(RBufferLen)); buff[2] := hi(Word(RBufferLen)); buff[3] := DevAddr; buff[4] := 0; usb_bulk_write(FDevHandle, OUT_EP, buff[0], HEADER_LEN, STREAM_TIMEOUT_MS); Result := Result + usb_bulk_read(FDevHandle, IN_EP, RBuffer, RBufferLen, STREAM_TIMEOUT_MS); end; end; procedure TAvrispHardware.I2CStart; var buffer: byte; begin if not FDevOpened then Exit; buffer:= CMD_I2C_START; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; procedure TAvrispHardware.I2CStop; var buffer: byte; begin if not FDevOpened then Exit; buffer:= CMD_I2C_STOP; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; function TAvrispHardware.I2CReadByte(ack: boolean): byte; var buff: array[0..1] of byte; data: byte; begin if not FDevOpened then Exit; buff[0] := CMD_I2C_READBYTE; if ack then buff[1] := 0 else buff[1] := 1; usb_bulk_write(FDevHandle, OUT_EP, buff, SizeOf(buff), STREAM_TIMEOUT_MS); usb_bulk_read(FDevHandle, IN_EP, data, 1, STREAM_TIMEOUT_MS); Result := data; end; function TAvrispHardware.I2CWriteByte(data: byte): boolean; var buff: array[0..1] of byte; status: byte = 1; begin if not FDevOpened then Exit; buff[0] := CMD_I2C_WRITEBYTE; buff[1] := data; usb_bulk_write(FDevHandle, OUT_EP, buff, SizeOf(buff), STREAM_TIMEOUT_MS); usb_bulk_read(FDevHandle, IN_EP, status, 1, STREAM_TIMEOUT_MS); Result := Boolean(Status); end; //MICROWIRE_____________________________________________________________________ function TAvrispHardware.MWInit(speed: integer): boolean; var buffer: array[0..2] of byte; begin if not FDevOpened then Exit(false); result := true; //spi speed buffer[0]:= CMD_SET_PARAMETER; buffer[1]:= PARAM_SCK_DURATION; buffer[2]:= speed; if usb_bulk_write(FDevHandle, OUT_EP, buffer, SizeOf(buffer), STREAM_TIMEOUT_MS) <> SizeOf(buffer) then result := false; if usb_bulk_read(FDevHandle, IN_EP, buffer, 2, STREAM_TIMEOUT_MS) <> 2 then result := false; if buffer[1] <> 0 then begin FStrError := 'STR_SET_SPEED_ERROR'; Exit(false); end; //spi init buffer[0]:= CMD_MW_INIT; if usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS) <> 1 then result := false; end; procedure TAvrispHardware.MWDeInit; var buffer: array[0..1] of byte; begin if not FDevOpened then Exit; buffer[0]:= CMD_LEAVE_PROGMODE_SPI25; usb_bulk_write(FDevHandle, OUT_EP, buffer, 1, STREAM_TIMEOUT_MS); end; function TAvrispHardware.MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; var buff: array[0..3] of byte; begin if not FDevOpened then Exit(-1); buff[0] := CMD_MW_READ; buff[1] := lo(Word(BufferLen)); buff[2] := hi(Word(BufferLen)); buff[3] := CS; result := 0; usb_bulk_write(FDevHandle, OUT_EP, buff, Length(buff), STREAM_TIMEOUT_MS); if BufferLen = 0 then BufferLen := 1; //костыль result := usb_bulk_read(FDevHandle, IN_EP, buffer, BufferLen, STREAM_TIMEOUT_MS); end; function TAvrispHardware.MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; const HEADER_SIZE = 5; var buff: array of byte; bytes: byte; begin if not FDevOpened then Exit(-1); SetLength(buff, 2+HEADER_SIZE); bytes := ByteNum(BitsWrite); buff[0] := CMD_MW_WRITE; buff[1] := bytes; buff[2] := 0; buff[3] := CS; buff[4] := BitsWrite; Move(buffer, buff[HEADER_SIZE], 2); result := usb_bulk_write(FDevHandle, OUT_EP, buff[0], bytes+HEADER_SIZE, STREAM_TIMEOUT_MS)-HEADER_SIZE; if result = bytes then result := BitsWrite; logprint(inttostr(result)); end; function TAvrispHardware.MWIsBusy: boolean; var buf: byte; begin buf := CMD_MW_BUSY; result := False; usb_bulk_write(FDevHandle, OUT_EP, buf, 1, STREAM_TIMEOUT_MS); usb_bulk_read(FDevHandle, IN_EP, buf, 1, STREAM_TIMEOUT_MS); if buf = 1 then result := True; end; end.
{Дан двумерный массив A[m,n]. Найти среднее значение отрицательных элементов массива, величина которых < -20. Результаты выдать на экран.} var a:array[1..100,1..100] of integer; var i,j,n,m,k:integer; var s,sr:real; begin randomize; s:=0; k:=0; read(n,m); for i:=1 to n do begin for j:=1 to m do begin a[i,j]:=random(-50,50); if a[i,j]<-20 then begin s:=s+a[i,j]; k:=k+1; sr:=s/k; end; end; end; for i:=1 to n do begin for j:=1 to m do begin write(a[i,j]:4) end; writeln; end; writeln('Сумма: ',s); writeln('Количество: ',k); writeln('Среднее значение: ',sr:0:2); end. //проверочные данные:3,3
unit uSqlFunctions; interface uses Sysutils, uSystemConst, xBase, uSystemTypes, uStringFunctions; Const ORDER_AUTO = -1; ORDER_ASC = 0; ORDER_DESC = 1; type TSQLStatement = array[0..10] of String; TSQLAgregate = array[0..4] of String; // amfsouza May 3, 2013 TSQLOptimizer = array[0..6] of String; const aSqlStatement : TSQLStatement = ('SELECT', 'FROM', 'INNER JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN', 'WHERE' , 'GROUP BY', 'HAVING', 'ORDER BY', 'COMPUTE'); aSqlOptimizer : TSQLOptimizer = ('INDEX', 'NOLOCK', 'HOLDLOCK', 'UPDLOCK', 'TABLOCK', 'PAGLOCK', 'TABLOCKX'); aSqlAgregate : TSQLAgregate = ('AVG(', 'COUNT(', 'MAX(', 'MIN(', 'SUM('); ST_SELECT = 0; ST_FROM = 1; ST_INNERJOIN = 2; ST_LEFTJOIN = 3; ST_RIGHTJOIN = 4; ST_FULLJOIN = 5; ST_WHERE = 6; ST_GROUP = 7; ST_HAVING = 8; ST_ORDER = 9; ST_COMPUTE = 10; function ChangeWhereClause(OldSQL, NewWhere : String; IsChange : Boolean) : String; function ChangeHavingClause(OldSQL, NewHaving : String; IsChange : Boolean) : String; function BuildMaxSQL(MaxField, OldSQl : String) : String; function GetSQLFirstTableName(SQlText : String) : String; function GetSQLFirstTableAlias(SQlText : String) : String; function ChangeSQLOrder(SQlText, AFieldName : String; TypeOrder : Integer) : String; function ChangeSQLState(OldSQL : String; DesativadoState : TDesativadoState; HiddenState : THiddenState) : String; function UnMountSQL(SQlText : String) : TSqlStatement; function UnMountPureSQL(SQlText : String) : TSqlStatement; function MountSQL(SqlStatement : TSqlStatement) : String; function GetFieldAlias(AFieldName, SQLText : String) : String; function GetFieldOrigin(SQLText, FieldName : String) : String; function IsAgregate(SQLText : String) : Boolean; function MontaComboWhereClause(sTableAlias, sTableField, sSource : string):String; implementation function ChangeWhereClause(OldSQL, NewWhere : String; IsChange : Boolean) : String; var MySqlStatement : TSQlStatement; begin if NewWhere = '' then begin Result := OldSQL; Exit; end; MySqlStatement := UnMountSQL(OldSQL); if IsChange or (MySqlStatement[ST_WHERE] = '') then MySqlStatement[ST_WHERE] := NewWhere else MySqlStatement[ST_WHERE] := MySqlStatement[ST_WHERE] + ' AND ' + NewWhere; Result := MountSQL(MySqlStatement); end; function ChangeHavingClause(OldSQL, NewHaving : String; IsChange : Boolean) : String; var MySqlStatement : TSQlStatement; begin if NewHaving = '' then begin Result := OldSQL; Exit; end; MySqlStatement := UnMountSQL(OldSQL); if IsChange or (MySqlStatement[ST_HAVING] = '') then MySqlStatement[ST_HAVING] := NewHaving else MySqlStatement[ST_HAVING] := MySqlStatement[ST_HAVING] + ' AND ' + NewHaving; Result := MountSQL(MySqlStatement); end; function BuildMaxSQL(MaxField, OldSQl : String) : String; var MySqlStatement : TSQlStatement; begin MySqlStatement := UnMountSQL(OldSQL); MySqlStatement[ST_SELECT] := 'MAX( ' + MaxField + ' )'; MySqlStatement[ST_ORDER] := ''; Result := MountSQL(MySqlStatement); end; function GetSQLFirstTableName(SQlText : String) : String; var MySqlStatement : TSQLStatement; AuxTable, AuxSQl : String; i : integer; begin MySqlStatement := UnMountPureSQL(SQlText); // Descubro quem e a primeira tabela AuxSql := Trim(MySQlStatement[ST_FROM]); AuxTable := ''; for i := 1 to Length(AuxSQl) do begin if not ( AuxSQL[i] in ['(', ')', ',', ' '] ) then AuxTable := AuxTable + AuxSql[i]; if ( AuxSql[i] in [',', ' '] ) or ( i = Length(AuxSQl) ) then Break; end; Result := Trim(AuxTable); end; function GetSQLFirstTableAlias(SQlText : String) : String; var MySqlStatement : TSQLStatement; AuxTable, AuxSQl : String; i, IniPos : integer; begin MySqlStatement := UnMountPureSQL(SQlText); // Descubro quem e a primeira tabela AuxSql := Trim(MySQlStatement[ST_FROM]); AuxTable := ''; IniPos := Pos(' ', AuxSQl); if IniPos = 0 then begin IniPos := Pos(' AS ', AuxSQl); if IniPos > 0 then Inc(i); end; Inc(IniPos); for i := IniPos to Length(AuxSQl) do begin if not ( AuxSQL[i] in ['(', ')', ',', ' '] ) then AuxTable := AuxTable + AuxSql[i]; if ( AuxSql[i] in [',', ' '] ) or ( i = Length(AuxSQl) ) then Break; end; Result := Trim(AuxTable); end; function ChangeSQLOrder(SQlText, AFieldName : String; TypeOrder : Integer) : String; var PosOrder : integer; strTypeOrder : String; begin // Descobre o Order By do Query PosOrder := Pos('ORDER BY', UpperCase(SqlText)); if TypeOrder = ORDER_ASC then strTypeOrder := ' ASC' else strTypeOrder := ' DESC'; if PosOrder > 0 then SQlText := LeftStr(SQlText, PosOrder-1); // amfsouza 11.30.2011 Result := Trim(SQlText + 'ORDER BY ' + GetFieldAlias(AFieldName, SQLText) + lowerCase(AFieldName) + strTypeOrder); Result:= Result + ''; end; function ChangeSQLState(OldSQL : String; DesativadoState : TDesativadoState; HiddenState : THiddenState) : String; var FirstTable, WhereClause1, WhereClause2 : String; begin FirstTable := GetSQLFirstTableAlias(OldSQL); case DesativadoState of STD_DESATIVADO : WhereClause1 := FirstTable + '.DESATIVADO = 1'; STD_NAODESATIVADO : WhereClause1 := FirstTable + '.DESATIVADO = 0'; STD_AMBOSDESATIVADO : WhereClause1 := ''; end; case HiddenState of STD_HIDDEN : WhereClause2 := FirstTable + '.HIDDEN = 1'; STD_NAOHIDDEN : WhereClause2 := FirstTable + '.HIDDEN = 0'; STD_AMBOSHIDDEN : WhereClause2 := ''; end; Result := ChangeWhereClause(OldSQL, WhereClause1, False); Result := ChangeWhereClause(Result, WhereClause2, False); end; function UnMountSQL(SQlText : String) : TSqlStatement; var i, IniPos, NextPos, NextState : integer; AuxPos : array[0..10] of integer; begin SQLText := Trim(SQLText); // Calcula posicao inicial do Statement for i := 0 to High(aSqlStatement) do AuxPos[i] := Pos(aSqlStatement[i], UpperCase(RemoveUserText(SQlText))); // Separa as clausulas for i := 0 to High(aSqlStatement) do begin if AuxPos[i] = 0 then begin Result[i] := ''; Continue; end; // Descobre qual a proxima clausula disponivel e existente NextState := i+1; while NextState <= High(aSqlStatement) do begin if AuxPos[NextState] > 0 then Break; Inc(NextState); end; if NextState > High(aSqlStatement) then // nao existe mais statements NextPos := Length(SQlText) + 1 else NextPos := AuxPos[NextState]; IniPos := AuxPos[i] + Length(aSqlStatement[i]); Result[i] := Trim(Copy(SQlText, IniPos, NextPos - IniPos)); end; end; function UnMountPureSQL(SQlText : String) : TSqlStatement; var PosHint, i, IniDel, FimDel : integer; SubSQL : String; begin Result := UnMountSQL(SQlText); if Result[ST_FROM] <> '' then begin SubSQL := UpperCase(Result[ST_FROM]); // retira hints de otimizacao for i := 0 to High(aSqlOptimizer) do begin PosHint := Pos(aSqlOptimizer[i], SubSQL); while PosHint > 0 do begin PosHint := Pos(aSqlOptimizer[i], SubSQL); // acha o hint e deve retiralo if PosHint > 0 then begin IniDel := PosHint; FimDel := PosHint; // acha o ( inicial while SubSQL[IniDel] <> '(' do Dec(IniDel); // acha o ( final while SubSQL[FimDel] <> ')' do Inc(FimDel); Delete(SubSQL, IniDel, FimDel-IniDel+1); end; end; end; Result[ST_FROM] := SubSQL; end; end; function MountSQL(SqlStatement : TSqlStatement) : String; var i : integer; begin Result := ''; // Calcula posicao inicial do Statement for i := 0 to High(SqlStatement) do begin if SqlStatement[i] <> '' then Result := Result + aSqlStatement[i] + ' ' + SqlStatement[i] + ' '; end; end; function GetFieldAlias(AFieldName, SQLText : String) : String; var i, PosAlias : integer; AliasOrder : String; MySqlStatement : TSqlStatement; begin // Coloca a Alias do field a ser ordenado se houver MySqlStatement := UnMountSQL(SQlText); PosAlias := Pos('.' + UpperCase(AFieldName) + ',', UpperCase(MySqlStatement[ST_SELECT])); if PosAlias = 0 then PosAlias := Pos('.' + UpperCase(AFieldName) + ' ', UpperCase(MySqlStatement[ST_SELECT])); if PosAlias > 0 then begin Dec(PosAlias); i := PosAlias; while i > 0 do begin if (MySqlStatement[ST_SELECT][i] = ' ') or (MySqlStatement[ST_SELECT][i] = ',') then Break; Dec(i); end; Result := Copy(MySqlStatement[ST_SELECT], i+1, (PosAlias-i)+1) end else Result := ''; end; function GetFieldOrigin(SQLText, FieldName : String) : String; var nPos, nStartField, nEndField, LenField : integer; MySqlStatement : TSqlStatement; AuxField, SelectText : String; begin // Se nao e derivado de alias ele mesmo e sua descricao completa MySqlStatement := UnMountSQL(SQlText); SelectText := UpperCase(MySqlStatement[ST_SELECT]); FieldName := UpperCase(FieldName); LenField := Length(FieldName); nEndField := 0; // descobre aonde esta o field for nPos := 1 to Length(SelectText) do begin if Copy(SelectText, nPos, LenField) = FieldName then begin if SelectText[nPos-1] = ' ' then begin if (nPos+LenField-1 = Length(SelectText)) or (SelectText[nPos+LenField] = ' ') or (SelectText[nPos+LenField] = ',') then begin nEndField := nPos-1; Break; end; end; end; end; if nEndField = 0 then Result := GetFieldAlias(FieldName, SQLText) + FieldName else begin // Acha aonde comeca o Field nStartField := 1; nPos := nEndField; while nPos > 0 do begin if SelectText[nPos] = ',' then begin nStartField := nPos+1; nPos := -1; end else Dec(nPos) end; // Monta o field AuxField := ''; for nPos := nStartField to nEndField do begin if (SelectText[nPos] = ' ') and (SelectText[nPos+1] = 'A') and (SelectText[nPos+2] = 'S') and (SelectText[nPos+3] = ' ') then begin Break; end else begin AuxField := AuxField + SelectText[nPos]; end; end; Result := AuxField; // Caso o campo esteja sozinho if Trim(Result) = '' then Result := GetFieldAlias(FieldName, SQLText) + FieldName; end; end; function IsAgregate(SQLText : String) : Boolean; var i : integer; begin Result := False; for i := 0 to High(aSqlAgregate) do begin if Pos(aSqlAgregate[i], UpperCase(SQLText)) > 0 then begin Result := True; Break; end; end; end; function MontaComboWhereClause(sTableAlias, sTableField, sSource : String):String; begin Result := sTableAlias + '.' + sTableField + ' IN (' + sSource + ')'; end; end.
unit Modules.Configuration; interface uses System.SysUtils, System.Classes, Vcl.BaseImageCollection, AdvTypes, System.ImageList, Vcl.ImgList, Vcl.VirtualImageList, AdvStyleIF, AdvAppStyler; type TConfiguration = class(TDataModule) SVGCollection: TAdvSVGImageCollection; Glyphs: TVirtualImageList; AppStyler: TAdvAppStyler; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FURI: String; FFolderName: String; { Private declarations } procedure LoadFromReg; procedure SaveToReg; public { Public declarations } property URI: String read FURI write FURI; property FolderName: String read FFolderName write FFolderName; end; var Configuration: TConfiguration; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses Windows, Registry; const KEY = 'Software\FlixEngineering\BikeTour'; { TConfiguration } procedure TConfiguration.DataModuleCreate(Sender: TObject); begin LoadFromReg; end; procedure TConfiguration.DataModuleDestroy(Sender: TObject); begin SaveToReg; end; procedure TConfiguration.LoadFromReg; var LReg: TRegistry; begin LReg := TRegistry.Create; try LReg.RootKey := HKEY_CURRENT_USER; if LReg.OpenKey( KEY, False ) then begin URI := LReg.ReadString('URI'); FolderName := LReg.ReadString('FolderName'); end; finally LReg.Free; end; end; procedure TConfiguration.SaveToReg; var LReg : TRegistry; begin LReg := TRegistry.Create; try LReg.RootKey := HKEY_CURRENT_USER; if LReg.OpenKey( KEY, True ) then begin LReg.WriteString('URI', FURI); LReg.WriteString('FolderName', FFolderName); LReg.CloseKey; end; finally LReg.Free; end; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0048.PAS Description: Math Evaluations Author: WARREN PORTER Date: 11-21-93 09:29 *) { From: WARREN PORTER Subj: eval Program to evaluate expressions using a stack. } const Maxstack = 100; type stack = record top : 0..Maxstack; Item : array[1..Maxstack] of char end; RealStack = record top: 0..Maxstack; Item : array[1..Maxstack] of real end; xptype = record oper : char; opnd : real end; Function Empty(var A:stack):boolean; Begin Empty:= A.top = 0; End; Function Pop(var A:stack):char; Begin if A.Top < 1 then begin writeln('Attempt to pop an empty stack'); halt(1) end; Pop:= A.item[A.top]; A.top:= A.top - 1 End; Procedure Push(var A:stack; Nchar:char); Begin if A.Top = Maxstack then begin writeln('Stack already full'); halt(1) end; A.top:= A.top + 1; A.item[A.top]:=Nchar End; {The following functions are for the real stack only.} Function REmpty(var D:RealStack):boolean; Begin REmpty:= D.top = 0; End; Function RPop(var D:RealStack):real; Begin if D.Top < 1 then begin writeln('Attempt to pop an empty RealStack'); halt(1) end; RPop:= D.item[D.top]; D.top:= D.top - 1 End; Procedure RPush(var D:RealStack; Nreal:real); Begin if D.Top = MaxStack then begin writeln('Stack already full'); halt(1) end; D.top:= D.top + 1; D.item[D.top]:=Nreal End; Function pri(op1, op2:char):boolean; var tpri: boolean; Begin if op2 = ')' then tpri:= true else if (op1 = '$') and (op2 <> '$') and (op2 <> '(') then tpri:= true else if (op1 in ['*','/']) and (op2 in ['+','-']) then tpri:= true else tpri:= false; pri:= tpri{; write('Eval op 1= ',op1, ' op2 = ',op2); if tpri= false then writeln(' false') else writeln(' true')} End; Function ConvReal(a:real;NumDec:integer):real; var i, tenpower: integer; Begin tenpower:= 1; for i:= 1 to NumDec do tenpower:= tenpower * 10; ConvReal:= a / tenpower End; Function ROper(opnd1, opnd2: real; oper: char):real; Var temp: real; Begin Case oper of '+': temp:= opnd1 + opnd2; '-': temp:= opnd1 - opnd2; '*': temp:= opnd1 * opnd2; '/': temp:= opnd1 / opnd2; '$': temp:= exp(ln(opnd1) * opnd2) End {Case} ; {Writeln(opnd1:6:3,' ',oper,' ',opnd2:6:3 ,' = ',temp:6:3);} ROper := temp End; {R oper} {Main procedure starts here} var A: stack; Inbuff:string[Maxstack]; len, i, j, NumDecPnt, lenexp: integer; temp, opnd1, opnd2, result : real; valid, expdigit, expdec, isneg, openok: boolean; operators, digits : set of char; HoldTop : char; B: array[1..Maxstack] of xptype; C: array[1..Maxstack] of xptype; D: RealStack; Begin digits:= ['0'..'9']; operators:= ['$','*','/','+','-','(',')']; Writeln('Enter expression to evaluate or RETURN to stop'); Writeln('A space should follow a minus sign unless it is used to'); Writeln('negate the following number. Real numbers with multi-'); Writeln('digits and decimal point (if needed) may be entered.'); Writeln; Readln(Inbuff); len:=length(Inbuff); repeat i:= 1; A.top:= 0; valid:= true; repeat if Inbuff[i] in ['(','[','{'] then push(A,Inbuff[i]) else if Inbuff[i] in [')',']','}'] then if empty(A) then valid:= false else if (ord(Inbuff[i]) - ord(Pop(A))) > 2 then valid:= false; i:= i + 1 until (i > len) or (not valid); if not empty(A) then valid:= false; if not valid then Writeln('The expression is invalid') else Begin {Change all groupings to parenthesis} for i:= 1 to len do Begin if Inbuff[i] in ['[','{'] then Inbuff[i]:= '(' else if Inbuff[i] in [']','}'] then Inbuff[i]:= ')'; B[i].oper:= ' '; B[i].opnd:= 0; C[i].oper:= ' '; C[i].opnd:= 0 End; { The B array will be the reformatted input string. The C array will be the postfix expression. } i:= 1; j:= 1; expdigit:= false; expdec:= false; isneg:= false; while i <= len do Begin if (Inbuff[i] = '-') and (Inbuff[i + 1] in digits) then Begin isneg:= true; i:= i + 1 End; if (Inbuff[i] = '.' ) then Begin i:= i + 1; expdec:= true End; if Inbuff[i] in digits then Begin if expdec then NumDecPnt:= NumDecPnt + 1; if expdigit then temp:= temp * 10 + ord(inbuff[i]) - ord('0') else Begin temp:= ord(inbuff[i]) - ord('0'); expdigit:= true End End else if expdigit = true then Begin if isneg then temp:= temp * -1; B[j].opnd:= ConvReal(temp,NumDecPnt); j:= j + 1; expdigit := false; expdec := false; NumDecPnt:= 0; isneg:= false End; If Inbuff[i] in operators then Begin B[j].oper:= Inbuff[i]; j:= j + 1 End; if not (Inbuff[i] in digits) and not (Inbuff[i] in operators) and not (Inbuff[i] = ' ') then Begin Writeln('Found invalid operator: ',Inbuff[i]); valid:= false End; i:= i + 1; End; {While loop to parse string.} if expdigit = true then Begin if isneg then temp:= temp * -1; B[j].opnd:= ConvReal(temp,NumDecPnt); j:= j + 1; expdigit := false; expdec := false; NumDecPnt:= 0; isneg:= false End; End; {First if valid loop. Next one won't run if invalid operator} if valid then Begin lenexp:= j - 1; {Length of converted expression} writeln; for i:= 1 to lenexp do Begin if B[i].oper = ' ' then write(B[i].opnd:2:3) else write(B[i].oper); write(' ') End; {Ready to create postfix expression in array C } A.top:= 0; j:= 0; for i:= 1 to lenexp do Begin {writeln('i = ',i);} if B[i].oper = ' ' then Begin j:= j + 1; C[j].opnd:= B[i].opnd End else Begin openok := true; while (not empty(A) and openok and pri(A.item[A.top],B[i].oper)) do Begin HoldTop:= pop(A); if HoldTop = '(' then openok:= false else Begin j:= j + 1; C[j].oper:=HoldTop End End; if B[i].oper <> ')' then push(A,B[i].oper); End; {Else} End; {For loop} while not empty(A) do Begin HoldTop:= pop(A); if HoldTop <> '(' then Begin j:= j + 1; C[j].oper:=HoldTop End End; lenexp:= j; {Since parenthesis are not included in postfix.} for i:= 1 to lenexp do Begin if C[i].oper = ' ' then write(C[i].opnd:2:3) else write(C[i].oper); write(' ') End; {The following evaluates the expression in the real stack} D.top:=0; for i:= 1 to lenexp do Begin if C[i].oper = ' ' then Rpush(D,C[i].opnd) else Begin opnd2:= Rpop(D); opnd1:= Rpop(D); result:= ROper(opnd1,opnd2,C[i].oper); Rpush(D,result) End {else} End; {for loop} result:= Rpop(D); if Rempty(D) then writeln(' = ',result:2:3) else writeln(' Could not evaluate',chr(7)) End; Readln(Inbuff); len:= length(Inbuff) until len = 0 End.
unit ibSHUserFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, ELPropInsp, ExtCtrls, TypInfo; type TibSHUserForm = class(TibBTComponentForm) Panel1: TPanel; PropInspector: TELPropertyInspector; procedure PropInspectorFilterProp(Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo; var AIncludeProp: Boolean); procedure PropInspectorGetEditorClass(Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo; var AEditorClass: TELPropEditorClass); private { Private declarations } FUserIntf: IibSHUser; procedure DoShowProps(AInspector: TELPropertyInspector; APersistent: TPersistent); protected procedure DoOnIdle; override; procedure DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); override; procedure DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; function ReceiveEvent(AEvent: TSHEvent): Boolean; override; property User: IibSHUser read FUserIntf; end; var ibSHUserForm: TibSHUserForm; implementation {$R *.dfm} { TibSHUserForm } constructor TibSHUserForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHUser, FUserIntf); DoShowProps(PropInspector, Component); if Assigned(ModalForm) then begin SetFormSize(240, 340); if Component.CanShowProperty('UserName') then Caption := Format('%s', ['Add New User']) else Caption := Format('Modify User "%s"', [User.UserName]); end; end; destructor TibSHUserForm.Destroy; begin inherited Destroy; end; procedure TibSHUserForm.DoShowProps(AInspector: TELPropertyInspector; APersistent: TPersistent); var AList: TList; begin AList := TList.Create; try if Assigned(AInspector) then with AInspector do begin BeginUpdate; if Assigned(APersistent) then begin AList.Add(APersistent); Objects.SetObjects(AList); end else Objects.Clear; EndUpdate; end; finally AList.Free; end; end; procedure TibSHUserForm.DoOnIdle; begin end; procedure TibSHUserForm.DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); begin if ModalResult = mrOK then PropInspector.Perform(CM_EXIT, 0, 0); end; procedure TibSHUserForm.DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); begin inherited DoOnAfterModalClose(Sender, ModalResult); end; function TibSHUserForm.ReceiveEvent(AEvent: TSHEvent): Boolean; begin case AEvent.Event of SHE_REFRESH_OBJECT_INSPECTOR: PropInspector.UpdateItems; end; Result := True; end; procedure TibSHUserForm.PropInspectorFilterProp(Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo; var AIncludeProp: Boolean); begin AIncludeProp := Assigned(Component) and Component.CanShowProperty(APropInfo.Name); end; procedure TibSHUserForm.PropInspectorGetEditorClass(Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo; var AEditorClass: TELPropEditorClass); begin AEditorClass := TELPropEditorClass(Designer._GetProxiEditorClass( TELPropertyInspector(Sender), AInstance, APropInfo)); end; end.
(******************************************************) (* *) (* Program HP Calculator *) (* *) (* PASCAL 187 with Sushant Patnaik *) (* Scott Janousek [SCOTTJ] #011-52-0632 *) (* Assigment #2 post fix Calculator *) (* *) (******************************************************) program Calculator(input,output); CONST MaxStack = 4; TYPE (* Stack abstract Data Type *) Commands = packed array [1..10] of char; ErrorStacks = ARRAY [1..MaxStack] of Boolean; Stack = ARRAY [1..MaxStack] of Real; (* Stack Defined *) (***********************) (* *) (* Variable Statements *) (* *) (***********************) VAR Command: Commands; StackADT: stack; ErrorStack: Errorstacks; (* Define all Variables *) Num: integer; Err: boolean; quit: boolean; c: integer; X,Y,Z,T: Real; NewVal: real; (*****************************************************************************) procedure Push(VAR Value: real; VAR Errors: boolean); begin StackADT[4]:=StackADT[3]; (* Push the elements into Stack *) StackADT[3]:=StackADT[2]; StackADT[2]:=StackADT[1]; StackADT[1]:=Value; ErrorStack[4]:=ErrorStack[3]; ErrorStack[3]:=ErrorStack[2]; (* Push errorchecking *) ErrorStack[2]:=ErrorStack[1]; ErrorStack[1]:=Errors; end; (*****************************************************************************) procedure Create; var c: integer; begin (* Create the Stack for use *) for c:=1 to 4 do begin StackADT[c]:=0; ErrorStack[c]:=FALSE; end; end; (******************************************************************************) procedure Pop; begin StackADT[1]:=StackADT[2]; (* Pop the element out of stack *) StackADT[2]:=StackADT[3]; StackADT[3]:=StackADT[4]; end; (******************************************************************************) procedure RollUp; var Value: Real; ErrorTemp: Boolean; begin Value:=StackADT[1]; (* Roll Stack up each element *) StackADT[1]:=StackADT[2]; StackADT[2]:=StackADT[3]; StackADT[3]:=StackADT[4]; StackADT[4]:=Value; ErrorTemp:=ErrorStack[1]; ErrorStack[1]:=ErrorStack[2]; ErrorStack[2]:=ErrorStack[3]; ErrorStack[3]:=ErrorStack[4]; ErrorStack[4]:=ErrorTemp; end; (******************************************************************************) procedure RollDown; var Value: Real; ErrorTemp: Boolean; (* Roll the stack down each element *) begin Value:=StackADT[4]; StackADT[4]:=StackADT[3]; StackADT[3]:=StackADT[2]; StackADT[2]:=StackADT[1]; StackADT[1]:=Value; ErrorTemp:=ErrorStack[4]; ErrorStack[4]:=ErrorStack[3]; ErrorStack[3]:=ErrorStack[2]; ErrorStack[2]:=ErrorStack[1]; ErrorStack[1]:=ErrorTemp; end; (******************************************************************************) procedure SwapXY; var Value: Real; Errortemp: Boolean; begin Value:=StackADT[1]; (* Swap the X and Y in Stack *) StackADT[1]:=StackADT[2]; StackADT[2]:=Value; ErrorTemp:=ErrorStack[1]; ErrorStack[1]:=ErrorStack[2]; ErrorStack[2]:=ErrorTemp; end; (******************************************************************************) procedure Help; begin writeln; writeln('** HELP ** HELP ** HELP ** HELP **HELP **'); writeln; writeln('+ Addition Q Quit '); writeln('- subtraction % swap X and Y '); writeln('* Multiplication < Roll up '); writeln('/ division > Roll down '); writeln('- subtraction C Clear '); writeln('@ Change Sign ~ Inverse '); writeln('X Erase X'); writeln; writeln('** HELP ** HELP ** HELP ** HELP ** HELP **'); writeln; end; (******************************************************************************) procedure DrawScreen; (* Draw the Screen Output (Stack) *) begin writeln; writeln; for c:=1 to 4 do begin if ErrorStack[c] = TRUE then write(' ERROR ') else Case c of 1: writeln('X: ',StackADT[c]:4:2); 2: writeln('Y: ',StackADT[c]:4:2); 3: writeln('Z: ',StackADT[c]:4:2); 4: writeln('T: ',StackADT[c]:4:2); end; end; end; (******************************************************************************) begin (* Main Program *) REPEAT DrawScreen; writeln; writeln; writeln; write('Enter X: (of type ? for help)> '); readln(command); readv(command, X, error:=continue); if (statusV = 0) then Push(X, err) ELSE writeln; CASE command[1] OF (* CASE of Valid Operands *) (* No need for error in CASE *) ' ': (* only reads first character *) begin Push(X,err); (* Push X down Stack if enter *) end; 'Q','q': begin quit:=TRUE; (* Quit the program *) end; '>': begin Rollup (* Roll Up X and rest of stack*) end; '<': begin Rolldown; (* Roll down X and rest of stack *) end; '~': begin if NOT (ErrorStack[1]) then (* Do an inverse *) StackADT[1]:=(1/StackADT[1]); end; '+': (* X and Y Addition *) begin NewVal:=StackADT[2] + StackADT[1]; Pop; StackADT[1]:=NewVal; end; '-': begin (* X and Y Subtraction *) NewVal:=StackADT[1] - StackADT[2]; Pop; StackADT[1]:=NewVal; end; '*': (* X and Y Multiplication *) begin NewVal:=StackADT[2] * StackADT[1]; Pop; StackADT[1]:=NewVal; end; '/': (* X and Y Division *) begin if StackADT[1] <> 0 then begin NewVal:=StackADT[1] / StackADT[2]; Pop; StackADT[1]:=NewVal; end else Push(X, err); end; 'X','x': (* Erase element X *) begin StackADT[1]:=0; end; '%': (* Swap X and Y *) begin SwapXY; end; '@': (* Change the sign of X *) begin if NOT (ErrorStack[1] = true) then StackADT[1]:=StackADT[1] * (-1); end; 'c','C': (* Clear all stack *) begin Create; end; '?': (* Help *) begin Help; end; end; until quit = TRUE; writeln; writeln('ProgramHP Terminated . . .'); end.
namespace LinqToSQL; interface uses System.Drawing, System.Collections, System.Collections.Generic, System.Linq, System.Data.Linq, System.Data.Linq.Mapping, System.Windows.Forms, System.ComponentModel; type /// <summary> /// Summary description for Form1. /// </summary> MainForm = partial class(System.Windows.Forms.Form) private method btnSelectDBFile_Click(sender: System.Object; e: System.EventArgs); method btnExecuteSELECT_Click(sender: System.Object; e: System.EventArgs); method btnExecuteJOIN_Click(sender: System.Object; e: System.EventArgs); protected method Dispose(aDisposing: Boolean); override; public constructor; end; implementation {$REGION Construction and Disposition} constructor MainForm; begin // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // end; method MainForm.Dispose(aDisposing: Boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); // // TODO: Add custom disposition code here // end; inherited Dispose(aDisposing); end; {$ENDREGION} method MainForm.btnSelectDBFile_Click(sender: System.Object; e: System.EventArgs); begin if openFileDialog.ShowDialog = DialogResult.OK then begin tbDatabase.Text := openFileDialog.FileName; end; end; method MainForm.btnExecuteSELECT_Click(sender: System.Object; e: System.EventArgs); var path : String := System.IO.Path.GetFullPath(tbDatabase.Text); db : DataContext := new DataContext(path); begin Cursor := Cursors.WaitCursor; try var contacts := from contact in db.GetTable<Contact>() where contact.ModifiedDate.Year = 2001 select contact; dataGridView.DataSource := contacts; finally Cursor := Cursors.Default; end; end; method MainForm.btnExecuteJOIN_Click(sender: System.Object; e: System.EventArgs); var path : String := System.IO.Path.GetFullPath(tbDatabase.Text); db : DataContext := new DataContext(path); cats : Table<Category> := db.GetTable<Category>(); subcats : Table<SubCategory> := db.GetTable<SubCategory>(); begin Cursor := Cursors.WaitCursor; try var query := from cat in cats join subcat in subcats on cat.CategoryID equals subcat.CategoryID order by cat.Name select new class ( cat.Name, subcat.SubCatName); dataGridView.DataSource := query; finally Cursor := Cursors.Default; end; end; end.
(* Copyright (c) 2016 Darian Miller All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. As of January 2016, latest version available online at: https://github.com/darianmiller/dxLib_Tests *) unit dxLib_Test_JSONObjectArray; interface {$I '..\Dependencies\dxLib\Source\dxLib.inc'} uses TestFramework, dxLib_JSONObjects; type TestTdxJSONObjectArray = class(TTestCase) published procedure TestStringArray(); procedure TestBoolArray(); procedure TestCurrencyArray(); procedure TestFloatArray(); procedure TestIntegerArray(); procedure TestInt64Array(); end; implementation uses dxLib_JSONUtils; procedure TestTdxJSONObjectArray.TestStringArray(); var vArray:TdxJSONArrayOfString; vJSON:String; begin vArray := TdxJSONArrayOfString.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '["1"]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '["1","2"]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add('1'); vArray.Add('2'); vArray.Add('3'); vArray.Add('4'); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString('1', vArray.Items[0]); CheckEqualsString('2', vArray.Items[1]); CheckEqualsString('3', vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('["1","2","3"]', vJSON); vArray.AsJSON := '["1","2","3"]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vJSON, vArray.AsJSON); //somewhat liberal conversion: Boolean/Integer auto-converted to string vArray.AsJson := '["1",2,3,true,false,null]'; CheckEquals(6, vArray.Count, 'Count'); CheckEqualsString('1', vArray.Items[0]); CheckEqualsString('2', vArray.Items[1]); CheckEqualsString('3', vArray.Items[2]); CheckEqualsString('true', vArray.Items[3]); CheckEqualsString('false', vArray.Items[4]); CheckEqualsString('', vArray.Items[5]); //null string finally vArray.Free(); end; end; procedure TestTdxJSONObjectArray.TestBoolArray(); var vArray:TdxJSONArrayOfBoolean; vJSON:String; begin vArray := TdxJSONArrayOfBoolean.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '[false]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '[false,false]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add(false); vArray.Add(true); vArray.Add(false); vArray.Add(true); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEquals(false, vArray.Items[0]); CheckEquals(true, vArray.Items[1]); CheckEquals(false, vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('[false,true,false]', vJSON); vArray.AsJSON := '[false,true,false]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vArray.AsJSON, vJSON); //somewhat liberal conversion: null + strings (true|false) auto-converted to boolean but not other types like integer/float //If desiring integer, change TdxJSONArrayOfBoolean.GetItem vArray.AsJson := '[1, "TRUE", 1.1, null]'; CheckEquals(4, vArray.Count, 'Count'); CheckEquals(false, vArray.Items[0]); CheckEquals(true, vArray.Items[1]); CheckEquals(false, vArray.Items[2]); CheckEquals(false, vArray.Items[3]); finally vArray.Free(); end; end; procedure TestTdxJSONObjectArray.TestCurrencyArray(); var vArray:TdxJSONArrayOfCurrency; vJSON:String; begin vArray := TdxJSONArrayOfCurrency.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '[1]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '[1,2]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add(0); vArray.Add(1); vArray.Add(2); vArray.Add(3); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('[0.00,1.00,2.00]', vJSON); vArray.AsJSON := '[0,1,2]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vJSON, vArray.AsJSON); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); //somewhat liberal conversion: strings auto-converted to currency, null to 0, bool (True or False) to 0 vArray.AsJson := '["1", 2, "3", null, true, "FALSE"]'; CheckEquals(6, vArray.Count, 'Count'); CheckEquals(1, vArray.Items[0]); CheckEquals(2, vArray.Items[1]); CheckEquals(3, vArray.Items[2]); CheckEquals(0, vArray.Items[3]); CheckEquals(0, vArray.Items[4]); CheckEquals(0, vArray.Items[5]); finally vArray.Free(); end; end; procedure TestTdxJSONObjectArray.TestFloatArray; var vArray:TdxJSONArrayOfFloat; vJSON:String; begin vArray := TdxJSONArrayOfFloat.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '[1]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '[1,2]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add(0); vArray.Add(1.1); vArray.Add(2.2); vArray.Add(3); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEquals(0, vArray.Items[0]); CheckEquals(1.1, vArray.Items[1]); CheckEquals(2.2, vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('[0,1.1,2.2]', vJSON); vArray.AsJSON := '[0,1.1,2.2]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vJSON, vArray.AsJSON); CheckEquals(0, vArray.Items[0]); CheckEquals(1.1, vArray.Items[1]); CheckEquals(2.2, vArray.Items[2]); //somewhat liberal conversion: strings auto-converted to float, null to 0, bool (True or False) to 0 vArray.AsJson := '["1.1", 2.2, "3", null, true, "FALSE"]'; CheckEquals(6, vArray.Count, 'Count'); CheckEquals(1.1, vArray.Items[0]); CheckEquals(2.2, vArray.Items[1]); CheckEquals(3, vArray.Items[2]); CheckEquals(0, vArray.Items[3]); CheckEquals(0, vArray.Items[4]); CheckEquals(0, vArray.Items[5]); finally vArray.Free(); end; end; procedure TestTdxJSONObjectArray.TestIntegerArray; var vArray:TdxJSONArrayOfInteger; vJSON:String; begin vArray := TdxJSONArrayOfInteger.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '[1]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '[1,2]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add(0); vArray.Add(1); vArray.Add(2); vArray.Add(3); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('[0,1,2]', vJSON); vArray.AsJSON := '[0,1,2]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vJSON, vArray.AsJSON); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); //somewhat liberal conversion: strings auto-converted to float, null to 0, bool (True or False) to 0 vArray.AsJson := '["1", 2, "3", null, true, "FALSE"]'; CheckEquals(6, vArray.Count, 'Count'); CheckEquals(1, vArray.Items[0]); CheckEquals(2, vArray.Items[1]); CheckEquals(3, vArray.Items[2]); CheckEquals(0, vArray.Items[3]); CheckEquals(0, vArray.Items[4]); CheckEquals(0, vArray.Items[5]); finally vArray.Free(); end; end; procedure TestTdxJSONObjectArray.TestInt64Array; var vArray:TdxJSONArrayOfInt64; vJSON:String; vLongInt:Int64; begin vArray := TdxJSONArrayOfInt64.Create(); try CheckEquals(0, vArray.Count, 'Count'); CheckEqualsString(JSON_EMPTY_ARRAY, vArray.AsJson); vArray.AsJson := JSON_EMPTY_ARRAY; CheckEquals(0, vArray.Count, 'Count'); vArray.AsJson := '[1]'; CheckEquals(1, vArray.Count, 'Count'); vArray.AsJson := '[1,2]'; CheckEquals(2, vArray.Count, 'Count'); vArray.Clear(); CheckEquals(0, vArray.Count, 'Count'); vArray.Add(0); vArray.Add(1); vArray.Add(2); vArray.Add(3); vArray.Delete(3); CheckEquals(3, vArray.Count, 'Count'); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); vJSON := vArray.AsJson; CheckEqualsString('[0,1,2]', vJSON); vArray.AsJSON := '[0,1,2]'; CheckEquals(3, vArray.Count, 'Count'); CheckEqualsString(vJSON, vArray.AsJSON); CheckEquals(0, vArray.Items[0]); CheckEquals(1, vArray.Items[1]); CheckEquals(2, vArray.Items[2]); //somewhat liberal conversion: strings auto-converted to float, null to 0, bool (True or False) to 0 vArray.AsJson := '["1", 2, "3", null, true, "FALSE"]'; CheckEquals(6, vArray.Count, 'Count'); CheckEquals(1, vArray.Items[0]); CheckEquals(2, vArray.Items[1]); CheckEquals(3, vArray.Items[2]); CheckEquals(0, vArray.Items[3]); CheckEquals(0, vArray.Items[4]); CheckEquals(0, vArray.Items[5]); vArray.Clear; vLongInt := MaxInt; vLongInt := vLongInt + 1; vArray.Add(vLongInt); CheckEquals(1, vArray.Count, 'Count'); CheckEquals(vLongInt, vArray.Items[0]); finally vArray.Free(); end; end; initialization RegisterTest(TestTdxJSONObjectArray.Suite); end.
(* SPELLINT.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit SpellInt; {-interface unit for SPELLER.DLL} {version 2.0 no longer uses the DLL} {This file is provided for backward compatibility for users who} {accessed version 1.0 DLL directly} {$I SPELLDEF.PAS} interface uses {$IFDEF Win32} LexDCT32, {$ELSE} LexDCT, {$ENDIF} SysUtils, Classes; function dllOpenDictionary(FileName : string) : Boolean; {-Opens the specified dictionary; Returns TRUE if successful} function dllInDictionary(AWord: String) : Boolean; {-Returns TRUE if AWord is in the dictionary} function dllAddWord(AWord : String) : Boolean; {-Adds AWord to User Dictionary; Returns TRUE if successful} function dllSuggestWords(AWord: String; NumSuggest: byte): TStringList; {-Suggests words; Returns nil if unsuccessful} procedure dllDeleteUserWords; {-Deletes all word in User Dictionary} procedure dllCloseDictionary; {-Closes the currently open dictionary} implementation function dllOpenDictionary(FileName : string) : Boolean; {-Opens the specified dictionary; Returns TRUE if successful} begin if DCT = nil then DCT := TDictionary.Create; Result := DCT.OpenDictionary (Filename, 'USERDCT.TXT'); end; { dllOpenDictionary } function dllInDictionary(AWord: String) : Boolean; {-Returns TRUE if AWord is in the dictionary} begin Result := DCT.InDictionary (AWord); end; { dllInDictionary } function dllAddWord(AWord : String) : Boolean; {-Adds AWord to User Dictionary; Returns TRUE if successful} begin Result := DCT.AddWord (AWord); end; { dllAddWord } function dllSuggestWords(AWord: String; NumSuggest: byte): TStringList; {-Suggests words; Returns nil if unsuccessful} begin Result := DCT.SuggestWords (AWord, NumSuggest); end; { dllSuggestWords } procedure dllDeleteUserWords; {-Deletes all word in User Dictionary} var F: File; begin DCT.AddedWords.Clear; Assign (F, ExtractFilePath (DCT.DictFile) + DCT.UserDict); Erase (F); end; { dllDeleteUserWords } procedure dllCloseDictionary; {-Closes the currently open dictionary} begin DCT.Destroy; end; { dllCloseDictionary } end. { SpellInt }
unit ufrmBrowseQuotation; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterBrowse, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, System.Actions, Vcl.ActnList, ufraFooter4Button, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, Vcl.ExtCtrls; type TfrmBrowseQuotation = class(TfrmMasterBrowse) btnActivate: TcxButton; procedure FormCreate(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure btnActivateClick(Sender: TObject); procedure cxGridViewFocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); private { Private declarations } protected public procedure RefreshData; override; { Public declarations } end; var frmBrowseQuotation: TfrmBrowseQuotation; implementation uses ufrmDialogQuotation, uDMClient, uDXUtils; {$R *.dfm} procedure TfrmBrowseQuotation.FormCreate(Sender: TObject); begin inherited; btnActivate.Visible := False; end; procedure TfrmBrowseQuotation.actAddExecute(Sender: TObject); begin inherited; ShowDialogForm(TfrmDialogQuotation); end; procedure TfrmBrowseQuotation.actEditExecute(Sender: TObject); begin inherited; ShowDialogForm(TfrmDialogQuotation, cxGridView.DS.FieldByName('Quotation_ID').AsString); end; procedure TfrmBrowseQuotation.btnActivateClick(Sender: TObject); var frm: TfrmDialogQuotation; lResult: Integer; begin frm := TfrmDialogQuotation.Create(Application); Self.Enabled := False; Try frm.LoadData(cxGridView.DS.FieldByName('Quotation_ID').AsString); frm.InitActivation(True); lResult := frm.ShowModal; if (AutoRefreshData) and (lResult = mrOk) then RefreshData; Finally FreeAndNil(frm); Self.Cursor := crDefault; Self.Enabled := True; Self.SetFocusRec(cxGrid); End; end; procedure TfrmBrowseQuotation.cxGridViewFocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); var lDS: TDataSet; begin inherited; lDS := cxGridView.DS; if not Assigned(lDS) then exit; if lDS.Eof then exit; btnActivate.Left := btnSearch.Left-btnActivate.Width; btnActivate.Visible := cxGridView.DS.FieldByName('ISPROCESSED').AsInteger = 0; end; procedure TfrmBrowseQuotation.RefreshData; begin cxGridView.LoadFromDS( DMClient.DSProviderClient.Quotation_GetDSOverview(dtAwalFilter.Date, dtAkhirFilter.Date), Self ); cxGridView.SetVisibleColumns(['Quotation_ID'], False); end; end.
{****** 单 元:uParam.pas 作 者:刘景威 日 期:2007-6.1 说 明:参数设置单元 更 新: ******} unit uParam; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, ComCtrls, CtrlsEx, Quiz; type TfrmParam = class(TfrmBase) Bevel7: TBevel; lblFont: TLabel; lblSizeT: TLabel; edtSizeT: TEdit; udT: TUpDown; lblColorT: TLabel; cbTopic: TColorBox; lblTopicF: TLabel; lblSizeA: TLabel; edtSizeA: TEdit; udA: TUpDown; lblColorA: TLabel; cbAnswer: TColorBox; lblAnsF: TLabel; Bevel1: TBevel; lblDefSet: TLabel; lblPoint: TLabel; edtPoint: TEdit; udPoint: TUpDown; lblTimes: TLabel; edtAttempts: TEdit; udAttempts: TUpDown; lblFeed: TLabel; lblCrt: TLabel; meoCrt: TMemo; Bevel2: TBevel; lblErr: TLabel; meoErr: TMemo; lblLevel: TLabel; cbLevel: TComboBox; Bevel3: TBevel; lblSet: TLabel; cbSplash: TCheckBox; btnApplayAll: TBitBtn; cbBoldT: TCheckBox; cbBoldA: TCheckBox; cbShowIcon: TCheckBox; cbSetAudio: TCheckBox; procedure btnApplayAllClick(Sender: TObject); private { Private declarations } FQuizSet: TQuizSet; protected procedure LoadData; override; procedure SaveData; override; procedure ResetData; override; public { Public declarations } end; var frmParam: TfrmParam; function ShowParam(AQuizSet: TQuizSet): Boolean; implementation {$R *.dfm} function ShowParam(AQuizSet: TQuizSet): Boolean; begin with TfrmParam.Create(Application.MainForm) do begin try FQuizSet := AQuizSet; QuizObj.ImageList.GetIcon(6, Icon); LoadData(); Result := ShowModal() = mrOk; finally Free; end; end; end; procedure TfrmParam.LoadData; begin HelpHtml := 'param_set.html'; with FQuizSet do begin udT.Position := FontSetT.Size; cbTopic.Selected := FontSetT.Color; cbBoldT.Checked := FontSetT.Bold; udA.Position := FontSetA.Size; cbAnswer.Selected := FontSetA.Color; cbBoldA.Checked := FontSetA.Bold; udPoint.Position := Points; udAttempts.Position := Attempts; cbLevel.ItemIndex := Ord(QuesLevel); meoCrt.Text := FeedInfo.CrtInfo; meoErr.Text := FeedInfo.ErrInfo; cbShowIcon.Checked := ShowIcon; cbSplash.Checked := ShowSplash; cbSetAudio.Checked := SetAudio; end; btnApplayAll.Enabled := QuizObj.QuesList.Count <> 0; end; procedure TfrmParam.SaveData; begin with FQuizSet do begin with FontSetT do begin Size := StrToInt(edtSizeT.Text); Color := cbTopic.Selected; Bold := cbBoldT.Checked; end; with FontSetA do begin Size := StrToInt(edtSizeA.Text); Color := cbAnswer.Selected; Bold := cbBoldA.Checked; end; Points := StrToInt(edtPoint.Text); Attempts := StrToInt(edtAttempts.Text); QuesLevel := TQuesLevel(cbLevel.ItemIndex); with FeedInfo do begin CrtInfo := meoCrt.Text; ErrInfo := meoErr.Text; end; ShowIcon := cbShowIcon.Checked; ShowSplash := cbSplash.Checked; SetAudio := cbSetAudio.Checked; SaveToReg(); end; end; procedure TfrmParam.ResetData; begin udT.Position := 12; cbTopic.Selected := clBlack; cbBoldT.Checked := False; udA.Position := 12; cbAnswer.Selected := clBlack; cbBoldA.Checked := False; udPoint.Position := 10; udAttempts.Position := 0; cbLevel.ItemIndex := 2; meoCrt.Text := '恭喜您,答对了'; meoErr.Text := '您答错了'; cbShowIcon.Checked := True; cbSplash.Checked := True; cbSetAudio.Checked := False; end; procedure TfrmParam.btnApplayAllClick(Sender: TObject); var i: Integer; fi: TFeedInfo; begin if MessageBox(Handle, '您确定应用反馈信息到每个试题吗?', '提示', MB_YESNO + MB_ICONQUESTION) = ID_NO then Exit; for i := 0 to QuizObj.QuesList.Count - 1 do begin fi.CrtInfo := meoCrt.Text; fi.ErrInfo := meoErr.Text; QuizObj.QuesList.Items[i].FeedInfo := fi; end; PostMessage(QuizObj.Handle, WM_QUIZCHANGE, QUIZ_CHANGED, 0); end; end.
unit VirtualExplorerListviewEx; {============================================================================== Version 1.4.6 (VirtualShellTools release 1.1.x) Software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. The initial developer of this code is Robert Lee. Requirements: - Mike Lischke's Virtual Treeview (VT) http://www.lischke-online.de/VirtualTreeview/VT.html - Jim Kuenaman's Virtual Shell Tools (VSTools) http://groups.yahoo.com/group/VirtualExplorerTree - Mike Lischke's Theme Manager 1.9.0 or above (ONLY for Delphi 5 or Delphi 6) - Comctl32.dll v.5.81 (Internet Explorer 5.00) or later is required for the VCL Listview to work as expected in Thumbnail viewstyle. Credits: Special thanks to Mike Lischke (VT) and Jim Kuenaman (VSTools) for the magnificent components they made available to the Delphi community. Thanks to (in alphabetical order): Aaron, Adem Baba (ImageMagick conversion), Nils Haeck (ImageMagick wrapper), Gerald Köder (bugs hunter), Werner Lehmann (Thumbs Cache), Bill Miller (HyperVirtualExplorer), Renate Schaaf (Graphics guru), Boris Tadjikov (bugs hunter), Milan Vandrovec (CBuilder port), Philip Wand, Troy Wolbrink (Unicode support). Known issues: - If the Anchors property is changed at runtime and the ViewStyle is not vsxReport SyncOptions must be called. - If the node selection is changed at runtime and the ViewStyle is not vsxReport SyncSelected must be called. - If ComCtrl 6 is used the scrollbars are not invalidated correctly when the BevelKind <> bkNone, and the ViewStyle <> vsxReport. This is a VCL bug. - If ComCtrl 6 is used the Listview standard hints are not correctly painted (only the first line is showed), this happens only when ViewStyle <> vsxReport. This is a VCL bug. Development notes: - Don't use PaintTo, WinXP doesn't support it. - Don't use DrawTextW, Win9x doesn't support it, instead use: if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(...) else Windows.DrawTextW(...); - Don't use Item.DisplayRect, use TUnicodeOwnerDataListView.GetLVItemRect instead, ComCtrl 6 returns the item rect adding the item space. - Bug in Delphi 5 TGraphic class: when creating a bitmap by using its class type (TGraphicClass) it doesn't calls the TBitmap constructor. That's because in Delphi 5 the TGraphic.Create is protected, and TBitmap.Create is public, so TGraphicClass(ABitmap).Create will NOT call TBitmap.Create because it's not visible by TGraphicClass. To fix this we need to make it visible by creating a TGraphicClass cracker. Fixed in LoadGraphic helper. More info on: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00000331.0164178b%40xmission.com VCL TListview bugs fixed by VELVEx: - TListview bug: setting ShowHint to False doesn't disable the hints. Fixed in TSyncListView.CMShowHintChanged. - TListview bug: if the ClientHeight is too small to fit 2 items the PageUp/PageDown key buttons won't work. To fix this I had to fake these keys to Up/Down in TSyncListView.KeyDown. - TListview bug only in Delphi 7: the Listview invalidates the canvas when scrolling, the problem is in ComCtrls.pas: TCustomListView.WMVScroll. Fixed in TSyncListView.WMVScroll, I had to call the TWinControl WM_VSCROLL handler, sort of inherited-inherited. Contact Mike Lischke, this was introduced by D7 ThemeManager engine. - TListview bug only in Win2K and WinXP: the Listview Edit control is not showed correctly when the font size is large (Height > 15), this is visible in vsReport, vsList and vsSmallIcon viewstyles. We must reshow the Edit control. Fixed in TUnicodeOwnerDataListView.CNNotify with LVN_BEGINLABELEDIT and LVN_BEGINLABELEDITW messages. - TListview bug only on WinXP using ComCtl 6: a thick black border around the edit box is showed when editing an item in the list. Fixed in TUnicodeOwnerDataListView.WMCtlColorEdit. - OwnerData TListview bug on WinXP using ComCtl 6: it has to invalidate its Canvas on resizing. Fixed in TUnicodeOwnerDataListView.WMWindowPosChanging. This is fixed on Delphi 2005: http://qc.borland.com/qc/wc/wc.exe/details?ReportID=5920 - OwnerData TListview bug on WinXP using ComCtl 6: Item.DisplayRect(drBounds) returns an incorrect Rect, the R.Left and R.Right includes the item spacing, this problem is related with the selectable space between icons issue. This is corrected in TUnicodeOwnerDataListView.GetLVItemIconRect. - OwnerData TListview bug on WinXP using ComCtl 6: the white space between icons (vsxIcon or vsxThumbs) becomes selectable, but not the space between the captions. This is related to previous bug. Fixed in TUnicodeOwnerDataListView.WndProc. - OwnerData TListview bug: when the Listview is small enough to not fit 2 fully visible items the PageUp/PageDown buttons don't work. Fixed in TSyncListView.KeyDown. - OwnerData TListview bug: when Shift-Selecting an item, it just selects all the items from the last selected to the current selected, index wise, it should box-select the items. Fixed in TSyncListView.OwnerDataStateChange, KeyMultiSelectEx and MouseMultiSelectEx. - OwnerData TListview bug: the OnAdvancedCustomDrawItem event doesn't catch cdPostPaint paint stage. Fixed in TSyncListView.CNNotify. - OwnerData TListview bug: when the Listview is unfocused and a previously selected item caption is clicked it enters in editing mode. This is an incorrect TListview behavior. To fix this issue I set a flag: FPrevEditing in TSyncListView.CMEnter and deactivate it in TSyncListView.CanEdit and when the selection changes in TSyncListView.CNNotify. - OwnerData TListview bug: the virtual TListView raises an AV in vsReport mode. Fixed in TSyncListView.LVMInsertColumn and TSyncListView.LVMSetColumn. - OwnerData TListview bug: when the icon arrangement is iaLeft the arrow keys are scrambled. Fixed in TSyncListView.KeyDown. To Do - History: 6 November 2005 - Added support for threaded enumeration of objects - Jim K 28 September 2005 - version 1.4.6 - Made GetChildByIndex function more robust. - Fixed 0000017 Mantis entry: AV when deleting file. - Fixed 0000023 Mantis entry: incorrect mouse click events when HideCaptions or ComCtl6 was used. - Fixed problem in CM_FONTCHANGED and Begin/End Update causing TListview to access window handle during streaming, thanks to Jim for the fix. - Fixed incorrect selection painting, now it uses the Colors.FocusedSelectionColor and Colors.UnFocusedSelectionColor properties. - Fixed incorrect focus painting when syncronizing the selection. - Added new border styles, tbWindowed and tbFit. - Added new SingleLineCaptions property to the ThumbsOptions. - Added Ctrl-I shortcut to invert the selection. 31 May 2005 - version 1.4.5 - Fixed AV when creating large Metafiles thumbnails, thanks to Polo for the fix. - Fixed incorrect drag image when DragImageKind was diNoImage, thanks to Thomas Bauer for reporting this. - Denied Theme Manager subclassing. - Added new property: ThumbsOptions.CacheOptions.AdjustIconSize to allow dynamic thumbnails resizing. 21 December 2004 - version 1.4.4 - Added EditFile method, to easily browse for a file to select it and begin to edit it. - Fixed incorrect checkboxes sync. - Fixed incorrect mouse button click handling when ComCtrls 6 is used, thanks to Gabriel Cristescu for reporting this. 27 August 2004 - version 1.4.3 - Added checkbox support for vsxThumbs viewstyle. - Added partial background image support to non vsxReport ViewStyles, the background should be loaded in the listview using the ListView_SetBkImage API: var BK: TLVBKImage; begin // LVBKIF_SOURCE_HBITMAP flag is not supported by ListView_SetBkImage // TLVBKImage.hbm is not supported by ListView_SetBkImage Fillchar(BK, SizeOf(BK), 0); BK.ulFlags := LVBKIF_SOURCE_URL or LVBKIF_STYLE_TILE; BK.pszImage := PChar(Edit1.text); ListView_SetBkImage(LV.ChildListview.Handle, @BK); end; 23 May 2004 - version 1.4.2 - Added support for toHideOverlay and toRestoreTopNodeOnRefresh properties. - Added new property: ThumbsOptions.CacheOptions.CacheProcessing to allow ascending or descending sorting of the thread cache processing list. When this property is tcpAscending the top files in the listview are thumbnailed first. - Fixed incorrect selection painting, it now uses the values in Colors.FocusedSelectionColor and Colors.UnFocusedSelectionColor. - Fixed an incorrect call to OnEditCancelled. - Reworked the internal cache events. 5 March 2004 - version 1.4.1 - Compatible with VSTools 1.1.15 - Fixed drag and drop synchronization, it now correctly fires OnDragDrop event when the ViewStyle <> vsxReport. - Fixed incorrect icon spacing when the handle is recreated. ==============================================================================} interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ComCtrls, ImgList, Dialogs, Forms, VirtualTrees, VirtualExplorerTree, VirtualShellutilities, ActiveX, Commctrl, VirtualUtilities, VirtualUnicodeDefines, VirtualWideStrings, ShlObj, VirtualResources, VirtualShellTypes, VirtualSystemImageLists, VirtualIconThread, // Got to have it for the Thumbnail thread {$IFDEF USEGRAPHICEX} GraphicEx, {$ELSE} {$IFDEF USEIMAGEEN} ImageEnIo, {$ELSE} {$IFDEF USEIMAGEMAGICK} MagickImage, ImageMagickAPI, {$ENDIF} {$ENDIF} {$ENDIF} VirtualUnicodeControls, JPeg, ComObj; const SCROLL_DELAY_TIMER = 100; SCROLL_TIMER = 101; WM_VLVEXTHUMBTHREAD = WM_SHELLNOTIFY + 100; CM_DENYSUBCLASSING = CM_BASE + 2000; // Prevent Theme Manager subclassing { // TListView Extended Styles LVS_EX_LABELTIP = $00004000; // Partially hidden captions hint LVS_EX_BORDERSELECT = $00008000; // Highlight the border when selecting items // TListView Extended Styles for ComCtl32.dll version 6 // LVS_EX_DOUBLEBUFFER = $00010000; // Enables alpha blended selection, defined in VirtualShellTypes LVS_EX_HIDELABELS = $00020000; // Hide the captions, like Shift clicking Thumbnails viewstyle option in Explorer LVS_EX_SINGLEROW = $00040000; // Like thumb stripes mode LVS_EX_SNAPTOGRID = $00080000; // Snaps the icons to grid LVS_EX_SIMPLESELECT = $00100000; // ? } type TCustomVirtualExplorerListviewEx = class; TThumbsCacheItem = class; TThumbsCache = class; TIconSpacing = record X: Word; Y: Word; end; TIconAttributes = record Size: TPoint; Spacing: TIconSpacing; end; TThumbnailState = ( tsEmpty, //empty data tsProcessing, //processing thumbnail tsValid, //valid image tsInvalid); //not an image TThumbnailBorder = (tbNone, tbRaised, tbDoubleRaised, tbSunken, tbDoubleSunken, tbBumped, tbEtched, tbFramed, tbWindowed, tbFit); TThumbnailHighlight = (thNone, thSingleColor, thMultipleColors); TThumbnailImageLibrary = (timNone, timGraphicEx, timImageEn, timEnvision, timImageMagick); TViewStyleEx = (vsxIcon, vsxSmallIcon, vsxList, vsxReport, vsxThumbs); TThumbsCacheStorage = (tcsCentral, tcsPerFolder); TThumbsCacheProcessing = (tcpAscending, tcpDescending); PThumbnailData = ^TThumbnailData; TThumbnailData = packed record CachePos: integer; Reloading: Boolean; State: TThumbnailState; end; PThumbnailThreadData = ^TThumbnailThreadData; TThumbnailThreadData = packed record ImageWidth: integer; ImageHeight: integer; State: TThumbnailState; MemStream: TMemoryStream; CompressedStream: Boolean; end; TOLEListviewButtonState = ( LButtonDown, RButtonDown, MButtonDown ); TOLEListviewButtonStates = set of TOLEListviewButtonState; TRectArray = array of TRect; TLVThumbsDraw = procedure(Sender: TCustomVirtualExplorerListviewEx; ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean) of object; TLVThumbsDrawHint = procedure(Sender: TCustomVirtualExplorerListviewEx; HintBitmap: TBitmap; Node: PVirtualNode; var DefaultDraw: Boolean) of object; TLVThumbsGetDetails = procedure(Sender: TCustomVirtualExplorerListviewEx; Node: PVirtualNode; HintDetails: Boolean; var Details: WideString) of object; TLVThumbsCacheItemReadEvent = procedure(Sender: TCustomVirtualExplorerListviewEx; Filename: WideString; Thumbnail: TBitmap; var DoDefault: Boolean) of object; TLVThumbsCacheItemLoadEvent = procedure(Sender: TCustomVirtualExplorerListviewEx; NS: TNamespace; CacheItem: TThumbsCacheItem; var DoDefault: Boolean) of object; TLVThumbsCacheItemProcessingEvent = procedure(Sender: TCustomVirtualExplorerListviewEx; NS: TNamespace; Thumbnail: TBitmap; var ImageWidth, ImageHeight: Integer; var DoDefault: Boolean) of object; TLVThumbsCacheEvent = procedure(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList; var DoDefault: Boolean) of object; TExtensionsList = class(TWideStringList) private function GetColors(Index: integer): TColor; procedure SetColors(Index: integer; const Value: TColor); public constructor Create; virtual; function Add(const Extension: WideString; HighlightColor: TColor): Integer; reintroduce; function AddObject(const S: WideString; AObject: TObject): Integer; override; function IndexOf(const S: WideString): Integer; override; function DeleteString(const S: WideString): Boolean; virtual; property Colors[Index: integer]: TColor read GetColors write SetColors; end; TBitmapHint = class(THintWindow) private FHintBitmap: TBitmap; FActivating: Boolean; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; protected procedure Paint; override; public property Activating: Boolean read FActivating; procedure ActivateHint(Rect: TRect; const AHint: string); override; procedure ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer); override; end; TThumbsCacheItem = class private FFileDateTime: TDateTime; FImageWidth: Integer; FImageHeight: Integer; FExif: WideString; FComment: WideString; FCompressed: Boolean; FThumbImageStream: TMemoryStream; FStreamSignature: WideString; protected FFilename: WideString; procedure Changed; virtual; function DefaultStreamSignature: WideString; virtual; property CompressedThumbImageStream: Boolean read FCompressed write FCompressed; property ThumbImageStream: TMemoryStream read FThumbImageStream; public constructor Create(AFilename: WideString); virtual; constructor CreateFromStream(ST: TStream); virtual; destructor Destroy; override; procedure Assign(CI: TThumbsCacheItem); virtual; procedure Fill(AFileDateTime: TDateTime; AExif, AComment: WideString; AImageWidth, AImageHeight: Integer; ACompressed: Boolean; AThumbImageStream: TMemoryStream); function LoadFromStream(ST: TStream): Boolean; virtual; procedure SaveToStream(ST: TStream); virtual; function ReadBitmap(OutBitmap: TBitmap): Boolean; procedure WriteBitmap(ABitmap: TBitmap; CompressIt: Boolean); property Comment: WideString read FComment write FComment; property Exif: WideString read FExif write FExif; property Filename: WideString read FFilename; property FileDateTime: TDateTime read FFileDateTime write FFileDateTime; property ImageWidth: Integer read FImageWidth write FImageWidth; property ImageHeight: Integer read FImageHeight write FImageHeight; property StreamSignature: WideString read FStreamSignature; end; TThumbsCacheItemClass = class of TThumbsCacheItem; TThumbsCache = class private FDirectory: WideString; FLoadedFromFile: Boolean; FStreamVersion: Integer; FSize: Integer; FInvalidCount: Integer; FThumbWidth: Integer; FThumbHeight: Integer; FComments: TWideStringList; function GetCount: integer; protected FHeaderFilelist: TWideStringList; //List of filenames encoded like: "filename*comment", it owns TMemoryStreams FScreenBuffer: TWideStringList; //List of filenames, owns TBitmaps, it's a cache to speed screen rendering function DefaultStreamVersion: integer; virtual; public constructor Create; virtual; destructor Destroy; override; procedure Clear; function IndexOf(Filename: WideString): integer; function Add(Filename: WideString; CI: TThumbsCacheItem): Integer; overload; function Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer; ACompressIt: Boolean; AThumbImage: TBitmap): Integer; overload; function Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer; ACompressed: Boolean; AThumbImageStream: TMemoryStream): Integer; overload; procedure Assign(AThumbsCache: TThumbsCache); function Delete(Filename: WideString): boolean; function Read(Index: integer; var OutCacheItem: TThumbsCacheItem): Boolean; overload; function Read(Index: integer; OutBitmap: TBitmap): Boolean; overload; procedure LoadFromFile(const Filename: WideString); overload; procedure LoadFromFile(const Filename: WideString; InvalidFiles: TWideStringList); overload; procedure SaveToFile(const Filename: WideString); property Directory: WideString read FDirectory write FDirectory; property ThumbWidth: integer read FThumbWidth write FThumbWidth; property ThumbHeight: integer read FThumbHeight write FThumbHeight; property Comments: TWideStringList read FComments; property Count: integer read GetCount; //Count includes the deleted thumbs, ValidCount = Count - InvalidCount property InvalidCount: integer read FInvalidCount; property LoadedFromFile: boolean read FLoadedFromFile; property StreamVersion: integer read FStreamVersion; property Size: integer read FSize; end; TCacheList = class(TWideStringList) private FCentralFolder: WideString; FDefaultFilename: WideString; procedure SetCentralFolder(const Value: WideString); public constructor Create; virtual; procedure DeleteAllFiles; procedure DeleteInvalidFiles; function GetCacheFileToLoad(Dir: Widestring): WideString; function GetCacheFileToSave(Dir: Widestring): WideString; procedure SaveToFile; reintroduce; procedure LoadFromFile; reintroduce; property CentralFolder: WideString read FCentralFolder write SetCentralFolder; property DefaultFilename: WideString read FDefaultFilename write FDefaultFilename; end; TThumbsCacheOptions = class(TPersistent) private FOwner: TCustomVirtualExplorerListviewEx; FAdjustIconSize: boolean; FAutoSave: boolean; FAutoLoad: boolean; FCompressed: boolean; FStorageType: TThumbsCacheStorage; FDefaultFilename: WideString; FBrowsingFolder: WideString; FCacheProcessing: TThumbsCacheProcessing; function GetCentralFolder: WideString; function GetSize: integer; function GetThumbsCount: integer; procedure SetBrowsingFolder(const Value: WideString); procedure SetCacheProcessing(const Value: TThumbsCacheProcessing); procedure SetCentralFolder(const Value: WideString); procedure SetCompressed(const Value: boolean); protected FThumbsCache: TThumbsCache; //Cache of the browsing folder FCacheList: TCacheList; //List of cache files public constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure ClearCache(DeleteAllFiles: Boolean = False); function GetCacheFileFromCentralFolder(Dir: WideString): WideString; function RenameCacheFileFromCentralFolder(Dir, NewDirName: WideString; NewCacheFilename: WideString = ''): Boolean; procedure Reload(Node: PVirtualNode); overload; procedure Reload(Filename: WideString); overload; procedure Load(Force: Boolean = false); procedure Save; function Read(Node: PVirtualNode; var OutCacheItem: TThumbsCacheItem): Boolean; overload; function Read(Filename: WideString; var OutCacheItem: TThumbsCacheItem): Boolean; overload; function Read(Node: PVirtualNode; OutBitmap: TBitmap): Boolean; overload; function Read(Filename: WideString; OutBitmap: TBitmap): Boolean; overload; property Size: integer read GetSize; property ThumbsCount: integer read GetThumbsCount; property Owner: TCustomVirtualExplorerListviewEx read FOwner; property BrowsingFolder: WideString read FBrowsingFolder write SetBrowsingFolder; published property AdjustIconSize: boolean read FAdjustIconSize write FAdjustIconSize default False; property AutoLoad: boolean read FAutoLoad write FAutoLoad default False; property AutoSave: boolean read FAutoSave write FAutoSave default False; property DefaultFilename: WideString read FDefaultFilename write FDefaultFilename; property StorageType: TThumbsCacheStorage read FStorageType write FStorageType default tcsCentral; property CacheProcessing: TThumbsCacheProcessing read FCacheProcessing write SetCacheProcessing default tcpDescending; property CentralFolder: WideString read GetCentralFolder write SetCentralFolder; property Compressed: boolean read FCompressed write SetCompressed default False; end; TThumbsOptions = class(TPersistent) private FOwner: TCustomVirtualExplorerListviewEx; FCacheOptions: TThumbsCacheOptions; FThumbsIconAtt: TIconAttributes; FDetails: Boolean; FBorderOnFiles: Boolean; FDetailsHeight: Integer; FHighlightColor: TColor; FBorder: TThumbnailBorder; FHighlight: TThumbnailHighlight; FLoadAllAtOnce: Boolean; FBorderSize: Integer; FUseShellExtraction: Boolean; FShowSmallIcon: Boolean; FShowXLIcons: Boolean; FStretch: Boolean; FUseSubsampling: Boolean; function GetHeight: Integer; function GetSpaceHeight: Word; function GetSpaceWidth: Word; function GetWidth: Integer; procedure SetBorder(const Value: TThumbnailBorder); procedure SetBorderSize(const Value: Integer); procedure SetBorderOnFiles(const Value: Boolean); procedure SetDetailedHints(const Value: Boolean); procedure SetDetails(const Value: Boolean); procedure SetDetailsHeight(const Value: Integer); procedure SetHeight(const Value: Integer); procedure SetHighlight(const Value: TThumbnailHighlight); procedure SetHighlightColor(const Value: TColor); procedure SetSpaceHeight(const Value: Word); procedure SetSpaceWidth(const Value: Word); procedure SetWidth(const Value: Integer); procedure SetUseShellExtraction(const Value: Boolean); procedure SetShowSmallIcon(const Value: Boolean); procedure SetShowXLIcons(const Value: Boolean); procedure SetStretch(const Value: Boolean); procedure SetUseSubsampling(const Value: Boolean); function GetDetailedHints: Boolean; function GetHideCaptions: Boolean; procedure SetHideCaptions(const Value: Boolean); function GetSingleLineCaptions: Boolean; procedure SetSingleLineCaptions(const Value: Boolean); public constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual; destructor Destroy; override; property Owner: TCustomVirtualExplorerListviewEx read FOwner; published property Border: TThumbnailBorder read FBorder write SetBorder default tbFramed; property BorderSize: Integer read FBorderSize write SetBorderSize default 4; property BorderOnFiles: Boolean read FBorderOnFiles write SetBorderOnFiles default False; property Width: Integer read GetWidth write SetWidth default 120; property Height: Integer read GetHeight write SetHeight default 120; property SpaceWidth: Word read GetSpaceWidth write SetSpaceWidth default 40; property SpaceHeight: Word read GetSpaceHeight write SetSpaceHeight default 40; property DetailedHints: Boolean read GetDetailedHints write SetDetailedHints default False; property Details: Boolean read FDetails write SetDetails default False; property DetailsHeight: Integer read FDetailsHeight write SetDetailsHeight default 40; property HideCaptions: Boolean read GetHideCaptions write SetHideCaptions default False; property SingleLineCaptions: Boolean read GetSingleLineCaptions write SetSingleLineCaptions default False; property Highlight: TThumbnailHighlight read FHighlight write SetHighlight default thMultipleColors; property HighlightColor: TColor read FHighlightColor write SetHighlightColor default $EFD3D3; property LoadAllAtOnce: Boolean read FLoadAllAtOnce write FLoadAllAtOnce default False; property ShowSmallIcon: Boolean read FShowSmallIcon write SetShowSmallIcon default True; property ShowXLIcons: Boolean read FShowXLIcons write SetShowXLIcons default True; property UseShellExtraction: Boolean read FUseShellExtraction write SetUseShellExtraction default True; property UseSubsampling: Boolean read FUseSubsampling write SetUseSubsampling default True; property Stretch: Boolean read FStretch write SetStretch default False; property CacheOptions: TThumbsCacheOptions read FCacheOptions write FCacheOptions; end; TThumbThread = class(TVirtualImageThread) private FOwner: TCustomVirtualExplorerListviewEx; FThumbThreadData: TThumbnailThreadData; FThumbCompression: boolean; FThumbWidth: integer; FThumbHeight: integer; FTransparentColor: TColor; FThumbStretch: boolean; FThumbSubsampling: boolean; protected procedure ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo); override; procedure ExtractedInfoLoad(Info: PVirtualThreadIconInfo); override; // Load Info before being sent to Control(s) procedure InvalidateExtraction; override; procedure ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); override; function CreateThumbnail(Filename: WideString; var Thumbnail: TBitmap; var ImageWidth, ImageHeight: integer; var CompressIt: boolean): Boolean; virtual; public constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual; procedure ResetThumbOptions; virtual; property ThumbCompression: boolean read FThumbCompression; property ThumbWidth: integer read FThumbWidth; property ThumbHeight: integer read FThumbHeight; property ThumbStretch: boolean read FThumbStretch; property ThumbSubsampling: boolean read FThumbSubsampling; property TransparentColor: TColor read FTransparentColor; property Owner: TCustomVirtualExplorerListviewEx read FOwner; end; TThumbThreadClass = class of TThumbThread; TThumbThreadClassEvent = procedure(Sender: TCustomVirtualExplorerListviewEx; var ThreadClass: TThumbThreadClass) of object; //TUnicodeOwnerDataListView adds Unicode support to OWNER-DATA-ONLY TListview TUnicodeOwnerDataListView = class(TListView) private FIsComCtl6: Boolean; FHideCaptions: Boolean; FSingleLineCaptions: Boolean; FEditingItemIndex: Integer; FSingleLineMaxChars: Integer; procedure SetHideCaptions(const Value: Boolean); procedure SetSingleLineCaptions(const Value: Boolean); procedure CMDenySubclassing(var Message: TMessage); message CM_DENYSUBCLASSING; procedure CMFontchanged(var Message: TMessage); message CM_FONTCHANGED; procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY; procedure WMCtlColorEdit(var Message: TWMCtlColorEdit); message WM_CTLCOLOREDIT; procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING; protected Win32PlatformIsUnicode: boolean; PWideFindString: PWideChar; CurrentDispInfo: PLVDispInfoW; OriginalDispInfoMask: Cardinal; procedure WndProc(var Msg: TMessage); override; procedure CreateWnd; override; procedure CreateWindowHandle(const Params: TCreateParams); override; function GetItem(Value: TLVItemW): TListItem; function GetItemCaption(Index: Integer): WideString; virtual; abstract; property EditingItemIndex: Integer read FEditingItemIndex; public constructor Create(AOwner: TComponent); override; function GetFilmstripHeight: Integer; function GetLVItemRect(Index: integer; DisplayCode: TDisplayCode): TRect; procedure UpdateSingleLineMaxChars; property HideCaptions: Boolean read FHideCaptions write SetHideCaptions default False; property SingleLineCaptions: Boolean read FSingleLineCaptions write SetSingleLineCaptions default False; property IsComCtl6: Boolean read FIsComCtl6; property SingleLineMaxChars: Integer read FSingleLineMaxChars; end; //TSyncListView is used to sync VCL LV with VELV TSyncListView = class(TUnicodeOwnerDataListView) private FVETController: TCustomVirtualExplorerListviewEx; FSavedPopupNamespace: TNamespace; FFirstShiftClicked: Integer; FOwnerDataPause: Boolean; FSelectionPause: Boolean; FInPaintCycle: Boolean; FPrevEditing: Boolean; FDetailedHints: Boolean; FThumbnailHintBitmap: TBitmap; FDefaultTooltipsHandle: THandle; procedure ContextMenuCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; var Handled: Boolean); procedure ContextMenuShowCallback(Namespace: TNamespace; Menu: hMenu; var Allow: Boolean); procedure ContextMenuAfterCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; Successful: Boolean); procedure SetDetailedHints(const Value: Boolean); procedure UpdateHintHandle; procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL; procedure CMShowHintChanged(var Message: TMessage); message CM_SHOWHINTCHANGED; procedure LVMSetColumn(var Message: TMessage); message LVM_SETCOLUMN; procedure LVMInsertColumn(var Message: TMessage); message LVM_INSERTCOLUMN; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; protected procedure WndProc(var Msg: TMessage); override; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure CMHintShow(var Message: TCMHintShow); message CM_HINTSHOW; function OwnerDataFetch(Item: TListItem; Request: TItemRequest): Boolean; override; function OwnerDataHint(StartIndex: Integer; EndIndex: Integer): Boolean; override; function OwnerDataFind(Find: TItemFind; const FindString: AnsiString; const FindPosition: TPoint; FindData: Pointer; StartIndex: Integer; Direction: TSearchDirection; Wrap: Boolean): Integer; override; function OwnerDataStateChange(StartIndex, EndIndex: Integer; OldState, NewState: TItemStates): Boolean; override; procedure DoContextPopup(MousePos: TPoint; var Handled: Boolean); override; procedure Edit(const Item: TLVItem); override; function CanEdit(Item: TListItem): Boolean; override; function GetItemCaption(Index: Integer): WideString; override; function IsBackgroundValid: Boolean; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure DblClick; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateHandle; override; function IsItemGhosted(Item: TListitem): Boolean; procedure FetchThumbs(StartIndex, EndIndex: integer); procedure UpdateArrangement; property DetailedHints: Boolean read FDetailedHints write SetDetailedHints default False; property InPaintCycle: Boolean read FInPaintCycle; property OwnerDataPause: boolean read FOwnerDataPause write FOwnerDataPause; property VETController: TCustomVirtualExplorerListviewEx read FVETController write FVETController; end; //TOLEListview adds drag & drop support to TSyncListView TOLEListview = class(TSyncListView, IDropTarget, IDropSource) private FDropTargetHelper: IDropTargetHelper; FDragDataObject: IDataObject; FCurrentDropIndex: integer; FDragging: Boolean; FMouseButtonState: TOLEListviewButtonStates; FAutoScrolling: Boolean; FDropped: Boolean; FDragItemIndex: integer; //Scrolling support FScrollDelayTimer: THandle; FScrollTimer: THandle; FAutoScrollTimerStub: Pointer; // Stub for timer callback function procedure AutoScrollTimerCallback(Window: hWnd; Msg, idEvent: integer; dwTime: Longword); stdcall; protected procedure ClearTimers; procedure CreateDragImage(TotalDragRect: TRect; RectArray: TRectArray; var Bitmap: TBitmap); procedure CreateWnd; override; procedure DestroyWnd; override; function DragEnter(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall; function IDropTarget.DragOver = DragOverOLE; // Naming Clash procedure DoContextPopup(MousePos: TPoint; var Handled: Boolean); override; function DragOverOLE(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall; function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall; function DragLeave: HResult; virtual; stdcall; function GiveFeedback(dwEffect: Longint): HResult; virtual; stdcall; function ListIndexToNamespace(ItemIndex: integer): TNamespace; function ListItemToNamespace(Item: TListItem; BackGndIfNIL: Boolean): TNamespace; function QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: Longint): HResult; virtual; stdcall; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure WMRButtonDown(var Message: TWMRButtonDown); message WM_RBUTTONDOWN; procedure WMRButtonUp(var Message: TWMRButtonUp); message WM_RBUTTONUP; procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE; procedure WMTimer(var Message: TWMTimer); message WM_TIMER; property CurrentDropIndex: integer read FCurrentDropIndex write FCurrentDropIndex default -2; property DragDataObject: IDataObject read FDragDataObject write FDragDataObject; property DropTargetHelper: IDropTargetHelper read FDropTargetHelper; property MouseButtonState: TOLEListviewButtonStates read FMouseButtonState write FMouseButtonState; property AutoScrolling: Boolean read FAutoScrolling; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Dragging: Boolean; reintroduce; end; TCustomVirtualExplorerListviewEx = class(TVirtualExplorerListview) private FVisible: boolean; FAccumulatedChanging: boolean; FViewStyle: TViewStyleEx; FThumbThread: TThumbThread; FThumbsThreadPause: Boolean; FImageLibrary: TThumbnailImageLibrary; FExtensionsList: TExtensionsList; FShellExtractExtensionsList: TExtensionsList; FExtensionsExclusionList: TExtensionsList; FOnThumbsDrawBefore, FOnThumbsDrawAfter: TLVThumbsDraw; FOnThumbsDrawHint: TLVThumbsDrawHint; FOnThumbsGetDetails: TLVThumbsGetDetails; FOnThumbsCacheItemAdd: TLVThumbsCacheItemProcessingEvent; FOnThumbsCacheItemRead: TLVThumbsCacheItemReadEvent; FOnThumbsCacheItemLoad: TLVThumbsCacheItemLoadEvent; FOnThumbsCacheItemProcessing: TLVThumbsCacheItemProcessingEvent; FOnThumbsCacheLoad: TLVThumbsCacheEvent; FOnThumbsCacheSave: TLVThumbsCacheEvent; FInternalDataOffset: Cardinal; // offset to the internal data of the ExplorerListviewEx FThumbsOptions: TThumbsOptions; FOnThumbThreadClass: TThumbThreadClassEvent; function GetThumbThread: TThumbThread; procedure SetThumbThreadClassEvent(const Value: TThumbThreadClassEvent); procedure SetViewStyle(const Value: TViewStyleEx); procedure SetVisible(const Value: boolean); procedure LVOnAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED; procedure CMShowHintChanged(var Message: TMessage); message CM_SHOWHINTCHANGED; protected FListview: TOLEListview; FDummyIL: TImageList; FSearchCache: PVirtualNode; FLastDeletedNode: PVirtualNode; procedure CreateWnd; override; procedure RequestAlign; override; procedure SetParent(AParent: TWinControl); override; procedure SetZOrder(TopMost: Boolean); override; function GetAnimateWndParent: TWinControl; override; function GetClientRect: TRect; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED; procedure CMCursorChanged(var Message: TMessage); message CM_CURSORCHANGED; procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY; {$IFDEF THREADEDICONS} procedure WMVTSetIconIndex(var Msg: TWMVTSetIconIndex); message WM_VTSETICONINDEX; {$ENDIF} procedure WMVLVExThumbThread(var Message: TMessage); message WM_VLVEXTHUMBTHREAD; procedure WMEnumThreadFinished(var Msg: TMessage); message WM_ENUMTHREADFINISHED; procedure WMEnumThreadStart(var Msg: TMessage); message WM_ENUMTHREADSTART; //VirtualTree methods procedure DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); override; procedure DoFreeNode(Node: PVirtualNode); override; procedure RebuildRootNamespace; override; procedure DoRootChanging(const NewRoot: TRootFolder; Namespace: TNamespace; var Allow: Boolean); override; procedure DoStructureChange(Node: PVirtualNode; Reason: TChangeReason); override; procedure ReReadAndRefreshNode(Node: PVirtualNode; SortNode: Boolean); override; procedure DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); override; function InternalData(Node: PVirtualNode): Pointer; function IsAnyEditing: Boolean; override; function GetNodeByIndex(Index: Cardinal): PVirtualNode; procedure FlushSearchCache; //Thumbnails processing function IsValidChildListview: boolean; function GetThumbThreadClass: TThumbThreadClass; virtual; //Thumbnails cache function DoThumbsCacheItemAdd(NS: TNamespace; Thumbnail: TBitmap; ImageWidth, ImageHeight: Integer): Boolean; virtual; // A Thumbnail is about to be added to the cache function DoThumbsCacheItemLoad(NS: TNamespace; var CacheItem: TThumbsCacheItem): Boolean; virtual; // A Thumbnail was loaded from the cache function DoThumbsCacheItemRead(Filename: WideString; Thumbnail: TBitmap): Boolean; virtual; // A Thumbnail must be read from the cache function DoThumbsCacheItemProcessing(NS: TNamespace; Thumbnail: TBitmap; var ImageWidth, ImageHeight: Integer): Boolean; virtual; // A Thumbnail must be created function DoThumbsCacheLoad(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; virtual; // The cache was loaded from file function DoThumbsCacheSave(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; virtual; // The cache is about to be saved procedure ResetThumbImageList(ResetSpacing: boolean = True); procedure ResetThumbSpacing; procedure ResetThumbThread; //Thumbnails drawing function GetDetailsString(Node: PVirtualNode; ThumbFormatting: Boolean = True): WideString; function DoThumbsGetDetails(Node: PVirtualNode; HintDetails: Boolean): WideString; procedure DoThumbsDrawBefore(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); virtual; procedure DoThumbsDrawAfter(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); virtual; function DoThumbsDrawHint(HintBitmap: TBitmap; Node: PVirtualNode): Boolean; procedure DrawThumbBG(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect); procedure DrawThumbFocus(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect); procedure DrawIcon(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; RThumb, RDetails: TRect; var RDestination: TRect); property ViewStyle: TViewStyleEx read FViewStyle write SetViewStyle; property ThumbsOptions: TThumbsOptions read FThumbsOptions write FThumbsOptions; property ThumbThread: TThumbThread read GetThumbThread; property ThumbsThreadPause: Boolean read FThumbsThreadPause write FThumbsThreadPause; property OnThumbThreadClass: TThumbThreadClassEvent read FOnThumbThreadClass write SetThumbThreadClassEvent; property OnThumbsCacheItemAdd: TLVThumbsCacheItemProcessingEvent read FOnThumbsCacheItemAdd write FOnThumbsCacheItemAdd; property OnThumbsCacheItemLoad: TLVThumbsCacheItemLoadEvent read FOnThumbsCacheItemLoad write FOnThumbsCacheItemLoad; property OnThumbsCacheItemRead: TLVThumbsCacheItemReadEvent read FOnThumbsCacheItemRead write FOnThumbsCacheItemRead; property OnThumbsCacheItemProcessing: TLVThumbsCacheItemProcessingEvent read FOnThumbsCacheItemProcessing write FOnThumbsCacheItemProcessing; property OnThumbsCacheLoad: TLVThumbsCacheEvent read FOnThumbsCacheLoad write FOnThumbsCacheLoad; property OnThumbsCacheSave: TLVThumbsCacheEvent read FOnThumbsCacheSave write FOnThumbsCacheSave; property OnThumbsDrawBefore: TLVThumbsDraw read FOnThumbsDrawBefore write FOnThumbsDrawBefore; property OnThumbsDrawAfter: TLVThumbsDraw read FOnThumbsDrawAfter write FOnThumbsDrawAfter; property OnThumbsDrawHint: TLVThumbsDrawHint read FOnThumbsDrawHint write FOnThumbsDrawHint; property OnThumbsGetDetails: TLVThumbsGetDetails read FOnThumbsGetDetails write FOnThumbsGetDetails; function DoKeyAction(var CharCode: Word; var Shift: TShiftState): Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; //VT methods procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; function Focused: Boolean; override; procedure SetFocus; override; function EditNode(Node: PVirtualNode; Column: TColumnIndex): Boolean; override; function EditFile(APath: WideString): Boolean; procedure Clear; override; procedure CopyToClipBoard; override; procedure CutToClipBoard; override; function PasteFromClipboard: Boolean; override; function InvalidateNode(Node: PVirtualNode): TRect; override; //VET methods function BrowseToByPIDL(APIDL: PItemIDList; ExpandTarget, SelectTarget, SetFocusToVET, CollapseAllFirst: Boolean; ShowAllSiblings: Boolean = True): Boolean; override; procedure SelectedFilesDelete; override; procedure SelectedFilesPaste(AllowMultipleTargets: Boolean); override; procedure SelectedFilesShowProperties; override; //Synchronization methods procedure SyncInvalidate; procedure SyncItemsCount; virtual; procedure SyncOptions; virtual; procedure SyncSelectedItems(UpdateChildListview: Boolean = True); //Thumbnails public methods procedure FillExtensionsList(FillColors: Boolean = true); virtual; function GetThumbDrawingBounds(IncludeThumbDetails, IncludeBorderSize: Boolean): TRect; function IsImageFileIndex(FileName: WideString): integer; function IsImageFile(FileName: WideString): Boolean; overload; function IsImageFile(Node: PVirtualNode): TNamespace; overload; function ValidateThumbnail(Node: PVirtualNode; var ThumbData: PThumbnailData): Boolean; function ValidateListItem(Node: PVirtualNode; var ListItem: TListItem): Boolean; //Public properties property ImageLibrary: TThumbnailImageLibrary read FImageLibrary; property ChildListview: TOLEListview read FListview; property ExtensionsList: TExtensionsList read FExtensionsList; property ShellExtractExtensionsList: TExtensionsList read FShellExtractExtensionsList; property ExtensionsExclusionList: TExtensionsList read FExtensionsExclusionList; published property Visible: boolean read FVisible write SetVisible default true; end; TVirtualExplorerListviewEx = class(TCustomVirtualExplorerListviewEx) published property ViewStyle; property ThumbsOptions; property OnThumbThreadClass; property OnThumbsCacheItemAdd; property OnThumbsCacheItemLoad; property OnThumbsCacheItemRead; property OnThumbsCacheItemProcessing; property OnThumbsCacheLoad; property OnThumbsCacheSave; property OnThumbsDrawBefore; property OnThumbsDrawAfter; property OnThumbsDrawHint; property OnThumbsGetDetails; end; // Misc helpers function SpMakeObjectInstance(Method: TWndMethod): Pointer; procedure SpFreeObjectInstance(ObjectInstance: Pointer); function SpCompareText(W1, W2: WideString): Boolean; function SpPathCompactPath(S: WideString; Max: Integer): WideString; //Node manipulation helpers function GetChildByIndex(ParentNode: PVirtualNode; ChildIndex: Cardinal; var SearchCache: PVirtualNode): PVirtualNode; function IsThumbnailActive(ThumbnailState: TThumbnailState): Boolean; function SupportsShellExtract(NS: TNamespace): boolean; //Image manipulation helpers procedure InitBitmap(OutB: TBitmap; W, H: integer; BackgroundColor: TColor); procedure SpStretchDraw(G: TGraphic; OutBitmap: TBitmap; DestR: TRect; UseSubsampling: Boolean); function RectAspectRatio(ImageW, ImageH, ThumbW, ThumbH: integer; Center, Stretch: boolean): TRect; procedure DrawThumbBorder(ACanvas: TCanvas; ThumbBorder: TThumbnailBorder; R: TRect; Selected: Boolean); function IsIncompleteJPGError(E: Exception): boolean; function IsDelphiSupportedImageFile(FileName: WideString): Boolean; function GetGraphicClass(Filename: WideString): TGraphicClass; function LoadImageEnGraphic(Filename: WideString; outBitmap: TBitmap): Boolean; function LoadGraphic(Filename: WideString; outP: TPicture): boolean; function LoadImage(Filename: WideString; OutP: TPicture): boolean; function MakeThumbFromFile(Filename: WideString; OutBitmap: TBitmap; ThumbW, ThumbH: integer; Center: boolean; BgColor: TColor; Stretch, Subsampling: Boolean; var ImageWidth, ImageHeight: integer): Boolean; //Stream helpers function ReadDateTimeFromStream(ST: TStream): TDateTime; procedure WriteDateTimeToStream(ST: TStream; D: TDateTime); function ReadIntegerFromStream(ST: TStream): Integer; procedure WriteIntegerToStream(ST: TStream; I: Integer); function ReadWideStringFromStream(ST: TStream): WideString; procedure WriteWideStringToStream(ST: TStream; WS: WideString); function ReadMemoryStreamFromStream(ST: TStream; MS: TMemoryStream): Boolean; procedure WriteMemoryStreamToStream(ST: TStream; MS: TMemoryStream); function ReadBitmapFromStream(ST: TStream; B: TBitmap): Boolean; procedure WriteBitmapToStream(ST: TStream; B: TBitmap); procedure ConvertBitmapStreamToJPGStream(MS: TMemoryStream; CompressionQuality: TJPEGQualityRange); procedure ConvertJPGStreamToBitmapStream(MS: TMemoryStream); procedure ConvertJPGStreamToBitmap(MS: TMemoryStream; OutBitmap: TBitmap); implementation uses ShellApi, Math; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { Helpers } function SpMakeObjectInstance(Method: TWndMethod): Pointer; begin {$IFDEF COMPILER_6_UP} Result := Classes.MakeObjectInstance(Method); {$ELSE} Result := Forms.MakeObjectInstance(Method); {$ENDIF} end; procedure SpFreeObjectInstance(ObjectInstance: Pointer); begin {$IFDEF COMPILER_6_UP} Classes.FreeObjectInstance(ObjectInstance); {$ELSE} Forms.FreeObjectInstance(ObjectInstance); {$ENDIF} end; function SpCompareText(W1, W2: WideString): Boolean; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_NT then begin if lstrcmpiW_VST(PWideChar(W1), PWideChar(W2)) = 0 then Result := True; end else if AnsiCompareText(W1, W2) = 0 then Result := True; end; function SpPathCompactPath(S: WideString; Max: Integer): WideString; var L: Integer; begin L := Length(S); if (L > 3) and (Max > 0) and (L > Max) then begin SetLength(S, Max - 3); S := S + '...'; end; Result := S; end; function GetChildByIndex(ParentNode: PVirtualNode; ChildIndex: Cardinal; var SearchCache: PVirtualNode): PVirtualNode; var N: PVirtualNode; Count: Cardinal; begin Result := nil; if not Assigned(ParentNode) then Exit; Count := ParentNode.ChildCount; if ChildIndex >= Count then Exit; // This speeds up the search drastically if Assigned(SearchCache) and Assigned(SearchCache.Parent) and (SearchCache.Parent = ParentNode) then begin if ChildIndex >= SearchCache.Index then begin N := SearchCache; while Assigned(N) do if N.Index = ChildIndex then begin Result := N; Break; end else N := N.NextSibling; end else begin N := SearchCache; while Assigned(N) do if N.Index = ChildIndex then begin Result := N; Break; end else N := N.PrevSibling; end; end else if ChildIndex <= Count div 2 then begin N := ParentNode.FirstChild; while Assigned(N) do if N.Index = ChildIndex then begin Result := N; Break; end else N := N.NextSibling; end else begin N := ParentNode.LastChild; while Assigned(N) do if N.Index = ChildIndex then begin Result := N; Break; end else N := N.PrevSibling; end; SearchCache := Result; end; function IsThumbnailActive(ThumbnailState: TThumbnailState): Boolean; begin Result := (ThumbnailState = tsValid) or (ThumbnailState = tsProcessing); end; function SupportsShellExtract(NS: TNamespace): boolean; begin Result := Assigned(NS.ExtractImage.ExtractImageInterface); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { Drawing helpers } function RectAspectRatio(ImageW, ImageH, ThumbW, ThumbH: integer; Center, Stretch: boolean): TRect; begin Result := Rect(0, 0, 0, 0); if (ImageW < 1) or (ImageH < 1) then Exit; if (ImageW <= ThumbW) and (ImageH <= ThumbH) and (not Stretch) then begin Result.Right := ImageW; Result.Bottom := ImageH; end else begin Result.Right := (ThumbH * ImageW) div ImageH; if (Result.Right <= ThumbW) then Result.Bottom := ThumbH else begin Result.Right := ThumbW; Result.Bottom := (ThumbW * ImageH) div ImageW; end; end; if Center then with Result do begin left := (ThumbW - right) div 2; top := (ThumbH - bottom) div 2; right := left + right; bottom := top + bottom; end; // TJPEGImage doesn't accepts images with 1 pixel width or height if Result.Right <= 1 then Result.Right := 2; if Result.Bottom <= 1 then Result.Bottom := 2; end; procedure InitBitmap(OutB: TBitmap; W, H: integer; BackgroundColor: TColor); begin // OutB.PixelFormat := pf24bit; //do this first! OutB.Width := W; OutB.Height := H; OutB.Canvas.Brush.Color := BackgroundColor; OutB.Canvas.Fillrect(Rect(0, 0, W, H)); end; procedure SpStretchDraw(G: TGraphic; OutBitmap: TBitmap; DestR: TRect; UseSubsampling: Boolean); // Canvas.StretchDraw is NOT THREADSAFE!!! // Use StretchBlt instead, we have to use a worker bitmap to do so var Work: TBitmap; begin Work := TBitmap.Create; Work.Canvas.Lock; try // Paint the Picture in Work if (G is TJpegImage) or (G is TBitmap) then Work.Assign(G) //assign works in this case else begin Work.Width := G.Width; Work.Height := G.Height; Work.Canvas.Draw(0, 0, G); end; if UseSubsampling then SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_HALFTONE) else SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_DELETESCANS); StretchBlt(OutBitmap.Canvas.Handle, DestR.Left, DestR.Top, DestR.Right - DestR.Left, DestR.Bottom - DestR.Top, Work.Canvas.Handle, 0, 0, G.Width, G.Height, SRCCopy); finally Work.Canvas.Unlock; Work.Free; end; end; procedure DrawThumbBorder(ACanvas: TCanvas; ThumbBorder: TThumbnailBorder; R: TRect; Selected: Boolean); const Edge: array [TThumbnailBorder] of Cardinal = (0, BDR_RAISEDINNER, EDGE_RAISED, BDR_SUNKENOUTER, EDGE_SUNKEN, EDGE_BUMP, EDGE_ETCHED, 0, 0, 0); begin if ThumbBorder <> tbNone then begin Case ThumbBorder of tbNone: ; tbFramed: begin ACanvas.Brush.Color := clBtnFace; ACanvas.FrameRect(R); end; tbWindowed: if Selected then begin ACanvas.Brush.Color := clHighlight; InflateRect(R, -2, -2); ACanvas.FrameRect(R); InflateRect(R, -1, -1); ACanvas.FrameRect(R); end else begin ACanvas.Brush.Color := clBtnFace; InflateRect(R, -2, -2); ACanvas.FrameRect(R); end; tbFit: if Selected then begin ACanvas.Brush.Color := clHighlight; ACanvas.FrameRect(R); InflateRect(R, -1, -1); ACanvas.FrameRect(R); ACanvas.Brush.Color := clWhite; InflateRect(R, -1, -1); ACanvas.FrameRect(R); end; else DrawEdge(ACanvas.Handle, R, Edge[ThumbBorder], BF_RECT); end; end; end; function IsIncompleteJPGError(E: Exception): boolean; var S: string; begin S := E.Message; Result := (S = 'JPEG error #68') or (S = 'JPEG error #67') or (S = 'JPEG error #60') or (S = 'JPEG error #57'); end; function IsDelphiSupportedImageFile(FileName: WideString): Boolean; var Ext: WideString; begin Ext := WideLowerCase(ExtractFileExtW(Filename)); Result := (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') or (Ext = '.bmp') or (Ext = '.wmf') or (Ext = '.emf') or (Ext = '.ico'); end; function GetGraphicClass(Filename: WideString): TGraphicClass; var Ext: WideString; begin Ext := WideLowerCase(ExtractFileExtW(Filename)); Delete(Ext, 1, 1); {$IFDEF USEGRAPHICEX} Result := GraphicEx.FileFormatList.GraphicFromExtension(Ext); {$ELSE} Result := nil; if (Ext = 'jpg') or (Ext = 'jpeg') or (Ext = 'jif') then Result := TJpegImage else if Ext = 'bmp' then Result := TBitmap else if (Ext = 'wmf') or (Ext = 'emf') then Result := TMetafile else if Ext = 'ico' then Result := TIcon; {$IFDEF USEIMAGEMAGICK} if Result = nil then Result := MagickImage.MagickFileFormatList.GraphicFromExtension(Ext); {$ENDIF} {$ENDIF} end; function LoadImageEnGraphic(Filename: WideString; outBitmap: TBitmap): Boolean; // Loads an image file with a unicode name using ImageEn graphic library {$IFDEF USEIMAGEEN} var B: TBitmap; ImageEnIO: TImageEnIO; F: TWideFileStream; {$ENDIF} begin Result := false; {$IFDEF USEIMAGEEN} ImageEnIO := TImageEnIO.Create(nil); try ImageEnIO.AttachedBitmap := outBitmap; F := TWideFileStream.Create(Filename, fmOpenRead or fmShareDenyNone); try ImageEnIO.LoadFromStream(F); Result := true; finally F.Free; end; finally ImageEnIO.Free; end; {$ENDIF} end; // Bug in Delphi 5: // When creating a bitmap by using its class type (TGraphicClass) it doesn't calls // the TBitmap constructor. // That's because in Delphi 5 the TGraphic.Create is protected, and TBitmap.Create // is public, so TGraphicClass(ABitmap).Create will NOT call TBitmap.Create because // it's not visible by TGraphicClass. // To fix this we need to make it visible by creating a TGraphicClass cracker. // More info on: // http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00000331.0164178b%40xmission.com type TFixedGraphic = class(TGraphic); TFixedGraphicClass = class of TFixedGraphic; function LoadGraphic(Filename: WideString; outP: TPicture): boolean; // Loads an image file with a unicode name var NewGraphic: TGraphic; GraphicClass: TGraphicClass; F: TWideFileStream; {$IFDEF USEIMAGEEN} B: TBitmap; {$ENDIF} begin Result := false; {$IFDEF USEIMAGEEN} B := TBitmap.Create; try Result := LoadImageEnGraphic(Filename, B); finally B.Free; end; {$ELSE} GraphicClass := GetGraphicClass(Filename); if GraphicClass = nil then outP.LoadFromFile(Filename) //try the default loader else begin F := TWideFileStream.Create(Filename, fmOpenRead or fmShareDenyNone); try NewGraphic := TFixedGraphicClass(GraphicClass).Create; try NewGraphic.LoadFromStream(F); outP.Graphic := NewGraphic; Result := true; finally NewGraphic.Free; end; finally F.Free; end; end; {$ENDIF} end; function LoadImage(Filename: WideString; OutP: TPicture): boolean; var J: TJpegImage; begin Result := false; if (Filename = '') or not Assigned(outP) then Exit; try LoadGraphic(Filename, OutP); if OutP.Graphic is TJpegImage then begin J := TJpegImage(OutP.Graphic); J.DIBNeeded; //load the JPG end; except on E:Exception do if not IsIncompleteJPGError(E) then raise; end; Result := true; end; function MakeThumbFromFile(Filename: WideString; OutBitmap: TBitmap; ThumbW, ThumbH: integer; Center: boolean; BgColor: TColor; Stretch, SubSampling: Boolean; var ImageWidth, ImageHeight: integer): Boolean; var P: TPicture; J: TJpegImage; WMFScale: Single; DestR: TRect; Ext: string; begin Result := false; if not Assigned(OutBitmap) then exit; Ext := Lowercase(ExtractFileExtW(Filename)); P := TPicture.create; try LoadGraphic(Filename, P); if P.Graphic <> nil then begin if (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') then begin // 5x faster loading jpegs, try to load just the minimum possible jpg // From Danny Thorpe: http://groups.google.com/groups?hl=en&frame=right&th=69a64eafb3ee2b12&seekm=01bdee71%24e5a5ded0%247e018f0a%40agamemnon#link6 try J := TJpegImage(P.graphic); J.Performance := jpBestSpeed; J.Scale := jsFullSize; while ((J.width > ThumbW) or (J.height > ThumbH)) and (J.Scale < jsEighth) do J.Scale := Succ(J.Scale); if J.Scale <> jsFullSize then J.Scale := Pred(J.Scale); J.DibNeeded; //now load the JPG except on E:Exception do if not IsIncompleteJPGError(E) then Raise; end; end else // We need to scale down the metafile images if (Ext = '.wmf') or (Ext = '.emf') then begin WMFScale := Min(1, Min(ThumbW/P.Graphic.Width, ThumbH/P.Graphic.Height)); P.Graphic.Width := Round(P.Graphic.Width * WMFScale); P.Graphic.Height := Round(P.Graphic.Height * WMFScale); end; ImageWidth := P.Graphic.Width; ImageHeight := P.Graphic.Height; // Resize the thumb // Need to lock/unlock the canvas here OutBitmap.Canvas.Lock; try // init OutBitmap DestR := RectAspectRatio(ImageWidth, ImageHeight, ThumbW, ThumbH, Center, Stretch); if Center then InitBitmap(OutBitmap, ThumbW, ThumbH, BgColor) else InitBitmap(OutBitmap, DestR.Right, DestR.Bottom, BgColor); // StretchDraw is NOT THREADSAFE!!! Use SpStretchDraw instead SpStretchDraw(P.Graphic, OutBitmap, DestR, Subsampling); Result := True; finally OutBitmap.Canvas.UnLock; end; end; finally P.free; end; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { Stream helpers } function ReadDateTimeFromStream(ST: TStream): TDateTime; begin ST.ReadBuffer(Result, SizeOf(Result)); end; procedure WriteDateTimeToStream(ST: TStream; D: TDateTime); begin ST.WriteBuffer(D, SizeOf(D)); end; function ReadIntegerFromStream(ST: TStream): Integer; begin ST.ReadBuffer(Result, SizeOf(Result)); end; procedure WriteIntegerToStream(ST: TStream; I: Integer); begin ST.WriteBuffer(I, SizeOf(I)); end; function ReadWideStringFromStream(ST: TStream): WideString; var L: integer; WS: WideString; begin Result := ''; ST.ReadBuffer(L, SizeOf(L)); SetLength(WS, L); ST.ReadBuffer(PWideChar(WS)^, 2 * L); Result := WS; end; procedure WriteWideStringToStream(ST: TStream; WS: WideString); var L: integer; begin L := Length(WS); ST.WriteBuffer(L, SizeOf(L)); ST.WriteBuffer(PWideChar(WS)^, 2 * L); end; function ReadMemoryStreamFromStream(ST: TStream; MS: TMemoryStream): Boolean; var L: integer; begin Result := false; ST.ReadBuffer(L, SizeOf(L)); if L > 0 then begin MS.Size := L; ST.ReadBuffer(MS.Memory^, L); Result := true; end; end; procedure WriteMemoryStreamToStream(ST: TStream; MS: TMemoryStream); var L: integer; begin L := MS.Size; ST.WriteBuffer(L, SizeOf(L)); ST.WriteBuffer(MS.Memory^, L); end; function ReadBitmapFromStream(ST: TStream; B: TBitmap): Boolean; var MS: TMemoryStream; begin Result := false; MS := TMemoryStream.Create; try if ReadMemoryStreamFromStream(ST, MS) then if Assigned(B) then begin B.LoadFromStream(MS); Result := true; end; finally MS.Free; end; end; procedure WriteBitmapToStream(ST: TStream; B: TBitmap); var L: integer; MS: TMemoryStream; begin if Assigned(B) then begin MS := TMemoryStream.Create; try B.SaveToStream(MS); WriteMemoryStreamToStream(ST, MS); finally MS.Free; end; end else begin L := 0; ST.WriteBuffer(L, SizeOf(L)); end; end; procedure ConvertBitmapStreamToJPGStream(MS: TMemoryStream; CompressionQuality: TJPEGQualityRange); var B: TBitmap; J: TJPEGImage; begin B := TBitmap.Create; J := TJPEGImage.Create; try MS.Position := 0; B.LoadFromStream(MS); //WARNING, first set the JPEG options J.CompressionQuality := CompressionQuality; //90 is the default, 60 is the best setting //Now assign the Bitmap J.Assign(B); J.Compress; MS.Clear; J.SaveToStream(MS); MS.Position := 0; finally B.Free; J.Free; end; end; procedure ConvertJPGStreamToBitmapStream(MS: TMemoryStream); var B: TBitmap; J: TJPEGImage; begin B := TBitmap.Create; J := TJPEGImage.Create; try MS.Position := 0; J.LoadFromStream(MS); B.Assign(J); MS.Clear; B.SaveToStream(MS); MS.Position := 0; finally B.Free; J.Free; end; end; procedure ConvertJPGStreamToBitmap(MS: TMemoryStream; OutBitmap: TBitmap); var B: TMemoryStream; begin B := TMemoryStream.Create; try MS.Position := 0; B.LoadFromStream(MS); MS.Position := 0; ConvertJPGStreamToBitmapStream(B); OutBitmap.LoadFromStream(B); finally B.Free; end; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TExtensionsList } constructor TExtensionsList.Create; begin inherited; Sorted := True; end; function TExtensionsList.Add(const Extension: WideString; HighlightColor: TColor): Integer; begin Result := inherited Add(Extension); if Result > -1 then Colors[Result] := HighlightColor; end; function TExtensionsList.AddObject(const S: WideString; AObject: TObject): Integer; var Aux: WideString; begin Aux := WideLowerCase(S); //Add the '.' part of the extension if (Length(Aux) > 0) and (Aux[1] <> '.') then Aux := '.' + Aux; Result := inherited AddObject(Aux, AObject); end; function TExtensionsList.IndexOf(const S: WideString): Integer; var Aux: WideString; begin Aux := WideLowerCase(S); //Add the '.' part of the extension if (Length(Aux) > 0) and (Aux[1] <> '.') then Aux := '.' + Aux; Result := inherited IndexOf(Aux); end; function TExtensionsList.DeleteString(const S: WideString): Boolean; var I: integer; begin I := IndexOf(S); if I > -1 then begin Delete(I); Result := True; end else Result := False; end; function TExtensionsList.GetColors(Index: integer): TColor; begin if Assigned(Objects[Index]) then Result := TColor(Objects[Index]) else Result := clNone; end; procedure TExtensionsList.SetColors(Index: integer; const Value: TColor); begin Objects[Index] := Pointer(Value); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TBitmapHint } procedure TBitmapHint.ActivateHint(Rect: TRect; const AHint: string); begin FActivating := True; try inherited ActivateHint(Rect, AHint); finally FActivating := False; end; end; procedure TBitmapHint.ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer); begin //The AData parameter is a bitmap FHintBitmap := TBitmap(AData); Rect.Right := Rect.Left + FHintBitmap.Width - 2; Rect.Bottom := Rect.Top + FHintBitmap.Height - 2; inherited ActivateHintData(Rect, AHint, AData); end; procedure TBitmapHint.CMTextChanged(var Message: TMessage); begin Message.Result := 1; end; procedure TBitmapHint.Paint; begin Canvas.Draw(0, 0, FHintBitmap); end; procedure TBitmapHint.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin //Don't erase the background as this causes flickering Paint; Message.Result := 1; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TThumbsCache } constructor TThumbsCache.Create; begin FHeaderFilelist := TWideStringList.Create; FHeaderFilelist.OwnsObjects := true; FScreenBuffer := TWideStringList.Create; FScreenBuffer.OwnsObjects := true; FScreenBuffer.Sorted := true; FComments := TWideStringList.Create; Clear; end; destructor TThumbsCache.Destroy; begin Clear; FHeaderFilelist.Free; FScreenBuffer.Free; FComments.Free; inherited; end; procedure TThumbsCache.Clear; begin FHeaderFilelist.Clear; FScreenBuffer.Clear; FComments.Clear; FStreamVersion := DefaultStreamVersion; FLoadedFromFile := false; FDirectory := ''; FSize := 0; FInvalidCount := 0; FThumbWidth := 0; FThumbHeight := 0; end; function TThumbsCache.IndexOf(Filename: WideString): Integer; begin Result := FHeaderFilelist.IndexOf(Filename); end; function TThumbsCache.Add(Filename: WideString; CI: TThumbsCacheItem): Integer; begin Result := FHeaderFilelist.AddObject(Filename, CI); if Result > -1 then FSize := FSize + CI.ThumbImageStream.Size; end; function TThumbsCache.Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer; ACompressIt: Boolean; AThumbImage: TBitmap): Integer; var CI: TThumbsCacheItem; begin Result := -1; CI := TThumbsCacheItem.Create(Filename); try CI.WriteBitmap(AThumbImage, ACompressIt); CI.Fill(AFileDateTime, AExif, AComment, AImageWidth, AImageHeight, ACompressIt, nil); Result := Add(Filename, CI); except CI.Free; end; end; function TThumbsCache.Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer; ACompressed: Boolean; AThumbImageStream: TMemoryStream): Integer; var CI: TThumbsCacheItem; begin Result := -1; CI := TThumbsCacheItem.Create(Filename); try CI.Fill(AFileDateTime, AExif, AComment, AImageWidth, AImageHeight, ACompressed, AThumbImageStream); Result := Add(Filename, CI); except CI.Free; end; end; function TThumbsCache.Delete(Filename: WideString): Boolean; var I, J: integer; M: TMemoryStream; begin I := IndexOf(Filename); Result := I > -1; if Result then begin M := TThumbsCacheItem(FHeaderFilelist.Objects[I]).ThumbImageStream; FSize := FSize - M.Size; // Don't delete it from the HeaderFilelist, instead free the ThumbsCacheItem and clear the string TThumbsCacheItem(FHeaderFilelist.Objects[I]).Free; FHeaderFilelist.Objects[I] := nil; FHeaderFilelist[I] := ''; Inc(FInvalidCount); // Delete the ScreenBuffer item J := FScreenBuffer.IndexOf(Filename); if J > -1 then FScreenBuffer.Delete(J); Result := true; end; end; function TThumbsCache.Read(Index: integer; var OutCacheItem: TThumbsCacheItem): Boolean; begin if (Index > -1) and (Index < FHeaderFilelist.Count) then OutCacheItem := FHeaderFilelist.Objects[Index] as TThumbsCacheItem else OutCacheItem := nil; Result := Assigned(OutCacheItem); end; function TThumbsCache.Read(Index: integer; OutBitmap: TBitmap): Boolean; var CI: TThumbsCacheItem; I: integer; B: TBitmap; begin Result := false; if Read(Index, CI) and Assigned(CI.ThumbImageStream) and Assigned(FScreenBuffer) then begin // Retrieve the bitmap from the ScreenBuffer I := FScreenBuffer.IndexOf(CI.Filename); if I > -1 then begin OutBitmap.Assign(TBitmap(FScreenBuffer.Objects[I])); Result := true; end else begin CI.ReadBitmap(OutBitmap); // Add it to the ScreenBuffer B := TBitmap.Create; try B.Assign(OutBitmap); FScreenBuffer.AddObject(CI.Filename, B); // The ScreenBuffer owns the bitmaps except B.Free; end; // Set capacity to 50 while FScreenBuffer.Count > 50 do FScreenBuffer.Delete(0); // FIFO list Result := true; end; end; end; function TThumbsCache.DefaultStreamVersion: integer; begin // Version 11, has FileDateTime defined as TDateTime, uses TThumbsCacheItem.SaveToStream, // has per file compression // and stores ThumbWidth/ThumbHeight Result := 11; end; procedure TThumbsCache.LoadFromFile(const Filename: Widestring); var FileStream: TStream; CI: TThumbsCacheItem; I, FileCount: integer; begin Clear; FileStream := TWideFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try // Read the header FDirectory := ReadWideStringFromStream(FileStream); FileCount := ReadIntegerFromStream(FileStream); FStreamVersion := ReadIntegerFromStream(FileStream); FThumbWidth := ReadIntegerFromStream(FileStream); FThumbHeight := ReadIntegerFromStream(FileStream); if FStreamVersion = DefaultStreamVersion then begin // Read the file list for I := 0 to FileCount - 1 do begin CI := TThumbsCacheItem.CreateFromStream(FileStream); try if FileExistsW(CI.Filename) then Add(CI.Filename, CI) else begin // The file is not valid, don't add it CI.Free; end; except Inc(FInvalidCount); CI.Free; end; end; // Read the comments or extra options FComments.LoadFromStream(FileStream); FLoadedFromFile := true; end; finally FileStream.Free; end; end; procedure TThumbsCache.LoadFromFile(const Filename: Widestring; InvalidFiles: TWideStringList); var AuxThumbsCache: TThumbsCache; CI, CICopy: TThumbsCacheItem; I: integer; begin if not Assigned(InvalidFiles) or (InvalidFiles.Count = 0) then LoadFromFile(Filename) else begin // Tidy the list for I := 0 to InvalidFiles.Count - 1 do InvalidFiles[I] := WideLowerCase(InvalidFiles[I]); InvalidFiles.Sort; // Load a cache file and ATTACH only the streams that are NOT in InvalidFiles list AuxThumbsCache := TThumbsCache.Create; try AuxThumbsCache.LoadFromFile(Filename); for I := 0 to AuxThumbsCache.Count - 1 do begin if AuxThumbsCache.Read(I, CI) and (InvalidFiles.IndexOf(CI.Filename) < 0) then begin CICopy := TThumbsCacheItem.Create(CI.Filename); try CICopy.Assign(CI); Self.Add(CI.Filename, CICopy); except CICopy.Free; end; end; end; FLoadedFromFile := true; finally AuxThumbsCache.Free; end; end; end; procedure TThumbsCache.SaveToFile(const Filename: Widestring); var FileStream: TStream; CI: TThumbsCacheItem; I: integer; begin FileStream := TWideFileStream.Create(Filename, fmCreate); try // Write the header WriteWideStringToStream(FileStream, Directory); WriteIntegerToStream(FileStream, Count - InvalidCount); WriteIntegerToStream(FileStream, DefaultStreamVersion); WriteIntegerToStream(FileStream, FThumbWidth); WriteIntegerToStream(FileStream, FThumbHeight); // Write the file list FHeaderFilelist.Sort; for I := 0 to Count - 1 do if FHeaderFilelist[I] <> '' then begin Read(I, CI); CI.SaveToStream(FileStream); end; // Save comments or extra options FComments.SaveToStream(FileStream); finally FileStream.Free; end; end; procedure TThumbsCache.Assign(AThumbsCache: TThumbsCache); var I: integer; CI, CICopy: TThumbsCacheItem; begin if Assigned(AThumbsCache) then begin Clear; Directory := AThumbsCache.Directory; FLoadedFromFile := AThumbsCache.LoadedFromFile; FStreamVersion := AThumbsCache.StreamVersion; FThumbWidth := AThumbsCache.ThumbWidth; FThumbHeight := AThumbsCache.ThumbHeight; FComments.Assign(AThumbsCache.Comments); //Clone for I := 0 to AThumbsCache.Count - 1 do begin AThumbsCache.Read(I, CI); if CI.Filename <> '' then begin CICopy := TThumbsCacheItem.Create(CI.Filename); try CICopy.Assign(CI); Self.Add(CI.Filename, CICopy); except CICopy.Free; end; end; end; end; end; function TThumbsCache.GetCount: integer; begin Result := FHeaderFilelist.Count; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TCacheList } function PosRight(SubStr: WideChar; S: WideString): Integer; // Like Pos function but starting from the last char var I, L: integer; begin Result := -1; L := Length(S); if L > 0 then for I := L downto 1 do if S[I] = SubStr then begin Result := I; Break; end; end; function NameFromRight(L: TWideStringList; const Index: Integer): WideString; // Like TWideStringList.Names[] but starting from the last char var P: Integer; begin Result := L[Index]; P := PosRight('\', Result); if P > 0 then SetLength(Result, P) else Result := ''; end; function ValueFromIndexRight(L: TWideStringList; const Index: Integer): WideString; // Like TWideStringList.ValueFromIndex but starting from the last char var S: WideString; begin Result := ''; if Index > -1 then begin // get name S := NameFromRight(L, Index); // copy the result if S <> '' then Result := Copy(L[Index], Length(S) + 2, MaxInt); end; end; function IndexOfNameRight(L: TWideStringList; const Name: WideString): Integer; // Like TWideStringList.IndexOfName but starting from the last char var I: integer; S: WideString; begin Result := -1; for I := 0 to L.Count - 1 do begin S := NameFromRight(L, I); if S <> '' then if SpCompareText(S, Name) then begin Result := I; Break; end; end; end; function IndexOfValueRight(L: TWideStringList; const Value: WideString): Integer; // Like TWideStringList.IndexOfValue but starting from the last char var P: Integer; I: integer; begin Result := -1; for I := 0 to L.Count - 1 do begin P := PosRight('\', L[I]); if P > 0 then if SpCompareText(ValueFromIndexRight(L, I), Value) then begin Result := I; Break; end; end; end; constructor TCacheList.Create; begin inherited; FDefaultFilename := 'CacheList.txt'; FCentralFolder := ''; end; function TCacheList.GetCacheFileToSave(Dir: Widestring): WideString; var WCH: PWideChar; F, WS: WideString; I: integer; begin Result := ''; if FCentralFolder = '' then exit; Dir := IncludeTrailingBackslashW(Dir); I := IndexOfNameRight(Self, Dir); if I <> -1 then Result := FCentralFolder + ValueFromIndexRight(Self, I) else begin //find a unique file name to store the cache if IsDriveW(Dir) then WS := Dir[1] else begin // NameForParsingInFolder WS := ''; WCH := StrRScanW(PWideChar(StripTrailingBackslashW(Dir)), WideChar('\')); if Assigned(WCH) then begin WCH := WCH + 1; //get rid of the first '\' WS := WCH; end; // Delete all the '=' chars WCH := StrScanW(PWideChar(WS), WideChar('=')); if Assigned(WCH) then begin I := Length(WS) - Integer(StrLenW(WCH)); if I > 0 then Dec(I); SetLength(WS, I); if WS = '' then WS := '0'; end; end; F := WS + '.cache'; //find a unique file name I := -1; while IndexOfValueRight(Self, F) <> -1 do begin inc(I); F := WS + '.' + inttostr(I) + '.cache'; end; Add(Dir + '=' + F); Sort; Result := FCentralFolder + F; end; end; function TCacheList.GetCacheFileToLoad(Dir: Widestring): WideString; var I: integer; begin Result := ''; if FCentralFolder <> '' then begin I := IndexOfNameRight(Self, IncludeTrailingBackslashW(Dir)); if I <> -1 then Result := FCentralFolder + ValueFromIndexRight(Self, I); end; end; procedure TCacheList.LoadFromFile; begin if FileExistsW(FCentralFolder + DefaultFileName) then inherited LoadFromFile(FCentralFolder + DefaultFileName) else Clear; end; procedure TCacheList.SaveToFile; begin DeleteInvalidFiles; inherited SaveToFile(FCentralFolder + DefaultFileName); end; procedure TCacheList.DeleteAllFiles; var I: integer; F: WideString; begin if FCentralFolder = '' then Exit; // Delete all the cache files for I := 0 to Count - 1 do begin F := FCentralFolder + ValueFromIndexRight(Self, I); if (F <> '') and FileExistsW(F) then DeleteFileW(PWideChar(F)); end; // Delete the cache list file F := FCentralFolder + FDefaultFileName; if (F <> '') and FileExistsW(F) then DeleteFileW(PWideChar(F)); // Clear the cache list Clear; end; procedure TCacheList.DeleteInvalidFiles; var I: integer; F: WideString; begin if FCentralFolder = '' then Exit; // Delete the invalid cache files for I := Count - 1 downto 0 do begin // Delete the entry if the cache file doesn't exist F := FCentralFolder + ValueFromIndexRight(Self, I); if (F = '') or not FileExistsW(F) then Delete(I) else // Delete the cache file if the Dir doesn't exist if not DirExistsW(NameFromRight(Self, I)) then if (F <> '') and FileExistsW(F) then begin DeleteFileW(PWideChar(F)); Delete(I); end; end; end; procedure TCacheList.SetCentralFolder(const Value: WideString); begin if FCentralFolder <> Value then if Value = '' then FCentralFolder := '' else FCentralFolder := IncludeTrailingBackslashW(Value); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TThumbsCacheOptions } constructor TThumbsCacheOptions.Create(AOwner: TCustomVirtualExplorerListviewEx); begin FOwner := AOwner; FThumbsCache := TThumbsCache.Create; FCacheList := TCacheList.Create; FAutoLoad := False; FAutoSave := False; FCompressed := False; FDefaultFilename := 'Thumbnails.Cache'; FStorageType := tcsCentral; FCacheProcessing := tcpDescending; end; destructor TThumbsCacheOptions.Destroy; begin if AutoSave then Save; //Save the cache on exit FThumbsCache.Free; FCacheList.Free; inherited; end; procedure TThumbsCacheOptions.ClearCache(DeleteAllFiles: Boolean = False); var F: WideString; begin if Assigned(Owner.RootFolderNamespace) and SpCompareText(Owner.RootFolderNamespace.NameForParsing, BrowsingFolder) then begin if DeleteAllFiles then case FStorageType of tcsPerFolder: begin F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename; if (F <> '') and FileExistsW(F) then DeleteFileW(PWideChar(F)); end; tcsCentral: FCacheList.DeleteAllFiles; end; Owner.ResetThumbThread; //reset and reload the thread end; end; procedure TThumbsCacheOptions.Reload(Node: PVirtualNode); var TD: PThumbnailData; begin if Assigned(Node) and (vsInitialized in Node.States) then if Owner.ValidateThumbnail(Node, TD) and (TD.State = tsValid) then begin // Reset the TD TD.Reloading := True; TD.State := tsEmpty; // TD.CachePos := -1; don't reset the CachePos if Owner.ViewStyle = vsxThumbs then Owner.FListview.UpdateItems(Node.Index, Node.Index); // invalidate canvas end; end; procedure TThumbsCacheOptions.Reload(Filename: WideString); begin Reload(Owner.FindNode(Filename)); end; procedure TThumbsCacheOptions.Load(Force: boolean); var InvalidFiles: TWideStringList; N: PVirtualNode; NS: TNamespace; TD: PThumbnailData; F: WideString; begin F := ''; case FStorageType of tcsPerFolder: if FDefaultFilename <> '' then F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename; tcsCentral: F := FCacheList.GetCacheFileToLoad(FBrowsingFolder); end; if not Owner.DoThumbsCacheLoad(FThumbsCache, F, FThumbsCache.Comments) then FThumbsCache.FLoadedFromFile := True else if FileExistsW(F) then begin // Load only the bitmap streams that are not already loaded InvalidFiles := TWideStringList.Create; try // Iterate through the nodes and populate the InvalidFiles with the images filenames. if not Force then begin N := Owner.RootNode.FirstChild; while Assigned(N) do begin if (vsInitialized in N.States) and Owner.ValidateNamespace(N, NS) and Owner.ValidateThumbnail(N, TD) then if IsThumbnailActive(TD.State) then InvalidFiles.Add(WideLowerCase(NS.NameForParsing)); N := N.NextSibling; end; end; // Load only the bitmap streams that are not already loaded FThumbsCache.LoadFromFile(F, InvalidFiles); finally InvalidFiles.Free; end; end; end; procedure TThumbsCacheOptions.Save; var F: WideString; begin if (FThumbsCache.Count = 0) or not DirExistsW(FBrowsingFolder) then Exit; case FStorageType of tcsPerFolder: if FDefaultFilename <> '' then begin F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename; if Owner.DoThumbsCacheSave(FThumbsCache, F, FThumbsCache.Comments) then FThumbsCache.SaveToFile(F); end; tcsCentral: if CentralFolder <> '' then if DirExistsW(CentralFolder) or CreateDirW(CentralFolder) then begin F := FCacheList.GetCacheFileToSave(FBrowsingFolder); if F <> '' then begin if Owner.DoThumbsCacheSave(FThumbsCache, F, FThumbsCache.Comments) then FThumbsCache.SaveToFile(F); end; FCacheList.SaveToFile; end; end; end; function TThumbsCacheOptions.Read(Node: PVirtualNode; var OutCacheItem: TThumbsCacheItem): Boolean; var TD: PThumbnailData; begin Result := False; if Assigned(FOwner) and FOwner.ValidateThumbnail(Node, TD) then if (TD.State = tsValid) and (TD.CachePos > -1) then Result := FThumbsCache.Read(TD.CachePos, OutCacheItem); end; function TThumbsCacheOptions.Read(Filename: WideString; var OutCacheItem: TThumbsCacheItem): Boolean; var I: integer; begin Result := False; I := FThumbsCache.IndexOf(Filename); if I > -1 then Result := FThumbsCache.Read(I, OutCacheItem); end; function TThumbsCacheOptions.Read(Node: PVirtualNode; OutBitmap: TBitmap): Boolean; var TD: PThumbnailData; begin Result := False; if Assigned(FOwner) and FOwner.ValidateThumbnail(Node, TD) then if (TD.State = tsValid) and (TD.CachePos > -1) then Result := FThumbsCache.Read(TD.CachePos, OutBitmap); end; function TThumbsCacheOptions.Read(Filename: WideString; OutBitmap: TBitmap): Boolean; var I: integer; begin Result := False; I := FThumbsCache.IndexOf(Filename); if I > -1 then Result := FThumbsCache.Read(I, OutBitmap); end; procedure TThumbsCacheOptions.Assign(Source: TPersistent); begin if Source is TThumbsCacheOptions then begin AutoLoad := TThumbsCacheOptions(Source).AutoLoad; AutoSave := TThumbsCacheOptions(Source).AutoSave; DefaultFilename := TThumbsCacheOptions(Source).DefaultFilename; StorageType := TThumbsCacheOptions(Source).StorageType; CentralFolder := TThumbsCacheOptions(Source).CentralFolder; end else inherited; end; function TThumbsCacheOptions.GetCacheFileFromCentralFolder(Dir: WideString): WideString; begin // Gets the corresponding cache file from the central folder Result := FCacheList.GetCacheFileToLoad(Dir); end; function TThumbsCacheOptions.RenameCacheFileFromCentralFolder(Dir, NewDirName: WideString; NewCacheFilename: WideString = ''): Boolean; var I: integer; D, F, PrevF: WideString; NS: TNamespace; begin Result := False; if Dir <> '' then Dir := IncludeTrailingBackslashW(Dir); if NewDirName <> '' then NewDirName := IncludeTrailingBackslashW(NewDirName); I := IndexOfNameRight(FCacheList, Dir); if I > -1 then begin // Delete the entry PrevF := ValueFromIndexRight(FCacheList, I); FCacheList.Delete(I); // Rename the previous Dir entry for the new one if NewDirName <> '' then D := NewDirName else D := Dir; // Rename the previous Cache File for the new one if NewCacheFilename <> '' then begin F := NewCacheFilename; FCacheList.Add(D + '=' + F); end else F := ExtractFileNameW(FCacheList.GetCacheFileToSave(D)); // Update the BrowsingFolder property if SpCompareText(IncludeTrailingBackslashW(BrowsingFolder), Dir) then BrowsingFolder := D; // Rename the file if PrevF <> '' then begin NS := TNamespace.CreateFromFileName(FCacheList.CentralFolder + PrevF); try NS.SetNameOf(F); finally NS.Free; end; end; Result := True; end; end; function TThumbsCacheOptions.GetSize: integer; begin Result := FThumbsCache.Size; end; function TThumbsCacheOptions.GetThumbsCount: integer; begin Result := FThumbsCache.Count - FThumbsCache.InvalidCount; end; procedure TThumbsCacheOptions.SetBrowsingFolder(const Value: WideString); begin if FBrowsingFolder <> Value then begin FThumbsCache.Directory := Value; FBrowsingFolder := Value; end; end; procedure TThumbsCacheOptions.SetCacheProcessing(const Value: TThumbsCacheProcessing); begin if FCacheProcessing <> Value then begin FCacheProcessing := Value; end; end; function TThumbsCacheOptions.GetCentralFolder: WideString; begin Result := FCacheList.CentralFolder; end; procedure TThumbsCacheOptions.SetCentralFolder(const Value: WideString); begin if FCacheList.CentralFolder <> Value then begin FCacheList.CentralFolder := Value; FCacheList.LoadFromFile; end; end; procedure TThumbsCacheOptions.SetCompressed(const Value: boolean); begin if FCompressed <> Value then begin FCompressed := Value; ClearCache(False); end; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TThumbsOptions } constructor TThumbsOptions.Create(AOwner: TCustomVirtualExplorerListviewEx); begin FOwner := AOwner; FCacheOptions := TThumbsCacheOptions.Create(AOwner); FThumbsIconAtt.Size.X := 120; FThumbsIconAtt.Size.Y := 120; FThumbsIconAtt.Spacing.X := 40; FThumbsIconAtt.Spacing.Y := 40; FBorder := tbFramed; FBorderSize := 4; FDetailsHeight := 40; FHighlight := thMultipleColors; FHighlightColor := $EFD3D3; FShowSmallIcon := True; FShowXLIcons := True; FUseShellExtraction := True; FUseSubSampling := True; end; destructor TThumbsOptions.Destroy; begin FCacheOptions.Free; inherited; end; function TThumbsOptions.GetWidth: Integer; begin Result := FThumbsIconAtt.Size.X; end; function TThumbsOptions.GetHeight: Integer; begin Result := FThumbsIconAtt.Size.Y; end; function TThumbsOptions.GetSpaceWidth: Word; begin Result := FThumbsIconAtt.Spacing.X; end; function TThumbsOptions.GetSpaceHeight: Word; begin Result := FThumbsIconAtt.Spacing.Y; end; procedure TThumbsOptions.SetBorder(const Value: TThumbnailBorder); begin if FBorder <> Value then begin FBorder := Value; if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate; end; end; procedure TThumbsOptions.SetBorderSize(const Value: Integer); begin if FBorderSize <> Value then begin FBorderSize := Value; if FBorderSize < 0 then FBorderSize := 0; Owner.ResetThumbImageList; end; end; procedure TThumbsOptions.SetBorderOnFiles(const Value: Boolean); begin if FBorderOnFiles <> Value then begin FBorderOnFiles := Value; if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate; end; end; function TThumbsOptions.GetDetailedHints: Boolean; begin Result := Owner.FListview.DetailedHints; end; procedure TThumbsOptions.SetDetailedHints(const Value: Boolean); begin Owner.FListview.DetailedHints := Value; end; procedure TThumbsOptions.SetDetails(const Value: Boolean); begin if FDetails <> Value then begin FDetails := Value; Owner.ResetThumbImageList; end; end; procedure TThumbsOptions.SetDetailsHeight(const Value: Integer); begin if FDetailsHeight <> Value then begin FDetailsHeight := Value; Owner.ResetThumbImageList; end; end; procedure TThumbsOptions.SetWidth(const Value: Integer); begin if Value <> FThumbsIconAtt.Size.X then begin FThumbsIconAtt.Size.X := Value; Owner.ResetThumbImageList; Owner.ResetThumbThread; //reset and reload the thread Owner.ChildListview.UpdateSingleLineMaxChars; end; end; procedure TThumbsOptions.SetHeight(const Value: Integer); begin if Value <> FThumbsIconAtt.Size.Y then begin FThumbsIconAtt.Size.Y := Value; Owner.ResetThumbImageList; Owner.ResetThumbThread; //reset and reload the thread end; end; procedure TThumbsOptions.SetSpaceWidth(const Value: Word); begin if Value <> FThumbsIconAtt.Spacing.X then begin FThumbsIconAtt.Spacing.X := Value; if Owner.ViewStyle = vsxThumbs then begin Owner.ResetThumbSpacing; Owner.SyncInvalidate; end; end; end; procedure TThumbsOptions.SetSpaceHeight(const Value: Word); begin if Value <> FThumbsIconAtt.Spacing.Y then begin FThumbsIconAtt.Spacing.Y := Value; if Owner.ViewStyle = vsxThumbs then begin Owner.ResetThumbSpacing; Owner.SyncInvalidate; end; end; end; function TThumbsOptions.GetHideCaptions: Boolean; begin Result := Owner.ChildListview.HideCaptions; end; procedure TThumbsOptions.SetHideCaptions(const Value: Boolean); begin Owner.ChildListview.HideCaptions := Value; end; function TThumbsOptions.GetSingleLineCaptions: Boolean; begin Result := Owner.ChildListview.SingleLineCaptions; end; procedure TThumbsOptions.SetSingleLineCaptions(const Value: Boolean); begin Owner.ChildListview.SingleLineCaptions := Value; end; procedure TThumbsOptions.SetHighlight(const Value: TThumbnailHighlight); begin if FHighlight <> Value then begin FHighlight := Value; Owner.SyncInvalidate; end; end; procedure TThumbsOptions.SetHighlightColor(const Value: TColor); begin if FHighlightColor <> Value then begin FHighlightColor := Value; if FHighlight = thSingleColor then Owner.SyncInvalidate; end; end; procedure TThumbsOptions.SetUseShellExtraction(const Value: Boolean); begin if FUseShellExtraction <> Value then begin FUseShellExtraction := Value; end; end; procedure TThumbsOptions.SetShowSmallIcon(const Value: Boolean); begin if FShowSmallIcon <> Value then begin FShowSmallIcon := Value; if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate; end; end; procedure TThumbsOptions.SetShowXLIcons(const Value: Boolean); begin if FShowXLIcons <> Value then begin FShowXLIcons := Value; if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate; end; end; procedure TThumbsOptions.SetStretch(const Value: Boolean); begin if FStretch <> Value then begin FStretch := Value; Owner.ResetThumbThread; //reset and reload the thread end; end; procedure TThumbsOptions.SetUseSubsampling(const Value: Boolean); begin if FUseSubsampling <> Value then begin FUseSubsampling := Value; Owner.ResetThumbThread; end; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TThumbThread } constructor TThumbThread.Create(AOwner: TCustomVirtualExplorerListviewEx); begin inherited Create(False); FOwner := AOwner; {$IFDEF DELPHI_7_UP} Priority := tpIdle; {$ENDIF} ResetThumbOptions; end; procedure TThumbThread.ExtractedInfoLoad(Info: PVirtualThreadIconInfo); begin inherited; // Use the UserData2 Pointer to pass the PThumbnailData to the Control(s) GetMem(Info.UserData2, SizeOf(TThumbnailThreadData)); FillChar(Info.UserData2^, SizeOf(TThumbnailThreadData), #0); //Clone the FThumbThreadData with PThumbnailThreadData(Info.UserData2)^ do begin ImageWidth := FThumbThreadData.ImageWidth; ImageHeight := FThumbThreadData.ImageHeight; CompressedStream := FThumbThreadData.CompressedStream; State := FThumbThreadData.State; if Assigned(FThumbThreadData.MemStream) then begin MemStream := TMemoryStream.Create; MemStream.LoadFromStream(FThumbThreadData.MemStream); end; end; //Clear the FThumbThreadData FreeAndNil(FThumbThreadData.MemStream); FillChar(FThumbThreadData, SizeOf(FThumbThreadData), #0); end; function TThumbThread.CreateThumbnail(Filename: WideString; var Thumbnail: TBitmap; var ImageWidth, ImageHeight: integer; var CompressIt: boolean): Boolean; {$IFDEF USEIMAGEEN} var B: TBitmap; DestR: TRect; {$ENDIF} begin CompressIt := false; Result := False; try {$IFDEF USEIMAGEEN} if IsDelphiSupportedImageFile(Filename) then //common image, do default Result := MakeThumbFromFile(Filename, Thumbnail, FThumbWidth, FThumbHeight, false, FTransparentColor, FThumbStretch, FThumbSubsampling, ImageWidth, ImageHeight) else begin B := TBitmap.Create; try if LoadImageEnGraphic(Filename, B) then begin ImageWidth := B.Width; ImageHeight := B.Height; DestR := RectAspectRatio(ImageWidth, ImageHeight, FThumbWidth, FThumbHeight, false, FThumbStretch); InitBitmap(Thumbnail, DestR.Right, DestR.Bottom, FTransparentColor); // StretchDraw is NOT THREADSAFE!!! Use SpStretchDraw instead SpStretchDraw(B, Thumbnail, DestR, true); Result := true; end; finally B.Free; end; end; {$ELSE} Result := MakeThumbFromFile(Filename, Thumbnail, FThumbWidth, FThumbHeight, false, FTransparentColor, FThumbStretch, FThumbSubsampling, ImageWidth, ImageHeight); {$ENDIF} except //don't raise any image errors, just ignore them, the state will be tsInvalid FThumbThreadData.State := tsInvalid; end; CompressIt := Result and (ImageWidth > 200) and (ImageHeight > 200); end; procedure TThumbThread.ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo); var Folder, Desktop: IShellFolder; OldCB: Word; OldPIDL: PItemIDList; B: TBitmap; AllsOk: Boolean; function ExtractImageFromPIDL(OutBitmap: TBitmap): Boolean; var StrRet: TSTRRET; WS, Ext: WideString; ExtractImage: IExtractImage; Buffer: array[0..MAX_PATH] of WideChar; Priority, Flags: Longword; Size: TSize; Bits: HBitmap; ByShellExtract: Boolean; begin Result := False; if Succeeded(Folder.GetDisplayNameOf(OldPIDL, SHGDN_FORADDRESSBAR or SHGDN_FORPARSING, StrRet)) then begin WS := StrRetToStr(StrRet, OldPIDL); Ext := WideLowerCase(ExtractFileExtW(WS)); // ByShellExtract is hardcoded to LargeIcon, take a look at TSyncListView.OwnerDataHint ByShellExtract := Info.LargeIcon; if not ByShellExtract then Result := CreateThumbnail(WS, OutBitmap, FThumbThreadData.ImageWidth, FThumbThreadData.ImageHeight, FThumbThreadData.CompressedStream) else // Load it with the Shell IExtract Interface // If ThumbsOptions.UseShellExtract = False and the file extension is in // ShellExtractExtensionsList then ByShellExtract will be True. // Suppose you want just images + html files, then you should turn off // UseShellExtract and add '.html' to the ShellExtractExtensionsList. if Succeeded(Folder.GetUIObjectOf(0, 1, OldPIDL, IID_IExtractImage, nil, ExtractImage)) then begin Priority := IEI_PRIORITY_NORMAL; Flags := IEIFLAG_ASPECT or IEIFLAG_OFFLINE; Size.cx := ThumbWidth; Size.cy := ThumbHeight; if Succeeded(ExtractImage.GetLocation(Buffer, SizeOf(Buffer), Priority, Size, 32, Flags)) and Succeeded(ExtractImage.Extract(Bits)) and (Bits <> 0) then begin OutBitmap.Handle := Bits; Result := True; end; end; end; end; begin StripLastID(PIDL, OldCB, OldPIDL); try SHGetDesktopFolder(Desktop); {JIM // Special case for the desktop children, plus memory leak fix} if PIDL <> OldPIDL then AllsOk := Succeeded(Desktop.BindToObject(PIDL, nil, IID_IShellFolder, Folder)) else begin Folder := Desktop; AllsOk := Assigned(Folder) end; if AllsOk then begin OldPIDL.mkid.cb := OldCB; FThumbThreadData.ImageWidth := 0; FThumbThreadData.ImageHeight := 0; FThumbThreadData.CompressedStream := false; FThumbThreadData.State := tsInvalid; FThumbThreadData.MemStream := nil; B := TBitmap.Create; try B.Canvas.Lock; if ExtractImageFromPIDL(B) then begin FThumbThreadData.MemStream := TMemoryStream.Create; try B.SaveToStream(FThumbThreadData.MemStream); FThumbThreadData.CompressedStream := FThumbCompression and FThumbThreadData.CompressedStream; if FThumbThreadData.CompressedStream then //JPEG compressed ConvertBitmapStreamToJPGStream(FThumbThreadData.MemStream, 60); FThumbThreadData.State := tsValid; except FreeAndNil(FThumbThreadData.MemStream); end; end; finally B.Canvas.Unlock; FreeAndNil(B); end; end; finally if Assigned(OldPIDL) then OldPIDL.mkid.cb := OldCB end end; procedure TThumbThread.InvalidateExtraction; begin inherited; if Assigned(FThumbThreadData.MemStream) then begin FreeAndNil(FThumbThreadData.MemStream); FillChar(FThumbThreadData, SizeOf(FThumbThreadData), #0) end end; procedure TThumbThread.ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); begin if Assigned(Item) then begin // Will only be valid if the image has been extracted already if Assigned(PThumbnailThreadData(Item.UserData2)) then begin FreeAndNil(PThumbnailThreadData(Item.UserData2).MemStream); FreeMem(PThumbnailThreadData(Item.UserData2)); end; end; inherited; end; procedure TThumbThread.ResetThumbOptions; begin QueryList.LockList; try FThumbWidth := FOwner.ThumbsOptions.Width; FThumbHeight := FOwner.ThumbsOptions.Height; FThumbStretch := FOwner.ThumbsOptions.Stretch; FThumbSubsampling := FOwner.ThumbsOptions.UseSubsampling; FThumbCompression := FOwner.ThumbsOptions.CacheOptions.Compressed; FTransparentColor := FOwner.Color; finally QueryList.UnlockList; end; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TUnicodeOwnerDataListView } constructor TUnicodeOwnerDataListView.Create(AOwner: TComponent); begin inherited; FEditingItemIndex := -1; OwnerData := true; Win32PlatformIsUnicode := (Win32Platform = VER_PLATFORM_WIN32_NT); FIsComCtl6 := GetComCtlVersion >= $00060000; end; procedure TUnicodeOwnerDataListView.CreateWnd; begin inherited; // Enables alpha blended selection if ComCtrl 6 is used // Unfortunately the flicker is unbearable // if IsComCtl6 then // ListView_SetExtendedListViewStyle(Handle, LVS_EX_DOUBLEBUFFER); end; procedure TUnicodeOwnerDataListView.CreateWindowHandle(const Params: TCreateParams); var Column: TLVColumn; begin // Do not call inherited, we need to create the unicode handle CreateUnicodeHandle(Self, Params, WC_LISTVIEW); if (Win32PlatformIsUnicode) then begin ListView_SetUnicodeFormat(Handle, True); // the only way I could get editing to work is after a column had been inserted Column.mask := 0; ListView_InsertColumn(Handle, 0, Column); ListView_DeleteColumn(Handle, 0); end; end; procedure TUnicodeOwnerDataListView.WndProc(var Msg: TMessage); var Item: TListitem; P: TPoint; R: TRect; SimulateClick: Boolean; begin // OwnerData TListview bug on WinXP using ComCtl 6: the white space between // icons (vsxIcon or vsxThumbs) becomes selectable, but not the space between // the captions. SimulateClick := False; Case Msg.Msg of WM_LBUTTONDOWN..WM_MBUTTONDBLCLK: if HideCaptions or FIsComCtl6 then begin P := Point(Msg.LParamLo, Msg.LParamHi); Item := GetItemAt(P.X, P.Y); if Assigned(Item) then begin // Disallow the click on the caption if HideCaption is true if HideCaptions then begin R := GetLVItemRect(Item.Index, drLabel); if PtInRect(R, P) then SimulateClick := True; end else // Disallow the click on the left and right side of the Icon when using ComCtrl 6 if FIsComCtl6 then begin R := GetLVItemRect(Item.Index, drBounds); if not PtInRect(R, P) then begin Selected := nil; SimulateClick := True; end; end; end; end; end; if SimulateClick then begin Case Msg.Msg of WM_LBUTTONDOWN: MouseDown(mbLeft, [], P.X, P.Y); WM_LBUTTONUP: MouseUp(mbLeft, [], P.X, P.Y); WM_MBUTTONDOWN: MouseDown(mbMiddle, [], P.X, P.Y); WM_MBUTTONUP: MouseUp(mbMiddle, [], P.X, P.Y); WM_RBUTTONDOWN: MouseDown(mbRight, [], P.X, P.Y); WM_RBUTTONUP: begin MouseUp(mbRight, [], P.X, P.Y); DoContextPopup(P, SimulateClick); end; end; end else inherited; end; procedure TUnicodeOwnerDataListView.CMDenySubclassing(var Message: TMessage); begin // Prevent Theme Manager subclassing // If a Windows XP Theme Manager component is used in the application it will // try to subclass all controls which do not explicitly deny this. Message.Result := 1; end; procedure TUnicodeOwnerDataListView.CMFontchanged(var Message: TMessage); begin inherited; UpdateSingleLineMaxChars; end; procedure TUnicodeOwnerDataListView.CNNotify(var Message: TWMNotify); var Item: TListItem; S: string; LVEditHandle: THandle; begin if (not Win32PlatformIsUnicode) then inherited else begin with Message do begin Case NMHdr^.code of HDN_TRACKW: begin NMHdr^.code := HDN_TRACKA; try inherited; finally NMHdr^.code := HDN_TRACKW; end; end; LVN_GETDISPINFOW: begin // call inherited without the LVIF_TEXT flag CurrentDispInfo := PLVDispInfoW(NMHdr); try OriginalDispInfoMask := PLVDispInfoW(NMHdr)^.item.mask; PLVDispInfoW(NMHdr)^.item.mask := PLVDispInfoW(NMHdr)^.item.mask and (not LVIF_TEXT); try NMHdr^.code := LVN_GETDISPINFOA; try inherited; finally NMHdr^.code := LVN_GETDISPINFOW; end; finally PLVDispInfoW(NMHdr)^.item.mask := OriginalDispInfoMask; end; finally CurrentDispInfo := nil; end; // handle any text info with PLVDispInfoW(NMHdr)^.item do if ((mask and LVIF_TEXT) <> 0) and (iSubItem = 0) then if HideCaptions and (FEditingItemIndex <> iItem) then pszText[0] := #0 else StrLCopyW(pszText, PWideChar(GetItemCaption(iItem)), cchTextMax - 1); end; LVN_ODFINDITEMW: with PNMLVFindItem(NMHdr)^ do begin if ((lvfi.flags and LVFI_PARTIAL) <> 0) or ((lvfi.flags and LVFI_STRING) <> 0) then PWideFindString := TLVFindInfoW(lvfi).psz else PWideFindString := nil; lvfi.psz := nil; NMHdr^.code := LVN_ODFINDITEMA; try inherited; {will result in call to OwnerDataFind} finally TLVFindInfoW(lvfi).psz := PWideFindString; NMHdr^.code := LVN_ODFINDITEMW; PWideFindString := nil; end; end; LVN_BEGINLABELEDITW: begin Item := GetItem(PLVDispInfoW(NMHdr)^.item); if not CanEdit(Item) then Result := 1; end; LVN_ENDLABELEDITW: with PLVDispInfoW(NMHdr)^ do if (item.pszText <> nil) and (item.IItem <> -1) then Edit(TLVItemA(item)); LVN_GETINFOTIPW: begin NMHdr^.code := LVN_GETINFOTIPA; try inherited; finally NMHdr^.code := LVN_GETINFOTIPW; end; end; else inherited; end; end; end; // Handle the edit control: // The Edit control is not showed correctly when the font size // is large (Height > 15), this is visible in vsReport, vsList and vsSmallIcon // viewstyles. We must reshow the Edit control. Case Message.NMHdr^.code of LVN_GETDISPINFO: // handle HideCaptions for Ansi text if not Win32PlatformIsUnicode and HideCaptions then with PLVDispInfoA(Message.NMHdr)^.item do if ((mask and LVIF_TEXT) <> 0) and (iSubItem = 0) and (FEditingItemIndex = iItem) then pszText[0] := #0; LVN_BEGINLABELEDIT, LVN_BEGINLABELEDITW: if Message.Result = 0 then begin LVEditHandle := ListView_GetEditControl(Handle); if LVEditHandle <> 0 then begin SetWindowPos(LVEditHandle, 0, 0, 0, 500, 200, SWP_SHOWWINDOW + SWP_NOMOVE); if Win32PlatformIsUnicode then begin FEditingItemIndex := PLVDispInfoW(Message.NMHdr)^.item.iItem; if HideCaptions or SingleLineCaptions then SendMessageW(LVEditHandle, WM_SETTEXT, 0, Longint(PWideChar(GetItemCaption(FEditingItemIndex)))); end else begin FEditingItemIndex := PLVDispInfoA(Message.NMHdr)^.item.iItem; if HideCaptions then begin S := GetItemCaption(FEditingItemIndex); SendMessageA(LVEditHandle, WM_SETTEXT, 0, Longint(PAnsiChar(S))); end; end; end; end; LVN_ENDLABELEDIT, LVN_ENDLABELEDITW: FEditingItemIndex := -1; end; end; procedure TUnicodeOwnerDataListView.WMCtlColorEdit(var Message: TWMCtlColorEdit); begin Message.Result := DefWindowProc(Handle, Message.Msg, Message.ChildDC, Message.ChildWnd); end; procedure TUnicodeOwnerDataListView.WMWindowPosChanging(var Message: TWMWindowPosChanging); begin inherited; // Bug in ComCtrl 6 in WinXP, does not redraw on resize if FIsComCtl6 then InvalidateRect(Handle, nil, False); end; function TUnicodeOwnerDataListView.GetItem(Value: TLVItemW): TListItem; begin Result := Items[Value.iItem]; end; procedure TUnicodeOwnerDataListView.SetHideCaptions(const Value: Boolean); begin if Value <> FHideCaptions then begin FHideCaptions := Value; Invalidate; end; end; procedure TUnicodeOwnerDataListView.SetSingleLineCaptions(const Value: Boolean); begin if Value <> FSingleLineCaptions then begin FSingleLineCaptions := Value; IconOptions.WrapText := not Value; end; end; function TUnicodeOwnerDataListView.GetFilmstripHeight: Integer; var Size: TSize; I: Integer; begin Result := 0; if Assigned(LargeImages) then begin I := GetSystemMetrics(SM_CYHSCROLL); if not HideCaptions then begin Size := VirtualWideStrings.TextExtentW('W', Font); if SingleLineCaptions then I := I + (Size.cy * 2) else I := I + (Size.cy * 4); end; Result := LargeImages.Height + I + 10; end; end; function TUnicodeOwnerDataListView.GetLVItemRect(Index: Integer; DisplayCode: TDisplayCode): TRect; var RealWidthHalf: integer; Half: integer; const IconSizePlus = 16; Codes: array[TDisplayCode] of Longint = (LVIR_BOUNDS, LVIR_ICON, LVIR_LABEL, LVIR_SELECTBOUNDS); begin ListView_GetItemRect(Handle, Index, Result, Codes[DisplayCode]); if FIsComCtl6 and (DisplayCode <> drLabel) and (ViewStyle = vsIcon) and Assigned(LargeImages) then begin // Another WinXP painting issue... // Item.displayrect() returns a bigger TRect // We need to adjust it here RealWidthHalf := (LargeImages.Width + IconSizePlus) div 2; Half := (Result.Right - Result.Left) div 2 + Result.Left; Result.Left := Half - RealWidthHalf; Result.Right := Half + RealWidthHalf; end; end; procedure TUnicodeOwnerDataListView.UpdateSingleLineMaxChars; var Size: TSize; begin if Assigned(LargeImages) then begin Size := VirtualWideStrings.TextExtentW('-', Font); if Size.cx <= 0 then Size.cx := 2; FSingleLineMaxChars := (LargeImages.Width div Size.cx) - 2; end else FSingleLineMaxChars := 0; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TSyncListView } constructor TSyncListView.Create(AOwner: TComponent); begin inherited; FDefaultTooltipsHandle := 0; Visible := false; ControlStyle := ControlStyle + [csNoDesignVisible]; HideSelection := false; IconOptions.AutoArrange := true; FFirstShiftClicked := -1; FThumbnailHintBitmap := TBitmap.Create; end; destructor TSyncListView.Destroy; begin FThumbnailHintBitmap.Free; inherited; end; procedure TSyncListView.CreateHandle; var H: THandle; begin inherited; H := ListView_GetToolTips(Handle); if H <> 0 then FDefaultTooltipsHandle := H; UpdateHintHandle; // Boris: When the handle is recreated the icon spacing is not updated if (HandleAllocated) and (VETController.ViewStyle = vsxThumbs) then VETController.ResetThumbSpacing; end; function TSyncListView.IsItemGhosted(Item: TListitem): Boolean; var Node: PVirtualNode; begin Result := false; if Assigned(Item) then if Item.Cut then Result := true //Hidden file else begin Node := PVirtualNode(Item.Data); if Assigned(Node) and (vsCutOrCopy in Node.States) then Result := true; //Marked as Cut or Copy end; end; procedure TSyncListView.FetchThumbs(StartIndex, EndIndex: integer); begin //Fire the thread to create ALL the thumbnails at once if (Items.Count > 0) and (StartIndex > -1) and (StartIndex < Items.Count) and (EndIndex > -1) and (EndIndex < Items.Count) then OwnerDataHint(StartIndex, EndIndex); end; procedure TSyncListView.UpdateArrangement; var i, Max, Temp: integer; begin if Visible then begin //Update column size if (ViewStyle in [vsSmallIcon, vsList]) and (Items.Count > 0) then begin Max := 0; for i := 0 to Items.Count - 1 do begin Temp := TextExtentW(Items[I].Caption, Canvas).cx; if Temp > Max then Max := Temp; end; ListView_SetColumnWidth(Handle, 0, Max + SmallImages.Width + 10); end; //Update arrangement and scrollbars Parent.DisableAlign; try Width := Width + 1; Width := Width - 1; finally Parent.EnableAlign; end; end; end; procedure TSyncListView.CNNotify(var Message: TWMNotify); var TmpItem: TLVItem; ChangeEventCalled, DummyB: boolean; Node: PVirtualNode; begin // Update Selection and Focused Item in VET if (Message.NMHdr^.code = LVN_ITEMCHANGED) and Assigned(VETController) and (not FSelectionPause) then with PNMListView(Message.NMHdr)^ do if uChanged = LVIF_STATE then if not Assigned(Items[iItem]) then begin FPrevEditing := false; // see CMEnter FFirstShiftClicked := -1; VETController.ClearSelection; end else begin Node := PVirtualNode(Items[iItem].Data); if Assigned(Node) then begin ChangeEventCalled := false; if ((uOldState and LVIS_SELECTED <> 0) and (uNewState and LVIS_SELECTED = 0)) or ((uOldState and LVIS_SELECTED = 0) and (uNewState and LVIS_SELECTED <> 0)) then begin VETController.Selected[Node] := (uNewState and LVIS_SELECTED <> 0); ChangeEventCalled := true; // changing the selection will call the OnChange event end; if (uOldState and LVIS_FOCUSED = 0) and (uNewState and LVIS_FOCUSED <> 0) then begin FPrevEditing := false; // see CMEnter VETController.FocusedNode := Node; if not ChangeEventCalled and Assigned(VETController.OnChange) then VETController.OnChange(VETController, Node); // call VET event end; end; end; // The VCL totally destroys the speed of this message we will take care of it if Message.NMHdr^.code <> NM_CUSTOMDRAW then inherited; // Handle cdPostPaint, Delphi doesn't do it :( if (Message.NMHdr^.code = NM_CUSTOMDRAW) and Assigned(Canvas) then with PNMCustomDraw(Message.NMHdr)^ do begin case PNMCustomDraw(Message.NMHdr)^.dwDrawStage of CDDS_PREPAINT: if not FInPaintCycle then Message.Result := CDRF_SKIPDEFAULT else Message.Result := CDRF_NOTIFYITEMDRAW; CDDS_ITEMPREPAINT: begin Message.Result := CDRF_NOTIFYPOSTPAINT; Canvas.Lock; try // We are drawing an item, NOT a subitem, in a postpaint stage FillChar(TmpItem, SizeOf(TmpItem), 0); TmpItem.iItem := dwItemSpec; DummyB := True; Canvas.Handle := hdc; // Assign the font and brush Canvas.Font.Assign(Font); Canvas.Brush.Assign(Brush); if Assigned(OnAdvancedCustomDrawItem) then OnAdvancedCustomDrawItem(Self, Items[TmpItem.iItem], TCustomDrawState(Word(uItemState)), cdPrePaint , DummyB); // Set the font and brush colors if IsBackgroundValid then begin SetBkMode(hdc, TRANSPARENT); with PNMLVCustomDraw(Message.NMHdr)^ do begin clrText := CLR_NONE; clrTextBk := CLR_NONE; end; end else with PNMLVCustomDraw(Message.NMHdr)^ do begin clrText := ColorToRGB(Canvas.Font.Color); clrTextBk := ColorToRGB(Canvas.Brush.Color); end; Canvas.Handle := 0; finally Canvas.Unlock; end; end; CDDS_ITEMPOSTPAINT: begin Message.Result := CDRF_DODEFAULT; Canvas.Lock; try //We are drawing an item, NOT a subitem, in a postpaint stage FillChar(TmpItem, SizeOf(TmpItem), 0); TmpItem.iItem := dwItemSpec; DummyB := true; Canvas.Handle := hdc; if Assigned(OnAdvancedCustomDrawItem) then OnAdvancedCustomDrawItem(Self, Items[TmpItem.iItem], TCustomDrawState(Word(uItemState)), cdPostPaint, DummyB); Canvas.Handle := 0; finally Canvas.Unlock; end; end; end; end; // Fire OnEditCancelled if (Message.NMHdr^.code = LVN_ENDLABELEDITW) and Assigned(VETController.OnEditCancelled) then if Win32PlatformIsUnicode then begin with PLVDispInfoW(Message.NMHdr)^ do if (item.pszText = nil) or (item.IItem = -1) then VETController.OnEditCancelled(VETController, 0); end else begin with PLVDispInfo(Message.NMHdr)^ do if (item.pszText = nil) or (item.IItem = -1) then VETController.OnEditCancelled(VETController, 0); end; end; procedure TSyncListView.CMEnter(var Message: TCMEnter); begin //When the Listview is unfocused and a previously selected item caption is //clicked it enters in editing mode. This is an incorrect TListview behavior. //Set a flag, and deactivate it in CanEdit and when the selection changes in CNNotify FPrevEditing := true; inherited; if Assigned(VETController) and Assigned(VETController.OnEnter) then VETController.OnEnter(VETController); end; procedure TSyncListView.CMExit(var Message: TCMExit); begin inherited; if Assigned(VETController) and Assigned(VETController.OnExit) then VETController.OnExit(VETController); end; procedure TSyncListView.CMMouseWheel(var Message: TCMMouseWheel); var I, dy: integer; begin //Scroll by thumbs if (VETController.ViewStyle = vsxThumbs) and (Items.Count > 0) and Assigned(Items[0]) then begin if (IconOptions.Arrangement = iaTop) then begin I := VETController.ThumbsOptions.Height + VETController.ThumbsOptions.SpaceHeight + 8; dy := (Message.WheelDelta div WHEEL_DELTA) * I; Scroll(0, -dy); Message.Result := 1; end else begin I := VETController.ThumbsOptions.Width + VETController.ThumbsOptions.SpaceHeight + 8; dy := (Message.WheelDelta div WHEEL_DELTA) * I; Scroll(-dy, 0); Message.Result := 1; end; end else inherited; end; procedure TSyncListView.LVMInsertColumn(var Message: TMessage); begin // Fix the VCL bug for XP with PLVColumn(Message.LParam)^ do begin // Fix TListView report mode bug. // But this screws up List style ... grrrr if (iImage = - 1) and (ViewStyle = vsReport) then Mask := Mask and not LVCF_IMAGE; end; inherited; end; procedure TSyncListView.LVMSetColumn(var Message: TMessage); begin // Fix the VCL bug for XP with PLVColumn(Message.LParam)^ do begin // Fix TListView report mode bug. // But this screws up List style ... grrrr if (iImage = - 1) and (ViewStyle = vsReport) then Mask := Mask and not LVCF_IMAGE; end; inherited; end; procedure TSyncListView.WndProc(var Msg: TMessage); var ContextResult: LRESULT; begin inherited; if Assigned(VETController) then Case Msg.Msg of WM_INITMENUPOPUP, WM_DRAWITEM, WM_MEASUREITEM: if Assigned(FSavedPopupNamespace) then //show the Send To item in the contextmenu FSavedPopupNamespace.HandleContextMenuMsg(Msg.Msg, Msg.WParam, Msg.LParam, ContextResult); end; end; function TSyncListView.OwnerDataHint(StartIndex, EndIndex: Integer): Boolean; var I, CacheIndex, W, H: integer; CI: TThumbsCacheItem; WSExt: WideString; Node: PVirtualNode; NS: TNamespace; Data: PThumbnailData; B: TBitmap; Cache: TThumbsCache; ByImageLibrary, ByShellExtract: boolean; begin Result := inherited OwnerDataHint(StartIndex, EndIndex); if (csDesigning in ComponentState) or (not Assigned(VETController)) or (OwnerDataPause) or (Items.Count = 0) then exit; for I := StartIndex to EndIndex do begin Node := VETController.GetNodeByIndex(I); // This is fast enough if VETController.ValidateNamespace(Node, NS) then begin {$IFDEF THREADEDICONS} // Call the VET icon thread to pre-load the index if not NS.ThreadedIconLoaded and (VETController.ThreadedImagesEnabled) then begin if not NS.ThreadIconLoading then begin NS.ThreadIconLoading := True; if VETController.ViewStyle = vsxIcon then ImageThreadManager.AddNewItem(VETController, WM_VTSETICONINDEX, NS.AbsolutePIDL, True, Node, I) else ImageThreadManager.AddNewItem(VETController, WM_VTSETICONINDEX, NS.AbsolutePIDL, False, Node, I) end; end; {$ENDIF} // Call the thumb thread if (VETController.ViewStyle = vsxThumbs) and VETController.ValidateThumbnail(Node, Data) and (Data.State = tsEmpty) and (NS.FileSystem) and (not NS.Folder) then begin Data.State := tsInvalid; if not (vsInitialized in Node.States) then VETController.InitNode(Node); WSExt := ExtractFileExtW(NS.NameForParsing); if VETController.ExtensionsExclusionList.IndexOf(WSExt) > -1 then begin ByImageLibrary := False; ByShellExtract := False; end else begin ByImageLibrary := VETController.ExtensionsList.IndexOf(WSExt) > -1; ByShellExtract := False; if not ByImageLibrary then if VETController.ThumbsOptions.UseShellExtraction or (VETController.ShellExtractExtensionsList.IndexOf(WSExt) > -1) then ByShellExtract := SupportsShellExtract(NS); end; if ByImageLibrary or ByShellExtract then begin Cache := VETController.ThumbsOptions.CacheOptions.FThumbsCache; // If the cache was loaded from file we don't need to call the thread :) if Cache.LoadedFromFile and not Data.Reloading then begin CacheIndex := Cache.IndexOf(NS.NameForParsing); if (CacheIndex > -1) and Cache.Read(CacheIndex, CI) then begin Data.CachePos := CacheIndex; Data.State := tsValid; // Update the cache entry if the file was changed if not VETController.DoThumbsCacheItemLoad(NS, CI) then VETController.ThumbsOptions.CacheOptions.Reload(Node); end; end else begin //let the application decide if Assigned(VetController.OnThumbsCacheItemRead) then begin B := TBitmap.Create; try if not VETController.DoThumbsCacheItemRead(NS.NameForParsing, B) then begin Data.CachePos := -1; Data.State := tsValid; end; finally B.Free; end; end; end; if (Data.State <> tsValid) and Assigned(VETController.ThumbThread) then begin //Process the thumb outside the thread? if Assigned(VetController.OnThumbsCacheItemProcessing) then begin B := TBitmap.Create; try B.Width := VETController.ThumbsOptions.Width; B.Height := VETController.ThumbsOptions.Height; if not VETController.DoThumbsCacheItemProcessing(NS, B, W, H) then if not Assigned(VETController.OnThumbsCacheItemAdd) or VETController.DoThumbsCacheItemAdd(NS, B, W, H) then begin Data.CachePos := Cache.Add(NS.NameForParsing, '', '', NS.LastWriteDateTime, W, H, False, B); Data.State := tsValid; end; finally B.Free; end; end; //Call the thread if (Data.State <> tsValid) and not VETController.ThumbsThreadPause then begin if VETController.ThumbsOptions.LoadAllAtOnce or (VETController.ThumbsOptions.CacheOptions.CacheProcessing = tcpAscending) then VETController.ThumbThread.InsertNewItem(VETController, WM_VLVEXTHUMBTHREAD, NS.AbsolutePIDL, ByShellExtract, Node, I) //ByShellExtract hardcoded to LargeIcon parameter else VETController.ThumbThread.AddNewItem(VETController, WM_VLVEXTHUMBTHREAD, NS.AbsolutePIDL, ByShellExtract, Node, I); //ByShellExtract hardcoded to LargeIcon parameter Data.State := tsProcessing; //it should be tsProcessing at first end; end; end; end; end; end; end; function TSyncListView.OwnerDataFetch(Item: TListItem; Request: TItemRequest): Boolean; var NS: TNamespace; Node: PVirtualNode; WS: WideString; begin Result := True; if (csDesigning in ComponentState) or not Assigned(Item) or not Assigned(VETController) or (Items.Count = 0) or (Item.Index < 0) or (Item.Index >= Items.Count) then Exit; Node := VETController.GetNodeByIndex(Item.Index); // this is fast enough if VETController.ValidateNamespace(Node, NS) then begin if not (vsInitialized in Node.States) then VETController.InitNode(Node); Item.Data := Node; // Keep a reference of the Node // Fill the Item caption for W9x, the displayed caption is in unicode. WS := NS.NameInFolder; FVETController.DoGetVETText(0, Node, NS, WS); Item.Caption := WS; if irImage in Request then begin {$IFDEF THREADEDICONS} if not (csDesigning in ComponentState) and VETController.ThreadedImagesEnabled and not NS.ThreadedIconLoaded then begin // Show default images if NS.Folder and NS.FileSystem then Item.ImageIndex := VETController.UnknownFolderIconIndex else Item.ImageIndex := VETController.UnknownFileIconIndex end else begin if NS.ThreadIconLoading then begin if NS.Folder and NS.FileSystem then Item.ImageIndex := VETController.UnknownFolderIconIndex else Item.ImageIndex := VETController.UnknownFileIconIndex end else Item.ImageIndex := NS.GetIconIndex(false, icLarge); end; {$ELSE} Item.ImageIndex := NS.GetIconIndex(false, icLarge); {$ENDIF} Item.Cut := NS.Ghosted; if not (toHideOverlay in VETController.TreeOptions.VETImageOptions) and Assigned(NS.ShellIconOverlayInterface) then Item.OverlayIndex := NS.OverlayIndex - 1 else if NS.Link then Item.OverlayIndex := 1 else if NS.Share then Item.OverlayIndex := 0 else Item.OverlayIndex := -1; end; end; end; function TSyncListView.OwnerDataFind(Find: TItemFind; const FindString: AnsiString; const FindPosition: TPoint; FindData: Pointer; StartIndex: Integer; Direction: TSearchDirection; Wrap: Boolean): Integer; //OnDataFind gets called in response to calls to FindCaption, FindData, //GetNearestItem, etc. It also gets called for each keystroke sent to the //ListView (for incremental searching) var I: Integer; Found: Boolean; Node: PVirtualNode; NS: TNamespace; WS: WideString; begin Result := -1; if Assigned(PWideFindString) then WS := PWideFindString else WS := FindString; //search in VET if Assigned(VETController) and (not OwnerDataPause) then begin I := StartIndex; Found := false; if (Find = ifExactString) or (Find = ifPartialString) then begin WS := WideLowerCase(WS); repeat if I > Items.Count-1 then if Wrap then I := 0 else Exit; Node := PVirtualNode(Items[I].Data); if VETController.ValidateNamespace(Node, NS) then Found := Pos(WS, WideLowerCase(NS.NameInFolder)) = 1; Inc(I); until Found or (I = StartIndex); if Found then Result := I-1; end; end; // Fire OnDataFind, don't call inherited if Assigned(OnDataFind) then OnDataFind(Self, Find, WS, FindPosition, FindData, StartIndex, Direction, Wrap, Result); end; function TSyncListView.OwnerDataStateChange(StartIndex, EndIndex: Integer; OldState, NewState: TItemStates): Boolean; begin // In OwnerDraw, the selections with the SHIFT and Mouse fire LVN_ODSTATECHANGED // and not the the CN_NOTIFY message Result := inherited OwnerDataStateChange(StartIndex, EndIndex, OldState, NewState); if Assigned(VETController) then begin VETController.SyncSelectedItems(False); if Assigned(VETController.OnChange) then VETController.OnChange(VETController, nil); end; end; function TSyncListView.GetItemCaption(Index: Integer): WideString; var NS: TNamespace; begin Result := ''; if Assigned(VETController) then if FVETController.ValidateNamespace(PVirtualNode(Items[Index].Data), NS) then begin Result := NS.NameInFolder; FVETController.DoGetVETText(0, PVirtualNode(Items[Index].Data), NS, Result); if SingleLineCaptions and (EditingItemIndex <> Index) and (SingleLineMaxChars > 0) then if (ViewStyle = vsIcon) then Result := SpPathCompactPath(Result, SingleLineMaxChars); end; end; function TSyncListView.IsBackgroundValid: Boolean; var BK: TLVBKImage; begin Result := False; if Assigned(VETController) and (toShowBackground in VETController.TreeOptions.PaintOptions) then begin Fillchar(BK, SizeOf(BK), 0); ListView_GetBkImage(Handle, @BK); if BK.ulFlags > 0 then Result := True; end; end; procedure TSyncListView.Edit(const Item: TLVItem); var WS: WideString; EditItem: TListItem; Node: PVirtualNode; NS: TNamespace; TD: PThumbnailData; ExtChanged: Boolean; begin inherited; if (not Win32PlatformIsUnicode) then WS := Item.pszText else WS := TLVItemW(Item).pszText; EditItem := GetItem(TLVItemW(Item)); if Assigned(VETController) and Assigned(EditItem) then begin Node := PVirtualNode(EditItem.Data); if VETController.ValidateNamespace(Node, NS) and VETController.ValidateThumbnail(Node, TD) then begin ExtChanged := not SpCompareText(NS.Extension, ExtractFileExtW(WS)); if NS.SetNameOf(WS) then begin NS.InvalidateCache; if ExtChanged then begin if TD.State <> tsEmpty then TD.State := tsEmpty; end; end; if Assigned(VETController.OnEdited) then VETController.OnEdited(VETController, Node, 0); end; end; end; function TSyncListView.CanEdit(Item: TListItem): Boolean; var Node: PVirtualNode; begin if FPrevEditing or (toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin FPrevEditing := false; //see CMEnter Result := false; end else begin Result := inherited CanEdit(Item); if Assigned(Item) then begin if Assigned(VETController) and Assigned(VetController.OnEditing) then begin Node := PVirtualNode(Item.Data); VetController.OnEditing(VetController, Node, 0, Result); end; end; end; end; function GetSelectionBox(LV: TListview): TRect; var Item: TListItem; begin Result := Rect(0, 0, 0, 0); //Find the Top-Left and Bottom-Right of the selection box Item := LV.Selected; if Assigned(Item) then begin Result.TopLeft := Item.Position; Result.BottomRight := Item.Position; while Assigned(Item) do begin Result.Left := Min(Result.Left, Item.Position.X); Result.Top := Min(Result.Top, Item.Position.Y); Result.Right := Max(Result.Right, Item.Position.X); Result.Bottom := Max(Result.Bottom, Item.Position.Y); Item := LV.GetNextItem(Item, sdAll, [isSelected]); end; end; end; function IsPointInRect(R: TRect; P: TPoint): boolean; begin // Alternative to PtInRect, since in PtInRect a point on the right or // bottom side is considered outside the rectangle. Result := (P.X >= R.Left) and (P.X <= R.Right) and (P.Y >= R.Top) and (P.Y <= R.Bottom); end; function KeyMultiSelectEx(LV: TListview; SD: TSearchDirection): boolean; // The MS Listview control in virtual mode (OwnerData) has a bug when // Shift-Selecting an item, it just selects all the items from the last // selected to the current selected, index wise. // This little function will solve this issue. // From MSDN: // For normal Listviews LVN_ITEMCHANGING is triggered for every item that is // being selected: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_itemchanging.asp // // But for ownerdata listviews LVN_ODSTATECHANGED is triggered ONCE with all // the selected items: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_odstatechanged.asp // // The NMLVODSTATECHANGE member has only 2 integers specifying the range of // selected items, with no differentiation. // http://msdn.microsoft.com/library/en-us/shellcc/platform/commctls/listview/structures/nmlvodstatechange.asp var Item: TListItem; R, RFocused: TRect; P: TPoint; I, iClicked, iFocused: integer; begin // TSearchDirection = (sdLeft, sdRight, sdAbove, sdBelow, or sdAll); // Note: when ItemFocused or Selected is called the TListItem pointer is changed, weird. Result := false; if Assigned(LV.ItemFocused) and (LV.Items.Count > 1) and (SD <> sdAll) then begin R := GetSelectionBox(LV); iFocused := LV.ItemFocused.Index; Item := LV.GetNextItem(LV.ItemFocused, SD, []); iClicked := Item.Index; if Assigned(LV.Items[iClicked]) and (iClicked <> iFocused) then begin P := LV.Items[iClicked].Position; if IsPointInRect(R, P) then begin // Contract the selection box Case SD of ComCtrls.sdLeft: R.Right := P.X; ComCtrls.sdAbove: R.Bottom := P.Y; ComCtrls.sdRight: R.Left := P.X; ComCtrls.sdBelow: R.Top := P.Y; end; end else begin // Expand the selection box if P.X < R.Left then R.Left := P.X else if P.X > R.Right then R.Right := P.X; if P.Y < R.Top then R.Top := P.Y else if P.Y > R.Bottom then R.Bottom := P.Y; end; // Update, select and focus the item ListView_GetItemRect(LV.Handle, iFocused, RFocused, LVIR_BOUNDS); LV.Items[iClicked].Selected := true; LV.Items[iClicked].Focused := true; InvalidateRect(LV.Handle, @RFocused, true); // Select all items in the selection box and unselect the rest for I := 0 to LV.Items.Count-1 do begin Item := LV.Items[I]; Item.Selected := IsPointInRect(R, Item.Position); end; LV.Items[iClicked].MakeVisible(false); Result := true; end; end; end; function MouseMultiSelectEx(LV: TListview; iClickedItem, iFirstClicked: integer): boolean; // The MS Listview control in virtual mode (OwnerData) has a bug when // Shift-Selecting an item, it just selects all the items from the last // selected to the current selected, index wise. // This little function will solve this issue. // From MSDN: // For normal Listviews LVN_ITEMCHANGING is triggered for every item that is // being selected: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_itemchanging.asp // // But for ownerdata listviews LVN_ODSTATECHANGED is triggered ONCE with all // the selected items: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_odstatechanged.asp // // The NMLVODSTATECHANGE member has only 2 integers specifying the range of // selected items, with no differentiation. // http://msdn.microsoft.com/library/en-us/shellcc/platform/commctls/listview/structures/nmlvodstatechange.asp var Item: TListItem; R, RFocused: TRect; I, iFocused: integer; begin Result := false; if (iClickedItem > -1) and (iClickedItem < LV.Items.Count) then begin // When ItemFocused is called the Item parameter is changed, weird iFocused := LV.ItemFocused.Index; if Assigned(LV.ItemFocused) and (LV.Items.Count > 1) then begin // Update, select and focus the item ListView_GetItemRect(LV.Handle, iFocused, RFocused, LVIR_BOUNDS); LV.Items[iClickedItem].Selected := true; LV.Items[iClickedItem].Focused := true; InvalidateRect(LV.Handle, @RFocused, true); if (iFirstClicked < 0) or (iFirstClicked > LV.Items.Count-1) then iFirstClicked := iFocused; // From the Focused if there's no FirstClicked // Set the selection box from the FirstClicked to the ClickedItem R.Left := Min(LV.Items[iClickedItem].Position.X, LV.Items[iFirstClicked].Position.X); R.Top := Min(LV.Items[iClickedItem].Position.Y, LV.Items[iFirstClicked].Position.Y); R.Right := Max(LV.Items[iClickedItem].Position.X, LV.Items[iFirstClicked].Position.X); R.Bottom := Max(LV.Items[iClickedItem].Position.Y, LV.Items[iFirstClicked].Position.Y); // Select all items in the selection box and unselect the rest for I := 0 to LV.Items.Count-1 do begin Item := LV.Items[I]; Item.Selected := IsPointInRect(R, Item.Position); end; Result := true; end; end; end; procedure TSyncListView.WMLButtonDown(var Message: TWMLButtonDown); var Shift: TShiftState; P: TPoint; R: TRect; Item: TListItem; Node: PVirtualNode; iClicked: integer; begin //This will solve the MS Listview Shift-Select bug Shift := KeysToShiftState(Message.Keys); P := Point(Message.XPos, Message.YPos); if (MultiSelect) and (ViewStyle in [vsIcon, vsSmallIcon]) and (ssShift in Shift) then begin Item := GetItemAt(P.X, P.Y); if Assigned(Item) then begin iClicked := Item.Index; if SelCount = 0 then FFirstShiftClicked := -1 else if SelCount = 1 then FFirstShiftClicked := Selected.Index; MouseMultiSelectEx(Self, iClicked, FFirstShiftClicked); end else inherited; end else begin // Enable Thumbnail checkbox clicks if (Shift = [ssLeft]) and (VETController.ViewStyle = vsxThumbs) and (toCheckSupport in VETController.TreeOptions.MiscOptions) then begin Item := GetItemAt(P.X, P.Y); if Assigned(Item) then begin Node := PVirtualNode(Item.Data); if Assigned(Node) and (Node.CheckType <> VirtualTrees.ctNone) then begin R := Item.DisplayRect(drIcon); if FIsComCtl6 then R.Left := R.Left + VETController.ThumbsOptions.SpaceWidth div 2; R.Right := R.Left + 15; R.Bottom := R.Top + 15; if PtInRect(R, P) then begin VETController.CheckState[Node] := VETController.DetermineNextCheckState(Node.CheckType, Node.CheckState); InvalidateRect(Handle, @R, True); Exit; end; end; end; end; inherited; end; end; procedure TSyncListView.KeyDown(var Key: Word; Shift: TShiftState); var I, H: integer; Node: PVirtualNode; DoDefault: boolean; begin inherited; if IsEditing then Exit; //If the ClientHeight is to small to fit 2 thumbnails the PageUp/PageDown //key buttons won't work. //This is a VCL TListview bug, to workaround this I had to fake these keys //to Up/Down. if (VETController.ViewStyle = vsxThumbs) and (Items.Count > 0) and Assigned(ItemFocused) and (Key in [VK_NEXT, VK_PRIOR]) then begin H := (VETController.ThumbsOptions.Height + VETController.ThumbsOptions.SpaceHeight) * 2 + 5; if ClientHeight < H then begin // if there's not at least 2 full visible items Case Key of VK_NEXT: Key := VK_DOWN; VK_PRIOR: Key := VK_UP; end; end; end; //Corrected TListview bug in virtual mode, when the icon arrangement is iaLeft the arrow keys are scrambled if IconOptions.Arrangement = iaLeft then Case Key of VK_UP: Key := VK_LEFT; VK_DOWN: Key := VK_RIGHT; VK_LEFT: Key := VK_UP; VK_RIGHT: Key := VK_DOWN; end; //This will solve the MS Listview Shift-Select bug if (MultiSelect) and (ViewStyle in [vsIcon, vsSmallIcon]) and (ssShift in Shift) and (Key in [VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT]) then begin Case Key of VK_UP: KeyMultiSelectEx(Self, ComCtrls.sdAbove); VK_DOWN: KeyMultiSelectEx(Self, ComCtrls.sdBelow); VK_LEFT: KeyMultiSelectEx(Self, ComCtrls.sdLeft); VK_RIGHT: KeyMultiSelectEx(Self, ComCtrls.sdRight); end; Key := 0; end else if Assigned(VETController) then begin //call VET events DoDefault := true; if Assigned(VETController.OnKeyDown) then VETController.OnKeyDown(VETController, Key, Shift); if Assigned(VETController.OnKeyAction) then VETController.OnKeyAction(VETController, Key, Shift, DoDefault); if DoDefault then begin Case Key of VK_RETURN: if (ItemFocused <> nil) and (ItemFocused.Selected) then begin VETController.ClearSelection; Node := PVirtualNode(ItemFocused.Data); if Assigned(Node) then begin VETController.Selected[Node] := true; VETController.DoShellExecute(Node); end; end; VK_BACK: VETController.BrowseToPrevLevel; VK_F2: if (not ReadOnly) and (ItemFocused <> nil) then ItemFocused.EditCaption; VK_F5: VETController.RefreshTree(toRestoreTopNodeOnRefresh in VETController.TreeOptions.VETMiscOptions); VK_DELETE: VETController.SelectedFilesDelete; Ord('A'), Ord('a'): if ssCtrl in Shift then begin VETController.SelectAll(true); for I := 0 to Items.Count - 1 do Items[I].Selected := True; end; Ord('C'), Ord('c'): if ssCtrl in Shift then VETController.CopyToClipboard; Ord('X'), Ord('x'): if ssCtrl in Shift then VETController.CutToClipboard; Ord('V'), Ord('v'): if ssCtrl in Shift then VETController.PasteFromClipboard; Ord('I'), Ord('i'): if (ssCtrl in Shift) then begin VETController.InvertSelection(False); VETController.SyncSelectedItems; end; VK_INSERT: // Lefties favorite keys! if ssShift in Shift then VETController.PasteFromClipboard else if ssCtrl in Shift then VETController.CopyToClipboard; end; end; end; end; procedure TSyncListView.KeyPress(var Key: Char); begin inherited; if Assigned(VETController) and Assigned(VETController.OnKeyPress) then VETController.OnKeyPress(VETController, Key); end; procedure TSyncListView.KeyUp(var Key: Word; Shift: TShiftState); begin inherited; if Assigned(VETController) and Assigned(VETController.OnKeyUp) then VETController.OnKeyUp(VETController, Key, Shift); end; procedure TSyncListView.DblClick; var Node: PVirtualNode; begin inherited; if Assigned(VETController) then begin // Set the selection in the VETController Node := nil; if Assigned(ItemFocused) and (ItemFocused.Selected) then begin Node := PVirtualNode(ItemFocused.Data); if Assigned(Node) then begin VETController.ClearSelection; VETController.FocusedNode := Node; VETController.Selected[Node] := True; end; end; // Fire VETController.OnDblClick event if Assigned(VETController.OnDblClick) then VETController.OnDblClick(VETController); // Browse the Node if Assigned(Node) then VETController.DoShellExecute(Node); end; end; procedure TSyncListView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Assigned(VETController) and Assigned(VETController.OnMouseDown) then VETController.OnMouseDown(VETController, Button, Shift, X, Y); end; procedure TSyncListView.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if Assigned(VETController) and Assigned(VETController.OnMouseMove) then VETController.OnMouseMove(VETController, Shift, X, Y); end; procedure TSyncListView.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Assigned(VETController) then begin if Assigned(VETController.OnMouseUp) then VETController.OnMouseUp(VETController, Button, Shift, X, Y); if Assigned(VETController.OnClick) then VETController.OnClick(VETController); end; end; procedure TSyncListView.ContextMenuCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; var Handled: Boolean); begin Handled := False; if Assigned(VETController) and Assigned(VETController.OnContextMenuCmd) then VETController.OnContextMenuCmd(VETController, Namespace, Verb, MenuItemID, Handled); if (Verb = 'rename') and not Handled then begin Handled := True; if (not ReadOnly) and (ItemFocused <> nil) then ItemFocused.EditCaption; end; end; procedure TSyncListView.ContextMenuShowCallback(Namespace: TNamespace; Menu: hMenu; var Allow: Boolean); begin Allow := True; if Assigned(VETController) and Assigned(VETController.OnContextMenuShow) then VETController.OnContextMenuShow(VETController, Namespace, Menu, Allow); end; procedure TSyncListView.ContextMenuAfterCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; Successful: Boolean); begin if Successful then begin if Verb = 'cut' then VETController.MarkNodesCut; if Verb = 'copy' then VETController.MarkNodesCopied; Invalidate; end end; procedure TSyncListView.DoContextPopup(MousePos: TPoint; var Handled: Boolean); var Node: PVirtualNode; Pt: TPoint; begin if Assigned(VETController) and not(toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin Pt := ClientToScreen(MousePos); if (toContextMenus in VETController.TreeOptions.VETShellOptions) and Assigned(Selected) then begin Handled := true; //We are going to work on ExplorerLV, first sync the selected items VETController.SyncSelectedItems(false); Node := VETController.GetFirstSelected; //Save the namespace for WM_INITMENUPOPUP, WM_DRAWITEM, WM_MEASUREITEM messages if VETController.ValidateNamespace(Node, FSavedPopupNamespace) then FSavedPopupNamespace.ShowContextMenuMulti(Self, ContextMenuCmdCallback, ContextMenuShowCallback, ContextMenuAfterCmdCallback, VETController.SelectedToNamespaceArray, @Pt, VETController.ShellContextSubMenu, VETController.ShellContextSubMenuCaption); end else if Assigned(VETController.PopupMenu) then begin Handled := True; VETController.PopupMenu.Popup(Pt.x, Pt.y); end; end; if not Handled then inherited; end; procedure TSyncListView.SetDetailedHints(const Value: Boolean); begin //Disable the tooltip that is shown when an item caption is truncated if FDetailedHints <> Value then begin if Value then VETController.ShowHint := True; FDetailedHints := Value; UpdateHintHandle; end; end; procedure TSyncListView.WMPaint(var Message: TWMPaint); begin FInPaintCycle := True; inherited; FInPaintCycle := False; end; procedure TSyncListView.WMVScroll(var Message: TWMVScroll); // Local function by Peter Bellow // http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00007ac9.007e7c13%40antispam.compuserve.com function FindDynamicMethod( aClass: TClass; anIndex: SmallInt ): Pointer; type TIndices= Array [1..1024] of SmallInt; TProcs = Array [1..1024] of Pointer; var pDMT : PWord; i, count: Word; pIndices : ^TIndices; pProcs : ^TProcs; begin Result := nil; If aClass = nil Then Exit; pDMT := Pointer(aClass); // Find pointer to DMT in VMT, first Word is the count of dynamic // methods pDMT := Pointer(PDword( Integer(pDMT) + vmtDynamicTable )^); count := pDMT^; pIndices := Pointer( Integer( pDMT ) + 2 ); pProcs := Pointer( Integer( pDMT ) + 2 + count * sizeof( smallint )); // find handler for anIndex for i:= 1 to count do if pIndices^[i] = anIndex then begin Result := pProcs^[i]; Break; end; If Result = nil Then Result := FindDynamicMethod( aClass.Classparent, anIndex ); end; {$IFDEF DELPHI_7_UP} var oldWMVScroll: procedure(var Message: TWMVScroll) of object; {$ENDIF} begin // Delphi 7 bug: the Listview invalidates the canvas when Scrolling :( // The problem is in ComCtrls.pas: TCustomListView.WMVScroll {$IFDEF DELPHI_7_UP} // Call the grandfather WM_VSCROLL handler, sort of inherited-inherited TMethod(oldWMVScroll).code := FindDynamicMethod(TWincontrol, WM_VSCROLL); TMethod(oldWMVScroll).data := Self; oldWMVScroll(Message); {$ELSE} inherited; {$ENDIF} // Set the focus when the scrollbar is clicked if not Focused then SetFocus; end; procedure TSyncListView.WMHScroll(var Message: TWMHScroll); begin inherited; // Set the focus when the scrollbar is clicked if not Focused then SetFocus; end; procedure TSyncListView.UpdateHintHandle; begin if HandleAllocated then begin if not ShowHint then // VCL TListview bug, setting ShowHint to False doesn't disable the hints // We must do this explicitly ListView_SetToolTips(Handle, 0) else if FDetailedHints then ListView_SetToolTips(Handle, 0) else ListView_SetToolTips(Handle, FDefaultTooltipsHandle); end; end; procedure TSyncListView.CMShowHintChanged(var Message: TMessage); begin inherited; // VCL TListview bug, setting ShowHint to False doesn't disable the hints // We must do this explicitly UpdateHintHandle; end; procedure TSyncListView.CMHintShow(var Message: TCMHintShow); var HintInfo: PHintInfo; Item: TListItem; Node: PVirtualNode; NS: TNamespace; S: WideString; R: TRect; P: TPoint; OverlayI: integer; Style: Cardinal; begin if FDetailedHints and Assigned(VETController) and (VETController.ViewStyle <> vsxReport) then begin HintInfo := TCMHintShow(Message).HintInfo; Item := GetItemAt(HintInfo.CursorPos.X, HintInfo.CursorPos.Y); if Assigned(Item) and VETController.ValidateNamespace(PVirtualNode(Item.Data), NS) then begin Node := PVirtualNode(Item.Data); //Set the Hint HintInfo.HintWindowClass := TBitmapHint; //custom HintWindow class HintInfo.HintData := FThumbnailHintBitmap; //TApplication.ActivateHint will pass the data to the HintWindow HintInfo.HintStr := Item.Caption; HintInfo.CursorRect := GetLVItemRect(Item.Index, drBounds); HintInfo.CursorRect.TopLeft := ClientToScreen(HintInfo.CursorRect.TopLeft); HintInfo.CursorRect.BottomRight := ClientToScreen(HintInfo.CursorRect.BottomRight); // HintInfo.HintPos.X := HintInfo.CursorRect.Left + GetSystemMetrics(SM_CXCURSOR) - 5; // HintInfo.HintPos.Y := HintInfo.CursorRect.Top + GetSystemMetrics(SM_CYCURSOR) ; HintInfo.HintMaxWidth := ClientWidth; HintInfo.HideTimeout := 60000; //1 minute //Draw in the hint S := VETController.DoThumbsGetDetails(Node, true); if S <> '' then begin R := Rect(0, 0, 0, 0); if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(FThumbnailHintBitmap.Canvas.Handle, PChar(AnsiString(S)), -1, R, DT_CALCRECT) else Windows.DrawTextW(FThumbnailHintBitmap.Canvas.Handle, PWideChar(S), -1, R, DT_CALCRECT); FThumbnailHintBitmap.Width := R.Right + LargeSysImages.Width + 16; if R.Bottom >= LargeSysImages.Height then FThumbnailHintBitmap.Height := R.Bottom + 8 else FThumbnailHintBitmap.Height := LargeSysImages.Height + 8; FThumbnailHintBitmap.Canvas.Font.Color := clInfoText; FThumbnailHintBitmap.Canvas.Pen.Color := clBlack; FThumbnailHintBitmap.Canvas.Brush.Color := clInfoBk; FThumbnailHintBitmap.Canvas.FillRect(Rect(0, 0, FThumbnailHintBitmap.Width, FThumbnailHintBitmap.Height)); //Custom drawing if VETController.DoThumbsDrawHint(FThumbnailHintBitmap, Node) then begin P.x := 4; P.y := (FThumbnailHintBitmap.Height - LargeSysImages.Height) div 2; Style := ILD_TRANSPARENT; OverlayI := -1; if not (toHideOverlay in VETController.TreeOptions.VETImageOptions) and Assigned(NS.ShellIconOverlayInterface) then OverlayI := NS.OverlayIndex - 1 else if NS.Link then OverlayI := 1 else if NS.Share then OverlayI := 0; if OverlayI > -1 then Style := Style or ILD_OVERLAYMASK and Cardinal(IndexToOverlayMask(OverlayI + 1)); ImageList_DrawEx(LargeSysImages.Handle, NS.GetIconIndex(false, icLarge), FThumbnailHintBitmap.Canvas.Handle, P.x, P.y, 0, 0, CLR_NONE, CLR_NONE, Style); OffsetRect(R, LargeSysImages.Width + 8, (FThumbnailHintBitmap.Height - R.Bottom) div 2); if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(FThumbnailHintBitmap.Canvas.Handle, PChar(AnsiString(S)), -1, R, 0) else Windows.DrawTextW(FThumbnailHintBitmap.Canvas.Handle, PWideChar(S), -1, R, 0); end; Message.Result := 0; end; end; end else inherited; end; procedure TSyncListView.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if IsBackgroundValid then begin DefaultHandler(Message); Message.Result := 1; end else inherited; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TOLEListview } procedure TOLEListview.AutoScrollTimerCallback(Window: hWnd; Msg, idEvent: integer; dwTime: Longword); var Pt: TPoint; begin FAutoScrolling := True; try Pt := Mouse.CursorPos; Pt := ScreenToClient(Pt); if Pt.y < 20 then Scroll(0, -(20 - Pt.y)*2); if Pt.y > ClientHeight - 20 then Scroll(0, (20 - (ClientHeight - Pt.y)) * 2); if Pt.x < 20 then Scroll(-(20 - Pt.x)*2, 0); if Pt.x > ClientWidth - 20 then Scroll((20 - (ClientWidth - Pt.x)) * 2, 0); finally FAutoScrolling := False; end end; procedure TOLEListview.ClearTimers; begin if FScrollTimer <> 0 then begin KillTimer(Handle, FScrollTimer); FScrollTimer := 0; end; if FScrollDelayTimer <> 0 then begin KillTimer(Handle, FScrollDelayTimer); FScrollDelayTimer := 0; end; end; constructor TOLEListview.Create(AOwner: TComponent); begin inherited; CurrentDropIndex := -2; // -1 = backgound -2 = nothing FDragItemIndex := -1; FAutoScrollTimerStub := CreateStub(Self, @TOLEListview.AutoScrollTimerCallback); end; procedure TOLEListview.CreateDragImage(TotalDragRect: TRect; RectArray: TRectArray; var Bitmap: TBitmap); var i: integer; LVBitmap: TBitmap; Offset: TPoint; R: TRect; begin if Assigned(Bitmap) and (SelCount > 0) then begin //Get a Bitmap with all the selected items LVBitmap := TBitmap.Create; Bitmap.Canvas.Lock; try //update Bitmap size Bitmap.Width := TotalDragRect.Right - TotalDragRect.Left; Bitmap.Height := TotalDragRect.Bottom - TotalDragRect.Top; Bitmap.Canvas.Brush.Color := Self.Color; Bitmap.Canvas.FillRect(Rect(0, 0, Bitmap.Width, Bitmap.Height)); LVBitmap.Width := ClientWidth; LVBitmap.Height := ClientHeight; LVBitmap.Canvas.Lock; //we need to Lock the canvas in order to use the PaintTo method try //Don't use PaintTo, WinXP doesn't support it. BitBlt(LVBitmap.Canvas.Handle, 0, 0, ClientWidth, ClientHeight, Canvas.Handle, 0, 0, srcCopy); finally LVBitmap.Canvas.UnLock; end; Offset.X := TotalDragRect.Left; Offset.Y := TotalDragRect.Top; //Iterate and CopyRect the selected items for I := 0 to Length(RectArray) - 1 do begin R := RectArray[I]; if R.Top <= 0 then R.Top := 0; //don't draw borders if R.Left <= 0 then R.Left := 0; //don't draw borders StretchBlt(Bitmap.Canvas.Handle, R.Left - Offset.x, R.top - Offset.y, R.Right - R.Left, R.Bottom - R.Top, LVBitmap.Canvas.Handle, R.Left+2, R.Top+2, R.Right - R.Left+2, R.Bottom - R.Top+2, cmSrcCopy); end; finally Bitmap.Canvas.Unlock; LVBitmap.Free; end; end; end; procedure TOLEListview.CreateWnd; begin inherited; if not (csDesigning in ComponentState) then begin CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper, FDropTargetHelper); RegisterDragDrop(Handle, Self) end end; destructor TOLEListview.Destroy; begin ClearTimers; if Assigned(FAutoScrollTimerStub) then DisposeStub(FAutoScrollTimerStub); inherited; end; procedure TOLEListview.DoContextPopup(MousePos: TPoint; var Handled: Boolean); begin // Clear the mouse states as the context menu grabs the mouse and never sends us a WM_xMOUSEUP message MouseButtonState := []; inherited; end; procedure TOLEListview.DestroyWnd; begin if not (csDesigning in ComponentState) then RevokeDragDrop(Handle); inherited; end; function TOLEListview.DragEnter(const dataObj: IDataObject; grfKeyState: Integer; pt: TPoint; var dwEffect: Integer): HResult; begin if Assigned(DropTargetHelper) then DropTargetHelper.DragEnter(Handle, dataObj, Pt, dwEffect); DragDataObject := DataObj; FScrollDelayTimer := SetTimer(Handle, SCROLL_DELAY_TIMER, VETController.AutoScrollDelay, nil); Result := S_OK; end; function TOLEListview.Dragging: Boolean; begin Result := FDragging end; function TOLEListview.DragLeave: HResult; var TempNS: TNamespace; TempItem: TListItem; begin if Assigned(DropTargetHelper) then DropTargetHelper.DragLeave; ClearTimers; TempNS := nil; if CurrentDropIndex > -2 then begin if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then begin TempItem := Items[CurrentDropIndex]; TempItem.DropTarget := False; // DropTarget only hilight caption TempNS := ListItemToNamespace(TempItem, True); end else VETController.ValidateNamespace(VETController.RootNode, TempNS); if Assigned(TempNS) then TempNS.DragLeave; end; CurrentDropIndex := -2; DragDataObject := nil; Result := S_OK; end; function TOLEListview.DragOverOLE(grfKeyState: Integer; pt: TPoint; var dwEffect: Integer): HResult; var HitNS, TempNS: TNamespace; HitItem, TempItem: TListItem; HitIndex: integer; ShiftState: TShiftState; begin // Update any drag image if Assigned(DropTargetHelper) then DropTargetHelper.DragOver(pt, dwEffect); Result := S_OK; if AutoScrolling or not (toAcceptOLEDrop in VETController.TreeOptions.MiscOptions) or (toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin dwEffect := DROPEFFECT_NONE; Exit; end; ShiftState := KeysToShiftState(grfKeyState); // Fire VETController.OnDragOver event VETController.DoDragOver(Self, ShiftState, dsDragMove, Pt, dmOnNode, dwEffect); Pt := ScreenToClient(Pt); HitItem := GetItemAt(Pt.X, Pt.Y); HitNS := ListItemToNamespace(HitItem, True); if Assigned(HitItem) then HitIndex := HitItem.Index else HitIndex := -1; // Don't allow to drop in the dragging item unless Shift, Alt or Ctrl is // pressed and the item is inside the listview if (HitIndex = FDragItemIndex) and (FDragItemIndex > -1) and (ShiftState * [ssRight, ssShift, ssAlt, ssCtrl] = []) then begin if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then Items[CurrentDropIndex].DropTarget := False; // reset highlight caption dwEffect := DROPEFFECT_NONE; CurrentDropIndex := -2; exit; end; // If the HitIndex is different that the current drop target then // update everything to select the new item (or parent if the drop is "into" the list view if (HitIndex <> CurrentDropIndex) then begin //<<<<<if GetHitTestInfoAt(Pt.X, Pt.Y) * [htOnIcon, htOnLabel] <> [] then begin if HitIndex > -1 then begin // Try to enter the new namespace Result := HitNS.DragEnter(DragDataObject, grfKeyState, pt, dwEffect); // If we can't drop on that namespace then we need to just default to dropping // "into" the current list view, i.e. the RootNode of the VT. Otherwise every // thing is hunky dory and the HitItem will be selected if dwEffect <> DROPEFFECT_NONE then HitItem.DropTarget := True // DropTarget only hilight caption else begin HitNS.DragLeave; // Leave the HitItem namespace, not going to use it exit; // cancel the drag end; end; // If we were on the background and the hit node does not take drops leave it // in the backgound with making any changes if CurrentDropIndex <> HitIndex then begin TempNS := nil; if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then begin TempItem := Items[CurrentDropIndex]; TempItem.DropTarget := False; // reset highlight caption TempNS := ListItemToNamespace(TempItem, False); end else VETController.ValidateNamespace(VETController.RootNode, TempNS); if Assigned(TempNS) then begin // Only drag leave if the current actually was somewhere (-2 means current was over nothing) if (CurrentDropIndex > -2) and (CurrentDropIndex < Items.Count) then TempNS.DragLeave; TempNS := ListIndexToNamespace(HitIndex); TempNS.DragEnter(DragDataObject, grfKeyState, pt, dwEffect); end; CurrentDropIndex := HitIndex end else begin dwEffect := DROPEFFECT_NONE; end; end else begin // Don't allow to drop in the background unless Shift, Alt or Ctrl is // pressed and the drag item is INSIDE the Listview if (HitIndex = -1) and (FDragItemIndex > -1) and (ShiftState * [ssRight, ssShift, ssAlt, ssCtrl] = []) then dwEffect := DROPEFFECT_NONE else begin TempNS := ListIndexToNamespace(CurrentDropIndex); if Assigned(TempNS) then TempNS.DragOver(grfKeyState, pt, dwEffect); end; end; end; function TOLEListview.Drop(const dataObj: IDataObject; grfKeyState: Integer; Pt: TPoint; var dwEffect: Integer): HResult; var TempNS: TNamespace; TempItem: TListItem; ClientPt: TPoint; I: Integer; begin FDropped := True; try if Assigned(DropTargetHelper) then DropTargetHelper.Drop(dataObj, Pt, dwEffect); ClearTimers; TempNS := nil; // Fire VETController.OnDragDrop event I := dwEffect; ClientPt := ScreenToClient(Pt); VETController.DoDragDrop(Self, dataObj, nil, KeysToShiftState(grfKeyState), ClientPt, I, dmOnNode); if (CurrentDropIndex > -2) and (I <> DROPEFFECT_NONE) then begin if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then begin TempItem := Items[CurrentDropIndex]; TempItem.DropTarget := False; // DropTarget only highlight caption TempNS := ListItemToNamespace(TempItem, True); end else VETController.ValidateNamespace(VETController.RootNode, TempNS); if Assigned(TempNS) then TempNS.Drop(dataObj, grfKeyState, pt, dwEffect); end; CurrentDropIndex := -2; DragDataObject := nil; Result := S_OK; // Fire OnDragDrop for the TOLEListview control if I <> DROPEFFECT_NONE then DragDrop(Self, ClientPt.X, ClientPt.Y); finally FDropped := False; end; end; function TOLEListview.GiveFeedback(dwEffect: Integer): HResult; begin Result := DRAGDROP_S_USEDEFAULTCURSORS end; function TOLEListview.ListIndexToNamespace(ItemIndex: integer): TNamespace; // use -1 to get the Listview background namespace var Node: PVirtualNode; begin Result := nil; if (ItemIndex > -1) and (ItemIndex < Items.Count) then begin Node := VETController.GetNodeByIndex(ItemIndex); //this is fast enough VETController.ValidateNamespace(Node, Result); end else if ItemIndex = -1 then VETController.ValidateNamespace(VETController.RootNode, Result); end; function TOLEListview.ListItemToNamespace(Item: TListItem; BackGndIfNIL: Boolean): TNamespace; var Node: PVirtualNode; begin Result := nil; if Assigned(Item) then begin Node := VETController.GetNodeByIndex(Item.Index); //this is fast enough VETController.ValidateNamespace(Node, Result); end else if BackGndIfNIL then VETController.ValidateNamespace(VETController.RootNode, Result); end; function TOLEListview.QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: Integer): HResult; begin Result := S_OK; if fEscapePressed then Result := DRAGDROP_S_CANCEL else if LButtonDown in MouseButtonState then begin if grfKeyState and MK_LBUTTON > 0 then // is the LButton flag set? Result := S_OK // Button is still down else Result := DRAGDROP_S_DROP; // Button has been released end else if RButtonDown in MouseButtonState then begin if grfKeyState and MK_RBUTTON > 0 then // is the RButton flag set? Result := S_OK // Button is still down else Result := DRAGDROP_S_DROP; // Button has been released end; end; procedure TOLEListview.WMLButtonDown(var Message: TWMLButtonDown); begin Include(FMouseButtonState, LButtonDown); inherited; end; procedure TOLEListview.WMLButtonUp(var Message: TWMLButtonUp); begin Exclude(FMouseButtonState, LButtonDown); inherited end; procedure TOLEListview.WMMouseMove(var Message: TWMMouseMove); var dwOkEffects, dwEffectResult: LongInt; DataObject: IDataObject; NSArray: TNamespaceArray; i: integer; Item: TListItem; Pt: TPoint; DoDrag: Boolean; Bitmap: TBitmap; DragSourceHelper: IDragSourceHelper; SHDragImage: TSHDragImage; TotalDragRect, R: TRect; RectArray: TRectArray; DummyDragObject: TDragObject; begin if MouseButtonState * [LButtonDown, RButtonDown] <> [] then begin DoDrag := False; Pt := SmallPointToPoint(Message.Pos); Item := GetItemAt(Pt.X, Pt.Y); if Assigned(Item) then DoDrag := (GetHitTestInfoAt(Pt.X, Pt.Y) * [htOnLabel, htOnIcon] <> []) and VETController.DoBeforeDrag(Item.Data, -1); if DoDrag and (SelCount > 0) then begin FDragging := DragDetectPlus(Parent.Handle, Pt); if Dragging then begin DummyDragObject := nil; // Fire OnStartDrag for the TOLEListview control DoStartDrag(DummyDragObject); // Fire VETController.OnStartDrag VETController.DoStartDrag(DummyDragObject); FDragItemIndex := Item.Index; Bitmap := TBitmap.Create; try SetLength(NSArray, SelCount); SetLength(RectArray, 1); Item := Selected; NSArray[0] := ListItemToNamespace(Item, False); RectArray[0] := GetLVItemRect(Item.Index, drSelectBounds); TotalDragRect := RectArray[0]; if Assigned(NSArray[0]) then begin i := 1; while (i < SelCount) do begin Item := GetNextItem(Item, sdAll, [isSelected]); NSArray[i] := ListItemToNamespace(Item, False); //Add visible items bounds to the RectArray R := GetLVItemRect(Item.Index, drSelectBounds); if PtInRect(ClientRect, R.TopLeft) then begin SetLength(RectArray, i + 1); RectArray[i] := R; //update TotalDragRect size if R.Left < TotalDragRect.Left then TotalDragRect.Left := R.Left; if R.Top < TotalDragRect.Top then TotalDragRect.Top := R.Top; if R.Right > TotalDragRect.Right then TotalDragRect.Right := R.Right; if R.Bottom > TotalDragRect.Bottom then TotalDragRect.Bottom := R.Bottom; end; Inc(i) end; DataObject := NSArray[0].DataObjectMulti(NSArray); if VETController.CanShowDragImage and Succeeded(CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER, IID_IDragSourceHelper, DragSourceHelper)) then begin FillChar(SHDragImage, SizeOf(SHDragImage), #0); Bitmap.Width := VETController.DragWidth; Bitmap.Height := VETController.DragHeight; CreateDragImage(TotalDragRect, RectArray, Bitmap); SHDragImage.sizeDragImage.cx := Bitmap.Width; SHDragImage.sizeDragImage.cy := Bitmap.Height; SHDragImage.ptOffset.X := SmallPointToPoint(Message.Pos).X - TotalDragRect.Left; SHDragImage.ptOffset.Y := SmallPointToPoint(Message.Pos).Y - TotalDragRect.Top; SHDragImage.ColorRef := ColorToRGB(Color); SHDragImage.hbmpDragImage := CopyImage(Bitmap.Handle, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG); if SHDragImage.hbmpDragImage <> 0 then if not Succeeded(DragSourceHelper.InitializeFromBitmap(SHDragImage, DataObject)) then DeleteObject(SHDragImage.hbmpDragImage); end; dwOkEffects := DROPEFFECT_COPY or DROPEFFECT_MOVE or DROPEFFECT_LINK; if not FDropped then DoDragDrop(DataObject, Self, dwOkEffects, dwEffectResult); MouseButtonState := []; end finally FDragging := False; Bitmap.Free; FDragItemIndex := -1; // Fire OnEndDrag for the TOLEListview control DoEndDrag(Self, Pt.X, Pt.Y); // Fire VETController.OnEndDrag VETController.DoEndDrag(Self, Pt.X, Pt.Y); end end end; end; inherited; end; procedure TOLEListview.WMRButtonDown(var Message: TWMRButtonDown); begin Include(FMouseButtonState, RButtonDown); inherited; end; procedure TOLEListview.WMRButtonUp(var Message: TWMRButtonUp); begin Exclude(FMouseButtonState, RButtonDown); inherited; end; procedure TOLEListview.WMTimer(var Message: TWMTimer); begin inherited; case Message.TimerID of SCROLL_DELAY_TIMER: begin KillTimer(Handle, FScrollDelayTimer); FScrollDelayTimer := 0; FScrollTimer := SetTimer(Handle, SCROLL_TIMER, VETController.AutoScrollInterval, FAutoScrollTimerStub); end; end end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TCustomVirtualExplorerListviewEx } constructor TCustomVirtualExplorerListviewEx.Create(AOwner: TComponent); begin inherited Create(AOwner); FImageLibrary := timNone; {$IFDEF USEGRAPHICEX} FImageLibrary := timGraphicEx; {$ELSE} {$IFDEF USEIMAGEEN} FImageLibrary := timImageEn; {$ELSE} {$IFDEF USEENVISION} FImageLibrary := timImageMagick; {$ELSE} {$IFDEF USEIMAGEMAGICK} FImageLibrary := timImageMagick; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} FInternalDataOffset := AllocateInternalDataArea(SizeOf(TThumbnailData)); FThumbsOptions := TThumbsOptions.Create(Self); FListview := TOLEListview.Create(Self); FListview.VETController := Self; FListview.OnAdvancedCustomDrawItem := LVOnAdvancedCustomDrawItem; FListview.SmallImages := VirtualSystemImageLists.SmallSysImages; FDummyIL := TImageList.Create(Self); FExtensionsList := TExtensionsList.Create; FShellExtractExtensionsList := TExtensionsList.Create; FExtensionsExclusionList := TExtensionsList.Create; FillExtensionsList; FVisible := true; FViewStyle := vsxReport; FAccumulatedChanging := false; end; destructor TCustomVirtualExplorerListviewEx.Destroy; begin {$IFDEF THREADEDICONS} if ThreadedImagesEnabled then ImageThreadManager.ClearPendingItems(Self, WM_VTSETICONINDEX, Malloc); {$ENDIF} //The Listview is automatically freed. //FreeAndNil(FListview); FDummyIL.Free; FExtensionsList.Free; FShellExtractExtensionsList.Free; FExtensionsExclusionList.Free; FThumbsOptions.Free; FThumbsOptions := nil; if Assigned(FThumbThread) then begin FThumbThread.Priority := tpNormal; //D6 has a Thread bug, we must set the priority to tpNormal before destroying FThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc); FThumbThread.Terminate; FThumbThread.SetEvent; FThumbThread.WaitFor; FreeAndNil(FThumbThread); end; inherited; end; function TCustomVirtualExplorerListviewEx.GetAnimateWndParent: TWinControl; begin if ViewStyle <> vsxReport then Result := ChildListview else Result := Self end; procedure TCustomVirtualExplorerListviewEx.CreateWnd; begin inherited; SyncOptions; end; procedure TCustomVirtualExplorerListviewEx.Loaded; begin inherited; SyncOptions; end; procedure TCustomVirtualExplorerListviewEx.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FListView) then FListView := nil; end; procedure TCustomVirtualExplorerListviewEx.RequestAlign; begin inherited; if IsValidChildListview then if (FListview.Align <> Align) or (FListview.Anchors <> Anchors) or (FListview.Constraints.MaxWidth <> Constraints.MaxWidth) or (FListview.Constraints.MaxHeight <> Constraints.MaxHeight) or (FListview.Constraints.MinWidth <> Constraints.MinWidth) or (FListview.Constraints.MinHeight <> Constraints.MinHeight) then SyncOptions; end; procedure TCustomVirtualExplorerListviewEx.SetParent(AParent: TWinControl); begin inherited; //This is not a compound component, a compound component is a container //with 1 or more controls in it. //The parent of the child VCL Listview is the Self.Parent, this is so //to retain all the properties of TExplorerListview, that means I don't have //to copy all these properties and you don't loose usability. if Assigned(FListview) and (AParent <> nil) then FListview.Parent := AParent; end; procedure TCustomVirtualExplorerListviewEx.SetZOrder(TopMost: Boolean); begin inherited; if (ViewStyle <> vsxReport) and Assigned(FListview) then FListview.SetZOrder(TopMost); end; function TCustomVirtualExplorerListviewEx.GetClientRect: TRect; begin if ViewStyle = vsxReport then Result := inherited GetClientRect else Result := FListview.GetClientRect; end; procedure TCustomVirtualExplorerListviewEx.CMShowHintChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.ShowHint := ShowHint; end; procedure TCustomVirtualExplorerListviewEx.CMBorderChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then begin FListview.BevelEdges := BevelEdges; FListview.BevelInner := BevelInner; FListview.BevelKind := BevelKind; FListview.BevelOuter := BevelOuter; FListview.BevelWidth := BevelWidth; FListview.BorderWidth := BorderWidth; end; end; procedure TCustomVirtualExplorerListviewEx.CMBidimodechanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.BiDiMode := BiDiMode; end; procedure TCustomVirtualExplorerListviewEx.CMCtl3DChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.Ctl3D := Ctl3D; end; procedure TCustomVirtualExplorerListviewEx.CMColorChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.Color := Color; end; procedure TCustomVirtualExplorerListviewEx.CMCursorChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.Cursor := Cursor; end; procedure TCustomVirtualExplorerListviewEx.CMEnabledchanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.Enabled := Enabled; end; procedure TCustomVirtualExplorerListviewEx.CMFontChanged(var Message: TMessage); begin inherited; if Assigned(FListview) then FListview.Font.Assign(Font); end; procedure TCustomVirtualExplorerListviewEx.WMEnumThreadFinished( var Msg: TMessage); begin inherited; if ViewStyle <> vsxReport then begin SyncItemsCount; SyncInvalidate; ChildListview.Cursor := crArrow end end; procedure TCustomVirtualExplorerListviewEx.WMEnumThreadStart(var Msg: TMessage); begin inherited; if ViewStyle <> vsxReport then begin ChildListview.HandleNeeded; ChildListview.Cursor := crHourGlass end end; procedure TCustomVirtualExplorerListviewEx.WMNCDestroy(var Message: TWMNCDestroy); begin if Assigned(FThumbThread) then FThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc); inherited; end; {$IFDEF THREADEDICONS} procedure TCustomVirtualExplorerListviewEx.WMVTSetIconIndex(var Msg: TWMVTSetIconIndex); var NS: TNamespace; R: TRect; begin if FViewStyle = vsxReport then inherited else begin try if ValidateNamespace(Msg.IconInfo.UserData, NS) then begin NS.SetIconIndexByThread(Msg.IconInfo.IconIndex, True); R := FListview.GetLVItemRect(Msg.IconInfo.Tag, drIcon); InvalidateRect(FListview.Handle, @R, False); end finally ImageThreadManager.ReleaseItem(Msg.IconInfo, Malloc) end end; end; {$ENDIF} procedure TCustomVirtualExplorerListviewEx.WMVLVExThumbThread(var Message: TMessage); var TD: PThumbnailData; ThumbThreadData: PThumbnailThreadData; NS: TNamespace; Node: PVirtualNode; Info: PVirtualThreadIconInfo; B: TBitmap; CI: TThumbsCacheItem; I: integer; begin Info := PVirtualThreadIconInfo(Message.wParam); if Assigned(Info) then begin try ThumbThreadData := PThumbnailThreadData(Info.UserData2); if Assigned(ThumbThreadData) then begin Node := Info.UserData; if (ThumbThreadData.State = tsValid) and ValidateNamespace(Node, NS) then begin if ValidateThumbnail(Node, TD) then begin TD.State := ThumbThreadData.State; if TD.Reloading then begin TD.Reloading := False; if ThumbsOptions.CacheOptions.FThumbsCache.Read(TD.CachePos, CI) then begin I := ThumbsOptions.CacheOptions.FThumbsCache.FScreenBuffer.IndexOf(NS.NameForParsing); if I > -1 then ThumbsOptions.CacheOptions.FThumbsCache.FScreenBuffer.Delete(I); CI.CompressedThumbImageStream := ThumbThreadData.CompressedStream; CI.FThumbImageStream.LoadFromStream(ThumbThreadData.MemStream); end; end else if Assigned(OnThumbsCacheItemAdd) then begin B := TBitmap.Create; try if ThumbThreadData.CompressedStream then ConvertJPGStreamToBitmap(ThumbThreadData.MemStream, B) else B.LoadFromStream(ThumbThreadData.MemStream); if DoThumbsCacheItemAdd(NS, B, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight) then TD.CachePos := ThumbsOptions.CacheOptions.FThumbsCache.Add(NS.NameForParsing, '', '', NS.LastWriteDateTime, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight, ThumbThreadData.CompressedStream, ThumbThreadData.MemStream); finally B.Free; end; end else TD.CachePos := ThumbsOptions.CacheOptions.FThumbsCache.Add(NS.NameForParsing, '', '', NS.LastWriteDateTime, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight, ThumbThreadData.CompressedStream, ThumbThreadData.MemStream); //redraw the item FListview.UpdateItems(Info.Tag, Info.Tag); //Update inmediatly, from ListView_RedrawItems windows help FListview.Update; end; end; end; finally ThumbThread.ReleaseItem(Info, Malloc); end; end; end; procedure TCustomVirtualExplorerListviewEx.DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); var Data: PThumbnailData; begin if ValidateThumbnail(Node, Data) then begin Data.CachePos := -1; Data.Reloading := False; Data.State := tsEmpty; end; inherited; end; procedure TCustomVirtualExplorerListviewEx.DoFreeNode(Node: PVirtualNode); begin FLastDeletedNode := Node; if Assigned(Node) and Assigned(FThumbThread) then FThumbThread.ClearPendingItem(Self, Node, WM_VLVEXTHUMBTHREAD, Malloc); inherited; end; function TCustomVirtualExplorerListviewEx.DoKeyAction(var CharCode: Word; var Shift: TShiftState): Boolean; begin Result := inherited DoKeyAction(CharCode, Shift); if Result then Case CharCode of Ord('I'), Ord('i'): if (ssCtrl in Shift) then InvertSelection(False); end; end; procedure TCustomVirtualExplorerListviewEx.Clear; begin // Clear the cache before we rebuild the tree, called by RebuildRootNamespace if Assigned(ThumbsOptions) then begin ThumbsOptions.CacheOptions.FThumbsCache.Clear; ThumbsOptions.CacheOptions.FThumbsCache.ThumbWidth := ThumbsOptions.Width; ThumbsOptions.CacheOptions.FThumbsCache.ThumbHeight := ThumbsOptions.Height; end; inherited end; procedure TCustomVirtualExplorerListviewEx.RebuildRootNamespace; var NS: TNamespace; C: TThumbsCache; begin //I was overriding DoRootRebuild to do this, but I need to do it here //because in TCustomVirtualExplorerTree.RebuildRootNamespace there's a call //to EndUpdate and this fires FListview.OwnerDataHint (via DoStructureChange, Accumulated event). if (RebuildRootNamespaceCount = 0) and not (csLoading in ComponentState) and Assigned(RootFolderNamespace) and Active then begin FListview.OwnerDataPause := True; //avoid generating data try inherited; // We're clear to rebuild the tree, it will call Clear FListview.Items.BeginUpdate; try ThumbsOptions.CacheOptions.BrowsingFolder := RootFolderNamespace.NameForParsing; NS := RootFolderNamespace; if Assigned(ThumbsOptions.CacheOptions) and ThumbsOptions.CacheOptions.AutoLoad and Assigned(NS) and NS.Folder and NS.FileSystem then begin ThumbsOptions.CacheOptions.Load; C := ThumbsOptions.CacheOptions.FThumbsCache; if ThumbsOptions.CacheOptions.AdjustIconSize and C.LoadedFromFile and ((ThumbsOptions.Width <> C.ThumbWidth) or (ThumbsOptions.Height <> C.ThumbHeight)) then begin ThumbsThreadPause := True; try ThumbsOptions.Width := C.ThumbWidth; ThumbsOptions.Height := C.ThumbHeight; finally ThumbsThreadPause := False; end; end; end; SyncItemsCount; FListview.Selected := nil; finally FListview.Items.EndUpdate; end; finally FListview.OwnerDataPause := False; FListview.UpdateArrangement; if ThumbsOptions.LoadAllAtOnce then FListview.FetchThumbs(0, FListview.Items.Count - 1); if FListview.items.count > 0 then FListview.ItemFocused := FListview.Items[0]; end; end; FlushSearchCache; end; procedure TCustomVirtualExplorerListviewEx.DoRootChanging( const NewRoot: TRootFolder; Namespace: TNamespace; var Allow: Boolean); var NS: TNamespace; begin if (RebuildRootNamespaceCount = 0) and not (csLoading in ComponentState) and Active then FListview.OwnerDataPause := True; //avoid generating data FlushSearchCache; inherited DoRootChanging(NewRoot, Namespace, Allow); if not Allow and FListview.OwnerDataPause then FListview.OwnerDataPause := False; if Allow and not (csLoading in Componentstate) and Assigned(ThumbsOptions) and Assigned(ThumbsOptions.CacheOptions) then begin NS := RootFolderNamespace; if ThumbsOptions.CacheOptions.AutoSave and Assigned(NS) and NS.Folder and NS.FileSystem then if (ThumbsOptions.CacheOptions.StorageType = tcsCentral) or not NS.ReadOnly then ThumbsOptions.CacheOptions.Save; end; end; procedure TCustomVirtualExplorerListviewEx.DoStructureChange(Node: PVirtualNode; Reason: TChangeReason); begin FlushSearchCache; inherited; if FViewStyle <> vsxReport then begin Case Reason of crChildAdded: begin SyncSelectedItems; SyncItemsCount; end; crChildDeleted: begin SyncSelectedItems; SyncItemsCount; // Don't catch this when the RootNode is deleted (happens when changing dir) if Node <> RootNode then begin // Focus the last item if required if (FListview.ItemFocused = nil) and (Flistview.Items.Count > 0) then FListview.ItemFocused := FListview.Items[Flistview.Items.Count - 1]; if ViewStyle <> vsxReport then SyncInvalidate; end; end; crAccumulated: begin SyncSelectedItems; if FAccumulatedChanging then begin // Take a look at ReReadAndRefreshNode SyncItemsCount; // Focus the last item if required if (FListview.ItemFocused = nil) and (Flistview.Items.Count > 0) then FListview.ItemFocused := FListview.Items[Flistview.Items.Count - 1]; if ViewStyle <> vsxReport then SyncInvalidate; end; end; end; end; end; procedure TCustomVirtualExplorerListviewEx.ReReadAndRefreshNode(Node: PVirtualNode; SortNode: Boolean); begin // This method is called by WM_SHELLNOTIFY and it's responsible for updating // the nodes, looking if they were added or deleted. // The nodes are updated inside a BeginUpdate/EndUpdate block, when EndUpdate // is reached DoStructureChange (with crAccumulated) is called once. // We need a flag so DoStructureChange knows who's calling it. FAccumulatedChanging := true; inherited; FAccumulatedChanging := false; end; procedure TCustomVirtualExplorerListviewEx.DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); var NS: TNamespace; I: integer; begin if ValidateNamespace(Node, NS) then if ThumbsOptions.Highlight = thMultipleColors then begin I := IsImageFileIndex(NS.NameForParsing); if I > -1 then if FExtensionsList.Colors[I] <> clNone then begin Canvas.Brush.Color := FExtensionsList.Colors[I]; Canvas.FillRect(CellRect); end; end else if ThumbsOptions.Highlight = thSingleColor then if IsImageFile(NS.NameForParsing) then begin Canvas.Brush.Color := ThumbsOptions.HighlightColor; Canvas.FillRect(CellRect); end; inherited; end; function TCustomVirtualExplorerListviewEx.InternalData(Node: PVirtualNode): Pointer; begin if Node = nil then Result := nil else Result := PChar(Node) + FInternalDataOffset; end; function TCustomVirtualExplorerListviewEx.IsAnyEditing: Boolean; begin Result := (inherited IsAnyEditing) or (IsValidChildListview and FListview.IsEditing); end; function TCustomVirtualExplorerListviewEx.GetNodeByIndex(Index: Cardinal): PVirtualNode; begin Result := GetChildByIndex(RootNode, Index, FSearchCache); if Result = FLastDeletedNode then Result := nil; end; procedure TCustomVirtualExplorerListviewEx.FlushSearchCache; begin FSearchCache := nil; FLastDeletedNode := nil; end; function TCustomVirtualExplorerListviewEx.ValidateThumbnail(Node: PVirtualNode; var ThumbData: PThumbnailData): Boolean; begin Result := False; ThumbData := nil; if Assigned(Node) then begin ThumbData := InternalData(Node); Result := Assigned(ThumbData); end end; function TCustomVirtualExplorerListviewEx.ValidateListItem(Node: PVirtualNode; var ListItem: TListItem): Boolean; var C: Cardinal; begin Result := False; ListItem := nil; if Assigned(Node) and Assigned(FListview) then begin if not (vsInitialized in Node.States) then InitNode(Node); C := FListview.Items.Count; if (C > 0) and (Node.Index < C) then ListItem := FListview.Items[Node.Index]; Result := Assigned(ListItem); end end; function TCustomVirtualExplorerListviewEx.IsValidChildListview: boolean; begin Result := Assigned(FListview) and FListview.HandleAllocated; end; procedure TCustomVirtualExplorerListviewEx.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; if IsValidChildListview then if not EqualRect(FListview.BoundsRect, Rect(ALeft, ATop, AWidth, AHeight)) then FListview.SetBounds(ALeft, ATop, AWidth, AHeight); end; function TCustomVirtualExplorerListviewEx.Focused: Boolean; begin if (ViewStyle <> vsxReport) and IsValidChildListview then Result := FListview.Focused else Result := inherited Focused; end; procedure TCustomVirtualExplorerListviewEx.SetFocus; begin if Parent.Visible then begin if ViewStyle = vsxReport then inherited else if IsValidChildListview then FListview.SetFocus; end; end; function TCustomVirtualExplorerListviewEx.BrowseToByPIDL(APIDL: PItemIDList; ExpandTarget, SelectTarget, SetFocusToVET, CollapseAllFirst: Boolean; ShowAllSiblings: Boolean = True): Boolean; begin Result := inherited BrowseToByPIDL(APIDL, ExpandTarget, SelectTarget, SetFocusToVET, CollapseAllFirst, ShowAllSiblings); if FViewStyle <> vsxReport then SyncSelectedItems; end; procedure TCustomVirtualExplorerListviewEx.CopyToClipBoard; begin if FViewStyle <> vsxReport then SyncSelectedItems(false); inherited; end; procedure TCustomVirtualExplorerListviewEx.CutToClipBoard; begin if FViewStyle <> vsxReport then SyncSelectedItems(false); inherited; end; function TCustomVirtualExplorerListviewEx.PasteFromClipboard: Boolean; begin if FViewStyle <> vsxReport then SyncSelectedItems(false); Result := inherited PasteFromClipboard; end; procedure TCustomVirtualExplorerListviewEx.SelectedFilesDelete; begin if FViewStyle <> vsxReport then SyncSelectedItems(false); inherited; end; procedure TCustomVirtualExplorerListviewEx.SelectedFilesPaste(AllowMultipleTargets: Boolean); begin if not (toVETReadOnly in TreeOptions.VETMiscOptions) then begin if FViewStyle <> vsxReport then SyncSelectedItems(false); inherited; end; end; procedure TCustomVirtualExplorerListviewEx.SelectedFilesShowProperties; begin if FViewStyle <> vsxReport then SyncSelectedItems(false); inherited; end; function TCustomVirtualExplorerListviewEx.EditNode(Node: PVirtualNode; Column: TColumnIndex): Boolean; begin Result := false; if FViewStyle = vsxReport then Result := inherited EditNode(Node, Column) else begin if Assigned(Node) and not (vsDisabled in Node.States) and not (toReadOnly in TreeOptions.MiscOptions) then begin if not Focused then SetFocus; FocusedNode := Node; if not (vsInitialized in Node.States) then InitNode(Node); SyncSelectedItems; Result := FListview.Items[Node.index].EditCaption; end; end; end; function TCustomVirtualExplorerListviewEx.EditFile(APath: WideString): Boolean; // Selects a file to edit it. // APath parameter can be a filename or a full pathname to a file. // If APath is a filename it searches the file in the current directory. // If APath is a full pathname it changes the current directory to the APath // dir and searches the file. var Node: PVirtualNode; D: WideString; begin Result := False; if Pos(':', APath) = 0 then // It's a file, include the current directory APath := IncludeTrailingBackslashW(RootFolderNamespace.NameForParsing) + APath else begin // Browse to the directory if the root is incorrect D := ExtractFileDirW(APath); if not SpCompareText(RootFolderNamespace.NameForParsing, D) then BrowseTo(D); end; Node := FindNode(APath); if Assigned(Node) then begin ClearSelection; Selected[Node] := True; EditNode(Node, 0); // EditNode calls SyncSelected Result := True; end; end; function TCustomVirtualExplorerListviewEx.InvalidateNode(Node: PVirtualNode): TRect; var L: TListItem; R: TRect; begin Result := inherited InvalidateNode(Node); if Assigned(Node) and (Node.CheckType <> VirtualTrees.ctNone) and not (csDesigning in ComponentState) and HandleAllocated and IsValidChildListview and (ViewStyle <> vsxReport) and ValidateListItem(Node, L) then begin R := L.DisplayRect(drIcon); InvalidateRect(FListview.Handle, @R, True); end; end; procedure TCustomVirtualExplorerListviewEx.SyncInvalidate; begin if ViewStyle = vsxReport then Invalidate else if HandleAllocated and (ViewStyle <> vsxReport) and IsValidChildListview and not (csDesigning in ComponentState) then FListview.Invalidate; end; procedure TCustomVirtualExplorerListviewEx.SyncItemsCount; begin if HandleAllocated then FListview.Items.Count := RootNode.ChildCount; end; procedure TCustomVirtualExplorerListviewEx.SyncOptions; begin if Assigned(FListview) then begin FListview.SetBounds(left, top, width, height); FListview.Align := Align; FListview.Anchors := Anchors; FListview.Constraints.Assign(Constraints); FListview.ReadOnly := not (toEditable in TreeOptions.MiscOptions); FListview.MultiSelect := toMultiSelect in TreeOptions.SelectionOptions; FListview.PopupMenu := PopupMenu; FListview.BorderStyle := BorderStyle; end; end; procedure TCustomVirtualExplorerListviewEx.SyncSelectedItems(UpdateChildListview: Boolean = True); var Node: PVirtualNode; LItem: TListItem; begin if not FListview.HandleAllocated then Exit; //Sync focused and selected items if UpdateChildListview then begin //Clear the selection, but pause automatic selection sync of TSyncListView.CNNotify FListview.FSelectionPause := True; //pause the selection try //Long captions items doen't get refreshed, we can't use FListview.Selected := nil; LItem := FListview.Selected; while Assigned(LItem) do begin LItem.Selected := False; FListview.UpdateItems(LItem.index, LItem.Index); LItem := FListview.GetNextItem(LItem, sdAll, [isSelected]); end; finally FListview.FSelectionPause := False; //restore end; Node := GetFirstSelected; while Assigned(Node) do begin FListview.Items[Node.Index].Selected := True; Node := GetNextSelected(Node); end; if Assigned(FocusedNode) then begin LItem := FListview.ItemFocused; if Assigned(LItem) then FListview.UpdateItems(LItem.index, LItem.Index); FListview.Items[FocusedNode.Index].Focused := True; FListview.Items[FocusedNode.Index].MakeVisible(False); end; end else begin ClearSelection; LItem := FListview.Selected; while Assigned(LItem) do begin Node := PVirtualNode(LItem.Data); if Assigned(Node) then Selected[Node] := true; LItem := FListview.GetNextItem(LItem, sdAll, [isSelected]); end; if Assigned(FListview.ItemFocused) then FocusedNode := PVirtualNode(FListview.ItemFocused.Data); end; end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemAdd(NS: TNamespace; Thumbnail: TBitmap; ImageWidth, ImageHeight: Integer): Boolean; begin Result := True; if Assigned(OnThumbsCacheItemAdd) then FOnThumbsCacheItemAdd(Self, NS, Thumbnail, ImageWidth, ImageHeight, Result); end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemLoad(NS: TNamespace; var CacheItem: TThumbsCacheItem): Boolean; begin // Update the cache entry if the file was changed Result := NS.LastWriteDateTime = CacheItem.FileDateTime; if Assigned(OnThumbsCacheItemLoad) then FOnThumbsCacheItemLoad(Self, NS, CacheItem, Result); CacheItem.FileDateTime := NS.LastWriteDateTime; end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemRead(Filename: WideString; Thumbnail: TBitmap): Boolean; begin Result := True; if Assigned(OnThumbsCacheItemRead) then FOnThumbsCacheItemRead(Self, Filename, Thumbnail, Result); end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemProcessing(NS: TNamespace; Thumbnail: TBitmap; var ImageWidth, ImageHeight: integer): Boolean; begin Result := True; if Assigned(OnThumbsCacheItemProcessing) then FOnThumbsCacheItemProcessing(Self, NS, Thumbnail, ImageWidth, ImageHeight, Result); end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheLoad(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; begin Result := True; if Assigned(FOnThumbsCacheLoad) then FOnThumbsCacheLoad(Sender, CacheFilePath, Comments, Result); end; function TCustomVirtualExplorerListviewEx.DoThumbsCacheSave(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; begin Result := True; if Assigned(FOnThumbsCacheSave) then FOnThumbsCacheSave(Sender, CacheFilePath, Comments, Result); end; function TCustomVirtualExplorerListviewEx.GetDetailsString(Node: PVirtualNode; ThumbFormatting: Boolean = True): WideString; var NS: TNamespace; TD: PThumbnailData; CI: TThumbsCacheItem; S, K, D: WideString; I: integer; begin //When ThumbFormatting is true it returns the minimum info available, //mantaining the line order. Result := ''; if ValidateNamespace(Node, NS) then begin //Image size S := ''; if ValidateThumbnail(Node, TD) and (TD.State = tsValid) and (TD.CachePos > -1) then begin if ThumbsOptions.CacheOptions.FThumbsCache.Read(TD.CachePos, CI) and (CI.ImageWidth > 0) and (CI.ImageHeight > 0) then S := Format('%dx%d', [CI.ImageWidth, CI.ImageHeight]) end; //File size if not NS.Folder then K := NS.SizeOfFileKB else K := ''; //Modified date D := NS.LastWriteTime; if D <> '' then begin //Delete the seconds from the LastWriteTime for I := Length(D) downto 0 do if D[I] = ':' then break; if I > 0 then Delete(D, I, Length(D)); end; if ThumbFormatting then begin Result := Format('%s' + #13 + '%s' + #13 + '%s', [S, K, D]); if Result = #13 + #13 then Result := ''; end else begin if NS.NameInFolder <> '' then Result := Result + NS.NameInFolder; if S <> '' then Result := Result + #13 + S; if K <> '' then Result := Result + #13 + K; if D <> '' then Result := Result + #13 + D; end; end; end; function TCustomVirtualExplorerListviewEx.DoThumbsGetDetails(Node: PVirtualNode; HintDetails: Boolean): WideString; begin Result := GetDetailsString(Node, not HintDetails); if Assigned(FOnThumbsGetDetails) then FOnThumbsGetDetails(Self, Node, HintDetails, Result); end; procedure TCustomVirtualExplorerListviewEx.DoThumbsDrawBefore(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); begin if Assigned(OnThumbsDrawBefore) then FOnThumbsDrawBefore(Self, ACanvas, ListItem, ThumbData, AImageRect, ADetailsRect, DefaultDraw); end; procedure TCustomVirtualExplorerListviewEx.DoThumbsDrawAfter(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); begin if Assigned(OnThumbsDrawAfter) then FOnThumbsDrawAfter(Self, ACanvas, ListItem, ThumbData, AImageRect, ADetailsRect, DefaultDraw); end; function TCustomVirtualExplorerListviewEx.DoThumbsDrawHint(HintBitmap: TBitmap; Node: PVirtualNode): Boolean; begin Result := true; if Assigned(FOnThumbsDrawHint) then FOnThumbsDrawHint(Self, HintBitmap, Node, Result); end; procedure TCustomVirtualExplorerListviewEx.DrawThumbBG(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect); begin if (ThumbData.State = tsValid) or (ThumbsOptions.BorderOnFiles) then begin if not (ThumbsOptions.Border in [tbWindowed, tbFit]) and Item.Selected and (not FListview.IsEditing) then begin if FListview.Focused then ACanvas.Brush.Color := Colors.FocusedSelectionColor else ACanvas.Brush.Color := Colors.UnFocusedSelectionColor; end; ACanvas.Fillrect(R); end; end; procedure DrawFocusRect2(ACanvas: TCanvas; const R: TRect); var DC: HDC; C1, C2: TColor; begin DC := ACanvas.Handle; C1 := SetTextColor(DC, clBlack); C2 := SetBkColor(DC, clWhite); Windows.DrawFocusRect(DC, R); SetTextColor(DC, C1); SetBkColor(DC, C2); end; procedure TCustomVirtualExplorerListviewEx.DrawThumbFocus(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect); begin if (ThumbData.State = tsValid) or (ThumbsOptions.BorderOnFiles) then begin ACanvas.Brush.Style := bsSolid; case ThumbsOptions.Border of tbWindowed: DrawThumbBorder(ACanvas, ThumbsOptions.Border, R, Item.Selected); tbFit: if ThumbData.State = tsValid then DrawThumbBorder(ACanvas, ThumbsOptions.Border, R, Item.Selected); else if FListview.Focused and Item.Focused then DrawFocusRect2(ACanvas, R) else DrawThumbBorder(ACanvas, ThumbsOptions.Border, R, Item.Selected); end; end; end; procedure DrawImageListIcon(ACanvas: TCanvas; ImgL: TImageList; X, Y: integer; LV: TCustomVirtualExplorerListviewEx; Item: TListItem); var ForeColor, Style: Cardinal; begin if LV.ChildListview.IsItemGhosted(Item) then ForeColor := ColorToRGB(LV.ChildListview.Color) else if ((LV.ViewStyle <> vsxThumbs) or not LV.ThumbsOptions.BorderOnFiles) and LV.ChildListview.Focused and Item.Selected then ForeColor := ColorToRGB(clHighlight) else ForeColor := CLR_NONE; if ForeColor = CLR_NONE then Style := ILD_TRANSPARENT else Style := ILD_TRANSPARENT or ILD_BLEND; if Item.OverlayIndex > -1 then Style := Style or ILD_OVERLAYMASK and Cardinal(IndexToOverlayMask(Item.OverlayIndex + 1)); ImageList_DrawEx(ImgL.Handle, Item.ImageIndex, ACanvas.Handle, X, Y, 0, 0, CLR_NONE, ForeColor, Style); end; procedure TCustomVirtualExplorerListviewEx.DrawIcon(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; RThumb, RDetails: TRect; var RDestination: TRect); var X, Y: integer; IL: TImageList; CacheThumb: TBitmap; S: WideString; NS: TNamespace; begin RDestination := Rect(0, 0, 0, 0); //Paint the Thumbs details if ThumbsOptions.Details and (ViewStyle = vsxThumbs) then begin S := DoThumbsGetDetails(PVirtualNode(Item.Data), false); if S <> '' then begin ACanvas.Brush.Style := bsClear; ACanvas.Font.Size := 8; if FListview.Focused and Item.selected then begin ACanvas.Font.Color := clHighlightText; ACanvas.Brush.Color := clHighlight; end; if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(ACanvas.Handle, PChar(AnsiString(S)), -1, RDetails, DT_CENTER) else Windows.DrawTextW(ACanvas.Handle, PWideChar(S), -1, RDetails, DT_CENTER); end; end; //Paint the Thumbs or Icons if (ViewStyle = vsxThumbs) and (ThumbData.State = tsValid) then begin CacheThumb := TBitmap.Create; try if (Assigned(OnThumbsCacheItemRead) and ValidateNamespace(PVirtualNode(Item.Data), NS) and not DoThumbsCacheItemRead(NS.NameForParsing, CacheThumb)) or ((ThumbData.CachePos > -1) and ThumbsOptions.CacheOptions.FThumbsCache.Read(ThumbData.CachePos, CacheThumb)) then begin X := RThumb.left + (RThumb.right - RThumb.left - CacheThumb.Width) div 2; Y := RThumb.top + (RThumb.bottom - RThumb.top - CacheThumb.Height) div 2; ACanvas.Draw(X, Y, CacheThumb); RDestination := Bounds(X, Y, CacheThumb.Width, CacheThumb.Height); end; finally CacheThumb.Free; end; end else begin Case ViewStyle of vsxThumbs: if ThumbsOptions.ShowXLIcons and (ThumbsOptions.Width >= 48) and (ThumbsOptions.Height >= 48) then IL := VirtualSystemImageLists.ExtraLargeSysImages else IL := VirtualSystemImageLists.LargeSysImages; vsxIcon: IL := VirtualSystemImageLists.LargeSysImages else IL := VirtualSystemImageLists.SmallSysImages; end; X := RThumb.left + (RThumb.right - RThumb.left - IL.Width) div 2; Y := RThumb.top + (RThumb.bottom - RThumb.top - IL.Height) div 2; DrawImageListIcon(ACanvas, IL, X, Y, Self, Item); RDestination := Bounds(X, Y, IL.Width, IL.Height); end; end; procedure TCustomVirtualExplorerListviewEx.LVOnAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); var ThumbDefaultDraw: boolean; RIcon, R, RThumb, RDetails, RThumbDestination: TRect; Node: PVirtualNode; ThumbData: PThumbnailData; PaintInfo: TVTPaintInfo; B: TBitmap; NS: TNamespace; I: Integer; WS: WideString; begin if (ViewStyle = vsxReport) or (not Assigned(FListview)) or (FListview.OwnerDataPause) or (FListview.Items.Count = 0) or (Item = nil) or (Item.Index < 0) or (Item.Index >= FListview.Items.Count) then Exit; case Stage of cdPrePaint: if not Item.Selected then begin Node := PVirtualNode(Item.Data); if ValidateNamespace(Node, NS) then begin Case ThumbsOptions.Highlight of thSingleColor: if IsImageFile(NS.NameForParsing) then Sender.Canvas.Brush.Color := ThumbsOptions.HighlightColor; thMultipleColors: begin I := IsImageFileIndex(NS.NameForParsing); if I > -1 then if FExtensionsList.Colors[I] <> clNone then Sender.Canvas.Brush.Color := FExtensionsList.Colors[I]; end; end; if not (toNoUseVETColorsProp in TreeOptions.VETFolderOptions) then begin if NS.Compressed then Sender.Canvas.Font.Color := VETColors.CompressedTextColor else if NS.Folder then Sender.Canvas.Font.Color := VETColors.FolderTextColor else Sender.Canvas.Font.Color := VETColors.FileTextColor; end; if Assigned(OnPaintText) then OnPaintText(Self, Sender.Canvas, Node, 0, ttNormal); end; end; cdPostPaint: begin //In a normal ViewStyle only draw when there's an overlay icon if ViewStyle in [vsxIcon, vsxSmallIcon, vsxList] then if not (FListview.IsItemGhosted(Item) or (Item.OverlayIndex > -1)) then Exit; //Do the drawing in a bitmap buffer B := TBitmap.Create; B.Canvas.Lock; try RThumbDestination := Rect(0, 0, 0, 0); RIcon := FListview.GetLVItemRect(Item.index, drIcon); R := Rect(0, 0, RIcon.Right - RIcon.Left, RIcon.Bottom - RIcon.Top); InitBitmap(B, R.Right, R.Bottom, Self.Color); if FListview.IsBackgroundValid then B.Canvas.CopyRect(R, Sender.Canvas, RIcon); B.Canvas.Brush.Color := Sender.Canvas.Brush.Color; if ViewStyle = vsxThumbs then begin Node := PVirtualNode(Item.Data); if ValidateThumbnail(Node, ThumbData) then begin DrawThumbBG(B.Canvas, Item, ThumbData, R); if ThumbsOptions.Details then begin RThumb := Rect(R.Left, R.Top, R.Right, R.Bottom - ThumbsOptions.DetailsHeight); RDetails := Rect(R.Left, R.Bottom - ThumbsOptions.DetailsHeight, R.Right, R.Bottom); end else begin RThumb := R; RDetails := Rect(0, 0, 0, 0); end; ThumbDefaultDraw := true; DoThumbsDrawBefore(B.Canvas, Item, ThumbData, RThumb, RDetails, ThumbDefaultDraw); //if ThumbDefaultDraw and (ThumbData.State <> tsProcessing) then //this will increase the rendering speed, but it looks odd if ThumbDefaultDraw then begin DrawIcon(B.Canvas, Item, ThumbData, RThumb, RDetails, RThumbDestination); // Draw the checkbox if (toCheckSupport in TreeOptions.MiscOptions) and (Node.CheckType <> VirtualTrees.ctNone) then begin PaintInfo.Node := Node; PaintInfo.Canvas := B.Canvas; PaintInfo.ImageInfo[iiCheck].Index := GetCheckImage(Node); PaintInfo.ImageInfo[iiCheck].XPos := 0; PaintInfo.ImageInfo[iiCheck].YPos := 0; PaintCheckImage(PaintInfo); end; end; ThumbDefaultDraw := true; DoThumbsDrawAfter(B.Canvas, Item, ThumbData, RThumb, RDetails, ThumbDefaultDraw); if ThumbDefaultDraw then begin if ThumbsOptions.ShowSmallIcon and (ThumbData.State = tsValid) then DrawImageListIcon(B.Canvas, VirtualSystemImageLists.SmallSysImages, (RThumb.right - RThumb.left - VirtualSystemImageLists.SmallSysImages.Width) - 2, 2, Self, Item); if ThumbsOptions.Border = tbFit then DrawThumbFocus(B.Canvas, Item, ThumbData, RThumbDestination) else DrawThumbFocus(B.Canvas, Item, ThumbData, R); end; end; end else begin //Listviews in virtual mode doesn't draw overlay images, from: //http://groups.google.com/groups?hl=en&selm=7gftob%24aq4%40forums.borland.com DrawIcon(B.Canvas, Item, nil, R, R, RThumbDestination); end; Sender.Canvas.Lock; try // The TListview Canvas is very delicate // We must set the font color for the default focus painting if ColorToRGB(Sender.Canvas.Brush.Color) = 0 then Sender.Canvas.Font.Color := clWhite else Sender.Canvas.Font.Color := clWindowText; Sender.Canvas.Draw(RIcon.Left, RIcon.Top, B); if not FListview.IsEditing and Item.Selected then begin R := FListview.GetLVItemRect(Item.index, drLabel); if FListview.Focused then begin Sender.Canvas.Brush.Color := Colors.FocusedSelectionColor; Sender.Canvas.Font.Color := clHighlightText; end else Sender.Canvas.Brush.Color := Colors.UnFocusedSelectionColor; Sender.Canvas.FillRect(R); WS := FListview.GetItemCaption(Item.Index); if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(Sender.Canvas.Handle, PChar(AnsiString(WS)), -1, R, DT_CENTER) else Windows.DrawTextW(Sender.Canvas.Handle, PWideChar(WS), -1, R, DT_CENTER or DT_WORDBREAK or DT_EDITCONTROL); if FListview.Focused and Item.Focused then DrawFocusRect2(Sender.Canvas, R); end; finally Sender.Canvas.UnLock; end; finally B.Canvas.UnLock; B.Free; end; end; end; end; function TCustomVirtualExplorerListviewEx.GetThumbDrawingBounds(IncludeThumbDetails, IncludeBorderSize: Boolean): TRect; begin // Obtains the REAL Thumbnail drawing Bounds Rect // It's like Item.displayrect(dricon) if IncludeBorderSize then Result := Rect(0, 0, ThumbsOptions.Width + ThumbsOptions.BorderSize * 2, ThumbsOptions.Height + ThumbsOptions.BorderSize * 2) else Result := Rect(0, 0, ThumbsOptions.Width, ThumbsOptions.Height); if IncludeThumbDetails and ThumbsOptions.Details then Result.Bottom := Result.Bottom + ThumbsOptions.DetailsHeight; end; function TCustomVirtualExplorerListviewEx.IsImageFileIndex(FileName: WideString): integer; var Ext: WideString; begin Result := -1; Ext := ExtractFileExtW(FileName); if ExtensionsExclusionList.IndexOf(Ext) < 0 then begin Result := ExtensionsList.IndexOf(Ext); if Result < 0 then Result := ShellExtractExtensionsList.IndexOf(Ext); end; end; function TCustomVirtualExplorerListviewEx.IsImageFile(FileName: WideString): Boolean; begin Result := IsImageFileIndex(FileName) > -1; end; function TCustomVirtualExplorerListviewEx.IsImageFile(Node: PVirtualNode): TNamespace; begin // Returns the namespace if it's an Image file Result := nil; if ValidateNamespace(Node, Result) and Result.FileSystem and not Result.Folder then begin if not IsImageFile(Result.NameForParsing) then Result := nil; end else Result := nil; end; procedure TCustomVirtualExplorerListviewEx.ResetThumbSpacing; var R: TRect; W, H: integer; begin //The cx and cy parameters of ListView_SetIconSpacing are relative to the //upper-left corner of an icon. //Therefore, to set spacing between icons that do not overlap, the cx or cy //values must include the size of the icon + the amount of empty space //desired between icons. Values that do not include the width of the icon //will result in overlaps. //When defining the icon spacing, cx and cy must set to 4 or larger. //Smaller values will not yield the desired layout. //To reset cx and cy to the default spacing, set the lParam value to -1. //i.e SendMessage(FListview.Handle, LVM_SETICONSPACING, 0, -1); if ViewStyle = vsxThumbs then begin R := GetThumbDrawingBounds(true, true); W := R.Right + ThumbsOptions.SpaceWidth; H := R.Bottom + ThumbsOptions.SpaceHeight; ListView_SetIconSpacing(FListview.Handle, W, H); FListview.UpdateArrangement; if Assigned(FListview.ItemFocused) then FListview.ItemFocused.MakeVisible(false); end; end; procedure TCustomVirtualExplorerListviewEx.ResetThumbThread; var N: PVirtualNode; TD: PThumbnailData; begin if FThumbsThreadPause then Exit; //Reset the thread properties and reload ThumbThread.QueryList.LockList; try ThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc); ThumbThread.ResetThumbOptions; ThumbsOptions.CacheOptions.FThumbsCache.Clear; ThumbsOptions.CacheOptions.FThumbsCache.ThumbWidth := ThumbsOptions.Width; ThumbsOptions.CacheOptions.FThumbsCache.ThumbHeight := ThumbsOptions.Height; //Iterate through the nodes and reset the thumb state of valid items N := RootNode.FirstChild; while Assigned(N) do begin if (vsInitialized in N.States) and ValidateThumbnail(N, TD) then if IsThumbnailActive(TD.State) then begin TD.CachePos := -1; TD.Reloading := False; TD.State := tsEmpty; end; N := N.NextSibling; end; finally ThumbThread.QueryList.UnlockList; end; if ViewStyle = vsxThumbs then SyncInvalidate; end; procedure TCustomVirtualExplorerListviewEx.SetViewStyle(const Value: TViewStyleEx); var PrevFocused: boolean; begin if FViewStyle <> Value then begin SyncOptions; FListview.Items.BeginUpdate; try if not (csDesigning in ComponentState) and FVisible and ((FViewStyle = vsxReport) and (Value <> vsxReport)) or ((FViewStyle <> vsxReport) and (Value = vsxReport)) then begin PrevFocused := Focused; Parent.DisableAlign; try FListview.Visible := Value <> vsxReport; inherited Visible := not FListview.Visible; if FListview.Visible then //force hiding SetWindowPos(Self.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE + SWP_NOMOVE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_HIDEWINDOW); finally Parent.EnableAlign; end; //Sync focused and selected items if (FViewStyle = vsxReport) and (Value <> vsxReport) then begin SyncItemsCount; SyncSelectedItems(true); end else if (FViewStyle <> vsxReport) and (Value = vsxReport) then SyncSelectedItems(false); //Sync the focus if PrevFocused then begin FViewStyle := Value; SetFocus; end; end; FViewStyle := Value; //Set the child Listview.ViewStyle, this might look simple but the //icon spacing is incorrect if you don't force it. //To force correct spacing you should: // - Make sure the Listview is visible // - Set the correct icon spacing //I haven't found a better way, if you do just let me know. FListview.LargeImages := nil; Case Value of vsxThumbs: begin ResetThumbImageList(false); FListview.LargeImages := FDummyIL; FListview.ViewStyle := vsIcon; ResetThumbSpacing; //reset the spacing after vsIcon is setted end; vsxIcon: begin FListview.LargeImages := VirtualSystemImageLists.LargeSysImages; FListview.ViewStyle := vsIcon; ListView_SetIconSpacing(FListview.Handle, GetSystemMetrics(SM_CXICONSPACING), GetSystemMetrics(SM_CYICONSPACING)); end; vsxList: FListview.ViewStyle := vsList; vsxSmallIcon: FListview.ViewStyle := vsSmallIcon; end; FListview.UpdateSingleLineMaxChars; finally FListview.Items.EndUpdate; if Value <> vsxThumbs then FListview.UpdateArrangement; end; end; end; procedure TCustomVirtualExplorerListviewEx.SetVisible(const Value: boolean); begin if FVisible <> Value then begin FListview.Visible := Value and (FViewStyle <> vsxReport); inherited Visible := Value and (not FListview.Visible); FVisible := Value; end; end; function TCustomVirtualExplorerListviewEx.GetThumbThread: TThumbThread; begin if not Assigned(FThumbThread) then FThumbThread := GetThumbThreadClass.Create(Self); Result := FThumbThread; end; function TCustomVirtualExplorerListviewEx.GetThumbThreadClass: TThumbThreadClass; begin Result := nil; if Assigned(OnThumbThreadClass) then FOnThumbThreadClass(Self, Result); if not Assigned(Result) then Result := TThumbThread; end; procedure TCustomVirtualExplorerListviewEx.SetThumbThreadClassEvent(const Value: TThumbThreadClassEvent); begin if Assigned(FThumbThread) then begin FThumbThread.Priority := tpNormal; //D6 has a Thread bug, we must set the priority to tpNormal before destroying ResetThumbThread; FThumbThread.Terminate; FThumbThread.SetEvent; FThumbThread.WaitFor; FreeAndNil(FThumbThread); end; FOnThumbThreadClass := Value; end; procedure TCustomVirtualExplorerListviewEx.ResetThumbImageList(ResetSpacing: boolean = True); begin if ViewStyle = vsxThumbs then begin FDummyIL.Width := ThumbsOptions.Width - 16 + (ThumbsOptions.BorderSize * 2); if ThumbsOptions.Details then FDummyIL.Height := ThumbsOptions.Height - 4 + (ThumbsOptions.BorderSize * 2) + ThumbsOptions.DetailsHeight else FDummyIL.Height := ThumbsOptions.Height - 4 + (ThumbsOptions.BorderSize * 2); if ResetSpacing then ResetThumbSpacing; end; end; procedure TCustomVirtualExplorerListviewEx.FillExtensionsList(FillColors: Boolean = true); var I: integer; Ext: WideString; {$IFDEF USEGRAPHICEX} L: TStringList; {$ELSE} {$IFDEF USEIMAGEMAGICK} L: TStringList; {$ENDIF} {$ENDIF} begin FExtensionsList.Clear; {$IFDEF USEGRAPHICEX} L := TStringList.Create; try FileFormatList.GetExtensionList(L); FExtensionsList.AddStrings(L); FExtensionsList.DeleteString('ico'); // Don't add ico finally L.Free; end; {$ELSE} {$IFDEF USEIMAGEMAGICK} L := TStringList.Create; try if Assigned(MagickFileFormatList) then begin MagickFileFormatList.GetExtensionList(L); FExtensionsList.AddStrings(L); FExtensionsList.DeleteString('ico'); // Don't add ico FExtensionsList.DeleteString('pdf'); // TODO -cImageMagick : Stack overflow exception in TMagickImage.LoadFromStream, MagickImage.pas line 744 FExtensionsList.DeleteString('txt'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728 FExtensionsList.DeleteString('avi'); // TODO -cImageMagick : infinite loop in BlobToImage: Trace: TMagickImage.LoadFromStream -> StreamToImage -> BlobToImage. FExtensionsList.DeleteString('mpg'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728 FExtensionsList.DeleteString('mpeg'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728 FExtensionsList.DeleteString('htm'); // TODO -cImageMagick : delegate not supported FExtensionsList.DeleteString('html'); // TODO -cImageMagick : delegate not supported end; finally L.Free; end; {$ELSE} with FExtensionsList do begin CommaText := '.jpg, .jpeg, .jif, .bmp, .emf, .wmf'; {$IFDEF USEIMAGEEN} CommaText := CommaText + ', .png, .pcx, .tif, .tiff, .gif'; {$ELSE} {$IFDEF USEENVISION} //version 1.1 CommaText := CommaText + ', .png, .pcx, .pcc, .tif, .tiff, .dcx, .tga, .vst, .afi'; //version 2.0, eps (Encapsulated Postscript) and jp2 (JPEG2000 version) //CommaText := CommaText + ', .eps, .jp2'; <<<<<<< still in beta {$ENDIF} {$ENDIF} end; {$ENDIF} {$ENDIF} if FillColors then begin for I := 0 to FExtensionsList.Count - 1 do begin Ext := FExtensionsList[I]; if (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') or (Ext = '.jfif') or (Ext = '.jpe') then FExtensionsList.Colors[I] := $BADDDD else if (Ext = '.bmp') or (Ext = '.rle') or (Ext = '.dib') then FExtensionsList.Colors[I] := $EFD3D3 else if (Ext = '.emf') or (Ext = '.wmf') then FExtensionsList.Colors[I] := $7DC7B0 else if (Ext = '.gif') then FExtensionsList.Colors[I] := $CCDBCC else if (Ext = '.png') then FExtensionsList.Colors[I] := $DAB6DA else if (Ext = '.tif') or (Ext = '.tiff') or (Ext = '.fax') or (Ext = '.eps') then FExtensionsList.Colors[I] := $DBB5B0 else if (Ext = '.pcx') or (Ext = '.dcx') or (Ext = '.pcc') or (Ext = '.scr') then FExtensionsList.Colors[I] := $D6D6DB else if (Ext = '.tga') or (Ext = '.vst') or (Ext = '.vda') or (Ext = '.win') or (Ext = '.icb') or (Ext = '.afi') then FExtensionsList.Colors[I] := $EFEFD6 else if (Ext = '.psd') or (Ext = '.pdd') then FExtensionsList.Colors[I] := $D3EFEF else if (Ext = '.psp') then FExtensionsList.Colors[I] := $93C0DD else if (Ext = '.sgi') or (Ext = '.rgba') or (Ext = '.rgb') or (Ext = '.bw') then FExtensionsList.Colors[I] := $C2BBE3 else if (Ext = '.rla') or (Ext = '.rpf') then FExtensionsList.Colors[I] := $D3EFEF else if (Ext = '.ppm') or (Ext = '.pgm') or (Ext = '.pbm') then FExtensionsList.Colors[I] := $95D4DD else if (Ext = '.cel') or (Ext = '.pic') then FExtensionsList.Colors[I] := $AFEFEE else if (Ext = '.cut') then FExtensionsList.Colors[I] := $AFEFEE else if (Ext = '.pcd') then FExtensionsList.Colors[I] := $AFEFEE; // $7DC7B0 = green, $FFBD0B = orange, CFCFCF = grey end; end; ExtensionsExclusionList.CommaText := '.url, .lnk, .ico'; end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { TThumbsCacheItem } constructor TThumbsCacheItem.Create(AFilename: WideString); begin FThumbImageStream := TMemoryStream.Create; FStreamSignature := DefaultStreamSignature; FFilename := AFilename; end; constructor TThumbsCacheItem.CreateFromStream(ST: TStream); begin FThumbImageStream := TMemoryStream.Create; FStreamSignature := DefaultStreamSignature; LoadFromStream(ST); end; destructor TThumbsCacheItem.Destroy; begin FThumbImageStream.Free; inherited; end; procedure TThumbsCacheItem.Fill(AFileDateTime: TDateTime; AExif, AComment: WideString; AImageWidth, AImageHeight: Integer; ACompressed: Boolean; AThumbImageStream: TMemoryStream); begin FFileDateTime := AFileDateTime; FExif := AExif; FComment := AComment; FImageWidth := AImageWidth; FImageHeight := AImageHeight; FCompressed := ACompressed; if Assigned(AThumbImageStream) then FThumbImageStream.LoadFromStream(AThumbImageStream); Changed; end; function TThumbsCacheItem.DefaultStreamSignature: WideString; begin // Override this method to change the default stream signature // Use the StreamSignature to load or not the custom properties // in LoadFromStream. Result := '1.4'; end; procedure TThumbsCacheItem.Assign(CI: TThumbsCacheItem); begin // Override this method to Assign the the custom properties. Fill(CI.FileDateTime, CI.Exif, CI.Comment, CI.ImageWidth, CI.ImageHeight, CI.CompressedThumbImageStream, CI.ThumbImageStream); end; procedure TThumbsCacheItem.Changed; begin // Override this method to set the custom properties. // At this point all the properties are filled and valid. // The protected FFilename variable is also valid. end; function TThumbsCacheItem.LoadFromStream(ST: TStream): Boolean; begin // Override this method to read the properties from the stream // Use the StreamSignature to load or not the custom properties Result := True; FStreamSignature := ReadWideStringFromStream(ST); FFilename := ReadWideStringFromStream(ST); FFileDateTime := ReadDateTimeFromStream(ST); FImageWidth := ReadIntegerFromStream(ST); FImageHeight := ReadIntegerFromStream(ST); FExif := ReadWideStringFromStream(ST); FComment := ReadWideStringFromStream(ST); FCompressed := Boolean(ReadIntegerFromStream(ST)); ReadMemoryStreamFromStream(ST, FThumbImageStream); end; procedure TThumbsCacheItem.SaveToStream(ST: TStream); begin // Override this method to write the properties to the stream WriteWideStringToStream(ST, FStreamSignature); WriteWideStringToStream(ST, FFilename); WriteDateTimeToStream(ST, FFileDateTime); WriteIntegerToStream(ST, FImageWidth); WriteIntegerToStream(ST, FImageHeight); WriteWideStringToStream(ST, FExif); WriteWideStringToStream(ST, FComment); WriteIntegerToStream(ST, Integer(FCompressed)); WriteMemoryStreamToStream(ST, FThumbImageStream); end; function TThumbsCacheItem.ReadBitmap(OutBitmap: TBitmap): Boolean; begin Result := False; if Assigned(FThumbImageStream) then if FCompressed then ConvertJPGStreamToBitmap(FThumbImageStream, OutBitmap) // JPEG compressed, convert to Bitmap else begin OutBitmap.LoadFromStream(FThumbImageStream); FThumbImageStream.Position := 0; end; end; procedure TThumbsCacheItem.WriteBitmap(ABitmap: TBitmap; CompressIt: Boolean); begin FCompressed := CompressIt; ABitmap.SaveToStream(FThumbImageStream); if FCompressed then ConvertBitmapStreamToJPGStream(FThumbImageStream, 60); //JPEG compressed end; end.
unit SlideShowFullScreen; interface uses System.Types, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.AppEvnts, Vcl.ComCtrls, Dmitry.Utils.System, uWinApi, uDBForm, uFormInterfaces, uVCLHelpers; type TFullScreenView = class(TDBForm, IFullScreenImageForm) MouseTimer: TTimer; ApplicationEvents1: TApplicationEvents; procedure FormPaint(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure Execute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDeactivate(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MouseTimerTimer(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure FormClick(Sender: TObject); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HideMouse; procedure ShowMouse; procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FOldPoint: TPoint; FFloatPanel: IFullScreenControl; protected { Protected declarations } function CanUseMaskingForModal: Boolean; override; procedure InterfaceDestroyed; override; public { Public declarations } procedure DrawImage(Image: TBitmap); procedure Pause; procedure Play; procedure DisableControl; procedure EnableControl; end; implementation {$R *.dfm} procedure TFullScreenView.FormPaint(Sender: TObject); begin Viewer.DrawTo(Canvas, 0, 0); end; procedure TFullScreenView.FormKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = VK_ESCAPE then Viewer.CloseActiveView; end; procedure TFullScreenView.EnableControl; begin if FFloatPanel <> nil then FFloatPanel.SetButtonsEnabled(True); end; procedure TFullScreenView.DisableControl; begin if FFloatPanel <> nil then FFloatPanel.SetButtonsEnabled(False); end; procedure TFullScreenView.Execute(Sender: TObject); begin Show; FFloatPanel.Show; MouseTimer.Restart; SystemParametersInfo(SPI_SCREENSAVERRUNNING, 1, nil, 0); end; procedure TFullScreenView.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TFullScreenView.FormDeactivate(Sender: TObject); begin ShowMouse; SystemParametersInfo(SPI_SCREENSAVERRUNNING, 0, nil, 0); end; procedure TFullScreenView.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ShowMouse; MouseTimer.Restart; end; procedure TFullScreenView.MouseTimerTimer(Sender: TObject); begin if Visible then begin if FFloatPanel = nil then Exit; if FFloatPanel.HasMouse then Exit; HideMouse; end; end; procedure TFullScreenView.Pause; begin if FFloatPanel <> nil then FFloatPanel.Pause; end; procedure TFullScreenView.Play; begin if FFloatPanel <> nil then FFloatPanel.Play; end; procedure TFullScreenView.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin MouseTimer.Enabled := True; if (Abs(FOldPoint.X - X) > 5) or (Abs(FOldPoint.X - X) > 5) then begin ShowMouse; FOldPoint := Point(X, Y); MouseTimer.Restart; end; end; procedure TFullScreenView.FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); begin ShowMouse; MouseTimer.Enabled := False; Viewer.ShowPopup(ClientToScreen(MousePos).X, ClientToScreen(MousePos).Y); end; procedure TFullScreenView.FormClick(Sender: TObject); begin Viewer.NextImage; end; procedure TFullScreenView.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ShowMouse; MouseTimer.Restart; end; procedure TFullScreenView.HideMouse; var CState: Integer; begin CState := ShowCursor(True); while Cstate >= 0 do Cstate := ShowCursor(False); if FFloatPanel <> nil then FFloatPanel.Hide; end; procedure TFullScreenView.InterfaceDestroyed; begin inherited; Release; end; procedure TFullScreenView.ShowMouse; var Cstate: Integer; begin Cstate := ShowCursor(True); while CState < 0 do CState := ShowCursor(True); if Viewer.IsFullScreenNow then if FFloatPanel <> nil then FFloatPanel.Show; end; procedure TFullScreenView.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); function CanProcessMessage: Boolean; var P: TPoint; begin GetCursorPos(P); Result := Active or PtInRect(BoundsRect, P); end; begin if not Visible then Exit; if Viewer.IsFullScreenNow and CanProcessMessage then if Msg.message = WM_SYSKEYDOWN then Msg.message := 0; if Viewer.IsFullScreenNow and CanProcessMessage then if Msg.message = WM_KEYDOWN then begin if Msg.WParam = VK_LEFT then Viewer.PreviousImage; if Msg.WParam = VK_RIGHT then Viewer.NextImage; if Msg.WParam = VK_SPACE then Viewer.NextImage; if Msg.WParam = VK_ESCAPE then Viewer.CloseActiveView; if (Msg.WParam = VK_F4) then if AltKeyDown then Msg.WParam := 29; if (Msg.WParam = VK_RETURN) then Viewer.CloseActiveView; Msg.message := 0; end; if (Msg.message = WM_MOUSEWHEEL) and CanProcessMessage then begin if Viewer.IsFullScreenNow then if NativeInt(Msg.WParam) > 0 then Viewer.PreviousImage else Viewer.NextImage; Handled := True; end; end; procedure TFullScreenView.FormResize(Sender: TObject); begin if FFloatPanel <> nil then FFloatPanel.MoveToForm(Self); end; procedure TFullScreenView.FormCreate(Sender: TObject); begin FFloatPanel := FullScreenControl; FFloatPanel.Show; DisableSleep; end; procedure TFullScreenView.FormDestroy(Sender: TObject); begin FFloatPanel := nil; ShowMouse; SystemParametersInfo(SPI_SCREENSAVERRUNNING, 0, nil, 0); EnableSleep; end; function TFullScreenView.CanUseMaskingForModal: Boolean; begin Result := False; end; procedure TFullScreenView.DrawImage(Image: TBitmap); begin Canvas.Draw(0, 0, Image); end; initialization FormInterfaces.RegisterFormInterface(IFullScreenImageForm, TFullScreenView); end.
unit Editor; {$mode objfpc}{$H+} interface uses Classes, Windows, SysUtils, FileUtil, SynEdit, SynHighlighterAny, SynCompletion, Forms, Controls, ComCtrls, ExtCtrls, StdCtrls, Menus, Global, Dialogs, Types, LCLType, Graphics; type { TEditorFrame } TEditorFrame = class(TFrame) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; CheckBox1: TCheckBox; CheckBox2: TCheckBox; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; FindDlgPanel: TPanel; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; EditorPanel: TPanel; CodeSchemeImageList: TImageList; CodeSchemePanel: TPanel; Panel1: TPanel; PopupMenu1: TPopupMenu; ReplaceDlgPanel: TPanel; SaveDialog1: TSaveDialog; Splitter1: TSplitter; SynAnySyn1: TSynAnySyn; SynCompletion: TSynCompletion; SelfTab: TTabSheet; SelfStates: TStatusBar; CWUpdateTimer: TTimer; SynEdit: TSynEdit; CodeSchemeTimer: TTimer; SchemeTreeView: TTreeView; 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 CodeSchemeTimerTimer(Sender: TObject); constructor CreateEditor(TabSheet: TTabSheet; StatusBar: TStatusBar; OpenOp: TOpenOp; OpenParam: string); procedure CWUpdateTimerTimer(Sender: TObject); destructor Destroy; override; procedure FindDlg; procedure MenuItem10Click(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem4Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem7Click(Sender: TObject); procedure MenuItem8Click(Sender: TObject); procedure MenuItem9Click(Sender: TObject); procedure ReplaceDlg; procedure SchemeTreeViewSelectionChanged(Sender: TObject); procedure SynCompletionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); function SynCompletionPaintItem(const AKey: string; ACanvas: TCanvas; X, Y: integer; Selected: boolean; Index: integer): boolean; procedure SynEditChange(Sender: TObject); procedure SynEditKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure SynEditKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); procedure SynEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure SynEditMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean); procedure SynEditMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean); procedure UpdateState; function CW_MakeDescr(wrd, descr, infile: string): string; procedure CW_Add(s: string); procedure CW_Update; procedure CW_ParseFile(fp: string); private CW_ParsedFiles, CW_Lst: TStringList; CW_MaxWordLen, CW_MaxDescrLen, CW_LastMaxWordLen, CW_LastMaxDescrLen: word; KeyUpCnt, LastKeyUp: cardinal; public DefFile: string; Saved: boolean; end; implementation {$R *.lfm} constructor TEditorFrame.CreateEditor(TabSheet: TTabSheet; StatusBar: TStatusBar; OpenOp: TOpenOp; OpenParam: string); begin inherited Create(SelfTab); CW_ParsedFiles := TStringList.Create; CW_Lst := TStringList.Create; CW_MaxWordLen := 0; CW_MaxDescrLen := 0; CW_LastMaxWordLen := 0; CW_LastMaxDescrLen := 0; Self.Parent := SelfTab; SelfTab := TabSheet; SelfStates := StatusBar; Saved := False; KeyUpCnt := 1; LastKeyUp := 0; case OpenOp of opopOpen: begin SynEdit.Lines.LoadFromFile(OpenParam); Saved := True; CW_ParseFile(OpenParam); end; end; DefFile := OpenParam; FindDlgPanel.Visible := False; ReplaceDlgPanel.Visible := False; SynEdit.SetFocus; CodeSchemeTimerTimer(nil); end; procedure TEditorFrame.CWUpdateTimerTimer(Sender: TObject); begin if FileExists(DefFile) then begin CW_ParsedFiles.Clear; CW_Lst.Clear; CW_MaxWordLen := 0; CW_MaxDescrLen := 0; CW_ParseFile(DefFile); CW_Update; end; end; destructor TEditorFrame.Destroy; begin FreeAndNil(CW_ParsedFiles); FreeAndNil(CW_Lst); inherited; end; procedure TEditorFrame.Button2Click(Sender: TObject); begin FindDlgPanel.Visible := False; end; procedure TEditorFrame.Button3Click(Sender: TObject); begin if CheckBox2.Checked then SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text, []) else SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text, [rfIgnoreCase]); end; procedure TEditorFrame.Button1Click(Sender: TObject); var p: cardinal; s: string; begin if Edit1.Text <> SynEdit.SelText then begin //find first if CheckBox1.Checked then p := Pos(Edit1.Text, SynEdit.Text) else p := Pos(LowerCase(Edit1.Text), LowerCase(SynEdit.Text)); if p <> 0 then begin SynEdit.SelStart := p; SynEdit.SelEnd := p + Length(Edit1.Text); end else begin ShowMessage('No matches found.'); SynEdit.SelEnd := SynEdit.SelStart; end; end else begin //find next s := SynEdit.Text; Delete(s, 1, SynEdit.SelEnd); if CheckBox1.Checked then p := Pos(Edit1.Text, s) else p := Pos(LowerCase(Edit1.Text), LowerCase(s)); if p <> 0 then begin p := SynEdit.SelEnd + p; SynEdit.SelStart := p; SynEdit.SelEnd := p + Length(Edit1.Text); end else begin SynEdit.SelEnd := SynEdit.SelStart; Button1Click(Sender); end; end; end; procedure TEditorFrame.Button4Click(Sender: TObject); begin ReplaceDlgPanel.Visible := False; end; procedure TEditorFrame.Button5Click(Sender: TObject); begin if CheckBox2.Checked then SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text, [rfReplaceAll]) else SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text, [rfIgnoreCase, rfReplaceAll]); end; procedure TEditorFrame.Button6Click(Sender: TObject); begin CodeSchemePanel.Width := 0; end; procedure TEditorFrame.FindDlg; begin ReplaceDlgPanel.Visible := False; FindDlgPanel.Visible := True; Edit1.SetFocus; end; procedure TEditorFrame.MenuItem10Click(Sender: TObject); begin SynEdit.SelectAll; end; procedure TEditorFrame.MenuItem1Click(Sender: TObject); begin SynEdit.Undo; ; end; procedure TEditorFrame.MenuItem2Click(Sender: TObject); begin SynEdit.Redo; end; procedure TEditorFrame.MenuItem4Click(Sender: TObject); begin FindDlg; end; procedure TEditorFrame.MenuItem5Click(Sender: TObject); begin ReplaceDlg; end; procedure TEditorFrame.MenuItem7Click(Sender: TObject); begin SynEdit.CutToClipboard; end; procedure TEditorFrame.MenuItem8Click(Sender: TObject); begin SynEdit.CopyToClipboard; end; procedure TEditorFrame.MenuItem9Click(Sender: TObject); begin SynEdit.PasteFromClipboard; end; procedure TEditorFrame.ReplaceDlg; begin FindDlgPanel.Visible := False; ReplaceDlgPanel.Visible := True; Edit2.SetFocus; end; procedure TEditorFrame.SchemeTreeViewSelectionChanged(Sender: TObject); begin SchemeTreeView.Selected := nil; end; procedure TEditorFrame.SynCompletionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); begin Delete(Value, Pos('`', Value), Length(Value)); end; function TEditorFrame.SynCompletionPaintItem(const AKey: string; ACanvas: TCanvas; X, Y: integer; Selected: boolean; Index: integer): boolean; var s, wrd, desc, infile: string; begin s := SynCompletion.ItemList[Index]; wrd := copy(s, 1, pos('`', s) - 1); Delete(s, 1, pos('`', s)); desc := copy(s, 1, pos('`', s) - 1); Delete(s, 1, pos('`', s)); infile := s; if Selected then begin ACanvas.Brush.Color := clHighlight; ACanvas.FillRect(X, Y, X + SynCompletion.Width, Y + ACanvas.TextHeight('|')); ACanvas.Font.Style := [fsBold]; ACanvas.Font.Color := clWhite; ACanvas.TextOut(X + 2, Y, wrd); ACanvas.Font.Style := []; ACanvas.Font.Color := clSilver; ACanvas.TextOut(X + 2 + ACanvas.TextWidth('_') * (CW_LastMaxWordLen + 8), Y, desc); ACanvas.Font.Style := []; ACanvas.Font.Color := clSilver; ACanvas.TextOut(X + 2 + ACanvas.TextWidth('_') * (CW_LastMaxWordLen + 8) + ACanvas.TextWidth('_') * (CW_LastMaxDescrLen + 8), Y, infile); end else begin ACanvas.Brush.Color := clWhite; ACanvas.FillRect(X, Y, X + SynCompletion.Width, Y + ACanvas.TextHeight('|')); ACanvas.Font.Style := [fsBold]; ACanvas.Font.Color := clBlack; ACanvas.TextOut(X + 2, Y, wrd); ACanvas.Font.Style := []; ACanvas.Font.Color := clBlue; if copy(desc, 1, 4) = 'proc' then ACanvas.Font.Color := clMaroon; if (desc[1] = '[') and (desc[2] <> '@') then ACanvas.Font.Color := clOlive; ACanvas.TextOut(X + 2 + ACanvas.TextWidth('_') * (CW_LastMaxWordLen + 8), Y, desc); ACanvas.Font.Style := []; ACanvas.Font.Color := clGreen; ACanvas.TextOut(X + 2 + ACanvas.TextWidth('_') * (CW_LastMaxWordLen + 8) + ACanvas.TextWidth('_') * (CW_LastMaxDescrLen + 8), Y, infile); end; Result := True; end; procedure TEditorFrame.SynEditChange(Sender: TObject); begin Saved := False; UpdateState; end; procedure TEditorFrame.SynEditKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if ssCtrl in Shift then case Key of VK_S: begin if FileExists(DefFile) then begin SynEdit.Lines.SaveToFile(DefFile); Saved := True; UpdateState; end else if SaveDialog1.Execute then begin DefFile := SaveDialog1.FileName; SelfTab.Caption := ExtractFileName(DefFile) + ' [X]'; SynEdit.Lines.SaveToFile(DefFile); Saved := True; UpdateState; end; end; VK_F: FindDlg; VK_R: ReplaceDlg; end; end; procedure TEditorFrame.SynEditKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); begin Inc(KeyUpCnt); end; procedure TEditorFrame.SynEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin UpdateState; end; procedure TEditorFrame.SynEditMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean); begin if (GetAsyncKeyState(VK_CONTROL) <> 0) and (GetAsyncKeyState(VK_CONTROL) <> 0) then begin if SynEdit.Font.Size > 1 then SynEdit.Font.Size := SynEdit.Font.Size - 1; Handled := True; end; end; procedure TEditorFrame.SynEditMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean); begin if (GetAsyncKeyState(VK_CONTROL) <> 0) and (GetAsyncKeyState(VK_CONTROL) <> 0) then begin SynEdit.Font.Size := SynEdit.Font.Size + 1; Handled := True; end; end; procedure TEditorFrame.UpdateState; begin SelfStates.Panels[0].Text := 'Lines: ' + IntToStr(SynEdit.Lines.Count); SelfStates.Panels[1].Text := 'CaretXY: ' + IntToStr(SynEdit.CaretX) + '/' + IntToStr(SynEdit.CaretY); if Saved then SelfStates.Panels[2].Text := 'Status: Saved' else SelfStates.Panels[2].Text := 'Status: Modified'; SelfStates.Panels[3].Text := 'File: "' + DefFile + '"'; end; function CheckName(n: string): boolean; var chars: set of char = ['a'..'z', '0'..'9', '_', '.']; begin Result := False; if not (n[1] in ['0'..'9']) then begin Delete(n, 1, 1); while Length(n) > 0 do begin if not (n[1] in chars) then exit; Delete(n, 1, 1); end; Result := True; end; end; function TrimCodeStr(s: string): string; var ConstStr: boolean; begin s := Trim(s); ConstStr := False; Result := ''; while Length(s) > 0 do begin if s[1] = '"' then ConstStr := not ConstStr; if ConstStr then begin Result := Result + s[1]; Delete(s, 1, 1); end else begin if copy(s, 1, 2) = '//' then break; Result := Result + s[1]; Delete(s, 1, 1); end; end; end; function Tk(s: string; w: word): string; begin Result := ''; while (length(s) > 0) and (w > 0) do begin if s[1] = '"' then begin Delete(s, 1, 1); Result := copy(s, 1, pos('"', s) - 1); Delete(s, 1, pos('"', s)); s := trim(s); end else if Pos(' ', s) > 0 then begin Result := copy(s, 1, pos(' ', s) - 1); Delete(s, 1, pos(' ', s)); s := trim(s); end else begin Result := s; s := ''; end; Dec(w); end; end; function TEditorFrame.CW_MakeDescr(wrd, descr, infile: string): string; begin if CW_MaxWordLen < Length(wrd) then CW_MaxWordLen := Length(wrd); if CW_MaxDescrLen < Length(descr) then CW_MaxDescrLen := Length(descr); Result := wrd + '`' + descr + '`' + infile; end; procedure TEditorFrame.CW_Add(s: string); begin if CW_Lst.IndexOf(s) = -1 then begin CW_Lst.Add(s); end; end; procedure TEditorFrame.CW_Update; begin CW_LastMaxWordLen := CW_MaxWordLen; CW_LastMaxDescrLen := CW_MaxDescrLen; SynCompletion.ItemList.Text := CW_Lst.Text; end; procedure TEditorFrame.CW_ParseFile(fp: string); var s, fp2: string; f: textfile; begin AssignFile(f, fp); Reset(f); CW_ParsedFiles.Add(fp); while not EOF(f) do begin ReadLn(f, s); s := TrimCodeStr(s); if s <> '' then begin if Tk(s, 1) = 'uses' then begin Delete(s, 1, length('uses')); s := Trim(s); if s[1] = '<' then fp2 := ExtractFilePath(ParamStr(0)) + 'inc\' else if FileExists(fp) then fp2 := ExtractFilePath(fp); Delete(s, 1, 1); Delete(s, Length(s), 1); fp2 := fp2 + s; if not FileExists(fp2) then begin if FileExists(fp2 + '.mash') then fp2 := fp2 + '.mash'; if FileExists(fp2 + '.h') then fp2 := fp2 + '.h'; if FileExists(fp2 + '.inc') then fp2 := fp2 + '.inc'; end; if FileExists(fp2) and (CW_ParsedFiles.IndexOf(fp2) = -1) then CW_ParseFile(fp2); end; if Tk(s, 1) = 'import' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[@] "' + Tk(s, 3) + '":"' + Tk(s, 4) + '"', '"' + ExtractFileName(fp) + '"')); end; if Tk(s, 1) = 'proc' then begin Delete(s, 1, length('proc')); s := Trim(s); if Length(s) > 0 then begin if s[length(s)] = ':' then Delete(s, length(s), 1); s := Trim(s); if (pos('::', s) = 0) and (pos('(', s) <> 0) then CW_Add(CW_MakeDescr(copy(s, 1, pos('(', s) - 1), 'proc ' + s, '"' + ExtractFileName(fp) + '"')); end; end; if Tk(s, 1) = 'func' then begin Delete(s, 1, length('func')); s := Trim(s); if length(s) > 0 then begin if s[length(s)] = ':' then Delete(s, length(s), 1); s := Trim(s); if (pos('::', s) = 0) and (pos('(', s) <> 0) then CW_Add(CW_MakeDescr(copy(s, 1, pos('(', s) - 1), 'func ' + s, '"' + ExtractFileName(fp) + '"')); end; end; if Tk(s, 1) = 'word' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[word] ' + Tk(s, 3), '"' + ExtractFileName(fp) + '"')); end; if Tk(s, 1) = 'int' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[int] ' + Tk(s, 3), '"' + ExtractFileName(fp) + '"')); end; if Tk(s, 1) = 'real' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[real] ' + Tk(s, 3), '"' + ExtractFileName(fp) + '"')); end; if Tk(s, 1) = 'str' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[str] "' + Tk(s, 3) + '"', '"' + ExtractFileName(fp) + '"')); end; if Tk(s, 1) = 'stream' then begin CW_Add(CW_MakeDescr(Tk(s, 2), '[stream] "' + Tk(s, 3) + '"', '"' + ExtractFileName(fp) + '"')); end; {if s[Length(s)] = ':' then begin Delete(s,length(s),1); CW_Add(CW_MakeDescr(s,'[label] '+s+':','"'+ExtractFileName(fp)+'"')); end;} end; end; CloseFile(f); end; procedure TEditorFrame.CodeSchemeTimerTimer(Sender: TObject); var c, x: cardinal; s, bf: string; classopned: boolean; Nodes, Vars, Extends, Procs: TTreeNode; ExtendsLst: TStringList; begin if KeyUpCnt <> LastKeyUp then begin SchemeTreeView.BeginUpdate; c := 0; while c < SchemeTreeView.Items.Count do begin SchemeTreeView.Items.Item[c].Free; Inc(c); end; SchemeTreeView.Items.Clear; c := 0; while c < SynEdit.Lines.Count do begin s := TrimCodeStr(SynEdit.Lines[c]); if length(s) > 0 then if tk(s, 1) = 'class' then begin Delete(s, 1, 5); s := Trim(s); if s[Length(s)] = ':' then begin Delete(s, length(s), 1); s := Trim(s); end; ExtendsLst := TStringList.Create; if pos('(', s) > 0 then begin bf := s; Delete(s, pos('(', s), length(s)); Delete(bf, 1, pos('(', bf)); Delete(bf, length(bf), 1); bf := Trim(bf); while pos(',', bf) > 0 do begin ExtendsLst.Add(Trim(Copy(bf, 1, pos(',', bf) - 1))); Delete(bf, 1, pos(',', bf)); bf := Trim(bf); end; bf := Trim(bf); if Length(bf) > 0 then ExtendsLst.Add(bf); end; Nodes := SchemeTreeView.Items.AddFirst(SchemeTreeView.Items.GetFirstNode, s); Nodes.ImageIndex := 0; Extends := SchemeTreeView.Items.AddChild(Nodes, 'extends'); Extends.ImageIndex := 4; while ExtendsLst.Count > 0 do begin SchemeTreeView.Items.AddChild(Extends, ExtendsLst[0]).ImageIndex := 0; ExtendsLst.Delete(0); end; FreeAndNil(ExtendsLst); Vars := SchemeTreeView.Items.AddChild(Nodes, 'variables'); Vars.ImageIndex := 4; Procs := SchemeTreeView.Items.AddChild(Nodes, 'methods'); Procs.ImageIndex := 4; while c < SynEdit.Lines.Count do begin Inc(c); s := TrimCodeStr(SynEdit.Lines[c]); if s = 'end' then break; if tk(s, 1) = 'var' then begin Delete(s, 1, 3); s := Trim(s); while pos(',', s) > 0 do begin SchemeTreeView.Items.AddChild(Vars, Trim(Copy(s, 1, pos(',', s) - 1))).ImageIndex := 3; Delete(s, 1, pos(',', s)); s := Trim(s); end; s := Trim(s); if Length(s) > 0 then begin SchemeTreeView.Items.AddChild(Vars, s).ImageIndex := 3; end; end; if (tk(s, 1) = 'proc') or (tk(s, 1) = 'func') then begin bf := tk(s, 1); if bf = 'func' then x := 1 else x := 2; Delete(s, 1, 4); s := Trim(s); if Length(s) > 0 then begin while pos(',', s) > 0 do begin SchemeTreeView.Items.AddChild(Procs, Trim(Copy(s, 1, pos(',', s) - 1))).ImageIndex := x; Delete(s, 1, pos(',', s)); s := Trim(s); end; s := Trim(s); if Length(s) > 0 then SchemeTreeView.Items.AddChild(Procs, s).ImageIndex := x; end; end; end; end; Inc(c); end; Nodes := SchemeTreeView.Items.Add(SchemeTreeView.Items.GetFirstNode, 'methods'); Nodes.ImageIndex := 4; c := 0; while c < SynEdit.Lines.Count do begin s := TrimCodeStr(SynEdit.Lines[c]); if (tk(s, 1) = 'proc') or (tk(s, 1) = 'func') then begin bf := tk(s, 1); if bf = 'func' then x := 1 else x := 2; Delete(s, 1, 4); s := Trim(s); if Length(s) > 0 then begin if s[length(s)] = ':' then Delete(s, length(s), 1); s := Trim(s); if pos('(', s) > 0 then SchemeTreeView.Items.AddChild(Nodes, s).ImageIndex := x; end; end; Inc(c); end; Nodes := SchemeTreeView.Items.Add(Nodes, 'imports'); Nodes.ImageIndex := 4; c := 0; while c < SynEdit.Lines.Count do begin s := TrimCodeStr(SynEdit.Lines[c]); if tk(s, 1) = 'import' then begin Delete(s, 1, 6); s := Trim(s); Delete(s, pos('"', s), length(s)); s := Trim(s); SchemeTreeView.Items.AddChild(Nodes, s).ImageIndex := 5; end; Inc(c); end; SchemeTreeView.EndUpdate; SchemeTreeView.Update; LastKeyUp := KeyUpCnt; end; end; end.
unit feli_event_ticket; {$mode objfpc} interface uses feli_document, feli_collection, fpjson; type FeliEventTicketKeys = class public const id = 'id'; tType = 'type'; fee = 'fee'; end; FeliEventTicket = class(FeliDocument) public id, tType: ansiString; fee: real; function toTJsonObject(secure: boolean = false): TJsonObject; override; procedure generateId(); class function fromTJsonObject(ticketObject: TJsonObject): FeliEventTicket; static; function validate(var error: ansiString): boolean; end; FeliEventTicketCollection = class(FeliCollection) public procedure add(eventTicket: FeliEventTicket); class function fromFeliCollection(collection: FeliCollection): FeliEventTicketCollection; static; end; FeliUserEventJoinedCollection = class(FeliEventTicketCollection) end; FeliUserEventCreatedCollection = class(FeliEventTicketCollection) end; FeliUserEventPendingCollection = class(FeliEventTicketCollection) end; implementation uses feli_crypto, feli_stack_tracer, sysutils; function FeliEventTicket.toTJsonObject(secure: boolean = false): TJsonObject; var userEvent: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliEventTicket.toTJsonObject(secure: boolean = false): TJsonObject;'); userEvent := TJsonObject.create(); userEvent.add(FeliEventTicketKeys.id, id); userEvent.add(FeliEventTicketKeys.tType, tType); userEvent.add(FeliEventTicketKeys.fee, fee); result := userEvent; FeliStackTrace.trace('end', 'function FeliEventTicket.toTJsonObject(secure: boolean = false): TJsonObject;'); end; procedure FeliEventTicket.generateId(); begin id := FeliCrypto.generateSalt(32); end; class function FeliEventTicket.fromTJsonObject(ticketObject: TJsonObject): FeliEventTicket; static; var feliEventTicketInstance: FeliEventTicket; tempString: ansiString; begin feliEventTicketInstance := FeliEventTicket.create(); with feliEventTicketInstance do begin try tType := ticketObject.getPath(FeliEventTicketKeys.tType).asString; except on e: exception do begin end; end; try begin tempString := ticketObject.getPath(FeliEventTicketKeys.fee).asString; fee := StrToFloat(tempString); end; except on e: exception do begin end; end; try id := ticketObject.getPath(FeliEventTicketKeys.id).asString; except on e: exception do begin end; end; end; result := feliEventTicketInstance; end; function FeliEventTicket.validate(var error: ansiString): boolean; begin result := true; if (tType = '') then begin result := false; error := 'ticket_type_empty' end; end; procedure FeliEventTicketCollection.add(eventTicket: FeliEventTicket); begin FeliStackTrace.trace('begin', 'procedure FeliEventTicketCollection.add(eventTicket: FeliEventTicket);'); data.add(eventTicket.toTJsonObject()); FeliStackTrace.trace('end', 'procedure FeliEventTicketCollection.add(eventTicket: FeliEventTicket);'); end; class function FeliEventTicketCollection.fromFeliCollection(collection: FeliCollection): FeliEventTicketCollection; static; var feliEventTicketCollectionInstance: FeliEventTicketCollection; begin FeliStackTrace.trace('begin', 'class function FeliEventTicketCollection.fromFeliCollection(collection: FeliCollection): FeliEventTicketCollection; static;'); feliEventTicketCollectionInstance := FeliEventTicketCollection.create(); feliEventTicketCollectionInstance.data := collection.data; result := feliEventTicketCollectionInstance; FeliStackTrace.trace('end', 'class function FeliEventTicketCollection.fromFeliCollection(collection: FeliCollection): FeliEventTicketCollection; static;'); end; end.
unit Win32.MPEG2Structs; {$mode delphi} interface uses Windows, Classes, SysUtils; const MPEG2_FILTER_VERSION_1_SIZE = 124; MPEG2_FILTER_VERSION_2_SIZE = 133; type {$Z1} TPID_BITS_MIDL = record Bits: word; end; TMPEG_HEADER_BITS_MIDL = record Bits: word; end; TMPEG_HEADER_VERSION_BITS_MIDL = record Bits: byte; end; TPID = word; PPID = ^TPID; TTID = byte; PTID = ^TTID; TTEID = word; PTEID = ^TTEID; TClientKey = UINT; PClientKey = ^TClientKey; TMPEG_CURRENT_NEXT_BIT = ( MPEG_SECTION_IS_NEXT = 0, MPEG_SECTION_IS_CURRENT = 1 ); TTID_EXTENSION = record wTidExt: word; wCount: word; end; PTID_EXTENSION = ^TTID_EXTENSION; TSECTION = record TableId: TTID; Header: record case integer of 0: (S: TMPEG_HEADER_BITS_MIDL); 1: (W: word); end; SectionData: PBYTE; end; PSECTION = ^TSECTION; TLONG_SECTION = record TableId: TTID; Header: record case integer of 0: (S: TMPEG_HEADER_BITS_MIDL); 1: (W: word); end; TableIdExtension: TTEID; Version: record case integer of 0: (S: TMPEG_HEADER_VERSION_BITS_MIDL); 1: (B: byte); end; SectionNumber: byte; LastSectionNumber: byte; RemainingData: PBYTE; end; PLONG_SECTION = ^TLONG_SECTION; TDSMCC_SECTION = record TableId: TTID; Header: record case integer of 0: (S: TMPEG_HEADER_BITS_MIDL); 1: (W: word); end; TableIdExtension: TTEID; Version: record case integer of 0: (S: TMPEG_HEADER_VERSION_BITS_MIDL); 1: (B: byte); end; SectionNumber: byte; LastSectionNumber: byte; ProtocolDiscriminator: byte; DsmccType: byte; MessageId: word; TransactionId: DWORD; Reserved: byte; AdaptationLength: byte; MessageLength: word; RemainingData: PBYTE; end; PDSMCC_SECTION = ^TDSMCC_SECTION; TMPEG_RQST_PACKET = record dwLength: DWORD; pSection: PSECTION; end; PMPEG_RQST_PACKET = ^TMPEG_RQST_PACKET; TMPEG_PACKET_LIST = record wPacketCount: word; PacketList {array}: PMPEG_RQST_PACKET; end; PMPEG_PACKET_LIST = ^TMPEG_PACKET_LIST; TDSMCC_FILTER_OPTIONS = record fSpecifyProtocol: longbool; Protocol: byte; fSpecifyType: longbool; _Type: byte; fSpecifyMessageId: longbool; MessageId: word; fSpecifyTransactionId: longbool; fUseTrxIdMessageIdMask: longbool; TransactionId: DWORD; fSpecifyModuleVersion: longbool; ModuleVersion: byte; fSpecifyBlockNumber: longbool; BlockNumber: word; fGetModuleCall: longbool; NumberOfBlocksInModule: word; end; TATSC_FILTER_OPTIONS = record fSpecifyEtmId: longbool; EtmId: DWORD; end; TDVB_EIT_FILTER_OPTIONS = record fSpecifySegment: longbool; bSegment: byte; end; TMPEG2_FILTER = record bVersionNumber: byte; wFilterSize: word; fUseRawFilteringBits: longbool; Filter: array[0.. 15] of byte; Mask: array [0.. 15] of byte; fSpecifyTableIdExtension: longbool; TableIdExtension: word; fSpecifyVersion: longbool; Version: byte; fSpecifySectionNumber: longbool; SectionNumber: byte; fSpecifyCurrentNext: longbool; fNext: longbool; fSpecifyDsmccOptions: longbool; Dsmcc: TDSMCC_FILTER_OPTIONS; fSpecifyAtscOptions: longbool; Atsc: TATSC_FILTER_OPTIONS; end; PMPEG2_FILTER = ^TMPEG2_FILTER; TMPEG2_FILTER2 = record case integer of 0: ( bVersionNumber: byte; wFilterSize: word; fUseRawFilteringBits: longbool; Filter: array[0..15] of byte; Mask: array[0..15] of byte; fSpecifyTableIdExtension: longbool; TableIdExtension: word; fSpecifyVersion: longbool; Version: byte; fSpecifySectionNumber: longbool; SectionNumber: byte; fSpecifyCurrentNext: longbool; fNext: longbool; fSpecifyDsmccOptions: longbool; Dsmcc: TDSMCC_FILTER_OPTIONS; fSpecifyAtscOptions: longbool; Atsc: TATSC_FILTER_OPTIONS; fSpecifyDvbEitOptions: longbool; DvbEit: TDVB_EIT_FILTER_OPTIONS; ); 1: (bVersion1Bytes: array [0.. 123] of byte); end; PMPEG2_FILTER2 = ^TMPEG2_FILTER2; TMPEG_STREAM_BUFFER = record hr: HRESULT; dwDataBufferSize: DWORD; dwSizeOfDataRead: DWORD; pDataBuffer: PBYTE; end; PMPEG_STREAM_BUFFER = ^TMPEG_STREAM_BUFFER; TMPEG_TIME = record Hours: byte; Minutes: byte; Seconds: byte; end; TMPEG_DURATION = TMPEG_TIME; TMPEG_DATE = record Date: byte; Month: byte; Year: word; end; TMPEG_DATE_AND_TIME = record D: TMPEG_DATE; T: TMPEG_TIME; end; TMPEG_CONTEXT_TYPE = ( MPEG_CONTEXT_BCS_DEMUX = 0, MPEG_CONTEXT_WINSOCK = (MPEG_CONTEXT_BCS_DEMUX + 1) ); TMPEG_BCS_DEMUX = record AVMGraphId: DWORD; end; TMPEG_WINSOCK = record AVMGraphId: DWORD; end; TMPEG_CONTEXT = record _Type: TMPEG_CONTEXT_TYPE; u: record case integer of 0: (Demux: TMPEG_BCS_DEMUX); 1: (Winsock: TMPEG_WINSOCK); end; end; PMPEG_CONTEXT = ^TMPEG_CONTEXT; TMPEG_REQUEST_TYPE = ( MPEG_RQST_UNKNOWN = 0, MPEG_RQST_GET_SECTION = (MPEG_RQST_UNKNOWN + 1), MPEG_RQST_GET_SECTION_ASYNC = (MPEG_RQST_GET_SECTION + 1), MPEG_RQST_GET_TABLE = (MPEG_RQST_GET_SECTION_ASYNC + 1), MPEG_RQST_GET_TABLE_ASYNC = (MPEG_RQST_GET_TABLE + 1), MPEG_RQST_GET_SECTIONS_STREAM = (MPEG_RQST_GET_TABLE_ASYNC + 1), MPEG_RQST_GET_PES_STREAM = (MPEG_RQST_GET_SECTIONS_STREAM + 1), MPEG_RQST_GET_TS_STREAM = (MPEG_RQST_GET_PES_STREAM + 1), MPEG_RQST_START_MPE_STREAM = (MPEG_RQST_GET_TS_STREAM + 1) ); TMPEG_SERVICE_REQUEST = record _Type: TMPEG_REQUEST_TYPE; Context: TMPEG_CONTEXT; Pid: TPID; TableId: TTID; Filter: TMPEG2_FILTER; Flags: DWORD; end; PMPEG_SERVICE_REQUEST = ^TMPEG_SERVICE_REQUEST; TMPEG_SERVICE_RESPONSE = record IPAddress: DWORD; Port: word; end; PMPEG_SERVICE_RESPONSE = ^TMPEG_SERVICE_RESPONSE; PDSMCC_ELEMENT = ^TDSMCC_ELEMENT; TDSMCC_ELEMENT = record pid: TPID; bComponentTag: byte; dwCarouselId: DWORD; dwTransactionId: DWORD; pNext: PDSMCC_ELEMENT; end; PMPE_ELEMENT = ^TMPE_ELEMENT; TMPE_ELEMENT = record pid: TPID; bComponentTag: byte; pNext: PMPE_ELEMENT; end; TMPEG_STREAM_FILTER = record wPidValue: word; dwFilterSize: DWORD; fCrcEnabled: longbool; rgchFilter: array[0.. 15] of byte; rgchMask: array [0.. 15] of byte; end; PMPEG_STREAM_FILTER = ^TMPEG_STREAM_FILTER; {$Z4} implementation end.
unit Turtle; {$mode objfpc}{$H+} interface uses Graphics, Classes, SysUtils, lua, plua, pLuaObject, LuaWrapper; procedure RegisterTurtle(LuaInstance : TLua); var TurtleCanvas : TCanvas; implementation var TurtleInfo : TLuaClassInfo; type { TTurtle } TTurtle = class private FColor: TColor; FPenDown: Boolean; FX: integer; FY: integer; procedure SetColor(const AValue: TColor); procedure SetPenDown(const AValue: Boolean); procedure SetX(const AValue: integer); procedure SetY(const AValue: integer); public property Color : TColor read FColor write SetColor; property X : integer read FX write SetX; property Y : integer read FY write SetY; property PenDown : Boolean read FPenDown write SetPenDown; end; { TTurtle } procedure TTurtle.SetColor(const AValue: TColor); begin if FColor=AValue then exit; FColor:=AValue; end; procedure TTurtle.SetPenDown(const AValue: Boolean); begin if FPenDown=AValue then exit; FPenDown:=AValue; end; procedure TTurtle.SetX(const AValue: integer); begin if FX=AValue then exit; FX:=AValue; end; procedure TTurtle.SetY(const AValue: integer); begin if FY=AValue then exit; FY:=AValue; end; function newTurtle(l : Plua_State; paramidxstart, paramcount : integer; InstanceInfo : PLuaInstanceInfo) : TObject; begin result := TTurtle.Create; end; procedure releaseTurtle(target : TObject; l : Plua_State); begin end; function GetColor(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; begin turtle := TTurtle(target); lua_pushinteger(l, turtle.Color); result := 1; end; function SetColor(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; begin turtle := TTurtle(target); turtle.Color := lua_tointeger(l, paramidxstart); result := 0; end; function GetPenDown(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; begin turtle := TTurtle(target); lua_pushboolean(l, turtle.PenDown); result := 1; end; function SetPenDown(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; begin turtle := TTurtle(target); turtle.PenDown := lua_toboolean(l, paramidxstart); result := 0; end; function MoveTo(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; tx, ty : Integer; begin turtle := TTurtle(target); tX := lua_tointeger(l, paramidxstart); tY := lua_tointeger(l, paramidxstart+1); if turtle.PenDown then begin TurtleCanvas.Pen.Color := turtle.Color; if (abs(tx-turtle.X)>1) or (abs(ty-turtle.Y)>1) then begin TurtleCanvas.Line(turtle.X, turtle.Y, tX, tY); end else begin TurtleCanvas.Pixels[turtle.X, turtle.Y] := turtle.Color; TurtleCanvas.Pixels[tX, tY] := turtle.Color; end; end; turtle.X := tX; turtle.Y := tY; result := 0; end; function LineTo(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var turtle : TTurtle; tx, ty : Integer; begin turtle := TTurtle(target); tX := lua_tointeger(l, paramidxstart); tY := lua_tointeger(l, paramidxstart+1); TurtleCanvas.Pen.Color := turtle.Color; TurtleCanvas.Line(turtle.X, turtle.Y, tX, tY); turtle.X := tX; turtle.Y := tY; result := 0; end; function setTurtleInfo : TLuaClassInfo; begin plua_initClassInfo(result); result.ClassName := 'Turtle'; result.New := @newTurtle; result.Release := @releaseTurtle; plua_AddClassProperty(result, 'Color', @GetColor, @SetColor); plua_AddClassProperty(result, 'PenDown', @GetPenDown, @SetPenDown); plua_AddClassMethod(result, 'MoveTo', @MoveTo); plua_AddClassMethod(result, 'LineTo', @LineTo); end; procedure RegisterTurtle(LuaInstance: TLua); var L : PLua_State; begin L := LuaInstance.LuaState; plua_registerclass(L, TurtleInfo); end; initialization TurtleInfo := setTurtleInfo; finalization end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Logger.Provider.Rest Description : Log Api Rest Provider Author : Kike Pérez Version : 1.23 Created : 15/10/2017 Modified : 24/04/2020 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Logger.Provider.Rest; {$i QuickLib.inc} interface uses Classes, SysUtils, Quick.HttpClient, Quick.Commons, Quick.Logger; type TLogRestProvider = class (TLogProviderBase) private fHTTPClient : TJsonHTTPClient; fURL : string; fUserAgent : string; public constructor Create; override; destructor Destroy; override; property URL : string read fURL write fURL; property UserAgent : string read fUserAgent write fUserAgent; property JsonOutputOptions : TJsonOutputOptions read fJsonOutputOptions write fJsonOutputOptions; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogRestProvider : TLogRestProvider; implementation constructor TLogRestProvider.Create; begin inherited; LogLevel := LOG_ALL; fURL := ''; fUserAgent := DEF_USER_AGENT; IncludedInfo := [iiAppName,iiHost]; end; destructor TLogRestProvider.Destroy; begin if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); inherited; end; procedure TLogRestProvider.Init; begin fHTTPClient := TJsonHTTPClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := fUserAgent; fHTTPClient.HandleRedirects := True; inherited; end; procedure TLogRestProvider.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TLogRestProvider.WriteLog(cLogItem : TLogItem); var resp : IHttpRequestResponse; begin if CustomMsgOutput then resp := fHTTPClient.Post(fURL,LogItemToFormat(cLogItem)) else resp := fHTTPClient.Post(fURL,LogItemToJson(cLogItem)); if not (resp.StatusCode in [200,201]) then raise ELogger.Create(Format('[TLogRestProvider] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText])); end; initialization GlobalLogRestProvider := TLogRestProvider.Create; finalization if Assigned(GlobalLogRestProvider) and (GlobalLogRestProvider.RefCount = 0) then GlobalLogRestProvider.Free; end.
unit ibSHFieldListRetriever; interface uses Classes, SysUtils, SHDesignIntf, ibSHDesignIntf, ibSHValues, ibSHSQLs, pSHIntf; type TibBTFieldListRetriever = class(TSHComponent, IpSHFieldListRetriever, ISHDemon) private FDatabase: IibSHDatabase; function GetDatabase: IInterface; procedure SetDatabase(const Value: IInterface); protected public procedure Notification(AComponent: TComponent; Operation: TOperation); override; class function GetClassIIDClassFnc: TGUID; override; function GetFieldList(const AObjectName: string; AList: TStrings): Boolean; property Database: IInterface read GetDatabase write SetDatabase; end; implementation procedure Register; begin SHRegisterComponents([TibBTFieldListRetriever]); end; { TibBTFieldListRetriever } function TibBTFieldListRetriever.GetDatabase: IInterface; begin Result := FDatabase; end; procedure TibBTFieldListRetriever.SetDatabase( const Value: IInterface); begin ReferenceInterface(FDatabase, opRemove); if Supports(Value, IibSHDatabase, FDatabase) then ReferenceInterface(FDatabase, opInsert); end; procedure TibBTFieldListRetriever.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FDatabase) then FDatabase := nil; end; inherited Notification(AComponent, Operation); end; class function TibBTFieldListRetriever.GetClassIIDClassFnc: TGUID; begin Result := IpSHFieldListRetriever; end; function TibBTFieldListRetriever.GetFieldList( const AObjectName: string; AList: TStrings): Boolean; var vClassIIDList: TStrings; vDesigner: ISHDesigner; vObjectName: string; vObjectIID: TGUID; vSQL_TEXT: string; vComponentClass: TSHComponentClass; vDomain: IibSHDomain; vDDLGenerator: IibSHDDLGenerator; vDomainComponent: TSHComponent; vDDLGeneratorComponent: TSHComponent; vCodeNormalizer: IibSHCodeNormalizer; function NormalizeName(const AName: string): string; begin if Assigned(vCodeNormalizer) then Result := vCodeNormalizer.MetadataNameToSourceDDLCase(FDatabase, AName) else Result := AName; end; begin Result := False; if Assigned(FDatabase) then begin vObjectName := AObjectName; vClassIIDList := FDatabase.GetSchemeClassIIDList(vObjectName); if vClassIIDList.Count > 0 then begin Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer); vObjectIID := StringToGUID(vClassIIDList[0]); if IsEqualGUID(vObjectIID, IibSHView) then begin vSQL_TEXT := FormatSQL(SQL_GET_VIEW_FIELDS); if FDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [vObjectName], False,True) then begin AList.Clear; while not FDatabase.DRVQuery.Eof do begin AList.Add(NormalizeName(FDatabase.DRVQuery.GetFieldStrValue(0)) + '='); FDatabase.DRVQuery.Next; end; FDatabase.DRVQuery.Transaction.Commit; end; end else begin if not FDatabase.ExistsPrecision then begin if IsEqualGUID(vObjectIID, IibSHTable) or IsEqualGUID(vObjectIID, IibSHSystemTable) then vSQL_TEXT := FormatSQL(SQL_GET_TABLE_FIELDS1) else if IsEqualGUID(vObjectIID, IibSHProcedure) then vSQL_TEXT := FormatSQL(SQL_GET_OUT_PROCEDURE_PARAMS1) else Exit; end else begin if IsEqualGUID(vObjectIID, IibSHTable) or IsEqualGUID(vObjectIID, IibSHSystemTable) then vSQL_TEXT := FormatSQL(SQL_GET_TABLE_FIELDS3) else if IsEqualGUID(vObjectIID, IibSHProcedure) then vSQL_TEXT := FormatSQL(SQL_GET_OUT_PROCEDURE_PARAMS3) else Exit; end; if SHSupports(ISHDesigner, vDesigner) then begin vDDLGeneratorComponent := nil; vDomainComponent := nil; vComponentClass := vDesigner.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then vDDLGeneratorComponent := vComponentClass.Create(nil); try vComponentClass := vDesigner.GetComponent(IibSHDomain); if Assigned(vComponentClass) then begin vDomainComponent := vComponentClass.Create(nil); vDomainComponent.OwnerIID := FDatabase.InstanceIID; end; try if Assigned(vDDLGeneratorComponent) and Assigned(vDomainComponent) and Supports(vDDLGeneratorComponent, IibSHDDLGenerator, vDDLGenerator) and Supports(vDomainComponent, IibSHDomain, vDomain) and FDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [vObjectName], False,True) then begin AList.Clear; vDDLGenerator.GetDDLText(vDomain); while not FDatabase.DRVQuery.Eof do begin vDDLGenerator.SetBasedOnDomain(FDatabase.DRVQuery, vDomain, 'Domain'); AList.Add(NormalizeName(FDatabase.DRVQuery.GetFieldStrValue(0)) + '= ' + vDomain.DataTypeExt); FDatabase.DRVQuery.Next; end; FDatabase.DRVQuery.Transaction.Commit; end; finally vDomain := nil; if Assigned(vDomainComponent) then vDomainComponent.Free; end; finally vDDLGeneratorComponent := nil; if Assigned(vDDLGeneratorComponent) then vDDLGeneratorComponent.Free; end; end; end; end; end; end; initialization Register; end.
{ This application shows how to localize package files (.bpl). The main application Project1.exe uses two packages: - a custom package SamplePackage.bpl - a standard VCL package vcl250.bpl (Delphi 10.2 Tokyo) SamplePacakge.bpl contains a form (TSampleForm), a frame (TSampleFrame) and a resource string (SampleConsts.SSampleString). Main form contaisn four labels: 1) Label1 contains a desing time string 2) Label2 is set on run time to hold a local resource string value (comes from Project1.exe or Project1.?? resource DLL) 3) Label3 is set on run time to hold a resource string value of SamplePackage package (comes from SamplePackage.bpl or SamplePacakge.?? resource DLL) 4) Label4 is set on run time to hold a VCL resource string value (comes from vcl230.bpl or vcl230.?? resource DLL) GroupBox1 contains a package frame. If you click Button1 a package form will be shown. } unit Unit1; 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) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Button1: TButton; GroupBox1: TGroupBox; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private FFrame: TFrame; end; var Form1: TForm1; implementation {$R *.dfm} uses Consts, SampleConsts, SampleFra, SampleFor; procedure TForm1.FormCreate(Sender: TObject); resourcestring SMsg = 'Resource string'; begin Label2.Caption := SMsg; // Local resource string Label3.Caption := SampleConsts.SSampleString; // Custom package resource string Label4.Caption := Consts.SMsgDlgInformation; // VCL package resource string FFrame := TSampleFrame.Create(nil); FFrame.Parent := GroupBox1; FFrame.Left := 8; FFrame.Top := 16; end; procedure TForm1.Button1Click(Sender: TObject); var form: TSampleForm; begin form := TSampleForm.Create(nil); try form.ShowModal; finally form.Free; end; end; end.
unit QQWry; interface uses Windows, SysUtils, Classes, StrUtils, Controls, Math; const //用于内存文件映射标志 QQWryMapFileTag = 'QQWryMapFile'; type TQQWry = class(TObject) public constructor Create(AQQWryFileName: string); destructor Destroy; override; function GetQQWryFileName: string; function GetQQWryFileSize: int64; function GetIPDataNum: int64; function GetQQWryDate: TDate; function GetQQWryDataFrom: string; procedure GetIPDataByIPRecordID(IPRecordID: int64; var IPData: PChar); overload; procedure GetIPLocationByEndIPOffset(EndIPOffset: int64; var IPLocation: PChar); procedure GetIPDataByIPRecordID(IPRecordID: int64; var IPData: TStringlist); overload; function GetIPLocalData(IPRecordID: int64): PChar; function GetIPValue(IP: string): int64; function GetIPDataID(IP: string): int64; function ExtractIPDataToTxtFile(ATxtFileName: string): integer; private QQWryFileName: string; QQWryFileSize: int64; IPDataNum: int64; FirstIPIndexOffset, LastIPIndexOffset: integer; hQQWryFile, hQQWryMapFile: THandle; pQQWryMapFile: Pointer; pQQWryPos: PByte; function GetFileSize(AFileName: string): int64; end; implementation ///** //* 获取文件大小 //* @param (AFileName) (文件全名) //* @return (文件大小) //*/ function TQQWry.GetFileSize(AFileName: string): int64; var FileStream: TFileStream; begin try FileStream:=TFileStream.Create(AFileName, fmOpenRead); except raise Exception.Create(format('文件 %s 无法打开!', [AFileName])); exit; end; result:=FileStream.Size; FileStream.Free; end; ///** //* 构造函数,构造一个TQQWry即纯真IP数据库处理对象 //* @param (AQQWryFileName) (纯真IP数据库文件的全文件名) //* @return 无 //*/ constructor TQQWry.Create(AQQWryFileName: string); var Buffer: TOFStruct; begin inherited Create; try QQWryFileName:=AQQWryFileName; //测文件存在 if not FileExists(QQWryFileName) then raise Exception.Create(format('文件 %s 不存在!', [QQWryFileName])); //测文件大小 QQWryFileSize:=GetFileSize(QQWryFileName); if QQWryFileSize=0 then raise Exception.Create(format('文件 %s 大小为空!', [QQWryFileName])); //打开文件句柄 hQQWryFile:=OpenFile(PChar(QQWryFileName), Buffer, OF_READWRITE); if hQQWryFile=-1 then raise Exception.Create(format('文件 %s 不能打开!', [QQWryFileName])); //创建文件映像对象 hQQWryMapFile:=CreateFileMapping(hQQWryFile, nil, PAGE_READWRITE, 0, QQWryFileSize, PChar(QQWryMapFileTag)); if hQQWryMapFile=0 then begin CloseHandle(hQQWryFile); raise Exception.Create('不能创建内存映象文件!'); end; //获取映象文件映射地址 pQQWryMapFile:=MapViewOfFile(hQQWryMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0); if pQQWryMapFile=nil then begin CloseHandle(hQQWryFile); CloseHandle(hQQWryMapFile); raise Exception.Create('不能获取文件映射地址!'); end; pQQWryPos:=pQQWryMapFile; FirstIPIndexOffset:=PInteger(pQQWryPos)^; Inc(pQQWryPos, 4); LastIPIndexOffset:=PInteger(pQQWryPos)^; IPDataNum:=(LastIPIndexOffset - FirstIPIndexOffset) div 7 + 1; except on E: Exception do begin raise Exception.Create(E.Message); exit; end; end; end; ///** //* 析构函数 (释放TQQWry对象,关闭文件映射,关闭文件映像对象句柄,关闭文件句柄) //* @param 无 //* @return 无 //*/ destructor TQQWry.Destroy; begin if pQQWryMapFile<>nil then UnMapViewOfFile(pQQWryMapFile); //关闭文件映射 if hQQWryMapFile<>0 then CloseHandle(hQQWryMapFile); //关闭文件映像对象句柄 if hQQWryFile<>0 then CloseHandle(hQQWryFile); //关闭文件句柄 inherited Destroy; end; ///** //* 获取纯真IP数据库文件的全文件名 //* @param 无 //* @return (纯真IP数据库文件的全文件名) //*/ function TQQWry.GetQQWryFileName: string; begin Result:=QQWryFileName; end; ///** //* 获取纯真IP数据库文件大小 //* @param 无 //* @return (纯真IP数据库文件大小) //*/ function TQQWry.GetQQWryFileSize: int64; begin Result:=QQWryFileSize; end; ///** //* 获取纯真IP数据库内含有的IP地址信息记录数 //* @param 无 //* @return (纯真IP数据库记录数) //*/ function TQQWry.GetIPDataNum: int64; begin Result:=IPDataNum; end; ///** //* 获取当前QQIP数据库的更新日期 //* @param 无 //* @return QQIP当前数据库的更新日期 TDate //*/ function TQQWry.GetQQWryDate: TDate; var DateString: string; IPData: TStringlist; begin IPData:=TStringlist.Create; GetIPDataByIPRecordID(GetIPDataNum, IPData); DateString:=IPData[3]; IPData.Free; DateString:=copy(DateString, 1, pos('IP数据', DateString) - 1); DateString:=StringReplace(DateString, '年', '-', [rfReplaceAll, rfIgnoreCase]); DateString:=StringReplace(DateString, '月', '-', [rfReplaceAll, rfIgnoreCase]); DateString:=StringReplace(DateString, '日', '-', [rfReplaceAll, rfIgnoreCase]); Result:=StrToDate(DateString); end; ///** //* 获取当前QQIP数据库的来源信息 //* @param 无 //* @return 当前QQIP数据库的来源信息 string //*/ function TQQWry.GetQQWryDataFrom: string; var FromString: string; IPData: TStringlist; begin IPData:=TStringlist.Create; GetIPDataByIPRecordID(GetIPDataNum, IPData); FromString:=IPData[2]; IPData.Free; Result:=FromString; end; ///** //* 给定一个IP地址信息记录号,返回该项记录的信息 //* @param (IPRecordID, IPData) (IP地址信息记录号, 返回的该条信息:①起始IP 15字节 ②结束IP 15字节 ③国家 ④地区 ⑤回车键2字节) //* @return 无 //*/ function TQQWry.GetIPLocalData(IPRecordID: int64): PChar; var EndIPOffset: integer; i: integer; pBlank, pReturn: PChar; IPByteStr: string; IPByteStrLen: integer; IPDataPos: integer; IPLocation: PChar; begin try if (IPRecordID<=0) or (IPRecordID>GetIPDataNum) then raise Exception.Create('IP信息记录号过小或越界!'); pBlank:=' '; pReturn:=#13#10; EndIPOffset:=0; //取内存文件映射首地址 pQQWryPos:=pQQWryMapFile; //根据记录的ID号移到该记录号的索引处,因为高位在后所以从后往前读 Inc(pQQWryPos, FirstIPIndexOffset + (IPRecordID - 1) * 7 + 3); //取始末IP地址 //索引的前4个字节为该条记录的起始IP地址 IPDataPos:=0; for i:=0 to 3 do begin IPByteStr:=IntToStr(pQQWryPos^); IPByteStrLen:=Length(IPByteStr); CopyMemory(@Result[IPDataPos], PChar(IPByteStr), IPByteStrLen); Inc(IPDataPos, IPByteStrLen); if i<>3 then begin Result[IPDataPos]:='.'; Inc(IPDataPos); end; dec(pQQWryPos); end; //填充空格至16位 CopyMemory(@Result[IPDataPos], pBlank, 16-IPDataPos); IPDataPos:=16; Inc(pQQWryPos, 5); //后3个字节是该条记录的内容区域的偏移值,内容区域的前4个字节为该条记录的结束IP地址 CopyMemory(@EndIPOffset, pQQWryPos, 3); //取该条记录的结束IP地址 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, EndIPOffset + 3); for i:=0 to 3 do begin IPByteStr:=IntToStr(pQQWryPos^); IPByteStrLen:=Length(IPByteStr); CopyMemory(@Result[IPDataPos], PChar(IPByteStr), IPByteStrLen); Inc(IPDataPos, IPByteStrLen); if i<>3 then begin Result[IPDataPos]:='.'; Inc(IPDataPos); end; dec(pQQWryPos); end; //填充空格至16位 CopyMemory(@Result[IPDataPos], pBlank, 32-IPDataPos); IPDataPos:=32; //取该条记录的国家地区信息 IPLocation:=PChar(@Result[IPDataPos]); //GetIPLocationByEndIPOffset(EndIPOffset, IPLocation); //结尾的回车 { if IPLocation[StrLen(IPLocation) - 1]<>' ' then Inc(IPDataPos, StrLen(IPLocation)) else Inc(IPDataPos, StrLen(IPLocation) - 1); CopyMemory(@Result[IPDataPos], pReturn, 2); } except on E: Exception do begin Destroy; raise Exception.Create(E.Message); exit; end; end; end; procedure TQQWry.GetIPDataByIPRecordID(IPRecordID: int64; var IPData: PChar); var EndIPOffset: integer; i: integer; pBlank, pReturn: PChar; IPByteStr: string; IPByteStrLen: integer; IPDataPos: integer; IPLocation: PChar; begin try if (IPRecordID<=0) or (IPRecordID>GetIPDataNum) then raise Exception.Create('IP信息记录号过小或越界!'); pBlank:=' '; pReturn:=#13#10; EndIPOffset:=0; //取内存文件映射首地址 pQQWryPos:=pQQWryMapFile; //根据记录的ID号移到该记录号的索引处,因为高位在后所以从后往前读 Inc(pQQWryPos, FirstIPIndexOffset + (IPRecordID - 1) * 7 + 3); //取始末IP地址 //索引的前4个字节为该条记录的起始IP地址 IPDataPos:=0; for i:=0 to 3 do begin IPByteStr:=IntToStr(pQQWryPos^); IPByteStrLen:=Length(IPByteStr); CopyMemory(@IPData[IPDataPos], PChar(IPByteStr), IPByteStrLen); Inc(IPDataPos, IPByteStrLen); if i<>3 then begin IPData[IPDataPos]:='.'; Inc(IPDataPos); end; dec(pQQWryPos); end; //填充空格至16位 CopyMemory(@IPData[IPDataPos], pBlank, 16-IPDataPos); IPDataPos:=16; Inc(pQQWryPos, 5); //后3个字节是该条记录的内容区域的偏移值,内容区域的前4个字节为该条记录的结束IP地址 CopyMemory(@EndIPOffset, pQQWryPos, 3); //取该条记录的结束IP地址 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, EndIPOffset + 3); for i:=0 to 3 do begin IPByteStr:=IntToStr(pQQWryPos^); IPByteStrLen:=Length(IPByteStr); CopyMemory(@IPData[IPDataPos], PChar(IPByteStr), IPByteStrLen); Inc(IPDataPos, IPByteStrLen); if i<>3 then begin IPData[IPDataPos]:='.'; Inc(IPDataPos); end; dec(pQQWryPos); end; //填充空格至16位 CopyMemory(@IPData[IPDataPos], pBlank, 32-IPDataPos); IPDataPos:=32; //取该条记录的国家地区信息 IPLocation:=PChar(@IPData[IPDataPos]); GetIPLocationByEndIPOffset(EndIPOffset, IPLocation); //结尾的回车 if IPLocation[StrLen(IPLocation) - 1]<>' ' then Inc(IPDataPos, StrLen(IPLocation)) else Inc(IPDataPos, StrLen(IPLocation) - 1); CopyMemory(@IPData[IPDataPos], pReturn, 2); except on E: Exception do begin Destroy; raise Exception.Create(E.Message); exit; end; end; end; ///** //* 给定一条记录的结束IP地址的偏移,返回该条记录的国家地区信息 //* @param (EndIPOffset, IPLocation) (该条记录的结束IP地址偏移, 该条记录的国家地区信息) //* @return 无 //*/ procedure TQQWry.GetIPLocationByEndIPOffset(EndIPOffset: int64; var IPLocation: PChar); const //实际信息字串存放位置的重定向模式 REDIRECT_MODE_1 = 1; REDIRECT_MODE_2 = 2; var RedirectMode: byte; pSplit: PChar; CountryFirstOffset, CountrySecondOffset: int64; IPCountryLen: integer; IPArea: PChar; ///** //* 给定一个地区信息偏移值,返回在数据文件中该偏移量下的地区信息 //* @param (AreaOffset, IPArea) (地区信息在文件中的偏移值, 返回的地区信息) //* @return //*/ procedure ReadIPAreaByAreaOffset(AreaOffset: int64; var IPArea: PChar); var ModeByte: byte; ReadAreaOffset: int64; begin try ModeByte:=0; ReadAreaOffset:=0; //取内存文件映射首地址 pQQWryPos:=pQQWryMapFile; //移到偏移处 inc(pQQWryPos, AreaOffset); //读模式 CopyMemory(@ModeByte, pQQWryPos, 1); //模式1或2,后3字节为偏移 if (ModeByte = REDIRECT_MODE_1) or (ModeByte = REDIRECT_MODE_2) then begin //读偏移 Inc(pQQWryPos); CopyMemory(@ReadAreaOffset, pQQWryPos, 3); //若偏移为0,则为未知地区,对于以前的数据库有这个错误 if ReadAreaOffset=0 then IPArea:='未知地区' else begin //去偏移处读字符串 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, ReadAreaOffset); CopyMemory(IPArea, PChar(pQQWryPos), StrLen(PChar(pQQWryPos))); end; //没有模式,直接读字符串 end else begin pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, AreaOffset); CopyMemory(IPArea, PChar(pQQWryPos), StrLen(PChar(pQQWryPos))); end; except on E: Exception do begin raise Exception.Create(E.Message); exit; end; end; end; begin try RedirectMode:=0; pSplit:=' '; CountryFirstOffset:=0; CountrySecondOffset:=0; //取内存文件映射首地址 pQQWryPos:=pQQWryMapFile; //根据记录ID号移到该记录号的索引处 Inc(pQQWryPos, EndIPOffset + 4); CopyMemory(@RedirectMode, pQQWryPos, 1); //重定向模式1的处理 if RedirectMode = REDIRECT_MODE_1 then begin Inc(pQQWryPos); //模式值为1,则后3个字节的内容为国家信息的偏移值 CopyMemory(@CountryFirstOffset, pQQWryPos, 3); //进行重定向 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, CountryFirstOffset); //第二次读取国家信息的重定向模式 CopyMemory(@RedirectMode, pQQWryPos, 1); //第二次重定向模式为模式2的处理 if RedirectMode = REDIRECT_MODE_2 then begin //后3字节的内容即为第二次重定向偏移值 Inc(pQQWryPos); CopyMemory(@CountrySecondOffset, pQQWryPos, 3); //读取第二次重定向偏移值下的字符串值,即为国家信息 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, CountrySecondOffset); IPCountryLen:=StrLen(PChar(pQQWryPos)); CopyMemory(IPLocation, PChar(pQQWryPos), IPCountryLen); //用空格分割国家和地区 CopyMemory(@IPLocation[IPCountryLen], pSplit, 1); //若第一次重定向模式为1,进行重定向后读取的第二次重定向模式为2, //则地区信息存放在第一次国家信息偏移值的后面 IPArea:=PChar(@IPLocation[IPCountryLen + 1]); ReadIPAreaByAreaOffset(CountryFirstOffset + 4, IPArea); //第二次重定向模式不是模式2的处理 end else begin IPCountryLen:=StrLen(PChar(pQQWryPos)); CopyMemory(IPLocation, PChar(pQQWryPos), IPCountryLen); //用空格分割国家和地区 CopyMemory(@IPLocation[IPCountryLen], pSplit, 1); //读地区信息 IPArea:=PChar(@IPLocation[IPCountryLen + 1]); ReadIPAreaByAreaOffset(CountryFirstOffset + IPCountryLen + 1, IPArea); end; //重定向模式2的处理 end else if RedirectMode = REDIRECT_MODE_2 then begin Inc(pQQWryPos); //模式值为2,则后3个字节的内容为国家信息的偏移值 CopyMemory(@CountrySecondOffset, pQQWryPos, 3); //进行重定向 pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, CountrySecondOffset); //国家信息 IPCountryLen:=StrLen(PChar(pQQWryPos)); CopyMemory(IPLocation, PChar(pQQWryPos), IPCountryLen); //用空格分割国家和地区 CopyMemory(@IPLocation[IPCountryLen], pSplit, 1); //地区信息 IPArea:=PChar(@IPLocation[IPCountryLen + 1]); ReadIPAreaByAreaOffset(EndIPOffset + 8, IPArea); //不是重定向模式的处理,存放的即是IP地址信息 end else begin //国家信息 IPCountryLen:=StrLen(PChar(pQQWryPos)); CopyMemory(IPLocation, PChar(pQQWryPos), IPCountryLen); //用空格分割国家和地区 CopyMemory(@IPLocation[IPCountryLen], pSplit, 1); //地区信息 IPArea:=PChar(@IPLocation[IPCountryLen + 1]); ReadIPAreaByAreaOffset(EndIPOffset + 4 + IPCountryLen + 1, IPArea); end; except on E: Exception do begin raise Exception.Create(E.Message); exit; end; end; end; ///** //* 给定一个IP地址信息记录号,返回该项记录的信息,用Stringlist接收该条信息,效率较低 //* @param (IPRecordID, IPData) (IP地址信息记录号, 返回的该条信息:①起始IP ②结束IP ③国家 ④地区) //* @return 无 //*/ procedure TQQWry.GetIPDataByIPRecordID(IPRecordID: int64; var IPData: TStringlist); var aryIPData: array[0..254] of char; pIPData: PChar; i: integer; begin try FillChar(aryIPData, SizeOf(aryIPData), #0); pIPData:=PChar(@aryIPData[0]); GetIPDataByIPRecordID(IPRecordID, pIPData); //去掉结尾的回车符 pIPData[StrLen(pIPData) - 2]:=#0; IPData.CommaText:=StrPas(pIPData); //有可能地区为空,也有可能地区中含有空格 for i:=1 to 4 - IPData.Count do IPData.Add('无'); for i:=5 to IPData.Count do IPData[3]:=IPData[3] + ' ' + IPData[i - 1]; except on E: Exception do begin raise Exception.Create(E.Message); exit; end; end; end; ///** //* 给定一个IP地址(四段点分字符串形式),返回该IP的数值 //* @param (IP) (IP地址,四段点分字符串形式) //* @return 该IP的数值 //*/ function TQQWry.GetIPValue(IP: string): int64; var slIP: TStringlist; i: integer; function SplitStringToStringlist(aString: string; aSplitChar: string): TStringlist; begin Result:=TStringList.Create; while pos(aSplitChar, aString)>0 do begin Result.Add(copy(aString, 1, pos(aSplitChar, aString)-1)); aString:=copy(aString, pos(aSplitChar, aString)+1, length(aString)-pos(aSplitChar, aString)); end; Result.Add(aString); end; begin try slIP:=SplitStringToStringlist(IP, '.'); Result:=0; for i:=3 downto 0 do begin Result:=Result + StrToInt(slIP[i]) * trunc(power(256, 3-i)); end; except on E: Exception do begin raise Exception.Create('无效的IP地址!'); exit; end; end; end; ///** //* 给定一个IP地址(四段点分字符串形式),返回该IP地址所在的记录号 //* @param IP IP地址(四段点分字符串形式) string //* @return 该IP地址所在的记录号 Cardinal //*/ function TQQWry.GetIPDataID(IP: string): int64; function SearchIPDataID(IPRecordFrom, IPRecordTo, IPValue: int64): int64; var CompareIPValue1, CompareIPValue2: int64; begin Result:=0; CompareIPValue1:=0; CompareIPValue2:=0; pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, FirstIPIndexOffset + ((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom - 1) * 7); CopyMemory(@CompareIPValue1, pQQWryPos, 4); pQQWryPos:=pQQWryMapFile; Inc(pQQWryPos, FirstIPIndexOffset + ((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom) * 7); CopyMemory(@CompareIPValue2, pQQWryPos, 4); //找到了 if (IPRecordFrom=IPRecordTo) or ((IPValue>=CompareIPValue1) and (IPValue<CompareIPValue2)) then begin Result:=(IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom; end else //后半段找 if IPValue>CompareIPValue1 then begin Result:=SearchIPDataID((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom + 1, IPRecordTo, IPValue); end else //前半段找 if IPValue<CompareIPValue1 then begin Result:=SearchIPDataID(IPRecordFrom, (IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom - 1, IPValue); end; end; begin try Result:=SearchIPDataID(1, GetIPDataNum, GetIPValue(IP)); except on E: Exception do begin Destroy; raise Exception.Create(E.Message); exit; end; end; end; ///** //* 将IP地址数据库解压成文本文件 //* @param (ATxtFileName) (解压后的文本文件全名) //* @return -1为解压失败,非-1值为解压所耗时间,单位毫秒 //*/ function TQQWry.ExtractIPDataToTxtFile(ATxtFileName: string): integer; var QQWryMemoryStream: TMemoryStream; i: integer; IPData, NowPos: PChar; TimeCounter: DWORD; pReturn: PChar; begin result:=-1; try IPData:=StrAlloc(41943040); NowPos:=IPData; TimeCounter:=GetTickCount; for i:=1 to GetIPDataNum do begin GetIPDataByIPRecordID(i, NowPos); Inc(NowPos, StrLen(NowPos)); end; pReturn:=#13#10; NowPos:=StrECopy(NowPos, pReturn); NowPos:=StrECopy(NowPos, pReturn); NowPos:=StrECopy(NowPos, PChar(format('IP数据库共有数据 : %d 条', [GetIPDataNum]))); NowPos:=StrECopy(NowPos, pReturn); QQWryMemoryStream:=TMemoryStream.Create; QQWryMemoryStream.SetSize(NowPos - IPData); QQWryMemoryStream.WriteBuffer(IPData^, NowPos - IPData); QQWryMemoryStream.SaveToFile(ATxtFileName); StrDispose(IPData); QQWryMemoryStream.Destroy; result:=GetTickCount-TimeCounter; except on E: Exception do begin raise Exception.Create(E.Message); exit; end; end; end; end.
unit FilterPart; interface uses stdctrls, windows, classes, Sysutils, Controls, comctrls, Forms, extctrls, db, dbgrids, buttons, graphics, Placemnt, DBGridEh; type { TAvGrid = class(TDBGrid) private FIniLink: TIniLink; FLabel: TLabel; FEdit: TEdit; FButton: TBitBtn; FPanel: TPanel; FShift: TShiftState; FStatusBar: TStatusBar; function GetStorage: TFormPlacement; procedure SetStorage(Value: TFormPlacement); procedure IniSave(Sender: TObject); procedure IniLoad(Sender: TObject); procedure InternalSaveLayout(IniFile: TObject; const Section: string); procedure InternalRestoreLayout(IniFile: TObject; const Section: string); procedure SaveColumnsLayout(IniFile: TObject; const Section: string); procedure RestoreColumnsLayout(IniFile: TObject; const Section: string); procedure OnFButtonClick(Sender: TObject); procedure OnFPanelExit(Sender: TObject); procedure SetStatusBar(Value: TStatusBar); protected procedure TitleClick(Column: TColumn); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetParent(AParent: TWinControl); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property StatusBar: TStatusBar read FStatusBar write SetStatusBar; property IniStorage: TFormPlacement read GetStorage write SetStorage; end; } TAvEhGridOption = (aegFilter); TAvEhGridOptions = set of TAvEhGridOption; TAvEhGrid = class(TDBGridEh) private FOptionsAv: TAvEhGridOptions; FIniLink: TIniLink; FLabel: TLabel; FEdit: TEdit; FButton: TBitBtn; FPanel: TPanel; FShift: TShiftState; FStatusBar: TStatusBar; function GetStorage: TFormPlacement; procedure SetStorage(Value: TFormPlacement); procedure IniSave(Sender: TObject); procedure IniLoad(Sender: TObject); procedure InternalSaveLayout(IniFile: TObject; const Section: string); procedure InternalRestoreLayout(IniFile: TObject; const Section: string); procedure SaveColumnsLayout(IniFile: TObject; const Section: string); procedure RestoreColumnsLayout(IniFile: TObject; const Section: string); procedure OnFButtonClick(Sender: TObject); procedure OnFPanelKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnFPanelExit(Sender: TObject); procedure SetStatusBar(Value: TStatusBar); procedure SetOptionsAv(const Value: TAvEhGridOptions); protected procedure TitleClick(Column: TColumnEh); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetParent(AParent: TWinControl); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //procedure DefaultApplySorting; override; published property StatusBar: TStatusBar read FStatusBar write SetStatusBar; property IniStorage: TFormPlacement read GetStorage write SetStorage; property OptionsAv: TAvEhGridOptions read FOptionsAv write SetOptionsAv default []; end; procedure Register; function FilterPart1(s:string; FType:TFieldType; c: string):string; implementation uses ADOdb, VCLUtils, DbConsts, Dialogs, DbUtils, AppUtils, RxStrUtils; procedure Register; begin // RegisterComponents('Data Controls', [TAvGrid]); RegisterComponents('Data Controls', [TAvEhGrid]); end; function FilterPart1(s:string; FType:TFieldType; c: string):string; var sgn: string; begin if s = '' then exit; case s[1] of '>': begin Delete(s,1,1); if (s<>'')and(s[1]='=') then begin sgn:='>='; Delete(s,1,1); end else sgn:='>'; end; '<': begin Delete(s,1,1); if (s<>'')and(s[1] in ['=','>']) then begin sgn := '<'+s[1]; Delete(s,1,1); end else sgn := '<'; end; '=': begin sgn:='='; Delete(s,1,1); end; else begin if FType in [ftString,ftWideString] then sgn := ' LIKE ' else sgn := '='; end; end; if s <> '' then begin if (s[1] <> '''') and (FType in [ftString,ftWideString,ftDate, ftTime, ftDateTime]) then begin if (sgn = ' LIKE ') and (Pos(c, s) = 0) then s:=c+s+c; s := ''''+s+''''; end; Result := sgn+s; end else Result := ''; end; { constructor TAvGrid.Create(AOwner: TComponent); begin inherited; FPanel := TPanel.Create(Self); FPanel.Visible := False; FPanel.Height := 33; FPanel.Width := 0; FPanel.OnExit := OnFPanelExit; FLabel := TLabel.Create(Self); FLabel.Parent := FPanel; FLabel.Top := 10; FLabel.Left := 8; FEdit := TEdit.Create(Self); FEdit.Parent := FPanel; FEdit.Top := 8; FEdit.Width := 129; FButton := TBitBtn.Create(Self); FButton.Parent := FPanel; FButton.OnClick := OnFButtonClick; FButton.Top := 8; FButton.Width := 22; FButton.Height := 22; FButton.Glyph.Handle := LoadBitmap(hInstance, 'FILTER'); FIniLink := TIniLink.Create; FIniLink.OnSave := IniSave; FIniLink.OnLoad := IniLoad; end; destructor TAvGrid.Destroy; begin FIniLink.Free; inherited Destroy; end; procedure TAvGrid.OnFPanelExit(Sender: TObject); begin FPanel.Visible := False; SetFocus; end; procedure TAvGrid.SetParent(AParent: TWinControl); begin inherited; if Assigned(AParent) then FPanel.Parent := AParent; end; procedure TAvGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FShift := Shift; if (dgMultiSelect in Options) and Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[0].Text := 'Выделено '+IntToStr(SelectedRows.Count)+' строк'; inherited; end; procedure TAvGrid.KeyUp(var Key: Word; Shift: TShiftState); begin if (dgMultiSelect in Options) and Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[0].Text := 'Выделено '+IntToStr(SelectedRows.Count)+' строк'; inherited; end; procedure TAvGrid.OnFButtonClick(Sender: TObject); var s: string; sAnd: string; DataSet: TCustomADODataSet; begin DataSet := DataSource.DataSet as TCustomADODataSet; try s := FilterPart1(FEdit.Text, SelectedField.DataType, '*'); if s <> '' then begin sAnd := ''; if DataSet.Filter <> '' then sAnd := ' and '; try DataSet.Filter := DataSet.Filter+sAnd+SelectedField.FieldName+s; DataSet.Filtered := DataSet.Filter <> ''; if Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[2].Text := DataSet.Filter; except on EDatabaseError do Application.MessageBox('Неверное выражение фильтра', PChar(Caption),MB_ICONERROR+MB_OK); end; end; finally FPanel.Visible := False; SetFocus; end; end; procedure TAvGrid.TitleClick(Column: TColumn); var mc: TColumn; rect: TRect; ds: TCustomADODataSet; i: Integer; z: string; begin inherited; if not Assigned(DataSource) or not Assigned(DataSource.DataSet) then Exit; if not (ssCtrl in FShift) then begin ds := DataSource.DataSet as TCustomADODataSet; if ssShift in FShift then begin if not (fsBold in Column.Title.Font.Style) then begin z := ''; if ds.Sort <> '' then z := ','; ds.Sort := ds.Sort+z+Column.Field.FieldName; Column.Title.Font.Style := Column.Title.Font.Style+[fsBold]; if Assigned(FStatusBar) and (FStatusBar.Panels.Count > 1) then FStatusBar.Panels[1].Text := FStatusBar.Panels[1].Text+','+Column.Title.Caption; end end else begin if Column.Field <> nil then begin ds.Sort := Column.Field.FieldName; for i := 0 to Columns.Count-1 do Columns[i].Title.Font.Style := Columns.Items[i].Title.Font.Style-[fsBold]; Column.Title.Font.Style := Column.Title.Font.Style+[fsBold]; if Assigned(FStatusBar) and (FStatusBar.Panels.Count > 1) then FStatusBar.Panels[1].Text := 'Сорт.: '+Column.Title.Caption; end; end; end else begin if (Column.Field.DataType = ftString) or (Column.Field.DataType = ftFloat) or (Column.Field.DataType = ftCurrency) then begin FLabel.Caption := Column.Title.Caption; rect := CalcTitleRect(Column,0,mc); FEdit.Left := FLabel.Left+FLabel.Width+10; FButton.Left := FEdit.Left+FEdit.Width+2; FPanel.Width := FButton.Left+FButton.Width+5; FPanel.Left := rect.Left; if FPanel.Left+FPanel.Width > Width then FPanel.Left := Width-FPanel.Width; if FPanel.Left < 0 then FPanel.Left := 0; FPanel.Top := 1+Top; FPanel.Visible := True; FPanel.BringToFront; FEdit.Text := Column.Field.AsString; SelectedField := Column.Field; FEdit.SetFocus; end; end; end; procedure TAvGrid.SetStatusBar(Value: TStatusBar); begin FStatusBar := Value; end; procedure TAvGrid.IniSave(Sender: TObject); var Section: string; begin if (Name <> '') and (FIniLink.IniObject <> nil) then begin if StoreColumns then Section := FIniLink.RootSection + GetDefaultSection(Self) else if (FIniLink.RootSection <> '') and (DataSource <> nil) and (DataSource.DataSet <> nil) then Section := FIniLink.RootSection + DataSetSectionName(DataSource.DataSet) else Section := ''; InternalSaveLayout(FIniLink.IniObject, Section); end; end; procedure TAvGrid.InternalSaveLayout(IniFile: TObject; const Section: string); begin if (DataSource <> nil) and (DataSource.DataSet <> nil) then if StoreColumns then SaveColumnsLayout(IniFile, Section) else InternalSaveFields(DataSource.DataSet, IniFile, Section); end; procedure TAvGrid.IniLoad(Sender: TObject); var Section: string; begin if (Name <> '') and (FIniLink.IniObject <> nil) then begin if StoreColumns then Section := FIniLink.RootSection + GetDefaultSection(Self) else if (FIniLink.RootSection <> '') and (DataSource <> nil) and (DataSource.DataSet <> nil) then Section := FIniLink.RootSection + DataSetSectionName(DataSource.DataSet) else Section := ''; InternalRestoreLayout(FIniLink.IniObject, Section); end; end; procedure TAvGrid.InternalRestoreLayout(IniFile: TObject; const Section: string); begin if (DataSource <> nil) and (DataSource.DataSet <> nil) then begin HandleNeeded; BeginLayout; try if StoreColumns then RestoreColumnsLayout(IniFile, Section) else InternalRestoreFields(DataSource.DataSet, IniFile, Section, False); finally EndLayout; end; end; end; procedure TAvGrid.SaveColumnsLayout(IniFile: TObject; const Section: string); var I: Integer; S: string; begin if Section <> '' then S := Section else S := GetDefaultSection(Self); IniEraseSection(IniFile, S); with Columns do begin for I := 0 to Count - 1 do begin IniWriteString(IniFile, S, Format('%s.%s', [Name, Items[I].FieldName]), Format('%d,%d', [Items[I].Index, Items[I].Width])); end; end; end; procedure TAvGrid.RestoreColumnsLayout(IniFile: TObject; const Section: string); type TColumnInfo = record Column: TColumn; EndIndex: Integer; end; PColumnArray = ^TColumnArray; TColumnArray = array[0..0] of TColumnInfo; const Delims = [' ',',']; var I, J: Integer; SectionName, S: string; ColumnArray: PColumnArray; begin if Section <> '' then SectionName := Section else SectionName := GetDefaultSection(Self); with Columns do begin ColumnArray := AllocMemo(Count * SizeOf(TColumnInfo)); try for I := 0 to Count - 1 do begin S := IniReadString(IniFile, SectionName, Format('%s.%s', [Name, Items[I].FieldName]), ''); ColumnArray^[I].Column := Items[I]; ColumnArray^[I].EndIndex := Items[I].Index; if S <> '' then begin ColumnArray^[I].EndIndex := StrToIntDef(ExtractWord(1, S, Delims), ColumnArray^[I].EndIndex); Items[I].Width := StrToIntDef(ExtractWord(2, S, Delims), Items[I].Width); end; end; for I := 0 to Count - 1 do begin for J := 0 to Count - 1 do begin if ColumnArray^[J].EndIndex = I then begin ColumnArray^[J].Column.Index := ColumnArray^[J].EndIndex; Break; end; end; end; finally FreeMemo(Pointer(ColumnArray)); end; end; end; function TAvGrid.GetStorage: TFormPlacement; begin Result := FIniLink.Storage; end; procedure TAvGrid.SetStorage(Value: TFormPlacement); begin FIniLink.Storage := Value; end; } constructor TAvEhGrid.Create(AOwner: TComponent); begin inherited; FPanel := TPanel.Create(Self); FPanel.Visible := False; FPanel.Height := 33; FPanel.Width := 0; FPanel.OnExit := OnFPanelExit; FLabel := TLabel.Create(Self); FLabel.Parent := FPanel; FLabel.Top := 10; FLabel.Left := 8; FEdit := TEdit.Create(Self); FEdit.Parent := FPanel; FEdit.Top := 8; FEdit.Width := 129; FButton := TBitBtn.Create(Self); FButton.Parent := FPanel; FButton.OnClick := OnFButtonClick; FButton.Top := 8; FButton.Width := 22; FButton.Height := 22; FButton.Glyph.Handle := LoadBitmap(hInstance, 'FILTER'); FIniLink := TIniLink.Create; FIniLink.OnSave := IniSave; FIniLink.OnLoad := IniLoad; OptionsEh := [dghFixed3D, dghHighlightFocus, dghClearSelection, dghAutoSortMarking, dghMultiSortMarking, dghEnterAsTab, dghIncSearch, dghPreferIncSearch, dghRowHighlight, dghDblClickOptimizeColWidth]; AllowedOperations := []; AllowedSelections := [gstRecordBookmarks,gstAll]; RowHeight := 17; TitleHeight := 15; TitleLines := 0; end; destructor TAvEhGrid.Destroy; begin FIniLink.Free; inherited Destroy; end; procedure TAvEhGrid.OnFPanelExit(Sender: TObject); begin FPanel.Visible := False; FEdit.OnKeyDown := nil; SetFocus; end; procedure TAvEhGrid.SetParent(AParent: TWinControl); begin inherited; if Assigned(AParent) then FPanel.Parent := AParent; end; procedure TAvEhGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FShift := Shift; if (dgMultiSelect in Options) and Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[0].Text := 'Выделено '+IntToStr(SelectedRows.Count)+' строк'; inherited; end; procedure TAvEhGrid.KeyUp(var Key: Word; Shift: TShiftState); begin if (dgMultiSelect in Options) and Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[0].Text := 'Выделено '+IntToStr(SelectedRows.Count)+' строк'; inherited; end; procedure TAvEhGrid.OnFPanelKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then begin Key := 0; OnFButtonClick(Sender); end; end; procedure TAvEhGrid.OnFButtonClick(Sender: TObject); var s: string; sAnd: string; DataSet: TDataSet; //TCustomADODataSet; begin DataSet := DataSource.DataSet; // as TCustomADODataSet; try if (DataSource.DataSet is TCustomADODataSet) then s := FilterPart1(FEdit.Text, SelectedField.DataType, '%') else s := FilterPart1(FEdit.Text, SelectedField.DataType, '*'); if s <> '' then begin sAnd := ''; if DataSet.Filter <> '' then sAnd := ' and '; try DataSet.Filter := DataSet.Filter+sAnd+SelectedField.FieldName+s; DataSet.Filtered := DataSet.Filter <> ''; if Assigned(FStatusBar) and (FStatusBar.Panels.Count > 2) then FStatusBar.Panels[2].Text := DataSet.Filter; except on EDatabaseError do Application.MessageBox('Неверное выражение фильтра', PChar(Caption),MB_ICONERROR+MB_OK); end; end; finally FPanel.Visible := False; FEdit.OnKeyDown := nil; SetFocus; end; end; procedure TAvEhGrid.TitleClick(Column: TColumnEh); var rect: TRect; begin inherited; if not (aegFilter in FOptionsAv) then Exit; if not Assigned(DataSource) or not Assigned(DataSource.DataSet) then Exit; if ssCtrl in FShift then begin if (Column.Field.DataType = ftSmallint) or (Column.Field.DataType = ftInteger) or (Column.Field.DataType = ftString) or (Column.Field.DataType = ftWideString) or (Column.Field.DataType = ftFloat) or (Column.Field.DataType = ftCurrency) then begin FLabel.Caption := Column.Title.Caption; rect := CellRect(Column.Index+1,0); FEdit.Left := FLabel.Left+FLabel.Width+10; FButton.Left := FEdit.Left+FEdit.Width+2; FPanel.Width := FButton.Left+FButton.Width+5; FPanel.Left := rect.Left; if FPanel.Left+FPanel.Width > Width then FPanel.Left := Width-FPanel.Width; if FPanel.Left < 0 then FPanel.Left := 0; FPanel.Top := 1+Top; FPanel.Visible := True; FPanel.BringToFront; FEdit.Text := Column.Field.AsString; SelectedField := Column.Field; FEdit.OnKeyDown := OnFPanelKeyDown; FEdit.SetFocus; end; end; end; procedure TAvEhGrid.SetStatusBar(Value: TStatusBar); begin FStatusBar := Value; end; procedure TAvEhGrid.IniSave(Sender: TObject); var Section: string; begin if (Name <> '') and (FIniLink.IniObject <> nil) then begin if StoreColumns then Section := FIniLink.RootSection + GetDefaultSection(Self) else if (FIniLink.RootSection <> '') and (DataSource <> nil) and (DataSource.DataSet <> nil) then Section := FIniLink.RootSection + DataSetSectionName(DataSource.DataSet) else Section := ''; InternalSaveLayout(FIniLink.IniObject, Section); end; end; procedure TAvEhGrid.InternalSaveLayout(IniFile: TObject; const Section: string); begin if (DataSource <> nil) and (DataSource.DataSet <> nil) then if StoreColumns then SaveColumnsLayout(IniFile, Section) else InternalSaveFields(DataSource.DataSet, IniFile, Section); end; procedure TAvEhGrid.IniLoad(Sender: TObject); var Section: string; begin if (Name <> '') and (FIniLink.IniObject <> nil) then begin if StoreColumns then Section := FIniLink.RootSection + GetDefaultSection(Self) else if (FIniLink.RootSection <> '') and (DataSource <> nil) and (DataSource.DataSet <> nil) then Section := FIniLink.RootSection + DataSetSectionName(DataSource.DataSet) else Section := ''; InternalRestoreLayout(FIniLink.IniObject, Section); end; end; procedure TAvEhGrid.InternalRestoreLayout(IniFile: TObject; const Section: string); begin if (DataSource <> nil) and (DataSource.DataSet <> nil) then begin HandleNeeded; BeginLayout; try if StoreColumns then RestoreColumnsLayout(IniFile, Section) else InternalRestoreFields(DataSource.DataSet, IniFile, Section, False); finally EndLayout; end; end; end; procedure TAvEhGrid.SaveColumnsLayout(IniFile: TObject; const Section: string); var I: Integer; S: string; begin if Section <> '' then S := Section else S := GetDefaultSection(Self); IniEraseSection(IniFile, S); with Columns do begin for I := 0 to Count - 1 do begin IniWriteString(IniFile, S, Format('%s.%s', [Name, Items[I].FieldName]), Format('%d,%d', [Items[I].Index, Items[I].Width])); end; end; end; procedure TAvEhGrid.RestoreColumnsLayout(IniFile: TObject; const Section: string); type TColumnInfo = record Column: TColumnEh; EndIndex: Integer; end; PColumnArray = ^TColumnArray; TColumnArray = array[0..0] of TColumnInfo; const Delims = [' ',',']; var I, J: Integer; SectionName, S: string; ColumnArray: PColumnArray; begin if Section <> '' then SectionName := Section else SectionName := GetDefaultSection(Self); with Columns do begin ColumnArray := AllocMemo(Count * SizeOf(TColumnInfo)); try for I := 0 to Count - 1 do begin S := IniReadString(IniFile, SectionName, Format('%s.%s', [Name, Items[I].FieldName]), ''); ColumnArray^[I].Column := Items[I]; ColumnArray^[I].EndIndex := Items[I].Index; if S <> '' then begin ColumnArray^[I].EndIndex := StrToIntDef(ExtractWord(1, S, Delims), ColumnArray^[I].EndIndex); Items[I].Width := StrToIntDef(ExtractWord(2, S, Delims), Items[I].Width); end; end; for I := 0 to Count - 1 do begin for J := 0 to Count - 1 do begin if ColumnArray^[J].EndIndex = I then begin ColumnArray^[J].Column.Index := ColumnArray^[J].EndIndex; Break; end; end; end; finally FreeMemo(Pointer(ColumnArray)); end; end; end; function TAvEhGrid.GetStorage: TFormPlacement; begin Result := FIniLink.Storage; end; procedure TAvEhGrid.SetStorage(Value: TFormPlacement); begin FIniLink.Storage := Value; end; procedure TAvEhGrid.SetOptionsAv(const Value: TAvEhGridOptions); begin if (OptionsAv = Value) then Exit; FOptionsAv := Value; LayoutChanged; end; { procedure TAvEhGrid.DefaultApplySorting; var i: Integer; s: String; bm: TBookmark; begin if not (DataSource.DataSet is TCustomADODataSet) then Exit; s := ''; for i := 0 to SortMarkedColumns.Count-1 do begin if SortMarkedColumns[i].Title.SortMarker = smUpEh then s := s + SortMarkedColumns[i].FieldName + ' DESC , ' else s := s + SortMarkedColumns[i].FieldName + ', '; end; if s <> '' then s := Copy(s,1,Length(s)-2); bm := DataSource.DataSet.GetBookmark; (DataSource.DataSet as TCustomADODataSet).Sort := s; DataSource.DataSet.GotoBookmark(bm); DataSource.DataSet.FreeBookmark(bm); end; } end.
unit RangeTree2D_u; { generic 2D Range Tree -> TRangeTree2D<TKey> Based on Ideas given in Session 3 of the course 6.851 MIT OpenWare https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-851-advanced-data-structures-spring-2012/lecture-videos/ HOW TO USE: TKey is a userdefined class that allows for relational operators <_x and <_y. These operators are defined through two comparison functions that must be provided by the user in the constructor. Then the DS TRangeTree2D<TKey> is built (statically) with an input list Of keys, being ready to perform report queries on the form: given a set of keys S, find the subset Sm with the keys that lie inside the rage [k1,k2], where k1, k2 are some bounding keys that can be seen as the bottomLeft and topRight corners of 2D interval [k1.x,k2.x]x[k1.y,k2.y]. The expected scaling time is O(|Sm| + log |S|). See HowToUseExample at the end of the unit, were TKey = TSPt2D, a record (x,y,PtNo), is used along with standard <_x, <_y comparison functions. OVERVIEW: There is a Balanced Tree with the data at the leafs sorted by X. Each node contains a Sorted List with the keys living in node's subtree sorted by Y. Fractional Cascading is employed to track nodes in YRange while XTree is navigated for XRange. TODO : upgrade to Dynamic see RangeTree1D_u.pas } interface uses Math, System.SysUtils,DIalogs, System.Variants, System.Classes, System.Generics.collections, Generics.Defaults; type TyNode<TKey> = class key : TKey; isPromoted : Boolean; PromotedSucc, PromotedPred, NoPromotedSucc, NoPromotedPred, PromotedInLeftList, PromotedInRightList, PromotedInParentList : TYNode<TKey>; posInList : Integer; constructor create(const key_ : TKey); end; type TRangeTree2DNode<TKey> = class parent, left, right : TRangeTree2DNode<TKey>; isLeftChild : Boolean; key : TKey; compareX : TComparison<TKey>; compareY : TComparison<TyNode<TKey>>; comparerY : IComparer<TyNode<TKey>>; // needded for binarySearch SortedListOfyNodes : TList<TyNode<TKey>>; public constructor create(const compareX_ : TComparison<TKey>; const compareY_ : TComparison<TyNode<TKey>>; const comparerY_ : IComparer<TyNode<TKey>>); procedure free; procedure initNode(const key_: TKey; const parent_: TRangeTree2DNode<TKey>); function find(const key : TKey) : TRangeTree2DNode<TKey>; protected procedure DeleteSubTreeAndGetSortedObjects(var List : TList<TRangeTree2DNode<TKey>>); protected function updatePosInYRange(const ky1,ky2 : TyNode<Tkey>) : Boolean; private posOfFirstInYRange, posOfLastInYRange : Integer; isLeaf : Boolean; procedure SplitNode(const idxStart, idxEnd : Integer;const SortedList : TList<TKey>; const DictOfKeyToPosInSortedList : TDictionary<TKey,Integer>); {overload;} procedure buildSortedListOfyNodes(const idxStart, idxEnd : Integer;const PrevSortedListOfyNodes : TList<TyNode<TKey>>; const DictOfKeyToPosInSortedList : TDictionary<TKey,Integer>); procedure updatePosInListOfyNodes; procedure cascade; procedure cascadeNodes(const PrevSortedListOfyNodes : TList<TyNode<TKey>>); function updatePosOfFirstInYRange(const PromPred, ky1 : TyNode<TKey>) : Boolean; function updatePosOfLastInYRange(const PromSucc, ky2 : TyNode<TKey>) : Boolean; function IsLeafInYRange : Boolean; end; type TRangeTree2D<TKey> = Class(TObject) compareX : TComparison<TKey>; compareY : TComparison<TKey>; private root : TRangeTree2DNode<TKey>; compareYNode : TComparison<TyNode<TKey>>; OutputSortedListOfKeys : TList<TKey>; FCount : Integer; // number of objects in the tree procedure FractionalCascading; procedure CollectSortedKeysOfSubtree(const node : TRangeTree2DNode<TKey>; const ky1, ky2 : TyNode<TKey>); procedure CollectSortedKeysGTk1(const node : TRangeTree2DNode<TKey>; const kx1 : TKey; const ky1, ky2 : TyNode<TKey>); procedure CollectSortedKeysLTk2(const node : TRangeTree2DNode<TKey>; const kx2 : TKey; const ky1, ky2 : TyNode<TKey>); function getBifurcationNode(const kx1,kx2 : TKey; const ky1, ky2 : TyNode<TKey>) : TRangeTree2DNode<TKey>; public constructor create(const compareX_ : TComparison<TKey>; const compareY_ : TComparison<TKey>); procedure BuildTree(const ListOfKeys : TList<TKey>); procedure Clear; procedure free; function find(const key : TKey): TRangeTree2DNode<TKey>; property Count : integer read FCount; function getSortedListOfMembersInRange(const key1, key2 : TKey) : TList<TKey>; end; implementation const CascadeConstant = 2; // Begin define methods of TYNode<TKey> constructor TyNode<TKey>.create(const key_ : TKey); begin inherited create; key := key_; isPromoted := FALSE; // initiallize pointers PromotedSucc := nil; PromotedPred := nil; NoPromotedSucc := nil; NoPromotedPred := nil; PromotedInLeftList := nil; PromotedInRIghtList := nil; PromotedInParentList := nil; end; // End define methods of TyNode<TKey> // begin define methods of TRangeTree2DNode<TKey> constructor TRangeTree2DNode<TKey>.create(const compareX_ : TComparison<TKey>; const compareY_ : TComparison<TyNode<TKey>>; const comparerY_ : IComparer<TyNode<TKey>>); {} begin inherited create; compareX := compareX_; compareY := compareY_; comparerY := comparerY_; SortedListOfyNodes := TList<TyNode<TKey>>.create; end; procedure TRangeTree2DNode<TKey>.free; var i: Integer; begin for i := 0 to SortedListOfyNodes.Count-1 do SortedListOfyNodes[i].Free; SortedListOfyNodes.Free; inherited Free; end; procedure TRangeTree2DNode<TKey>.initNode(const key_: TKey; const parent_: TRangeTree2DNode<TKey>); begin key := key_; right := nil; left := nil; parent := parent_; isLeaf := TRUE; end; function TRangeTree2DNode<TKey>.find(const key : TKey) : TRangeTree2DNode<TKey>; (* returns the node containing the key in calling Node's subtree or nil if not found *) var anInteger : Integer; begin anInteger := compareX(Self.key,key); if anInteger = 0 then begin RESULT := Self; Exit; end else if anInteger >0 then begin // look for key in left subtree if NOT Assigned(Self.left) then begin RESULT := nil; Exit; end; RESULT := Self.left.find(key); end else //then key > RESULT.key begin // look for key in right subtree if NOT Assigned(Self.right) then begin RESULT := nil; Exit; end; RESULT := Self.right.find(key); end; end; procedure TRangeTree2DNode<TKey>.DeleteSubTreeAndGetSortedObjects(var List : TList<TRangeTree2DNode<TKey>>); begin if isLeaf then List.Add(Self) else begin Self.left.DeleteSubTreeAndGetSortedObjects(List); Self.right.DeleteSubTreeAndGetSortedObjects(List); Self.Free; end; end; procedure TRangeTree2DNode<TKey>.buildSortedListOfyNodes(const idxStart, idxEnd : Integer;const PrevSortedListOfyNodes : TList<TyNode<TKey>>; const DictOfKeyToPosInSortedList : TDictionary<TKey,Integer>); var i, posInXList : Integer; yNode, newINode : TyNode<TKey>; begin for i := 0 to PrevSortedListOfyNodes.Count-1 do begin yNode := PrevSortedListOfyNodes[i]; posInXList := DictOfKeyToPosInSortedList[yNode.key]; if (posInXList < idxStart) OR (posInXList > idxEnd) then continue; newINode := TyNode<TKey>.create(yNode.key); SortedListOfyNodes.Add(newINode); end; end; procedure TRangeTree2DNode<TKey>.updatePosInListOfyNodes; var i : Integer; begin for i := 0 to SortedListOfyNodes.Count-1 do SortedListOfyNodes[i].posInList := i; end; procedure TRangeTree2DNode<TKey>.cascade; begin updatePosInListOfyNodes; if NOT isLeaf then begin // cascade next level left.cascadeNodes(SortedListOfyNodes); left.cascade; right.cascadeNodes(SortedListOfyNodes); right.cascade; end; end; procedure TRangeTree2DNode<TKey>.cascadeNodes(const PrevSortedListOfyNodes : TList<TyNode<TKey>>); var i, j, posInList, counter : Integer; yNode, NewyNode, NoPromPred, NoPromSucc, LastPromoted, LastNoPromoted : TyNode<TKey>; ListOfNPNotAssignedSuccesor, ListOfPNotAssignedSuccesor : TList<TyNode<TKey>>; begin {Avoid analysis of PrevSortedListOfYNodes twice, we only do when left.child} if isLeftChild then begin LastPromoted := nil; LastNoPromoted := nil; ListOfNPNotAssignedSuccesor := TList<TyNode<TKey>>.create; ListOfPNotAssignedSuccesor := TList<TyNode<TKey>>.create; for i := 0 to PrevSortedListOfyNodes.Count-1 do begin yNode := PrevSortedListOfyNodes[i]; if (i mod CascadeConstant) = 0 then begin yNode.isPromoted := TRUE; // revise left/right connections in prevSortedList yNode.NoPromotedPred := LastNoPromoted; ListOfPNotAssignedSuccesor.add(ynode); // asses PromSucc of Previuous NPNodes for j := 0 to ListOfNPNotAssignedSuccesor.Count-1 do ListOfNPNotAssignedSuccesor[j].PromotedSucc := yNode; ListOfNPNotAssignedSuccesor.Clear; // update LastPromoted := yNode; // promote yNode to next List NewyNode := TyNode<TKey>.create(yNode.key); // revise up/Down Conections yNode.PromotedInLeftList := NewyNode; NewyNode.PromotedInParentList := yNode; // search position for yNode and insert SortedListOfyNodes.BinarySearch(NewyNode,posInList,comparerY); SortedListOfyNodes.insert(posInList,NewYNode); end else begin yNode.isPromoted := FALSE; yNode.PromotedPred := LastPromoted; ListOfNPNotAssignedSuccesor.add(yNode); // revise NPSucc of Previous PromotedNodes for j := 0 to ListOfPNotAssignedSuccesor.Count-1 do ListOfPNotAssignedSuccesor[j].NoPromotedSucc := yNode; ListOfPNotAssignedSuccesor.Clear; // update LastNoPromoted := yNode; end; end; ListOfNPNotAssignedSuccesor.Free; ListOfPNotAssignedSuccesor.Free; end else // then rightChild, we just promote to next List begin for i := 0 to PrevSortedListOfyNodes.Count-1 do begin yNode := PrevSortedListOfyNodes[i]; if (i mod CascadeConstant) = 0 then begin NewyNode := TyNode<TKey>.create(yNode.key); // revise up/Down Conections yNode.PromotedInRightList := NewyNode; NewyNode.PromotedInParentList := yNode; // search position for yNode SortedListOfyNodes.BinarySearch(NewyNode,posInList,comparerY); SortedListOfyNodes.insert(posInList,NewYNode); end end; end; end; procedure TRangeTree2DNode<TKey>.SplitNode(const idxStart, idxEnd : Integer; const SortedList : TList<TKey>; const DictOfKeyToPosInSortedList : TDictionary<TKey,Integer>); var idxEndLeft, n, no2 : Integer; leafKey : TKey; begin n := idxEnd-idxStart; if n = 0 then begin leafkey := SortedList[idxStart]; key := leafkey; isLeaf := TRUE; end else begin no2 := Trunc(0.5*n); idxEndLeft := idxStart + no2; // revise CurrentNode key := SortedList[idxEndLeft]; isLeaf := FALSE; // Create New Left Node left := TRangeTree2DNode<TKey>.create(compareX,compareY,comparerY); left.parent := self; left.isLeftChild := TRUE; left.buildSortedListOfyNodes(idxStart,idxEndLeft,SortedListOfyNodes,DictOfKeyToPosInSortedList); left.SplitNode(idxStart,idxEndLeft,SortedList,DictOfKeyToPosInSortedList); // Create New Left Node right := TRangeTree2DNode<TKey>.create(compareX,compareY,comparerY); right.parent := self; right.isLeftChild := FALSE; right.buildSortedListOfyNodes(idxEndLeft+1,idxEnd,SortedListOfyNodes,DictOfKeyToPosInSortedList); right.SplitNode(idxEndLeft+1,idxEnd,SortedList,DictOfKeyToPosInSortedList); end; end; function TRangeTree2DNode<TKey>.updatePosOfFirstInYRange(const PromPred, ky1 : TyNode<TKey>) : Boolean; begin RESULT := TRUE; if Assigned(PromPred) then posOfFirstInYRange := promPred.posInList else posOfFirstInYRange := 0; // Trak ListUp for a sharper predecessor while compareY(ky1,SortedListOfyNodes[max(posOfFirstInYRange,0)]) = 1 do begin Inc(posOfFirstInYRange); if posOfFirstInYRange = SortedListOfyNodes.Count then begin RESULT := FALSE; EXIT end; end; end; function TRangeTree2DNode<TKey>.updatePosOfLastInYRange(const PromSucc, ky2 : TyNode<TKey>) : Boolean; begin RESULT := TRUE; if Assigned(promSucc) then posOfLastInYRange := promSucc.posInList else posOfLastInYRange := SortedListOfyNodes.Count-1; // Trak ListDown for a sharper successor while compareY(ky2,SortedListOfyNodes[min(posOfLastInYRange,SortedListOfyNodes.Count-1)]) = -1 do begin Dec(posOfLastInYRange); if posOfLastInYRange = 0 then begin RESULT := FALSE; EXIT end; end; end; function TRangeTree2DNode<TKey>.updatePosInYRange(const ky1,ky2 : TyNode<Tkey>) : Boolean; {Assumed node is not the root} var y1Node, y2Node, promSucc, promPred : TyNode<TKey>; begin // look for promoted Predecessor and successor yNodes in node's Y list // Find PromotedPredecessor In parent Node if parent.posOfFirstInYRange = 0 then promPred := nil else begin y1Node := parent.SortedListOfyNodes[parent.posOfFirstInYRange-1]; if y1Node.isPromoted then promPred := y1Node else promPred := y1Node.PromotedPred; end; // Find PromotedSuccessor In parent Node if (parent.posOfLastInYRange = parent.SortedListOfyNodes.Count-1) then PromSucc := nil else begin y2Node := parent.SortedListOfyNodes[parent.posOfLastInYRange+1]; if y2Node.isPromoted then promSucc := y2Node else promSucc := y2Node.PromotedSucc; end; // track promoted parent nodes to nodes Level and Solve Yrange problem if isLeftChild then begin if Assigned(promPred) then PromPred := PromPred.PromotedInLeftList; if updatePosOfFirstInYRange(PromPred,ky1) then begin if Assigned(promSucc) then PromSucc := promSucc.PromotedInLeftList; if NOT updatePosOfLastInYRange(PromSucc,ky2) then begin RESULT := FALSE; Exit; end; end else begin RESULT := FALSE; Exit; end; end else // Then RightChild begin if Assigned(promPred) then PromPred := PromPred.PromotedInRightList; if updatePosOfFirstInYRange(PromPred,ky1) then begin if Assigned(promSucc) then PromSucc := promSucc.PromotedInRightList; if NOT updatePosOfLastInYRange(PromSucc,ky2) then begin RESULT := FALSE; Exit; end; end else begin RESULT := FALSE; Exit; end; end; if posOfFirstInYRange > posOfLastInYRange then RESULT := FALSE else RESULT := TRUE; end; function TRangeTree2DNode<TKey>.IsLeafInYRange : Boolean; var i : Integer; yNode : TyNode<TKey>; begin for i := posOfFirstInYRange to posOfLastInYRange do begin yNode := SortedListOfyNodes[i]; if NOT Assigned(yNode.PromotedInParentList) then begin RESULT := TRUE; Exit; end; end; // reached this line all yNodes in [PosOfFrst,PosOfLast] have been promoted from parent RESULT := FALSE; end; // End Define methods of TRangeTree2DNode<TKey> // Begin define methods of TRangeTree2D constructor TRangeTree2D<TKey>.create(const compareX_ : TComparison<TKey>; const compareY_ : TComparison<TKey>); begin inherited create; root := nil; compareX := compareX_; compareY := compareY_; compareYNode := function(const left, right: TyNode<TKey>): Integer begin RESULT := compareY(left.key,right.key); end; OutputSortedListOfKeys := TList<TKey>.create; end; procedure TRangeTree2D<TKey>.Clear; var ListOfNodes : TList<TRangeTree2DNode<TKey>>; node : TRangeTree2DNode<TKey>; i : Integer; begin if Assigned(root) then begin ListOfNodes := TList<TRangeTree2DNode<TKey>>.create; root.DeleteSubTreeAndGetSortedObjects(ListOfNodes); for i := 0 to ListOfNodes.Count-1 do begin node := ListOfNodes[i]; node.free; end; ListOfNodes.free; root := nil; end; OutputSortedListOfKeys.Clear; end; procedure TRangeTree2D<TKey>.free; begin Clear; OutputSortedListOfKeys.Free; inherited free; end; function TRangeTree2D<TKey>.find(const key : TKey) : TRangeTree2DNode<TKey>; (* returns node containing key or nil if it is not there *) begin RESULT := Self.root.find(key); end; procedure TRangeTree2D<TKey>.BuildTree(const ListOfKeys : TList<TKey>); var compareXFun : IComparer<TKey>; compareYFun : IComparer<TyNode<TKey>>; ListOfKeysSortedByX : TList<TKey>; i : Integer; tmpKey : TKey; yNode : TyNode<TKey>; DictOfKeyToPosInXList : TDictionary<TKey,Integer>; node : TRangeTree2DNode<TKey>; begin Clear; // construct comparers compareXFun := TComparer<TKey>.Construct(compareX); compareYFun := TComparer<TyNode<TKey>>.Construct(compareYNode); // XSorted List of Keys ListOfKeysSortedByX := TList<TKey>.create; for i := 0 to ListOfKeys.Count-1 do ListOfKeysSortedByX.Add(ListOfKeys[i]); ListOfKeysSortedByX.Sort(compareXFun); // Build root Node root := TRangeTree2DNode<TKey>.Create(compareX,compareYNode,compareYFun); DictOfKeyToPosInXList := TDictionary<TKey,Integer>.create; for i := 0 to ListOfKeysSortedByX.Count-1 do begin tmpKey := ListOfKeysSortedByX[i]; // Build yNode yNode := TyNode<TKey>.create(tmpkey); DictOfKeyToPosInXList.Add(yNode.key,i); root.SortedListOfYNodes.Add(yNode); end; root.SortedListOfYNodes.Sort(compareYFun); root.splitNode(0,ListOfKeysSortedByX.Count-1,ListOfKeysSortedByX,DictOfKeyToPosInXList); FractionalCascading; FCount := ListOfKeys.Count; // Free memory DictOfKeyToPosInXList.Free; ListOfKeysSortedByX.Free; end; procedure TRangeTree2D<TKey>.FractionalCascading; begin if NOT Assigned(root) then Exit; root.cascade; end; function TRangeTree2D<TKey>.getBifurcationNode(const kx1,kx2 : TKey; const ky1, ky2 : TyNode<TKey>) : TRangeTree2DNode<TKey>; {assumed kx1<kx2, ky1<ky2} var node : TRangeTree2DNode<TKey>; int1, int2, posky1, posky2 : Integer; promSucc, promPred, y1Node, y2Node : TyNode<TKey>; begin RESULT := nil; // BinarySearch YRange just once, At the root with root do begin SortedListOfyNodes.BinarySearch(ky1,posOfFirstInYRange,comparerY); SortedListOfyNodes.BinarySearch(ky2,posOfLastInYRange,comparerY); if posOfFirstInYRange = posOfLastInYRange then Exit // no members in YRange else posOfLastInYRange := posOfLastInYRange-1; end; // Find BifurcationNode node := root; while Assigned(node) do begin int1 := node.compareX(kx1,node.key); if int1 <> 1 then begin int2 := node.compareX(kx2,node.key); if int2 = 1 then begin RESULT := node; Exit; end else node := node.left; end else node := node.right; if Assigned(node) then begin if NOT node.updatePosInYRange(ky1,ky2) then Exit; end; end; end; procedure TRangeTree2D<TKey>.CollectSortedKeysOfSubtree(const node : TRangeTree2DNode<TKey>; const ky1, ky2 : TyNode<TKey>); begin if node.isLeaf then begin if node.IsLeafInYRange then OutputSortedListOfKeys.Add(node.key); end else begin if node.left.updatePosInYRange(ky1,ky2) then CollectSortedKeysOfSubtree(node.left,ky1,ky2); if node.right.updatePosInYRange(ky1,ky2) then CollectSortedKeysOfSubtree(node.right,ky1,ky2); end; end; procedure TRangeTree2D<TKey>.CollectSortedKeysGTk1(const node : TRangeTree2DNode<TKey>; const kx1 : TKey; const ky1, ky2 : TyNode<TKey>); {assumed that if node = root then root is leaf} var anInteger : Integer; begin anInteger := node.compareX(kx1,node.key); if node.isLeaf then begin if (anInteger <> 1) AND node.IsLeafInYRange then OutputSortedListOfKeys.Add(node.key); end else begin if anInteger <> 1 then begin if node.left.updatePosInYRange(ky1,ky2) then CollectSortedKeysGTk1(node.left,kx1,ky1,ky2); if node.right.updatePosInYRange(ky1,ky2) then CollectSortedKeysOfSubtree(node.right,ky1,ky2); end else begin if node.right.updatePosInYRange(ky1,ky2) then CollectSortedKeysGTk1(node.right,kx1,ky1,ky2); end; end; end; procedure TRangeTree2D<TKey>.CollectSortedKeysLTk2(const node : TRangeTree2DNode<TKey>; const kx2 : TKey; const ky1, ky2 : TyNode<TKey>); {assumed that if node = root then root is leaf} var anInteger : Integer; begin anInteger := node.compareX(kx2,node.key); if node.isLeaf then begin if (anInteger <> -1) AND node.IsLeafInYRange then OutputSortedListOfKeys.Add(node.key); end else begin if anInteger <> 1 then begin // node <> root (otherwise posInYRange Already assigned) if node.left.updatePosInYRange(ky1,ky2) then CollectSortedKeysLTk2(node.left,kx2,ky1,ky2); end else begin if node.left.updatePosInYRange(ky1,ky2) then CollectSortedKeysOfSubtree(node.left,ky1,ky2); if node.right.updatePosInYRange(ky1,ky2) then CollectSortedKeysLTk2(node.right,kx2,ky1,ky2); end end; end; function TRangeTree2D<TKey>.getSortedListOfMembersInRange(const key1, key2 : TKey) : TList<TKey>; { outputs the sorted list of keys satisfying k1 < k < k2 : Note input is sorted to satisfy k1<k2 } var node, BifurcationNode : TRangeTree2DNode<TKey>; int1, int2 : Integer; kx1, kx2 : TKey; ky1, ky2, dummy1, dummy2 : TyNode<TKey>; begin OutputSortedListOfKeys.Clear; RESULT := OutputSortedListOfKeys; if Assigned(root) then begin // get X range [kx1,kx2] if root.compareX(key1,key2) = 1 then begin kx1 := key2; kx2 := key1; end else begin kx1 := key1; kx2 := key2; end; // get Y range [ky1,ky2] dummy1 := TyNode<TKey>.create(key1); dummy2 := TyNode<TKey>.create(key2); if root.compareY(dummy1,dummy2) = 1 then begin ky1 := dummy2; ky2 := dummy1; end else begin ky1 := dummy1; ky2 := dummy2; end; // in case of NoPoints in YRange BifNode = nil BifurcationNode := getBifurcationNode(kx1,kx2,ky1,ky2); if Assigned(BifurcationNode) then begin if BifurcationNode.isLeaf then begin CollectSortedKeysGTk1(BifurcationNode,kx1,ky1,ky2); CollectSortedKeysLTk2(BifurcationNode,kx2,ky1,ky2); end else begin if BifurcationNode.left.updatePosInYRange(ky1,ky2) then CollectSortedKeysGTk1(BifurcationNode.left,kx1,ky1,ky2); if BifurcationNode.right.updatePosInYRange(ky1,ky2) then CollectSortedKeysLTk2(BifurcationNode.right,kx2,ky1,ky2); end; end; // free memory ky1.Free; ky2.Free; end; end; type TSPt2D = record x, y : Single; ptNo : Integer; end; procedure HowToUseExample; var compareXYPtNo, compareYXPtNo : TComparison<TSPt2D>; RT2D : TRangeTree2D<TSPt2D>; ListOfKeys, L : TList<TSPt2D>; pt, k1, k2 : TSPt2D; i : Integer; begin // generate 100 random points in [0,1]x[0,1] ListOfKeys := TList<TSPt2D>.Create;; for i := 0 to 100 do begin pt.x := random; pt.y := random; pt.ptNo := i; // Add to list ListOfKeys.Add(pt); end; // RT2D is an object of the class TRangeTree2D<TSPt2D>, that is a TRangeTree2D<TKey> // where TKey is TSPt2D, a Range Tree of 2D points. the constructor requires two comparison // function <_X and <_Y to be applied on objects of the class Tkey. As they are // constructed below no two keys in ListOfKeys can be equal, since they all have a // different pointNo. This permits to have repeated (x,y) points in the Tree, // corresponding to keys that are different wrt the comparison function. compareXYPtNo := function(const left, right: TSPt2D): Integer begin RESULT := TComparer<Single>.Default.Compare(left.x,right.x); if RESULT = 0 then begin RESULT := TComparer<Single>.Default.Compare(left.y,right.y); if RESULT =0 then RESULT := TComparer<Integer>.Default.Compare(left.PtNo,right.PtNo); end; end; compareYXPtNo := function(const left, right: TSPt2D): Integer begin RESULT := TComparer<Single>.Default.Compare(left.y,right.y); if RESULT = 0 then begin RESULT := TComparer<Single>.Default.Compare(left.x,right.x); if RESULT =0 then RESULT := TComparer<Integer>.Default.Compare(left.PtNo,right.PtNo); end; end; RT2D := TRangeTree2D<TSPt2D>.Create(compareXYPtNo,compareYXPtNo); // Fill up the structure with a list of keys such that no equality is possible // (i.e No two keys are equal) under both comparison functions previously defined. RT2D.BuildTree(ListOfKeys); // Create my range defined by [k1,k2], being k1 the BottomLeftMost point and k2 the TopRightMost // point of the axis aligned quadrilateral defining the interval [k1.x,k2.x]x[k1.y,k2.y] k1.x := 0.2; k1.y := 0.4; k2.x := 0.8; k2.y := 0.5; // defines 2D interval [0.2,0.8] x [0.4,0.5] // use ptNo on the keys to make Closed/Open Intervals k1.ptNo := -1; k2.ptNo := High(Integer); // closed interval // for open intervals use // k1.ptNo := High(Integer); // k2.ptNo := -1; // semi-Open intervals are possible // get all members of ListOfKeys in the range [k1,k2], note L is a internal field // of the class and should ot be freed L := RT2D.getSortedListOfMembersInRange(k1,k2); // Free memory ListOfKeys.Free; RT2D.free; end; end.
{***************************************************************************} { TMiniGrid component } { for Delphi } { } { written by mini188 } { Email : mini188.com@qq.com } { } {***************************************************************************} unit uMiniGrid; interface uses Windows, Classes, Contnrs, Grids, SysUtils, RTLConsts, Graphics, Controls, Messages, ShellAPI, StrUtils, IniFiles; type TMiniGrid = class; TColumns = class; TUrlCache = class FullData: string; Url: string; Text: string; Col: Integer; Row: Integer; end; TColumn = class(TComponent) private FOwner: TColumns; FTitle: string; FFieldName: string; FWidth: Integer; FFontColor: TColor; FHeadBackgroundColor: TColor; FFont: TFont; procedure SetFieldName(const Value: string); procedure SetTitle(const Value: string); procedure SetWidth(const Value: Integer); public constructor Create(AOwner: TColumns); destructor Destroy; override; property Title: string read FTitle write SetTitle; property FieldName: string read FFieldName write SetFieldName; property Width: Integer read FWidth write SetWidth; property Font: TFont read FFont write FFont; property HeadBackgroundColor: TColor read FHeadBackgroundColor write FHeadBackgroundColor; end; TColumns = class(TObjectList) private FOwnerGrid: TMiniGrid; function GetColumn(Index: Integer): TColumn; public constructor Create(AOwner: TMiniGrid); destructor Destroy; override; function AddColumn: TColumn; procedure DeleteColumn(AIndex: Integer); procedure Changed; property Columns[Index: Integer]: TColumn read GetColumn; end; TMergeInfo = class(TPersistent) private FRowSpan: Integer; FRow: Integer; FColSpan: Integer; FCol: Integer; FPaintId: Integer; public property Col: Integer read FCol write FCol; property Row: Integer read FRow write FRow; property RowSpan: Integer read FRowSpan write FRowSpan; property ColSpan: Integer read FColSpan write FColSpan; property PaintId: Integer read FPaintId write FPaintId; end; TMergeInfos = class(TObjectList) private function GetMergeInfo(AIndex: Integer): TMergeInfo; public function IsMergeCell(ACol, ARow: Integer): Boolean; function IsBaseCell(ACol, ARow: Integer): Boolean; function FindMergeInfo(ACol, ARow: Integer): TMergeInfo; function FindBaseCell(ACol, ARow: Integer): TMergeInfo; property MerageInfo[AIndex: Integer]: TMergeInfo read GetMergeInfo; end; TMiniGrid = class(TStringGrid) private FColumns: TColumns; FMergeInfos: TMergeInfos; FActiveColor: TColor; FPaintID: Integer; FOldCursor: TCursor; FUrlCache: TStrings; FFixedFont: TFont; procedure DoInitColumns; procedure Paint; override; procedure RepaintCell(ACol, ARow: integer); procedure DoDrawAxisLines(ARect: TRect; AState: TGridDrawState); procedure DoDrawText(const AText: string; ARect: TRect; AWordBreak: Boolean); overload; procedure DoDrawText(const AText: string; ACol, ARow: Integer; ARect: TRect; AWordBreak: Boolean); overload; procedure DoDrawUrlText(const AText: string; ARect: TRect); procedure WMPaint(var Msg: TWMPAINT); message WM_PAINT; function IsUrl(const AText: string): Boolean; function PtInUrlRange(const X, Y: Integer): Boolean; function CellRect(ACol, ARow: Integer): TRect; function GetCellEx(ACol, ARow: Integer): String; procedure SetCellEx(ACol, ARow: Integer; const Value: String); function GetColCount: Integer; procedure SetColCount(const Value: Integer); function AnalysisUrl(const ASrcText: string; ACol, ARow: Integer): TUrlCache; function GetUrlCacheKey(ACol, ARow: Integer): string; function FindUrlCache(ACol, ARow: Integer): TUrlCache; //隐藏此属性,不让直接访问 property ColCount: Integer read GetColCount write SetColCount; protected procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; function SelectCell(ACol, ARow: Longint): Boolean; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure MergeCells(ABaseCol, ABaseRow, ARowSpan, AColSpan: Integer); property Columns: TColumns read FColumns; property MergeInfos: TMergeInfos read FMergeInfos; property ActiveColor: TColor read FActiveColor write FActiveColor default clHighlight; property PaintId: Integer read FPaintID; property Cells[ACol, ARow: Integer]: String read GetCellEx write SetCellEx; published property FixedFont: TFont read FFixedFont write FFixedFont; end; implementation /// <summary> /// 字符串定位函数 /// 因为Delphi6及以下版本并不支持此函数,所以从delphi xe版本迁移代码,省略了asm部分 /// </summary> function PosEx(const SubStr, S: string; Offset: Integer = 1): Integer; var I, LIterCnt, L, J: Integer; PSubStr, PS: PChar; begin if SubStr = '' then begin Result := 0; Exit; end; { Calculate the number of possible iterations. Not valid if Offset < 1. } LIterCnt := Length(S) - Offset - Length(SubStr) + 1; { Only continue if the number of iterations is positive or zero (there is space to check) } if (Offset > 0) and (LIterCnt >= 0) then begin L := Length(SubStr); PSubStr := PChar(SubStr); PS := PChar(S); Inc(PS, Offset - 1); for I := 0 to LIterCnt do begin J := 0; while (J >= 0) and (J < L) do begin if (PS + I + J)^ = (PSubStr + J)^ then Inc(J) else J := -1; end; if J >= L then begin Result := I + Offset; Exit; end; end; end; Result := 0; end; { TMiniGrid } constructor TMiniGrid.Create(AOwner: TComponent); begin inherited; FDoubleBuffered := True; DefaultDrawing := False; FFixedFont := TFont.Create; FColumns := TColumns.Create(Self); FMergeInfos := TMergeInfos.Create; FUrlCache := THashedStringList.Create; FixedCols := 1; FixedRows := 1; RowCount := 2; ColWidths[0] := 20; FActiveColor := clHighlight; FPaintID := 0; FOldCursor := Cursor; end; destructor TMiniGrid.Destroy; var i: integer; begin if Assigned(FFixedFont) then FreeAndNil(FFixedFont); if Assigned(FColumns) then FreeAndNil(FColumns); if Assigned(FMergeInfos) then FreeAndNil(FMergeInfos); if Assigned(FUrlCache) then begin for i := FUrlCache.Count - 1 downto 0 do FUrlCache.Objects[i].Free; FreeAndNil(FUrlCache); end; inherited; end; procedure TMiniGrid.DoInitColumns; var i: Integer; objCol: TColumn; begin for i := 0 to FColumns.Count - 1 do begin objCol := FColumns.Columns[i]; ColWidths[i+1] := objCol.Width; Cols[i+1].Text := objCol.Title; end; end; function TMiniGrid.CellRect(ACol, ARow: Integer): TRect; function _CalcRect(c, r, spanx, spany: Integer): TRect; var i: Integer; begin if c < LeftCol then c := LeftCol; if r < TopRow then r := TopRow; Result := inherited CellRect(c, r); for i := c+1 to (c+spanx) do Result.Right := Result.Right + ColWidths[i]; if c+1 > (c+spanx) then Result.Right := Result.Right else Result.Right := Result.Right + spanx*GridLineWidth; for i := r+1 to (r+spany) do Result.Bottom := Result.Bottom + RowHeights[i]; if r+1 > (r+spany) then Result.Bottom := Result.Bottom else Result.Bottom := Result.Bottom + spany*GridLineWidth; end; var objMergeInfo: TMergeInfo; begin if not FMergeInfos.IsMergeCell(ACol, ARow) then Result := inherited CellRect(ACol, ARow) else begin objMergeInfo := FMergeInfos.FindBaseCell(ACol, ARow); if objMergeInfo <> nil then Result := _CalcRect(objMergeInfo.Col, objMergeInfo.Row, objMergeInfo.ColSpan, objMergeInfo.RowSpan); end; end; procedure TMiniGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); var sCellText: string; objMI: TMergeInfo; begin Canvas.Font.Assign(Font); sCellText := Cells[ACol, ARow]; if FMergeInfos.IsMergeCell(ACol, ARow) and not FMergeInfos.IsBaseCell(ACol, ARow) then begin ARect := CellRect(ACol, ARow); objMI := FMergeInfos.FindBaseCell(ACol, ARow); if (objMI <> nil) and (objMI.PaintId <> FPaintID) then begin if ((Selection.Left <= (objMI.Col+objMi.ColSpan)) and (Selection.Top <= (objMI.Row+objMI.RowSpan))) and ((Selection.Left >= objMI.Col) and (Selection.Top >= objMI.Row)) then AState := AState + [gdSelected] else AState := AState - [gdSelected]; objMI.PaintId := FPaintID; DrawCell(objMI.Col, objMI.Row, ARect, AState); end; Exit; end; ARect := CellRect(ACol, ARow); if gdFixed in AState then Canvas.Brush.Color := FixedColor else if gdSelected in AState then Canvas.Brush.Color := FActiveColor else Canvas.Brush.Color := Color; Canvas.Pen.Color := Canvas.Brush.Color; Canvas.Rectangle(ARect); if gdFixed in AState then begin Canvas.Font.Assign(FFixedFont); Canvas.Pen.Color := clGray; Canvas.Pen.Width := 1; end else begin Canvas.Font.Assign(FColumns.Columns[ACol-1].Font); if GridLineWidth > 0 then Canvas.Pen.Color := clGray; Canvas.Pen.Width := GridLineWidth; end; DoDrawAxisLines(ARect, AState); if TopRow <= ARow then begin InflateRect(ARect, -GridLineWidth, -GridLineWidth); DoDrawText(sCellText, ACol, ARow, ARect, True); end; if Assigned(OnDrawCell) then OnDrawCell(Self, ACol, ARow, ARect, AState); end; procedure TMiniGrid.DoDrawAxisLines(ARect: TRect; AState: TGridDrawState); begin if ((goHorzLine in Options) and not (gdFixed in AState)) or ((goFixedHorzLine in Options) and (gdFixed in AState)) then begin Canvas.MoveTo(ARect.Left, ARect.Bottom); Canvas.LineTo(ARect.Right, ARect.Bottom); end; if ((goVertLine in Options) and not (gdFixed in AState)) or ((goFixedVertLine in Options) and (gdFixed in AState)) then begin if UseRightToLeftAlignment then begin Canvas.MoveTo(ARect.Right,ARect.Bottom); Canvas.LineTo(ARect.Right,ARect.Top); end else begin Canvas.MoveTo(ARect.Right, ARect.Bottom); Canvas.LineTo(ARect.Right, ARect.Top); end; end; end; procedure TMiniGrid.MergeCells(ABaseCol, ABaseRow, ARowSpan, AColSpan: Integer); var mergeInfo: TMergeInfo; begin mergeInfo := TMergeInfo.Create; FMergeInfos.Add(mergeInfo); mergeInfo.Col := ABaseCol; mergeInfo.Row := ABaseRow; mergeInfo.RowSpan := ARowSpan; mergeInfo.ColSpan := AColSpan; end; function TMiniGrid.SelectCell(ACol, ARow: Integer): Boolean; begin RepaintCell(Col,Row); Result := inherited SelectCell(Acol, ARow); RepaintCell(ACol,ARow); end; procedure TMiniGrid.RepaintCell(ACol, ARow: integer); var rc: TRect; begin if HandleAllocated Then begin rc := CellRect(ACol, ARow); InvalidateRect(Handle, @rc, True); end; end; procedure TMiniGrid.Paint; begin inherited; inc(FPaintID); end; /// <summary> /// 绘制Html格式的链接内容 /// </summary> /// <param name="AText"> 原始文本</param> /// <param name="ARect"> 内容矩形框</param> procedure TMiniGrid.DoDrawUrlText(const AText: string; ARect: TRect); begin if AText = '' then Exit; Canvas.Font.Style := Canvas.Font.Style + [fsUnderline]; Canvas.Font.Color := clBlue; DrawText(Canvas.Handle, PChar(AText), Length(AText), ARect, DT_WORDBREAK or DT_END_ELLIPSIS); Canvas.Font.Style := Canvas.Font.Style - [fsUnderline]; Canvas.Font.Color := Font.Color; end; procedure TMiniGrid.DoDrawText(const AText: string; ARect: TRect; AWordBreak: Boolean); var rc: TRect; oColor: TColor; dDrawStyle: DWord; begin rc := ARect; oColor := Canvas.Font.Color; dDrawStyle := DT_END_ELLIPSIS; if AWordBreak then dDrawStyle := dDrawStyle or DT_WORDBREAK; if IsUrl(AText) then begin Canvas.Font.Style := Canvas.Font.Style + [fsUnderline]; Canvas.Font.Color := clBlue; end; DrawTextEx(Canvas.Handle, PChar(AText), Length(AText), rc, dDrawStyle, nil); if IsUrl(AText) then begin Canvas.Font.Style := Canvas.Font.Style - [fsUnderline]; Canvas.Font.Color := oColor; end; end; function TMiniGrid.IsUrl(const AText: string): Boolean; begin Result := (Pos('://', AText) > 0) or (Pos('mailto:', AText) > 0); end; /// <summary> /// 解析html格式<A>标签,如下所示 /// exmaple: /// <A href="http://www.cnblogs.com/5207/">Click here</A> /// </summary> /// <param name="ASrcText"></param> /// <returns></returns> function TMiniGrid.AnalysisUrl(const ASrcText: string; ACol, ARow: Integer): TUrlCache; var oColor: TColor; sText, sUrl, sContent: string; iPos, iBegin, iEnd: Integer; begin Result := TUrlCache.Create; Result.FullData := ASrcText; Result.Col := ACol; Result.Row := ARow; iBegin := 0; iBegin := PosEx('<A', ASrcText, 1); if iBegin > 0 then begin iEnd := PosEx('</A>', ASrcText, iBegin); sContent := Copy(ASrcText, iBegin, iEnd+Length('</A>')); iPos := PosEx('href=', ASrcText, 1); if (iPos > 0) then begin sUrl := ''; Inc(iPos, Length('href=')); while ASrcText[iPos] <> '>' do begin sUrl := sUrl + ASrcText[iPos]; Inc(iPos); end; StringReplace(sUrl, '"', '', [rfReplaceAll, rfIgnoreCase]); StringReplace(sUrl, '''', '', [rfReplaceAll, rfIgnoreCase]); Result.Url := sUrl; end; iPos := PosEx('>', ASrcText, 1); if (iPos > 0) then begin Inc(iPos); sText := ''; while ASrcText[iPos] <> '<' do begin sText := sText + ASrcText[iPos]; Inc(iPos); end; Result.Text := sText; end; end else if IsUrl(ASrcText) then begin Result.Url := ASrcText; Result.Text := ASrcText; end; //缓存url资源 FUrlCache.AddObject(GetUrlCacheKey(ACol, ARow), Result); end; function TMiniGrid.PtInUrlRange(const X, Y: Integer): Boolean; var gc: TGridCoord; sData: String; cellRect: TRect; p: TPoint; objUrlCache: TUrlCache; begin Result := False; gc := Self.MouseCoord(X,Y); if (gc.X < 0) or (gc.Y < 0) then Exit; sData := Self.Cells[gc.X, gc.Y]; if IsUrl(sData) then begin objUrlCache := FindUrlCache(gc.X, gc.Y); if objUrlCache <> nil then sData := objUrlCache.Text; p.X := X; p.Y := Y; cellRect := Self.CellRect(gc.X, gc.Y); DrawText(Canvas.Handle, PChar(sData), Length(sData), cellRect, DT_WORDBREAK or DT_CALCRECT); Result := (gc.Y > 0) and (gc.Y < Self.RowCount)and PtInRect(cellRect, p); end; end; procedure TMiniGrid.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if PtInUrlRange(X, Y) then Cursor := crHandPoint else Cursor := FOldCursor; end; procedure TMiniGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var gc: TGridCoord; sUrl: String; p: TPoint; objUrlCache: TUrlCache; begin inherited; if PtInUrlRange(X, Y) then begin gc := Self.MouseCoord(X, Y); objUrlCache := FindUrlCache(gc.X, gc.Y); sUrl := Self.Cells[gc.X, gc.Y]; if objUrlCache <> nil then sUrl := objUrlCache.Url; ShellExecute(self.handle, 'open', PChar(sUrl), 0, 0, SW_SHOW); end; end; procedure TMiniGrid.WMPaint(var Msg: TWMPaint); var DC, MemDC: HDC; MemBitmap, OldBitmap: HBITMAP; PS: TPaintStruct; begin if not FDoubleBuffered or (Msg.DC <> 0) then begin if not (csCustomPaint in ControlState) and (ControlCount = 0) then inherited else PaintHandler(Msg); end else begin DC := GetDC(0); MemBitmap := CreateCompatibleBitmap(DC, ClientRect.Right, ClientRect.Bottom); ReleaseDC(0, DC); MemDC := CreateCompatibleDC(0); OldBitmap := SelectObject(MemDC, MemBitmap); try DC := BeginPaint(Handle, PS); Perform(WM_ERASEBKGND, MemDC, MemDC); Msg.DC := MemDC; WMPaint(Msg); Msg.DC := 0; BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, MemDC, 0, 0, SRCCOPY); EndPaint(Handle, PS); finally SelectObject(MemDC, OldBitmap); DeleteDC(MemDC); DeleteObject(MemBitmap); end; end; end; function TMiniGrid.GetCellEx(ACol, ARow: Integer): String; var objMI: TMergeInfo; begin if FMergeInfos.IsMergeCell(ACol, ARow) then begin objMI := FMergeInfos.FindBaseCell(ACol, ARow); Result := inherited Cells[objMI.Col, objMi.Row]; end else Result := inherited Cells[ACol, ARow]; end; procedure TMiniGrid.SetCellEx(ACol, ARow: Integer; const Value: String); var objMI: TMergeInfo; begin if FMergeInfos.IsMergeCell(ACol, ARow) then begin objMI := FMergeInfos.FindBaseCell(ACol, ARow); inherited Cells[objMI.Col, objMI.Row] := Value; if Assigned(Parent) then RepaintCell(ACol, ARow); end else begin inherited Cells[ACol, ARow] := Value; end; end; function TMiniGrid.GetColCount: Integer; begin Result := inherited ColCount; end; procedure TMiniGrid.SetColCount(const Value: Integer); begin inherited ColCount := Value+1; DoInitColumns; end; function TMiniGrid.GetUrlCacheKey(ACol, ARow: Integer): string; begin Result := Format('%d/%d', [ACol, ARow]); end; function TMiniGrid.FindUrlCache(ACol, ARow: Integer): TUrlCache; var idx: Integer; begin Result := nil; idx := FUrlCache.IndexOf(GetUrlCacheKey(ACol, ARow)); if idx <> -1 then Result := TUrlCache(FUrlCache.Objects[idx]); end; procedure TMiniGrid.DoDrawText(const AText: string; ACol, ARow: Integer; ARect: TRect; AWordBreak: Boolean); var objUrlCache: TUrlCache; begin if IsUrl(AText) then begin objUrlCache := FindUrlCache(ACol, ARow); if objUrlCache = nil then objUrlCache := AnalysisUrl(AText, ACol, ARow); DoDrawUrlText(objUrlCache.Text, ARect); end else DoDrawText(AText, ARect, True); end; { TColumns } function TColumns.AddColumn: TColumn; begin Result := TColumn.Create(Self); Add(Result); FOwnerGrid.ColCount := Count; end; procedure TColumns.Changed; begin FOwnerGrid.ColCount := Count; end; constructor TColumns.Create(AOwner: TMiniGrid); begin inherited Create(True); FOwnerGrid := AOwner; end; procedure TColumns.DeleteColumn(AIndex: Integer); begin if (AIndex < 0) or (AIndex >= Count) then Error(@SListIndexError, AIndex); self.Delete(AIndex); FOwnerGrid.DeleteColumn(AIndex+1); end; destructor TColumns.Destroy; begin inherited; end; function TColumns.GetColumn(Index: Integer): TColumn; begin if (Index < 0) or (Index >= Count) then Error(@SListIndexError, Index); Result := TColumn(Items[Index]); end; { TColumn } constructor TColumn.Create(AOwner: TColumns); begin FOwner := AOwner; FWidth := 100; FFontColor := clWindowText; FHeadBackgroundColor := clWindow; FFont := TFont.Create; end; destructor TColumn.Destroy; begin inherited; if Assigned(FFont) then FreeAndNil(FFont); end; procedure TColumn.SetFieldName(const Value: string); begin FFieldName := Value; FOwner.Changed; end; procedure TColumn.SetTitle(const Value: string); begin FTitle := Value; FOwner.Changed; end; procedure TColumn.SetWidth(const Value: Integer); begin FWidth := Value; FOwner.Changed; end; { TMergeInfos } function TMergeInfos.FindBaseCell(ACol, ARow: Integer): TMergeInfo; var i: Integer; begin for i := 0 to Count - 1 do begin with MerageInfo[i] do begin if (ACol >= Col) and (ACol <= (Col+ColSpan)) and (ARow >= Row) and (ARow <= (Row+RowSpan))then begin Result := MerageInfo[i]; Exit; end; end; end; Result := nil; end; function TMergeInfos.FindMergeInfo(ACol, ARow: Integer): TMergeInfo; var i: Integer; begin for i := 0 to Count - 1 do begin if (MerageInfo[i].Col = ACol) and (MerageInfo[i].Row = ARow) then begin Result := MerageInfo[i]; Exit; end; end; Result := nil; end; function TMergeInfos.GetMergeInfo(AIndex: Integer): TMergeInfo; begin if (AIndex < 0) or (AIndex >= Count) then Error(@SListIndexError, AIndex); Result := TMergeInfo(Items[AIndex]); end; function TMergeInfos.IsBaseCell(ACol, ARow: Integer): Boolean; var i: Integer; begin for i := 0 to Count - 1 do begin if (MerageInfo[i].Col = ACol) and (MerageInfo[i].Row = ARow) then begin Result := True; Exit; end; end; Result := False; end; function TMergeInfos.IsMergeCell(ACol, ARow: Integer): Boolean; var i: Integer; begin Result := False; for i := 0 to Count - 1 do begin with MerageInfo[i] do begin if (ACol >= Col) and (ACol <= (Col+ColSpan)) and (ARow >= Row) and (ARow <= (Row+RowSpan))then begin Result := True; Exit; end; end; end; end; end.
{ HighLighter pou Elphy C'est SynHighLighterPas modifié. La fonction de codage est Function HighLightCode(st:string):integer; var i:integer; begin st:=UpperCase(st); result:=0; for i:=1 to length(st) do if st[i] in ['A'..'Z'] then inc(result,ord(st[i])-64); end; Les mots-clés sont introduits dans la fonction funcXXX où XXX est le code du mot clé On ajoute InitProcess(147), InitProcess0(147), Process(95), ProcessCont(147), EndProcess(118) } {------------------------------------------------------------------------------ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: SynHighlighterPas.pas, released 2000-04-17. The Original Code is based on the mwPasSyn.pas file from the mwEdit component suite by Martin Waldenburg and other developers, the Initial Author of this file is Martin Waldenburg. Portions created by Martin Waldenburg are Copyright (C) 1998 Martin Waldenburg. All Rights Reserved. Contributors to the SynEdit and mwEdit projects are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: SynHighlighterPas.pas,v 1.30 2005/01/28 16:53:24 maelh Exp $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net Known Issues: -------------------------------------------------------------------------------} { @abstract(Provides a Pascal/Delphi syntax highlighter for SynEdit) @author(Martin Waldenburg) @created(1998, converted to SynEdit 2000-04-07) @lastmod(2001-11-21) The SynHighlighterPas unit provides SynEdit with a Object Pascal syntax highlighter. Two extra properties included (DelphiVersion, PackageSource): DelphiVersion - Allows you to enable/disable the highlighting of various language enhancements added in the different Delphi versions. PackageSource - Allows you to enable/disable the highlighting of package keywords } {$IFNDEF QSYNHIGHLIGHTERPAS} unit SynHighlighterElphy; {$ENDIF} {$I SynEdit.inc} interface uses {$IFDEF SYN_CLX} QGraphics, QSynEditTypes, QSynEditHighlighter, {$ELSE} Windows, Graphics, SynEditTypes, SynEditHighlighter, {$ENDIF} SysUtils, Classes, debug0; type TtkTokenKind = (tkAsm, tkComment, tkIdentifier, tkKey, tkNull, tkNumber, tkSpace, tkString, tkSymbol, tkUnknown, tkFloat, tkHex, tkDirec, tkChar); TRangeState = (rsANil, rsAnsi, rsAnsiAsm, rsAsm, rsBor, rsBorAsm, rsProperty, rsExports, rsDirective, rsDirectiveAsm, rsUnKnown); TProcTableProc = procedure of object; PIdentFuncTableFunc = ^TIdentFuncTableFunc; TIdentFuncTableFunc = function: TtkTokenKind of object; TDelphiVersion = (dvDelphi1, dvDelphi2, dvDelphi3, dvDelphi4, dvDelphi5, dvDelphi6, dvDelphi7, dvDelphi8, dvDelphi2005); const LastDelphiVersion = dvDelphi2005; type TSynElphySyn = class(TSynCustomHighlighter) private fAsmStart: Boolean; fRange: TRangeState; fLine: PChar; fLineNumber: Integer; fProcTable: array[#0..#255] of TProcTableProc; Run: LongInt; fStringLen: Integer; fToIdent: PChar; fIdentFuncTable: array[0..191] of TIdentFuncTableFunc; fTokenPos: Integer; FTokenID: TtkTokenKind; fStringAttri: TSynHighlighterAttributes; fCharAttri: TSynHighlighterAttributes; fNumberAttri: TSynHighlighterAttributes; fFloatAttri: TSynHighlighterAttributes; fHexAttri: TSynHighlighterAttributes; fKeyAttri: TSynHighlighterAttributes; fSymbolAttri: TSynHighlighterAttributes; fAsmAttri: TSynHighlighterAttributes; fCommentAttri: TSynHighlighterAttributes; fDirecAttri: TSynHighlighterAttributes; fIdentifierAttri: TSynHighlighterAttributes; fSpaceAttri: TSynHighlighterAttributes; fDelphiVersion: TDelphiVersion; fPackageSource: Boolean; function KeyHash(ToHash: PChar): Integer; function KeyComp(const aKey: string): Boolean; function Func15: TtkTokenKind; function Func19: TtkTokenKind; function Func20: TtkTokenKind; function Func21: TtkTokenKind; function Func23: TtkTokenKind; function Func25: TtkTokenKind; function Func27: TtkTokenKind; function Func28: TtkTokenKind; function Func29: TtkTokenKind; function Func32: TtkTokenKind; function Func33: TtkTokenKind; function Func35: TtkTokenKind; function Func37: TtkTokenKind; function Func38: TtkTokenKind; function Func39: TtkTokenKind; function Func40: TtkTokenKind; function Func41: TtkTokenKind; function Func42: TtkTokenKind; function Func44: TtkTokenKind; function Func45: TtkTokenKind; function Func46: TtkTokenKind; function Func47: TtkTokenKind; function Func49: TtkTokenKind; function Func52: TtkTokenKind; function Func54: TtkTokenKind; function Func55: TtkTokenKind; function Func56: TtkTokenKind; function Func57: TtkTokenKind; function Func59: TtkTokenKind; function Func60: TtkTokenKind; function Func61: TtkTokenKind; function Func63: TtkTokenKind; function Func64: TtkTokenKind; function Func65: TtkTokenKind; function Func66: TtkTokenKind; function Func69: TtkTokenKind; function Func71: TtkTokenKind; function Func73: TtkTokenKind; function Func75: TtkTokenKind; function Func76: TtkTokenKind; function Func79: TtkTokenKind; function Func81: TtkTokenKind; function Func84: TtkTokenKind; function Func85: TtkTokenKind; function Func87: TtkTokenKind; function Func88: TtkTokenKind; function Func91: TtkTokenKind; function Func92: TtkTokenKind; function Func94: TtkTokenKind; function Func95: TtkTokenKind; function Func96: TtkTokenKind; function Func97: TtkTokenKind; function Func98: TtkTokenKind; function Func99: TtkTokenKind; function Func100: TtkTokenKind; function Func101: TtkTokenKind; function Func102: TtkTokenKind; function Func103: TtkTokenKind; function Func105: TtkTokenKind; function Func106: TtkTokenKind; function Func108: TtkTokenKind; function Func112: TtkTokenKind; function Func117: TtkTokenKind; function Func118: TtkTokenKind; function Func126: TtkTokenKind; function Func129: TtkTokenKind; function Func132: TtkTokenKind; function Func133: TtkTokenKind; function Func136: TtkTokenKind; function Func141: TtkTokenKind; function Func143: TtkTokenKind; function Func147: TtkTokenKind; function Func166: TtkTokenKind; function Func168: TtkTokenKind; function Func191: TtkTokenKind; function AltFunc: TtkTokenKind; procedure InitIdent; function IdentKind(MayBe: PChar): TtkTokenKind; procedure MakeMethodTables; procedure AddressOpProc; procedure AsciiCharProc; procedure AnsiProc; procedure BorProc; procedure BraceOpenProc; procedure ColonOrGreaterProc; procedure CRProc; procedure IdentProc; procedure IntegerProc; procedure LFProc; procedure LowerProc; procedure NullProc; procedure NumberProc; procedure PointProc; procedure RoundOpenProc; procedure SemicolonProc; procedure SlashProc; procedure SpaceProc; procedure StringProc; procedure SymbolProc; procedure UnknownProc; procedure SetDelphiVersion(const Value: TDelphiVersion); procedure SetPackageSource(const Value: Boolean); protected function GetIdentChars: TSynIdentChars; override; function GetSampleSource: string; override; function IsFilterStored: boolean; override; public class function GetCapabilities: TSynHighlighterCapabilities; override; class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override; function GetEol: Boolean; override; function GetRange: Pointer; override; function GetToken: string; override; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenID: TtkTokenKind; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; procedure Next; override; procedure ResetRange; override; procedure SetLine({$IFDEF FPC}const {$ENDIF}NewValue: string; LineNumber:Integer); override; procedure SetRange(Value: Pointer); override; function UseUserSettings(VersionIndex: integer): boolean; override; procedure EnumUserSettings(DelphiVersions: TStrings); override; property IdentChars; published property AsmAttri: TSynHighlighterAttributes read fAsmAttri write fAsmAttri; property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri; property DirectiveAttri: TSynHighlighterAttributes read fDirecAttri write fDirecAttri; property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri; property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri; property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri; property FloatAttri: TSynHighlighterAttributes read fFloatAttri write fFloatAttri; property HexAttri: TSynHighlighterAttributes read fHexAttri write fHexAttri; property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri; property CharAttri: TSynHighlighterAttributes read fCharAttri write fCharAttri; property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri write fSymbolAttri; property DelphiVersion: TDelphiVersion read fDelphiVersion write SetDelphiVersion default LastDelphiVersion; property PackageSource: Boolean read fPackageSource write SetPackageSource default True; end; implementation uses {$IFDEF SYN_CLX} QSynEditStrConst; {$ELSE} SynEditStrConst; {$ENDIF} var Identifiers: array[#0..#255] of ByteBool; mHashTable: array[#0..#255] of Integer; procedure MakeIdentTable; var I, J: Char; begin for I := #0 to #255 do begin Case I of '_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True; else Identifiers[I] := False; end; J := UpCase(I); Case I of 'a'..'z', 'A'..'Z', '_': mHashTable[I] := Ord(J) - 64; else mHashTable[Char(I)] := 0; end; end; end; procedure TSynElphySyn.InitIdent; var I: Integer; pF: PIdentFuncTableFunc; begin pF := PIdentFuncTableFunc(@fIdentFuncTable); for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do begin {$IFDEF FPC} pF^ := @AltFunc; {$ELSE} pF^ := AltFunc; {$ENDIF} Inc(pF); end; fIdentFuncTable[15] := {$IFDEF FPC} @Func15; {$ELSE} Func15; {$ENDIF} fIdentFuncTable[19] := {$IFDEF FPC} @Func19; {$ELSE} Func19; {$ENDIF} fIdentFuncTable[20] := {$IFDEF FPC} @Func20; {$ELSE} Func20; {$ENDIF} fIdentFuncTable[21] := {$IFDEF FPC} @Func21; {$ELSE} Func21; {$ENDIF} fIdentFuncTable[23] := {$IFDEF FPC} @Func23; {$ELSE} Func23; {$ENDIF} fIdentFuncTable[25] := {$IFDEF FPC} @Func25; {$ELSE} Func25; {$ENDIF} fIdentFuncTable[27] := {$IFDEF FPC} @Func27; {$ELSE} Func27; {$ENDIF} fIdentFuncTable[28] := {$IFDEF FPC} @Func28; {$ELSE} Func28; {$ENDIF} fIdentFuncTable[29] := {$IFDEF FPC} @Func29; {$ELSE} Func29; {$ENDIF} fIdentFuncTable[32] := {$IFDEF FPC} @Func32; {$ELSE} Func32; {$ENDIF} fIdentFuncTable[33] := {$IFDEF FPC} @Func33; {$ELSE} Func33; {$ENDIF} fIdentFuncTable[35] := {$IFDEF FPC} @Func35; {$ELSE} Func35; {$ENDIF} fIdentFuncTable[37] := {$IFDEF FPC} @Func37; {$ELSE} Func37; {$ENDIF} fIdentFuncTable[38] := {$IFDEF FPC} @Func38; {$ELSE} Func38; {$ENDIF} fIdentFuncTable[39] := {$IFDEF FPC} @Func39; {$ELSE} Func39; {$ENDIF} fIdentFuncTable[40] := {$IFDEF FPC} @Func40; {$ELSE} Func40; {$ENDIF} fIdentFuncTable[41] := {$IFDEF FPC} @Func41; {$ELSE} Func41; {$ENDIF} fIdentFuncTable[42] := {$IFDEF FPC} @Func42; {$ELSE} Func42; {$ENDIF} fIdentFuncTable[44] := {$IFDEF FPC} @Func44; {$ELSE} Func44; {$ENDIF} fIdentFuncTable[45] := {$IFDEF FPC} @Func45; {$ELSE} Func45; {$ENDIF} fIdentFuncTable[46] := {$IFDEF FPC} @Func46; {$ELSE} Func46; {$ENDIF} fIdentFuncTable[47] := {$IFDEF FPC} @Func47; {$ELSE} Func47; {$ENDIF} fIdentFuncTable[49] := {$IFDEF FPC} @Func49; {$ELSE} Func49; {$ENDIF} fIdentFuncTable[52] := {$IFDEF FPC} @Func52; {$ELSE} Func52; {$ENDIF} fIdentFuncTable[54] := {$IFDEF FPC} @Func54; {$ELSE} Func54; {$ENDIF} fIdentFuncTable[55] := {$IFDEF FPC} @Func55; {$ELSE} Func55; {$ENDIF} fIdentFuncTable[56] := {$IFDEF FPC} @Func56; {$ELSE} Func56; {$ENDIF} fIdentFuncTable[57] := {$IFDEF FPC} @Func57; {$ELSE} Func57; {$ENDIF} fIdentFuncTable[59] := {$IFDEF FPC} @Func59; {$ELSE} Func59; {$ENDIF} fIdentFuncTable[60] := {$IFDEF FPC} @Func60; {$ELSE} Func60; {$ENDIF} fIdentFuncTable[61] := {$IFDEF FPC} @Func61; {$ELSE} Func61; {$ENDIF} fIdentFuncTable[63] := {$IFDEF FPC} @Func63; {$ELSE} Func63; {$ENDIF} fIdentFuncTable[64] := {$IFDEF FPC} @Func64; {$ELSE} Func64; {$ENDIF} fIdentFuncTable[65] := {$IFDEF FPC} @Func65; {$ELSE} Func65; {$ENDIF} fIdentFuncTable[66] := {$IFDEF FPC} @Func66; {$ELSE} Func66; {$ENDIF} fIdentFuncTable[69] := {$IFDEF FPC} @Func69; {$ELSE} Func69; {$ENDIF} fIdentFuncTable[71] := {$IFDEF FPC} @Func71; {$ELSE} Func71; {$ENDIF} fIdentFuncTable[73] := {$IFDEF FPC} @Func73; {$ELSE} Func73; {$ENDIF} fIdentFuncTable[75] := {$IFDEF FPC} @Func75; {$ELSE} Func75; {$ENDIF} fIdentFuncTable[76] := {$IFDEF FPC} @Func76; {$ELSE} Func76; {$ENDIF} fIdentFuncTable[79] := {$IFDEF FPC} @Func79; {$ELSE} Func79; {$ENDIF} fIdentFuncTable[81] := {$IFDEF FPC} @Func81; {$ELSE} Func81; {$ENDIF} fIdentFuncTable[84] := {$IFDEF FPC} @Func84; {$ELSE} Func84; {$ENDIF} fIdentFuncTable[85] := {$IFDEF FPC} @Func85; {$ELSE} Func85; {$ENDIF} fIdentFuncTable[87] := {$IFDEF FPC} @Func87; {$ELSE} Func87; {$ENDIF} fIdentFuncTable[88] := {$IFDEF FPC} @Func88; {$ELSE} Func88; {$ENDIF} fIdentFuncTable[91] := {$IFDEF FPC} @Func91; {$ELSE} Func91; {$ENDIF} fIdentFuncTable[92] := {$IFDEF FPC} @Func92; {$ELSE} Func92; {$ENDIF} fIdentFuncTable[94] := {$IFDEF FPC} @Func94; {$ELSE} Func94; {$ENDIF} fIdentFuncTable[95] := {$IFDEF FPC} @Func95; {$ELSE} Func95; {$ENDIF} fIdentFuncTable[96] := {$IFDEF FPC} @Func96; {$ELSE} Func96; {$ENDIF} fIdentFuncTable[97] := {$IFDEF FPC} @Func97; {$ELSE} Func97; {$ENDIF} fIdentFuncTable[98] := {$IFDEF FPC} @Func98; {$ELSE} Func98; {$ENDIF} fIdentFuncTable[99] := {$IFDEF FPC} @Func99; {$ELSE} Func99; {$ENDIF} fIdentFuncTable[100] :={$IFDEF FPC} @Func100; {$ELSE} Func100; {$ENDIF} fIdentFuncTable[101] :={$IFDEF FPC} @Func101; {$ELSE} Func101; {$ENDIF} fIdentFuncTable[102] :={$IFDEF FPC} @Func102; {$ELSE} Func102; {$ENDIF} fIdentFuncTable[103] :={$IFDEF FPC} @Func103; {$ELSE} Func103; {$ENDIF} fIdentFuncTable[105] :={$IFDEF FPC} @Func105; {$ELSE} Func105; {$ENDIF} fIdentFuncTable[106] :={$IFDEF FPC} @Func106; {$ELSE} Func106; {$ENDIF} fIdentFuncTable[108] :={$IFDEF FPC} @Func108; {$ELSE} Func108; {$ENDIF} fIdentFuncTable[112] :={$IFDEF FPC} @Func112; {$ELSE} Func112; {$ENDIF} fIdentFuncTable[117] :={$IFDEF FPC} @Func117; {$ELSE} Func117; {$ENDIF} fIdentFuncTable[118] :={$IFDEF FPC} @Func118; {$ELSE} Func118; {$ENDIF} fIdentFuncTable[126] :={$IFDEF FPC} @Func126; {$ELSE} Func126; {$ENDIF} fIdentFuncTable[129] :={$IFDEF FPC} @Func129; {$ELSE} Func129; {$ENDIF} fIdentFuncTable[132] :={$IFDEF FPC} @Func132; {$ELSE} Func132; {$ENDIF} fIdentFuncTable[133] :={$IFDEF FPC} @Func133; {$ELSE} Func133; {$ENDIF} fIdentFuncTable[136] :={$IFDEF FPC} @Func136; {$ELSE} Func136; {$ENDIF} fIdentFuncTable[141] :={$IFDEF FPC} @Func141; {$ELSE} Func141; {$ENDIF} fIdentFuncTable[143] :={$IFDEF FPC} @Func143; {$ELSE} Func143; {$ENDIF} fIdentFuncTable[147] :={$IFDEF FPC} @Func147; {$ELSE} Func147; {$ENDIF} fIdentFuncTable[166] :={$IFDEF FPC} @Func166; {$ELSE} Func166; {$ENDIF} fIdentFuncTable[168] :={$IFDEF FPC} @Func168; {$ELSE} Func168; {$ENDIF} fIdentFuncTable[191] :={$IFDEF FPC} @Func191; {$ELSE} Func191; {$ENDIF} end; function TSynElphySyn.KeyHash(ToHash: PChar): Integer; begin Result := 0; while ToHash^ in ['a'..'z', 'A'..'Z'] do begin inc(Result, mHashTable[ToHash^]); inc(ToHash); end; if ToHash^ in ['_', '0'..'9'] then inc(ToHash); fStringLen := ToHash - fToIdent; end; { KeyHash } function TSynElphySyn.KeyComp(const aKey: string): Boolean; var I: Integer; Temp: PChar; begin Temp := fToIdent; if Length(aKey) = fStringLen then begin Result := True; for i := 1 to fStringLen do begin if mHashTable[Temp^] <> mHashTable[aKey[i]] then begin Result := False; break; end; inc(Temp); end; end else Result := False; end; { KeyComp } function TSynElphySyn.Func15: TtkTokenKind; begin if KeyComp('If') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func19: TtkTokenKind; begin if KeyComp('Do') then Result := tkKey else if KeyComp('And') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func20: TtkTokenKind; begin if KeyComp('As') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func21: TtkTokenKind; begin if KeyComp('Of') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func23: TtkTokenKind; begin if KeyComp('End') then begin Result := tkKey; fRange := rsUnknown; end else if KeyComp('In') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func25: TtkTokenKind; begin if KeyComp('Far') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func27: TtkTokenKind; begin if (DelphiVersion >= dvDelphi2) and KeyComp('Cdecl') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func28: TtkTokenKind; begin if KeyComp('Is') then Result := tkKey else if (fRange = rsProperty) and KeyComp('Read') then Result := tkKey else if KeyComp('Case') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func29: TtkTokenKind; begin if KeyComp('on') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func32: TtkTokenKind; begin if KeyComp('Label') then Result := tkKey else if KeyComp('Mod') then Result := tkKey else if KeyComp('File') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func33: TtkTokenKind; begin if KeyComp('Or') then Result := tkKey else if KeyComp('Asm') then begin Result := tkKey; fRange := rsAsm; fAsmStart := True; end else if (fRange = rsExports) and KeyComp('name') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func35: TtkTokenKind; begin if KeyComp('Nil') then Result := tkKey else if KeyComp('To') then Result := tkKey else if KeyComp('Div') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func37: TtkTokenKind; begin if KeyComp('Begin') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func38: TtkTokenKind; begin if KeyComp('Near') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func39: TtkTokenKind; begin if KeyComp('For') then Result := tkKey else if KeyComp('Shl') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func40: TtkTokenKind; begin if KeyComp('Packed') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func41: TtkTokenKind; begin if KeyComp('Else') then Result := tkKey else if KeyComp('Var') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func42: TtkTokenKind; begin if (DelphiVersion >= dvDelphi8) and KeyComp('Final') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func44: TtkTokenKind; begin if KeyComp('Set') then Result := tkKey else if PackageSource and KeyComp('package') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func45: TtkTokenKind; begin if KeyComp('Shr') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func46: TtkTokenKind; begin if (DelphiVersion >= dvDelphi8) and KeyComp('Sealed') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func47: TtkTokenKind; begin if KeyComp('Then') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func49: TtkTokenKind; begin if KeyComp('Not') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func52: TtkTokenKind; begin if KeyComp('Pascal') then Result := tkKey else if KeyComp('Raise') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func54: TtkTokenKind; begin if KeyComp('Class') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func55: TtkTokenKind; begin if KeyComp('Object') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func56: TtkTokenKind; begin if (fRange in [rsProperty, rsExports]) and KeyComp('Index') then Result := tkKey else if KeyComp('Out') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func57: TtkTokenKind; begin if KeyComp('Goto') then Result := tkKey else if KeyComp('While') then Result := tkKey else if KeyComp('Xor') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func59: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Safecall') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func60: TtkTokenKind; begin if KeyComp('With') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func61: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Dispid') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func63: TtkTokenKind; begin if KeyComp('Public') then Result := tkKey else if KeyComp('Record') then Result := tkKey else if KeyComp('Array') then Result := tkKey else if KeyComp('Try') then Result := tkKey else if KeyComp('Inline') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func64: TtkTokenKind; begin if KeyComp('Unit') then Result := tkKey else if KeyComp('Uses') then Result := tkKey else if (DelphiVersion >= dvDelphi8) and KeyComp('Helper') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func65: TtkTokenKind; begin if KeyComp('Repeat') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func66: TtkTokenKind; begin if KeyComp('Type') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func69: TtkTokenKind; begin if KeyComp('Default') then Result := tkKey else if KeyComp('Dynamic') then Result := tkKey else if KeyComp('Message') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func71: TtkTokenKind; begin if (DelphiVersion >= dvDelphi2) and KeyComp('Stdcall') then Result := tkKey else if KeyComp('Const') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func73: TtkTokenKind; begin if KeyComp('Except') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func75: TtkTokenKind; begin if (fRange = rsProperty) and KeyComp('Write') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func76: TtkTokenKind; begin if KeyComp('Until') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func79: TtkTokenKind; begin if KeyComp('Finally') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func81: TtkTokenKind; begin if (fRange = rsProperty) and KeyComp('Stored') then Result := tkKey else if KeyComp('Interface') then Result := tkKey else if (DelphiVersion >= dvDelphi6) and KeyComp('deprecated') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func84: TtkTokenKind; begin if KeyComp('Abstract') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func85: TtkTokenKind; begin if KeyComp('Forward') then Result := tkKey else if KeyComp('Library') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func87: TtkTokenKind; begin if KeyComp('String') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func88: TtkTokenKind; begin if KeyComp('Program') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func91: TtkTokenKind; begin if KeyComp('Downto') then Result := tkKey else if KeyComp('Private') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func92: TtkTokenKind; begin if (DelphiVersion >= dvDelphi4) and KeyComp('overload') then Result := tkKey else if KeyComp('Inherited') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func94: TtkTokenKind; begin if KeyComp('Assembler') then Result := tkKey else if (DelphiVersion >= dvDelphi3) and (fRange = rsProperty) and KeyComp('Readonly') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func95: TtkTokenKind; begin if KeyComp('Absolute') then Result := tkKey else if KeyComp('Process') then Result := tkKey else if PackageSource and KeyComp('contains') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func96: TtkTokenKind; begin if KeyComp('Published') then Result := tkKey else if KeyComp('Override') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func97: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Threadvar') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func98: TtkTokenKind; begin if KeyComp('Export') then Result := tkKey else if (fRange = rsProperty) and KeyComp('Nodefault') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func99: TtkTokenKind; begin if KeyComp('External') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func100: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Automated') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func101: TtkTokenKind; begin if KeyComp('Register') then Result := tkKey else if (DelphiVersion >= dvDelphi6) and KeyComp('platform') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func102: TtkTokenKind; begin if KeyComp('Function') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func103: TtkTokenKind; begin if KeyComp('Virtual') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func105: TtkTokenKind; begin if KeyComp('Procedure') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func106: TtkTokenKind; begin if KeyComp('Protected') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func108: TtkTokenKind; begin if (DelphiVersion >= dvDelphi8) and KeyComp('Operator') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func112: TtkTokenKind; begin if PackageSource and KeyComp('requires') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func117: TtkTokenKind; begin if KeyComp('Exports') then begin Result := tkKey; fRange := rsExports; end else Result := tkIdentifier; end; function TSynElphySyn.Func118: TtkTokenKind; begin if KeyComp('EndProcess') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func126: TtkTokenKind; begin if (fRange = rsProperty) and (DelphiVersion >= dvDelphi4) and KeyComp('Implements') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func129: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Dispinterface') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func132: TtkTokenKind; begin if (DelphiVersion >= dvDelphi4) and KeyComp('Reintroduce') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func133: TtkTokenKind; begin if KeyComp('Property') then begin Result := tkKey; fRange := rsProperty; end else Result := tkIdentifier; end; function TSynElphySyn.Func136: TtkTokenKind; begin if (DelphiVersion >= dvDelphi2) and KeyComp('Finalization') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func141: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and (fRange = rsProperty) and KeyComp('Writeonly') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func143: TtkTokenKind; begin if KeyComp('Destructor') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func147: TtkTokenKind; begin if KeyComp('InitProcess') then Result := tkKey else if KeyComp('InitProcess0') then Result := tkKey else if KeyComp('ProcessCont') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func166: TtkTokenKind; begin if KeyComp('Constructor') then Result := tkKey else if KeyComp('Implementation') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func168: TtkTokenKind; begin if KeyComp('Initialization') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.Func191: TtkTokenKind; begin if (DelphiVersion >= dvDelphi3) and KeyComp('Resourcestring') then Result := tkKey else if (DelphiVersion >= dvDelphi3) and KeyComp('Stringresource') then Result := tkKey else Result := tkIdentifier; end; function TSynElphySyn.AltFunc: TtkTokenKind; begin Result := tkIdentifier end; function TSynElphySyn.IdentKind(MayBe: PChar): TtkTokenKind; var HashKey: Integer; begin fToIdent := MayBe; HashKey := KeyHash(MayBe); if HashKey < 192 then Result := fIdentFuncTable[HashKey]() else Result := tkIdentifier; end; procedure TSynElphySyn.MakeMethodTables; var I: Char; begin for I := #0 to #255 do case I of #0: fProcTable[I] := {$IFDEF FPC} @NullProc; {$ELSE} NullProc; {$ENDIF} #10: fProcTable[I] := {$IFDEF FPC} @LFProc; {$ELSE} LFProc; {$ENDIF} #13: fProcTable[I] := {$IFDEF FPC} @CRProc; {$ELSE} CRProc; {$ENDIF} #1..#9, #11, #12, #14..#32: fProcTable[I] := {$IFDEF FPC} @SpaceProc; {$ELSE} SpaceProc; {$ENDIF} '#': fProcTable[I] := {$IFDEF FPC} @AsciiCharProc; {$ELSE} AsciiCharProc; {$ENDIF} '$': fProcTable[I] := {$IFDEF FPC} @IntegerProc; {$ELSE} IntegerProc; {$ENDIF} #39: fProcTable[I] := {$IFDEF FPC} @StringProc; {$ELSE} StringProc; {$ENDIF} '0'..'9': fProcTable[I] := {$IFDEF FPC} @NumberProc; {$ELSE} NumberProc; {$ENDIF} 'A'..'Z', 'a'..'z', '_': fProcTable[I] := {$IFDEF FPC} @IdentProc; {$ELSE} IdentProc; {$ENDIF} '{': fProcTable[I] := {$IFDEF FPC} @BraceOpenProc; {$ELSE} BraceOpenProc; {$ENDIF} '}', '!', '"', '%', '&', '('..'/', ':'..'@', '['..'^', '`', '~': begin case I of '(': fProcTable[I] := {$IFDEF FPC} @RoundOpenProc; {$ELSE} RoundOpenProc; {$ENDIF} '.': fProcTable[I] := {$IFDEF FPC} @PointProc; {$ELSE} PointProc; {$ENDIF} ';': fProcTable[I] := {$IFDEF FPC} @SemicolonProc; {$ELSE} SemicolonProc; {$ENDIF} '/': fProcTable[I] := {$IFDEF FPC} @SlashProc; {$ELSE} SlashProc; {$ENDIF} ':', '>': fProcTable[I] := {$IFDEF FPC} @ColonOrGreaterProc; {$ELSE} ColonOrGreaterProc; {$ENDIF} '<': fProcTable[I] := {$IFDEF FPC} @LowerProc; {$ELSE} LowerProc; {$ENDIF} '@': fProcTable[I] := {$IFDEF FPC} @AddressOpProc; {$ELSE} AddressOpProc; {$ENDIF} else fProcTable[I] := {$IFDEF FPC} @SymbolProc; {$ELSE} SymbolProc; {$ENDIF} end; end; else fProcTable[I] := {$IFDEF FPC} @UnknownProc; {$ELSE} UnknownProc; {$ENDIF} end; end; constructor TSynElphySyn.Create(AOwner: TComponent); begin inherited Create(AOwner); fDelphiVersion := LastDelphiVersion; fPackageSource := True; fAsmAttri := TSynHighlighterAttributes.Create(SYNS_AttrAssembler); AddAttribute(fAsmAttri); fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment); fCommentAttri.Style:= [fsItalic]; AddAttribute(fCommentAttri); fDirecAttri := TSynHighlighterAttributes.Create(SYNS_AttrPreprocessor); fDirecAttri.Style:= [fsItalic]; AddAttribute(fDirecAttri); fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier); AddAttribute(fIdentifierAttri); fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord); fKeyAttri.Style:= [fsBold]; AddAttribute(fKeyAttri); fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber); AddAttribute(fNumberAttri); fFloatAttri := TSynHighlighterAttributes.Create(SYNS_AttrFloat); AddAttribute(fFloatAttri); fHexAttri := TSynHighlighterAttributes.Create(SYNS_AttrHexadecimal); AddAttribute(fHexAttri); fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace); AddAttribute(fSpaceAttri); fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString); AddAttribute(fStringAttri); fCharAttri := TSynHighlighterAttributes.Create(SYNS_AttrCharacter); AddAttribute(fCharAttri); fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol); AddAttribute(fSymbolAttri); SetAttributesOnChange({$IFDEF FPC}@{$ENDIF}DefHighlightChange); InitIdent; MakeMethodTables; fRange := rsUnknown; fAsmStart := False; fDefaultFilter := SYNS_FilterPascal; end; { Create } procedure TSynElphySyn.SetLine({$IFDEF FPC}Const {$ENDIF}NewValue: string; LineNumber:Integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; Next; end; { SetLine } procedure TSynElphySyn.AddressOpProc; begin fTokenID := tkSymbol; inc(Run); if fLine[Run] = '@' then inc(Run); end; procedure TSynElphySyn.AsciiCharProc; begin fTokenID := tkChar; Inc(Run); while FLine[Run] in ['0'..'9', '$', 'A'..'F', 'a'..'f'] do Inc(Run); end; procedure TSynElphySyn.BorProc; begin case fLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; else begin if fRange in [rsDirective, rsDirectiveAsm] then fTokenID := tkDirec else fTokenID := tkComment; repeat if fLine[Run] = '}' then begin Inc(Run); if fRange in [rsBorAsm, rsDirectiveAsm] then fRange := rsAsm else fRange := rsUnKnown; break; end; Inc(Run); until fLine[Run] in [#0, #10, #13]; end; end; end; procedure TSynElphySyn.BraceOpenProc; begin if (fLine[Run + 1] = '$') then begin if fRange = rsAsm then fRange := rsDirectiveAsm else fRange := rsDirective; end else begin if fRange = rsAsm then fRange := rsBorAsm else fRange := rsBor; end; BorProc; end; procedure TSynElphySyn.ColonOrGreaterProc; begin fTokenID := tkSymbol; inc(Run); if fLine[Run] = '=' then inc(Run); end; procedure TSynElphySyn.CRProc; begin fTokenID := tkSpace; inc(Run); if fLine[Run] = #10 then Inc(Run); end; { CRProc } procedure TSynElphySyn.IdentProc; begin fTokenID := IdentKind((fLine + Run)); inc(Run, fStringLen); while Identifiers[fLine[Run]] do Inc(Run); end; { IdentProc } procedure TSynElphySyn.IntegerProc; begin inc(Run); fTokenID := tkHex; while FLine[Run] in ['0'..'9', 'A'..'F', 'a'..'f'] do Inc(Run); end; { IntegerProc } procedure TSynElphySyn.LFProc; begin fTokenID := tkSpace; inc(Run); end; { LFProc } procedure TSynElphySyn.LowerProc; begin fTokenID := tkSymbol; inc(Run); if fLine[Run] in ['=', '>'] then Inc(Run); end; { LowerProc } procedure TSynElphySyn.NullProc; begin fTokenID := tkNull; end; { NullProc } procedure TSynElphySyn.NumberProc; begin Inc(Run); fTokenID := tkNumber; while FLine[Run] in ['0'..'9', '.', 'e', 'E', '-', '+'] do begin case FLine[Run] of '.': if FLine[Run + 1] = '.' then Break else fTokenID := tkFloat; 'e', 'E': fTokenID := tkFloat; '-', '+': begin if fTokenID <> tkFloat then // arithmetic Break; if not (FLine[Run - 1] in ['e', 'E']) then Break; //float, but it ends here end; end; Inc(Run); end; end; { NumberProc } procedure TSynElphySyn.PointProc; begin fTokenID := tkSymbol; inc(Run); if fLine[Run] in ['.', ')'] then Inc(Run); end; { PointProc } procedure TSynElphySyn.AnsiProc; begin case fLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; else fTokenID := tkComment; repeat if (fLine[Run] = '*') and (fLine[Run + 1] = ')') then begin Inc(Run, 2); if fRange = rsAnsiAsm then fRange := rsAsm else fRange := rsUnKnown; break; end; Inc(Run); until fLine[Run] in [#0, #10, #13]; end; end; procedure TSynElphySyn.RoundOpenProc; begin Inc(Run); case fLine[Run] of '*': begin Inc(Run); if fRange = rsAsm then fRange := rsAnsiAsm else fRange := rsAnsi; fTokenID := tkComment; if not (fLine[Run] in [#0, #10, #13]) then AnsiProc; end; '.': begin inc(Run); fTokenID := tkSymbol; end; else fTokenID := tkSymbol; end; end; procedure TSynElphySyn.SemicolonProc; begin Inc(Run); fTokenID := tkSymbol; if fRange in [rsProperty, rsExports] then fRange := rsUnknown; end; procedure TSynElphySyn.SlashProc; begin Inc(Run); if (fLine[Run] = '/') and (fDelphiVersion > dvDelphi1) then begin fTokenID := tkComment; repeat Inc(Run); until fLine[Run] in [#0, #10, #13]; end else fTokenID := tkSymbol; end; procedure TSynElphySyn.SpaceProc; begin inc(Run); fTokenID := tkSpace; while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run); end; procedure TSynElphySyn.StringProc; begin fTokenID := tkString; Inc(Run); while not (fLine[Run] in [#0, #10, #13]) do begin if fLine[Run] = #39 then begin Inc(Run); if fLine[Run] <> #39 then break; end; Inc(Run); end; end; procedure TSynElphySyn.SymbolProc; begin inc(Run); fTokenID := tkSymbol; end; procedure TSynElphySyn.UnknownProc; begin {$IFDEF SYN_MBCSSUPPORT} if FLine[Run] in LeadBytes then Inc(Run, 2) else {$ENDIF} inc(Run); fTokenID := tkUnknown; end; procedure TSynElphySyn.Next; begin fAsmStart := False; fTokenPos := Run; case fRange of rsAnsi, rsAnsiAsm: AnsiProc; rsBor, rsBorAsm, rsDirective, rsDirectiveAsm: BorProc; else fProcTable[fLine[Run]]; end; end; function TSynElphySyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fCommentAttri; SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri; SYN_ATTR_KEYWORD: Result := fKeyAttri; SYN_ATTR_STRING: Result := fStringAttri; SYN_ATTR_WHITESPACE: Result := fSpaceAttri; SYN_ATTR_SYMBOL: Result := fSymbolAttri; else Result := nil; end; end; function TSynElphySyn.GetEol: Boolean; begin Result := fTokenID = tkNull; end; function TSynElphySyn.GetToken: string; var Len: LongInt; begin Len := Run - fTokenPos; SetString(Result, (FLine + fTokenPos), Len); end; function TSynElphySyn.GetTokenID: TtkTokenKind; begin if not fAsmStart and (fRange = rsAsm) and not (fTokenId in [tkNull, tkComment, tkDirec, tkSpace]) then Result := tkAsm else Result := fTokenId; end; function TSynElphySyn.GetTokenAttribute: TSynHighlighterAttributes; begin case GetTokenID of tkAsm: Result := fAsmAttri; tkComment: Result := fCommentAttri; tkDirec: Result := fDirecAttri; tkIdentifier: Result := fIdentifierAttri; tkKey: Result := fKeyAttri; tkNumber: Result := fNumberAttri; tkFloat: Result := fFloatAttri; tkHex: Result := fHexAttri; tkSpace: Result := fSpaceAttri; tkString: Result := fStringAttri; tkChar: Result := fCharAttri; tkSymbol: Result := fSymbolAttri; tkUnknown: Result := fSymbolAttri; else Result := nil; end; end; function TSynElphySyn.GetTokenKind: integer; begin Result := Ord(GetTokenID); end; function TSynElphySyn.GetTokenPos: Integer; begin Result := fTokenPos; end; function TSynElphySyn.GetRange: Pointer; begin Result := Pointer(fRange); end; procedure TSynElphySyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; procedure TSynElphySyn.ResetRange; begin fRange:= rsUnknown; end; procedure TSynElphySyn.EnumUserSettings(DelphiVersions: TStrings); begin { returns the user settings that exist in the registry } {$IFNDEF SYN_CLX} with TBetterRegistry.Create do begin try RootKey := HKEY_LOCAL_MACHINE; if OpenKeyReadOnly('\SOFTWARE\Borland\Delphi') then begin try GetKeyNames(DelphiVersions); finally CloseKey; end; end; finally Free; end; end; {$ENDIF} end; function TSynElphySyn.UseUserSettings(VersionIndex: integer): boolean; // Possible parameter values: // index into TStrings returned by EnumUserSettings // Possible return values: // true : settings were read and used // false: problem reading settings or invalid version specified - old settings // were preserved {$IFNDEF SYN_CLX} function ReadDelphiSettings(settingIndex: integer): boolean; function ReadDelphiSetting(settingTag: string; attri: TSynHighlighterAttributes; key: string): boolean; function ReadDelphi2Or3(settingTag: string; attri: TSynHighlighterAttributes; name: string): boolean; var i: integer; begin for i := 1 to Length(name) do if name[i] = ' ' then name[i] := '_'; Result := attri.LoadFromBorlandRegistry(HKEY_CURRENT_USER, '\Software\Borland\Delphi\'+settingTag+'\Highlight',name,true); end; { ReadDelphi2Or3 } function ReadDelphi4OrMore(settingTag: string; attri: TSynHighlighterAttributes; key: string): boolean; begin Result := attri.LoadFromBorlandRegistry(HKEY_CURRENT_USER, '\Software\Borland\Delphi\'+settingTag+'\Editor\Highlight',key,false); end; { ReadDelphi4OrMore } begin { ReadDelphiSetting } try if (settingTag[1] = '2') or (settingTag[1] = '3') then Result := ReadDelphi2Or3(settingTag,attri,key) else Result := ReadDelphi4OrMore(settingTag,attri,key); except Result := false; end; end; { ReadDelphiSetting } var tmpAsmAttri : TSynHighlighterAttributes; tmpCommentAttri : TSynHighlighterAttributes; tmpIdentAttri : TSynHighlighterAttributes; tmpKeyAttri : TSynHighlighterAttributes; tmpNumberAttri : TSynHighlighterAttributes; tmpSpaceAttri : TSynHighlighterAttributes; tmpStringAttri : TSynHighlighterAttributes; tmpSymbolAttri : TSynHighlighterAttributes; iVersions : TStringList; iVersionTag : string; begin { ReadDelphiSettings } {$IFDEF SYN_DELPHI_7_UP} Result := False; // Silence the compiler warning {$ENDIF} iVersions := TStringList.Create; try EnumUserSettings( iVersions ); if (settingIndex < 0) or (settingIndex >= iVersions.Count) then begin Result := False; Exit; end; iVersionTag := iVersions[ settingIndex ]; finally iVersions.Free; end; tmpAsmAttri := TSynHighlighterAttributes.Create(''); tmpCommentAttri := TSynHighlighterAttributes.Create(''); tmpIdentAttri := TSynHighlighterAttributes.Create(''); tmpKeyAttri := TSynHighlighterAttributes.Create(''); tmpNumberAttri := TSynHighlighterAttributes.Create(''); tmpSpaceAttri := TSynHighlighterAttributes.Create(''); tmpStringAttri := TSynHighlighterAttributes.Create(''); tmpSymbolAttri := TSynHighlighterAttributes.Create(''); Result := ReadDelphiSetting( iVersionTag, tmpAsmAttri,'Assembler') and ReadDelphiSetting( iVersionTag, tmpCommentAttri,'Comment') and ReadDelphiSetting( iVersionTag, tmpIdentAttri,'Identifier') and ReadDelphiSetting( iVersionTag, tmpKeyAttri,'Reserved word') and ReadDelphiSetting( iVersionTag, tmpNumberAttri,'Number') and ReadDelphiSetting( iVersionTag, tmpSpaceAttri,'Whitespace') and ReadDelphiSetting( iVersionTag, tmpStringAttri,'String') and ReadDelphiSetting( iVersionTag, tmpSymbolAttri,'Symbol'); if Result then begin fAsmAttri.AssignColorAndStyle( tmpAsmAttri ); fCharAttri.AssignColorAndStyle( tmpStringAttri ); { Delphi lacks Char attribute } fCommentAttri.AssignColorAndStyle( tmpCommentAttri ); fDirecAttri.AssignColorAndStyle( tmpCommentAttri ); { Delphi lacks Directive attribute } fFloatAttri.AssignColorAndStyle( tmpNumberAttri ); { Delphi lacks Float attribute } fHexAttri.AssignColorAndStyle( tmpNumberAttri ); { Delphi lacks Hex attribute } fIdentifierAttri.AssignColorAndStyle( tmpIdentAttri ); fKeyAttri.AssignColorAndStyle( tmpKeyAttri ); fNumberAttri.AssignColorAndStyle( tmpNumberAttri ); fSpaceAttri.AssignColorAndStyle( tmpSpaceAttri ); fStringAttri.AssignColorAndStyle( tmpStringAttri ); fSymbolAttri.AssignColorAndStyle( tmpSymbolAttri ); end; tmpAsmAttri.Free; tmpCommentAttri.Free; tmpIdentAttri.Free; tmpKeyAttri.Free; tmpNumberAttri.Free; tmpSpaceAttri.Free; tmpStringAttri.Free; tmpSymbolAttri.Free; end; { ReadDelphiSettings } {$ENDIF} begin {$IFNDEF SYN_CLX} Result := ReadDelphiSettings( VersionIndex ); {$ELSE} Result := False; {$ENDIF} end; { TSynElphySyn.UseUserSettings } function TSynElphySyn.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars; end; function TSynElphySyn.GetSampleSource: string; begin Result := '{ Syntax highlighting }'#13#10 + 'procedure TForm1.Button1Click(Sender: TObject);'#13#10 + 'var'#13#10 + ' Number, I, X: Integer;'#13#10 + 'begin'#13#10 + ' Number := 123456;'#13#10 + ' Caption := ''The Number is'' + #32 + IntToStr(Number);'#13#10 + ' for I := 0 to Number do'#13#10 + ' begin'#13#10 + ' Inc(X);'#13#10 + ' Dec(X);'#13#10 + ' X := X + 1.0;'#13#10 + ' X := X - $5E;'#13#10 + ' end;'#13#10 + ' {$R+}'#13#10 + ' asm'#13#10 + ' mov AX, 1234H'#13#10 + ' mov Number, AX'#13#10 + ' end;'#13#10 + ' {$R-}'#13#10 + 'end;'; end; { GetSampleSource } class function TSynElphySyn.GetLanguageName: string; begin Result := SYNS_LangPascal; end; class function TSynElphySyn.GetCapabilities: TSynHighlighterCapabilities; begin Result := inherited GetCapabilities + [hcUserSettings]; end; function TSynElphySyn.IsFilterStored: boolean; begin Result := fDefaultFilter <> SYNS_FilterPascal; end; procedure TSynElphySyn.SetDelphiVersion(const Value: TDelphiVersion); begin if fDelphiVersion <> Value then begin fDelphiVersion := Value; if (fDelphiVersion < dvDelphi3) and fPackageSource then fPackageSource := False; DefHighlightChange( Self ); end; end; procedure TSynElphySyn.SetPackageSource(const Value: Boolean); begin if fPackageSource <> Value then begin fPackageSource := Value; if fPackageSource and (fDelphiVersion < dvDelphi3) then fDelphiVersion := dvDelphi3; DefHighlightChange( Self ); end; end; Initialization AffDebug('Initialization SynHighlighterElphy',0); MakeIdentTable; {$IFNDEF SYN_CPPB_1} RegisterPlaceableHighlighter(TSynElphySyn); {$ENDIF} end.
unit DataSetDM5; interface uses SysUtils, Classes, DSServer, DBXInterBase, DB, SqlExpr, FMTBcd, Provider, ServerContainer, Generics.Collections, DBClient, DBXCommon, DBXJSON, Location, DBXJSONReflect, DBXDBReaders; type TDMDataSet5 = class(TDSServerModule) CDSRegion: TClientDataSet; CDSCountry: TClientDataSet; CDSState: TClientDataSet; CDSCity: TClientDataSet; private { Private declarations } FRegionList: TObjectDictionary<Integer, TRegion>; FCountryList: TObjectDictionary<String, TCountry>; FStateList: TObjectDictionary<String, TState>; FCityList: TObjectDictionary<Integer,TCity>; function GetRecords(Fields, Table: String): TDBXReader; function FromReadertoRegion(Reader: TDBXReader): TRegion; function FromReadertoCountry(Reader: TDBXReader): TCountry; function FromReadertoState(Reader: TDBXReader): TState; function FromReadertoCity(Reader: TDBXReader): TCity; function GetData(Cds : TClientDataSet; Fields, Table: String) : TDBXReader; public function GetRegion: TDBXReader; function GetCountry: TDBXReader; function GetState: TDBXReader; function GetCity: TDBXReader; function ListofClassRegion: TJSONArray; function ListofClassCountry: TJSONArray; function ListofClassState: TJSONArray; function ListofClassCity: TJSONArray; end; implementation {$R *.dfm} function TDMDataSet5.FromReadertoCity(Reader: TDBXReader): TCity; var stateId, countryId : String; begin Result := TCity.Create; Result.Id := Reader.Value['ID_CITY'].GetInt32; Result.Name := String(Reader.Value['NAME'].GetAnsiString); stateId := String(Reader.Value['ID_STATE'].GetAnsiString); countryId := String(Reader.Value['ID_COUNTRY'].GetAnsiString); if FStateList.ContainsKey( countryId + ';' + stateId) then Result.State := FStateList.Items[countryId + ';' + stateId] else Result.State := nil; end; function TDMDataSet5.FromReadertoCountry(Reader: TDBXReader): TCountry; var regionId : Integer; begin Result := TCountry.Create; Result.Id := String(Reader.Value['ID_COUNTRY'].GetAnsiString); Result.Name := String(Reader.Value['NAME'].GetAnsiString); regionId := Reader.Value['ID_REGION'].GetInt32; if FRegionList.ContainsKey(regionId) then Result.Region := FRegionList.Items[regionId] else Result.Region := nil; end; function TDMDataSet5.FromReadertoRegion(Reader: TDBXReader): TRegion; begin Result := TRegion.Create; Result.Id := Reader.Value['ID_REGION'].GetInt32; Result.Name := String(Reader.Value['NAME'].GetAnsiString); end; function TDMDataSet5.FromReadertoState(Reader: TDBXReader): TState; var countryId : String; begin Result := TState.Create; Result.Id := String(Reader.Value['ID_STATE'].GetAnsiString); Result.Name := String(Reader.Value['NAME'].GetAnsiString); countryId := String(Reader.Value['ID_COUNTRY'].GetAnsiString); if FCountryList.ContainsKey(countryId) then Result.Country := FCountryList.Items[countryId] else Result.Country := nil; end; function TDMDataSet5.GetRecords(Fields, Table: String): TDBXReader; var cmd: TDBXCommand; begin cmd := DMServerContainer.GetConnection.DBXConnection.CreateCommand; try cmd.Text := 'Select ' + Fields + ' from ' + Table; Result := cmd.ExecuteQuery; except raise; end; end; function TDMDataSet5.GetRegion: TDBXReader; begin Result := GetData( CDSRegion, 'ID_REGION, NAME', 'Region' ); end; function TDMDataSet5.GetCity: TDBXReader; begin Result := GetData( CDSCity, 'ID_CITY, NAME, ID_COUNTRY, ID_STATE', 'City'); end; function TDMDataSet5.GetCountry: TDBXReader; begin Result := GetData( CDSCountry, 'ID_COUNTRY, NAME, ID_REGION', 'Country' ); end; function TDMDataSet5.GetData(Cds: TClientDataSet; Fields, Table: String): TDBXReader; var Reader : TDBXReader; begin if not Cds.Active then begin Reader := GetRecords(Fields, Table); TDBXDataSetReader.CopyReaderToClientDataSet( Reader, Cds ); Reader.Free; Cds.Open; end; Result := TDBXDataSetReader.Create(Cds, False (* InstanceOwner *) ); end; function TDMDataSet5.GetState: TDBXReader; begin Result := GetData( CDSState, 'ID_STATE, NAME, ID_COUNTRY', 'State' ); end; function TDMDataSet5.ListofClassCity: TJSONArray; var city: TCity; reader: TDBXReader; Marshal : TJSONMarshal; begin Result := TJSONArray.Create; Marshal := TJSONMarshal.Create(TJSONConverter.Create); if not Assigned(FCityList) then begin // Make sure state is already in cache, if not force if not Assigned(FStateList) then ListOfClassState; reader := GetCity; try FCityList := TObjectDictionary<Integer, TCity>.Create; while reader.Next do begin city := FromReadertoCity(reader); FCityList.Add(city.Id, city); Result.AddElement(city.ObjectToJSON<TCity>(city, Marshal)); end; reader.Close; finally reader.Free; end; end else begin for city in FCityList.Values do begin Result.AddElement(city.ObjectToJSON<TCity>(city, Marshal)); end; end; Marshal.Free; end; function TDMDataSet5.ListofClassCountry: TJSONArray; var country: TCountry; reader: TDBXReader; Marshal : TJSONMarshal; begin Result := TJSONArray.Create; Marshal := TJSONMarshal.Create(TJSONConverter.Create); if not Assigned(FCountryList) then begin // Make sure Region is already in cache, if not force if not Assigned(FRegionList) then ListofClassRegion; reader := GetCountry; try Result := TJSONArray.Create; FCountryList := TObjectDictionary<String, TCountry>.Create; while reader.Next do begin country := FromReadertoCountry(reader); FCountryList.Add(country.Id, country); Result.AddElement(country.ObjectToJSON<TCountry>(country, Marshal)); end; reader.Close; finally reader.Free; end; end else begin for country in FCountryList.Values do begin Result.AddElement(country.ObjectToJSON<TCountry>(country, Marshal)); end; end; Marshal.Free; end; function TDMDataSet5.ListofClassRegion: TJSONArray; var region: TRegion; reader: TDBXReader; Marshal : TJSONMarshal; begin Result := TJSONArray.Create; Marshal := TJSONMarshal.Create(TJSONConverter.Create); if not Assigned(FRegionList) then begin reader := GetRegion; try FRegionList := TObjectDictionary<Integer, TRegion>.Create; while reader.Next do begin region := FromReadertoRegion(reader); FRegionList.Add(region.Id, region); Result.AddElement(region.ObjectToJSON<TRegion>(region, Marshal)); end; reader.Close; finally reader.Free; end; end else begin for region in FRegionList.Values do begin Result.AddElement(region.ObjectToJSON<TRegion>(region, Marshal)); end; end; Marshal.Free; end; function TDMDataSet5.ListofClassState: TJSONArray; var state: TState; reader: TDBXReader; Marshal : TJSONMarshal; begin Result := TJSONArray.Create; Marshal := TJSONMarshal.Create(TJSONConverter.Create); if not Assigned(FStateList) then begin // Make sure state is already in cache, if not force if not Assigned(FCountryList) then ListOfClassCountry; reader := GetState; try FStateList := TObjectDictionary<String, TState>.Create; while reader.Next do begin state := FromReadertoState(reader); FStateList.Add(state.Country.Id + ';' + state.Id, state); Result.AddElement(state.ObjectToJSON<TState>(state, Marshal)); end; reader.Close; finally reader.Free; end; end else begin for state in FStateList.Values do begin Result.AddElement(state.ObjectToJSON<TState>(state, Marshal)); end; end; Marshal.Free; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0112.PAS Description: Re: Trunc() and Frac() Author: PEDRO GUTIERREZ Date: 05-31-96 09:17 *) Program Sample_Trunc_Frac; Var nNumber, nTrunc, nFrac : Real; { Number es xxxx.yyy } Procedure Trunc_Frac(nIn : Real; Var nTruncOut,nFracOut : Real); Var cSt : String; nDummy : Integer; Begin Str(nIn:18:8,cSt); Val(Copy(cSt,1,10),nTruncOut,nDummy); Val('0'+Copy(cSt,10,5),nFracOut,nDummy); { .xxx } End; Begin Writeln; nNumber := 1234567.891234; Trunc_frac(nNumber,nTrunc,nFrac); Writeln('Number : ',nNumber:18:8, ' Trunc : ',nTrunc:10:0, ' Frac : ',nFrac:18:8); nNumber := 5555.0; Trunc_frac(nNumber,nTrunc,nFrac); Writeln('Number : ',nNumber:18:8, ' Trunc : ',nTrunc:10:0, ' Frac : ',nFrac:18:8); nNumber := -10001.555; Trunc_frac(nNumber,nTrunc,nFrac); Writeln('Number : ',nNumber:18:8, ' Trunc : ',nTrunc:10:0, ' Frac : ',nFrac:18:8); End.
Unit Buffer; { * Buffer : * * * * Aqui es implementado el buffer cache del sistema , los bloques * * son anidados en dos colas las cola Lru y la cola Hash , por * * ahora solo maneja el cache de bloques de dispositivos de bloque * * * * Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> * * All Rights Reserved * * * * * * 12 / 04 / 06 : Es solucionado bug en pop_buffer * * * * 14 / 10 / 05 : Solucionado bug en Invalid_sb() * * * * 24 / 06 / 05 : Es reescritoro dando soporte al vfs * * * * 07 / 03 / 05 : Es creada la funcion Get_Virtual_Block , y * * las funciones Buffer_Read y Buffer_Write , se protegen los * * bufferes con Buffer_Lock y Buffer_Unlock . Get_block devuelve * * ahora buffer_head * * * * 15 / 12 / 04 : Es resuelto el probleme de lecturas erroneas , se * * elimna el sistema de tablas y se implementan buffer_heads dina * * mincos * * * * 18 / 08 / 04 : Se aplica la syscall Sync y se modifica la * * estructura Buffer_Head * * * * 11 / 02 / 04 : Primera Version * * * ******************************************************************** } {DEFINE DEBUG} interface {$I ../include/head/asm.h} {$I ../include/toro/procesos.inc} {$I ../include/toro/buffer.inc} {$I ../include/head/devices.h} {$I ../include/head/procesos.h} {$I ../include/head/scheduler.h} {$I ../include/head/printk_.h} {$I ../include/head/malloc.h} {$I ../include/head/paging.h} {$I ../include/head/mm.h} {$I ../include/head/ll_rw_block.h} {$I ../include/head/dcache.h} {$I ../include/head/inodes.h} {$I ../include/head/super.h} {$I ../include/head/itimer.h} {$define Use_Tail } {$define nodo_struct := p_buffer_head } {$define next_nodo := next_buffer } {$define prev_nodo := prev_buffer } {$define Push_Buffer := Push_Node} {$define Pop_Buffer := Pop_Node } {$define buffer_lock := lock } {$define buffer_unlock := unlock } var Buffer_Hash:array[1..Nr_blk] of p_buffer_head; Buffer_Lru : p_buffer_head ; Buffer_Dirty : p_buffer_head; Max_Buffers:dword; procedure Sys_Sync ; implementation {$I ../include/head/list.h} {$I ../include/head/lock.h} { * Lru_Find : * * * * Dev_blk : Dispositivo de Bloque * * Bloque : Numero de Bloque * * Retorno : Puntero buffer_head o nil se falla * * * * Esta funcion busca dentro de la cola Lru un bloque dado y si lo * * encuentra devuelve un puntero a la estructura buffer_head o de lo * * contrario nil * * * *********************************************************************** } function lru_find(Mayor,Menor,Bloque,Size:dword):p_buffer_head; var tmp:p_buffer_head; begin If Buffer_Lru = nil then exit (nil) ; tmp:=Buffer_Lru; repeat if (tmp^.Mayor=Mayor) and (tmp^.menor = Menor) and (tmp^.bloque=bloque) and (tmp^.size = size) then exit(tmp); tmp := tmp^.next_buffer; until ( tmp = Buffer_Lru); exit(nil); end; { * Push_Hash : * * * * Procedimiento que coloca un buffer_head en la cola hash * * * *********************************************************************** } procedure push_hash(buffer:p_buffer_head);inline; begin Push_Buffer (buffer , Buffer_Hash[buffer^.mayor]); end; { * Pop_Hash : * * * * Procedimiento que quita un buffer_head de la cola hash * * * *********************************************************************** } procedure pop_hash(Buffer:p_buffer_head);inline; begin Pop_Buffer (buffer , Buffer_Hash[buffer^.mayor]); end; function hash_find(Mayor,Menor,Bloque,size:dword):p_buffer_head;[public , alias :'HASH_FIND']; var tmp:p_buffer_head; begin tmp:=Buffer_Hash[Mayor]; if tmp=nil then exit(nil); repeat If (tmp^.menor = Menor) and (tmp^.bloque = Bloque) and (tmp^.size = size) then exit(tmp); tmp:=tmp^.next_buffer; until (tmp=Buffer_Hash[Mayor]); exit(nil); end; function buffer_update (Buffer:p_buffer_head):dword;[public , alias : 'BUFFER_UPDATE']; begin if ( buffer^.state and Bh_Dirty = Bh_Dirty) then begin if buffer_write (buffer) <> -1 then begin buffer^.state := buffer^.state xor Bh_dirty; exit(0) end else exit(-1); end else exit(0); end; procedure Init_Bh (bh : p_buffer_head ; mayor , menor , bloque : dword) ;inline; begin bh^.mayor := mayor ; bh^.menor := menor ; bh^.bloque := bloque ; bh^.count := 1; bh^.state := 0 ; bh^.wait_on_buffer.lock := false; bh^.wait_on_buffer.lock_wait := nil ; bh^.prev_buffer := nil ; bh^.next_buffer := nil ; end; { * Alloc_Buffer : * * * * size : Tama¤o del nuevo bloque a crear * * * * crea un buffer utilizando la variable Max_Buffers como indicador * * * *********************************************************************** } function alloc_buffer (size : dword ) : p_buffer_head ; var tmp :p_buffer_head ; tm : pointer ; begin {situacion critica} if Max_Buffers = 0 then begin if buffer_lru = nil then exit(nil); tmp := Buffer_Lru^.prev_buffer; {limpiar la cola de sucios} if (tmp^.state and BH_dirty ) = Bh_Dirty then sys_sync; {si el tama¤o del buffer no es igual habra que liberar y solicitar} if tmp^.size <> size then begin tm := kmalloc (size); if tm = nil then exit (nil); kfree_s (tmp^.data,tmp^.size); tmp^.data := tm ; tmp^.size := size; end; Pop_Buffer(tmp,Buffer_Lru); exit(tmp); end; {hay suficiente memoria como para seguir creando estructuras} tmp := kmalloc (sizeof (buffer_head)); if tmp = nil then exit (nil) ; tmp^.data := kmalloc (size) ; if tmp^.data = nil then begin kfree_s (tmp,sizeof(buffer_head)); exit(nil); end; tmp^.size := size ; Max_Buffers -= 1; exit (tmp); end; procedure free_buffer (bh : p_buffer_head );inline; begin kfree_s (bh^.data,bh^.size); kfree_s (bh,sizeof(buffer_head)); end; { * Get_Block : * * * * Mayor : Dev Mayor * * Menor : Dev Menor * * Bloque : Numero de bloque * * Retorno : nil si fue incorrecta o puntero a los datos * * * * Esta funcion es el nucleo del buffer , por ahora solo trabaja con * * bloques de dispostivos de bloque y con un tamano constante * * * *********************************************************************** } function get_block(Mayor,Menor,Bloque,size:dword):p_buffer_head;[public , alias :'GET_BLOCK']; var tmp:p_buffer_head; begin {Busco en la tabla hash} tmp := Hash_Find(Mayor,Menor,Bloque,size); {esta en uso} If tmp <> nil then begin tmp^.count += 1; exit (tmp); end; {Es Buscado en la tabla Lru} tmp := Lru_Find(Mayor,Menor,Bloque,size); If tmp <> nil then begin { En la Lru se guardan los q no estan en uso} Pop_Buffer(tmp,Buffer_Lru); tmp^.count := 1; Push_Hash(tmp); exit(tmp); end; tmp := alloc_buffer (size); {situacion poco querida} if tmp = nil then begin printk('/Vvfs/n : No hay mas buffer-heads libres\n',[]); exit(nil); end; Init_Bh (tmp,mayor,menor,bloque); {se trae la data del disco} If Buffer_Read(tmp) = 0 then begin Push_Hash(tmp); Get_Block := tmp; end else begin {hubo un error se devuelve el buffer} printk('/Vvfs/n : Error de Lectura : block %d dev %d %d \n',[tmp^.bloque,tmp^.mayor,tmp^.menor]); free_buffer (tmp); Max_Buffers += 1; exit(nil); end; end; { * Mark_Buffer_Dirty : * * * * bh : puntero a una estructura buffer * * * * Procedimiento que marca a un buffer como sucio y lo coloca en la * * utilizada por sync * * * *********************************************************************** } procedure Mark_Buffer_Dirty (Bh : p_buffer_head );[public , alias :'MARK_BUFFER_DIRTY']; begin if (bh^.state and Bh_dirty ) = Bh_Dirty then exit; Bh^.state := bh^.state or Bh_Dirty ; bh^.next_bh_dirty := Buffer_Dirty; Buffer_Dirty := bh ; end; { * Put_Block : * * * * Mayor : Dispositivo de bloque * * Menor : Dispositvo Menor * * Bloque : Numero de bloque * * * * Devuelve el uso de un bloque , y es llamado cada vez que se termina su uso * * y decrementa su uso * * Es importante , ya que luego de un GET_BLOCK deve venir un PUT_BLOCK , que * * devuelva a la reserva , y si el bloque es del sistema se actualizara la * * version del disco , ademas se decrementara el uso , para que pueda salir de* * la cola hash * * * ****************************************************************************** } function Put_Block(buffer:p_buffer_head):dword;[public , alias :'PUT_BLOCK']; var tmp : p_buffer_head ; begin if buffer=nil then panic('VFS : Se quita un buffer no pedido'); buffer^.count -= 1; {ya nadie lo esta utilizando} If buffer^.count = 0 then begin Pop_Hash (buffer); Push_buffer (buffer,Buffer_Lru); end; end; { * Sys_Sync : * * * * Implementacion de la llamada al sistema Sync() que actualiza todos * * bloques no utilizados al disco * * * * Versiones : * * * * 20 / 06 / 2005 : Rescritura con el nuevo modelo de FS * * 26 / 12 / 2004 : Son escritos tambien los bloques en la cola Hash * * * *********************************************************************** } procedure Sys_Sync ; [public , alias :'SYS_SYNC']; var tmp:p_buffer_head; begin sync_inodes ; {es simple se rastrea toda la cola de sucios} tmp := Buffer_Dirty ; while (tmp <> nil) do begin if Buffer_Update (tmp) = -1 then printk('/Vvfs/n : Error de escritura : block %d dev %d %d\n',[tmp^.bloque,tmp^.mayor,tmp^.menor]); tmp := tmp^.next_bh_dirty ; end; Buffer_Dirty := nil ; end; { * Invalid_Sb * * * * sb : Puntero a un superbloque * * * * Procedimiento que limpia todos los bloques y dado un sb manda los * * bloques en uso de ese sb a la cola LRU * * * *********************************************************************** } procedure Invalid_Sb ( sb : p_super_block_t) ;[public , alias : 'INVALID_SB']; var mayor,menor : dword ; bh , tbh : p_buffer_head ; begin mayor := sb^.mayor ; menor := sb^.menor ; {primero mando a todos al disco} sys_sync ; {ahora que estan todos limpios los quita de las de en uso} {si no hay salgo!} if Buffer_Hash[mayor] = nil then exit ; {todos los bufferes en uso son movidos a la cola lru} bh := Buffer_Hash [mayor]^.prev_buffer ; repeat pop_hash (bh); push_buffer (bh , Buffer_Lru); bh := bh^.prev_buffer ; until (bh <> nil); end; { * Buffer_Init : * * * * Proceso q inicializa la unidad de Buffer Cache , se inicializa la * * cola Lru y la cola Hash y se calcula el numero maximo de Bufferes * * * ************************************************************************** } procedure buffer_init;[public , alias :'BUFFER_INIT']; var tmp:dword; begin Buffer_Lru := nil; Buffer_Dirty := nil; for tmp:= 1 to Nr_blk do Buffer_Hash[tmp]:=nil; {Este numero es muy grande aunque Buffer_Use_mem solo valga 1%} Max_Buffers := ((Buffer_Use_Mem * MM_MemFree ) div 100) div sizeof(buffer_head); {aqui son configuradas las variables } Max_dentrys := Max_Buffers ; Max_Inodes := Max_dentrys ; printk('/Vvfs/n ... Buffer - Cache /V%d /nBufferes\n',[Max_Buffers]); printk('/Vvfs/n ... Inode - Cache /V%d /nBufferes\n',[Max_Buffers]); end; end.
unit HeaderFooterFormwithNavigation; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Forms, FMX.Dialogs, FMX.TabControl, System.Actions, FMX.ActnList, FMX.Objects, FMX.StdCtrls, FMX.Advertising; type THeaderFooterwithNavigation = class(TForm) ActionList1: TActionList; PreviousTabAction1: TPreviousTabAction; TitleAction: TControlAction; NextTabAction1: TNextTabAction; TopToolBar: TToolBar; btnBack: TSpeedButton; ToolBarLabel: TLabel; btnNext: TSpeedButton; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; BottomToolBar: TToolBar; BannerAd1: TBannerAd; procedure FormCreate(Sender: TObject); procedure PreviousTabAction1Update(Sender: TObject); procedure TitleActionUpdate(Sender: TObject); private { Private declarations } public { Public declarations } end; var HeaderFooterwithNavigation: THeaderFooterwithNavigation; implementation {$R *.fmx} procedure THeaderFooterwithNavigation.TitleActionUpdate(Sender: TObject); begin if Sender is TCustomAction then begin if TabControl1.ActiveTab <> nil then TCustomAction(Sender).Text := TabControl1.ActiveTab.Text else TCustomAction(Sender).Text := ''; end; end; procedure THeaderFooterwithNavigation.FormCreate(Sender: TObject); begin { This defines the default active tab at runtime } TabControl1.First(TTabTransition.ttNone); BannerAd1.AdUnitID := 'ca-app-pub-5009748780040029/5628984656'; BannerAd1.LoadAd; end; procedure THeaderFooterwithNavigation.PreviousTabAction1Update(Sender: TObject); begin {$IFDEF ANDROID} if Sender is TCustomAction then TCustomAction(Sender).Visible := False; {$ENDIF} end; end.
unit ClassLN; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TLn = class x: Real; function ln():Real; private public error: Real; constructor create(); destructor Destroy; override; end; implementation function potencia( b: Real; n: Integer ): Real; var i: Integer; begin Result:= 1; for i:= 1 to n do Result:= Result * b; end; function factorial( n: Integer ): LongInt; begin case n of 0, 1: Result:= 1; else Result:= n * factorial( n - 1 ); end; end; constructor TLn.create(); begin error:= 0.1; x:= 0; end; destructor TLn.Destroy; begin // end; function TLn.ln(): Real; var n : Integer = 0; NewError, xn: Real; begin Result:=0; xn:=1000000; repeat Result:= Result + ( potencia(-1, n-1) * (potencia(x, n) / n) ); NewError := abs( Result - xn); n := n + 1; xn := Result; until ((newError <= Error ) or ( n > 10)); end; end.
%TITLE('----- CRT Mapping Utility _____') %PAGE(50) { This version setup for Televideo terminals. To adapt to other terminals modify PROCEDURE PART2 which generates the cursor positioning (gotoxy) and clear screen (clear) codes. } {=================================================================} PROGRAM crtmap; TYPE char16 = ARRAY [1..16] OF char; VAR ch : char; alphameric : SET OF char; end_of_file : boolean; map_file_name : STRING[15]; word : char16; exproc_name : char16; include_name : char16; record_name : char16; f1, f2 : FILE OF char; {=================================================================} PROCEDURE error (msg : STRING[40]); VAR dummy : char16; BEGIN writeln; writeln; writeln(msg); writeln; { abnormally terminate - return to CP/M } call(0, dummy, dummy); END; {=================================================================} PROCEDURE get_char; BEGIN read(f1; ch); IF ch = chr(1ah) THEN error('Premature end of input file'); write(ch); END; {=================================================================} PROCEDURE get_word; LABEL 99; VAR i : integer; BEGIN word := ' '; WHILE NOT (ch IN alphameric) DO BEGIN get_char; END; word[1] := ch; i := 2; get_char; WHILE (ch IN alphameric) DO BEGIN word[i] := ch; i := i + 1; get_char; END; word := upcase(word); END; {get_word} {=================================================================} PROCEDURE init; BEGIN writeln('CRTMAP ver 4.0'); writeln; write('name of Map Description File : '); readln(map_file_name); writeln; writeln; reset(f1, map_file_name, binary, 256); end_of_file := false; ch := ' '; alphameric := ['A'..'Z', 'a'..'z', '0'..'9', ':', '.', '_', '$']; get_word; IF word <> 'EXPROC' THEN error('EXPROC command expected'); get_word; exproc_name := word; rewrite(f2, exproc_name + '.pas', binary, 256); get_word; IF word <> 'INCLUDE' THEN error('INCLUDE command expected'); get_word; include_name := word; get_word; IF word <> 'RECORD' THEN error('RECORD command expected'); get_word; record_name := word; END; {init} {=================================================================} PROCEDURE part1; BEGIN writeln(f2; '{ CRTMAP generated external procedure }'); writeln(f2; 'extern'); writeln(f2); writeln(f2; 'type'); writeln(f2; '%include (''', include_name, ''')'); writeln(f2); writeln(f2; 'procedure ', exproc_name, '( var r : ', record_name, ');'); writeln(f2); END; {part1} {=================================================================} PROCEDURE part2; BEGIN writeln(f2; 'procedure clear;'); writeln(f2; 'begin'); writeln(f2; 'write(chr(27),''*'');'); writeln(f2; 'end;'); writeln(f2); writeln(f2; 'procedure gotoxy ( x,y : integer );'); writeln(f2; 'begin'); writeln(f2; 'write(chr(27),''='',chr(y+20h),chr(x+20h));'); writeln(f2; 'end;'); writeln(f2); END; {part2} {=================================================================} PROCEDURE part3; {create DISPLAY procedure} {=================================================================} PROCEDURE process_coordinates; VAR x_coord, y_coord : char16; BEGIN get_word; x_coord := word; get_word; y_coord := word; writeln(f2; 'gotoxy( ', x_coord, ',', y_coord, ');'); END; {=================================================================} PROCEDURE process_string; BEGIN {find start of string} WHILE NOT (ch IN ['''', chr(0dh), ' ', chr(9), chr(1ah)]) DO get_char; IF ch <> '''' THEN error('Literal string expected'); write(f2; 'write('); REPEAT write(f2; ch); get_char; UNTIL ch = chr(0dh); writeln(f2; ');'); END; BEGIN {part3} writeln(f2; 'procedure display;'); writeln(f2; 'begin'); writeln(f2; 'clear;'); WHILE NOT end_of_file DO BEGIN get_word; CASE word OF 'LITERAL' : BEGIN process_coordinates; process_string; END; 'FIELD' : BEGIN process_coordinates; get_word; writeln(f2; 'write( r.', word, ');'); END; 'CURSOR' : process_coordinates; 'END' : end_of_file := true; ELSE : error('LITERAL, FIELD, CURSOR or END command expected'); END; END; writeln(f2; 'end;'); writeln(f2); END; {part3} {=================================================================} PROCEDURE part9; BEGIN writeln(f2; 'begin'); writeln(f2; 'display;'); writeln(f2; 'end;.'); END; {part9} BEGIN {crtmap} init; part1; part2; part3; part9; close(f1); close(f2); END {crtmap} . 
(* TXBUFF.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit TXBuff; {-TXTextControl buffer manager for EDSSpell component} interface uses Classes, Controls, Graphics, SysUtils, Forms, StdCtrls, Dialogs, WinProcs, WinTypes, VBXCtrl, BIVBX, Tx4vb, {$IFDEF Win32} {$IFDEF Ver100} LexDCTD3, {$ELSE} LexDCT32, {$ENDIF} {$ELSE} LexDCT, {$ENDIF} AbsBuff, MemoUtil, SpellGbl; (* For version 5.0 of the TX-Text Control, it was necessary to add a *) (* carraige return counter for the highlighighting of the word. If *) (* you are using version 5.0 then you must enable the $Define for *) (* TXText5 by removing the period below. *) {.$DEFINE TXText5} type TTXTextBuf = class (TPCharBuffer) {TX Text-Control Editor Buffer Manager} private { Private declarations } FCRCount: integer; {-counter for carraige returns within TX-Text Control} protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} procedure SetSelectedText; override; {-highlights the current word using BeginPos & EndPos} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} {$IFDEF TXText5} function GetNextWord: string; override; {-returns the next word in the buffer} property CRCount: integer read FCRCount write FCRCount; {$ENDIF} end; { TTXTextBuf } implementation {TX Text-Control Editor Buffer Manager} constructor TTXTextBuf.Create (AParent: TControl); begin inherited Create (AParent); {$IFDEF TXText5} CRCount := 0; {!!ES 7/2797} {$ENDIF} end; { TTXTextBuf.Create } function TTXTextBuf.IsModified: Boolean; {-returns TRUE if parent had been modified} begin {Result := TTextControl (Parent).Modified;} Result := TRUE; end; { TTXTextBuf.IsModified } procedure TTXTextBuf.SetModified (NowModified: Boolean); {-sets parents modified flag} begin {TTextControl (Parent).Modified := NowModified;} end; { TTXTextBuf.SetModified } {$IFDEF TXText5} (* The following code was essentially copied from AbsBuff.PAS *) (* Changes that were made are identified with the {!!ES} identifier *) function TTXTextBuf.GetNextWord: string; {-returns the next word in the buffer} var S: string; {string being constructed} InHTML: Boolean; {TRUE if '<' has been encountered} Ch: Char; begin BeginPos := CurPos; EndPos := CurPos; S := ''; InHTML := FALSE; AllNumbers := TRUE; {!!ES 7/27/97} {find the first letter of the next word} while (not (Char (PCurPos^) in ValidChars)) and (CurPos<BufSize) or InHTML do begin if SupportHTML then begin Ch := PCurPos^; if InHTML and (Ch = '>') then InHTML := FALSE else if Ch = '<' then InHTML := TRUE; end; { if... } Inc (CurPos, 1); PCurPos := @Buffer^[CurPos]; end; { while } if CurPos<BufSize then begin BeginPos := CurPos; {goto the end of the word} while ((Char (PCurPos^) in ValidChars) and (CurPos<BufSize)) do begin S := ConCat (S, Char (PCurPos^)); Inc (CurPos, 1); if AllNumbers and (not (Char (PCurPos^) in NumberSet)) then AllNumbers := FALSE; {!!ES 7/27/97} PCurPos := @Buffer^[CurPos]; EndPos := CurPos; if EndPos - BeginPos = MaxWordLength then begin MessageDlg ('Aborting spell check (Invalid word): ' + #13 + S, mtError, [mbOk], 0); S := ''; Break; end; { if... } end; { while } if Char (PCurPos^) = #13 then {!!ES 7/2797} CRCount := CRCount + 1; Result := S; end {:} else Result := ''; end; { TTXTextBuf.GetNextword } {$ENDIF} function TTXTextBuf.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} begin Result := 0; end; { TTXTextBuf.GetYPos } procedure TTXTextBuf.SetSelectedText; {-highlights the current word using FBeginPos & FEndPos} begin with Parent as TTextControl do begin SelStart := BeginPos - 1; {$IFDEF TXText5} SelStart := SelStart - CRCount; {!!ES 7/2797} {$ENDIF} SelLength := EndPos - BeginPos; Update; end; { with } end; { TTXTextBuf.SetSelectedText } procedure TTXTextBuf.UpdateBuffer; {-updates the buffer from the parent component, if any} begin BufSize := TTextControl (Parent).GetTextLen + 1; TTextControl (Parent).GetTextBuf (pChar(Buffer), BufSize); {support international characters} AnsiToOemBuff (pChar (Buffer), pChar (Buffer), BufSize); PCurPos := @Buffer^[CurPos]; end; { TTXTextBuf.UpdateBuffer } procedure TTXTextBuf.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin with Parent as TTextControl do begin CurPos := CurPos - (EndPos - BeginPos); SelText := WithWord; CurPos := CurPos + SelLength; UpdateBuffer; end; { with } end; { TTXTextBuf.ReplaceWord } end. { TXBuff }
unit u_ast_constructions_blocks; {$INTERFACES CORBA} {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_tokens, u_ast_blocks, u_ast_expression_blocks; type TMashASTB_Import = class(TMashASTBlock) public method_name: string; lib_name: string; native_name: string; call_counter: cardinal; constructor Create(_method_name, _lib_name, _native_name: string); end; TMashASTB_RegAPI = class(TMashASTBlock) public method_name: string; number: string; constructor Create(_method_name, _number: string); end; TMashASTB_Uses = class(TMashASTBlock) public Expr: TList; constructor Create; destructor Destroy; override; end; TMashASTB_Inline = class(TMashASTBlock) public asm_string: string; constructor Create(_asm_string: string); end; TMashASTB_Const = class(TMashASTBlock) public const_name: string; const_value: TMashToken; isStream: boolean; constructor Create(_name: string; _value: TMashToken; _isStream: boolean); end; TMashASTB_Method = class(TMashASTBlockWithNodes) public is_function: boolean; method_name: string; is_class_method: boolean; class_name: string; params: TList; local_vars: TStringList; line: cardinal; fp: PString; call_counter: word; internal_calls: TList; // of TMashASTB_Method external_calls: TList; // of TMashASTB_Import allocations: TList; // of TMashASTB_Class constructor Create(_is_function: boolean; _method_name: string; _is_class_method: boolean; _class_name: string; _line: cardinal; var _fp: string); destructor Destroy; override; end; TMashASTB_Param = class(TMashASTBlock) public is_enumerable: boolean; param: TMashToken; constructor Create(_param: TMashToken; _is_enumerable: boolean); end; TMashASTB_If = class(TMashASTBlockWithNodes) public Expr: TMashASTB_Expression; hasElse: boolean; ElseNodes: TList; constructor Create(_Expr: TMashASTB_Expression); destructor Destroy; override; end; TMashASTB_ForEach = class(TMashASTBlockWithNodes) public forVar: string; isBack: boolean; Expr: TMashASTB_Expression; constructor Create(_forVar: string; _isBack: boolean; _Expr: TMashASTB_Expression); end; TMashASTB_While = class(TMashASTBlockWithNodes) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Whilst = class(TMashASTBlockWithNodes) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Return = class(TMashASTBlock) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Switch = class(TMashASTBlockWithNodes) public Expr: TMashASTB_Expression; hasElse: boolean; ElseCase: TMashASTBlock; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Case = class(TMashASTBlockWithNodes) public Expr: TMashASTB_Expression; isElse: boolean; constructor Create(_Expr: TMashASTB_Expression; _isElse: boolean); end; TMashASTB_Launch = class(TMashASTBlockWithNodes) public constructor Create; end; TMashASTB_Async = class(TMashASTBlockWithNodes) public forVar: string; constructor Create(_forVar: string); end; TMashASTB_Wait = class(TMashASTBlock) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Break = class(TMashASTBlock) public constructor Create; end; TMashASTB_Continue = class(TMashASTBlock) public constructor Create; end; TMashASTB_Class = class(TMashASTBlock) public class_name: string; class_vars: TStringList; class_methods: TList; class_parents: TStringList; constructor Create(_class_name: string); destructor Destroy; override; end; TMashClassMethodReference = class public method_name: string; reference: TMashASTB_Method; constructor Create(_method_name: string; _reference: TMashASTB_Method); end; TMashASTB_ClassField = class(TMashASTBlock) public names: TStringList; constructor Create; destructor Destroy; override; end; TMashASTB_Public = class(TMashASTBlock) public constructor Create; end; TMashASTB_Private = class(TMashASTBlock) public constructor Create; end; TMashASTB_Protected = class(TMashASTBlock) public constructor Create; end; TMashASTB_Try = class(TMashASTBlockWithNodes) public hasCatch: boolean; NodesCatch: TList; forVar: string; constructor Create; destructor Destroy; override; end; TMashASTB_Raise = class(TMashASTBlock) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Safe = class(TMashASTBlock) public Expr: TMashASTB_Expression; constructor Create(_Expr: TMashASTB_Expression); end; TMashASTB_Enum = class(TMashASTBlockWithNodes) public Name: string; constructor Create(_Name: string); end; TMashASTB_EnumItem = class(TMashASTBlock) public Name: string; hasDefValue: boolean; DefValue: TMashToken; constructor Create(_Name: string); end; implementation constructor TMashASTB_Import.Create(_method_name, _lib_name, _native_name: string); begin inherited Create(btImport); self.method_name := _method_name; self.lib_name := _lib_name; self.native_name := _native_name; self.call_counter := 0; end; constructor TMashASTB_RegAPI.Create(_method_name, _number: string); begin inherited Create(btRegAPI); self.method_name := _method_name; self.number := _number; end; constructor TMashASTB_Uses.Create; begin inherited Create(btUses); self.Expr := TList.Create; end; destructor TMashASTB_Uses.Destroy; begin FreeAndNil(self.Expr); inherited; end; constructor TMashASTB_Inline.Create(_asm_string: string); begin inherited Create(btInline); self.asm_string := _asm_string; end; constructor TMashASTB_Const.Create(_name: string; _value: TMashToken; _isStream: boolean); begin inherited Create(btConst); self.const_name := _name; self.const_value := _value; self.isStream := _isStream; end; constructor TMashASTB_Method.Create(_is_function: boolean; _method_name: string; _is_class_method: boolean; _class_name: string; _line: cardinal; var _fp: string); begin inherited Create(btMethod); self.is_function := _is_function; self.method_name := _method_name; self.is_class_method := _is_class_method; self.class_name := _class_name; self.line := _line; self.fp := @_fp; self.params := TList.Create; self.call_counter := 0; self.internal_calls := TList.Create; self.external_calls := TList.Create; self.allocations := TList.Create; self.local_vars := TStringList.Create; end; destructor TMashASTB_Method.Destroy; begin FreeAndNil(self.params); FreeAndNil(self.internal_calls); FreeAndNil(self.external_calls); FreeAndNil(self.allocations); FreeAndNil(self.local_vars); inherited; end; constructor TMashASTB_Param.Create(_param: TMashToken; _is_enumerable: boolean); begin inherited Create(btParam); self.param := _param; self.is_enumerable := _is_enumerable; end; constructor TMashASTB_If.Create(_Expr: TMashASTB_Expression); begin inherited Create(btIf); self.Expr := _Expr; self.hasElse := false; self.ElseNodes := TList.Create; end; destructor TMashASTB_If.Destroy; begin FreeAndNil(self.ElseNodes); inherited; end; constructor TMashASTB_ForEach.Create(_forVar: string; _isBack: boolean; _Expr: TMashASTB_Expression); begin inherited Create(btForEach); self.forVar := _forVar; self.isBack := _isBack; self.Expr := _Expr; end; constructor TMashASTB_While.Create(_Expr: TMashASTB_Expression); begin inherited Create(btWhile); self.Expr := _Expr; end; constructor TMashASTB_Whilst.Create(_Expr: TMashASTB_Expression); begin inherited Create(btWhilst); self.Expr := _Expr; end; constructor TMashASTB_Return.Create(_Expr: TMashASTB_Expression); begin inherited Create(btReturn); self.Expr := _Expr; end; constructor TMashASTB_Switch.Create(_Expr: TMashASTB_Expression); begin inherited Create(btSwitch); self.Expr := _Expr; self.hasElse := false; self.ElseCase := nil; end; constructor TMashASTB_Case.Create(_Expr: TMashASTB_Expression; _isElse: boolean); begin inherited Create(btCase); self.Expr := _Expr; self.isElse := _isElse; end; constructor TMashASTB_Launch.Create; begin inherited Create(btLaunch); end; constructor TMashASTB_Async.Create(_forVar: string); begin inherited Create(btAsync); self.forVar := _forVar; end; constructor TMashASTB_Wait.Create(_Expr: TMashASTB_Expression); begin inherited Create(btWait); self.Expr := _Expr; end; constructor TMashASTB_Break.Create; begin inherited Create(btBreak); end; constructor TMashASTB_Continue.Create; begin inherited Create(btContinue); end; constructor TMashASTB_Class.Create(_class_name: string); begin inherited Create(btClass); self.class_name := _class_name; self.class_vars := TStringList.Create; self.class_methods := TList.Create; self.class_parents := TStringList.Create; end; destructor TMashASTB_Class.Destroy; begin FreeAndNil(self.class_vars); FreeAndNil(self.class_parents); while self.class_methods.count > 0 do begin TMashClassMethodReference(self.class_methods[0]).Free; self.class_methods.Delete(0); end; FreeAndNil(self.class_methods); inherited; end; constructor TMashClassMethodReference.Create(_method_name: string; _reference: TMashASTB_Method); begin self.method_name := _method_name; self.reference := _reference; end; constructor TMashASTB_ClassField.Create; begin inherited Create(btClassField); self.names := TStringList.Create; end; destructor TMashASTB_ClassField.Destroy; begin FreeAndNil(self.names); inherited; end; constructor TMashASTB_Public.Create; begin inherited Create(btPublic); end; constructor TMashASTB_Private.Create; begin inherited Create(btPrivate); end; constructor TMashASTB_Protected.Create; begin inherited Create(btProtected); end; constructor TMashASTB_Try.Create; begin inherited Create(btTry); self.hasCatch := false; self.NodesCatch := TList.Create; self.forVar := ''; end; destructor TMashASTB_Try.Destroy; begin FreeAndNil(self.NodesCatch); inherited; end; constructor TMashASTB_Raise.Create(_Expr: TMashASTB_Expression); begin inherited Create(btRaise); self.Expr := _Expr; end; constructor TMashASTB_Safe.Create(_Expr: TMashASTB_Expression); begin inherited Create(btSafe); self.Expr := _Expr; end; constructor TMashASTB_Enum.Create(_Name: string); begin inherited Create(btEnum); self.Name := _Name; end; constructor TMashASTB_EnumItem.Create(_Name: string); begin inherited Create(btEnumItem); self.Name := _Name; self.hasDefValue := false; self.DefValue := nil; end; end.
unit uZeeBeClient; interface uses System.SysUtils, System.Classes, gateway_protocol.Proto, gateway_protocol.Client; type EZeeBeError = class(Exception); ECompleteJobError = class(EZeeBeError); EDoJobError = class(EZeeBeError); EProcessMessageError = class(EZeeBeError); Type TWorkerProc = procedure(JobInfo: TActivatedJob) of object; TdmZeeBeClient = class(TDataModule) procedure DataModuleCreate(Sender: TObject); private FClient: IGateway_Client; fServer: string; fPort: Integer; procedure SetPort(const Value: Integer); procedure SetServer(const Value: string); function GetTopologie: string; function GetClient: IGateway_Client; public property Server: string read FServer write SetServer; property Port: Integer read FPort write SetPort; property Client: IGateway_Client read GetClient; property Topology: string read GetTopologie; procedure RestartClient; //after port changed etc. Function DeployWorkflow(const ZeeBeFileName: string): string; Function StartCase(const BPMNID, CaseVars: String): UInt64; //Result: WFInstanceID procedure ActivateJob(const JobType: string; BusinessLogic: TWorkerProc; IsAutoComplete: Boolean); procedure CompleteJobRequest(JobKey: UInt64; const Variables: string = ''); procedure PublishMessage(const aName, correlationKey: String; WFInstance: UInt64); procedure SetVariables(WFInstance: UInt64; const aVars: string; local: Boolean = false); end; var ZeeBeClient: TdmZeeBeClient; function IZeeBeClient: IGateway_Client; implementation uses System.IOUtils, System.Threading, Superobject, Grijjy.ProtocolBuffers; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmZeeBeClient } function IZeeBeClient: IGateway_Client; begin if not Assigned(ZeeBeClient.fClient) then ZeeBeClient.fClient := TGateway_Client.Create(ZeeBeClient.Server, ZeeBeClient.Port); Result := ZeeBeClient.fClient; end; procedure TdmZeeBeClient.ActivateJob(const JobType: string; BusinessLogic: TWorkerProc; IsAutoComplete: Boolean); var aActivateJobsRequest: TActivateJobsRequest; begin aActivateJobsRequest._type := JobType; aActivateJobsRequest.worker := 'PMM'; aActivateJobsRequest.timeout := 100000; aActivateJobsRequest.maxJobsToActivate := 10; aActivateJobsRequest.fetchVariable := []; {[] = all / [JobVars];} aActivateJobsRequest.requestTimeout := 10000; try Client.ActivateJobs(aActivateJobsRequest, procedure(const aResponse: TActivatedJobArray; const aHasData, aClosed: Boolean) begin TParallel.For(0, High(aResponse), procedure(I: Integer) var aRes: TActivatedJob; begin aRes := aResponse[I]; BusinessLogic(aRes); // >>> do the business logic <<< if IsAutoComplete then CompleteJobRequest(UInt64(aRes.Key)); end); end); except on e: Exception do raise EDoJobError.CreateFmt('Error in ActivateJobs "%s": %s',[JobType,e.Message]) end; end; procedure TdmZeeBeClient.CompleteJobRequest(JobKey: UInt64; const Variables: string); var aCJob: TCompleteJobRequest; begin aCJob.jobKey := UInt64(JobKey); aCJob.variables := Variables; try TGateway_Client.Create(FServer, FPort).CompleteJob(aCJob); except on E: EgoSerializationError do; on e: Exception do raise ECompleteJobError.CreateFmt('Exception in CompleteJobRequest(#%s): %s.',[JobKey,e.Message]); end; end; procedure TdmZeeBeClient.DataModuleCreate(Sender: TObject); begin fServer := '127.0.0.1'; fPort := 26500; end; Function TdmZeeBeClient.DeployWorkflow(const ZeeBeFileName: string): string; var aWFRequest:TWorkflowRequestObject; aWFs: TWorkflowRequestObjectArray; aWFResponse: TDeployWorkflowResponse; begin try aWFRequest.name := ZeeBeFileName; aWFRequest._type := BPMN; aWFRequest.definition := TFile.ReadAllBytes(aWFRequest.name); aWFs := [aWFRequest]; aWFResponse := Client.DeployWorkflow(aWFs); RESULT := TSuperRttiContext.Create.AsJson<TDeployWorkflowResponse>(aWFResponse).AsJSon(); except on e: exception do RESULT := e.Message; end; end; function TdmZeeBeClient.GetClient: IGateway_Client; begin if not Assigned(fClient) then fClient := TGateway_Client.Create(self.Server, self.Port); Result := fClient; end; function TdmZeeBeClient.GetTopologie: string; var aTR: TTopologyResponse; begin aTR := IZeeBeClient.Topology(); Result := TSuperRttiContext.Create.AsJson<TTopologyResponse>(aTR).AsJSon(); end; procedure TdmZeeBeClient.PublishMessage(const aName, correlationKey: String; WFInstance: UInt64); var aPMRequest: TPublishMessageRequest; begin try aPMRequest.name := aName; aPMRequest.correlationKey := correlationKey; aPMRequest.timeToLive := 10000; aPMRequest.messageId := IntToStr(WFInstance); aPMRequest.variables := ''; Client.PublishMessage(aPMRequest); except on E: EgoSerializationError do; //happens because of returned empty record type on E: Exception do raise EProcessMessageError.CreateFmt('Error in PublishMessage: %s',[E.Message]); end; end; procedure TdmZeeBeClient.RestartClient; begin FClient := nil; end; procedure TdmZeeBeClient.SetPort(const Value: Integer); begin if FPort <> Value then Begin RestartClient; FPort := Value; End; end; procedure TdmZeeBeClient.SetServer(const Value: string); begin if FServer <> Value then Begin RestartClient; FServer := Value; End; end; procedure TdmZeeBeClient.SetVariables(WFInstance: UInt64; const aVars: string; local: Boolean); var aRequest: TSetVariablesRequest; begin try aRequest.elementInstanceKey := WFInstance; aRequest.variables := aVars; aRequest.local := local; Client.SetVariables(aRequest); except on E: EgoSerializationError do; //passiert, weil Rückgabe-Type ein leerer Record ist. on E: Exception do raise EProcessMessageError.CreateFmt('Error in SetMessage: %s',[E.Message]); end; end; function TdmZeeBeClient.StartCase(const BPMNID, CaseVars: String): UInt64; var aWFIRequest: TCreateWorkflowInstanceRequest; begin aWFIRequest.workflowKey := UInt64(-1); //-1 = NULL / must be casted to UInt aWFIRequest.bpmnProcessId := BPMNID; aWFIRequest.version := UInt32(-1); //-1 = latest / must be casted to UInt aWFIRequest.variables := CaseVars; Result := Client.CreateWorkflowInstance(aWFIRequest).workflowInstanceKey; end; initialization finalization end.
unit Jobs; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, JvComponentBase, JvFormMagnet, Vcl.StdCtrls, Vcl.CheckLst; type TForm2 = class(TForm) JvFormMagnet1: TJvFormMagnet; JobList: TCheckListBox; BatchBtn: TButton; ClearBtn: TButton; DeSelBtn: TButton; SelectBtn: TButton; procedure FormShow(Sender: TObject); procedure BatchBtnClick(Sender: TObject); procedure JobListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure AddJob(const AFile : string; const tDuration : string); procedure SaveINI; procedure ClearBtnClick(Sender: TObject); procedure SelectBtnClick(Sender: TObject); procedure DeSelBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation uses Main, IniFiles, Contnrs, IOUtils; type TJobObj = class Cuts : TStringList; TheShow : string; constructor Create; destructor Destroy; override; end; var JobHelper : TObjectList; {$R *.dfm} (*------------------------------------------------------------------------------ TJobObj, it contains the information for 1 Job ------------------------------------------------------------------------------*) constructor TJobObj.Create; begin inherited Create; Cuts := TStringList.Create; end; destructor TJobObj.Destroy; begin Cuts.Free; inherited; end; (*------------------------------------------------------------------------------ New Job Creation ------------------------------------------------------------------------------*) procedure TForm2.AddJob(const AFile : string; const tDuration : string); const // args = '"%s" -i "%s" -ss %s -to %s -acodec copy -vcodec libx264 -y "%s"'; //input file, start, end , outputfilename Line = '%d Clips(s) | %s'; var //cutpoints : TStringList; idx : integer; AJob : TJobObj; begin AJob := TJobObj.Create; AJob.TheShow := AFile; AJob.Cuts.Append('00:00:00.00'); for idx := 0 to Form1.BlackSegList.Count -1 do begin if Form1.BlackSegList.Checked[idx] then begin AJob.Cuts.Append( StringReplace(Form1.BlackSegList.Items.Strings[idx],'*','',[rfReplaceAll]) ); end; end; AJob.Cuts.Append(tDuration); if AJob.Cuts.Count = 2 then begin ShowMessage('Nothing to Cut'); AJob.Free; //Its never added so free exit; end; {CutPoints := TStringList.Create; for idx := 0 to Form1.CutList.Lines.Count -1 do begin CutPoints.CommaText := Form1.CutList.Lines.Strings[idx]; CutPoints.Add(AFile); JobList.Checked[JobList.Items.Add(CutPoints.CommaText)] := true; end; CutPoints.Free;} idx := JobList.Items.AddObject( Format(Line,[AJob.Cuts.Count-1,ExtractFileName(AJob.TheShow)]), AJob ); JobHelper.Add(AJob); //this owns the Job Object JobList.TopIndex := JobList.Items.Count - 1; JobList.Checked[idx] := true; SaveINI; end; (*------------------------------------------------------------------------------ Job List -> Batch File ------------------------------------------------------------------------------*) procedure TForm2.BatchBtnClick(Sender: TObject); const args = '"%s" -i "%s" -ss %s -to %s -acodec copy -vcodec libx264 -y "%s"'; //input file, start, end , outputfilename var idx : integer; AJob : TJobObj; Batch : TStringList; cutidx : integer; begin Batch := TStringList.Create; for idx := 0 to JobList.Count -1 do begin if JobList.Checked[idx] then begin AJob := JobList.Items.Objects[idx] as TJobObj; for cutidx := 0 to AJob.Cuts.Count - 2 do begin Batch.Add(Format(args, [ffmpeg, AJob.TheShow, AJob.Cuts.Strings[cutidx], AJob.Cuts.Strings[cutidx+1], ExtractFilePath(AJob.TheShow)+TPath.GetFileNameWithoutExtension(AJob.TheShow)+'('+IntToStr(cutidx+1)+').mkv']) ); end; end; end; Batch.SaveToFile('Jobs.cmd'); Batch.Free; ShowMessage('Done, see Jobs.cmd'); end; (*------------------------------------------------------------------------------ Form Controls ------------------------------------------------------------------------------*) procedure TForm2.JobListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key=VK_Delete) and (JobList.ItemIndex > -1) then begin JobList.Items.Delete(JobList.ItemIndex); JobHelper.Delete(JobList.ItemIndex); end; end; procedure TForm2.FormCreate(Sender: TObject); const Line = '%d Clips(s) | %s'; var ini : TMemIniFile; i : integer; JobInfo : TStringList; JobLines : TStringList; AJob : TJobObj; begin JobInfo := TStringList.Create; JobLines := TStringList.Create; JobHelper := TObjectList.Create; JobHelper.OwnsObjects := true; ini := TMemIniFile.Create('Jobs.ini'); try JobLines.Clear; JobInfo.Clear; ini.ReadSection('Jobs', JobLines); for i := 0 to JobLines.Count - 1 do begin JobInfo.CommaText := JobLines.Strings[i]; AJob := TJobObj.Create; AJob.Cuts.Assign(JobInfo); AJob.TheShow := AJob.Cuts.Strings[AJob.Cuts.Count-1]; AJob.Cuts.Delete(AJob.Cuts.Count-1); JobList.Items.AddObject( Format(Line,[AJob.Cuts.Count-1,ExtractFileName(AJob.TheShow)]), AJob ); JobHelper.Add(AJob); //this owns the Job Object JobList.Checked[i] := ini.ReadBool('Jobs', JobLines[i], False); end; finally ini.Free; JobInfo.Free; JobLines.Free; end; end; procedure TForm2.SaveINI; var ini : TMemIniFile; i : integer; tmp : TStringList; begin tmp := TStringList.Create; ini := TMemIniFile.Create('Jobs.ini'); ini.Clear; try for i := 0 to JobList.Items.Count - 1 do begin tmp.Clear; tmp.Assign( TJobObj(JobList.Items.Objects[i]).Cuts ); tmp.Append( TJobObj(JobList.Items.Objects[i]).TheShow ); ini.WriteBool('Jobs', tmp.CommaText, JobList.Checked[i]); end; ini.UpdateFile; finally ini.Free; end; tmp.Free; end; procedure TForm2.SelectBtnClick(Sender: TObject); var idx : integer; begin for idx := 0 to JobList.Count-1 do JobList.Checked[idx] := true; end; procedure TForm2.ClearBtnClick(Sender: TObject); begin JobList.Clear; JobHelper.Clear; end; procedure TForm2.DeSelBtnClick(Sender: TObject); var idx : integer; begin for idx := 0 to JobList.Count-1 do JobList.Checked[idx] := false; end; procedure TForm2.FormDestroy(Sender: TObject); begin SaveINI; JobHelper.Free; end; procedure TForm2.FormShow(Sender: TObject); begin Self.Left := Form1.Left+Form1.Width; Self.Top := Form1.Top; Self.Height := Form1.Height; end; end.
{$B-,I-,Q-,R-,S-} {$M 65384,0,655360} {Problema 11: Cumplea¤os Bovino [Tradicional, 2005] Bessie le pregunt˘ a su amiga en que dĦa de la semana naci˘ ella. Ella sabĦa que ella naci˘ el 25 de Mayo de 2003, pero no sabĦa que dĦa era. Escriba un programa para ayudarla. Note que ninguna vaca naci˘ antes del a¤o 1800. Hechos a saber: * El 1 de Enero de 1900 fue un Lunes. * Longitudes de los meses: Ene 31 May 31 Sep 30 Feb 28 o 29 Jun 30 Oct 31 Mar 31 Jul 31 Nov 30 Abr 30 Ago 31 Dic 31 * Cada a¤o divisible por 4 es un a¤o bisiesto (1992 = 4*498, por lo tanto 1992 es un a¤o bisiesto, pero al a¤o 1900 no es un a¤o bisiesto. * La regla anterior no se cumple para a¤os de centuria. Los a¤os de centuria divisibles por 400 son a¤os bisiestos, los otros no lo son. Por lo tanto los a¤os centuria 1700, 1800, 1900 y 2100 no son a¤os Bisiestos, pero 2000 sĦ es un a¤o bisiesto. No use ninguna funci˘n pre-definida en su lenguaje de programaci˘n. NOMBRE DEL PROBLEMA: bday FORMATO DE ENTRADA: * LĦnea 1: Tres enteros separados por espacios que representan respectivamente, el a¤o, el mes (en el rango 1..12), y un dĦa de una fecha. ENTRADA EJEMPLO (archivo bday.in): 2003 5 25 DETALLES DE LA ENTRADA: 25 de Mayo de 2003 FORMATO DE SALIDA: * Una sola lĦnea que es el dĦa de la semana (en inglès) de la fecha especificada (de la lista en minuscula: monday(lunes), tuesday(martes), wednesday(mi‚rcoles), thursday(jueves), friday(viernes), saturday(sàbado), sunday(domingo)). SALIDA EJEMPLO (archivo bday.out): Sunday DETALLES DE LA SALIDA: Mayo 2003 Do Lu Ma Mi Ju Vi Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Ene 31 May 31 Sep 30 Feb 28 o 29 Jun 30 Oct 31 Mar 31 Jul 31 Nov 30 Abr 30 Ago 31 Dic 31 } const day : array[1..7] of string =('monday','tuesday','wednesday','thursday','friday','saturday','sunday'); mes : array[1..12] of byte=(31,28,31,30,31,30,31,31,30,31,30,31); var fe,fs : text; a,m,d,i,di,j,k : longint; procedure open; begin assign(fe,'bday.in'); reset(fe); assign(fs,'bday.out'); rewrite(fs); readln(fe,a,m,d); close(fe); end; procedure closer; begin if i=6 then i:=1 else if i=7 then i:=2 else i:=i+2; writeln(fs,day[i]); close(fs); end; procedure work; begin i:=0; k:=1799; di:=0; j:=0; repeat begin inc(k); mes[2]:=28; if (k mod 4 = 0) then begin mes[2]:=29; if (k mod 100 = 0) then begin if k mod 400 = 0 then mes[2]:=29 else mes[2]:=28; end; end else mes[2]:=28; j:=0; repeat begin inc(j); di:=0; repeat begin inc(di); if i=7 then i:=1 else inc(i); if (di=d) and (j=m) and (k=a) then exit; end; until di=mes[j]; end; until J=12; end; until k=a; end; begin open; work; closer; end.
unit OTFECrossCryptTestApp_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface {$IFDEF LINUX} This software is only intended for use under MS Windows {$ENDIF} {$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already // protecting against that! uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin64, FileCtrl, ExtCtrls, ComCtrls, OTFE_U, OTFECrossCrypt_U; type TOTFECrossCryptTestApp_F = class(TForm) pbClose: TButton; pbVersion: TButton; pbIsEncryptedVolFile: TButton; edTestIfMtdVolFile: TEdit; DriveComboBox1: TDriveComboBox; OpenDialog1: TOpenDialog; pbBrowse: TButton; pbDisountVolume: TButton; pbMountVolume: TButton; pbDismountDrive: TButton; pbClear: TButton; rgActive: TRadioGroup; ckDismountDriveEmergency: TCheckBox; pbGetFileMountedForDrive: TButton; pbGetDriveMountedForFile: TButton; pbNumDrivesMounted: TButton; pbRefresh: TButton; pbGetDrivesMounted: TButton; pbIsDriverInstalled: TButton; pbDismountAll: TButton; RichEdit1: TRichEdit; pbDriveInfo: TButton; gbVolInfo: TGroupBox; lblReadOnly: TLabel; lblDriveMountedAs: TLabel; Label15: TLabel; Label22: TLabel; Label2: TLabel; lblVolumeFile: TLabel; pbVersionStr: TButton; lblUserDevice: TLabel; Label7: TLabel; OTFECrossCrypt1: TOTFECrossCrypt; Button1: TButton; seCreateVolSize: TSpinEdit64; Label1: TLabel; lblKernelDevice: TLabel; procedure pbCloseClick(Sender: TObject); procedure pbVersionClick(Sender: TObject); procedure pbIsEncryptedVolFileClick(Sender: TObject); procedure pbBrowseClick(Sender: TObject); procedure pbMountVolumeClick(Sender: TObject); procedure pbDisountVolumeClick(Sender: TObject); procedure pbDismountDriveClick(Sender: TObject); procedure pbClearClick(Sender: TObject); procedure rgActiveClick(Sender: TObject); procedure pbGetFileMountedForDriveClick(Sender: TObject); procedure pbGetDriveMountedForFileClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbNumDrivesMountedClick(Sender: TObject); procedure pbRefreshClick(Sender: TObject); procedure pbGetDrivesMountedClick(Sender: TObject); procedure pbIsDriverInstalledClick(Sender: TObject); procedure pbDismountAllClick(Sender: TObject); procedure pbDriveInfoClick(Sender: TObject); procedure pbVersionStrClick(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure ReportWhetherActive(); procedure RefreshDriveComboBox(); public { Public declarations } end; var OTFECrossCryptTestApp_F: TOTFECrossCryptTestApp_F; implementation {$R *.DFM} uses ShellAPI; procedure TOTFECrossCryptTestApp_F.ReportWhetherActive(); begin if OTFECrossCrypt1.Active then begin RichEdit1.lines.add('CrossCrypt component ACTIVE'); rgActive.ItemIndex:=0; end else begin RichEdit1.lines.add('CrossCrypt component NOT Active'); rgActive.ItemIndex:=1; end; end; procedure TOTFECrossCryptTestApp_F.pbCloseClick(Sender: TObject); begin Close; end; procedure TOTFECrossCryptTestApp_F.pbVersionClick(Sender: TObject); begin RichEdit1.lines.add('Driver version: 0x'+inttohex(OTFECrossCrypt1.Version(), 1)); end; procedure TOTFECrossCryptTestApp_F.pbIsEncryptedVolFileClick(Sender: TObject); var filename: string; output: string; begin filename := edTestIfMtdVolFile.text; output := filename; if OTFECrossCrypt1.IsEncryptedVolFile(filename) then begin output := output + ' IS '; end else begin output := output + ' is NOT '; end; output := output + 'a CrossCrypt volume file'; RichEdit1.lines.add(output); end; procedure TOTFECrossCryptTestApp_F.pbBrowseClick(Sender: TObject); begin OpenDialog1.Filename := edTestIfMtdVolFile.text; if OpenDialog1.execute() then begin edTestIfMtdVolFile.text := OpenDialog1.FileName; end; end; procedure TOTFECrossCryptTestApp_F.pbMountVolumeClick(Sender: TObject); begin if OTFECrossCrypt1.Mount(edTestIfMtdVolFile.text)<>#0 then begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' mounted OK'); end else begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' mount failed'); end; RefreshDriveComboBox(); end; procedure TOTFECrossCryptTestApp_F.pbDisountVolumeClick(Sender: TObject); begin if OTFECrossCrypt1.Dismount(edTestIfMtdVolFile.text, ckDismountDriveEmergency.checked) then begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismounted OK'); end else begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismount failed'); end; RefreshDriveComboBox(); end; procedure TOTFECrossCryptTestApp_F.pbDismountDriveClick(Sender: TObject); var output: string; begin output := DriveComboBox1.drive + ': '; if OTFECrossCrypt1.Dismount(DriveComboBox1.drive, ckDismountDriveEmergency.checked) then begin output := output + 'dismounted OK'; end else begin output := output + 'dismount FAILED'; end; RichEdit1.lines.add(output); RefreshDriveComboBox(); end; procedure TOTFECrossCryptTestApp_F.RefreshDriveComboBox(); var origCase: TTextCase; begin origCase := DriveComboBox1.TextCase; DriveComboBox1.TextCase := tcUpperCase; DriveComboBox1.TextCase := tcLowerCase; DriveComboBox1.TextCase := origCase; end; procedure TOTFECrossCryptTestApp_F.pbClearClick(Sender: TObject); begin RichEdit1.lines.Clear(); end; procedure TOTFECrossCryptTestApp_F.rgActiveClick(Sender: TObject); begin try OTFECrossCrypt1.Active := (rgActive.ItemIndex=0); finally ReportWhetherActive(); end; end; procedure TOTFECrossCryptTestApp_F.pbGetFileMountedForDriveClick(Sender: TObject); var output: string; begin output := DriveComboBox1.drive + ': is CrossCrypt volume file: "' + OTFECrossCrypt1.GetVolFileForDrive(DriveComboBox1.drive) + '"'; RichEdit1.lines.add(output); end; procedure TOTFECrossCryptTestApp_F.pbGetDriveMountedForFileClick(Sender: TObject); var output: string; begin output := '"' + edTestIfMtdVolFile.text + '" is mounted as: '+ OTFECrossCrypt1.GetDriveForVolFile(edTestIfMtdVolFile.text) + ':'; RichEdit1.lines.add(output); end; procedure TOTFECrossCryptTestApp_F.FormCreate(Sender: TObject); begin edTestIfMtdVolFile.text := 'C:\crosscrypt.dat'; end; procedure TOTFECrossCryptTestApp_F.pbNumDrivesMountedClick(Sender: TObject); var output: string; begin output := 'Number of CrossCrypt volumes mounted: '; output := output + inttostr(OTFECrossCrypt1.CountDrivesMounted()); RichEdit1.lines.add(output); end; procedure TOTFECrossCryptTestApp_F.pbRefreshClick(Sender: TObject); begin RefreshDriveComboBox(); end; procedure TOTFECrossCryptTestApp_F.pbGetDrivesMountedClick(Sender: TObject); var output: string; begin output := 'CrossCrypt volumes mounted: '; output := output + OTFECrossCrypt1.DrivesMounted(); RichEdit1.lines.add(output); end; procedure TOTFECrossCryptTestApp_F.pbIsDriverInstalledClick(Sender: TObject); begin if OTFECrossCrypt1.IsDriverInstalled() then begin RichEdit1.lines.add('Driver installed'); end else begin RichEdit1.lines.add('Driver NOT installed'); end; end; procedure TOTFECrossCryptTestApp_F.pbDismountAllClick( Sender: TObject); var dismountFailedFor: string; begin dismountFailedFor := OTFECrossCrypt1.DismountAll(ckDismountDriveEmergency.checked); if dismountFailedFor='' then begin RichEdit1.lines.add('DismountAll OK'); end else begin RichEdit1.lines.add('DismountAll failed for drives: '+dismountFailedFor); end; end; procedure TOTFECrossCryptTestApp_F.pbDriveInfoClick(Sender: TObject); var output: string; volumeInfo: TOTFECrossCryptVolumeInfo; begin output := DriveComboBox1.drive + ': '; if OTFECrossCrypt1.GetVolumeInfo(DriveComboBox1.drive, volumeInfo) then begin output := output + 'Got drive info OK'; lblDriveMountedAs.caption := volumeInfo.DriveLetter+':'; lblVolumeFile.caption := volumeInfo.Filename; lblKernelDevice.caption := volumeInfo.KernelModeDeviceName; lblUserDevice.caption := volumeInfo.UserModeDeviceName; if volumeInfo.ReadOnly then begin lblReadOnly.caption := 'readonly'; end else begin lblReadOnly.caption := 'read/write'; end; end else begin output := output + 'DriveInfo FAILED'; end; RichEdit1.lines.add(output); RefreshDriveComboBox(); end; procedure TOTFECrossCryptTestApp_F.pbVersionStrClick(Sender: TObject); begin RichEdit1.lines.add('Driver version string: '+OTFECrossCrypt1.VersionStr()); end; procedure TOTFECrossCryptTestApp_F.Button1Click(Sender: TObject); begin if OTFECrossCrypt1.CreateVolume(edTestIfMtdVolFile.text, seCreateVolSize.Value)<>#0 then begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' CreateVolume OK'); end else begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' CreateVolume failed'); end; RefreshDriveComboBox(); end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- {$WARN UNIT_PLATFORM ON} // ----------------------------------------------------------------------------- END.
unit uSerasaHTML; interface uses Windows, SysUtils, Classes, Sockets, uSerasaTypes, uSerasaConsts, uSerasaFunctions, Dialogs; type TSerasaSearch = class(TComponent) private FSerasaHeader: TSerasaHeader; FClient : TTcpClient; sResponse, sResponseUncripted: String; FLastResult: String; FWaitingResponse: Boolean; FRemoteHost: String; FRemotePort: String; procedure TCPClientReceive(Sender: TObject; Buf: PAnsiChar; var DataLen: Integer); function TrataResposta(sResposta: String): String; procedure TCPClientConnect(Sender: TObject); procedure TCPClientError(Sender: TObject; SocketError: Integer); procedure DisconnectSocket; procedure ResetSearch; procedure SetRemoteHost(const Value: String); procedure SetRemotePort(const Value: String); public property SerasaHeader: TSerasaHeader read FSerasaHeader write fSerasaHeader; property LastResult: String read FLastResult; property RemoteHost: String read FRemoteHost write SetRemoteHost; property RemotePort: String read FRemotePort write SetRemotePort; constructor Create(AOwner: TComponent);override; Destructor Destroy;override; procedure DoSearch; end; implementation { TSerasaSearch } function TSerasaSearch.TrataResposta(sResposta: String) : String; var sTemp : String; CodResposta, UltimaResposta: Integer; stlHTML : TStringList; TheHeader : String; begin sTemp := sResposta; if Length(sTemp) < Length(SerasaHeader.ToHeader) then begin ShowMessage(StringReplace(sTemp, #3, '', [rfReplaceAll])); Result := ''; Exit; end; TheHeader := Copy(SerasaHeader.ToHeader, 25, 16); stlHTML := TStringList.Create; CodResposta := -1; UltimaResposta := -1; Delete(sTemp, 1, 300); stlHTML.Add('<html>'); stlHTML.Add(' <head>'); stlHTML.Add(' </head>'); stlHTML.Add(' <body>'); while Copy(sTemp, 1, 2) <> COD_FINALIZACAO do begin If CodResposta <> 90 then begin CodResposta := StrToInt(Copy(sTemp, 1, 2)); end; if UltimaResposta <> CodResposta then begin if UltimaResposta <> -1 then stlHTML.Add(' </table>'); stlHTML.Add(' <BR>'); end; case CodResposta of 00: begin stlHTML.Add(Reg00ToHTML(Copy(sTemp, 1, TAM_REG00), SerasaHeader.TipoDocumentoPesquisa, UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG00); end; 02: begin stlHTML.Add(Reg02ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 04: begin stlHTML.Add(Reg04ToHTML(Copy(sTemp, 1, TAM_REG04), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG04); end; 05: begin stlHTML.Add(Reg05ToHTML(Copy(sTemp, 1, TAM_REG05), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG05); end; 06: begin stlHTML.Add(Reg06ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 08: begin stlHTML.Add(Reg08ToHTML(Copy(sTemp, 1, TAM_REG08), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG08); end; 10: begin stlHTML.Add(Reg10ToHTML(Copy(sTemp, 1, TAM_REG10), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG10); end; 12: begin stlHTML.Add(Reg12ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 14: begin stlHTML.Add(Reg14ToHTML(Copy(sTemp, 1, TAM_REG14), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG14); end; 16: begin stlHTML.Add(Reg16ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 18: begin stlHTML.Add(Reg18ToHTML(Copy(sTemp, 1, TAM_REG18), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG18); end; 20: begin stlHTML.Add(Reg20ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 22: begin stlHTML.Add(Reg22ToHTML(Copy(sTemp, 1, TAM_REG22), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG22); end; 24: begin stlHTML.Add(Reg24ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 26: begin stlHTML.Add(Reg26ToHTML(Copy(sTemp, 1, TAM_REG26), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG26); end; 28: begin stlHTML.Add(Reg28ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 30: begin stlHTML.Add(Reg30ToHTML(Copy(sTemp, 1, TAM_REG30), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG30); end; 32: begin stlHTML.Add(Reg32ToHTML(Copy(sTemp, 1, TAM_REG32), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG32); end; 34: begin stlHTML.Add(Reg34ToHTML(Copy(sTemp, 1, TAM_REG34), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG34); end; 36: begin stlHTML.Add(Reg36ToHTML(Copy(sTemp, 1, TAM_REG36), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG36); end; 38: begin stlHTML.Add(Reg38ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 40: begin stlHTML.Add(Reg40ToHTML(Copy(sTemp, 1, TAM_REG40), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG40); end; 42: begin stlHTML.Add(Reg42ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 44: begin stlHTML.Add(Reg44ToHTML(Copy(sTemp, 1, TAM_REG44), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG44); end; 46: begin stlHTML.Add(Reg46ToHTML(Copy(sTemp, 1, TAM_REG46), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG46); end; 48: begin stlHTML.Add(Reg48ToHTML(Copy(sTemp, 1, TAM_REG48), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG48); end; 50: begin stlHTML.Add(Reg50ToHTML(Copy(sTemp, 1, TAM_REG_NADA_CONSTA))); Delete(sTemp, 1, TAM_REG_NADA_CONSTA); end; 52: begin stlHTML.Add(Reg52ToHTML(Copy(sTemp, 1, TAM_REG52), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG52); end; 54: begin stlHTML.Add(Reg54ToHTML(Copy(sTemp, 1, TAM_REG54), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG54); end; 90: begin stlHTML.Add(Reg90ToHTML(Copy(sTemp, 1, TAM_REG90), UltimaResposta <> CodResposta)); Delete(sTemp, 1, TAM_REG90); end; else raise Exception.CreateFmt(MSG_ERRO_RETORNO_INVALIDO, [Copy(sTemp, 1, 2)]); end; UltimaResposta := CodResposta; if TheHeader = Copy(sTemp, 1, 16) then Delete(sTemp, 1, 300); end; stlHTML.Add(' </table>'); stlHTML.Add(' </body>'); stlHTML.Add('</html>'); Result := stlHTML.GetText; end; procedure TSerasaSearch.TCPClientReceive(Sender: TObject; Buf: PAnsiChar; var DataLen: Integer); var I : Integer; begin if not FWaitingResponse then Exit; try for I := 0 to DataLen-1{Length(Buf)} do begin if Buf[I] = #3 then begin FClient.Disconnect; sResponseUncripted := DescriptografaSERASA(sResponse); FLastResult := TrataResposta(sResponseUncripted); FWaitingResponse := False; Break; end; sResponse := sResponse + Buf[I]; end; except FWaitingResponse := False; end; end; procedure TSerasaSearch.TCPClientConnect(Sender: TObject); var Buf: array[0..999] of Char; Header: String; begin Header := SerasaHeader.ToHeader; Header := CriptografaSERASA(Header) + #3; FClient.SendBuf(pchar(Header)^, length(Header), 0); FillChar(Buf, Length(Buf), #0); while FClient.ReceiveBuf(Buf, Length(Buf)) >= Length(Buf) do begin FillChar(Buf, Length(Buf), #0); Sleep(0); end; end; procedure TSerasaSearch.TCPClientError(Sender: TObject; SocketError: Integer); begin ShowMessage('Error : ' + IntToStr(SocketError)); end; constructor TSerasaSearch.Create(AOwner: TComponent); begin inherited Create(AOWner); FClient := TTcpClient.Create(Self); FClient.RemoteHost := FRemoteHost; FClient.RemotePort := FRemotePort; FClient.OnConnect := TCPClientConnect; FClient.OnReceive := TCPClientReceive; FClient.OnError := TCPClientError; FSerasaHeader := TSerasaHeader.Create; with FSerasaHeader do begin Transacao := HEADER_COD_TRANS; TransacaoContratada := HEADER_COD_TRANS_CONTRATADA; CodigoRelease := HEADER_COD_RELEASE; end; ResetSearch; end; destructor TSerasaSearch.Destroy; begin DisconnectSocket; FClient.Free; FSerasaHeader.Free; inherited; end; procedure TSerasaSearch.DisconnectSocket; begin if FClient.Connected then FClient.Disconnect; end; procedure TSerasaSearch.ResetSearch; begin FLastResult := ''; sResponse := ''; sResponseUncripted := ''; DisconnectSocket; FWaitingResponse := False; end; procedure TSerasaSearch.DoSearch; begin ResetSearch; FWaitingResponse := True; FClient.Connect; end; procedure TSerasaSearch.SetRemoteHost(const Value: String); begin FRemoteHost := Value; FClient.RemoteHost := FRemoteHost; end; procedure TSerasaSearch.SetRemotePort(const Value: String); begin FRemotePort := Value; FClient.RemotePort := FRemotePort; end; end.
unit FMain; interface uses Classes, Controls, Forms, NLDSnakeImage, StdCtrls; type TMainForm = class(TForm) StopButton: TButton; Thanks: TStaticText; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure StopButtonClick(Sender: TObject); private FSnakeImage: TNLDSnakeImage; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin FSnakeImage := TNLDSnakeImage.Create(Self); FSnakeImage.SetBounds((ClientWidth - 800) div 2, (ClientHeight - 600) div 2, 800, 600); FSnakeImage.Anchors := []; FSnakeImage.HeadColor := $00AFD6E5; FSnakeImage.TailColor := $00076DB5; FSnakeImage.GraphicFileName := 'Guitar.jpg'; FSnakeImage.Parent := Self; end; procedure TMainForm.FormShow(Sender: TObject); begin FSnakeImage.Start; end; procedure TMainForm.StopButtonClick(Sender: TObject); begin FSnakeImage.Stop; StopButton.Enabled := False; FSnakeImage.SendToBack; end; end.
unit uSettings; interface uses Windows, Classes, SysUtils, uMemory, uConstants, uConfiguration, UnitINI; type TExifSettings = class; TAppSettings = class(TObject) private FRegistryCache: TDBRegistryCache; FExifSettings: TExifSettings; function GetDataBase: string; public constructor Create; destructor Destroy; override; procedure ClearCache; function ReadProperty(Key, Name: string): string; procedure DeleteKey(Key: string); procedure WriteProperty(Key, Name, Value: string); procedure WriteBool(Key, Name: string; Value: Boolean); procedure WriteBoolW(Key, Name: string; Value: Boolean); procedure WriteInteger(Key, Name: string; Value: Integer); procedure WriteStringW(Key, Name, Value: string); procedure WriteString(Key, Name: string; Value: string); procedure WriteDateTime(Key, Name: string; Value: TDateTime); function ReadKeys(Key: string): TStrings; function ReadValues(Key: string): TStrings; function ReadBool(Key, Name: string; Default: Boolean): Boolean; function ReadRealBool(Key, Name: string; Default: Boolean): Boolean; function ReadBoolW(Key, Name: string; Default: Boolean): Boolean; function ReadInteger(Key, Name: string; Default: Integer): Integer; function ReadString(Key, Name: string; Default: string = ''): string; function ReadStringW(Key, Name: string; Default: string = ''): string; function ReadDateTime(Key, Name: string; Default: TDateTime): TDateTime; procedure IncrementInteger(Key, Name: string); function GetSection(Key: string; ReadOnly: Boolean): TBDRegistry; procedure DeleteValues(Key: string); property DataBase: string read GetDataBase; property Exif: TExifSettings read FExifSettings; end; TSettingsNode = class(TObject) private FInfoAvailable: Boolean; procedure Init(Force: Boolean = False); protected procedure ReadSettings; virtual; abstract; public constructor Create; end; TExifSettings = class(TSettingsNode) private FReadInfoFromExif: Boolean; FSaveInfoToExif: Boolean; FUpdateExifInfoInBackground: Boolean; function GetReadInfoFromExif: Boolean; procedure SetReadInfoFromExif(const Value: Boolean); function GetSaveInfoToExif: Boolean; procedure SetSaveInfoToExif(const Value: Boolean); function GetUpdateExifInfoInBackground: Boolean; procedure SetUpdateExifInfoInBackground(const Value: Boolean); protected procedure ReadSettings; override; public property ReadInfoFromExif: Boolean read GetReadInfoFromExif write SetReadInfoFromExif; property SaveInfoToExif: Boolean read GetSaveInfoToExif write SetSaveInfoToExif; property UpdateExifInfoInBackground: Boolean read GetUpdateExifInfoInBackground write SetUpdateExifInfoInBackground; end; function AppSettings: TAppSettings; function GetAppDataDirectoryFromSettings: string; implementation var FSettings: TAppSettings = nil; function AppSettings: TAppSettings; begin if FSettings = nil then FSettings := TAppSettings.Create; Result := FSettings; end; function GetAppDataDirectoryFromSettings: string; begin Result := AppSettings.ReadString('Settings', 'AppData'); if Result = '' then begin Result :=GetAppDataDirectory; AppSettings.WriteString('Settings', 'AppData', Result); end; end; function TAppSettings.Readbool(Key, Name: string; Default: Boolean): Boolean; var Reg: TBDRegistry; Value: string; begin Result := Default; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Value := AnsiLowerCase(Reg.ReadString(Name)); if Value = 'true' then Result := True; if Value = 'false' then Result := False; end; function TAppSettings.ReadRealBool(Key, Name: string; Default: Boolean): Boolean; var Reg : TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Result := Reg.ReadBool(Name); end; function TAppSettings.ReadboolW(Key, Name: string; Default: Boolean): Boolean; var Reg: TBDRegistry; Value : string; begin Result := Default; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, True); Value := AnsiLowerCase(Reg.ReadString(Name)); if Value = 'true' then Result := True; if Value = 'false' then Result := False; end; function TAppSettings.ReadInteger(Key, Name: string; Default: Integer): Integer; var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Result := StrToIntDef(Reg.ReadString(Name), Default); end; function TAppSettings.ReadDateTime(Key, Name : string; Default: TDateTime): TDateTime; var Reg: TBDRegistry; begin Result := Default; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); if Reg.ValueExists(Name) then Result:=Reg.ReadDateTime(Name); end; function TAppSettings.ReadProperty(Key, Name: string): string; var Reg: TBDRegistry; begin Result := ''; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, True); Result := Reg.ReadString(Name); end; function TAppSettings.ReadKeys(Key: string): TStrings; var Reg: TBDRegistry; begin Result := TStringList.Create; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Reg.GetKeyNames(Result); end; function TAppSettings.ReadValues(Key: string): TStrings; var Reg: TBDRegistry; begin Result := TStringList.Create; Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Reg.GetValueNames(Result); end; procedure TAppSettings.DeleteValues(Key: string); var Reg: TBDRegistry; I: Integer; Result: TStrings; begin Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try Result := TStringList.Create; try Reg.OpenKey(GetRegRootKey + Key, True); Reg.GetValueNames(Result); for I := 0 to Result.Count - 1 do Reg.DeleteValue(Result[I]); finally F(Result); end; finally F(Reg); end; end; procedure TAppSettings.ClearCache; begin FRegistryCache.Clear; FExifSettings.Init(True); end; constructor TAppSettings.Create; begin FRegistryCache := TDBRegistryCache.Create; FExifSettings := TExifSettings.Create; end; destructor TAppSettings.Destroy; begin F(FRegistryCache); F(FExifSettings); inherited; end; procedure TAppSettings.DeleteKey(Key: string); var Reg: TBDRegistry; begin Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try Reg.DeleteKey(GetRegRootKey + Key); finally; F(Reg); end; end; function TAppSettings.ReadString(Key, Name: string; Default: string = ''): string; var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, True); Result := Reg.ReadString(name); if Result = '' then Result := Default; end; function TAppSettings.ReadStringW(Key, Name: string; Default: string = ''): string; var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, True); Result := Reg.ReadString(Name); if Result = '' then Result := Default; end; procedure TAppSettings.WriteBool(Key, name: string; Value: Boolean); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, False); if Value then Reg.WriteString(name, 'True') else Reg.WriteString(name, 'False'); end; procedure TAppSettings.WriteBoolW(Key, Name: string; Value: Boolean); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, False); if Value then Reg.WriteString(Name, 'True') else Reg.WriteString(Name, 'False'); end; procedure TAppSettings.WriteInteger(Key, Name: string; Value: Integer); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, False); Reg.WriteString(Name, IntToStr(Value)); end; procedure TAppSettings.WriteProperty(Key, Name, Value: string); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, False); Reg.WriteString(Name, Value); end; procedure TAppSettings.WriteString(Key, Name, Value: string); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, False); Reg.WriteString(Name, Value); end; procedure TAppSettings.WriteStringW(Key, Name, value: string); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot + Key, False); Reg.WriteString(Name, Value); end; procedure TAppSettings.WriteDateTime(Key, Name : String; Value: TDateTime); var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, False); Reg.WriteDateTime(Name, Value); end; function TAppSettings.GetDataBase: string; var Reg: TBDRegistry; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot, True); Result := Reg.ReadString('DBDefaultName'); end; function TAppSettings.GetSection(Key: string; ReadOnly: Boolean): TBDRegistry; begin Result := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, RegRoot, ReadOnly); end; procedure TAppSettings.IncrementInteger(Key, Name: string); var Reg: TBDRegistry; SValue: string; Value: Integer; begin Reg := FRegistryCache.GetSection(REGISTRY_CURRENT_USER, GetRegRootKey + Key, False); SValue := Reg.ReadString(Name); Value := StrToIntDef(SValue, 0); Inc(Value); Reg.WriteString(Name, IntToStr(Value)); end; { TExifSettings } function TExifSettings.GetReadInfoFromExif: Boolean; begin Init; Result := FReadInfoFromExif; end; procedure TExifSettings.SetReadInfoFromExif(const Value: Boolean); begin FReadInfoFromExif := Value; AppSettings.WriteBool('EXIF', 'ReadInfoFromExif', Value); end; function TExifSettings.GetSaveInfoToExif: Boolean; begin Init; Result := FSaveInfoToExif; end; procedure TExifSettings.SetSaveInfoToExif(const Value: Boolean); begin FSaveInfoToExif := Value; AppSettings.WriteBool('EXIF', 'SaveInfoToExif', Value); end; function TExifSettings.GetUpdateExifInfoInBackground: Boolean; begin Init; Result := FUpdateExifInfoInBackground; end; procedure TExifSettings.SetUpdateExifInfoInBackground(const Value: Boolean); begin FUpdateExifInfoInBackground := Value; AppSettings.WriteBool('EXIF', 'UpdateExifInfoInBackground', Value); end; procedure TExifSettings.ReadSettings; begin FReadInfoFromExif := AppSettings.ReadBool('EXIF', 'ReadInfoFromExif', True); FSaveInfoToExif := AppSettings.ReadBool('EXIF', 'SaveInfoToExif', True); FUpdateExifInfoInBackground := AppSettings.ReadBool('EXIF', 'UpdateExifInfoInBackground', True); end; { TSettingsNode } constructor TSettingsNode.Create; begin FInfoAvailable := False; end; procedure TSettingsNode.Init(Force: Boolean = False); begin if not FInfoAvailable or Force then ReadSettings; end; initialization finalization F(FSettings); end.
namespace org.me.tabbedapp; //Sample app by Brian Long (http://blong.com) { This example shows how to build a simple tabbed application This main activity is a TabActivity, and each tab set up on the TabHost has its own activity The TabWidget is upodated when you add new tabs onto the TabHost } interface uses java.util, android.os, android.app, android.util, android.view, android.content, android.widget; type MainActivity = public class(TabActivity) public method onCreate(savedInstanceState: Bundle); override; end; implementation method MainActivity.onCreate(savedInstanceState: Bundle); begin inherited; // Set our view from the "main" layout resource ContentView := R.layout.main; var res := Resources; // Resource object to get Drawables var tabHost := TabHost; // The activity TabHost var spec: TabHost.TabSpec; // Resusable TabSpec for each tab var tabIntent: Intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) tabIntent := new Intent().setClass(self, typeOf(TabOneActivity)); // Initialize a TabSpec for each tab and add it to the TabHost spec := tabHost.newTabSpec("one").setIndicator(String[R.string.tab_one_title], res.Drawable[R.drawable.ic_tab_one]) .setContent(tabIntent); tabHost.addTab(spec); // Do the same for the other tabs tabIntent := new Intent().setClass(self, typeOf(TabTwoActivity)); spec := tabHost.newTabSpec("two").setIndicator(String[R.string.tab_two_title], res.Drawable[R.drawable.ic_tab_two]) .setContent(tabIntent); tabHost.addTab(spec); tabIntent := new Intent().setClass(self, typeOf(TabThreeActivity)); spec := tabHost.newTabSpec("three").setIndicator(String[R.string.tab_three_title], res.Drawable[R.drawable.ic_tab_three]) .setContent(tabIntent); tabHost.addTab(spec); tabHost.CurrentTab := 0; end; end.
unit ThCommandManager; interface uses ThTypes, ThClasses, System.Generics.Collections; type TThCommandManager = class(TThInterfacedObject, IThObserver) type TThCommandStack = TStack<IThCommand>; private FSubject: IThSubject; FUndoStack: TThCommandStack; FRedoStack: TThCommandStack; function GetRedoCount: Integer; function GetUndoCount: Integer; procedure ClearRedoCommand; public constructor Create; destructor Destroy; override; procedure Notifycation(ACommand: IThCommand); procedure SetSubject(ASubject: IThSubject); procedure UndoAction; procedure RedoAction; property UndoCount: Integer read GetUndoCount; property RedoCount: Integer read GetRedoCount; end; implementation uses ThItemCommand, ThSystemCommand; { TThCommandHistory } constructor TThCommandManager.Create; begin FUndoStack := TThCommandStack.Create; FRedoStack := TThCommandStack.Create; end; destructor TThCommandManager.Destroy; begin FSubject.UnregistObserver(Self); ClearRedoCommand; FUndoStack.Clear; FRedoStack.Clear; FUndoStack.Free; FRedoStack.Free; inherited; end; function TThCommandManager.GetRedoCount: Integer; begin Result := FRedoStack.Count; end; function TThCommandManager.GetUndoCount: Integer; begin Result := FUndoStack.Count; end; procedure TThCommandManager.SetSubject(ASubject: IThSubject); begin FSubject := ASubject; FSubject.RegistObserver(Self); end; procedure TThCommandManager.Notifycation(ACommand: IThCommand); begin if ACommand is TThItemCommand then begin FUndoStack.Push(ACommand); // Undo된 TThCommandItemAdd 커맨드의 Items는 신규 커맨드 요청 시 해제(Free) ClearRedoCommand; end; end; procedure TThCommandManager.UndoAction; var Command: IThCommand; begin if FUndoStack.Count = 0 then Exit; Command := FUndoStack.Pop; if not Assigned(Command) then Exit; Command.Rollback; FRedoStack.Push(Command); end; procedure TThCommandManager.RedoAction; var Command: IThCommand; begin if FRedoStack.Count = 0 then Exit; Command := FRedoStack.Pop; if not Assigned(Command) then Exit; Command.Execute; FUndoStack.Push(Command); end; procedure TThCommandManager.ClearRedoCommand; var I: Integer; Command: IThCommand; begin for I := 0 to FRedoStack.Count - 1 do begin Command := FRedoStack.Pop; if Command is TThCommandItemAdd then FSubject.Subject(Self, TThCommandSystemItemDestroy.Create(TThCommandItemAdd(Command).Items)); end; // Undo된(FRedoStack에 위치한) 커맨드들은 새로운 커맨드 요청 시 Clear FRedoStack.Clear; end; end.
unit UTxtToPath; interface uses Windows, SysUtils, Classes,Graphics,GR32,GR32_Paths,math; type TWrapWordKind=(wwNone,wwSplit,wwWrap); TTxtAlignement=(tacLeft,tacCenter,tacRight,tacJustify); TArrayOfInteger=array of Integer; TArrayOfWord=array of Word; TTxtGlyphs = class protected FAdvs:TArrayOfInteger; FTextMetric:TTextMetricW; FAttrs:TArrayOfWord; FGlyphs:TArrayOfWord; FCount:integer; FRowCount:integer; FCurrOffsetX:Double;// precision for text justification FDc:HDC; function GetTextSize: TSize; function TrackLine(var P: PWidechar; var AOut: widestring): boolean; procedure SetDC(const Value: HDC); function WrapTxt(Start:integer;var lpnFit: Integer): TWrapWordKind; procedure PackMerged(const AStr:widestring); procedure PrepareTxt(); procedure AddGlyph(Index, AlignHoriz:integer); function JustRow(First, Last: integer):boolean; procedure AlignRow(First, Last: integer); procedure BuildGlyph(ADC:HDC;Glyph:integer;const X,Y:Double);virtual; public Measuring:boolean; TxtAlignement:TTxtAlignement; MaxExtent: integer; procedure ProcessLines(const AStr: widestring); procedure ProcessLine(const AStr: widestring); property DC:HDC read FDC write SetDC; property TxtSize:TSize read GetTextSize; end; TArrayOfGlyphs=array of TArrayOfArrayOfFloatPoint; TGRTxtGlyphs=class(TTxtGlyphs) protected Mat:TMat2; FRet:TArrayOfGlyphs; FPath:TFlattenedPath; FX,FY:TFloat; procedure BuildGlyph(ADC:HDC;Glyph:integer;const X,Y:Double);override; public constructor Create; destructor Destroy();override; end; function ScriptToPath(const AStr:widestring;AFont:TFont;const ADest:TFloatRect; ATxtAlignement:TTxtAlignement):TArrayOfGlyphs; function ScriptToMeasure(const AStr: widestring; AFont: TFont; const ADest:TFloatRect; ATxtAlignement: TTxtAlignement): TFLoatRect; implementation function GetCharacterPlacementW(DC: HDC; p2: PWideChar; p3, p4: Integer; var p5: TGCPResultsW; p6: DWORD): DWORD; stdcall;external 'gdi32.dll'; type TJustItem=record mStart:integer; mEnd:integer; end; TArrayOfJustItem=array of TJustItem; procedure TTxtGlyphs.AddGlyph(Index,AlignHoriz:integer); var Y:integer; begin Y:=FTextMetric.tmHeight*(FRowCount-1); BuildGlyph(Dc,FGlyphs[Index],FCurrOffsetX+AlignHoriz,Y); FCurrOffsetX:=FCurrOffsetX+FAdvs[Index]; end; procedure TTxtGlyphs.PackMerged(const AStr:widestring); var Ret:TGCPResultsW; I,L,Prv,Pz:integer; Chars:array of WideChar; Orders:TArrayOfInteger; begin L:=Length(AStr); Setlength(Orders,L); Setlength(FGlyphs,L); Setlength(FAdvs,L); fillchar(Ret,sizeof(Ret),0); Ret.lStructSize:=sizeof(Ret); Ret.lpGlyphs:=@FGlyphs[0]; Ret.lpDx:=@FAdvs[0]; Ret.nGlyphs:=L; Ret.lpOrder:=@Orders[0]; GetCharacterPlacementW(Dc,@AStr[1],L,0,Ret,GCP_REORDER); Setlength(Chars,L); Prv:=-1; FCount:=0; for I := 0 to L - 1 do begin Pz:=Orders[I]; if Prv=Pz then continue; Chars[Pz]:=AStr[I+1] ; Prv:=Pz; Inc(FCount); end; Setlength(FAdvs,FCount); Setlength(FGlyphs,FCount); Setlength(FAttrs,FCount); GetStringTypeExW(0,CT_CTYPE2,@Chars[0],FCount,FAttrs[0]); end; function TTxtGlyphs.WrapTxt(Start:integer;var lpnFit:Integer):TWrapWordKind; const BREAKS=[C2_EUROPESEPARATOR,C2_WHITESPACE,C2_OTHERNEUTRAL]; var I,Adv,ValidBreak:integer; LastAttr,attr:byte; begin ValidBreak:=-1; lpnFit:=Start; Adv:= FAdvs[Start]; LastAttr:=FAttrs[Start]; for I := Start+1 to FCount-1 do begin Adv :=Adv+FAdvs[I]; if Adv >= MaxExtent then begin if (ValidBreak<>-1) then begin lpnFit:=ValidBreak; Result:=wwWrap; end else Result:=wwSplit; Exit; end; attr:=FAttrs[I]; if (attr <> LastAttr)or(attr in BREAKS)then begin ValidBreak:=I; LastAttr:=attr; if attr<>C2_WHITESPACE then dec(ValidBreak); continue; end; lpnFit:= I; end; Result:=wwNone; lpnFit:= FCount-1; end; function TTxtGlyphs.JustRow(First,Last: integer):boolean; var Len,Pos1,D:integer; C,OldChar,I:integer; Delta,TxtWidth:integer; ErrRem:Double; Items:TArrayOfJustItem; procedure Add(APos,AEnd:integer); begin Items[Len].mStart:=APos; Items[Len].mEnd:=AEnd; Inc(Len); end; begin Result:=False; Len:=Last-First; if Len=0 then Exit; Setlength(Items,Len); Pos1:=First; TxtWidth:=0; Len:=0; OldChar:=1; while (First<Last)and( FAttrs[First] = C2_WHITESPACE) do begin //add space leads only for first Row TxtWidth :=TxtWidth+FAdvs[First]; Inc(First); end; for I := First to Last do begin C:=Ord(FAttrs[I]<>C2_WHITESPACE); if C = 1 then //not a space TxtWidth :=TxtWidth+FAdvs[I]; if (C <> OldChar) then begin if C=0 then Add(Pos1,I-1) else Pos1:=I; end; OldChar :=C; end; if OldChar=1 then Add(Pos1,Last); // SetLength(Items,Len); Len:=Len-1; if Len< 1 then Exit; Result:=True; Delta:=MaxExtent-TxtWidth; ErrRem:= Delta / Len; for I:=0 to Len do with Items[I] do begin for D := mStart to mEnd do AddGlyph(D,0); FCurrOffsetX:=FCurrOffsetX+ErrRem; end; end; procedure TTxtGlyphs.AlignRow(First,Last: integer); var Width,I:integer; begin Width:=0; if TxtAlignement in [tacRight,tacCenter] then begin for I := First to Last do Width :=Width+FAdvs[I]; case TxtAlignement of tacRight:Width:=MaxExtent-Width; tacCenter:Width:=(MaxExtent-Width)div 2; end; end; for I := First to Last do AddGlyph(I,Width); end; procedure TTxtGlyphs.PrepareTxt(); var Curr,Nxt,Last:integer; W:TWrapWordKind; Justified:boolean; begin Curr:=0; repeat inc(FRowCount); if Curr >= FCount then break; W:=WrapTxt(Curr,Nxt); Last:=Nxt; while (Curr < Last)and (FAttrs[Last] = C2_WHITESPACE) do Dec(Last); // FOffsetX:=FTextMetric.tmAveCharWidth div 2; FCurrOffsetX:=0; if not Measuring then begin Justified:=False; if (W=wwWrap)and(TxtAlignement=tacJustify) then Justified:=JustRow(Curr,Last); if not Justified then AlignRow(Curr,Last); end; if W=wwNone then break; Curr:=Nxt+1; while(FAttrs[Curr] = C2_WHITESPACE) do Inc(Curr); until False; end; function TTxtGlyphs.TrackLine(var P: PWidechar;var AOut:widestring):boolean; var Start: PWidechar; W:integer; begin Start := P; if P <> nil then begin repeat W:=Ord(P^); if(W=10)or(W=13)or(W=0)then break; Inc(P); until False; SetString(AOut, Start, P - Start); if Ord(P^) = 13 then Inc(P); if Ord(P^) = 10 then Inc(P); end; Result:=Start <> P; end; procedure TTxtGlyphs.ProcessLine(const AStr: widestring); var P:PWideChar; S,Txt:Widestring; begin FRowCount:=0; Txt:=''; P:=PWideChar(AStr); while TrackLine(P,S) do Txt:=Txt+' '+S; if Txt='' then Exit; PackMerged(Txt); PrepareTxt(); end; procedure TTxtGlyphs.ProcessLines(const AStr: widestring); var P:PWideChar; S:Widestring; begin FRowCount:=0; P:=PWideChar(AStr); while TrackLine(P,S) do begin PackMerged(S); PrepareTxt(); end; end; procedure TTxtGlyphs.SetDC(const Value: HDC); begin FDC := Value; if FDC=0 then Exit; GetTextMetricsW(FDC,FTextMetric); end; function TTxtGlyphs.GetTextSize: TSize; begin if FRowCount=0 then begin Result.cx:=0; Result.cy:=0; end else begin Result.cy:=FTextMetric.tmHeight*FRowCount; if FRowCount=1 then Result.cx:=Round(FCurrOffsetX+0.49)//Ceil else Result.cx:=MaxExtent; end; end; procedure TTxtGlyphs.BuildGlyph(ADC: HDC;Glyph:integer;const X,Y:Double); begin windows.ExtTextOut(ADC,Round(X),Round(Y),ETO_GLYPH_INDEX,nil,@Glyph,1,nil); end; type TRefCanvas=class(TCanvas); { TGRTxtGlyphs } constructor TGRTxtGlyphs.Create; begin FPath:=TFlattenedPath.Create; Fillchar(Mat,sizeof(Mat),0); Mat.eM11.value:=1; Mat.eM22.value:=-1; end; destructor TGRTxtGlyphs.Destroy; begin FPath.Free; inherited; end; var gg:integer; procedure TGRTxtGlyphs.BuildGlyph(ADC: HDC; Glyph: integer; const X, Y: Double); const GGO_BEZIER=3; var CharPos:TFloatPoint; function toFloatPoint(const Pt: TPointFX): TFloatPoint; begin Result.X := CharPos.X+ Integer(Pt.X)* FixedToFloat; Result.Y := CharPos.Y+ Integer(Pt.Y)* FixedToFloat; end; function ConvToPts(const A:TTPolyCurve):TArrayOfFloatPoint; var I:integer; begin Setlength(Result,A.cpfx); for I:=0 to A.cpfx-1 do Result[I]:=toFloatPoint(A.apfx[I]); end; var GlyphMetrics:TGlyphMetrics; P:Pointer; Len:integer; Sz,idx,i,t:integer; Px:PTTPolygonHeader; pPolys:PTTPolyCurve; Pts:TArrayOfFloatPoint; begin CharPos:=FloatPoint(FX+X,FY+Y ); Len:= GetGlyphOutlineW(adc,Glyph,GGO_BEZIER or GGO_GLYPH_INDEX ,GlyphMetrics,0,nil,Mat); if Len=-1 then Exit; Getmem(P,Len); GetGlyphOutlineW(adc,Glyph,GGO_BEZIER or GGO_GLYPH_INDEX ,GlyphMetrics,Len,P,Mat); Px:=P; pPolys:=P; FPath.Clear; FPath.BeginUpdate; repeat t:= px.cb; with toFloatPoint(Px.pfxStart) do FPath.MoveTo(x,y); inc(PByte(pPolys),sizeof(TTTPolygonHeader)); repeat Pts :=ConvToPts(pPolys^); if pPolys.wType= TT_PRIM_LINE then begin //lines FPath.PolyLine(Pts) end else begin for i:= 0 to pPolys.cpfx div 3 -1 do begin idx:=I*3; FPath.Curveto(Pts[idx],Pts[idx+1],Pts[idx+2]) ; end; end; Sz:=pPolys.cpfx*Sizeof(TPointFX)+4; inc(PByte(pPolys),Sz); t:=t-Sz; until t<= Sizeof(TTTPolygonHeader); with toFloatPoint(Px.pfxStart) do FPath.LineTo(x,y); Px:= Pointer(pPolys); FPath.EndPath(True); until Integer(Px) >= integer(P)+Len; FPath.EndUpdate; Freemem(P); t:=Length(FRet); Setlength(FRet,t+1); FRet[t]:=FPath.Path; inc(gg); end; procedure InternalScriptToPath(const AStr: widestring; AFont: TFont; const ADest:TFloatRect; ATxtAlignement: TTxtAlignement;ACalc:boolean; var AOut:TArrayOfGlyphs;var ASize:TSize); var Canvas:TCanvas; begin with TGRTxtGlyphs.Create do try MaxExtent:= Round(ADest.Right-ADest.Left); FX:=ADest.Left; FY:=ADest.Top; TxtAlignement:=ATxtAlignement; Measuring:=ACalc; Canvas:=TCanvas.Create; Canvas.Handle:=GetDc(0); Canvas.Font:=AFont; DC:=Canvas.Handle; TRefCanvas(Canvas).RequiredState([csHandleValid, csFontValid]); ProcessLines(AStr); AOut:=FRet; ASize:=TxtSize; Canvas.Free; ReleaseDC(0, DC); finally Free; end; end; function ScriptToPath(const AStr: widestring; AFont: TFont; const ADest:TFloatRect; ATxtAlignement: TTxtAlignement): TArrayOfGlyphs; var Sz:TSize; begin InternalScriptToPath(AStr,AFont,ADest,ATxtAlignement,False,Result,Sz); end; function ScriptToMeasure(const AStr: widestring; AFont: TFont; const ADest:TFloatRect; ATxtAlignement: TTxtAlignement): TFLoatRect; var Sz:TSize; Ret:TArrayOfGlyphs; begin InternalScriptToPath(AStr,AFont,ADest,ATxtAlignement,False,Ret,Sz); Result.TopLeft:=ADest.TopLeft; Result.BottomRight:=FloatPoint(ADest.Left+Sz.cx,ADest.Top+Sz.cy); end; end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { } { Copyright (c) 1997, 2001 Borland Software Corporation } { } { *************************************************************************** } unit DBConsts; interface resourcestring SInvalidFieldSize = 'Tamanho de campo inválido'; SInvalidFieldKind = 'FieldKind inválido'; SInvalidFieldRegistration = 'Registro de campo inválido'; SUnknownFieldType = 'Campo ''%s'' de tipo desconhecido'; SFieldNameMissing = 'Nome do campo ausente'; SDuplicateFieldName = 'Nome de campo duplicado ''%s'''; SFieldNotFound = '%s: Campo ''%s'' não encontrado'; SFieldAccessError = 'Não é possível acessar o campo ''%s'' do tipo %s'; SFieldValueError = 'Valor inválido para o campo ''%s'''; SFieldRangeError = '%g Não é um valor válido para o campo ''%s''. A faixa permitida é de %g até %g'; SBcdFieldRangeError = '%s não é um valor válido para o campo ''%s''. A faixa permitida is %s para %s'; SInvalidIntegerValue = '''%s'' não é um inteiro válido para o campo ''%s'''; SInvalidBoolValue = '''%s'' não é uma valor boleano válido para o campo ''%s'''; SInvalidFloatValue = '''%s'' não é um valor de ponto flutuante válido para o campo ''%s'''; SFieldTypeMismatch = 'Campo ''%s'' não é do tipo esperado'; SFieldSizeMismatch = 'Tamanho sem combinação para campo '' %s '', esperando: %d atual: %d'; SInvalidVarByteArray = 'Tipo ou tamanho da variante inválido para o campo ''%s'''; SFieldOutOfRange = 'Valor do campo ''%s'' está fora de faixa'; // SBCDOverflow = '(Estouro da capacidade)'; SFieldRequired = 'Campo ''%s'' deve ter um valor'; SDataSetMissing = 'Campo ''%s'' não tem arquivo'; SInvalidCalcType = 'Campo ''%s'' não pode ser um campo calculado ou lookup'; SFieldReadOnly = 'Campo ''%s'' não pode ser modificado'; SFieldIndexError = 'Índice de campo fora de faixa'; SNoFieldIndexes = 'Índice corrente não ativo'; SNotIndexField = 'Campo ''%s'' não está indexado e não pode ser modificado'; SIndexFieldMissing = 'Não é possível acessar o índice do campo ''%s'''; SDuplicateIndexName = 'Nome de índice duplicado ''%s'''; SNoIndexForFields = '''%s'' não tem índice para os campos ''%s'''; SIndexNotFound = 'Índice ''%s'' não encontrado'; SDuplicateName = 'Nome duplicado ''%s'' em %s'; SCircularDataLink = 'Ligações de dados circulares não são permitidas'; SLookupInfoError = 'Informação Lookup para o campo ''%s'' está incompleta'; SNewLookupFieldCaption = 'Novo Campo Lookup'; SDataSourceChange = 'DataSource não pode ser atualizado'; SNoNestedMasterSource = 'Arquivos aninhados não podem ter uma tabela mestra'; SDataSetOpen = 'Não é possível realizar esta operação em um arquivo aberto'; SNotEditing = 'Arquivo não está em modo de edição ou inserção'; SDataSetClosed = 'Não é possível realizar esta operação em um arquivo fechado'; SDataSetEmpty = 'Não é possível realizar esta operação em um arquivo vazio'; SDataSetReadOnly = 'Não é possível modificar um arquivo somente de leitura'; SNestedDataSetClass = 'Arquivo aninhado têm que herdar de %s'; SExprTermination = 'Expressão de filtro incorretamente terminada'; SExprNameError = 'Nome de campo não terminado'; SExprStringError = 'Constante de string não terminada'; SExprInvalidChar = 'Caractere inválido na expressão de filtro: ''%s'''; SExprNoLParen = ''')'' esperado mas %s encontrado'; SExprNoRParen = ''')'' esperado mas %s encontrado'; SExprNoRParenOrComma = ''')'' ou '','' aguardado mas %s existe'; SExprExpected = 'Expressão esperada mas %s encontrada'; SExprBadField = 'Campo ''%s'' não pode ser usado em uma expressão de filtro'; SExprBadNullTest = 'NULL somente permitido com ''='' e ''<>'''; SExprRangeError = 'Constante fora de faixa'; SExprNotBoolean = 'Campo ''%s'' não é do tipo boleano'; SExprIncorrect = 'Expressão de filtro formada incorretamente'; SExprNothing = 'Absolutamente'; SExprTypeMis = 'Tipo de expressão desconhecida'; SExprBadScope = 'Operação não pode misturar valor agregado com valor registro-variado'; SExprNoArith = 'Filtro de expressão aritmética não suportada'; SExprNotAgg = 'Expressão não é uma expressão agregada'; SExprBadConst = 'Constante corrente não é do tipo %s'; SExprNoAggFilter = 'Expressões agregadas não permitem filtros'; SExprEmptyInList = 'Lista de predicados IN pode não estar vazia'; SInvalidKeywordUse = 'Uso de Keyword inválido'; STextFalse = 'Falso'; STextTrue = 'Verdadeiro'; SParameterNotFound = 'Parametro ''%s'' não encontrado'; SInvalidVersion = 'Não é possível carregar parâmetros da fita'; SParamTooBig = 'Parâmetro ''%s'', não é possível salvar dados maiores que %d bytes'; SBadFieldType = 'Campo ''%s'' é um tipo não suportado'; SAggActive = 'Esta propriedade não pode ser modificada enquanto o agregado está ativo'; SProviderSQLNotSupported = 'SQL não é suportada: %s'; SProviderExecuteNotSupported = 'Execução não é suportada: %s'; SExprNoAggOnCalcs = 'Field ''%s'' is not the correct type of calculated field to be used in an aggregate, use an internalcalc'; SRecordChanged = 'Registro foi alterado por outro usuário'; SDataSetUnidirectional = 'Operação não permitida em um dataset unidirecional'; SUnassignedVar = 'Valor variant não atribuído'; SRecordNotFound = 'Registro não encontrado'; SFileNameBlank = 'Propriedade FileName não pode ser vazia'; SFieldNameTooLarge = 'Nome de campo %s excede %d caracteres'; { For FMTBcd } SBcdOverflow = 'BCD estouro de capacidade'; SInvalidBcdValue = '%s não é uma valor BCD válido'; SInvalidFormatType = 'Tipo de formato inválido para BCD'; { For SqlTimSt } SCouldNotParseTimeStamp = 'Poderia não analisar string SQL TimeStamp'; SInvalidSqlTimeStamp = 'Valores de SQL data/hota inválidas'; SDeleteRecordQuestion = 'Apagar registro?'; SDeleteMultipleRecordsQuestion = 'Apagar todos os registros selecionados?'; STooManyColumns = 'Grid requisitou para mostrar mais do que 256 colunas'; { For reconcile error } SSkip = 'Skip'; SAbort = 'Abortar'; SMerge = 'Mesclar'; SCorrect = 'Corrigir'; SCancel = 'Cancelar'; SRefresh = 'Atualizar'; SModified = 'Modificado'; SInserted = 'Inserido'; SDeleted = 'Apagado'; SCaption = 'Erro de atualização - %s'; SUnchanged = '<Não alterado>'; SBinary = '(Binário)'; SAdt = '(ADT)'; SArray = '(Matriz)'; SFieldName = 'Nome do Campo'; SOriginal = 'Valor Original'; SConflict = 'Valor Conflitante'; SValue = ' Valor'; SNoData = '<Sem Registros>'; SNew = 'Novo'; implementation end.
unit TextureBank; interface uses BasicDataTypes, dglOpengl, TextureBankItem, SysUtils, Windows, Graphics, Abstract2DImageData; type TTextureBank = class private Items : array of PTextureBankItem; // Constructors and Destructors procedure Clear; // Adds function Search(const _Filename: string): integer; overload; function Search(const _ID: GLInt): integer; overload; function SearchReadOnly(const _Filename: string): integer; overload; function SearchReadOnly(const _ID: GLInt): integer; overload; function SearchEditable(const _ID: GLInt): integer; public // Constructors and Destructors constructor Create; destructor Destroy; override; // I/O function Load(var _ID: GLInt; const _Filename: string): PTextureBankItem; function LoadNew: PTextureBankItem; function Save(var _ID: GLInt; const _Filename: string): boolean; // Adds function Add(const _filename: string): PTextureBankItem; overload; function Add(const _ID: GLInt): PTextureBankItem; overload; function Add(const _Bitmap: TBitmap): PTextureBankItem; overload; function Add(const _Bitmaps: TABitmap): PTextureBankItem; overload; function Add(const _Bitmap: TBitmap; const _AlphaMap: TByteMap): PTextureBankItem; overload; function Add(const _Bitmaps: TABitmap; const _AlphaMaps: TAByteMap): PTextureBankItem; overload; function Add(const _Image: TAbstract2DImageData): PTextureBankItem; overload; function AddReadOnly(const _filename: string): PTextureBankItem; overload; function AddReadOnly(const _ID: GLInt): PTextureBankItem; overload; function Clone(const _filename: string): PTextureBankItem; overload; function Clone(const _ID: GLInt): PTextureBankItem; overload; function Clone(const _Bitmap: TBitmap): PTextureBankItem; overload; function Clone(const _Bitmaps: TABitmap): PTextureBankItem; overload; function Clone(const _Bitmap: TBitmap; const _AlphaMap: TByteMap): PTextureBankItem; overload; function Clone(const _Bitmaps: TABitmap; const _AlphaMaps: TAByteMap): PTextureBankItem; overload; function Clone(const _Image: TAbstract2DImageData): PTextureBankItem; overload; function CloneEditable(const _ID: GLInt): PTextureBankItem; overload; // Deletes procedure Delete(const _ID : GLInt); end; implementation // Constructors and Destructors constructor TTextureBank.Create; begin SetLength(Items,0); end; destructor TTextureBank.Destroy; begin Clear; inherited Destroy; end; // Only activated when the program is over. procedure TTextureBank.Clear; var i : integer; begin for i := Low(Items) to High(Items) do begin Items[i]^.Free; end; end; // I/O function TTextureBank.Load(var _ID: GLInt; const _Filename: string): PTextureBankItem; var i : integer; begin i := SearchEditable(_ID); if i <> -1 then begin Items[i].DecCounter; if Items[i].GetCount = 0 then begin try Items[i]^.Free; dispose(Items[i]); new(Items[i]); Items[i]^ := TTextureBankItem.Create(_Filename); Result := Items[i]; except Result := nil; exit; end; Items[i]^.SetEditable(true); end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Filename); except Items[High(Items)]^.Free; SetLength(Items,High(Items)); Result := nil; exit; end; Items[High(Items)]^.SetEditable(true); Result := Items[High(Items)]; end; end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Filename); except Items[High(Items)]^.Free; SetLength(Items,High(Items)); Result := nil; exit; end; Items[High(Items)]^.SetEditable(true); Result := Items[High(Items)]; end; end; function TTextureBank.LoadNew: PTextureBankItem; begin SetLength(Items,High(Items)+2); new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create; Items[High(Items)]^.SetEditable(true); Result := Items[High(Items)]; end; function TTextureBank.Save(var _ID: GLInt; const _Filename: string): boolean; var i : integer; begin i := Search(_ID); if i <> -1 then begin Items[i]^.SaveTexture(_Filename); Result := true; end else begin Result := false; end; end; // Adds function TTextureBank.Search(const _filename: string): integer; var i : integer; begin Result := -1; if Length(_Filename) = 0 then exit; i := Low(Items); while i <= High(Items) do begin if CompareStr(_Filename,Items[i]^.GetFilename) = 0 then begin Result := i; exit; end; inc(i); end; end; function TTextureBank.Search(const _ID: GLInt): integer; var i : integer; begin Result := -1; if _ID <= 0 then exit; i := Low(Items); while i <= High(Items) do begin if _ID = Items[i]^.GetID then begin Result := i; exit; end; inc(i); end; end; function TTextureBank.SearchReadOnly(const _filename: string): integer; var i : integer; begin Result := -1; if Length(_Filename) = 0 then exit; i := Low(Items); while i <= High(Items) do begin if not Items[i]^.GetEditable then begin if CompareStr(_Filename,Items[i]^.GetFilename) = 0 then begin Result := i; exit; end; end; inc(i); end; end; function TTextureBank.SearchReadOnly(const _ID: GLInt): integer; var i : integer; begin Result := -1; if _ID <= 0 then exit; i := Low(Items); while i <= High(Items) do begin if not Items[i]^.GetEditable then begin if _ID = Items[i]^.GetID then begin Result := i; exit; end; end; inc(i); end; end; function TTextureBank.SearchEditable(const _ID: GLInt): integer; var i : integer; begin Result := -1; if _ID <= 0 then exit; i := Low(Items); while i <= High(Items) do begin if Items[i]^.GetEditable then begin if _ID = Items[i]^.GetID then begin Result := i; exit; end; end; inc(i); end; end; function TTextureBank.Add(const _filename: string): PTextureBankItem; var i : integer; begin i := Search(_Filename); if i <> -1 then begin Items[i]^.IncCounter; Result := Items[i]; end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Filename); except Items[High(Items)]^.Free; dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; end; function TTextureBank.Add(const _ID: GLInt): PTextureBankItem; var i : integer; begin i := Search(_ID); if i <> -1 then begin Items[i]^.IncCounter; Result := Items[i]; end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_ID); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; end; function TTextureBank.Add(const _Bitmap: TBitmap): PTextureBankItem; begin Result := Clone(_Bitmap); end; function TTextureBank.Add(const _Bitmaps: TABitmap): PTextureBankItem; begin Result := Clone(_Bitmaps); end; function TTextureBank.Add(const _Bitmap: TBitmap; const _AlphaMap: TByteMap): PTextureBankItem; begin Result := Clone(_Bitmap,_AlphaMap); end; function TTextureBank.Add(const _Bitmaps: TABitmap; const _AlphaMaps: TAByteMap): PTextureBankItem; begin Result := Clone(_Bitmaps,_AlphaMaps); end; function TTextureBank.Add(const _Image: TAbstract2DImageData): PTextureBankItem; begin Result := Clone(_Image); end; function TTextureBank.AddReadOnly(const _filename: string): PTextureBankItem; var i : integer; begin i := SearchReadOnly(_Filename); if i <> -1 then begin Items[i]^.IncCounter; Result := Items[i]; end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Filename); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; end; function TTextureBank.AddReadOnly(const _ID: GLInt): PTextureBankItem; var i : integer; begin i := SearchReadOnly(_ID); if i <> -1 then begin Items[i]^.IncCounter; Result := Items[i]; end else begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_ID); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; end; function TTextureBank.Clone(const _filename: string): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Filename); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _ID: GLInt): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_ID); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _Bitmap: TBitmap): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Bitmap); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _Bitmaps: TABitmap): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Bitmaps); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _Bitmap: TBitmap; const _AlphaMap: TByteMap): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Bitmap,_AlphaMap); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _Bitmaps: TABitmap; const _AlphaMaps: TAByteMap): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Bitmaps,_AlphaMaps); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.Clone(const _Image: TAbstract2DImageData): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_Image); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Result := Items[High(Items)]; end; function TTextureBank.CloneEditable(const _ID: GLInt): PTextureBankItem; begin SetLength(Items,High(Items)+2); try new(Items[High(Items)]); Items[High(Items)]^ := TTextureBankItem.Create(_ID); except Items[High(Items)]^.Free; Dispose(Items[High(Items)]); SetLength(Items,High(Items)); Result := nil; exit; end; Items[High(Items)]^.SetEditable(true); Result := Items[High(Items)]; end; // Deletes procedure TTextureBank.Delete(const _ID : GLInt); var i : integer; begin i := Search(_ID); if i <> -1 then begin Items[i]^.DecCounter; if Items[i]^.GetCount = 0 then begin Items[i]^.Free; while i < High(Items) do begin Items[i] := Items[i+1]; inc(i); end; SetLength(Items,High(Items)); end; end; end; end.
unit sgDriverText; //============================================================================= // sgDriverText.pas //============================================================================= // // The TextDriver is responsible for providing an interface between SwinGame // code and the drivers. It can interface between any Text driver provided // // Change History: // 2012-01-05: Aaron : Created File. // // Notes: // - // TODO: // - //============================================================================= interface uses sgTypes, sgDriverTextSDL2, sgBackendTypes; type // These function and procedure pointers are required by the TextDriverRecord //loads a TTF font with a font name and size. Return a swingame Font LoadFontProcedure = function(const fontName, fileName : String; size : Longint) : FontPtr; // closes a font. CloseFontProcedure = procedure(fontToClose : FontPtr); /// This function prints "str" with font "font" and color "clrFg" /// * onto a rectangle of color "clrBg". /// * It does not pad the text. PrintStringsProcedure = procedure(dest: Bitmap; font: FontPtr;const str: String; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment); /// This function prints "str" with font "font" and color "clrFg" /// * onto a rectangle of color "clrBg". /// * It does not pad the text. PrintWideStringsProcedure = procedure(dest: Bitmap; font: FontPtr; str: WideString; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment); // sets the current font and font style. SetFontStyleProcedure = procedure(fontToSet : FontPtr; value: Fontstyle); // gets the current fontstyle of the given font GetFontStyleProcedure = function(font : FontPtr) : FontStyle; //returns the size of a given text using a given font. SizeOfTextProcedure = function(font : FontPtr ;const theText : String ; var w : Longint; var h : Longint) : Integer; //returns the size of a given text using a given font. SizeOfUnicodeProcedure = function(font : FontPtr; theText : WideString; var w : Longint; var h : Longint) : Integer; //closes the font module. QuitProcedure = procedure(); // shows error messages. GetErrorProcedure = function() : string; //checks if font library is initialiszed. InitProcedure = function() : integer; StringColorProcedure = procedure (dest : Bitmap; x,y : Single;const theText : String; theColor : Color); FontToIntFn = function (fnt: FontPtr) : Integer; TextDriverRecord = record LoadFont : LoadFontProcedure; CloseFont : CloseFontProcedure; PrintStrings : PrintStringsProcedure; PrintWideStrings : PrintWideStringsProcedure; SetFontStyle : SetFontStyleProcedure; GetFontStyle : GetFontStyleProcedure; SizeOfText : SizeOfTextProcedure; SizeOfUnicode : SizeOfUnicodeProcedure; Quit : QuitProcedure; GetError : GetErrorProcedure; Init : InitProcedure; StringColor : StringColorProcedure; LineSkip : FontToIntFn; end; var // Global variable used to allow SwinGame to access the functions and procedures // of the audio driver. TextDriver : TextDriverRecord; //============================================================================= implementation procedure LoadDefaultTextDriver(); begin LoadSDL2TextDriver(); end; function DefaultLoadFontProcedure(const fontName, fileName : String; size : Longint) : FontPtr; begin LoadDefaultTextDriver(); result := TextDriver.LoadFont(fontName, fileName, size); end; procedure DefaultCloseFontProcedure(fontToClose : FontPtr); begin LoadDefaultTextDriver(); TextDriver.CloseFont(fontToClose); end; procedure DefaultPrintStringsProcedure(dest: Bitmap; font: FontPtr;const str: String; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment); begin LoadDefaultTextDriver(); TextDriver.PrintStrings(dest,font,str,rc,clrFg,clrBg,flags) end; procedure DefaultPrintWideStringsProcedure(dest: Bitmap; font: FontPtr; str: WideString; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment) ; begin LoadDefaultTextDriver(); TextDriver.PrintWideStrings(dest,font,str,rc,clrFg,clrBg,flags) end; procedure DefaultSetFontStyleProcedure(fontToSet : FontPtr; value : FontStyle); begin LoadDefaultTextDriver(); TextDriver.SetFontStyle(fontToSet , value); end; function DefaultGetFontStyleProcedure(font : FontPtr) : FontStyle; begin LoadDefaultTextDriver(); result := TextDriver.GetFontStyle(font); end; function DefaultSizeOfTextProcedure(font : FontPtr;const theText : String; var w, h : Longint) : Integer; begin LoadDefaultTextDriver(); result := TextDriver.SizeOfText(font, theText, w, h); end; function DefaultSizeOfUnicodeProcedure(font : FontPtr; theText : WideString; var w : Longint; var h : Longint) : Integer; begin LoadDefaultTextDriver(); result := TextDriver.SizeOfUnicode(font, theText, w, h); end; procedure DefaultQuitProcedure(); begin LoadDefaultTextDriver(); TextDriver.Quit(); end; function DefaultGetErrorProcedure() : String; begin LoadDefaultTextDriver(); result := TextDriver.GetError(); end; function DefaultInitProcedure(): integer; begin LoadDefaultTextDriver(); result := TextDriver.Init(); end; procedure DefaultStringColorProcedure(dest : Bitmap; x,y : Single;const theText : String; theColor : Color); begin LoadDefaultTextDriver(); TextDriver.StringColor(dest,x,y,theText,theColor); end; function DefaultLineSkipFunction(fnt: FontPtr) : Integer; begin LoadDefaultTextDriver(); result := TextDriver.LineSkip(fnt); end; //============================================================================= initialization begin TextDriver.LoadFont := @DefaultLoadFontProcedure; TextDriver.CloseFont := @DefaultCloseFontProcedure; TextDriver.PrintStrings := @DefaultPrintStringsProcedure; TextDriver.PrintWideStrings := @DefaultPrintWideStringsProcedure; TextDriver.SetFontStyle := @DefaultSetFontStyleProcedure; TextDriver.GetFontStyle := @DefaultGetFontStyleProcedure; TextDriver.SizeOfText := @DefaultSizeOfTextProcedure; TextDriver.SizeOfUnicode := @DefaultSizeOfUnicodeProcedure; TextDriver.Quit := @DefaultQuitProcedure; TextDriver.GetError := @DefaultGetErrorProcedure; TextDriver.Init := @DefaultInitProcedure; TextDriver.StringColor := @DefaultStringColorProcedure; TextDriver.LineSkip := @DefaultLineSkipFunction; end; end.
unit kpPipeline; { TkpPipeline - трубопровод с анимацией версия 1.0 (c) К. Поляков, 2003 FIDO: 2:5030/542.251 e-mail: kpolyakov@mail.ru Web: http://kpolyakov.narod.ru http://kpolyakov.newmail.ru Ограничения: - одностороннее движение жидкости - ветки могут разветвляться, но не могут пересекаться - трубы соединяются только под прямым углом - движение потока имитируется движением прямоугольников разных цветов Описание схемы представляет собой набор символьных строк. Каждая строка описывает один элемент: s x y имя_входа вход в точке (x,y) l длина звено влево г длина звено вправо u длина звено вверх d длина звено вниз j имя_узла новый узел в текущей позиции курсора t имя_выхода выход в текущей позиции курсора g имя_узла перейти в узел Дополнительные свойства и методы: Animate: Boolean использовать анимацию или нет Color: TColor цвет воды FlowColor: TColor цвет промежутков AltColor: TColor цвет промежутков BkColor: TColor цвет фона BkBitmap: TBitmap фоновый рисунок JointColor: TColor цвет контура узлов TickLength: integer длина отрезка при анимации PipeWidth: integer ширина трубы MapList: TStrings описание трубопровода Period: integer интервал для анимации MoveStep: integer шаг движения HasLabels: Boolean ставить ли метки входов и выходов SourceState[Index: integer]: Boolean состояние входа (да/нет) TerminalState[Index: integer]: Boolean состояние выхода (да/нет) SourceStateByName[Name: string]: Boolean состояние входа по имени TerminalStateByName[Name: string]: Boolean состояние выхода по имени SourceNames: TStrings имена входов TerminalNames: TStrings имена выходов JointNames: TStrings имена узлов События: OnChange: TNotifyEvent изменилось состояние входов, могло (но не обязательно!) измениться и состояние выходов OnProcessLine: TLineNotifyEvent событие при обработке строки карты с указанным номером } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ExtCtrls; const PIPE_CHANGE = WM_USER + 100; MAXSOURCES = 100; MAXTERMINALS = 100; RJOINT = 5; XYCOMB = 10000; type TChainType = (ctUp, ctDown, ctLeft, ctRight, ctJoint, ctHide, ctSource, ctTerminal, ctGo, ctNone); PChain = ^TChain; TChain = record x, y, len: integer; cType, cTypePrev: TChainType; BeforeTerminal: Boolean; stage: integer; nSource: integer; end; EPipesError = class(Exception); TLineNotifyEvent = procedure(Sender: TObject; LineNo: integer) of object; TkpPipeline = class(TCustomPanel) private FMapList: TStrings; FChains: TList; FTimer: TTimer; FAnimate: Boolean; FFlowColor, FAltColor, FBkColor, FJointColor: TColor; FBitmap: TBitmap; FBkBitmap: TBitmap; FTickLength: integer; FPipeWidth: integer; FStartStage: integer; FMoveStep: integer; FSourceState: array[0..MAXSOURCES-1] of Boolean; FTerminalLink: array[0..MAXTERMINALS-1] of integer; FSources, FTerminals, FJoints: TStrings; FOnChange: TNotifyEvent; FOnProcessLine: TLineNotifyEvent; FNotifyList: TList; FClipRgn: HRGN; FHasLabels: Boolean; protected procedure Paint; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure Loaded; override; procedure SetAnimate(NewAnimate: Boolean); function GetColor: TColor; procedure SetColor(NewColor: TColor); procedure SetAltColor(NewAltColor: TColor); procedure SetFlowColor(NewFlowColor: TColor); procedure SetBkColor(NewBkColor: TColor); procedure SetBkBitmap(NewBkBitmap: TBitmap); procedure SetJointColor(NewJointColor: TColor); procedure SetTickLength(NewTickLength: integer); procedure SetPipeWidth(NewPipeWidth: integer); procedure SetMapList(NewMapList: TStrings); function GetPeriod: integer; procedure SetPeriod(NewPeriod: integer); procedure SetMoveStep(NewMoveStep: integer); function GetSourceState(Index: integer): Boolean; procedure SetSourceState(Index: integer; Active: Boolean); function GetTerminalState(Index: integer): Boolean; function GetSourceStateByName(Name: string): Boolean; procedure SetSourceStateByName(Name: string; Active: Boolean); function GetTerminalStateByName(Name: string): Boolean; procedure SetHasLabels(NewHasLabels: Boolean); function GetMargin: integer; procedure OnTimer(Sender: TObject); procedure FontChanged(Sender: TObject); procedure ClearChainList; procedure Parse(s: string; var cType: TChainType; var n1, n2: integer; var Name: string); procedure BuildPipeline; function CalcChainRect(var x0, y0: integer; len: integer; cType, cTypePrev: TChainType; IsLast, BeforeTerminal: Boolean): TRect; procedure DrawBorder(Cvs: TCanvas; x0, y0, len: integer; cType, cTypePrev: TChainType); procedure RefreshPicture; procedure Redraw(Cvs: TCanvas; FullRepaint: Boolean); procedure RedrawAll; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddNotify(Obj: TControl); procedure RemoveNotify(Obj: TControl); procedure Notification(AComponent: TComponent; Operation: TOperation); override; property SourceState[Index: integer]: Boolean read GetSourceState write SetSourceState; property TerminalState[Index: integer]: Boolean read GetTerminalState; property SourceStateByName[Name: string]: Boolean read GetSourceStateByName write SetSourceStateByName; property TerminalStateByName[Name: string]: Boolean read GetTerminalStateByName; property SourceNames: TStrings read FSources; property TerminalNames: TStrings read FTerminals; property JointNames: TStrings read FJoints; published property Animate: Boolean read FAnimate write SetAnimate; property AltColor: TColor read FAltColor write SetAltColor; property FlowColor: TColor read FFlowColor write SetFlowColor; property BkColor: TColor read FBkColor write SetBkColor; property BkBitmap: TBitmap read FBkBitmap write SetBkBitmap; property Color: TColor read GetColor write SetColor; property JointColor: TColor read FJointColor write SetJointColor; property TickLength: integer read FTickLength write SetTickLength; property PipeWidth: integer read FPipeWidth write SetPipeWidth; property MapList: TStrings read FMapList write SetMapList; property Period: integer read GetPeriod write SetPeriod; property MoveStep: integer read FMoveStep write SetMoveStep; property HasLabels: Boolean read FHasLabels write SetHasLabels; property Margin: integer read GetMargin; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnProcessLine: TLineNotifyEvent read FOnProcessLine write FOnProcessLine; property Align; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; // property Ctl3D; property DragCursor; property DragMode; property Enabled; property FullRepaint; // property Caption; property Font; property MouseCapture; property ParentColor; // property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; procedure Register; implementation //-------------- constructor ----------------------- constructor TkpPipeline.Create(AOwner: TComponent); begin FMapList := TStringList.Create; FChains := TList.Create; FSources := TStringList.Create; FTerminals := TStringList.Create; FJoints := TStringList.Create; FBitmap := TBitmap.Create; FBkBitmap := TBitmap.Create; FNotifyList := TList.Create; FTimer := TTimer.Create(nil); FTimer.OnTimer := OnTimer; FTimer.Interval := 1000; FTimer.Enabled := False; FMoveStep := 2; FTickLength := 5; FPipeWidth := 7; FFlowColor := clGreen; FAltColor := clWhite; FBkColor := clBtnFace; FJointColor := clYellow; inherited; ControlStyle := ControlStyle + [csOpaque]; Font.OnChange := FontChanged; Width := 50; Height := 50; end; //-------------- destructor ----------------------- destructor TkpPipeline.Destroy; begin if FClipRgn <> 0 then DeleteObject(FClipRgn); FMapList.Free; ClearChainList; FChains.Free; FTimer.Free; FBitmap.Free; FBkBitmap.Free; FNotifyList.Free; FSources.Free; FTerminals.Free; FJoints.Free; inherited; end; //-------------- ClearChainList ----------------------- procedure TkpPipeline.ClearChainList; var i: integer; P: PChain; begin for i:=0 to FChains.Count-1 do begin P := PChain(FChains[i]); Dispose(P); end; FChains.Clear; end; //-------------- AddNotify ------------------ procedure TkpPipeline.AddNotify(Obj: TControl); var i: integer; begin i := FNotifyList.IndexOf(Obj); if i < 0 then FNotifyList.Add(Pointer(Obj)); end; //-------------- RemoveNotify ------------------ procedure TkpPipeline.RemoveNotify(Obj: TControl); var i: integer; begin i := FNotifyList.IndexOf(Obj); if i >= 0 then FNotifyList.Delete(i); end; {============== Notification =========} procedure TkpPipeline.Notification(AComponent: TComponent; Operation: TOperation); var i: integer; begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin i := FNotifyList.IndexOf(AComponent); if i >= 0 then FNotifyList.Delete(i); end; end; //-------------- SetBounds ----------------------- procedure TkpPipeline.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin if (Width <> AWidth) or (Height <> AHeight) then begin FBitmap.Width := AWidth; FBitmap.Height := AHeight; RedrawAll; end; inherited; end; //-------------- Redraw all ------------------ procedure TkpPipeline.RedrawAll; var m, i: integer; begin with FBitmap.Canvas do begin if FBkBitmap.Width = 0 then Brush.Color := FBkColor else Brush.Bitmap := FBkBitmap; FillRect(Rect(0, 0, FBitmap.Width, FBitmap.Height)); end; BuildPipeline; Redraw(FBitmap.Canvas, True); m := Margin; if Assigned(Parent) then begin SelectClipRgn(Canvas.Handle, 0); BitBlt(Canvas.Handle, m, m, Width-2*m, Height-2*m, FBitmap.Canvas.Handle, 0, 0, SRCCOPY); end; for i:=0 to FNotifyList.Count-1 do TControl(FNotifyList[i]).Perform(PIPE_CHANGE, Integer(Self), 0); if Assigned(FOnChange) and not (csLoading in ComponentState) then FOnChange ( Self ); end; //-------------- Refresh Picture ------------------ procedure TkpPipeline.RefreshPicture; var m: integer; begin Redraw(FBitmap.Canvas, False); m := Margin; SelectClipRgn(Canvas.Handle, FClipRgn); // OffsetClipRgn(Canvas.Handle, Left, Top); // если делать на основе TPaintBox !!! OffsetClipRgn(Canvas.Handle, m, m); BitBlt(Canvas.Handle, m, m, Width-2*m, Height-2*m, FBitmap.Canvas.Handle, 0, 0, SRCCOPY); end; //-------------- Parse ------------------ procedure TkpPipeline.Parse(s: string; var cType: TChainType; var n1, n2: integer; var Name: string); //---------- GetWord ------------------------ function GetWord(var s: string): string; var p: integer; begin s := Trim(s); p := Pos(' ', s); if p = 0 then begin Result := s; s := ''; end else begin Result := Copy(s, 1, p-1); s := Copy(s, p+1, 999); end; end; begin cType := ctNone; n1 := -1; n2 := -1; Name := ''; s := Trim(s); if Length(s) < 1 then Exit; case s[1] of 's': cType := ctSource; 't': cType := ctTerminal; 'j': cType := ctJoint; 'g': cType := ctGo; 'h': cType := ctHide; 'u': cType := ctUp; 'd': cType := ctDown; 'l': cType := ctLeft; 'r': cType := ctRight; end; Delete(s, 1, 1); n1 := StrToIntDef(GetWord(s), -1); n2 := StrToIntDef(GetWord(s), -1); Name := Trim(s); end; //------------- DRAW BORDER --------------------------------------- procedure TkpPipeline.DrawBorder(Cvs: TCanvas; x0, y0, len: integer; cType, cTypePrev: TChainType); var w: integer; begin w := FPipeWidth div 2; with Cvs do begin Pen.Color := clBlack; if (cType = cTypePrev) or (not (cTypePrev in [ctUp,ctDown,ctLeft,ctRight])) then begin case cType of ctUp: begin MoveTo(x0-w,y0); LineTo(x0-w,y0-len-1); MoveTo(x0+w,y0); LineTo(x0+w,y0-len-1); end; ctDown: begin MoveTo(x0-w,y0); LineTo(x0-w,y0+len+1); MoveTo(x0+w,y0); LineTo(x0+w,y0+len+1); end; ctLeft: begin MoveTo(x0,y0-w); LineTo(x0-len-1,y0-w); MoveTo(x0,y0+w); LineTo(x0-len-1,y0+w); end; ctRight: begin MoveTo(x0,y0-w); LineTo(x0+len+1,y0-w); MoveTo(x0,y0+w); LineTo(x0+len+1,y0+w); end; end end; if (cType <> cTypePrev) and (cTypePrev <> ctSource) then begin case cType of ctUp: begin MoveTo(x0-w,y0+w); LineTo(x0+w+1,y0+w); if cTypePrev = ctRight then begin MoveTo(x0-w,y0-w); LineTo(x0-w,y0-len-1); MoveTo(x0+w,y0+w); LineTo(x0+w,y0-len-1); end else begin MoveTo(x0-w,y0+w); LineTo(x0-w,y0-len-1); MoveTo(x0+w,y0-w); LineTo(x0+w,y0-len-1); end; end; ctDown: begin MoveTo(x0-w,y0-w); LineTo(x0+w+1,y0-w); if cTypePrev = ctRight then begin MoveTo(x0-w,y0+w); LineTo(x0-w,y0+len+1); MoveTo(x0+w,y0-w); LineTo(x0+w,y0+len+1); end else begin MoveTo(x0-w,y0-w); LineTo(x0-w,y0+len+1); MoveTo(x0+w,y0+w); LineTo(x0+w,y0+len+1); end; end; ctLeft: begin MoveTo(x0+w,y0-w); LineTo(x0+w,y0+w+1); if cTypePrev = ctUp then begin MoveTo(x0+w,y0-w); LineTo(x0-len-1,y0-w); MoveTo(x0-w,y0+w); LineTo(x0-len-1,y0+w); end else begin MoveTo(x0-w,y0-w); LineTo(x0-len-1,y0-w); MoveTo(x0+w,y0+w); LineTo(x0-len-1,y0+w); end; end; ctRight: begin MoveTo(x0-w,y0-w); LineTo(x0-w,y0+w+1); if cTypePrev = ctUp then begin MoveTo(x0-w,y0-w); LineTo(x0+len+1,y0-w); MoveTo(x0+w,y0+w); LineTo(x0+len+1,y0+w); end else begin MoveTo(x0+w,y0-w); LineTo(x0+len+1,y0-w); MoveTo(x0-w,y0+w); LineTo(x0+len+1,y0+w); end; end; end; end; end; end; //-------------- CalcChainRect ------------------ function TkpPipeline.CalcChainRect( var x0, y0: integer; len: integer; cType, cTypePrev: TChainType; IsLast, BeforeTerminal: Boolean): TRect; var w, x1, y1, x2, y2, xi, yi, temp: integer; begin w := FPipeWidth div 2 - 1; xi := x0; yi := y0; x1 := x0; x2 := x0; y1 := y0; y2 := y0; case cType of ctUp: begin yi := y0 - len; x1 := x0 - w; x2 := x0 + w + 1; y1 := y0; y2 := yi; if IsLast and (not BeforeTerminal) then y2 := y2 - w; end; ctDown: begin yi := y0 + len; x1 := x0 - w; x2 := x0 + w + 1; y1 := y0; y2 := yi; if IsLast and (not BeforeTerminal) then y2 := y2 + w + 1; end; ctLeft: begin xi := x0 - len; x1 := x0 + 1; x2 := xi; y1 := y0 - w; y2 := y0 + w + 1; if IsLast and (not BeforeTerminal) then x2 := x2 - w; end; ctRight: begin xi := x0 + len; x1 := x0; x2 := xi + 1; y1 := y0 - w; y2 := y0 + w + 1; if IsLast and (not BeforeTerminal) then x2 := x2 + w; end; end; if x1 > x2 then begin temp := x1; x1 := x2; x2 := temp; end; if y1 > y2 then begin temp := y1; y1 := y2; y2 := temp; end; Result := Rect(x1, y1, x2, y2); x0 := xi; y0 := yi; end; //-------------- Redraw ------------------ var hideR: array[1..8] of integer = (1, 2, 3, 4, 5, 7, 9, 12); procedure TkpPipeline.Redraw(Cvs: TCanvas; FullRepaint: Boolean); var i, xy, x, y, stage: integer; P, PPrev: PChain; Skip: Boolean; rgn: HRGN; //------------- DRAW SEGMENT --------------------------------------- procedure DrawSegment(var x0, y0, len: integer; cType, cTypePrev: TChainType; Active, IsLast, BeforeTerminal: Boolean); var rct: TRect; begin rct := CalcChainRect(x0, y0, len, cType, cTypePrev, IsLast, BeforeTerminal); with Cvs do begin if Active then Brush.Color := FFlowColor else Brush.Color := FAltColor; Pen.Color := Brush.Color; Rectangle(rct.Left, rct.Top, rct.Right, rct.Bottom); if FullRepaint then begin rgn := CreateRectRgn(rct.Left, rct.Top, rct.Right, rct.Bottom); CombineRgn(FClipRgn, FClipRgn, rgn, RGN_OR); DeleteObject(rgn); end; end; end; //------------- DRAW PIPE --------------------------------------- procedure DrawPipe(x, y, len: integer; cType, cTypePrev: TChainType; SourceState, BeforeTerminal: Boolean); var lenSeg: integer; IsTick: Boolean; begin IsTick := stage > FTickLength; DrawBorder ( Cvs, x, y, len, cType, cTypePrev ); while len > 0 do begin if stage > FTickLength then lenSeg := stage - FTickLength else lenSeg := stage; if lenSeg > len then lenSeg := len; stage := stage - lenSeg; if stage = 0 then stage := 2*FTickLength; DrawSegment(x, y, lenSeg, cType, cTypePrev, IsTick and SourceState, len = lenSeg, BeforeTerminal); if stage mod FTickLength = 0 then IsTick := not IsTick; Dec(len, lenSeg); cTypePrev := cType; end; end; //------------------- DRAW NAME ------------------------- procedure DrawName(x, y: integer; Name: string; Dir: TChainType); var w, m: integer; rct: TRect; begin with Cvs do begin w := TextWidth(Name) div 2; Pen.Color := clBlack; Font.Assign(Self.Font); Brush.Color := FJointColor; case Dir of ctUp: x := x - w - 2; ctRight: x := x + FPipeWidth; end; y := y - FPipeWidth div 2 - 3 - TextHeight(Name); rct := Rect(x, y, x+w, y+5); m := Margin; if x < 2 then OffSetRect(rct, 2-x, 0); DrawText(Cvs.Handle, PChar(Name), Length(Name), rct, DT_SINGLELINE or DT_CALCRECT); if rct.Right+2+2*m > Width then OffSetRect(rct, Width-rct.Right-2-2*m, 0); Rectangle ( rct.Left-2, rct.Top-2, rct.Right+2, rct.Bottom+2); DrawText(Cvs.Handle, PChar(Name), Length(Name), rct, DT_SINGLELINE); end; end; //--------------------------------------------------------- procedure DrawHideArea ( x, y: integer ); var k, r: integer; begin with Cvs do begin Pen.Color := FBkColor; Brush.Style := bsClear; for k:=1 to 8 do begin r := hideR[k]; Ellipse(x-r, y-r, x+r+1, y+r+1); end; if FullRepaint then begin r := hideR[8]; rgn := CreateEllipticRgn(x-r, y-r, x+r+1, y+r+1); CombineRgn(FClipRgn, FClipRgn, rgn, RGN_OR); DeleteObject(rgn); end; end; end; //--------------------------------------------------------- procedure DrawJoint ( x, y: integer; Active: Boolean ); begin with Cvs do begin Pen.Color := FJointColor; if Active then Brush.Color := FFlowColor else Brush.Color := FAltColor; Ellipse(x-RJOINT, y-RJOINT, x+RJOINT, y+RJOINT); Pen.Color := clBlack; Brush.Style := bsClear; Ellipse(x-RJOINT-1, y-RJOINT-1, x+RJOINT+1, y+RJOINT+1); Brush.Style := bsSolid; if FullRepaint then begin rgn := CreateEllipticRgn(x-RJOINT-1, y-RJOINT-1, x+RJOINT+1, y+RJOINT+1); CombineRgn(FClipRgn, FClipRgn, rgn, RGN_OR); DeleteObject(rgn); end; end; end; //--------------------------------------------------------- begin FTimer.Enabled := False; Skip := False; if FullRepaint then begin if FClipRgn <> 0 then DeleteObject(FClipRgn); FClipRgn := CreateRectRgn(0, 0, 0, 0); end; PPrev := nil; for i:=0 to FChains.Count-1 do begin P := PChain(FChains[i]); case P^.cType of ctHide: Skip := True; ctLeft, ctRight, ctUp, ctDown: begin stage := P^.stage + FStartStage - 2*FTickLength; if stage <= 0 then stage := stage + 2*FTickLength; DrawPipe(P^.x, P^.y, P^.len, P^.cType, P^.cTypePrev, SourceState[P^.nSource], P^.BeforeTerminal); if Skip then DrawHideArea ( PPrev^.x, PPrev^.y ); Skip := False; end; end; PPrev := P; end; for i:=0 to FChains.Count-1 do begin P := PChain(FChains[i]); if P^.cType = ctJoint then DrawJoint(P^.x, P^.y, SourceState[P^.nSource]); end; if FullRepaint and FHasLabels then begin for i:=0 to FSources.Count-1 do begin if FSources[i] = '' then continue; xy := integer(FSources.Objects[i]); x := xy div XYCOMB; y := xy mod XYCOMB; DrawName ( x, y, FSources[i], ctUp ); end; for i:=0 to FTerminals.Count-1 do begin if FTerminals[i] = '' then continue; xy := integer(FTerminals.Objects[i]); x := xy div XYCOMB; y := xy mod XYCOMB; DrawName ( x, y, FTerminals[i], ctUp ); end; for i:=0 to FJoints.Count-1 do begin if FJoints[i] = '' then continue; P := PChain(FJoints.Objects[i]); DrawName ( P^.x, P^.y, FJoints[i], ctRight ); end; end; FTimer.Enabled := FAnimate; end; //-------------- BuildPipeline ------------------ procedure TkpPipeline.BuildPipeline; var x, y, i, n1, n2, k, stage, nSource, CurSource, nTerminal: integer; BeforeTerminal: Boolean; CurType, PrevType: TChainType; P: PChain; s, Name: string; //---------------- CreateChain ---------------------- function CreateChain ( len: integer ): PChain; var P: PChain; begin New(P); P^.x := x; P^.y := y; P^.len := len; P^.cType := CurType; P^.cTypePrev := PrevType; P^.stage := stage; P^.nSource := CurSource; P^.BeforeTerminal := BeforeTerminal; Result := P; end; //--------------------------------------------------- begin FTimer.Enabled := False; ClearChainList; FSources.Clear; FTerminals.Clear; FJoints.Clear; PrevType := ctNone; nSource := -1; CurSource := -1; nTerminal := -1; FStartStage := 2*FTickLength; for i:=0 to FMapList.Count-1 do begin if Assigned(FOnProcessLine) then FOnProcessLine(Self, i); Parse(FMapList[i], CurType, n1, n2, Name); BeforeTerminal := False; if (i < FMapList.Count-1) then begin s := Trim(FMapList[i+1]); BeforeTerminal := (Length(s) > 0) and (s[1] = 't'); end; case CurType of ctJoint: begin Name := Trim(Copy(FMapList[i],2,999)); if (Name <> '') and (FJoints.IndexOf(Name) >= 0) then raise EPipesError.CreateFmt('Узел ''%s'' уже есть в схеме', [Name]); P := CreateChain(0); FChains.Add(Pointer(P)); FJoints.AddObject(Name, TObject(P)); end; ctHide: begin P := CreateChain(0); FChains.Add(Pointer(P)); end; ctGo: begin if n1 >= 0 then begin x := n1; y := n2; end else begin Name := Trim(Copy(FMapList[i],2,999)); k := FJoints.IndexOf(Name); if k < 0 then raise EPipesError.CreateFmt('Узел ''%s'' не найден в схеме', [Name]); P := PChain(FJoints.Objects[k]); x := P^.x; y := P^.y; stage := P^.stage; CurSource := P^.nSource; end; end; ctSource: begin if (Name <> '') and (FSources.IndexOf(Name) >= 0) then raise EPipesError.CreateFmt('Источник ''%s'' уже есть в схеме', [Name]); x := n1; y := n2; Inc(nSource); FSources.AddObject(Name, TObject(x*XYCOMB+y)); CurSource := nSource; stage := FStartStage; end; ctTerminal: begin Name := Trim(Copy(FMapList[i],2,999)); if (Name <> '') and (FTerminals.IndexOf(Name) >= 0) then raise EPipesError.CreateFmt('Терминал ''%s'' уже есть в схеме', [Name]); Inc(nTerminal); FTerminalLink[nTerminal] := CurSource; FTerminals.AddObject(Name, TObject(x*XYCOMB+y)); end; ctNone: begin x := n1; y := n2; end; else begin P := CreateChain( n1 ); FChains.Add(Pointer(P)); CalcChainRect(x, y, n1, CurType, PrevType, False, BeforeTerminal); end; end; PrevType := CurType; end; FTimer.Enabled := FAnimate; end; //-------------- WMEraseBkgnd ------------------ procedure TkpPipeline.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin Message.Result := 1; end; //-------------- GetMargin ------------------ function TkpPipeLine.GetMargin: integer; begin Result := integer(BevelOuter <> bvNone)*BevelWidth + integer(BevelInner <> bvNone)*BevelWidth + BorderWidth; end; //-------------- Paint ------------------ procedure TkpPipeline.Paint; var Rct: TRect; TopColor, BottomColor: TColor; m: integer; //------------------------------------------------- procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; //------------------------------------------------- begin m := Margin; SelectClipRgn(Canvas.Handle, 0); Canvas.Draw(m, m, FBitmap); Rct := GetClientRect; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rct, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, Rct, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rct, TopColor, BottomColor, BevelWidth); end; end; //-------------- SetAnimate ------------------ procedure TkpPipeline.SetAnimate(NewAnimate: Boolean); begin if FAnimate = NewAnimate then Exit; FAnimate := NewAnimate; FTimer.Enabled := NewAnimate; end; //-------------- OnTimer ------------------ procedure TkpPipeline.OnTimer(Sender: TObject); begin FStartStage := (FStartStage + FMoveStep) mod (2*FTickLength); RefreshPicture; end; //-------------- SetAltColor ------------------ procedure TkpPipeline.SetAltColor(NewAltColor: TColor); begin if NewAltColor = FAltColor then Exit; FAltColor := NewAltColor; RefreshPicture; end; //-------------- SetFlowColor ------------------ procedure TkpPipeline.SetFlowColor(NewFlowColor: TColor); begin if NewFlowColor = FFlowColor then Exit; FFlowColor := NewFlowColor; RefreshPicture; end; //-------------- SetBkColor ------------------ procedure TkpPipeline.SetBkColor(NewBkColor: TColor); begin if NewBkColor = FBkColor then Exit; FBkColor := NewBkColor; RedrawAll; end; //-------------- GetColor ------------------ function TkpPipeline.GetColor: TColor; begin Result := inherited Color; end; //-------------- SetColor ------------------ procedure TkpPipeline.SetColor(NewColor: TColor); begin if inherited Color = NewColor then Exit; inherited Color := NewColor; Invalidate; end; //-------------- SetBkBitmap ------------------ procedure TkpPipeline.SetBkBitmap(NewBkBitmap: TBitmap); begin FBkBitmap.Assign(NewBkBitmap); if (FBkBitmap.Width > 0) and (FBkBitmap.Height > 0) then FBkColor := FBkBitmap.Canvas.Pixels[0,0]; RedrawAll; end; //-------------- SetJointColor ------------------ procedure TkpPipeline.SetJointColor(NewJointColor: TColor); begin if NewJointColor = FJointColor then Exit; FJointColor := NewJointColor; RefreshPicture; end; //-------------- SetTickLength ------------------ procedure TkpPipeline.SetTickLength(NewTickLength: integer); begin if NewTickLength = FTickLength then Exit; FTickLength := NewTickLength; FStartStage := 2*FTickLength; RefreshPicture; end; //-------------- SetPipeWidth ------------------ procedure TkpPipeline.SetPipeWidth(NewPipeWidth: integer); begin if NewPipeWidth = FPipeWidth then Exit; FPipeWidth := NewPipeWidth; RedrawAll; end; //-------------- Loaded ------------ procedure TkpPipeline.Loaded; begin RedrawAll; end; //-------------- GetMapList ------------------ procedure TkpPipeline.SetMapList(NewMapList: TStrings); var i: integer; begin FMapList.Assign(NewMapList); for i:=0 to MAXSOURCES-1 do FSourceState[i] := False; RedrawAll; end; //-------------- GetSourceState ------------------ function TkpPipeline.GetSourceState(Index: integer): Boolean; begin if (Index < 0) or (Index >= MAXSOURCES) then raise EPipesError.CreateFmt('Неизвестный вход #%d', [Index]); Result := FSourceState[Index]; end; //-------------- SetSourceState ------------------ procedure TkpPipeline.SetSourceState(Index: integer; Active: Boolean); var i: integer; begin if (Index < 0) or (Index >= MAXSOURCES) then raise EPipesError.CreateFmt('Неизвестный вход #%d', [Index]); if FSourceState[Index] = Active then Exit; FSourceState[Index] := Active; RefreshPicture; for i:=0 to FNotifyList.Count-1 do TControl(FNotifyList[i]).Perform(PIPE_CHANGE, Integer(Self), Index); if Assigned(FOnChange) then FOnChange ( Self ); end; //-------------- GetTerminalState ------------------ function TkpPipeline.GetTerminalState(Index: integer): Boolean; var nSource: integer; begin Result := False; if (Index < 0) or (Index >= MAXTERMINALS) then raise EPipesError.CreateFmt('Неизвестный выход #%d', [Index]); nSource := FTerminalLink[Index]; if (nSource < 0) or (nSource >= MAXSOURCES) then Exit; Result := FSourceState[nSource]; end; //-------------- States by Name ------------------ function TkpPipeline.GetSourceStateByName(Name: string): Boolean; var n: integer; begin n := FSources.IndexOf(Name); if n < 0 then raise EPipesError.CreateFmt('Неизвестный вход ''%s''', [Name]); Result := GetSourceState(n); end; procedure TkpPipeline.SetSourceStateByName(Name: string; Active: Boolean); var n: integer; begin n := FSources.IndexOf(Name); if n < 0 then raise EPipesError.CreateFmt('Неизвестный вход ''%s''', [Name]); SetSourceState(n, Active); end; function TkpPipeline.GetTerminalStateByName(Name: string): Boolean; var n: integer; begin n := FTerminals.IndexOf(Name); if n < 0 then raise EPipesError.CreateFmt('Неизвестный выход ''%s''', [Name]); Result := GetTerminalState(n); end; //-------------- GetPeriod ------------------ function TkpPipeline.GetPeriod: integer; begin Result := FTimer.Interval; end; //-------------- SetPeriod ------------------ procedure TkpPipeline.SetPeriod(NewPeriod: integer); begin if NewPeriod = FTimer.Interval then Exit; FTimer.Interval := NewPeriod; end; //-------------- SetMoveStep ------------------ procedure TkpPipeline.SetMoveStep(NewMoveStep: integer); begin if NewMoveStep = FMoveStep then Exit; FMoveStep := NewMoveStep; end; //-------------- SetHasLabels --------------------- procedure TkpPipeline.SetHasLabels(NewHasLabels: Boolean); begin if FHasLabels = NewHasLabels then Exit; FHasLabels := NewHasLabels; RedrawAll; end; //-------------- FontChanged ------------------ procedure TkpPipeline.FontChanged(Sender: TObject); begin if HasLabels then RedrawAll; end; {--------------------------------------------------------- REGISTER ----------------------------------------------------------} procedure Register; begin RegisterComponents('KP', [TkpPipeline]); end; end.
{ This sample shows how not only to localize user interface but database too. The sample also shows how to show only those rows that belong to the active language. } unit Unit1; interface uses Classes, Controls, Menus, Grids, DB, DBGrids, ADODB, Forms; type TMainForm = class(TForm) MainMenu: TMainMenu; DatabaseMenu: TMenuItem; OpenMenu: TMenuItem; CloseMenu: TMenuItem; N1: TMenuItem; LanguageMenu: TMenuItem; N2: TMenuItem; ExitMenu: TMenuItem; HelpMenu: TMenuItem; AboutMenu: TMenuItem; DBGrid1: TDBGrid; Connection1: TADOConnection; Query1: TADOQuery; DataSource1: TDataSource; procedure FormShow(Sender: TObject); procedure DatabaseMenuClick(Sender: TObject); procedure OpenMenuClick(Sender: TObject); procedure CloseMenuClick(Sender: TObject); procedure LanguageMenuClick(Sender: TObject); procedure ExitMenuClick(Sender: TObject); procedure AboutMenuClick(Sender: TObject); private procedure UpdateItems; end; var MainForm: TMainForm; implementation {$R *.DFM} uses SysUtils, Dialogs, NtBase, NtDatabaseUtils, NtLanguageDlg, NtLocalization, NtBaseTranslator, NtTranslator; procedure TMainForm.UpdateItems; function GetLanguageCode: String; begin if LoadedResourceLocale = '' then Result := 'en' else Result := TNtLocale.LocaleToIso639(TNtLocale.ExtensionToLocale(LoadedResourceLocale)); end; resourcestring SName = 'Name'; SFieldplayers = 'Fieldplayers'; SGoalie = 'Goalie'; SOrigin = 'Origin'; SDescription = 'Description'; begin Connection1.Connected := True; Query1.Close; Query1.SQL.Text := Format('SELECT * FROM Sport WHERE Lang=''%s''', [GetLanguageCode]); Query1.Open; TNtDatabaseUtils.HideField(Query1, 'Id'); TNtDatabaseUtils.HideField(Query1, 'Lang'); TNtDatabaseUtils.ShowField(Query1, 'Name', SName, 15); TNtDatabaseUtils.ShowField(Query1, 'Fieldplayers', SFieldplayers); TNtDatabaseUtils.ShowField(Query1, 'Goalie', SGoalie); TNtDatabaseUtils.ShowField(Query1, 'Origin', SOrigin, 15); TNtDatabaseUtils.ShowField(Query1, 'Description', SDescription, 100); DataSource1.DataSet := Query1; end; procedure TMainForm.FormShow(Sender: TObject); begin OpenMenuClick(Self); end; procedure TMainForm.DatabaseMenuClick(Sender: TObject); begin OpenMenu.Enabled := not Query1.Active; CloseMenu.Enabled := Query1.Active; end; procedure TMainForm.OpenMenuClick(Sender: TObject); begin UpdateItems; end; procedure TMainForm.CloseMenuClick(Sender: TObject); begin Query1.Close; end; procedure TMainForm.LanguageMenuClick(Sender: TObject); begin if TNtLanguageDialog.Select('en', '', lnNative, [ldShowErrorIfNoDll], [roSaveLocale]) then UpdateItems; end; procedure TMainForm.ExitMenuClick(Sender: TObject); begin Close; end; procedure TMainForm.AboutMenuClick(Sender: TObject); resourcestring SAboutMessage = 'This application shows how to localize database content.'; begin ShowMessage(SAboutMessage); end; initialization NtEnabledProperties := STRING_TYPES; end.
unit ExtUxLayout; // Generated by ExtToPascal v.0.9.8, at 7/1/2010 09:28:02 // from "C:\Trabalho\ext-3.0.0\docs\output" detected as ExtJS v.3 interface uses StrUtils, ExtPascal, ExtPascalUtils, ExtLayout, Ext; type TExtUxLayoutRowLayout = class; TExtUxLayoutCenterLayout = class; TExtUxLayoutRowLayout = class(TExtLayoutContainerLayout) private FEnableTabbing : Boolean; procedure SetFEnableTabbing(Value : Boolean); public function JSClassName : string; override; function SetActiveTab(Tab : string) : TExtFunction; overload; function SetActiveTab(Tab : TExtPanel) : TExtFunction; overload; property EnableTabbing : Boolean read FEnableTabbing write SetFEnableTabbing; end; TExtUxLayoutCenterLayout = class(TExtLayoutFitLayout) public function JSClassName : string; override; end; implementation procedure TExtUxLayoutRowLayout.SetFEnableTabbing(Value : Boolean); begin FEnableTabbing := Value; JSCode('enableTabbing:' + VarToJSON([Value])); end; function TExtUxLayoutRowLayout.JSClassName : string; begin Result := 'Ext.ux.layout.RowLayout'; end; function TExtUxLayoutRowLayout.SetActiveTab(Tab : string) : TExtFunction; begin JSCode(JSName + '.setActiveTab(' + VarToJSON([Tab]) + ');', 'TExtUxLayoutRowLayout'); Result := Self; end; function TExtUxLayoutRowLayout.SetActiveTab(Tab : TExtPanel) : TExtFunction; begin JSCode(JSName + '.setActiveTab(' + VarToJSON([Tab, false]) + ');', 'TExtUxLayoutRowLayout'); Result := Self; end; function TExtUxLayoutCenterLayout.JSClassName : string; begin Result := 'Ext.ux.layout.CenterLayout'; end; end.
unit NewsStoryU; interface uses Classes,sysutils,QuickRTTI,QRemote; type TClientNewsStory =class(TQRemoteObject) private fstory_id,ftitle,fbyline,fstory:STring; fcreated:Tdatetime; published property STORY_ID:STring read fstory_id write fstory_id; property CREATED:TDateTime read fcreated write fcreated; property TITLE:String read ftitle write ftitle; property BYLINE:STring read fbyline write fbyline; property STORY:String read fstory write fstory; end; TStoryList = class(TQRemoteObject) private fSTories:TStringlist; public constructor create (Service:STring);override; destructor destroy;override; published property Story_IDs:TStringlist read fstories write fstories; end; implementation constructor TStoryList.create (Service:STring); begin inherited create(service); fstories:=tstringlist.create; end; destructor TStoryList.destroy; begin try fstories.free; finally inherited destroy; end; end; end.
unit ChainsawData; { Data for Chainsaw. Written by Keith Wood (kbwood@iprimus.com.au) Version 1.0 - 19 September 2003. } interface uses SysUtils, Classes, DB, DBClient; type TdtmLogging = class(TDataModule) cdsLogging: TClientDataSet; cdsLoggingThreadId: TStringField; cdsLoggingTimestamp: TSQLTimeStampField; cdsLoggingElapsedTime: TIntegerField; cdsLoggingLevelName: TStringField; cdsLoggingLevelValue: TIntegerField; cdsLoggingLoggerName: TStringField; cdsLoggingMessage: TMemoField; cdsLoggingNDC: TStringField; cdsLoggingErrorMessage: TStringField; cdsLoggingErrorClass: TStringField; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure cdsLoggingMessageGetText(Sender: TField; var Text: String; DisplayText: Boolean); private FFieldMapping: TStringList; public property FieldMapping: TStringList read FFieldMapping; procedure AddLog(const Message, ThreadId: string; const Timestamp: TDateTime; const ElapsedTime: Integer; const LevelName: string; const LevelValue: Integer; const LoggerName, NDC, ErrorMessage, ErrorClass: string); procedure AddSort(const FieldName: string); procedure EmptyDataSet; end; var dtmLogging: TdtmLogging; implementation {$R *.dfm} { Initialisation - set field mappings both ways between field names and display labels. } procedure TdtmLogging.DataModuleCreate(Sender: TObject); var Index: Integer; Field: TField; begin FFieldMapping := TStringList.Create; for Index := 0 to cdsLogging.FieldCount - 1 do begin Field := cdsLogging.Fields[Index]; FFieldMapping.Values[Field.FieldName] := Field.DisplayLabel; FFieldMapping.Values[Field.DisplayLabel] := Field.FieldName; end; end; { Release resources. } procedure TdtmLogging.DataModuleDestroy(Sender: TObject); begin FFieldMapping.Free; end; { Add a logging event to the dataset. } procedure TdtmLogging.AddLog(const Message, ThreadId: string; const Timestamp: TDateTime; const ElapsedTime: Integer; const LevelName: string; const LevelValue: Integer; const LoggerName, NDC, ErrorMessage, ErrorClass: string); begin with cdsLogging do begin Insert; cdsLoggingMessage.AsString := Message; cdsLoggingThreadId.AsString := ThreadId; cdsLoggingTimestamp.AsDateTime := Timestamp; cdsLoggingElapsedTime.AsInteger := ElapsedTime; cdsLoggingLevelName.AsString := LevelName; cdsLoggingLevelValue.AsInteger := LevelValue; cdsLoggingLoggerName.AsString := LoggerName; cdsLoggingNDC.AsString := NDC; cdsLoggingErrorMessage.AsString := ErrorMessage; cdsLoggingErrorClass.AsString := ErrorClass; Post; end; end; { Add a field to the list of those used to sort the dataset (ascending only). } procedure TdtmLogging.AddSort(const FieldName: string); var FieldNames: string; Index: Integer; begin FieldNames := cdsLogging.IndexFieldNames; Index := Pos(FieldName, FieldNames); if Index > 0 then Delete(FieldNames, Index, Length(FieldName) + 1); FieldNames := FieldName + ';' + FieldNames; cdsLogging.IndexFieldNames := FieldNames; end; { Return the memo message field contents. } procedure TdtmLogging.cdsLoggingMessageGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin Text := Sender.AsString; end; { Remove all log events from the dataset. } procedure TdtmLogging.EmptyDataSet; begin cdsLogging.EmptyDataSet; end; end.
unit BVE.SVG2PathGeometry; //------------------------------------------------------------------------------ // // SVG Control Package 2.0 // Copyright (c) 2015 Bruno Verhue // //------------------------------------------------------------------------------ /// <summary> /// Unit containing pathe geometry classes. /// </summary> {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses System.SysUtils, System.Generics.Collections, BVE.SVG2Types, BVE.SVG2Intf, BVE.SVG2ParseUtility, BVE.SVG2PathData; type ISVGPathSegment = interface ['{CE946139-3E3E-42A7-A577-7E89D3218F54}'] function GetIsRelative: Boolean; procedure SetIsRelative(const Value: Boolean); property IsRelative: Boolean read GetIsRelative write SetIsRelative; end; ISVGLineSegment = interface(ISVGPathSegment) ['{F6574BFF-2D28-4782-B2A5-858FEC95F919}'] function GetPoint: TSVGPoint; procedure SetPoint(const Value: TSVGPoint); property Point: TSVGPoint read GetPoint write SetPoint; end; ISVGBezierSegment = interface(ISVGPathSegment) ['{B0AFA0DF-D2F8-4340-8F41-C8B8E0D91AB1}'] function GetPoint1: TSVGPoint; function GetPoint2: TSVGPoint; function GetPoint3: TSVGPoint; procedure SetPoint1(const Value: TSVGPoint); procedure SetPoint2(const Value: TSVGPoint); procedure SetPoint3(const Value: TSVGPoint); property Point1: TSVGPoint read GetPoint1 write SetPoint1; property Point2: TSVGPoint read GetPoint2 write SetPoint2; property Point3: TSVGPoint read GetPoint3 write SetPoint3; end; ISVGQuadSegment = interface(ISVGPathSegment) ['{FCA983E0-19A4-41FB-B394-BFF2467A2E63}'] function GetPoint1: TSVGPoint; function GetPoint2: TSVGPoint; procedure SetPoint1(const Value: TSVGPoint); procedure SetPoint2(const Value: TSVGPoint); property Point1: TSVGPoint read GetPoint1 write SetPoint1; property Point2: TSVGPoint read GetPoint2 write SetPoint2; end; ISVGArcSegment = interface(ISVGPathSegment) ['{3AB2BA25-A8EA-483D-8D7E-2B83D75B4A8F}'] function GetIsLargeArc: Boolean; function GetPoint: TSVGPoint; function GetRotationAngle: TSVGFloat; function GetRadius: TSVGPoint; function GetSweepDirection: Boolean; procedure SetIsLargeArc(const Value: Boolean); procedure SetPoint(const Value: TSVGPoint); procedure SetRotationAngle(const Value: TSVGFloat); procedure SetRadius(const Value: TSVGPoint); procedure SetSweepDirection(const Value: Boolean); property IsLargeArc: Boolean read GetIsLargeArc write SetIsLargeArc; property Point: TSVGPoint read GetPoint write SetPoint; property RotationAngle: TSVGFloat read GetRotationAngle write SetRotationAngle; property Radius: TSVGPoint read GetRadius write SetRadius; property SweepDirection: Boolean read GetSweepDirection write SetSweepDirection; end; ISVGPathFigure = interface ['{26971FD4-190B-4A79-A060-046FF77D84EB}'] function GetIsClosed: Boolean; function GetSegments: TList<ISVGPathSegment>; function GetStartPoint: TSVGPoint; procedure SetIsClosed(const Value: Boolean); procedure SetStartPoint(const Value: TSVGPoint); procedure AddLine(const aPoint: TSVGPoint); procedure AddBezier(const aPoint1, aPoint2, aPoint3: TSVGPoint); procedure AddQuad(const aPoint1, aPoint2: TSVGPoint); procedure AddArc(const aRadius: TSVGPoint; const aAngle: TSVGFloat; const aLarge, aSweep: Boolean; const aPoint: TSVGPoint); property IsClosed: Boolean read GetIsClosed write SetIsClosed; property StartPoint: TSVGPoint read GetStartPoint write SetStartPoint; property Segments: TList<ISVGPathSegment> read GetSegments; end; ISVGPathGeometry = interface ['{44CD989C-3B9A-4212-86ED-D1ED0B9DEA24}'] function GetAsString: TSVGUnicodeString; function GetFigures: TList<ISVGPathFigure>; procedure SetAsString(const Value: TSVGUnicodeString); procedure ConvertToPathData(aSink: ISVGPathDataSink); property AsString: TSVGUnicodeString read GetAsString write SetAsString; property Figures: TList<ISVGPathFigure> read GetFigures; end; TSVGPathSegment = class(TInterfacedObject, ISVGPathSegment) private FIsRelative: Boolean; protected function GetIsRelative: Boolean; procedure SetIsRelative(const Value: Boolean); public constructor Create; destructor Destroy; override; property IsRelative: Boolean read GetIsRelative write SetIsRelative; end; TSVGLineSegment = class(TSVGPathSegment, ISVGLineSegment) private FPoint: TSVGPoint; protected function GetPoint: TSVGPoint; procedure SetPoint(const Value: TSVGPoint); public constructor Create; destructor Destroy; override; property Point: TSVGPoint read GetPoint write SetPoint; end; TSVGBezierSegment = class(TSVGPathSegment, ISVGBezierSegment) private FPoint1: TSVGPoint; FPoint2: TSVGPoint; FPoint3: TSVGPoint; protected function GetPoint1: TSVGPoint; function GetPoint2: TSVGPoint; function GetPoint3: TSVGPoint; procedure SetPoint1(const Value: TSVGPoint); procedure SetPoint2(const Value: TSVGPoint); procedure SetPoint3(const Value: TSVGPoint); public constructor Create; destructor Destroy; override; property Point1: TSVGPoint read GetPoint1 write SetPoint1; property Point2: TSVGPoint read GetPoint2 write SetPoint2; property Point3: TSVGPoint read GetPoint3 write SetPoint3; end; TSVGQuadSegment = class(TSVGPathSegment, ISVGQuadSegment) private FPoint1: TSVGPoint; FPoint2: TSVGPoint; protected function GetPoint1: TSVGPoint; function GetPoint2: TSVGPoint; procedure SetPoint1(const Value: TSVGPoint); procedure SetPoint2(const Value: TSVGPoint); public constructor Create; destructor Destroy; override; property Point1: TSVGPoint read GetPoint1 write SetPoint1; property Point2: TSVGPoint read GetPoint2 write SetPoint2; end; TSVGArcSegment = class(TSVGPathSegment, ISVGArcSegment) private FIsLargeArc: Boolean; FPoint: TSVGPoint; FRotationAngle: TSVGFloat; FRadius: TSVGPoint; FSweepDirection: Boolean; protected function GetIsLargeArc: Boolean; function GetPoint: TSVGPoint; function GetRotationAngle: TSVGFloat; function GetRadius: TSVGPoint; function GetSweepDirection: Boolean; procedure SetIsLargeArc(const Value: Boolean); procedure SetPoint(const Value: TSVGPoint); procedure SetRotationAngle(const Value: TSVGFloat); procedure SetRadius(const Value: TSVGPoint); procedure SetSweepDirection(const Value: Boolean); public constructor Create; destructor Destroy; override; property IsLargeArc: Boolean read GetIsLargeArc write SetIsLargeArc; property Point: TSVGPoint read GetPoint write SetPoint; property RotationAngle: TSVGFloat read GetRotationAngle write SetRotationAngle; property Raidus: TSVGPoint read GetRadius write SetRadius; property SweepDirection: Boolean read GetSweepDirection write SetSweepDirection; end; TSVGPathFigure = class(TInterfacedObject, ISVGPathFigure) private FSegments: TList<ISVGPathSegment>; FStartPoint: TSVGPoint; FIsClosed: Boolean; protected function GetIsClosed: Boolean; function GetSegments: TList<ISVGPathSegment>; function GetStartPoint: TSVGPoint; procedure SetIsClosed(const Value: Boolean); procedure SetStartPoint(const Value: TSVGPoint); public constructor Create; destructor Destroy; override; procedure AddLine(const aPoint: TSVGPoint); procedure AddBezier(const aPoint1, aPoint2, aPoint3: TSVGPoint); procedure AddQuad(const aPoint1, aPoint2: TSVGPoint); procedure AddArc(const aRadius: TSVGPoint; const aAngle: TSVGFloat; const aLarge, aSweep: Boolean; const aPoint: TSVGPoint); property IsClosed: Boolean read GetIsClosed write SetIsClosed; property StartPoint: TSVGPoint read GetStartPoint write SetStartPoint; property Segments: TList<ISVGPathSegment> read GetSegments; end; TSVGPathGeometry = class(TInterfacedObject, ISVGPathGeometry, ISVGPathDataSink) private FFigures: TList<ISVGPathFigure>; function GetLastFigure: ISVGPathFigure; protected function GetAsString: TSVGUnicodeString; function GetFigures: TList<ISVGPathFigure>; procedure SetAsString(const Value: TSVGUnicodeString); property LastFigure: ISVGPathFigure read GetLastFigure; public constructor Create; destructor Destroy; override; procedure BeginFigure; procedure EndFigure; procedure MoveTo(const aP: TSVGPoint); procedure CurveTo(const aCP1, aCP2, aP2: TSVGPoint); procedure LineTo(const aP: TSVGPoint); procedure ClosePath(const aClosed: Boolean); procedure AddQuadCurve(const aP1, aCP, aP2: TSVGPoint); procedure AddArc(const aP1, aRadius: TSVGPoint; aAngle: TSVGFloat; const aLargeFlag, aSweepFlag: Boolean; const aP2: TSVGPoint); procedure ConvertToPathData(aSink: ISVGPathDataSink); property Figures: TList<ISVGPathFigure> read GetFigures; property AsString: TSVGUnicodeString read GetAsString write SetAsString; end; implementation { TSVGPathSegment } constructor TSVGPathSegment.Create; begin inherited Create; FIsRelative := False; end; destructor TSVGPathSegment.Destroy; begin inherited; end; function TSVGPathSegment.GetIsRelative: Boolean; begin Result := FIsRelative; end; procedure TSVGPathSegment.SetIsRelative(const Value: Boolean); begin if FIsRelative <> Value then begin FIsRelative := Value; end; end; { TSVGLineSegment } constructor TSVGLineSegment.Create; begin inherited Create; FPoint := SVGPoint(0, 0); end; destructor TSVGLineSegment.Destroy; begin inherited; end; function TSVGLineSegment.GetPoint: TSVGPoint; begin Result := FPoint; end; procedure TSVGLineSegment.SetPoint(const Value: TSVGPoint); begin if Value <> FPoint then begin FPoint := Value; end; end; { TSVGBezierSegment } constructor TSVGBezierSegment.Create; begin inherited Create; FPoint1 := SVGPoint(0, 0); FPoint2 := SVGPoint(0, 0); FPoint3 := SVGPoint(0, 0); end; destructor TSVGBezierSegment.Destroy; begin inherited; end; function TSVGBezierSegment.GetPoint1: TSVGPoint; begin Result := FPoint1; end; function TSVGBezierSegment.GetPoint2: TSVGPoint; begin Result := FPoint2; end; function TSVGBezierSegment.GetPoint3: TSVGPoint; begin Result := FPoint3; end; procedure TSVGBezierSegment.SetPoint1(const Value: TSVGPoint); begin if Value <> FPoint1 then begin FPoint1 := Value; end; end; procedure TSVGBezierSegment.SetPoint2(const Value: TSVGPoint); begin if Value <> FPoint2 then begin FPoint2 := Value; end; end; procedure TSVGBezierSegment.SetPoint3(const Value: TSVGPoint); begin if Value <> FPoint3 then begin FPoint3 := Value; end; end; { TSVGQuadSegment } constructor TSVGQuadSegment.Create; begin inherited Create; FPoint1 := SVGPoint(0, 0); FPoint2 := SVGPoint(0, 0); end; destructor TSVGQuadSegment.Destroy; begin inherited; end; function TSVGQuadSegment.GetPoint1: TSVGPoint; begin Result := FPoint1; end; function TSVGQuadSegment.GetPoint2: TSVGPoint; begin Result := FPoint2; end; procedure TSVGQuadSegment.SetPoint1(const Value: TSVGPoint); begin if FPoint1 <> value then begin FPoint1 := Value; end; end; procedure TSVGQuadSegment.SetPoint2(const Value: TSVGPoint); begin if FPoint2 <> value then begin FPoint2 := Value; end; end; { TSVGArcSegment } constructor TSVGArcSegment.Create; begin inherited Create; FIsLargeArc := False; FPoint := SVGPoint(0, 0); FRotationAngle := 0; FRadius := SVGPoint(0, 0); FSweepDirection := False; end; destructor TSVGArcSegment.Destroy; begin inherited; end; function TSVGArcSegment.GetIsLargeArc: Boolean; begin Result := FIsLargeArc; end; function TSVGArcSegment.GetPoint: TSVGPoint; begin Result := FPoint; end; function TSVGArcSegment.GetRotationAngle: TSVGFloat; begin Result := FRotationAngle; end; function TSVGArcSegment.GetRadius: TSVGPoint; begin Result := FRadius; end; function TSVGArcSegment.GetSweepDirection: Boolean; begin Result := FSweepDirection; end; procedure TSVGArcSegment.SetIsLargeArc(const Value: Boolean); begin if FIsLargeArc <> Value then begin FIsLargeArc := Value; end; end; procedure TSVGArcSegment.SetPoint(const Value: TSVGPoint); begin if FPoint <> Value then begin FPoint := Value; end; end; procedure TSVGArcSegment.SetRotationAngle(const Value: TSVGFloat); begin if FRotationAngle <> Value then begin FRotationAngle := Value; end; end; procedure TSVGArcSegment.SetRadius(const Value: TSVGPoint); begin if FRadius <> Value then begin FRadius := Value; end; end; procedure TSVGArcSegment.SetSweepDirection(const Value: Boolean); begin if FSweepDirection <> Value then begin FSweepDirection := Value; end; end; { TSVGPathFigure } procedure TSVGPathFigure.AddArc(const aRadius: TSVGPoint; const aAngle: TSVGFloat; const aLarge, aSweep: Boolean; const aPoint: TSVGPoint); var ArcSegment: ISVGArcSegment; begin ArcSegment := TSVGArcSegment.Create; Segments.Add(ArcSegment); ArcSegment.Radius := aRadius; ArcSegment.RotationAngle := aAngle; ArcSegment.IsLargeArc := aLarge; ArcSegment.SweepDirection := aSweep; ArcSegment.Point := aPoint; end; procedure TSVGPathFigure.AddBezier(const aPoint1, aPoint2, aPoint3: TSVGPoint); var BezierSegment: ISVGBezierSegment; begin BezierSegment := TSVGBezierSegment.Create; Segments.Add(BezierSegment); BezierSegment.Point1 := aPoint1; BezierSegment.Point2 := aPoint2; BezierSegment.Point3 := aPoint3; end; procedure TSVGPathFigure.AddLine(const aPoint: TSVGPoint); var LineSegment: ISVGLineSegment; begin LineSegment := TSVGLineSegment.Create; Segments.Add(LineSegment); LineSegment.Point := aPoint; end; procedure TSVGPathFigure.AddQuad(const aPoint1, aPoint2: TSVGPoint); var QuadSegment: ISVGQuadSegment; begin QuadSegment := TSVGQuadSegment.Create; Segments.Add(QuadSegment); QuadSegment.Point1 := aPoint1; QuadSegment.Point2 := aPoint2; end; constructor TSVGPathFigure.Create; begin inherited Create; FSegments := TList<ISVGPathSegment>.Create; FStartPoint := SVGPoint(0, 0); FIsClosed := False; end; destructor TSVGPathFigure.Destroy; begin FSegments.Free; inherited; end; function TSVGPathFigure.GetIsClosed: Boolean; begin Result := FIsClosed; end; function TSVGPathFigure.GetSegments: TList<ISVGPathSegment>; begin Result := FSegments; end; function TSVGPathFigure.GetStartPoint: TSVGPoint; begin Result := FStartPoint; end; procedure TSVGPathFigure.SetIsClosed(const Value: Boolean); begin FIsClosed := Value; end; procedure TSVGPathFigure.SetStartPoint(const Value: TSVGPoint); begin if FStartPoint <> Value then begin FStartPoint := Value; end; end; { TSVGPathGeometry } procedure TSVGPathGeometry.AddArc(const aP1, aRadius: TSVGPoint; aAngle: TSVGFloat; const aLargeFlag, aSweepFlag: Boolean; const aP2: TSVGPoint); begin LastFigure.AddArc(aRadius, aAngle, aLargeFlag, aSweepFlag, aP2); end; procedure TSVGPathGeometry.AddQuadCurve(const aP1, aCP, aP2: TSVGPoint); begin LastFigure.AddQuad(aCP, aP2); end; procedure TSVGPathGeometry.BeginFigure; begin // end; procedure TSVGPathGeometry.ClosePath(const aClosed: Boolean); begin LastFigure.IsClosed := aClosed; end; procedure TSVGPathGeometry.ConvertToPathData(aSink: ISVGPathDataSink); var Figure: ISVGPathFigure; Segment: ISVGPathSegment; LineSegment: ISVGLineSegment; BezierSegment: ISVGBezierSegment; QuadSegment: ISVGQuadSegment; ArcSegment: ISVGArcSegment; LastPoint: TSVGPoint; begin aSink.BeginFigure; try for Figure in FFigures do begin LastPoint := Figure.StartPoint; aSink.MoveTo(LastPoint); for Segment in Figure.Segments do begin if Supports(Segment, ISVGLineSegment, LineSegment) then begin LastPoint := LineSegment.Point; aSink.LineTo(LastPoint); end else if Supports(Segment, ISVGBezierSegment, BezierSegment) then begin LastPoint := BezierSegment.Point3; aSink.CurveTo( BezierSegment.Point1, BezierSegment.Point2, LastPoint); end else if Supports(Segment, ISVGQuadSegment, QuadSegment) then begin aSink.AddQuadCurve(LastPoint, QuadSegment.Point1, QuadSegment.Point2); LastPoint := QuadSegment.Point2; end else if Supports(Segment, ISVGArcSegment, ArcSegment) then begin aSink.AddArc( LastPoint, ArcSegment.Radius, ArcSegment.RotationAngle, ArcSegment.IsLargeArc, ArcSegment.SweepDirection, ArcSegment.Point); LastPoint := ArcSegment.Point; end; end; aSink.ClosePath(Figure.IsClosed); end; finally aSink.EndFigure; end; end; constructor TSVGPathGeometry.Create; begin inherited Create; FFigures := TList<ISVGPathFigure>.Create; end; procedure TSVGPathGeometry.CurveTo(const aCP1, aCP2, aP2: TSVGPoint); begin LastFigure.AddBezier(aCP1, aCP2, aP2); end; destructor TSVGPathGeometry.Destroy; begin FFigures.Free; inherited; end; procedure TSVGPathGeometry.EndFigure; begin // end; function TSVGPathGeometry.GetAsString: TSVGUnicodeString; var Figure: ISVGPathFigure; Segment: ISVGPathSegment; LineSegment: ISVGLineSegment; BezierSegment: ISVGBezierSegment; QuadSegment: ISVGQuadSegment; ArcSegment: ISVGArcSegment; StringBuilder: TBaseStringBuilder; Cmd, LastCmd: TSVGUnicodeChar; begin Result := ''; StringBuilder := TBaseStringBuilder.Create; try for Figure in FFigures do begin LastCmd := 'L'; StringBuilder.Append(Format('%s%g,%g', ['M', Figure.StartPoint.X, Figure.StartPoint.Y], USFormatSettings)); for Segment in Figure.Segments do begin if Supports(Segment, ISVGLineSegment, LineSegment) then begin StringBuilder.Append(' '); if LineSegment.IsRelative then Cmd := 'l' else Cmd := 'L'; if Cmd <> LastCmd then StringBuilder.Append(Cmd); LastCmd := Cmd; StringBuilder.Append(Format('%g,%g', [LineSegment.Point.X, LineSegment.Point.Y], USFormatSettings)); end else if Supports(Segment, ISVGBezierSegment, BezierSegment) then begin StringBuilder.Append(' '); if BezierSegment.IsRelative then Cmd := 'c' else Cmd := 'C'; if Cmd <> LastCmd then StringBuilder.Append(Cmd); LastCmd := Cmd; StringBuilder.Append(Format('%g,%g %g,%g %g,%g', [BezierSegment.Point1.X, BezierSegment.Point1.Y, BezierSegment.Point2.X, BezierSegment.Point2.Y, BezierSegment.Point3.X, BezierSegment.Point3.Y], USFormatSettings)); end else if Supports(Segment, ISVGQuadSegment, QuadSegment) then begin StringBuilder.Append(' '); if QuadSegment.IsRelative then Cmd := 'q' else Cmd := 'Q'; if Cmd <> LastCmd then StringBuilder.Append(Cmd); LastCmd := Cmd; StringBuilder.Append(Format('%g,%g %g,%g', [QuadSegment.Point1.X, QuadSegment.Point1.Y, QuadSegment.Point2.X, QuadSegment.Point2.Y], USFormatSettings)); end else if Supports(Segment, ISVGArcSegment, ArcSegment) then begin StringBuilder.Append(' '); if QuadSegment.IsRelative then Cmd := 'a' else Cmd := 'A'; if Cmd <> LastCmd then StringBuilder.Append(Cmd); LastCmd := Cmd; StringBuilder.Append(Format('%g,%g %g %d %d %g,%g', [ArcSegment.Radius.X, ArcSegment.Radius.Y, ArcSegment.RotationAngle, Integer(ArcSegment.IsLargeArc), Integer(ArcSegment.SweepDirection), ArcSegment.Point.X, ArcSegment.Point.Y], USFormatSettings)); end; end; if Figure.IsClosed then begin StringBuilder.Append(' Z'); end; end; Result := StringBuilder.ToUnicodeString; finally StringBuilder.Free; end; end; function TSVGPathGeometry.GetFigures: TList<ISVGPathFigure>; begin Result := FFigures; end; function TSVGPathGeometry.GetLastFigure: ISVGPathFigure; begin if Figures.Count = 0 then raise Exception.Create('Geometry contains no figures.'); Result := Figures[Figures.Count - 1]; end; procedure TSVGPathGeometry.LineTo(const aP: TSVGPoint); begin LastFigure.AddLine(aP); end; procedure TSVGPathGeometry.MoveTo(const aP: TSVGPoint); var Figure: ISVGPathFigure; begin Figure := TSVGPathFigure.Create; Figures.Add(Figure); Figure.StartPoint := aP; end; procedure TSVGPathGeometry.SetAsString(const Value: TSVGUnicodeString); var Parser: TSVGPathStringParser; LastPoint: TSVGPoint; begin Parser := TSVGPathStringParser.Create(Value); try FFigures.Clear; LastPoint := SVGPoint(0, 0); Parser.ParsePath(Self, LastPoint); finally Parser.Free; end; end; end.
unit ThCellPanel; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThWebControl, ThTag, ThPanel; type TThCellPanel = class(TThCustomPanel) protected procedure AlignCells(inAlign: TAlign; inLevel: Integer; var ioRect: TRect); // procedure Notification(AComponent: TComponent; // Operation: TOperation); override; procedure Tag(inTag: TThTag); override; public constructor Create(inOwner: TComponent); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; published property Align; property DesignOpaque; property ShowGrid; property ShowOutline default true; property Style; property StyleClass; property Visible; end; implementation uses ThComponentIterator; { TThCellPanel } constructor TThCellPanel.Create(inOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; end; procedure TThCellPanel.Tag(inTag: TThTag); begin inherited; end; procedure AlignCell(inCtrl: TControl; var ioRect: TRect); begin with inCtrl do case Align of alTop: begin Left := ioRect.Left; Width := ioRect.Right; Top := ioRect.Top; Inc(ioRect.Top, Height); Dec(ioRect.Bottom, Height); end; // alBottom: begin Left := ioRect.Left; Width := ioRect.Right; Dec(ioRect.Bottom, Height); Top := ioRect.Top + ioRect.Bottom; end; // alLeft: begin Top := ioRect.Top; Height := ioRect.Bottom; Left := ioRect.Left; if (Width > ioRect.Right) then Width := ioRect.Right; Inc(ioRect.Left, Width); Dec(ioRect.Right, Width); end; // alRight: begin Top := ioRect.Top; Height := ioRect.Bottom; Dec(ioRect.Right, Width); if (Width > ioRect.Right) then Width := ioRect.Right; Left := ioRect.Left + ioRect.Right; end; end; end; procedure TThCellPanel.AlignCells(inAlign: TAlign; inLevel: Integer; var ioRect: TRect); begin with TThSortedCtrlIterator.Create(Self, inAlign) do try while Next([inAlign]) do if (Ctrl.Tag = inLevel) then AlignCell(Ctrl, ioRect); finally Free; end; end; procedure TThCellPanel.AlignControls(AControl: TControl; var Rect: TRect); var mn, mx: Integer; r: TRect; l: Integer; begin mn := 0; mx := 0; // with TThCtrlIterator.Create(Self) do try while Next do if (Ctrl.Tag < mn) then mn := Ctrl.Tag else if (Ctrl.Tag > mx) then mx := Ctrl.Tag; finally Free; end; // r := Rect; // for l := mn to mx do begin AlignCells(alTop, l, r); AlignCells(alBottom, l, r); AlignCells(alLeft, l, r); AlignCells(alRight, l, r); end; end; end.
unit ufrmPopupFamilyMember; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ExtCtrls, DateUtils, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, cxLabel; type TfrmPopupFamilyMember = class(TForm) pnl1: TPanel; pnl2: TPanel; lblClose: TcxLabel; pnl3: TPanel; lbl4: TLabel; lbl5: TLabel; edtMemberName: TEdit; edtCardNo: TEdit; lblEditFamily: TcxLabel; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; cxlvMaster: TcxGridLevel; cxGridViewColumn1: TcxGridDBColumn; cxGridViewColumn2: TcxGridDBColumn; cxGridViewColumn3: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure lblCloseClick(Sender: TObject); procedure lblEditFamilyClick(Sender: TObject); private dataFamily: TDataSet; procedure ParseHeaderGrid(jmlData: Integer); procedure ParseDataGrid(); public FSelfUnitID: Integer; { Public declarations } MemberID: Integer; end; var frmPopupFamilyMember: TfrmPopupFamilyMember; implementation uses ufrmDialogFamilyMember, uTSCommonDlg; {$R *.dfm} procedure TfrmPopupFamilyMember.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmPopupFamilyMember.FormDestroy(Sender: TObject); begin frmPopupFamilyMember := nil; end; procedure TfrmPopupFamilyMember.ParseDataGrid; var intI: Integer; // arrParam: TArr; begin {if not Assigned(MemberShip) then MemberShip := TMemberShip.Create; SetLength(arrParam,1); arrParam[0].tipe := ptInteger; arrParam[0].data := MemberID; dataFamily := MemberShip.GetListKeluargaMemberShip(arrParam); ParseHeaderGrid(dataFamily.RecordCount); if dataFamily.RecordCount > 0 then begin //initiate intI := 1; dataFamily.First; while not(dataFamily.Eof) do begin with strgGrid do begin Cells[0,intI] := dataFamily.FieldByName('MEMBERKLRG_STAKLRG_ID').AsString + '=' + dataFamily.FieldByName('STAKLRG_NAME').AsString; Cells[1,intI] := dataFamily.FieldByName('MEMBERKLRG_FULL_NAME').AsString; Cells[2,intI] := dataFamily.FieldByName('MEMBERKLRG_BIRTH_DATE').AsString; end; Inc(intI); dataFamily.Next; end; //while not eof end;// end if recordcount strgGrid.FixedRows := 1; strgGrid.AutoSize := true; } end; procedure TfrmPopupFamilyMember.ParseHeaderGrid(jmlData: Integer); begin { with strgGrid do begin Clear; ColCount := 3; RowCount := jmlData + 1; Cells[0,0] := 'STATUS DLM KELUARGA'; Cells[1,0] := 'NAMA LENGKAP'; Cells[2,0] := 'TANGGAL LAHIR'; if jmlData < 1 then begin RowCount := 2; Cells[0,1] := ''; Cells[1,1] := ''; Cells[2,1] := ''; end; FixedRows := 1; AutoSize := true; end; } end; procedure TfrmPopupFamilyMember.FormShow(Sender: TObject); begin ParseDataGrid; end; procedure TfrmPopupFamilyMember.lblCloseClick(Sender: TObject); begin Close; end; procedure TfrmPopupFamilyMember.lblEditFamilyClick(Sender: TObject); var countI: Integer; begin if not Assigned(frmDialogFamilyMember) then frmDialogFamilyMember := TfrmDialogFamilyMember.Create(Self); frmDialogFamilyMember.MemberID := MemberID; frmDialogFamilyMember.edtMemberName.Text := edtMemberName.Text; frmDialogFamilyMember.edtCardNo.Text := edtCardNo.Text; {frmDialogFamilyMember.strgGrid.RowCount := strgGrid.RowCount; if strgGrid.RowCount > 1 then for countI := 1 to strgGrid.RowCount-1 do begin frmDialogFamilyMember.strgGrid.Cells[0,countI] := strgGrid.Cells[0,countI]; frmDialogFamilyMember.strgGrid.Cells[1,countI] := strgGrid.Cells[1,countI]; frmDialogFamilyMember.strgGrid.Cells[2,countI] := strgGrid.Cells[2,countI]; end; } frmDialogFamilyMember.DialogUnit := FSelfUnitID; frmDialogFamilyMember.ShowModal; if frmDialogFamilyMember.IsProcessSuccessfull then begin CommonDlg.ShowConfirmSuccessfull(atEdit); ParseDataGrid; end; frmDialogFamilyMember.Free; end; end.
unit Rules; interface uses Kitto.Rules, Kitto.Store; type TDefaultPhaseStartTime = class(TKRuleImpl) public procedure NewRecord(const ARecord: TKRecord); override; end; implementation uses SysUtils, Variants, EF.Localization, Kitto.Metadata.DataView; { TDefaultPhaseStartTime } procedure TDefaultPhaseStartTime.NewRecord(const ARecord: TKRecord); var LLastDate: Variant; begin inherited; LLastDate := ARecord.Store.Max('END_DATE'); if VarIsNull(LLastDate) then ARecord.FieldByName('START_DATE').AsDate := Date else ARecord.FieldByName('START_DATE').AsDate := LLastDate + 1; end; initialization TKRuleImplRegistry.Instance.RegisterClass(TDefaultPhaseStartTime.GetClassId, TDefaultPhaseStartTime); finalization TKRuleImplRegistry.Instance.UnregisterClass(TDefaultPhaseStartTime.GetClassId); end.
// // Generated by JavaToPas v1.4 20140526 - 132719 //////////////////////////////////////////////////////////////////////////////// unit javax.xml.validation.SchemaFactory; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.xml.sax.ErrorHandler, org.w3c.dom.ls.LSResourceResolver, javax.xml.validation.Schema, javax.xml.transform.Source; type JSchemaFactory = interface; JSchemaFactoryClass = interface(JObjectClass) ['{16D27B75-B27E-4AAC-A0D1-D01BE6E414C5}'] function getErrorHandler : JErrorHandler; cdecl; // ()Lorg/xml/sax/ErrorHandler; A: $401 function getFeature(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1 function getProperty(&name : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $1 function getResourceResolver : JLSResourceResolver; cdecl; // ()Lorg/w3c/dom/ls/LSResourceResolver; A: $401 function isSchemaLanguageSupported(JStringparam0 : JString) : boolean; cdecl;// (Ljava/lang/String;)Z A: $401 function newInstance(schemaLanguage : JString) : JSchemaFactory; cdecl; overload;// (Ljava/lang/String;)Ljavax/xml/validation/SchemaFactory; A: $9 function newInstance(schemaLanguage : JString; factoryClassName : JString; classLoader : JClassLoader) : JSchemaFactory; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)Ljavax/xml/validation/SchemaFactory; A: $9 function newSchema : JSchema; cdecl; overload; // ()Ljavax/xml/validation/Schema; A: $401 function newSchema(TJavaArrayJSourceparam0 : TJavaArray<JSource>) : JSchema; cdecl; overload;// ([Ljavax/xml/transform/Source;)Ljavax/xml/validation/Schema; A: $401 function newSchema(schema : JFile) : JSchema; cdecl; overload; // (Ljava/io/File;)Ljavax/xml/validation/Schema; A: $1 function newSchema(schema : JSource) : JSchema; cdecl; overload; // (Ljavax/xml/transform/Source;)Ljavax/xml/validation/Schema; A: $1 function newSchema(schema : JURL) : JSchema; cdecl; overload; // (Ljava/net/URL;)Ljavax/xml/validation/Schema; A: $1 procedure setErrorHandler(JErrorHandlerparam0 : JErrorHandler) ; cdecl; // (Lorg/xml/sax/ErrorHandler;)V A: $401 procedure setFeature(&name : JString; value : boolean) ; cdecl; // (Ljava/lang/String;Z)V A: $1 procedure setProperty(&name : JString; &object : JObject) ; cdecl; // (Ljava/lang/String;Ljava/lang/Object;)V A: $1 procedure setResourceResolver(JLSResourceResolverparam0 : JLSResourceResolver) ; cdecl;// (Lorg/w3c/dom/ls/LSResourceResolver;)V A: $401 end; [JavaSignature('javax/xml/validation/SchemaFactory')] JSchemaFactory = interface(JObject) ['{783726CD-654E-4AAD-A023-9589A2B9980E}'] function getErrorHandler : JErrorHandler; cdecl; // ()Lorg/xml/sax/ErrorHandler; A: $401 function getFeature(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1 function getProperty(&name : JString) : JObject; cdecl; // (Ljava/lang/String;)Ljava/lang/Object; A: $1 function getResourceResolver : JLSResourceResolver; cdecl; // ()Lorg/w3c/dom/ls/LSResourceResolver; A: $401 function isSchemaLanguageSupported(JStringparam0 : JString) : boolean; cdecl;// (Ljava/lang/String;)Z A: $401 function newSchema : JSchema; cdecl; overload; // ()Ljavax/xml/validation/Schema; A: $401 function newSchema(TJavaArrayJSourceparam0 : TJavaArray<JSource>) : JSchema; cdecl; overload;// ([Ljavax/xml/transform/Source;)Ljavax/xml/validation/Schema; A: $401 function newSchema(schema : JFile) : JSchema; cdecl; overload; // (Ljava/io/File;)Ljavax/xml/validation/Schema; A: $1 function newSchema(schema : JSource) : JSchema; cdecl; overload; // (Ljavax/xml/transform/Source;)Ljavax/xml/validation/Schema; A: $1 function newSchema(schema : JURL) : JSchema; cdecl; overload; // (Ljava/net/URL;)Ljavax/xml/validation/Schema; A: $1 procedure setErrorHandler(JErrorHandlerparam0 : JErrorHandler) ; cdecl; // (Lorg/xml/sax/ErrorHandler;)V A: $401 procedure setFeature(&name : JString; value : boolean) ; cdecl; // (Ljava/lang/String;Z)V A: $1 procedure setProperty(&name : JString; &object : JObject) ; cdecl; // (Ljava/lang/String;Ljava/lang/Object;)V A: $1 procedure setResourceResolver(JLSResourceResolverparam0 : JLSResourceResolver) ; cdecl;// (Lorg/w3c/dom/ls/LSResourceResolver;)V A: $401 end; TJSchemaFactory = class(TJavaGenericImport<JSchemaFactoryClass, JSchemaFactory>) end; implementation end.
unit feli_storage; {$mode objfpc} interface uses feli_user, feli_event, fpjson; type FeliStorageAPI = class(TObject) private public // users class function getUser(usernameOrEmail: ansiString): FeliUser; class function getUsers(): FeliUserCollection; class procedure addUser(user: FeliUser); class procedure removeUser(usernameOrEmail: ansiString); class procedure setUsers(users: FeliUserCollection); class procedure setUser(user: FeliUser); // event class function getEvent(eventId: ansiString): FeliEvent; class function getEvents(): FeliEventCollection; class procedure addEvent(event: FeliEvent); class procedure removeEvent(eventId: ansiString); class procedure setEvents(events: FeliEventCollection); class procedure setEvent(event: FeliEvent); // DEBUG class procedure debug(); static; end; implementation uses feli_logger, feli_file, feli_constants, feli_exceptions, feli_operators, feli_collection, feli_stack_tracer, jsonparser, sysutils; class function FeliStorageAPI.getUser(usernameOrEmail: ansiString): FeliUser; var userObject: TJsonObject; users, filteredUsers, filteredUsersTemp: FeliUserCollection; tempCollection: FeliCollection; begin FeliStackTrace.trace('begin', 'class function FeliStorageAPI.getUser(usernameOrEmail: ansiString): FeliUser;'); result := nil; users := FeliStorageAPI.getUsers(); tempCollection := users.where(FeliUserKeys.username, FeliOperators.equalsTo, usernameOrEmail); filteredUsers := FeliUserCollection.fromFeliCollection(tempCollection); tempCollection := users.where(FeliUserKeys.email, FeliOperators.equalsTo, usernameOrEmail); filteredUsersTemp := FeliUserCollection.fromFeliCollection(tempCollection); filteredUsers.join(filteredUsersTemp); if (filteredUsers.length() <= 0) then result := nil else begin if (filteredUsers.length() > 1) then FeliLogger.warn(format('There are multiple entries for user %s, fallback to using the first user found', [usernameOrEmail])); userObject := filteredUsers.toTJsonArray()[0] as TJsonObject; result := FeliUser.fromTJsonObject(userObject); end; FeliStackTrace.trace('end', 'class function FeliStorageAPI.getUser(usernameOrEmail: ansiString): FeliUser;'); end; class function FeliStorageAPI.getUsers(): FeliUserCollection; var usersJsonArray: TJsonArray; tempCollection: FeliCollection; begin FeliStackTrace.trace('begin', 'class function FeliStorageAPI.getUsers(): FeliUserCollection;'); usersJsonArray := FeliFileAPI.getJsonArray(usersFilePath); tempCollection := FeliUserCollection.fromTJsonArray(usersJsonArray); result := FeliUserCollection.fromFeliCollection(tempCollection); FeliStackTrace.trace('end', 'class function FeliStorageAPI.getUsers(): FeliUserCollection;'); end; class procedure FeliStorageAPI.addUser(user: FeliUser); var users: FeliUserCollection; begin FeliStackTrace.trace('begin', 'class procedure FeliStorageAPI.addUser(user: FeliUser);'); if (FeliStorageAPI.getUser(user.username) <> nil) or (FeliStorageAPI.getUser(user.email) <> nil) then begin raise FeliExceptions.FeliStorageUserExist.Create('User already exist'); end else begin users := FeliStorageAPI.getUsers(); users.add(user); FeliStorageAPI.setUsers(users); end; FeliStackTrace.trace('end', 'class procedure FeliStorageAPI.addUser(user: FeliUser);'); end; class procedure FeliStorageAPI.setUsers(users: FeliUserCollection); begin FeliStackTrace.trace('begin', 'class procedure FeliStorageAPI.setUsers(users: FeliUserCollection);'); FeliFileAPI.put(usersFilePath, users.toJson()); // Error FeliStackTrace.trace('end', 'class procedure FeliStorageAPI.setUsers(users: FeliUserCollection);'); end; class procedure FeliStorageAPI.setUser(user: FeliUser); begin FeliStorageAPI.removeUser(user.username); FeliStorageAPI.addUser(user); end; class procedure FeliStorageAPI.removeUser(usernameOrEmail: ansiString); var users: FeliUserCollection; tempCollection: FeliCollection; oldLength: int64; begin FeliStackTrace.trace('begin', 'class procedure FeliStorageAPI.removeUser(usernameOrEmail: ansiString);'); users := FeliStorageAPI.getUsers(); oldLength := users.length(); tempCollection := users.where(FeliUserKeys.username, FeliOperators.notEqualsTo, usernameOrEmail); users := FeliUserCollection.fromFeliCollection(tempCollection); tempCollection := users.where(FeliUserKeys.email, FeliOperators.notEqualsTo, usernameOrEmail); users := FeliUserCollection.fromFeliCollection(tempCollection); if (users.length() = oldLength) then FeliLogger.error(format('User %s was not found, ergo unable to remove %s', [usernameOrEmail, usernameOrEmail])) else FeliLogger.info(format('User %s removed successfully', [usernameOrEmail])); FeliStorageAPI.setUsers(users); FeliStackTrace.trace('end', 'class procedure FeliStorageAPI.removeUser(usernameOrEmail: ansiString);'); end; class function FeliStorageAPI.getEvent(eventId: ansiString): FeliEvent; var eventObject: TJsonObject; events, filteredEvents: FeliEventCollection; tempCollection: FeliCollection; begin result := nil; events := FeliStorageAPI.getEvents(); tempCollection := events.where(FeliEventKeys.id, FeliOperators.equalsTo, eventId); filteredEvents := FeliEventCollection.fromFeliCollection(tempCollection); if (filteredEvents.length() <= 0) then result := nil else begin if (filteredEvents.length() > 1) then FeliLogger.warn(format('There are multiple entries for event %s, fallback to using the first event found', [eventId])); eventObject := filteredEvents.toTJsonArray()[0] as TJsonObject; result := FeliEvent.fromTJsonObject(eventObject); end; end; class function FeliStorageAPI.getEvents(): FeliEventCollection; var eventsJsonArray: TJsonArray; tempCollection: FeliCollection; begin eventsJsonArray := FeliFileAPI.getJsonArray(eventsFilePath); tempCollection := FeliEventCollection.fromTJsonArray(eventsJsonArray); result := FeliEventCollection.fromFeliCollection(tempCollection); end; class procedure FeliStorageAPI.addEvent(event: FeliEvent); var events: FeliEventCollection; begin if (FeliStorageAPI.getEvent(event.id) <> nil) then begin raise FeliExceptions.FeliStorageEventExist.create(format('Event already exist %s', [event.id])); end else begin if (event.id = '') then event.generateId(); events := FeliStorageAPI.getEvents(); events.add(event); FeliStorageAPI.setEvents(events); end; end; class procedure FeliStorageAPI.removeEvent(eventId: ansiString); var events: FeliEventCollection; oldLength: int64; tempCollection: FeliCollection; begin events := FeliStorageAPI.getEvents(); oldLength := events.length(); tempCollection := events.where(FeliEventKeys.id, FeliOperators.notEqualsTo, eventId); events := FeliEventCollection.fromFeliCollection(tempCollection); if (events.length() = oldLength) then FeliLogger.error(format('Event %s was not found, ergo unable to remove %s', [eventId, eventId])) else FeliLogger.info(format('Event %s removed successfully', [eventId])); FeliStorageAPI.setEvents(events); end; class procedure FeliStorageAPI.setEvents(events: FeliEventCollection); begin FeliFileAPI.put(eventsFilePath, events.ToJson()); end; class procedure FeliStorageAPI.setEvent(event: FeliEvent); var events: FeliEventCollection; begin FeliStorageAPI.removeEvent(event.id); FeliStorageAPI.addEvent(event); end; class procedure FeliStorageAPI.debug(); static; begin FeliLogger.info(format('[FeliStorageAPI.debug] Events file using %s', [eventsFilePath])); FeliLogger.info(format('[FeliStorageAPI.debug] Users file using %s', [usersFilePath])); end; end.
unit structTypes; interface type Integer = Integer; Single = Single; IUnknown = interface ['{00000000-0000-0000-C000-000000000046}'] function func(): Single; virtual; procedure proc; virtual; end; TA = class FA: string; strict private FPrivate: TA; private strict protected FProtected: TA; protected public published property A: TA read FPrivate write FPrivate; end; TObserverMapping = class public const EditLinkID = 1; EditGridLinkID = 2; PositionLinkID = 3; MappedID = 100; private FMappings: TObserverMapping; class var FInstance: TObserverMapping; protected class function Instance: TObserverMapping; public constructor Create; destructor Destroy; override; class destructor Destroy; class function GetObserverID(const Key: Single): Integer; property DefProp[ind: Integer]: TA; default; end; CA = class of TA; PVec = ^TVec; TVec = packed record x, Y: Single; z: TA; end; TVarRec = packed record X, Y: Single; case Single of 0: (X, Y: Single); 1: (V: array[0..1] of Single) end; TBitRec = bitpacked record OneBit, a: 0..1; TwoBits: 0..3; FourBits: 0..15; EightBits: 0..255; end; TVarRec1 = record case tag: Single of 1: (a: Integer) end; TVarRec2 = record aa: Integer; private case aa: Single of 1: (aa: Integer); 0: ( X1, Y1: Single; case aa: Single of 0: (X, Y: Single) ) end; TOuter = record case Byte of 1: (inner: record f1: Byte; end); end; TArray = array[0..100] of TA; TArrayP = bitpacked array of PVec; PArrayP = ^TArrayP; TOSVersion = record public type TPlatform = (pfWindows, pfMacOS); private class var FPlatform: TPlatform; public class property Platform: TPlatform read FPlatform; end; implementation var vec: TVarRec2; a: tvarrec; o: TOuter; class function TObserverMapping.Instance: TObserverMapping; begin end; constructor TObserverMapping.Create; var structTypes: TVec; begin structTypes.x; end; class destructor TObserverMapping.Destroy; begin end; class function TObserverMapping.GetObserverID(const Key: Single): Integer; begin end; var vr2: TVarRec1; begin with a do begin v[0] := 1; v[1].<error descr="Undeclared identifier">X</error> := 0; end; with TVarRec2(a) do begin aa := 111; end; with a as TVarRec2 do aa := 111; with vec do Y := 1; vr2.tag := 1; o.inner; o.inner.f1; end.
unit NpPriceDocEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EditBase, VirtualTable, DB, MemDS, DBAccess, Ora, uOilQuery, StdCtrls, Buttons, ExtCtrls, Mask, ToolEdit, Grids, DBGridEh, Menus, PrihSop, NPTypeRef, GridsEh, DBGridEhGrouping, ComCtrls, ListSelect,uCommonForm, RXDBCtrl, DBCtrls; type TNpPriceDocEditForm = class(TEditBaseForm) vt: TVirtualTable; lblDateOn: TLabel; deDateOn: TDateEdit; sbDel: TSpeedButton; ds: TOraDataSource; Label1: TLabel; PageControl1: TPageControl; tsPrice: TTabSheet; tsState: TTabSheet; Grid: TDBGridEh; DBGridEh1: TDBGridEh; qOrderState: TOilQuery; dsOrderState: TOraDataSource; Label3: TLabel; edNum: TEdit; qOrderAzs: TOilQuery; tsAzs: TTabSheet; CheckBox1: TCheckBox; Label2: TLabel; cbMethod: TComboBox; cbEmp: TComboEdit; procedure sbDelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GridEditButtonClick(Sender: TObject); procedure GridKeyPress(Sender: TObject; var Key: Char); procedure PageControl1Change(Sender: TObject); procedure cbEmpButtonClick(Sender: TObject); protected DATE_ON: TDateTime; private FEmpId, FEmpInst: integer; LSF: TListSelectForm; function GetVisibleCod: TNpTypeCod; procedure SetVisibleCod(const Value: TNpTypeCod); public ListAzs, OperList: string; function GetOperList(): string; procedure Init; override; procedure Test; override; procedure Save; override; class function Edit(ADateOn:TDateTime; AInst: integer): Boolean; overload; property VisibleCod: TNpTypeCod read GetVisibleCod write SetVisibleCod; end; var NpPriceDocEditForm: TNpPriceDocEditForm; implementation uses Main, UDbFunc, EmpRef, ExFunc; {$R *.dfm} procedure TNpPriceDocEditForm.sbDelClick(Sender: TObject); begin inherited; if not vt.IsEmpty then vt.Delete; end; function TNpPriceDocEditForm.GetVisibleCod: TNpTypeCod; begin Result := CommonGetVisibleCod(Grid); end; procedure TNpPriceDocEditForm.Init; var qList:TOilQuery; begin inherited; if DATE_ON <> 0 then begin deDateOn.Date := DATE_ON; q.Close; _OpenQueryPar(q, ['inst', INST, 'date_on', DATE_ON]); vt.Assign(q); vt.Open; bbOk.Enabled := MAIN_ORG.Inst = INST; end else begin deDateOn.Date := Date(); q.Close; _OpenQueryPar(q, ['inst', 0, 'date_on', DATE_ON]); vt.Assign(q); vt.Open; end; CommonVisibleCodInit(Grid); cbEmp.Text:= vt.FieldByName('name_f').AsString; edNum.Text:= vt.FieldByName('numb').AsString; FEmpId:= vt.FieldByName('emp_id').AsInteger; FEmpInst:= vt.FieldByName('emp_inst').AsInteger; qOrderState.Filtered:=false; qOrderState.Filter:=' price_order_id = '+IntToStr(q.FieldByName('price_order_id').AsInteger); qOrderState.Filtered:=true; // Получить список АЗС (для хинта), по которым менялись цены qList:=TOilQuery.Create(self); qList.close; qList.sql.text:= 'select t.azs_id, tt.name from oil_price_order_azs t , v_oil_azs tt where t.State = ''Y'' and '+ ' t.azs_id = tt.id '; if not (vt.FieldByName('opo_id').AsString = '') then qList.Sql.Add(' and t.price_order_id = '+ vt.FieldByName('opo_id').AsString + ' and t.price_order_inst = '+ vt.FieldByName('opo_inst').AsString) else qList.Sql.Add(' and t.price_order_id = null '); qList.open; try qList.First; while not qList.Eof do begin ListAzs:= ListAzs + #13#10 + qList.FieldByName('name').AsString; if OperList <> '' then OperList := OperList +','+ qList.FieldByName('azs_id').AsString else OperList := qList.FieldByName('azs_id').AsString; qList.Next; end; finally qList.Free; end; PageControl1.Hint := ListAzs; end; procedure TNpPriceDocEditForm.Save; var IDdoc : integer; qAZS : TOilQuery; begin inherited; _ExecSql('update OIL_PRICE_ORDER set state = ''N'' ' + 'where id in (select t.price_order_id from OIL_NP_PRICE t ' + 'where t.date_on = :date_on and t.inst = :inst)', ['date_on', deDateOn.Date, 'inst', INST]); IDdoc:=DBSaver.SaveRecord('OIL_PRICE_ORDER', ['ID', GetNextId('OIL_PRICE_ORDER',['INST',INST]), 'INST', INST, 'STATE','Y', 'NUMB', edNum.Text, // vt.FieldByName('max_numb').AsString, 'EMP_ID', BoolTo_(FEmpId=0,null,FEmpId), 'EMP_INST',BoolTo_(FEmpInst=0,null,FEmpInst), 'VERIFIED', 1, 'APPLY_METHOD', 777, 'NOTICE_METHOD', 888 ]); _ExecSql('update OIL_NP_PRICE set state = ''N'' where date_on = :date_on and inst = :inst', ['date_on', deDateOn.Date, 'inst', INST]); vt.First; while not vt.Eof do begin DBSaver.SaveRecord('OIL_NP_PRICE', ['ID', GetNextId('OIL_NP_PRICE', ['DATE_ON', deDateOn.Date, 'INST',INST, 'ORG_ID', INST, 'ORG_INST', INST]), 'INST', INST, 'STATE','Y', 'ORG_ID', INST, 'ORG_INST', INST, 'NP_ID', vt.FieldByName('NP_TYPE_ID').AsInteger, 'DATE_ON', deDateOn.Date, 'PRICE', vt.FieldByName('PRICE').AsCurrency, 'PRICE_ORDER_ID', IdDoc, 'PRICE_ORDER_INST', INST ]); vt.Next; end; { // Создать запись состояния документа _ExecSql('update OIL_PRICE_ORDER_STATE set state = ''N'' where inst = :inst and PRICE_ORDER_ID = ' + IntToStr(IdDoc),['inst', INST]); DBSaver.SaveRecord('OIL_PRICE_ORDER_STATE', ['ID', GetNextId('OIL_PRICE_ORDER_STATE', ['PRICE_ORDER_ID', IdDoc ,'INST',INST]), // q.FieldByName('price_order_id').AsInteger 'INST', INST, 'STATE','Y', 'PRICE_ORDER_ID', IdDoc, 'PRICE_ORDER_INST', INST, 'STATE_ID', 290, 'DATE_OF', deDateOn.Date ]); } // Занести список АЗС OperList := GetOperList(); if not ((OperList = '') or (OperList = '()')) then begin _ExecSql('update OIL_PRICE_ORDER_AZS set state = ''N'' where PRICE_ORDER_ID = ' + IntToStr(IdDoc) + ' and inst = :inst', ['inst', INST]); qAZS:=TOilQuery.Create(self); try qAZS.close; qAZS.sql.text:=' select * from v_oil_azs where id in ' + OperList; qAZS.open; qAZS.first; while not qAZS.Eof do begin DBSaver.SaveRecord('OIL_PRICE_ORDER_AZS', ['ID', GetNextId('OIL_PRICE_ORDER_AZS', ['INST',INST]), 'INST', INST, 'STATE','Y', 'PRICE_ORDER_ID', IdDoc, 'PRICE_ORDER_INST', INST, 'AZS_ID', qAZS.FieldByName('ID').AsInteger, 'AZS_INST', qAZS.FieldByName('INST').AsInteger ]); qAZS.Next; end; finally qAZS.Free; end; end; end; procedure TNpPriceDocEditForm.SetVisibleCod(const Value: TNpTypeCod); begin CommonSetVisibleCod(Grid, Value); end; procedure TNpPriceDocEditForm.Test; var sl: TStringList; begin inherited; vt.DisableControls; sl := TStringList.Create; try vt.First; while not vt.Eof do begin if sl.Values[vt.FieldByName('np_type_id').AsString] = '1' then raise Exception.Create('Нельзя ввести в одном приказе один товар дважды!') else sl.Values[vt.FieldByName('np_type_id').AsString] := '1'; vt.Next; end; finally sl.Free; vt.EnableControls; end; if cbMethod.Text = '' then begin MessageDlg(TranslateText('Не определен метод проведения документа !'), mtError, [mbOk], 0); Exit; end; end; class function TNpPriceDocEditForm.Edit(ADateOn: TDateTime; AInst: integer): Boolean; var F: TNpPriceDocEditForm; begin F := Self.Create(Application); try F.DATE_ON := ADateOn; F.INST := AInst; F.Init; Result := F.ShowModal=mrOk; finally F.Free; end; end; procedure TNpPriceDocEditForm.FormCreate(Sender: TObject); begin inherited; qOrderState.Close; qOrderState.Open; PageControl1.ActivePage := tsPrice; FreeAndNil(LSF); end; procedure TNpPriceDocEditForm.GridEditButtonClick(Sender: TObject); var Table: TOraQuery; begin inherited; if Grid.SelectedField.FieldName = 'NP_NAME' then begin Table := TOraQuery.Create(nil); try if TNPTypeRefForm.Choose(Table) then begin if not (vt.State in [dsEdit,dsInsert]) then vt.Edit; vt.FieldByName('np_type_id').AsInteger := Table.FieldByName('id').AsInteger; vt.FieldByName('np_name').AsString := Table.FieldByName('name').AsString; vt.FieldByName('codavias').AsInteger := Table.FieldByName('codavias').AsInteger; vt.FieldByName('codoptima').AsInteger := Table.FieldByName('codoptima').AsInteger; vt.FieldByName('codint').AsInteger := Table.FieldByName('codint').AsInteger; end; finally Table.Free; end; end; end; procedure TNpPriceDocEditForm.GridKeyPress(Sender: TObject; var Key: Char); var Table: TOraQuery; begin inherited; if (Grid.SelectedField.FieldName = 'PRICE') then begin case key of '.', ',': key := DecimalSeparator; #13: begin vt.Append; Grid.SelectedField := vt.FieldByName(VISIBLE_COD_FIELDS[VisibleCod]); end; end; end else if (Key = #13) and (Grid.SelectedField.FieldName = VISIBLE_COD_FIELDS[VisibleCod]) then begin Table := TOraQuery.Create(nil); try if TNPTypeRefForm.Choose(vt.FieldByName(VISIBLE_COD_FIELDS[VisibleCod]).AsInteger, VisibleCod, Table) then begin if not (vt.State in [dsEdit,dsInsert]) then vt.Edit; vt.FieldByName('np_type_id').AsInteger := Table.FieldByName('id').AsInteger; vt.FieldByName('np_name').AsString := Table.FieldByName('name').AsString; vt.FieldByName('codavias').AsInteger := Table.FieldByName('codavias').AsInteger; vt.FieldByName('codoptima').AsInteger := Table.FieldByName('codoptima').AsInteger; vt.FieldByName('codint').AsInteger := Table.FieldByName('codint').AsInteger; Grid.SelectedField := vt.FieldByName('price'); end; finally Table.Free; end; end; end; procedure TNpPriceDocEditForm.PageControl1Change(Sender: TObject); begin inherited; if PageControl1.ActivePage = tsPrice then sbDel.Enabled:=True else sbDel.Enabled:=False; if (PageControl1.ActivePage = tsAzs) and (LSF = nil) then begin LSF := TListSelectForm.Create(tsAzs); LSF.Parent := tsAzs; Lsf.TableName:='v_oil_azs'; Lsf.AddCondition := 'obl_id = ov.getval(''INST'')'; LSF.WindowState := wsMaximized; LSF.BorderStyle := bsNone; LSF.Anchors := [akLeft, akTop, akRight, akBottom]; LSF.Position := poDefault; LSF.List := OperList; Lsf.OKBtn.Visible := false; Lsf.CancelBtn.Visible := false; LSF.Show; end; end; function TNpPriceDocEditForm.GetOperList(): string; begin result := ''; if LSF <> nil then begin LSF.OKBtnClick(nil); result := LSF.List; end; end; procedure TNpPriceDocEditForm.cbEmpButtonClick(Sender: TObject); var Emp: TEmpRefForm; begin Emp := TEmpRefForm.Create(Application); try Emp.ShowModal; if Emp.ModalResult = mrOk then if not Emp.q.eof then begin FEmpId := Emp.q.fieldbyname('id').AsInteger; FEmpInst := Emp.q.fieldbyname('inst').AsInteger; cbEmp.Text := Emp.q.FieldByName('F_name').AsString + ' ' + Emp.q.FieldByName('I_name').AsString + ' ' + Emp.q.FieldByName('O_name').AsString; end; finally Emp.Free; end; end; end.
unit Binac1; {Versions Delphi} INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses classes, sysutils, util1,Gdos,Ncdef2; procedure proReset(numF:integer;st:AnsiString);pascal; procedure proRewrite(numF:integer;st:AnsiString);pascal; procedure proBlockread(numF:integer;var x;taille:integer;tpn:word;var res:integer);pascal; procedure proBlockwrite(numF:integer;var x;taille:integer;tpn:word);pascal; procedure proClose(numF:integer);pascal; procedure proSeek(numF:integer;n:longint);pascal; function fonctionFileSize(numF:integer):longint;pascal; procedure proBlockreadReal(numF:integer;var x;taille:integer;tpn:word;var res:integer);pascal; procedure proBlockwriteReal(numF:integer;var x;taille:integer;tpn:word);pascal; IMPLEMENTATION const maxFichierPg=20; var fichierBin:array[1..maxFichierPg] of TfileStream; procedure open(numF:integer;st:AnsiString;Vreset:boolean); begin if (numF<1) or (numF>maxFichierPg) then sortieErreur(E_NumFichier); if st='' then sortieErreur(E_NomDeFichierIncorrect); fichierBin[numF].Free; fichierBin[numF]:=nil; try if Vreset then fichierBin[numF]:=TfileStream.create(st,fmOpenReadWrite) else fichierBin[numF]:=TfileStream.create(st,fmCreate); except fichierBin[numF]:=nil; sortieErreur('Error opening '+st); end; end; procedure proReset(numF:integer;st:AnsiString); begin open(numF,st,true); end; procedure proRewrite(numF:integer;st:AnsiString); begin open(numF,st,false); end; procedure controleF(numF:integer); begin if (numF<1) or (numF>maxFichierPg) then sortieErreur(E_NumFichier); if fichierBin[numF]=nil then sortieErreur('File not open'); end; procedure proBlockwrite(numF:integer;var x;taille:integer;tpn:word); begin controleF(numF); try fichierBin[numF].Write(x,taille); except sortieErreur('BlockWrite Error'); end; end; procedure proBlockread(numF:integer;var x;taille:integer;tpn:word;var res:integer); begin controleF(numF); try fichierBin[numF].read(x,taille); except sortieErreur('BlockRead error'); end; end; procedure proClose(numF:integer); begin controleF(numF); fichierBin[numF].Free; fichierBin[numF]:=nil; end; procedure proSeek(numF:integer;n:longint); begin controleF(numF); try fichierBin[numF].Position:=n; except sortieErreur('Seek error'); end; end; function fonctionFileSize(numF:integer):longint; begin controleF(numF); try result:= fichierBin[numF].Size; except sortieErreur('FileSize error'); end; end; procedure proBlockreadReal(numF:integer;var x;taille:integer;tpn:word;var res:integer); var buf:typeTabFloat1 ABSOLUTE x; y:single; i:integer; begin controleF(numF); with fichierBin[numF] do begin for i:=1 to taille div 10 do if read(y,4)=4 then buf[i]:=y;; end; end; procedure proBlockwriteReal(numF:integer;var x;taille:integer;tpn:word); var buf:typeTabFloat1 ABSOLUTE x; y:single; i:integer; begin controleF(numF); with fichierBin[numF] do begin for i:=1 to taille div 10 do begin y:=buf[i]; write(y,4); end; end; end; end.
(* Weak enemy with simple AI, no pathfinding *) unit cave_rat; {$mode objfpc}{$H+} interface uses SysUtils, Math, map; (* Create a cave rat *) procedure createCaveRat(uniqueid, npcx, npcy: smallint); (* Take a turn *) procedure takeTurn(id, spx, spy: smallint); (* Move in a random direction *) procedure wander(id, spx, spy: smallint); (* Chase the player *) procedure chasePlayer(id, spx, spy: smallint); (* Check if player is next to NPC *) function isNextToPlayer(spx, spy: smallint): boolean; (* Run from player *) procedure escapePlayer(id, spx, spy: smallint); (* Combat *) procedure combat(id: smallint); implementation uses entities, globalutils, ui, los; procedure createCaveRat(uniqueid, npcx, npcy: smallint); begin // Add a cave rat to the list of creatures entities.listLength := length(entities.entityList); SetLength(entities.entityList, entities.listLength + 1); with entities.entityList[entities.listLength] do begin npcID := uniqueid; race := 'cave rat'; description := 'a large rat'; glyph := 'r'; maxHP := randomRange(4, 6); currentHP := maxHP; attack := randomRange(entityList[0].attack - 2, entityList[0].attack + 3); defense := randomRange(entityList[0].defense - 2, entityList[0].defense + 2); weaponDice := 0; weaponAdds := 0; xpReward := maxHP; visionRange := 4; NPCsize := 1; trackingTurns := 0; moveCount := 0; targetX := 0; targetY := 0; inView := False; blocks := False; discovered := False; weaponEquipped := False; armourEquipped := False; isDead := False; abilityTriggered := False; stsDrunk := False; stsPoison := False; tmrDrunk := 0; tmrPoison := 0; posX := npcx; posY := npcy; end; (* Occupy tile *) map.occupy(npcx, npcy); end; procedure takeTurn(id, spx, spy: smallint); begin (* Can the NPC see the player *) if (los.inView(spx, spy, entities.entityList[0].posX, entities.entityList[0].posY, entities.entityList[id].visionRange) = True) then begin (* If NPC has low health... *) if (entities.entityList[id].currentHP < 3) then begin (* and they're adjacent to the player, they run *) if (isNextToPlayer(spx, spy) = True) then escapePlayer(id, spx, spy) else (* if not near the player, heal *) begin if (entityList[id].currentHP < entityList[id].maxHP) then Inc(entityList[id].currentHP) else wander(id, spx, spy); end; end else (* if they are next to player, and not low on health, they attack *) chasePlayer(id, spx, spy); end (* Cannot see the player *) else wander(id, spx, spy); end; procedure wander(id, spx, spy: smallint); var direction, attempts, testx, testy: smallint; begin attempts := 0; testx := 0; testy := 0; direction := 0; repeat // Reset values after each failed loop so they don't keep dec/incrementing testx := spx; testy := spy; direction := random(6); // limit the number of attempts to move so the game doesn't hang if NPC is stuck Inc(attempts); if attempts > 10 then begin entities.moveNPC(id, spx, spy); exit; end; case direction of 0: Dec(testy); 1: Inc(testy); 2: Dec(testx); 3: Inc(testx); 4: testx := spx; 5: testy := spy; end until (map.canMove(testx, testy) = True) and (map.isOccupied(testx, testy) = False); entities.moveNPC(id, testx, testy); end; procedure chasePlayer(id, spx, spy: smallint); var newX, newY, dx, dy: smallint; distance: double; begin newX := 0; newY := 0; (* Get new coordinates to chase the player *) dx := entityList[0].posX - spx; dy := entityList[0].posY - spy; if (dx = 0) and (dy = 0) then begin newX := spx; newy := spy; end else begin distance := sqrt(dx ** 2 + dy ** 2); dx := round(dx / distance); dy := round(dy / distance); newX := spx + dx; newY := spy + dy; end; (* New coordinates set. Check if they are walkable *) if (map.canMove(newX, newY) = True) then begin (* Do they contain the player *) if (map.hasPlayer(newX, newY) = True) then begin (* Remain on original tile and attack *) entities.moveNPC(id, spx, spy); combat(id); end (* Else if tile does not contain player, check for another entity *) else if (map.isOccupied(newX, newY) = True) then begin ui.bufferMessage('The cave rat bumps into ' + getCreatureName(newX, newY)); entities.moveNPC(id, spx, spy); end (* if map is unoccupied, move to that tile *) else if (map.isOccupied(newX, newY) = False) then entities.moveNPC(id, newX, newY); end else wander(id, spx, spy); end; function isNextToPlayer(spx, spy: smallint): boolean; var dx, dy: smallint; distance: double; // try single begin Result := False; dx := entityList[0].posX - spx; dy := entityList[0].posY - spy; distance := sqrt(dx ** 2 + dy ** 2); if (round(distance) = 0) then Result := True; end; procedure escapePlayer(id, spx, spy: smallint); var newX, newY, dx, dy: smallint; distance: single; begin newX := 0; newY := 0; (* Get new coordinates to escape the player *) dx := entityList[0].posX - spx; dy := entityList[0].posY - spy; if (dx = 0) and (dy = 0) then begin newX := spx; newy := spy; end else begin distance := sqrt(dx ** 2 + dy ** 2); dx := round(dx / distance); dy := round(dy / distance); if (dx > 0) then dx := -1; if (dx < 0) then dx := 1; dy := round(dy / distance); if (dy > 0) then dy := -1; if (dy < 0) then dy := 1; newX := spx + dx; newY := spy + dy; end; if (map.canMove(newX, newY) = True) then begin if (map.hasPlayer(newX, newY) = True) then begin entities.moveNPC(id, spx, spy); combat(id); end else if (map.isOccupied(newX, newY) = False) then entities.moveNPC(id, newX, newY); end else wander(id, spx, spy); end; procedure combat(id: smallint); var damageAmount: smallint; begin damageAmount := globalutils.randomRange(1, entities.entityList[id].attack) - entities.entityList[0].defense; if (damageAmount > 0) then begin entities.entityList[0].currentHP := (entities.entityList[0].currentHP - damageAmount); if (entities.entityList[0].currentHP < 1) then begin if (killer = 'empty') then killer := entityList[id].race; exit; end else begin if (damageAmount = 1) then ui.bufferMessage('The cave rat slightly wounds you') else ui.bufferMessage('The cave rat bites you, inflicting ' + IntToStr(damageAmount) + ' damage'); (* Update health display to show damage *) ui.updateHealth; end; end else ui.bufferMessage('The cave rat attacks but misses'); end; end.
{******************************************************************************} {* *} {* Copyright (c) 2002, NVIDIA Corporation. *} {* *} {* Files: cgGL.h *} {* Content: NVIDIA Cg OpenGL interface include files *} {* *} {* NVIDIA "Cg" Release 1.2 ObjectPascal adaptation by Alexey Barkovoy *} {* E-Mail: clootie@ixbt.com *} {* *} {* Modified: 14-Mar-2004 *} {* *} {* Latest version can be downloaded from: *} {* http://clootie.narod.ru *} {* http://developer.nvidia.com/object/cg_download.html *} {* *} {******************************************************************************} { } { Obtained through: Joint Endeavour of Delphi Innovators (Project JEDI) } { } { The contents of this file are used with permission, subject to the Mozilla } { Public License Version 1.1 (the "License"); you may not use this file except } { in compliance with the License. You may obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { 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. } { } { Alternatively, the contents of this file may be used under the terms of the } { GNU Lesser General Public License (the "LGPL License"), in which case the } { provisions of the LGPL License are applicable instead of those above. } { If you wish to allow use of your version of this file only under the terms } { of the LGPL License and not to allow others to use your version of this file } { under the MPL, indicate your decision by deleting the provisions above and } { replace them with the notice and other provisions required by the LGPL } { License. If you do not delete the provisions above, a recipient may use } { your version of this file under either the MPL or the LGPL License. } { } { For more information about the LGPL: http://www.gnu.org/copyleft/lesser.html } { } {******************************************************************************} (* * * Copyright (c) 2002, NVIDIA Corporation. * * * * NVIDIA Corporation("NVIDIA") supplies this software to you in consideration * of your agreement to the following terms, and your use, installation, * modification or redistribution of this NVIDIA software constitutes * acceptance of these terms. If you do not agree with these terms, please do * not use, install, modify or redistribute this NVIDIA software. * * In consideration of your agreement to abide by the following terms, and * subject to these terms, NVIDIA grants you a personal, non-exclusive license, * under NVIDIARs copyrights in this original NVIDIA software (the "NVIDIA * Software"), to use, reproduce, modify and redistribute the NVIDIA * Software, with or without modifications, in source and/or binary forms; * provided that if you redistribute the NVIDIA Software, you must retain the * copyright notice of NVIDIA, this notice and the following text and * disclaimers in all such redistributions of the NVIDIA Software. Neither the * name, trademarks, service marks nor logos of NVIDIA Corporation may be used * to endorse or promote products derived from the NVIDIA Software without * specific prior written permission from NVIDIA. Except as expressly stated * in this notice, no other rights or licenses express or implied, are granted * by NVIDIA herein, including but not limited to any patent rights that may be * infringed by your derivative works or by other works in which the NVIDIA * Software may be incorporated. No hardware is licensed hereunder. * * THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR ITS USE AND OPERATION * EITHER ALONE OR IN COMBINATION WITH OTHER PRODUCTS. * * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, * EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOST * PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY OUT OF THE USE, * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE NVIDIA SOFTWARE, * HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF NVIDIA HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * *) unit cgGL; {$I VXScene.inc} interface uses {$IFDEF MSWINDOWS} Winapi.Windows,{$ENDIF} cg; const {$IFDEF MSWINDOWS} CgGLlibrary = 'cgGL.dll'; {$ELSE} CgGLlibrary = 'libCgGL.so'; {$ENDIF} (*****************************************************************************) (*** cgGL Type Definitions ***) (*****************************************************************************) type TCGGLenum = Cardinal; CGGLenum = TCGGLenum; const CG_GL_MATRIX_IDENTITY = 0; CG_GL_MATRIX_TRANSPOSE = 1; CG_GL_MATRIX_INVERSE = 2; CG_GL_MATRIX_INVERSE_TRANSPOSE = 3; CG_GL_MODELVIEW_MATRIX = 4; CG_GL_PROJECTION_MATRIX = 5; CG_GL_TEXTURE_MATRIX = 6; CG_GL_MODELVIEW_PROJECTION_MATRIX = 7; CG_GL_VERTEX = 8; CG_GL_FRAGMENT = 9; (****************************************************************************** *** Profile Functions *****************************************************************************) function cgGLIsProfileSupported(profile: TCGprofile): TCGbool; cdecl; external CgGLlibrary; procedure cgGLEnableProfile(profile: TCGprofile); cdecl; external CgGLlibrary; procedure cgGLDisableProfile(profile: TCGprofile); cdecl; external CgGLlibrary; function cgGLGetLatestProfile(profile_type: TCGGLenum): TCGprofile; cdecl; external CgGLlibrary; procedure cgGLSetOptimalOptions(profile: TCGprofile); cdecl; external CgGLlibrary; (****************************************************************************** *** Program Managment Functions *****************************************************************************) procedure cgGLLoadProgram(_program: PCGprogram); cdecl; external CgGLlibrary; function cgGLIsProgramLoaded(_program: PCGprogram): TCGbool; cdecl; external CgGLlibrary; procedure cgGLBindProgram(_program: PCGprogram); cdecl; external CgGLlibrary; procedure cgGLUnbindProgram(profile: TCGprofile); cdecl; external CgGLlibrary; function cgGLGetProgramID(_program: PCGprogram): Cardinal; cdecl; external CgGLlibrary; (****************************************************************************** *** Parameter Managment Functions *****************************************************************************) procedure cgGLSetParameter1f(param: PCGparameter; x: Single); cdecl; external CgGLlibrary; procedure cgGLSetParameter2f(param: PCGparameter; x, y: Single); cdecl; external CgGLlibrary; procedure cgGLSetParameter3f(param: PCGparameter; x, y, z: Single); cdecl; external CgGLlibrary; procedure cgGLSetParameter4f(param: PCGparameter; x, y, z, w: Single); cdecl; external CgGLlibrary; procedure cgGLSetParameter1fv(param: PCGparameter; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameter2fv(param: PCGparameter; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameter3fv(param: PCGparameter; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameter4fv(param: PCGparameter; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameter1d(param: PCGparameter; x: Double); cdecl; external CgGLlibrary; procedure cgGLSetParameter2d(param: PCGparameter; x, y: Double); cdecl; external CgGLlibrary; procedure cgGLSetParameter3d(param: PCGparameter; x, y, z: Double); cdecl; external CgGLlibrary; procedure cgGLSetParameter4d(param: PCGparameter; x, y, z, w: Double); cdecl; external CgGLlibrary; procedure cgGLSetParameter1dv(param: PCGparameter; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameter2dv(param: PCGparameter; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameter3dv(param: PCGparameter; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameter4dv(param: PCGparameter; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameter1f(param: PCGparameter; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameter2f(param: PCGparameter; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameter3f(param: PCGparameter; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameter4f(param: PCGparameter; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameter1d(param: PCGparameter; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameter2d(param: PCGparameter; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameter3d(param: PCGparameter; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameter4d(param: PCGparameter; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray1f(param: PCGparameter; offset, nelements: Longint; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray2f(param: PCGparameter; offset, nelements: Longint; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray3f(param: PCGparameter; offset, nelements: Longint; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray4f(param: PCGparameter; offset, nelements: Longint; const v: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray1d(param: PCGparameter; offset, nelements: Longint; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray2d(param: PCGparameter; offset, nelements: Longint; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray3d(param: PCGparameter; offset, nelements: Longint; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameterArray4d(param: PCGparameter; offset, nelements: Longint; const v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray1f(param: PCGparameter; offset, nelements: Longint; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray2f(param: PCGparameter; offset, nelements: Longint; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray3f(param: PCGparameter; offset, nelements: Longint; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray4f(param: PCGparameter; offset, nelements: Longint; v: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray1d(param: PCGparameter; offset, nelements: Longint; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray2d(param: PCGparameter; offset, nelements: Longint; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray3d(param: PCGparameter; offset, nelements: Longint; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetParameterArray4d(param: PCGparameter; offset, nelements: Longint; v: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetParameterPointer(param: PCGparameter; fsize: Integer; _type: Cardinal; stride: Integer; const _pointer: Pointer); cdecl; external CgGLlibrary; procedure cgGLEnableClientState(param: PCGparameter); cdecl; external CgGLlibrary; procedure cgGLDisableClientState(param: PCGparameter); cdecl; external CgGLlibrary; (****************************************************************************** *** Matrix Parameter Managment Functions *****************************************************************************) procedure cgGLSetMatrixParameterdr(param: PCGparameter; const matrix: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterfr(param: PCGparameter; const matrix: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterdc(param: PCGparameter; const matrix: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterfc(param: PCGparameter; const matrix: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterdr(param: PCGparameter; matrix: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterfr(param: PCGparameter; matrix: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterdc(param: PCGparameter; matrix: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterfc(param: PCGparameter; matrix: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetStateMatrixParameter(param: PCGparameter; matrix: TCGGLenum; transform: TCGGLenum); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterArrayfc(param: PCGparameter; offset, nelements: Longint; const matrices: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterArrayfr(param: PCGparameter; offset, nelements: Longint; const matrices: PSingle); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterArraydc(param: PCGparameter; offset, nelements: Longint; const matrices: PDouble); cdecl; external CgGLlibrary; procedure cgGLSetMatrixParameterArraydr(param: PCGparameter; offset, nelements: Longint; const matrices: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterArrayfc(param: PCGparameter; offset, nelements: Longint; matrices: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterArrayfr(param: PCGparameter; offset, nelements: Longint; matrices: PSingle); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterArraydc(param: PCGparameter; offset, nelements: Longint; matrices: PDouble); cdecl; external CgGLlibrary; procedure cgGLGetMatrixParameterArraydr(param: PCGparameter; offset, nelements: Longint; matrices: PDouble); cdecl; external CgGLlibrary; (****************************************************************************** *** Texture Parameter Managment Functions *****************************************************************************) procedure cgGLSetTextureParameter(param: PCGparameter; texobj: Cardinal); cdecl; external CgGLlibrary; function cgGLGetTextureParameter(param: PCGparameter): Cardinal; cdecl; external CgGLlibrary; procedure cgGLEnableTextureParameter(param: PCGparameter); cdecl; external CgGLlibrary; procedure cgGLDisableTextureParameter(param: PCGparameter); cdecl; external CgGLlibrary; function cgGLGetTextureEnum(param: PCGparameter): Cardinal; cdecl; external CgGLlibrary; procedure cgGLSetManageTextureParameters(ctx: PCGcontext; flag: TCGbool); cdecl; external CgGLlibrary; function cgGLGetManageTextureParameters(ctx: PCGcontext): TCGbool; cdecl; external CgGLlibrary; implementation end.
program three; var A,S,R:Real; begin Write("Введите размер ребра куба: "); ReadLn(A); S:=Pow(A, 3); R:=6 * Pow(A, 2); WriteLn("Объем куба: ", S); WriteLn("Площадь поверхности куба: ", R); end. program four; var A,B,S:Integer; begin Write("Введите первое число: "); ReadLn(A); Write("Введите второе число: "); ReadLn(B); S:=min(A, B) - (max(A, B) - min(A, B)); WriteLn("Среднее арифметическое двух введенных чисел: ", S); end. program five; var A,B,S,R:Real; begin Write("Введите первый катет: "); ReadLn(A); Write("Введите второй катет: "); ReadLn(B); S:=sqrt(pow(A, 2) + pow(B, 2)); R:= 0.5 * (A * B); WriteLn("Гипотенуза данного прямоугольного треугольника равна: ", S); WriteLn("Площадь: ", S); end. program six; var L,S:Real; begin Write("Введите высоту: "); ReadLn(L); S:=L / 9.78; WriteLn("Время падения объекта с высоты ", L, ": ", S); end. program twenty_two; var N,M:Integer; var S,A,B:Real; begin Write("Введите количество мальчиков: "); ReadLn(N); Write("Введите количество девочек: "); ReadLn(M); S:=(N + M) / 100; A:=N / S; B:=M / S; WriteLn("Количество мальчиков в процентах: ", A); WriteLn("Количество девочек в процентах: ", B); end. program twenty_one; var S:Integer; var R:Real; begin Write("Сумма положенная на счет: "); ReadLn(S); R:=S * 1.4; WriteLn("Сумма при снятии со счет в конце года: ", R, "тыс. грн."); end. program twenty; var S:Integer; var R:Real; begin Write("Зарплата работника: "); ReadLn(S); R:=S * 0.8; WriteLn("Полученные им деньги, после уплаты налогов: ", R, " грн."); end. program seven; var A,B,C,D,E,R1,R2:Real; Uses WinCrt; begin Write("Сторона квадрата: "); ReadLn(A); R1:=((sqrt(2) / 2) * A); R2:=0.5 * A; B:=2 * Pi * R2; C:=2 * Pi * R1; D:=Pi * R2; E:=Pi * R1; WriteLn("Длина круга вписанного в данный квадрат: ", B); WriteLn("Длина круга описанного вокруг квадрата: ", С); WriteLn("Площадь круга вписанного в данный квадрат: ", D); WriteLn("Площадь круга описанного вокруг квадрата: ", E); end. program eight; var A,B:Real; Uses WinCrt; begin Write("Сторона квадрата: "); ReadLn(A); B:=2 * Pi * A; WriteLn("Длина круга с радиусом ", A, ": ", B); end. program ten; var A,B:Real; begin Write("Второй радиус кольца: "); ReadLn(A); B:=Pi * (pow(A, 2) - 100); WriteLn("Площадь кольца: ", B); end. program eleven; type x = Array[1..256] of Real; var A:x; var K, M, B:Real; var I, N:Integer; begin Write("Введите первичное значение арифметической прогрессии: "); ReadLn(A[1]); Write("Введише шаг арифметической прогрессии: "); ReadLn(K); Write("Количество шагов арифметической прогрессии: ") ReadLn(N); Write("Нужный элемент арифметической прогрессии: "); ReadLn(M); I:=2; B:=A[I - 1]; While I <> N do A[I] = A[I - 1] + K; B:= B + A[I]; Inc(I); end; WriteLn("Сумма всех членов арифметической прогрессии: ", B); WriteLn(M, " элемент арифметической прогрессии: ", A[M]); end. program 12; type x = Array[1..256] of Real; var A:x; var Q, M B:Real; var I, N:Integer; begin Write("Введите первичное значение геометрической прогрессии: "); ReadLn(A[1]); Write("Введише шаг геометрической прогрессии: "); ReadLn(Q); Write("Количество шагов геометрической прогрессии: ") ReadLn(N); I:=2; B:=A[I - 1]; While I <> N do A[I] = A[I - 1] * K; B:= B + A[I]; Inc(I); end; WriteLn("Сумма всех членов геометрической прогрессии: ", B); WriteLn(M, " элемент геометрической прогрессии: ", A[M]); end. program 13; var A, B:Real; var I, T:Integer; begin Write("Прискорення: "); ReadLn(A); Write("Время: "); ReadLn(T); I:=1; B:=0; if (T <> 1) then begin While I <> T do B:= B + A; Inc(I); end; end else begin B:=A; end; WriteLn("Скорость машины через данное время: ", B); end. program 18; var T,L:Real; Uses WinCrt; begin Write("Введите длину маятника: "); ReadLn(L); T:= 2 * Pi * sqrt(L); Write("Период колебания маятника: ", T); end. program 18; var T,L:Real; Uses WinCrt; begin Write("Введите длину маятника: "); ReadLn(L); T:= 2 * Pi * sqrt(L); Write("Период колебания маятника: ", T); end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado ŕ tabela [NFSE_CABECALHO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfseCabecalhoController; interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, NfseCabecalhoVO; type TNfseCabecalhoController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaNfseCabecalhoVO; class function ConsultaObjeto(pFiltro: String): TNfseCabecalhoVO; class procedure Insere(pObjeto: TNfseCabecalhoVO); class function Altera(pObjeto: TNfseCabecalhoVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM, NFSeDetalheVO, NFSeIntermediarioVO; var ObjetoLocal: TNfseCabecalhoVO; class function TNfseCabecalhoController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TNfseCabecalhoVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TNfseCabecalhoController.ConsultaLista(pFiltro: String): TListaNfseCabecalhoVO; begin try ObjetoLocal := TNfseCabecalhoVO.Create; Result := TListaNfseCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TNfseCabecalhoController.ConsultaObjeto(pFiltro: String): TNfseCabecalhoVO; begin try Result := TNfseCabecalhoVO.Create; Result := TNfseCabecalhoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class procedure TNfseCabecalhoController.Insere(pObjeto: TNfseCabecalhoVO); var UltimoID: Integer; DetalheVO: TNFSeDetalheVO; IntermediarioVO: TNFSeIntermediarioVO; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // Detalhe DetalheEnumerator := pObjeto.ListaNFSeDetalheVO.GetEnumerator; try with DetalheEnumerator do begin while MoveNext do begin DetalheVO := Current; DetalheVO.IdNfseCabecalho := UltimoID; TT2TiORM.Inserir(DetalheVO); end; end; finally DetalheEnumerator.Free; end; // Intermediário IntermediarioEnumerator := pObjeto.ListaNFSeIntermediarioVO.GetEnumerator; try with IntermediarioEnumerator do begin while MoveNext do begin IntermediarioVO := Current; IntermediarioVO.IdNfseCabecalho := UltimoID; TT2TiORM.Inserir(IntermediarioVO); end; end; finally IntermediarioEnumerator.Free; end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TNfseCabecalhoController.Altera(pObjeto: TNfseCabecalhoVO): Boolean; var begin try Result := TT2TiORM.Alterar(pObjeto); // Detalhe try DetalheEnumerator := pObjeto.ListaNFSeDetalheVO.GetEnumerator; with DetalheEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdNfseCabecalho := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(DetalheEnumerator); end; // Intermediário try IntermediarioEnumerator := pObjeto.ListaNFSeIntermediarioVO.GetEnumerator; with IntermediarioEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdNfseCabecalho := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(IntermediarioEnumerator); end; finally end; end; class function TNfseCabecalhoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TNfseCabecalhoVO; begin try ObjetoLocal := TNfseCabecalhoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; begin Result := FDataSet; end; begin FDataSet := pDataSet; end; begin try finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TNfseCabecalhoController); finalization Classes.UnRegisterClass(TNfseCabecalhoController); end.
unit API_VCL_UIExt; interface uses VirtualTrees; type TVSTreeHelper = class helper for TVirtualStringTree private function DoFindNode<T: class>(aParentNode: PVirtualNode; aObject: T): PVirtualNode; public function FindNode<T: class>(aObject: T): PVirtualNode; end; implementation function TVSTreeHelper.DoFindNode<T>(aParentNode: PVirtualNode; aObject: T): PVirtualNode; var NodeObject: T; VirtualNode: PVirtualNode; begin Result := nil; for VirtualNode in ChildNodes(aParentNode) do begin NodeObject := GetNodeData<T>(VirtualNode); if NodeObject = aObject then Exit(VirtualNode); Result := DoFindNode<T>(VirtualNode, aObject); if Result <> nil then Break; end; end; function TVSTreeHelper.FindNode<T>(aObject: T): PVirtualNode; begin Result := DoFindNode<T>(Self.RootNode, aObject); end; end.