text
stringlengths
14
6.51M
program Hello; begin writeln ('Today is Monday.'); end.
unit OTFETrueCryptStructures_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, SysUtils, Windows; type ETrueCryptError = Exception; ETrueCryptNotConnected = ETrueCryptError; ETrueCryptExeNotFound = ETrueCryptError; ETrueCryptVxdNotFound = ETrueCryptError; TDeviceIOControlRegisters = packed record reg_EBX : DWORD; reg_EDX : DWORD; reg_ECX : DWORD; reg_EAX : DWORD; reg_EDI : DWORD; reg_ESI : DWORD; reg_Flags : DWORD; end; TParamBlock = packed record Operation : Integer; NumLocks : Integer; end; const VWIN32_DIOC_DOS_IOCTL = 1; type TrueCrypt_VOLUME_FILE_TYPE = (vtidUnknown, vtidPartition, vtidTrueCryptFile); // This is ALL the different cypher types, in ALL versions of TrueCrypt // Unsupported cyphers are flagged by checking the relevant // TrueCrypt_CIPHER_IDS_xxx const for the value $FFFF TrueCrypt_CIPHER_TYPE = ( cphrNone, cphrBlowfish, cphrAES, cphrCAST, cphrIDEA, cphrTRIPLEDES, cphrDES56, cphrSerpent, cphrTwofish, cphrUnknown ); TrueCrypt_PKCS5_TYPE = (pkcs5HMAC_SHA_1, pkcs5HMAC_RIPEMD_160, pkcs5Unknown); TrueCrypt_CIPHER_MODE = (cphrmodeCBC, cphrmodeOuterCBC, cphrmodeInnerCBC, cphrmodeUnknown); const TrueCrypt_OS_WIN_95 = $a; TrueCrypt_OS_WIN_98 = $b; TrueCrypt_OS_WIN_NT = $c; TrueCrypt_VOLUME_FILE_TYPE_NAMES: array [TrueCrypt_VOLUME_FILE_TYPE] of string = ('Unknown', 'Partition', 'File'); type // OK, now *THIS* is *puke* - *every* different TrueCrypt versions use // different IDs, so we're stuck with doing this :( // Couldn't they just use nice enums in their code, as opposed to #defining // everything?!! Ewww! // Because of this, we allow the users of this component to "hint" which // version of TrueCrypt is installed. // If this software is ever in any doubt, this value will be referred to TTrueCryptVersionHint = (tcvAuto, tcv21, tcv21a); const // Filesize, in bytes, of different versions of TrueCrypt TrueCrypt_EXE_FILESIZES: array [TTrueCryptVersionHint] of integer = ( 0, // tcvAuto 360448, // tcv21 356352 // tcv21a ); // This is ALL the different cypher types, in ALL versions of TrueCrypt TrueCrypt_CIPHER_NAMES: array [TrueCrypt_CIPHER_TYPE] of string = ( 'None', 'Blowfish', 'AES', 'CAST', 'IDEA', 'Triple-DES', 'DES', 'Serpent', 'Twofish', '<Unknown>' ); // These are the internal TrueCrypt IDs of the various items TrueCrypt_PKCS5_IDS: array [TrueCrypt_PKCS5_TYPE] of integer = (1, 2, $ffff); TrueCrypt_PKCS5_NAMES: array [TrueCrypt_PKCS5_TYPE] of string = ('HMAC-SHA-1', 'HMAC-RIPEMD-160', '<Unknown>'); TrueCrypt_CIPHER_MODE_IDS: array [TrueCrypt_CIPHER_MODE] of integer = (1, 2, 3, $ffff); TrueCrypt_CIPHER_MODE_NAMES: array [TrueCrypt_CIPHER_MODE] of string = ('CBC', 'Outer-CBC', 'Inner-CBC', '<Unknown>'); const TrueCrypt_DISKKEY_SIZE = 256; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- TrueCrypt_APP_NAME = 'TrueCrypt'; TrueCrypt_APP_EXE_NAME = 'TrueCrypt.exe'; //kTrueCryptDriverName // setup when the component is created; depends on the OS TrueCrypt_SERVICE_NAME = 'TrueCrypt'; TrueCrypt_REGISTRY_EXE_ROOT = HKEY_CLASSES_ROOT; TrueCrypt_REGISTRY_EXE_PATH = '\TrueCryptVolume\Shell\Open\command'; // Registry keys TrueCrypt_REGISTRY_SETTINGS_ROOT = HKEY_CURRENT_USER; TrueCrypt_REGISTRY_SETTINGS_PATH = '\Software\TrueCrypt'; // Options TrueCrypt_REGISTRY_SETTINGS_PARAM_CACHEPASSWORDSINDRIVER = 'CachePasswordsInDriver'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CACHEPASSWORDSINDRIVER = FALSE; TrueCrypt_REGISTRY_SETTINGS_PARAM_OPENEXPLORERWINDOWAFTERMOUNT = 'OpenExplorerWindowAfterMount'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_OPENEXPLORERWINDOWAFTERMOUNT = FALSE; TrueCrypt_REGISTRY_SETTINGS_PARAM_CLOSEEXPLORERWINDOWSONDISMOUNT = 'CloseExplorerWindowsOnDismount'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CLOSEEXPLORERWINDOWSONDISMOUNT = TRUE; TrueCrypt_REGISTRY_SETTINGS_PARAM_SAVEMOUNTEVOLUMESHISTORY = 'SaveMountedVolumesHistory'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_SAVEMOUNTEVOLUMESHISTORY = FALSE; TrueCrypt_REGISTRY_SETTINGS_PARAM_WIPEPASSWORDCACHEONEXIT = 'WipePasswordCacheOnExit'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_WIPEPASSWORDCACHEONEXIT = FALSE; // Drive Letter TrueCrypt_REGISTRY_SETTINGS_PARAM_LASTSELECTEDDRIVE = 'LastSelectedDrive'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTSELECTEDDRIVE = ''; // History TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME = 8; // The TrueCrypt application stores the last 8 volume files TrueCrypt_REGISTRY_SETTINGS_PARAM_PREFIX_LASTMOUNTEVOLUME = 'LastMountedVolume'; TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTMOUNTEVOLUME = ''; // TrueCrypt driver name (9x only) const TrueCrypt_WIN9X_DRIVER_NAME = '\\.\TRUCRYPT'; const TrueCrypt_TC_UNIQUE_ID_PREFIX = 'TrueCrypt'; const TrueCrypt_TC_MOUNT_PREFIX = '\Device\TrueCryptVolume'; // xxx - under NT these should be "WIDE"?? - see "DRIVER_STR" #define thing const TrueCrypt_NT_MOUNT_PREFIX = '\Device\TrueCryptVolume'; const TrueCrypt_NT_ROOT_PREFIX = '\Device\TrueCrypt'; const TrueCrypt_DOS_MOUNT_PREFIX = '\DosDevices\'; const TrueCrypt_DOS_ROOT_PREFIX = '\DosDevices\TrueCrypt'; const TrueCrypt_WIN32_ROOT_PREFIX = '\\.\TrueCrypt'; // TrueCrypt service // YUCK! In the TrueCrypt source, this is a hardcoded value! const TrueCrypt_PIPE_SERVICE = '\\.\pipe\truecryptservice'; const TrueCrypt_HDD_PARTITION_DEVICE_NAME_FORMAT = '\Device\Harddisk%d\Partition%d'; const TrueCrypt_HDD_MAX_PHYSICAL_DRIVES = 9; // E4M can only OPEN_TEST a drive with a // single digit number (0-9) const TrueCrypt_HDD_MAX_PARTITIONS = 9; // E4M can only OPEN_TEST a partition // with a single digit number (1-9) const TrueCrypt_SIZEOF_MRU_LIST = 8; // 0-7 const TrueCrypt_DWORD_TRUE = 1; const TrueCrypt_DWORD_FALSE = 0; // TrueCrypt DeviceIOControl values const TrueCrypt_IOCTL_MOUNT = 466944; // Mount a volume or partition const TrueCrypt_IOCTL_MOUNT_LIST = 466948; // Return list of mounted volumes const TrueCrypt_IOCTL_OPEN_TEST = 466952; // Open a file at ring0 const TrueCrypt_IOCTL_UNMOUNT = 466956; // Unmount a volume const TrueCrypt_IOCTL_WIPE_CACHE = 466960; // Wipe the driver password cache const TrueCrypt_IOCTL_HALT_SYSTEM = 466964; // Halt system; (only NT when compiled with debug) const TrueCrypt_IOCTL_DRIVER_VERSION = 466968; // Current driver version const TrueCrypt_IOCTL_RELEASE_TIME_SLICE = 466972; // Release time slice on apps behalf (only Win9x) const TrueCrypt_IOCTL_MOUNT_LIST_N = 466976; // Get volume info from the device (only Win9x) const TrueCrypt_IOCTL_DISKIO = 466980; // Read/Write at ring0 for win32 gui (only Win9x) const TrueCrypt_IOCTL_ALLOW_FAST_SHUTDOWN = 466984; // Fast shutdown under win98 (only Win9x) const TrueCrypt_IOCTL_CACHE_STATUS = 466988; // Get password cache status const TrueCrypt_IOCTL_VOLUME_PROPERTIES = 466992; // Get mounted volume properties const TrueCrypt_IOCTL_UNMOUNT_PENDING = 475112; // Flush the device with this api before sending UNMOUNT const TrueCrypt_ERR_OS_ERROR = 1; const TrueCrypt_ERR_OUTOFMEMORY = 2; const TrueCrypt_ERR_PASSWORD_WRONG = 3; const TrueCrypt_ERR_VOL_FORMAT_BAD = 4; const TrueCrypt_ERR_BAD_DRIVE_LETTER = 5; const TrueCrypt_ERR_DRIVE_NOT_FOUND = 6; const TrueCrypt_ERR_FILES_OPEN = 7; const TrueCrypt_ERR_VOL_SIZE_WRONG = 8; const TrueCrypt_ERR_COMPRESSION_NOT_SUPPORTED = 9; const TrueCrypt_ERR_PASSWORD_CHANGE_VOL_TYPE = 10; const TrueCrypt_ERR_PASSWORD_CHANGE_VOL_VERSION = 11; const TrueCrypt_ERR_VOL_SEEKING = 12; const TrueCrypt_ERR_VOL_WRITING = 13; const TrueCrypt_ERR_FILES_OPEN_LOCK = 14; const TrueCrypt_ERR_VOL_READING = 15; const TrueCrypt_ERR_DRIVER_VERSION = 16; const TrueCrypt_ERR_NEW_VERSION_REQUIRED = 17; const TrueCrypt_ERR_VOL_ALREADY_MOUNTED = 32; const TrueCrypt_ERR_NO_FREE_SLOTS = 33; const TrueCrypt_ERR_NO_FREE_DRIVES = 34; const TrueCrypt_ERR_FILE_OPEN_FAILED = 35; const TrueCrypt_ERR_VOL_MOUNT_FAILED = 36; const TrueCrypt_ERR_INVALID_DEVICE = 37; const TrueCrypt_ERR_ACCESS_DENIED = 38; const TrueCrypt_TC_MAX_PATH = 260; // Includes the null terminator const TrueCrypt_MIN_PASSWORD = 12; const TrueCrypt_MAX_PASSWORD = 64; type // This is only used by Delphi applications; not the TrueCrypt driver TOTFETrueCryptVolumeInfo = record // This is not part of the TrueCrypt source volumeFilename: string; // !! WARNING !! // The driver will only ever return up to 64 // chars for a volume filename (*YUCK!*). // This is due to a limitation of the TrueCrypt // driver mountedAs: ansichar; diskLength: int64; ciphers: array [0..2] of TrueCrypt_CIPHER_TYPE; // Unused elements will be populated with cphrNone cipherNames: string; cipherMode: TrueCrypt_CIPHER_MODE; cipherModeName: string; pkcs5Type: TrueCrypt_PKCS5_TYPE; pkcs5TypeName: string; pkcs5Iterations: integer; volumeLocation: TrueCrypt_VOLUME_FILE_TYPE; volumeLocationName: string; hidden: boolean; volumeCreated: TDateTime; passwordChanged: TDateTime; readOnly: boolean; end; pTOTFETrueCryptVolumeInfo = ^TOTFETrueCryptVolumeInfo; type // The following structures are used by the TrueCrypt driver // Note: TrueCrypt v2.0 itself uses an $25D sized buffer (checked with // debugger on the running TrueCrypt executable) TOTFETrueCrypt_MOUNT_STRUCT_PRE30 = packed record nReturnCode: integer; // Return code back from driver wszVolume: array [0..(TrueCrypt_TC_MAX_PATH-1)] of WCHAR; // Volume to be mounted - -1 since we index from 0 szPassword: array [0..((TrueCrypt_MAX_PASSWORD+1)-1)] of AnsiChar; // User password - -1 since we index from 0 nPasswordLen: integer; // User password length bCache: boolean; // Cache passwords in driver junkPadding: array [0..2] of byte; // junk padding to align with word boundry nDosDriveNo: integer; // Drive number to mount time: DWORD; // Time when this volume was mounted end; // Note: TrueCrypt v3.0a itself uses an $26D sized buffer (checked with // debugger on the running TrueCrypt executable) TOTFETrueCrypt_MOUNT_STRUCT_30 = packed record nReturnCode: integer; // Return code back from driver wszVolume: array [0..(TrueCrypt_TC_MAX_PATH-1)] of WCHAR; // Volume to be mounted - -1 since we index from 0 szPassword: array [0..((TrueCrypt_MAX_PASSWORD+1)-1)] of AnsiChar; // User password - -1 since we index from 0 nPasswordLen: integer; // User password length bCache: boolean; // Cache passwords in driver junkPadding1: array [0..2] of byte; // junk padding to align with word boundry nDosDriveNo: integer; // Drive number to mount bMountReadOnly: boolean; // Mount volume in read-only mode junkPadding2: array [0..2] of byte; // junk padding to align with word boundry bMountRemovable: boolean; // Mount volume as removable media junkPadding3: array [0..2] of byte; // junk padding to align with word boundry bExclusiveAccess: boolean; // Open host file/device in exclusive access mode junkPadding4: array [0..2] of byte; // junk padding to align with word boundry bMountManager: boolean; // Announce volume to mount manager junkPadding5: array [0..2] of byte; // junk padding to align with word boundry time: DWORD; // Time when this volume was mounted end; // Structure valid for pre-v3.0 versions of TrueCrypt // Note: The TrueCrypt GUI NEVER USES THIS (Though the command line // interface might...). This Delphi component calls the TrueCrypt // service instead via a named pipe, like the TrueCrypt GUI. TOTFETrueCrypt_UNMOUNT_STRUCT_PRE30 = packed record nReturnCode: integer; // Return code back from driver nDosDriveNo: integer; // Drive letter to unmount end; // Structure valid for v3.0 and later versions of TrueCrypt // v3.0a *does* use this... // Note: TrueCrypt v3.0a itself uses an $C sized buffer (checked with // debugger on the running TrueCrypt executable) TOTFETrueCrypt_UNMOUNT_STRUCT_30 = packed record nDosDriveNo: integer; // Drive letter to unmount ignoreOpenFiles: boolean; junkPadding: array [0..2] of byte; // junk padding to align with word boundry nReturnCode: integer; // Return code back from driver end; // Note: TrueCrypt v2.0 itself uses an $E3C sized buffer (checked with // debugger on the running TrueCrypt executable) TOTFETrueCrypt_MOUNT_LIST_STRUCT_PRE30 = packed record ulMountedDrives: cardinal; // Bitfield of all mounted drive letters // Yes, it is 64 in the next line; it was hardcoded in the TrueCrypt source // (I would have *expected* it to be "TrueCrypt_TC_MAX_PATH", not 64! Looks // like a throwback from E4M - the same was hardcoded there to... wszVolume: array [0..26-1] of array [0..64-1] of WCHAR; // Volume names of mounted volumes diskLength: array [0..26-1] of int64; cipher: array [0..26-1] of integer; // -1 because we index from 0, giving 26 array elements end; // Note: TrueCrypt v3.0a itself uses an $EA4 sized buffer (checked with // debugger on the running TrueCrypt executable) TOTFETrueCrypt_MOUNT_LIST_STRUCT_30 = packed record ulMountedDrives: cardinal; // Bitfield of all mounted drive letters // Yes, it is 64 in the next line; it was hardcoded in the TrueCrypt source // (I would have *expected* it to be "TrueCrypt_TC_MAX_PATH", not 64! Looks // like a throwback from E4M - the same was hardcoded there to... wszVolume: array [0..26-1] of array [0..64-1] of WCHAR; // Volume names of mounted volumes diskLength: array [0..26-1] of int64; ea: array [0..26-1] of integer; // -1 because we index from 0, giving 26 array elements hiddenVol: array [0..26-1] of integer; // -1 because we index from 0, giving 26 array elements // We use integer for this as the // BOOLs TrueCrypt uses appear to be // 4 bytes each; probably one byte // plus 3 padding bytes end; // Win9x only TOTFETrueCrypt_MOUNT_LIST_N_STRUCT = record nReturnCode: integer; // Return code back from driver nDosDriveNo: integer; /// Drive letter to get info on wszVolume: array [0..TrueCrypt_TC_MAX_PATH-1] of WCHAR; // Volume names of mounted volumes mountfilehandle: DWORD; // Device file handle or 0 end; // YES, THIS ONE IS A **PACKED** RECORD // If it's not packed, then the diskLength member grows the record by an // extra 8 bytes (totalling 176 bytes) - though if you don't pack the record, // and you change diskLength to an array of 8 bytes, it works (168 bytes)?!! // Structure valid for pre-v3.0 versions of TrueCrypt TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_PRE30 = packed record driveNo: integer; // Yes, it is 64 in the next line; it was hardcoded in the TrueCrypt source // (I would have *expected* it to be "TrueCrypt_TC_MAX_PATH", not 64! Looks // like a throwback from E4M... wszVolume: array [0..64-1] of WCHAR; // bs: array [1..8] of byte; diskLength: int64; cipher: integer; pkcs5: integer; pkcs5Iterations: integer; volumeCreationTime: int64; headerCreationTime: int64; //int readOnly; // Commented out in TrueCrypt source for some reason?! end; // YES, THIS ONE IS A **PACKED** RECORD // If it's not packed, then the diskLength member grows the record by an // extra 8 bytes (totalling 176 bytes) - though if you don't pack the record, // and you change diskLength to an array of 8 bytes, it works (168 bytes)?!! // Structure valid for v3.0-v3.1 versions of TrueCrypt TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_30 = packed record driveNo: integer; // Yes, it is 64 in the next line; it was hardcoded in the TrueCrypt source // (I would have *expected* it to be "TrueCrypt_TC_MAX_PATH", not 64! Looks // like a throwback from E4M... wszVolume: array [0..64-1] of WCHAR; diskLength: int64; ea: integer; pkcs5: integer; pkcs5Iterations: integer; hiddenVolume: boolean; junkPadding: array [0..2] of byte; // junk padding to align with word boundry volumeCreationTime: int64; headerCreationTime: int64; //int readOnly; // Commented out in TrueCrypt source for some reason?! end; // YES, THIS ONE IS A **PACKED** RECORD // If it's not packed, then the diskLength member grows the record by an // extra 8 bytes (totalling 176 bytes) - though if you don't pack the record, // and you change diskLength to an array of 8 bytes, it works (168 bytes)?!! // Structure valid for v3.1a and later versions of TrueCrypt TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_31a = packed record driveNo: integer; // Yes, it is 64 in the next line; it was hardcoded in the TrueCrypt source // (I would have *expected* it to be "TrueCrypt_TC_MAX_PATH", not 64! Looks // like a throwback from E4M... wszVolume: array [0..64-1] of WCHAR; diskLength: int64; ea: integer; pkcs5: integer; pkcs5Iterations: integer; hiddenVolume: boolean; junkPadding1: array [0..2] of byte; // junk padding to align with word boundry readOnly: boolean; junkPadding2: array [0..2] of byte; // junk padding to align with word boundry volumeCreationTime: int64; headerCreationTime: int64; //int readOnly; // Commented out in TrueCrypt source for some reason?! end; TOTFETrueCrypt_OPEN_TEST = record wszFileName: array [1..TrueCrypt_TC_MAX_PATH] of WCHAR; // Volume to be "open tested" nReturnCode: integer; //Win9x only secstart: cardinal; // Win9x only seclast: cardinal; // Win9x only device: cardinal; // Win9x only end; TOTFETrueCrypt_VERSION = record // This is not part of the TrueCrypt source; it's just a // DWORD, but is included for completeness version: DWORD; end; implementation END.
unit StereoFrm; interface uses Winapi.OpenGL, Winapi.OpenGLext, Winapi.Windows, Winapi.Messages, System.Classes, System.SysUtils, System.Math, Vcl.Controls, Vcl.Menus, Vcl.Graphics, Vcl.Forms, Vcl.Dialogs, WGLext, GLKeyboard, GLScene, GLWin32Viewer, GLMaterial, GLObjects, GLCadencer, GLTexture, GLVectorGeometry, GLGraphics, GLHUDObjects, GLContext, GLTeapot, GLTexCombineShader, GLUserShader, GLAsyncTimer, GLCoordinates, GLBaseClasses, GLRenderContextInfo, GLCrossPlatform; type TAaStereoForm = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLMemoryViewer1: TGLMemoryViewer; CameraTarget: TGLDummyCube; GLLightSource1: TGLLightSource; GLCamera1: TGLCamera; GLCadencer1: TGLCadencer; GLHUDSprite1: TGLHUDSprite; Setup: TGLDirectOpenGL; LeftCamera: TGLCamera; RightCamera: TGLCamera; GLMaterialLibrary1: TGLMaterialLibrary; StereoScene: TGLDummyCube; Cleanup: TGLDirectOpenGL; GLTeapot1: TGLTeapot; GLUserShader1: TGLUserShader; AsyncTimer1: TGLAsyncTimer; PopupMenu1: TPopupMenu; Colors1: TMenuItem; RedBlueColor: TMenuItem; BLueRed1: TMenuItem; GreenBlue1: TMenuItem; BlueGreen1: TMenuItem; StereoView1: TMenuItem; NotStereo1: TMenuItem; GlyphMenu: TMenuItem; Pinout1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; Rotate1: TMenuItem; VSync1: TMenuItem; N2: TMenuItem; About1: TMenuItem; GLSphere1: TGLSphere; Blurred1: TMenuItem; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure GLSceneViewer1BeforeRender(Sender: TObject); procedure SetupRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure CleanupRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure GLUserShader1DoApply(Sender: TObject; var rci: TGLRenderContextInfo); procedure GLUserShader1DoUnApply(Sender: TObject; Pass: Integer; var rci: TGLRenderContextInfo; var Continue: Boolean); procedure AsyncTimer1Timer(Sender: TObject); procedure RedBlueColorClick(Sender: TObject); procedure NotStereo1Click(Sender: TObject); procedure Rotate1Click(Sender: TObject); procedure VSync1Click(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Exit1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure About1Click(Sender: TObject); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure GLSceneViewer1DblClick(Sender: TObject); private StereoCapable, MemCapable, Switcheroo: Boolean; StereoMode, mdx, mdy: Integer; pseye: Double; public RenderPass, RenderPassLeft, RenderPassRight: Integer; end; var AaStereoForm: TAaStereoForm; implementation {$R *.dfm} procedure TAaStereoForm.FormCreate(Sender: TObject); var flag: BYTEBOOL; flagged: PGLBoolean; begin { Dunno how this is supposed to be.. but it does NOT work procedure glGetBooleanv(pname: TGLEnum; params: PGLboolean); } flag := True; { False; } { It will return Whatever i send it } flagged := Addr(flag); glGetBooleanv(GL_STEREO, flagged); { Should return Stereo Capability } // flag := flagged^; if (flagged^=0) then // If flag = false then begin Pinout1.Caption := 'NA'; StereoCapable := false; end else StereoCapable := True; StereoMode := 2; (* if (not WGL_ARB_pbuffer)<>0 then showmessage('no p buffer'); WGL_ARB_pbuffer:=CheckExtension('WGL_STEREO_ARB '); *) if (WGL_DOUBLE_BUFFER_ARB = 0) then showmessage('no double buffer'); if (not WGL_STEREO_ARB) = 0 then showmessage('no stereo buffer'); if (WGL_PBUFFER_LOST_ARB = 0) then begin GlyphMenu.Caption := 'NA'; MemCapable := false; StereoMode := 0; NotStereo1.Checked := True; end else MemCapable := True; Switcheroo := True; RenderPassLeft := 1; { Red } RenderPassRight := 3; { Blue } pseye := 0.25; end; procedure TAaStereoForm.Exit1Click(Sender: TObject); begin Close; end; procedure TAaStereoForm.About1Click(Sender: TObject); begin showmessage('GLScene Stereo Demo Version 0.1' + #13#10 + 'GLScene: http://glscene.org/' + #13#10 + 'Written by Stuart Gooding and Stuart Little II'); end; procedure TAaStereoForm.FormResize(Sender: TObject); begin // This lines take cares of auto-zooming. // magic numbers explanation : from caterpillar demo // 250 is a form width where things looks good when focal length is 50, // ie. when form width is 250, uses 38 as focal length, // when form is 500, uses 76, etc... // GLCameraBase.FocalLength:=Width*38/250; GLCamera1.FocalLength := Width * 50 / 512; LeftCamera.FocalLength := Width * 50 / 512; RightCamera.FocalLength := Width * 50 / 512; { Do some ps.eye ? stuff } end; procedure TAaStereoForm.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin { AaStereoForm.Width:=520; AaStereoForm.Height:=546; } { Make sure the form is Square ?power of 2? kinda goofy, move the corner.. it will work } If NewHeight > (NewWidth + 26) then begin NewHeight := (NewWidth + 26); end else begin NewWidth := (NewHeight - 26); end; Resize := True; GLSceneViewer1.ResetPerformanceMonitor; end; procedure TAaStereoForm.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin If Rotate1.Checked then GLTeapot1.Turn(deltaTime * 25); GLHUDSprite1.Visible := false; StereoScene.Visible := True; Case StereoMode of 0: Begin RenderPass := 0; End; 1: Begin If Switcheroo then begin RenderPass := RenderPassLeft; GLSceneViewer1.Camera := LeftCamera; Switcheroo := false; end else begin RenderPass := RenderPassRight; GLSceneViewer1.Camera := RightCamera; Switcheroo := True; end; End; 2: Begin with GLMemoryViewer1 do begin Camera := LeftCamera; RenderPass := RenderPassLeft; Render; CopyToTexture(GLMaterialLibrary1.Materials[0].Material.Texture); Camera := RightCamera; RenderPass := RenderPassRight; Render; CopyToTexture(GLMaterialLibrary1.Materials[1].Material.Texture); end; GLSceneViewer1.Invalidate; End; 3: Begin { Need to Write to Left and Right Buffers } glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT); If Switcheroo then begin RenderPass := RenderPassLeft; GLSceneViewer1.Camera := LeftCamera; glDrawBuffer(GL_BACK_LEFT); Switcheroo := false; end else begin RenderPass := RenderPassRight; GLSceneViewer1.Camera := RightCamera; glDrawBuffer(GL_BACK_RIGHT); Switcheroo := True; end; End; End; end; procedure TAaStereoForm.GLSceneViewer1BeforeRender(Sender: TObject); begin Case StereoMode of 2: Begin StereoScene.Visible := false; with GLHUDSprite1 do begin Visible := True; Width := GLSceneViewer1.Width; Height := GLSceneViewer1.Height; Position.SetPoint(Width / 2, Height / 2, 0); end; RenderPass := 0; end; end; end; procedure TAaStereoForm.SetupRender(Sender: TObject; var rci: TGLRenderContextInfo); begin case RenderPass of 1: glColorMask(1, 0, 0, 1); 2: glColorMask(0, 1, 0, 1); 3: glColorMask(0, 0, 1, 1); else glColorMask(1, 1, 1, 1); end; end; procedure TAaStereoForm.CleanupRender(Sender: TObject; var rci: TGLRenderContextInfo); begin glColorMask(1, 1, 1, 1); end; procedure TAaStereoForm.GLUserShader1DoApply(Sender: TObject; var rci: TGLRenderContextInfo); begin GLMaterialLibrary1.Materials[0].Material.Texture.Apply(rci); end; procedure TAaStereoForm.GLUserShader1DoUnApply(Sender: TObject; Pass: Integer; var rci: TGLRenderContextInfo; var Continue: Boolean); begin case Pass of 1: begin GLMaterialLibrary1.Materials[0].Material.Texture.UnApply(rci); glPushAttrib(GL_ENABLE_BIT); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); GLMaterialLibrary1.Materials[1].Material.Texture.Apply(rci); Continue := True; end; 2: begin GLMaterialLibrary1.Materials[1].Material.Texture.UnApply(rci); glPopAttrib; Continue := false; end; else Assert(false, 'Invalid use of shader!!!'); end; end; procedure TAaStereoForm.AsyncTimer1Timer(Sender: TObject); begin AaStereoForm.Caption := Format('%.2f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TAaStereoForm.RedBlueColorClick(Sender: TObject); var Item: TMenuItem; begin Item := Sender as TMenuItem; Item.Checked := not Item.Checked; case TMenuItem(Sender).Tag of 11: begin RenderPassLeft := 1; { Red } RenderPassRight := 3; { Blue } end; 12: begin RenderPassLeft := 3; RenderPassRight := 1; end; 13: begin RenderPassLeft := 2; { Green } RenderPassRight := 3; end; 14: begin RenderPassLeft := 3; RenderPassRight := 2; end; end; end; procedure TAaStereoForm.NotStereo1Click(Sender: TObject); var Item: TMenuItem; begin Item := Sender as TMenuItem; Item.Checked := not Item.Checked; GLSceneViewer1.Buffer.ContextOptions := [roDoubleBuffer, roRenderToWindow]; case TMenuItem(Sender).Tag of 0: StereoMode := Item.Tag; 1: StereoMode := Item.Tag; 2: begin If (not MemCapable) then begin StereoMode := 0; NotStereo1.Checked := True; end else StereoMode := Item.Tag; end; 3: begin If not StereoCapable then begin StereoMode := 0; NotStereo1.Checked := True; end else begin StereoMode := Item.Tag; GLSceneViewer1.Buffer.ContextOptions := [roDoubleBuffer, roRenderToWindow, roStereo]; end; end; end; GLSceneViewer1.Invalidate; end; procedure TAaStereoForm.Rotate1Click(Sender: TObject); var Item: TMenuItem; begin Item := Sender as TMenuItem; Item.Checked := not Item.Checked; end; procedure TAaStereoForm.VSync1Click(Sender: TObject); begin VSync1.Checked := not VSync1.Checked; if VSync1.Checked then GLSceneViewer1.VSync := vsmSync else GLSceneViewer1.VSync := vsmNoSync; end; procedure TAaStereoForm.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // store mouse coordinates when a button went down mdx := X; mdy := Y; end; procedure TAaStereoForm.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var dx, dy: Integer; v: TVector; begin // calculate delta since last move or last mousedown dx := mdx - X; dy := mdy - Y; mdx := X; mdy := Y; if ssLeft in Shift then begin if ssShift in Shift then begin // left button with shift rotates the teapot // (rotation happens around camera's axis) GLCamera1.RotateObject(StereoScene, dy, dx); end else if ssCtrl in Shift then begin // left button with Ctrl changes camera angle // (we're moving around the parent and target dummycube) GLCamera1.MoveAroundTarget(dy, dx); end else begin // left button moves our target and parent dummycube v := GLCamera1.ScreenDeltaToVectorXY(dx, -dy, 0.12 * GLCamera1.DistanceToTarget / GLCamera1.FocalLength); StereoScene.Position.Translate(v); // notify camera that its position/target has been changed GLCamera1.TransformationChanged; end; end; end; procedure TAaStereoForm.FormKeyPress(Sender: TObject; var Key: Char); begin if IsKeyDown(VK_ESCAPE) then Close; case Key of 'q': Close; 'Q': Close; 't': begin pseye := pseye - 0.05; // move eye distance LeftCamera.Position.X := (-1 * pseye); RightCamera.Position.X := (pseye); end; 'y': begin pseye := pseye + 0.05; // move eye distance LeftCamera.Position.X := (-1 * pseye); RightCamera.Position.X := (pseye); end; 'g': begin pseye := pseye - 0.01; // move eye distance LeftCamera.Position.X := (-1 * pseye); RightCamera.Position.X := (pseye); end; 'h': begin pseye := pseye + 0.01; // move eye distance LeftCamera.Position.X := (-1 * pseye); RightCamera.Position.X := (pseye); end; 'n': GLCamera1.MoveAroundTarget(-3, 0); 'm': GLCamera1.MoveAroundTarget(3, 0); 'j': GLCamera1.MoveAroundTarget(0, -3); 'k': GLCamera1.MoveAroundTarget(0, 3); '-': GLCamera1.AdjustDistanceToTarget(1.1); '+': GLCamera1.AdjustDistanceToTarget(1 / 1.1); 'f': begin GLCamera1.FocalLength := GLCamera1.FocalLength + 10; // Camera focus plane foward */ LeftCamera.FocalLength := LeftCamera.FocalLength + 10; RightCamera.FocalLength := RightCamera.FocalLength + 10; end; 'v': begin GLCamera1.FocalLength := GLCamera1.FocalLength - 10; // Camera focus plane back */ LeftCamera.FocalLength := LeftCamera.FocalLength - 10; RightCamera.FocalLength := RightCamera.FocalLength - 10; end; 'd': begin GLCamera1.DepthOfView := GLCamera1.DepthOfView + 10; // Camera DepthOfView foward */ LeftCamera.DepthOfView := LeftCamera.DepthOfView + 10; RightCamera.DepthOfView := RightCamera.DepthOfView + 10; end; 'c': begin GLCamera1.DepthOfView := GLCamera1.DepthOfView - 10; // Camera DepthOfView back */ LeftCamera.DepthOfView := LeftCamera.DepthOfView - 10; RightCamera.DepthOfView := RightCamera.DepthOfView - 10; end; end; // end keyboard with GLTeapot1 do case Key of '7': RotateAbsolute(-15, 0, 0); '9': RotateAbsolute(+15, 0, 0); '4': RotateAbsolute(0, -15, 0); '6': RotateAbsolute(0, +15, 0); '1': RotateAbsolute(0, 0, -15); '3': RotateAbsolute(0, 0, +15); end; Key := #0; end; procedure TAaStereoForm.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin // Note that 1 wheel-step induces a WheelDelta of 120, // this code adjusts the distance to target with a 10% per wheel-step ratio GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120)); end; procedure TAaStereoForm.GLSceneViewer1DblClick(Sender: TObject); begin if (BorderStyle <> bsNone) then begin BorderStyle := bsNone; FormStyle := fsStayOnTop; Align := alClient; end; end; end.
unit AOCBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, system.Diagnostics, ClipBrd, system.UITypes; type TProcedureToRun = procedure of object; type TFunctionToRun = function: Variant of object; type TAdventOfCode = class(TPersistent) constructor Create; destructor Destroy; override; protected FInput: TStrings; function SolveA: Variant; virtual; function SolveB: Variant; virtual; procedure BeforeSolve; virtual; procedure AfterSolve; virtual; function SaveFilePath: String; private function InputFilePath: string; function MakeFilePath(const aFileName: String): string; function DayIndex: String; procedure DoProcedure(ProcedureToRun: TProcedureToRun; const aDisplayName: String); function DoFunction(FuntionToRun: TFunctionToRun; const aDisplayName: string; Out TicksTaken: Int64): String; procedure LoadInput; procedure WriteTicksToDebug(Const aFunctionName: string; Const aStartTick: Int64); procedure InternalSolve(Out SolutionA, SolutionB: string; out TimeA, TimeB: Int64); public { Public declarations } procedure Solve; procedure Test(Out SolutionA, SolutionB: String; Const OverRidenTestInput: String); end; implementation uses uAOCUtils; function TAdventOfCode.DayIndex: String; begin Result := AOCUtils.DayIndexFromClassName(Self.ClassName); end; constructor TAdventOfCode.Create; begin Assert(Self.ClassName.StartsWith('TAdventOfCodeDay'), 'Classname should begin with TAdventOfCodeDay, followd by the dayindex'); FInput := TStringList.Create; DoProcedure(LoadInput, 'LoadInput'); end; destructor TAdventOfCode.Destroy; begin FInput.Free; inherited; end; function TAdventOfCode.SaveFilePath: String; begin Result := MakeFilePath('Solution'); end; function TAdventOfCode.InputFilePath: string; begin Result := MakeFilePath('Input') end; function TAdventOfCode.MakeFilePath(const aFileName: String): string; begin result := Format('%s\%s%s.txt', [AOCUtils.Config.BaseFilePath, aFileName, DayIndex]) end; function TAdventOfCode.SolveA: Variant; begin Result := 'Not implemented' end; function TAdventOfCode.SolveB: Variant; begin Result := 'Not implemented' end; procedure TAdventOfCode.BeforeSolve; begin // To be overriden end; procedure TAdventOfCode.AfterSolve; begin // To be overriden end; procedure TAdventOfCode.WriteTicksToDebug(Const aFunctionName: string; Const aStartTick: Int64); begin Writeln(Format('%s -> TickCount: %d', [aFunctionName, GetTickCount-aStartTick] )); end; procedure TAdventOfCode.DoProcedure(ProcedureToRun: TProcedureToRun; const aDisplayName: String); var StartTick: Int64; begin StartTick := GetTickCount; ProcedureToRun; WriteTicksToDebug(aDisplayName, StartTick); end; function TAdventOfCode.DoFunction(FuntionToRun: TFunctionToRun; const aDisplayName: string; Out TicksTaken: Int64): String; var StartTick: Int64; begin StartTick := GetTickCount; Result := VarToStr(FuntionToRun); WriteTicksToDebug(aDisplayName, StartTick); TicksTaken := GetTickCount - StartTick; end; procedure TAdventOfCode.LoadInput; var FilePath: string; procedure _DownLoadInput; begin AOCUtils.DownLoadPuzzleInput(FInput, DayIndex); FInput.SaveToFile(FilePath); end; begin FilePath := InputFilePath; if FileExists(FilePath) then begin FInput.LoadFromFile(FilePath); if (FInput.Count > 0) And (FInput[0].StartsWith('Please don')) then _DownLoadInput //File exists, but downloaded to early, let's try again end else _DownLoadInput; end; procedure TAdventOfCode.Solve; var TimeA, TimeB, StartTime, TotalTime: Int64; SolutionA, SolutionB: String; begin StartTime := GetTickCount; InternalSolve(SolutionA, SolutionB, TimeA, TimeB); TotalTime := GetTickCount - StartTime; if (MessageDlg(Format('Solution A: %s Solved in %d ms.' +#10#13 + 'Copy to clipboard?', [SolutionA, TimeA]), mtInformation, [mbYes, mbNo], 0) <> Ord(mbNo)) then Clipboard.AsText := SolutionA; if (MessageDlg(Format('Solution B: %s Solved in %d ms.' + #10#13 + 'Total execution time: %d ms.' + #10#13 + 'Copy to clipboard?', [SolutionB, TimeB, TotalTime]), mtInformation, [mbYes, mbNo], 0) <> Ord(mbNo)) then Clipboard.AsText := SolutionB; end; procedure TAdventOfCode.InternalSolve(Out SolutionA, SolutionB: String; out TimeA, TimeB: Int64); begin DoProcedure(BeforeSolve, 'BeforeSolve'); SolutionA := DoFunction(SolveA, 'SolveA', TimeA); SolutionB := DoFunction(SolveB, 'SolveB', TimeB); DoProcedure(AfterSolve, 'AfterSolve'); end; procedure TAdventOfCode.Test(Out SolutionA, SolutionB: String; Const OverRidenTestInput: String); var Dummy: Int64; begin if OverRidenTestInput <> '' then begin FInput.Clear; FInput.Add(OverRidenTestInput); end; InternalSolve(SolutionA, SolutionB, Dummy, Dummy); end; end.
unit Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.JSON, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Controls, ChromeTabs, ChromeTabsClasses, ChromeTabsTypes, Utils.General, Messaging.EventBus, ExtGUI.ListBox.Books, Action.ImportFromWebService, Plus.TWork; type TForm1 = class(TForm) GroupBox1: TGroupBox; lbBooksReaded: TLabel; Splitter1: TSplitter; lbBooksAvaliable: TLabel; lbxBooksReaded: TListBox; lbxBooksAvaliable2: TListBox; ChromeTabs1: TChromeTabs; pnMain: TPanel; btnImport: TButton; tmrAppReady: TTimer; Splitter2: TSplitter; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ChromeTabs1ButtonCloseTabClick(Sender: TObject; ATab: TChromeTab; var Close: Boolean); procedure ChromeTabs1Change(Sender: TObject; ATab: TChromeTab; TabChangeType: TTabChangeType); procedure FormResize(Sender: TObject); procedure Splitter1Moved(Sender: TObject); procedure tmrAppReadyTimer(Sender: TObject); private FBooksConfig: TBooksListBoxConfigurator; actImportFromWebService: TWorkAction; procedure OnImportReaderReportLog(MessageID: integer; const AMessagee: TEventMessage); procedure ResizeBooksListBoxesInsideGroupBox(aGroupBox: TGroupBox); function AddChromeTabAndCreateFrame(AFrameClass: TFrameClass; ACaption: string): TFrame; procedure OnWorkFDone(Sender: TObject; Work: TWork); end; var Form1: TForm1; implementation {$R *.dfm} uses System.StrUtils, System.Math, System.DateUtils, Data.DB, Vcl.DBGrids, Vcl.Graphics, // TODO 2: [!] FireDAC dependency (requred because of FDManager) (comments below) // Should be moved into the DataModule FireDAC.Comp.Client, // TODO 2: [!] FireDAC dependency (requred because of EFDDBEngineException) FireDAC.Stan.Error, // ------------------------------------------------------------ Consts.Application, Utils.CipherAES128, Data.Main, ClientAPI.Readers, ClientAPI.Books, Frame.Welcome, Frame.Import, Helper.DataSet, Helper.TDBGrid, Helper.TApplication, Helper.TWinControl, Helper.TJSONObject, Work.ImportBooks, Work.ImportReadReports; var ShowBooksGrid: Boolean = False; procedure TForm1.FormCreate(Sender: TObject); var w1: TWork; w2: TWork; begin pnMain.Caption := ''; TEventBus._Register(EB_ImportReaderReports_LogInfo, OnImportReaderReportLog); FBooksConfig := TBooksListBoxConfigurator.Create(Self); actImportFromWebService := TWorkAction.Create(Self); actImportFromWebService.Caption := 'Import'; btnImport.Action := actImportFromWebService; w1 := actImportFromWebService.CreateAndAddWork(TImportBooksWork); w2 := actImportFromWebService.CreateAndAddWork(TImportReadReportsWork); (w1 as TImportBooksWork).BooksConfig := FBooksConfig; (w2 as TImportReadReportsWork).BooksConfig := FBooksConfig; actImportFromWebService.OnWorkDone := OnWorkFDone; end; procedure TForm1.FormDestroy(Sender: TObject); begin TEventBus._Unregister(EB_ImportReaderReports_LogInfo, OnImportReaderReportLog); end; procedure TForm1.FormResize(Sender: TObject); begin ResizeBooksListBoxesInsideGroupBox(GroupBox1); end; procedure TForm1.OnImportReaderReportLog(MessageID: integer; const AMessagee: TEventMessage); begin Caption := AMessagee.TagString; end; procedure TForm1.OnWorkFDone(Sender: TObject; Work: TWork); var frm: TFrameImport; DataSrc1: TDataSource; DBGrid1: TDBGrid; DataSrc2: TDataSource; DBGrid2: TDBGrid; begin // ---------------------------------------------------------- // ---------------------------------------------------------- frm := AddChromeTabAndCreateFrame(TFrameImport, 'Readers') as TFrameImport; // ---------------------------------------------------------- // ---------------------------------------------------------- // // Dynamically Add TDBGrid to TFrameImport // { TODO 2: [C] Move code down separate bussines logic from GUI } // warning for dataset dependencies, discuss TDBGrid dependencies DataSrc1 := TDataSource.Create(frm); DBGrid1 := TDBGrid.Create(frm); DBGrid1.AlignWithMargins := True; DBGrid1.Parent := frm; DBGrid1.Align := alClient; DBGrid1.DataSource := DataSrc1; DataSrc1.DataSet := DataModMain.dsReaders; // AutoSizeColumns(DBGrid1); DBGrid1.AutoSizeColumns(); // ---------------------------------------------------------- with TSplitter.Create(frm) do begin Align := alBottom; Parent := frm; Height := 5; end; DBGrid1.Margins.Bottom := 0; DataSrc2 := TDataSource.Create(frm); DBGrid2 := TDBGrid.Create(frm); DBGrid2.AlignWithMargins := True; DBGrid2.Parent := frm; DBGrid2.Align := alBottom; DBGrid2.Height := frm.Height div 3; DBGrid2.DataSource := DataSrc2; DataSrc2.DataSet := DataModMain.dsReports; DBGrid2.Margins.Top := 0; // AutoSizeColumns(DBGrid2); DBGrid2.AutoSizeColumns(); end; procedure TForm1.ChromeTabs1ButtonCloseTabClick(Sender: TObject; ATab: TChromeTab; var Close: Boolean); var obj: TObject; begin obj := TObject(ATab.Data); (obj as TFrame).Free; end; procedure TForm1.ChromeTabs1Change(Sender: TObject; ATab: TChromeTab; TabChangeType: TTabChangeType); var obj: TObject; begin if Assigned(ATab) then begin obj := TObject(ATab.Data); if (TabChangeType = tcActivated) and Assigned(obj) then begin pnMain.HideAllChildFrames; (obj as TFrame).Visible := True; end; end; end; procedure TForm1.ResizeBooksListBoxesInsideGroupBox(aGroupBox: TGroupBox); begin lbxBooksReaded.Height := (lbxBooksReaded.Height + lbxBooksAvaliable2.Height) div 2; end; // TODO 99: Usunąć z klasy TForm1 (Form.Main.pas) function TForm1.AddChromeTabAndCreateFrame(AFrameClass: TFrameClass; ACaption: string): TFrame; var tab: TChromeTab; begin Result := AFrameClass.Create(pnMain); Result.Parent := pnMain; Result.Visible := True; Result.Align := alClient; tab := ChromeTabs1.Tabs.Add; tab.Caption := ACaption; tab.Data := Result; end; procedure TForm1.Splitter1Moved(Sender: TObject); begin (Sender as TSplitter).Tag := 1; end; procedure TForm1.tmrAppReadyTimer(Sender: TObject); var frm: TFrameWelcome; datasrc: TDataSource; DataGrid: TDBGrid; begin tmrAppReady.Enabled := False; if Application.IsDeveloperMode then ReportMemoryLeaksOnShutdown := True; // ---------------------------------------------------------- // ---------------------------------------------------------- frm := AddChromeTabAndCreateFrame(TFrameWelcome, 'Welcome') as TFrameWelcome; // ---------------------------------------------------------- DataModMain.VerifyAndConnectToDatabase; // ---------------------------------------------------------- // ---------------------------------------------------------- // // * Initialize ListBox'es for books // * Load books form database // * Setup drag&drop functionality for two list boxes // * Setup OwnerDraw mode // FBooksConfig.PrepareListBoxes(lbxBooksReaded, lbxBooksAvaliable2); // ---------------------------------------------------------- // ---------------------------------------------------------- // // Create Books Grid for Quality Tests if Application.IsDeveloperMode and ShowBooksGrid then begin datasrc := TDataSource.Create(frm); DataGrid := TDBGrid.Create(frm); DataGrid.AlignWithMargins := True; DataGrid.Parent := frm; DataGrid.Align := alClient; DataGrid.DataSource := datasrc; datasrc.DataSet := DataModMain.dsBooks; // AutoSizeColumns(DataGrid); DataGrid.AutoSizeColumns(); end; end; end.
unit uLanguageForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uCommonForm, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, DBGridEh, RXDBCtrl,uOilQuery,Ora, uOilStoredProc; type TLanguageForm = class(TCommonForm) cbInterfaceLang: TComboBox; cbReportsLang: TComboBox; lbIntfLang: TLabel; lbRepLang: TLabel; Label1: TLabel; bbOk: TBitBtn; procedure FormCreate(Sender: TObject); procedure cbReportsLangChange(Sender: TObject); procedure cbInterfaceLangChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private public end; var LanguageForm: TLanguageForm; implementation uses Main, ExFunc; {$R *.DFM} procedure TLanguageForm.FormCreate(Sender: TObject); var Lang: String; begin inherited; cbReportsLang.ItemIndex := LANGUAGE; try Lang := ReadPieceOfRegistry(HKEY_CURRENT_USER,'Software\Oil','Language'); if Lang <> '' then cbInterfaceLang.ItemIndex := StrToInt(Lang) else cbInterfaceLang.ItemIndex := 0; except cbInterfaceLang.ItemIndex := 0; end; end; procedure TLanguageForm.cbReportsLangChange(Sender: TObject); begin inherited; if cbReportsLang.ItemIndex >= 0 then InitLanguage(cbReportsLang.ItemIndex); end; procedure TLanguageForm.cbInterfaceLangChange(Sender: TObject); begin inherited; if cbInterfaceLang.ItemIndex >= 0 then InitInterfaceLanguage(cbInterfaceLang.ItemIndex); end; procedure TLanguageForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; end.
unit gr_StudentCards_Filter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxCheckBox, StdCtrls, cxButtons, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls, cxGroupBox, cxSpinEdit, cxDropDownEdit, Unit_ZGlobal_Consts, IBase, PackageLoad, ZTypes, Dates, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, ZMessages, cxRadioGroup, cxLabel, ZProc, ActnList; type TZTypeDataFilter = (tztdfPeople,tztdfDepartment,tztdfVidOpl,tztdfNULL); function TypeDataFilterToByte(AParameter:TZTypeDataFilter):Byte; type TGrDataFilter = record KodSetup1:integer; KodSetup2:integer; TypeId:TZTypeDataFilter; Id:integer; TextId:string; ModalResult:TModalResult; end; type TGrStudentCardsFilter = class(TForm) YesBtn: TcxButton; CancelBtn: TcxButton; BoxKodSetup: TcxGroupBox; MonthesList1: TcxComboBox; YearSpinEdit1: TcxSpinEdit; DB: TpFIBDatabase; DSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; BoxDataFilter: TcxGroupBox; EditDataFilter: TcxButtonEdit; FilterType: TcxRadioGroup; MonthesList2: TcxComboBox; YearSpinEdit2: TcxSpinEdit; LabelFrom: TcxLabel; LabelTo: TcxLabel; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EditDataFilterPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FilterTypePropertiesChange(Sender: TObject); procedure ActionYesExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); private PParameter:TGrDataFilter; PLanguageIndex:byte; public constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TGrDataFilter);reintroduce; property Parameter:TGrDataFilter read PParameter; end; function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TGrDataFilter):TGrDataFilter; implementation uses StrUtils; {$R *.dfm} function TypeDataFilterToByte(AParameter:TZTypeDataFilter):Byte; begin Result:=0; case AParameter of tztdfPeople: Result:=1; tztdfDepartment: Result:=2; tztdfNULL: Result:=3; end; end; function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TGrDataFilter):TGrDataFilter; var Filter:TGrStudentCardsFilter; Res:TGrDataFilter; begin Filter := TGrStudentCardsFilter.Create(AOwner,ADB_Handle,AParameter); Res:=AParameter; if Filter.ShowModal=mrYes then Res:=Filter.Parameter; Res.ModalResult:=Filter.ModalResult; Filter.Free; ViewFilter:=Res; end; constructor TGrStudentCardsFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TGrDataFilter); begin inherited Create(AOwner); PParameter:=AParameter; PLanguageIndex:=LanguageIndex; //****************************************************************************** Caption := FilterBtn_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint := CancelBtn.Caption; FilterType.Properties.Items[0].Caption := LabelMan_Caption[PLanguageIndex]; FilterType.Properties.Items[1].Caption := LabelDepartment_Caption[PLanguageIndex]; FilterType.Properties.Items[2].Caption := LabelNotFilter_Caption[PLanguageIndex]; LabelFrom.Caption := LabelDateBeg_Caption[PLanguageIndex]; LabelTo.Caption := AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]); MonthesList1.Properties.Items.Text := MonthesList_Text[PlanguageIndex]; MonthesList2.Properties.Items.Text := MonthesList_Text[PlanguageIndex]; //****************************************************************************** DB.Handle := ADB_Handle; ReadTransaction.StartTransaction; if PParameter.KodSetup1=0 then begin DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_KOD_SETUP_RETURN'; DSet.Open; YearSpinEdit1.Value:=YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP']); MonthesList1.ItemIndex:= YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP'],false)-1; end else begin YearSpinEdit1.Value:=YearMonthFromKodSetup(PParameter.KodSetup1); MonthesList1.ItemIndex:= YearMonthFromKodSetup(PParameter.KodSetup1,false)-1; end; if PParameter.KodSetup2=0 then begin if not DSet.Active then begin DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_KOD_SETUP_RETURN'; DSet.Open; end; YearSpinEdit2.Value:=YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP']); MonthesList2.ItemIndex:= YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP'],false)-1; end else begin YearSpinEdit2.Value:=YearMonthFromKodSetup(PParameter.KodSetup2); MonthesList2.ItemIndex:= YearMonthFromKodSetup(PParameter.KodSetup2,false)-1; end; case PParameter.TypeId of tztdfPeople: begin FilterType.ItemIndex:=0; BoxDataFilter.Enabled:=True; EditDataFilter.Text := PParameter.TextId; end; tztdfDepartment: begin FilterType.ItemIndex:=1; BoxDataFilter.Enabled:=True; EditDataFilter.Text := PParameter.TextId; end; tztdfVidOpl: begin FilterType.ItemIndex:=2; BoxDataFilter.Enabled:=True; EditDataFilter.Text := PParameter.TextId; end; tztdfNULL: begin FilterType.ItemIndex:=3; BoxDataFilter.Enabled:=False; EditDataFilter.Text := ''; end; end; //****************************************************************************** end; procedure TGrStudentCardsFilter.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; end; procedure TGrStudentCardsFilter.EditDataFilterPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var ResultView:Variant; begin case FilterType.ItemIndex of 0: ResultView:=LoadPeopleModal(Self,DB.Handle); 1: ResultView:=LoadDepartment(Self,DB.Handle,zfsNormal); end; if VarArrayDimCount(ResultView)> 0 then If ResultView[0]<>NULL then begin case FilterType.ItemIndex of 0: begin PParameter.TypeId := tztdfPeople; EditDataFilter.Text := VarToStr(ResultView[4])+' - '+ VarToStr(ResultView[1])+' '+ VarToStr(ResultView[2])+' '+ VarToStr(ResultView[3]); PParameter.Id := ResultView[0]; PParameter.TextId := EditDataFilter.Text; end; 1: begin PParameter.TypeId := tztdfDepartment; EditDataFilter.Text := VarToStr(ResultView[1]); PParameter.Id := ResultView[0]; PParameter.TextId := VarToStr(ResultView[1]); end; 2: begin PParameter.TypeId := tztdfVidOpl; EditDataFilter.Text := VarToStr(ResultView[2])+' - '+ VarToStr(ResultView[1]); PParameter.Id := ResultView[0]; PParameter.TextId := EditDataFilter.Text; end; end; end; end; procedure TGrStudentCardsFilter.FilterTypePropertiesChange(Sender: TObject); var CurrentSelect:byte; begin CurrentSelect:=0; case PParameter.TypeId of tztdfPeople: CurrentSelect:=0; tztdfDepartment: CurrentSelect:=1; tztdfNULL: CurrentSelect:=2; end; BoxDataFilter.Enabled := (FilterType.ItemIndex<>FilterType.Properties.Items.Count-1); EditDataFilter.Text := IfThen(FilterType.ItemIndex=CurrentSelect,PParameter.TextId,''); end; procedure TGrStudentCardsFilter.ActionYesExecute(Sender: TObject); begin if FilterType.ItemIndex = FilterType.Properties.Items.Count-1 then begin PParameter.TypeId := tztdfNULL; PParameter.Id := 0; PParameter.TextId := ''; end; if PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1)>PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1) then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputKodSetups_ErrorText[PLanguageIndex],mtWarning,[mbOK]); MonthesList1.SetFocus; end else begin PParameter.KodSetup1:=PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1); PParameter.KodSetup2:=PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1); ModalResult:=mrYes; end; end; procedure TGrStudentCardsFilter.ActionCancelExecute(Sender: TObject); begin ModalResult:=mrCancel; end; end.
// // Generated by JavaToPas v1.5 20180804 - 082421 //////////////////////////////////////////////////////////////////////////////// unit android.location.GnssMeasurementsEvent_Callback; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.location.GnssMeasurementsEvent; type JGnssMeasurementsEvent_Callback = interface; JGnssMeasurementsEvent_CallbackClass = interface(JObjectClass) ['{A9C12E6B-7C23-43F9-B016-63CB0324217C}'] function _GetSTATUS_LOCATION_DISABLED : Integer; cdecl; // A: $19 function _GetSTATUS_NOT_SUPPORTED : Integer; cdecl; // A: $19 function _GetSTATUS_READY : Integer; cdecl; // A: $19 function init : JGnssMeasurementsEvent_Callback; cdecl; // ()V A: $1 procedure onGnssMeasurementsReceived(eventArgs : JGnssMeasurementsEvent) ; cdecl;// (Landroid/location/GnssMeasurementsEvent;)V A: $1 procedure onStatusChanged(status : Integer) ; cdecl; // (I)V A: $1 property STATUS_LOCATION_DISABLED : Integer read _GetSTATUS_LOCATION_DISABLED;// I A: $19 property STATUS_NOT_SUPPORTED : Integer read _GetSTATUS_NOT_SUPPORTED; // I A: $19 property STATUS_READY : Integer read _GetSTATUS_READY; // I A: $19 end; [JavaSignature('android/location/GnssMeasurementsEvent_Callback')] JGnssMeasurementsEvent_Callback = interface(JObject) ['{72B1154C-8E53-431B-8166-BF0E5810662A}'] procedure onGnssMeasurementsReceived(eventArgs : JGnssMeasurementsEvent) ; cdecl;// (Landroid/location/GnssMeasurementsEvent;)V A: $1 procedure onStatusChanged(status : Integer) ; cdecl; // (I)V A: $1 end; TJGnssMeasurementsEvent_Callback = class(TJavaGenericImport<JGnssMeasurementsEvent_CallbackClass, JGnssMeasurementsEvent_Callback>) end; const TJGnssMeasurementsEvent_CallbackSTATUS_LOCATION_DISABLED = 2; TJGnssMeasurementsEvent_CallbackSTATUS_NOT_SUPPORTED = 0; TJGnssMeasurementsEvent_CallbackSTATUS_READY = 1; implementation end.
unit NSqlFirebirdApiHelpersImpl; {$I ..\..\NSql.Inc} interface uses NSqlFirebirdApiHelpersIntf; function CreateDpb: IDpbBuilder; overload; function CreateTpb: ITpbBuilder; overload; implementation uses {$IFDEF NSQL_XE2UP} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} NSqlFirebirdBaseApi, NSqlSys; type TDpbBuilder = class(TInterfacedObject, IDpbBuilder) private FResult: AnsiString; FDescription: UnicodeString; FConnectionCharSet: UnicodeString; procedure AddId(Id: Byte; const ParamName: UnicodeString); // procedure AddByte(Id: Byte; Value: Byte; const ParamName: UnicodeString); procedure AddCardinal(Id: Byte; Value: Cardinal; const ParamName: UnicodeString); procedure AddString(Id: Byte; const Value: UnicodeString; const ParamName: UnicodeString); procedure AddToDescriptionEx(const S: UnicodeString); protected { IDpbBuilder } function PageSize(Value: Cardinal): IDpbBuilder; function NumBuffers(Value: Cardinal): IDpbBuilder; // function Debug(Value: Cardinal): IDpbBuilder; function Verify(Value: Cardinal): IDpbBuilder; function Sweep(Value: Cardinal): IDpbBuilder; function EnableJournal(const Value: UnicodeString): IDpbBuilder; function DisableJournal: IDpbBuilder; function DbkeyScope(Value: Cardinal): IDpbBuilder; // function Trace: IDpbBuilder; function Damaged: IDpbBuilder; function SysUserName(const Value: UnicodeString): IDpbBuilder; function EncryptKey(const Value: UnicodeString): IDpbBuilder; function SweepInterval(Value: Cardinal): IDpbBuilder; function DeleteShadow: IDpbBuilder; function ForceWrite(Value: Cardinal): IDpbBuilder; function BeginLog(const Value: UnicodeString): IDpbBuilder; function QuitLog: IDpbBuilder; function NoReserve(Value: Cardinal): IDpbBuilder; function UserName(const Value: UnicodeString): IDpbBuilder; function Password(const Value: UnicodeString): IDpbBuilder; function PasswordEnc(const Value: UnicodeString): IDpbBuilder; function SysUserNameEnc: IDpbBuilder; // function Interp(Value: Cardinal): IDpbBuilder; // function OnlineDump(Value: Cardinal): IDpbBuilder; // function OldFileSize(Value: Cardinal): IDpbBuilder; // function OldNumFiles(Value: Cardinal): IDpbBuilder; // function OldFile(const Value: UnicodeString): IDpbBuilder; // function OldStartPage(Value: Cardinal): IDpbBuilder; // function OldStartSeqno(Value: Cardinal): IDpbBuilder; // function OldStartFile(Value: Cardinal): IDpbBuilder; // function DropWalfile(Value: Cardinal): IDpbBuilder; // function OldDumpId(Value: Cardinal): IDpbBuilder; function WalBackupDir(const Value: UnicodeString): IDpbBuilder; function WalChktplen(Value: Cardinal): IDpbBuilder; function WalNumbufs(Value: Cardinal): IDpbBuilder; function WalBufsize(Value: Cardinal): IDpbBuilder; function WalGrpCmtWait(Value: Cardinal): IDpbBuilder; function LcMessages(const Value: UnicodeString): IDpbBuilder; function LcCtype(const Value: UnicodeString): IDpbBuilder; function Shutdown(Value: Cardinal): IDpbBuilder; function Online: IDpbBuilder; // function ShutdownDelay(Value: Cardinal): IDpbBuilder; function Reserved(const Value: UnicodeString): IDpbBuilder; function Overwrite(Value: Cardinal): IDpbBuilder; // function SecAttach(Value: Cardinal): IDpbBuilder; function DisableWal: IDpbBuilder; function ConnectTimeout(Value: Cardinal): IDpbBuilder; function DummyPacketInterval(Value: Cardinal): IDpbBuilder; // function GbakAttach(const Value: UnicodeString): IDpbBuilder; function SqlRoleName(const Value: UnicodeString): IDpbBuilder; // rolename function SetPageBuffers(Value: Cardinal): IDpbBuilder; // Change page buffer 50 >= buf >= 65535 (default 2048) function WorkingDirectory(const Value: UnicodeString): IDpbBuilder; function SqlDialect(Value: Cardinal): IDpbBuilder; // Set SQL Dialect for this connection function SetDbReadonly(Value: Cardinal): IDpbBuilder; function SetDbSqlDialect(Value: Cardinal): IDpbBuilder; // Change sqldialect // FB103_UP function SetDbCharset(const Value: UnicodeString): IDpbBuilder; // FB20_UP // function GsecAttach(Value: Byte): IDpbBuilder; function AddressPath(const Value: UnicodeString): IDpbBuilder; // FB21_UP function ProcessId(Value: Cardinal): IDpbBuilder; function NoDbTriggers(Value: Byte): IDpbBuilder; function TrustedAuth(const Value: UnicodeString): IDpbBuilder; function ProcessName(const Value: UnicodeString): IDpbBuilder; // FB25_UP function TrustedRole: IDpbBuilder; function OrgFilename(const Value: UnicodeString): IDpbBuilder; function Utf8Filename: IDpbBuilder; function ExtCallDepth(Value: Cardinal): IDpbBuilder; function Get: AnsiString; function GetDescription: UnicodeString; function GetConnectionCharSet: UnicodeString; public constructor Create; end; TTpbBuilder = class(TInterfacedObject, ITpbBuilder) private FResult: AnsiString; FIsReadOnly: Boolean; FDescription: UnicodeString; FComment: UnicodeString; procedure AddToDescription(const S: UnicodeString); protected { ITpbBuilder } // Access mode (default: Write) function Read: ITpbBuilder; function Write: ITpbBuilder; // Isolation level (default: Concurency) function Concurency: ITpbBuilder; function Consistency: ITpbBuilder; function ReadCommitedRecVersion: ITpbBuilder; function ReadCommitedNoRecVersion: ITpbBuilder; // Lock resolution (default: Wait) function Wait: ITpbBuilder; function NoWait: ITpbBuilder; // Table reservation // isc_tpb_lock_write | isc_tpb_lock_read <TABLE NAME> isc_tpb_shared | isc_tpb_protected | isc_tpb_exclusive function LockReadShared(const TableName: UnicodeString): ITpbBuilder; function LockReadProtected(const TableName: UnicodeString): ITpbBuilder; function LockReadExclusive(const TableName: UnicodeString): ITpbBuilder; function LockWriteShared(const TableName: UnicodeString): ITpbBuilder; function LockWriteProtected(const TableName: UnicodeString): ITpbBuilder; function LockWriteExclusive(const TableName: UnicodeString): ITpbBuilder; function Get: AnsiString; function GetIsReadOnly: Boolean; function GetDescription: UnicodeString; function GetComment: UnicodeString; function Comment(const Value: UnicodeString): ITpbBuilder; public constructor Create; end; function CreateDpb: IDpbBuilder; overload; begin Result := TDpbBuilder.Create; end; function CreateTpb: ITpbBuilder; overload; begin Result := TTpbBuilder.Create; end; { TDpbBuilder } //procedure TDpbBuilder.AddByte(Id, Value: Byte; const ParamName: UnicodeString); //var // S: AnsiString; //begin // SetLength(S, 2); // S[1] := AnsiChar(Id); // S[2] := AnsiChar(Value); // FResult := FResult + S; // AddToDescriptionEx(ParamName + ' = ' + IntToStr(Value)); //end; procedure TDpbBuilder.AddCardinal(Id: Byte; Value: Cardinal; const ParamName: UnicodeString); var S: AnsiString; begin if Value <= 255 then begin SetLength(S, 3); S[1] := AnsiChar(Id); S[2] := AnsiChar(1); S[3] := AnsiChar(Byte(Value)); end else if Value <= 65535 then begin SetLength(S, 4); S[1] := AnsiChar(Id); S[2] := AnsiChar(2); PWord(@S[3])^ := Word(Value); end else begin SetLength(S, 6); S[1] := AnsiChar(Id); S[2] := AnsiChar(4); PCardinal(@S[3])^ := Value; end; FResult := FResult + S; AddToDescriptionEx(ParamName + ' = ' + IntToStr(Value)); end; procedure TDpbBuilder.AddId(Id: Byte; const ParamName: UnicodeString); var S: AnsiString; begin SetLength(S, 2); S[1] := AnsiChar(Id); S[2] := #0; FResult := FResult + S; AddToDescriptionEx(ParamName); end; function TDpbBuilder.AddressPath(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_address_path, Value, 'address_path'); end; procedure TDpbBuilder.AddString(Id: Byte; const Value: UnicodeString; const ParamName: UnicodeString); var AValue: AnsiString; S: AnsiString; begin AValue := NSqlUnicodeStringToUtf8Bytes(Value); if Length(AValue) > 255 then Assert(False, 'DPB generator: strng length greater than 255:'#13#10 + AValue); S := AnsiChar(Id) + AnsiChar(Byte(Length(AValue))) + AValue; FResult := FResult + S; AddToDescriptionEx(ParamName + ' = "' + Value + '"'); end; procedure TDpbBuilder.AddToDescriptionEx(const S: UnicodeString); begin if FDescription = '' then FDescription := S else FDescription := FDescription + ', ' + S; end; function TDpbBuilder.BeginLog(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_begin_log, Value, 'begin_log'); end; function TDpbBuilder.ConnectTimeout(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_connect_timeout, Value, 'connect_timeout'); end; constructor TDpbBuilder.Create; begin inherited Create; FResult := AnsiChar(BaseApi.isc_dpb_version1); end; function TDpbBuilder.Damaged: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_damaged, 'damaged'); end; function TDpbBuilder.DbkeyScope(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_dbkey_scope, Value, 'dbkey_scope'); end; //function TDpbBuilder.Debug(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_debug, Value, 'debug'); //end; function TDpbBuilder.DeleteShadow: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_delete_shadow, 'delete_shadow'); end; function TDpbBuilder.DisableJournal: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_disable_journal, 'disable_journal'); end; function TDpbBuilder.DisableWal: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_disable_wal, 'disable_wal'); end; //function TDpbBuilder.DropWalfile(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_drop_walfile, Value, 'drop_walfile'); //end; function TDpbBuilder.DummyPacketInterval(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_dummy_packet_interval, Value, 'dummy_packet_interval'); end; function TDpbBuilder.EnableJournal(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_enable_journal, Value, 'enable_journal'); end; function TDpbBuilder.EncryptKey(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_encrypt_key, Value, 'encrypt_key'); end; function TDpbBuilder.ExtCallDepth(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_ext_call_depth, Value, 'ext_call_depth'); end; function TDpbBuilder.ForceWrite(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_force_write, Value, 'force_write'); end; //function TDpbBuilder.GbakAttach(const Value: UnicodeString): IDpbBuilder; //begin // Result := Self; // AddString(BaseApi.isc_dpb_gbak_attach, Value, 'gbak_attach'); //end; function TDpbBuilder.Get: AnsiString; begin Result := FResult; end; function TDpbBuilder.GetConnectionCharSet: UnicodeString; begin Result := FConnectionCharSet; end; function TDpbBuilder.GetDescription: UnicodeString; begin Result := FDescription; end; //function TDpbBuilder.GsecAttach(Value: Byte): IDpbBuilder; //begin // Result := Self; // AddId(BaseApi.isc_dpb_gsec_attach, 'gsec_attach'); //end; //function TDpbBuilder.Interp(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_interp, Value, 'interp'); //end; function TDpbBuilder.LcCtype(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_lc_ctype, Value, 'lc_ctype'); FConnectionCharSet := Value; end; function TDpbBuilder.LcMessages(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_lc_messages, Value, 'lc_messages'); end; function TDpbBuilder.NoDbTriggers(Value: Byte): IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_no_db_triggers, 'no_db_triggers'); end; function TDpbBuilder.NoReserve(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_no_reserve, Value, 'no_reserve'); end; function TDpbBuilder.NumBuffers(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_num_buffers, Value, 'num_buffers'); end; //function TDpbBuilder.OldDumpId(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_dump_id, Value, 'old_dump_id'); //end; //function TDpbBuilder.OldFile(const Value: UnicodeString): IDpbBuilder; //begin // Result := Self; // AddString(BaseApi.isc_dpb_old_file, Value, 'old_file'); //end; //function TDpbBuilder.OldFileSize(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_file_size, Value, 'old_file_size'); //end; //function TDpbBuilder.OldNumFiles(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_num_files, Value, 'old_num_files'); //end; //function TDpbBuilder.OldStartFile(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_start_file, Value, 'old_start_file'); //end; //function TDpbBuilder.OldStartPage(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_start_page, Value, 'old_start_page'); //end; //function TDpbBuilder.OldStartSeqno(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_old_start_seqno, Value, 'old_start_seqno'); //end; function TDpbBuilder.Online: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_online, 'online'); end; //function TDpbBuilder.OnlineDump(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_online_dump, Value, 'online_dump'); //end; function TDpbBuilder.OrgFilename(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_org_filename, Value, 'org_filename'); end; function TDpbBuilder.Overwrite(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_overwrite, Value, 'overwrite'); end; function TDpbBuilder.PageSize(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_page_size, Value, 'page_size'); end; function TDpbBuilder.Password(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_password, Value, 'password'); end; function TDpbBuilder.PasswordEnc(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_password_enc, Value, 'password_enc'); end; function TDpbBuilder.ProcessId(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_process_id, Value, 'process_id'); end; function TDpbBuilder.ProcessName(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_process_name, Value, 'process_name'); end; function TDpbBuilder.QuitLog: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_quit_log, 'quit_log'); end; function TDpbBuilder.Reserved(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_reserved, Value, 'reserved'); end; //function TDpbBuilder.SecAttach(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_sec_attach, Value, 'sec_attach'); //end; function TDpbBuilder.SetDbCharset(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_set_db_charset, Value, 'set_db_charset'); end; function TDpbBuilder.SetDbReadonly(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_set_db_readonly, Value, 'set_db_readonly'); end; function TDpbBuilder.SetDbSqlDialect(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_set_db_sql_dialect, Value, 'set_db_sql_dialect'); end; function TDpbBuilder.SetPageBuffers(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_set_page_buffers, Value, 'set_page_buffers'); end; function TDpbBuilder.Shutdown(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_shutdown, Value, 'shutdown'); end; //function TDpbBuilder.ShutdownDelay(Value: Cardinal): IDpbBuilder; //begin // Result := Self; // AddCardinal(BaseApi.isc_dpb_shutdown_delay, Value, 'shutdown_delay'); //end; function TDpbBuilder.SqlDialect(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_sql_dialect, Value, 'sql_dialect'); end; function TDpbBuilder.SqlRoleName(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_sql_role_name, Value, 'sql_role_name'); end; function TDpbBuilder.Sweep(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_sweep, Value, 'sweep'); end; function TDpbBuilder.SweepInterval(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_sweep_interval, Value, 'sweep_interval'); end; function TDpbBuilder.SysUserName(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_user_name, Value, 'user_name'); end; function TDpbBuilder.SysUserNameEnc: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_sys_user_name_enc, 'sys_user_name_enc'); end; //function TDpbBuilder.Trace: IDpbBuilder; //begin // Result := Self; // AddId(BaseApi.isc_dpb_trace, 'trace'); //end; function TDpbBuilder.TrustedAuth(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_trusted_auth, Value, 'trusted_auth'); end; function TDpbBuilder.TrustedRole: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_trusted_role, 'trusted_role'); end; function TDpbBuilder.UserName(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_user_name, Value, 'user_name'); end; function TDpbBuilder.Utf8Filename: IDpbBuilder; begin Result := Self; AddId(BaseApi.isc_dpb_utf8_filename, 'utf8_filename'); end; function TDpbBuilder.Verify(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_verify, Value, 'verify'); end; function TDpbBuilder.WalBackupDir(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_wal_backup_dir, Value, 'wal_backup_dir'); end; function TDpbBuilder.WalBufsize(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_wal_bufsize, Value, 'wal_bufsize'); end; function TDpbBuilder.WalChktplen(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_wal_chkptlen, Value, 'wal_chkptlen'); end; function TDpbBuilder.WalGrpCmtWait(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_wal_grp_cmt_wait, Value, 'wal_grp_cmt_wait'); end; function TDpbBuilder.WalNumbufs(Value: Cardinal): IDpbBuilder; begin Result := Self; AddCardinal(BaseApi.isc_dpb_wal_numbufs, Value, 'wal_numbufs'); end; function TDpbBuilder.WorkingDirectory(const Value: UnicodeString): IDpbBuilder; begin Result := Self; AddString(BaseApi.isc_dpb_working_directory, Value, 'working_directory'); end; { TTpbBuilder } procedure TTpbBuilder.AddToDescription(const S: UnicodeString); begin if FDescription = '' then FDescription := S else FDescription := FDescription + ', ' + S; end; function TTpbBuilder.Comment(const Value: UnicodeString): ITpbBuilder; begin Result := Self; FComment := Value; if FComment <> '' then AddToDescription('comment: "' + FComment + '"'); end; function TTpbBuilder.Concurency: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_concurrency; AddToDescription('concurency'); end; function TTpbBuilder.Consistency: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_consistency; AddToDescription('consistency'); end; constructor TTpbBuilder.Create; begin inherited Create; FResult := AnsiChar(BaseApi.isc_tpb_version3); end; function TTpbBuilder.Get: AnsiString; begin Result := FResult; end; function TTpbBuilder.GetComment: UnicodeString; begin Result := FComment; end; function TTpbBuilder.GetDescription: UnicodeString; begin Result := FDescription; end; function TTpbBuilder.GetIsReadOnly: Boolean; begin Result := FIsReadOnly; end; function TTpbBuilder.LockReadExclusive( const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_read + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_exclusive ; AddToDescription('lock_read, "' + TableName + '", exclusive'); end; function TTpbBuilder.LockReadProtected( const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_read + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_protected ; AddToDescription('lock_read, "' + TableName + '", protected'); end; function TTpbBuilder.LockReadShared(const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_read + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_shared ; AddToDescription('lock_read, "' + TableName + '", shared'); end; function TTpbBuilder.LockWriteExclusive( const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_write + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_exclusive ; AddToDescription('lock_write, "' + TableName + '", exclusive'); end; function TTpbBuilder.LockWriteProtected( const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_write + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_protected ; AddToDescription('lock_write, "' + TableName + '", protected'); end; function TTpbBuilder.LockWriteShared(const TableName: UnicodeString): ITpbBuilder; var Utf8TableName: AnsiString; begin Result := Self; Utf8TableName := NSqlUnicodeStringToUtf8Bytes(TableName); FResult := FResult + BaseApi.isc_tpb_lock_write + AnsiChar(Byte(Length(Utf8TableName))) + Utf8TableName + BaseApi.isc_tpb_shared ; AddToDescription('lock_write, "' + TableName + '", shared'); end; function TTpbBuilder.NoWait: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_nowait; AddToDescription('nowait'); end; function TTpbBuilder.Read: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_read; FIsReadOnly := True; AddToDescription('read'); end; function TTpbBuilder.ReadCommitedNoRecVersion: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_read_committed + BaseApi.isc_tpb_no_rec_version; AddToDescription('read_commited, no_rec_version)'); end; function TTpbBuilder.ReadCommitedRecVersion: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_read_committed + BaseApi.isc_tpb_rec_version; AddToDescription('read_commited, rec_version)'); end; function TTpbBuilder.Wait: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_wait; AddToDescription('wait'); end; function TTpbBuilder.Write: ITpbBuilder; begin Result := Self; FResult := FResult + BaseApi.isc_tpb_write; FIsReadOnly := False; AddToDescription('write'); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.IDE.Types; interface uses DPM.Core.Constants, DPM.Core.Types; {$SCOPEDENUMS ON} type TDPMPackageStatus = (NotInstalled, Installed, //latest version installed. UpdateAvailable //installed but not on the latest version ); TDPMEditViewMode = (vmProject, vmGroup); TDPMSearchOption = (IncludePrerelease, IncludeCommercial, IncludeTrial); TDPMSearchOptions = set of TDPMSearchOption; const //The current IDE version to TCompilerVersion. {$IFDEF VER350}IDECompilerVersion = TCompilerVersion.RS11_0; {$ENDIF} {$IFDEF VER340}IDECompilerVersion = TCompilerVersion.RS10_4; {$ENDIF} {$IFDEF VER330}IDECompilerVersion = TCompilerVersion.RS10_3; {$ENDIF} {$IFDEF VER320}IDECompilerVersion = TCompilerVersion.RS10_2; {$ENDIF} {$IFDEF VER310}IDECompilerVersion = TCompilerVersion.RS10_1; {$ENDIF} {$IFDEF VER300}IDECompilerVersion = TCompilerVersion.RS10_0; {$ENDIF} {$IFDEF VER290}IDECompilerVersion = TCompilerVersion.RSXE8; {$ENDIF} {$IFDEF VER280}IDECompilerVersion = TCompilerVersion.RSXE7; {$ENDIF} {$IFDEF VER270}IDECompilerVersion = TCompilerVersion.RSXE6; {$ENDIF} {$IFDEF VER260}IDECompilerVersion = TCompilerVersion.RSXE5; {$ENDIF} {$IFDEF VER250}IDECompilerVersion = TCompilerVersion.RSXE4; {$ENDIF} {$IFDEF VER240}IDECompilerVersion = TCompilerVersion.RSXE3; {$ENDIF} {$IFDEF VER230}IDECompilerVersion = TCompilerVersion.RSXE2; {$ENDIF} {$IFDEF VER220}IDECompilerVersion = TCompilerVersion.RSXE; {$ENDIF} {$IFDEF VER210}IDECompilerVersion = TCompilerVersion.RS2010; {$ENDIF} cDPMIDEOptionsFileName = 'dpm-ide.config'; cDPMIDEDefaultOptionsFile = cDefaultDPMFolder + '\' + cDPMIDEOptionsFileName; implementation end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uError; {$mode objfpc}{$H+} { Errorhandler. Use command line switch '-traceon' to display trace messages runtime. } interface {$IFNDEF Release} uses SysUtils, Forms, Controls, StdCtrls; {$ENDIF} type TTraceMode = (trOff, trShowWindow); TErrorHandler = class public constructor Create; destructor Destroy; override; procedure SetTraceMode(Mode: TTraceMode); procedure Trace(const Msg: string); private {$IFNDEF Release} TraceMode: TTraceMode; TraceWindow: TForm; TraceMemo: TMemo; {$ENDIF} end; var ErrorHandler: TErrorHandler; implementation {-------------------} { ErrorHandler } constructor TErrorHandler.Create; begin {$IFNDEF Release} SetTraceMode(trOff); // SetTraceMode(trShowWindow); {$ENDIF} end; destructor TErrorHandler.Destroy; begin inherited; if TraceWindow <> nil then TraceWindow.Free; end; procedure TErrorHandler.SetTraceMode(Mode: TTraceMode); { Avgör hur tracemeddelanden visas. trOff Stänger av trace trWinDebug Meddelande skrivs till eventlog Använd View - Debug Windows - Event log i delphi för att visa dessa meddelanden trShowWindow Tracemeddelanden visas i ett eget fönster } begin {$IFNDEF Release} TraceMode := Mode; if (TraceMode = trShowWindow) and (TraceWindow = nil) then begin TraceWindow := TForm.Create(Application.MainForm); //Fönstret skapas nere i högra hörnet, med full bredd. with TraceWindow do begin FormStyle := fsStayOnTop; Left := Screen.Width div 2; Top := (Screen.Height div 3) * 2 -100; Width := Screen.Width div 2; Height := Screen.Height div 3; end; TraceMemo := TMemo.Create(TraceWindow); with TraceMemo do begin Parent := TraceWindow; Align := alClient; ScrollBars := ssVertical; end; TraceWindow.Show; end; {$ENDIF} end; procedure TErrorHandler.Trace(const Msg: string); begin {$IFNDEF Release} case TraceMode of trOff: ; trShowWindow: TraceMemo.Lines.Add(Msg); end; {$ENDIF} end; {--------------------} initialization ErrorHandler := TErrorHandler.Create; {$IFNDEF Release} // if FindCmdLineSwitch('traceon', ['-', '/'], True) then // ErrorHandler.SetTraceMode(trShowWindow); {$ENDIF} finalization ErrorHandler.Free; end.
unit St_sp_Build_livers_registration_view; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxTextEdit, cxCalendar, cxCurrencyEdit, DB, cxDBData, cxLookAndFeelPainters, FIBDataSet, pFIBDataSet, cxDropDownEdit, StdCtrls, cxButtons, cxGridDBTableView, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxPC, cxMaskEdit, cxCheckBox, cxContainer, cxGroupBox; type TRegistration_Form = class(TForm) cxPageControl1: TcxPageControl; cxTabSheet1: TcxTabSheet; cxGroupBox1: TcxGroupBox; Full_Build_Label: TLabel; cxGrid2: TcxGrid; cxGridTableView_of_Live: TcxGridTableView; cxGridColumn3: TcxGridColumn; cxGridColumn0: TcxGridColumn; cxGridColumn1: TcxGridColumn; cxGridColumn2: TcxGridColumn; cxGridColumn4: TcxGridColumn; cxGridColumn5: TcxGridColumn; cxGridColumn6: TcxGridColumn; cxGridColumn7: TcxGridColumn; flag4: TcxGridColumn; cxGridLevel1: TcxGridLevel; cxTabSheet2: TcxTabSheet; cxGroupBox4: TcxGroupBox; Full_Cat_Label: TLabel; cxGrid1: TcxGrid; cxGridTableView1: TcxGridTableView; cxGridTableView1Column1: TcxGridColumn; cxGridTableView1Column2: TcxGridColumn; cxGridTableView1Column3: TcxGridColumn; cxGridTableView1Column4: TcxGridColumn; cxGridTableView1Column7: TcxGridColumn; flag3: TcxGridColumn; cxGridLevel2: TcxGridLevel; cxTabSheet4: TcxTabSheet; cxGroupBox5: TcxGroupBox; Sub_Type_Label: TLabel; cxGrid3: TcxGrid; cxGridTableView2: TcxGridTableView; cxGridTableView2Column1: TcxGridColumn; cxGridTableView2Column2: TcxGridColumn; cxGridTableView2Column3: TcxGridColumn; cxGridTableView2Column4: TcxGridColumn; cxGridTableView2Column5: TcxGridColumn; cxGridTableView2Column6: TcxGridColumn; cxGridTableView2Column7: TcxGridColumn; cxGridTableView2Column8: TcxGridColumn; cxGridTableView2Column9: TcxGridColumn; cxGridTableView2Column10: TcxGridColumn; flag2: TcxGridColumn; cxGridLevel3: TcxGridLevel; cxTabSheet5: TcxTabSheet; cxGroupBox6: TcxGroupBox; Lgot_Full_Label: TLabel; cxGrid4: TcxGrid; cxGridTableView3: TcxGridTableView; cxGridTableView3Column1: TcxGridColumn; cxGridColumn8: TcxGridColumn; cxGridColumn9: TcxGridColumn; cxGridColumn13: TcxGridColumn; cxGridColumn16: TcxGridColumn; flag: TcxGridColumn; cxGridLevel4: TcxGridLevel; cxTabSheet6: TcxTabSheet; cxGroupBox11: TcxGroupBox; Image1: TImage; cxGrid5: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1TableView1: TcxGridTableView; IstFinance: TcxGridColumn; Summa: TcxGridColumn; id_smeta: TcxGridColumn; id_razdel: TcxGridColumn; id_stat: TcxGridColumn; id_kekv: TcxGridColumn; cxGrid1Level1: TcxGridLevel; Sum_Result: TcxCurrencyEdit; CancelButton: TcxButton; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; FIO_Label: TLabel; Fac_Label: TLabel; Kurs_Label: TLabel; DataRog_Label: TLabel; FIOCOMBO_Label: TLabel; cxGridTableView1Column5: TcxGridColumn; procedure CancelButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cxGridTableView_of_LiveFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure cxGridTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure cxGridTableView2FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure cxGridTableView3FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); private { Private declarations } public procedure SortGridData; procedure SortGridData_Live; procedure SortGridData_Subsidy; procedure SortGridData_Lg; end; var Registration_Form: TRegistration_Form; implementation {$R *.dfm} procedure TRegistration_Form.SortGridData; var i : integer; temp_kod_category : Smallint; doNew : boolean; temp_date_beg, temp_date_end : TDate; temp_Kategoriya : integer; temp_flag, temp_SHORT_NAME_CATEGORY : string; temp_sum : Double; begin if cxGridTableView1.DataController.RecordCount < 2 then exit; doNew := true; while doNew do begin doNew := false; for i := 0 to cxGridTableView1.DataController.RecordCount - 2 do begin if (cxGridTableView1.DataController.Values[i, 1] <= cxGridTableView1.DataController.Values[i + 1, 2]) and (cxGridTableView1.DataController.Values[i, 2] < cxGridTableView1.DataController.Values[i + 1, 2]) then begin temp_flag :=''; temp_kod_category := cxGridTableView1.DataController.Values[i, 0]; temp_date_beg := cxGridTableView1.DataController.Values[i, 1]; temp_date_end := cxGridTableView1.DataController.Values[i, 2]; temp_Kategoriya := cxGridTableView1.DataController.Values[i, 3]; temp_SHORT_NAME_CATEGORY := cxGridTableView1.DataController.Values[i, 4]; temp_sum := cxGridTableView1.DataController.Values[i, 6]; If cxGridTableView1.DataController.Values[i, 5] <> null then begin temp_flag := cxGridTableView1.DataController.Values[i, 5]; cxGridTableView1.DataController.Values[i, 5]:= ''; end; cxGridTableView1.DataController.Values[i, 0] := cxGridTableView1.DataController.Values[i + 1, 0]; cxGridTableView1.DataController.Values[i, 1] := cxGridTableView1.DataController.Values[i + 1, 1]; cxGridTableView1.DataController.Values[i, 2] := cxGridTableView1.DataController.Values[i + 1, 2]; cxGridTableView1.DataController.Values[i, 3] := cxGridTableView1.DataController.Values[i + 1, 3]; cxGridTableView1.DataController.Values[i, 4] := cxGridTableView1.DataController.Values[i + 1, 4]; cxGridTableView1.DataController.Values[i, 6] := cxGridTableView1.DataController.Values[i + 1, 6]; if cxGridTableView1.DataController.Values[i + 1, 5] <> null then begin cxGridTableView1.DataController.Values[i, 5] := cxGridTableView1.DataController.Values[i + 1, 5]; cxGridTableView1.DataController.Values[i + 1, 5]:=''; end; cxGridTableView1.DataController.Values[i + 1, 0] := temp_kod_category; cxGridTableView1.DataController.Values[i + 1, 1] := temp_date_beg; cxGridTableView1.DataController.Values[i + 1, 2] := temp_date_end; cxGridTableView1.DataController.Values[i + 1, 3] := temp_Kategoriya; cxGridTableView1.DataController.Values[i + 1, 4] := temp_SHORT_NAME_CATEGORY; cxGridTableView1.DataController.Values[i + 1, 6] := temp_sum; if temp_flag <> '' then cxGridTableView1.DataController.Values[i + 1, 5] := temp_flag; doNew := true; end; end; end; end; procedure TRegistration_Form.SortGridData_Live; var i, temp_Type_Room, temp_kod_build : integer; doNew : boolean; temp_date_beg, temp_date_end : TDate; temp_flag,temp_obsh, temp_komnata, temp_N_Room, temp_Short_Name_Build: string; begin if cxGridTableView_of_Live.DataController.RecordCount < 2 then exit; doNew := true; while doNew do begin doNew := false; for i := 0 to cxGridTableView_of_Live.DataController.RecordCount - 2 do begin if (cxGridTableView_of_Live.DataController.Values[i, 2] <= cxGridTableView_of_Live.DataController.Values[i + 1, 3]) and (cxGridTableView_of_Live.DataController.Values[i, 3] < cxGridTableView_of_Live.DataController.Values[i + 1, 3]) then begin temp_flag :=''; temp_obsh:= cxGridTableView_of_Live.DataController.Values[i, 0]; temp_komnata:= cxGridTableView_of_Live.DataController.Values[i, 1]; temp_date_beg := cxGridTableView_of_Live.DataController.Values[i, 2]; temp_date_end := cxGridTableView_of_Live.DataController.Values[i, 3]; temp_kod_build:= cxGridTableView_of_Live.DataController.Values[i, 4]; temp_N_Room:= cxGridTableView_of_Live.DataController.Values[i, 5]; temp_Type_Room := cxGridTableView_of_Live.DataController.Values[i, 6]; temp_Short_Name_Build := cxGridTableView_of_Live.DataController.Values[i,7]; if cxGridTableView_of_Live.DataController.Values[i, 8]<> null then begin temp_flag := cxGridTableView_of_Live.DataController.Values[i, 8]; cxGridTableView_of_Live.DataController.Values[i, 8]:= ''; end; cxGridTableView_of_Live.DataController.Values[i, 0] := cxGridTableView_of_Live.DataController.Values[i + 1, 0]; cxGridTableView_of_Live.DataController.Values[i, 1] := cxGridTableView_of_Live.DataController.Values[i + 1, 1]; cxGridTableView_of_Live.DataController.Values[i, 2] := cxGridTableView_of_Live.DataController.Values[i + 1, 2]; cxGridTableView_of_Live.DataController.Values[i, 3] := cxGridTableView_of_Live.DataController.Values[i + 1, 3]; cxGridTableView_of_Live.DataController.Values[i, 4] := cxGridTableView_of_Live.DataController.Values[i + 1, 4]; cxGridTableView_of_Live.DataController.Values[i, 5] := cxGridTableView_of_Live.DataController.Values[i + 1, 5]; cxGridTableView_of_Live.DataController.Values[i, 6] := cxGridTableView_of_Live.DataController.Values[i + 1, 6]; cxGridTableView_of_Live.DataController.Values[i, 7] := cxGridTableView_of_Live.DataController.Values[i + 1, 7]; if cxGridTableView_of_Live.DataController.Values[i + 1, 8]<> null then begin cxGridTableView_of_Live.DataController.Values[i, 8] := cxGridTableView_of_Live.DataController.Values[i + 1, 8]; cxGridTableView_of_Live.DataController.Values[i + 1, 8]:=''; end; cxGridTableView_of_Live.DataController.Values[i + 1, 0] := temp_obsh; cxGridTableView_of_Live.DataController.Values[i + 1, 1] := temp_komnata; cxGridTableView_of_Live.DataController.Values[i + 1, 2] := temp_date_beg; cxGridTableView_of_Live.DataController.Values[i + 1, 3] := temp_date_end; cxGridTableView_of_Live.DataController.Values[i + 1, 4] := temp_kod_build; cxGridTableView_of_Live.DataController.Values[i + 1, 5] := temp_N_Room; cxGridTableView_of_Live.DataController.Values[i + 1, 6] := temp_Type_Room; cxGridTableView_of_Live.DataController.Values[i + 1, 7] := temp_Short_Name_Build; if temp_flag<>'' then cxGridTableView_of_Live.DataController.Values[i + 1, 8] := temp_flag; doNew := true; end; end; end; end; procedure TRegistration_Form.SortGridData_Subsidy; var i ,temp_id_subsidy, temp_id_state : integer; doNew : boolean; temp_date_beg, temp_date_end : TDate; temp_summa, temp_kol_month, temp_sostoyanie, temp_Comment, temp_fullname, temp_short_name:string ; temp_flag : string; begin if cxGridTableView2.DataController.RecordCount < 2 then exit; doNew := true; while doNew do begin doNew := false; for i := 0 to cxGridTableView2.DataController.RecordCount - 2 do begin temp_flag :=''; if (cxGridTableView2.DataController.Values[i, 0] <= cxGridTableView2.DataController.Values[i + 1, 1]) and (cxGridTableView2.DataController.Values[i, 1] < cxGridTableView2.DataController.Values[i + 1, 1]) then begin temp_date_beg := cxGridTableView2.DataController.Values[i, 0]; temp_date_end := cxGridTableView2.DataController.Values[i, 1]; temp_summa := cxGridTableView2.DataController.Values[i, 2]; temp_kol_month := cxGridTableView2.DataController.Values[i, 3]; temp_sostoyanie := cxGridTableView2.DataController.Values[i, 4]; temp_id_subsidy := cxGridTableView2.DataController.Values[i, 5]; temp_id_state := cxGridTableView2.DataController.Values[i, 6]; if cxGridTableView2.DataController.Values[i, 7] <> null then temp_Comment := cxGridTableView2.DataController.Values[i, 7] else temp_Comment :=''; temp_fullname := cxGridTableView2.DataController.Values[i, 8]; temp_short_name := cxGridTableView2.DataController.Values[i, 9]; if cxGridTableView2.DataController.Values[i, 10]<> null then begin temp_flag := cxGridTableView2.DataController.Values[i, 10]; cxGridTableView2.DataController.Values[i, 10]:= ''; end; cxGridTableView2.DataController.Values[i, 0] := cxGridTableView2.DataController.Values[i + 1, 0]; cxGridTableView2.DataController.Values[i, 1] := cxGridTableView2.DataController.Values[i + 1, 1]; cxGridTableView2.DataController.Values[i, 2] := cxGridTableView2.DataController.Values[i + 1, 2]; cxGridTableView2.DataController.Values[i, 3] := cxGridTableView2.DataController.Values[i + 1, 3]; cxGridTableView2.DataController.Values[i, 4] := cxGridTableView2.DataController.Values[i + 1, 4]; cxGridTableView2.DataController.Values[i, 5] := cxGridTableView2.DataController.Values[i + 1, 5]; cxGridTableView2.DataController.Values[i, 6] := cxGridTableView2.DataController.Values[i + 1, 6]; cxGridTableView2.DataController.Values[i, 7] := cxGridTableView2.DataController.Values[i + 1, 7]; cxGridTableView2.DataController.Values[i, 8] := cxGridTableView2.DataController.Values[i + 1, 8]; cxGridTableView2.DataController.Values[i, 9] := cxGridTableView2.DataController.Values[i + 1, 9]; if cxGridTableView2.DataController.Values[i + 1, 10]<> null then begin cxGridTableView2.DataController.Values[i, 10] := cxGridTableView2.DataController.Values[i + 1, 10]; cxGridTableView2.DataController.Values[i + 1, 10]:=''; end; cxGridTableView2.DataController.Values[i + 1, 0] := temp_date_beg; cxGridTableView2.DataController.Values[i + 1, 1] := temp_date_end; cxGridTableView2.DataController.Values[i + 1, 2] := temp_summa; cxGridTableView2.DataController.Values[i + 1, 3] := temp_kol_month; cxGridTableView2.DataController.Values[i + 1, 4] := temp_sostoyanie; cxGridTableView2.DataController.Values[i + 1, 5] := temp_id_subsidy; cxGridTableView2.DataController.Values[i + 1, 6] := temp_id_state; cxGridTableView2.DataController.Values[i + 1, 7] := temp_Comment; cxGridTableView2.DataController.Values[i + 1, 8] := temp_fullname; cxGridTableView2.DataController.Values[i + 1, 9] := temp_short_name; if temp_flag<>'' then cxGridTableView2.DataController.Values[i + 1, 10] := temp_flag; doNew := true; end; end; end; end; procedure TRegistration_Form.SortGridData_Lg; var i ,temp_id_lg , temp_kod_lg : integer; doNew : boolean; temp_date_beg, temp_date_end : TDate; temp_flag, temp_fullname : string ; begin if cxGridTableView3.DataController.RecordCount < 2 then exit; doNew := true; while doNew do begin doNew := false; for i := 0 to cxGridTableView3.DataController.RecordCount - 2 do begin temp_flag :=''; if cxGridTableView3.DataController.Values[i, 1] <= cxGridTableView3.DataController.Values[i + 1, 2] and (cxGridTableView3.DataController.Values[i, 2] < cxGridTableView3.DataController.Values[i + 1, 2]) then begin temp_kod_lg := cxGridTableView3.DataController.Values[i, 0]; temp_date_beg := cxGridTableView3.DataController.Values[i, 1]; temp_date_end := cxGridTableView3.DataController.Values[i, 2]; temp_id_lg := cxGridTableView3.DataController.Values[i, 3]; temp_fullname := cxGridTableView3.DataController.Values[i, 4]; if cxGridTableView3.DataController.Values[i, 5]<> null then begin temp_flag := cxGridTableView3.DataController.Values[i, 5]; cxGridTableView3.DataController.Values[i, 5]:= ''; end; cxGridTableView3.DataController.Values[i, 0] := cxGridTableView3.DataController.Values[i + 1, 0]; cxGridTableView3.DataController.Values[i, 1] := cxGridTableView3.DataController.Values[i + 1, 1]; cxGridTableView3.DataController.Values[i, 2] := cxGridTableView3.DataController.Values[i + 1, 2]; cxGridTableView3.DataController.Values[i, 3] := cxGridTableView3.DataController.Values[i + 1, 3]; cxGridTableView3.DataController.Values[i, 4] := cxGridTableView3.DataController.Values[i + 1, 4]; if cxGridTableView3.DataController.Values[i + 1, 5]<> null then begin cxGridTableView3.DataController.Values[i, 5] := cxGridTableView3.DataController.Values[i + 1, 5]; cxGridTableView3.DataController.Values[i + 1, 5]:=''; end; cxGridTableView3.DataController.Values[i + 1, 0] := temp_kod_lg; cxGridTableView3.DataController.Values[i + 1, 1] := temp_date_beg; cxGridTableView3.DataController.Values[i + 1, 2] := temp_date_end; cxGridTableView3.DataController.Values[i + 1, 3] := temp_id_lg; cxGridTableView3.DataController.Values[i + 1, 4] := temp_fullname; if temp_flag<>'' then cxGridTableView3.DataController.Values[i + 1, 5] := temp_flag; doNew := true; end; end; end; end; procedure TRegistration_Form.CancelButtonClick(Sender: TObject); begin close; end; procedure TRegistration_Form.FormCreate(Sender: TObject); begin with cxGridTableView_of_Live do begin Items[0].DataBinding.ValueTypeClass := TcxStringValueType; Items[1].DataBinding.ValueTypeClass := TcxStringValueType; Items[2].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[3].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[4].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[5].DataBinding.ValueTypeClass := TcxStringValueType; Items[6].DataBinding.ValueTypeClass := TcxIntegerValueType;; Items[7].DataBinding.ValueTypeClass := TcxStringValueType; Items[8].DataBinding.ValueTypeClass := TcxStringValueType; end; with cxGridTableView1 do begin Items[0].DataBinding.ValueTypeClass := TcxSmallintValueType; Items[1].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[2].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[3].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[4].DataBinding.ValueTypeClass := TcxStringValueType; Items[5].DataBinding.ValueTypeClass := TcxStringValueType; Items[6].DataBinding.ValueTypeClass := TcxFloatValueType; end; with cxGridTableView2 do begin Items[0].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[1].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[2].DataBinding.ValueTypeClass := TcxStringValueType; Items[3].DataBinding.ValueTypeClass := TcxStringValueType; Items[4].DataBinding.ValueTypeClass := TcxStringValueType; Items[5].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[6].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[7].DataBinding.ValueTypeClass := TcxStringValueType; Items[8].DataBinding.ValueTypeClass := TcxStringValueType; Items[9].DataBinding.ValueTypeClass := TcxStringValueType; Items[10].DataBinding.ValueTypeClass := TcxStringValueType; Items[11].DataBinding.ValueTypeClass := TcxIntegerValueType; end; with cxGridTableView3 do begin Items[0].DataBinding.ValueTypeClass := TcxSmallintValueType; Items[1].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[2].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[3].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[4].DataBinding.ValueTypeClass := TcxStringValueType; Items[5].DataBinding.ValueTypeClass := TcxStringValueType; Items[6].DataBinding.ValueTypeClass := TcxDateTimeValueType; Items[7].DataBinding.ValueTypeClass := TcxStringValueType; end; with cxGrid1TableView1 do begin Items[0].DataBinding.ValueTypeClass := TcxStringValueType; Items[1].DataBinding.ValueTypeClass := TcxFloatValueType; Items[2].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[3].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[4].DataBinding.ValueTypeClass := TcxIntegerValueType; Items[5].DataBinding.ValueTypeClass := TcxIntegerValueType; end; end; procedure TRegistration_Form.cxGridTableView_of_LiveFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if cxGridTableView_of_Live.DataController.Values[cxGridTableView_of_Live.DataController.FocusedRecordIndex, 7] <> null then Full_Build_Label.Caption:=cxGridTableView_of_Live.DataController.Values[cxGridTableView_of_Live.DataController.FocusedRecordIndex, 7]; end; procedure TRegistration_Form.cxGridTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if cxGridTableView1.DataController.Values[cxGridTableView1.DataController.FocusedRecordIndex, 4] <> null then Full_Cat_Label.Caption:=cxGridTableView1.DataController.Values[cxGridTableView1.DataController.FocusedRecordIndex, 4]; end; procedure TRegistration_Form.cxGridTableView2FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if cxGridTableView2.DataController.Values[cxGridTableView2.DataController.FocusedRecordIndex, 8] <> null then Sub_Type_Label.Caption:=cxGridTableView2.DataController.Values[cxGridTableView2.DataController.FocusedRecordIndex, 8]; end; procedure TRegistration_Form.cxGridTableView3FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if cxGridTableView3.DataController.Values[cxGridTableView3.DataController.FocusedRecordIndex, 4] <> null then Lgot_Full_Label.Caption:=cxGridTableView3.DataController.Values[cxGridTableView3.DataController.FocusedRecordIndex, 4]; end; end.
unit gif; {Header zu gif.asm} Interface uses modexlib; {wg. SetPal} var vram_pos, {aktuelle Position im VGA-Ram} rest, errornr:word; {restliche Bytes im Hauptspeicher und Fehler} gifname:String; {Name, erweitert um #0} Procedure LoadGif(GName:String); {LĄdt Gif-Datei "GName.gif" in vscreen} Procedure LoadGif_Pos(GName:String;Posit:Word); {LĄdt Gif-Datei an Bildschirmoffset Posit} Implementation Procedure ReadGif;external; {eigentlicher Gif-Loader, kompl. in Asm} {$l gif} Procedure LoadGif; {LĄdt Gif-Datei "GName.gif" in vscreen} Begin If pos('.',gname) = 0 then {evtl. Endung ".gif" anhĄngen} gname:=gname+'.gif'; Gifname:=GName+#0;; {ASCIIZ - String erzeugen} vram_pos:=0; {im VGA-Ram an Offset 0 beginnen} ReadGif; {und Bild laden} If Errornr <> 0 Then {bei Fehler abbrechen} Halt(Errornr); SetPal; {geladene Palette setzen} End; Procedure LoadGif_pos; {LĄdt Gif-Datei an Bildschirmoffset Posit} Begin If pos('.',gname) = 0 then {evtl. Endung ".gif" anhĄngen} gname:=gname+'.gif'; Gifname:=GName+#0; {ASCIIZ - String erzeugen} vram_pos:=posit; {im VGA-Ram an Ābergebenen Offset beginnen} ReadGif; {und Bild laden} If Errornr <> 0 Then {bei Fehler abbrechen} Halt(Errornr); SetPal; {geladene Palette setzen} End; Begin errornr:=0; {normalerweise kein Fehler} GetMem(VScreen,64000); {virtuellen Bildschirm allokieren} End.
unit Nathan.ObjectMapping.Core; interface uses System.IOUtils, System.SysUtils, System.Rtti, System.Generics.Collections, Nathan.ObjectMapping.Config, Nathan.ObjectMapping.Types; {$REGION 'Info'}{ ** Work in progres ** This project is a work in progress, check back soon for updates here. }{$ENDREGION} {$M+} type ENoMappingsFoundException = class(Exception); // INathanObjectMappingCore<S, D: IInterface> = interface // INathanObjectMappingCore<S, D: constructor, class> = interface // INathanObjectMappingCore<S, D: class> = interface INathanObjectMappingCore<S, D> = interface ['{40203DC3-18C7-487D-B356-0E50784609A7}'] function Config(): INathanObjectMappingConfig<S, D>; overload; function Config(AValue: INathanObjectMappingConfig<S, D>): INathanObjectMappingCore<S, D>; overload; function Map(ASource: S): D; overload; function MapReverse(ADestination: D): S; overload; end; TNathanObjectMappingCore<S, D> = class(TInterfacedObject, INathanObjectMappingCore<S, D>) strict private FConfig: INathanObjectMappingConfig<S, D>; function Creator(AType: TRttiType): TValue; function CreateDestination(): D; function CreateSource(): S; function GetInnerValue(AMappingType: TMappingType; AMember: TRttiMember; AValueFromObject: TValue): TValue; procedure SetInnerValue(AMappingType: TMappingType; AMember: TRttiMember; AValueFromObject, AValueToSet: TValue); procedure UpdateCreation(ASrc: S; ADest: D); overload; procedure UpdateCreation(ADest: D; ASrc: S); overload; procedure ValidateStarting; public constructor Create(); overload; destructor Destroy; override; function Config(): INathanObjectMappingConfig<S, D>; overload; function Config(AValue: INathanObjectMappingConfig<S, D>): INathanObjectMappingCore<S, D>; overload; function Map(ASource: S): D; overload; function MapReverse(ADestination: D): S; overload; end; {$M-} implementation constructor TNathanObjectMappingCore<S, D>.Create(); begin inherited Create; FConfig := nil; end; destructor TNathanObjectMappingCore<S, D>.Destroy; begin //... inherited; end; function TNathanObjectMappingCore<S, D>.Config: INathanObjectMappingConfig<S, D>; begin Result := FConfig; end; function TNathanObjectMappingCore<S, D>.Config(AValue: INathanObjectMappingConfig<S, D>): INathanObjectMappingCore<S, D>; begin FConfig := AValue; Result := Self; end; function TNathanObjectMappingCore<S, D>.Creator(AType: TRttiType): TValue; var LObjImplement: TObject; LMethCreate: TRttiMethod; LInstanceType: TRttiInstanceType; LValue: TValue; Args: array of TValue; LObjType: TRttiType; begin // Example how to create the destination object... Args := ['Internal value for properties']; if (AType.TypeKind = tkClass) then begin LInstanceType := AType.AsInstance; for LMethCreate in AType.GetMethods do begin if (LMethCreate.IsConstructor) then begin if (Length(LMethCreate.GetParameters) = 0) then begin // Constructor parameters, here are emtpy []... LValue := LMethCreate.Invoke(LInstanceType.MetaclassType, []); // v := t.GetMethod('Create').Invoke(t.AsInstance.MetaclassType,[]); Exit(LValue); end else if (Length(LMethCreate.GetParameters) = Length(Args)) then begin // With constructor parameters, here are a dummy... LValue := LMethCreate.Invoke(LInstanceType.MetaclassType, Args); Exit(LValue); end; end; end; end else if (AType.TypeKind = tkInterface) then begin // https://stackoverflow.com/questions/39584234/how-to-obtain-rtti-from-an-interface-reference-in-delphi?rq=1 // https://www.thedelphigeek.com/2012/10/automagically-creating-object-fields.html // https://www.delphipraxis.net/195026-custom-constructor-di-bei-factory-basierter-objekterstellung-2.html // http://qaru.site/questions/2180093/unable-to-invoke-method-declare-in-class-implement-generic-interface-method // https://stackoverflow.com/questions/6278381/delphi-rtti-for-interfaces-in-a-generic-context // https://stackoverflow.com/questions/10600186/why-does-findtype-fail-to-get-rtti-when-gettype-succeeds // https://stackanswers.net/questions/how-to-obtain-rtti-from-an-interface-reference-in-delphi // https://stackoverflow.com/questions/8158035/creating-an-interface-implementer-instance-at-runtime // https://github.com/VSoftTechnologies/Delphi-Mocks/blob/master/Delphi.Mocks.Proxy.pas search to FVirtualInterface for LObjType in TRTTIContext.Create.GetTypes do begin if (LObjType.Name = 'T' + AType.name.Substring(1)) then begin LInstanceType := LObjType.AsInstance; //LInstanceType := AType.AsInstance; LObjImplement := LInstanceType.GetMethod('Create').Invoke(LInstanceType.MetaclassType, []).AsObject; if (not LObjImplement.GetInterface(LInstanceType.GetImplementedInterfaces[0].GUID, Result)) then LObjImplement.Free(); Exit(Result); end; end; // Otherwise Address.QueryInterface() end; end; function TNathanObjectMappingCore<S, D>.CreateDestination: D; var RTypeD: TRttiType; ValueD: TValue; begin RTypeD := TRTTIContext.Create.GetType(TypeInfo(D)); ValueD := Creator(RTypeD); Exit(ValueD.AsType<D>); end; function TNathanObjectMappingCore<S, D>.CreateSource: S; var RTypeS: TRttiType; ValueS: TValue; begin RTypeS := TRTTIContext.Create.GetType(TypeInfo(S)); ValueS := Creator(RTypeS); Exit(ValueS.AsType<S>); end; function TNathanObjectMappingCore<S, D>.GetInnerValue( AMappingType: TMappingType; AMember: TRttiMember; AValueFromObject: TValue): TValue; begin case AMappingType of mtUnknown: Result := nil; mtField: Result := TRttiField(AMember).GetValue(AValueFromObject.AsObject); mtProperty: Result := TRttiProperty(AMember).GetValue(AValueFromObject.AsObject); mtMethod: Result := TRttiMethod(AMember).Invoke(AValueFromObject.AsObject, []) else Result := nil; end; end; procedure TNathanObjectMappingCore<S, D>.SetInnerValue( AMappingType: TMappingType; AMember: TRttiMember; AValueFromObject, AValueToSet: TValue); begin case AMappingType of mtField: TRttiField(AMember).SetValue(AValueFromObject.AsObject, AValueToSet); mtProperty: TRttiProperty(AMember).SetValue(AValueFromObject.AsObject, AValueToSet); mtMethod: begin // Will come in the future... end; end; end; procedure TNathanObjectMappingCore<S, D>.UpdateCreation(ASrc: S; ADest: D); var Idx: Integer; LValue: TValue; ValueFromS: TValue; ValueFromD: TValue; MemberS: TRttiMember; MemberD: TRttiMember; Item: TPair<string, TMappedSrcDest>; begin ValueFromS := TValue.From<S>(ASrc); ValueFromD := TValue.From<D>(ADest); for Item in FConfig.GetMemberMap do begin MemberS := Item.Value[msdSource].MemberClass; MemberD := Item.Value[msdDestination].MemberClass; LValue := GetInnerValue(Item.Value[msdSource].MappingType, MemberS, ValueFromS); SetInnerValue(Item.Value[msdDestination].MappingType, MemberD, ValueFromD, LValue); end; for Idx := 0 to FConfig.GetUserMap.Count - 1 do FConfig.GetUserMap.Items[Idx](ASrc, ADest); end; procedure TNathanObjectMappingCore<S, D>.UpdateCreation(ADest: D; ASrc: S); var Idx: Integer; LValue: TValue; ValueFromS: TValue; ValueFromD: TValue; MemberS: TRttiMember; MemberD: TRttiMember; Item: TPair<string, TMappedSrcDest>; begin ValueFromD := TValue.From<D>(ADest); ValueFromS := TValue.From<S>(ASrc); for Item in FConfig.GetMemberMap do begin MemberD := Item.Value[msdDestination].MemberClass; MemberS := Item.Value[msdSource].MemberClass; LValue := GetInnerValue(Item.Value[msdDestination].MappingType, MemberD, ValueFromD); SetInnerValue(Item.Value[msdSource].MappingType, MemberS, ValueFromS, LValue); end; for Idx := 0 to FConfig.GetUserMapReverse.Count - 1 do FConfig.GetUserMapReverse[Idx](ADest, ASrc); end; procedure TNathanObjectMappingCore<S, D>.ValidateStarting; begin if ((not Assigned(FConfig)) or ((FConfig.GetMemberMap.Count = 0) and (FConfig.GetUserMap.Count = 0))) then raise ENoMappingsFoundException.Create('No mapping information found.'); end; function TNathanObjectMappingCore<S, D>.Map(ASource: S): D; //var // LObjImplement: TObject; // LInstanceType: TRttiInstanceType; // LObjType: TRttiType; begin ValidateStarting; // Create an empty destination object... Result := CreateDestination; // for LObjType in TRTTIContext.Create.GetTypes do // begin // // if (LObjType.Name = 'IAddressDto') then // // if (LObjType.Name = 'TAddressDto') then // // if (LObjType.Name = 'T' + 'AddressDto') then // begin // LInstanceType := LObjType.AsInstance; // // //LInstanceType := AType.AsInstance; // LObjImplement := LInstanceType.GetMethod('Create').Invoke(LInstanceType.MetaclassType, []).AsObject; // if (not LObjImplement.GetInterface(LInstanceType.GetImplementedInterfaces[0].GUID, Result)) then // LObjImplement.Free(); // //// Exit(Result); // end; // end; // Update our destination class... UpdateCreation(ASource, Result); end; function TNathanObjectMappingCore<S, D>.MapReverse(ADestination: D): S; begin ValidateStarting; // Create an empty source object... Result := CreateSource; // Update our source class... UpdateCreation(ADestination, Result); end; end.
unit BDEToFIBSP; interface uses SysUtils, Classes; type TBDEToFIBSP = class(TComponent) private FMappings: TStrings; procedure SetMappings(Value: TStrings); protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Public declarations } published property Mappings: TStrings read FMappings write SetMappings; end; procedure Register; implementation constructor TBDEToFIBSP.Create(AOwner: TComponent); begin inherited Create(AOwner); FMappings := TStringList.Create; end; destructor TBDEToFIBSP.Destroy; begin FMappings.Free; inherited Destroy; end; procedure TBDEToFIBSP.SetMappings(Value: TStrings); begin FMappings.Assign(Value); end; procedure Register; begin RegisterComponents('Samples', [TBDEToFIBSP]); end; end.
unit Address_EditForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uAddModifForm, uInvisControl, uSpravControl, uFormControl, StdCtrls, Buttons, uFControl, uLabeledFControl, uCharControl, DB, FIBDataSet, pFIBDataSet, uAdr_DataModule, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, IBase, cxLookAndFeelPainters, cxButtons, ActnList; type TfAdrEditForm = class(TAddModifForm) CBCountry: TcxLookupComboBox; CountryBtn: TcxButton; CountryLbl: TLabel; CBRegion: TcxLookupComboBox; RegionBtn: TcxButton; RegionLbl: TLabel; CBDistrict: TcxLookupComboBox; DistrictBtn: TcxButton; DistrictLbl: TLabel; CBTown: TcxLookupComboBox; TownBtn: TcxButton; TownLbl: TLabel; CBStreet: TcxLookupComboBox; StreetBtn: TcxButton; StreetLbl: TLabel; CBArea: TcxLookupComboBox; AreaBtn: TcxButton; AreaLbl: TLabel; TEZip: TcxTextEdit; TEFlat: TcxTextEdit; TEHouse: TcxTextEdit; TEKorpus: TcxTextEdit; KorpusLbl: TLabel; HouseLbl: TLabel; FlatLbl: TLabel; ZipLbl: TLabel; AcceptBtn: TcxButton; CancelBtn: TcxButton; ActionList1: TActionList; AcceptAction: TAction; CancelAction: TAction; procedure DistrictOpenSprav(Sender: TObject); procedure CountryOpenSprav(Sender: TObject); procedure RegionOpenSprav(Sender: TObject); procedure PlaceOpenSprav(Sender: TObject); procedure StreetOpenSprav(Sender: TObject); procedure AreaOpenSprav(Sender: TObject); procedure CBCountryPropertiesEditValueChanged(Sender: TObject); procedure CBRegionPropertiesEditValueChanged(Sender: TObject); procedure CBDistrictPropertiesEditValueChanged(Sender: TObject); procedure CBTownPropertiesEditValueChanged(Sender: TObject); procedure CancelActionExecute(Sender: TObject); private { Private declarations } FMode: TFormMode; DM: TAdrDM; procedure EnableRegion(AID_Country:Variant);// Если параметр NULL, то объект становится недотупным procedure EnableDistrict(AID_Region:Variant); procedure EnableTown(AID_Region, AID_District:Variant); procedure EnableStreet(AID_Town:Variant); procedure EnableArea(AID_Town:Variant); public constructor Create(AOwner:TComponent; ADB_Handle:TISC_DB_HANDLE; AIdAddress:Integer); reintroduce; //DMod: TAdrDM; Where: Variant; id_PK:Variant); reintroduce; Mode: TFormMode end; implementation {$R *.dfm} uses RxMemDS, uUnivSprav, StdConvs, FIBDatabase; procedure TfAdrEditForm.EnableRegion(AID_Country:Variant); var MakeEnabled:Boolean; begin Refresh; MakeEnabled:= not VarIsNull(AID_Country); if DM.pFIBDS_SelectRegion.Active then DM.pFIBDS_SelectRegion.Close; if MakeEnabled then begin DM.pFIBDS_SelectRegion.ParamByName('ID_COUNTRY').AsVariant:=AID_COUNTRY; DM.pFIBDS_SelectRegion.Open; end; CBRegion.Enabled:=MakeEnabled; RegionBtn.Enabled:=MakeEnabled; // В случае изм. значения обнуляется значение поля ОБЛАСТЬ и закрываются дочерние поля CBRegion.EditValue:=Null; EnableDistrict(Null); end; procedure TfAdrEditForm.EnableDistrict(AID_Region:Variant); var MakeEnabled:Boolean; begin Refresh; MakeEnabled:= not VarIsNull(AID_Region); if DM.pFIBDS_SelectDistrict.Active then DM.pFIBDS_SelectDistrict.Close; if MakeEnabled then begin DM.pFIBDS_SelectDistrict.ParamByName('ID_REGION').AsVariant:=AID_REGION; DM.pFIBDS_SelectDistrict.Open; end; CBDistrict.Enabled:=MakeEnabled; DistrictBtn.Enabled:=MakeEnabled; CBDistrict.EditValue:=Null; EnableTown(AID_Region,Null); end; procedure TfAdrEditForm.EnableTown(AID_Region, AID_District:Variant); var MakeEnabled:Boolean; begin Refresh; MakeEnabled:= not VarIsNull(AID_Region); if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; if MakeEnabled then begin DM.pFIBDS_SelectPlace.ParamByName('ID_REGION').AsVariant :=AID_Region; DM.pFIBDS_SelectPlace.ParamByName('ID_DISTRICT').AsVariant:=AID_District; DM.pFIBDS_SelectPlace.Open; end; CBTown.Enabled:=MakeEnabled; TownBtn.Enabled:=MakeEnabled; CBTown.EditValue:=Null; EnableStreet(Null); EnableArea(Null); end; procedure TfAdrEditForm.EnableStreet(AID_Town:Variant); var MakeEnabled:Boolean; begin Refresh; MakeEnabled:= not VarIsNull(AID_Town); if DM.pFIBDS_SelectStreet.Active then DM.pFIBDS_SelectStreet.Close; if MakeEnabled then begin DM.pFIBDS_SelectStreet.ParamByName('ID_PLACE').AsVariant:=AID_Town; DM.pFIBDS_SelectStreet.Open; end; CBStreet.Enabled:=MakeEnabled; StreetBtn.Enabled:=MakeEnabled; CBStreet.EditValue:=Null; end; procedure TfAdrEditForm.EnableArea(AID_Town:Variant); var MakeEnabled:Boolean; begin Refresh; MakeEnabled:= not VarIsNull(AID_Town); if DM.pFIBDS_SelectArea.Active then DM.pFIBDS_SelectArea.Close; if MakeEnabled then begin DM.pFIBDS_SelectArea.ParamByName('ID_PLACE').AsVariant:=AID_Town; DM.pFIBDS_SelectArea.Open; end; CBArea.Enabled:=MakeEnabled; AreaBtn.Enabled:=MakeEnabled; CBArea.EditValue:=Null; END; constructor TfAdrEditForm.Create(AOwner:TComponent; ADB_Handle:TISC_DB_HANDLE;AIdAddress:Integer); {Mode: TFormMode);} //DMod: TAdrDM; Where: Variant; id_PK:Variant); begin inherited Create(AOwner); // FMode := Mode; DM := TAdrDM.Create(Self); DM.pFIBDB_Adr.Handle := ADB_Handle; DM.pFIBDB_Adr.DefaultTransaction.Active:=True; DBHandle:=Integer(DM.pFIBDB_Adr.Handle); //****************************************************************************** // Настраиваем поля ввода // Страна DM.pFIBDS_SelectCountry.Open; CBCountry.Properties.ListSource:=DM.DSourceCountry; CBCountry.EditValue:=DM.DSourceCountry.DataSet['ID_COUNTRY']; CBCountry.Clear; // Область CBRegion.Properties.ListSource:=DM.DSourceRegion; CBRegion.EditValue:=DM.DSourceRegion.DataSet['ID_REGION']; CBRegion.Enabled:=False; RegionBtn.Enabled:=False; // Район области CBDistrict.Properties.ListSource:=DM.DSourceDistrict; CBDistrict.EditValue:=DM.DSourceDistrict.DataSet['ID_DISTRICT']; DM.pFIBDS_SelectDistrict.Active; CBDistrict.Enabled:=False; DistrictBtn.Enabled:=False; // Город CBTown.Properties.ListSource:=DM.DSourcePlace; CBTown.EditValue:=DM.DSourcePlace.DataSet['ID_PLACE']; CBTown.Enabled:=False; TownBtn.Enabled:=False; // Улица CBStreet.Properties.ListSource:=DM.DSourceStreet; CBStreet.EditValue:=DM.DSourceStreet.DataSet['ID_STREET']; CBStreet.Enabled:=False; StreetBtn.Enabled:=False; // Район городской CBArea.Properties.ListSource:=DM.DSourceArea; CBArea.EditValue:=DM.DSourceArea.DataSet['ID_CITY_AREA']; CBArea.Enabled:=False; StreetBtn.Enabled:=False; end; procedure TfAdrEditForm.CountryOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник країн'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Country_Form'; Params.ModifFormClass:='TAdd_Country_Form'; Params.TableName:='adr_country'; Params.Fields:='Name_country,id_country'; Params.FieldsName:='Назва'; Params.KeyField:='id_country'; Params.ReturnFields:='Name_country,id_country'; Params.DeleteSQL:='execute procedure adr_country_d(:id_country);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin if DM.pFIBDS_SelectCountry.Active then DM.pFIBDS_SelectCountry.Close; DM.pFIBDS_SelectCountry.Open; CBCountry.EditValue:=output['id_country']; end; end; procedure TfAdrEditForm.RegionOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник регіонів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Region_Form'; Params.ModifFormClass:='TAdd_Region_Form'; Params.TableName:='ADR_REGION_SELECT('+IntToStr(CBCountry.EditValue)+');'; Params.Fields:='Name_region,id_region'; Params.FieldsName:='Назва'; Params.KeyField:='id_region'; Params.ReturnFields:='Name_region,id_region'; Params.DeleteSQL:='execute procedure adr_region_d(:id_region);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin EnableRegion(CBCountry.EditValue); CBRegion.EditValue:=output['id_region']; end; end; procedure TfAdrEditForm.DistrictOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник районів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_District_Form'; Params.ModifFormClass:='TAdd_District_Form'; Params.TableName:='adr_district_select('+IntToStr(CBRegion.EditValue)+');'; Params.Fields:='Name_district,id_district'; Params.FieldsName:='Район'; Params.KeyField:='id_district'; Params.ReturnFields:='Name_district,id_district'; Params.DeleteSQL:='execute procedure adr_district_d(:id_district);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin EnableDistrict(CBRegion.EditValue); CBDistrict.EditValue:=output['id_district']; end; end; procedure TfAdrEditForm.PlaceOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; id_distr: string; begin if not VarIsNull(CBDistrict.EditValue) then id_distr:=IntToStr(CBDistrict.EditValue) else id_distr:='null'; Params.FormCaption:='Довідник міст'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Place_Form'; Params.ModifFormClass:='TAdd_Place_Form'; Params.TableName:='ADR_PLACE_SELECT('+IntToStr(CBRegion.EditValue)+','+id_distr+')'; Params.Fields:='Name_place,id_place'; Params.FieldsName:='Назва'; Params.KeyField:='id_place'; Params.ReturnFields:='Name_place,id_place'; Params.DeleteSQL:='execute procedure adr_place_d(:id_place);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin EnableTown(CBRegion.EditValue,CBDistrict.EditValue); CBTown.EditValue:=output['id_place']; end; end; procedure TfAdrEditForm.StreetOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник вулиць'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Street_Form'; Params.ModifFormClass:='TAdd_Street_Form'; Params.TableName:='ADR_STREET_SELECT('+IntToStr(CBTown.EditValue)+');'; Params.Fields:='Name_street,id_street'; Params.FieldsName:='Вулиця'; Params.KeyField:='id_street'; Params.ReturnFields:='Name_street,id_street'; Params.DeleteSQL:='execute procedure adr_street_d(:id_street);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin EnableStreet(CBTown.EditValue); CBStreet.EditValue:=output['id_street']; end; end; procedure TfAdrEditForm.AreaOpenSprav(Sender: TObject); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник міських районів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbModif,fbDelete,fbExit]; Params.AddFormClass:='TAddCityArea'; Params.ModifFormClass:='TAddCityArea'; Params.TableName:='adr_city_area_select('+IntToStr(CBTown.EditValue)+')'; Params.Fields:='Name_CITY_AREA,id_CITY_AREA'; Params.FieldsName:='Назва'; Params.KeyField:='id_CITY_AREA'; Params.ReturnFields:='Name_CITY_AREA,id_CITY_AREA'; Params.DeleteSQL:='execute procedure adr_CITY_AREA_d(:id_CITY_AREA);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin EnableArea(CBTown.EditValue); CBArea.EditValue:=output['id_CITY_AREA']; end; end; procedure TfAdrEditForm.CBCountryPropertiesEditValueChanged( Sender: TObject); begin EnableRegion(CBCountry.EditValue); end; procedure TfAdrEditForm.CBRegionPropertiesEditValueChanged( Sender: TObject); begin EnableDistrict(CBRegion.EditValue); end; procedure TfAdrEditForm.CBDistrictPropertiesEditValueChanged( Sender: TObject); begin EnableTown(CBRegion.EditValue,CBDistrict.EditValue); end; procedure TfAdrEditForm.CBTownPropertiesEditValueChanged( Sender: TObject); begin EnableStreet(CBTown.EditValue); EnableArea(CBTown.EditValue); end; procedure TfAdrEditForm.CancelActionExecute(Sender: TObject); begin ModalResult:=mrCancel; end; initialization RegisterClass(TfAdrEditForm); end.
namespace RemObjects.Elements.EUnit; interface uses Sugar; type Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF} public method AreEqual(Actual, Expected : Object; Message: String := nil); method AreNotEqual(Actual, Expected: Object; Message: String := nil); method IsNil(Actual: Object; Message: String := nil); method IsNotNil(Actual: Object; Message: String := nil); end; implementation class method Assert.AreEqual(Actual: Object; Expected: Object; Message: String := nil); begin if Expected = nil then begin IsNil(Actual); exit; end; FailIfNot(Expected.{$IF NOUGAT}isEqual{$ELSE}Equals{$ENDIF}(Actual), Actual, Expected, coalesce(Message, AssertMessages.NotEqual)); end; class method Assert.AreNotEqual(Actual: Object; Expected: Object; Message: String := nil); begin if Expected = nil then begin IsNotNil(Actual); exit; end; FailIf(Expected.{$IF NOUGAT}isEqual{$ELSE}Equals{$ENDIF}(Actual), Actual, Expected, coalesce(Message, AssertMessages.Equal)); end; class method Assert.IsNil(Actual: Object; Message: String := nil); begin FailIfNot(Actual = nil, Actual, nil, coalesce(Message, AssertMessages.NotEqual)); end; class method Assert.IsNotNil(Actual: Object; Message: String := nil); begin FailIfNot(Actual <> nil, coalesce(Message, AssertMessages.ObjectIsNil)); end; end.
unit uParentButtonSubList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentCustomSubList, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns, dxPSCore, dxPScxGridLnk, ImgList, mrConfigList, ExtCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, XiButton, uParentCustomList; type TParentButtonSubList = class(TParentCustomSubList) btnNew: TXiButton; btnOpen: TXiButton; btnDelete: TXiButton; private { Private declarations } protected procedure SetCommandOptionsVisibility; override; procedure LoadImages; override; procedure RestrictForm; override; public { Public declarations } end; implementation {$R *.dfm} { TParentButtonSubList } procedure TParentButtonSubList.LoadImages; begin inherited; imgBrowser.GetBitmap(BTN_LIST_DELETE, btnDelete.Glyph); imgBrowser.GetBitmap(BTN_LIST_OPEN, btnOpen.Glyph); imgBrowser.GetBitmap(BTN_LIST_NEW, btnNew.Glyph); end; procedure TParentButtonSubList.RestrictForm; begin inherited; btnNew.Enabled := False; btnDelete.Enabled := False; end; procedure TParentButtonSubList.SetCommandOptionsVisibility; var mrCommandOption : TmrCommandOption; begin inherited; mrCommandOption := TmrCommandOption(btnNew.Tag); btnNew.Enabled := (mrCommandOption in ConfigList.CommandOptions); mrCommandOption := TmrCommandOption(btnOpen.Tag); btnOpen.Enabled := (mrCommandOption in ConfigList.CommandOptions); mrCommandOption := TmrCommandOption(btnDelete.Tag); btnDelete.Enabled := (mrCommandOption in ConfigList.CommandOptions); end; end.
unit uDM_RepositoryPostgreSQL; interface uses Forms, Dialogs, uiRepositories, uiRepoSystem, System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client; type TDM_RepositoryPostgreSQL = class(TDataModule, IRepositories) FDConnPostgreSQL: TFDConnection; FDPhysPgDriverLink1: TFDPhysPgDriverLink; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } function Repository: IRepoSystem; end; var DM_RepositoryPostgreSQL: TDM_RepositoryPostgreSQL; procedure initialize; //declaration implementation uses uRepositorySystemPostgreSQL; {%CLASSGROUP 'Vcl.Controls.TControl'} var mRepository : IRepoSystem; procedure initialize; begin If Assigned( DM_RepositoryPostgreSQL ) then exit; Application.CreateForm(TDM_RepositoryPostgreSQL, DM_RepositoryPostgreSQL); end; {$R *.dfm} procedure TDM_RepositoryPostgreSQL.DataModuleCreate(Sender: TObject); begin Try FDConnPostgreSQL.Connected := False; FDConnPostgreSQL.Connected := True; Except On E : Exception do ShowMessage('Error Connect PostgreSQL : ' + E.Message) End; end; function TDM_RepositoryPostgreSQL.Repository: IRepoSystem; begin if not assigned(mRepository) then mRepository := TDM_RepositorySystemPostgreSQL.Create(Self); Result := mRepository; end; end.
unit sys_Connect_Log; interface uses pFIBDatabase, pFIBQuery, pFIBStoredProc, pFIBDataSet, Dialogs, FIBDataBase, Controls, Forms, IB_Externals, Classes, Registry, Windows, ExtCtrls, IBase, SysUtils; type TConnectLog = class private S_id_User : integer; Connect_PK_ID : int64; STransaction : TpFIBTransaction; StoredProc : TpFIBStoredProc; function GetLocalComputerName: String; function GetUserName:string; procedure DatabaseBeforeDisconnect(Sender: TObject); public { Public declarations } end; function InitializeConnectLog(DB : TpFIBDatabase; id_User : integer) : boolean; procedure DatabaseAfterConnect(Sender: TObject); implementation uses FIBQuery; var ConnectLog : TConnectLog; function InitializeConnectLog(DB : TpFIBDatabase; id_User : integer) : boolean; begin Result := False; try ConnectLog := TConnectLog.Create; ConnectLog.S_id_User := id_User; ConnectLog.STransaction := TpFIBTransaction.Create(nil); ConnectLog.STransaction.DefaultDatabase := DB; DB.BeforeDisconnect := ConnectLog.DatabaseBeforeDisconnect; ConnectLog.StoredProc := TpFIBStoredProc.Create(nil); ConnectLog.StoredProc.Transaction := ConnectLog.STransaction; except ShowMessage('Ініціалізація служби протоколювання транзакцій користувачів закінчено невдачою!' + #13 + #13 + 'Зв''яжіться із розробниками!'); Exit; end; Result := True; end; { TConnectLog } procedure DatabaseAfterConnect(Sender: TObject); begin try ConnectLog.StoredProc.Transaction.StartTransaction; ConnectLog.StoredProc.ExecProcedure('SYS_CONNECT_LOG_ADD', [ConnectLog.S_id_User, ConnectLog.GetLocalComputerName, ConnectLog.GetUserName]); ConnectLog.Connect_PK_ID := ConnectLog.StoredProc.Fields[0].AsInt64; ConnectLog.StoredProc.Transaction.Commit; except ConnectLog.StoredProc.Transaction.Rollback; ShowMessage('Помилка!' + #13 + #13 + 'Помилка протоколювання з''єднання користувача з БД!'); end; end; procedure TConnectLog.DatabaseBeforeDisconnect(Sender: TObject); begin try StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('SYS_CONNECT_LOG_UPD', [Connect_PK_ID]); StoredProc.Transaction.Commit; except StoredProc.Transaction.Rollback; ShowMessage('Помилка!' + #13 + #13 + 'Помилка протоколювання транзакції користувача!'); end; end; function TConnectLog.GetLocalComputerName: String; var L : LongWord; begin L := MAX_COMPUTERNAME_LENGTH + 2; SetLength(Result, L); if Windows.GetComputerName(PChar(Result), L) and (L > 0) then SetLength(Result, StrLen(PChar(Result))) else Result := ''; end; function TConnectLog.GetUserName: string; var Buffer: array[0..MAX_PATH] of Char; sz:DWord; begin sz:=MAX_PATH-1; if windows.GetUserName(Buffer,sz) then begin if sz>0 then dec(sz); SetString(Result,Buffer,sz); end else Result := ''; end; end.
{-$Id: AddMovingTypeUnit.pas,v 1.1.1.1 2005/07/07 10:35:05 oleg Exp $} {******************************************************************************} { Автоматизированная система управления персоналом } { (c) Донецкий национальный университет, 2002-2004 } {******************************************************************************} { Модуль "Добавление типа перемещения" } { Добавляет тип перемещения в справочник перемещений } { Ответственный: Кропов Валентин } unit AddMovingTypeUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TAddMovingTypeForm = class(TForm) MovingTypeEdit: TEdit; OkButton: TBitBtn; CancelButton: TBitBtn; Label1: TLabel; Is_First: TCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); private { Private declarations } public FormType : Integer; {0 - Add, 1 - Modify} ID_ACTION : Integer; { Public declarations } end; var AddMovingTypeForm: TAddMovingTypeForm; implementation {$R *.DFM} procedure TAddMovingTypeForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then Action := caFree;; end; procedure TAddMovingTypeForm.OkButtonClick(Sender: TObject); begin if (MovingTypeEdit.Text = '') then begin MessageDlg('Введіть назву нового типу переміщення!', mtError, [mbOk], 0); ModalResult := mrNone; end; end; procedure TAddMovingTypeForm.CancelButtonClick(Sender: TObject); begin Close; end; end.
Program pembuatanRekeningBank; //uses crt; const gold = 1000000; platinum = 2000000; nMax = 100; type idn = record id : integer; nama : string; jenisTabungan : string; jumlahSetoranAwal : longint; biayaAdminBulanan : integer; biayaPenarikanlain : integer; end; nasabah = array[1..nMax] of idn; var i,n, num: integer; bank: nasabah; procedure tampilan; begin writeln('Selamat datang di Menu utama Pembuatan Rekening'); writeln('1. Input data'); writeln('2. Cari data'); writeln('3. Sorting data'); writeln('4. Edit data'); writeln('5. Outputkan data'); writeln('6. Keluar'); end; procedure pilihan(var i : integer); begin write('Pilihan Anda : '); readln(i); end; function admin(jenis: string;uang: longint):integer; begin if (jenis = 'GOLD') then if(uang >= 3*gold) then admin := 0 else if(uang = 2*gold) then admin := 1000 else admin := 2500 else if(uang >= 3*platinum) then admin := 0 else if(uang = 2*platinum) then admin := 1000 else admin := 2500; end; procedure olahData(var x: nasabah; pos: integer); begin x[pos].biayaAdminBulanan := admin(x[pos].jenisTabungan,x[pos].jumlahSetoranAwal); x[pos].biayaPenarikanlain := x[pos].biayaAdminBulanan * 5 div 100; end; procedure inputNama(var x: string); var a : string; begin write('Masukan Nama : '); readln(a); while(a ='') do begin write('Masukan Nama : '); readln(a); end; x :=a; end; procedure inputJenisSetoran(var x: string;var setoran:longint); var b : boolean; uang:longint; jenis: string; begin write('Masukan Jenis Tabungan : '); readln(jenis); jenis:= upcase(jenis); while not((jenis <> 'GOLD') xor (jenis <> 'PLATINUM')) do begin writeln('Maaf Jenis Tabungan anda tak tersedia'); writeln('Maaf Jenis tabungan bukan gold atau platinum'); write('Masukan Jenis Tabungan : '); readln(jenis); jenis := upcase(jenis); end; x := jenis; b:= false; repeat write('Masukan Setoran awal : '); readln(uang); if(x = 'GOLD') then if (uang >= gold) then b:= True else writeln('Setoran awal anda kurang dari 1000000'); if(x = 'PLATINUM') then if (uang >= platinum) then b:= True else writeln('Setoran awal anda kurang dari 2000000'); until (b); setoran:= uang; end; procedure olahArray(x:nasabah;pos:integer); var silver,gold,i : integer; begin writeln; silver := 0; gold := 0; for i := 1 to pos do if(x[i].jenisTabungan = 'GOLD') then gold := gold +1 else silver := silver+1; writeln('Banyaknya Nasabah Gold : ',gold); writeln('Banyaknya Nasabah Silver : ',silver); writeln; end; procedure sortingDataNama(var x: nasabah;n:integer); var i,j:integer; tmp : idn; begin writeln; for i:= 2 to n do begin tmp:= x[i]; j:= i-1; while(j >= 1) and(x[j].nama > tmp.nama) do begin x[j+1]:=x[j]; j:=j-1; end; x[j+1]:=tmp; end; writeln; end; procedure delete(var x: nasabah; pos: integer); begin x[pos].nama := ''; x[pos].jenisTabungan:= ''; x[pos].jumlahSetoranAwal:=0; x[pos].biayaAdminBulanan := 0; x[pos].biayaPenarikanlain := 0; end; procedure sortingDataSetoran(var x: nasabah;n:integer); var i,j:integer; tmp : idn; begin writeln; for i:= 2 to n do begin tmp:= x[i]; j:= i-1; while(j >= 1) and(x[j].jumlahSetoranAwal < tmp.jumlahSetoranAwal) do begin x[j+1]:=x[j]; j:=j-1; end; x[j+1]:=tmp; end; writeln; end; procedure outputSemua(x: nasabah; awal,pos : integer); var i : integer; begin writeln; for i := awal to pos do if(x[i].nama <>'') then begin writeln('Id : ',x[i].id); writeln('Nama : ',x[i].nama); writeln('Jenis Tabungan : ',x[i].jenisTabungan); writeln('Setoran awal : ',x[i].jumlahSetoranAwal); writeln('Biaya admin bulanan : ',x[i].biayaAdminBulanan); writeln('Biaya penarikan di atm lain : ',x[i].biayaPenarikanlain); writeln; end; writeln; end; function cariNama(x: nasabah; pos : integer;y:string):integer; var i: integer; begin i:=1; while(i < pos) and (i <nMax) and (x[i].nama <> y) do i:= i+1; if (x[i].nama = y) then cariNama:= i else cariNama:=-1; end; procedure isiData(var x: nasabah;var pos,y: integer); var n,i: integer; begin writeln; write('Jumlah data : '); readln(n); i:=0; while(i< n) and (pos < nMax) do begin writeln; pos := pos+1; x[pos].id:= y; inputNama(x[pos].nama); inputJenisSetoran(x[pos].jenisTabungan,x[pos].jumlahSetoranAwal); olahData(x,pos); i := i+1; y := y+1; end; writeln; end; procedure sortingData(var x: nasabah; pos : integer); var i : integer; begin repeat writeln('Menu Sorting Data'); writeln('1. Sorting Nama'); writeln('2. Sorting setoran'); writeln('3. Menu utama'); pilihan(i); if(i = 1) then begin sortingDataNama(x,pos); writeln('Data telah Terurut dari A ke Z'); end; if(i = 2) then begin sortingDataSetoran(x,pos); writeln('Data telah Terurut dari terbesar'); end; writeln; until(i = 3); end; procedure cariData(x: nasabah; pos : integer); var y,z:string; i: integer; begin writeln; write('Nama yang ingin dicari : '); readln(y); i:= cariNama(x,pos,y); if(i <> -1) then begin writeln('Nama yang dicari ditemukan'); write('Tampilkan semua datanya ? (ya/tidak) '); readln(z); if(z ='ya') then outputSemua(x,i,i); end else writeln('Nama tak ditemukan '); writeln; end; procedure editData(var x: nasabah; var pos : integer); var a,y,cek:string; i,z:integer; begin repeat writeln; write('Nama yang ingin diedit / didelete : '); readln(y); i:= cariNama(x,pos,y); if(i <> -1) then begin outputSemua(x,i,i); write('delete / edit ? '); readln(a); if(a ='edit') then begin repeat writeln('1. Nama'); writeln('2. Jenis tabungan dan jumlah setoran awal '); writeln('3. Selesai'); write('Data yang diedit? '); readln(z); if(z = 1) then inputNama(x[i].nama); if(z = 2) then inputJenisSetoran(x[i].jenisTabungan,x[i].jumlahSetoranAwal); olahData(x,i); until (z = 3); end; if(a = 'delete') then begin delete(x,i); writeln('data teleh didelete'); sortingDataSetoran(x,pos); pos:=pos-1; end; end else writeln('Nama tak ditemukan'); repeat write('ingin mencari lagi? (ya/tidak) '); readln(cek); until((cek ='ya') or (cek ='tidak')); until(cek = 'tidak'); writeln; end; procedure outputData(x: nasabah; pos : integer); var i:integer; begin writeln; repeat writeln('1. Semua data'); writeln('2. Banyaknya nasabah perjenis tabungan'); writeln('3. Menu utama'); pilihan(i); if(i = 1) then outputSemua(x, 1,pos); if(i = 2) then olahArray(x,pos); until(i = 3); writeln; end; begin n:=0; num := 1234; repeat tampilan; pilihan(i); case i of 1 : isiData(bank,n,num); 2 : cariData(bank,n); 3 : sortingData(bank,n); 4 : editData(bank,n); 5 : outputData(bank,n); end; until (i = 6); writeln('Terima Kasih'); end.
unit UCardPackHand; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses sysutils, math, Generics.Collections; type TCard = class private Rank: 1 .. 13; Suit: 0 .. 3; public constructor Create(r: integer; s: integer); function GetRank: integer; function GetSuit: integer; function GetRankAsString: string; function GetSuitAsString: string; end; TCards = array [0 .. 51] of TCard; TPack = class //TPack creates and contains 52 TCards in the form of a circular queue private FCards: TCards; Ffront, Frear, FSize: integer; // FSize is number of cards currently in pack public constructor Create; // creates cards and fills array with them destructor Destroy; override; // frees cards procedure Shuffle; // rearranges cards randomly procedure Show; function DealCard: TCard; // removes top card and increments top pointer procedure AddCard(card: TCard); // adds card to bottom and increments bottom pointer function IsEmpty: boolean; function IsFull: boolean; property Top: integer read Ffront write Ffront; // points to top card property Bottom: integer read Frear write Frear; // points to bottom card property Size: integer read FSize write FSize; // number of cards currently in pack end; THand = class // THand is a collection of previously-created cards, typically contained // in TPack.Cards // THand does not create any TCards itself protected //list of references to TCards FCards: TList<TCard>; function GetCard(i: integer): TCard; function GetSize: integer; public constructor Create; destructor Destroy; override; procedure AddCard(card: TCard); procedure ShowHand; property Size: integer read GetSize; property Cards[i: integer]: TCard read GetCard; end; TPokerHand = class(THand) protected RoF, bet,bank:integer; public procedure SetRof; function GetScore:integer; function GetBet:integer; procedure SetBet(plusBet:integer); function GetBank:integer; procedure SetBank(cash:integer); procedure Sort; function GetRoF:integer; procedure Fold; end; implementation { TCard } constructor TCard.Create(r: integer; s: integer); begin Rank := r; Suit := s; end; function TCard.GetRank: integer; begin result := Rank; end; function TCard.GetRankAsString: string; begin case Rank of 1: result := 'Ace'; 2: result := 'Two'; 3: result := 'Three'; 4: result := 'Four'; 5: result := 'Five'; 6: result := 'Six'; 7: result := 'Seven'; 8: result := 'Eight'; 9: result := 'Nine'; 10: result := 'Ten'; 11: result := 'Jack'; 12: result := 'Queen'; 13: result := 'King'; end; end; function TCard.GetSuit: integer; begin result := Suit; end; function TCard.GetSuitAsString: string; begin case Suit of 0: result := 'Clubs'; 1: result := 'Diamonds'; 2: result := 'Hearts'; 3: result := 'Spades'; end; end; { TPack } procedure TPack.AddCard(card: TCard); //the card is returned to the queue //FCards[Bottom+1] is overwritten by this procedure //so it relies on it being referenced elsewhere (usually in a THand object) begin if not IsFull then begin if (Bottom = 51) then Bottom := 0 else Bottom := Bottom + 1; FCards[Bottom] := card; Size := Size + 1; end; end; constructor TPack.Create; var I: integer; begin inherited Create; //writeln('erw]oinrw[ofnrgnrgfounrfonrfgoinrfiu'); for I := 0 to 51 do FCards[I] := TCard.Create((I mod 13) + 1, I div 13); Top := 0; Bottom := 51; Size := 52; //writeln('yy coming up'); end; destructor TPack.Destroy; var I: integer; begin for I := 0 to 51 do FCards[I].Free; inherited Destroy; end; function TPack.IsEmpty: boolean; begin result := Size = 0; end; function TPack.IsFull: boolean; begin result := Size = 52; end; procedure TPack.Shuffle; var I, r: integer; temp: TCard; begin for I := Top to Bottom do begin Randomize; r := randomrange(I, Bottom + 1); temp := FCards[I]; FCards[I] := FCards[r]; FCards[r] := temp; end; end; function TPack.DealCard: TCard; //the card removed remains in the Cards array //removal just involves incrementing the Top pointer to remove it from the queue begin if not IsEmpty then // NB if empty, return value is undefined begin result := FCards[Top]; if Top = 51 then Top := 0 else Top := Top + 1; Size := Size - 1; end; end; { THand } procedure THand.AddCard(card: TCard); //add card to hand, using Add method of TList<> begin FCards.Add(card); end; procedure THand.ShowHand; var i:integer; begin for i := 0 to Size-1 do begin writeln('Card[',i+1,'] is the: ', Cards[i].GetRankAsString, ' of ', Cards[i].GetSuitAsString); end; writeln; end; function TPokerHand.GetScore:integer; var score,i,count:integer; straight,triple,double,flush:boolean; begin score:=0; flush:=false; //If they have a flush straight:=false; //If they have a straight triple:=false; //If they have three of a kind double:=false; //If they have two of a kind //Check for two of a kind for i := 0 to Size-2 do begin if Cards[i].GetRank = Cards[i+1].GetRank then begin score:=1; double:=true; end; if i <> 0 then begin if (Cards[i].GetRank = Cards[i+1].GetRank) AND (Cards[i].GetRank = Cards[i-1].GetRank) then begin //In case it is actually three of a kind score:=0; double:=false; end; end; end; //Check for two pairs count:=0; for i := 0 to Size-2 do begin if (Cards[i].GetRank = Cards[i+1].GetRank) then begin if i = 0 then begin count := count + 1; end else if Cards[i].GetRank <> Cards[i-1].GetRank then begin count:=count+1; end; end; end; if count >= 2 then begin score:=2; end; count:=0; //resets count //Check for three of a kind for i := 0 to Size-3 do begin if Cards[i].GetRank = Cards[i+1].GetRank then begin count:=count+1; end else count:=0; if count >= 2 then begin score:=3; triple:=true; end; end; //Find a straight count:=0; for i := 0 to Size-2 do begin if Cards[i].GetRank+1 = Cards[i+1].GetRank then count:=count+1 else if Cards[i].GetRank = Cards[i+1].GetRank then count:=count else count:=0; end; if count >= 4 then begin score:=4; straight:=true; end; //Finding a flush count:=0; for i := 0 to Size-2 do begin if Cards[i].GetSuit = Cards[i+1].GetSuit then count:=count+1; end; if count >= 4 then begin score:=5; flush:=true; end; //Finding a full house if (double = true) AND (triple = true) then begin score:=6; end; //Finding four of a kind count:=0; for i := 0 to Size-2 do begin if Cards[i].GetRank=Cards[i+1].GetRank then count:=count+1 else count:=0; end; if count = 3 then begin score := 7; end; //Finding a straight Flush if (flush) AND (straight) then begin score:=8; end; //Finding a royal flush if flush=true then begin //Couldn't get working end; writeln; case score of //Display what hand the player had 1: writeln('Two of a kind'); 2: writeln('Two pair'); 3: writeln('Three of a kind'); 4: writeln('Straight'); 5: writeln('Flush'); 6: writeln('Full House'); 7: writeln('Four of a kind'); 8: writeln('Straight flush'); 9: writeln('Royal Flush'); 0: writeln('peepe'); end; result:=score; end; constructor THand.Create; begin inherited; FCards := TList<TCard>.Create; //create the list //writeln(':('); end; destructor THand.Destroy; begin FCards.Free; //free the list inherited; end; function THand.GetSize: integer; begin result := FCards.Count; end; function THand.GetCard(i: integer): TCard; begin result := FCards[i]; end; procedure TPack.Show; var z:integer; begin for z := 0 to 51 do begin writeln('Card ',z,' is the: ',FCards[z].Rank, ' of ', FCards[z].Suit); end; end; procedure TPokerHand.Sort; var o,tempRank,tempSuit:integer; swapped:boolean; begin repeat swapped:=false; for o := 0 to Size-2 do begin if Cards[o].Rank > Cards[o+1].Rank then begin //writeln('Swapping Cards'); tempRank:= Cards[o].GetRank; tempSuit := Cards[o].GetSuit; //writeln('Temp card is set'); Cards[o].Rank:=Cards[o+1].GetRank; Cards[o].Suit:=Cards[o+1].GetSuit; //writeln('First card is set'); Cards[o+1].Rank:=tempRank; Cards[o+1].Suit:=tempSuit; //writeln('Second card is set'); swapped:=true; //writeln('Cards Swapped'); end; end; until swapped=false; end; procedure TPokerHand.SetRof; begin RoF:=10; end; function TPokerHand.GetRoF:integer; begin result:=RoF; end; procedure TPokerHand.Fold; begin RoF:=0; writeln('I Fold'); end; function TPokerHand.GetBank:integer; begin result:=bank; end; function TPokerHand.GetBet:integer; begin result:=Bet; end; procedure TPokerHand.SetBet(plusBet: Integer); begin bet:=bet+plusBet; end; procedure TPokerHand.SetBank(cash: Integer); begin bank:=bank+cash; end; end.
var TimeZoneInfo: TTimezoneinformation; Minutes: Integer; Sign: string; begin if not (GetTimezoneInformation(TimeZoneInfo) in [TIME_ZONE_ID_UNKNOWN, TIME_ZONE_ID_STANDARD, TIME_ZONE_ID_DAYLIGHT]) then Result(''); Minutes := (TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias) * -1; if Minutes < 0 then Sign := '-' else Sign := '+'; Result := Sign + FormatDateTime('hh:MM', IncMinute(0, Minutes)); end;
unit AST.Delphi.Options; interface uses AST.Parser.Options; type TWarnOption = class(TOption) public class function ArgsCount: Integer; override; end; TDelphiOptions = class(TOptions) private fOptSCOPEDENUMS: TBoolOption; fOptPOINTERMATH: TBoolOption; function GetSCOPEDENUMSValue: Boolean; function GetPOINTERMATHValue: Boolean; public constructor Create(Parent: TOptions); override; property SCOPEDENUMS: Boolean read GetSCOPEDENUMSValue; property POINTERMATH: Boolean read GetPOINTERMATHValue; end; implementation { TWarnOption } class function TWarnOption.ArgsCount: Integer; begin Result := 2; end; { TDelphiOptions } constructor TDelphiOptions.Create(Parent: TOptions); begin inherited; fOptSCOPEDENUMS := AddBoolOption('SCOPEDENUMS'); fOptPOINTERMATH := AddBoolOption('POINTERMATH'); //// Align fields (Delphi) //{$A},{$ALIGN} //// Application type (Delphi) //{$APPTYPE} //// Assert directives (Delphi) //{$C},{$ASSERTIONS} //// Boolean short-circuit evaluation (Delphi compiler directive) //{$B},{$BOOLEVAL} //// Code align (Delphi) //{$CODEALIGN} //// Debug information (Delphi) //{$D},{$DEBUGINFO} //// DENYPACKAGEUNIT directive (Delphi) //{$DENYPACKAGEUNIT} //// Description (Delphi) //{$D},{$DESCRIPTION} //// DESIGNONLY directive (Delphi) //{$DESIGNONLY} //// Executable extension (Delphi) //{$E},{$EXTENSION} //// Export symbols (Delphi) //{$ObjExportAll} //// Extended syntax (Delphi) //{$X},{$EXTENDEDSYNTAX} //// Extended type compatibility (Delphi) //{$EXTENDEDCOMPATIBILITY} //// External Symbols (Delphi) //{$EXTERNALSYM [ 'typeNameInHpp' [ 'typeNameInHppUnion' ]]} //// Floating point precision control (Delphi for x64) //{$EXCESSPRECISION} //// HIGHCHARUNICODE directive (Delphi) //{$HIGHCHARUNICODE} //// Hints (Delphi) //{$HINTS} //// HPP emit (Delphi) //{$HPPEMIT} //// Image base address //{$IMAGEBASE} //// Implicit Build (Delphi) //{$IMPLICITBUILD} //// Imported data //{$G},{$IMPORTEDDATA} //// Include file (Delphi) //{$I},{$INCLUDE} //// Input output checking (Delphi) //{$I},{$IOCHECKS} //// Compiler directives for libraries or shared objects (Delphi) //{$LIBPREFIX}, {$LIBSUFFIX}, {$LIBVERSION} //// Link object file (Delphi) //{$L file},{$LINK file} //// Local symbol information (Delphi) //{$L+},{$LOCALSYMBOLS} //// Long strings (Delphi) //{$H},{$LONGSTRINGS} //// Memory allocation sizes (Delphi) //{$M},{$MINSTACKSIZE},{$MAXSTACKSIZE} //// METHODINFO directive (Delphi) //{$METHODINFO} //// Minimum enumeration size (Delphi) //{$Z1},{$Z2},{$Z4},{$MINENUMSIZE 1},{$MINENUMSIZE 2},{$MINENUMSIZE 4} //// NOINCLUDE (Delphi) //{$NOINCLUDE} //// OBJTYPENAME directive (Delphi) //{$OBJTYPENAME typeIdent ['{B|N}typeNameInObj']} //// Old type layout (Delphi) //{$OLDTYPELAYOUT ON} //// Open String Parameters (Delphi) //{$P},{$OPENSTRINGS} //// Optimization (Delphi) //{$O},{$OPTIMIZATION} //// Overflow checking (Delphi) //{$Q},{$OVERFLOWCHECKS} //// PE (portable executable) header flags (Delphi) //{$SetPEFlags},{$SetPEOptFlags} //// PE header operating system version //{$SETPEOSVERSION} //// PE header subsystem version //{$SETPESUBSYSVERSION} //// PE header user version //{$SETPEUSERVERSION} //// Pentium-safe FDIV operations (Delphi) //{$U},{$SAFEDIVIDE} //// Pointer Math (Delphi) //{$POINTERMATH} //// Range checking //{$R},{$RANGECHECKS} //// Real48 compatibility (Delphi) //{$REALCOMPATIBILITY} //// Regions //{$REGION},{$ENDREGION} //// Reserved address space for resources (Delphi, Linux) //{$M},{$RESOURCERESERVE} //// Resource file (Delphi) //{$R},{$RESOURCE} //// RTTI directive (Delphi) //{$RTTI INHERIT|EXPLICIT} //// RUNONLY directive (Delphi) //{$RUNONLY} //// Run-Time Type Information (Delphi) //{$M},{$TYPEINFO} //// Scoped Enums (Delphi) //{$SCOPEDENUMS} //// Stack frames (Delphi) //{$W},{$STACKFRAMES} //// Strong link types (Delphi) //{$STRONGLINKTYPES} //// Symbol declaration and cross-reference information (Delphi) //{$Y},{$REFERENCEINFO},{DEFINITIONINFO} //// Type-checked pointers (Delphi) //{$T},{$TYPEDADDRESS} //// Var-string checking (Delphi) //{$V},{$VARSTRINGCHECKS} //// Warning messages (Delphi) //{$WARN} //// Warnings (Delphi) //{$WARNINGS} //// Weak packaging //{$WEAKPACKAGEUNIT} //// WEAKLINKRTTI directive (Delphi) //{$WEAKLINKRTTI} //// Writeable typed constants (Delphi) //{$J},{$WRITEABLECONST} //// Zero-based strings (Delphi) //{$ZEROBASEDSTRINGS} end; function TDelphiOptions.GetPOINTERMATHValue: Boolean; begin Result := fOptPOINTERMATH.Value; end; function TDelphiOptions.GetSCOPEDENUMSValue: Boolean; begin Result := fOptSCOPEDENUMS.Value; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { The object manager is used for registering classes together with a category, description + icon, so that they can be displayed visually. This can then be used by run-time or design-time scene editors for choosing which scene objects to place into a scene. TODO: add some notification code, so that when a scene object is registered/ unregistered, any editor that is using the object manager can be notified. } unit VXS.ObjectManager; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, System.UITypes, FMX.Graphics, FMX.Controls, FMX.Menus, VXS.CrossPlatform, VXS.Scene; type PSceneObjectEntry = ^TVXSceneObjectEntry; // holds a relation between an scene object class, its global identification, // its location in the object stock and its icon reference TVXSceneObjectEntry = record ObjectClass: TVXSceneObjectClass; Name: string; // type name of the object Category: string; // category of object Index, // index into "FSceneObjectList" ImageIndex: Integer; // index into "FObjectIcons" end; // TVXObjectManager // TVXObjectManager = class(TComponent) private FSceneObjectList: TList; FObjectIcons: TStyleBook; // In VCL FObjectIcons: TImageList; <- a list of icons for scene objects {$IFDEF MSWINDOWS} FOverlayIndex, // indices into the object icon list {$ENDIF} FSceneRootIndex, FCameraRootIndex, FLightsourceRootIndex, FObjectRootIndex: Integer; protected procedure DestroySceneObjectList; function FindSceneObjectClass(AObjectClass: TVXSceneObjectClass; const ASceneObject: string = ''): PSceneObjectEntry; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateDefaultObjectIcons(ResourceModule: Cardinal); function GetClassFromIndex(Index: Integer): TVXSceneObjectClass; function GetImageIndex(ASceneObject: TVXSceneObjectClass): Integer; function GetCategory(ASceneObject: TVXSceneObjectClass): string; procedure GetRegisteredSceneObjects(ObjectList: TStringList); procedure PopulateMenuWithRegisteredSceneObjects(AMenuItem: TMenuItem; AClickEvent: TNotifyEvent); // Registers a stock object and adds it to the stock object list procedure RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const AName, ACategory: string); overload; procedure RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const AName, ACategory: string; ABitmap: TBitmap); overload; procedure RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const AName, ACategory: string; ResourceModule: Cardinal; ResourceName: string = ''); overload; // Unregisters a stock object and removes it from the stock object list procedure UnRegisterSceneObject(ASceneObject: TVXSceneObjectClass); property ObjectIcons: TStyleBook read FObjectIcons; //In VCL TImageList property SceneRootIndex: Integer read FSceneRootIndex; property LightsourceRootIndex: Integer read FLightsourceRootIndex; property CameraRootIndex: Integer read FCameraRootIndex; property ObjectRootIndex: Integer read FObjectRootIndex; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ //----------------- TVXObjectManager --------------------------------------------- // Create // constructor TVXObjectManager.Create(AOwner: TComponent); begin inherited; FSceneObjectList := TList.Create; // FObjectIcons Width + Height are set when you add the first bitmap FObjectIcons := TStyleBook.Create(AOwner); //In VCL TImageList.CreateSize(16, 16); end; // Destroy // destructor TVXObjectManager.Destroy; begin DestroySceneObjectList; FObjectIcons.Free; inherited Destroy; end; // FindSceneObjectClass // function TVXObjectManager.FindSceneObjectClass(AObjectClass: TVXSceneObjectClass; const aSceneObject: string = ''): PSceneObjectEntry; var I: Integer; Found: Boolean; begin Result := nil; Found := False; with FSceneObjectList do begin for I := 0 to Count - 1 do with TVXSceneObjectEntry(Items[I]^) do if (ObjectClass = AObjectClass) and (Length(ASceneObject) = 0) or (CompareText(Name, ASceneObject) = 0) then begin Found := True; Break; end; if Found then Result := Items[I]; end; end; // GetClassFromIndex // function TVXObjectManager.GetClassFromIndex(Index: Integer): TVXSceneObjectClass; begin if Index < 0 then Index := 0; if Index > FSceneObjectList.Count - 1 then Index := FSceneObjectList.Count - 1; Result := TVXSceneObjectEntry(FSceneObjectList.Items[Index + 1]^).ObjectClass; end; // GetImageIndex // function TVXObjectManager.GetImageIndex(ASceneObject: TVXSceneObjectClass): Integer; var classEntry: PSceneObjectEntry; begin classEntry := FindSceneObjectClass(ASceneObject); if Assigned(classEntry) then Result := classEntry^.ImageIndex else Result := 0; end; // GetCategory // function TVXObjectManager.GetCategory(ASceneObject: TVXSceneObjectClass): string; var classEntry: PSceneObjectEntry; begin classEntry := FindSceneObjectClass(ASceneObject); if Assigned(classEntry) then Result := classEntry^.Category else Result := ''; end; // GetRegisteredSceneObjects // procedure TVXObjectManager.GetRegisteredSceneObjects(objectList: TStringList); var i: Integer; begin if Assigned(objectList) then with objectList do begin Clear; for i := 0 to FSceneObjectList.Count - 1 do with TVXSceneObjectEntry(FSceneObjectList.Items[I]^) do AddObject(Name, Pointer(ObjectClass)); end; end; procedure TVXObjectManager.PopulateMenuWithRegisteredSceneObjects(AMenuItem: TMenuItem; AClickEvent: TNotifyEvent); var ObjectList: TStringList; i, j: Integer; Item, CurrentParent: TMenuItem; CurrentCategory: string; Soc: TVXSceneObjectClass; begin ObjectList := TStringList.Create; try GetRegisteredSceneObjects(ObjectList); for i := 0 to ObjectList.Count - 1 do if ObjectList[i] <> '' then begin CurrentCategory := GetCategory(TVXSceneObjectClass(ObjectList.Objects[i])); if CurrentCategory = '' then CurrentParent := AMenuItem else begin CurrentParent := TMenuItem.Create(nil); CurrentParent.Text := ObjectList[j]; //in VCL CurrentParent := NewItem(CurrentCategory, 0, False, True, nil, 0, ''); AMenuItem.AddObject(CurrentParent); end; for j := i to ObjectList.Count - 1 do if ObjectList[j] <> '' then begin Soc := TVXSceneObjectClass(ObjectList.Objects[j]); if CurrentCategory = GetCategory(Soc) then begin Item := TMenuItem.Create(nil); Item.Text := ObjectList[j]; //in VCL Item := NewItem(ObjectList[j], 0, False, True, AClickEvent, 0, ''); { TODO : E2003 Undeclared identifier: 'ImageIndex' } (*Item.ImageIndex := GetImageIndex(Soc);*) CurrentParent.AddObject(Item); ObjectList[j] := ''; if CurrentCategory = '' then Break; end; end; end; finally ObjectList.Free; end; end; // RegisterSceneObject // procedure TVXObjectManager.RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const aName, aCategory: string); var resBitmapName: string; bmp: TBitmap; begin // Since no resource name was provided, assume it's the same as class name resBitmapName := ASceneObject.ClassName; bmp := TBitmap.Create; try // Try loading bitmap from module that class is in GLLoadBitmapFromInstance(FindClassHInstance(ASceneObject), bmp, resBitmapName); if bmp.Width = 0 then GLLoadBitmapFromInstance(HInstance, bmp, resBitmapName); // If resource was found, register scene object with bitmap if bmp.Width <> 0 then begin RegisterSceneObject(ASceneObject, aName, aCategory, bmp); end else // Resource not found, so register without bitmap RegisterSceneObject(ASceneObject, aName, aCategory, nil); finally bmp.Free; end; end; // RegisterSceneObject // procedure TVXObjectManager.RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const AName, ACategory: string; ABitmap: TBitmap); var NewEntry: PSceneObjectEntry; bmp: TBitmap; begin if Assigned(RegisterNoIconProc) then RegisterNoIcon([aSceneObject]); with FSceneObjectList do begin // make sure no class is registered twice if Assigned(FindSceneObjectClass(ASceneObject, AName)) then Exit; New(NewEntry); try with NewEntry^ do begin // object stock stuff // registered objects list stuff ObjectClass := ASceneObject; NewEntry^.Name := aName; NewEntry^.Category := aCategory; Index := FSceneObjectList.Count; if Assigned(aBitmap) then begin bmp := TBitmap.Create; try // If we just add the bitmap, and it has different dimensions, then // all icons will be cleared, so ensure this doesn't happen { TODO : E2129 Cannot assign to a read-only property } (*bmp.PixelFormat := TPixelFormat.RGBA; //in VCL glpf24bit;*) { TODO : E2003 Undeclared identifier: 'Width', 'Height'} (* bmp.Width := FObjectIcons.Width; bmp.Height := FObjectIcons.Height; *) { TODO : E2003 Undeclared identifiers: 'SrcRect' etc.} (*bmp.Canvas.DrawBitmap(ABitmap, SrcRect, DstRect, AOpacity, HighSpeed);*) //in VCL bmp.Canvas.Draw(0, 0, ABitmap); { TODO : E2003 Undeclared identifier: 'AddMasked' } (*FObjectIcons.AddMasked(bmp, bmp.Canvas.Pixels[0, 0]);*) ImageIndex := FObjectIcons.Index - 1; //in VCL FObjectIcons.Count finally bmp.free; end; end else ImageIndex := 0; end; Add(NewEntry); finally // end; end; end; // RegisterSceneObject // procedure TVXObjectManager.RegisterSceneObject(ASceneObject: TVXSceneObjectClass; const aName, aCategory: string; ResourceModule: Cardinal; ResourceName: string = ''); var bmp: TBitmap; resBitmapName: string; begin if ResourceName = '' then resBitmapName := ASceneObject.ClassName else resBitmapName := ResourceName; bmp := TBitmap.Create; try // Load resource if (ResourceModule <> 0) then GLLoadBitmapFromInstance(ResourceModule, bmp, resBitmapName); // If the resource was found, then register scene object using the bitmap if bmp.Width > 0 then RegisterSceneObject(ASceneObject, aName, aCategory, bmp) else // Register the scene object with no icon RegisterSceneObject(ASceneObject, aName, aCategory, nil); finally bmp.Free; end; end; // UnRegisterSceneObject // procedure TVXObjectManager.UnRegisterSceneObject(ASceneObject: TVXSceneObjectClass); var oldEntry: PSceneObjectEntry; begin // find the class in the scene object list OldEntry := FindSceneObjectClass(ASceneObject); // found? if assigned(OldEntry) then begin // remove its entry from the list of registered objects FSceneObjectList.Remove(OldEntry); // finally free the memory for the entry Dispose(OldEntry); end; end; // CreateDefaultObjectIcons // procedure TVXObjectManager.CreateDefaultObjectIcons(ResourceModule: Cardinal); var bmp: TBitmap; begin bmp := TBitmap.Create; with FObjectIcons, bmp.Canvas do begin try // There's a more direct way for loading images into the image list, but // the image quality suffers too much GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_root'); { TODO : E2003 Undeclared identifier: 'AddMasked' } (*FSceneRootIndex := AddMasked(bmp, Pixels[0, 0]);*) GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_camera'); { TODO : E2003 Undeclared identifier: 'AddMasked' } (*FCameraRootIndex := AddMasked(bmp, Pixels[0, 0]);*) GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_lights'); { TODO : E2003 Undeclared identifier: 'AddMasked' } (*FLightsourceRootIndex := AddMasked(bmp, Pixels[0, 0]);*) GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_objects'); { TODO : E2003 Undeclared identifier: 'AddMasked' } (*FObjectRootIndex := AddMasked(bmp, Pixels[0, 0]);*) finally bmp.Free; end; end; end; // DestroySceneObjectList // procedure TVXObjectManager.DestroySceneObjectList; var i: Integer; begin with FSceneObjectList do begin for i := 0 to Count - 1 do Dispose(PSceneObjectEntry(Items[I])); Free; end; end; initialization end.
unit Spielen_Klassen; interface uses SysUtils; type TMensch = class(TObject) private sName: String; iAlter: Integer; public constructor Create(name: String; alter: Integer); property Name: String read sName write sName; property Alter: Integer read iAlter write iAlter; end; TBerufstaetig = class(TMensch) private sBranche: String; // Monatsgehalt fGehalt: Single; function getEinkommen: Single; procedure setEinkommen(einkommen: Single); public constructor Create(name: String; alter: Integer; branche: String; gehalt: Single); property Branche: String read sBranche write sBranche; // Jahreseinkommen property Einkommen: Single read getEinkommen write setEinkommen; end; TStudent = class(TMensch) private sFach: String; // Monatliches Einkommen fBafoeg: Single; function getEinkommen: Single; procedure setEinkommen(einkommen: Single); public constructor Create(name: String; alter: Integer; fach: String; bafoeg: Single); property Fach: String read sFach write sFach; // Jahreseinkommen property Einkommen: Single read getEinkommen write setEinkommen; end; implementation { TMensch } constructor TMensch.Create(name: String; alter: Integer); begin sName := name; iAlter := alter; end; { TBerufstaetig } constructor TBerufstaetig.Create(name: String; alter: Integer; branche: String; gehalt: Single); begin inherited Create(name, alter); sBranche := Branche; fGehalt := gehalt; end; // Berechnet das Jahreseinkommen aus Feld fGehalt function TBerufstaetig.getEinkommen: Single; const // Einkommenssteuersätze für 2013 fGrundfreibetrag = 8004; fEingangssteuersatz = 0.86; fProgressionsende1 = 52882; fSpitzensteuersatz1 = 0.58; fProgressionsende2 = 250731; fSpitzensteuersatz2 = 0.55; var fEinkommenOhneSteuern: Single; begin fEinkommenOhneSteuern := 12 * fGehalt; if fGehalt < fGrundfreibetrag then Result := fEinkommenOhneSteuern else if fGehalt < fProgressionsende1 then Result := fEinkommenOhneSteuern * fEingangssteuersatz else if fGehalt < fProgressionsende2 then Result := fEinkommenOhneSteuern * fSpitzensteuersatz1 else Result := fEinkommenOhneSteuern * fSpitzensteuersatz2; end; // Schreibt das gegebene Jahreseinkommen ins Feld fGehalt procedure TBerufstaetig.setEinkommen(einkommen: Single); begin fGehalt := einkommen / 12; end; { TStudent } constructor TStudent.Create(name: String; alter: Integer; fach: String; bafoeg: Single); begin inherited Create(name, alter); sFach := fach; fBafoeg := bafoeg; end; // Berechnet das Jahreseinkommen aus Feld fBafoeg function TStudent.getEinkommen: Single; begin Result := fBafoeg * 12; end; // Schreibt das gegebene Jahreseinkommen ins Feld fBafoeg procedure TStudent.setEinkommen(einkommen: Single); begin fBafoeg := einkommen / 12; end; end.
unit UnitRegistro; interface uses Windows, UnitComandos, StreamUnit; type TSysLocale = packed record DefaultLCID: Integer; PriLangID: Integer; SubLangID: Integer; FarEast: Boolean; MiddleEast: Boolean; end; TMbcsByteType = (mbSingleByte, mbLeadByte, mbTrailByte); function ListarClaves(Clave: String): String; function ListarValores(Clave: String): String; function BorraClave(Clave: String):boolean; function AniadirClave(Clave, Val, Tipo: String):boolean; function RenombrarClave(Ruta, ViejaClave, NuevaClave: PChar):boolean; function ToKey(Clave: String):hKey; function IntToHex(Value: Integer; Digits: Integer): string; overload; function IntToHex(Value: Int64; Digits: Integer): string; overload; function RenameRegistryItem(Old, New: String): boolean; implementation var SysLocale: TSysLocale; LeadBytes: set of Char = []; Type KeysRecord = record Name: shortString; end; type ValoresRecord = record Name: shortstring; Tipo: shortString; Dados: shortstring; end; function ListarClaves(Clave: String): String; var phkResult: hkey; lpName: PChar; lpcbName, dwIndex: Cardinal; lpftLastWriteTime: FileTime; ResultStream: TMemoryStream; KR: KeysRecord; begin result := ''; if clave = '' then exit; RegOpenKeyEx(ToKey(Copy(Clave, 1, Pos('\', Clave) - 1)), PChar(Copy(Clave, Pos('\', Clave) + 1, Length(Clave))), 0, KEY_ENUMERATE_SUB_KEYS, phkResult); lpcbName := 255; GetMem(lpName, lpcbName); dwIndex := 0; ResultStream := TMemoryStream.Create; while RegEnumKeyEx(phkResult, dwIndex, @lpName[0] , lpcbName, nil, nil, nil, @lpftLastWriteTime) = ERROR_SUCCESS do begin Inc(dwIndex); lpcbName := 255; KR.Name := lpName; ResultStream.WriteBuffer(KR, sizeof(KeysRecord)); end; RegCloseKey(phkResult); result := StreamToStr(ResultStream); ResultStream.Free; end; procedure CvtInt; { IN: EAX: The integer value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[16] ECX: Base for conversion: 0 for signed decimal, 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Length of converted text } asm OR CL,CL JNZ @CvtLoop @C1: OR EAX,EAX JNS @C2 NEG EAX CALL @C2 MOV AL,'-' INC ECX DEC ESI MOV [ESI],AL RET @C2: MOV ECX,10 @CvtLoop: PUSH EDX PUSH ESI @D1: XOR EDX,EDX DIV ECX DEC ESI ADD DL,'0' CMP DL,'0'+10 JB @D2 ADD DL,('A'-'0')-10 @D2: MOV [ESI],DL OR EAX,EAX JNE @D1 POP ECX POP EDX SUB ECX,ESI SUB EDX,ECX JBE @D5 ADD ECX,EDX MOV AL,'0' SUB ESI,EDX JMP @z @zloop: MOV [ESI+EDX],AL @z: DEC EDX JNZ @zloop MOV [ESI],AL @D5: end; function IntToHex(Value: Integer; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EDX, 32 // Digits < buffer length? JBE @A1 XOR EDX, EDX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 PUSH ECX // result ptr MOV ECX, 16 // base 16 EDX = Digits = field width CALL CvtInt MOV EDX, ESI POP EAX // result ptr CALL System.@LStrFromPCharLen ADD ESP, 32 POP ESI end; procedure CvtInt64; { IN: EAX: Address of the int64 value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[32] ECX: Base for conversion: 0 for signed decimal, or 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Byte length of converted text } asm OR CL, CL JNZ @start // CL = 0 => signed integer conversion MOV ECX, 10 TEST [EAX + 4], $80000000 JZ @start PUSH [EAX + 4] PUSH [EAX] MOV EAX, ESP NEG [ESP] // negate the value ADC [ESP + 4],0 NEG [ESP + 4] CALL @start // perform unsigned conversion MOV [ESI-1].Byte, '-' // tack on the negative sign DEC ESI INC ECX ADD ESP, 8 RET @start: // perform unsigned conversion PUSH ESI SUB ESP, 4 FNSTCW [ESP+2].Word // save FNSTCW [ESP].Word // scratch OR [ESP].Word, $0F00 // trunc toward zero, full precision FLDCW [ESP].Word MOV [ESP].Word, CX FLD1 TEST [EAX + 4], $80000000 // test for negative JZ @ld1 // FPU doesn't understand unsigned ints PUSH [EAX + 4] // copy value before modifying PUSH [EAX] AND [ESP + 4], $7FFFFFFF // clear the sign bit PUSH $7FFFFFFF PUSH $FFFFFFFF FILD [ESP + 8].QWord // load value FILD [ESP].QWord FADD ST(0), ST(2) // Add 1. Produces unsigned $80000000 in ST(0) FADDP ST(1), ST(0) // Add $80000000 to value to replace the sign bit ADD ESP, 16 JMP @ld2 @ld1: FILD [EAX].QWord // value @ld2: FILD [ESP].Word // base FLD ST(1) @loop: DEC ESI FPREM // accumulator mod base FISTP [ESP].Word FDIV ST(1), ST(0) // accumulator := acumulator / base MOV AL, [ESP].Byte // overlap long FPU division op with int ops ADD AL, '0' CMP AL, '0'+10 JB @store ADD AL, ('A'-'0')-10 @store: MOV [ESI].Byte, AL FLD ST(1) // copy accumulator FCOM ST(3) // if accumulator >= 1.0 then loop FSTSW AX SAHF JAE @loop FLDCW [ESP+2].Word ADD ESP,4 FFREE ST(3) FFREE ST(2) FFREE ST(1); FFREE ST(0); POP ECX // original ESI SUB ECX, ESI // ECX = length of converted string SUB EDX,ECX JBE @done // output longer than field width = no pad SUB ESI,EDX MOV AL,'0' ADD ECX,EDX JMP @z @zloop: MOV [ESI+EDX].Byte,AL @z: DEC EDX JNZ @zloop MOV [ESI].Byte,AL @done: end; function IntToHex(Value: Int64; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EAX, 32 // Digits < buffer length? JLE @A1 XOR EAX, EAX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 // 32 chars MOV ECX, 16 // base 10 PUSH EDX // result ptr MOV EDX, EAX // zero filled field width: 0 for no leading zeros LEA EAX, Value; CALL CvtInt64 MOV EDX, ESI POP EAX // result ptr CALL System.@LStrFromPCharLen ADD ESP, 32 POP ESI end; function IntToStr(i: Integer): String; begin Str(i, Result); end; function StrToInt(S: String): Integer; begin Val(S, Result, Result); end; function ListarValores(Clave: String): String; var phkResult: hkey; dwIndex, lpcbValueName, lpcbData: Cardinal; lpData: PChar; lpType: DWORD; lpValueName: PChar; strTipo, strDatos, Nombre: String; j, Resultado: integer; DValue: PDWORD; VR: ValoresRecord; ResultStream: TMemoryStream; begin result := ''; if clave = '' then exit; RegOpenKeyEx(ToKey(Copy(Clave, 1, Pos('\', Clave) - 1)), PChar(Copy(Clave, Pos('\', Clave) + 1, Length(Clave))), 0, KEY_QUERY_VALUE, phkResult); dwIndex := 0; GetMem(lpValueName, 16383); //Longitud máxima del nombre de un valor: 16383 Resultado := ERROR_SUCCESS; ResultStream := TMemoryStream.Create; while (Resultado = ERROR_SUCCESS) do begin //Se guarda en lpcbData el tamaño del valor que vamor a leer RegEnumValue(phkResult, dwIndex, lpValueName, lpcbValueName, nil, @lpType, nil, @lpcbData); //Reservamos memoria if lpcbData > 16383 then lpcbData := 16383; GetMem(lpData, lpcbData); // <------------------ aqui lpcbValueName := 16383; //Y ahora lo leemos Resultado := RegEnumValue(phkResult, dwIndex, lpValueName, lpcbValueName, nil, @lpType, PByte(lpData), @lpcbData); if Resultado = ERROR_SUCCESS then begin strDatos := ''; if lpType = REG_DWORD then begin DValue := PDWORD(lpData); strDatos := '0x'+ IntToHex(DValue^, 8) + ' (' + IntToStr(DValue^) + ')'; //0xHexValue (IntValue) end else if lpType = REG_BINARY then begin if lpcbData = 0 then // strDatos := '(Não há valores)' strDatos := '(Empty)' else for j := 0 to lpcbData - 1 do strDatos:=strDatos + IntToHex(Ord(lpData[j]), 2) + ' '; //4D 5A 00 10 end else if lpType = REG_MULTI_SZ then begin for j := 0 to lpcbData - 1 do if lpData[j] = #0 then //Fin de una cadena múltiple lpData[j] := ' '; strDatos := lpData; end else //En caso de no ser DWORD, BINARY o MULTI_SZ copiar tal cual strDatos := lpData; if lpValueName[0] = #0 then //Primer caracter = fin de linea, cadena vacía // Nombre := '(Predeterminado)' Nombre := '(Default)' else Nombre := lpValueName; case lpType of REG_BINARY: strTipo := REG_BINARY_; REG_DWORD: strTipo := REG_DWORD_; REG_DWORD_BIG_ENDIAN: strTipo := REG_DWORD_BIG_ENDIAN_; REG_EXPAND_SZ: strTipo := REG_EXPAND_SZ_; REG_LINK: strTipo := REG_LINK_; REG_MULTI_SZ: strTipo := REG_MULTI_SZ_; REG_NONE: strTipo := REG_NONE_; REG_SZ: strTipo := REG_SZ_; end; VR.Name := Nombre; VR.Tipo := strTipo; VR.Dados := strDatos; ResultStream.WriteBuffer(VR, Sizeof(ValoresRecord)); Inc(dwIndex); end; end; RegCloseKey(phkResult); Result := StreamToStr(ResultStream); ResultStream.Free; end; //Función para pasar de cadena a valor HKEY function ToKey(Clave: String): HKEY; begin if Clave = HKEY_CLASSES_ROOT_ then Result := HKEY_CLASSES_ROOT else if Clave = HKEY_CURRENT_CONFIG_ then Result := HKEY_CURRENT_CONFIG else if Clave = HKEY_CURRENT_USER_ then Result := HKEY_CURRENT_USER else if Clave = HKEY_LOCAL_MACHINE_ then Result := HKEY_LOCAL_MACHINE else if Clave = HKEY_USERS_ then Result := HKEY_USERS else Result:=0; end; function StrScan(const Str: PChar; Chr: Char): PChar; begin Result := Str; while Result^ <> Chr do begin if Result^ = #0 then begin Result := nil; Exit; end; Inc(Result); end; end; function ByteTypeTest(P: PChar; Index: Integer): TMbcsByteType; var I: Integer; begin Result := mbSingleByte; if (P = nil) or (P[Index] = #$0) then Exit; if (Index = 0) then begin if P[0] in LeadBytes then Result := mbLeadByte; end else begin I := Index - 1; while (I >= 0) and (P[I] in LeadBytes) do Dec(I); if ((Index - I) mod 2) = 0 then Result := mbTrailByte else if P[Index] in LeadBytes then Result := mbLeadByte; end; end; function ByteType(const S: string; Index: Integer): TMbcsByteType; begin Result := mbSingleByte; if SysLocale.FarEast then Result := ByteTypeTest(PChar(S), Index-1); end; function LastDelimiter(S: String; Delimiter: Char): Integer; var i: Integer; begin Result := -1; i := Length(S); if (S = '') or (i = 0) then Exit; while S[i] <> Delimiter do begin if i < 0 then break; dec(i); end; Result := i; end; //Función que borra una clave (HKEY_LOCAL_MACHINE\SOFTWARE\ZETA\) o un valor //(HKEY_LOCAL_MACHINE\SOFTWARE\ZETA\value) function BorraClave(Clave: String):boolean; var phkResult: hkey; Valor: String; ClaveTemp, ClaveBase, SubClaves: String; begin result := false; ClaveTemp := Clave; //ClaveTemp:= HKEY_LOCAL_MACHINE\SOFTWARE\ZETA\ ClaveBase:=Copy(ClaveTemp, 1, Pos('\', ClaveTemp) - 1); //ClaveBase := HKEY_LOCAL_MACHINE Delete(ClaveTemp, 1, Pos('\', ClaveTemp)); //ClaveTemp := SOFTWARE\ZETA\ if ClaveTemp[Length(ClaveTemp)]='\' then //Borrando CLAVE begin ClaveTemp:=Copy(ClaveTemp, 1, Length(ClaveTemp) - 1); //Clave := SOFTWARE\ZETA Valor:= Copy(ClaveTemp, LastDelimiter(ClaveTemp, '\') + 1, Length(ClaveTemp)); //Valor := ZETA Delete(ClaveTemp, LastDelimiter(ClaveTemp, '\'), Length(ClaveTemp)); //Clave := SOFTWARE RegOpenKeyEx(ToKey(ClaveBase), PChar(ClaveTemp), 0, KEY_WRITE, phkResult); if ListarClaves(Clave) = '' then //No hay subclaves Result := (RegDeleteKey(phkResult, PChar(Valor)) = ERROR_SUCCESS) else //Hay subclaves, tenemos que borrarlas antes de borrar la clave begin SubClaves := ListarClaves(Clave); while Pos('|', SubClaves)>0 do begin Result := BorraClave(Clave + Copy(SubClaves, 1, Pos('|', SubClaves) - 1) + '\'); if Result = False then break; //No seguimos borrando Delete(SubClaves, 1, Pos('|', SubClaves)); end; //Una vez borradas las subclaves ahora podemos borrar la clave Result := (RegDeleteKey(phkResult, PChar(Valor)) = ERROR_SUCCESS) end; end else //Borrando VALOR por ejemplo: ////ClaveTemp:= SOFTWARE\ZETA\Value begin Valor:=Copy(ClaveTemp, LastDelimiter(ClaveTemp, '\') + 1, Length(ClaveTemp)); //Valor := Value Delete(ClaveTemp, LastDelimiter(ClaveTemp, '\'), Length(ClaveTemp)); //ClaveTemp:= SOFTWARE\ZETA RegOpenKeyEx(ToKey(ClaveBase), PChar(ClaveTemp), 0, KEY_SET_VALUE, phkResult); Result := (RegDeleteValue(phkResult, PChar(Valor)) = ERROR_SUCCESS); end; RegCloseKey(phkResult); end; function UpperString(S: String): String; var i: Integer; begin for i := 1 to Length(S) do S[i] := char(CharUpper(PChar(S[i]))); Result := S; end; function HexToInt(s: string): longword; var b: byte; c: char; begin Result := 0; s := UpperString(s); for b := 1 to Length(s) do begin Result := Result * 16; c := s[b]; case c of '0'..'9': Inc(Result, Ord(c) - Ord('0')); 'A'..'F': Inc(Result, Ord(c) - Ord('A') + 10); else result := 0; end; end; end; //Función para añadir una clave o un valor de cualquier tipo function AniadirClave(Clave, Val, Tipo: String):boolean; var phkResult: hkey; Valor: String; ClaveBase: String; Cadena: String; binary: Array of Byte; i: integer; begin result := false; ClaveBase := Copy(Clave, 1, Pos('\', Clave) - 1); //Se queda por ejemplo con HKEY_LOCAL_MACHINE Delete(Clave, 1, Pos('\', Clave)); //Borramos de clave lo que acabamos de copiar a ClaveBase Valor := Copy(Clave, LastDelimiter(Clave, '\') + 1, Length(Clave)); //Leemos el valor Delete(Clave, LastDelimiter(Clave, '\'), Length(Clave)); //Borramos de clave el valor if Tipo = 'clave' then begin RegOpenKeyEx(ToKey(ClaveBase), PChar(Clave), 0, KEY_CREATE_SUB_KEY, phkResult); Result := (RegCreateKey(phkResult, PChar(Valor), phkResult) = ERROR_SUCCESS); RegCloseKey(phkResult); Exit; end; if RegOpenKeyEx(ToKey(ClaveBase), PChar(Clave), 0, KEY_SET_VALUE, phkResult) = ERROR_SUCCESS then begin if Tipo = REG_SZ_ then Result := (RegSetValueEx(phkResult, Pchar(Valor), 0, REG_SZ, Pchar(Val), Length(Val)) = ERROR_SUCCESS); if Tipo = REG_BINARY_ then begin if Val[Length(Val)] <> ' ' then //Forzamos a que el último caracter sea un espacio Val := Val + ' '; Cadena := Val; i := 0; SetLength(binary, Length(Cadena) div 3); while Cadena <> '' do //Recorremos la cadena rellenando el array de bytes begin binary[i] := HexToInt(Copy(Cadena, 0, Pos(' ', Cadena) - 1)); Delete(Cadena, 1, Pos(' ', Cadena) + 1); inc(i); end; Result := (RegSetValueEx(phkResult, Pchar(Valor), 0, REG_BINARY, @binary[0], Length(binary)) = ERROR_SUCCESS); end; if Tipo = REG_DWORD_ then begin i := StrToInt(Val); Result := (RegSetValueEx(phkResult, Pchar(Valor), 0, REG_DWORD, @i, sizeof(i)) = ERROR_SUCCESS); end; if Tipo = REG_MULTI_SZ_ then begin while Pos(#13#10, Val) > 0 do //Sustituye los saltos de linea #13#10 por caracteres de fin de linea #0 Val:=Copy(Val, 1, Pos(#13#10, Val) - 1) + #0+ Copy(Val, Pos(#13#10, Val) + 2, Length(Val)); Val := Val + #0#0; //El doble caracter de fin de linea indica el final de una clave MULTI_SZ Result := (RegSetValueEx(phkResult, Pchar(Valor), 0, REG_MULTI_SZ, PChar(Val), Length(Val)) = ERROR_SUCCESS); end; RegCloseKey(phkResult); end else Result := False; end; function RenombrarClave(Ruta, ViejaClave, NuevaClave: PChar):boolean; var NewKey: hkey; ClaveBase: String; tipo, lenDatos: DWORD; Datos: Pointer; begin Result := False; ClaveBase := Copy(Ruta, 1, Pos('\', Ruta) - 1); if RegOpenKeyEx(ToKey(ClaveBase), PChar(Copy(Ruta, Pos('\', Ruta) + 1, Length(Ruta))), 0, KEY_READ or KEY_SET_VALUE, NewKey) = ERROR_SUCCESS then begin if RegQueryValueEx(NewKey, ViejaClave, nil, @tipo, nil, @lenDatos) = ERROR_SUCCESS then begin GetMem(Datos, lenDatos); if RegQueryValueEx(NewKey, ViejaClave, nil, @tipo, Datos, @lenDatos) = ERROR_SUCCESS then //Creamos la clave con el nuevo nombre if RegSetValueEx(NewKey, NuevaClave, 0, tipo, Datos, lenDatos) = ERROR_SUCCESS then //Borramos la anterior clave Result := RegDeleteValue(NewKey, ViejaClave) = ERROR_SUCCESS; FreeMem(Datos, lenDatos); end; end; RegCloseKey(NewKey); end; function AllocMem(Size: Cardinal): Pointer; begin GetMem(Result, Size); FillChar(Result^, Size, 0); end; function CopyRegistryKey(Source, Dest: HKEY): boolean; const DefValueSize = 512; DefBufferSize = 8192; var Status : Integer; Key : Integer; ValueSize, BufferSize : Cardinal; KeyType : Integer; ValueName : String; Buffer : Pointer; NewTo, NewFrom : HKEY; begin result := false; SetLength(ValueName,DefValueSize); Buffer := AllocMem(DefBufferSize); try Key := 0; repeat ValueSize := DefValueSize; BufferSize := DefBufferSize; // enumerate data values at current key Status := RegEnumValue(Source,Key,PChar(ValueName),ValueSize,nil,@KeyType,Buffer,@BufferSize); if Status = ERROR_SUCCESS then begin // move each value to new place Status := RegSetValueEx(Dest,PChar(ValueName),0,KeyType,Buffer,BufferSize); // delete old value RegDeleteValue(Source,PChar(ValueName)); end; until Status <> ERROR_SUCCESS; // Loop until all values found // start over, looking for keys now instead of values Key := 0; repeat ValueSize := DefValueSize; BufferSize := DefBufferSize; Status := RegEnumKeyEx(Source,Key,PChar(ValueName),ValueSize,nil,Buffer,@BufferSize,nil); // was a valid key found? if Status = ERROR_SUCCESS then begin // open the key if found Status := RegCreateKey(Dest,PChar(ValueName),NewTo); if Status = ERROR_SUCCESS then begin // Create new key of old name Status := RegCreateKey(Source,PChar(ValueName),NewFrom); if Status = ERROR_SUCCESS then begin // if that worked, recurse back here CopyRegistryKey(NewFrom,NewTo); RegCloseKey(NewFrom); RegDeleteKey(Source,PChar(ValueName)); end; RegCloseKey(NewTo); end; end; until Status <> ERROR_SUCCESS; // loop until key enum fails finally FreeMem(Buffer); end; end; function RegKeyExists(const RootKey: HKEY; Key: String): Boolean; var Handle : HKEY; begin if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_ENUMERATE_SUB_KEYS, Handle) = ERROR_SUCCESS then begin Result := True; RegCloseKey(Handle); end else Result := False; end; procedure RenRegItem(AKey: HKEY; Old, New: String); var OldKey, NewKey : HKEY; Status : Integer; begin // Open Source key Status := RegOpenKey(AKey,PChar(Old),OldKey); if Status = ERROR_SUCCESS then begin // Create Destination key Status := RegCreateKey(AKey,PChar(New),NewKey); if Status = ERROR_SUCCESS then CopyRegistryKey(OldKey,NewKey); RegCloseKey(OldKey); RegCloseKey(NewKey); // Delete last top-level key RegDeleteKey(AKey,PChar(Old)); end; end; function RenameRegistryItem(Old, New: String): boolean; var AKey : HKEY; ClaveBase: string; begin ClaveBase := Copy(Old, 1, Pos('\', Old) - 1); AKey := ToKey(ClaveBase); delete(new, 1, pos('\', new)); delete(Old, 1, pos('\', Old)); if RegKeyExists(AKey, New) = true then begin result := false; exit; end; RenRegItem(AKey, old, new); if RegKeyExists(AKey, old) = true then begin result := false; exit; end; result := RegKeyExists(AKey, new); end; end.
unit uParams; interface uses classes; type TParamItem = class(TCollectionItem) private FName: string; FValue: variant; public property Name: string read FName; property Value: variant read FValue write FValue; end; TParamCollection = class(TCollection) private function GetItems(Index: integer): TParamItem; function GetItemByName(AName: string): TParamItem; public property Items[Index: integer]: TParamItem read GetItems; property ItemByName[AName: string]: TParamItem read GetItemByName; default; function Add(AName: string): TParamItem; function Exists(AName: string): boolean; procedure CopyFrom(Source: TParamCollection); end; implementation uses SysUtils, uException; { TParamCollection } function TParamCollection.Add(AName: string): TParamItem; begin result:=TParamItem(inherited Add); result.FName:=AName; end; procedure TParamCollection.CopyFrom(Source: TParamCollection); var i: integer; begin if not Assigned(Source) then exit; Clear; for i:=0 to Source.Count-1 do Add(Source.Items[i].Name).Value:=Source.Items[i].Value; end; function TParamCollection.Exists(AName: string): boolean; var i: integer; begin result:=false; AName:=AnsiLowerCase(AName); for i:=0 to Count-1 do if AnsiLowerCase(Items[i].Name)=AName then begin result:=true; exit; end; end; function TParamCollection.GetItemByName(AName: string): TParamItem; var i: integer; begin result:=nil; for i:=0 to Count-1 do if AnsiLowerCase(Items[i].Name)=AnsiLowerCase(AName) then begin result:=Items[i]; exit; end; //если не найден - то добавляем result:=Add(AName); // raise EParamNotFoundException.Create(format('Параметр "%s" не найден', [AName])); end; function TParamCollection.GetItems(Index: integer): TParamItem; begin result:=TParamItem(inherited Items[Index]); end; end.
var oneX, twoX: real; functionY, functionZ: real; a, b, c, y, z: real; dublicate: real; begin writeln('Enter numbers:'); write('a -> '); readln(a); write('b -> '); readln(b); write('c -> '); readln(c); writeln; dublicate:= sqrt( abs( sqr(b) - 4 * a * c ) ); oneX:= (b + dublicate) / 2 * a; twoX:= (b - dublicate) / 2 * a; y:= ( exp( -(oneX) ) + exp( -(twoX) )) / 2; z:= ( a * sqrt( oneX ) - b * sqrt( twoX )) / c; writeln('Calculation result:'); writeln('Value x1 -> ', oneX); writeln('Value x2 -> ', twoX); writeln('--------------------'); writeln('y -> ', y); writeln('z -> ', z); end.
unit ufrmDialogCreditCard; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ExtCtrls, StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, uInterface, uModCreditCard, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, Datasnap.DBClient, uClientClasses; type TfrmDialogCreditCard = class(TfrmMasterDialog, iCRUDAble) cboisCredit: TComboBox; chkIsActive: TCheckBox; chkIsCachBack: TCheckBox; chkIsKring: TCheckBox; cxLookupAccount: TcxExtLookupComboBox; cxLookupAccountCashBack: TcxExtLookupComboBox; edtCardCode: TEdit; edtCardName: TEdit; edtLimit: TcxCurrencyEdit; fedtCharge: TcxCurrencyEdit; fedtDisc: TcxCurrencyEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; lbl6: TLabel; lbl7: TLabel; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure edtLimitEnter(Sender: TObject); procedure fedtChargeExit(Sender: TObject); procedure fedtDiscExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FCDSRekening: TClientDataSet; FDSClient: TDSProviderClient; FModCreditCard: TModCreditCard; procedure ClearForm; function GetCDSRekening: TClientDataSet; function GetDSClient: TDSProviderClient; function GetModCreditCard: TModCreditCard; function IsValidate: Boolean; procedure SavingData; property CDSRekening: TClientDataSet read GetCDSRekening write FCDSRekening; property DSClient: TDSProviderClient read GetDSClient write FDSClient; property ModCreditCard: TModCreditCard read GetModCreditCard write FModCreditCard; public procedure LoadData(AID: string); end; var frmDialogCreditCard: TfrmDialogCreditCard; implementation uses uTSCommonDlg, uDXUtils, uDBUtils, uDMClient, uAppUtils, uConstanta, uModRekening; {$R *.dfm} procedure TfrmDialogCreditCard.actDeleteExecute(Sender: TObject); begin inherited; if TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then begin DMClient.CrudClient.DeleteFromDB(ModCreditCard); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); Self.Close; end; end; procedure TfrmDialogCreditCard.actSaveExecute(Sender: TObject); begin inherited; if IsValidate then SavingData; end; procedure TfrmDialogCreditCard.ClearForm; begin edtCardCode.Clear; edtCardName.Clear; cboisCredit.ItemIndex := 0; edtLimit.Value := 0; fedtCharge.Value := 0; fedtDisc.Value := 0; chkIsActive.Checked := True; chkIsCachBack.Checked := False; chkIsKring.Checked := False; end; procedure TfrmDialogCreditCard.edtLimitEnter(Sender: TObject); begin inherited; edtLimit.SelectAll; end; procedure TfrmDialogCreditCard.fedtChargeExit(Sender: TObject); begin inherited; if fedtCharge.Value > 100 then fedtCharge.Value := 100; end; procedure TfrmDialogCreditCard.fedtDiscExit(Sender: TObject); begin inherited; if fedtDisc.Value > 100 then fedtDisc.Value := 100; end; procedure TfrmDialogCreditCard.FormCreate(Sender: TObject); begin inherited; ClearForm; cxLookupAccount.Properties.LoadFromCDS(CDSRekening,'Rekening_ID','Rek_Name',['Rekening_ID'],Self); cxLookupAccount.Properties.SetMultiPurposeLookup; cxLookupAccountCashBack.Properties.LoadFromCDS(CDSRekening,'Rekening_ID','Rek_Name',['Rekening_ID'],Self); cxLookupAccountCashBack.Properties.SetMultiPurposeLookup; Self.AssignKeyDownEvent; end; procedure TfrmDialogCreditCard.FormDestroy(Sender: TObject); begin inherited; frmDialogCreditCard := nil; end; function TfrmDialogCreditCard.GetCDSRekening: TClientDataSet; begin if not Assigned(FCDSRekening) then begin FCDSRekening := TDBUtils.DSToCDS(DSClient.Rekening_GetDSLookup, Self ); end; Result := FCDSRekening; end; function TfrmDialogCreditCard.GetDSClient: TDSProviderClient; begin if not Assigned(FDSClient) then FDSClient := TDSProviderClient.Create(DMClient.RestConn); Result := FDSClient; end; function TfrmDialogCreditCard.GetModCreditCard: TModCreditCard; begin if not Assigned(FModCreditCard) then FModCreditCard := TModCreditCard.Create; Result := FModCreditCard; end; function TfrmDialogCreditCard.IsValidate: Boolean; begin Result := False; if edtCardCode.Text = '' then begin TAppUtils.Warning('Card Code belum diisi'); exit; end else if edtCardName.Text = '' then begin TAppUtils.Warning('Card Name belum diisi'); exit; end else Result := True; end; procedure TfrmDialogCreditCard.LoadData(AID: string); begin if Assigned(FModCreditCard) then FreeAndNil(FModCreditCard); FModCreditCard := DMClient.CrudClient.Retrieve(TModCreditCard.ClassName, AID) as TModCreditCard; edtCardCode.Text := ModCreditCard.CARD_CODE; edtCardName.Text := ModCreditCard.CARD_NAME; cboisCredit.ItemIndex := ModCreditCard.CARD_IS_CREDIT; edtLimit.Value := ModCreditCard.CARD_LIMIT; fedtCharge.Value := ModCreditCard.CARD_CHARGE; fedtDisc.Value := ModCreditCard.CARD_DISCOUNT; chkIsActive.Checked := ModCreditCard.CARD_IS_ACTIVE = 1; chkIsCachBack.Checked := ModCreditCard.CARD_IS_CASHBACK = 1; chkIsKring.Checked := ModCreditCard.CARD_IS_KRING = 1; if Assigned(ModCreditCard.REKENING) then cxLookupAccount.EditValue := ModCreditCard.REKENING.ID; if Assigned(ModCreditCard.REKENING_CASH_BACK) then cxLookupAccountCashBack.EditValue := ModCreditCard.REKENING_CASH_BACK.ID; end; procedure TfrmDialogCreditCard.SavingData; begin ModCreditCard.CARD_CODE := edtCardCode.Text; ModCreditCard.CARD_NAME := edtCardName.Text; ModCreditCard.CARD_IS_CREDIT := cboisCredit.ItemIndex; ModCreditCard.CARD_LIMIT := edtLimit.Value; ModCreditCard.CARD_CHARGE := fedtCharge.Value; ModCreditCard.CARD_DISCOUNT := fedtDisc.Value; ModCreditCard.CARD_IS_ACTIVE := TAppUtils.BoolToInt(chkIsActive.Checked); ModCreditCard.CARD_IS_CASHBACK := TAppUtils.BoolToInt(chkIsCachBack.Checked); ModCreditCard.CARD_IS_KRING := TAppUtils.BoolToInt(chkIsKring.Checked); if not VarIsNull(cxLookupAccount.EditValue) then begin ModCreditCard.REKENING := TModRekening.CreateID(cxLookupAccount.EditValue); end; if not VarIsNull(cxLookupAccountCashBack.EditValue) then begin ModCreditCard.REKENING_CASH_BACK := TModRekening.CreateID(cxLookupAccountCashBack.EditValue); end; Try DMClient.CrudClient.SaveToDB(ModCreditCard); TAppUtils.Information(CONF_ADD_SUCCESSFULLY); ModalResult := mrOk; except TAppUtils.Error(ER_INSERT_FAILED); Raise; End; end; end.
unit Tiny.Rtti; {******************************************************************************} { Copyright (c) Dmitry Mozulyov } { } { 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. } { } { email: softforyou@inbox.ru } { skype: dimandevil } { repository: https://github.com/d-mozulyov/Tiny.Rtti } {******************************************************************************} {$I TINY.DEFINES.inc} interface {$ifdef MSWINDOWS} uses {$ifdef UNITSCOPENAMES}Winapi.Windows{$else}Windows{$endif}; {$endif} type { RTL types } {$ifdef FPC} PUInt64 = ^UInt64; PBoolean = ^Boolean; PString = ^string; {$else} {$if CompilerVersion < 16} UInt64 = Int64; PUInt64 = ^UInt64; {$ifend} {$if CompilerVersion < 21} NativeInt = Integer; NativeUInt = Cardinal; {$ifend} {$if CompilerVersion < 22} PNativeInt = ^NativeInt; PNativeUInt = ^NativeUInt; {$ifend} PWord = ^Word; {$endif} {$if SizeOf(Extended) >= 10} {$define EXTENDEDSUPPORT} {$ifend} TBytes = {$if (not Defined(FPC)) and (CompilerVersion >= 23)}TArray<Byte>{$else}array of Byte{$ifend}; PBytes = ^TBytes; {$ifdef ANSISTRSUPPORT} {$if Defined(NEXTGEN) and (CompilerVersion >= 31)} AnsiChar = type System.UTF8Char; PAnsiChar = ^AnsiChar; AnsiString = type System.RawByteString; PAnsiString = ^AnsiString; UTF8Char = System.UTF8Char; PUTF8Char = System.PUTF8Char; {$POINTERMATH ON} {$else} AnsiChar = System.AnsiChar; PAnsiChar = System.PAnsiChar; AnsiString = System.AnsiString; PAnsiString = System.PAnsiString; UTF8Char = type System.AnsiChar; PUTF8Char = ^UTF8Char; {$ifend} UTF8String = System.UTF8String; PUTF8String = System.PUTF8String; {$ifdef UNICODE} RawByteString = System.RawByteString; {$ifdef FPC} PRawByteString = ^RawByteString; {$else} PRawByteString = System.PRawByteString; {$endif} {$else} RawByteString = type AnsiString; PRawByteString = ^RawByteString; {$endif} {$else} AnsiChar = type Byte; PAnsiChar = ^AnsiChar; UTF8Char = type AnsiChar; PUTF8Char = ^UTF8Char; AnsiString = array of AnsiChar; PAnsiString = ^AnsiString; UTF8String = type AnsiString; PUTF8String = ^UTF8String; RawByteString = type AnsiString; PRawByteString = ^RawByteString; {$endif} {$ifdef SHORTSTRSUPPORT} ShortString = System.ShortString; PShortString = System.PShortString; {$else} ShortString = array[0{length}..255] of AnsiChar{/UTF8Char}; PShortString = ^ShortString; {$endif} {$ifdef WIDESTRSUPPORT} WideString = System.WideString; PWideString = System.PWideString; {$else} WideString = array of WideChar; PWideString = ^WideString; {$endif} {$ifdef UNICODE} {$ifdef FPC} UnicodeChar = System.WideChar; PUnicodeChar = System.PWideChar; {$else} UnicodeChar = System.Char; PUnicodeChar = System.PChar; {$endif} UnicodeString = System.UnicodeString; PUnicodeString = System.PUnicodeString; {$else} UnicodeChar = System.WideChar; PUnicodeChar = System.PWideChar; UnicodeString = System.WideString; PUnicodeString = System.PWideString; {$endif} WideChar = System.WideChar; PWideChar = System.PWideChar; UCS4Char = System.UCS4Char; PUCS4Char = System.PUCS4Char; UCS4String = System.UCS4String; PUCS4String = ^UCS4String; type PDynArrayRec = ^TDynArrayRec; TDynArrayRec = packed object protected {$ifdef FPC} function GetLength: NativeInt; {$ifdef INLINESUPPORT}inline;{$endif} procedure SetLength(const AValue: NativeInt); {$ifdef INLINESUPPORT}inline;{$endif} {$else .DELPHI} function GetHigh: NativeInt; {$ifdef INLINESUPPORT}inline;{$endif} procedure SetHigh(const AValue: NativeInt); {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public {$ifdef FPC} property Length: NativeInt read GetLength write SetLength; {$else .DELPHI} property High: NativeInt read GetHigh write SetHigh; {$endif} public {$ifdef FPC} RefCount: NativeInt; High: NativeInt; {$else .DELPHI} {$ifdef LARGEINT}_Padding: Integer;{$endif} RefCount: Integer; Length: NativeInt; {$endif} end; {$ifdef UNICODE} PUnicodeStrRec = ^TUnicodeStrRec; TUnicodeStrRec = packed record case Integer of 0: ( {$ifdef FPC} CodePageElemSize: Integer; {$ifdef LARGEINT}_Padding: Integer;{$endif} RefCount: NativeInt; Length: NativeInt; {$else .DELPHI} {$ifdef LARGEINT}_Padding: Integer;{$endif} CodePageElemSize: Integer; RefCount: Integer; Length: Integer; {$endif} ); 1: ( {$if (not Defined(FPC)) and Defined(LARGEINT)}_: Integer;{$ifend} CodePage: Word; ElementSize: Word; ); end; const {$ifdef FPC} USTR_OFFSET_LENGTH = SizeOf(NativeInt); USTR_OFFSET_REFCOUNT = USTR_OFFSET_LENGTH + SizeOf(NativeInt); USTR_OFFSET_CODEPAGE = SizeOf(TUnicodeStrRec); {$else .DELPHI} USTR_OFFSET_LENGTH = 4{SizeOf(Integer)}; USTR_OFFSET_REFCOUNT = USTR_OFFSET_LENGTH + SizeOf(Integer); USTR_OFFSET_CODEPAGE = USTR_OFFSET_REFCOUNT + {ElemSize}SizeOf(Word) + {CodePage}SizeOf(Word); {$endif} {$endif} type PAnsiStrRec = ^TAnsiStrRec; {$if not Defined(ANSISTRSUPPORT)} TAnsiStrRec = TDynArrayRec; const {$ifdef FPC} // None {$else .DELPHI} ASTR_OFFSET_LENGTH = {$ifdef SMALLINT}4{$else}8{$endif}{SizeOf(NativeInt)}; ASTR_OFFSET_REFCOUNT = ASTR_OFFSET_LENGTH + SizeOf(Integer); {$endif} {$elseif not Defined(INTERNALCODEPAGE)} TAnsiStrRec = packed record RefCount: Integer; Length: Integer; end; const {$ifdef FPC} // None {$else .DELPHI} ASTR_OFFSET_LENGTH = 4{SizeOf(Integer)}; ASTR_OFFSET_REFCOUNT = ASTR_OFFSET_LENGTH + SizeOf(Integer); {$endif} {$else .INTERNALCODEPAGE} TAnsiStrRec = TUnicodeStrRec; const ASTR_OFFSET_LENGTH = USTR_OFFSET_LENGTH; ASTR_OFFSET_REFCOUNT = USTR_OFFSET_REFCOUNT; ASTR_OFFSET_CODEPAGE = USTR_OFFSET_CODEPAGE; {$ifend} type PWideStrRec = ^TWideStrRec; {$if not Defined(WIDESTRSUPPORT)} TWideStrRec = TDynArrayRec; const WSTR_OFFSET_LENGTH = {$ifdef SMALLINT}4{$else}8{$endif}{SizeOf(NativeInt)}; {$elseif Defined(MSWINDOWS)} TWideStrRec = packed object protected function GetLength: Integer; {$ifdef INLINESUPPORT}inline;{$endif} procedure SetLength(const AValue: Integer); {$ifdef INLINESUPPORT}inline;{$endif} public property Length: Integer read GetLength write SetLength; public Size: Integer; end; const WSTR_OFFSET_SIZE = 4{SizeOf(Integer)}; {$else .INTERNALCODEPAGE} TWideStrRec = TUnicodeStrRec; const WSTR_OFFSET_LENGTH = USTR_OFFSET_LENGTH; {$ifend} {$ifNdef UNICODE} type PUnicodeStrRec = PWideStrRec; TUnicodeStrRec = TWideStrRec; const USTR_OFFSET_SIZE = WSTR_OFFSET_SIZE; {$endif} type PUCS4StrRec = ^TUCS4StrRec; TUCS4StrRec = TDynArrayRec; type PShortStringHelper = ^ShortStringHelper; ShortStringHelper = packed object protected function GetValue: Integer; {$ifdef INLINESUPPORT}inline;{$endif} procedure SetValue(const AValue: Integer); {$ifdef INLINESUPPORT}inline;{$endif} function GetAnsiValue: AnsiString; function GetUTF8Value: UTF8String; function GetUnicodeValue: UnicodeString; function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Value: ShortString; property Length: Integer read GetValue write SetValue; property AnsiValue: AnsiString read GetAnsiValue; property UTF8Value: UTF8String read GetUTF8Value; property UnicodeValue: UnicodeString read GetUnicodeValue; property StringValue: string read {$ifdef UNICODE}GetUnicodeValue{$else .ANSI}GetAnsiValue{$endif}; property Tail: Pointer read GetTail; end; string1 = {$ifdef SHORTSTRSUPPORT}string[1]{$else}array[0..1] of AnsiChar{$endif}; string2 = {$ifdef SHORTSTRSUPPORT}string[2]{$else}array[0..2] of AnsiChar{$endif}; string3 = {$ifdef SHORTSTRSUPPORT}string[3]{$else}array[0..3] of AnsiChar{$endif}; string4 = {$ifdef SHORTSTRSUPPORT}string[4]{$else}array[0..4] of AnsiChar{$endif}; string5 = {$ifdef SHORTSTRSUPPORT}string[5]{$else}array[0..5] of AnsiChar{$endif}; string6 = {$ifdef SHORTSTRSUPPORT}string[6]{$else}array[0..6] of AnsiChar{$endif}; string7 = {$ifdef SHORTSTRSUPPORT}string[7]{$else}array[0..7] of AnsiChar{$endif}; string8 = {$ifdef SHORTSTRSUPPORT}string[8]{$else}array[0..8] of AnsiChar{$endif}; string9 = {$ifdef SHORTSTRSUPPORT}string[9]{$else}array[0..9] of AnsiChar{$endif}; string10 = {$ifdef SHORTSTRSUPPORT}string[10]{$else}array[0..10] of AnsiChar{$endif}; string11 = {$ifdef SHORTSTRSUPPORT}string[11]{$else}array[0..11] of AnsiChar{$endif}; string12 = {$ifdef SHORTSTRSUPPORT}string[12]{$else}array[0..12] of AnsiChar{$endif}; string13 = {$ifdef SHORTSTRSUPPORT}string[13]{$else}array[0..13] of AnsiChar{$endif}; string14 = {$ifdef SHORTSTRSUPPORT}string[14]{$else}array[0..14] of AnsiChar{$endif}; string15 = {$ifdef SHORTSTRSUPPORT}string[15]{$else}array[0..15] of AnsiChar{$endif}; string16 = {$ifdef SHORTSTRSUPPORT}string[16]{$else}array[0..16] of AnsiChar{$endif}; string17 = {$ifdef SHORTSTRSUPPORT}string[17]{$else}array[0..17] of AnsiChar{$endif}; string18 = {$ifdef SHORTSTRSUPPORT}string[18]{$else}array[0..18] of AnsiChar{$endif}; string19 = {$ifdef SHORTSTRSUPPORT}string[19]{$else}array[0..19] of AnsiChar{$endif}; string20 = {$ifdef SHORTSTRSUPPORT}string[20]{$else}array[0..20] of AnsiChar{$endif}; string21 = {$ifdef SHORTSTRSUPPORT}string[21]{$else}array[0..21] of AnsiChar{$endif}; string22 = {$ifdef SHORTSTRSUPPORT}string[22]{$else}array[0..22] of AnsiChar{$endif}; string23 = {$ifdef SHORTSTRSUPPORT}string[23]{$else}array[0..23] of AnsiChar{$endif}; string24 = {$ifdef SHORTSTRSUPPORT}string[24]{$else}array[0..24] of AnsiChar{$endif}; string25 = {$ifdef SHORTSTRSUPPORT}string[25]{$else}array[0..25] of AnsiChar{$endif}; string26 = {$ifdef SHORTSTRSUPPORT}string[26]{$else}array[0..26] of AnsiChar{$endif}; string27 = {$ifdef SHORTSTRSUPPORT}string[27]{$else}array[0..27] of AnsiChar{$endif}; string28 = {$ifdef SHORTSTRSUPPORT}string[28]{$else}array[0..28] of AnsiChar{$endif}; string29 = {$ifdef SHORTSTRSUPPORT}string[29]{$else}array[0..29] of AnsiChar{$endif}; string30 = {$ifdef SHORTSTRSUPPORT}string[30]{$else}array[0..30] of AnsiChar{$endif}; string31 = {$ifdef SHORTSTRSUPPORT}string[31]{$else}array[0..31] of AnsiChar{$endif}; string32 = {$ifdef SHORTSTRSUPPORT}string[32]{$else}array[0..32] of AnsiChar{$endif}; string33 = {$ifdef SHORTSTRSUPPORT}string[33]{$else}array[0..33] of AnsiChar{$endif}; string34 = {$ifdef SHORTSTRSUPPORT}string[34]{$else}array[0..34] of AnsiChar{$endif}; string35 = {$ifdef SHORTSTRSUPPORT}string[35]{$else}array[0..35] of AnsiChar{$endif}; string36 = {$ifdef SHORTSTRSUPPORT}string[36]{$else}array[0..36] of AnsiChar{$endif}; string37 = {$ifdef SHORTSTRSUPPORT}string[37]{$else}array[0..37] of AnsiChar{$endif}; string38 = {$ifdef SHORTSTRSUPPORT}string[38]{$else}array[0..38] of AnsiChar{$endif}; string39 = {$ifdef SHORTSTRSUPPORT}string[39]{$else}array[0..39] of AnsiChar{$endif}; string40 = {$ifdef SHORTSTRSUPPORT}string[40]{$else}array[0..40] of AnsiChar{$endif}; string41 = {$ifdef SHORTSTRSUPPORT}string[41]{$else}array[0..41] of AnsiChar{$endif}; string42 = {$ifdef SHORTSTRSUPPORT}string[42]{$else}array[0..42] of AnsiChar{$endif}; string43 = {$ifdef SHORTSTRSUPPORT}string[43]{$else}array[0..43] of AnsiChar{$endif}; string44 = {$ifdef SHORTSTRSUPPORT}string[44]{$else}array[0..44] of AnsiChar{$endif}; string45 = {$ifdef SHORTSTRSUPPORT}string[45]{$else}array[0..45] of AnsiChar{$endif}; string46 = {$ifdef SHORTSTRSUPPORT}string[46]{$else}array[0..46] of AnsiChar{$endif}; string47 = {$ifdef SHORTSTRSUPPORT}string[47]{$else}array[0..47] of AnsiChar{$endif}; string48 = {$ifdef SHORTSTRSUPPORT}string[48]{$else}array[0..48] of AnsiChar{$endif}; string49 = {$ifdef SHORTSTRSUPPORT}string[49]{$else}array[0..49] of AnsiChar{$endif}; string50 = {$ifdef SHORTSTRSUPPORT}string[50]{$else}array[0..50] of AnsiChar{$endif}; string51 = {$ifdef SHORTSTRSUPPORT}string[51]{$else}array[0..51] of AnsiChar{$endif}; string52 = {$ifdef SHORTSTRSUPPORT}string[52]{$else}array[0..52] of AnsiChar{$endif}; string53 = {$ifdef SHORTSTRSUPPORT}string[53]{$else}array[0..53] of AnsiChar{$endif}; string54 = {$ifdef SHORTSTRSUPPORT}string[54]{$else}array[0..54] of AnsiChar{$endif}; string55 = {$ifdef SHORTSTRSUPPORT}string[55]{$else}array[0..55] of AnsiChar{$endif}; string56 = {$ifdef SHORTSTRSUPPORT}string[56]{$else}array[0..56] of AnsiChar{$endif}; string57 = {$ifdef SHORTSTRSUPPORT}string[57]{$else}array[0..57] of AnsiChar{$endif}; string58 = {$ifdef SHORTSTRSUPPORT}string[58]{$else}array[0..58] of AnsiChar{$endif}; string59 = {$ifdef SHORTSTRSUPPORT}string[59]{$else}array[0..59] of AnsiChar{$endif}; string60 = {$ifdef SHORTSTRSUPPORT}string[60]{$else}array[0..60] of AnsiChar{$endif}; string61 = {$ifdef SHORTSTRSUPPORT}string[61]{$else}array[0..61] of AnsiChar{$endif}; string62 = {$ifdef SHORTSTRSUPPORT}string[62]{$else}array[0..62] of AnsiChar{$endif}; string63 = {$ifdef SHORTSTRSUPPORT}string[63]{$else}array[0..63] of AnsiChar{$endif}; string64 = {$ifdef SHORTSTRSUPPORT}string[64]{$else}array[0..64] of AnsiChar{$endif}; string65 = {$ifdef SHORTSTRSUPPORT}string[65]{$else}array[0..65] of AnsiChar{$endif}; string66 = {$ifdef SHORTSTRSUPPORT}string[66]{$else}array[0..66] of AnsiChar{$endif}; string67 = {$ifdef SHORTSTRSUPPORT}string[67]{$else}array[0..67] of AnsiChar{$endif}; string68 = {$ifdef SHORTSTRSUPPORT}string[68]{$else}array[0..68] of AnsiChar{$endif}; string69 = {$ifdef SHORTSTRSUPPORT}string[69]{$else}array[0..69] of AnsiChar{$endif}; string70 = {$ifdef SHORTSTRSUPPORT}string[70]{$else}array[0..70] of AnsiChar{$endif}; string71 = {$ifdef SHORTSTRSUPPORT}string[71]{$else}array[0..71] of AnsiChar{$endif}; string72 = {$ifdef SHORTSTRSUPPORT}string[72]{$else}array[0..72] of AnsiChar{$endif}; string73 = {$ifdef SHORTSTRSUPPORT}string[73]{$else}array[0..73] of AnsiChar{$endif}; string74 = {$ifdef SHORTSTRSUPPORT}string[74]{$else}array[0..74] of AnsiChar{$endif}; string75 = {$ifdef SHORTSTRSUPPORT}string[75]{$else}array[0..75] of AnsiChar{$endif}; string76 = {$ifdef SHORTSTRSUPPORT}string[76]{$else}array[0..76] of AnsiChar{$endif}; string77 = {$ifdef SHORTSTRSUPPORT}string[77]{$else}array[0..77] of AnsiChar{$endif}; string78 = {$ifdef SHORTSTRSUPPORT}string[78]{$else}array[0..78] of AnsiChar{$endif}; string79 = {$ifdef SHORTSTRSUPPORT}string[79]{$else}array[0..79] of AnsiChar{$endif}; string80 = {$ifdef SHORTSTRSUPPORT}string[80]{$else}array[0..80] of AnsiChar{$endif}; string81 = {$ifdef SHORTSTRSUPPORT}string[81]{$else}array[0..81] of AnsiChar{$endif}; string82 = {$ifdef SHORTSTRSUPPORT}string[82]{$else}array[0..82] of AnsiChar{$endif}; string83 = {$ifdef SHORTSTRSUPPORT}string[83]{$else}array[0..83] of AnsiChar{$endif}; string84 = {$ifdef SHORTSTRSUPPORT}string[84]{$else}array[0..84] of AnsiChar{$endif}; string85 = {$ifdef SHORTSTRSUPPORT}string[85]{$else}array[0..85] of AnsiChar{$endif}; string86 = {$ifdef SHORTSTRSUPPORT}string[86]{$else}array[0..86] of AnsiChar{$endif}; string87 = {$ifdef SHORTSTRSUPPORT}string[87]{$else}array[0..87] of AnsiChar{$endif}; string88 = {$ifdef SHORTSTRSUPPORT}string[88]{$else}array[0..88] of AnsiChar{$endif}; string89 = {$ifdef SHORTSTRSUPPORT}string[89]{$else}array[0..89] of AnsiChar{$endif}; string90 = {$ifdef SHORTSTRSUPPORT}string[90]{$else}array[0..90] of AnsiChar{$endif}; string91 = {$ifdef SHORTSTRSUPPORT}string[91]{$else}array[0..91] of AnsiChar{$endif}; string92 = {$ifdef SHORTSTRSUPPORT}string[92]{$else}array[0..92] of AnsiChar{$endif}; string93 = {$ifdef SHORTSTRSUPPORT}string[93]{$else}array[0..93] of AnsiChar{$endif}; string94 = {$ifdef SHORTSTRSUPPORT}string[94]{$else}array[0..94] of AnsiChar{$endif}; string95 = {$ifdef SHORTSTRSUPPORT}string[95]{$else}array[0..95] of AnsiChar{$endif}; string96 = {$ifdef SHORTSTRSUPPORT}string[96]{$else}array[0..96] of AnsiChar{$endif}; string97 = {$ifdef SHORTSTRSUPPORT}string[97]{$else}array[0..97] of AnsiChar{$endif}; string98 = {$ifdef SHORTSTRSUPPORT}string[98]{$else}array[0..98] of AnsiChar{$endif}; string99 = {$ifdef SHORTSTRSUPPORT}string[99]{$else}array[0..99] of AnsiChar{$endif}; string100 = {$ifdef SHORTSTRSUPPORT}string[100]{$else}array[0..100] of AnsiChar{$endif}; string101 = {$ifdef SHORTSTRSUPPORT}string[101]{$else}array[0..101] of AnsiChar{$endif}; string102 = {$ifdef SHORTSTRSUPPORT}string[102]{$else}array[0..102] of AnsiChar{$endif}; string103 = {$ifdef SHORTSTRSUPPORT}string[103]{$else}array[0..103] of AnsiChar{$endif}; string104 = {$ifdef SHORTSTRSUPPORT}string[104]{$else}array[0..104] of AnsiChar{$endif}; string105 = {$ifdef SHORTSTRSUPPORT}string[105]{$else}array[0..105] of AnsiChar{$endif}; string106 = {$ifdef SHORTSTRSUPPORT}string[106]{$else}array[0..106] of AnsiChar{$endif}; string107 = {$ifdef SHORTSTRSUPPORT}string[107]{$else}array[0..107] of AnsiChar{$endif}; string108 = {$ifdef SHORTSTRSUPPORT}string[108]{$else}array[0..108] of AnsiChar{$endif}; string109 = {$ifdef SHORTSTRSUPPORT}string[109]{$else}array[0..109] of AnsiChar{$endif}; string110 = {$ifdef SHORTSTRSUPPORT}string[110]{$else}array[0..110] of AnsiChar{$endif}; string111 = {$ifdef SHORTSTRSUPPORT}string[111]{$else}array[0..111] of AnsiChar{$endif}; string112 = {$ifdef SHORTSTRSUPPORT}string[112]{$else}array[0..112] of AnsiChar{$endif}; string113 = {$ifdef SHORTSTRSUPPORT}string[113]{$else}array[0..113] of AnsiChar{$endif}; string114 = {$ifdef SHORTSTRSUPPORT}string[114]{$else}array[0..114] of AnsiChar{$endif}; string115 = {$ifdef SHORTSTRSUPPORT}string[115]{$else}array[0..115] of AnsiChar{$endif}; string116 = {$ifdef SHORTSTRSUPPORT}string[116]{$else}array[0..116] of AnsiChar{$endif}; string117 = {$ifdef SHORTSTRSUPPORT}string[117]{$else}array[0..117] of AnsiChar{$endif}; string118 = {$ifdef SHORTSTRSUPPORT}string[118]{$else}array[0..118] of AnsiChar{$endif}; string119 = {$ifdef SHORTSTRSUPPORT}string[119]{$else}array[0..119] of AnsiChar{$endif}; string120 = {$ifdef SHORTSTRSUPPORT}string[120]{$else}array[0..120] of AnsiChar{$endif}; string121 = {$ifdef SHORTSTRSUPPORT}string[121]{$else}array[0..121] of AnsiChar{$endif}; string122 = {$ifdef SHORTSTRSUPPORT}string[122]{$else}array[0..122] of AnsiChar{$endif}; string123 = {$ifdef SHORTSTRSUPPORT}string[123]{$else}array[0..123] of AnsiChar{$endif}; string124 = {$ifdef SHORTSTRSUPPORT}string[124]{$else}array[0..124] of AnsiChar{$endif}; string125 = {$ifdef SHORTSTRSUPPORT}string[125]{$else}array[0..125] of AnsiChar{$endif}; string126 = {$ifdef SHORTSTRSUPPORT}string[126]{$else}array[0..126] of AnsiChar{$endif}; string127 = {$ifdef SHORTSTRSUPPORT}string[127]{$else}array[0..127] of AnsiChar{$endif}; string128 = {$ifdef SHORTSTRSUPPORT}string[128]{$else}array[0..128] of AnsiChar{$endif}; string129 = {$ifdef SHORTSTRSUPPORT}string[129]{$else}array[0..129] of AnsiChar{$endif}; string130 = {$ifdef SHORTSTRSUPPORT}string[130]{$else}array[0..130] of AnsiChar{$endif}; string131 = {$ifdef SHORTSTRSUPPORT}string[131]{$else}array[0..131] of AnsiChar{$endif}; string132 = {$ifdef SHORTSTRSUPPORT}string[132]{$else}array[0..132] of AnsiChar{$endif}; string133 = {$ifdef SHORTSTRSUPPORT}string[133]{$else}array[0..133] of AnsiChar{$endif}; string134 = {$ifdef SHORTSTRSUPPORT}string[134]{$else}array[0..134] of AnsiChar{$endif}; string135 = {$ifdef SHORTSTRSUPPORT}string[135]{$else}array[0..135] of AnsiChar{$endif}; string136 = {$ifdef SHORTSTRSUPPORT}string[136]{$else}array[0..136] of AnsiChar{$endif}; string137 = {$ifdef SHORTSTRSUPPORT}string[137]{$else}array[0..137] of AnsiChar{$endif}; string138 = {$ifdef SHORTSTRSUPPORT}string[138]{$else}array[0..138] of AnsiChar{$endif}; string139 = {$ifdef SHORTSTRSUPPORT}string[139]{$else}array[0..139] of AnsiChar{$endif}; string140 = {$ifdef SHORTSTRSUPPORT}string[140]{$else}array[0..140] of AnsiChar{$endif}; string141 = {$ifdef SHORTSTRSUPPORT}string[141]{$else}array[0..141] of AnsiChar{$endif}; string142 = {$ifdef SHORTSTRSUPPORT}string[142]{$else}array[0..142] of AnsiChar{$endif}; string143 = {$ifdef SHORTSTRSUPPORT}string[143]{$else}array[0..143] of AnsiChar{$endif}; string144 = {$ifdef SHORTSTRSUPPORT}string[144]{$else}array[0..144] of AnsiChar{$endif}; string145 = {$ifdef SHORTSTRSUPPORT}string[145]{$else}array[0..145] of AnsiChar{$endif}; string146 = {$ifdef SHORTSTRSUPPORT}string[146]{$else}array[0..146] of AnsiChar{$endif}; string147 = {$ifdef SHORTSTRSUPPORT}string[147]{$else}array[0..147] of AnsiChar{$endif}; string148 = {$ifdef SHORTSTRSUPPORT}string[148]{$else}array[0..148] of AnsiChar{$endif}; string149 = {$ifdef SHORTSTRSUPPORT}string[149]{$else}array[0..149] of AnsiChar{$endif}; string150 = {$ifdef SHORTSTRSUPPORT}string[150]{$else}array[0..150] of AnsiChar{$endif}; string151 = {$ifdef SHORTSTRSUPPORT}string[151]{$else}array[0..151] of AnsiChar{$endif}; string152 = {$ifdef SHORTSTRSUPPORT}string[152]{$else}array[0..152] of AnsiChar{$endif}; string153 = {$ifdef SHORTSTRSUPPORT}string[153]{$else}array[0..153] of AnsiChar{$endif}; string154 = {$ifdef SHORTSTRSUPPORT}string[154]{$else}array[0..154] of AnsiChar{$endif}; string155 = {$ifdef SHORTSTRSUPPORT}string[155]{$else}array[0..155] of AnsiChar{$endif}; string156 = {$ifdef SHORTSTRSUPPORT}string[156]{$else}array[0..156] of AnsiChar{$endif}; string157 = {$ifdef SHORTSTRSUPPORT}string[157]{$else}array[0..157] of AnsiChar{$endif}; string158 = {$ifdef SHORTSTRSUPPORT}string[158]{$else}array[0..158] of AnsiChar{$endif}; string159 = {$ifdef SHORTSTRSUPPORT}string[159]{$else}array[0..159] of AnsiChar{$endif}; string160 = {$ifdef SHORTSTRSUPPORT}string[160]{$else}array[0..160] of AnsiChar{$endif}; string161 = {$ifdef SHORTSTRSUPPORT}string[161]{$else}array[0..161] of AnsiChar{$endif}; string162 = {$ifdef SHORTSTRSUPPORT}string[162]{$else}array[0..162] of AnsiChar{$endif}; string163 = {$ifdef SHORTSTRSUPPORT}string[163]{$else}array[0..163] of AnsiChar{$endif}; string164 = {$ifdef SHORTSTRSUPPORT}string[164]{$else}array[0..164] of AnsiChar{$endif}; string165 = {$ifdef SHORTSTRSUPPORT}string[165]{$else}array[0..165] of AnsiChar{$endif}; string166 = {$ifdef SHORTSTRSUPPORT}string[166]{$else}array[0..166] of AnsiChar{$endif}; string167 = {$ifdef SHORTSTRSUPPORT}string[167]{$else}array[0..167] of AnsiChar{$endif}; string168 = {$ifdef SHORTSTRSUPPORT}string[168]{$else}array[0..168] of AnsiChar{$endif}; string169 = {$ifdef SHORTSTRSUPPORT}string[169]{$else}array[0..169] of AnsiChar{$endif}; string170 = {$ifdef SHORTSTRSUPPORT}string[170]{$else}array[0..170] of AnsiChar{$endif}; string171 = {$ifdef SHORTSTRSUPPORT}string[171]{$else}array[0..171] of AnsiChar{$endif}; string172 = {$ifdef SHORTSTRSUPPORT}string[172]{$else}array[0..172] of AnsiChar{$endif}; string173 = {$ifdef SHORTSTRSUPPORT}string[173]{$else}array[0..173] of AnsiChar{$endif}; string174 = {$ifdef SHORTSTRSUPPORT}string[174]{$else}array[0..174] of AnsiChar{$endif}; string175 = {$ifdef SHORTSTRSUPPORT}string[175]{$else}array[0..175] of AnsiChar{$endif}; string176 = {$ifdef SHORTSTRSUPPORT}string[176]{$else}array[0..176] of AnsiChar{$endif}; string177 = {$ifdef SHORTSTRSUPPORT}string[177]{$else}array[0..177] of AnsiChar{$endif}; string178 = {$ifdef SHORTSTRSUPPORT}string[178]{$else}array[0..178] of AnsiChar{$endif}; string179 = {$ifdef SHORTSTRSUPPORT}string[179]{$else}array[0..179] of AnsiChar{$endif}; string180 = {$ifdef SHORTSTRSUPPORT}string[180]{$else}array[0..180] of AnsiChar{$endif}; string181 = {$ifdef SHORTSTRSUPPORT}string[181]{$else}array[0..181] of AnsiChar{$endif}; string182 = {$ifdef SHORTSTRSUPPORT}string[182]{$else}array[0..182] of AnsiChar{$endif}; string183 = {$ifdef SHORTSTRSUPPORT}string[183]{$else}array[0..183] of AnsiChar{$endif}; string184 = {$ifdef SHORTSTRSUPPORT}string[184]{$else}array[0..184] of AnsiChar{$endif}; string185 = {$ifdef SHORTSTRSUPPORT}string[185]{$else}array[0..185] of AnsiChar{$endif}; string186 = {$ifdef SHORTSTRSUPPORT}string[186]{$else}array[0..186] of AnsiChar{$endif}; string187 = {$ifdef SHORTSTRSUPPORT}string[187]{$else}array[0..187] of AnsiChar{$endif}; string188 = {$ifdef SHORTSTRSUPPORT}string[188]{$else}array[0..188] of AnsiChar{$endif}; string189 = {$ifdef SHORTSTRSUPPORT}string[189]{$else}array[0..189] of AnsiChar{$endif}; string190 = {$ifdef SHORTSTRSUPPORT}string[190]{$else}array[0..190] of AnsiChar{$endif}; string191 = {$ifdef SHORTSTRSUPPORT}string[191]{$else}array[0..191] of AnsiChar{$endif}; string192 = {$ifdef SHORTSTRSUPPORT}string[192]{$else}array[0..192] of AnsiChar{$endif}; string193 = {$ifdef SHORTSTRSUPPORT}string[193]{$else}array[0..193] of AnsiChar{$endif}; string194 = {$ifdef SHORTSTRSUPPORT}string[194]{$else}array[0..194] of AnsiChar{$endif}; string195 = {$ifdef SHORTSTRSUPPORT}string[195]{$else}array[0..195] of AnsiChar{$endif}; string196 = {$ifdef SHORTSTRSUPPORT}string[196]{$else}array[0..196] of AnsiChar{$endif}; string197 = {$ifdef SHORTSTRSUPPORT}string[197]{$else}array[0..197] of AnsiChar{$endif}; string198 = {$ifdef SHORTSTRSUPPORT}string[198]{$else}array[0..198] of AnsiChar{$endif}; string199 = {$ifdef SHORTSTRSUPPORT}string[199]{$else}array[0..199] of AnsiChar{$endif}; string200 = {$ifdef SHORTSTRSUPPORT}string[200]{$else}array[0..200] of AnsiChar{$endif}; string201 = {$ifdef SHORTSTRSUPPORT}string[201]{$else}array[0..201] of AnsiChar{$endif}; string202 = {$ifdef SHORTSTRSUPPORT}string[202]{$else}array[0..202] of AnsiChar{$endif}; string203 = {$ifdef SHORTSTRSUPPORT}string[203]{$else}array[0..203] of AnsiChar{$endif}; string204 = {$ifdef SHORTSTRSUPPORT}string[204]{$else}array[0..204] of AnsiChar{$endif}; string205 = {$ifdef SHORTSTRSUPPORT}string[205]{$else}array[0..205] of AnsiChar{$endif}; string206 = {$ifdef SHORTSTRSUPPORT}string[206]{$else}array[0..206] of AnsiChar{$endif}; string207 = {$ifdef SHORTSTRSUPPORT}string[207]{$else}array[0..207] of AnsiChar{$endif}; string208 = {$ifdef SHORTSTRSUPPORT}string[208]{$else}array[0..208] of AnsiChar{$endif}; string209 = {$ifdef SHORTSTRSUPPORT}string[209]{$else}array[0..209] of AnsiChar{$endif}; string210 = {$ifdef SHORTSTRSUPPORT}string[210]{$else}array[0..210] of AnsiChar{$endif}; string211 = {$ifdef SHORTSTRSUPPORT}string[211]{$else}array[0..211] of AnsiChar{$endif}; string212 = {$ifdef SHORTSTRSUPPORT}string[212]{$else}array[0..212] of AnsiChar{$endif}; string213 = {$ifdef SHORTSTRSUPPORT}string[213]{$else}array[0..213] of AnsiChar{$endif}; string214 = {$ifdef SHORTSTRSUPPORT}string[214]{$else}array[0..214] of AnsiChar{$endif}; string215 = {$ifdef SHORTSTRSUPPORT}string[215]{$else}array[0..215] of AnsiChar{$endif}; string216 = {$ifdef SHORTSTRSUPPORT}string[216]{$else}array[0..216] of AnsiChar{$endif}; string217 = {$ifdef SHORTSTRSUPPORT}string[217]{$else}array[0..217] of AnsiChar{$endif}; string218 = {$ifdef SHORTSTRSUPPORT}string[218]{$else}array[0..218] of AnsiChar{$endif}; string219 = {$ifdef SHORTSTRSUPPORT}string[219]{$else}array[0..219] of AnsiChar{$endif}; string220 = {$ifdef SHORTSTRSUPPORT}string[220]{$else}array[0..220] of AnsiChar{$endif}; string221 = {$ifdef SHORTSTRSUPPORT}string[221]{$else}array[0..221] of AnsiChar{$endif}; string222 = {$ifdef SHORTSTRSUPPORT}string[222]{$else}array[0..222] of AnsiChar{$endif}; string223 = {$ifdef SHORTSTRSUPPORT}string[223]{$else}array[0..223] of AnsiChar{$endif}; string224 = {$ifdef SHORTSTRSUPPORT}string[224]{$else}array[0..224] of AnsiChar{$endif}; string225 = {$ifdef SHORTSTRSUPPORT}string[225]{$else}array[0..225] of AnsiChar{$endif}; string226 = {$ifdef SHORTSTRSUPPORT}string[226]{$else}array[0..226] of AnsiChar{$endif}; string227 = {$ifdef SHORTSTRSUPPORT}string[227]{$else}array[0..227] of AnsiChar{$endif}; string228 = {$ifdef SHORTSTRSUPPORT}string[228]{$else}array[0..228] of AnsiChar{$endif}; string229 = {$ifdef SHORTSTRSUPPORT}string[229]{$else}array[0..229] of AnsiChar{$endif}; string230 = {$ifdef SHORTSTRSUPPORT}string[230]{$else}array[0..230] of AnsiChar{$endif}; string231 = {$ifdef SHORTSTRSUPPORT}string[231]{$else}array[0..231] of AnsiChar{$endif}; string232 = {$ifdef SHORTSTRSUPPORT}string[232]{$else}array[0..232] of AnsiChar{$endif}; string233 = {$ifdef SHORTSTRSUPPORT}string[233]{$else}array[0..233] of AnsiChar{$endif}; string234 = {$ifdef SHORTSTRSUPPORT}string[234]{$else}array[0..234] of AnsiChar{$endif}; string235 = {$ifdef SHORTSTRSUPPORT}string[235]{$else}array[0..235] of AnsiChar{$endif}; string236 = {$ifdef SHORTSTRSUPPORT}string[236]{$else}array[0..236] of AnsiChar{$endif}; string237 = {$ifdef SHORTSTRSUPPORT}string[237]{$else}array[0..237] of AnsiChar{$endif}; string238 = {$ifdef SHORTSTRSUPPORT}string[238]{$else}array[0..238] of AnsiChar{$endif}; string239 = {$ifdef SHORTSTRSUPPORT}string[239]{$else}array[0..239] of AnsiChar{$endif}; string240 = {$ifdef SHORTSTRSUPPORT}string[240]{$else}array[0..240] of AnsiChar{$endif}; string241 = {$ifdef SHORTSTRSUPPORT}string[241]{$else}array[0..241] of AnsiChar{$endif}; string242 = {$ifdef SHORTSTRSUPPORT}string[242]{$else}array[0..242] of AnsiChar{$endif}; string243 = {$ifdef SHORTSTRSUPPORT}string[243]{$else}array[0..243] of AnsiChar{$endif}; string244 = {$ifdef SHORTSTRSUPPORT}string[244]{$else}array[0..244] of AnsiChar{$endif}; string245 = {$ifdef SHORTSTRSUPPORT}string[245]{$else}array[0..245] of AnsiChar{$endif}; string246 = {$ifdef SHORTSTRSUPPORT}string[246]{$else}array[0..246] of AnsiChar{$endif}; string247 = {$ifdef SHORTSTRSUPPORT}string[247]{$else}array[0..247] of AnsiChar{$endif}; string248 = {$ifdef SHORTSTRSUPPORT}string[248]{$else}array[0..248] of AnsiChar{$endif}; string249 = {$ifdef SHORTSTRSUPPORT}string[249]{$else}array[0..249] of AnsiChar{$endif}; string250 = {$ifdef SHORTSTRSUPPORT}string[250]{$else}array[0..250] of AnsiChar{$endif}; string251 = {$ifdef SHORTSTRSUPPORT}string[251]{$else}array[0..251] of AnsiChar{$endif}; string252 = {$ifdef SHORTSTRSUPPORT}string[252]{$else}array[0..252] of AnsiChar{$endif}; string253 = {$ifdef SHORTSTRSUPPORT}string[253]{$else}array[0..253] of AnsiChar{$endif}; string254 = {$ifdef SHORTSTRSUPPORT}string[254]{$else}array[0..254] of AnsiChar{$endif}; string255 = {$ifdef SHORTSTRSUPPORT}string[255]{$else}array[0..255] of AnsiChar{$endif}; { Universal timestamp format Recommendation: The number of 100-nanosecond intervals since January 1, 1601 UTC (Windows FILETIME format) } TimeStamp = type Int64; PTimeStamp = ^TimeStamp; { References (interfaces, objects, methods) } PReference = ^TReference; TReference = (rfDefault, rfWeak, rfUnsafe); PReferences = ^TReferences; TReferences = set of TReference; type { Internal RTTI enumerations } PTypeKind = ^TTypeKind; {$if Defined(FPC)} TTypeKind = (tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat, tkSet, tkMethod, tkSString, tkLString, tkAString, tkWString, tkVariant, tkArray, tkRecord, tkInterface, tkClass, tkObject, tkWChar, tkBool, tkInt64, tkQWord, tkDynArray, tkInterfaceRaw, tkProcVar, tkUString, tkUChar, tkHelper, tkFile, tkClassRef, tkPointer); {$elseif (CompilerVersion >= 28)} TTypeKind = System.TTypeKind; {$else} TTypeKind = (tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat, tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString, tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray {$ifdef UNICODE} , tkUString {$endif} {$ifdef EXTENDEDRTTI} , tkClassRef, tkPointer, tkProcedure {$endif} {$ifdef MANAGEDRECORDS} , tkMRecord {$endif}); {$ifend} PTypeKinds = ^TTypeKinds; TTypeKinds = set of TTypeKind; POrdType = ^TOrdType; TOrdType = (otSByte, otUByte, otSWord, otUWord, otSLong, otULong); PFloatType = ^TFloatType; TFloatType = (ftSingle, ftDouble, ftExtended, ftComp, ftCurr); PFloatTypes = ^TFloatTypes; TFloatTypes = set of TFloatType; PMethodKind = ^TMethodKind; TMethodKind = (mkProcedure, mkFunction, mkConstructor, mkDestructor, mkClassProcedure, mkClassFunction {$if Defined(FPC) or (CompilerVersion >= 21)} , mkClassConstructor, mkClassDestructor, mkOperatorOverload {$ifend} {$ifNdef FPC} , mkSafeProcedure, mkSafeFunction {$endif} ); PMethodKinds = ^TMethodKinds; TMethodKinds = set of TMethodKind; PParamFlag = ^TParamFlag; TParamFlag = (pfVar, pfConst, pfArray, pfAddress, pfReference, pfOut{$ifdef EXTENDEDRTTI}, pfResult{$endif}); PParamFlags = ^TParamFlags; TParamFlags = set of TParamFlag; PIntfFlag = ^TIntfFlag; TIntfFlag = (ifHasGuid, ifDispInterface, ifDispatch{$ifdef FPC}, ifHasStrGUID{$endif}); PIntfFlags = ^TIntfFlags; TIntfFlags = set of TIntfFlag; PMemberVisibility = ^TMemberVisibility; TMemberVisibility = (mvPrivate, mvProtected, mvPublic, mvPublished); PMemberVisibilities = ^TMemberVisibilities; TMemberVisibilities = set of TMemberVisibility; PCallConv = ^TCallConv; TCallConv = (ccReg, ccCdecl, ccPascal, ccStdCall, ccSafeCall {$ifdef FPC} , ccCppdecl, ccFar16, ccOldFPCCall, ccInternProc, ccSysCall, ccSoftFloat, ccMWPascal {$endif} ); PCallConvs = ^TCallConvs; TCallConvs = set of TCallConv; { Internal RTTI attribute routine } type {$ifdef EXTENDEDRTTI} PAttrData = ^TAttrData; PVmtMethodSignature = ^TVmtMethodSignature; PAttrEntryReader = ^TAttrEntryReader; TAttrEntryReader = packed object protected function RangeError: Pointer; function GetEOF: Boolean; function GetMargin: NativeUInt; public Current: PByte; Overflow: PByte; procedure ReadData(var ABuffer; const ASize: NativeUInt); {$ifdef INLINESUPPORT}inline;{$endif} function Reserve(const ASize: NativeUInt): Pointer; {$ifdef INLINESUPPORT}inline;{$endif} function ReadBoolean: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} function ReadAnsiChar: AnsiChar; {$ifdef INLINESUPPORT}inline;{$endif} function ReadWideChar: WideChar; {$ifdef INLINESUPPORT}inline;{$endif} function ReadUCS4Char: UCS4Char; {$ifdef INLINESUPPORT}inline;{$endif} function ReadShortInt: ShortInt; {$ifdef INLINESUPPORT}inline;{$endif} function ReadByte: Byte; {$ifdef INLINESUPPORT}inline;{$endif} function ReadSmallInt: SmallInt; {$ifdef INLINESUPPORT}inline;{$endif} function ReadWord: Word; {$ifdef INLINESUPPORT}inline;{$endif} function ReadInteger: Integer; {$ifdef INLINESUPPORT}inline;{$endif} function ReadCardinal: Cardinal; {$ifdef INLINESUPPORT}inline;{$endif} function ReadInt64: Int64; {$ifdef INLINESUPPORT}inline;{$endif} function ReadUInt64: UInt64; {$ifdef INLINESUPPORT}inline;{$endif} function ReadSingle: Single; {$ifdef INLINESUPPORT}inline;{$endif} function ReadDouble: Double; {$ifdef INLINESUPPORT}inline;{$endif} function ReadExtended: Extended; {$ifdef INLINESUPPORT}inline;{$endif} function ReadComp: Comp; {$ifdef INLINESUPPORT}inline;{$endif} function ReadCurrency: Currency; {$ifdef INLINESUPPORT}inline;{$endif} function ReadDateTime: TDateTime; {$ifdef INLINESUPPORT}inline;{$endif} function ReadPointer: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} function ReadTypeInfo: Pointer{PTypeInfo}; {$ifdef INLINESUPPORT}inline;{$endif} function ReadClass: TClass; function ReadShortString: ShortString; function ReadUTF8String: UTF8String; function ReadString: string; property EOF: Boolean read GetEOF; property Margin: NativeUInt read GetMargin; end; PAttrEntry = ^TAttrEntry; TAttrEntry = packed object protected function GetClassType: TClass; {$ifdef INLINESUPPORT}inline;{$endif} function GetConstructorSignature: PVmtMethodSignature; function GetReader: TAttrEntryReader; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public AttrType: Pointer{PTypeInfoRef}; AttrCtor: Pointer; ArgLen: Word; ArgData: array[1..65536 {ArgLen - 2}] of Byte; property Size: Word read ArgLen; property ClassType: TClass read GetClassType; property ConstructorAddress: Pointer read AttrCtor; property ConstructorSignature: PVmtMethodSignature read GetConstructorSignature; property Reader: TAttrEntryReader read GetReader; property Tail: Pointer read GetTail; end; TAttrData = packed object protected function GetValue: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} function GetCount: Integer; function GetReference: TReference; {$if Defined(INLINESUPPORT) and not Defined(WEAKREF)}inline;{$ifend} public Len: Word; Entries: TAttrEntry; {Entries: array[] of TAttrEntry} property Value: PAttrData read GetValue; property Tail: Pointer read GetTail; property Count: Integer read GetCount; property Reference: TReference read GetReference; end; {$endif .EXTENDEDRTTI} { Internal RTTI structures } PTypeData = ^TTypeData; PPTypeInfo = ^PTypeInfo; PTypeInfo = ^TTypeInfo; TTypeInfo = packed object protected function GetTypeData: PTypeData; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetAttrData: PAttrData; {$endif} public Kind: TTypeKind; Name: ShortStringHelper; property TypeData: PTypeData read GetTypeData; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; PPTypeInfoRef = ^PTypeInfoRef; PTypeInfoRef = {$ifdef INLINESUPPORT}packed object{$else}class{$endif} protected {$ifdef INLINESUPPORT} F: packed record case Integer of 0: (Value: {$ifdef FPC}PTypeInfo{$else .DELPHI}PPTypeInfo{$endif}); 1: (Address: Pointer); end; {$else} function GetAddress: Pointer; {$endif} function GetAssigned: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef FPC} public property Value: PTypeInfo read F.Value; {$else .DELPHI} function GetValue: PTypeInfo; {$ifdef INLINESUPPORT}inline;{$endif} public property Value: PTypeInfo read GetValue; {$endif} property Address: Pointer read {$ifdef INLINESUPPORT}F.Address{$else}GetAddress{$endif}; property Assigned: Boolean read GetAssigned; end; PParamData = ^TParamData; TParamData = packed object Name: PShortStringHelper; TypeInfo: PTypeInfo; TypeName: PShortStringHelper; end; PReferencedParamData = ^TReferencedParamData; TReferencedParamData = packed object(TParamData) Reference: TReference; end; PArgumentData = ^TArgumentData; TArgumentData = packed object(TParamData) Flags: TParamFlags; end; PResultData = ^TResultData; TResultData = packed object(TReferencedParamData) protected function GetAssigned: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} public property Assigned: Boolean read GetAssigned; end; PFieldData = ^TFieldData; TFieldData = packed object(TReferencedParamData) Visibility: TMemberVisibility; {$ifdef EXTENDEDRTTI} AttrData: PAttrData; {$endif} Offset: Cardinal; end; PPropInfo = ^TPropInfo; TPropInfo = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public PropType: PTypeInfoRef; GetProc: Pointer; SetProc: Pointer; StoredProc: Pointer; Index: Integer; Default: Integer; NameIndex: SmallInt; Name: ShortStringHelper; property Tail: Pointer read GetTail; end; PPropData = ^TPropData; TPropData = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public PropCount: Word; PropList: array[Word] of TPropInfo; property Tail: Pointer read GetTail; end; TPropInfoProc = procedure(PropInfo: PPropInfo) of object; PPropList = ^TPropList; TPropList = array[0..16379] of PPropInfo; PManagedField = ^TManagedField; TManagedField = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public TypeRef: PTypeInfoRef; FldOffset: NativeInt; property Tail:Pointer read GetTail; end; PVmtFieldClassTab = ^TVmtFieldClassTab; TVmtFieldClassTab = packed object public Count: Word; ClassRef: array[Word] of ^TClass; end; PVmtFieldEntry = ^TVmtFieldEntry; TVmtFieldEntry = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public FieldOffset: Cardinal; TypeIndex: Word; // index into ClassTab Name: ShortStringHelper; property Tail: Pointer read GetTail; end; PVmtFieldTable = ^TVmtFieldTable; TVmtFieldTable = packed object protected function GetTail: Pointer; public Count: Word; // Published fields ClassTab: PVmtFieldClassTab; Entries: TVmtFieldEntry; {Entries: array[1..Count] of TVmtFieldEntry; Tail: TVmtFieldTableEx;} property Tail: Pointer read GetTail; end; PVmtMethodEntry = ^TVmtMethodEntry; TVmtMethodEntry = packed object protected {$ifdef EXTENDEDRTTI} function GetSignature: PVmtMethodSignature; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Len: Word; CodeAddress: Pointer; Name: ShortStringHelper; {Signature: TVmtMethodSignature;} // only exists if Len indicates data here {$ifdef EXTENDEDRTTI} property Signature: PVmtMethodSignature read GetSignature; {$endif} property Tail: Pointer read GetTail; end; PVmtMethodTable = ^TVmtMethodTable; TVmtMethodTable = packed object protected function GetTail: Pointer; public Count: Word; Entries: TVmtMethodEntry; {Entries: array[1..Count] of TVmtMethodEntry; Tail: TVmtMethodTableEx;} property Tail: Pointer read GetTail; end; PIntfMethodParamTail = ^TIntfMethodParamTail; TIntfMethodParamTail = packed object protected {$ifdef EXTENDEDRTTI} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public ParamType: PTypeInfoRef; {$ifdef EXTENDEDRTTI} AttrDataRec: TAttrData; // not currently entered property AttrData: PAttrData read GetAttrData; {$endif} end; PIntfMethodParam = ^TIntfMethodParam; TIntfMethodParam = packed object protected function GetTypeName: PShortStringHelper; {$ifdef INLINESUPPORT}inline;{$endif} function GetParamTail: PIntfMethodParamTail; {$ifdef INLINESUPPORT}inline;{$endif} function GetParamType: PTypeInfo; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} function GetData: TArgumentData; function GetTail: Pointer; public Flags: TParamFlags; ParamName: ShortStringHelper; {TypeName: ShortStringHelper; ParamTail: TIntfMethodParamTail;} property TypeName: PShortStringHelper read GetTypeName; property ParamType: PTypeInfo read GetParamType; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} property Data: TArgumentData read GetData; property Tail: Pointer read GetTail; end; PIntfMethodSignature = ^TIntfMethodSignature; TIntfMethodSignature = packed object protected function GetParamsTail: PByte; function GetResultData: TResultData; {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Kind: Byte; // 0=proc or 1=func CC: TCallConv; ParamCount: Byte; Params: TIntfMethodParam; {Params: array[1..ParamCount] of TIntfMethodParam; ResultTypeName: ShortStringHelper; // only if func ResultType: PTypeInfoRef; // only if Len(Name) > 0 AttrData: TAttrData;} property ResultData: TResultData read GetResultData; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} property Tail: Pointer read GetTail; end; PIntfMethodEntryTail = ^TIntfMethodEntryTail; TIntfMethodEntryTail = packed object(TIntfMethodSignature) end; PIntfMethodEntry = ^TIntfMethodEntry; TIntfMethodEntry = packed object protected function GetSignature: PIntfMethodSignature; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Name: ShortStringHelper; {Signature: TIntfMethodSignature;} property Signature: PIntfMethodSignature read GetSignature; property Tail: Pointer read GetTail; end; PIntfMethodTable = ^TIntfMethodTable; TIntfMethodTable = packed object protected function GetHasEntries: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public Count: Word; // methods in this interface RttiCount: Word; // = Count, or $FFFF if no further data Entries: TIntfMethodEntry; {Entries: array[1..Count] of TIntfMethodEntry; AttrData: TAttrData;} property HasEntries: Boolean read GetHasEntries; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; {$if Defined(FPC) or Defined(EXTENDEDRTTI)} PProcedureParam = ^TProcedureParam; TProcedureParam = packed object protected {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} function GetData: TArgumentData; function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: TParamFlags; ParamType: PTypeInfoRef; Name: ShortStringHelper; {AttrData: TAttrData;} {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} property Data: TArgumentData read GetData; property Tail: Pointer read GetTail; end; PProcedureSignature = ^TProcedureSignature; TProcedureSignature = packed object protected function GetIsValid: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} function GetResultValue: TParamData; function GetTail: Pointer; public Flags: Byte; // if 255 then record stops here, with Flags CC: TCallConv; ResultType: PTypeInfoRef; ParamCount: Byte; Params: TProcedureParam; {Params: array[1..ParamCount] of TProcedureParam;} property IsValid: Boolean read GetIsValid; property ResultValue: TParamData read GetResultValue; property Tail: Pointer read GetTail; end; {$ifend .FPC.EXTENDEDRTTI} {$ifdef EXTENDEDRTTI} PPropInfoEx = ^TPropInfoEx; TPropInfoEx = packed object protected function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: Byte; Info: PPropInfo; AttrDataRec: TAttrData; property AttrData: PAttrData read GetAttrData; property Tail: Pointer read GetTail; end; PPropDataEx = ^TPropDataEx; TPropDataEx = packed object protected function GetTail: Pointer; public PropCount: Word; PropList: TPropInfoEx; {PropList: array[1..PropCount] of TPropInfoEx} property Tail: Pointer read GetTail; end; PArrayPropInfo = ^TArrayPropInfo; TArrayPropInfo = packed object protected function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: Byte; ReadIndex: Word; WriteIndex: Word; Name: ShortStringHelper; {AttrData: TAttrData;} property AttrData: PAttrData read GetAttrData; property Tail: Pointer read GetTail; end; PArrayPropData = ^TArrayPropData; TArrayPropData = packed object protected function GetTail: Pointer; public Count: Word; PropData: TArrayPropInfo; {PropData: array[1..Count] of TArrayPropInfo;} property Tail: Pointer read GetTail; end; PVmtFieldExEntry = ^TVmtFieldExEntry; TVmtFieldExEntry = packed object protected function GetVisibility: TMemberVisibility; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetValue: TFieldData; function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: Byte; TypeRef: PTypeInfoRef; Offset: Cardinal; Name: ShortStringHelper; {AttrData: TAttrData} property Visibility: TMemberVisibility read GetVisibility; property AttrData: PAttrData read GetAttrData; property Value: TFieldData read GetValue; property Tail: Pointer read GetTail; end; PFieldExEntry = ^TFieldExEntry; TFieldExEntry = packed object(TVmtFieldExEntry) end; PVmtFieldTableEx = ^TVmtFieldTableEx; TVmtFieldTableEx = packed object Count: Word; Entries: TVmtFieldExEntry; {Entries: array[1..Count] of TVmtFieldExEntry;} end; PVmtMethodParam = ^TVmtMethodParam; TVmtMethodParam = packed object protected function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetData: TArgumentData; function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: TParamFlags; ParamType: PTypeInfoRef; ParOff: Byte; // Parameter location: 0..2 for reg, >=8 for stack Name: ShortStringHelper; {AttrData: TAttrData;} property AttrData: PAttrData read GetAttrData; property Data: TArgumentData read GetData; property Tail: Pointer read GetTail; end; TVmtMethodSignature = packed object protected function GetAttrDataRec: PAttrData; function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetResultData: TResultData; public Version: Byte; // =3 CC: TCallConv; ResultType: PTypeInfoRef; // nil for procedures ParOff: Word; // total size of data needed for stack parameters + 8 (ret-addr + pushed EBP) ParamCount: Byte; Params: TVmtMethodParam; {Params: array[1..ParamCount] of TVmtMethodParam; AttrData: TAttrData;} property AttrData: PAttrData read GetAttrData; property ResultData: TResultData read GetResultData; end; PVmtMethodEntryTail = ^TVmtMethodEntryTail; TVmtMethodEntryTail = packed object(TVmtMethodSignature) end; PVmtMethodExEntry = ^TVmtMethodExEntry; TVmtMethodExEntry = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Entry: PVmtMethodEntry; Flags: Word; VirtualIndex: SmallInt; // signed word property Tail: Pointer read GetTail; end; PVmtMethodTableEx = ^TVmtMethodTableEx; TVmtMethodTableEx = packed object protected function GetVirtualCount: Word; {$ifdef INLINESUPPORT}inline;{$endif} public Count: Word; Entries: array[Word] of TVmtMethodExEntry; {VirtualCount: Word;} property VirtualCount: Word read GetVirtualCount; end; PRecordTypeOptions = ^TRecordTypeOptions; TRecordTypeOptions = packed object protected function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Count: Byte; Values: array[Byte] of Pointer; property Tail: Pointer read GetTail; end; PRecordTypeField = ^TRecordTypeField; TRecordTypeField = packed object protected function GetVisibility: TMemberVisibility; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetFieldData: TFieldData; function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Field: TManagedField; Flags: Byte; Name: ShortStringHelper; {AttrData: TAttrData;} property Visibility: TMemberVisibility read GetVisibility; property AttrData: PAttrData read GetAttrData; property FieldData: TFieldData read GetFieldData; property Tail: Pointer read GetTail; end; PRecordTypeFields = ^TRecordTypeFields; TRecordTypeFields = packed object protected function GetTail: Pointer; public Count: Integer; Fields: TRecordTypeField; {Fields: array[1..Count] of TRecordTypeField;} property Tail: Pointer read GetTail; end; PRecordTypeMethod = ^TRecordTypeMethod; TRecordTypeMethod = packed object protected function GetSignature: PProcedureSignature; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: Byte; Code: Pointer; Name: ShortStringHelper; {Signature: TProcedureSignature; AttrData: TAttrData;} property Signature: PProcedureSignature read GetSignature; property AttrData: PAttrData read GetAttrData; property Tail: Pointer read GetTail; end; PRecordTypeMethods = ^TRecordTypeMethods; TRecordTypeMethods = packed object protected function GetTail: Pointer; public Count: Word; Methods: TRecordTypeMethod; {Methods: array[1..Count] of TRecordTypeMethod;} property Tail: Pointer read GetTail; end; {$endif .EXTENDEDRTTI} PEnumerationTypeData = ^TEnumerationTypeData; TEnumerationTypeData = packed object protected function GetCount: Integer; {$ifdef INLINESUPPORT}inline;{$endif} function GetEnumName(const AValue: Integer): PShortStringHelper; function GetEnumValue(const AName: ShortString): Integer; function GetUnitName: PShortStringHelper; {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public OrdType: TOrdType; MinValue: Integer; MaxValue: Integer; BaseType: PTypeInfoRef; NameList: ShortStringHelper; {EnumUnitName: ShortStringHelper; EnumAttrData: TAttrData;} property Count: Integer read GetCount; property EnumNames[const AValue: Integer]: PShortStringHelper read GetEnumName; property EnumValues[const AName: ShortString]: Integer read GetEnumValue; property UnitName: PShortStringHelper read GetUnitName; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; PMethodParam = ^TMethodParam; TMethodParam = packed object protected function GetTypeName: PShortStringHelper; {$ifdef INLINESUPPORT}inline;{$endif} function GetTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} public Flags: TParamFlags; ParamName: ShortStringHelper; {TypeName: ShortStringHelper;} property TypeName: PShortStringHelper read GetTypeName; property Tail: Pointer read GetTail; end; PMethodSignature = ^TMethodSignature; TMethodSignature = packed object protected function GetParamsTail: Pointer; function GetResultData: TResultData; function GetResultTail: Pointer; {$ifdef INLINESUPPORT}inline;{$endif} function GetCallConv: TCallConv; {$ifdef INLINESUPPORT}inline;{$endif} function GetParamTypes: PPTypeInfoRef; {$ifdef INLINESUPPORT}inline;{$endif} public MethodKind: TMethodKind; // only mkFunction or mkProcedure ParamCount: Byte; ParamList: TMethodParam; {ParamList: array[1..ParamCount] of TMethodParam; ResultType: ShortStringHelper; // only if MethodKind = mkFunction ResultTypeRef: PTypeInfoRef; // only if MethodKind = mkFunction CC: TCallConv; ParamTypeRefs: array[1..ParamCount] of PTypeInfoRef; // extended rtti MethSig: PProcedureSignature; MethAttrData: TAttrData;} property ResultData: TResultData read GetResultData; property CallConv: TCallConv read GetCallConv; property ParamTypes: PPTypeInfoRef read GetParamTypes; end; PMethodTypeData = ^TMethodTypeData; TMethodTypeData = packed object(TMethodSignature) {$ifdef EXTENDEDRTTI} protected function GetSignature: PProcedureSignature; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} public property Signature: PProcedureSignature read GetSignature; property AttrData: PAttrData read GetAttrData; {$endif} end; PClassTypeData = ^TClassTypeData; TClassTypeData = packed object protected function GetFieldTable: PVmtFieldTable; {$ifdef INLINESUPPORT}inline;{$endif} function GetMethodTable: PVmtMethodTable; {$ifdef INLINESUPPORT}inline;{$endif} function GetPropData: PPropData; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetFieldTableEx: PVmtFieldTableEx; {$ifdef INLINESUPPORT}inline;{$endif} function GetMethodTableEx: PVmtMethodTableEx; {$ifdef INLINESUPPORT}inline;{$endif} function GetPropDataEx: PPropDataEx; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetArrayPropData: PArrayPropData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public ClassType: TClass; ParentInfo: PTypeInfoRef; PropCount: SmallInt; UnitName: ShortStringHelper; {PropData: TPropData; // extended rtti PropDataEx: TPropDataEx; ClassAttrData: TAttrData; ArrayPropCount: Word; ArrayPropData: array[1..ArrayPropCount] of TArrayPropInfo;} property FieldTable: PVmtFieldTable read GetFieldTable; property MethodTable: PVmtMethodTable read GetMethodTable; property PropData: PPropData read GetPropData; {$ifdef EXTENDEDRTTI} property FieldTableEx: PVmtFieldTableEx read GetFieldTableEx; property MethodTableEx: PVmtMethodTableEx read GetMethodTableEx; property PropDataEx: PPropDataEx read GetPropDataEx; property AttrData: PAttrData read GetAttrData; property ArrayPropData: PArrayPropData read GetArrayPropData; {$endif} end; PInterfaceTypeData = ^TInterfaceTypeData; TInterfaceTypeData = packed object protected function GetMethodTable: PIntfMethodTable; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public Parent: PTypeInfoRef; { ancestor } Flags: TIntfFlags; Guid: TGUID; UnitName: ShortStringHelper; {IntfMethods: TIntfMethodTable; IntfAttrData: TAttrData;} property MethodTable: PIntfMethodTable read GetMethodTable; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; PDynArrayTypeData = ^TDynArrayTypeData; TDynArrayTypeData = packed object protected function GetArrElType: PTypeInfo; {$ifdef INLINESUPPORT}inline;{$endif} {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public {$ifdef FPC} elSize: NativeUInt; elType2: PTypeInfoRef; varType: Integer; elType: PTypeInfoRef; {$else .DELPHI} elSize: Integer; elType: PTypeInfoRef; // nil if type does not require cleanup varType: Integer; // Ole Automation varType equivalent elType2: PTypeInfoRef; // independent of cleanup {$endif} UnitName: ShortStringHelper; {DynArrElType: PTypeInfoRef; // actual element type, even if dynamic array DynArrAttrData: TAttrData;} property ArrElType: PTypeInfo read GetArrElType; {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; PArrayTypeData = ^TArrayTypeData; TArrayTypeData = packed object protected {$ifdef EXTENDEDRTTI} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public Size: Integer; ElCount: Integer; // product of lengths of all dimensions ElType: PTypeInfoRef; DimCount: Byte; Dims: array[0..255 {DimCount-1}] of PTypeInfoRef; {AttrData: TAttrData;} {$ifdef EXTENDEDRTTI} property AttrData: PAttrData read GetAttrData; {$endif} end; PRecordTypeData = ^TRecordTypeData; TRecordTypeData = packed object protected {$ifdef EXTENDEDRTTI} function GetOptions: PRecordTypeOptions; {$ifdef INLINESUPPORT}inline;{$endif} function GetFields: PRecordTypeFields; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrDataRec: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetAttrData: PAttrData; {$ifdef INLINESUPPORT}inline;{$endif} function GetMethods: PRecordTypeMethods; {$ifdef INLINESUPPORT}inline;{$endif} {$endif} public Size: Integer; ManagedFieldCount: Integer; ManagedFields: TManagedField; {ManagedFields: array[0..ManagedFldCnt - 1] of TManagedField; NumOps: Byte; RecOps: array[1..NumOps] of Pointer; RecFldCnt: Integer; RecFields: array[1..RecFldCnt] of TRecordTypeField; RecAttrData: TAttrData; RecMethCnt: Word; RecMeths: array[1..RecMethCnt] of TRecordTypeMethod;} {$ifdef EXTENDEDRTTI} property Options: PRecordTypeOptions read GetOptions; property Fields: PRecordTypeFields read GetFields; property AttrData: PAttrData read GetAttrData; property Methods: PRecordTypeMethods read GetMethods; {$endif} end; TTypeData = packed record case TTypeKind of tkUnknown: ( case TTypeKind of tkEnumeration: (EnumerationData: TEnumerationTypeData); tkMethod: ( case Integer of 0: (MethodSignature: TMethodSignature); 1: (MethodData: TMethodTypeData); 2: (_: packed record end); ); tkClass: (ClassData: TClassTypeData); tkInterface: (InterfaceData: TInterfaceTypeData); tkDynArray: (DynArrayData: TDynArrayTypeData); tkRecord: (RecordData: TRecordTypeData); tkUnknown: (__: packed record end); ); {$ifdef UNICODE} tkUString, {$endif} {$ifdef WIDESTRSUPPORT} tkWString, {$endif} tkVariant: ({$ifdef EXTENDEDRTTI}AttrData: TAttrData{$endif}); {$ifdef ANSISTRSUPPORT} tkLString: ( CodePage: Word; {$ifdef EXTENDEDRTTI}LStrAttrData: TAttrData{$endif}); {$endif} tkInteger, {$ifdef ANSISTRSUPPORT} tkChar, {$endif} tkEnumeration, {EnumerationData: TEnumerationTypeData;} tkSet, tkWChar: ( OrdType: TOrdType; case TTypeKind of tkInteger, tkChar, tkEnumeration, tkWChar: ( MinValue: Integer; MaxValue: Integer; case TTypeKind of tkInteger, tkChar, tkWChar: ( {$ifdef EXTENDEDRTTI}OrdAttrData: TAttrData;{$endif}); tkEnumeration: ( BaseType: PTypeInfoRef; NameList: ShortStringHelper; {EnumUnitName: ShortStringHelper; EnumAttrData: TAttrData;} ___: packed record end;)); tkSet: ( {$if (not Defined(FPC)) and (CompilerVersion >= 33)} SetTypeOrSize: Byte; {$ifend} CompType: PTypeInfoRef; {$ifdef EXTENDEDRTTI}SetAttrData: TAttrData;{$endif} ____: packed record end;)); tkFloat: ( FloatType: TFloatType; {$ifdef EXTENDEDRTTI}FloatAttrData: TAttrData;{$endif}); {$ifdef SHORTSTRSUPPORT} {$ifdef FPC}tkSString{$else}tkString{$endif}: ( MaxLength: Byte; {$ifdef EXTENDEDRTTI}StrAttrData: TAttrData{$endif}); {$endif} tkClass: ( {ClassData: TClassTypeData;} ClassType: TClass; // most data for instance types is in VMT offsets ParentInfo: PTypeInfoRef; PropCount: SmallInt; // total properties inc. ancestors UnitName: ShortStringHelper; {PropData: TPropData; // extended rtti PropDataEx: TPropDataEx; ClassAttrData: TAttrData; ArrayPropCount: Word; ArrayPropData: array[1..ArrayPropCount] of TArrayPropInfo;}); tkMethod: ( {MethodData: TMethodTypeData;} MethodKind: TMethodKind; // only mkFunction or mkProcedure ParamCount: Byte; ParamList: TMethodParam; {ParamList: array[1..ParamCount] of TMethodParam; ResultType: ShortStringHelper; // only if MethodKind = mkFunction ResultTypeRef: PTypeInfoRef; // only if MethodKind = mkFunction CC: TCallConv; ParamTypeRefs: array[1..ParamCount] of PTypeInfoRef; // extended rtti MethSig: PProcedureSignature; MethAttrData: TAttrData;}); tkInterface: ( {InterfaceData: TInterfaceTypeData;} IntfParent: PTypeInfoRef; { ancestor } IntfFlags: TIntfFlags; Guid: TGUID; IntfUnit: ShortStringHelper; {IntfMethods: TIntfMethodTable; IntfAttrData: TAttrData;}); tkInt64: ( MinInt64Value, MaxInt64Value: Int64; {$ifdef EXTENDEDRTTI}Int64AttrData: TAttrData;{$endif}); tkDynArray: ( {DynArrayData: TDynArrayTypeData;} {$ifdef FPC} elSize: NativeUInt; elType2: PTypeInfoRef; varType: Integer; elType: PTypeInfoRef; {$else .DELPHI} elSize: Integer; elType: PTypeInfoRef; // nil if type does not require cleanup varType: Integer; // Ole Automation varType equivalent elType2: PTypeInfoRef; // independent of cleanup {$endif} DynUnitName: ShortStringHelper; {DynArrElType: PTypeInfoRef; // actual element type, even if dynamic array DynArrAttrData: TAttrData;}); tkArray: ( ArrayData: TArrayTypeData; {ArrAttrData: TAttrData;}); tkRecord: ({RecordData: TRecordTypeData} RecSize: Integer; ManagedFldCount: Integer; ManagedFields: TManagedField; {ManagedField: array[0..ManagedFldCnt - 1] of TManagedField; NumOps: Byte; RecOps: array[1..NumOps] of Pointer; RecFldCnt: Integer; RecFields: array[1..RecFldCnt] of TRecordTypeField; RecAttrData: TAttrData; RecMethCnt: Word; RecMeths: array[1..RecMethCnt] of TRecordTypeMethod;}); {$ifdef EXTENDEDRTTI} tkClassRef: ( InstanceType: PTypeInfoRef; ClassRefAttrData: TAttrData;); tkPointer: ( RefType: PTypeInfoRef; PtrAttrData: TAttrData;); tkProcedure: ( ProcSig: PProcedureSignature; ProcAttrData: TAttrData;); {$endif} {$ifdef FPC} tkHelper: (HelperParent: PTypeInfo; ExtendedInfo: PTypeInfo; HelperProps: SmallInt; HelperUnit: ShortStringHelper; {here the properties follow as array of TPropInfo}); tkProcVar: (ProcSig: TProcedureSignature); tkQWord: (MinQWordValue, MaxQWordValue: QWord); tkInterfaceRaw: (RawIntfParent: PTypeInfoRef; RawIntfFlags: TIntfFlags; IID: TGUID; RawIntfUnit: ShortStringHelper; IIDStr: ShortStringHelper;); {$endif} end; { UniConv aliases More details: https://github.com/d-mozulyov/UniConv} {$ifdef UNICODE} var _utf8_equal_utf8_ignorecase: function(S1: PUTF8Char; L1: NativeUInt; S2: PUTF8Char; L2: NativeUInt): Boolean; {$endif} { Universal RTTI types } type PRttiHFA = ^TRttiHFA; TRttiHFA = (hfaNone, hfaSingle1, hfaDouble1, hfaSingle2, hfaDouble2, hfaSingle3, hfaDouble3, hfaSingle4, hfaDouble4); PRttiHFAs = ^TRttiHFAs; TRttiHFAs = set of TRttiHFA; PRttiCallConv = ^TRttiCallConv; TRttiCallConv = (rcRegister, rcCdecl, rcPascal, rcStdCall, rcSafeCall, // https://clang.llvm.org/docs/AttributeReference.html#calling-conventions rcVectorPCV, rcFastCall, rcWindows, rcPCV, rcPreserveAll, rcPreserveMost, rcRegisterAll, rcRegister1, rcRegister2, rcRegister3, {regparm(N)} rcThisCall, rcVectorCall ); PRttiCallConvs = ^TRttiCallConvs; TRttiCallConvs = set of TRttiCallConv; PRttiTypeGroup = ^TRttiTypeGroup; TRttiTypeGroup = ( {000} rgUnknown, {001} rgPointer, {002} rgBoolean, {003} rgOrdinal, {004} rgFloat, {005} rgDateTime, {006} rgString, {007} rgEnumeration, {008} rgMetaType, {009} rgMetaTypeRef, {000} rgVariant, {011} rgFunction, {012} rg012, {013} rg013, {014} rg014, {015} rg015, {016} rg016, {017} rg017, {018} rg018, {019} rg019, {020} rg020, {021} rg021, {022} rg022, {023} rg023, {024} rg024, {025} rg025, {026} rg026, {027} rg027, {028} rg028, {029} rg029, {030} rg030, {031} rg031, {032} rg032, {033} rg033, {034} rg034, {035} rg035, {036} rg036, {037} rg037, {038} rg038, {039} rg039, {040} rg040, {041} rg041, {042} rg042, {043} rg043, {044} rg044, {045} rg045, {046} rg046, {047} rg047, {048} rg048, {049} rg049, {050} rg050, {051} rg051, {052} rg052, {053} rg053, {054} rg054, {055} rg055, {056} rg056, {057} rg057, {058} rg058, {059} rg059, {060} rg060, {061} rg061, {062} rg062, {063} rg063, {064} rg064, {065} rg065, {066} rg066, {067} rg067, {068} rg068, {069} rg069, {070} rg070, {071} rg071, {072} rg072, {073} rg073, {074} rg074, {075} rg075, {076} rg076, {077} rg077, {078} rg078, {079} rg079, {080} rg080, {081} rg081, {082} rg082, {083} rg083, {084} rg084, {085} rg085, {086} rg086, {087} rg087, {088} rg088, {089} rg089, {090} rg090, {091} rg091, {092} rg092, {093} rg093, {094} rg094, {095} rg095, {096} rg096, {097} rg097, {098} rg098, {099} rg099, {100} rg100, {101} rg101, {102} rg102, {103} rg103, {104} rg104, {105} rg105, {106} rg106, {107} rg107, {108} rg108, {109} rg109, {110} rg110, {111} rg111, {112} rg112, {113} rg113, {114} rg114, {115} rg115, {116} rg116, {117} rg117, {118} rg118, {119} rg119, {120} rg120, {121} rg121, {122} rg122, {123} rg123, {124} rg124, {125} rg125, {126} rg126, {127} rg127, {128} rg128, {129} rg129, {130} rg130, {131} rg131, {132} rg132, {133} rg133, {134} rg134, {135} rg135, {136} rg136, {137} rg137, {138} rg138, {139} rg139, {140} rg140, {141} rg141, {142} rg142, {143} rg143, {144} rg144, {145} rg145, {146} rg146, {147} rg147, {148} rg148, {149} rg149, {150} rg150, {151} rg151, {152} rg152, {153} rg153, {154} rg154, {155} rg155, {156} rg156, {157} rg157, {158} rg158, {159} rg159, {160} rg160, {161} rg161, {162} rg162, {163} rg163, {164} rg164, {165} rg165, {166} rg166, {167} rg167, {168} rg168, {169} rg169, {170} rg170, {171} rg171, {172} rg172, {173} rg173, {174} rg174, {175} rg175, {176} rg176, {177} rg177, {178} rg178, {179} rg179, {180} rg180, {181} rg181, {182} rg182, {183} rg183, {184} rg184, {185} rg185, {186} rg186, {187} rg187, {188} rg188, {189} rg189, {190} rg190, {191} rg191, {192} rg192, {193} rg193, {194} rg194, {195} rg195, {196} rg196, {197} rg197, {198} rg198, {199} rg199, {200} rg200, {201} rg201, {202} rg202, {203} rg203, {204} rg204, {205} rg205, {206} rg206, {207} rg207, {208} rg208, {209} rg209, {210} rg210, {211} rg211, {212} rg212, {213} rg213, {214} rg214, {215} rg215, {216} rg216, {217} rg217, {218} rg218, {219} rg219, {220} rg220, {221} rg221, {222} rg222, {223} rg223, {224} rg224, {225} rg225, {226} rg226, {227} rg227, {228} rg228, {229} rg229, {230} rg230, {231} rg231, {232} rg232, {233} rg233, {234} rg234, {235} rg235, {236} rg236, {237} rg237, {238} rg238, {239} rg239, {240} rg240, {241} rg241, {242} rg242, {243} rg243, {244} rg244, {245} rg245, {246} rg246, {247} rg247, {248} rg248, {249} rg249, {250} rg250, {251} rg251, {252} rg252, {253} rg253, {254} rg254, {255} rg255); PRttiTypeGroups = ^TRttiTypeGroups; TRttiTypeGroups = set of TRttiTypeGroup; PRttiType = ^TRttiType; TRttiType = ( // rgUnknown {000} rtUnknown, // rgPointer {001} rtPointer, // rgBoolean {002} rtBoolean, {003} rtBoolean16, {004} rtBoolean32, {005} rtBoolean64, {006} rtByteBool, {007} rtWordBool, {008} rtLongBool, {009} rtQWordBool, // rgOrdinal {010} rtByte, {011} rtShortInt, {012} rtWord, {013} rtSmallInt, {014} rtCardinal, {015} rtInteger, {016} rtUInt64, {017} rtInt64, // rgFloat {018} rtComp, {019} rtCurrency, {020} rtSingle, {021} rtDouble, {022} rtExtended, // rgDateTime {023} rtDate, {024} rtTime, {025} rtDateTime, {026} rtTimeStamp, // rgString {027} rtSBCSChar, {028} rtUTF8Char, {029} rtWideChar, {020} rtShortString, {031} rtSBCSString, {032} rtUTF8String, {033} rtWideString, {034} rtUnicodeString, {035} rtUCS4String, // rgEnumeration {036} rtEnumeration, // rgMetaType {037} rtSet, {038} rtRecord, {039} rtStaticArray, {030} rtDynamicArray, {041} rtObject, {042} rtInterface, // rgMetaTypeRef {043} rtClassRef, // rgVariant {044} rtBytes, {045} rtVariant, {046} rtOleVariant, {047} rtVarRec, // rgFunction {048} rtFunction, {049} rtMethod, {050} rtClosure, // Reserved {051} rt051, {052} rt052, {053} rt053, {054} rt054, {055} rt055, {056} rt056, {057} rt057, {058} rt058, {059} rt059, {060} rt060, {061} rt061, {062} rt062, {063} rt063, {064} rt064, {065} rt065, {066} rt066, {067} rt067, {068} rt068, {069} rt069, {070} rt070, {071} rt071, {072} rt072, {073} rt073, {074} rt074, {075} rt075, {076} rt076, {077} rt077, {078} rt078, {079} rt079, {080} rt080, {081} rt081, {082} rt082, {083} rt083, {084} rt084, {085} rt085, {086} rt086, {087} rt087, {088} rt088, {089} rt089, {090} rt090, {091} rt091, {092} rt092, {093} rt093, {094} rt094, {095} rt095, {096} rt096, {097} rt097, {098} rt098, {099} rt099, {100} rt100, {101} rt101, {102} rt102, {103} rt103, {104} rt104, {105} rt105, {106} rt106, {107} rt107, {108} rt108, {109} rt109, {110} rt110, {111} rt111, {112} rt112, {113} rt113, {114} rt114, {115} rt115, {116} rt116, {117} rt117, {118} rt118, {119} rt119, {120} rt120, {121} rt121, {122} rt122, {123} rt123, {124} rt124, {125} rt125, {126} rt126, {127} rt127, {128} rt128, {129} rt129, {130} rt130, {131} rt131, {132} rt132, {133} rt133, {134} rt134, {135} rt135, {136} rt136, {137} rt137, {138} rt138, {139} rt139, {140} rt140, {141} rt141, {142} rt142, {143} rt143, {144} rt144, {145} rt145, {146} rt146, {147} rt147, {148} rt148, {149} rt149, {150} rt150, {151} rt151, {152} rt152, {153} rt153, {154} rt154, {155} rt155, {156} rt156, {157} rt157, {158} rt158, {159} rt159, {160} rt160, {161} rt161, {162} rt162, {163} rt163, {164} rt164, {165} rt165, {166} rt166, {167} rt167, {168} rt168, {169} rt169, {170} rt170, {171} rt171, {172} rt172, {173} rt173, {174} rt174, {175} rt175, {176} rt176, {177} rt177, {178} rt178, {179} rt179, {180} rt180, {181} rt181, {182} rt182, {183} rt183, {184} rt184, {185} rt185, {186} rt186, {187} rt187, {188} rt188, {189} rt189, {190} rt190, {191} rt191, {192} rt192, {193} rt193, {194} rt194, {195} rt195, {196} rt196, {197} rt197, {198} rt198, {199} rt199, {200} rt200, {201} rt201, {202} rt202, {203} rt203, {204} rt204, {205} rt205, {206} rt206, {207} rt207, {208} rt208, {209} rt209, {210} rt210, {211} rt211, {212} rt212, {213} rt213, {214} rt214, {215} rt215, {216} rt216, {217} rt217, {218} rt218, {219} rt219, {220} rt220, {221} rt221, {222} rt222, {223} rt223, {224} rt224, {225} rt225, {226} rt226, {227} rt227, {228} rt228, {229} rt229, {230} rt230, {231} rt231, {232} rt232, {233} rt233, {234} rt234, {235} rt235, {236} rt236, {237} rt237, {238} rt238, {239} rt239, {240} rt240, {241} rt241, {242} rt242, {243} rt243, {244} rt244, {245} rt245, {246} rt246, {247} rt247, {248} rt248, {249} rt249, {250} rt250, {251} rt251, {252} rt252, {253} rt253, {254} rt254, {255} rt255); PRttiTypes = ^TRttiTypes; TRttiTypes = set of TRttiType; PRttiRangeData = ^TRttiRangeData; TRttiRangeData = packed object protected F: packed record case Integer of 0: ( OrdType: TOrdType; case Integer of 0: (ILow, IHigh: Integer); 1: (ULow, UHigh: Cardinal); 2: (_: packed record end;); ); 1: (I64Low, I64High: Int64); 2: (U64Low, U64High: UInt64); end; function GetCount: Cardinal; {$ifdef INLINESUPPORT}inline;{$endif} function GetCount64: UInt64; {$ifdef INLINESUPPORT}inline;{$endif} public property ILow: Integer read F.ILow; property IHigh: Integer read F.IHigh; property ULow: Cardinal read F.ULow; property UHigh: Cardinal read F.UHigh; property I64Low: Int64 read F.I64Low; property I64High: Int64 read F.I64High; property U64Low: UInt64 read F.U64Low; property U64High: UInt64 read F.U64High; property Count: Cardinal read GetCount; property Count64: UInt64 read GetCount64; end; PRttiEnumerationData = ^TRttiEnumerationData; TRttiEnumerationData = packed object(TRttiRangeData) protected FBaseType: PTypeInfoRef; public NameList: ShortStringHelper; end; PRttiExTypeData = ^TRttiExTypeData; TRttiExTypeData = packed object // ToDo end; PRttiMetaType = ^TRttiMetaType; TRttiMetaType = packed object(TRttiExTypeData) // ToDo end; PRttiExType = ^TRttiExType; TRttiExType = packed object protected F: packed record case Integer of 0: ( Base: TRttiType; PtrDepth: Byte; case Integer of 0: (CodePage: Word); 1: (MaxLength: Byte; SBCSIndex: ShortInt); 2: (ChildType: TRttiType; Flags: Byte); 3: (ExFlags: Word); High(Integer): (_: packed record end;)); 1: ( Options: Cardinal; case Integer of 0: (Data: Pointer); 1: (TypeData: PTypeData); 2: (RangeData: PRttiRangeData); 3: (EnumerationData: PRttiEnumerationData); 4: (MetaType: PRttiMetaType); High(Integer): (__: packed record end;)); end; public property Base: TRttiType read F.Base write F.Base; property PtrDepth: Byte read F.PtrDepth write F.PtrDepth; property CodePage: Word read F.CodePage write F.CodePage; property MaxLength: Byte read F.MaxLength write F.MaxLength; property SBCSIndex: ShortInt read F.SBCSIndex write F.SBCSIndex; property ChildType: TRttiType read F.ChildType write F.ChildType; property Flags: Byte read F.Flags write F.Flags; property ExFlags: Word read F.ExFlags write F.ExFlags; property Options: Cardinal read F.Options write F.Options; property Data: Pointer read F.Data write F.Data; property TypeData: PTypeData read F.TypeData write F.TypeData; property RangeData: PRttiRangeData read F.RangeData write F.RangeData; property EnumerationData: PRttiEnumerationData read F.EnumerationData write F.EnumerationData; property MetaType: PRttiMetaType read F.MetaType write F.MetaType; end; var RTTI_TYPE_GROUPS: array[TRttiType] of TRttiTypeGroup = ( // rgUnknown {000} rgUnknown, // rtUnknown, // rgPointer {001} rgPointer, // rtPointer, // rgBoolean {002} rgBoolean, // rtBoolean, {003} rgBoolean, // rtBoolean16, {004} rgBoolean, // rtBoolean32, {005} rgBoolean, // rtBoolean64, {006} rgBoolean, // rtByteBool, {007} rgBoolean, // rtWordBool, {008} rgBoolean, // rtLongBool, {009} rgBoolean, // rtQWordBool, // rgOrdinal {010} rgOrdinal, // rtByte, {011} rgOrdinal, // rtShortInt, {012} rgOrdinal, // rtWord, {013} rgOrdinal, // rtSmallInt, {014} rgOrdinal, // rtCardinal, {015} rgOrdinal, // rtInteger, {016} rgOrdinal, // rtUInt64, {017} rgOrdinal, // rtInt64, // rgFloat {018} rgFloat, // rtComp, {019} rgFloat, // rtCurrency, {020} rgFloat, // rtSingle, {021} rgFloat, // rtDouble, {022} rgFloat, // rtExtended, // rgDateTime {023} rgDateTime, // rtDate, {024} rgDateTime, // rtTime, {025} rgDateTime, // rtDateTime, {026} rgDateTime, // rtTimeStamp, // rgString {027} rgString, // rtSBCSChar, {028} rgString, // rtUTF8Char, {029} rgString, // rtWideChar, {020} rgString, // rtShortString, {031} rgString, // rtSBCSString, {032} rgString, // rtUTF8String, {033} rgString, // rtWideString, {034} rgString, // rtUnicodeString, {035} rgString, // rtUCS4String, // rgEnumeration {036} rgEnumeration, // rtEnumeration, // rgMetaType {037} rgMetaType, // rtSet, {038} rgMetaType, // rtRecord, {039} rgMetaType, // rtStaticArray, {030} rgMetaType, // rtDynamicArray, {041} rgMetaType, // rtObject, {042} rgMetaType, // rtInterface, // rgMetaTypeRef {043} rgMetaTypeRef, // rtClassRef, // rgVariant {044} rgVariant, // rtBytes, {045} rgVariant, // rtVariant, {046} rgVariant, // rtOleVariant, {047} rgVariant, // rtVarRec, // rgFunction {048} rgFunction, // rtFunction, {049} rgFunction, // rtMethod, {050} rgFunction, // rtClosure, // Reserved {051} rgUnknown, {052} rgUnknown, {053} rgUnknown, {054} rgUnknown, {055} rgUnknown, {056} rgUnknown, {057} rgUnknown, {058} rgUnknown, {059} rgUnknown, {060} rgUnknown, {061} rgUnknown, {062} rgUnknown, {063} rgUnknown, {064} rgUnknown, {065} rgUnknown, {066} rgUnknown, {067} rgUnknown, {068} rgUnknown, {069} rgUnknown, {070} rgUnknown, {071} rgUnknown, {072} rgUnknown, {073} rgUnknown, {074} rgUnknown, {075} rgUnknown, {076} rgUnknown, {077} rgUnknown, {078} rgUnknown, {079} rgUnknown, {080} rgUnknown, {081} rgUnknown, {082} rgUnknown, {083} rgUnknown, {084} rgUnknown, {085} rgUnknown, {086} rgUnknown, {087} rgUnknown, {088} rgUnknown, {089} rgUnknown, {090} rgUnknown, {091} rgUnknown, {092} rgUnknown, {093} rgUnknown, {094} rgUnknown, {095} rgUnknown, {096} rgUnknown, {097} rgUnknown, {098} rgUnknown, {099} rgUnknown, {100} rgUnknown, {101} rgUnknown, {102} rgUnknown, {103} rgUnknown, {104} rgUnknown, {105} rgUnknown, {106} rgUnknown, {107} rgUnknown, {108} rgUnknown, {109} rgUnknown, {110} rgUnknown, {111} rgUnknown, {112} rgUnknown, {113} rgUnknown, {114} rgUnknown, {115} rgUnknown, {116} rgUnknown, {117} rgUnknown, {118} rgUnknown, {119} rgUnknown, {120} rgUnknown, {121} rgUnknown, {122} rgUnknown, {123} rgUnknown, {124} rgUnknown, {125} rgUnknown, {126} rgUnknown, {127} rgUnknown, {128} rgUnknown, {129} rgUnknown, {130} rgUnknown, {131} rgUnknown, {132} rgUnknown, {133} rgUnknown, {134} rgUnknown, {135} rgUnknown, {136} rgUnknown, {137} rgUnknown, {138} rgUnknown, {139} rgUnknown, {140} rgUnknown, {141} rgUnknown, {142} rgUnknown, {143} rgUnknown, {144} rgUnknown, {145} rgUnknown, {146} rgUnknown, {147} rgUnknown, {148} rgUnknown, {149} rgUnknown, {150} rgUnknown, {151} rgUnknown, {152} rgUnknown, {153} rgUnknown, {154} rgUnknown, {155} rgUnknown, {156} rgUnknown, {157} rgUnknown, {158} rgUnknown, {159} rgUnknown, {160} rgUnknown, {161} rgUnknown, {162} rgUnknown, {163} rgUnknown, {164} rgUnknown, {165} rgUnknown, {166} rgUnknown, {167} rgUnknown, {168} rgUnknown, {169} rgUnknown, {170} rgUnknown, {171} rgUnknown, {172} rgUnknown, {173} rgUnknown, {174} rgUnknown, {175} rgUnknown, {176} rgUnknown, {177} rgUnknown, {178} rgUnknown, {179} rgUnknown, {180} rgUnknown, {181} rgUnknown, {182} rgUnknown, {183} rgUnknown, {184} rgUnknown, {185} rgUnknown, {186} rgUnknown, {187} rgUnknown, {188} rgUnknown, {189} rgUnknown, {190} rgUnknown, {191} rgUnknown, {192} rgUnknown, {193} rgUnknown, {194} rgUnknown, {195} rgUnknown, {196} rgUnknown, {197} rgUnknown, {198} rgUnknown, {199} rgUnknown, {200} rgUnknown, {201} rgUnknown, {202} rgUnknown, {203} rgUnknown, {204} rgUnknown, {205} rgUnknown, {206} rgUnknown, {207} rgUnknown, {208} rgUnknown, {209} rgUnknown, {210} rgUnknown, {211} rgUnknown, {212} rgUnknown, {213} rgUnknown, {214} rgUnknown, {215} rgUnknown, {216} rgUnknown, {217} rgUnknown, {218} rgUnknown, {219} rgUnknown, {220} rgUnknown, {221} rgUnknown, {222} rgUnknown, {223} rgUnknown, {224} rgUnknown, {225} rgUnknown, {226} rgUnknown, {227} rgUnknown, {228} rgUnknown, {229} rgUnknown, {230} rgUnknown, {231} rgUnknown, {232} rgUnknown, {233} rgUnknown, {234} rgUnknown, {235} rgUnknown, {236} rgUnknown, {237} rgUnknown, {238} rgUnknown, {239} rgUnknown, {240} rgUnknown, {241} rgUnknown, {242} rgUnknown, {243} rgUnknown, {244} rgUnknown, {245} rgUnknown, {246} rgUnknown, {247} rgUnknown, {248} rgUnknown, {249} rgUnknown, {250} rgUnknown, {251} rgUnknown, {252} rgUnknown, {253} rgUnknown, {254} rgUnknown, {255} rgUnknown); procedure CopyRecord(Dest, Source, TypeInfo: Pointer); {$if Defined(FPC) or (not Defined(CPUINTEL))}inline;{$ifend} {$if Defined(FPC) or (CompilerVersion <= 20)} procedure CopyArray(Dest, Source, TypeInfo: Pointer; Count: NativeUInt); procedure InitializeArray(Source, TypeInfo: Pointer; Count: NativeUInt); procedure FinalizeArray(Source, TypeInfo: Pointer; Count: NativeUInt); {$ifend} function GetTypeName(const ATypeInfo: PTypeInfo): PShortStringHelper; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} function GetTypeData(const ATypeInfo: PTypeInfo): PTypeData; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} function GetEnumName(const ATypeInfo: PTypeInfo; const AValue: Integer): PShortStringHelper; function GetEnumValue(const ATypeInfo: PTypeInfo; const AName: ShortString): Integer; function IsManaged(const ATypeInfo: PTypeInfo): Boolean; function HasWeakRef(const ATypeInfo: PTypeInfo): Boolean; {$if Defined(INLINESUPPORTSIMPLE) and not Defined(WEAKREF)}inline;{$ifend} function RttiTypeGroupCurrent: TRttiTypeGroup; function RttiTypeGroupAdd: TRttiTypeGroup; function RttiTypeCurrent: TRttiType; function RttiTypeAdd(const AGroup: TRttiTypeGroup): TRttiType; function RttiAlloc(const ASize: Integer): Pointer; implementation const CP_UTF8 = 65001; SHORTSTR_RESULT: array[0..6] of Byte = (6, Ord('R'), Ord('e'), Ord('s'), Ord('u'), Ord('l'), Ord('t')); REFERENCED_TYPE_KINDS = [{$ifdef WEAKINSTREF}tkClass, tkMethod,{$endif} {$ifdef WEAKREF}tkInterface{$endif}]; { System.TypInfo/System.Rtti helpers } {$ifdef FPC} function int_copy(Src, Dest, TypeInfo: Pointer): SizeInt; [external name 'FPC_COPY']; procedure int_initialize(Data, TypeInfo: Pointer); [external name 'FPC_INITIALIZE']; procedure int_finalize(Data, TypeInfo: Pointer); [external name 'FPC_FINALIZE']; {$endif} procedure CopyRecord(Dest, Source, TypeInfo: Pointer); {$if Defined(FPC)} begin int_copy(Source, Dest, TypeInfo); end; {$elseif Defined(CPUINTEL)} asm jmp System.@CopyRecord end; {$else} begin System.CopyArray(Dest, Source, TypeInfo, 1); end; {$ifend} {$if Defined(FPC) or (CompilerVersion <= 20)} procedure CopyArray(Dest, Source, TypeInfo: Pointer; Count: NativeUInt); {$ifdef FPC} var i, LItemSize: NativeInt; LItemDest, LItemSrc: Pointer; begin LItemDest := Dest; LItemSrc := Source; case PTypeInfo(TypeInfo).Kind of tkVariant: LItemSize := SizeOf(Variant); tkLString, tkWString, tkInterface, tkDynArray, tkAString: LItemSize := SizeOf(Pointer); tkArray, tkRecord, tkObject: LItemSize := PTypeData(NativeUInt(TypeInfo) + PByte(@PTypeInfo(TypeInfo).Name)^).RecSize; else Exit; end; for i := 1 to Count do begin int_copy(LItemSrc, LItemDest, TypeInfo); Inc(NativeInt(LItemDest), LItemSize); Inc(NativeInt(LItemSrc), LItemSize); end; end; {$else} asm cmp byte ptr [ecx], tkArray jne @1 push eax push edx movzx edx, [ecx + TTypeInfo.Name] mov eax, [ecx + edx + 6] mov ecx, [ecx + edx + 10] mul Count mov ecx, [ecx] mov Count, eax pop edx pop eax @1: pop ebp jmp System.@CopyArray end; {$endif} procedure InitializeArray(Source, TypeInfo: Pointer; Count: NativeUInt); {$ifdef FPC} var i, LItemSize: NativeInt; LItemPtr: Pointer; begin LItemPtr := Source; case PTypeInfo(TypeInfo).Kind of tkVariant: LItemSize := SizeOf(Variant); tkLString, tkWString, tkInterface, tkDynArray, tkAString: LItemSize := SizeOf(Pointer); tkArray, tkRecord, tkObject: LItemSize := PTypeData(NativeUInt(TypeInfo) + PByte(@PTypeInfo(TypeInfo).Name)^).RecSize; else Exit; end; for i := 1 to Count do begin int_initialize(LItemPtr, TypeInfo); Inc(NativeInt(LItemPtr), LItemSize); end; end; {$else} asm jmp System.@InitializeArray end; {$endif} procedure FinalizeArray(Source, TypeInfo: Pointer; Count: NativeUInt); {$ifdef FPC} var i, LItemSize: NativeInt; LItemPtr: Pointer; begin LItemPtr := Source; case PTypeInfo(TypeInfo).Kind of tkVariant: LItemSize := SizeOf(Variant); tkLString, tkWString, tkInterface, tkDynArray, tkAString: LItemSize := SizeOf(Pointer); tkArray, tkRecord, tkObject: LItemSize := PTypeData(NativeUInt(TypeInfo) + PByte(@PTypeInfo(TypeInfo).Name)^).RecSize; else Exit; end; for i := 1 to Count do begin int_finalize(LItemPtr, TypeInfo); Inc(NativeInt(LItemPtr), LItemSize); end; end; {$else} asm jmp System.@FinalizeArray end; {$endif} {$ifend} function GetTypeName(const ATypeInfo: PTypeInfo): PShortStringHelper; begin Result := @ATypeInfo.Name; end; function GetTypeData(const ATypeInfo: PTypeInfo): PTypeData; var LCount: NativeUInt; begin LCount := NativeUInt(ATypeInfo.Name.Value[0]); Result := Pointer(@ATypeInfo.Name.Value[LCount + 1]); end; function GetEnumName(const ATypeInfo: PTypeInfo; const AValue: Integer): PShortStringHelper; begin if (Assigned(ATypeInfo)) and (ATypeInfo.Kind = tkEnumeration) then begin Result := ATypeInfo.TypeData.EnumerationData.EnumNames[AValue]; end else begin Result := nil; end; end; function GetEnumValue(const ATypeInfo: PTypeInfo; const AName: ShortString): Integer; begin if (Assigned(ATypeInfo)) and (ATypeInfo.Kind = tkEnumeration) then begin Result := ATypeInfo.TypeData.EnumerationData.EnumValues[AName]; end else begin Result := -1; end; end; function IsManaged(const ATypeInfo: PTypeInfo): Boolean; var LTypeData: PTypeData; begin Result := False; if Assigned(ATypeInfo) then case ATypeInfo.Kind of tkVariant, {$ifdef AUTOREFCOUNT} tkClass, {$endif} {$ifdef WEAKINSTREF} tkMethod, {$endif} {$ifdef FPC} tkAString, {$endif} tkWString, tkLString, {$ifdef UNICODE}tkUString,{$endif} tkInterface, tkDynArray: begin Result := True; Exit; end; tkArray{static array}: begin LTypeData := PTypeData(NativeUInt(ATypeInfo) + PByte(@ATypeInfo.Name)^); if (LTypeData.ArrayData.ElType.Assigned) then Result := IsManaged(LTypeData.ArrayData.ElType.Value); end; tkRecord{$ifdef FPC}, tkObject{$endif}: begin LTypeData := PTypeData(NativeUInt(ATypeInfo) + PByte(@ATypeInfo.Name)^); Result := (LTypeData.ManagedFldCount <> 0); end; end; end; function HasWeakRef(const ATypeInfo: PTypeInfo): Boolean; {$ifdef WEAKREF} var i: Integer; LTypeData: PTypeData; LField: PManagedField; begin Result := False; if Assigned(ATypeInfo) then case ATypeInfo.Kind of {$ifdef WEAKINSTREF} tkMethod: begin Result := True; end; {$endif} tkArray{static array}: begin LTypeData := PTypeData(NativeUInt(ATypeInfo) + PByte(@ATypeInfo.Name)^); if (LTypeData.ArrayData.ElType.Assigned) then Result := HasWeakRef(LTypeData.ArrayData.ElType.Value); end; tkRecord{$ifdef FPC}, tkObject{$endif}: begin LTypeData := PTypeData(NativeUInt(ATypeInfo) + PByte(@ATypeInfo.Name)^); LField := @LTypeData.ManagedFields; for i := 0 to LTypeData.ManagedFldCount - 1 do begin if (not LField.TypeRef.Assigned) or (HasWeakRef(LField.TypeRef.Value)) then begin Result := True; Exit; end; Inc(LField); end; end; end; end; {$else} begin Result := False; end; {$endif} { Groups and types } var TypeGroupCurrent: TRttiTypeGroup = rgFunction; TypeCurrent: TRttiType = rtClosure; function RttiTypeGroupCurrent: TRttiTypeGroup; begin Result := TypeGroupCurrent; end; function RttiTypeGroupAdd: TRttiTypeGroup; begin Result := TypeGroupCurrent; if (Result = High(TRttiTypeGroup)) then begin System.Error(reIntOverflow); end; Inc(Result); TypeGroupCurrent := Result; end; function RttiTypeCurrent: TRttiType; begin Result := TypeCurrent; end; function RttiTypeAdd(const AGroup: TRttiTypeGroup): TRttiType; begin Result := TypeCurrent; if (Result = High(TRttiType)) then begin System.Error(reIntOverflow); end; if (Byte(AGroup) > Byte(TypeGroupCurrent)) then begin System.Error(reInvalidCast); end; Inc(Result); TypeCurrent := Result; RTTI_TYPE_GROUPS[Result] := AGroup; end; { Effective 8 bytes aligned allocator } var MemoryDefaultBuffer: array[0..8 * 1024 - 1] of Byte; MemoryCurrent, MemoryOverflow: PByte; MemoryBuffers: array of TBytes; function RttiMemoryReserve(const ASize: NativeUInt): PByte; const MAX_BUFFER_SIZE = 4 * 1024 * 1024 - 128; var LBufferCount: NativeUInt; LBufferSize: NativeUInt; begin LBufferCount := Length(MemoryBuffers); SetLength(MemoryBuffers, LBufferCount + 1); if (ASize > MAX_BUFFER_SIZE) then begin LBufferSize := ASize; end else begin LBufferSize := SizeOf(MemoryDefaultBuffer); while (LBufferSize < ASize) do begin LBufferSize := LBufferSize shl 1; end; end; SetLength(MemoryBuffers[LBufferCount], LBufferSize); Result := Pointer(MemoryBuffers[LBufferCount]); MemoryCurrent := Result; MemoryOverflow := Pointer(NativeUInt(Result) + LBufferSize); end; function RttiAlloc(const ASize: Integer): Pointer; var LSize: NativeUInt; LPtr: PByte; begin if (ASize <= 0) then begin Result := nil; Exit; end; LSize := Cardinal(ASize); LPtr := MemoryCurrent; if (not Assigned(LPtr)) then begin LPtr := @MemoryDefaultBuffer[Low(MemoryDefaultBuffer)]; MemoryCurrent := LPtr; MemoryOverflow := Pointer(NativeUInt(LPtr) + SizeOf(MemoryDefaultBuffer)); end; LPtr := Pointer((NativeInt(LPtr) + 7) and -8); Result := LPtr; Inc(LPtr, LSize); if (NativeUInt(LPtr) <= NativeUInt(MemoryOverflow)) then begin MemoryCurrent := LPtr; Exit; end; LPtr := RttiMemoryReserve(LSize + 7); LPtr := Pointer((NativeInt(LPtr) + 7) and -8); Result := LPtr; Inc(LPtr, LSize); MemoryCurrent := LPtr; end; { TDynArrayRec } {$ifdef FPC} function TDynArrayRec.GetLength: NativeInt; begin Result := High + 1; end; procedure TDynArrayRec.SetLength(const AValue: NativeInt); begin High := AValue - 1; end; {$else .DELPHI} function TDynArrayRec.GetHigh: NativeInt; begin Result := Length - 1; end; procedure TDynArrayRec.SetHigh(const AValue: NativeInt); begin Length := AValue + 1; end; {$endif} { TWideStrRec } {$ifdef MSWINDOWS} function TWideStrRec.GetLength: Integer; begin Result := Size shr 1; end; procedure TWideStrRec.SetLength(const AValue: Integer); begin Size := AValue + AValue; end; {$endif} { ShortStringHelper } function ShortStringHelper.GetValue: Integer; begin Result := Byte(Pointer(@Value)^); end; procedure ShortStringHelper.SetValue(const AValue: Integer); begin Byte(Pointer(@Value)^) := AValue; end; function ShortStringHelper.GetAnsiValue: AnsiString; var LCount: Integer; begin LCount := Byte(Pointer(@Value)^); SetLength(Result, LCount); System.Move(Value[1], Pointer(Result)^, LCount); end; function ShortStringHelper.GetUTF8Value: UTF8String; var LCount: Integer; begin LCount := Byte(Pointer(@Value)^); SetLength(Result, LCount); System.Move(Value[1], Pointer(Result)^, LCount); end; function ShortStringHelper.GetUnicodeValue: UnicodeString; {$ifdef UNICODE} var LCount: Integer; begin if (Byte(Pointer(@Value)^) = 0) then begin Result := ''; end else begin LCount := {$ifdef MSWINDOWS}MultiByteToWideChar{$else}UnicodeFromLocaleChars{$endif}(CP_UTF8, 0, Pointer(@Value[1]), Byte(Pointer(@Value)^), nil, 0); SetLength(Result, LCount); {$ifdef MSWINDOWS}MultiByteToWideChar{$else}UnicodeFromLocaleChars{$endif}(CP_UTF8, 0, Pointer(@Value[1]), Byte(Pointer(@Value)^), Pointer(Result), LCount); end; end; {$else .ANSI} var i: Integer; LCount: Integer; LSource: PByte; LTarget: PWord; begin LCount := Byte(Pointer(@Value)^); SetLength(Result, LCount); LSource := Pointer(@Value[1]); LTarget := Pointer(Result); for i := 1 to LCount do begin LTarget^ := LSource^; Inc(LSource); Inc(LTarget); end; end; {$endif} function ShortStringHelper.GetTail: Pointer; var LCount: NativeUInt; begin LCount := NativeUInt(Value[0]); Result := Pointer(@Value[LCount + 1]); end; {$ifdef EXTENDEDRTTI} { TAttrEntryReader } function TAttrEntryReader.RangeError: Pointer; begin System.Error(reRangeError); Result := nil; end; function TAttrEntryReader.GetEOF: Boolean; begin Result := (Current = Overflow); end; function TAttrEntryReader.GetMargin: NativeUInt; begin Result := NativeUInt(Overflow) - NativeUInt(Current); end; procedure TAttrEntryReader.ReadData(var ABuffer; const ASize: NativeUInt); var LCurrent: PByte; begin LCurrent := Current; Inc(LCurrent, ASize); if (NativeUInt(LCurrent) > NativeUInt(Overflow)) then begin RangeError; Exit; end; Current := LCurrent; Dec(LCurrent, ASize); System.Move(LCurrent^, ABuffer, ASize); end; function TAttrEntryReader.Reserve(const ASize: NativeUInt): Pointer; var LCurrent: PByte; begin LCurrent := Current; Inc(LCurrent, ASize); if (NativeUInt(LCurrent) > NativeUInt(Overflow)) then begin Result := RangeError; Exit; end; Current := LCurrent; Dec(LCurrent, ASize); Result := LCurrent; end; function TAttrEntryReader.ReadBoolean: Boolean; begin Result := Boolean(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadAnsiChar: AnsiChar; begin Result := AnsiChar(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadWideChar: WideChar; begin Result := WideChar(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadUCS4Char: UCS4Char; begin Result := UCS4Char(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadShortInt: ShortInt; begin Result := ShortInt(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadByte: Byte; begin Result := Byte(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadSmallInt: SmallInt; begin Result := SmallInt(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadWord: Word; begin Result := Word(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadInteger: Integer; begin Result := Integer(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadCardinal: Cardinal; begin Result := Cardinal(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadInt64: Int64; begin Result := Int64(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadUInt64: UInt64; begin Result := UInt64(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadSingle: Single; begin Result := Single(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadDouble: Double; begin Result := Double(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadExtended: Extended; begin Result := Extended(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadComp: Comp; begin Result := Comp(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadCurrency: Currency; begin Result := Currency(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadDateTime: TDateTime; begin Result := TDateTime(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadPointer: Pointer; begin Result := Pointer(Reserve(SizeOf(Result))^); end; function TAttrEntryReader.ReadTypeInfo: Pointer{PTypeInfo}; begin Result := Pointer{PPTypeInfo}(Reserve(SizeOf(Result))^); if (Assigned(Result)) then begin Result := PPointer(Result)^; end; end; function TAttrEntryReader.ReadClass: TClass; var LTypeInfo: PTypeInfo; begin LTypeInfo := ReadTypeInfo; if (Assigned(LTypeInfo)) then begin if (LTypeInfo.Kind = tkClass) then begin Result := LTypeInfo.TypeData.ClassType; Exit; end else begin System.Error(reInvalidCast); end; end; Result := nil; end; function TAttrEntryReader.ReadShortString: ShortString; var LCount: NativeUInt; LPtr: PByte; begin LCount := ReadWord; if (LCount = 0) then begin PByte(@Result)^ := 0; Exit; end; LPtr := Reserve(LCount); if (LCount > 255) then begin LCount := 255; end; PByte(@Result)^ := LCount; System.Move(LPtr^, Result[1], LCount); end; function TAttrEntryReader.ReadUTF8String: UTF8String; var LCount: NativeUInt; LPtr: PByte; begin LCount := ReadWord; if (LCount = 0) then begin Result := {$ifdef ANSISTRSUPPORT}''{$else}nil{$endif}; Exit; end; LPtr := Reserve(LCount); SetLength(Result, LCount); System.Move(LPtr^, Pointer(Result)^, LCount); end; function TAttrEntryReader.ReadString: string; var LCount, LTargetCount: NativeUInt; LPtr: PByte; begin LCount := ReadWord; LPtr := Reserve(LCount); if (LCount = 0) then begin Result := ''; Exit; end; LTargetCount := {$ifdef MSWINDOWS}MultiByteToWideChar{$else}UnicodeFromLocaleChars{$endif}(CP_UTF8, 0, Pointer(LPtr), LCount, nil, 0); SetLength(Result, LTargetCount); {$ifdef MSWINDOWS}MultiByteToWideChar{$else}UnicodeFromLocaleChars{$endif}(CP_UTF8, 0, Pointer(LPtr), LCount, Pointer(Result), LTargetCount); end; { TAttrEntry } function TAttrEntry.GetClassType: TClass; var LTypeInfo: PTypeInfo; begin LTypeInfo := PTypeInfoRef(AttrType).Value; if (Assigned(LTypeInfo)) then begin Result := LTypeInfo.TypeData.ClassType; Exit; end; Result := nil; end; function TAttrEntry.GetConstructorSignature: PVmtMethodSignature; var i: Integer; LTypeInfo: PTypeInfo; LAddress, LImplAddress: Pointer; {$ifdef MSWINDOWS} LPtr: PByte; {$endif} LTypeData: PTypeData; LMethodTable: PVmtMethodTableEx; LEntry: PVmtMethodEntry; LEntryAddress: Pointer; begin LTypeInfo := PTypeInfoRef(AttrType).Value; LAddress := ConstructorAddress; Result := nil; if (not Assigned(LTypeInfo)) or (not Assigned(LAddress)) then Exit; LImplAddress := nil; {$ifdef MSWINDOWS} LPtr := LAddress; if (LPtr^ = $FF) then begin Inc(LPtr); if (LPtr^ = $25) then begin Inc(LPtr); {$ifdef CPUX86} LImplAddress := PPointer((NativeInt(LPtr) + 4) + PInteger(LPtr)^)^; {$else .CPUX64} LImplAddress := PPointer(PPointer(LPtr)^)^; {$endif} end; end; {$endif} repeat LTypeData := LTypeInfo.TypeData; LMethodTable := LTypeData.ClassData.MethodTableEx; if (Assigned(LMethodTable)) then begin for i := 0 to Integer(LMethodTable.Count) - 1 do begin LEntry := LMethodTable.Entries[i].Entry; if (Assigned(LEntry)) then begin LEntryAddress := LEntry.CodeAddress; if (Assigned(LEntryAddress)) then begin if (LEntryAddress = LAddress) or (LEntryAddress = LImplAddress) then begin Result := LEntry.Signature; Exit; end; end; end; end; end; LTypeInfo := LTypeData.ClassData.ParentInfo.Value; until (not Assigned(LTypeInfo)); Result := nil; end; function TAttrEntry.GetReader: TAttrEntryReader; begin Result.Current := Pointer(@ArgData); Result.Overflow := Pointer(@ArgData[ArgLen + Low(ArgData)]); end; function TAttrEntry.GetTail: Pointer; begin Result := @ArgData[ArgLen + Low(ArgData)]; end; { TAttrData } function TAttrData.GetValue: PAttrData; begin Result := @Self; if (Result.Len = SizeOf(Word)) then begin Result := nil; end; end; function TAttrData.GetTail: Pointer; begin Result := Pointer(PAnsiChar(@Len) + Len); end; function TAttrData.GetCount: Integer; var LEntry, LTail: PAttrEntry; begin LEntry := @Entries; LTail := Tail; Result := 0; repeat if (LEntry = LTail) then Break; Inc(Result); LEntry := LEntry.Tail; if (NativeUInt(LEntry) > NativeUInt(LTail)) then begin System.Error(reInvalidPtr); Exit; end; until (False); end; function TAttrData.GetReference: TReference; {$ifdef WEAKREF} var LEntry, LTail: PAttrEntry; LClassType: TClass; begin LEntry := @Entries; LTail := Tail; Result := rfDefault; repeat if (LEntry = LTail) then Break; LClassType := LEntry.ClassType; if (Assigned(LClassType)) then begin if (LClassType.InheritsFrom(UnsafeAttribute)) then begin Result := rfUnsafe; Exit; end else if (LClassType.InheritsFrom(WeakAttribute)) then begin Result := rfWeak; end; end; LEntry := LEntry.Tail; if (NativeUInt(LEntry) > NativeUInt(LTail)) then begin System.Error(reInvalidPtr); Exit; end; until (False); end; {$else} begin Result := rfDefault; end; {$endif} {$endif .EXTENDEDRTTI} { TTypeInfo } function TTypeInfo.GetTypeData: PTypeData; var LCount: NativeUInt; begin LCount := NativeUInt(Name.Value[0]); Result := Pointer(@Name.Value[LCount + 1]); end; {$ifdef EXTENDEDRTTI} function TTypeInfo.GetAttrData: PAttrData; var LTypeData: PTypeData; begin LTypeData := GetTypeData; case Kind of {$ifdef UNICODE} tkUString, {$endif} {$ifdef WIDESTRSUPPORT} tkWString, {$endif} tkVariant: Result := @LTypeData.AttrData; {$ifdef ANSISTRSUPPORT} tkLString: Result := @LTypeData.LStrAttrData; {$endif} {$ifdef SHORTSTRSUPPORT} tkString: Result := @LTypeData.StrAttrData; {$endif} tkSet: Result := @LTypeData.SetAttrData; {$ifdef ANSISTRSUPPORT} tkChar, {$endif} tkWChar, tkInteger: Result := @LTypeData.OrdAttrData; tkFloat: Result := @LTypeData.FloatAttrData; tkInt64: Result := @LTypeData.Int64AttrData; tkClassRef: Result := @LTypeData.ClassRefAttrData; tkPointer: Result := @LTypeData.PtrAttrData; tkProcedure: Result := @LTypeData.ProcAttrData; tkEnumeration: Result := LTypeData.EnumerationData.GetAttrDataRec; tkClass: Result := LTypeData.ClassData.GetAttrDataRec; tkMethod: Result := LTypeData.MethodData.GetAttrDataRec; tkInterface: Result := LTypeData.InterfaceData.GetAttrDataRec; tkDynArray: Result := LTypeData.DynArrayData.GetAttrDataRec; tkArray: Result := LTypeData.ArrayData.GetAttrDataRec; tkRecord: Result := LTypeData.RecordData.GetAttrDataRec; else Result := nil; end; if (Assigned(Result)) then begin case Result.Len of 0, 1: System.Error(reInvalidPtr); 2: Result := nil; end; end; end; {$endif} { PTypeInfoRef } {$ifNdef INLINESUPPORT} function PTypeInfoRef.GetAddress: Pointer; begin Result := Self; end; {$endif} function PTypeInfoRef.GetAssigned: Boolean; begin Result := System.Assigned({$ifdef INLINESUPPORT}F.Address{$else}Self{$endif}); end; {$ifNdef FPC} function PTypeInfoRef.GetValue: PTypeInfo; begin Result := Pointer({$ifdef INLINESUPPORT}F.Value{$else}Self{$endif}); if (System.Assigned(Result)) then begin Result := PPointer(Result)^; end; end; {$endif} { TResultData } function TResultData.GetAssigned: Boolean; begin Result := System.Assigned(Name); end; { TPropInfo } function TPropInfo.GetTail: Pointer; begin Result := @Name; Inc(NativeUInt(Result), NativeUInt(Byte(Result^)) + SizeOf(Byte)); end; { TPropData} function TPropData.GetTail: Pointer; begin Result := @PropList[PropCount]; end; { TManagedField } function TManagedField.GetTail: Pointer; begin Result := @Self; Inc(NativeUInt(Result), SizeOf(Self)); end; { TVmtFieldEntry } function TVmtFieldEntry.GetTail: Pointer; begin Result := Name.Tail; end; { TVmtFieldTable } function TVmtFieldTable.GetTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Entries); for i := 0 to Integer(Count) - 1 do begin LPtr := PVmtFieldEntry(LPtr).Tail; end; Result := Pointer(LPtr); end; { TVmtMethodEntry } function TVmtMethodEntry.GetTail: Pointer; begin Result := @Len; Inc(NativeUInt(Result), Len); end; {$ifdef EXTENDEDRTTI} function TVmtMethodEntry.GetSignature: PVmtMethodSignature; begin Result := Name.Tail; if (Result = Tail) then begin Result := nil; end; end; {$endif} { TVmtMethodTable } function TVmtMethodTable.GetTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Entries); for i := 0 to Integer(Count) - 1 do begin LPtr := PVmtMethodEntry(LPtr).Tail; end; Result := Pointer(LPtr); end; { TIntfMethodParamTail } {$ifdef EXTENDEDRTTI} function TIntfMethodParamTail.GetAttrData: PAttrData; begin Result := AttrDataRec.Value; end; {$endif} { TIntfMethodParam } function TIntfMethodParam.GetTypeName: PShortStringHelper; begin Result := ParamName.Tail; end; function TIntfMethodParam.GetParamTail: PIntfMethodParamTail; begin Result := TypeName.Tail; end; function TIntfMethodParam.GetParamType: PTypeInfo; begin Result := GetParamTail.ParamType.Value; end; {$ifdef EXTENDEDRTTI} function TIntfMethodParam.GetAttrDataRec: PAttrData; begin Result := @GetParamTail.AttrDataRec; end; function TIntfMethodParam.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} function TIntfMethodParam.GetData: TArgumentData; begin Result.Name := @ParamName; Result.TypeInfo := ParamType; Result.TypeName := TypeName; Result.Flags := Flags; end; function TIntfMethodParam.GetTail: Pointer; begin {$ifdef EXTENDEDRTTI} Result := GetParamTail.AttrDataRec.Tail; {$else} Result := GetParamTail; Inc(NativeUInt(Result), SizeOf(PTypeInfoRef)); {$endif} end; { TIntfMethodSignature } function TIntfMethodSignature.GetParamsTail: PByte; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Params); for i := 0 to Integer(ParamCount) - 1 do begin LPtr := PIntfMethodParam(LPtr).Tail; end; Result := LPtr; end; function TIntfMethodSignature.GetResultData: TResultData; var LPtr: PByte; begin Result.Reference := rfDefault; if (Kind = 1) then begin LPtr := GetParamsTail; Result.TypeName := PShortStringHelper(LPtr); if (Result.TypeName.Length <> 0) then begin LPtr := PShortStringHelper(LPtr).Tail; Result.TypeInfo := PTypeInfoRef(PPointer(LPtr)^).Value; Result.Name := PShortStringHelper(@SHORTSTR_RESULT); {Result.Reference ToDo} Exit; end; end; Result.Name := nil; Result.TypeInfo := nil; Result.TypeName := nil; end; {$ifdef EXTENDEDRTTI} function TIntfMethodSignature.GetAttrDataRec: PAttrData; var LPtr: PByte; begin LPtr := GetParamsTail; if (Kind = 1) then begin if (LPtr^ = 0) then begin Inc(LPtr); end else begin Inc(LPtr, SizeOf(Byte) + SizeOf(Pointer)); end; end; Result := Pointer(LPtr); end; function TIntfMethodSignature.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif .EXTENDEDRTTI} function TIntfMethodSignature.GetTail: Pointer; {$ifdef EXTENDEDRTTI} begin Result := GetAttrDataRec.Tail; end; {$else} var LPtr: PByte; begin LPtr := GetParamsTail; if (Kind = 1) then begin if (LPtr^ = 0) then begin Inc(LPtr); end else begin Inc(LPtr, SizeOf(Byte) + SizeOf(Pointer)); end; end; Result := Pointer(LPtr); end; {$endif} { TIntfMethodEntry } function TIntfMethodEntry.GetSignature: PIntfMethodSignature; begin Result := Name.Tail; end; function TIntfMethodEntry.GetTail: Pointer; begin Result := Signature.Tail; end; { TIntfMethodTable } function TIntfMethodTable.GetHasEntries: Boolean; begin case RttiCount of 0, $ffff: Result := False; else Result := True; end; end; {$ifdef EXTENDEDRTTI} function TIntfMethodTable.GetAttrDataRec: PAttrData; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Entries); if (RttiCount <> $ffff) then for i := 0 to Integer(RttiCount) - 1 do begin LPtr := PIntfMethodEntry(LPtr).Tail; end; Result := Pointer(LPtr); end; function TIntfMethodTable.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} {$if Defined(FPC) or Defined(EXTENDEDRTTI)} { TProcedureParam } {$ifdef EXTENDEDRTTI} function TProcedureParam.GetAttrDataRec: PAttrData; begin Result := Name.Tail; end; function TProcedureParam.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} function TProcedureParam.GetData: TArgumentData; begin Result.Name := @Name; Result.TypeInfo := ParamType.Value; Result.TypeName := nil; Result.Flags := Flags; end; function TProcedureParam.GetTail: Pointer; begin {$ifdef EXTENDEDRTTI} Result := GetAttrDataRec.Tail; {$else} Result := Name.Tail; {$endif} end; { TProcedureSignature } function TProcedureSignature.GetIsValid: Boolean; begin Result := (Flags <> 255); end; function TProcedureSignature.GetResultValue: TParamData; begin Result.TypeName := nil; Result.Name := nil; if (IsValid) then begin Result.TypeInfo := ResultType.Value; if (Assigned(Result.TypeInfo)) then begin Result.Name := PShortStringHelper(@SHORTSTR_RESULT); end; end else begin Result.TypeInfo := nil; end; end; function TProcedureSignature.GetTail: Pointer; var i: Integer; begin if (IsValid) then begin Result := @Params; for i := 0 to Integer(ParamCount) - 1 do begin Result := TProcedureParam(Result^).Tail; end; end else begin Result := @CC; end; end; {$ifend .FPC.EXTENDEDRTTI} {$ifdef EXTENDEDRTTI} { TPropInfoEx } function TPropInfoEx.GetAttrData: PAttrData; begin Result := AttrDataRec.Value; end; function TPropInfoEx.GetTail: Pointer; begin Result := AttrDataRec.Tail; end; { TPropDataEx } function TPropDataEx.GetTail: Pointer; var i: Integer; LPtr: Pointer; begin LPtr := Pointer(@PropList); for i := 0 to Integer(PropCount) - 1 do begin LPtr := PPropInfoEx(LPtr).Tail; end; Result := LPtr; end; { TArrayPropInfo } function TArrayPropInfo.GetAttrDataRec: PAttrData; begin Result := Name.Tail; end; function TArrayPropInfo.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TArrayPropInfo.GetTail: Pointer; begin Result := GetAttrDataRec.Tail; end; { TArrayPropData } function TArrayPropData.GetTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@PropData); for i := 0 to Integer(Count) - 1 do begin LPtr := PArrayPropInfo(LPtr).Tail; end; Result := LPtr; end; { TVmtFieldExEntry } function TVmtFieldExEntry.GetVisibility: TMemberVisibility; begin Result := TMemberVisibility(Flags and 3); end; function TVmtFieldExEntry.GetAttrDataRec: PAttrData; begin Result := Name.Tail; end; function TVmtFieldExEntry.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TVmtFieldExEntry.GetValue: TFieldData; begin Result.Name := @Name; Result.TypeInfo := TypeRef.Value; Result.TypeName := nil; Result.Visibility := Visibility; Result.AttrData := AttrData; end; function TVmtFieldExEntry.GetTail: Pointer; begin Result := GetAttrDataRec.Tail; end; { TVmtMethodParam } function TVmtMethodParam.GetAttrDataRec: PAttrData; begin Result := Name.Tail; end; function TVmtMethodParam.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TVmtMethodParam.GetData: TArgumentData; begin Result.Name := @Name; Result.TypeInfo := ParamType.Value; Result.TypeName := nil; Result.Flags := Flags; end; function TVmtMethodParam.GetTail: Pointer; begin Result := GetAttrDataRec.Tail; end; { TVmtMethodSignature } function TVmtMethodSignature.GetAttrDataRec: PAttrData; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Params); for i := 0 to Integer(ParamCount) - 1 do begin LPtr := PVmtMethodParam(LPtr).Tail; end; Result := Pointer(LPtr); end; function TVmtMethodSignature.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TVmtMethodSignature.GetResultData: TResultData; begin Result.TypeInfo := ResultType.Value; Result.TypeName := nil; Result.Reference := rfDefault; if (Assigned(Result.TypeInfo)) then begin Result.Name := PShortStringHelper(@SHORTSTR_RESULT); {Result.Reference ToDo} end else begin Result.Name := nil; end; end; { TVmtMethodExEntry } function TVmtMethodExEntry.GetTail: Pointer; begin Result := @Self; Inc(NativeUInt(Result), SizeOf(Self)); end; { TVmtMethodTableEx } function TVmtMethodTableEx.GetVirtualCount: Word; begin Result := PWord(@Entries[Count])^; end; { TRecordTypeOptions } function TRecordTypeOptions.GetTail: Pointer; begin Result := @Values[Count]; end; { TRecordTypeField } function TRecordTypeField.GetVisibility: TMemberVisibility; begin Result := TMemberVisibility(Flags and 3); end; function TRecordTypeField.GetAttrDataRec: PAttrData; begin Result := Name.Tail; end; function TRecordTypeField.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TRecordTypeField.GetFieldData: TFieldData; begin Result.Name := @Name; Result.TypeInfo := Field.TypeRef.Value; Result.TypeName := nil; Result.Reference := rfDefault; Result.Visibility := Visibility; Result.AttrData := AttrData; Result.Offset := Cardinal(Field.FldOffset); {$ifdef WEAKREF} if (Assigned(Result.AttrData)) then begin if (Assigned(Result.TypeInfo)) and (Result.TypeInfo.Kind in REFERENCED_TYPE_KINDS) then begin Result.Reference := Result.AttrData.Reference; end; end; {$endif} end; function TRecordTypeField.GetTail: Pointer; begin Result := GetAttrDataRec.Tail; end; { TRecordTypeFields } function TRecordTypeFields.GetTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Fields); for i := 0 to Count - 1 do begin LPtr := PRecordTypeField(LPtr).Tail; end; Result := LPtr; end; { TRecordTypeMethod } function TRecordTypeMethod.GetSignature: PProcedureSignature; begin Result := Name.Tail; end; function TRecordTypeMethod.GetAttrDataRec: PAttrData; begin Result := Signature.Tail; end; function TRecordTypeMethod.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TRecordTypeMethod.GetTail: Pointer; begin Result := GetAttrDataRec.Tail; end; { TRecordTypeMethods } function TRecordTypeMethods.GetTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@Methods); for i := 0 to Integer(Count) - 1 do begin LPtr := PRecordTypeMethod(LPtr).Tail; end; Result := LPtr; end; {$endif .EXTENDEDRTTI} { TEnumerationTypeData } function TEnumerationTypeData.GetCount: Integer; begin Result := (MaxValue - MinValue) + 1; end; function TEnumerationTypeData.GetEnumName(const AValue: Integer): PShortStringHelper; var i: Integer; begin Result := nil; if (AValue < 0) or (AValue > MaxValue) or (MinValue <> 0) then Exit; Result := @NameList; for i := MinValue to AValue - 1 do begin Result := Pointer(@Result.Value[Byte(Result.Value[0]) + 1]){Result.Tail}; end; end; {$ifdef UNICODE} function InternalUTF8CharsCompare(const AStr1, AStr2: PAnsiChar; const ACount: NativeUInt): Boolean; label failure; {$ifdef MSWINDOWS} var i, LCount1, LCount2: Integer; LBuffer1, LBuffer2: array[0..255] of WideChar; {$endif} begin if (Assigned(_utf8_equal_utf8_ignorecase)) then begin Result := _utf8_equal_utf8_ignorecase(PUTF8Char(AStr1), ACount, PUTF8Char(AStr2), ACount); end else begin {$ifdef MSWINDOWS} LCount1 := MultiByteToWideChar(CP_UTF8, 0, AStr1, ACount, nil, 0); LCount2 := MultiByteToWideChar(CP_UTF8, 0, AStr2, ACount, nil, 0); if (LCount1 = LCount2) then begin MultiByteToWideChar(CP_UTF8, 0, AStr1, ACount, @LBuffer1[0], High(LBuffer1)); MultiByteToWideChar(CP_UTF8, 0, AStr2, ACount, @LBuffer2[0], High(LBuffer2)); CharLowerBuffW(@LBuffer1[0], LCount1); CharLowerBuffW(@LBuffer2[0], LCount1); for i := 0 to LCount1 - 1 do begin if (LBuffer1[i] <> LBuffer2[i]) then goto failure; end; Result := True; Exit; end; {$endif} failure: Result := False; end; end; {$endif} function TEnumerationTypeData.GetEnumValue(const AName: ShortString): Integer; label failure; var LCount, LTempCount: NativeUInt; LMaxResult: Integer; LSource, LTarget: PAnsiChar; LSourceChar, LTargetChar: Cardinal; begin LSource := Pointer(@AName[0]); LCount := PByte(LSource)^; if (MinValue <> 0) or (LCount = 0) then goto failure; LMaxResult := MaxValue; LTarget := Pointer(@NameList); Result := -1; repeat Inc(Result); if (PByte(LTarget)^ = LCount) then begin repeat Inc(LSource); Inc(LTarget); if (LCount = 0) then Exit; LSourceChar := PByte(LSource)^; LTargetChar := PByte(LTarget)^; Dec(LCount); {$ifdef UNICODE} if (LSourceChar or LTargetChar <= $7f) then {$endif} begin if (LSourceChar <> LTargetChar) then begin case (LSourceChar) of Ord('A')..Ord('Z'): LSourceChar := LSourceChar or $20; end; case (LTargetChar) of Ord('A')..Ord('Z'): LTargetChar := LTargetChar or $20; end; if (LSourceChar <> LTargetChar) then Break; end; end {$ifdef UNICODE} else if (LSourceChar xor LTargetChar > $7f) then begin Break; end else begin Inc(LCount); LTempCount := LCount; Dec(LSource); Dec(LTarget); repeat Inc(LSource); Inc(LTarget); if (LCount = 0) then Exit; Dec(LCount); if (LSource^ <> LTarget^) then Break; until (False); Inc(LCount); Dec(NativeInt(LCount), NativeInt(LTempCount)); Inc(LSource, NativeInt(LCount)); Inc(LTarget, NativeInt(LCount)); LCount := LTempCount; if (InternalUTF8CharsCompare(LSource, LTarget, LCount)) then Exit; Dec(LCount); Break; end {$endif} ; until (False); LSource := Pointer(@AName[0]); LTempCount := LCount; LCount := PByte(LSource)^; Dec(NativeInt(LTempCount), NativeInt(LCount)); Inc(LTarget, NativeInt(LTempCount)); end; LTarget := LTarget + PByte(LTarget)^ + 1; until (Result = LMaxResult); failure: Result := -1; end; function TEnumerationTypeData.GetUnitName: PShortStringHelper; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@NameList); for i := 0 to Count - 1 do begin LPtr := PShortStringHelper(LPtr).Tail; end; Result := Pointer(LPtr); end; {$ifdef EXTENDEDRTTI} function TEnumerationTypeData.GetAttrDataRec: PAttrData; begin Result := UnitName.Tail; end; function TEnumerationTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} { TMethodParam } function TMethodParam.GetTypeName: PShortStringHelper; begin Result := ParamName.Tail; end; function TMethodParam.GetTail: Pointer; begin Result := TypeName.Tail; end; { TMethodSignature } function TMethodSignature.GetParamsTail: Pointer; var i: Integer; LPtr: PByte; begin LPtr := Pointer(@ParamList); for i := 0 to Integer(ParamCount) - 1 do begin LPtr := PMethodParam(LPtr).Tail; end; Result := LPtr; end; function TMethodSignature.GetResultData: TResultData; var LPtr: PByte; begin Result.Reference := rfDefault; if (MethodKind <> mkFunction) then begin Result.Name := nil; Result.TypeInfo := nil; Result.TypeName := nil; Exit; end; LPtr := GetParamsTail; Result.Name := PShortStringHelper(@SHORTSTR_RESULT); Result.TypeName := Pointer(LPtr); Result.TypeInfo := PTypeInfoRef(PPointer(Result.TypeName.Tail)^).Value; {Result.Reference ToDo} end; function TMethodSignature.GetResultTail: Pointer; var LPtr: PByte; begin LPtr := GetParamsTail; if (MethodKind = mkFunction) then begin LPtr := PShortStringHelper(LPtr).Tail; Inc(LPtr, SizeOf(Pointer)); end; Result := LPtr; end; function TMethodSignature.GetCallConv: TCallConv; begin Result := PCallConv(GetResultTail)^; end; function TMethodSignature.GetParamTypes: PPTypeInfoRef; var LPtr: PByte; begin LPtr := GetResultTail; Inc(LPtr, SizeOf(TCallConv)); Result := Pointer(LPtr); end; { TMethodTypeData} {$ifdef EXTENDEDRTTI} function TMethodTypeData.GetSignature: PProcedureSignature; var LPtr: PByte; begin LPtr := GetResultTail; Inc(LPtr, SizeOf(TCallConv)); Inc(LPtr, NativeUInt(ParamCount) * SizeOf(PTypeInfoRef)); Result := PPointer(LPtr)^; end; function TMethodTypeData.GetAttrDataRec: PAttrData; var LPtr: PByte; begin LPtr := GetResultTail; Inc(LPtr, SizeOf(TCallConv)); Inc(LPtr, NativeUInt(ParamCount) * SizeOf(Pointer)); Inc(LPtr, SizeOf(PProcedureSignature)); Result := Pointer(LPtr); end; function TMethodTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif .EXTENDEDRTTI} { TClassTypeData } function TClassTypeData.GetFieldTable: PVmtFieldTable; begin Result := PPointer(NativeInt(ClassType) + vmtFieldTable)^; end; function TClassTypeData.GetMethodTable: PVmtMethodTable; begin Result := PPointer(NativeInt(ClassType) + vmtMethodTable)^; end; function TClassTypeData.GetPropData: PPropData; begin Result := UnitName.Tail; end; {$ifdef EXTENDEDRTTI} function TClassTypeData.GetFieldTableEx: PVmtFieldTableEx; var LPtr: PByte; begin LPtr := Pointer(FieldTable); if (Assigned(LPtr)) then begin LPtr := PVmtFieldTable(LPtr).Tail; end; Result := Pointer(LPtr); end; function TClassTypeData.GetMethodTableEx: PVmtMethodTableEx; var LPtr: PByte; begin LPtr := Pointer(MethodTable); if (Assigned(LPtr)) then begin LPtr := PVmtMethodTable(LPtr).Tail; end; Result := Pointer(LPtr); end; function TClassTypeData.GetPropDataEx: PPropDataEx; begin Result := PropData.Tail; end; function TClassTypeData.GetAttrDataRec: PAttrData; begin Result := PropDataEx.Tail; end; function TClassTypeData.GetArrayPropData: PArrayPropData; begin Result := GetAttrDataRec.Tail; end; function TClassTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif .EXTENDEDRTTI} { TInterfaceTypeData } function TInterfaceTypeData.GetMethodTable: PIntfMethodTable; begin Result := UnitName.Tail; end; {$ifdef EXTENDEDRTTI} function TInterfaceTypeData.GetAttrDataRec: PAttrData; begin Result := MethodTable.GetAttrDataRec; end; function TInterfaceTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} { TDynArrayTypeData } function TDynArrayTypeData.GetArrElType: PTypeInfo; begin Result := PTypeInfoRef(UnitName.Tail^).Value; end; {$ifdef EXTENDEDRTTI} function TDynArrayTypeData.GetAttrDataRec: PAttrData; var LPtr: PByte; begin LPtr := UnitName.Tail; Inc(LPtr, SizeOf(PTypeInfoRef)); Result := Pointer(LPtr); end; function TDynArrayTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} { TArrayTypeData } {$ifdef EXTENDEDRTTI} function TArrayTypeData.GetAttrDataRec: PAttrData; var LPtr: PByte; begin LPtr := Pointer(@Dims); Inc(LPtr, NativeUInt(DimCount) * SizeOf(Pointer)); Result := Pointer(LPtr); end; function TArrayTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; {$endif} { TRecordTypeData } {$ifdef EXTENDEDRTTI} function TRecordTypeData.GetOptions: PRecordTypeOptions; var LPtr: PByte; begin LPtr := Pointer(@ManagedFields); Inc(LPtr, NativeUInt(ManagedFieldCount) * SizeOf(TManagedField)); Result := Pointer(LPtr); end; function TRecordTypeData.GetFields: PRecordTypeFields; begin Result := Options.Tail; end; function TRecordTypeData.GetAttrDataRec: PAttrData; begin Result := Fields.Tail; end; function TRecordTypeData.GetAttrData: PAttrData; begin Result := GetAttrDataRec.Value; end; function TRecordTypeData.GetMethods: PRecordTypeMethods; begin Result := GetAttrDataRec.Tail; end; {$endif .EXTENDEDRTTI} { TRttiRangeData } function TRttiRangeData.GetCount: Cardinal; begin Result := F.UHigh - F.ULow + 1; end; function TRttiRangeData.GetCount64: UInt64; begin Result := F.U64High - F.U64Low + 1; end; initialization finalization MemoryBuffers := nil; end.
namespace org.me.listviewapp; { This is a ListActivity descendant and so has no layout file It automatically gets an item click virtual method, but also hooks up an item long click handler This is also hooked up to an adapter to give fast-scrolling The adapter is either a standard array adapter or a custom indexed array adapter, based on the value of a shared preference. The shared preference can be edited by using the menu to invoke a preference display/edit activity } interface uses android.app, android.content, android.os, android.view, android.widget, android.preference, android.util, android.net; type ListViewActivity2 = public class(ListActivity) private const SETTINGS_ID = 1; var sharedPrefs: SharedPreferences; var useCustomAdapter: Boolean; protected method onActivityResult(requestCode, resultCode: Integer; data: Intent); override; method onListItemClick(l: ListView; v: View; position: Integer; id: Int64); override; public method onCreate(savedInstanceState: Bundle); override; method onCreateOptionsMenu(menu: Menu): Boolean; override; method onOptionsItemSelected(item: MenuItem): Boolean; override; method listView_ItemLongClick(parent: AdapterView; v: View; position: Integer; id: Int64): Boolean; end; implementation method ListViewActivity2.onCreate(savedInstanceState: Bundle); begin inherited; //No content view resource loaded //Set up a list header ListView.addHeaderView(LayoutInflater.inflate(R.layout.listview_header, nil)); //Add a divider between the header and the list ListView.HeaderDividersEnabled := true; //Add in the fast-scroll 'thumb bar' button ListView.FastScrollEnabled := true; var countries := Resources.StringArray[R.array.countries]; //Check if shared preference indicates we need a custom adapter sharedPrefs := PreferenceManager.getDefaultSharedPreferences(Self); useCustomAdapter := sharedPrefs.getBoolean(ListViewActivitySettingsActivity.AdapterPreference, false); if useCustomAdapter then ListView.Adapter := new ArrayAdapterWithSections<String>(self, R.layout.listitem_twolines, Android.R.id.text1, countries) else ListView.Adapter := new ArrayAdapter(self, R.layout.listitem_twolines, Android.R.id.text1, countries); ListView.OnItemLongClickListener := new interface AdapterView.OnItemLongClickListener(onItemLongClick := @listView_ItemLongClick); end; method ListViewActivity2.onCreateOptionsMenu(menu: Menu): Boolean; begin //Create a single item menu shown via the Menu h/w button var item := menu.add(0, SETTINGS_ID, 0, R.string.list_activity_settings); //Options menu items support icons item.Icon := Android.R.drawable.ic_menu_preferences; Result := true; end; method ListViewActivity2.onOptionsItemSelected(item: MenuItem): Boolean; begin //When menu item is selected... if item.ItemId = SETTINGS_ID then begin //... invoke the settings activity, which will return us a result startActivityForResult(new Intent(Self, typeOf(ListViewActivitySettingsActivity)), SETTINGS_ID); exit true end; exit false; end; method ListViewActivity2.onActivityResult(requestCode, resultCode: Integer; data: Intent); begin inherited; //Execute logic herein when the settings activity returns if requestCode = SETTINGS_ID then begin //Check setting and restart activity if necessary var newUseCustomAdapter := sharedPrefs.getBoolean(ListViewActivitySettingsActivity.AdapterPreference, false); if newUseCustomAdapter <> useCustomAdapter then begin finish; startActivity(new Intent(Self, typeOf(ListViewActivity2))); end end; end; method ListViewActivity2.onListItemClick(l: ListView; v: View; position: Integer; id: Int64); begin //Clicking a country generates a short toast message if v is TwoLineListItem then begin var country := TwoLineListItem(v).Text1.Text.toString; Toast.makeText(self, country, Toast.LENGTH_SHORT).show end end; method ListViewActivity2.listView_ItemLongClick(parent: AdapterView; v: View; position: Integer; id: Int64): Boolean; begin //Long-clicking a country creates a URL to display it in Google Maps, //then asks Android to view the URL in a suitable application if v is TwoLineListItem then begin var country := TwoLineListItem(v).Text1.Text.toString; startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse(WideString.format('http://maps.google.com/?t=h&q=%s', country.replace(WideString(' '), '%20'))))) end end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFUrlrequestClient; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefUrlrequestClientOwn = class(TCefBaseRefCountedOwn, ICefUrlrequestClient) protected procedure OnRequestComplete(const request: ICefUrlRequest); virtual; procedure OnUploadProgress(const request: ICefUrlRequest; current, total: Int64); virtual; procedure OnDownloadProgress(const request: ICefUrlRequest; current, total: Int64); virtual; procedure OnDownloadData(const request: ICefUrlRequest; data: Pointer; dataLength: NativeUInt); virtual; function OnGetAuthCredentials(isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; public constructor Create; virtual; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFUrlRequest, uCEFAuthCallback; procedure cef_url_request_client_on_request_complete(self: PCefUrlRequestClient; request: PCefUrlRequest); stdcall; begin with TCefUrlrequestClientOwn(CefGetObject(self)) do OnRequestComplete(TCefUrlRequestRef.UnWrap(request)); end; procedure cef_url_request_client_on_upload_progress(self: PCefUrlRequestClient; request: PCefUrlRequest; current, total: Int64); stdcall; begin with TCefUrlrequestClientOwn(CefGetObject(self)) do OnUploadProgress(TCefUrlRequestRef.UnWrap(request), current, total); end; procedure cef_url_request_client_on_download_progress(self: PCefUrlRequestClient; request: PCefUrlRequest; current, total: Int64); stdcall; begin with TCefUrlrequestClientOwn(CefGetObject(self)) do OnDownloadProgress(TCefUrlRequestRef.UnWrap(request), current, total); end; procedure cef_url_request_client_on_download_data(self: PCefUrlRequestClient; request: PCefUrlRequest; const data: Pointer; data_length: NativeUInt); stdcall; begin with TCefUrlrequestClientOwn(CefGetObject(self)) do OnDownloadData(TCefUrlRequestRef.UnWrap(request), data, data_length); end; function cef_url_request_client_get_auth_credentials(self: PCefUrlRequestClient; isProxy: Integer; const host: PCefString; port: Integer; const realm, scheme: PCefString; callback: PCefAuthCallback): Integer; stdcall; begin with TCefUrlrequestClientOwn(CefGetObject(self)) do Result := Ord(OnGetAuthCredentials(isProxy <> 0, CefString(host), port, CefString(realm), CefString(scheme), TCefAuthCallbackRef.UnWrap(callback))); end; constructor TCefUrlrequestClientOwn.Create; begin inherited CreateData(SizeOf(TCefUrlrequestClient)); with PCefUrlrequestClient(FData)^ do begin on_request_complete := cef_url_request_client_on_request_complete; on_upload_progress := cef_url_request_client_on_upload_progress; on_download_progress := cef_url_request_client_on_download_progress; on_download_data := cef_url_request_client_on_download_data; get_auth_credentials := cef_url_request_client_get_auth_credentials; end; end; procedure TCefUrlrequestClientOwn.OnDownloadData(const request: ICefUrlRequest; data: Pointer; dataLength: NativeUInt); begin end; procedure TCefUrlrequestClientOwn.OnDownloadProgress( const request: ICefUrlRequest; current, total: Int64); begin end; function TCefUrlrequestClientOwn.OnGetAuthCredentials(isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; begin Result := False; end; procedure TCefUrlrequestClientOwn.OnRequestComplete( const request: ICefUrlRequest); begin end; procedure TCefUrlrequestClientOwn.OnUploadProgress( const request: ICefUrlRequest; current, total: Int64); begin end; end.
unit uFhtHelper; {$I ..\Include\IntXLib.inc} interface uses uConstants, uXBits, uDigitHelper, {$IFDEF DEBUG} uIntX, {$ENDIF DEBUG} uIntXLibTypes; type /// <summary> /// Contains helping methods to work with FHT (Fast Hartley Transform). /// FHT is a better alternative of FFT (Fast Fourier Transform) - at least for <see cref="TIntX" />. /// </summary> TFhtHelper = class sealed(TObject) strict private type /// <summary> /// Trigonometry values. /// </summary> TTrigValues = record private /// <summary> /// Sin value from <see cref="TFhtHelper.F_sineTable" />. /// </summary> TableSin: Double; /// <summary> /// Cos value from <see cref="TFhtHelper.F_sineTable" />. /// </summary> TableCos: Double; /// <summary> /// Sin value. /// </summary> Sin: Double; /// <summary> /// Cos value. /// </summary> Cos: Double; end; /// <summary> /// Pointer to our Record (TTrigValues). /// </summary> PTrigValues = ^TTrigValues; private /// <summary> /// Fills sine table for FHT. /// </summary> /// <param name="sineTable">Sine table to fill.</param> class procedure FillSineTable(var sineTable: TIntXLibDoubleArray); static; /// <summary> /// Performs FHT "in place" for given double array slice. /// Fast version for length = 4. /// </summary> /// <param name="slice">Double array slice.</param> class procedure Fht4(slice: PDouble); static; /// <summary> /// Performs reverse FHT "in place" for given double array slice. /// Fast version for length = 8. /// </summary> /// <param name="slice">Double array slice.</param> class procedure ReverseFht8(slice: PDouble); static; /// <summary> /// Performs "butterfly" operation for <see cref="TFhtHelper.Fht(PDouble,UInt32,Integer)" />. /// </summary> /// <param name="slice1">First data array slice.</param> /// <param name="slice2">Second data array slice.</param> /// <param name="index1">First slice index.</param> /// <param name="index2">Second slice index.</param> /// <param name="Cos">Cos value.</param> /// <param name="Sin">Sin value.</param> class procedure FhtButterfly(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); static; /// <summary> /// Performs "butterfly" operation for <see cref="TFhtHelper.ReverseFht(PDouble,UInt32,Integer)" />. /// </summary> /// <param name="slice1">First data array slice.</param> /// <param name="slice2">Second data array slice.</param> /// <param name="index1">First slice index.</param> /// <param name="index2">Second slice index.</param> /// <param name="Cos">Cos value.</param> /// <param name="Sin">Sin value.</param> class procedure ReverseFhtButterfly(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); static; /// <summary> /// Performs "butterfly" operation for <see cref="TFhtHelper.ReverseFht(PDouble,UInt32,Integer)" />. /// Another version. /// </summary> /// <param name="slice1">First data array slice.</param> /// <param name="slice2">Second data array slice.</param> /// <param name="index1">First slice index.</param> /// <param name="index2">Second slice index.</param> /// <param name="Cos">Cos value.</param> /// <param name="Sin">Sin value.</param> class procedure ReverseFhtButterfly2(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); static; /// <summary> /// Initializes trigonometry values for FHT. /// </summary> /// <param name="valuesPtr">Values to init.</param> /// <param name="lengthLog2">Log2(processing slice length).</param> class procedure GetInitialTrigValues(valuesPtr: PTrigValues; lengthLog2: Integer); /// <summary> /// Generates next trigonometry values for FHT basing on previous ones. /// </summary> /// <param name="valuesPtr">Current trig values.</param> class procedure NextTrigValues(valuesPtr: PTrigValues); public /// <summary> /// Class Constructor. /// </summary> class constructor Create(); /// <summary> /// SQRT(2.0). /// </summary> /// <returns>SquareRoot of 2.0</returns> class function Sqrt2: Double; static; /// <summary> /// SQRT(2.0) / 2. /// </summary> /// <returns>(SquareRoot of 2.0) / 2</returns> class function Sqrt2Div2: Double; static; /// <summary> /// Converts <see cref="TIntX" /> digits into real representation (used in FHT). /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength"><paramref name="digits" /> length.</param> /// <param name="newLength">Multiplication result length (must be pow of 2).</param> /// <returns>Double array.</returns> class function ConvertDigitsToDouble(digits: TIntXLibUInt32Array; mlength: UInt32; newLength: UInt32): TIntXLibDoubleArray; overload; static; /// <summary> /// Converts <see cref="TIntX" /> digits into real representation (used in FHT). /// </summary> /// <param name="digitsPtr">Big integer digits.</param> /// <param name="mlength"><paramref name="digitsPtr" /> length.</param> /// <param name="newLength">Multiplication result length (must be pow of 2).</param> /// <returns>Double array.</returns> class function ConvertDigitsToDouble(digitsPtr: PCardinal; mlength: UInt32; newLength: UInt32): TIntXLibDoubleArray; overload; static; /// <summary> /// Converts real digits representation (result of FHT) into usual <see cref="TIntX" /> digits. /// </summary> /// <param name="marray">Real digits representation.</param> /// <param name="mlength"><paramref name="marray" /> length.</param> /// <param name="digitsLength">New digits array length (we always do know the upper value for this array).</param> /// <param name="digitsRes">Big integer digits.</param> class procedure ConvertDoubleToDigits(marray: TIntXLibDoubleArray; mlength: UInt32; digitsLength: UInt32; digitsRes: TIntXLibUInt32Array); overload; static; /// <summary> /// Converts real digits representation (result of FHT) into usual <see cref="TIntX" /> digits. /// </summary> /// <param name="slice">Real digits representation.</param> /// <param name="mlength"><paramref name="slice" /> length.</param> /// <param name="digitsLength">New digits array length (we always do know the upper value for this array).</param> /// <param name="digitsResPtr">Resulting digits storage.</param> /// <returns>Big integer digits (dword values).</returns> class procedure ConvertDoubleToDigits(slice: PDouble; mlength: UInt32; digitsLength: UInt32; digitsResPtr: PCardinal); overload; static; /// <summary> /// Performs FHT "in place" for given double array. /// </summary> /// <param name="marray">Double array.</param> /// <param name="mlength">Array length.</param> class procedure Fht(marray: TIntXLibDoubleArray; mlength: UInt32); overload; static; /// <summary> /// Performs FHT "in place" for given double array slice. /// </summary> /// <param name="slice">Double array slice.</param> /// <param name="mlength">Slice length.</param> /// <param name="lengthLog2">Log2(<paramref name="mlength" />).</param> class procedure Fht(slice: PDouble; mlength: UInt32; lengthLog2: Integer); overload; static; /// <summary> /// Multiplies two FHT results and stores multiplication in first one. /// </summary> /// <param name="data">First FHT result.</param> /// <param name="data2">Second FHT result.</param> /// <param name="mlength">FHT results length.</param> class procedure MultiplyFhtResults(data: TIntXLibDoubleArray; data2: TIntXLibDoubleArray; mlength: UInt32); overload; static; /// <summary> /// Multiplies two FHT results and stores multiplication in first one. /// </summary> /// <param name="slice">First FHT result.</param> /// <param name="slice2">Second FHT result.</param> /// <param name="mlength">FHT results length.</param> class procedure MultiplyFhtResults(slice: PDouble; slice2: PDouble; mlength: UInt32); overload; static; /// <summary> /// Performs FHT reverse "in place" for given double array. /// </summary> /// <param name="marray">Double array.</param> /// <param name="mlength">Array length.</param> class procedure ReverseFht(marray: TIntXLibDoubleArray; mlength: UInt32); overload; static; /// <summary> /// Performs reverse FHT "in place" for given double array slice. /// </summary> /// <param name="slice">Double array slice.</param> /// <param name="mlength">Slice length.</param> /// <param name="lengthLog2">Log2(<paramref name="mlength" />).</param> class procedure ReverseFht(slice: PDouble; mlength: UInt32; lengthLog2: Integer); overload; static; class var /// <summary> /// array used for storing sineTable. for Internal Use. /// </summary> F_sineTable: TIntXLibDoubleArray; const /// <summary> /// DoubleDataBytes. for Internal Use. /// </summary> DoubleDataBytes = Integer(1); /// <summary> /// DoubleDataLengthShift. for Internal Use. /// </summary> DoubleDataLengthShift = Integer(2); /// <summary> /// DoubleDataDigitShift. for Internal Use. /// </summary> DoubleDataDigitShift = Integer(8); /// <summary> /// DoubleDataBaseInt. for Internal Use. /// </summary> DoubleDataBaseInt = Int64(256); /// <summary> /// DoubleDataBase. for Internal Use. /// </summary> DoubleDataBase: Double = 256.0; /// <summary> /// DoubleDataBaseDiv2. for Internal Use. /// </summary> DoubleDataBaseDiv2: Double = 128.0; end; implementation // static class constructor class constructor TFhtHelper.Create(); begin // Initialize SinTable SetLength(F_sineTable, 31); FillSineTable(F_sineTable); end; class function TFhtHelper.Sqrt2: Double; begin result := Sqrt(2.0); end; class function TFhtHelper.Sqrt2Div2: Double; begin result := (Sqrt2 / 2.0); end; class function TFhtHelper.ConvertDigitsToDouble(digits: TIntXLibUInt32Array; mlength: UInt32; newLength: UInt32): TIntXLibDoubleArray; var digitsPtr: PCardinal; begin digitsPtr := @digits[0]; result := ConvertDigitsToDouble(digitsPtr, mlength, newLength); end; class function TFhtHelper.ConvertDigitsToDouble(digitsPtr: PCardinal; mlength: UInt32; newLength: UInt32): TIntXLibDoubleArray; var data: TIntXLibDoubleArray; slice: PDouble; unitCount, i: UInt32; unitDigitsPtr: PByte; carry, dataDigit: Double; begin // Maybe fix newLength (make it the nearest bigger pow of 2) newLength := UInt32(1) shl TBits.CeilLog2(newLength); // For better FHT accuracy we will choose length smaller then dwords. // So new length must be modified accordingly newLength := newLength shl DoubleDataLengthShift; SetLength(data, newLength); slice := @data[0]; // Amount of units pointed by digitsPtr unitCount := mlength shl DoubleDataLengthShift; // Copy all words from digits into new double array unitDigitsPtr := PByte(digitsPtr); i := 0; while i < (unitCount) do begin slice[i] := unitDigitsPtr[i]; Inc(i); end; // Clear remaining double values TDigitHelper.SetBlockDigits(slice + unitCount, newLength - unitCount, 0.0); // FHT (as well as FFT) works more accurate with "balanced" data, so let's balance it carry := 0; i := 0; while ((i < unitCount) or ((i < newLength) and (carry <> 0))) do begin dataDigit := slice[i] + carry; if (dataDigit >= DoubleDataBaseDiv2) then begin dataDigit := dataDigit - DoubleDataBase; carry := 1.0; end else begin carry := 0; end; slice[i] := dataDigit; Inc(i); end; if (carry > 0) then begin slice[0] := slice[0] - carry; end; result := data; end; class procedure TFhtHelper.ConvertDoubleToDigits(marray: TIntXLibDoubleArray; mlength: UInt32; digitsLength: UInt32; digitsRes: TIntXLibUInt32Array); var slice: PDouble; digitsResPtr: PCardinal; begin slice := @marray[0]; digitsResPtr := @digitsRes[0]; ConvertDoubleToDigits(slice, mlength, digitsLength, digitsResPtr); end; class procedure TFhtHelper.ConvertDoubleToDigits(slice: PDouble; mlength: UInt32; digitsLength: UInt32; digitsResPtr: PCardinal); var normalizeMultiplier, carry, dataDigit {$IFDEF DEBUG}, error, maxError {$ENDIF DEBUG} : Double; unitCount, i, digitsCarry, oldDigit: UInt32; carryInt, dataDigitInt: Int64; unitDigitsPtr: PByte; begin // Calculate data multiplier (don't forget about additional div 2) normalizeMultiplier := 0.5 / mlength; // Count of units in digits unitCount := digitsLength shl DoubleDataLengthShift; // Carry and current digit carryInt := 0; {$IFDEF DEBUG} // Rounding error maxError := 0; {$ENDIF DEBUG} // Walk thru all double digits unitDigitsPtr := PByte(digitsResPtr); i := 0; while i < (mlength) do begin // Get data digit (don't forget it might be balanced) dataDigit := slice[i] * normalizeMultiplier; {$IFDEF DEBUG} // Round to the nearest if dataDigit < 0 then begin dataDigitInt := Trunc(dataDigit - 0.5) end else begin dataDigitInt := Trunc(dataDigit + 0.5); end; // Calculate and (maybe) store max error error := Abs(dataDigit - dataDigitInt); if (error > maxError) then begin maxError := error; end; // Add carry dataDigitInt := dataDigitInt + carryInt; {$ELSE} // Round to the nearest if dataDigit < 0 then begin dataDigitInt := Trunc(dataDigit - 0.5) + carryInt end else begin dataDigitInt := Trunc(dataDigit + 0.5) + carryInt; end; {$ENDIF DEBUG} // Get next carry floored; maybe modify data digit carry := dataDigitInt / DoubleDataBase; if (carry < 0) then begin carry := carry + (Trunc(carry) mod Trunc(1.0)); end; carryInt := Trunc(carry); dataDigitInt := dataDigitInt - (carryInt shl DoubleDataDigitShift); if (dataDigitInt < 0) then begin dataDigitInt := dataDigitInt + DoubleDataBaseInt; Dec(carryInt); end; // Maybe add to the digits if (i < unitCount) then begin unitDigitsPtr[i] := Byte(dataDigitInt); end; Inc(i); end; // Last carry must be accounted if (carryInt < 0) then begin digitsResPtr[0] := digitsResPtr[0] - UInt32(-carryInt); end else if (carryInt > 0) then begin digitsCarry := UInt32(carryInt); i := 0; while ((digitsCarry <> 0) and (i < (digitsLength))) do begin oldDigit := digitsResPtr[i]; digitsResPtr[i] := digitsResPtr[i] + digitsCarry; // Check for an overflow if digitsResPtr[i] < oldDigit then digitsCarry := UInt32(1) else begin digitsCarry := UInt32(0); end; Inc(i); end; end; {$IFDEF DEBUG} // Finally store max error in public visible field TIntX._maxFhtRoundErrorCriticalSection.Acquire; try if (maxError > TIntX.MaxFhtRoundError) then begin TIntX.MaxFhtRoundError := maxError; end; finally TIntX._maxFhtRoundErrorCriticalSection.Release; end; {$ENDIF DEBUG} end; class procedure TFhtHelper.Fht(marray: TIntXLibDoubleArray; mlength: UInt32); var slice: PDouble; begin slice := @marray[0]; Fht(slice, mlength, TBits.Msb(mlength)); end; class procedure TFhtHelper.Fht(slice: PDouble; mlength: UInt32; lengthLog2: Integer); var rightSlice: PDouble; lengthDiv2, lengthDiv4, i: UInt32; leftDigit, rightDigit: Double; trigValues: TTrigValues; begin // Special fast processing for mlength = 4 if (mlength = 4) then begin Fht4(slice); Exit; end; // Divide data into 2 recursively processed parts mlength := mlength shr 1; Dec(lengthLog2); rightSlice := slice + mlength; lengthDiv2 := mlength shr 1; lengthDiv4 := mlength shr 2; // Perform initial "butterfly" operations over left and right array parts leftDigit := slice[0]; rightDigit := rightSlice[0]; slice[0] := leftDigit + rightDigit; rightSlice[0] := leftDigit - rightDigit; leftDigit := slice[lengthDiv2]; rightDigit := rightSlice[lengthDiv2]; slice[lengthDiv2] := leftDigit + rightDigit; rightSlice[lengthDiv2] := leftDigit - rightDigit; // Get initial trig values // trigValues := TTrigValues.Create(0); GetInitialTrigValues(@trigValues, lengthLog2); // Perform "butterfly" i := 1; while i < (lengthDiv4) do begin FhtButterfly(slice, rightSlice, i, mlength - i, trigValues.Cos, trigValues.Sin); FhtButterfly(slice, rightSlice, lengthDiv2 - i, lengthDiv2 + i, trigValues.Sin, trigValues.Cos); // Get next trig values NextTrigValues(@trigValues); Inc(i); end; // Final "butterfly" FhtButterfly(slice, rightSlice, lengthDiv4, mlength - lengthDiv4, Sqrt2Div2, Sqrt2Div2); // Finally perform recursive run Fht(slice, mlength, lengthLog2); Fht(rightSlice, mlength, lengthLog2); end; class procedure TFhtHelper.Fht4(slice: PDouble); var d0, d1, d2, d3, d02, d13: Double; begin // Get 4 digits d0 := slice[0]; d1 := slice[1]; d2 := slice[2]; d3 := slice[3]; // Perform fast "butterfly" addition/subtraction for them. // In case when length = 4 we can do it without trigonometry d02 := d0 + d2; d13 := d1 + d3; slice[0] := d02 + d13; slice[1] := d02 - d13; d02 := d0 - d2; d13 := d1 - d3; slice[2] := d02 + d13; slice[3] := d02 - d13; end; class procedure TFhtHelper.MultiplyFhtResults(data: TIntXLibDoubleArray; data2: TIntXLibDoubleArray; mlength: UInt32); var slice, slice2: PDouble; begin slice := @data[0]; slice2 := @data2[0]; MultiplyFhtResults(slice, slice2, mlength); end; class procedure TFhtHelper.MultiplyFhtResults(slice: PDouble; slice2: PDouble; mlength: UInt32); var d11, d12, d21, d22, ad, sd: Double; stepStart, stepEnd, index1, index2: UInt32; begin // Step0 and Step1 slice[0] := slice[0] * (2.0 * slice2[0]); slice[1] := slice[1] * (2.0 * slice2[1]); // Perform all other steps stepStart := 2; stepEnd := 4; while stepStart < (mlength) do begin index1 := stepStart; index2 := stepEnd - 1; while index1 < (stepEnd) do begin d11 := slice[index1]; d12 := slice[index2]; d21 := slice2[index1]; d22 := slice2[index2]; ad := d11 + d12; sd := d11 - d12; slice[index1] := d21 * ad + d22 * sd; slice[index2] := d22 * ad - d21 * sd; index1 := index1 + 2; index2 := index2 - 2; end; stepStart := stepStart * 2; stepEnd := stepEnd * 2; end; end; class procedure TFhtHelper.ReverseFht(marray: TIntXLibDoubleArray; mlength: UInt32); var slice: PDouble; begin slice := @marray[0]; ReverseFht(slice, mlength, TBits.Msb(mlength)); end; class procedure TFhtHelper.ReverseFht(slice: PDouble; mlength: UInt32; lengthLog2: Integer); var rightSlice: PDouble; lengthDiv2, lengthDiv4, i: UInt32; trigValues: TTrigValues; begin // Special fast processing for length = 8 if (mlength = 8) then begin ReverseFht8(slice); Exit; end; // Divide data into 2 recursively processed parts mlength := mlength shr 1; Dec(lengthLog2); rightSlice := slice + mlength; lengthDiv2 := mlength shr 1; lengthDiv4 := mlength shr 2; // Perform recursive run ReverseFht(slice, mlength, lengthLog2); ReverseFht(rightSlice, mlength, lengthLog2); // Get initial trig values // trigValues := TTrigValues.Create(0); GetInitialTrigValues(@trigValues, lengthLog2); // Perform "butterfly" i := 1; while i < (lengthDiv4) do begin ReverseFhtButterfly(slice, rightSlice, i, mlength - i, trigValues.Cos, trigValues.Sin); ReverseFhtButterfly(slice, rightSlice, lengthDiv2 - i, lengthDiv2 + i, trigValues.Sin, trigValues.Cos); // Get next trig values NextTrigValues(@trigValues); Inc(i); end; // Final "butterfly" ReverseFhtButterfly(slice, rightSlice, lengthDiv4, mlength - lengthDiv4, Sqrt2Div2, Sqrt2Div2); ReverseFhtButterfly2(slice, rightSlice, 0, 0, 1.0, 0); ReverseFhtButterfly2(slice, rightSlice, lengthDiv2, lengthDiv2, 0, 1.0); end; class procedure TFhtHelper.ReverseFht8(slice: PDouble); var d0, d1, d2, d3, d4, d5, d6, d7, da01, ds01, da23, ds23, daa0123, dsa0123, das0123, dss0123, da45, ds45, da67, ds67, daa4567, dsa4567: Double; begin // Get 8 digits d0 := slice[0]; d1 := slice[1]; d2 := slice[2]; d3 := slice[3]; d4 := slice[4]; d5 := slice[5]; d6 := slice[6]; d7 := slice[7]; // Calculate add and subtract pairs for first 4 digits da01 := d0 + d1; ds01 := d0 - d1; da23 := d2 + d3; ds23 := d2 - d3; // Calculate add and subtract pairs for first pairs daa0123 := da01 + da23; dsa0123 := da01 - da23; das0123 := ds01 + ds23; dss0123 := ds01 - ds23; // Calculate add and subtract pairs for next 4 digits da45 := d4 + d5; ds45 := (d4 - d5) * Sqrt2; da67 := d6 + d7; ds67 := (d6 - d7) * Sqrt2; // Calculate add and subtract pairs for next pairs daa4567 := da45 + da67; dsa4567 := da45 - da67; // Store digits values slice[0] := daa0123 + daa4567; slice[4] := daa0123 - daa4567; slice[2] := dsa0123 + dsa4567; slice[6] := dsa0123 - dsa4567; slice[1] := das0123 + ds45; slice[5] := das0123 - ds45; slice[3] := dss0123 + ds67; slice[7] := dss0123 - ds67; end; class procedure TFhtHelper.FhtButterfly(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); var d11, d12, temp: Double; begin d11 := slice1[index1]; d12 := slice1[index2]; temp := slice2[index1]; slice1[index1] := d11 + temp; d11 := d11 - temp; temp := slice2[index2]; slice1[index2] := d12 + temp; d12 := d12 - temp; slice2[index1] := d11 * Cos + d12 * Sin; slice2[index2] := d11 * Sin - d12 * Cos; end; class procedure TFhtHelper.ReverseFhtButterfly(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); var d21, d22, temp, temp2: Double; begin d21 := slice2[index1]; d22 := slice2[index2]; temp := slice1[index1]; temp2 := d21 * Cos + d22 * Sin; slice1[index1] := temp + temp2; slice2[index1] := temp - temp2; temp := slice1[index2]; temp2 := d21 * Sin - d22 * Cos; slice1[index2] := temp + temp2; slice2[index2] := temp - temp2; end; class procedure TFhtHelper.ReverseFhtButterfly2(slice1: PDouble; slice2: PDouble; index1: UInt32; index2: UInt32; Cos: Double; Sin: Double); var temp, temp2: Double; begin temp := slice1[index1]; temp2 := slice2[index1] * Cos + slice2[index2] * Sin; slice1[index1] := temp + temp2; slice2[index2] := temp - temp2; end; class procedure TFhtHelper.FillSineTable(var sineTable: TIntXLibDoubleArray); var i, p: Integer; begin i := 0; p := 1; while i < (length(sineTable)) do begin sineTable[i] := Sin(TConstants.PI / p); Inc(i); p := p * 2; end; end; class procedure TFhtHelper.GetInitialTrigValues(valuesPtr: PTrigValues; lengthLog2: Integer); begin valuesPtr^.TableSin := F_sineTable[lengthLog2]; valuesPtr^.TableCos := F_sineTable[lengthLog2 + 1]; valuesPtr^.TableCos := valuesPtr^.TableCos * -2.0 * (valuesPtr^.TableCos); valuesPtr^.Sin := valuesPtr^.TableSin; valuesPtr^.Cos := valuesPtr^.TableCos + 1.0; end; class procedure TFhtHelper.NextTrigValues(valuesPtr: PTrigValues); var oldCos: Double; begin oldCos := valuesPtr^.Cos; valuesPtr^.Cos := valuesPtr^.Cos * valuesPtr^.TableCos - valuesPtr^.Sin * valuesPtr^.TableSin + valuesPtr^.Cos; valuesPtr^.Sin := valuesPtr^.Sin * valuesPtr^.TableCos + oldCos * valuesPtr^.TableSin + valuesPtr^.Sin; end; end.
unit uStudentEditDialog; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, ComCtrls, uModel; type EValidationError = class(Exception); TStudentEditDialog = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; edName: TEdit; edEmail: TEdit; dtpDateOfBirth: TDateTimePicker; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } procedure InitView(const AStudent: IStudent); procedure UpdateModel(const AStudent: IStudent); procedure ValidateView; public class function Edit(const AStudent: IStudent): Boolean; end; implementation {$R *.dfm} { TStudentEditDialog } class function TStudentEditDialog.Edit(const AStudent: IStudent): Boolean; var dlg: TStudentEditDialog; begin dlg := TStudentEditDialog.Create(Application); try dlg.InitView(AStudent); Result := dlg.ShowModal = mrOk; if Result then dlg.UpdateModel(AStudent); finally dlg.Free; end; end; procedure TStudentEditDialog.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ModalResult = mrOk then ValidateView; end; procedure TStudentEditDialog.InitView(const AStudent: IStudent); begin edName.Text := AStudent.Name; edEmail.Text := AStudent.Email; dtpDateOfBirth.Date := AStudent.DateOfBirth; if Trunc(dtpDateOfBirth.Date) = 0 then dtpDateOfBirth.Date := Now; end; procedure TStudentEditDialog.UpdateModel(const AStudent: IStudent); begin AStudent.Name := edName.Text; AStudent.Email := edEmail.Text; AStudent.DateOfBirth := Int(dtpDateOfBirth.Date); end; procedure TStudentEditDialog.ValidateView; begin if edName.Text = '' then begin edName.SetFocus; raise EValidationError.Create('Nome não pode ser vazio!'); end; if edEmail.Text = '' then begin edEmail.SetFocus; raise EValidationError.Create('Email não poder ser vazio!'); end; if dtpDateOfBirth.Date < EncodeDate(1960, 1, 1) then begin dtpDateOfBirth.SetFocus; raise EValidationError.Create('Data inválida'); end; end; end.
namespace SqliteApp; interface uses Foundation, UIKit; type DetailViewController = public class (UIViewController, IUISplitViewControllerDelegate) private fDetailItem: id; method setDetailItem(newDetailItem: id); method configureView; protected public property detailItem: id read fDetailItem write setDetailItem; property detailDescriptionLabel: weak UILabel; property masterPopoverController: UIPopoverController; method viewDidLoad; override; method didReceiveMemoryWarning; override; method splitViewController(splitController: UISplitViewController) willHideViewController(viewController: UIViewController) withBarButtonItem(barButtonItem: UIBarButtonItem) forPopoverController(popoverController: UIPopoverController); method splitViewController(splitController: UISplitViewController) willShowViewController(viewController: UIViewController) invalidatingBarButtonItem(barButtonItem: UIBarButtonItem); end; implementation method DetailViewController.viewDidLoad; begin inherited.viewDidLoad; // Do any additional setup after loading the view, typically from a nib. configureView(); end; method DetailViewController.setDetailItem(newDetailItem: id); begin if fDetailItem ≠ newDetailItem then begin fDetailItem := newDetailItem; configureView(); end; if assigned(masterPopoverController) then masterPopoverController.dismissPopoverAnimated(true); end; method DetailViewController.configureView; begin // Update the user interface for the detail item. if assigned(detailItem) then //detailDescriptionLabel.text := detailItem.description; //bug: why isn't detailDescriptionLabel getting connected from storyboard? end; method DetailViewController.didReceiveMemoryWarning; begin inherited.didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; {$REGION Split view delegate} method DetailViewController.splitViewController(splitController: UISplitViewController) willHideViewController(viewController: UIViewController) withBarButtonItem(barButtonItem: UIBarButtonItem) forPopoverController(popoverController: UIPopoverController); begin barButtonItem:title := 'Master'; navigationItem:setLeftBarButtonItem(barButtonItem) animated(true); masterPopoverController := popoverController; end; method DetailViewController.splitViewController(splitController: UISplitViewController) willShowViewController(viewController: UIViewController) invalidatingBarButtonItem(barButtonItem: UIBarButtonItem); begin // Called when the view is shown again in the split view, invalidating the button and popover controller. navigationItem.setLeftBarButtonItem(nil) animated(true); masterPopoverController := nil; end; {$ENDREGION} end.
unit Dmitry.PathProviders.Network; interface uses System.SysUtils, System.SyncObjs, System.Classes, Winapi.Windows, Vcl.Graphics, Dmitry.Memory, Dmitry.Utils.Files, Dmitry.Utils.Network, Dmitry.Utils.ShellIcons, Dmitry.PathProviders, Dmitry.PathProviders.MyComputer; type TNetworkItem = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TWorkGroupItem = class(TPathItem) protected function InternalGetParent: TPathItem; override; function GetProvider: TPathProvider; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TComputerItem = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TShareItem = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TWorkgroupComputers = class private FComputers: TStrings; FWorkgroup: string; public constructor Create(Workgroup: string; AComputers: TStrings); destructor Destroy; override; property Workgroup: string read FWorkgroup; property Computers: TStrings read FComputers; end; TWorkgroupComputerList = class(TObject) private FSync: TCriticalSection; FList: TList; public constructor Create; destructor Destroy; override; procedure AddWorkGroupContent(Workgroup: string; Computers: TStrings); function GetComputerWorkgroup(ComputerName: string): string; end; TNetworkProvider = class(TPathProvider) private FWorkgroups: TStrings; FSyncW: TCriticalSection; WorkgroupComputers: TWorkgroupComputerList; protected function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override; public constructor Create; destructor Destroy; override; function Supports(Item: TPathItem): Boolean; overload; override; function Supports(Path: string): Boolean; overload; override; function CreateFromPath(Path: string): TPathItem; override; end; implementation uses Dmitry.PathProviders.FileSystem; { TNetworkProvider } destructor TNetworkProvider.Destroy; begin F(FWorkgroups); F(FSyncW); F(WorkgroupComputers); inherited; end; constructor TNetworkProvider.Create; begin inherited; FWorkgroups := TStringList.Create; FSyncW := TCriticalSection.Create; WorkgroupComputers := TWorkgroupComputerList.Create; end; function TNetworkProvider.InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize, PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; var I: Integer; GI: TNetworkItem; Cancel: Boolean; WorkgroupList, ComputerList, ShareList: TStrings; Wg: TWorkGroupItem; CI: TComputerItem; SI: TShareItem; begin inherited; Result := True; Cancel := False; if Item is THomeItem then begin GI := TNetworkItem.CreateFromPath(cNetworkPath, Options, ImageSize); List.Add(GI); end; if Item is TNetworkItem then begin if PacketSize = 0 then PacketSize := 1; WorkgroupList := TStringList.Create; try FillNetLevel(nil, WorkgroupList); FSyncW.Enter; try FWorkgroups.Assign(WorkgroupList); finally FSyncW.Leave; end; for I := 0 to WorkgroupList.Count - 1 do begin Wg := TWorkGroupItem.CreateFromPath(WorkgroupList[I], Options, ImageSize); List.Add(Wg); if List.Count mod PacketSize = 0 then begin if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); if Cancel then Break; end; end; finally F(WorkgroupList); end; end; if Item is TWorkgroupItem then begin if PacketSize = 0 then PacketSize := 5; ComputerList := TStringList.Create; try Result := not ((FindAllComputers(Item.Path, ComputerList) <> 0) and (ComputerList.Count = 0)); WorkgroupComputers.AddWorkGroupContent(Item.Path, ComputerList); for I := 0 to ComputerList.Count - 1 do begin CI := TComputerItem.CreateFromPath(ComputerList[I], Options, ImageSize); List.Add(CI); if List.Count mod PacketSize = 0 then begin if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); if Cancel then Break; end; end; finally F(ComputerList); end; end; if Item is TComputerItem then begin if PacketSize = 0 then PacketSize := 5; ShareList := TStringList.Create; try Result := not ((FindAllComputers(Item.Path, ShareList) <> 0) and (ShareList.Count = 0)); for I := 0 to ShareList.Count - 1 do begin SI := TShareItem.CreateFromPath(ShareList[I], Options, ImageSize); List.Add(SI); if List.Count mod PacketSize = 0 then begin if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); if Cancel then Break; end; end; finally F(ShareList); end; end; if Item is TShareItem then PathProviderManager.Find(TFileSystemProvider).FillChildList(Sender, Item, List, Options, ImageSize, PacketSize, CallBack); if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); end; function TNetworkProvider.Supports(Item: TPathItem): Boolean; begin Result := Item is TNetworkItem; Result := Item is TWorkGroupItem or Result; Result := Item is TComputerItem or Result; Result := Item is TShareItem or Result; Result := Result or Supports(Item.Path); end; function TNetworkProvider.Supports(Path: string): Boolean; var I: Integer; begin Result := IsNetworkServer(Path) or IsNetworkShare(Path) or (Path = cNetworkPath); if not Result then begin FSyncW.Enter; try for I := 0 to FWorkgroups.Count - 1 do if AnsiLowerCase(FWorkgroups[I]) = AnsiLowerCase(Path) then Result := True; finally FSyncW.Leave; end; end; end; function TNetworkProvider.CreateFromPath(Path: string): TPathItem; begin if IsNetworkServer(Path) then Result := TComputerItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0) else if IsNetworkShare(Path) then Result := TShareItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0) else if Path = cNetworkPath then Result := TNetworkItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0) else Result := TWorkGroupItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); end; { TGroupsItem } constructor TNetworkItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FPath := cNetworkPath; FDisplayName := 'Network'; UpdateText; if (Options and PATH_LOAD_NO_IMAGE = 0) and (ImageSize > 0) then LoadImage(Options, ImageSize); end; function TNetworkItem.GetIsDirectory: Boolean; begin Result := True; end; function TNetworkItem.InternalCreateNewInstance: TPathItem; begin Result := TNetworkItem.Create; end; function TNetworkItem.InternalGetParent: TPathItem; begin Result := THomeItem.Create; end; function TNetworkItem.LoadImage(Options, ImageSize: Integer): Boolean; begin F(FImage); UpdateImage(ImageSize); Result := True; end; { TWorkGroupItem } constructor TWorkGroupItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FPath := AnsiUpperCase(APath); FDisplayName := AnsiUpperCase(APath); if (ImageSize > 0) and (Options and PATH_LOAD_NO_IMAGE = 0) then LoadImage(Options, ImageSize); end; function TWorkGroupItem.GetIsDirectory: Boolean; begin Result := True; end; function TWorkGroupItem.GetProvider: TPathProvider; begin Result := PathProviderManager.Find(TNetworkProvider); end; function TWorkGroupItem.InternalCreateNewInstance: TPathItem; begin Result := TWorkGroupItem.Create; end; function TWorkGroupItem.InternalGetParent: TPathItem; begin Result := TNetworkItem.CreateFromPath(cNetworkPath, PATH_LOAD_NO_IMAGE, 0); end; function TWorkGroupItem.LoadImage(Options, ImageSize: Integer): Boolean; begin F(FImage); UpdateImage(ImageSize); Result := True; end; { TComputerItem } constructor TComputerItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FPath := ExcludeTrailingPathDelimiter(APath); FDisplayName := FPath; if (ImageSize > 0) and (Options and PATH_LOAD_NO_IMAGE = 0) then LoadImage(Options, ImageSize); end; function TComputerItem.GetIsDirectory: Boolean; begin Result := True; end; function TComputerItem.InternalCreateNewInstance: TPathItem; begin Result := TComputerItem.Create; end; function TComputerItem.InternalGetParent: TPathItem; var Workgroup: string; Provider: TNetworkProvider; begin Provider := PathProviderManager.Find(TNetworkProvider) as TNetworkProvider; Workgroup := Provider.WorkgroupComputers.GetComputerWorkgroup(FPath); if Workgroup <> '' then Result := TWorkGroupItem.CreateFromPath(Workgroup, PATH_LOAD_NO_IMAGE, 0) else Result := TNetworkItem.CreateFromPath(cNetworkPath, PATH_LOAD_NO_IMAGE, 0); end; function TComputerItem.LoadImage(Options, ImageSize: Integer): Boolean; begin F(FImage); UpdateImage(ImageSize); Result := True; end; { TShareItem } constructor TShareItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FPath := APath; FDisplayName := ExtractFileName(APath); if (Options and PATH_LOAD_NO_IMAGE = 0) and (ImageSize > 0) then LoadImage(Options, ImageSize) end; function TShareItem.GetIsDirectory: Boolean; begin Result := True; end; function TShareItem.InternalCreateNewInstance: TPathItem; begin Result := TShareItem.Create; end; function TShareItem.InternalGetParent: TPathItem; begin Result := TComputerItem.CreateFromPath(ExtractFilePath(ExcludeTrailingPathDelimiter(Path)), PATH_LOAD_NO_IMAGE, 0); end; function TShareItem.LoadImage(Options, ImageSize: Integer): Boolean; begin F(FImage); UpdateImage(ImageSize); Result := True; end; { TWorkgroupComputers } constructor TWorkgroupComputers.Create(Workgroup: string; AComputers: TStrings); var I: Integer; begin FWorkgroup := Workgroup; FComputers := TStringList.Create; for I := 0 to AComputers.Count - 1 do FComputers.Add(AnsiUpperCase(AComputers[I])); end; destructor TWorkgroupComputers.Destroy; begin F(FComputers); inherited; end; { TWorkgroupComputerList } procedure TWorkgroupComputerList.AddWorkGroupContent(Workgroup: string; Computers: TStrings); var I, J: Integer; WGC: TWorkgroupComputers; begin FSync.Enter; try for I := 0 to FList.Count - 1 do begin WGC := TWorkgroupComputers(FList[I]); if AnsiUpperCase(WGC.Workgroup) = AnsiUpperCase(Workgroup) then begin WGC.Computers.Clear; for J := 0 to Computers.Count - 1 do WGC.Computers.Add(AnsiUpperCase(Computers[J])); Exit; end; end; WGC := TWorkgroupComputers.Create(Workgroup, Computers); FList.Add(WGC); finally FSync.Leave; end; end; constructor TWorkgroupComputerList.Create; begin FSync := TCriticalSection.Create; FList := TList.Create; end; destructor TWorkgroupComputerList.Destroy; begin F(FSync); FreeList(FList); inherited; end; function TWorkgroupComputerList.GetComputerWorkgroup( ComputerName: string): string; var I: Integer; begin Result := ''; ComputerName := AnsiUpperCase(ComputerName); FSync.Enter; try for I := 0 to FList.Count - 1 do begin if TWorkgroupComputers(FList[I]).Computers.IndexOf(ComputerName) > -1 then begin Result := TWorkgroupComputers(FList[I]).Workgroup; Break; end; end; finally FSync.Leave; end; end; initialization PathProviderManager.RegisterProvider(TNetworkProvider.Create); PathProviderManager.RegisterSubProvider(TMyComputerProvider, TNetworkProvider, True); end.
unit fre_accesscontrol_app; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FOS_TOOL_INTERFACES, FRE_DB_INTERFACE, FRE_DB_COMMON, fre_accesscontrol_common ; const CHIDE_INTERNAL = true; type { TFRE_COMMON_ACCESSCONTROL_APP } TFRE_COMMON_ACCESSCONTROL_APP=class(TFRE_DB_APPLICATION) protected procedure MyUpdateSitemap (const session: TFRE_DB_UserSession);override; procedure SetupApplicationStructure ; override; public class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; class procedure InstallDBObjects4Domain (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); override; class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); override; function isMultiDomainApp : Boolean; override; published end; procedure Register_DB_Extensions; implementation { TFRE_COMMON_ACCESSCONTROL_APP } procedure TFRE_COMMON_ACCESSCONTROL_APP.SetupApplicationStructure; begin inherited SetupApplicationStructure; InitApp('description','images_apps/accesscontrol/accesscontrol.svg'); AddApplicationModule(TFRE_COMMON_DOMAIN_MOD.create); AddApplicationModule(TFRE_COMMON_USER_MOD.create); AddApplicationModule(TFRE_COMMON_GROUP_MOD.create); AddApplicationModule(TFRE_COMMON_ROLE_MOD.create); end; procedure TFRE_COMMON_ACCESSCONTROL_APP.MyUpdateSitemap(const session: TFRE_DB_UserSession); var SiteMapData : IFRE_DB_Object; conn : IFRE_DB_CONNECTION; pos : Integer; begin conn:=session.GetDBConnection; SiteMapData := GFRE_DBI.NewObject; FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status',FetchAppTextShort(session,'sitemap_main'),'images_apps/accesscontrol/accesscontrol.svg','',0,conn.sys.CheckClassRight4AnyDomain(sr_FETCH,TFRE_COMMON_ACCESSCONTROL_APP)); if session.SysConfig.HasFeature('DOMAIN') and conn.SYS.CheckClassRight4AnyDomain(sr_FETCH,TFRE_COMMON_DOMAIN_MOD) then begin FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Domains',FetchAppTextShort(session,'sitemap_domains'),'images_apps/accesscontrol/domain.svg',TFRE_COMMON_DOMAIN_MOD.ClassName); pos:=0; end else begin pos:=-45; end; FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/User',FetchAppTextShort(session,'sitemap_users'),'images_apps/accesscontrol/user.svg',TFRE_COMMON_USER_MOD.Classname,0,conn.sys.CheckClassRight4AnyDomain(sr_FETCH,TFRE_COMMON_USER_MOD)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Groups',FetchAppTextShort(session,'sitemap_groups'),'images_apps/accesscontrol/group.svg',TFRE_COMMON_GROUP_MOD.Classname,0,conn.sys.CheckClassRight4AnyDomain(sr_FETCH,TFRE_COMMON_GROUP_MOD)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Status/Roles',FetchAppTextShort(session,'sitemap_roles'),'images_apps/accesscontrol/role.svg',TFRE_COMMON_ROLE_MOD.ClassName,0,conn.sys.CheckClassRight4AnyDomain(sr_FETCH,TFRE_COMMON_ROLE_MOD)); FREDB_SiteMap_RadialAutoposition(SiteMapData,pos); session.GetSessionAppData(ClassName).Field('SITEMAP').AsObject := SiteMapData; end; class procedure TFRE_COMMON_ACCESSCONTROL_APP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if (currentVersionId='') then begin currentVersionId:='1.0'; CreateAppText(conn,'caption','Access Control','Access Control','Access Control'); CreateAppText(conn,'user_description','Users','Users','Users'); CreateAppText(conn,'group_description','Groups','Groups','Groups'); CreateAppText(conn,'role_description','Roles','Roles','Roles'); CreateAppText(conn,'domain_description','Domains','Domains','Domains'); CreateAppText(conn,'sitemap_main','Access Control','','Access Control'); CreateAppText(conn,'sitemap_users','Users','','Users'); CreateAppText(conn,'sitemap_groups','Groups','','Groups'); CreateAppText(conn,'sitemap_roles','Roles','','Roles'); CreateAppText(conn,'sitemap_domains','Domains','','Domains'); end; end; class procedure TFRE_COMMON_ACCESSCONTROL_APP.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); var role : IFRE_DB_ROLE; group : IFRE_DB_GROUP; begin inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID); if currentVersionId='' then begin currentVersionId:='1.0'; CheckDbResult(conn.AddGroup('ACADMINS','Access Control Admins','Access Control Admins',domainUID,true),'could not create admins group'); CheckDbResult(conn.AddRole('ADMINUSER','Allowed to create, modify and delete Users','',domainUID,true),'could not add role ADMINUSER'); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSER',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_USER_MOD.GetClassRoleNameFetch ))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSER',domainUID,TFRE_DB_USER.GetClassStdRoles)); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSER',domainUID,TFRE_DB_DOMAIN.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSER',domainUID,TFRE_DB_NOTE.GetClassStdRoles)); CheckDbResult(conn.AddRole('ADMINGROUP','Allowed to create, modify and delete Groups','',domainUID,true),'could not add role ADMINGROUP'); CheckDbResult(conn.AddRoleRightsToRole('ADMINGROUP',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_GROUP_MOD.GetClassRoleNameFetch, TFRE_COMMON_ROLE_MOD.GetClassRoleNameFetch ))); CheckDbResult(conn.AddRoleRightsToRole('ADMINGROUP',domainUID,TFRE_DB_GROUP.GetClassStdRoles)); CheckDbResult(conn.AddRoleRightsToRole('ADMINGROUP',domainUID,TFRE_DB_ROLE.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINGROUP',domainUID,TFRE_DB_DOMAIN.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINGROUP',domainUID,TFRE_DB_StringArray.Create(TFRE_DB_ROLE.GetClassRoleName('assignRole')))); CheckDbResult(conn.AddRole('ADMINUSERGROUP','Allowed to modify Users and assign Groups to Users','',domainUID,true),'could not add role ADMINUSERGROUP'); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_USER_MOD.GetClassRoleNameFetch, TFRE_COMMON_GROUP_MOD.GetClassRoleNameFetch, TFRE_COMMON_ROLE_MOD.GetClassRoleNameFetch ))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_USER.GetClassStdRoles(false,true,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_GROUP.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_ROLE.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_DOMAIN.GetClassStdRoles(false,false,false,true))); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_NOTE.GetClassStdRoles)); CheckDbResult(conn.AddRoleRightsToRole('ADMINUSERGROUP',domainUID,TFRE_DB_StringArray.Create(TFRE_DB_GROUP.GetClassRoleName('assignGroup')))); CheckDbResult(conn.AddRole('ACADMINUSER','Allowed to create, modify and delete Users','',domainUID),'could not add role ACADMINUSER'); CheckDbResult(conn.AddRole('ACADMINGROUP','Allowed to create, modify and delete Groups','',domainUID),'could not add role ACADMINGROUP'); CheckDbResult(conn.AddRole('ACADMINUSERGROUP','Allowed to modify Users and assign Groups to Users','',domainUID),'could not add role ACADMINUSERGROUP'); CheckDbResult(conn.AddRoleRightsToRole('ACADMINUSER',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_ACCESSCONTROL_APP.GetClassRoleNameFetch, TFRE_DB_USER.GetClassRoleName('resetpass'), 'ADMINUSER' ))); CheckDbResult(conn.AddRoleRightsToRole('ACADMINGROUP',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_ACCESSCONTROL_APP.GetClassRoleNameFetch, 'ADMINGROUP' ))); CheckDbResult(conn.AddRoleRightsToRole('ACADMINUSERGROUP',domainUID,TFRE_DB_StringArray.Create( TFRE_COMMON_ACCESSCONTROL_APP.GetClassRoleNameFetch, 'ADMINUSERGROUP' ))); CheckDbResult(conn.AddRolesToGroup('ACADMINS',domainUID,TFRE_DB_StringArray.Create('ACADMINUSER','ACADMINGROUP','ACADMINUSERGROUP')),'could not add roles for group Admins'); CheckDbResult(conn.FetchGroup('ACADMINS',domainUID,group)); if (conn.GetDefaultDomainUID<>domainUID) then begin group.isDisabled:=true; end; CheckDbResult(conn.UpdateGroup(group)); end; end; class procedure TFRE_COMMON_ACCESSCONTROL_APP.RegisterSystemScheme( const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION'); end; function TFRE_COMMON_ACCESSCONTROL_APP.isMultiDomainApp: Boolean; begin Result:=true; end; procedure Register_DB_Extensions; begin fre_accesscontrol_common.Register_DB_Extensions; GFRE_DBI.RegisterObjectClassEx(TFRE_COMMON_ACCESSCONTROL_APP); end; function _getDomainDisplayValues(const conn: IFRE_DB_CONNECTION; const domainIds: TFRE_DB_GUIDArray): TFRE_DB_StringArray; var i : Integer; domainObj: IFRE_DB_Object; begin SetLength(Result,Length(domainIds)); for i := 0 to High(domainIds) do begin if conn.sys.CheckClassRight4DomainId(sr_FETCH,TFRE_DB_DOMAIN,domainIds[i]) then begin CheckDbResult(conn.Fetch(domainIds[i],domainObj)); Result[i]:=domainObj.Field('displayname').AsString; end else begin Result[i]:='-'; end; end; end; end.
unit MenuPrincipal; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, LblEffct, DB, DBTables, Buttons, Grids, DBGrids, Registry, inifiles, jpeg, ComCtrls, ToolWin, ADODB, ShellAPI, siComp, siLangRT, uSystemObj, uSystemConst, uOperationSystem, Menus; const MAX_SHORTCUTS = 9; MRBUILD = 625; //622; DBBUILD = 350; //347; type TMenuItem = record CountSubMenu : Integer; Name : string; end; TSubMenuItem = record IDMenu, IDSubMenu : Integer; Image, Shortcut : Integer; Name, Tip : string; Enabled : boolean; end; TMainMenu = class(TForm) quSubMenu: TADOQuery; quSubMenuIDMenu: TIntegerField; quSubMenuIDSubMenu: TIntegerField; quSubMenuName: TStringField; quSubMenuTip: TStringField; quSubMenuParentMenu: TStringField; tmrTime: TTimer; quParamTimerCash: TADOQuery; quParamTimerCashSrvParameter: TStringField; quParamTimerCashSrvValue: TStringField; quParamTimerCashDefaultValue: TStringField; quParamTimerCashDescription: TStringField; tmrCashier: TTimer; tmTestMessage: TTimer; PanelControl: TPanel; PnlPointOfSale: TPanel; pnlUtil: TPanel; pnlOfficeM: TPanel; pnlMaintenace: TPanel; pnlCommission: TPanel; pnlInventory: TPanel; pnlPurchasing: TPanel; pnlMediaResult: TPanel; pnlSalesSupporte: TPanel; lbPOSShortCut: TLabel; Label8: TLabel; Label9: TLabel; lbSaleSupShortCut: TLabel; Label2: TLabel; lbAdvertiseShortCut: TLabel; Label10: TLabel; lbPurchaseShortCut: TLabel; Label11: TLabel; lbInventoryShortCut: TLabel; Label12: TLabel; lbCommissionShortCut: TLabel; Label14: TLabel; lbMaintenanceShortCut: TLabel; Label1: TLabel; lbOMShortCut: TLabel; lblSystemExit: TLabel; lbUtilShortCut: TLabel; pnlExit: TPanel; Label3: TLabel; lbExitShortCut: TLabel; tmrTrialCount: TTimer; quSubMenuEnabled: TBooleanField; siLang: TsiLangRT; pnlLeft: TPanel; Shape7: TShape; pnlSistemInfo: TPanel; lbSisUser: TLabel; lbSisStore: TLabel; quSubMenuShortcut: TIntegerField; quSubMenuImageIndex: TIntegerField; lbSM1: TLabelEffect; lbSM2: TLabelEffect; lbSM3: TLabelEffect; lbSM4: TLabelEffect; lbSM5: TLabelEffect; lbSM6: TLabelEffect; lbSM7: TLabelEffect; lbSM8: TLabelEffect; lbSM9: TLabelEffect; lbSM10: TLabelEffect; lbSM11: TLabelEffect; lbSM12: TLabelEffect; lbSM13: TLabelEffect; Image1: TImage; Image2: TImage; Image3: TImage; Image4: TImage; Image5: TImage; Image6: TImage; Image7: TImage; Image8: TImage; Image9: TImage; Image10: TImage; Image11: TImage; Image12: TImage; Image13: TImage; lbDemo: TLabel; TIP: TLabel; imgCashierOpen: TImage; lblCashier: TLabel; pnlControl: TPanel; pnlShortcuts: TPanel; shpShortCut: TShape; lbShortCuts: TLabel; pnlSCControl: TPanel; pnlSC1: TPanel; imgSC1: TImage; lbSC1: TStaticText; pnlSC2: TPanel; imgSC2: TImage; lbSC2: TStaticText; pnlSC3: TPanel; imgSC3: TImage; lbSC3: TStaticText; pnlSC4: TPanel; imgSC4: TImage; lbSC4: TStaticText; pnlSC6: TPanel; imgSC6: TImage; lbSC6: TStaticText; pnlSC5: TPanel; imgSC5: TImage; lbSC5: TStaticText; pnlSC8: TPanel; imgSC8: TImage; lbSC8: TStaticText; pnlSC9: TPanel; imgSC9: TImage; lbSC9: TStaticText; pnlSC7: TPanel; imgSC7: TImage; lbSC7: TStaticText; pnlSystem: TPanel; shpSystem: TShape; imgManagerClose: TImage; imgManagerOpen: TImage; Label13: TLabel; lbLogIn: TLabel; lblOdblClick: TLabel; imgSystemInfo: TImage; lbSysInfo: TLabel; lbMenuColor: TLabel; imgMenuColor: TImage; pnlHelp: TPanel; shpHelp: TShape; Label6: TLabel; lbTip: TLabel; imgTip: TImage; imgHelp: TImage; lbHelp: TLabel; pnlDiv1: TPanel; Panel1: TPanel; Shape4: TShape; Image14: TImage; lbSM14: TLabelEffect; Shape6: TShape; lblVersion: TLabel; lbModule: TLabel; Label4: TLabel; Shape5: TShape; lbHelpShort: TLabel; lbLogShort: TLabel; lblClockShadow: TLabel; lblClock: TLabel; Panel3: TPanel; imgTop: TImage; Panel2: TPanel; imgClientLogo: TImage; Label5: TLabel; imgLanguage: TImage; imgBackup: TImage; lbBackup: TLabel; imgOnlineHelp: TImage; lbOnlineHelp: TLabel; imgMessage: TImage; lbMessage: TLabel; lbPowered: TLabel; Image15: TImage; lbSM15: TLabelEffect; Image16: TImage; lbSM16: TLabelEffect; lbVersion: TLabel; Image17: TImage; quSubMenuVisible: TBooleanField; PopupMenu1: TPopupMenu; procedure MenuMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SubMenuMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SubMenuMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SubMenuMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SubMenuClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lblSystemExitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btAtuVersaoClick(Sender: TObject); procedure tmrTimeTimer(Sender: TObject); procedure lblCashierDblClick(Sender: TObject); procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure tmrCashierTimer(Sender: TObject); procedure tmTestMessageTimer(Sender: TObject); procedure tmrTrialCountTimer(Sender: TObject); procedure lbDemoClick(Sender: TObject); procedure imgTipClick(Sender: TObject); procedure quSubMenuBeforeOpen(DataSet: TDataSet); procedure lblOdblClickClick(Sender: TObject); procedure imgSystemInfoClick(Sender: TObject); procedure imgHelpClick(Sender: TObject); procedure imgMenuColorClick(Sender: TObject); procedure imgSC1Click(Sender: TObject); procedure imgLanguageClick(Sender: TObject); procedure lbBackupClick(Sender: TObject); procedure imgOnlineHelpClick(Sender: TObject); procedure lbMessageClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure btnReasonClick(Sender: TObject); private { Private declarations } fFirstTime : Boolean; fScreenHelp, fHowToHelp, fOnlineHelpPage : String; OldKeyMode : Boolean; lbOldOverMenu : TLabel; lbOldOverSubMenu : TLabelEffect; OldPoint : TPoint; ID1, ID2 : String; fFchParamType : Integer; procedure ShowSubMenu(Sender: TObject); procedure SetSubMenu(Txt: string; IDSubMenu: integer; Enabled: boolean; Count: integer; Img:Integer); procedure LoadMenu; procedure ConstructMenuMain; procedure MyIdle(Sender: TObject; var Done: Boolean); procedure CallTip; procedure CallHelp; procedure CallOnlineHelp; procedure CallBackup; procedure GetShortCutsImg; procedure SetShortCut(ID, Img:Integer; Text, Hint:String); function ParamDefault(IDMenu, IDSubMenu : Integer):String; public { Public declarations } vtMenu : array[0..50] of TMenuItem; vtSubMenu : array[0..200] of TSubMenuItem; vtShortCuts : array[1..MAX_SHORTCUTS] of String; IDMenu, IDSubMenu : integer; property FchParamType : Integer read fFchParamType write fFchParamType; procedure RefreshColor; end; var MainMenu: TMainMenu; implementation {$R *.DFM} uses uDM, uDMGlobal, uMsgConstant, uSystemTypes, uEncryptFunctions, uFileFunctions, uWebFunctions, uFrmUserMessager, ExitQue, { Close Query Padrao } uPassword, { Password } uBrwModel, { Browse de Modelos } uBrwGroup, { Browse de Grupos de Modelos } uBrwUser, { Browse dos Usuarios do Sistema } uBrwUserType, { Browse de Tipos de Usuario } uBrwInventMovType, { Browse de Tipos Movimentação de Estoque } uBrwCashRegister, { Browse de CashRegister } uBrwCashRegMov, { Browse de CashRegister Movements} uCashRegWidraw, { Cash Register Widraw } uCashRegManager, { Cash Register Close } uFrmParameter, { Parametros } uBrwSpecialPrice, { Browse de Special Prices } uBrwStore, { Browse de Stores } uBrwSaleRequest, { Browse de Sales Request } uQueryInventory, { Query Inventory } uBrwDeliverType, { Browse de Deliver Type } uNewPreSales, { New PreSale } uEditPreSale, { Edit PreSale } uFchParam, { Parametros Locais } uBrwMidia, { browse padrao de midias } uBrwInvoice, { Browse de Invoices } uBrwRepairCli, uBrwRepairInv, uBrwInventoryMov, { Modulo de Inventory Movement } uBrwPurchase, { Browse de Purchases } uBrwNewPO, { Browse de Purchases Orders } uBrwInventory, uBrwTrajeto, uBrwCostType, uBrwTouristGroup, uCashRegOpen, uFrmPagaGuia, uFrmPagaAgencia, uFrmPagaVendedor, uFrmPagaOther, uFchModel, uBrwHotel, uBrwModelTransf, uTourGroupResult, uMenuItem, uFrmInventoryCount, uMsgBox, uAskManager, uInventoryCleanUp, uBrwCotation, uFrmTransferData, uFrmHourResult, uBrwPessoa, uBrwMeioPag, uBrwTaxCategory, uFrmTimeControl, uMediaResults, uBrwColor, uBrwSize, ufrmLanguageMR, ufrmLanguage, uFrmSystemInfo, uParamFunctions, uFrmPricingSetup, PaiDeBrowses, uFrmMainPOS, uFrmBarcodePrint, uFrmAccountCard, uFrmTeleMarketing, uFrmPromotionSetup, ubrwMovDocument, uFrmServiceOrder, MRPuppySettings, TagView, MRPuppyIntegrationCls, AdjustQtyReasonView; procedure TMainMenu.GetShortCutsImg; begin //Help DM.imgSmall.GetBitmap(BTN18_LAMP,imgTip.Picture.Bitmap); DM.imgSmall.GetBitmap(BTN18_HELP,imgHelp.Picture.Bitmap); DM.imgSmall.GetBitmap(BTN18_ONLINEHELP,imgOnlineHelp.Picture.Bitmap); //System DM.imgSmall.GetBitmap(BTN18_COMPUTER,imgSystemInfo.Picture.Bitmap); DM.imgSmall.GetBitmap(BTN18_DISPLAY,imgMenuColor.Picture.Bitmap); DM.imgSmall.GetBitmap(BTM18_FLAGS,imgLanguage.Picture.Bitmap); DM.imgSmall.GetBitmap(BTM18_BACKUP,imgBackup.Picture.Bitmap); DM.imgSmall.GetBitmap(BTM18_BACKUP,imgBackup.Picture.Bitmap); DM.imgSmall.GetBitmap(BTN18_MESSAGE,imgMessage.Picture.Bitmap); end; function TMainMenu.ParamDefault(IDMenu, IDSubMenu : Integer):String; var sMenu, sSubMenu : String; i : integer; bFound : Boolean; begin sMenu := vtMenu[IDMenu].Name; i := 0; bFound := False; while (i <= High(vtSubMenu)) and not bFound do begin If (vtSubMenu[i].IDMenu = IDMenu) and (vtSubMenu[i].IDSubMenu = IDSubMenu) then begin DM.fMainMenu.Image := vtSubMenu[i].Image; DM.fMainMenu.MenuName := sMenu; DM.fMainMenu.SubMenuName := vtSubMenu[i].Name; sSubMenu := vtSubMenu[i].Name; bFound := True; end; inc(i); end; Result := 'MenuCaption='+sMenu +';SubMenuCaption='+sSubMenu+';'; end; procedure TMainMenu.ConstructMenuMain; Var bShow : Boolean; begin With DM.quFreeSQL do begin if Active then Close; SQL.Clear; SQL.Add('SELECT IDMenu, Visible'); SQL.Add('FROM MenuMain (NOLOCK) '); Open; First; While not EOF do begin bShow := FieldByName('Visible').AsBoolean; Case FieldByName('IDMenu').AsInteger of 1 : PnlPointOfSale.Visible := bShow; 2 : pnlSalesSupporte.Visible := bShow; 3 : pnlMediaResult.Visible := bShow; 4 : pnlPurchasing.Visible := bShow; 5 : pnlInventory.Visible := bShow; 6 : pnlCommission.Visible := bShow; 7 : pnlMaintenace.Visible := bShow; 8 : pnlOfficeM.Visible := bShow; 9 : pnlUtil.Visible := bShow; end; Next; end; Close; end; end; procedure TMainMenu.ShowSubMenu(Sender: TObject); var lbMenuItem : TLabel; Idx, Count : Integer; Out : Boolean; procedure ClearImg(img:TImage); begin img.Picture := nil; end; Begin lbMenuItem := TLabel(Sender); Out := False; // Desliga todos os panels do SubMenu lbSM1.Visible := False; lbSM2.Visible := False; lbSM3.Visible := False; lbSM4.Visible := False; lbSM5.Visible := False; lbSM6.Visible := False; lbSM7.Visible := False; lbSM8.Visible := False; lbSM9.Visible := False; lbSM10.Visible := False; lbSM11.Visible := False; lbSM12.Visible := False; lbSM13.Visible := False; lbSM14.Visible := False; lbSM15.Visible := False; lbSM16.Visible := False; ClearImg(Image1); ClearImg(Image2); ClearImg(Image3); ClearImg(Image4); ClearImg(Image5); ClearImg(Image6); ClearImg(Image7); ClearImg(Image8); ClearImg(Image9); ClearImg(Image10); ClearImg(Image11); ClearImg(Image12); ClearImg(Image13); ClearImg(Image14); ClearImg(Image15); ClearImg(Image16); // Seta os Itens do SubMenu Idx := 1; while (Idx <= High(vtSubMenu)) and not Out do Begin if vtSubMenu[Idx].IDMenu = lbMenuItem.Tag then begin for Count := 1 to vtMenu[IDMenu].CountSubMenu do begin SetSubMenu(vtSubMenu[Idx + Count -1].Name, vtSubMenu[Idx + Count -1].IDSubMenu, vtSubMenu[Idx + Count -1].Enabled, Count, vtSubMenu[Idx + Count -1].Image); end; Out := True; end; Inc(Idx); end; end; procedure TMainMenu.SetSubMenu(Txt: string; IDSubMenu: integer; Enabled: boolean; Count: integer; Img : Integer); begin case Count of 1: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM1.caption := Txt; lbSM1.visible := True; lbSM1.Tag := IDSubMenu; Image1.Visible := True; Case IDMenu of 1 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 2 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); 9 : DM.imgSubMenu.GetBitmap(Img,Image1.Picture.Bitmap); End; end; 2: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM2.caption := Txt; lbSM2.visible := True; lbSM2.Tag := IDSubMenu; Case IDMenu of 1 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 2 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 7 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); 9 : DM.imgSubMenu.GetBitmap(Img,Image2.Picture.Bitmap); End; end; 3: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM3.caption := Txt; lbSM3.visible := True; lbSM3.Tag := IDSubMenu; Case IDMenu of 1 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 2 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); 9 : DM.imgSubMenu.GetBitmap(Img,Image3.Picture.Bitmap); End; end; 4: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM4.caption := Txt; lbSM4.visible := True; lbSM4.Tag := IDSubMenu; Case IDMenu of 1 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 2 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); 9 : DM.imgSubMenu.GetBitmap(Img,Image4.Picture.Bitmap); End; end; 5: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM5.caption := Txt; lbSM5.visible := True; lbSM5.Tag := IDSubMenu; Case IDMenu of 1 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 2 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image5.Picture.Bitmap); End; end; 6: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM6.caption := Txt; lbSM6.visible := True; lbSM6.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); 6 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image6.Picture.Bitmap); End; end; 7: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM7.caption := Txt; lbSM7.visible := True; lbSM7.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image7.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image7.Picture.Bitmap); 4 : DM.imgSubMenu.GetBitmap(Img,Image7.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image7.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image7.Picture.Bitmap); End; end; 8: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM8.caption := Txt; lbSM8.visible := True; lbSM8.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image8.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image8.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image8.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image8.Picture.Bitmap); End; end; 9: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM9.caption := Txt; lbSM9.visible := True; lbSM9.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image9.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image9.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image9.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image9.Picture.Bitmap); End; end; 10: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM10.caption := Txt; lbSM10.visible := True; lbSM10.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image10.Picture.Bitmap); 3 : DM.imgSubMenu.GetBitmap(Img,Image10.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image10.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image10.Picture.Bitmap); End; end; 11: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM11.caption := Txt; lbSM11.visible := True; lbSM11.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image11.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image11.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image11.Picture.Bitmap); End; end; 12: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM12.caption := Txt; lbSM12.visible := True; lbSM12.Tag := IDSubMenu; Case IDMenu of 2 : DM.imgSubMenu.GetBitmap(Img,Image12.Picture.Bitmap); 5 : DM.imgSubMenu.GetBitmap(Img,Image12.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image12.Picture.Bitmap); End; end; 13: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM13.caption := Txt; lbSM13.visible := True; lbSM13.Tag := IDSubMenu; Case IDMenu of 5 : DM.imgSubMenu.GetBitmap(Img,Image13.Picture.Bitmap); 8 : DM.imgSubMenu.GetBitmap(Img,Image13.Picture.Bitmap); End; end; 14: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM14.caption := Txt; lbSM14.visible := True; lbSM14.Tag := IDSubMenu; Case IDMenu of 5 : DM.imgSubMenu.GetBitmap(Img,Image14.Picture.Bitmap); End; end; 15: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM15.caption := Txt; lbSM15.visible := True; lbSM15.Tag := IDSubMenu; Case IDMenu of 5 : DM.imgSubMenu.GetBitmap(Img,Image15.Picture.Bitmap); End; end; 16: begin if (not Enabled) and (trim(Txt) <> '') then Txt := '* '+ Txt; lbSM16.caption := Txt; lbSM16.visible := True; lbSM16.Tag := IDSubMenu; Case IDMenu of 5 : DM.imgSubMenu.GetBitmap(Img,Image16.Picture.Bitmap); End; end; end; end; procedure TMainMenu.SubMenuMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var NowKeyMode : Boolean; lbOverSubMenu : TLabelEffect; Idx : integer; NowPoint : TPoint; begin // Guarda a posicao antiga do mouse NowKeyMode := ([ssShift, ssAlt, ssCtrl] = Shift) and (X+Y = 0); NowPoint.X := X; NowPoint.Y := Y; if not OldKeyMode then begin if not NowKeyMode then OldPoint := TLabelEffect(Sender).ClientToScreen(NowPoint); end else begin if not NowKeyMode then begin NowPoint := TLabelEffect(Sender).ClientToScreen(NowPoint); // Testa se mouse se mantem nas mesmas coordenadas if ( (OldPoint.X <> NowPoint.X) or (OldPoint.Y <> NowPoint.Y) ) then OldKeyMode := False else Exit; end; end; if NowKeyMode then OldKeyMode := True; lbOverSubMenu := TlabelEffect(Sender); IDSubMenu := lbOverSubMenu.Tag; if not assigned(lbOldOverSubMenu) then Begin lbOverSubMenu.font.color := DM.fMainMenu.SubMenuHighlight; lbOverSubMenu.Font.Style := [fsBold,fsUnderline]; lbOldOverSubMenu := lbOverSubMenu; end else if lbOverSubMenu <> lbOldOverSubMenu then Begin //lbOldOverSubMenu.Font.Color := clGray; lbOldOverSubMenu.Font.Color := DM.fMainMenu.SubMenuColor; lbOldOverSubMenu.Font.Style := [fsBold]; lbOverSubMenu.font.color := DM.fMainMenu.SubMenuHighlight; lbOverSubMenu.Font.Style := [fsBold,fsUnderline]; lbOldOverSubMenu := lbOverSubMenu; end; // Seta o Tip Idx := 1; while (vtSubMenu[Idx].IDMenu <> IDMenu) or (vtSubMenu[Idx].IDSubMenu <> IDSubMenu) do Inc(Idx); Tip.Caption := vtSubMenu[Idx].Tip; end; procedure TMainMenu.MenuMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var lbOverMenu : TLabel; Image : TImage; NowKeyMode : Boolean; NowPoint : TPoint; begin TIP.Caption := ''; Image := TImage(Sender); lbOverMenu := Tlabel(Sender); NowPoint.X := X; NowPoint.Y := Y; // Guarda a posicao antiga do mouse NowKeyMode := ([ssShift, ssAlt, ssCtrl] = Shift) and (X+Y = 0); if not OldKeyMode then begin if not NowKeyMode then OldPoint := TLabel(Sender).ClientToScreen(NowPoint); end else begin if not NowKeyMode then begin NowPoint := TLabelEffect(Sender).ClientToScreen(NowPoint); // Testa se mouse se mantem nas mesmas coordenadas if ( (OldPoint.X <> NowPoint.X) or (OldPoint.Y <> NowPoint.Y) ) then OldKeyMode := False else Exit; end; end; If NowKeyMode then OldKeyMode := True; If Sender is TImage then IDMenu := Image.Tag else IDMenu := lbOverMenu.Tag; if not assigned(lbOldOverMenu) then Begin lbOldOverMenu := lbOverMenu; if IDMenu < (vtMenu[0].CountSubMenu+1) then begin //lbOverMenu.font.color := clRed; lbOverMenu.font.color := DM.fMainMenu.MenuColorHighlight; lbOverMenu.font.Style := [fsBold]; lbOverMenu.Color := DM.fMainMenu.BackGroundColor; lbOverMenu.Transparent := False; ShowSubMenu(Sender); end else begin //lbOverMenu.font.color := clRed; lbOverMenu.font.color := DM.fMainMenu.MenuColorHighlight; lbOverMenu.font.Style := [fsBold]; lbOverMenu.Color := DM.fMainMenu.BackGroundColor; lbOverMenu.Transparent := False; end; end else if lbOverMenu <> lbOldOverMenu then Begin //lbOldOverMenu.Font.Color := clSilver; lbOldOverMenu.Font.Color := DM.fMainMenu.MenuColor; lbOldOverMenu.font.Style := []; lbOldOverMenu.Color := DM.fMainMenu.BackGroundColor; lbOldOverMenu.Transparent := True; lbOldOverMenu := lbOverMenu; if IDMenu < (vtMenu[0].CountSubMenu+1) then begin //lbOverMenu.font.color := clRed; lbOverMenu.font.color := DM.fMainMenu.MenuColorHighlight; lbOverMenu.font.Style := [fsBold]; lbOverMenu.Transparent := False; ShowSubMenu(Sender); end else begin //lbOverMenu.font.color := clRed; lbOverMenu.font.color := DM.fMainMenu.MenuColorHighlight; lbOverMenu.font.Style := [fsBold]; lbOverMenu.Transparent := False; ShowSubMenu(Sender); end; if assigned(lbOldOverSubMenu) then begin //lbOldOverSubMenu.font.color := clGray; lbOldOverSubMenu.font.color := DM.fMainMenu.SubMenuColor; lbOldOverSubMenu.font.Style := [fsBold]; lbOldOverSubMenu := nil; end; end; end; procedure TMainMenu.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin with TExitQuery.Create(Self) do CanClose := (ShowModal = mrOK); end; procedure TMainMenu.SubMenuMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //TLabelEffect(Sender).EffectStyle := esSunken; end; procedure TMainMenu.SubMenuMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //TLabelEffect(Sender).EffectStyle := LblEffct.esRaised; end; procedure TMainMenu.LoadMenu; var Count, OldMenu, SubCount : Integer; textSubmenu: string; begin // Zera a captura das teclas OldKeyMode := False; //Deixa para a rotina de tratamento das setas do teclado IDSubMenu := 0; OldMenu := 0; with quSubMenu do begin Open; Count := 1; SubCount := 0; while not eof do begin if OldMenu <> quSubMenuIDMenu.AsInteger then begin // Testa se e novo menu vtMenu[quSubMenuIDMenu.AsInteger].Name := quSubMenuParentMenu.AsString; OldMenu := quSubMenuIDMenu.AsInteger; SubCount := 0; end; vtSubMenu[Count].IDMenu := quSubMenuIDMenu.AsInteger; vtSubMenu[Count].IDSubMenu := quSubMenuIDSubMenu.AsInteger; vtSubMenu[Count].Name := quSubMenuName.AsString; vtSubMenu[Count].Tip := quSubMenuTip.AsString; //amfsouza 09.08.2011: to puppytracker integration if ( (vtSubMenu[count].IDSubMenu = 14) and (vtSubMenu[count].IDMenu = 8) ) then vtSubMenu[Count].Enabled := ( DM.fSystem.SrvParam[PARAM_PUPPY_TRACKER_INTEGRATION] = 'True' ) else vtSubMenu[Count].Enabled := quSubMenuEnabled.AsBoolean; vtSubMenu[Count].Image := quSubMenuImageIndex.AsInteger; vtSubMenu[Count].Shortcut := quSubMenuShortcut.AsInteger; Inc(Count); Inc(SubCount); vtMenu[quSubMenuIDMenu.AsInteger].CountSubMenu := SubCount; // Totaliza o total de itens no Menu vtMenu[0].CountSubMenu := quSubMenuIDMenu.AsInteger; //SetShortcuts if ((quSubMenuShortcut.AsInteger)>0) and (quSubMenuShortcut.AsInteger<=MAX_SHORTCUTS) then begin pnlShortcuts.Visible := True; vtShortCuts[quSubMenuShortcut.AsInteger] := 'M='+quSubMenuIDMenu.AsString+';'+ 'S='+quSubMenuIDSubMenu.AsString+';'; // Just to change text to shows the shortcut Employee Files on the right side of screen textSubmenu := quSubMenuName.AsString; if (quSubMenuShortCut.AsInteger = 7) then begin textSubMenu := 'Employee File'; end; SetShortCut(quSubMenuShortcut.AsInteger, quSubMenuImageIndex.AsInteger, textSubmenu,//quSubMenuName.AsString, quSubMenuTip.AsString); end; Next; end; Close; end; end; procedure TMainMenu.SetShortCut(ID, Img:Integer; Text, Hint:String); var fLabel: TLabel; fPanel: TPanel; fImage: TImage; begin fPanel := TPanel(FindComponent('pnlSC'+IntToStr(ID))); if Assigned(fPanel) then fPanel.Visible := True; fLabel := TLabel(FindComponent('lbSC'+IntToStr(ID))); if Assigned(fLabel) then begin fLabel.Caption := Text; fLabel.Hint := Hint; fLabel.Tag := ID end; fImage := TImage(FindComponent('imgSC'+IntToStr(ID))); if Assigned(fImage) then begin DM.imgSubMenu.GetBitmap(Img,fImage.Picture.Bitmap); fImage.Tag := ID; fImage.Hint := Hint; end; end; procedure TMainMenu.FormShow(Sender: TObject); var sVersion : String; fAutoOpen : Boolean; begin // Acerta o timer tmrTimeTimer(nil); Application.OnIdle := MyIdle; // Trial Counter tmrTrialCount.Enabled:= (DM.fSystem.StartMode = SYS_MODULE_TRIAL); //Version % Build DM.fSystem.VerBuild := 'Build ('+IntToStr(DM.fSystem.Build)+'-'+IntToStr(MRBUILD)+')'; lblVersion.Caption := DM.fSystem.VerBuild; //Module Info if DM.fSystem.StartMode = SYS_MODULE_TRIAL then DM.fSystem.Module := 'MainRetail - Premium' else begin case DM.fSystem.StartMode of SYS_MODULE_1, SYS_MODULE_2 : sVersion := 'Basic'; SYS_MODULE_3 : sVersion := 'Premium'; SYS_MODULE_4, SYS_MODULE_5 : sVersion := 'Enterprise'; end; DM.fSystem.Module := 'MainRetail - '+ sVersion ; end; lbModule.Caption := DM.fSystem.Module; // Seta as coordenadas iniciais if not DM.fMainMenu.WindowMode then begin Left := 0; Top := 0; Height := Screen.Height; Width := Screen.Width; end; // Guarda Posicao do mouse inicial GetCursorPos(OldPoint); //Monta o MenuMain ConstructMenuMain; //Acerta o menu LoadMenu; //** Só em tempo de desenvolvimento //lblODblClickDblClick (Self); tmTestMessage.Enabled := True; //Rodrigo - Usado para o Demo. D - Demo, F - Full App, E - Error. if DM.fSystem.StartMode = SYS_ERROR then lbDemo.Visible := False else lbDemo.Visible := (DM.fSystem.StartMode = SYS_MODULE_TRIAL); //if (DM.fSystem.StartMode <> SYS_ERROR) and DM.fSystem.ShowTip then // CallTip; //Display images for shortcust GetShortCutsImg; //Set default param call fFchParamType := PARAM_OPEN_ALL; lbHelpShort.Left := lbHelp.Left + lbHelp.Width + 3; //Verifica se o sistema esta com a chave Valida if DM.fSystem.StartMode <> SYS_ERROR then begin DM.ValidateLicense; end; // Max - 19/10/2006 // Fazer a chamada da SP que processa o saldo de inventário //DM.ProcessInventoryBalance; fAutoOpen := False; fFirstTime := True; case DM.fStartOption of START_LAYAWAY : begin fAutoOpen := True; IDMenu := 1; IDSubMenu := 1; SubMenuClick(lbSM1); end; START_INVENT_TYPE : begin fAutoOpen := True; IDMenu := 5; IDSubMenu := 5; SubMenuClick(lbSM5); end; end; if (not fAutoOpen) and (DM.fSystem.SrvParam[PARAM_ASK_PASSWORD_BEFORE_OPEN_SOFTWARE]) then begin IDMenu := 1; IDSubMenu := 1; SubMenuClick(lbSM1); end; fFirstTime := False; if Assigned(DM.fSystem.Logo) then begin imgTop.Picture.Bitmap := DM.fSystem.Logo.Bitmap; lbPowered.Visible := True; end; end; procedure TMainMenu.CallTip; begin if FileExists(extractfilepath(application.exename)+'MRTip.exe') then ExecuteFile(extractfilepath(application.exename)+'MRTip.exe', IntToStr(IDMenu-1), '', SW_SHOW); end; procedure TMainMenu.CallHelp; begin try ExecuteFile(extractfilepath(application.exename)+fHowToHelp, '', '', SW_SHOW) except MsgBox(MSG_CRT_NO_HELP,vbOkOnly + vbCritical); end; end; procedure TMainMenu.CallBackup; begin if FileExists(extractfilepath(application.exename)+'MRBackup.exe') then ExecuteFile(extractfilepath(application.exename)+'MRBackup.exe', '', '', SW_SHOW) end; procedure TMainMenu.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var IncMenu, IncSubMenu, i : Integer; IsOpenSub, IsClick : Boolean; begin // Testa se chamou a hot key do Exit if (Shift = [ssAlt]) and (Chr(Key) = 'X') then begin Close; Exit; end; IncMenu := 0; IncSubMenu := 0; IsClick := False; // Testa se submenu esta desligado IsOpenSub := (IDSubMenu <> 0); case Key of VK_F1: imgHelpClick(self); VK_F9: lblOdblClickClick(self); VK_DOWN: if IsOpenSub then IncSubMenu := 1 else IncMenu := 1; VK_UP: if IsOpenSub then IncSubMenu := -1 else IncMenu := -1; VK_LEFT: begin IsOpenSub := False; if Assigned(lbOldOverSubMenu) then begin //lbOldOverSubMenu.font.color := clGray; lbOldOverSubMenu.font.color := DM.fMainMenu.SubMenuColor; lbOldOverSubMenu.font.Style := [fsBold]; lbOldOverSubMenu := nil; end; end; VK_RIGHT: begin IDSubMenu := 1; IsOpenSub := True; end; VK_RETURN: begin if IDMenu = (vtMenu[0].CountSubMenu+1) then begin Close; Exit; end else IsClick := IsOpenSub; end; // A, C, D, I, M, P, R, S, T, U, F, E // 65, 67, 68, 73, 77, 80, 82, 83, 84, 85 70 69 MAIUSCULAS // 107, 109, 110, 115, 119, 122, 124, 125, 126, 127 minúsculas //82, 124 : begin IsOpenSub := False; IDMenu := 1; IDSubMenu := 1; end; // F de Point of Sale { 70, 124 : begin IsOpenSub := False; IDMenu := 1; IDSubMenu := 1; end; // F de Point of Sale 83, 125 : begin IsOpenSub := False; IDMenu := 2; IDSubMenu := 1; end;// S de Sales Support 84, 126 : begin IsOpenSub := False; IDMenu := 3; IDSubMenu := 1; end;// T de Advertising 80, 122 : begin IsOpenSub := False; IDMenu := 4; IDSubMenu := 1; end;// P de Purchases 73, 115 : begin IsOpenSub := False; IDMenu := 5; IDSubMenu := 1; end;// I de Inventory 67, 109 : begin IsOpenSub := False; IDMenu := 6; IDSubMenu := 1; end;// C de Commissions 65, 107 : begin IsOpenSub := False; IDMenu := 7; IDSubMenu := 1; end;// A de Office Manager 77, 119 : begin IsOpenSub := False; IDMenu := 8; IDSubMenu := 1; end;// M de Maintenance 85, 127 : begin IsOpenSub := False; IDMenu := 9; IDSubMenu := 1; end;// U de Utilities //68, 110 : begin IsOpenSub := False; IDMenu := 10; IDSubMenu := 1; end;// D de Exit 69, 110 : begin IsOpenSub := False; IDMenu := 10; IDSubMenu := 1; end;// D de Exit} 49,97 : begin IsOpenSub := False; IDMenu := 1; IDSubMenu := 1; end; // 1 de Point of Sale 50,98 : begin IsOpenSub := False; IDMenu := 2; IDSubMenu := 1; end;// 2 de Sales Support 51,99 : begin IsOpenSub := False; IDMenu := 3; IDSubMenu := 1; end;// 3 de Advertising 52,100 : begin IsOpenSub := False; IDMenu := 4; IDSubMenu := 1; end;// 4 de Purchases 53,101 : begin IsOpenSub := False; IDMenu := 5; IDSubMenu := 1; end;// 5 de Inventory 54,102 : begin IsOpenSub := False; IDMenu := 6; IDSubMenu := 1; end;// 6 de Commissions 55,103 : begin IsOpenSub := False; IDMenu := 7; IDSubMenu := 1; end;// 7 de Office Manager 56,104 : begin IsOpenSub := False; IDMenu := 8; IDSubMenu := 1; end;// 8 de Maintenance 57,105 : begin IsOpenSub := False; IDMenu := 9; IDSubMenu := 1; end;// 9 de Utilities 48,96 : begin IsOpenSub := False; IDMenu := 10; IDSubMenu := 1; end;// 0 de Exit else Exit; end; if not IsOpenSub then Tip.Caption := ''; if (IDMenu + IncMenu) > (vtMenu[0].CountSubMenu+1) then IDMenu := 1 else if (IDMenu + IncMenu) = 0 then IDMenu := vtMenu[0].CountSubMenu+1 else Inc(IDMenu, IncMenu); if IDMenu = -1 then IDMenu := vtMenu[0].CountSubMenu+1; if (IDSubMenu + IncSubMenu) > vtMenu[IDMenu].CountSubMenu then IDSubMenu := 1 else if (IDSubMenu + IncSubMenu) = 0 then IDSubMenu := vtMenu[IDMenu].CountSubMenu else Inc(IDSubMenu, IncSubMenu); if (not IsOpenSub) or (vtMenu[IDMenu].CountSubMenu = 0) then IDSubMenu := 0; // For que habilita os menus if not IsOpenSub then begin for i := 0 to ComponentCount - 1 do if (Components[i] is TLabel) and (not (Components[i] is TLabelEffect)) and (TLabel(Components[i]).Tag = IDMenu) then begin MenuMouseMove(TObject(Components[i]), [ssShift, ssAlt, ssCtrl], 0, 0); Exit; end end else begin for i := 0 to ComponentCount - 1 do if (Components[i] is TLabelEffect) and (TLabelEffect(Components[i]).Tag = IDSubMenu) then begin if IsClick then begin SubMenuMouseDown(TObject(Components[i]), mbLeft, [ssShift], 0, 0); SubMenuClick(TObject(Components[i])); SubMenuMouseUp(TObject(Components[i]), mbLeft, [ssShift], 0, 0); end else SubMenuMouseMove(TObject(Components[i]), [ssShift, ssAlt, ssCtrl], 0, 0); Exit; end; end; end; procedure TMainMenu.SubMenuClick(Sender: TObject); var MyCmdLine, sDB, sMyParam : String; i, IDCashRegMov, iIDPessoa: integer; //amfsouza September 10, 2012 msgCashOpen: String; cashRegName: String; // Antonio Marcos, May 01, 2015: MR-173 :a hook to window hMRWindow: HWND; titleMRWindow: array [0..255] of char; sizeTitleMRWindow: Integer; begin // Validating if Module is Enabled for i:= 0 to High(vtSubMenu) do begin if (vtSubMenu[i].IDMenu = IDMenu) and (vtSubMenu[i].IDSubMenu = IDSubMenu) then begin if not(vtSubMenu[i].Enabled) then begin MsgBox(MSG_EXC_MODULE_DISABLE, vbOKOnly + vbInformation); Exit; end; break; end; end; {Aqui entra o tratamento da senha} Password.MenuName := vtMenu[IDmenu].Name; Password.SubMenuName := TLabel(Sender).Caption; if ((IDMenu = 9) and (IDSubMenu >= 5)) or //((IDMenu = 1) and (IDSubMenu = 1)) or // ** Point of Sale / Cash Register ((IDMenu = 9) and (IDSubMenu = 1)) or // Help ((IDMenu = 2) and (IDSubMenu = 1)) or // ** Sales Suporte / Hold ((IDMenu = 7) and (IDSubMenu = 2)) or // Accounting Password.Start(IDMenu, IDSubMenu) then begin if not (((IDMenu = 2) and (IDSubMenu = 1)) or ((IDMenu = 7) and (IDSubMenu = 2)) or ((IDMenu = 9) and (IDSubMenu >= 5)) or ((IDMenu = 9) and (IDSubMenu = 1))) then if not Password.CanAccessMenu(Password.MyMenuItem, Password.MySubMenuItem, DM.fUser.Password) then begin MsgBox(MSG_INF_CANNOT_ACCESS_MODULE, vbOKOnly + vbInformation); Exit; end; sMyParam := ParamDefault(IDMenu, IDSubMenu); case (IDMenu * 1000 + IDSubMenu * 10) of //--------------------------------------------------------------- //--------------------- Point Of Sale ---------------------------- 1010: begin // ** Cash Register { amfsouza September 10, 2012 if DM.ExecRunning > 1 then begin MsgBox(MSG_INF_MORE_THAN_ONE_EXEC, vbOKOnly + vbInformation); Exit; end; } if ( dm.IsCashRegisterOpen(dm.fCashRegister.IDDefault) ) then begin msgCashOpen := 'Cash Register %s shows as already being open.'+#13#10+ 'Close the other instance and then try again.'+#13#10 + 'If you know there is no other instance, you could override it. Do you wish override ?'; cashRegName := dm.getCashRegisterName(dm.fCashRegister.IDDefault); msgCashOpen := format(msgCashOpen, [cashRegName]); if ( Application.MessageBox(PChar(msgCashOpen), 'Cash Register Warning', MB_YESNO + MB_ICONWARNING) = mrYes ) then begin // Antonio Marcos: MR-173 dm.setCashRegister(dm.fCashRegister.IDDefault, false); // getting the previous instance hMRWindow := FindWindow('TFrmMainPOS', nil); sizeTitleMRWindow := 256; GetWindowText(hMRWindow, titleMRWindow, sizeTitleMRWindow); // ShowMessage('closing the window: ' + titleMRWindow); // close previous instance sendMessage(hMRWindow, WM_SYSCOMMAND, SC_CLOSE, 0); end else begin exit; end; end else begin // Antonio Marcos: MR-155 dm.setCashRegister(dm.fCashRegister.IDDefault, true); hMRWindow := FindWindow('TFrmMainPOS', nil); sizeTitleMRWindow := 256; GetWindowText(hMRWindow, titleMRWindow, sizeTitleMRWindow); // ShowMessage('closing the window: ' + titleMRWindow); end; Screen.Cursor := crHourGlass; // Modulo de controle de cash register case DM.CheckCashRegState(DM.fCashRegister.IDDefault, IDCashRegMov) of CASHREG_OPEN: begin // Caixa aberta, abre tela de Manipulação case DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] of CASHREG_TYPE_FULL_POS : begin with TFrmMainPOS.Create(Self) do Start(SALE_CASHREG, IDCashRegMov); end; else with TCashRegManager.Create(Self) do Start(IDCashRegMov, DM.fCashRegister.IDDefault, DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE], True); end; end; CASHREG_CLOSE: begin // Caixa Fechada, abre tela da abertura with TCashRegOpen.Create(Self) do Start(DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE], DM.fCashRegister.IDDefault); end; end; Screen.Cursor := crDefault; end; 1020: begin Screen.Cursor := crHourGlass; with TbrwCashRegMov.Create(Self) do // ** Cash Register History begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 1030: begin Screen.Cursor := crHourGlass; with TBrwInvoice.Create(Self) do // ** Invoice History begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 1040: begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; 1050: begin Screen.Cursor := crHourGlass; with TbrwCashRegister.Create(Self) do // ** Maintenance begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Sales Support ---------------------------- 2010: begin Screen.Cursor := crHourGlass; with TFrmEditPreSale.Create(Self) do // ** Hold Start(SALE_PRESALE); Screen.Cursor := crDefault; end; 2020: begin Screen.Cursor := crHourGlass; with TQueryInventory.Create(Self) do // ** View Inventory begin btDetail.Visible := False; ShowModal; end; Screen.Cursor := crDefault; end; 2030: begin Screen.Cursor := crHourGlass; with TBrwSaleRequest.Create(Self) do // ** Sales Person Request begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 2040: begin Screen.Cursor := crHourGlass; with TFrmEditPreSale.Create(Self) do // ** UnLock Hold Start(SALE_UNLOCK_PRESALE); Screen.Cursor := crDefault; end; 2050: begin Screen.Cursor := crHourGlass; with TbrwRepairCli.Create(Self) do // ** Customer Repair begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 2060: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Customers File begin quTreeView.Parameters.ParambyName('Path').Value := '.001%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 2070: begin Screen.Cursor := crHourGlass; with TFrmHourResult.Create(Self) do // ** Sales Graphs ShowModal; Screen.Cursor := crDefault; end; 2080: begin Screen.Cursor := crHourGlass; with TFrmAccountCard.Create(Self) do //Gift Start; Screen.Cursor := crDefault; end; 2090: begin Screen.Cursor := crHourGlass; with TFrmTeleMarketing.Create(Self) do //Telemarketing Start; Screen.Cursor := crDefault; end; 2100: begin Screen.Cursor := crHourGlass; with TFrmPromotionSetup.Create(Self) do //Promotions Start; Screen.Cursor := crDefault; end; 2110: begin Screen.Cursor := crHourGlass; with TbrwMovDocument.Create(Self) do //Document Control Start; Screen.Cursor := crDefault; end; 2120: begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; //------------------------------------------------------------------- //--------------------- Advertising ------------------------------ 3010: begin Screen.Cursor := crHourGlass; with TbrwMidia.Create(Self) do // Media begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3020: begin Screen.Cursor := crHourGlass; with TMediaResults.Create(Self) do //Media Results Start; Screen.Cursor := crDefault; end; 3030: begin Screen.Cursor := crHourGlass; with TBrwTrajeto.Create(Self) do // ** Routes begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3040: begin Screen.Cursor := crHourGlass; with TBrwCostType.Create(Self) do // ** Expence Category begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3050: begin Screen.Cursor := crHourGlass; with TBrwTouristGroup.Create(Self) do // ** Agency Groups begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3060: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Outside Agents begin quTreeView.Parameters.ParambyName('Path').Value := '.003.002%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3070: begin Screen.Cursor := crHourGlass; with TBrwHotel.Create(Self) do // ** Hotels begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3080: begin Screen.Cursor := crHourGlass; with TTourGroupResult.Create(Self) do // ** Agency Group Result ShowModal; Screen.Cursor := crDefault; end; 3090: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Agency File begin quTreeView.Parameters.ParambyName('Path').Value := '.003.003%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 3100: begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Purchasing --------------------------- 4010: begin Screen.Cursor := crHourGlass; with TBrwCotation.Create(Self) do // ** Price Quotes begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 4020: begin Screen.Cursor := crHourGlass; with TBrwNewPO.Create(Self) do // ** Purchase Orders Start; Screen.Cursor := crDefault; end; 4030: begin Screen.Cursor := crHourGlass; with TbrwPurchase.Create(Self) do // ** Pre Receiving begin sParam := sMyParam; iPurStatus := 1; //Pre Receive Start; end; Screen.Cursor := crDefault; end; 4040: begin Screen.Cursor := crHourGlass; with TbrwPurchase.Create(Self) do // ** Final Receiving begin sParam := sMyParam; iPurStatus := 2; //Final Receive Start; end; Screen.Cursor := crDefault; end; 4050: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Vendor File begin quTreeView.Parameters.ParambyName('Path').Value := '.002%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 4060: begin Screen.Cursor := crHourGlass; with TbrwPurchase.Create(Self) do // ** Purchase History begin iPurStatus := 3; //Completed sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 4070: begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Inventory ---------------------------- 5010: begin Screen.Cursor := crHourGlass; with TbrwModel.Create(Self) do // ** Inventory Maintenance begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5020: begin Screen.Cursor := crHourGlass; with TbrwInventory.Create(Self) do // ** View by Store begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5030: begin Screen.Cursor := crHourGlass; with TbrwGroup.Create(Self) do // ** Category Maintenance Tree View begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5040: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Manufacturers Maintenance begin quTreeView.Parameters.ParambyName('Path').Value := '.004%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5050: begin Screen.Cursor := crHourGlass; with TbrwInventoryMov.Create(Self) do // ** Movement History begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5060: begin Screen.Cursor := crHourGlass; with TbrwInventMovType.Create(Self) do // ** Movement Types begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5070: begin Screen.Cursor := crHourGlass; with TbrwRepairInv.Create(Self) do // ** Inventory Return begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5080: begin Screen.Cursor := crHourGlass; with TFchModel.Create(Self) do // ** View Inventory by Model begin ShowLookUp := True; Start(btAlt, nil, False, ID1, ID2, nil); Free; end; Screen.Cursor := crDefault; end; 5090: begin Screen.Cursor := crHourGlass; with TBrwModelTransf.Create(Self) do // ** Move Items begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5100: begin Screen.Cursor := crHourGlass; with TInventoryCleanUp.Create(Self) do // ** Clean Up Inventory ShowModal; Screen.Cursor := crDefault; end; 5110: begin Screen.Cursor := crHourGlass; with TFrmInventoryCount.Create(Self) do // ** Inventory Count Start; Screen.Cursor := crDefault; end; 5120: begin Screen.Cursor := crHourGlass; with TbrwColor.Create(Self) do //Color begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5130: begin Screen.Cursor := crHourGlass; with TbrwSize.Create(Self) do //Size begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 5140: //Barcode Lis begin with TFrmBarcodePrint.Create(Self) do Start('', ''); end; 5150: //Pricing Setup begin Screen.Cursor := crHourGlass; with TFrmPricingSetup.Create(Self) do Start; Screen.Cursor := crDefault; end; 5160: //Report begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; 5170: // Antonio 2014 Apr 08 - Tag begin Screen.Cursor := crHourGlass; with TfrmTagView.Create(self) do begin start; end; // to call new Tag screen Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Commission ---------------------------- 6010: begin Screen.Cursor := crHourGlass; with TFrmPagaVendedor.Create(Self) do // ** Sales Person ShowModal; Screen.Cursor := crDefault; end; 6020: begin Screen.Cursor := crHourGlass; with TFrmPagaGuia.Create(Self) do // ** Pay Agent ShowModal; Screen.Cursor := crDefault; end; 6030: begin Screen.Cursor := crHourGlass; with TFrmPagaAgencia.Create(Self) do // ** Pay Agency ShowModal; Screen.Cursor := crDefault; end; 6040: begin Screen.Cursor := crHourGlass; with TFrmPagaOther.Create(Self) do //* Pay Other begin ShowModal; end; Screen.Cursor := crDefault; end; 6050: begin Screen.Cursor := crHourGlass; DM.CallReport(DM.fUser.Password); Screen.Cursor := crDefault; end; 6060: begin Screen.Cursor := crHourGlass; with TBrwPessoa.Create(Self) do // ** Maintenance begin quTreeView.Parameters.ParambyName('Path').Value := '.003%'; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Accounting -------------------------- // Puppy Tracker Integration 7010: begin screen.Cursor := crHourGlass; try try winExec('PT2MR.exe --config', SW_SHOWNORMAL); except on e: Exception do begin MsgBox(MSG_CRT_NO_PUPPYT,vbOkOnly + vbCritical); end; end; finally screen.cursor := crDefault; end; end; 7020: begin screen.Cursor := crHourGlass; try try winExec('PT2MR.exe', SW_SHOWNORMAL); except on e: Exception do begin MsgBox(MSG_CRT_NO_PUPPYT,vbOkOnly + vbCritical); end; end; finally screen.cursor := crDefault; end; end; //--------------------------------------------------------------- //--------------------- Maintenance -------------------------- 8010: begin Screen.Cursor := crHourGlass; with TbrwStore.Create(Self) do //Store begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8020: begin Screen.Cursor := crHourGlass; with TbrwSpecialPrice.Create(Self) do //Special Price begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8030: begin Screen.Cursor := crHourGlass; with TbrwDeliverType.Create(Self) do //Deliver Type begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8040: begin Screen.Cursor := crHourGlass; with TbrwUser.Create(Self) do //User begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8050: begin Screen.Cursor := crHourGlass; with TbrwUserType.Create(Self) do //User Type begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8060: begin Screen.Cursor := crHourGlass; with TFchParameter.Create(Self) do Start(fFchParamType); //Client Parameters fFchParamType := PARAM_OPEN_ALL; Screen.Cursor := crDefault; end; 8070: begin Screen.Cursor := crHourGlass; with TFrmParameter.Create(Self) do ShowModal; //Server Parameters Screen.Cursor := crDefault; end; 8080: //NADA begin end; 8090: begin Screen.Cursor := crHourGlass; with TFrmMenuItem.Create(Self) do //Menu Items ShowModal; Screen.Cursor := crDefault; end; // Adjust Reason MR-230 8150: begin Screen.Cursor := crHourGlass; with TvwAdjustReason.Create(Self) do //Menu Items Start(); Screen.Cursor := crDefault; end; 8100: begin Screen.Cursor := crHourGlass; with TFrmTransferData.Create(self) do //Transfer Data ShowModal; Screen.Cursor := crDefault; end; 8110: begin Screen.Cursor := crHourGlass; with TBrwMeioPag.Create(self) do //Type of Payments begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8120: begin Screen.Cursor := crHourGlass; with TBrwTaxCategory.Create(self) do begin //recebe os parametros para inicializar os campos if DM.fSystem.SrvParam[PARAM_TAX_IN_COSTPRICE] then begin BrowseConfig.AutoOpen := False; pnlBasicFilter.Visible := True; pblGO.Visible := True; end; sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8130: begin Screen.Cursor := crHourGlass; with TBrwCostType.Create(Self) do // ** Expence Category begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; 8140: begin Screen.Cursor := crHourGlass; with TfrmPuppySetting.Create(Self) do // ** PuppyTracker Integration begin sParam := sMyParam; Start; end; Screen.Cursor := crDefault; end; //--------------------------------------------------------------- //--------------------- Utilities ----------------------------- 9010: //Help begin CallHelp; end; 9020: //Clock begin Screen.Cursor := crHourGlass; with DM.quFreeSQL do begin if Active then Close; SQl.Clear; SQL.ADD('SELECT P.IDPessoa'); SQL.ADD('FROM Store S (NOLOCK) , SystemUser SU (NOLOCK) '); SQL.ADD('JOIN Pessoa P (NOLOCK) ON ( SU.ComissionID = P.IDPessoa )'); SQL.ADD('WHERE S.IDStore = '+IntToStr(DM.fStore.ID)); SQL.ADD('AND SU.IDUser = '+IntToStr(DM.fUser.ID)); Open; if RecordCount = 0 then begin MsgBox(MSG_INF_NO_ASSOC_COMMITION, vbOKOnly + vbInformation); Close; exit; end; iIDPessoa := FieldByName('IDPessoa').AsInteger; Close; end; with TFrmTimeControl.Create(Self) do Start(iIDPessoa); Screen.Cursor := crDefault; end; 9030: //Shipping e Distribution begin Screen.Cursor := crHourGlass; case DM.CheckCashRegState(DM.fCashRegister.IDShippingReg, IDCashRegMov) of CASHREG_OPEN: begin with TCashRegManager.Create(Self) do Start(IDCashRegMov, DM.fCashRegister.IDShippingReg, CASHREG_TYPE_SHIPPING, True); end; CASHREG_CLOSE: begin with TCashRegOpen.Create(Self) do Start(CASHREG_TYPE_SHIPPING, DM.fCashRegister.IDShippingReg); end; end; Screen.Cursor := crDefault; end; 9040: //Service Order begin Screen.Cursor := crHourGlass; with TFrmServiceOrder.Create(Self) do Start; Screen.Cursor := crDefault; end; 9050..9090: begin MyCmdLine := DM.DescCodigo(['IDMenu', 'IDSubMenu'], [IntToStr(IDMenu), IntToStr(IDSubMenu)], 'MenuItem', 'CmdLine'); if MyCmdLine = '' then raise exception.Create(MSG_CRT_UTILITY_NOT_DEFINED) else begin Screen.Cursor := crHourGlass; // Abre a utility ExecuteFile(Trim(MyCmdLine), '', '', SW_SHOW); Screen.Cursor := crDefault; end; end; end; //end Case end else begin if fFirstTime then Application.Terminate; end; end; procedure TMainMenu.lblSystemExitClick(Sender: TObject); begin // Fecha conexao com database dm.setCashRegister(dm.fCashRegister.IDDefault, false); DM.ADODBConnect.Close; Close; end; procedure TMainMenu.FormClose(Sender: TObject; var Action: TCloseAction); begin tmTestMessage.Enabled := False; // Desliga o Windows if DM.fSystem.ShutDownOnExit then ExitWindowsEx(EWX_SHUTDOWN, 0); end; procedure TMainMenu.btAtuVersaoClick(Sender: TObject); begin //Rodrigo - Verificar // Atualiza nova versao do sistema retail if ExecuteFile('\\NtServer\SysRetail\Retail.exe', '', '', SW_SHOW) > 0 then begin DM.ADODBConnect.Close; Application.Terminate; end; end; procedure TMainMenu.tmrTimeTimer(Sender: TObject); begin lblClock.Caption := FormatDateTime('hh:mm AM/PM', Now); lblClockShadow.Caption := FormatDateTime('hh:mm AM/PM', Now); lblClock.Hint := FormatDateTime('dddd, mmmm d, yyyy', Now); end; procedure TMainMenu.MyIdle(Sender: TObject; var Done: Boolean); begin end; procedure TMainMenu.lblCashierDblClick(Sender: TObject); begin // Passa para Permanent Log On do Cashier if Password.PermanentCashLogOn then begin Password.PermanentCashLogOn := False; imgCashierOpen.Visible := False; tmrCashier.enabled := False; Exit; end; if Password.Start(-2, -2) then begin imgCashierOpen.Visible := True; tmrCashier.enabled := True; // ** Liga o timer que controla o tempo // ** de ociosidade do cashier end; end; procedure TMainMenu.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin // ** Zera a contagem do timer do caixa com o mov. do mouse if Password.PermanentLogOn then begin tmrCashier.Enabled := False; tmrCashier.Enabled := True; end; end; procedure TMainMenu.RefreshColor; begin Label8.Font.Color := DM.fMainMenu.MenuColor; Label9.Font.Color := DM.fMainMenu.MenuColor; Label2.Font.Color := DM.fMainMenu.MenuColor; Label10.Font.Color := DM.fMainMenu.MenuColor; Label11.Font.Color := DM.fMainMenu.MenuColor; Label12.Font.Color := DM.fMainMenu.MenuColor; Label1.Font.Color := DM.fMainMenu.MenuColor; Label14.Font.Color := DM.fMainMenu.MenuColor; Label3.Font.Color := DM.fMainMenu.MenuColor; lblSystemExit.Font.Color := DM.fMainMenu.MenuColor; lbSisStore.Font.Color := DM.fMainMenu.MenuColor; lbSisUser.Font.Color := DM.fMainMenu.MenuColor; Label8.Color := DM.fMainMenu.BackGroundColor; Label9.Color := DM.fMainMenu.BackGroundColor; Label2.Color := DM.fMainMenu.BackGroundColor; Label10.Color := DM.fMainMenu.BackGroundColor; Label11.Color := DM.fMainMenu.BackGroundColor; Label12.Color := DM.fMainMenu.BackGroundColor; Label1.Color := DM.fMainMenu.BackGroundColor; Label14.Color := DM.fMainMenu.BackGroundColor; Label3.Color := DM.fMainMenu.BackGroundColor; lblSystemExit.Color := DM.fMainMenu.BackGroundColor; lbPOSShortCut.Font.Color := DM.fMainMenu.MenuColor; lbSaleSupShortCut.Font.Color := DM.fMainMenu.MenuColor; lbAdvertiseShortCut.Font.Color := DM.fMainMenu.MenuColor; lbPurchaseShortCut.Font.Color := DM.fMainMenu.MenuColor; lbInventoryShortCut.Font.Color := DM.fMainMenu.MenuColor; lbCommissionShortCut.Font.Color := DM.fMainMenu.MenuColor; lbOMShortCut.Font.Color := DM.fMainMenu.MenuColor; lbMaintenanceShortCut.Font.Color := DM.fMainMenu.MenuColor; lbUtilShortCut.Font.Color := DM.fMainMenu.MenuColor; lbExitShortCut.Font.Color := DM.fMainMenu.MenuColor; lbPOSShortCut.Color := DM.fMainMenu.BackGroundColor; lbSaleSupShortCut.Color := DM.fMainMenu.BackGroundColor; lbAdvertiseShortCut.Color := DM.fMainMenu.BackGroundColor; lbPurchaseShortCut.Color := DM.fMainMenu.BackGroundColor; lbInventoryShortCut.Color := DM.fMainMenu.BackGroundColor; lbCommissionShortCut.Color := DM.fMainMenu.BackGroundColor; lbOMShortCut.Color := DM.fMainMenu.BackGroundColor; lbMaintenanceShortCut.Color := DM.fMainMenu.BackGroundColor; lbUtilShortCut.Color := DM.fMainMenu.BackGroundColor; lbExitShortCut.Color := DM.fMainMenu.BackGroundColor; lbSM1.Font.Color := DM.fMainMenu.SubMenuColor; lbSM2.Font.Color := DM.fMainMenu.SubMenuColor; lbSM3.Font.Color := DM.fMainMenu.SubMenuColor; lbSM4.Font.Color := DM.fMainMenu.SubMenuColor; lbSM5.Font.Color := DM.fMainMenu.SubMenuColor; lbSM6.Font.Color := DM.fMainMenu.SubMenuColor; lbSM7.Font.Color := DM.fMainMenu.SubMenuColor; lbSM8.Font.Color := DM.fMainMenu.SubMenuColor; lbSM9.Font.Color := DM.fMainMenu.SubMenuColor; lbSM10.Font.Color := DM.fMainMenu.SubMenuColor; lbSM11.Font.Color := DM.fMainMenu.SubMenuColor; lbSM12.Font.Color := DM.fMainMenu.SubMenuColor; lbSM13.Font.Color := DM.fMainMenu.SubMenuColor; lbSM14.Font.Color := DM.fMainMenu.SubMenuColor; lbSM15.Font.Color := DM.fMainMenu.SubMenuColor; lbSM16.Font.Color := DM.fMainMenu.SubMenuColor; PanelControl.Color := DM.fMainMenu.MenuBackColor; MainMenu.Color := DM.fMainMenu.BackGroundColor; TIP.Font.Color := DM.fMainMenu.SubMenuHighlight; shpHelp.Brush.Color := DM.fMainMenu.BackGroundColor; shpSystem.Brush.Color := DM.fMainMenu.BackGroundColor; shpShortCut.Brush.Color := DM.fMainMenu.BackGroundColor; Label13.Font.Color := DM.fMainMenu.BackGroundColor; Label6.Font.Color := DM.fMainMenu.BackGroundColor; lbShortCuts.Font.Color := DM.fMainMenu.BackGroundColor; lbShortCuts.Color := DM.fMainMenu.PanelShorcuts; lbSC1.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC2.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC3.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC4.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC5.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC6.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC7.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC8.Font.Color := DM.fMainMenu.PanelShorcuts; lbSC9.Font.Color := DM.fMainMenu.PanelShorcuts; Label13.Color := DM.fMainMenu.PanelSystem; lbLogIn.Font.Color := DM.fMainMenu.PanelSystem; lbLogShort.Font.Color := DM.fMainMenu.PanelSystem; lbMenuColor.Font.Color := DM.fMainMenu.PanelSystem; lbSysInfo.Font.Color := DM.fMainMenu.PanelSystem; Label5.Font.Color := DM.fMainMenu.PanelSystem; lbBackup.Font.Color := DM.fMainMenu.PanelSystem; Label6.Color := DM.fMainMenu.PanelHelp; lbTip.Font.Color := DM.fMainMenu.PanelHelp; lbHelp.Font.Color := DM.fMainMenu.PanelHelp; lbHelpShort.Font.Color := DM.fMainMenu.PanelHelp; if FileExists(DM.fMainMenu.Logo) then imgClientLogo.Picture.LoadFromFile(DM.fMainMenu.Logo); end; procedure TMainMenu.FormCreate(Sender: TObject); var cmd: String; i: Integer; startIntegration: boolean; puppyIntegration: TMRPuppyIntegration; IdMessage: Integer; fUserList: TStringList; sIDUSers: String; begin Case DMGlobal.IDLanguage of LANG_ENGLISH : begin fScreenHelp := 'MR_SCREEN_ES.HLP'; fHowToHelp := 'MR_HOWTO_ES.HLP'; fOnlineHelpPage := 'http://support.pinogy.net/'; end; LANG_PORTUGUESE : begin fScreenHelp := 'MR_SCREEN_BR.HLP'; fHowToHelp := 'MR_HOWTO_BR.HLP'; fOnlineHelpPage := 'http://support.pinogy.net/'; end; LANG_SPANISH : begin fScreenHelp := 'MR_SCREEN_SP.HLP'; fHowToHelp := 'MR_HOWTO_SP.HLP'; fOnlineHelpPage := 'http://support.pinogy.net/'; end; end; //Pego o help file Application.HelpFile := extractfilepath(application.exename) + fScreenHelp; quParamTimerCash.open; // ** abre a tabela de parametros do servidor tmrCashier.Interval := (StrToInt(quParamTimerCashSrvValue.Text) * 60000); quParamTimerCash.close; //Setup Language if (DMGlobal.IDLanguage <> LANG_ENGLISH) and (siLang.StorageFile <> '') then begin if FileExists(DMGlobal.LangFilesPath + siLang.StorageFile) then siLang.LoadAllFromFile(DMGlobal.LangFilesPath + siLang.StorageFile, True) else MsgBox(MSG_INF_DICTIONARI_NOT_FOUND ,vbOKOnly + vbInformation); end; if DM.fMainMenu.WindowMode then begin Left := 0; Top := 0; BorderStyle := bsSizeable; BorderIcons := [biMinimize,biMaximize,biSystemMenu]; end; RefreshColor; end; procedure TMainMenu.tmrCashierTimer(Sender: TObject); begin // ** Tira o UnLock do caixa caso ele tenha ficado ocioso por n minutos // ** onde n é definido em Server Parameters tmrCashier.enabled := False; PassWord.PermanentCashLogOn := False; imgCashierOpen.visible := False; //Password Normal Password.PermanentLogOn := False; imgManagerOpen.Visible := False; imgManagerClose.Visible := True; lbLogIn.Caption := 'LogIn'; lbLogShort.Left := lbLogIn.Left + lbLogIn.Width + 3; pnlSistemInfo.Visible := False; DM.fUser.CheckMessage := False; DM.VerifyMessage; end; procedure TMainMenu.tmTestMessageTimer(Sender: TObject); begin DM.VerifyMessage; end; procedure TMainMenu.tmrTrialCountTimer(Sender: TObject); var iCurCount: integer; buildInfo: String; begin with TRegistry.Create do try // acessa a chave CURRENT_USER se Windows 7 if ( getOS(buildInfo) = osW7 ) then RootKey := HKEY_CURRENT_USER else RootKey:= HKEY_LOCAL_MACHINE; OpenKey('SOFTWARE\Applenet\CurrentVersions', True); if not ValueExists('TrialCount') then begin MsgBox(MSG_CRT_NO_VALID_TRIAL_INFO, vbOKOnly + vbCritical); Application.Terminate; end; iCurCount:= StrToInt(DecodeServerInfo(ReadString('TrialCount'), 'Count', CIPHER_TEXT_STEALING, FMT_UU)); Inc(iCurCount); WriteString('TrialCount', EncodeServerInfo(IntToStr(iCurCount), 'Count', CIPHER_TEXT_STEALING, FMT_UU)); finally Free; end; end; procedure TMainMenu.lbDemoClick(Sender: TObject); begin OpenURL('http://www.mainretail.com/'); end; procedure TMainMenu.imgTipClick(Sender: TObject); begin CallTip; end; procedure TMainMenu.quSubMenuBeforeOpen(DataSet: TDataSet); begin quSubMenu.Parameters.ParamByName('IDLanguage').Value := DMGlobal.IDLanguage; end; procedure TMainMenu.lblOdblClickClick(Sender: TObject); begin // Passa para Permanent Log On if Password.PermanentLogOn then begin Password.PermanentLogOn := False; imgManagerOpen.Visible := False; imgManagerClose.Visible := True; tmrCashier.Enabled := False; lbLogIn.Caption := 'Login'; lbLogShort.Left := lbLogIn.Left + lbLogIn.Width + 3; pnlSistemInfo.Visible := False; DM.fUser.ID := 0; DM.VerifyMessage; Exit; end else tmrCashier.Enabled := True; Screen.Cursor := crHourGlass; if Password.Start(-1, -1) then begin imgManagerOpen.Visible := True; imgManagerClose.Visible := False; lbLogIn.Caption := 'LogOut'; lbLogShort.Left := lbLogIn.Left + lbLogIn.Width + 3; pnlSistemInfo.Visible := True; lbSisUser.Caption := DM.fUser.UserName; lbSisStore.Caption := DM.fStore.Name; end; Screen.Cursor := crDefault; end; procedure TMainMenu.imgSystemInfoClick(Sender: TObject); begin with TFrmSystemInfo.Create(Self) do Start; end; procedure TMainMenu.imgHelpClick(Sender: TObject); begin CallHelp; end; procedure TMainMenu.imgMenuColorClick(Sender: TObject); var iMOld, iSOld : Integer; begin //Chama o FchParam com a opcao de cores do menu iMOld := IDMenu; iSOld := IDSubMenu; //Seta o menu de FchParam IDMenu := 8; IDSubMenu := 6; fFchParamType := PARAM_OPEN_MENU; SubMenuClick(nil); //Volta para o menu anterior IDMenu := iMOld; IDSubMenu := iSOld; end; procedure TMainMenu.imgSC1Click(Sender: TObject); var iMOld, iSOld : Integer; begin iMOld := IDMenu; iSOld := IDSubMenu; //Seta o menu IDMenu := StrToIntDef(ParseParam(vtShortCuts[TComponent(Sender).Tag],'M'),1);; IDSubMenu := StrToIntDef(ParseParam(vtShortCuts[TComponent(Sender).Tag],'S'),1);; SubMenuClick(nil); //Volta para o menu anterior IDMenu := iMOld; IDSubMenu := iSOld; end; procedure TMainMenu.imgLanguageClick(Sender: TObject); begin with TfrmLanguageMR.Create(Self) do Start(MR); end; procedure TMainMenu.lbBackupClick(Sender: TObject); var sDBPath : String; begin //Test Local Server with DM.quFreeSQL do begin if Active then Close; SQl.Text := 'SELECT filename ' + 'FROM master..sysdatabases ' + 'WHERE Name = ' + QuotedStr(DM.fSQLConnectParam.DBAlias); Open; sDBPath := FieldByName('filename').AsString; Close; end; if (sDBPath='') or (not FileExists(sDBPath)) then begin MsgBox(MSG_INF_NOT_SERVER, vbOKOnly + vbInformation); Exit; end; //Call Backup CallBackup; end; procedure TMainMenu.CallOnlineHelp; begin OpenURL(fOnlineHelpPage); end; procedure TMainMenu.imgOnlineHelpClick(Sender: TObject); begin CallOnlineHelp; end; procedure TMainMenu.lbMessageClick(Sender: TObject); begin lblOdblClickClick(Self); if DM.fUser.ID <> 0 then with TFrmUserMessager.Create(Self) do Start; Password.PermanentLogOn := False; lbSisUser.Caption := ''; lbSisStore.Caption := ''; end; procedure TMainMenu.FormActivate(Sender: TObject); var msgError: String; begin // Antonio 2013 Nov 08, MR-100 if ( DBBUILD <> dm.getBuildDbVersion ) then begin msgError := 'MainRetail version is not compatible with the database.' + #13#10 + 'Call support at 877-360-7381 to correct this issue.'; MessageDlg(msgError, mtError, [mbOK], 0); Application.Terminate; end; if (DM.fSystem.MRBuildValidate) and (MRBUILD <> DM.fSystem.MRBuild) then begin MessageDlg('MainRetail version is out of date. Call support at 877-360-7381 to schedule a time to update.', mtWarning, [mbOK], 0); end; end; procedure TMainMenu.btnReasonClick(Sender: TObject); var view: TvwAdjustReason; begin view := TvwAdjustReason.Create(Self); view.Start(); end; end.
unit VRS; interface uses Errors; type TVRSInfo = record wID_VRS:word; sText:string[256]; sSitLink:word; end; TVRSFile = file of TVRSInfo; TVRS = class private viVRSInfo:TVRSInfo; fVRSFile:TVRSFile; iCurFilePos:int64; isFileAssigned:boolean; isFileOpened:boolean; function SeekInFile(piPos:int64):byte; function CheckFile:byte; public function CreateVRSFile(isOverwriteExisting:boolean):byte; //Done function AssignVRSFile(psFName:string):byte; function LoadVRS(pwID:integer):byte; function SaveCurVRS:byte; function GenNewVRS:byte; function GetFileOpened:boolean; function GetFileAssigned:boolean; procedure SetText(psText:string[256]); procedure SetSitLink(psLink:word); function GetText:string[256]; function GetSitLink:word; end; implementation function TVRS.CreateVRSFile(isOverwriteExisting:boolean):byte; //Done begin if not isFileAssigned then begin result:=ERROR_FILE_NOT_ASSIGNED; exit; end; try Rewrite(fVRSFile); isFileOpened:=true; except on Exception do begin result:=ERROR_UNKNOWN; exit; end; end; //Файл создан. Можем закрывать)) if isFileOpened then begin CloseFile(fVRSFile); isFileOpened:=false; end; end; function TVRS.AssignVRSFile(psFName:string):byte; begin AssignFile(self.fVRSFile, psFName); isFileAssigned:=true; end; function TVRS.LoadVRS(pwID:integer):byte; var viBufVRS:TVRSInfo; i:int64; begin result:=ERROR_VRS_NOT_FOUND; //Проверяем, на тему присвоения и открытия файла if isFileOpened then begin result:=ERROR_FILE_BUSY; exit; end; if not isFileAssigned then begin result:=ERROR_FILE_NOT_ASSIGNED; exit; end; //Открываем файл try Reset(fVRSFile); isFileOpened:=true; SeekInFile(0); except on Exception do begin result:=ERROR_UNKNOWN; exit; end; end; //Идем циклом по всему файлу for i:= 0 to FileSize(fVRSFile)-1 do begin SeekInFile(i); read(fVRSFile, viBufVRS); //Нашли - записываем инфу из файла в инфу объекта. Возвращаем ошибку FOUND. if viBufVRS.wID_VRS = pwID then begin result:=ERROR_VRS_FOUND; viVRSInfo:=viBufVRS; break; end; end; //Зыкрываем файл. CloseFile(fVRSFile); isFileOpened:=false; end; function TVRS.SaveCurVRS:byte; var liFileError:byte; liVRSError:byte; begin //Проверяем файл liFileError:=CheckFile; if liFileError<>ERROR_SUCCESS then begin result:=liFileError; exit; end; //Если в ВРСе объекта ID = 0 - выходим if viVRSInfo.wID_VRS = 0 then begin result:=ERROR_VRS_NOT_ASSIGNED; exit; end; //Ищем в файле ВРС с ID = ID ВРСа объекта и передвигаем указатель на найденное liVRSError:=LoadVRS(viVRSInfo.wID_VRS); //Открываем файл try Reset(fVRSFile); isFileOpened:=true; except on Exception do begin result:=ERROR_UNKNOWN; exit; end; end; //Если не нашли - идем в конец. Иначе - идем на позицию найденной записи. if liVRSError = ERROR_VRS_NOT_FOUND then SeekInFile(FileSize(fVRSFile)) else SeekInFile(self.iCurFilePos); //Записываем запись в положение, которое определили выше write(fVRSFile, viVRSInfo); //Закрываем файл CloseFile(fVRSFile); isFileOpened:=false; end; function TVRS.CheckFile:byte; begin result:=ERROR_SUCCESS; if not isFileAssigned then begin result:=ERROR_FILE_NOT_ASSIGNED; exit; end; if isFileOpened then begin result:=ERROR_FILE_BUSY; exit; end; end; function TVRS.SeekInFile(piPos:int64):byte; var liFileError:byte; begin //Проверка isFileAssigned и isFileOpened liFileError:=CheckFile; if liFileError<>ERROR_FILE_BUSY then begin result:=ERROR_FILE_NOT_BUSY; exit; end; Seek(fVRSFile, piPos); iCurFilePos:=piPos; end; function TVRS.GetFileOpened:boolean; begin GetFileOpened:=isFileOpened; end; function TVRS.GetFileAssigned:boolean; begin GetFileAssigned:=isFileAssigned; end; procedure TVRS.SetText(psText:string[256]); begin viVRSInfo.sText:=psText; end; procedure TVRS.SetSitLink(psLink:word); begin viVRSInfo.sSitLink:=psLink; end; function TVRS.GetText:string[256]; begin GetText:=viVRSInfo.sText; end; function TVRS.GetSitLink:word; begin GetSitLink:=viVRSInfo.sSitLink; end; function TVRS.GenNewVRS:byte; var lwID:word; liError:integer; begin Randomize; liError:=ERROR_VRS_FOUND; while liError <> ERROR_VRS_NOT_FOUND do begin lwID:=Random(word.MaxValue); liError:=self.LoadVRS(lwID); write('.'); end; self.viVRSInfo.wID_VRS:=lwID; end; end.
unit Handlebars; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpjson, HandlebarsParser, DataContext; type { THandlebarsTemplate } THandlebarsTemplate = class private FProgram: THandlebarsProgram; FSource: String; procedure DoCompile; procedure SetSource(const AValue: String); public destructor Destroy; override; procedure Compile; function Render(Context: TDataContext): String; function Render(Data: TJSONData): String; function Render(Instance: TObject): String; property Source: String read FSource write SetSource; end; function RenderTemplate(const TemplateSrc: String; Data: TJSONObject): String; implementation function RenderTemplate(const TemplateSrc: String; Data: TJSONObject): String; var Template: THandlebarsTemplate; begin Template := THandlebarsTemplate.Create; try Template.Source := TemplateSrc; Result := Template.Render(Data); finally Template.Destroy; end; end; { THandlebarsTemplate } procedure THandlebarsTemplate.SetSource(const AValue: String); begin if FSource = AValue then Exit; FSource := AValue; FreeAndNil(FProgram); end; procedure THandlebarsTemplate.DoCompile; var Parser: THandlebarsParser; begin Parser := THandlebarsParser.Create(FSource); try FProgram := Parser.Parse; finally Parser.Destroy; end; end; destructor THandlebarsTemplate.Destroy; begin FProgram.Free; inherited Destroy; end; procedure THandlebarsTemplate.Compile; begin if FProgram = nil then DoCompile; end; function THandlebarsTemplate.Render(Context: TDataContext): String; begin if FProgram = nil then DoCompile; Result := FProgram.GetText(Context); end; function THandlebarsTemplate.Render(Data: TJSONData): String; var Context: TJSONDataContext; begin Context := TJSONDataContext.Create(Data); try Result := Render(Context); finally Context.Destroy; end; end; function THandlebarsTemplate.Render(Instance: TObject): String; var Context: TDataContext; begin Context := CreateContext(Instance); try Result := Render(Context); finally Context.Destroy; end; end; end.
unit FormWeatherMobile3Unit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, System.Actions, FMX.ActnList, FMX.ListView.Types, FMX.ListView, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Fmx.Bind.Navigator, FMX.ListBox, FMX.Layouts, FMX.Objects; type TFormWeatherMobile3 = class(TForm) TabControlMain: TTabControl; TabItemOverview: TTabItem; ToolBar1: TToolBar; ToolBar2: TToolBar; ActionList1: TActionList; ChangeTabActionOverview: TChangeTabAction; TabItemFavs: TTabItem; ChangeTabActionFavs: TChangeTabAction; LabelTitle1: TLabel; SpeedButtonInfo: TSpeedButton; LiveBindingsBindNavigatePrior1: TFMXBindNavigatePrior; LiveBindingsBindNavigateNext1: TFMXBindNavigateNext; ToolBar4: TToolBar; SpeedButtonGoToOverview: TSpeedButton; Label2: TLabel; ComboBoxCountry: TComboBox; Panel1: TPanel; ListBoxSel: TListBox; ListBoxItem8: TListBoxItem; ListBoxItem9: TListBoxItem; ComboBoxCity: TComboBox; SpeedButtonFavAdd: TSpeedButton; SpeedButtonFavDel: TSpeedButton; ListBoxFavs: TListBox; ListBoxHeader2: TListBoxHeader; Label3: TLabel; LabelUpdated: TLabel; SpeedButtonRefresh: TSpeedButton; TabItemPleaseWait: TTabItem; ChangeTabActionPleaseWait: TChangeTabAction; PanelPleaseWait: TPanel; Label4: TLabel; ToolBar5: TToolBar; Label5: TLabel; ListBoxOverview: TListBox; AniIndicator2: TAniIndicator; StyleBook1: TStyleBook; procedure ComboBoxCountryChange(Sender: TObject); procedure SpeedButtonInfoClick(Sender: TObject); procedure SpeedButtonFavDelClick(Sender: TObject); procedure SpeedButtonFavAddClick(Sender: TObject); procedure SpeedButtonGoToOverviewClick(Sender: TObject); procedure SpeedButtonRefreshClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure LoadCountries; procedure LoadCities; procedure RefreshFavorites; procedure UpdateWeatherInfo; procedure RefreshLastUpdated; procedure RefreshOverview; public { Public declarations } end; var FormWeatherMobile3: TFormWeatherMobile3; implementation {$R *.fmx} uses DMWeatherUnit, weather_utils; procedure TFormWeatherMobile3.ComboBoxCountryChange(Sender: TObject); begin LoadCities; end; procedure TFormWeatherMobile3.FormCreate(Sender: TObject); begin TabControlMain.ActiveTab := TabItemOverview; DMWeather.GetLastWeather; RefreshOverview; RefreshLastUpdated; end; procedure TFormWeatherMobile3.LoadCities; var country: string; cities: TStringDynArray; i: integer; begin ComboBoxCity.Clear; if ComboBoxCountry.Selected <> nil then begin country := ComboBoxCountry.Selected.Text; cities := DMWeather.GetCityList(country); if cities <> nil then begin for i := 0 to Length(cities)-1 do ComboBoxCity.Items.Add(cities[i]); Finalize(cities); if ComboBoxCity.Items.Count > 0 then ComboBoxCity.ItemIndex := 0; end; end; end; procedure TFormWeatherMobile3.LoadCountries; var countries: TStringDynArray; i: integer; begin ComboBoxCountry.Clear; countries := DMWeather.GetCountryList; if countries <> nil then begin for i := 0 to Length(countries)-1 do ComboBoxCountry.Items.Add(countries[i]); Finalize(countries); if ComboBoxCountry.Items.Count > 0 then ComboBoxCountry.ItemIndex := 0; LoadCities; end; end; procedure TFormWeatherMobile3.RefreshFavorites; var favs: TCityCountryDynArray; i: integer; begin ListBoxFavs.Clear; favs := DMWeather.FavoritesGet; if favs <> nil then for i := 0 to Length(favs)-1 do ListBoxFavs.Items.Add(' ' + favs[i].City + ' (' + favs[i].Country + ')'); end; procedure TFormWeatherMobile3.RefreshLastUpdated; begin LabelUpdated.Text := 'Updated: ' + DMWeather.LastUpdated.ToString; end; procedure TFormWeatherMobile3.RefreshOverview; var location, aTime, tempC, pressurehPa, humidity, windDir, windSpeed, visibility, skyConditions : string; listItem: TListBoxItem; txt: TText; begin ListBoxOverview.Clear; if DMWeather.cdsWeather.Active then begin DMWeather.cdsWeather.First; while not DMWeather.cdsWeather.Eof do begin location := DMWeather.cdsWeatherLocName.AsString; aTime := DMWeather.cdsWeatherTime.AsString; tempC := DMWeather.cdsWeatherTempC.AsString; pressurehPa := DMWeather.cdsWeatherPressurehPa.AsString; humidity := DMWeather.cdsWeatherRelativeHumidity.AsString; windDir := DMWeather.cdsWeatherWindDir.AsString; windSpeed := DMWeather.cdsWeatherWindSpeed.AsString; visibility := DMWeather.cdsWeatherVisibility.AsString; skyConditions := DMWeather.cdsWeatherSkyConditions.AsString; listItem := TListBoxItem.Create(ListBoxOverview); listItem.Parent := ListBoxOverview; listItem.Height := 75; listItem.StyleLookup := 'weatheritem'; txt := listItem.FindStyleResource('txtlocation') as TText; if Assigned(txt) then txt.Text := location; txt := listItem.FindStyleResource('txttime') as TText; if Assigned(txt) then txt.Text := 'time: ' + aTime; txt := listItem.FindStyleResource('txttempc') as TText; if Assigned(txt) then txt.Text := 'temp: ' + tempC + '°C'; txt := listItem.FindStyleResource('txthumidity') as TText; if Assigned(txt) then txt.Text := 'humidity: ' + humidity + '%'; txt := listItem.FindStyleResource('txtpressurehpa') as TText; if Assigned(txt) then txt.Text := 'pressure: ' + pressurehPa + 'hPa'; txt := listItem.FindStyleResource('txtwindspeed') as TText; if Assigned(txt) then txt.Text := 'wind speed: ' + windSpeed + ' MPH'; txt := listItem.FindStyleResource('txtvisibility') as TText; if Assigned(txt) then txt.Text := 'visibility: ' + visibility; txt := listItem.FindStyleResource('txtskyconditions') as TText; if Assigned(txt) then txt.Text := 'sky conditions: ' + skyConditions; txt := listItem.FindStyleResource('txtwinddirval') as TText; if Assigned(txt) then txt.Text := windDir + '°'; DMWeather.cdsWeather.Next; end; end; end; procedure TFormWeatherMobile3.SpeedButtonFavAddClick(Sender: TObject); var cc: TCityCountry; begin if (ComboBoxCountry.Selected <> nil) and (ComboBoxCity.Selected <> nil) then begin cc.Country := ComboBoxCountry.Selected.Text; cc.City := ComboBoxCity.Selected.Text; if DMWeather.FavoritesAdd(cc) then RefreshFavorites; end; end; procedure TFormWeatherMobile3.SpeedButtonFavDelClick(Sender: TObject); begin if ListBoxFavs.Selected <> nil then begin if DMWeather.FavoritesDel(ListBoxFavs.Selected.Index+1) then RefreshFavorites; end; end; procedure TFormWeatherMobile3.SpeedButtonGoToOverviewClick(Sender: TObject); begin UpdateWeatherInfo; end; procedure TFormWeatherMobile3.SpeedButtonInfoClick(Sender: TObject); begin LoadCountries; RefreshFavorites; ChangeTabActionFavs.ExecuteTarget(self); end; procedure TFormWeatherMobile3.SpeedButtonRefreshClick(Sender: TObject); begin UpdateWeatherInfo; end; procedure TFormWeatherMobile3.UpdateWeatherInfo; begin ChangeTabActionPleaseWait.ExecuteTarget(self); try DMWeather.UpdateWeather; RefreshOverview; RefreshLastUpdated; finally ChangeTabActionOverview.ExecuteTarget(self); end; end; end.
unit TrafficSignal; {$mode delphi} interface uses SysUtils, Graphics, Classes, LCLIntf, Entity; type TSignalSequence = (Go, Stop); TSignalEntity = class(TEntity) protected CurrentSequence: TSignalSequence; procedure SetSequence(s: TSignalSequence); virtual; public ID: String; property Sequence: TSignalSequence read CurrentSequence write SetSequence; end; TPedestrianSignalEntity = class(TSignalEntity) public constructor Create; procedure Paint; override; end; TCarSignalEntity = class(TSignalEntity) protected NextSequence: TSignalSequence; LastChange: LongInt; procedure SetSequence(s: TSignalSequence); override; public constructor Create; procedure Paint; override; function Think: Boolean; override; end; implementation procedure TSignalEntity.SetSequence; begin self.CurrentSequence := s; end; constructor TPedestrianSignalEntity.Create; begin inherited; self.CurrentSequence := Stop; end; procedure TPedestrianSignalEntity.Paint; begin with self.PaintBox.Canvas do begin Pen.Width := 1; Pen.Style := psSolid; Pen.Color := clBlack; Brush.Color := clGray; self.DrawRectangle(-1.0, -1.0, 1.0, 1.0); if self.Sequence = Stop then Brush.Color := clRed else Brush.Color := clGray; self.DrawEllipse(-0.675, -0.8, 0.675, -0.15); if self.Sequence = Go then Brush.Color := clGreen else Brush.Color := clGray; self.DrawEllipse(-0.675, 0.15, 0.675, 0.8); end; end; constructor TCarSignalEntity.Create; begin inherited; self.CurrentSequence := Stop; self.NextSequence := Stop; end; procedure TCarSignalEntity.Paint; begin with self.PaintBox.Canvas do begin Pen.Width := 1; Pen.Style := psSolid; Pen.Color := clBlack; Brush.Color := clGray; self.DrawRectangle(-1.0, -1.0, 1.0, 1.0); if self.CurrentSequence = Stop then Brush.Color := clRed else Brush.Color := clGray; self.DrawEllipse(-0.4, -0.8, 0.4, -0.4); if self.CurrentSequence <> self.NextSequence then Brush.Color := clYellow else Brush.Color := clGray; self.DrawEllipse(-0.4, -0.2, 0.4, 0.2); if (self.CurrentSequence = Go) and (self.NextSequence <> Stop) then Brush.Color := clGreen else Brush.Color := clGray; self.DrawEllipse(-0.4, 0.4, 0.4, 0.8); end; end; procedure TCarSignalEntity.SetSequence; begin if s = self.CurrentSequence then exit; self.LastChange := GetTickCount; self.NextSequence := s; end; function TCarSignalEntity.Think; var Now: LongInt; begin Result := True; if self.CurrentSequence = self.NextSequence then exit; Now := GetTickCount; if Now - self.LastChange > 1000 then begin self.CurrentSequence := self.NextSequence; self.LastChange := Now; end; end; end.
unit LocationDemoUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Sensors, FMX.StdCtrls, System.Sensors, FMX.WebBrowser, FMX.Layouts, FMX.Memo, FMX.ListBox; type TLocationDemoForm = class(TForm) LocationSensor1: TLocationSensor; WebBrowser1: TWebBrowser; ListBox1: TListBox; ListBoxGroupHeader1: TListBoxGroupHeader; ListBoxItemLatitude: TListBoxItem; ListBoxItemLongitude: TListBoxItem; ListBoxGroupHeader2: TListBoxGroupHeader; ListBoxItemAdminArea: TListBoxItem; ListBoxItemCountryCode: TListBoxItem; ListBoxItemCountryName: TListBoxItem; ListBoxItemFeatureName: TListBoxItem; ListBoxItemLocality: TListBoxItem; ListBoxItemPostalCode: TListBoxItem; ListBoxItemSubAdminArea: TListBoxItem; ListBoxItemSubLocality: TListBoxItem; ListBoxItemSubThoroughfare: TListBoxItem; ListBoxItemThoroughfare: TListBoxItem; ListBoxHeader1: TListBoxHeader; Layout1: TLayout; Switch1: TSwitch; Label1: TLabel; procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure Switch1Switch(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FGeocoder: TGeocoder; procedure OnGeocodeReverseEvent(const Address: TCivicAddress); public { Public declarations } end; var LocationDemoForm: TLocationDemoForm; implementation {$R *.fmx} procedure TLocationDemoForm.Switch1Switch(Sender: TObject); begin LocationSensor1.Active := Switch1.IsChecked; end; procedure TLocationDemoForm.FormCreate(Sender: TObject); begin System.SysUtils.FormatSettings.DecimalSeparator := '.'; end; procedure TLocationDemoForm.LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); var URLString: String; begin // Show current location ListBoxItemLatitude.ItemData.Detail := NewLocation.Latitude.ToString; ListBoxItemLongitude.ItemData.Detail := NewLocation.Longitude.ToString; // Show Map using Google Maps &output=embed' URLString := Format( 'https://maps.google.com/maps?q=%s,%s&output=embed&t=k&z=17', [NewLocation.Latitude.ToString, NewLocation.Longitude.ToString]); WebBrowser1.Navigate(URLString); // Setup an instance of TGeocoder if not Assigned(FGeocoder) then begin if Assigned(TGeocoder.Current) then FGeocoder := TGeocoder.Current.Create; if Assigned(FGeocoder) then FGeocoder.OnGeocodeReverse := OnGeocodeReverseEvent; end; // Translate location to address if Assigned(FGeocoder) and not FGeocoder.Geocoding then FGeocoder.GeocodeReverse(NewLocation); end; procedure TLocationDemoForm.OnGeocodeReverseEvent(const Address: TCivicAddress); begin ListBoxItemAdminArea.ItemData.Detail := Address.AdminArea; ListBoxItemCountryCode.ItemData.Detail := Address.CountryCode; ListBoxItemCountryName.ItemData.Detail := Address.CountryName; ListBoxItemFeatureName.ItemData.Detail := Address.FeatureName; ListBoxItemLocality.ItemData.Detail := Address.Locality; ListBoxItemPostalCode.ItemData.Detail := Address.PostalCode; ListBoxItemSubAdminArea.ItemData.Detail := Address.SubAdminArea; ListBoxItemSubLocality.ItemData.Detail := Address.SubLocality; ListBoxItemSubThoroughfare.ItemData.Detail := Address.SubThoroughfare; ListBoxItemThoroughfare.ItemData.Detail := Address.Thoroughfare; end; end.
unit uOrderItems; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, Buttons, ExtCtrls, FIBDataSet, pFIBDataSet, pFIBDatabase, ActnList, uActionControl, FIBDatabase, IBase; type TfmOrderItems = class(TForm) StyleRepository: TcxStyleRepository; stBackground: TcxStyle; stContent: TcxStyle; stContentEven: TcxStyle; stContentOdd: TcxStyle; stFilterBox: TcxStyle; stFooter: TcxStyle; stGroup: TcxStyle; stGroupByBox: TcxStyle; stHeader: TcxStyle; stInactive: TcxStyle; stIncSearch: TcxStyle; stIndicator: TcxStyle; stPreview: TcxStyle; stSelection: TcxStyle; stHotTrack: TcxStyle; qizzStyle: TcxGridTableViewStyleSheet; OrderViewGrid: TcxGrid; OrderItemsView: TcxGridDBTableView; OrderViewGridLevel1: TcxGridLevel; Panel1: TPanel; AddButton: TSpeedButton; ModifyButton: TSpeedButton; DeleteButton: TSpeedButton; RefreshButton: TSpeedButton; CancelButton: TSpeedButton; ItemsSelect: TpFIBDataSet; SelectButton: TSpeedButton; ActionList1: TActionList; AddAction: TAction; ModifyAction: TAction; DeleteAction: TAction; RefreshAction: TAction; ItemsDataSource: TDataSource; ActionControl: TqFActionControl; DB: TpFIBDatabase; DefaultTransaction: TpFIBTransaction; ReadTransaction: TpFIBTransaction; SelectAction: TAction; NumItem: TcxGridDBColumn; Text: TcxGridDBColumn; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ActionControlBeforePrepare(Sender: TObject; Form: TForm); procedure SelectActionExecute(Sender: TObject); procedure OrderItemsViewDblClick(Sender: TObject); private Id_Order: Integer; public Num_Item: Integer; constructor Create(AOWner: TComponent; Id_Order: Integer; Handle: TISC_DB_HANDLE); reintroduce; end; var fmOrderItems: TfmOrderItems; implementation {$R *.dfm} uses uOrderItemEdit; { TfmOrderItems } constructor TfmOrderItems.Create(AOWner: TComponent; Id_Order: Integer; Handle: TISC_DB_HANDLE); begin inherited Create(AOwner); DB.Handle := Handle; Self.Id_Order := Id_Order; ActionControl.Database := DB; ItemsSelect.Close; ItemsSelect.ParamByName('Id_Order').AsInteger := Id_Order; ItemsSelect.Open; end; procedure TfmOrderItems.CancelButtonClick(Sender: TObject); begin Close; end; procedure TfmOrderItems.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then Action := caFree; end; procedure TfmOrderItems.ActionControlBeforePrepare(Sender: TObject; Form: TForm); begin if (Form is TfmOrderItemEdit) then (Form as TfmOrderItemEdit).Prepare(Id_Order); end; procedure TfmOrderItems.SelectActionExecute(Sender: TObject); begin if not ItemsSelect.IsEmpty then begin Num_Item := ItemsSelect['Num_Item']; ModalResult := mrOk; end; end; procedure TfmOrderItems.OrderItemsViewDblClick(Sender: TObject); begin SelectAction.Execute; end; end.
unit UUnidade; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, UUnidadeVO, UGenericVO, Generics.Collections, UUnidadeController, UPessoa, UPessoasController, UPessoasVO, UProprietarioUnidade, UProprietarioUnidadeVO, UInquilinoUnidade, UInquilinoUnidadeVO, IWVCLBaseControl, IWBaseControl, IWBaseHTMLControl, IWControl, IWCompEdit, Biblioteca, IWDBStdCtrls; type TFTelaCadastroUnidade = class(TFTelaCadastro) GroupBox2: TGroupBox; RadioButton1: TRadioButton; LabelEditNumero: TLabeledEdit; LabeledEditDescricao: TLabeledEdit; EditAreaTotal: TEdit; Label2: TLabel; Label4: TLabel; EditFracaoIdeal: TEdit; Label1: TLabel; EditQtdGas: TEdit; EditObservacao: TRichEdit; Label5: TLabel; BtnProprietario: TBitBtn; BtnInquilino: TBitBtn; procedure FormCreate(Sender: TObject); function DoSalvar: boolean; override; function MontaFiltro: string; procedure DoConsultar; override; function DoExcluir: boolean; override; procedure BitBtnNovoClick(Sender: TObject); procedure GridParaEdits; override; procedure BtnProprietarioClick(Sender: TObject); procedure BtnInquilinoClick(Sender: TObject); procedure BitBtnCancelaClick(Sender: TObject); procedure PageControlChange(Sender: TObject); procedure BitBtnAlteraClick(Sender: TObject); procedure CarregaObjetoSelecionado; override; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EditAreaTotalKeyPress(Sender: TObject; var Key: Char); procedure EditFracaoIdealKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } CodigoUnidade : integer; function EditsToObject(Unidade: TUnidadeVO): TUnidadeVO; end; var FTelaCadastroUnidade: TFTelaCadastroUnidade; ControllerUnidade: TUnidadeController; // FormPessoaConsulta : TFTelaCadastroPessoa; // PessoaController : TPessoasController; implementation {$R *.dfm} uses UEmpresaTrab; { TFTelaCadastroUnidade } procedure TFTelaCadastroUnidade.BitBtnAlteraClick(Sender: TObject); begin inherited; if (StatusTela = TStatusTela.stNavegandoGrid) then begin BtnProprietario.Enabled := true; BtnInquilino.Enabled := true; end else begin BtnProprietario.Enabled := false; BtnInquilino.Enabled := false; end; end; procedure TFTelaCadastroUnidade.BitBtnCancelaClick(Sender: TObject); begin inherited; if (StatusTela = TStatusTela.stNavegandoGrid) then begin BtnProprietario.Enabled := true; BtnInquilino.Enabled := true; end else begin BtnProprietario.Enabled := false; BtnInquilino.Enabled := false; end; end; procedure TFTelaCadastroUnidade.BitBtnNovoClick(Sender: TObject); begin inherited; EditObservacao.Clear; LabelEditNumero.SetFocus; if (StatusTela = TStatusTela.stNavegandoGrid) then begin BtnProprietario.Enabled := true; BtnInquilino.Enabled := true; end else begin BtnProprietario.Enabled := false; BtnInquilino.Enabled := false; end; end; procedure TFTelaCadastroUnidade.BtnInquilinoClick(Sender: TObject); var FormInquilino: TFTelaCadastroInquilino; begin FormInquilino := TFTelaCadastroInquilino.Create(nil); FormInquilino.FechaForm := true; FormInquilino.idunidade := CDSGrid.FieldByName('IDUNIDADE').AsInteger; FormInquilino.ShowModal; end; procedure TFTelaCadastroUnidade.BtnProprietarioClick(Sender: TObject); var FormProprietario: TFTelaCadastroProprietario; begin FormProprietario := TFTelaCadastroProprietario.Create(nil); FormProprietario.FechaForm := true; FormProprietario.idunidade := CDSGrid.FieldByName('IDUNIDADE').AsInteger; FormProprietario.ShowModal; end; procedure TFTelaCadastroUnidade.CarregaObjetoSelecionado; begin inherited; if (not CDSGrid.IsEmpty) then begin ObjetoRetornoVO := ControllerUnidade.ConsultarPorId(CDSGRID.FieldByName('IDUNIDADE').AsInteger); end; end; procedure TFTelaCadastroUnidade.DoConsultar; var listaUnidade: TObjectList<TUnidadeVO>; filtro: string; begin filtro := MontaFiltro; listaUnidade := ControllerUnidade.Consultar(filtro); PopulaGrid<TUnidadeVO>(listaUnidade); end; function TFTelaCadastroUnidade.DoExcluir: boolean; var Unidade: TUnidadeVO; begin try try Unidade := TUnidadeVO.Create; Unidade.idUnidade := CDSGrid.FieldByName('IDUNIDADE').AsInteger; ControllerUnidade.Excluir(Unidade); except on E: Exception do begin ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 + E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroUnidade.DoSalvar: boolean; var Unidade: TUnidadeVO; begin begin Unidade:=EditsToObject(TUnidadeVO.Create); try try Unidade.ValidarCampos(); if (StatusTela = stInserindo) then begin Unidade.idcondominio := FormEmpresaTrab.CodigoEmpLogada; ControllerUnidade.Inserir(Unidade); Result := true; CodigoUnidade := Unidade.idUnidade; end else if (StatusTela = stEditando) then begin Unidade := ControllerUnidade.ConsultarPorId(CDSGrid.FieldByName('IDUNIDADE') .AsInteger); Unidade := EditsToObject(Unidade); ControllerUnidade.Alterar(Unidade); Result := true; CodigoUnidade := Unidade.idUnidade; end; except on E: Exception do begin ShowMessage(E.Message); Result := false; end; end; finally end; end; end; procedure TFTelaCadastroUnidade.EditAreaTotalKeyPress(Sender: TObject; var Key: Char); begin EventoFormataCurrency(Sender,key); end; procedure TFTelaCadastroUnidade.EditFracaoIdealKeyPress(Sender: TObject; var Key: Char); begin EventoFormataCurrency(Sender,key); end; function TFTelaCadastroUnidade.EditsToObject(Unidade: TUnidadeVO): TUnidadeVO; begin if(LabelEditNumero.Text<>'')then Unidade.numero := StrToInt(LabelEditNumero.Text); if(EditQtdGas.Text<>'')then Unidade.vlgasinicial := StrToFloat(EditQtdGas.Text); if(editareatotal.Text<>'')then Unidade.vlareatotal := StrToFloat(EditAreaTotal.Text); if(EditFracaoIdeal.Text<>'')then Unidade.vlfracaoideal := StrToFloat(EditFracaoIdeal.Text); if (LabeledEditDescricao.Text <> '') then Unidade.DsUnidade := LabeledEditDescricao.Text; Unidade.observacao := EditObservacao.Text; Result := Unidade; end; procedure TFTelaCadastroUnidade.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(ControllerUnidade); end; procedure TFTelaCadastroUnidade.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TUnidadeVO; RadioButton1.Checked := true; ControllerUnidade := TUnidadeController.Create; CodigoUnidade := 0; inherited; end; procedure TFTelaCadastroUnidade.GridParaEdits; var Unidade: TUnidadeVO; begin inherited; Unidade := nil; if not CDSGrid.IsEmpty then Unidade := ControllerUnidade.ConsultarPorId(CDSGrid.FieldByName('IDUNIDADE') .AsInteger); if Unidade <> nil then begin LabelEditNumero.Text := IntToStr(Unidade.Numero); EditQtdGas.Text := FloatToStr(Unidade.vlgasinicial); EditAreaTotal.Text := FloatToStr(Unidade.vlareatotal); EditFracaoIdeal.Text := FloatToStr(Unidade.vlfracaoideal); EditObservacao.Text := Unidade.observacao; LabeledEditDescricao.Text := Unidade.DsUnidade; end; end; function TFTelaCadastroUnidade.MontaFiltro: string; begin Result := ' ( IDCONDOMINIO = '+inttostr(FormEmpresaTrab.CodigoEmpLogada)+ ' ) '; {if (RadioButton2.Checked = true) then begin if (editBusca.Text <> '') then begin Result := ' ( UPPER(NUMERO) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end; end else} if (RadioButton1.Checked = true) then begin if (editBusca.Text <> '') then Result := ' ( UPPER(DSUNIDADE) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end; end; procedure TFTelaCadastroUnidade.PageControlChange(Sender: TObject); begin inherited; if (PageControl.ActivePage = DadosCadastrais) then begin BtnProprietario.Enabled := true; BtnInquilino.Enabled := true; end else begin BtnProprietario.Enabled := false ; BtnInquilino.Enabled :=false; end; end; end.
unit Form.Option; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Objekt.Option, Vcl.Samples.Spin; type Tfrm_Option = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; edt_Datenbank: TEdit; edt_Backupdatei: TEdit; edt_User: TEdit; edt_Passwort: TEdit; edt_Uhrzeit: TDateTimePicker; cbx_Checksum: TCheckBox; cbx_Limbo: TCheckBox; cbx_MetaOnly: TCheckBox; cbx_NoGarbage: TCheckBox; cbx_OldMetadata: TCheckBox; cbx_NonTransportable: TCheckBox; cbx_Convert: TCheckBox; cbx_Zeitstempel: TCheckBox; Panel1: TPanel; btn_Ok: TButton; btn_Cancel: TButton; Label7: TLabel; edt_Servername: TEdit; cbx_MaxAnzahl: TCheckBox; edt_Anzahl: TSpinEdit; lbl_Anzahl: TLabel; Shape1: TShape; lbl_Hinweis: TLabel; Label8: TLabel; edt_Passwort2: TEdit; procedure FormCreate(Sender: TObject); procedure btn_OkClick(Sender: TObject); procedure btn_CancelClick(Sender: TObject); procedure CheckStateChangedMaxAnzahl; procedure cbx_MaxAnzahlClick(Sender: TObject); private fCancel: Boolean; fOption: TOption; fConnectCheck: Integer; procedure ErrorConnect(Sender: TObject; aMsg: string); procedure AfterConnected(Sender: TObject); public procedure setOption(aOption: TOption); procedure FillOption(aOption: TOption); property Cancel: Boolean read fCancel; end; var frm_Option: Tfrm_Option; implementation {$R *.dfm} uses Datenmodul.dm; procedure Tfrm_Option.FormCreate(Sender: TObject); begin fCancel := true; fOption := nil; lbl_Anzahl.Visible := false; edt_Anzahl.Visible := false; edt_Datenbank.Text := ''; edt_Backupdatei.Text := ''; edt_User.Text := 'SYSDBA'; edt_Passwort.Text := ''; edt_Servername.Text := ''; edt_Anzahl.Value := 0; fConnectCheck := 0; lbl_Hinweis.StyleElements := lbl_Hinweis.StyleElements - [seFont]; lbl_Hinweis.Font.Color := clBlack; end; procedure Tfrm_Option.setOption(aOption: TOption); begin fOption := aOption; if fOption = nil then exit; edt_Servername.Text := fOption.Servername; edt_Datenbank.Text := fOption.Datenbank; edt_Backupdatei.Text := fOption.Backupdatei; edt_User.Text := fOption.User; edt_Passwort.Text := fOption.Passwort; edt_Passwort2.Text := fOption.Passwort; edt_Uhrzeit.Time := fOption.StartZeit; cbx_Checksum.Checked := fOption.Checksum; cbx_Limbo.Checked := fOption.Limbo; cbx_MetaOnly.Checked := fOption.OnlyMeta; cbx_NoGarbage.Checked := fOption.NoGarbage; cbx_NonTransportable.Checked := fOption.NonTransportable; cbx_Convert.Checked := fOption.Convert; cbx_Zeitstempel.Checked := fOption.Zeitstempel; cbx_OldMetadata.Checked := fOption.OldMetadata; cbx_MaxAnzahl.Checked := fOption.MaxAnzahlBackupDateien; edt_Anzahl.Value := fOption.MaxAnzahlBackup; CheckStateChangedMaxAnzahl; end; procedure Tfrm_Option.FillOption(aOption: TOption); begin aOption.Servername := edt_Servername.Text; aOption.Datenbank := edt_Datenbank.Text; aOption.Backupdatei := edt_Backupdatei.Text; aOption.User := edt_User.Text; aOption.Passwort := edt_Passwort.Text; aOption.StartZeit := edt_Uhrzeit.Time; aOption.Checksum := cbx_Checksum.Checked; aOption.Limbo := cbx_Limbo.Checked; aOption.OnlyMeta := cbx_MetaOnly.Checked; aOption.NoGarbage := cbx_NoGarbage.Checked; aOption.NonTransportable := cbx_NonTransportable.Checked; aOption.Convert := cbx_Convert.Checked; aOption.Zeitstempel := cbx_Zeitstempel.Checked; aOption.OldMetadata := cbx_OldMetadata.Checked; aOption.MaxAnzahlBackup := edt_Anzahl.Value; aOption.MaxAnzahlBackupDateien := cbx_MaxAnzahl.Checked; CheckStateChangedMaxAnzahl; end; procedure Tfrm_Option.btn_CancelClick(Sender: TObject); begin close; end; procedure Tfrm_Option.btn_OkClick(Sender: TObject); var ConnectType: RConnectType; begin if edt_Passwort.Text <> edt_Passwort2.Text then begin MessageDlg('Das Passwort stimmt nicht überein.', mtError, [mbOk], 0); exit; end; ConnectType.Servername := edt_Servername.Text; ConnectType.Datenbank := edt_Datenbank.Text; ConnectType.Passwort := edt_Passwort.Text; ConnectType.User := edt_User.Text; fConnectCheck := 0; dm.OnConnectionError := ErrorConnect; dm.OnAfterConnect := AfterConnected; dm.CheckConnect(ConnectType); while fConnectCheck = 0 do; if fConnectCheck < 0 then begin if MessageDlg('Möchten Sie die Sicherheitsoptionen weiter bearbeiten?', mtConfirmation, [mbYes, mbNo], 0) <> mrNo then exit; end; fCancel := false; close; end; procedure Tfrm_Option.cbx_MaxAnzahlClick(Sender: TObject); begin CheckStateChangedMaxAnzahl; end; procedure Tfrm_Option.CheckStateChangedMaxAnzahl; begin lbl_Anzahl.Visible := cbx_MaxAnzahl.Checked; edt_Anzahl.Visible := cbx_MaxAnzahl.Checked; end; procedure Tfrm_Option.ErrorConnect(Sender: TObject; aMsg: string); begin fConnectCheck := -1; MessageDlg('Die Überprüfung der Datenbankverbindung ist fehlgeschlagen.' + sLineBreak + sLineBreak + aMsg, mtError, [mbOk], 0); end; procedure Tfrm_Option.AfterConnected(Sender: TObject); begin fConnectCheck := 1; end; end.
unit StackTrackDemoMain; interface {.$DEFINE ShowAllExceptions} // If ShowAllExceptions is defined then all exceptions (including those which // are not handled by TApplication object will be logged. // Otherwise, only exceptions handled by TApplication object will be logged. uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ScktComp; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; ListBox1: TListBox; RawCheckBox: TCheckBox; Button4: TButton; Button5: TButton; ClientSocket1: TClientSocket; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure RawCheckBoxClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private procedure ApplicationEvents1Exception(Sender: TObject; E: Exception); public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} uses {$IFDEF ShowAllExceptions} JclHookExcept, {$ENDIF} JclDebug; procedure AnyExceptionNotify(ExceptObj: TObject; ExceptAddr: Pointer; OSException: Boolean); begin with Form1 do begin Memo1.Lines.BeginUpdate; JclLastExceptStackListToStrings(Memo1.Lines, False, True, True); Memo1.Lines.EndUpdate; Memo1.Lines.Add(''); end; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin {$IFNDEF ShowAllExceptions} Application.OnException := ApplicationEvents1Exception; {$ENDIF} end; procedure TForm1.ApplicationEvents1Exception(Sender: TObject; E: Exception); begin Memo1.Lines.BeginUpdate; // Show exception stack info JclLastExceptStackListToStrings(Memo1.Lines, False, True, True); Memo1.Lines.EndUpdate; Memo1.Lines.Add(''); Application.ShowException(E); end; procedure TForm1.RawCheckBoxClick(Sender: TObject); begin if RawCheckBox.Checked then Include(JclStackTrackingOptions, stRawMode) else Exclude(JclStackTrackingOptions, stRawMode) end; procedure TForm1.Button1Click(Sender: TObject); begin PInteger(nil)^ := 0; end; procedure TForm1.Button2Click(Sender: TObject); begin ListBox1.Items[1] := 'a'; end; procedure AAA; begin PInteger(nil)^ := 0; end; procedure TForm1.Button3Click(Sender: TObject); begin AAA; end; procedure TForm1.Button4Click(Sender: TObject); begin ClientSocket1.Active := True; end; procedure TForm1.Button5Click(Sender: TObject); begin try // See ShowAllExceptions above for details StrToInt('abc'); except end; end; initialization // Start Exception tracking JclStartExceptionTracking; {$IFDEF ShowAllExceptions} // Assign notification procedure for hooked RaiseException API call. This // allows being notified of any exception JclAddExceptNotifier(AnyExceptionNotify); {$ENDIF} end.
unit NotYetImplementedException; interface uses SysUtils; type ENotYetImplementedException = class(Exception) public constructor Create; reintroduce; end; implementation { ENotYetImplemented } constructor ENotYetImplementedException.Create; begin inherited Create('not yet implemented!'); end; end.
unit E_ThreadManager; //------------------------------------------------------------------------------ // Модуль реализует класс менеджера потоков //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, SyncObjs, ExtCtrls, // TTimer E_Threads, E_Logger; //------------------------------------------------------------------------------ //! запрос выполнения задачи //------------------------------------------------------------------------------ function TryExecuteThis( const AProc: TThCallback; const AError: TThError; const AData: Pointer; const ALogger: TLogger ): Boolean; //------------------------------------------------------------------------------ //! завершение модуля //! должно вызываться из внешего источника ! //------------------------------------------------------------------------------ procedure FinalizeTMM(); //------------------------------------------------------------------------------ implementation type //------------------------------------------------------------------------------ //! информация о потоке //------------------------------------------------------------------------------ PMyThreadRec = ^TMyThreadRec; TMyThreadRec = record //! время последнего выполнения работы потоком LastTime: TDateTime; //! ссылка на логгер LogRef: TLogger; //! ссылка на класс потока Th: TThreadActivated; //! что выполняем CBProc: TThCallback; //! с чем выполняем CBData: Pointer; //! что выполняем если ошибка CBError: TThError; //! выполняет ли поток полезную работу InWork: Boolean; //! возникла ли ошибка выполнения WasError: Boolean; end; TMyThreadRecArray = array of TMyThreadRec; //------------------------------------------------------------------------------ //! фиктивный класс для процедуры таймера очистки холостых потоков //------------------------------------------------------------------------------ TTMMTimerDummy = class public class procedure IdleTimerTick( Sender: TObject ); end; //------------------------------------------------------------------------------ const //------------------------------------------------------------------------------ //! максимальное количество создаваемых потоков //------------------------------------------------------------------------------ cTMMaxThreads = 1500; //------------------------------------------------------------------------------ //! интервал очистки холостых потоков //------------------------------------------------------------------------------ cTMCleanUpInterval = 30000; // 30 секунд //------------------------------------------------------------------------------ //! сообщения //------------------------------------------------------------------------------ cTMCreateError: string = 'Не удалось создать новый поток:'#13#10'%s'; cTMLimitError: string = 'Достигнут лимит потоков, создание нового невозможно. (Max=%d)'; // cTMProcessError: string = 'Зафиксирована следующая ошибка во время выполнения потока:'#13#10'%s'; //------------------------------------------------------------------------------ var //------------------------------------------------------------------------------ //! список потоков //------------------------------------------------------------------------------ GTMMThreadsPool: TMyThreadRecArray; //------------------------------------------------------------------------------ //! блокировщик работы со списком //------------------------------------------------------------------------------ GTMMCritical: TCriticalSection; //------------------------------------------------------------------------------ //! таймер очистки холостых потоков //------------------------------------------------------------------------------ GTMMIdleTimer: TTimer; //------------------------------------------------------------------------------ //! флаг остановки модуля //------------------------------------------------------------------------------ GTMMEnded: Boolean; // = False //------------------------------------------------------------------------------ //! рабочая процедура потока //! выполняется в отдельном потоке //------------------------------------------------------------------------------ procedure ThWork( const AData: Pointer ); var //! типизированный AData LThis: PMyThreadRec; //------------------------------------------------------------------------------ begin LThis := AData; LThis^.CBProc( LThis^.CBData ); LThis^.LastTime := Now(); LThis^.InWork := False; end; //------------------------------------------------------------------------------ //! процедура ошибки потока //! выполняется в отдельном потоке //------------------------------------------------------------------------------ procedure ThError( const AData: Pointer; var AException: Exception; const AThreadID: TThreadID ); var //! типизированный AData LThis: PMyThreadRec; //------------------------------------------------------------------------------ begin LThis := AData; // LThis^.LogRef.ErrorToLog( Format( cTMProcessError, [AException.Message] ) ); LThis^.CBError( LThis^.CBData, AException, AThreadID ); LThis^.WasError := True; end; //------------------------------------------------------------------------------ //! поиск свободного потока в списке //------------------------------------------------------------------------------ function FindIdleThread(): Integer; begin for Result := Low( GTMMThreadsPool ) to High( GTMMThreadsPool ) do begin if Assigned( GTMMThreadsPool[Result].Th ) and not GTMMThreadsPool[Result].InWork then Exit; end; Result := -1; end; //------------------------------------------------------------------------------ //! поиск пустого места в списке для нового потока //------------------------------------------------------------------------------ function FindEmptySlot(): Integer; begin for Result := Low( GTMMThreadsPool ) to High( GTMMThreadsPool ) do begin if not Assigned( GTMMThreadsPool[Result].Th ) then Exit; end; Result := -1; end; //------------------------------------------------------------------------------ //! запрос выполнения задачи //------------------------------------------------------------------------------ function TryExecuteThis( const AProc: TThCallback; const AError: TThError; const AData: Pointer; const ALogger: TLogger ): Boolean; label A; var //! LRef: PMyThreadRec; //! LIndex: Integer; //------------------------------------------------------------------------------ begin Result := False; if GTMMEnded then Exit; // работаем GTMMCritical.Acquire(); try // ищем простаивающий поток LIndex := FindIdleThread(); if ( LIndex <> -1 ) then begin // нашли простаивающий поток LRef := @GTMMThreadsPool[LIndex]; // простая ссылка A: LRef^.WasError := False; // нет ошибки LRef^.InWork := True; // в работе LRef^.CBProc := AProc; // что LRef^.CBData := AData; // с чем LRef^.CBError := AError; // если всё плохо LRef^.LogRef := ALogger; // лог LRef^.Th.Work( LRef ); // вызов выполнения end else begin // не нашли простаивающий поток // ищем место для нового потока LIndex := FindEmptySlot(); if ( LIndex <> -1 ) then begin // нашли место для нового потока LRef := @GTMMThreadsPool[LIndex]; // простая ссылка // создаём новый поток try LRef^.Th := TThreadActivated.Create( ThWork, ThError ); except on Ex: Exception do begin ALogger.ErrorToLog( Format( cTMCreateError, [Ex.Message] ) ); Exit; end; end; // всё остальное goto A; end else begin // не нашли место для нового потока ALogger.ErrorToLog( Format( cTMLimitError, [cTMMaxThreads] ) ); Exit; end; end; finally GTMMCritical.Release(); end; Result := True; end; //------------------------------------------------------------------------------ //! процедура таймера очистки холостых потоков //------------------------------------------------------------------------------ class procedure TTMMTimerDummy.IdleTimerTick( Sender: TObject ); var //! LI: Integer; //------------------------------------------------------------------------------ begin if GTMMEnded then Exit; GTMMCritical.Acquire(); try for LI := Low( GTMMThreadsPool ) to High( GTMMThreadsPool ) do begin // очищаем остановившиеся при ошибках потоки if Assigned( GTMMThreadsPool[LI].Th ) and GTMMThreadsPool[LI].Th.IsTerminated() then FreeAndNil( GTMMThreadsPool[LI].Th ); // завершаем потоки с возникшей внешней ошибкой if Assigned( GTMMThreadsPool[LI].Th ) and GTMMThreadsPool[LI].WasError then FreeAndNil( GTMMThreadsPool[LI].Th ); // завершаем лишние не занятые работой потоки if Assigned( GTMMThreadsPool[LI].Th ) and ( not GTMMThreadsPool[LI].InWork ) and ( Now() - GTMMThreadsPool[LI].LastTime > ( cTMCleanUpInterval / 86400000 ) ) // миллисекунд в сутках then FreeAndNil( GTMMThreadsPool[LI].Th ); end; finally GTMMCritical.Release(); end; end; //------------------------------------------------------------------------------ //! начальная инициализация модуля //------------------------------------------------------------------------------ procedure InitTMM(); begin IsMultiThread := True; GTMMCritical := TCriticalSection.Create(); SetLength( GTMMThreadsPool, cTMMaxThreads ); GTMMIdleTimer := TTimer.Create( nil ); GTMMIdleTimer.Interval := cTMCleanUpInterval; GTMMIdleTimer.Enabled := True; GTMMIdleTimer.OnTimer := TTMMTimerDummy.IdleTimerTick; end; //------------------------------------------------------------------------------ //! завершение модуля //! должно вызываться из внешего источника !!! //------------------------------------------------------------------------------ procedure FinalizeTMM(); var //! LI: Integer; //------------------------------------------------------------------------------ begin if GTMMEnded then Exit; GTMMEnded := True; FreeAndNil( GTMMIdleTimer ); for LI := Low( GTMMThreadsPool ) to High( GTMMThreadsPool ) do FreeAndNil( GTMMThreadsPool[LI].Th ); SetLength( GTMMThreadsPool, 0 ); FreeAndNil( GTMMCritical ); end; //------------------------------------------------------------------------------ initialization InitTMM(); //------------------------------------------------------------------------------ finalization FinalizeTMM(); end.
unit TestFloatEdit; interface uses TestFramework, UFloatEdit, Controls, StdCtrls, Forms, Messages, Windows; type // Test methods for class TFloatEdit TestTFloatEdit = class(TTestCase) strict private FFloatEdit: TFloatEdit; FForm: TForm; FEdit: TEdit; public procedure SetUp; override; procedure TearDown; override; published procedure ValorInicialDeveSerIgualAoValorDoEdit; procedure ValorInicialInvalidoDeveRetornarZero; procedure DigitoDeveAcrescentarCentavos; procedure DigitoDeveAcrescentarCasasDecimais; procedure BackSpaceDeveRetirarCentavos; procedure BackSpaceDeveRetirarCasasDecimais; procedure OutrasTeclasDevemSerIgnoradas; procedure TextoAlteradoDeveAtualizarValor; procedure SomenteInteirosNaoDeveAlterarCentavos; procedure SomenteInteirosDeveArredondar; procedure FormatacaoPadraoCom2CasasDecimais; procedure FormatacaoSemCasasDecimaisDeveArredondar; procedure FormatacaoSemCasasDecimaisNaoDeveAlterarCentavos; procedure FormatacaoComCasasDecimaisDiferenteDoPadrao; // valor mínimo e máximo // separador de milhares e decimal end; implementation uses SysUtils; procedure TestTFloatEdit.SetUp; begin Application.CreateForm(TForm, FForm); FEdit := TEdit.Create(FForm); FEdit.Parent := FForm; end; procedure TestTFloatEdit.TearDown; begin FreeAndNil(FFloatEdit); FreeAndNil(FForm); end; procedure TestTFloatEdit.BackSpaceDeveRetirarCasasDecimais; var ValorInicial, ProximoValor: double; begin ValorInicial := 1.999; ProximoValor := 0.199; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, false, 3); SendMessage(FEdit.Handle, WM_CHAR, VK_BACK, 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.BackSpaceDeveRetirarCentavos; var ValorInicial, ProximoValor: double; begin ValorInicial := 1.99; ProximoValor := 0.19; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit); SendMessage(FEdit.Handle, WM_CHAR, VK_BACK, 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.SomenteInteirosDeveArredondar; var ValorInicial, ValorArredondado: double; begin ValorInicial := 1.99; ValorArredondado := 2; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, true); CheckEquals(ValorArredondado, FFloatEdit.Value); end; procedure TestTFloatEdit.SomenteInteirosNaoDeveAlterarCentavos; var ValorInicial, ProximoValor: double; begin ValorInicial := 100.00; ProximoValor := 1001.00; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, true); SendMessage(FEdit.Handle, WM_CHAR, ord('1'), 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.DigitoDeveAcrescentarCasasDecimais; var ValorInicial, ProximoValor: double; begin ValorInicial := 1.99; ProximoValor := 19.901; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, false, 3); SendMessage(FEdit.Handle, WM_CHAR, ord('1'), 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.DigitoDeveAcrescentarCentavos; var ValorInicial, ProximoValor: double; begin ValorInicial := 1.99; ProximoValor := 19.91; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit); SendMessage(FEdit.Handle, WM_CHAR, ord('1'), 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.FormatacaoComCasasDecimaisDiferenteDoPadrao; var ValorInicial: double; begin ValorInicial := 1.9999; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, false, 3); CheckEquals('2,000', FEdit.Text); end; procedure TestTFloatEdit.FormatacaoPadraoCom2CasasDecimais; var ValorInicial: double; begin ValorInicial := 100.00; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit); CheckEquals('100,00', FEdit.Text); end; procedure TestTFloatEdit.FormatacaoSemCasasDecimaisDeveArredondar; var ValorInicial, ValorArredondado: double; begin ValorInicial := 1.99; ValorArredondado := 2; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, false, 0); CheckEquals(ValorArredondado, FFloatEdit.Value); end; procedure TestTFloatEdit.FormatacaoSemCasasDecimaisNaoDeveAlterarCentavos; var ValorInicial, ProximoValor: double; begin ValorInicial := 1.99; ProximoValor := 21; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit, false, 0); SendMessage(FEdit.Handle, WM_CHAR, ord('1'), 0); CheckEquals(ProximoValor, FFloatEdit.Value); end; procedure TestTFloatEdit.OutrasTeclasDevemSerIgnoradas; var ValorInicial: double; begin ValorInicial := 1.99; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit); SendMessage(FEdit.Handle, WM_CHAR, ord('a'), 0); CheckEquals(ValorInicial, FFloatEdit.Value); end; procedure TestTFloatEdit.TextoAlteradoDeveAtualizarValor; var ValorInicial, ValorAlterado: double; begin ValorInicial := 123.46; ValorAlterado := 999; FEdit.Text := FloatToStr(ValorInicial); FFloatEdit := TFloatEdit.Create(FEdit); FEdit.Text := FloatToStr(ValorAlterado); CheckEquals(ValorAlterado, FFloatEdit.Value); end; procedure TestTFloatEdit.ValorInicialDeveSerIgualAoValorDoEdit; var Valor: double; begin Valor := 123.45; FEdit.Text := FloatToStr(Valor); FFloatEdit := TFloatEdit.Create(FEdit); CheckEquals(Valor, FFloatEdit.Value); end; procedure TestTFloatEdit.ValorInicialInvalidoDeveRetornarZero; begin FEdit.Text := 'teste'; FFloatEdit := TFloatEdit.Create(FEdit); CheckEquals(0, FFloatEdit.Value); end; initialization // Register any test cases with the test runner RegisterTest(TestTFloatEdit.Suite); end.
namespace MonoConsoleDBApplication; //Sample Mono console application //by Brian Long, 2009 //Console application compiled against Mono assemblies. //Uses MySQL Connector/Net to talk to MySQL: // - creates a DB & table // - runs a SELECT statement // - drops the table & DB //Works under .NET or Mono if MySQL conector is installed //MySQL connector available from http://dev.mysql.com/downloads/connector/net interface uses System.Text, System.Data, MySql.Data.MySqlClient; type ConsoleApp = class private class method SetupData(sqlConnection: MySqlConnection); class method TearDownData(sqlConnection: MySqlConnection); public class method GetSomeData(): String; class method Main; end; implementation class method ConsoleApp.Main; begin Console.WriteLine(GetSomeData()); Console.WriteLine(); Console.WriteLine('Press Enter to continue...'); Console.ReadLine(); end; class method ConsoleApp.SetupData(sqlConnection: MySqlConnection); const createSchemaSQL = 'CREATE SCHEMA IF NOT EXISTS `SampleDB`'; useSchemaSQL = 'USE `SampleDB`;'; dropTableSQL = 'DROP TABLE IF EXISTS `SampleDB`.`Customers`'; createTableSQL = 'CREATE TABLE `SampleDB`.`Customers` (' + ' `CustID` int(11) NOT NULL auto_increment, ' + ' `Name` varchar(45) NOT NULL, ' + ' `Town` varchar(45) NOT NULL, ' + ' `AccountNo` varchar(10) NOT NULL, ' + ' PRIMARY KEY (`CustID`)' + ') ENGINE=MyISAM'; insertSQLs: Array of String = [ 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''John Smith'', ''Manchester'', ''0001'')', 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''John Doe'', ''Dorchester'', ''0002'')', 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Fred Bloggs'', ''Winchester'', ''0003'')', 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Walter P. Jabsco'', ''Ilchester'', ''0004'')', 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Jane Smith'', ''Silchester'', ''0005'')', 'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Raymond Luxury-Yacht'', ''Colchester'', ''0006'')']; var sqlCommand: MySqlCommand := new MySqlCommand(); begin sqlCommand.Connection := sqlConnection; sqlCommand.CommandText := createSchemaSQL; sqlCommand.ExecuteNonQuery(); sqlCommand.CommandText := useSchemaSQL; sqlCommand.ExecuteNonQuery(); sqlCommand.CommandText := dropTableSQL; sqlCommand.ExecuteNonQuery(); sqlCommand.CommandText := createTableSQL; sqlCommand.ExecuteNonQuery(); for each insertSQL: String in insertSQLs do begin sqlCommand.CommandText := insertSQL; sqlCommand.ExecuteNonQuery(); end; end; class method ConsoleApp.TearDownData(sqlConnection: MySqlConnection); const dropSchemaSQL = 'DROP SCHEMA IF EXISTS `SampleDB`'; dropTableSQL = 'DROP TABLE IF EXISTS `SampleDB`.`Customers`'; var sqlCommand: MySqlCommand := new MySqlCommand(); begin sqlCommand.Connection := sqlConnection; sqlCommand.CommandText := dropSchemaSQL; sqlCommand.ExecuteNonQuery(); sqlCommand.CommandText := dropTableSQL; sqlCommand.ExecuteNonQuery(); end; class method ConsoleApp.GetSomeData(): string; const rootPassword = ''; //MySQL Connector/Net connection string connectionString = 'Server=localhost;UID=root;Password=' + rootPassword; selectSQL = 'SELECT * FROM Customers WHERE Town LIKE ''%che%'';'; widths: Array of Integer = [3, 22, 12, 6]; var results: StringBuilder := new StringBuilder(); begin using sqlConnection: MySqlConnection := new MySqlConnection(connectionString) do begin sqlConnection.Open(); SetupData(sqlConnection); var dataAdapter: MySqlDataAdapter := new MySqlDataAdapter(selectSQL, sqlConnection); var dataTable: DataTable := new DataTable('Results'); dataAdapter.Fill(dataTable); for each row: DataRow in dataTable.Rows do begin results.Append('|'); for I: Integer := 0 to dataTable.Columns.Count - 1 do begin var Width := 20; if I <= High(widths) then Width := widths[I]; results.AppendFormat('{0,' + Width.ToString() + '}|', row.Item[I]); end; results.Append(Environment.NewLine); end; TearDownData(sqlConnection); end; Result := results.ToString() end; end.
unit Aurelius.Commands.Exceptions; {$I Aurelius.inc} interface uses Aurelius.Global.Exceptions; type ESelectAlreadyOpen = class(EOPFBaseException) public constructor Create; end; ESelectNotOpen = class(EOPFBaseException) constructor Create; end; ECursorNotFetching = class(EOPFBaseException) constructor Create; end; ENilObjectReturned = class(EOPFBaseException) constructor Create; end; implementation { ESelectAlreadyOpen } constructor ESelectAlreadyOpen.Create; begin inherited Create('Cannot start selecting objects. A select operation has been already started.'); end; { ESelectNotOpen } constructor ESelectNotOpen.Create; begin inherited Create('Cannot fetch object. A select operation has not been started.'); end; { ECursorNotFetching } constructor ECursorNotFetching.Create; begin inherited Create('Cannot fetch object, cursor fetching has not started.'); end; { ENilObjectReturned } constructor ENilObjectReturned.Create; begin inherited Create('No object returned from database. Check if id column in database has a valid value.'); end; end.
program WATEM_DK; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, fileutil, Dos, gdata, idrisi_proc, lateralredistribution, rdata, surface, vector, CustApp, variables, Stat_output, tillage, CarbonCycling, model_implementation; type { TWATEMApplication } TWATEMApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; procedure Set_Parameter_Values; virtual; end; { TWATEMApplication } var //execution var hr, mins, se, s1 : word; procedure StartClock; begin GetTime (hr,mins,se,s1); end; Function StopClock:string; var hr2, min2, se2 : word; begin GetTime (hr2, min2, se2, s1); result := inttostr(se2-se+(min2-mins)*60+(hr2-hr)*60*60); end; Procedure TWATEMApplication.Set_Parameter_Values; begin if Hasoption('dir') then Working_Dir:=GetOptionValue('dir'); SetCurrentDir(Working_Dir); if Hasoption('c14input') then c14filename:=GetOptionValue('c14input'); if Hasoption('c13input') then c13filename:=GetOptionValue('c13input'); if Hasoption('Cs137input') then Cs137filename:= GetOptionValue('Cs137input'); if Hasoption('d','dtm') then dtmfilename:=GetOptionValue('d','dtm'); if Hasoption('p','prc') then prcfilename:=GetOptionValue('p','prc'); if Hasoption('u','RKCP') then RKCPfilename:=GetOptionValue('u','RKCP'); if Hasoption('k','ktc') then ktcfilename:=GetOptionValue('k','ktc'); if Hasoption('o','outf') then outfilename:=GetOptionValue('o','outf') else outfilename:='watem_out.rst'; if Hasoption('t','tfca') then TFCA:=strtoint(GetOptionValue('t','tfca')) else TFCA:=100; if Hasoption('ktil') then KTIL:=strtoint(GetOptionValue('ktil')) else KTIL:=0; if Hasoption('pdep') then PDEPTH:=strtoint(GetOptionValue('pdep')) else PDEPTH:=25; if Hasoption('r','ra') then begin if GetOptionValue('r','ra')='sd' then ra:=sdra else if GetOptionValue('r','ra')='mf' then ra:=mfra; end else ra:=mfra; if Hasoption('b','BD') then BD:=strtoint(GetOptionValue('b','BD')) else BD:=1350; // unit kg/m3 if Hasoption('m','MC_f') then McCool_factor:=strtofloat(GetOptionValue('m','MC_f')) else McCool_factor:=1.0; Cal_Frac:=false; if Hasoption('f','frac') then begin if (GetOptionValue('f','frac')='1') then begin Cal_Frac:=true; ra:=sdra; end //only do fraction calculations with steep descent algorithm else Cal_Frac:=false; end; Write_map:=true; if Hasoption('w','write_output') then begin if (GetOptionValue('w','Write_map')='1') then Write_map:=true else Write_map:=false; end; Write_txt:=false; if Hasoption('w','write_output') then begin if (GetOptionValue('w','Write_map')='1') then Write_map:=true else Write_map:=false; end; Write_detail_Exp:=true; if Hasoption('w_d_exp') then begin if (GetOptionValue('w_d_exp')='1') then Write_detail_Exp:=true else Write_detail_Exp:=false; end; Parcel_File_Format:=INT2S; if Hasoption('Par_Data_Type') then begin if (GetOptionValue('Par_Data_Type')='INT2S') then Parcel_File_Format:=INT2S else if (GetOptionValue('Par_Data_Type')='INT4S') then Parcel_File_Format:=INT4S; end; if Hasoption('erosion_start_year') then erosion_start_year:=strtoint(GetOptionValue('erosion_start_year')) else erosion_start_year:=2000; if Hasoption('erosion_end_year') then erosion_end_year:=strtoint(GetOptionValue('erosion_end_year')) else erosion_end_year:=2050; // variables for C cycling if Hasoption('depth_interval') then depth_interval:=strtoint(GetOptionValue('depth_interval')) else depth_interval:=5; if Hasoption('depth') then depth:=strtoint(GetOptionValue('depth')) else depth:=150; layer_num:=round(depth/depth_interval); if Hasoption('tillage_depth') then tillage_depth:=strtoint(GetOptionValue('tillage_depth')) else tillage_depth:=25; if Hasoption('time_equilibrium') then time_equilibrium:=strtoint(GetOptionValue('time_equilibrium')) else time_equilibrium:=1000; if Hasoption('deltaC13_ini_top') then deltaC13_ini_top:=strtofloat(GetOptionValue('deltaC13_ini_top')) else deltaC13_ini_top:=-27.0; if Hasoption('deltaC13_ini_bot') then deltaC13_ini_bot:=strtofloat(GetOptionValue('deltaC13_ini_bot')) else deltaC13_ini_bot:=-25.0; if Hasoption('deltaC14_ini_top') then deltaC14_ini_top:=strtofloat(GetOptionValue('deltaC14_ini_top')) else deltaC14_ini_top:=50.0; if Hasoption('deltaC14_ini_bot') then deltaC14_ini_bot:=strtofloat(GetOptionValue('deltaC14_ini_bot')) else deltaC14_ini_bot:=-500.0; if Hasoption('k1') then k1:=strtofloat(GetOptionValue('k1')) else k1:=2.1; if Hasoption('k2') then k2:=strtofloat(GetOptionValue('k2')) else k2:=0.03; if Hasoption('k3') then k3:=strtofloat(GetOptionValue('k3')) else k3:=0.005; if Hasoption('hAS') then hAS:=strtofloat(GetOptionValue('hAS')) else hAS:=0.12; if Hasoption('hAP') then hAP:=strtofloat(GetOptionValue('hAP')) else hAP:=0.02; if Hasoption('hSP') then hSP:=strtofloat(GetOptionValue('hSP')) else hSP:=0.02; if Hasoption('r0') then r0:=strtofloat(GetOptionValue('r0')) else r0:=1; if Hasoption('C_input') then C_input:=strtofloat(GetOptionValue('C_input')) else C_input:=0.7;// input from root if Hasoption('C_input2') then C_input2:=strtofloat(GetOptionValue('C_input2')) else C_input2:=0.5;// input from manure, residue if Hasoption('r_exp') then r_exp:=strtofloat(GetOptionValue('r_exp')) else r_exp:=3.30; if Hasoption('i_exp') then i_exp:=strtofloat(GetOptionValue('i_exp')) else i_exp:=6; if Hasoption('C13_discri') then C13_discri:=strtofloat(GetOptionValue('C13_discri')) else C13_discri:=0.9985; if Hasoption('C14_discri') then C14_discri:=strtofloat(GetOptionValue('C14_discri')) else C14_discri:=0.9985; if Hasoption('deltaC13_input_default') then deltaC13_input_default:=strtofloat(GetOptionValue('deltaC13_input_default')) else deltaC13_input_default:=-30.0; if Hasoption('deltaC14_input_default') then deltaC14_input_default:=strtofloat(GetOptionValue('deltaC14_input_default')) else deltaC14_input_default:=100.0; if Hasoption('Cs137_input_default') then Cs137_input_default:=strtofloat(GetOptionValue('Cs137_input_default')) else Cs137_input_default:=0.0; if Hasoption('Sand_ini_top') then Sand_ini_top:=strtofloat(GetOptionValue('Sand_ini_top')) else Sand_ini_top:=15; if Hasoption('Silt_ini_top') then Silt_ini_top:=strtofloat(GetOptionValue('Silt_ini_top')) else Silt_ini_top:=70; if Hasoption('Clay_ini_top') then Clay_ini_top:=strtofloat(GetOptionValue('Clay_ini_top')) else Clay_ini_top:=15; if Hasoption('Sand_ini_bot') then Sand_ini_bot:=strtofloat(GetOptionValue('Sand_ini_bot')) else Sand_ini_bot:=15; if Hasoption('Silt_ini_bot') then Silt_ini_bot:=strtofloat(GetOptionValue('Silt_ini_bot')) else Silt_ini_bot:=70; if Hasoption('Clay_ini_bot') then Clay_ini_bot:=strtofloat(GetOptionValue('Clay_ini_bot')) else Clay_ini_bot:=15; if Hasoption('K0') then K0:=strtofloat(GetOptionValue('K0')) else K0:=0.5; if Hasoption('Kfzp') then Kfzp:=strtofloat(GetOptionValue('Kfzp')) else Kfzp:=0.15; if Hasoption('v0') then v0:=strtofloat(GetOptionValue('v0')) else v0:=0.2; if Hasoption('vfzp') then vfzp:=strtofloat(GetOptionValue('vfzp')) else vfzp:=0.15; if Hasoption('a_erero') then a_erero:=strtofloat(GetOptionValue('a_erero')) else a_erero:=1.0; if Hasoption('b_erero') then b_erero:=strtofloat(GetOptionValue('b_erero')) else b_erero:=2000.0; if Hasoption('b_erdepo') then b_erdepo:=strtofloat(GetOptionValue('b_erdepo')) else b_erdepo:=-4000.0; if Hasoption('time_step') then time_step:=strtoint(GetOptionValue('time_step')) else time_step:=5; C_input:=C_input*time_step; C_input2:=C_input2*time_step; k1:=k1*time_step; k2:=k2*time_step; k3:=k3*time_step; K0:=K0*time_step; v0:=v0*time_step; unstable:=FALSE; end; procedure TWATEMApplication.DoRun; var Time:String; ErrorMsg: String; i: integer; begin StartClock; writeln('WATEM V4 BETA version DK Jan 2016'); writeln('Reference: Van Oost et al 2000, Landscape Ecology'); Set_Parameter_Values; writeln('Reading data from: ',GetCurrentDir); GetRFile(DTM,dtmfilename); write('Dem '); GetRFile(RKCP,RKCPfilename); write('RKCP '); GetGFile(ktc,ktcfilename); write('ktc '); If Parcel_File_Format=INT4S then Get32bitGFile(LS,prcfilename,PRC) else GetGFile(PRC,prcfilename); writeln('PRC '); write('Allocating Memory'); Allocate_Memory; writeln(': Done'); //CalculateSlopeAspect; writeln('Topo calculations'); Topo_Calculations(ra,DTM, LS, SLOPE, ASPECT, UPAREA, TFCA); If Write_map then writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'_LS', LS); writeln('Water Erosion Module'); outfilename_temp:=outfilename; //Water(WATEREROS,A12_eros, S12_eros, P12_eros, LS, RKCP, ktc, TFCA, ra, BD); //Carbon_Initilization; Carbon; write_txt:=TRUE; if write_txt then export_txt; //test_AD; writeln('Writing Output: Maps'); If Write_map then begin writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/Werodep_in_m', WATEREROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/WExport_in_m', W_Export); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/C_stock', C_stock); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/C_stock_equili', C_stock_equili); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A12_erosion', A12_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S12_erosion', S12_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P12_erosion', P12_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A13_erosion', A13_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S13_erosion', S13_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P13_erosion', P13_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A14_erosion', A14_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S14_erosion', S14_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P14_erosion', P14_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A14_erosion', Clay_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S14_erosion', Silt_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P14_erosion', Sand_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P14_erosion', Rock_EROS); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/CS137_activity', CS137_ACTIVITY); for i:=1 to layer_num do begin writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A12_'+inttostr(i), A12[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S12_'+inttostr(i), S12[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P12_'+inttostr(i), P12[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A13_'+inttostr(i), A13[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S13_'+inttostr(i), S13[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P13_'+inttostr(i), P13[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/A14_'+inttostr(i), A14[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/S14_'+inttostr(i), S14[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/P14_'+inttostr(i), P14[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/CLAY_'+inttostr(i), CLAY[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/SILT_'+inttostr(i), SILT[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/SAND_'+inttostr(i), SAND[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/ROCK_'+inttostr(i), ROCK[i]); writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'/CS137_'+inttostr(i), CS137[i]); end; end; writeln('Writing Output: Summary Statistics'); Write_STAT(WATEREROS, outfilename+'STAT_Water'); if KTIL>0 then begin writeln('Tillage Erosion Module'); tillage_dif; if Write_map then writeIdrisi32file(ncol,nrow, ChangeFileExt(outfilename,'')+'_Terodep_in_m', TILEROS); Write_STAT(TILEROS, ChangeFileExt(outfilename,'')+'STAT_Tillage'); end; writeln('Releasing Memory'); Release_Memory; Time:=StopClock; Writeln('Program Execution Time: ',Time,' sec'); Terminate; end; constructor TWATEMApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TWATEMApplication.Destroy; begin inherited Destroy; end; procedure TWATEMApplication.WriteHelp; begin { add your help code here } writeln('Usage: ',ExeName,' -h'); end; var Application: TWATEMApplication; begin Application:=TWATEMApplication.Create(nil); Application.Run; Application.Free; end.
unit Bind4D.Component.Edit; interface uses {$IFDEF HAS_FMX} FMX.StdCtrls, FMX.Edit, {$ELSE} Vcl.ExtCtrls, Vcl.StdCtrls, {$ENDIF} Bind4D.Component.Interfaces, Bind4D.Attributes, System.JSON; type TBind4DComponentEdit = class(TInterfacedObject, iBind4DComponent) private FComponent : TEdit; FAttributes : iBind4DComponentAttributes; function onChangeAttribute : TBind4DComponentEdit; //function onExitAttribute : TBind4DComponentEdit; function especialValidate : TBind4DComponentEdit; procedure TryValidations; public constructor Create(var aValue : TEdit); destructor Destroy; override; class function New(var aValue : TEdit) : iBind4DComponent; function Attributes : iBind4DComponentAttributes; function AdjusteResponsivity : iBind4DComponent; function FormatFieldGrid (aAttr : FieldDataSetBind) : iBind4DComponent; function ApplyStyles : iBind4DComponent; function ApplyText : iBind4DComponent; function ApplyImage : iBind4DComponent; function ApplyValue : iBind4DComponent; function ApplyRestData : iBind4DComponent; function GetValueString : String; function GetCaption : String; function Clear : iBind4DComponent; end; implementation uses Bind4D.Component.Attributes, Bind4D.Utils, Bind4D.ChangeCommand, Bind4D.Types, Data.DB, System.SysUtils, Bind4D.Utils.Rtti, Vcl.Graphics, System.Variants, ZC4B.Interfaces, ZC4B; { TBind4DComponentEdit } function TBind4DComponentEdit.FormatFieldGrid( aAttr: FieldDataSetBind): iBind4DComponent; begin Result := Self; end; function TBind4DComponentEdit.AdjusteResponsivity: iBind4DComponent; begin Result := Self; end; function TBind4DComponentEdit.ApplyImage: iBind4DComponent; begin Result := Self; end; function TBind4DComponentEdit.ApplyRestData: iBind4DComponent; begin Result := Self; end; function TBind4DComponentEdit.ApplyStyles: iBind4DComponent; begin Result := Self; {$IFDEF HAS_FMX} FComponent.StyledSettings := FAttributes.StyleSettings; FComponent.TextSettings.FontColor := FAttributes.FontColor; FComponent.TextSettings.Font.Family := FAttributes.FontName; {$ELSE} FComponent.StyleElements := FAttributes.StyleSettings; FComponent.Color := FAttributes.Color; FComponent.Font.Color := FAttributes.FontColor; FComponent.Font.Name := FAttributes.FontName; {$ENDIF} FComponent.Font.Size := FAttributes.FontSize; TCommandMaster.New.Add( FComponent, procedure (Sender : TObject) begin if Trim((Sender as TEdit).Text) <> '' then if Trim((Sender as TEdit).HelpKeyword) <> '' then (Sender as TEdit).Color := StringToColor((Sender as TEdit).HelpKeyword); end); onChangeAttribute; //onExitAttribute; especialValidate; end; function TBind4DComponentEdit.ApplyText: iBind4DComponent; begin Result := Self; FComponent.Text := FAttributes.ValueVariant; end; function TBind4DComponentEdit.ApplyValue: iBind4DComponent; begin Result := Self; if VarIsNull(FAttributes.ValueVariant) then exit; case FAttributes.FieldType of ftMemo, ftFmtMemo, ftFixedChar, ftWideString, ftFixedWideChar, ftWideMemo, ftLongWord, ftString : begin FComponent.Text := FAttributes.ValueVariant; end; ftLargeint, ftSmallint, ftShortint, ftInteger: begin FComponent.Text := IntToStr(FAttributes.ValueVariant); end; ftBoolean: begin FComponent.Text := FAttributes.ValueVariant.ToString; end; ftFloat, ftCurrency: begin FComponent.Text := FloatToStr(FAttributes.ValueVariant); end; end; end; function TBind4DComponentEdit.Attributes: iBind4DComponentAttributes; begin Result := FAttributes; end; function TBind4DComponentEdit.Clear: iBind4DComponent; begin Result := Self; FComponent.Text := ''; end; procedure TBind4DComponentEdit.TryValidations; var aAttrNotNull: fvNotNull; begin if RttiUtils.TryGet<fvNotNull>(FComponent, aAttrNotNull) then if Trim(FComponent.Text) = '' then begin if FComponent.Enabled then begin FComponent.SetFocus; FComponent.HelpKeyword := ColorToString(FComponent.Color); FComponent.Color := aAttrNotNull.ErrorColor; raise Exception.Create(aAttrNotNull.Msg); end; end; end; constructor TBind4DComponentEdit.Create(var aValue : TEdit); begin FAttributes := TBind4DComponentAttributes.Create(Self); FComponent := aValue; end; destructor TBind4DComponentEdit.Destroy; begin inherited; end; function TBind4DComponentEdit.especialValidate: TBind4DComponentEdit; var AttrBindFormat : ComponentBindFormat; begin Result := Self; if RttiUtils.TryGet<ComponentBindFormat>(FComponent, AttrBindFormat) then begin case AttrBindFormat.EspecialType of teCoin : begin TCommandMaster.New.Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarMoeda((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end ) end; teCell : begin TCommandMaster.New.Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarCelular((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end ) end; teCPF : begin TCommandMaster.New.Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarCPF((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end ) end; teCNPJ : begin TCommandMaster .New .Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarCNPJ((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end) end; teCEP : begin TCommandMaster .New .Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarCEP((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end) end; tePhone : begin TCommandMaster .New .Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormatarPhone((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end) end; tePercent : begin TCommandMaster .New .Add( FComponent, procedure (Sender : TObject) begin (Sender as TEdit).Text := TBind4DUtils.FormataPercentual((Sender as TEdit).Text); (Sender as TEdit).SelStart := Length((Sender as TEdit).Text); end) end; teNull : ; end; end; end; function TBind4DComponentEdit.GetCaption: String; begin Result := ''; end; function TBind4DComponentEdit.GetValueString: String; var aAttr : ComponentBindFormat; begin Result := FComponent.Text; TryValidations; if RttiUtils.TryGet<ComponentBindFormat>(FComponent, aAttr) then begin case aAttr.EspecialType of teNull : Result := FComponent.Text; teCoin : Result := TBind4DUtils.ExtrairMoeda(FComponent.Text); else Result := TBind4DUtils.ApenasNumeros(FComponent.Text); end; end; end; class function TBind4DComponentEdit.New(var aValue : TEdit) : iBind4DComponent; begin Result := Self.Create(aValue); end; function TBind4DComponentEdit.onChangeAttribute : TBind4DComponentEdit; begin Result := Self; FComponent.OnChange := TBind4DUtils .AnonProc2NotifyEvent( FComponent, procedure (Sender : TObject) begin TCommandMaster.New.Execute((Sender as TEdit)); end); end; //function TBind4DComponentEdit.onExitAttribute: TBind4DComponentEdit; //begin // Result := Self; // FComponent.OnExit := // TBind4DUtils // .AnonProc2NotifyEvent( // FComponent, // procedure (Sender : TObject) // begin // TCommandMaster.New.Execute((Sender as TEdit)); // end); //end; end.
unit fStyle; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.UITypes, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, uGlobal; type TStyleNameForm = class(TForm) BitBtn1: TBitBtn; StyleListBox: TListBox; EditName: TEdit; procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure StyleListBoxDblClick(Sender: TObject); private StyleAltered: Boolean; procedure SaveToFile; public Selecting: Boolean; end; var StyleNameForm: TStyleNameForm; //==================================================================== implementation //==================================================================== uses fMain, fFuncts, fNumeric; {$R *.dfm} procedure TStyleNameForm.FormShow(Sender: TObject); procedure ReadStyles; var F: File of TPlotStyle; s: TPlotStyle; so: TPlotStyleObject; begin AssignFile(F, StyleFName); Reset(F); while not Eof(F) do begin Read(F, s); so := TPlotStyleObject.Create(s); StyleListBox.Items.AddObject(String(s.StyleName), so); end; CloseFile(F); end; begin if Selecting then begin StyleListBox.Enabled := true; StyleListBox.ItemIndex := -1; EditName.Visible := false; Caption := ' Select a style'; BitBtn1.Hint := 'OK to apply selected style.'; StyleListBox.Hint := 'Press Del to delete an item.'; Hint := 'Press escape to deselect style.' end else begin StyleListBox.Enabled := false; EditName.Visible := true; Caption := ' Save a style as...'; BitBtn1.Hint := 'OK to add the current graph style.'; StyleListBox.Hint := ''; Hint := ''; end; StyleAltered := false; if FileExists(StyleFName) then ReadStyles; StyleListBox.ItemIndex := -1; with Layout do begin if Left = 0 then begin Left := (Screen.Width - Width) div 2; Top := (Screen.Height - Height) div 2; end else begin Left := StyleLeft; Top := StyleTop; end; end; end; procedure TStyleNameForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ApplyStyle; var s: TPlotStyle; so: TPlotStyleObject; i: integer; begin if StyleListbox.ItemIndex = -1 then exit; so := TPlotStyleObject(StyleListBox.Items.Objects[StyleListBox.ItemIndex]); s := so.Style; with GraphData do begin AreaAlpha := s.AreaAlpha; FontName := String(s.FontName); FontStyle := s.FontStyle; FontSize := s.FontSize; AxisWidth := s.AxisWidth; xMinorGrad := s.xMinorGrad; yMinorGrad := s.yMinorGrad; xMajorGrad := s.xMajorGrad; yMajorGrad := s.yMajorGrad; MinorWidth := s.MinorWidth; MajorWidth := s.MajorWidth; CoordWidth := s.CoordWidth; dydxWidth := s.dydxWidth; d2ydx2Width := s.d2ydx2Width; IntegCount := s.IntegCount; ydxWidth := s.ydxWidth; BackColor := s.BackColor; GridColor := s.GridColor; xAxisColor := s.xAxisColor; yAxisColor := s.yAxisColor; CoordColor := s.CoordColor; dydxColor := s.dydxColor; d2ydx2Color := s.d2ydx2Color; ydxColor := s.ydxColor; PosAreaColor := s.PosAreaColor; NegAreaColor := s.NegAreaColor; Grid := s.Grid; with FunctionsForm.CheckListBox do begin for i := 0 to Count -1 do with TPlotDataObject(Items.Objects[i]).Data do begin PlotWidth := s.Pens[i mod 12].PenWidth; PlotColor := s.Pens[i mod 12].PenColor; end; end; with NumericForm.CheckListBox do begin for i := 0 to Count -1 do with TNumericObject(Items.Objects[i]).Data do begin PlotWidth := s.NumLines[i mod 12].PenWidth; PlotColor := s.NumLines[i mod 12].PenColor; PointSize := s.NumPoints[i mod 12].PenWidth; PointColor := s.NumPoints[i mod 12].PenColor; end; end; end; MainForm.GLViewer.Buffer.BackgroundColor := GraphData.BackColor; end; { ApplyStyle } function UniqueName(s: string): Boolean; var i: integer; Found: Boolean; begin i := 0; Found := false; while not Found and (i < StyleListBox.Items.Count) do begin Found := LowerCase(s) = LowerCase(StyleListBox.Items[i]); Inc(i); end; Result := not Found; end; { UniqueName } procedure AddToList; var s: TPlotStyle; so: TPlotStyleObject; i: integer; begin with GraphData do begin s.AreaAlpha := AreaAlpha; s.FontName := ShortString(FontName); s.StyleName := ShortString(EditName.Text); s.FontStyle := FontStyle; s.FontSize := FontSize; s.AxisWidth := AxisWidth; s.xMinorGrad := xMinorGrad; s.yMinorGrad := yMinorGrad; s.xMajorGrad := xMajorGrad; s.yMajorGrad := yMajorGrad; s.MinorWidth := MinorWidth; s.MajorWidth := MajorWidth; s.CoordWidth := CoordWidth; s.dydxWidth := dydxWidth; s.d2ydx2Width := d2ydx2Width; s.IntegCount := IntegCount; s.ydxWidth := ydxWidth; s.BackColor := BackColor; s.GridColor := GridColor; s.xAxisColor := xAxisColor; s.yAxisColor := yAxisColor; s.CoordColor := CoordColor; s.dydxColor := dydxColor; s.d2ydx2Color := d2ydx2Color; s.ydxColor := ydxColor; s.PosAreaColor := PosAreaColor; s.NegAreaColor := NegAreaColor; s.Grid := Grid; for i := 0 to 11 do begin s.Pens[i].PenWidth := 1; s.Pens[i].PenColor := clBlack; end; with FunctionsForm.CheckListBox do begin for i := 0 to Count -1 do with TPlotDataObject(Items.Objects[i]).Data do begin s.Pens[i mod 12].PenWidth := PlotWidth; s.Pens[i mod 12].PenColor := PlotColor; end; end; with NumericForm.CheckListBox do begin for i := 0 to Count -1 do with TNumericObject(Items.Objects[i]).Data do begin s.NumLines[i mod 12].PenWidth := PlotWidth; s.NumLines[i mod 12].PenColor := PlotColor; s.NumPoints[i mod 12].PenWidth := PointSize; s.NumPoints[i mod 12].PenColor := PointColor; end; end; end; so := TPlotStyleObject.Create(s); StyleListBox.Items.AddObject(EditName.Text, so); SaveToFile; end; { AddToList } var i: integer; begin if Selecting then ApplyStyle else if StyleAltered then begin EditName.Text := Trim(EditName.Text); if EditName.Text <> '' then begin if UniqueName(EditName.Text) then AddToList else begin MessageDlg('The Style Name entered is not unique.', mtError, [mbOK], 0); CanClose := false; end; end; end; if CanClose then begin for i := 0 to StyleListBox.Items.Count -1 do StyleListBox.Items.Objects[i].Free; StyleListBox.Clear; end; with Layout do begin StyleLeft := Left; StyleTop := Top; end; end; procedure TStyleNameForm.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_DELETE then StyleAltered := true; end; procedure TStyleNameForm.EditKeyPress(Sender: TObject; var Key: Char); begin StyleAltered := true; end; procedure TStyleNameForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then StyleListBox.ItemIndex := -1; if (Key = VK_DELETE) and (StyleListBox.Items.Count > 0) then begin StyleListBox.DeleteSelected; SaveToFile; end; end; procedure TStyleNameForm.SaveToFile; var F: File of TPlotStyle; s: TPlotStyle; so: TPlotStyleObject; i: integer; begin AssignFile(F, StyleFName); Rewrite(F); for i := 0 to StyleListBox.Count -1 do begin so := TPlotStyleObject(StyleListBox.Items.Objects[i]); s := so.Style; write(F, s); end; CloseFile(F); end; procedure TStyleNameForm.StyleListBoxDblClick(Sender: TObject); begin Close; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_TYPES.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_TYPES; interface uses {$I uses.def} SysUtils, Classes, PAXCOMP_CONSTANTS; type TPauseException = class(EAbort) public constructor Create; end; THaltException = class(EAbort) public ExitCode: Integer; constructor Create(i_ExitCode: Integer); end; TWorkException = class(EAbort) end; PaxCompilerException = class(Exception) end; PaxCancelException = class(EAbort) end; TExitMode = (emExit, emBreak, emContinue); PaxExitException = class(EAbort) public Mode: TExitMode; end; {$IFDEF ARC} TPtrList = class(TList<Pointer>); {$ELSE} TPtrList = TList; {$ENDIF} TTypedList = class private function GetCount: Integer; function GetLast: TObject; protected {$IFDEF ARC} L: TList<TObject>; {$ELSE} L: TList; {$ENDIF} public constructor Create; destructor Destroy; override; procedure Clear; virtual; procedure RemoveAt(I: Integer); virtual; procedure InsertAt(I: Integer; X: TObject); procedure RemoveTop; procedure Remove(X: TObject); function IndexOf(P: Pointer): Integer; property Count: Integer read GetCount; property Last: TObject read GetLast; end; TIntegerList = class private {$IFDEF ARC} fItems: TList<Pointer>; {$ELSE} fItems: TList; {$ENDIF} fDupNo: Boolean; function GetItem(I: Integer): Integer; procedure SetItem(I: Integer; value: Integer); function GetCount: Integer; public constructor Create(DupNo: Boolean = false); destructor Destroy; override; procedure Clear; function Add(value: Integer): Integer; procedure Insert(I: Integer; value: Integer); function IndexOf(value: Integer): Integer; function LastIndexOf(value: Integer): Integer; procedure RemoveAt(I: Integer); procedure DeleteValue(value: Integer); function Top: Integer; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function SaveToPtr(P: Pointer): Integer; function LoadFromPtr(P: Pointer): Integer; procedure SaveToWriter(S: TWriter); procedure LoadFromReader(S: TReader); function Clone: TIntegerList; function BinSearch(const Key: Integer): Integer; procedure QuickSort; overload; procedure QuickSort(Start, Stop: Integer); overload; property Count: Integer read GetCount; property Items[I: Integer]: Integer read GetItem write SetItem; default; property Last: Integer read Top; end; TIntegerStack = class(TIntegerList) public procedure Push(value: Integer); function Pop: Integer; function Depth(value: Integer): Integer; end; TAssocIntegers = class private function GetCount: Integer; public Keys, Values: TIntegerList; constructor Create; destructor Destroy; override; procedure Clear; procedure Add(Key, Value: Integer); procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function SaveToPtr(P: Pointer): Integer; function LoadFromPtr(P: Pointer): Integer; function Clone: TAssocIntegers; procedure RemoveAt(I: Integer); function IndexOf(K, V: Integer): Integer; function Inside(c: Integer): Boolean; property Count: Integer read GetCount; end; TAssocStrings = class private function GetCount: Integer; function GetValue(const Key: String): String; procedure SetValue(const Key, Value: String); public Keys, Values: TStringList; constructor Create; destructor Destroy; override; procedure Clear; procedure Add(const Key, Value: String); procedure RemoveAt(I: Integer); property Count: Integer read GetCount; property ValueByKey[const S: String]: String read GetValue write SetValue; default; end; TStringObjectList = class(TStringList) private procedure ClearObjects; public procedure Clear; override; destructor Destroy; override; end; TAnonymContextRec = class public SubId: Integer; BindList: TIntegerList; constructor Create; destructor Destroy; override; end; TAnonymContextStack = class(TTypedList) private function GetRecord(I: Integer): TAnonymContextRec; function GetTop: TAnonymContextRec; public function Push(SubId: Integer): TAnonymContextRec; procedure Pop; property Top: TAnonymContextRec read GetTop; property Records[I: Integer]: TAnonymContextRec read GetRecord; default; end; TMessageRec = class public msg_id: Cardinal; FullName: String; Class_Name: String; Address: Pointer; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); end; TMessageList = class(TTypedList) private function GetRecord(I: Integer): TMessageRec; public function IndexOf(const FullName: String): Integer; function AddRecord: TMessageRec; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function CreateDmtTable(const AClassName: String; var Size: Integer): Pointer; property Records[I: Integer]: TMessageRec read GetRecord; default; end; TActualParamRec = class public SubId: Integer; Params: TPtrList; constructor Create; destructor Destroy; override; end; TActualParamList = class(TTypedList) private function GetRecord(I: Integer): TActualParamRec; public function Add(SubId: Integer; Param: Pointer): TActualParamRec; function Find(SubId: Integer): TActualParamRec; procedure Remove(SubId: Integer); property Records[I: Integer]: TActualParamRec read GetRecord; default; end; TExportRec = class public Offset: Cardinal; // prog Name: String; // prog Address: Cardinal; // pe NameAddress: Cardinal; // pe Ordinal: Word; // pe procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); end; TExportList = class(TTypedList) private function GetRecord(I: Integer): TExportRec; public function Add: TExportRec; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); property Records[I: Integer]: TExportRec read GetRecord; default; end; TStreamRec = class public UnitName: String; Stream: TMemoryStream; constructor Create; destructor Destroy;override; end; TStreamList = class(TTypedList) private function GetRecord(I: Integer): TStreamRec; public function IndexOf(const UnitName: String): Integer; procedure AddFromStream(S: TStream; const FileName: String); procedure AddFromFile(const FileName: String); property Records[I: Integer]: TStreamRec read GetRecord; default; end; TUpStringList = class(TStringList) public function IndexOf(const S: String): Integer; override; end; TUndeclaredTypeRec = class public Id, ErrorIndex: Integer; end; TUndeclaredTypeList = class(TStringList) procedure Reset; end; TUndeclaredIdentRec = class public Id: Integer; ErrorIndex: Integer; end; TUndeclaredIdentList = class(TStringList) procedure Reset; end; THashArray = class private function GetMaxId: Integer; public A: array[0..MaxHash] of TIntegerList; constructor Create; destructor Destroy; override; procedure AddName(const S: String; Id: Integer); procedure DeleteName(const S: String; Id: Integer); procedure Clear; function Clone: THashArray; function GetList(const S: String): TIntegerList; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); property MaxId: Integer read GetMaxId; end; TFastStringList = class private L: TStringList; X: THashArray; public constructor Create; destructor Destroy; override; procedure Clear; function Add(const S: String): Integer; function IndexOfEx(const S: String; Upcase: Boolean): Integer; property StringList: TStringList read L; end; TExternRecKind = (erNone, erLevel, erTypeId, erOwnerId, erPatternId, erAncestorId, erReadId, erWriteId, ePropertyInBaseClassId, erGUID); TExternRec = class public Id: Integer; FullName: String; RecKind: TExternRecKind; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); end; TExternList = class(TTypedList) private function GetRecord(I: Integer): TExternRec; public function Add(Id: Integer; const FullName: String; RecKind: TExternRecKind): TExternRec; function Clone: TExternList; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); property Records[I: Integer]: TExternRec read GetRecord; default; end; TCheckProc = function (const TypeName: String; Data: Pointer; errKind: TExternRecKind): Boolean; TSomeTypeRec = class public Name: String; Id: Integer; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); end; TSomeTypeList = class(TTypedList) private function GetRecord(I: Integer): TSomeTypeRec; public function Add(const Name: String; Id: Integer): TSomeTypeRec; function Clone: TSomeTypeList; function IndexOf(const Name: String): Integer; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); property Records[I: Integer]: TSomeTypeRec read GetRecord; default; end; TVarPathRec = class public Id: Integer; VarCount: Int64; end; TVarPath = class(TTypedList) private function GetItem(I: Integer): TVarPathRec; public function Add(Id: Integer; VarCount: Int64): TVarPathRec; function IndexOf(VarCount: Int64): Integer; function LastIndexOf(VarCount: Int64): Integer; property Items[I: Integer]: TVarPathRec read GetItem; default; end; TVarPathList = class(TTypedList) private function GetPath(I: Integer): TVarPath; public function AddPath: TVarPath; procedure Add(Id: Integer; VarCount: Int64); function GetLevel(VarCount: Int64): Integer; property Pathes[I: Integer]: TVarPath read GetPath; default; end; TGuidRec = class public GUID: TGUID; Id: Integer; Name: String; GuidIndex: Integer; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); end; TGuidList = class(TTypedList) private function GetRecord(I: Integer): TGuidRec; public function Add(const GUID: TGUID; Id: Integer; const Name: String): TGuidRec; function Clone: TGuidList; function IndexOf(const GUID: TGUID): Integer; function GetGuidByID(Id: Integer): TGUID; function HasId(Id: Integer): Boolean; procedure SaveToStream(S: TWriter); procedure LoadFromStream(S: TReader); property Records[I: Integer]: TGuidRec read GetRecord; default; end; TStdTypeRec = class public Name: String; TypeID: Integer; Size: Integer; NativeName: String; end; TStdTypeList = class(TTypedList) private fPAX64: Boolean; function GetRecord(I: Integer): TStdTypeRec; public constructor Create; function Add(const TypeName: String; Size: Integer): Integer; function IndexOf(const S: String): Integer; function GetSize(TypeID: Integer): Integer; property Records[I: Integer]: TStdTypeRec read GetRecord; default; property PAX64: Boolean read fPAX64 write fPAX64; end; TAssocStringInt = class private function GetCount: Integer; public Keys: TStringList; Values: TIntegerList; constructor Create; destructor Destroy; override; procedure Clear; procedure Add(const Key: String); procedure AddValue(const Key: String; Value: Integer); procedure RemoveAt(I: Integer); procedure Pack; property Count: Integer read GetCount; end; TMacroRec = class public S1, S2: String; Params: TStringList; constructor Create; destructor Destroy; override; end; TMacroList = class(TTypedList) private function GetRecord(I: Integer): TMacroRec; public function Add(const S1, S2: String; Params: TStrings): TMacroRec; function IndexOf(const S1: String): Integer; property Records[I: Integer]: TMacroRec read GetRecord; default; end; implementation uses PAXCOMP_SYS; // TAssocStringInt ------------------------------------------------------------- constructor TAssocStringInt.Create; begin inherited; Keys := TStringList.Create; Values := TIntegerList.Create; end; destructor TAssocStringInt.Destroy; begin FreeAndNil(Keys); FreeAndNil(Values); inherited; end; procedure TAssocStringInt.RemoveAt(I: Integer); begin Keys.Delete(I); Values.RemoveAt(I); end; procedure TAssocStringInt.Clear; begin Keys.Clear; Values.Clear; end; function TAssocStringInt.GetCount: Integer; begin result := Keys.Count; end; procedure TAssocStringInt.Add(const Key: String); begin AddValue(Key, 0); end; procedure TAssocStringInt.AddValue(const Key: String; Value: Integer); begin Keys.Add(Key); Values.Add(Value); end; procedure TAssocStringInt.Pack; var I: Integer; begin for I := 0 to Count - 1 do {$IFDEF ARC} begin end; {$ELSE} Keys.Objects[I] := Pointer(Values[I]); {$ENDIF} end; // TTypedList ------------------------------------------------------------------ constructor TTypedList.Create; begin inherited; {$IFDEF ARC} L := TList<TObject>.Create; {$ELSE} L := TList.Create; {$ENDIF} end; destructor TTypedList.Destroy; begin Clear; L.Free; inherited; end; function TTypedList.GetCount: Integer; begin result := L.Count; end; procedure TTypedList.Clear; var I: Integer; begin for I:=0 to L.Count - 1 do {$IFDEF ARC} L[I] := nil; {$ELSE} TObject(L[I]).Free; {$ENDIF} L.Clear; end; function TTypedList.IndexOf(P: Pointer): Integer; begin result := L.IndexOf(P); end; function TTypedList.GetLast: TObject; begin result := TObject(L[Count - 1]); end; procedure TTypedList.RemoveAt(I: Integer); begin {$IFDEF ARC} L[I] := nil; {$ELSE} TObject(L[I]).Free; {$ENDIF} L.Delete(I); end; procedure TTypedList.InsertAt(I: Integer; X: TObject); begin L.Insert(I, X); end; procedure TTypedList.Remove(X: TObject); var I: Integer; begin I := IndexOf(X); if I >= 0 then RemoveAt(I); end; procedure TTypedList.RemoveTop; begin {$IFDEF ARC} L[Count - 1] := nil; {$ELSE} TObject(L[Count - 1]).Free; {$ENDIF} L.Delete(Count - 1); end; //-- TIntegerList -------------------------------------------------------------- constructor TIntegerList.Create(DupNo: Boolean = false); begin inherited Create; {$IFDEF ARC} fItems := TList<Pointer>.Create; {$ELSE} fItems := TList.Create; {$ENDIF} fDupNo := DupNo; end; destructor TIntegerList.Destroy; begin fItems.Free; inherited; end; function TIntegerList.Clone: TIntegerList; var I: Integer; begin result := TIntegerList.Create; for I:=0 to Count - 1 do result.Add(Items[I]); end; procedure TIntegerList.Clear; begin fItems.Clear; end; function TIntegerList.GetCount: Integer; begin result := fItems.Count; end; function TIntegerList.GetItem(I: Integer): Integer; begin result := Integer(fItems[I]); end; procedure TIntegerList.SetItem(I: Integer; value: Integer); begin fItems[I] := Pointer(value); end; function TIntegerList.Add(value: Integer): Integer; begin if fDupNo then begin result := IndexOf(value); if result >= 0 then Exit; end; result := fItems.Add(Pointer(value)); end; procedure TIntegerList.Insert(I: Integer; value: Integer); begin if fDupNo then if IndexOf(value) >= 0 then Exit; fItems.Insert(I, Pointer(value)); end; procedure TIntegerList.RemoveAt(I: Integer); begin fItems.Delete(I); end; procedure TIntegerList.DeleteValue(value: Integer); var I: Integer; begin I := IndexOf(value); if I >= 0 then fItems.Delete(I); end; function TIntegerList.IndexOf(value: Integer): Integer; begin result := fItems.IndexOf(Pointer(value)); end; function TIntegerList.LastIndexOf(value: Integer): Integer; var I: Integer; begin result := -1; for I := Count - 1 downto 0 do if fItems[I] = Pointer(value) then begin result := I; Exit; end; end; function TIntegerList.Top: Integer; begin if Count = 0 then RIE; result := Items[Count - 1]; end; function TIntegerList.BinSearch(const Key: Integer): Integer; var First: Integer; Last: Integer; Pivot: Integer; Found: Boolean; begin First := 0; Last := Count - 1; Found := False; Result := -1; while (First <= Last) and (not Found) do begin Pivot := (First + Last) div 2; if Integer(fItems[Pivot]) = Key then begin Found := True; Result := Pivot; end else if Integer(fItems[Pivot]) > Key then Last := Pivot - 1 else First := Pivot + 1; end; end; procedure TIntegerList.QuickSort; begin QuickSort(0, Count - 1); end; procedure TIntegerList.QuickSort(Start, Stop: Integer); var Left: Integer; Right: Integer; Mid: Integer; Pivot: Integer; Temp: Pointer; begin Left := Start; Right := Stop; Mid := (Start + Stop) div 2; Pivot := Integer(fItems[mid]); repeat while Integer(fItems[Left]) < Pivot do Inc(Left); while Pivot < Integer(fItems[Right]) do Dec(Right); if Left <= Right then begin Temp := fItems[Left]; fItems[Left] := fItems[Right]; // Swops the two Strings fItems[Right] := Temp; Inc(Left); Dec(Right); end; until Left > Right; if Start < Right then QuickSort(Start, Right); // Uses if Left < Stop then QuickSort(Left, Stop); // Recursion end; procedure TIntegerList.SaveToStream(S: TStream); var I, K: Integer; A: array of Integer; P: Pointer; begin K := Count; SaveIntegerToStream(K, S); if K = 0 then Exit; SetLength(A, K); for I:=0 to K - 1 do A[I] := Integer(fItems[I]); P := @A[0]; S.Write(P^, K * SizeOf(Integer)); end; procedure TIntegerList.LoadFromStream(S: TStream); var I, K: Integer; A: array of Integer; P: Pointer; begin Clear; K := LoadIntegerFromStream(S); if K = 0 then Exit; SetLength(A, K); P := @A[0]; S.Read(P^, K * SizeOf(Integer)); for I:=0 to K - 1 do Add(A[I]); end; function TIntegerList.SaveToPtr(P: Pointer): Integer; var I, K: Integer; begin K := Count; Move(K, P^, 4); P := ShiftPointer(P, 4); for I:=0 to Count - 1 do begin K := Integer(fItems[I]); Move(K, P^, 4); P := ShiftPointer(P, 4); end; result := (Count * 4) + 4; end; function TIntegerList.LoadFromPtr(P: Pointer): Integer; var I, K, Z: Integer; begin Move(P^, K, 4); P := ShiftPointer(P, 4); for I:=0 to K - 1 do begin Move(P^, Z, 4); P := ShiftPointer(P, 4); Add(Z); end; result := (Count * 4) + 4; end; procedure TIntegerList.SaveToWriter(S: TWriter); var I: Integer; begin S.WriteInteger(Count); for I:=0 to Count - 1 do S.WriteInteger(Integer(fItems[I])); end; procedure TIntegerList.LoadFromReader(S: TReader); var I, K: Integer; begin Clear; K := S.ReadInteger(); for I:=0 to K - 1 do Add(S.ReadInteger()); end; //-- TIntegerStack ------------------------------------------------------------- procedure TIntegerStack.Push(value: Integer); begin Add(value); end; function TIntegerStack.Pop: Integer; begin result := Items[Count - 1]; fItems.Delete(Count - 1); end; function TIntegerStack.Depth(value: Integer): Integer; var I: Integer; begin result := -1; for I:=Count - 1 downto 0 do begin Inc(result); if Items[I] = value then Exit; end; raise Exception.Create(errInternalError); end; // TAssocIntegers -------------------------------------------------------------- constructor TAssocIntegers.Create; begin inherited; Keys := TIntegerList.Create; Values := TIntegerList.Create; end; destructor TAssocIntegers.Destroy; begin Keys.Free; Values.Free; inherited; end; function TAssocIntegers.Inside(c: Integer): Boolean; var I: Integer; begin result := false; for I := 0 to Count - 1 do if (c >= Keys[I]) and (c <= Values[I]) then begin result := true; Exit; end; end; function TAssocIntegers.IndexOf(K, V: Integer): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if (Keys[I] = K) and (Values[I] = V) then begin result := I; Exit; end; end; procedure TAssocIntegers.RemoveAt(I: Integer); begin Keys.RemoveAt(I); Values.RemoveAt(I); end; procedure TAssocIntegers.Clear; begin Keys.Clear; Values.Clear; end; function TAssocIntegers.Clone: TAssocIntegers; begin result := TAssocIntegers.Create; result.Keys.Free; result.Keys := Keys.Clone; result.Values.Free; result.Values := Values.Clone; end; procedure TAssocIntegers.SaveToStream(S: TStream); begin Keys.SaveToStream(S); Values.SaveToStream(S); end; procedure TAssocIntegers.LoadFromStream(S: TStream); begin Keys.LoadFromStream(S); Values.LoadFromStream(S); end; function TAssocIntegers.SaveToPtr(P: Pointer): Integer; begin result := Keys.SaveToPtr(P); P := ShiftPointer(P, result); Inc(result, Values.SaveToPtr(P)); end; function TAssocIntegers.LoadFromPtr(P: Pointer): Integer; begin result := Keys.LoadFromPtr(P); P := ShiftPointer(P, result); Inc(result, Values.LoadFromPtr(P)); end; function TAssocIntegers.GetCount: Integer; begin result := Keys.Count; end; procedure TAssocIntegers.Add(Key, Value: Integer); begin Keys.Add(Key); Values.Add(Value); end; // TAssocStrings --------------------------------------------------------------- constructor TAssocStrings.Create; begin inherited; Keys := TStringList.Create; Values := TStringList.Create; end; destructor TAssocStrings.Destroy; begin Keys.Free; Values.Free; inherited; end; function TAssocStrings.GetValue(const Key: String): String; var I: Integer; begin I := Keys.IndexOf(Key); if I >= 0 then result := Values[I] else result := ''; end; procedure TAssocStrings.SetValue(const Key, Value: String); var I: Integer; begin I := Keys.IndexOf(Key); if I >= 0 then Values[I] := Value else Add(Key, Value); end; procedure TAssocStrings.RemoveAt(I: Integer); begin Keys.Delete(I); Values.Delete(I); end; procedure TAssocStrings.Clear; begin Keys.Clear; Values.Clear; end; function TAssocStrings.GetCount: Integer; begin result := Keys.Count; end; procedure TAssocStrings.Add(const Key, Value: String); begin Keys.Add(Key); Values.Add(Value); end; //-- TPauseException ----------------------------------------------------------- constructor TPauseException.Create; begin inherited Create(''); end; //-- THaltException ------------------------------------------------------------ constructor THaltException.Create(i_ExitCode: Integer); begin inherited Create(''); ExitCode := i_ExitCode; end; procedure TStringObjectList.ClearObjects; var I: Integer; begin for I := 0 to Count - 1 do if Objects[I] <> nil then begin {$IFDEF ARC} Objects[I] := nil; {$ELSE} Objects[I].Free; {$ENDIF} Objects[I] := nil; end; end; procedure TStringObjectList.Clear; begin ClearObjects; inherited; end; destructor TStringObjectList.Destroy; begin ClearObjects; inherited; end; constructor TAnonymContextRec.Create; begin inherited; BindList := TIntegerList.Create; end; destructor TAnonymContextRec.Destroy; begin BindList.Free; inherited; end; function TAnonymContextStack.GetRecord(I: Integer): TAnonymContextRec; begin result := TAnonymContextRec(L[I]); end; function TAnonymContextStack.GetTop: TAnonymContextRec; begin result := Records[Count - 1]; end; function TAnonymContextStack.Push(SubId: Integer): TAnonymContextRec; begin result := TAnonymContextRec.Create; result.SubId := SubId; L.Add(result); end; procedure TAnonymContextStack.Pop; begin RemoveAt(Count - 1); end; procedure TMessageRec.SaveToStream(S: TStream); begin S.Write(msg_id, SizeOf(msg_id)); SaveStringToStream(FullName, S); end; procedure TMessageRec.LoadFromStream(S: TStream); begin S.Read(msg_id, SizeOf(msg_id)); FullName := LoadStringFromStream(S); end; function TMessageList.IndexOf(const FullName: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Records[I].FullName = FullName then begin result := I; Exit; end; end; function TMessageList.AddRecord: TMessageRec; begin result := TMessageRec.Create; L.Add(result); end; function TMessageList.GetRecord(I: Integer): TMessageRec; begin result := TMessageRec(L[I]); end; procedure TMessageList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(K)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TMessageList.LoadFromStream(S: TStream); var I, K: Integer; begin S.Read(K, SizeOf(K)); for I := 0 to K - 1 do AddRecord.LoadFromStream(S); end; function TMessageList.CreateDmtTable(const AClassName: String; var Size: Integer): Pointer; var I, K: Integer; DmtMethodList: PDmtMethodList; begin K := 0; for I := 0 to Count - 1 do if StrEql(Records[I].Class_Name, AClassName) then begin Inc(K); end; if K = 0 then result := nil else begin Size := SizeOf(Word) + K * SizeOf(SmallInt) + K * SizeOf(Pointer); result := AllocMem(Size); PDmtTable(result)^.Count := K; DmtMethodList := @PDmtTable(result)^.IndexList[K]; K := 0; for I := 0 to Count - 1 do if StrEql(Records[I].Class_Name, AClassName) then begin PDmtTable(result)^.IndexList[K] := Records[I].msg_id; DmtMethodList[K] := Records[I].Address; Inc(K); end; end; end; constructor TActualParamRec.Create; begin inherited; Params := TPtrList.Create; end; destructor TActualParamRec.Destroy; begin Params.Free; inherited; end; function TActualParamList.GetRecord(I: Integer): TActualParamRec; begin result := TActualParamRec(L[I]); end; function TActualParamList.Add(SubId: Integer; Param: Pointer): TActualParamRec; begin result := Find(SubId); if result = nil then begin result := TActualParamRec.Create; result.SubId := SubId; L.Add(result); end; result.Params.Add(Param); end; function TActualParamList.Find(SubId: Integer): TActualParamRec; var I: Integer; begin result := nil; for I := Count - 1 downto 0 do if Records[I].SubId = SubId then begin result := Records[I]; Exit; end; end; procedure TActualParamList.Remove(SubId: Integer); var I: Integer; begin for I := Count - 1 downto 0 do if Records[I].SubId = SubId then begin RemoveAt(I); Exit; end; end; procedure TExportRec.SaveToStream(S: TStream); begin SaveStringToStream(Name, S); S.Write(Offset, SizeOf(Offset)); end; procedure TExportRec.LoadFromStream(S: TStream); begin Name := LoadStringFromStream(S); S.Read(Offset, SizeOf(Offset)); end; function TExportList.GetRecord(I: Integer): TExportRec; begin result := TExportRec(L[I]); end; function TExportList.Add: TExportRec; begin result := TExportRec.Create; L.Add(result); result.Ordinal := Count; end; procedure TExportList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(K)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TExportList.LoadFromStream(S: TStream); var I, K: Integer; begin S.Read(K, SizeOf(K)); for I := 0 to K - 1 do Add.LoadFromStream(S); end; constructor TStreamRec.Create; begin inherited; Stream := TMemoryStream.Create; end; destructor TStreamRec.Destroy; begin inherited; Stream.Free; end; function TStreamList.GetRecord(I: Integer): TStreamRec; begin result := TStreamRec(L[I]); end; function TStreamList.IndexOf(const UnitName: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(UnitName, Records[I].UnitName) then begin result := I; Exit; end; end; procedure TStreamList.AddFromStream(S: TStream; const FileName: String); var UnitName: String; R: TStreamRec; begin UnitName := ExtractFullOwner(FileName); if IndexOf(UnitName) <> -1 then Exit; R := TStreamRec.Create; R.UnitName := UnitName; R.Stream.LoadFromStream(S); L.Add(R); end; procedure TStreamList.AddFromFile(const FileName: String); var UnitName: String; R: TStreamRec; begin UnitName := ExtractFullOwner(FileName); if IndexOf(UnitName) <> -1 then Exit; R := TStreamRec.Create; R.UnitName := UnitName; R.Stream.LoadFromFile(FileName); L.Add(R); end; // TUpStringList --------------------------------------------------------------- function TUpStringList.IndexOf(const S: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(Strings[I], S) then begin result := I; Exit; end; end; // TUndeclaredTypeList --------------------------------------------------------- procedure TUndeclaredTypeList.Reset; var I: Integer; begin for I:= 0 to Count - 1 do {$IFDEF ARC} Objects[I] := nil; {$ELSE} Objects[I].Free; {$ENDIF} Clear; end; // TUndeclaredIdentList -------------------------------------------------------- procedure TUndeclaredIdentList.Reset; var I: Integer; begin for I:= 0 to Count - 1 do {$IFDEF ARC} Objects[I] := nil; {$ELSE} Objects[I].Free; {$ENDIF} Clear; end; constructor THashArray.Create; var I: Integer; begin for I:=0 to MaxHash do A[I] := TIntegerList.Create; end; procedure THashArray.SaveToStream(S: TWriter); var I: Integer; begin for I:=0 to MaxHash do A[I].SaveToWriter(S); end; procedure THashArray.LoadFromStream(S: TReader); var I: Integer; begin for I:=0 to MaxHash do A[I].LoadFromReader(S); end; procedure THashArray.Clear; var I: Integer; begin for I:=0 to MaxHash do A[I].Clear; end; destructor THashArray.Destroy; var I: Integer; begin for I:=0 to MaxHash do A[I].Free; end; function THashArray.GetList(const S: String): TIntegerList; var H: Integer; begin H := HashNumber(S); result := A[H]; end; function THashArray.GetMaxId: Integer; var I, J: Integer; begin result := 0; for I:=0 to MaxHash do for J := 0 to A[I].Count - 1 do if A[I][J] > result then result := A[I][J]; end; procedure THashArray.AddName(const S: String; Id: Integer); var H: Integer; begin if S = '' then Exit; H := HashNumber(S); with A[H] do Add(Id); end; procedure THashArray.DeleteName(const S: String; Id: Integer); var H: Integer; begin if S = '' then Exit; H := HashNumber(S); with A[H] do DeleteValue(Id); end; function THashArray.Clone: THashArray; var I, J: Integer; begin result := THashArray.Create; for I:=0 to MaxHash do begin for J:=0 to A[I].Count - 1 do result.A[I].Add(A[I][J]); end; end; // TFastStringList ------------------------------------------------------------- constructor TFastStringList.Create; begin inherited; L := TStringList.Create; X := THashArray.Create; end; destructor TFastStringList.Destroy; begin L.Free; X.Free; inherited; end; procedure TFastStringList.Clear; begin L.Clear; X.Clear; end; function TFastStringList.Add(const S: String): Integer; var H: Integer; begin H := HashNumber(S); result := L.Add(S); X.A[H].Add(result); end; function TFastStringList.IndexOfEx(const S: String; Upcase: Boolean): Integer; var I, J: Integer; List: TIntegerList; begin result := -1; List := X.GetList(S); for I := 0 to List.Count - 1 do begin J := List[I]; if Upcase then begin if StrEql(L[J], S) then begin result := J; Exit; end; end else begin if L[J] = S then begin result := J; Exit; end; end; end; end; // TExternRec ------------------------------------------------------------------ procedure TExternRec.SaveToStream(S: TWriter); begin S.WriteInteger(id); S.WriteString(FullName); S.Write(RecKind, SizeOf(RecKind)); end; procedure TExternRec.LoadFromStream(S: TReader); begin Id := S.ReadInteger; FullName := S.ReadString; S.Read(RecKind, SizeOf(RecKind)); end; // TExternList ----------------------------------------------------------------- function TExternList.Clone: TExternList; var I: Integer; begin result := TExternList.Create; for I:=0 to Count - 1 do with Records[I] do begin result.Add(Id, FullName, RecKind); end; end; function TExternList.GetRecord(I: Integer): TExternRec; begin result := TExternRec(L[I]); end; function TExternList.Add(Id: Integer; const FullName: String; RecKind: TExternRecKind): TExternRec; begin result := TExternRec.Create; result.Id := Id; result.FullName := FullName; result.RecKind := RecKind; L.Add(result); end; procedure TExternList.SaveToStream(S: TWriter); var I: Integer; begin S.WriteInteger(Count); for I := 0 to Count - 1 do Records[I].SaveToStream(S); end; procedure TExternList.LoadFromStream(S: TReader); var I, K: Integer; R: TExternRec; begin K := S.ReadInteger; for I := 0 to K - 1 do begin R := TExternRec.Create; R.LoadFromStream(S); L.Add(R); end; end; // TSomeTypeRec ---------------------------------------------------------------- procedure TSomeTypeRec.SaveToStream(S: TWriter); begin S.WriteString(Name); S.WriteInteger(Id); end; procedure TSomeTypeRec.LoadFromStream(S: TReader); begin Name := S.ReadString(); Id := S.ReadInteger(); end; // TSomeTypeList --------------------------------------------------------------- function TSomeTypeList.GetRecord(I: Integer): TSomeTypeRec; begin result := TSomeTypeRec(L[I]); end; function TSomeTypeList.Add(const Name: String; Id: Integer): TSomeTypeRec; begin result := TSomeTypeRec.Create; result.Name := Name; result.Id := Id; L.Add(result); end; function TSomeTypeList.Clone: TSomeTypeList; var I: Integer; begin result := TSomeTypeList.Create; for I := 0 to Count - 1 do result.Add(Records[I].Name, Records[I].Id); end; function TSomeTypeList.IndexOf(const Name: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(Records[I].Name, Name) then begin result := I; Exit; end; end; procedure TSomeTypeList.SaveToStream(S: TWriter); var I, K: Integer; begin K := Count; S.WriteInteger(K); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TSomeTypeList.LoadFromStream(S: TReader); var I, K: Integer; R: TSomeTypeRec; begin K := S.ReadInteger(); for I := 0 to K - 1 do begin R := TSomeTypeRec.Create; R.LoadFromStream(S); L.Add(R); end; end; // TVarPath -------------------------------------------------------------------- function TVarPath.GetItem(I: Integer): TVarPathRec; begin result := TVarPathRec(L[I]); end; function TVarPath.Add(Id: Integer; VarCount: Int64): TVarPathRec; begin result := TVarPathRec.Create; result.Id := Id; result.VarCount := VarCount; L.Add(result); end; function TVarPath.IndexOf(VarCount: Int64): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Items[I].VarCount = VarCount then begin result := I; Exit; end; end; function TVarPath.LastIndexOf(VarCount: Int64): Integer; var I: Integer; begin result := -1; for I := Count - 1 downto 0 do if Items[I].VarCount = VarCount then begin result := I; Exit; end; end; // TVarPathList ---------------------------------------------------------------- function TVarPathList.GetPath(I: Integer): TVarPath; begin result := TVarPath(L[I]); end; function TVarPathList.AddPath: TVarPath; begin result := TVarPath.Create; L.Add(result); end; function TVarPathList.GetLevel(VarCount: Int64): Integer; begin if VarCount < 100 then result := 1 else if VarCount < 10000 then result := 2 else if VarCount < 1000000 then result := 3 else if VarCount < 100000000 then result := 4 else if VarCount < 10000000000 then result := 5 else if VarCount < 1000000000000 then result := 6 else if VarCount < 100000000000000 then result := 7 else raise PaxCompilerException.Create(errTooManyNestedCaseBlocks); end; procedure TVarPathList.Add(Id: Integer; VarCount: Int64); var I, J, Idx: Integer; Path: TVarPath; Level: Integer; ParentVarCount: Integer; R: TVarPathRec; new_path: Boolean; begin if Count = 0 then begin Path := AddPath; Path.Add(Id, VarCount); Exit; end; for I := 0 to Count - 1 do begin Path := Pathes[I]; Idx := Path.IndexOf(VarCount); if Idx >= 0 then begin Path.Add(Id, VarCount); Exit; end; end; Level := GetLevel(VarCount); if Level = 1 then begin Path := AddPath; Path.Add(Id, VarCount); Exit; end; case Level of 2: begin ParentVarCount := VarCount mod 100; new_path := VarCount div 100 > 1; end; 3: begin ParentVarCount := VarCount mod 10000; new_path := VarCount div 10000 > 1; end; 4: begin ParentVarCount := VarCount mod 1000000; new_path := VarCount div 1000000 > 1; end; 5: begin ParentVarCount := VarCount mod 100000000; new_path := VarCount div 100000000 > 1; end; 6: begin ParentVarCount := VarCount mod 10000000000; new_path := VarCount div 10000000000 > 1; end; 7: begin ParentVarCount := VarCount mod 1000000000000; new_path := VarCount div 1000000000000 > 1; end else raise PaxCompilerException.Create(errTooManyNestedCaseBlocks); end; for I := Count - 1 downto 0 do begin Idx := Pathes[I].LastIndexOf(ParentVarCount); if Idx >= 0 then begin if new_path then begin Path := AddPath; for J := 0 to Idx do begin R := Pathes[I][J]; Path.Add(R.Id, R.VarCount); end; Path.Add(Id, VarCount); end else begin Path := Pathes[I]; Path.Add(Id, VarCount); end; Exit; end; end; Path := AddPath; Path.Add(Id, VarCount); end; procedure TGuidRec.SaveToStream(S: TWriter); begin S.Write(Id, SizeOf(Id)); S.Write(Guid, SizeOf(Guid)); S.WriteString(Name); end; procedure TGuidRec.LoadFromStream(S: TReader); begin S.Read(Id, SizeOf(Id)); S.Read(Guid, SizeOf(Guid)); Name := S.ReadString; end; function TGuidList.Add(const GUID: TGUID; Id: Integer; const Name: String): TGuidRec; var I: Integer; begin I := IndexOf(GUID); if I >= 0 then begin result := Records[I]; Exit; end; result := TGuidRec.Create; L.Add(result); result.GUID := GUID; result.Name := Name; result.GuidIndex := L.Count - 1; result.Id := Id; end; function TGuidList.Clone: TGuidList; var I: Integer; begin result := TGuidList.Create; for I := 0 to Count - 1 do result.Add(Records[I].GUID, Records[I].Id, Records[I].Name); end; function TGuidList.IndexOf(const GUID: TGUID): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if GuidsAreEqual(Records[I].GUID, GUID) then begin result := I; Exit; end; end; function TGuidList.GetGuidByID(Id: Integer): TGUID; var I: Integer; begin for I := 0 to Count - 1 do if Records[I].Id = Id then begin result := Records[I].GUID; Exit; end; result := IUnknown; end; function TGuidList.HasId(Id: Integer): Boolean; var I: Integer; begin for I := 0 to Count - 1 do if Records[I].Id = Id then begin result := true; Exit; end; result := false; end; procedure TGuidList.SaveToStream(S: TWriter); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(K)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TGuidList.LoadFromStream(S: TReader); var I, K: Integer; R: TGuidRec; begin Clear; S.Read(K, SizeOf(K)); for I := 0 to K - 1 do begin R := TGuidRec.Create; R.LoadFromStream(S); Add(R.GUID, R.Id, R.Name); R.Free; end; end; function TGuidList.GetRecord(I: Integer): TGuidRec; begin result := TGuidRec(L[I]); end; constructor TStdTypeList.Create; begin inherited; {$IFDEF PAX64} fPAX64 := true; H_ExceptionPtr := H_ExceptionPtr_64; H_ByteCodePtr := H_ByteCodePtr_64; H_Flag := H_Flag_64; H_SkipPop := H_SkipPop_64; FirstShiftValue := FirstShiftValue_64; {$ENDIF} end; function TStdTypeList.IndexOf(const S: String): Integer; var I: Integer; Q: String; begin Q := UpperCase(S); for I:=0 to Count - 1 do if Records[I].Name = Q then begin result := I; Exit; end; result := -1; end; function TStdTypeList.GetRecord(I: Integer): TStdTypeRec; begin {$IFNDEF PAXARM} if I = typePANSICHAR then I := typePOINTER else {$ENDIF} if I = typePWIDECHAR then I := typePOINTER else if I = typePVOID then I := typePOINTER; result := TStdTypeRec(L[I]); end; function TStdTypeList.Add(const TypeName: String; Size: Integer): Integer; var R: TStdTypeRec; begin R := TStdTypeRec.Create; R.TypeID := L.Count; R.Size := Size; R.Name := UpperCase(TypeName); R.NativeName := TypeName; result := R.TypeID; L.Add(R); end; function TStdTypeList.GetSize(TypeID: Integer): Integer; begin result := Records[TypeID].Size; if PAX64 then begin if TypeID in [ {$IFNDEF PAXARM} typeANSISTRING, typeWIDESTRING, typeUNICSTRING, typePANSICHAR, {$ENDIF} typePOINTER, typeCLASS, typeCLASSREF, typePROC, typeDYNARRAY, typeOPENARRAY, typePWIDECHAR, typePVOID, typeINTERFACE] then result := 8 else if typeID = typeEVENT then result := 16 else if typeID in [typeVARIANT, typeOLEVARIANT] then result := 24; end; end; constructor TMacroRec.Create; begin inherited; Params := TStringList.Create; end; destructor TMacroRec.Destroy; begin FreeAndNil(Params); inherited; end; function TMacroList.GetRecord(I: Integer): TMacroRec; begin result := TMacroRec(L[I]); end; function TMacroList.Add(const S1, S2: String; Params: TStrings): TMacroRec; var I: Integer; begin result := TMacroRec.Create; result.S1 := S1; result.S2 := S2; for I := 0 to Params.Count - 1 do result.Params.Add(Params[I]); L.Add(result); end; function TMacroList.IndexOf(const S1: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Records[I].S1 = S1 then begin result := I; Exit; end; end; end.
(* CodeGen: HDO, 2004-02-06 ------- Byte code generator for the MiniPascal compiler. ===================================================================*) UNIT CodeGen; (*$I Chooser.inc*) INTERFACE USES CodeDef; PROCEDURE InitCodeGenerator; PROCEDURE Emit1(opc: OpCode); PROCEDURE Emit2(opc: OpCode; opd: INTEGER); (*$IFDEF Midi*) FUNCTION CurAddr: INTEGER; PROCEDURE FixUp(addr: INTEGER; opd: INTEGER); (*$ENDIF*) PROCEDURE GetCode(VAR ca: CodeArray); IMPLEMENTATION VAR ca: CodeArray; (*array of opCodes and opderands*) n: INTEGER; (*index of next free byte in c*) PROCEDURE InitCodeGenerator; (*-----------------------------------------------------------------*) VAR i: INTEGER; BEGIN n := 1; FOR i := 1 TO maxCodeLen DO BEGIN ca[i] := 0; END; (*FOR*) END; (*InitCodeGenerator*) PROCEDURE EmitByte(b: BYTE); BEGIN IF n = maxCodeLen THEN BEGIN WriteLn('*** Error: overflow in code array'); HALT; END; (*IF*) ca[n] := b; n := n + 1; END; (*EmitByte*) PROCEDURE EmitWord(w: INTEGER); BEGIN EmitByte(w DIV 256); EmitByte(w MOD 256); END; (*EmitWord*) PROCEDURE Emit1(opc: OpCode); (*-----------------------------------------------------------------*) BEGIN EmitByte(Ord(opc)); END; (*Emit1*) PROCEDURE Emit2(opc: OpCode; opd: INTEGER); (*-----------------------------------------------------------------*) BEGIN EmitByte(Ord(opc)); EmitWord(opd); END; (*Emit1*) (*$IFDEF Midi*) FUNCTION CurADdr: INTEGER; (*-----------------------------------------------------------------*) BEGIN CurAddr := n; END; (*CurAddr*) PROCEDURE FixUp(addr: INTEGER; opd: INTEGER); (*-----------------------------------------------------------------*) BEGIN ca[addr ] := opd DIV 256; ca[addr + 1] := opd MOD 256; END; (*FixUp*) (*$ENDIF*) PROCEDURE GetCode(VAR ca: CodeArray); (*-----------------------------------------------------------------*) BEGIN ca := CodeGen.ca; END; (*GetCode*) END. (*CodeGen*)
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } { Definition of TModelEntity is in it's own unit to avoid a circular unit reference bwtween uModel and uListeners IModelIterator is defined here for the same reason. } unit uModelEntity; {$mode objfpc}{$H+} interface uses Classes, Sysutils, LCLIntf, LCLType, uDocumentation; type TListenerMethodType = (mtBeforeChange, mtBeforeAddChild, mtBeforeRemove, mtBeforeEntityChange, mtAfterChange, mtAfterAddChild, mtAfterRemove, mtAfterEntityChange); TVisibility = (viPrivate, viProtected, viPublic, viPublished); { TModelEntity is the representation of UML 2.5 NamedElement abstract class. This is documented in Section 7.8.9 of the Formal Spec. This is inherently a PackageableElement [7.4.3.3] as its visibility may change depending on the owning package. The original code seems to assume that all NamedElements are owned at the package level and derive the NameSpace heirarchy from package ownership. } TModelEntity = class(TInterfacedPersistent) private function GetRoot: TModelEntity; protected // To be able to integrate with an editor we need the location of the entity // Sourcefilename is stored only where needed, in abstractpackage and classifier FSourceX, FSourceY: Integer; FName: string; FOwner: TModelEntity; FDocumentation : TDocumentation; FVisibility: TVisibility; Listeners: TInterfaceList; FLocked: boolean; procedure SetName(const Value: string); virtual; function GetFullName: string; class function GetBeforeListener: TGUID; virtual; class function GetAfterListener: TGUID; virtual; procedure SetVisibility(const Value: TVisibility); function GetLocked: boolean; procedure Fire(Method: TListenerMethodType; Info: TModelEntity = nil); virtual; function GetSourcefilename: String; virtual; procedure SetSourcefilename(const Value: String); virtual; function GetDescription: string; {IUnknown, behövs för att kunna vara lyssnare} function QueryInterface(const IID: TGUID; out Obj): HResult; function _AddRef: Integer; function _Release: Integer; public constructor Create(AOwner: TModelEntity); virtual; destructor Destroy; override; procedure AddListener(NewListener: IUnknown); procedure RemoveListener(Listener: IUnknown); property FullName: string read GetFullName; property Owner: TModelEntity read FOwner write FOwner; property Locked: boolean read GetLocked write FLocked; property Root : TModelEntity read GetRoot; property Documentation : TDocumentation read FDocumentation; property SourceX: Integer read FSourceX write FSourceX; published property Name: string read FName write SetName; property Visibility: TVisibility read FVisibility write SetVisibility; // TODO These are read only so are only here while developing Model property Sourcefilename: String read GetSourcefilename write SetSourcefilename; property SourceY: Integer read FSourceY write FSourceY; property Description : string read GetDescription; end; TModelEntityClass = class of TModelEntity; //Sortorder for iterators TIteratorOrder = (ioNone,ioVisibility,ioAlpha{,ioType}); //Basinterface for iterators IModelIterator = interface(IUnknown) ['{42329900-029F-46AE-96ED-6D4ABBEAFD4F}'] function HasNext : boolean; function Next : TModelEntity; procedure Reset; function Count : integer; end; //Basinterface for iteratorfilters IIteratorFilter = interface(IUnknown) ['{FD77FD42-456C-4B8A-A917-A2555881E164}'] function Accept(M : TModelEntity) : boolean; end; var CurrentSourcefilename: PString; CurrentSourceX: PInteger; CurrentSourceY: PInteger; implementation uses uListeners; constructor TModelEntity.Create(AOwner: TModelEntity); begin inherited Create; Self.Owner := AOwner; Listeners := TInterfaceList.Create; FDocumentation := TDocumentation.Create; if Assigned(CurrentSourceX) then SourceX := CurrentSourceX^; if Assigned(CurrentSourceY) then SourceY := CurrentSourceY^; end; destructor TModelEntity.Destroy; begin FreeAndNil(FDocumentation); FreeAndNil(Listeners); inherited; end; function TModelEntity.GetFullName: string; begin if Assigned(FOwner) then Result := FOwner.FullName + '::' + FName else Result := FName; end; function TModelEntity.GetLocked: boolean; begin Result := FLocked or (Assigned(Owner) and Owner.Locked); end; procedure TModelEntity.AddListener(NewListener: IUnknown); begin if self.Listeners.IndexOf(NewListener) = -1 then self.Listeners.Add(NewListener); end; procedure TModelEntity.RemoveListener(Listener: IUnknown); begin self.Listeners.Remove(Listener); end; procedure TModelEntity.SetName(const Value: string); var OldName: string; begin OldName := FName; FName := Value; try Fire(mtBeforeEntityChange) except FName := OldName; raise; end {try}; Fire(mtAfterEntityChange) end; procedure TModelEntity.SetVisibility(const Value: TVisibility); var Old: TVisibility; begin Old := Value; FVisibility := Value; try Fire(mtBeforeEntityChange) except FVisibility := Old; raise; end {try}; Fire(mtAfterEntityChange) end; procedure TModelEntity.Fire(Method: TListenerMethodType; Info: TModelEntity = nil); var I: integer; IL: IModelEntityListener; L: IUnknown; begin if not Locked then for I := 0 to Listeners.Count - 1 do begin L := Listeners[I]; case Method of mtBeforeAddChild: if Supports(L, GetBeforeListener, IL) then IL.AddChild(Self, Info); mtBeforeRemove: if Supports(L, GetBeforeListener, IL) then IL.Remove(Self); mtBeforeChange: if Supports(L, GetBeforeListener, IL) then IL.Change(Self); mtBeforeEntityChange: if Supports(L, GetBeforeListener, IL) then IL.EntityChange(Self); mtAfterAddChild: if Supports(L, GetAfterListener, IL) then IL.AddChild(Self, Info); mtAfterRemove: if Supports(L, GetAfterListener, IL) then IL.Remove(Self); mtAfterChange: if Supports(L, GetAfterListener, IL) then IL.Change(Self); mtAfterEntityChange: if Supports(L, GetAfterListener, IL) then IL.EntityChange(Self); else raise Exception.Create(ClassName + ' Eventmethod not recognized.'); end {case}; end; end; function TModelEntity.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE end; function TModelEntity._AddRef: Integer; begin Result := -1; // -1 indicates no reference counting is taking place end; function TModelEntity._Release: Integer; begin Result := -1; // -1 indicates no reference counting is taking place end; function TModelEntity.GetRoot: TModelEntity; begin Result := Self; while Result.Owner<>nil do Result := Result.Owner; end; class function TModelEntity.{%H-}GetAfterListener: TGUID; begin raise Exception.Create( ClassName + '.GetAfterListener'); end; class function TModelEntity.{%H-}GetBeforeListener: TGUID; begin raise Exception.Create( ClassName + '.GetBeforeListener'); end; function TModelEntity.GetSourcefilename: String; begin Result := ''; if Owner <> nil then Result := Owner.Sourcefilename; end; procedure TModelEntity.SetSourcefilename(const Value: String); begin if Owner <> nil then Owner.Sourcefilename := Value; end; function TModelEntity.GetDescription: string; begin Result := FDocumentation.Description; end; initialization CurrentSourcefilename := nil; CurrentSourceX := nil; CurrentSourceY := nil; end.
namespace RemObjects.Elements.EUnit; interface type BaseAction = assembly abstract class private Prev: BaseAction; protected method DoExecute(Context: RunContext); virtual; abstract; method HandleException(Context: RunContext; Ex: Exception): ITestResult; public constructor; constructor(RunAlways: Boolean); method Execute(Context: RunContext); virtual; method &Then(NextAction: BaseAction): BaseAction; property RunIfFailed: Boolean read write; end; implementation method BaseAction.Execute(Context: RunContext); begin try ArgumentNilException.RaiseIfNil(Context, "Context"); if Prev <> nil then Prev.Execute(Context); if (Context.CurrentResult:State = TestState.Failed) and (not RunIfFailed) then exit; DoExecute(Context); except on E: Exception do Context.CurrentResult := HandleException(Context, E); end; end; method BaseAction.Then(NextAction: BaseAction): BaseAction; begin ArgumentNilException.RaiseIfNil(NextAction, "NextAction"); var anAction := NextAction; while anAction.Prev <> nil do anAction := anAction.Prev; anAction.Prev := self; exit NextAction; end; method BaseAction.HandleException(Context: RunContext; Ex: Exception): ITestResult; begin {$IF COOPER} if Ex is java.lang.reflect.InvocationTargetException then Ex := Exception(java.lang.reflect.InvocationTargetException(Ex).TargetException); {$ELSEIF ECHOES} if Ex is System.Reflection.TargetInvocationException then Ex := System.Reflection.TargetInvocationException(Ex).InnerException else if Ex is System.AggregateException then Ex := System.AggregateException(Ex).InnerException; {$ENDIF} var Message: String := Ex.{$IF NOUGAT}reason{$ELSE}Message{$ENDIF}; var ExceptionName: String := {$IF COOPER}Ex.Class.SimpleName{$ELSEIF ECHOES}Ex.GetType.Name{$ELSEIF NOUGAT}Foundation.NSString.stringWithUTF8String(class_getName(Ex.class)){$ENDIF}; if Message = nil then Message := ""; if Ex is AssertException then exit new TestResultNode(Context.Test, TestState.Failed, Message) else exit new TestResultNode(Context.Test, TestState.Failed, "["+ExceptionName+"]"+ if Message = "" then "" else ": " + Message); end; constructor BaseAction; begin RunIfFailed := true; end; constructor BaseAction(RunAlways: Boolean); begin RunIfFailed := RunAlways; end; end.
unit feedHTML; interface uses eaterReg, VBScript_RegExp_55_TLB, jsonDoc; type THTMLFeedProcessor1=class(TFeedProcessor) private FURL:WideString; FPostItem,FPostBody:RegExp; public procedure AfterConstruction; override; function Determine(Store:IFeedStore;const FeedURL:WideString; var FeedData:WideString;const FeedDataType:WideString):boolean; override; procedure ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); override; end; THTMLFeedProcessor2=class(TFeedProcessor) private FURL:WideString; FFeedParams:IJSONDocument; FPostItem:RegExp; FFeedData:WideString; public procedure AfterConstruction; override; function Determine(Store:IFeedStore;const FeedURL:WideString; var FeedData:WideString;const FeedDataType:WideString):boolean; override; procedure ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); override; end; implementation uses SysUtils, Classes, Variants, eaterUtils, eaterSanitize; { THTMLFeedProcessor1 } procedure THTMLFeedProcessor1.AfterConstruction; begin inherited; FPostItem:=CoRegExp.Create; FPostItem.Global:=true; FPostItem.IgnoreCase:=true;//? FPostItem.Pattern:='<([a-z]+)[^>]*? class="post-item"[^>]*?>' +'.*?<time[^>]*? datetime="([^"]+?)"[^>]*?>.+?</time>' +'.*?<a[^>]*? href="([^"]+?)"[^>]*?>(.+?)</a>(.*?)</\1>'; FPostBody:=CoRegExp.Create; FPostBody.Global:=true; FPostBody.IgnoreCase:=true; FPostBody.Pattern:='^([^<]*?</[a-z]*?>)*' end; //RexExp.Multiline apparently doesn't make '.' accept #10 as well, //so switch before and after to a (presumably) unused code-point function c0(const x:WideString):WideString; var i:integer; begin Result:=x; for i:=1 to Length(Result) do if Result[i]=#10 then Result[i]:=#11; end; function c1(const x:WideString):WideString; var i:integer; begin Result:=x; for i:=1 to Length(Result) do if Result[i]=#11 then Result[i]:=#10; end; function THTMLFeedProcessor1.Determine(Store: IFeedStore; const FeedURL: WideString; var FeedData: WideString; const FeedDataType: WideString): boolean; begin FURL:=FeedURL; //Store.CheckLastLoadResultPrefix('HTML:1')? Result:=(FeedDataType='text/html') and FPostItem.Test(c0(FeedData)); end; procedure THTMLFeedProcessor1.ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); var mc:MatchCollection; m:Match; sm:SubMatches; mci:integer; title,url,body:WideString; d:TDateTime; begin inherited; mc:=FPostItem.Execute(c0(FeedData)) as MatchCollection; for mci:=0 to mc.Count-1 do begin m:=mc[mci] as Match; sm:=m.SubMatches as SubMatches; //assert sm.Count=5 try d:=ConvDate2(HTMLDecode(sm[1])) except d:=UtcNow; end; url:=HTMLDecode(sm[2]); //TODO: CombineURL! if Handler.CheckNewPost(url,url,d) then begin title:=SanitizeTitle(c1(sm[3])); body:=c1(FPostBody.Replace(sm[4],'')); //TODO: id? //TODO: image? Handler.RegisterPost(title,body); end; end; Handler.ReportSuccess('HTML:1'); end; { THTMLFeedProcessor2 } procedure THTMLFeedProcessor2.AfterConstruction; begin inherited; FPostItem:=CoRegExp.Create; FPostItem.Global:=true; FPostItem.IgnoreCase:=false;//? //FPostItem.Pattern:= see Determine end; function URLToFileName(const URL:string):string; var i,l:integer; begin i:=1; l:=Length(URL); //skip 'http://' while (i<=l) and (URL[i]<>'/') do inc(i); while (i<=l) and (URL[i]='/') do inc(i); while (i<=l) and (URL[i]<>'/') do begin case URL[i] of 'A'..'Z','a'..'z','0'..'9','-':Result:=Result+URL[i]; '.':Result:=Result+'_'; end; inc(i); end; end; function THTMLFeedProcessor2.Determine(Store: IFeedStore; const FeedURL: WideString; var FeedData: WideString; const FeedDataType: WideString): boolean; var fn:string; sl:TStringList; begin FURL:=FeedURL; //Store.CheckLastLoadResultPrefix('HTML:2')? Result:=false; if (FeedDataType='text/html') then begin fn:='feeds/'+URLToFileName(string(FeedURL))+'.json'; if FileExists(fn) then begin FFeedParams:=JSON; sl:=TStringList.Create; try sl.LoadFromFile(fn); FFeedParams.Parse(sl.Text); finally sl.Free; end; FPostItem.IgnoreCase:=FFeedParams['i']=true; FPostItem.Multiline:=FFeedParams['m']=true; //FPostItem.Global:=FFeedParams['g']=true; FPostItem.Pattern:=FFeedParams['p']; FFeedData:=c0(FeedData); Result:=FPostItem.Test(FFeedData); if not(Result) then FFeedData:=''; end; end; end; procedure THTMLFeedProcessor2.ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); var mc:MatchCollection; m:Match; sm:SubMatches; s:string; mci,i,n,l:integer; title,url,content:WideString; d:TDateTime; p:IJSONDocument; re:RegExp; begin inherited; p:=JSON(FFeedParams['feedname']); if p<>nil then begin re:=CoRegExp.Create; re.Pattern:=p['p']; re.IgnoreCase:=p['i']='true'; //re.Multiline:= mc:=re.Execute(FFeedData) as MatchCollection; if mc.Count<>0 then begin m:=mc[0] as Match; sm:=m.SubMatches as SubMatches; Handler.UpdateFeedName(sm[p['n']-1]); end; re:=nil; end; mc:=FPostItem.Execute(FFeedData) as MatchCollection; for mci:=0 to mc.Count-1 do begin m:=mc[mci] as Match; sm:=m.SubMatches as SubMatches; try p:=JSON(FFeedParams['pubDate']); s:=sm[p['n']-1]; if p['parse']='1' then d:=ConvDate1(s) else if p['parse']='2' then d:=ConvDate2(s) else if p['parse']='sloppy' then begin l:=Length(s); i:=1; while (i<=l) and not(AnsiChar(s[i]) in ['0'..'9']) do inc(i); n:=0; while (i<=l) and (AnsiChar(s[i]) in ['0'..'9']) do begin n:=n*10+(byte(s[i]) and $F); inc(i); end; inc(i);//' ' s:=Copy(s,i,l-i+1); if StartsWith(s,'hour ago') then d:=UtcNow-1.0/24.0 else if StartsWith(s,'hours ago') then d:=UtcNow-n/24.0 else if StartsWith(s,'day ago') then d:=UtcNow-1.0 else if StartsWith(s,'days ago') then d:=UtcNow-n else if StartsWith(s,'week ago') then d:=UtcNow-7.0 else if StartsWith(s,'weeks ago') then d:=UtcNow-n*7.0 else if StartsWith(s,'month ago') then d:=UtcNow-30.0 else if StartsWith(s,'months ago') then d:=UtcNow-n*30.0 else raise Exception.Create('Unknown time interval'); end else raise Exception.Create('Unknown PubDate Parse "'+VarToStr(p['parse'])+'"'); except d:=UtcNow; end; //TODO FFeedParams['guid'] p:=JSON(FFeedParams['url']); url:=HTMLDecode(sm[p['n']-1]); //TODO: CombineURL! if Handler.CheckNewPost(url,FURL+url,d) then begin p:=JSON(FFeedParams['title']); title:=sm[p['n']-1]; if p['trim']=true then title:=Trim(title); title:=SanitizeTitle(c1(title)); p:=JSON(FFeedParams['content']); if p=nil then content:='' else begin content:=c1(sm[p['n']-1]); //more? //TODO: absorb THTMLFeedProcessor1 here: //TODO: series of replaces end; p:=JSON(FFeedParams['postThumb']); if p<>nil then begin s:=sm[p['n']-1]; if s<>'' then begin content:='<img class="postthumb" referrerpolicy="no-referrer'+ '" src="'+HTMLEncodeQ(FURL+s)+ //'" alt="'+??? '" /><br />'#13#10+content; end; end; Handler.RegisterPost(title,content); end; end; Handler.ReportSuccess('HTML:P'); end; initialization //RegisterFeedProcessor(THTMLFeedProcessor1.Create); RegisterFeedProcessor(THTMLFeedProcessor2.Create); end.
unit frm_Update; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UPClient, UPMsgPack, Xml.XMLDoc, Xml.XMLIntf, System.IniFiles, Vcl.StdCtrls, Vcl.Grids; type TFileProcess = procedure(const APos, ASize: Cardinal) of object; TfrmUpdate = class(TForm) sgdFiles: TStringGrid; mmo: TMemo; btnDownLoad: TButton; chkBackup: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnDownLoadClick(Sender: TObject); private { Private declarations } FClient: TUPClient; FIniFile: TIniFile; FVerNo, // 本地版本序号 FLastVerNo, // 最新的版本序号 FDownFileIndex : Integer; FDownPath: string; // 客户端路径(不带最后的\) procedure UpdateDownLoadHint(const AIndex: Integer; const AHint: string); /// <summary> 显示升级信息(包括文件) </summary> procedure ShowUpdateInfo(const AMsgPack: TUPMsgPack); procedure FileProcess(const APos, ASize: Cardinal); /// <summary> 下载所有要升级的文件 </summary> procedure DownLoadAllUpdateFile; /// <summary> 下载某个要升级的文件并备份和替换 </summary> procedure DownLoadAndUpdateAFile(const APath, AName: string; const AFileProc: TFileProcess); public { Public declarations } function CheckUpdate: Boolean; end; function HCUpdate(const ABackUp: Boolean = False): Boolean; implementation uses UPCommon, Winapi.ShellAPI; function HCUpdate(const ABackUp: Boolean = False): Boolean; var vFrmUpdate: TfrmUpdate; begin Result := False; vFrmUpdate := TfrmUpdate.Create(nil); try vFrmUpdate.chkBackup.Checked := ABackUp; Result := vFrmUpdate.CheckUpdate; finally FreeAndNil(vFrmUpdate); end; end; {$R *.dfm} procedure TfrmUpdate.btnDownLoadClick(Sender: TObject); begin if btnDownLoad.Tag = 0 then // 未下载完成 begin btnDownLoad.Enabled := False; chkBackup.Enabled := False; TThread.CreateAnonymousThread(procedure() begin DownLoadAllUpdateFile; // 下载所有要升级的文件并替换 Self.BorderIcons := Self.BorderIcons - [biSystemMenu]; FIniFile.WriteInteger('version', 'lastverno', FLastVerNo); // 写入最新版本序号 btnDownLoad.Caption := '完成'; btnDownLoad.Tag := 1; btnDownLoad.Enabled := True; end).Start; end else // 下载完成,启动updaterp.exe begin ShellExecute(Handle, 'open', PChar(FDownPath + '\updaterp.exe'), PChar(ParamStr(0)), nil, SW_SHOW); Self.ModalResult := mrOk; end; end; function TfrmUpdate.CheckUpdate: Boolean; var vMsgPack: TUPMsgPack; begin Result := False; FVerNo := FIniFile.ReadInteger('version', 'verno', 0); FClient.Host := FIniFile.ReadString('connect', 'host', '127.0.0.1'); FClient.Port := FIniFile.ReadInteger('connect', 'port', 12840); FClient.ReConnectServer; // iocp //FClient.Connect; // idtcp if FClient.Connected then begin vMsgPack := TUPMsgPack.Create; try vMsgPack.I[MSG_CMD] := CMD_CHECKVERSION; vMsgPack.I[HCUP_VERNO] := FVerNo; FClient.PostMsgPack(vMsgPack); // 请求新版本 FClient.ReceiveMsgPack(vMsgPack); if vMsgPack.I[HCUP_VERNO] <> FVerNo then // 有新版本 begin FLastVerNo := vMsgPack.I[HCUP_VERNO]; ShowUpdateInfo(vMsgPack); Result := True; end; finally FreeAndNil(vMsgPack); end; end; end; procedure TfrmUpdate.DownLoadAllUpdateFile; var i: Integer; begin for i := 1 to sgdFiles.RowCount - 1 do sgdFiles.Cells[4, i] := '等待...'; for i := 1 to sgdFiles.RowCount - 1 do begin sgdFiles.Row := i; FDownFileIndex := i; UpdateDownLoadHint(FDownFileIndex, '正在下载...'); DownLoadAndUpdateAFile(sgdFiles.Cells[3, i], sgdFiles.Cells[0, i], FileProcess); end; if not FileExists(FDownPath + '\updaterp.exe') then begin mmo.Lines.Add('正在下载替换文件 updaterp.exe'); DownLoadAndUpdateAFile('\', 'updaterp.exe', nil); mmo.Lines.Add('升级下载完成!'); end; end; procedure TfrmUpdate.DownLoadAndUpdateAFile(const APath, AName: string; const AFileProc: TFileProcess); var vMsgPack: TUPMsgPack; vStream: TMemoryStream; vFile: string; vPos, vFileSize: Cardinal; vRect: TRect; begin vPos := 0; vFileSize := 0; vMsgPack := TUPMsgPack.Create; try vStream := TMemoryStream.Create; try while True do begin vMsgPack.Clear; vMsgPack.I[MSG_CMD] := CMD_DOWNLOADFILE; vMsgPack.S[HCUP_FILEPATH] := APath + AName; vMsgPack.I[HCUP_FILEPOS] := vPos; FClient.PostMsgPack(vMsgPack); // 请求文件 //Sleep(1); FClient.ReceiveMsgPack(vMsgPack); vPos := vMsgPack.I[HCUP_FILEPOS]; if vPos = 0 then begin mmo.Lines.Add('升级失败,服务端缺失文件:' + APath + AName); Exit; end; if vFileSize = 0 then begin vFileSize := vMsgPack.I[HCUP_FILESIZE]; vStream.Size := vFileSize; end; vMsgPack.ForcePathObject(HCUP_FILE).SaveBinaryToStream(vStream); if Assigned(AFileProc) then AFileProc(vPos, vFileSize); // 更新界面显示 if vPos = vFileSize then // 下载完了 Break; end; UpdateDownLoadHint(FDownFileIndex, '正在替换...'); if not DirectoryExists(FDownPath + APath) then // 本地没有此目录则创建 ForceDirectories(FDownPath + APath); vFile := FDownPath + APath + AName; if vFile = ParamStr(0) then // 要升级自己 begin FIniFile.WriteString('file', 'rp', vFile); // 记录需要处理占用的运行程序 FIniFile.WriteString('file', 'rpbackup', FDownPath + '\backup' + APath); vFile := vFile + '.temp'; // 先重命名把文件存下来 end else // 不是升级自己 if chkBackup.Checked then // 备份原文件 begin UpdateDownLoadHint(FDownFileIndex, '正在备份...'); if FileExists(vFile) then begin if not DirectoryExists(FDownPath + '\backup' + APath) then // 本地没有备份目录则创建 ForceDirectories(FDownPath + '\backup' + APath); MoveFile(PChar(vFile), PChar(FDownPath + '\backup' + APath + AName)); // 移动到备份中 end; end; UpdateDownLoadHint(FDownFileIndex, '正在保存...'); vStream.SaveToFile(vFile); // 下载的新文件保存到对应位置 UpdateDownLoadHint(FDownFileIndex, '完成!'); finally FreeAndNil(vStream); end; finally FreeAndNil(vMsgPack); end; end; procedure TfrmUpdate.FileProcess(const APos, ASize: Cardinal); begin UpdateDownLoadHint(FDownFileIndex, FormatFloat('#%', APos / ASize * 100)); end; procedure TfrmUpdate.FormCreate(Sender: TObject); begin Caption := Application.Title + '-升级'; FDownPath := ExtractFilePath(ParamStr(0)); Delete(FDownPath, Length(FDownPath), 1); FIniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'update.ini'); if not FIniFile.SectionExists('version') then begin FIniFile.WriteInteger('version', 'verno', 0); FIniFile.WriteInteger('version', 'lastverno', 0); end; if not FIniFile.SectionExists('connect') then begin FIniFile.WriteString('connect', 'host', '127.0.0.1'); FIniFile.WriteInteger('connect', 'port', 12840); end; FIniFile.WriteString('file', 'run', ParamStr(0)); FClient := TUPClient.Create; FDownFileIndex := -1; sgdFiles.ColCount := 5; sgdFiles.ColWidths[0] := 80; sgdFiles.ColWidths[1] := 100; sgdFiles.ColWidths[2] := 100; sgdFiles.ColWidths[3] := 150; sgdFiles.ColWidths[4] := 80; // sgdFiles.Cells[0, 0] := '文件名'; sgdFiles.Cells[1, 0] := '版本'; sgdFiles.Cells[2, 0] := '大小'; sgdFiles.Cells[3, 0] := '客户端路径'; sgdFiles.Cells[4, 0] := '下载进度'; end; procedure TfrmUpdate.FormDestroy(Sender: TObject); begin FClient.Free; FreeAndNil(FIniFile); end; procedure TfrmUpdate.ShowUpdateInfo(const AMsgPack: TUPMsgPack); var vXmlDoc: IXMLDocument; vFileNode: IXMLNode; vStream: TMemoryStream; i: Integer; begin vXmlDoc := TXMLDocument.Create(nil); // 取出要升级的文件 vStream := TMemoryStream.Create; try AMsgPack.ForcePathObject(HCUP_UPDATEFILES).SaveBinaryToStream(vStream); vStream.Position := 0; vXmlDoc.LoadFromStream(vStream); //vXmlDoc.SaveToFile('c:\a.xml'); //vXmlDoc.DocumentElement.Attributes['upfver'] = '1'; mmo.Clear; mmo.Lines.Add('版本序号:' + vXmlDoc.DocumentElement.Attributes['verno']); mmo.Lines.Add('版本号:' + vXmlDoc.DocumentElement.Attributes['version']); mmo.Lines.Add('更新说明:' + vXmlDoc.DocumentElement.Attributes['memo']); sgdFiles.RowCount := vXmlDoc.DocumentElement.ChildNodes.Count + 1; if sgdFiles.RowCount > 1 then sgdFiles.FixedRows := 1; for i := 0 to vXmlDoc.DocumentElement.ChildNodes.Count - 1 do begin vFileNode := vXmlDoc.DocumentElement.ChildNodes[i]; sgdFiles.Cells[0, i + 1] := vFileNode.Text; sgdFiles.Cells[1, i + 1] := vFileNode.Attributes['version']; sgdFiles.Cells[2, i + 1] := BytesToStr(vFileNode.Attributes['size']); sgdFiles.Cells[3, i + 1] := vFileNode.Attributes['path']; end; Self.ShowModal; finally FreeAndNil(vStream); end; FVerNo := AMsgPack.I[HCUP_VERNO]; end; procedure TfrmUpdate.UpdateDownLoadHint(const AIndex: Integer; const AHint: string); var vRect: TRect; begin sgdFiles.Cells[4, AIndex] := AHint; vRect := sgdFiles.CellRect(4, AIndex); InvalidateRect(sgdFiles.Handle, vRect, False); UpdateWindow(sgdFiles.Handle); end; end.
unit Interfaces.Player; interface uses System.Classes, System.Types, Vcl.ExtCtrls; type TPlayerDirection = (tpdNone, tpdUP, tpdDOWN, tpdLEFT, tpdRIGHT); IPlayer = Interface(IInterface) ['{149FF061-A040-4770-BF31-D3EECB49E6AD}'] function Position(const Value: TPoint): IPlayer; overload; function Position: TPoint; overload; function Owner(const Value: TGridPanel): IPlayer; overload; function Owner: TGridPanel; overload; function Direction(const Value: TPlayerDirection): IPlayer; overload; function Direction: TPlayerDirection; overload; function CreateImages: IPlayer; function ChangeImage: IPlayer; function ChangeParent: IPlayer; End; implementation end.
unit StatusFrameUnit; {$mode delphi} interface uses Classes, SysUtils, Forms, Controls, StdCtrls; type { TStatusFrame } TStatusFrame = class(TFrame) GroupBoxStatus: TGroupBox; Label10: TLabel; Label12: TLabel; Label14: TLabel; Label16: TLabel; Label18: TLabel; Label20: TLabel; Label40: TLabel; Label45: TLabel; Label49: TLabel; Label51: TLabel; Label52: TLabel; Label53: TLabel; Label54: TLabel; Label6: TLabel; Label8: TLabel; lbStatusCurrent: TLabel; lbStatusErrorD: TLabel; lbStatusErrorI: TLabel; lbStatusFlags: TLabel; lbStatusOutput: TLabel; lbStatusOutputLimited: TLabel; lbStatusPidTime: TLabel; lbStatusTestOsc: TLabel; StatusCommand: TLabel; StatusEnabled: TLabel; StatusEncoder: TLabel; StatusError: TLabel; StatusLast: TLabel; StatusMaxError: TLabel; StatusMaxOutput: TLabel; private public procedure ParseStatus(Parameters: TStrings); end; implementation {$R *.lfm} procedure TStatusFrame.ParseStatus(Parameters :TStrings); begin if Parameters.Count = 8 then begin StatusError.Caption := Parameters[0]; StatusCommand.Caption := Parameters[2]; StatusEncoder.Caption := Parameters[3]; StatusMaxError.Caption := Parameters[6]; StatusMaxOutput.Caption := Parameters[7]; //Status.Command := GetInt(sl[0]); //Status.Encoder:= GetInt(sl[1]); //Status.Error:= GetDouble(sl[2]); //Status.ErrorI:= GetDouble(sl[3]); //Status.ErrorD:= GetDouble(sl[4]); //Status.Output:= GetDouble(sl[5]); //Status.OutputLimited:= GetInt(sl[6]); //Status.Enabled:= GetInt(sl[7]); //Status.OscVal:= GetInt(sl[8]); //Status.PidTime:= GetDouble(sl[9]); //Status.Flags:= GetInt(sl[10]); //Status.Current:= GetDouble(sl[11]); StatusLast.Caption := FormatDateTime('H:m:s', Now()); end; end; end.
unit Uplasma; { Main loop in program should be: while ( simulating ) do begin get_from_UI ( dens_prev, u_prev, v_prev ); <<--- program should update dens_prev, u_prev, v_prev (= density array, u and v velocities) vel_step ( N, u, v, u_prev, v_prev, visc, dt ); <<--- step call dens_step ( N, dens, dens_prev, u, v, diff, dt ); <<--- step call draw_dens ( N, dens ); <<--- render graphics end; } interface uses System.SysUtils, Vcl.Dialogs; const N = 100; type TField = array [0 .. N + 1, 0 .. N + 1] of real; PField = ^TField; TForceField = class public dens, dens_prev, u, v, u_prev, v_prev: PField; constructor create; procedure dens_step(N: integer; var x: PField; var x0: PField; var u: PField; var v: PField; diff: real; dt: real; do_addSource: boolean); procedure vel_step(N: integer; var u: PField; var v: PField; var u0: PField; var v0: PField; visc: real; dt: real); private fdens, fdens_prev, fu, fv, fu_prev, fv_prev: TField; procedure SWAP(var px, py: PField); procedure add_source(N: integer; var x: PField; var s: PField; dt: real); procedure diffuse(N: integer; b: integer; var x: PField; var x0: PField; diff: real; dt: real); procedure advect(N: integer; b: integer; var d: PField; var d0: PField; var u: PField; var v: PField; dt: real); procedure project(N: integer; var u: PField; var v: PField; var p: PField; var dv: PField); procedure set_bnd(N: integer; b: integer; var x: PField); end; // ============================================================ implementation // ============================================================ { ForceField } constructor TForceField.create; begin // set pointers to array addresses dens := @fdens; dens_prev := @fdens_prev; u := @fu; v := @fv; u_prev := @fu_prev; v_prev := @fv_prev; end; procedure TForceField.add_source(N: integer; var x: PField; var s: PField; dt: real); var i, j: integer; begin for i := 0 to N + 1 do begin for j := 0 to N + 1 do begin x[i, j] := x[i, j] + (dt * s[i, j]); end; end; end; procedure TForceField.diffuse(N: integer; b: integer; var x: PField; var x0: PField; diff: real; dt: real); var i, j, k: integer; a, aa: real; begin a := dt * diff * N * N; aa := 1 / (1 + (4 * a)); for k := 0 to 20 do begin for i := 1 to N + 1 do begin for j := 1 to N + 1 do begin x[i, j] := (x0[i, j] + a * (x[i - 1, j] + x[i + 1, j] + x[i, j - 1] + x[i, j + 1])) * aa; end; end; set_bnd(N, b, x); end; end; procedure TForceField.advect(N: integer; b: integer; var d: PField; var d0: PField; var u: PField; var v: PField; dt: real); var i, j, i0, j0, i1, j1: integer; x, y, s0, t0, s1, t1, dt0: real; begin dt0 := dt * N; for i := 1 to N + 1 do begin for j := 1 to N + 1 do begin x := i - (dt0 * u[i, j]); y := j - (dt0 * v[i, j]); if (x < 0.5) then x := 0.5; if (x > N + 0.5) then x := N + 0.5; i0 := round(x); i1 := i0 + 1; if (y < 0.5) then y := 0.5; if (y > N + 0.5) then y := N + 0.5; j0 := round(y); j1 := j0 + 1; s1 := x - i0; s0 := 1 - s1; t1 := y - j0; t0 := 1 - t1; d[i, j] := s0 * (t0 * d0[i0, j0] + t1 * d0[i0, j1]) + s1 * (t0 * d0[i1, j0] + t1 * d0[i1, j1]); end; end; end; procedure TForceField.dens_step(N: integer; var x: PField; var x0: PField; var u: PField; var v: PField; diff: real; dt: real; do_addSource: boolean); begin if do_addSource then add_source(N, x, x0, dt); SWAP(x0, x); diffuse(N, 0, x, x0, diff, dt); SWAP(x0, x); advect(N, 0, x, x0, u, v, dt); end; procedure TForceField.SWAP(var px, py: PField); var ptmp: PField; begin ptmp := px; px := py; py := ptmp; end; procedure TForceField.vel_step(N: integer; var u: PField; var v: PField; var u0: PField; var v0: PField; visc: real; dt: real); begin add_source(N, u, u0, dt); add_source(N, v, v0, dt); SWAP(u0, u); diffuse(N, 1, u, u0, visc, dt); SWAP(v0, v); diffuse(N, 2, v, v0, visc, dt); project(N, u, v, u0, v0); SWAP(u0, u); SWAP(v0, v); advect(N, 1, u, u0, u0, v0, dt); advect(N, 2, v, v0, u0, v0, dt); project(N, u, v, u0, v0); end; procedure TForceField.project(N: integer; var u: PField; var v: PField; var p: PField; var dv: PField); var i, j, k: integer; h: real; begin h := 1 / N; for i := 1 to N + 1 do begin for j := 1 to N + 1 do begin dv[i, j] := -0.5 * h * (u[i + 1, j] - u[i - 1, j] + v[i, j + 1] - v[i, j - 1]); p[i, j] := 0; end; end; set_bnd(N, 0, dv); set_bnd(N, 0, p); for k := 0 to 20 do begin for i := 1 to N + 1 do begin for j := 1 to N + 1 do begin p[i, j] := (dv[i, j] + p[i - 1, j] + p[i + 1, j] + p[i, j - 1] + p[i, j + 1]) * 0.25; // era /4; end; end; set_bnd(N, 0, p); end; for i := 1 to N + 1 do begin for j := 1 to N + 1 do begin u[i, j] := u[i, j] - 0.5 * (p[i + 1, j] - p[i - 1, j]) * N; // era /h v[i, j] := v[i, j] - 0.5 * (p[i, j + 1] - p[i, j - 1]) * N; // era /h end; end; set_bnd(N, 1, u); set_bnd(N, 2, v); end; procedure TForceField.set_bnd(N: integer; b: integer; var x: PField); var i: integer; begin for i := 1 to N do begin if b = 1 then begin x[0, i] := -x[1, i]; x[N + 1, i] := -x[N, i]; end else begin x[0, i] := x[1, i]; x[N + 1, i] := x[N, i]; end; if b = 2 then begin x[i, 0] := -x[i, 1]; x[i, N + 1] := -x[i, N]; end else begin x[i, 0] := x[i, 1]; x[i, N + 1] := x[i, N]; end; end; x[0, 0] := 0.5 * (x[1, 0] + x[0, 1]); x[0, N + 1] := 0.5 * (x[1, N + 1] + x[0, N]); x[N + 1, 0] := 0.5 * (x[N, 0] + x[N + 1, 1]); x[N + 1, N + 1] := 0.5 * (x[N, N + 1] + x[N + 1, N]); end; // UNUSED: { procedure TForceField.normalize(max:real); var i, j:integer; dD,DFx,DFy:real; begin if DMax-DMin>0.01 then dD := max/(DMax-DMin) else dD:=1; if FxMax-FxMin>0.01 then dFx := max/(FXMax-FxMin) else dFx:=1; if FyMax-FyMin>0.01 then dFy := max/(FyMax-FyMin) else dFy:=1; for i := 0 to N+1 do begin for j := 0 to N+1 do begin nD[i,j]:=(D[i,j]-DMin)*dD; nFx[i,j]:=(Fx[i,j]-FxMin)*dFx; nFy[i,j]:=(Fy[i,j]-FyMin)*dFy; end; end; end; } end.
{Se tiene información sobre el equipaje de un conjunto de vuelos grabada en un archivo de texto, de la siguiente forma: En la misma línea:  código (si no se usa archivo, indicar con *** fin de vuelos)  cantidad de pasajeros, y a continuación para el mismo vuelo una línea por cada pasajero:  Categoría (A, B, C)  Peso (en kgs. del equipaje) Se pide leer la información descripta, calcular e informar: a) De cada pasajero kilos excedidos b) De cada vuelo, total de sobrepeso en cada categoría c) De todos los vuelos, el código de vuelo de mayor sobrepeso Utilizar la función SOBREPESO, que con los parámetros que considere necesarios devuelva el correspondiente sobrepeso de acuerdo a la siguiente escala: Categoría Peso permitido hasta A 40 B 30 C 23 } Program vuelos; Function SobrePeso(Cat:char; Peso:byte):byte; Var Aux:byte; Begin Aux:= 0; //Utilizo una variable auxiliar para ahorrarme de escribir el nombre completo de la funcion. If (Cat = 'A') and (Peso > 40) then Aux:= Peso - 40 Else if (Cat = 'B') and (Peso > 30) then Aux:= Peso - 30 Else if (Cat = 'C') and (Peso > 23) then Aux:= Peso - 23 Else Aux:= 0; SobrePeso:= Aux end; Var Cod,MaxCod:string[3]; Cat,Espacio:char; CantP,Peso,SP:byte; i,SobrePA,SobrePB,SobrePC,SobrePT,MaxSP:word; Arch:text; Begin MaxSP:= 0; Assign(Arch,'Vuelos.txt');reset(Arch); while not eof (Arch) do begin SobrePA:= 0; //Reseteo los valores de cada sobrepeso. SobrePB:= 0; SobrePC:= 0; SobrePT:= 0; readln(Arch,Cod,Espacio,CantP); writeln('Vuelo: ',Cod); For i:= 1 to CantP do begin readln(Arch,Cat,Espacio,Peso); SP:= SobrePeso(Cat,Peso); //Renombro la funcion para mayor comodidad. Case Cat of 'A':SobrePA:= SobrePA + SP; 'B':SobrePB:= SobrePB + SP; 'C':SobrePC:= SobrePC + SP; end; writeln('a- Sobrepeso del pasajero ',i,' :',SP); end; writeln; writeln('b- Sobrepeso en categoria A: ', SobrePA); writeln('b- Sobrepeso en categoria B: ', SobrePB); writeln('b- Sobrepeso en categoria C: ', SobrePC); SobrePT:= SobrePA + SobrePB + SobrePC; If (SobrePT > MaxSP) then begin MaxSP:= SobrePt; MaxCod:= Cod; end; writeln; writeln; end; writeln('c- El codigo de vuelo: ',MaxCod,' fue el de mayor sobrepeso'); Close(Arch); end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_BinaryUtils; interface uses Classes, uTPLb_IntegerUtils; function SwapEndien_u32( Value: uint32): uint32; function SwapEndien_s64( Value: int64 ): int64; function SwapEndien_u64( Value: uint64 ): uint64; function RotateLeft1Bit_u32( Value: uint32): uint32; procedure Read_BigEndien_u32_Hex( const Value: string; BinaryOut: TStream); // EXAMPLE: Value = '84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1' // ==> stream with bytes: $84 $98 $3E $44 $1C etc. // Spaces are optional, but encouraged. // Streaming is in place. That is to say, the stream is not moved or // resized prior to writing to. Assume that BinaryOut is not nil. function Get_TP_LockBox3_HINSTANCE: HMODULE; implementation uses SysUtils; function SwapEndien_u32( Value: uint32): uint32; begin result := ((Value and $000000FF) shl 24) or ((Value and $0000FF00) shl 8) or ((Value and $00FF0000) shr 8) or ((Value and $FF000000) shr 24) end; function SwapEndien_s64( Value: int64): int64; begin int64rec( result).Hi := SwapEndien_u32( int64rec( Value).Lo); int64rec( result).Lo := SwapEndien_u32( int64rec( Value).Hi) end; function SwapEndien_u64( Value: uint64): uint64; begin int64rec( result).Hi := SwapEndien_u32( int64rec( Value).Lo); int64rec( result).Lo := SwapEndien_u32( int64rec( Value).Hi) end; function RotateLeft1Bit_u32( Value: uint32): uint32; begin result := (Value shl 1) or (Value shr 31) end; procedure Read_BigEndien_u32_Hex( const Value: string; BinaryOut: TStream); var Idx, Nibble: integer; Ch: Char; isHighNibble: boolean; ByteValue: byte; begin ByteValue := 0; isHighNibble := True; for Idx := 1 to Length( Value) do begin Ch := Upcase( Value[ Idx]); if Ch = ' ' then continue; if Ord( Ch) >= 256 then continue; if (Ch >= '0') and (Ch <= '9') then Nibble := Ord( Ch) - Ord( '0') else Nibble := Ord( Ch) - Ord( 'A') + 10; if (Nibble < 0) or (Nibble > 15) then raise Exception.Create( ''); if isHighNibble then ByteValue := Nibble shl 4 else begin ByteValue := ByteValue + Nibble; BinaryOut.WriteBuffer( ByteValue, 1) end; isHighNibble := not isHighNibble end end; function Get_TP_LockBox3_HINSTANCE: HMODULE; begin result := HINSTANCE end; end.
unit CdModelo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Phys.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, DmDados, uPrincipal, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids; type TModeloCdForm = class(TForm) fdUpdCadastro: TFDUpdateSQL; fdQryCadastro: TFDQuery; pnlCadastro: TPanel; btnNovo: TBitBtn; btnGravar: TBitBtn; btnCancelar: TBitBtn; btnExcluir: TBitBtn; btnSair: TBitBtn; fdTransaction: TFDTransaction; dsCadastro: TDataSource; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btnNovoClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var ModeloCdForm: TModeloCdForm; implementation {$R *.dfm} procedure TModeloCdForm.btnCancelarClick(Sender: TObject); begin if fdQryCadastro.State in [dsEdit, dsInsert] then begin fdQryCadastro.Cancel; fdTransaction.RollbackRetaining; end; end; procedure TModeloCdForm.btnExcluirClick(Sender: TObject); begin fdQryCadastro.Edit; fdQryCadastro.FieldByName('Dat_Exclusao').AsDateTime := Date; fdTransaction.StartTransaction; fdQryCadastro.Post; fdTransaction.CommitRetaining; MessageBox(handle,'Registro excluído com sucesso','Informação',MB_OK+MB_ICONINFORMATION); end; procedure TModeloCdForm.btnGravarClick(Sender: TObject); begin if fdQryCadastro.State in [dsEdit, dsInsert] then begin fdTransaction.StartTransaction; fdQryCadastro.Post; fdTransaction.CommitRetaining; MessageBox(handle,'Registro gravado com sucesso','Informação',MB_OK+MB_ICONINFORMATION); end; end; procedure TModeloCdForm.btnNovoClick(Sender: TObject); begin if not (fdQryCadastro.State in [dsEdit, dsInsert]) then begin fdQryCadastro.Insert; end; end; procedure TModeloCdForm.btnSairClick(Sender: TObject); begin Self.Close; end; procedure TModeloCdForm.FormCreate(Sender: TObject); begin fdQryCadastro.Open(); end; procedure TModeloCdForm.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin key := #0; Self.Perform(WM_NEXTDLGCTL,0,0); end; end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clMailMessage; interface {$I clVer.inc} uses Classes, SysUtils, clEncoder; type TclMessagePriority = (mpLow, mpNormal, mpHigh); TclMessageFormat = (mfNone, mfMIME, mfUUencode); TclMailMessage = class; TclMessageBodies = class; TclMessageBody = class; TclGetBodyStreamEvent = procedure (Sender: TObject; ABody: TclMessageBody; const AFileName: string; var AData: TStream; var Handled: Boolean) of object; TclBodyDataAddedEvent = procedure (Sender: TObject; ABody: TclMessageBody; AData: TStream) of object; TclBodyEncodingProgress = procedure (Sender: TObject; ABodyNo, ABytesProceed, ATotalBytes: Integer) of object; EclMailMessageError = class(Exception); TclMessageBody = class(TPersistent) private FOwner: TclMessageBodies; FContentType: string; FEncoding: TclEncodeMethod; FEncoder: TclEncoder; FContentDisposition: string; FExtraFields: TStrings; FKnownFields: TStrings; FRawHeader: TStrings; FEncodedSize: Integer; FEncodedLines: Integer; FRawBodyStart: Integer; procedure SetContentType(const Value: string); procedure SetContentDisposition(const Value: string); procedure SetEncoding(const Value: TclEncodeMethod); procedure DoOnListChanged(Sender: TObject); procedure DoOnEncoderProgress(Sender: TObject; ABytesProceed, ATotalBytes: Integer); function GetIndex: Integer; procedure SetExtraFields(const Value: TStrings); protected procedure SetListChangedEvent(AList: TStringList); function GetMailMessage: TclMailMessage; procedure ReadData(Reader: TReader); virtual; procedure WriteData(Writer: TWriter); virtual; function HasEncodedData: Boolean; virtual; procedure AddData(AData: TStream; AEncodedLines: Integer); function GetData: TStream; function GetEncoding: TclEncodeMethod; virtual; procedure AssignBodyHeader(ASource: TStrings); virtual; procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); virtual; function GetSourceStream: TStream; virtual; abstract; function GetDestinationStream: TStream; virtual; abstract; procedure BeforeDataAdded(AData: TStream); virtual; procedure DataAdded(AData: TStream); virtual; procedure DecodeData(ASource, ADestination: TStream); virtual; procedure EncodeData(ASource, ADestination: TStream); virtual; procedure DoCreate; virtual; procedure RegisterField(const AField: string); procedure RegisterFields; virtual; property KnownFields: TStrings read FKnownFields; public constructor Create(AOwner: TclMessageBodies); virtual; destructor Destroy(); override; procedure Assign(Source: TPersistent); override; procedure Clear(); virtual; property ContentType: string read FContentType write SetContentType; property ContentDisposition: string read FContentDisposition write SetContentDisposition; property Encoding: TclEncodeMethod read GetEncoding write SetEncoding; property Index: Integer read GetIndex; property ExtraFields: TStrings read FExtraFields write SetExtraFields; property EncodedSize: Integer read FEncodedSize; property EncodedLines: Integer read FEncodedLines; property RawHeader: TStrings read FRawHeader; property RawBodyStart: Integer read FRawBodyStart; end; TclMessageBodyClass = class of TclMessageBody; TclTextBody = class(TclMessageBody) private FCharSet: string; FStrings: TStrings; procedure SetStrings(const Value: TStrings); procedure SetCharSet(const Value: string); protected procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; procedure AssignBodyHeader(ASource: TStrings); override; procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure DataAdded(AData: TStream); override; procedure DoCreate; override; public destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; override; property Strings: TStrings read FStrings write SetStrings; property CharSet: string read FCharSet write SetCharSet; end; TclMultipartBody = class(TclMessageBody) private FBodies: TclMessageBodies; FMailMessage: TclMailMessage; FContentSubType: string; procedure SetBodies(const Value: TclMessageBodies); procedure SetBoundary(const Value: string); procedure SetContentSubType(const Value: string); function GetBoundary: string; procedure DoOnGetDataStream(Sender: TObject; ABody: TclMessageBody; const AFileName: string; var AStream: TStream; var Handled: Boolean); procedure DoOnGetDataSourceStream(Sender: TObject; ABody: TclMessageBody; const AFileName: string; var AStream: TStream; var Handled: Boolean); procedure DoOnDataAdded(Sender: TObject; ABody: TclMessageBody; AData: TStream); protected procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; function HasEncodedData: Boolean; override; procedure AssignBodyHeader(ASource: TStrings); override; procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure DataAdded(AData: TStream); override; procedure DoCreate; override; public destructor Destroy(); override; procedure Assign(Source: TPersistent); override; procedure Clear(); override; property Boundary: string read GetBoundary; property Bodies: TclMessageBodies read FBodies write SetBodies; property ContentSubType: string read FContentSubType write SetContentSubType; end; TclAttachmentBody = class(TclMessageBody) private FContentID: string; FFileName: string; procedure AssignEncodingIfNeed; procedure SetContentID(const Value: string); function GetContentID(ASource, AFieldList: TStrings): string; function GetMessageRfc822FileName(ABodyPos: Integer; ASource: TStrings): string; protected procedure SetFileName(const Value: string); virtual; procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; function GetEncoding: TclEncodeMethod; override; procedure AssignBodyHeader(ASource: TStrings); override; procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); override; function GetSourceStream: TStream; override; function GetDestinationStream: TStream; override; procedure RegisterFields; override; public procedure Assign(Source: TPersistent); override; procedure Clear(); override; property FileName: string read FFileName write SetFileName; property ContentID: string read FContentID write SetContentID; end; TclImageBody = class(TclAttachmentBody) private function GetUniqueContentID(const AFileName: string): string; function GetFileType(const AFileName: string): string; protected procedure SetFileName(const Value: string); override; procedure AssignBodyHeader(ASource: TStrings); override; procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); override; public procedure Clear(); override; end; TclMessageBodies = class(TPersistent) private FOwner: TclMailMessage; FList: TList; function GetItem(Index: Integer): TclMessageBody; function GetCount: Integer; procedure Add(AItem: TclMessageBody); protected function GetMailMessage: TclMailMessage; procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Reader: TReader); virtual; procedure WriteData(Writer: TWriter); virtual; function AddItem(AItemClass: TclMessageBodyClass): TclMessageBody; public constructor Create(AOwner: TclMailMessage); destructor Destroy; override; procedure Assign(Source: TPersistent); override; function AddText(const AText: string): TclTextBody; function AddHtml(const AText: string): TclTextBody; function AddMultipart: TclMultipartBody; function AddAttachment(const AFileName: string): TclAttachmentBody; function AddImage(const AFileName: string): TclImageBody; procedure Delete(Index: Integer); procedure Move(CurIndex, NewIndex: Integer); procedure Clear; property Items[Index: Integer]: TclMessageBody read GetItem; default; property Count: Integer read GetCount; end; TclMailMessage = class(TComponent) private FCharSet: string; FSubject: string; FPriority: TclMessagePriority; FDate: TDateTime; FBodies: TclMessageBodies; FBCCList: TStrings; FCCList: TStrings; FToList: TStrings; FFrom: string; FMessageFormat: TclMessageFormat; FBoundary: string; FEncoding: TclEncodeMethod; FUpdateCount: Integer; FDataStream: TMemoryStream; FIsParse: Boolean; FOnChanged: TNotifyEvent; FOnGetDataStream: TclGetBodyStreamEvent; FOnDataAdded: TclBodyDataAddedEvent; FOnEncodingProgress: TclBodyEncodingProgress; FContentType: string; FContentSubType: string; FHeaderSource: TStrings; FBodiesSource: TStrings; FMessageSource: TStrings; FIncludeRFC822Header: Boolean; FReplyTo: string; FMessageID: string; FExtraFields: TStrings; FNewsGroups: TStrings; FReferences: TStrings; FLinesFieldPos: Integer; FReadReceiptTo: string; FOnGetDataSourceStream: TclGetBodyStreamEvent; FContentDisposition: string; FKnownFields: TStrings; FMimeOLE: string; FRawHeader: TStrings; FCharsPerLine: Integer; FRawBodyStart: Integer; procedure InternalParseHeader(ASource: TStrings); function ParseBodyHeader(AStartFrom: Integer; ASource: TStrings): TclMessageBody; procedure AssignBodyHeader(ASource: TStrings; ABody: TclMessageBody); procedure AfterAddData(ABody: TclMessageBody; AEncodedLines: Integer); procedure GetBodyFromSource(const ASource: string); procedure AddBodyToSource(ASource: TStrings; ABody: TclMessageBody); procedure SetBCCList(const Value: TStrings); procedure SetBodies(const Value: TclMessageBodies); procedure SetCCList(const Value: TStrings); procedure SetToList(const Value: TStrings); procedure SetCharSet(const Value: string); procedure SetDate(const Value: TDateTime); procedure SetEncoding(const Value: TclEncodeMethod); procedure SetFrom(const Value: string); procedure SetMessageFormat(const Value: TclMessageFormat); procedure SetPriority(const Value: TclMessagePriority); procedure SetSubject(const Value: string); procedure SetContentType(const Value: string); procedure SetContentSubType(const Value: string); procedure DoOnListChanged(Sender: TObject); procedure BuildImages(ABodies: TclMessageBodies; const AText, AHtml: string; AImages: TStrings); function BuildAlternative(ABodies: TclMessageBodies; const AText, AHtml: string): string; procedure BuildAttachments(ABodies: TclMessageBodies; Attachments: TStrings); function GetHeaderSource: TStrings; function GetBodiesSource: TStrings; function GetMessageSource: TStrings; procedure SetHeaderSource(const Value: TStrings); procedure SetMessageSource(const Value: TStrings); procedure SetIncludeRFC822Header(const Value: Boolean); procedure SetCharsPerLine(const Value: Integer); function ParseDate(ASource, AFieldList: TStrings): TDateTime; procedure SetExtraFields(const Value: TStrings); procedure SetNewsGroups(const Value: TStrings); procedure SetReferences(const Value: TStrings); procedure SetReplyTo(const Value: string); function BuildDelimitedField(AValues: TStrings; const ADelimiter: string): string; procedure InternalGetBodyText(ABodies: TclMessageBodies; AStrings: TStrings); procedure SetReadReceiptTo(const Value: string); procedure SetMessageID(const Value: string); procedure SetContentDisposition(const Value: string); function IsUUEBodyStart(const ALine: string; var AFileName: string): Boolean; function IsUUEBodyEnd(const ALine: string): Boolean; procedure SetMimeOLE(const Value: string); protected procedure SafeClear; procedure SetBoundary(const Value: string); procedure ParseBodies(ASource: TStrings); function ParseAllHeaders(AStartFrom: Integer; ASource, AHeaders: TStrings): Integer; procedure ParseExtraFields(AHeader, AKnownFields, AExtraFields: TStrings); procedure InternalAssignBodies(ASource: TStrings); procedure InternalAssignHeader(ASource: TStrings); procedure GenerateBoundary; function CreateBody(ABodies: TclMessageBodies; const AContentType, ADisposition: string): TclMessageBody; virtual; function CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody; virtual; function CreateUUEAttachmentBody(ABodies: TclMessageBodies; const AFileName: string): TclAttachmentBody; virtual; procedure Changed; virtual; procedure DoGetDataStream(ABody: TclMessageBody; const AFileName: string; var AData: TStream; var Handled: Boolean); virtual; procedure DoGetDataSourceStream(ABody: TclMessageBody; const AFileName: string; var AData: TStream; var Handled: Boolean); virtual; procedure DoDataAdded(ABody: TclMessageBody; AData: TStream); virtual; procedure DoEncodingProgress(ABodyNo, ABytesProceed, ATotalBytes: Integer); virtual; procedure Loaded; override; procedure ParseContentType(ASource, AFieldList: TStrings); virtual; procedure AssignContentType(ASource: TStrings); virtual; function GetIsMultiPartContent: Boolean; virtual; procedure RegisterField(const AField: string); procedure RegisterFields; virtual; property KnownFields: TStrings read FKnownFields; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; virtual; procedure Update; procedure BeginUpdate; procedure EndUpdate; procedure BuildMessage(const AText, AHtml: string; AImages, Attachments: TStrings); overload; procedure BuildMessage(const AText, AHtml: string; const AImages, Attachments: array of string); overload; procedure BuildMessage(const AText: string; Attachments: TStrings); overload; procedure BuildMessage(const AText: string; const Attachments: array of string); overload; procedure BuildMessage(const AText, AHtml: string); overload; procedure GetBodyText(AStrings: TStrings); property IsMultiPartContent: Boolean read GetIsMultiPartContent; property IsParse: Boolean read FIsParse; property Boundary: string read FBoundary; property HeaderSource: TStrings read GetHeaderSource write SetHeaderSource; property BodiesSource: TStrings read GetBodiesSource; property MessageSource: TStrings read GetMessageSource write SetMessageSource; property RawHeader: TStrings read FRawHeader; property RawBodyStart: Integer read FRawBodyStart; published property Bodies: TclMessageBodies read FBodies write SetBodies; property Subject: string read FSubject write SetSubject; property From: string read FFrom write SetFrom; property ToList: TStrings read FToList write SetToList; property CCList: TStrings read FCCList write SetCCList; property BCCList: TStrings read FBCCList write SetBCCList; property Priority: TclMessagePriority read FPriority write SetPriority default mpNormal; property Date: TDateTime read FDate write SetDate; property CharSet: string read FCharSet write SetCharSet; property ContentType: string read FContentType write SetContentType; property ContentSubType: string read FContentSubType write SetContentSubType; property ContentDisposition: string read FContentDisposition write SetContentDisposition; property MessageFormat: TclMessageFormat read FMessageFormat write SetMessageFormat default mfNone; property Encoding: TclEncodeMethod read FEncoding write SetEncoding default cmNone; property MimeOLE: string read FMimeOLE write SetMimeOLE; property IncludeRFC822Header: Boolean read FIncludeRFC822Header write SetIncludeRFC822Header default True; property ReplyTo: string read FReplyTo write SetReplyTo; property References: TStrings read FReferences write SetReferences; property NewsGroups: TStrings read FNewsGroups write SetNewsGroups; property ExtraFields: TStrings read FExtraFields write SetExtraFields; property ReadReceiptTo: string read FReadReceiptTo write SetReadReceiptTo; property MessageID: string read FMessageID write SetMessageID; property CharsPerLine: Integer read FCharsPerLine write SetCharsPerLine default DefaultCharsPerLine; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property OnGetDataStream: TclGetBodyStreamEvent read FOnGetDataStream write FOnGetDataStream; property OnGetDataSourceStream: TclGetBodyStreamEvent read FOnGetDataSourceStream write FOnGetDataSourceStream; property OnDataAdded: TclBodyDataAddedEvent read FOnDataAdded write FOnDataAdded; property OnEncodingProgress: TclBodyEncodingProgress read FOnEncodingProgress write FOnEncodingProgress; end; function EmailListToString(AEmailList: TStrings): string; procedure StringToEmailList(const AEmails: string; AEmailList: TStrings); function EncodeField(const AFieldValue, ACharSet: string; ADefaultEncoding: TclEncodeMethod; ACharsPerLine: Integer = DefaultCharsPerLine): string; function DecodeField(const AFieldValue, ADefaultCharSet: string): string; function EncodeEmail(const ACompleteEmail, ACharSet: string; ADefaultEncoding: TclEncodeMethod; ACharsPerLine: Integer = DefaultCharsPerLine): string; function DecodeEmail(const ACompleteEmail, ADefaultCharSet: string): string; procedure RegisterBody(AMessageBodyClass: TclMessageBodyClass); function GetRegisteredBodyItems: TList; function DateTimeToMailTime(ADateTime: TDateTime): string; function MailTimeToDateTime(const ADateTimeStr: string): TDateTime; function GetCompleteEmailAddress(const AName, AEmail: string): string; function GetEmailAddressParts(const ACompleteEmail: string; var AName, AEmail: string): Boolean; resourcestring cWrondEncodingMethod = 'Wrong encoding method in field'; cMailAgent = 'Clever Internet Suite v 6.2'; cMimeOLE = 'Produced By Clever Internet Suite MimeOLE v 6.2'; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsMailMessageDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses Windows, clUtils, clTranslator {$IFDEF DEMO}, Forms{$ENDIF}; const cDefaultContentType = 'text/plain'; cDefaultCharSet = 'iso-8859-1'; ImportanceMap: array[TclMessagePriority] of string = ('Low', '', 'High'); PiorityMap: array[TclMessagePriority] of string = ('5', '3', '1'); MSPiorityMap: array[TclMessagePriority] of string = ('Low', 'Normal', 'High'); EncodingMap: array[TclEncodeMethod] of string = ('7bit', 'quoted-printable', 'base64', '', '8bit'); ContentTypeMap: array[Boolean] of TclMessageFormat = (mfUUencode, mfMIME); var RegisteredBodyItems: TList = nil; procedure RegisterBody(AMessageBodyClass: TclMessageBodyClass); begin GetRegisteredBodyItems().Add(AMessageBodyClass); Classes.RegisterClass(AMessageBodyClass); end; function GetRegisteredBodyItems: TList; begin if (RegisteredBodyItems = nil) then begin RegisteredBodyItems := TList.Create(); end; Result := RegisteredBodyItems; end; function EmailListToString(AEmailList: TStrings): string; var i: Integer; begin Result := ''; for i := 0 to AEmailList.Count - 1 do begin Result := Result + ', ' + AEmailList[i]; end; System.Delete(Result, 1, 2); end; procedure StringToEmailList(const AEmails: string; AEmailList: TStrings); var StartPos, EndPos, Quote, i, Len: integer; s: string; begin AEmailList.Clear(); Quote := 0; i := 1; Len := Length(AEmails); while (i <= Len) do begin StartPos := i; EndPos := StartPos; while (i <= Len) do begin if (AEmails[i] in ['"', '''']) then begin Inc(Quote); end; if (AEmails[i] in [',', ';']) then begin if (Quote <> 1) then begin Break; end; end; Inc(EndPos); Inc(i); end; s := Trim(Copy(AEmails, StartPos, EndPos - StartPos)); if Length(s) > 0 then begin AEmailList.Add(TrimLeft(s)); end; i := EndPos + 1; Quote := 0; end; end; function EncodeField(const AFieldValue, ACharSet: string; ADefaultEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; const EncodingToName: array[TclEncodeMethod] of string = ('', 'Q', 'B', '', ''); var i: Integer; Strings: TStrings; Encoding: TclEncodeMethod; Encoder: TclEncoder; s: string; begin Result := AFieldValue; if (Result = '') then Exit; if (ADefaultEncoding = cmUUEncode) then begin Result := TclCharSetTranslator.TranslateTo(ACharSet, AFieldValue); end else begin Encoder := TclEncoder.Create(nil); try Encoder.CharsPerLine := ACharsPerLine; Encoder.SuppressCrlf := False; Encoding := Encoder.GetNeedEncoding(AFieldValue); if (Encoding <> cmNone) and (ACharSet <> '') then begin Strings := TStringList.Create; try s := TclCharSetTranslator.TranslateTo(ACharSet, AFieldValue); Encoder.EncodeString(s, Result, Encoding); if (Encoding = cmMIMEQuotedPrintable) then begin Result := StringReplace(Result, #32, '_', [rfReplaceAll]); end; Strings.Text := Result; for i := 0 to Strings.Count - 1 do begin Strings[i] := Format('=?%s?%s?%s?=', [ACharSet, EncodingToName[Encoding], Strings[i]]); end; Result := Strings.Text; Result := Copy(Result, 1, Length(Result) - 2); finally Strings.Free(); end; end; finally Encoder.Free(); end; end; end; function DecodeField(const AFieldValue, ADefaultCharSet: string): string; function EncodingNameToType(const AEncodingName: string): TclEncodeMethod; begin Result := cmNone; if (AEncodingName = '') then Exit; case UpperCase(AEncodingName)[1] of 'Q': Result := cmMIMEQuotedPrintable; 'B': Result := cmMIMEBase64; end; end; var Formatted, isUtf8: Boolean; EncodedBegin, FirstDelim, SecondDelim, EncodedEnd, TextBegin: Integer; Encoding: TclEncodeMethod; CurLine, ResString, s, EncodingName, CharsetName: String; Encoder: TclEncoder; begin isUtf8 := False; Result := ''; Encoder := TclEncoder.Create(nil); try Encoder.SuppressCrlf := False; Formatted := False; TextBegin := 1; CurLine := AFieldValue; EncodedBegin := Pos('=?', CurLine); while (EncodedBegin <> 0) do begin Result := Result + Copy(CurLine, TextBegin, EncodedBegin - TextBegin); TextBegin := EncodedBegin; FirstDelim := TextPos('?', CurLine, EncodedBegin + 2); if (FirstDelim <> 0) then begin SecondDelim := TextPos('?', CurLine, FirstDelim + 1); if ((SecondDelim - FirstDelim) = 2) then begin EncodedEnd := TextPos('?=', CurLine, SecondDelim + 1); if (EncodedEnd <> 0) then begin CharsetName := Copy(CurLine, EncodedBegin + 2, FirstDelim - 2 - EncodedBegin); EncodingName := CurLine[FirstDelim + 1]; s := Copy(CurLine, SecondDelim + 1, EncodedEnd - SecondDelim - 1); try Encoding := EncodingNameToType(EncodingName); if Encoding = cmNone then raise EclMailMessageError.Create(cWrondEncodingMethod); Encoder.DecodeString(s, ResString, Encoding); if (Encoding = cmMIMEQuotedPrintable) then begin ResString := StringReplace(ResString, '_', #32, [rfReplaceAll]); end; isUtf8 := isUtf8 or SameText(CharsetName, 'utf-8'); if not isUtf8 then begin s := TclCharSetTranslator.TranslateFrom(CharsetName, ResString); end else begin s := ResString; end; Result := Result + s; TextBegin := EncodedEnd + 2; Formatted := True; except TextBegin := EncodedBegin + 2; Result := Result + '=?'; end; CurLine := Copy(CurLine, TextBegin, Length(CurLine)); EncodedBegin := Pos('=?', CurLine); TextBegin := 1; Continue; end; end; end; EncodedBegin := 0; Result := Result + Copy(CurLine, TextBegin, Length(CurLine)); end; if (not isUtf8) and (not Formatted) then begin Result := TclCharSetTranslator.TranslateFrom(ADefaultCharSet, AFieldValue); end; finally Encoder.Free(); end; end; function EncodeEmail(const ACompleteEmail, ACharSet: string; ADefaultEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; var Name, EncodedName, Email: string; begin if GetEmailAddressParts(ACompleteEmail, Name, Email) then begin EncodedName := EncodeField(Name, ACharSet, ADefaultEncoding, ACharsPerLine); Result := GetCompleteEmailAddress(EncodedName, Email); end else begin Result := ACompleteEmail; end; end; function DecodeEmail(const ACompleteEmail, ADefaultCharSet: string): string; var AName, AEmail: string; begin if GetEmailAddressParts(ACompleteEmail, AName, AEmail) then begin AName := DecodeField(AName, ADefaultCharSet); Result := GetCompleteEmailAddress(AName, AEmail); end else begin Result := ACompleteEmail; end; end; function GetCompleteEmailAddress(const AName, AEmail: string): string; begin if (AName = '') or (AName = AEmail) then begin Result := AEmail; end else begin Result := Format('%s <%s>', [GetNormName(AName), AEmail]); end; end; function GetEmailAddressParts(const ACompleteEmail: string; var AName, AEmail: string): Boolean; function GetEmailAddressPartsByDelimiter(indStart: Integer; ADelimiterEnd: string): Boolean; var indEnd: Integer; begin AName := Trim(system.Copy(ACompleteEmail, 1, indStart - 1)); indEnd := TextPos(ADelimiterEnd, ACompleteEmail, indStart + 1); Result := (indEnd > 0); if Result then begin AEmail := Trim(system.Copy(ACompleteEmail, indStart + 1, indEnd - indStart -1)); end; end; var indStart: Integer; begin AName := ACompleteEmail; AEmail := ACompleteEmail; indStart := system.Pos('<', ACompleteEmail); Result := (indStart > 0); if Result then begin Result := GetEmailAddressPartsByDelimiter(indStart, '>'); end else begin indStart := system.Pos('(', ACompleteEmail); Result := (indStart > 0); if Result then begin Result := GetEmailAddressPartsByDelimiter(indStart, ')'); end; end; if Result then begin AName := Trim(GetDenormName(AName)); if (Length(AName) > 1) and (AName[1] = '''') and (AName[Length(AName)] = '''') then begin AName := Copy(AName, 2, Length(AName) - 2); end; end; end; function DateTimeToMailTime(ADateTime: TDateTime): string; var Year, Month, Day, Hour, Min, Sec, MSec: Word; DayName, MonthName: String; begin DecodeDate(ADateTime, Year, Month, Day); DecodeTime(ADateTime, Hour, Min, Sec, MSec); DayName := cDays[DayOfWeek(ADateTime)]; MonthName := cMonths[Month]; Result := Format('%s, %d %s %d %d:%.2d:%.2d %s', [DayName, Day, MonthName, Year, Hour, Min, Sec, TimeZoneBiasString]); end; function MailTimeToDateTime(const ADateTimeStr: string): TDateTime; function ParseTime(const ASrc: string): TDateTime; var pm, am: Integer; src: string; h, m, s: Word; begin src := UpperCase(ASrc); pm := system.Pos('PM', src); am := system.Pos('AM', src); if (pm > 0) then begin src := system.Copy(src, 1, pm - 1); end; if (am > 0) then begin src := system.Copy(src, 1, am - 1); end; src := Trim(src); h := StrToIntDef(ExtractWord(1, src, [':']), 0); m := StrToIntDef(ExtractWord(2, src, [':']), 0); s := StrToIntDef(ExtractWord(3, src, [':']), 0); if (pm > 0) then begin if h < 12 then begin h := h + 12; end; end; if (am > 0) then begin if h = 12 then begin h := 0; end; end; Result := EncodeTime(h, m, s, 0); end; function GetCurrentMonth: Word; var yy, dd: Word; begin DecodeDate(Date(), yy, Result, dd); end; var Year, Month, Day: Word; DayName, MonthName, YearName, TimeName, ZoneName: String; Time: TDateTime; DateTimeStr: String; P: Integer; s: string; begin Result := 0.0; Time := 0.0; Year := 0; Month := 0; Day := 0; DateTimeStr := Trim(ADateTimeStr); P := Pos(',', DateTimeStr); if (P > 0) then begin system.Delete(DateTimeStr, 1, Succ(P)); end; s := Trim(DateTimeStr); DateTimeStr := s; P := Pos(' ', DateTimeStr); if (P > 0) then begin DayName := Copy(DateTimeStr, 1, Pred(P)); Day := StrToInt(DayName); system.Delete(DateTimeStr, 1, P); end; s := Trim(DateTimeStr); DateTimeStr := s; P := Pos(' ', DateTimeStr); if (P > 0) then begin MonthName := Copy(DateTimeStr, 1, Pred(P)); Month := Succ(IndexOfStrArray(MonthName, cMonths)); if (Month = 0) then begin Month := GetCurrentMonth(); end else begin system.Delete(DateTimeStr, 1, P); end; end; s := Trim(DateTimeStr); DateTimeStr := s; P := Pos(' ', DateTimeStr); if (P > 0) then begin YearName := Copy(DateTimeStr, 1, Pred(P)); Year := StrToInt(YearName); if (Year < 100) then begin if (Year > 10) then Year := Year + 1900 else if (Year <= 10) then Year := Year + 2000; end; system.Delete(DateTimeStr, 1, P); end; s := Trim(DateTimeStr); DateTimeStr := s; P := Pos(' ', DateTimeStr); if (P > 0) then begin TimeName := Copy(DateTimeStr, 1, Pred(P)); Time := ParseTime(TimeName); system.Delete(DateTimeStr, 1, P); end; if (Year > 0) and (Month > 0) and (Day > 0) then begin ZoneName := DateTimeStr; Result := EncodeDate(Year, Month, Day); Result := Result + Time; Result := Result - TimeZoneBiasToDateTime(ZoneName); Result := GlobalTimeToLocalTime(Result); end; end; { TclMessageBodies } procedure TclMessageBodies.Add(AItem: TclMessageBody); begin FList.Add(AItem); GetMailMessage().Update(); end; function TclMessageBodies.AddAttachment(const AFileName: string): TclAttachmentBody; begin Result := TclAttachmentBody.Create(Self); Result.FileName := AFileName; end; function TclMessageBodies.AddHtml(const AText: string): TclTextBody; begin Result := AddText(AText); Result.ContentType := 'text/html'; end; function TclMessageBodies.AddImage(const AFileName: string): TclImageBody; begin Result := TclImageBody.Create(Self); Result.FileName := AFileName; end; function TclMessageBodies.AddItem(AItemClass: TclMessageBodyClass): TclMessageBody; begin Result := AItemClass.Create(Self); end; function TclMessageBodies.AddMultipart: TclMultipartBody; begin Result := TclMultipartBody.Create(Self); end; function TclMessageBodies.AddText(const AText: string): TclTextBody; var encoder: TclEncoder; begin Result := TclTextBody.Create(Self); Result.Strings.Text := AText; if (Result.Encoding = cmNone) then begin encoder := TclEncoder.Create(nil); try Result.Encoding := encoder.GetNeedEncoding(AText); finally encoder.Free(); end; end; end; procedure TclMessageBodies.Assign(Source: TPersistent); var i: Integer; Item: TclMessageBody; begin if (Source is TclMessageBodies) then begin Clear(); for i := 0 to TclMessageBodies(Source).Count - 1 do begin Item := TclMessageBodies(Source).Items[i]; AddItem(TclMessageBodyClass(Item.ClassType)).Assign(Item); end; end else begin inherited Assign(Source); end; end; procedure TclMessageBodies.Clear; var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; FList.Clear(); GetMailMessage().Update(); end; constructor TclMessageBodies.Create(AOwner: TclMailMessage); begin inherited Create(); Assert(AOwner <> nil); FOwner := AOwner; FList := TList.Create(); end; procedure TclMessageBodies.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('Items', ReadData, WriteData, (FList.Count > 0)); end; procedure TclMessageBodies.Delete(Index: Integer); begin Items[Index].Free(); FList.Delete(Index); GetMailMessage().Update(); end; destructor TclMessageBodies.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclMessageBodies.GetCount: Integer; begin Result := FList.Count; end; function TclMessageBodies.GetItem(Index: Integer): TclMessageBody; begin Result := TclMessageBody(FList[Index]); end; function TclMessageBodies.GetMailMessage: TclMailMessage; begin Result := FOwner; end; procedure TclMessageBodies.Move(CurIndex, NewIndex: Integer); begin FList.Move(CurIndex, NewIndex); GetMailMessage().Update(); end; procedure TclMessageBodies.ReadData(Reader: TReader); var ItemClass: TclMessageBodyClass; begin Clear(); Reader.ReadListBegin(); while not Reader.EndOfList() do begin ItemClass := TclMessageBodyClass(GetClass(Reader.ReadString())); if (ItemClass <> nil) then begin AddItem(ItemClass).ReadData(Reader); end; end; Reader.ReadListEnd(); end; procedure TclMessageBodies.WriteData(Writer: TWriter); var i: Integer; begin Writer.WriteListBegin(); for i := 0 to Count - 1 do begin Writer.WriteString(Items[i].ClassName); Items[i].WriteData(Writer); end; Writer.WriteListEnd(); end; { TclMailMessage } procedure TclMailMessage.GenerateBoundary; begin SetBoundary('Mark=_' + FloatToStr(Now()) + IntToStr(Random(1000))); end; procedure TclMailMessage.AssignContentType(ASource: TStrings); var s: string; begin if (MessageFormat = mfUUencode) then Exit; if IsMultiPartContent then begin s := Trim(ContentType); if (s = '') then begin s := 'multipart/mixed'; end; if (ContentSubType <> '') then begin AddHeaderArrayField(ASource, [s, 'type="' + ContentSubType + '"', 'boundary="' + Boundary + '"'], 'Content-Type', ';'); end else begin AddHeaderArrayField(ASource, [s, 'boundary="' + Boundary + '"'], 'Content-Type', ';'); end; end else begin s := Trim(ContentType); if (s = '') then begin s := 'text/plain'; end; if (CharSet <> '') then begin AddHeaderArrayField(ASource, [s, 'charset="' + CharSet + '"'], 'Content-Type', ';'); end else begin AddHeaderField(ASource, 'Content-Type', s); end; end; end; function TclMailMessage.BuildDelimitedField(AValues: TStrings; const ADelimiter: string): string; var i: Integer; Comma: array[Boolean] of string; begin Result := ''; if (AValues.Count > 0) then begin Comma[False] := ''; Comma[True] := ADelimiter; Result := Result + AValues[0] + Comma[AValues.Count > 1]; for i := 1 to AValues.Count - 1 do begin Result := Result + AValues[i] + Comma[i < (AValues.Count - 1)]; end; end; end; procedure TclMailMessage.InternalAssignHeader(ASource: TStrings); procedure AddEmailMultiField(ASource, AEmails: TStrings; const AName: string); var i: Integer; s: string; begin if (AEmails.Count > 0) then begin s := EncodeEmail(AEmails[0], CharSet, Encoding, CharsPerLine); for i := 1 to AEmails.Count - 1 do begin s := s + ','#13#10 + EncodeEmail(AEmails[i], CharSet, Encoding, CharsPerLine); end; AddHeaderField(ASource, AName, s); end; end; begin GenerateBoundary(); if IncludeRFC822Header then begin AddHeaderField(ASource, 'Message-ID', MessageID); AddHeaderField(ASource, 'From', EncodeEmail(From, CharSet, Encoding, CharsPerLine)); AddHeaderField(ASource, 'Reply-To', EncodeEmail(ReplyTo, CharSet, Encoding, CharsPerLine)); AddHeaderField(ASource, 'Newsgroups', BuildDelimitedField(NewsGroups, ',')); AddHeaderField(ASource, 'References', BuildDelimitedField(References, #32)); AddEmailMultiField(ASource, ToList, 'To'); AddEmailMultiField(ASource, CCList, 'Cc'); AddEmailMultiField(ASource, BCCList, 'Bcc'); AddHeaderField(ASource, 'Subject', EncodeField(Subject, CharSet, Encoding, CharsPerLine)); AddHeaderField(ASource, 'Date', EncodeField(DateTimeToMailTime(Self.Date), CharSet, Encoding, CharsPerLine)); FLinesFieldPos := ASource.Count; if (MessageFormat <> mfUUencode) then begin AddHeaderField(ASource, 'MIME-Version', '1.0'); end; end; AssignContentType(ASource); AddHeaderField(ASource, 'Content-Disposition', ContentDisposition); if not IsMultiPartContent then begin AddHeaderField(ASource, 'Content-Transfer-Encoding', EncodingMap[Encoding]); end; if IncludeRFC822Header then begin AddHeaderField(ASource, 'Importance', ImportanceMap[Priority]); AddHeaderField(ASource, 'X-Priority', PiorityMap[Priority]); if (MimeOLE <> '') then begin AddHeaderField(ASource, 'X-MSMail-Priority', MSPiorityMap[Priority]); end; AddHeaderField(ASource, 'X-MimeOLE', MimeOLE); AddHeaderField(ASource, 'Disposition-Notification-To', EncodeEmail(ReadReceiptTo, CharSet, Encoding, CharsPerLine)); ASource.AddStrings(ExtraFields); end; ASource.Add(''); end; function TclMailMessage.ParseAllHeaders(AStartFrom: Integer; ASource, AHeaders: TStrings): Integer; var i: Integer; begin Result := 0; AHeaders.Clear(); for i := AStartFrom to ASource.Count - 1 do begin Result := i; if (ASource[i] = '') then Break; AHeaders.Add(ASource[i]); end; end; procedure TclMailMessage.ParseContentType(ASource, AFieldList: TStrings); var s: string; begin s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); MessageFormat := ContentTypeMap[(s <> '') or (GetHeaderFieldValue(ASource, AFieldList, 'MIME-Version') <> '')]; ContentType := GetHeaderFieldValueItem(s, ''); ContentSubType := GetHeaderFieldValueItem(s, 'type='); SetBoundary(GetHeaderFieldValueItem(s, 'boundary=')); CharSet := GetHeaderFieldValueItem(s, 'charset='); end; procedure TclMailMessage.InternalParseHeader(ASource: TStrings); procedure AssignPriority(const ASource, ALowLexem, AHighLexem: string); begin if (Priority <> mpNormal) or (ASource = '') then Exit; if (LowerCase(ASource) = LowerCase(ALowLexem)) then begin Priority := mpLow; end else if (LowerCase(ASource) = LowerCase(AHighLexem)) then begin Priority := mpHigh; end; end; procedure DecodeEmailList(AEmails: TStrings); var i: Integer; begin for i := 0 to AEmails.Count - 1 do begin AEmails[i] := DecodeEmail(AEmails[i], CharSet); end; end; var s: string; FieldList: TStrings; begin FIsParse := True; FieldList := nil; try FieldList := TStringList.Create(); GetHeaderFieldList(0, ASource, FieldList); ParseContentType(ASource, FieldList); s := GetHeaderFieldValue(ASource, FieldList, 'Content-Disposition'); ContentDisposition := GetHeaderFieldValueItem(s, ''); s := LowerCase(GetHeaderFieldValue(ASource, FieldList, 'Content-Transfer-Encoding')); if (s = 'quoted-printable') then begin Encoding := cmMIMEQuotedPrintable; end else if (s = 'base64') then begin Encoding := cmMIMEBase64; end; From := DecodeEmail(GetHeaderFieldValue(ASource, FieldList, 'From'), CharSet); ToList.Text := StringReplace(GetHeaderFieldValue(ASource, FieldList, 'To'), ',', #13#10, [rfReplaceAll]); CCList.Text := StringReplace(GetHeaderFieldValue(ASource, FieldList, 'Cc'), ',', #13#10, [rfReplaceAll]); BCCList.Text := StringReplace(GetHeaderFieldValue(ASource, FieldList, 'Bcc'), ',', #13#10, [rfReplaceAll]); DecodeEmailList(ToList); DecodeEmailList(CCList); DecodeEmailList(BCCList); Subject := DecodeField(GetHeaderFieldValue(ASource, FieldList, 'Subject'), CharSet); try Self.Date := ParseDate(ASource, FieldList); except end; AssignPriority(GetHeaderFieldValue(ASource, FieldList, 'Importance'), 'Low', 'High'); AssignPriority(GetHeaderFieldValue(ASource, FieldList, 'X-Priority'), '5', '1'); AssignPriority(GetHeaderFieldValue(ASource, FieldList, 'X-MSMail-Priority'), 'Low', 'High'); ReplyTo := DecodeEmail(GetHeaderFieldValue(ASource, FieldList, 'Reply-To'), CharSet); ReadReceiptTo := DecodeEmail(GetHeaderFieldValue(ASource, FieldList, 'Disposition-Notification-To'), CharSet); MessageID := GetHeaderFieldValue(ASource, FieldList, 'Message-ID'); NewsGroups.Text := StringReplace(GetHeaderFieldValue(ASource, FieldList, 'Newsgroups'), ',', #13#10, [rfReplaceAll]); References.Text := StringReplace(GetHeaderFieldValue(ASource, FieldList, 'References'), #32, #13#10, [rfReplaceAll]); MimeOLE := GetHeaderFieldValue(ASource, FieldList, 'X-MimeOLE'); FRawBodyStart := ParseAllHeaders(0, ASource, RawHeader) + 1; ParseExtraFields(RawHeader, FKnownFields, ExtraFields); finally FieldList.Free(); FIsParse := False; end; end; procedure TclMailMessage.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclMailMessage.RegisterFields; begin RegisterField('Content-Type'); RegisterField('Content-Disposition'); RegisterField('Content-Transfer-Encoding'); RegisterField('From'); RegisterField('To'); RegisterField('Cc'); RegisterField('Bcc'); RegisterField('Subject'); RegisterField('Date'); RegisterField('Importance'); RegisterField('X-Priority'); RegisterField('X-MSMail-Priority'); RegisterField('X-MimeOLE'); RegisterField('Reply-To'); RegisterField('Disposition-Notification-To'); RegisterField('Message-ID'); RegisterField('MIME-Version'); RegisterField('Newsgroups'); RegisterField('References'); end; procedure TclMailMessage.ParseExtraFields(AHeader, AKnownFields, AExtraFields: TStrings); var i: Integer; s: string; FieldList: TStrings; begin FieldList := TStringList.Create(); try AExtraFields.Clear(); GetHeaderFieldList(0, AHeader, FieldList); for i := 0 to FieldList.Count - 1 do begin if (FindInStrings(AKnownFields, FieldList[i]) < 0) then begin s := system.Copy(AHeader[Integer(FieldList.Objects[i])], 1, Length(FieldList[i])); AExtraFields.Add(s + ': ' + GetHeaderFieldValue(AHeader, FieldList, i)); end; end; finally FieldList.Free(); end; end; function TclMailMessage.ParseDate(ASource, AFieldList: TStrings): TDateTime; var ind: Integer; s: string; begin Result := Now(); s := GetHeaderFieldValue(ASource, AFieldList, 'Date'); if (s <> '') then begin Result := MailTimeToDateTime(DecodeField(s, CharSet)); end else begin s := GetHeaderFieldValue(ASource, AFieldList, 'Received'); ind := RTextPos(';', s); if (ind > 0) then begin Result := MailTimeToDateTime(DecodeField(Trim(System.Copy(s, ind + 1, 1000)), CharSet)); end; end; end; procedure TclMailMessage.InternalAssignBodies(ASource: TStrings); var i: Integer; begin if (FBoundary = '') then begin GenerateBoundary(); end; for i := 0 to FBodies.Count - 1 do begin if (MessageFormat <> mfUUencode) and IsMultiPartContent then begin ASource.Add('--' + Boundary); AssignBodyHeader(ASource, Bodies[i]); ASource.Add(''); end; AddBodyToSource(ASource, Bodies[i]); if IsMultiPartContent then begin ASource.Add(''); end; end; if (MessageFormat <> mfUUencode) and IsMultiPartContent then begin ASource.Add('--' + Boundary + '--'); end; end; procedure TclMailMessage.AssignBodyHeader(ASource: TStrings; ABody: TclMessageBody); begin ABody.AssignBodyHeader(ASource); end; function TclMailMessage.CreateBody(ABodies: TclMessageBodies; const AContentType, ADisposition: string): TclMessageBody; begin if (system.Pos('multipart/', LowerCase(AContentType)) = 1) then begin Result := TclMultipartBody.Create(ABodies); end else if (system.Pos('image/', LowerCase(AContentType)) = 1) then begin Result := TclImageBody.Create(ABodies); end else if (LowerCase(ADisposition) = 'attachment') or (system.Pos('application/', LowerCase(AContentType)) = 1) or (system.Pos('message/', LowerCase(AContentType)) = 1) or (system.Pos('audio/', LowerCase(AContentType)) = 1) or (system.Pos('video/', LowerCase(AContentType)) = 1) then begin Result := TclAttachmentBody.Create(ABodies); end else begin Result := TclTextBody.Create(ABodies); end; end; function TclMailMessage.ParseBodyHeader(AStartFrom: Integer; ASource: TStrings): TclMessageBody; var ContType, Disposition: string; FieldList: TStrings; bodyPos: Integer; begin FieldList := TStringList.Create(); try bodyPos := GetHeaderFieldList(AStartFrom, ASource, FieldList); ContType := GetHeaderFieldValue(ASource, FieldList, 'Content-Type'); Disposition := GetHeaderFieldValue(ASource, FieldList, 'Content-Disposition'); Result := CreateBody(Bodies, GetHeaderFieldValueItem(ContType, ''), GetHeaderFieldValueItem(Disposition, '')); Result.ParseBodyHeader(bodyPos + 1, ASource, FieldList); finally FieldList.Free(); end; end; procedure TclMailMessage.AddBodyToSource(ASource: TStrings; ABody: TclMessageBody); var Src: TStream; s: string; begin if (MessageFormat = mfUUencode) and (ABody is TclAttachmentBody) then begin ASource.Add('begin 600 ' + ExtractFileName(TclAttachmentBody(ABody).FileName)); end; Src := ABody.GetData(); try SetString(s, nil, Src.Size); Src.Read(Pointer(s)^, Src.Size); AddTextStr(ASource, s); finally Src.Free(); end; if (MessageFormat = mfUUencode) and (ABody is TclAttachmentBody) then begin ASource.Add('end'); end; end; procedure TclMailMessage.AfterAddData(ABody: TclMessageBody; AEncodedLines: Integer); begin if (ABody <> nil) and (FDataStream.Size > 0) then begin try FDataStream.Position := 0; ABody.AddData(FDataStream, AEncodedLines); finally FDataStream.Clear(); end; end; end; procedure TclMailMessage.GetBodyFromSource(const ASource: string); begin FDataStream.Write(PChar(ASource)^, Length(ASource)); end; function TclMailMessage.IsUUEBodyStart(const ALine: string; var AFileName: string): Boolean; var ind: Integer; s: string; begin AFileName := ''; Result := (system.Pos('begin', LowerCase(ALine)) = 1); if Result then begin Result := False; ind := system.Pos(#32, ALine); if (ind > 0) then begin s := TrimLeft(system.Copy(ALine, ind + 1, 1000)); ind := system.Pos(#32, s); Result := (ind > 0) and (StrToIntDef(Trim(system.Copy(s, 1, ind)), -1) > -1); if Result then begin AFileName := Trim(system.Copy(s, ind + 1, 1000)); end; end; end; end; function TclMailMessage.IsUUEBodyEnd(const ALine: string): Boolean; begin Result := (Trim(LowerCase(ALine)) = 'end'); end; function TclMailMessage.CreateUUEAttachmentBody(ABodies: TclMessageBodies; const AFileName: string): TclAttachmentBody; begin Result := TclAttachmentBody.Create(ABodies); Result.FileName := AFileName; Result.Encoding := cmUUEncode; end; procedure TclMailMessage.ParseBodies(ASource: TStrings); procedure ParseMultiPartBodies(ASource: TStrings); var i, StartBody: Integer; s: string; BodyItem: TclMessageBody; begin BodyItem := nil; StartBody := 0; s := ''; for i := 0 to ASource.Count - 1 do begin if (system.Pos('--' + Boundary, ASource[i]) > 0) then begin if (BodyItem <> nil) and (i > StartBody) then begin GetBodyFromSource(s + #13#10); end; AfterAddData(BodyItem, i - StartBody); BodyItem := nil; if (system.Pos('--' + Boundary + '--', ASource[i]) = 0) then begin BodyItem := ParseBodyHeader(i, ASource); StartBody := ParseAllHeaders(i + 1, ASource, BodyItem.RawHeader); BodyItem.FRawBodyStart := StartBody + 1; ParseExtraFields(BodyItem.RawHeader, BodyItem.FKnownFields, BodyItem.ExtraFields); if (StartBody < ASource.Count - 1) then begin Inc(StartBody); end; s := ASource[StartBody]; end; end else begin if (BodyItem <> nil) and (i > StartBody) then begin GetBodyFromSource(s + #13#10); s := ASource[i]; end; end; end; if (BodyItem <> nil) then begin GetBodyFromSource(s + #13#10); end; AfterAddData(BodyItem, ASource.Count - 1 - StartBody); end; procedure ParseSingleBody(ASource: TStrings); var i, bodyStart: Integer; singleBodyItem, BodyItem: TclMessageBody; fileName: string; begin bodyStart := 0; BodyItem := nil; singleBodyItem := nil; for i := 0 to ASource.Count - 1 do begin if (ASource[i] = '') and (singleBodyItem = nil) then begin singleBodyItem := CreateSingleBody(ASource, Bodies); bodyStart := i; singleBodyItem.FRawBodyStart := bodyStart + 1; end else if (singleBodyItem <> nil) then begin if IsUUEBodyStart(ASource[i], fileName) then begin MessageFormat := mfUUencode; if (BodyItem <> nil) then begin AfterAddData(BodyItem, 0); end else begin AfterAddData(singleBodyItem, 0); end; BodyItem := CreateUUEAttachmentBody(Bodies, fileName); end else if (MessageFormat = mfUUencode) and IsUUEBodyEnd(ASource[i]) then begin AfterAddData(BodyItem, 0); BodyItem := nil; end else begin GetBodyFromSource(ASource[i] + #13#10); end; end; end; if (MessageFormat = mfUUencode) then begin AfterAddData(singleBodyItem, 0); end else begin AfterAddData(singleBodyItem, ASource.Count - 1 - bodyStart); end; end; procedure RemoveEmptySingleBody; var i: Integer; begin for i := Bodies.Count - 1 downto 0 do begin if (Bodies[i] is TclTextBody) and (Trim(TclTextBody(Bodies[i]).Strings.Text) = '') then begin Bodies.Delete(i); end; end; end; begin FIsParse := True; try if IsMultiPartContent then begin ParseMultiPartBodies(ASource); if (Bodies.Count = 0) then begin ParseSingleBody(ASource); RemoveEmptySingleBody(); end; end else begin ParseSingleBody(ASource); RemoveEmptySingleBody(); end; finally FIsParse := False; end; end; procedure TclMailMessage.DoOnListChanged(Sender: TObject); begin Update(); end; constructor TclMailMessage.Create(AOwner: TComponent); procedure SetListChangedEvent(AList: TStringList); begin AList.OnChange := DoOnListChanged; end; begin inherited Create(AOwner); FHeaderSource := TStringList.Create(); FBodiesSource := TStringList.Create(); FMessageSource := TStringList.Create(); FDataStream := TMemoryStream.Create(); FUpdateCount := 0; FBodies := TclMessageBodies.Create(Self); FBCCList := TStringList.Create(); SetListChangedEvent(FBCCList as TStringList); FCCList := TStringList.Create(); SetListChangedEvent(FCCList as TStringList); FToList := TStringList.Create(); SetListChangedEvent(FToList as TStringList); FIncludeRFC822Header := True; FReferences := TStringList.Create(); SetListChangedEvent(FReferences as TStringList); FNewsGroups := TStringList.Create(); SetListChangedEvent(FNewsGroups as TStringList); FExtraFields := TStringList.Create(); SetListChangedEvent(FExtraFields as TStringList); FKnownFields := TStringList.Create(); RegisterFields(); FRawHeader := TStringList.Create(); FCharsPerLine := DefaultCharsPerLine; Clear(); end; destructor TclMailMessage.Destroy; begin FRawHeader.Free(); FKnownFields.Free(); FExtraFields.Free(); FNewsGroups.Free(); FReferences.Free(); FToList.Free(); FCCList.Free(); FBCCList.Free(); FBodies.Free(); FDataStream.Free(); FMessageSource.Free(); FBodiesSource.Free(); FHeaderSource.Free(); inherited Destroy(); end; procedure TclMailMessage.SetBCCList(const Value: TStrings); begin FBCCList.Assign(Value); end; procedure TclMailMessage.SetBodies(const Value: TclMessageBodies); begin FBodies.Assign(Value); end; procedure TclMailMessage.SetCCList(const Value: TStrings); begin FCCList.Assign(Value); end; procedure TclMailMessage.SetToList(const Value: TStrings); begin FToList.Assign(Value); end; function TclMailMessage.GetIsMultiPartContent: Boolean; begin Result := (Bodies.Count > 1) or (FIsParse and (FBoundary <> '')); end; procedure TclMailMessage.Clear; begin BeginUpdate(); try SetBoundary(''); Subject := ''; From := ''; ToList.Clear(); CCList.Clear(); BCCList.Clear(); Priority := mpNormal; Date := Now(); Bodies.Clear(); MessageFormat := mfNone; ContentType := cDefaultContentType; ContentSubType := ''; MimeOLE := cMimeOLE; FMessageID := ''; ReplyTo := ''; References.Clear(); NewsGroups.Clear(); ExtraFields.Clear(); ReadReceiptTo := ''; ContentDisposition := ''; RawHeader.Clear(); FRawBodyStart := 0; CharSet := cDefaultCharSet; Encoding := cmNone; finally EndUpdate(); end; end; procedure TclMailMessage.Changed; begin FHeaderSource.Clear(); FBodiesSource.Clear(); FMessageSource.Clear(); if Assigned(OnChanged) then begin OnChanged(Self); end; end; procedure TclMailMessage.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; Update(); end; end; procedure TclMailMessage.SetDate(const Value: TDateTime); begin if (FDate <> Value) then begin FDate := Value; Update(); end; end; procedure TclMailMessage.SetEncoding(const Value: TclEncodeMethod); begin if (FEncoding <> Value) then begin FEncoding := Value; Update(); end; end; procedure TclMailMessage.SetFrom(const Value: string); begin if (FFrom <> Value) then begin FFrom := Value; Update(); end; end; procedure TclMailMessage.SetMessageFormat(const Value: TclMessageFormat); begin if (FMessageFormat <> Value) then begin FMessageFormat := Value; Update(); end; end; procedure TclMailMessage.SetPriority(const Value: TclMessagePriority); begin if (FPriority <> Value) then begin FPriority := Value; Update(); end; end; procedure TclMailMessage.SetSubject(const Value: string); begin if (FSubject <> Value) then begin FSubject := Value; Update(); end; end; procedure TclMailMessage.BeginUpdate; begin Inc(FUpdateCount); end; procedure TclMailMessage.EndUpdate; begin if (FUpdateCount > 0) then begin Dec(FUpdateCount); end; Update(); end; procedure TclMailMessage.Update; begin if (not (csDestroying in ComponentState)) and (not (csLoading in ComponentState)) and (not (csDesigning in ComponentState)) and (FUpdateCount = 0) then begin Changed(); end; end; procedure TclMailMessage.DoGetDataStream(ABody: TclMessageBody; const AFileName: string; var AData: TStream; var Handled: Boolean); begin if Assigned(OnGetDataStream) then begin OnGetDataStream(Self, ABody, AFileName, AData, Handled); end; end; procedure TclMailMessage.DoDataAdded(ABody: TclMessageBody; AData: TStream); begin if Assigned(OnDataAdded) then begin OnDataAdded(Self, ABody, AData); end; end; procedure TclMailMessage.DoEncodingProgress(ABodyNo, ABytesProceed, ATotalBytes: Integer); begin if Assigned(OnEncodingProgress) then begin OnEncodingProgress(Self, ABodyNo, ABytesProceed, ATotalBytes); end; end; procedure TclMailMessage.Loaded; begin inherited Loaded(); Update(); end; procedure TclMailMessage.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; Update(); end; end; function TclMailMessage.GetHeaderSource: TStrings; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (FHeaderSource.Count = 0) then begin InternalAssignHeader(FHeaderSource); end; Result := FHeaderSource; end; procedure TclMailMessage.SetBoundary(const Value: string); begin if (FBoundary <> Value) then begin FBoundary := Value; Update(); end; end; procedure TclMailMessage.BuildImages(ABodies: TclMessageBodies; const AText, AHtml: string; AImages: TStrings); var i: Integer; Multipart: TclMultipartBody; HtmlWithImages: string; ImageBody: TclImageBody; begin Multipart := ABodies.AddMultipart(); HtmlWithImages := AHtml; for i := 0 to AImages.Count - 1 do begin ImageBody := ABodies.AddImage(AImages[i]); HtmlWithImages := StringReplace(HtmlWithImages, ImageBody.FileName, 'cid:' + ImageBody.ContentID, [rfReplaceAll, rfIgnoreCase]); end; Multipart.ContentType := BuildAlternative(Multipart.Bodies, AText, HtmlWithImages); end; procedure TclMailMessage.BuildAttachments(ABodies: TclMessageBodies; Attachments: TStrings); var i: Integer; begin for i := 0 to Attachments.Count - 1 do begin ABodies.AddAttachment(Attachments[i]); end; end; function TclMailMessage.BuildAlternative(ABodies: TclMessageBodies; const AText, AHtml: string): string; begin Result := ''; if (AText <> '') then begin ABodies.AddText(AText); Result := 'text/plain'; end; if (AHtml <> '') then begin ABodies.AddHtml(AHtml); Result := 'text/html'; end; if (ABodies.Count > 1) then begin Result := 'multipart/alternative'; end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string; AImages, Attachments: TStrings); var Multipart: TclMultipartBody; TextSrc: string; dummyImg, dummyAttach: TStrings; begin dummyImg := nil; dummyAttach := nil; try if (AImages = nil) then begin dummyImg := TStringList.Create(); AImages := dummyImg; end; if (Attachments = nil) then begin dummyAttach := TStringList.Create(); Attachments := dummyAttach; end; Assert((AText <> '') or (AHtml <> '')); if ((AImages.Count > 0) and (AText = '') and (AHtml <> '')) then begin TextSrc := #32; end else begin TextSrc := AText; end; Assert((AImages.Count = 0) or ((TextSrc <> '') and (AHtml <> ''))); BeginUpdate(); try SafeClear(); if (AImages.Count = 0) and (Attachments.Count = 0) then begin ContentType := BuildAlternative(Bodies, TextSrc, AHtml); end else if (AImages.Count = 0) and (Attachments.Count > 0) then begin if (TextSrc <> '') and (AHtml <> '') then begin Multipart := Bodies.AddMultipart(); Multipart.ContentType := BuildAlternative(Multipart.Bodies, TextSrc, AHtml); end else begin BuildAlternative(Bodies, TextSrc, AHtml); end; BuildAttachments(Bodies, Attachments); ContentType := 'multipart/mixed'; end else if (AImages.Count > 0) and (Attachments.Count = 0) then begin BuildImages(Bodies, TextSrc, AHtml, AImages); ContentType := 'multipart/related'; ContentSubType := 'multipart/alternative'; end else if (AImages.Count > 0) and (Attachments.Count > 0) then begin Multipart := Bodies.AddMultipart(); BuildImages(Multipart.Bodies, TextSrc, AHtml, AImages); Multipart.ContentType := 'multipart/related'; Multipart.ContentSubType := 'multipart/alternative'; BuildAttachments(Bodies, Attachments); ContentType := 'multipart/mixed'; end else begin Assert(False); end; finally EndUpdate(); end; finally dummyAttach.Free(); dummyImg.Free(); end; end; procedure TclMailMessage.SetContentSubType(const Value: string); begin if (FContentSubType <> Value) then begin FContentSubType := Value; Update(); end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string); begin BuildMessage(AText, AHtml, nil, nil); end; procedure TclMailMessage.BuildMessage(const AText: string; Attachments: TStrings); begin BuildMessage(AText, '', nil, Attachments); end; function TclMailMessage.GetBodiesSource: TStrings; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (FBodiesSource.Count = 0) then begin InternalAssignBodies(FBodiesSource); end; Result := FBodiesSource; end; function TclMailMessage.GetMessageSource: TStrings; var lines: Integer; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (FMessageSource.Count = 0) then begin FLinesFieldPos := 0; InternalAssignHeader(FMessageSource); if IsMultiPartContent and (MessageFormat <> mfUUencode) then begin FMessageSource.Add('This is a multi-part message in MIME format.'); FMessageSource.Add(''); end; lines := FMessageSource.Count; InternalAssignBodies(FMessageSource); lines := FMessageSource.Count - lines; if (NewsGroups.Count > 0) and (FLinesFieldPos > 0) then begin FMessageSource.Insert(FLinesFieldPos, 'Lines: ' + IntToStr(lines)); end; end; Result := FMessageSource; end; procedure TclMailMessage.SetHeaderSource(const Value: TStrings); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} BeginUpdate(); try Clear(); InternalParseHeader(Value); finally EndUpdate(); end; end; procedure TclMailMessage.SetMessageSource(const Value: TStrings); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsMailMessageDemoDisplayed := True; IsEncoderDemoDisplayed := True; {$ENDIF} end; {$ENDIF} BeginUpdate(); try Clear(); InternalParseHeader(Value); ParseBodies(Value); finally EndUpdate(); end; end; function TclMailMessage.CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody; var FieldList: TStrings; bodyPos: Integer; begin FieldList := TStringList.Create(); try bodyPos := GetHeaderFieldList(0, ASource, FieldList); if (LowerCase(ContentDisposition) = 'attachment') or (system.Pos('application/', LowerCase(ContentType)) = 1) or (system.Pos('message/', LowerCase(ContentType)) = 1) or (system.Pos('audio/', LowerCase(ContentType)) = 1) or (system.Pos('video/', LowerCase(ContentType)) = 1) then begin Result := TclAttachmentBody.Create(ABodies); end else begin Result := TclTextBody.Create(ABodies); end; Result.ParseBodyHeader(bodyPos, ASource, FieldList); ParseAllHeaders(0, ASource, Result.RawHeader); ParseExtraFields(Result.RawHeader, Result.KnownFields, Result.ExtraFields); finally FieldList.Free(); end; end; procedure TclMailMessage.SetIncludeRFC822Header(const Value: Boolean); begin if (FIncludeRFC822Header <> Value) then begin FIncludeRFC822Header := Value; Update(); end; end; procedure TclMailMessage.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclMailMessage.SetNewsGroups(const Value: TStrings); begin FNewsGroups.Assign(Value); end; procedure TclMailMessage.SetReferences(const Value: TStrings); begin FReferences.Assign(Value); end; procedure TclMailMessage.SetReplyTo(const Value: string); begin if (FReplyTo <> Value) then begin FReplyTo := Value; Update(); end; end; procedure TclMailMessage.InternalGetBodyText(ABodies: TclMessageBodies; AStrings: TStrings); var i: Integer; begin for i := 0 to ABodies.Count - 1 do begin if (ABodies[i] is TclMultipartBody) then begin InternalGetBodyText((ABodies[i] as TclMultipartBody).Bodies, AStrings); end else if (ABodies[i] is TclTextBody) then begin AStrings.Assign((ABodies[i] as TclTextBody).Strings); Exit; end; end; end; procedure TclMailMessage.GetBodyText(AStrings: TStrings); begin InternalGetBodyText(Bodies, AStrings); end; procedure TclMailMessage.SetReadReceiptTo(const Value: string); begin if (FReadReceiptTo <> Value) then begin FReadReceiptTo := Value; Update(); end; end; procedure TclMailMessage.SetMessageID(const Value: string); begin if (FMessageID <> Value) then begin FMessageID := Value; Update(); end; end; procedure TclMailMessage.DoGetDataSourceStream(ABody: TclMessageBody; const AFileName: string; var AData: TStream; var Handled: Boolean); begin if Assigned(OnGetDataSourceStream) then begin OnGetDataSourceStream(Self, ABody, AFileName, AData, Handled); end; end; procedure TclMailMessage.BuildMessage(const AText: string; const Attachments: array of string); var i: Integer; list: TStrings; begin list := TStringList.Create(); try for i := Low(Attachments) to High(Attachments) do begin list.Add(Attachments[i]); end; BuildMessage(AText, list); finally list.Free(); end; end; procedure TclMailMessage.BuildMessage(const AText, AHtml: string; const AImages, Attachments: array of string); var i: Integer; imgs, attachs: TStrings; begin imgs := TStringList.Create(); attachs := TStringList.Create(); try for i := Low(AImages) to High(AImages) do begin imgs.Add(AImages[i]); end; for i := Low(Attachments) to High(Attachments) do begin attachs.Add(Attachments[i]); end; BuildMessage(AText, AHtml, imgs, attachs); finally attachs.Free(); imgs.Free(); end; end; procedure TclMailMessage.SetContentDisposition(const Value: string); begin if (FContentDisposition <> Value) then begin FContentDisposition := Value; Update(); end; end; procedure TclMailMessage.SetMimeOLE(const Value: string); begin if (FMimeOLE <> Value) then begin FMimeOLE := Value; Update(); end; end; procedure TclMailMessage.SetCharsPerLine(const Value: Integer); begin if (FCharsPerLine <> Value) then begin FCharsPerLine := Value; Update(); end; end; procedure TclMailMessage.SafeClear; var oldCharSet: string; oldEncoding: TclEncodeMethod; begin BeginUpdate(); try oldCharSet := CharSet; oldEncoding := Encoding; Clear(); CharSet := oldCharSet; Encoding := oldEncoding; finally EndUpdate(); end; end; { TclMessageBody } procedure TclMessageBody.Assign(Source: TPersistent); var Src: TclMessageBody; begin if (Source is TclMessageBody) then begin Src := (Source as TclMessageBody); ExtraFields.Assign(Src.ExtraFields); ContentType := Src.ContentType; Encoding := Src.Encoding; ContentDisposition := Src.ContentDisposition; RawHeader.Assign(Src.RawHeader); FEncodedSize := Src.EncodedSize; FEncodedLines := Src.EncodedLines; FRawBodyStart := Src.RawBodyStart; end else begin inherited Assign(Source); end; end; procedure TclMessageBody.Clear; begin FExtraFields.Clear(); ContentType := ''; Encoding := GetMailMessage().Encoding; ContentDisposition := ''; RawHeader.Clear(); FEncodedSize := 0; FEncodedLines := 0; FRawBodyStart := 0; end; procedure TclMessageBody.SetListChangedEvent(AList: TStringList); begin AList.OnChange := DoOnListChanged; end; constructor TclMessageBody.Create(AOwner: TclMessageBodies); begin inherited Create(); Assert(AOwner <> nil); FOwner := AOwner; FOwner.Add(Self); DoCreate(); Clear(); end; destructor TclMessageBody.Destroy(); begin FRawHeader.Free(); FKnownFields.Free(); FExtraFields.Free(); FEncoder.Free(); inherited Destroy(); end; procedure TclMessageBody.DoOnListChanged(Sender: TObject); begin GetMailMessage().Update(); end; function TclMessageBody.GetMailMessage: TclMailMessage; begin Result := FOwner.GetMailMessage(); end; procedure TclMessageBody.ReadData(Reader: TReader); begin ExtraFields.Text := Reader.ReadString(); ContentType := Reader.ReadString(); Encoding := TclEncodeMethod(Reader.ReadInteger()); ContentDisposition := Reader.ReadString(); end; procedure TclMessageBody.WriteData(Writer: TWriter); begin Writer.WriteString(ExtraFields.Text); Writer.WriteString(ContentType); Writer.WriteInteger(Integer(Encoding)); Writer.WriteString(ContentDisposition); end; procedure TclMessageBody.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; GetMailMessage().Update(); end; end; procedure TclMessageBody.SetEncoding(const Value: TclEncodeMethod); begin if (FEncoding <> Value) then begin FEncoding := Value; GetMailMessage().Update(); end; end; procedure TclMessageBody.AssignBodyHeader(ASource: TStrings); begin end; procedure TclMessageBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); var s: string; begin s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); ContentType := GetHeaderFieldValueItem(s, ''); s := LowerCase(GetHeaderFieldValue(ASource, AFieldList, 'Content-Transfer-Encoding')); if (s = 'quoted-printable') then begin Encoding := cmMIMEQuotedPrintable; end else if (s = 'base64') then begin Encoding := cmMIMEBase64; end; s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Disposition'); ContentDisposition := GetHeaderFieldValueItem(s, ''); end; procedure TclMessageBody.EncodeData(ASource, ADestination: TStream); begin FEncoder.CharsPerLine := GetMailMessage().CharsPerLine; FEncoder.EncodeStream(ASource, ADestination, Encoding); end; procedure TclMessageBody.DecodeData(ASource, ADestination: TStream); begin try FEncoder.DecodeStream(ASource, ADestination, Encoding); except ADestination.Size := 0; ASource.Position := 0; FEncoder.DecodeStream(ASource, ADestination, cmNone); end; end; function TclMessageBody.HasEncodedData: Boolean; begin Result := True; end; procedure TclMessageBody.AddData(AData: TStream; AEncodedLines: Integer); var Dst: TStream; begin Dst := GetDestinationStream(); try if HasEncodedData() and (AData.Size > 0) and (AEncodedLines > 0) then begin FEncodedSize := AData.Size; FEncodedLines := AEncodedLines; end; BeforeDataAdded(AData); AData.Position := 0; if (Dst <> nil) then begin DecodeData(AData, Dst); DataAdded(Dst); end; finally Dst.Free(); end; end; function TclMessageBody.GetData: TStream; var Src: TStream; begin Src := GetSourceStream(); try Result := TMemoryStream.Create(); if (Src <> nil) then begin EncodeData(Src, Result); end; Result.Position := 0; finally Src.Free(); end; end; procedure TclMessageBody.BeforeDataAdded(AData: TStream); var buf: array[0..1] of Char; begin if (AData.Size > 1) then begin AData.Position := AData.Size - 2; AData.Read(buf, 2); if (buf = #13#10) then begin AData.Size := AData.Size - 2; end; end; end; procedure TclMessageBody.DataAdded(AData: TStream); begin AData.Position := 0; GetMailMessage().DoDataAdded(Self, AData); end; function TclMessageBody.GetEncoding: TclEncodeMethod; begin if not GetMailMessage().IsMultiPartContent then begin Result := GetMailMessage().Encoding; end else begin Result := FEncoding; end; end; procedure TclMessageBody.DoOnEncoderProgress(Sender: TObject; ABytesProceed, ATotalBytes: Integer); begin GetMailMessage().DoEncodingProgress(Index, ABytesProceed, ATotalBytes); end; function TclMessageBody.GetIndex: Integer; begin Result := FOwner.FList.IndexOf(Self); end; procedure TclMessageBody.DoCreate; begin FEncoder := TclEncoder.Create(nil); FEncoder.SuppressCrlf := False; FEncoder.OnProgress := DoOnEncoderProgress; FExtraFields := TStringList.Create(); SetListChangedEvent(FExtraFields as TStringList); FKnownFields := TStringList.Create(); RegisterFields(); FRawHeader := TStringList.Create(); end; procedure TclMessageBody.SetContentDisposition(const Value: string); begin if (FContentDisposition <> Value) then begin FContentDisposition := Value; GetMailMessage().Update(); end; end; procedure TclMessageBody.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclMessageBody.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclMessageBody.RegisterFields; begin RegisterField('Content-Type'); RegisterField('Content-Transfer-Encoding'); RegisterField('Content-Disposition'); end; { TclTextBody } procedure TclTextBody.ReadData(Reader: TReader); begin Strings.Text := Reader.ReadString(); CharSet := Reader.ReadString(); inherited ReadData(Reader); end; procedure TclTextBody.WriteData(Writer: TWriter); begin Writer.WriteString(Strings.Text); Writer.WriteString(CharSet); inherited WriteData(Writer); end; procedure TclTextBody.SetStrings(const Value: TStrings); begin FStrings.Assign(Value); end; destructor TclTextBody.Destroy; begin FStrings.Free(); inherited Destroy(); end; procedure TclTextBody.Assign(Source: TPersistent); begin if (Source is TclTextBody) then begin Strings.Assign((Source as TclTextBody).Strings); CharSet := (Source as TclTextBody).CharSet; end; inherited Assign(Source); end; procedure TclTextBody.Clear; begin inherited Clear(); Strings.Clear(); ContentType := cDefaultContentType; CharSet := GetMailMessage().CharSet; end; procedure TclTextBody.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; GetMailMessage().Update(); end; end; procedure TclTextBody.AssignBodyHeader(ASource: TStrings); begin if (ContentType <> '') and (CharSet <> '') then begin AddHeaderArrayField(ASource, [ContentType, 'charset="' + CharSet + '"'], 'Content-Type', ';'); end; AddHeaderField(ASource, 'Content-Transfer-Encoding', EncodingMap[Encoding]); ASource.AddStrings(ExtraFields); end; procedure TclTextBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); var s: string; begin inherited ParseBodyHeader(ABodyPos, ASource, AFieldList); s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); CharSet := GetHeaderFieldValueItem(s, 'charset='); end; function TclTextBody.GetSourceStream: TStream; var size: Integer; s, res, chrSet: string; begin Result := TMemoryStream.Create(); s := FStrings.Text; size := Length(s); if (size - Length(#13#10) > 0) then begin size := size - Length(#13#10); end; chrSet := CharSet; if (chrSet = '') then begin chrSet := GetMailMessage().CharSet; end; res := TclCharSetTranslator.TranslateTo(chrSet, system.Copy(s, 1, size)); Result.WriteBuffer(Pointer(res)^, Length(res)); Result.Position := 0; end; function TclTextBody.GetDestinationStream: TStream; begin Result := TMemoryStream.Create(); end; procedure TclTextBody.DataAdded(AData: TStream); var s, res, chrSet: string; begin SetString(s, nil, AData.Size); AData.Position := 0; AData.Read(PChar(s)^, AData.Size); chrSet := CharSet; if not GetMailMessage().IsMultiPartContent then begin chrSet := GetMailMessage().CharSet; end; res := TclCharSetTranslator.TranslateFrom(chrSet, s); AddTextStr(FStrings, res); inherited DataAdded(AData); end; procedure TclTextBody.DoCreate; begin inherited DoCreate(); FStrings := TStringList.Create(); SetListChangedEvent(FStrings as TStringList); end; { TclAttachmentBody } procedure TclAttachmentBody.Assign(Source: TPersistent); begin if (Source is TclAttachmentBody) then begin FileName := (Source as TclAttachmentBody).FileName; ContentID := (Source as TclAttachmentBody).ContentID; end; inherited Assign(Source); end; procedure TclAttachmentBody.AssignBodyHeader(ASource: TStrings); var disposition: string; begin if (ContentType <> '') then begin if (FileName <> '') then begin AddHeaderArrayField(ASource, [ContentType, 'name="' + EncodeField(ExtractFileName(FileName), GetMailMessage().CharSet, GetMailMessage().Encoding, GetMailMessage().CharsPerLine) + '"'], 'Content-Type', ';'); end else begin AddHeaderField(ASource, 'Content-Type', ContentType); end; end; AddHeaderField(ASource, 'Content-Transfer-Encoding', EncodingMap[Encoding]); disposition := ContentDisposition; if (disposition = '') then begin disposition := 'attachment'; end; if (FileName <> '') then begin AddHeaderArrayField(ASource, [disposition, 'filename="' + EncodeField(ExtractFileName(FileName), GetMailMessage().CharSet, GetMailMessage().Encoding, GetMailMessage().CharsPerLine) + '"'], 'Content-Disposition', ';'); end else begin AddHeaderField(ASource, 'Content-Disposition', disposition); end; if (ContentID <> '') then begin AddHeaderField(ASource, 'Content-ID', '<' + EncodeField(ContentID, GetMailMessage().CharSet, GetMailMessage().Encoding, GetMailMessage().CharsPerLine) + '>'); end; ASource.AddStrings(ExtraFields); end; procedure TclAttachmentBody.Clear; begin inherited Clear(); FileName := ''; ContentType := 'application/octet-stream'; ContentID := ''; end; function TclAttachmentBody.GetMessageRfc822FileName(ABodyPos: Integer; ASource: TStrings): string; var filedList: TStrings; begin filedList := TStringList.Create(); try GetHeaderFieldList(ABodyPos, ASource, filedList); Result := GetHeaderFieldValue(ASource, filedList, 'Subject') + '.eml'; finally filedList.Free(); end; end; procedure TclAttachmentBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); var s: string; begin inherited ParseBodyHeader(ABodyPos, ASource, AFieldList); s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Disposition'); FileName := DecodeField(GetHeaderFieldValueItem(s, 'filename='), GetMailMessage().CharSet); if (FileName = '') then begin s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); FileName := DecodeField(GetHeaderFieldValueItem(s, 'filename='), GetMailMessage().CharSet); end; if (FileName = '') then begin FileName := DecodeField(GetHeaderFieldValue(ASource, AFieldList, 'Content-Description'), GetMailMessage().CharSet); if (Length(FileName) > 3) and (FileName[Length(FileName) - 3] <> '.') then begin FileName := FileName + '.dat'; end; end; if (FileName = '') then begin s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); FileName := DecodeField(GetHeaderFieldValueItem(s, 'name='), GetMailMessage().CharSet); end; if (FileName = '') and SameText('message/rfc822', ContentType) then begin FileName := GetMessageRfc822FileName(ABodyPos, ASource); end; ContentID := GetContentID(ASource, AFieldList); end; function TclAttachmentBody.GetContentID(ASource, AFieldList: TStrings): string; begin Result := GetHeaderFieldValue(ASource, AFieldList, 'Content-ID'); if (Result <> '') and (Result[1] = '<') then begin System.Delete(Result, 1, 1); end; if (Result <> '') and (Result[Length(Result)] = '>') then begin System.Delete(Result, Length(Result), 1); end; end; procedure TclAttachmentBody.ReadData(Reader: TReader); begin FileName := Reader.ReadString(); inherited ReadData(Reader); end; procedure TclAttachmentBody.SetFileName(const Value: string); begin if (FFileName <> Value) then begin FFileName := Value; AssignEncodingIfNeed(); GetMailMessage().Update(); end; end; procedure TclAttachmentBody.AssignEncodingIfNeed; var Stream: TStream; Encoder: TclEncoder; begin if not GetMailMessage().IsParse and FileExists(FileName) then begin Encoder := nil; Stream := nil; try Encoder := TclEncoder.Create(nil); Stream := GetSourceStream(); if (Stream <> nil) then begin Encoding := Encoder.GetNeedEncoding(Stream); end; finally Stream.Free(); Encoder.Free(); end; end; end; procedure TclAttachmentBody.WriteData(Writer: TWriter); begin Writer.WriteString(FileName); inherited WriteData(Writer); end; function TclAttachmentBody.GetDestinationStream: TStream; var Handled: Boolean; begin Result := nil; Handled := False; GetMailMessage().DoGetDataStream(Self, FileName, Result, Handled); end; function TclAttachmentBody.GetSourceStream: TStream; var Handled: Boolean; begin Result := nil; Handled := False; GetMailMessage().DoGetDataSourceStream(Self, FileName, Result, Handled); if not Handled then begin Result.Free(); Result := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); end; end; function TclAttachmentBody.GetEncoding: TclEncodeMethod; begin if (GetMailMessage().MessageFormat = mfUUencode) then begin Result := cmUUEncode; end else begin Result := inherited GetEncoding(); end; end; procedure TclAttachmentBody.SetContentID(const Value: string); begin if (FContentID <> Value) then begin FContentID := Value; GetMailMessage().Update(); end; end; procedure TclAttachmentBody.RegisterFields; begin inherited RegisterFields(); RegisterField('Content-Description'); RegisterField('Content-ID'); end; { TclImageBody } function TclImageBody.GetUniqueContentID(const AFileName: string): string; begin Result := AFileName + '@' + FloatToStr(Now()) + '.' + IntToStr(Random(1000)); end; procedure TclImageBody.AssignBodyHeader(ASource: TStrings); begin if (ContentType <> '') and (FileName <> '') then begin AddHeaderArrayField(ASource, [ContentType, 'name="' + EncodeField(ExtractFileName(FileName), GetMailMessage().CharSet, GetMailMessage().Encoding, GetMailMessage().CharsPerLine) + '"'], 'Content-Type', ';'); end; AddHeaderField(ASource, 'Content-Transfer-Encoding', EncodingMap[Encoding]); if (ContentID <> '') then begin AddHeaderField(ASource, 'Content-ID', '<' + EncodeField(ContentID, GetMailMessage().CharSet, GetMailMessage().Encoding, GetMailMessage().CharsPerLine) + '>'); end; ASource.AddStrings(ExtraFields); end; procedure TclImageBody.Clear; begin inherited Clear(); ContentType := ''; Encoding := cmMIMEBase64; end; procedure TclImageBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); var s: string; begin inherited ParseBodyHeader(ABodyPos, ASource, AFieldList); s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); FileName := DecodeField(GetHeaderFieldValueItem(s, 'name='), GetMailMessage().CharSet); ContentType := GetHeaderFieldValueItem(s, ''); ContentID := GetContentID(ASource, AFieldList); end; {$IFNDEF DELPHI6} const PathDelim = '\'; DriveDelim = ':'; {$ENDIF} function TclImageBody.GetFileType(const AFileName: string): string; var i: Integer; begin i := LastDelimiter('.' + PathDelim + DriveDelim, FileName); if (i > 0) and (FileName[i] = '.') then Result := Copy(FileName, i + 1, 1000) else Result := ''; end; procedure TclImageBody.SetFileName(const Value: string); begin inherited SetFileName(Value); if (FileName <> '') and (ContentID = '') then begin ContentID := GetUniqueContentID(ExtractFileName(FileName)); end; if (FileName <> '') and (ContentType = '') then begin ContentType := 'image/' + GetFileType(FileName); end; end; { TclMultipartBody } procedure TclMultipartBody.Assign(Source: TPersistent); var Multipart: TclMultipartBody; begin if (Source is TclMultipartBody) then begin Multipart := (Source as TclMultipartBody); Bodies := Multipart.Bodies; SetBoundary(Multipart.Boundary); ContentSubType := Multipart.ContentSubType; end; inherited Assign(Source); end; procedure TclMultipartBody.AssignBodyHeader(ASource: TStrings); begin FMailMessage.Clear(); FMailMessage.Bodies.Assign(Bodies); FMailMessage.GenerateBoundary(); if (ContentSubType <> '') then begin AddHeaderArrayField(ASource, [ContentType, 'type="' + ContentSubType + '"', 'boundary="' + Boundary + '"'], 'Content-Type', ';'); end else begin AddHeaderArrayField(ASource, [ContentType, 'boundary="' + Boundary + '"'], 'Content-Type', ';'); end; ASource.AddStrings(ExtraFields); ASource.Add(''); end; procedure TclMultipartBody.Clear; begin inherited Clear(); Bodies.Clear(); ContentType := 'multipart/mixed'; ContentSubType := ''; Encoding := cmNone; SetBoundary(''); end; procedure TclMultipartBody.DataAdded(AData: TStream); procedure FixRawBodyStart(ABodies: TclMessageBodies); var i: Integer; body: TclMessageBody; begin for i := 0 to ABodies.Count - 1 do begin body := ABodies[i]; body.FRawBodyStart := body.RawBodyStart + RawBodyStart; if(body is TclMultipartBody) then begin FixRawBodyStart(TclMultipartBody(body).Bodies); end; end; end; var list: TStrings; s: string; begin list := TStringList.Create(); try SetString(s, nil, AData.Size); AData.Position := 0; AData.Read(PChar(s)^, AData.Size); AddTextStr(list, s); FMailMessage.ParseBodies(list); Bodies.Assign(FMailMessage.Bodies); FixRawBodyStart(Bodies); FEncodedLines := list.Count; finally list.Free(); end; end; destructor TclMultipartBody.Destroy; begin FBodies.Free(); FMailMessage.Free(); inherited Destroy(); end; procedure TclMultipartBody.DoCreate; begin inherited DoCreate(); FMailMessage := TclMailMessage.Create(nil); FMailMessage.OnGetDataStream := DoOnGetDataStream; FMailMessage.OnGetDataSourceStream := DoOnGetDataSourceStream; FMailMessage.OnDataAdded := DoOnDataAdded; FBodies := TclMessageBodies.Create(GetMailMessage()); end; procedure TclMultipartBody.DoOnDataAdded(Sender: TObject; ABody: TclMessageBody; AData: TStream); begin AData.Position := 0; GetMailMessage().DoDataAdded(ABody, AData); end; procedure TclMultipartBody.DoOnGetDataSourceStream(Sender: TObject; ABody: TclMessageBody; const AFileName: string; var AStream: TStream; var Handled: Boolean); begin GetMailMessage().DoGetDataSourceStream(ABody, AFileName, AStream, Handled); end; procedure TclMultipartBody.DoOnGetDataStream(Sender: TObject; ABody: TclMessageBody; const AFileName: string; var AStream: TStream; var Handled: Boolean); begin GetMailMessage().DoGetDataStream(ABody, AFileName, AStream, Handled); end; function TclMultipartBody.GetBoundary: string; begin Result := FMailMessage.Boundary; end; function TclMultipartBody.GetDestinationStream: TStream; begin Result := TMemoryStream.Create(); end; function TclMultipartBody.GetSourceStream: TStream; var list: TStrings; s: string; begin Result := TMemoryStream.Create(); list := TStringList.Create(); try FMailMessage.InternalAssignBodies(list); s := list.Text; Result.WriteBuffer(Pointer(s)^, Length(s)); Result.Position := 0; finally list.Free(); end; end; function TclMultipartBody.HasEncodedData: Boolean; begin Result := False; end; procedure TclMultipartBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); var s: string; begin inherited ParseBodyHeader(ABodyPos, ASource, AFieldList); s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type'); SetBoundary(GetHeaderFieldValueItem(s, 'boundary=')); ContentSubType := GetHeaderFieldValueItem(s, 'type='); Encoding := cmNone; end; procedure TclMultipartBody.ReadData(Reader: TReader); begin ContentSubType := Reader.ReadString(); Bodies.ReadData(Reader); inherited ReadData(Reader); end; procedure TclMultipartBody.SetBodies(const Value: TclMessageBodies); begin FBodies.Assign(Value); end; procedure TclMultipartBody.SetBoundary(const Value: string); begin if (Boundary <> Value) then begin FMailMessage.SetBoundary(Value); GetMailMessage().Update(); end; end; procedure TclMultipartBody.SetContentSubType(const Value: string); begin if (FContentSubType <> Value) then begin FContentSubType := Value; GetMailMessage().Update(); end; end; procedure TclMultipartBody.WriteData(Writer: TWriter); begin Writer.WriteString(ContentSubType); Bodies.WriteData(Writer); inherited WriteData(Writer); end; initialization RegisterBody(TclTextBody); RegisterBody(TclAttachmentBody); RegisterBody(TclMultipartBody); RegisterBody(TclImageBody); finalization RegisteredBodyItems.Free(); end.
{ @abstract(Logger) The unit contains main logger interface and several default appenders @author(George Bakhtadze (avagames@gmail.com)) } unit g3log; {$I g3config.inc} interface uses g3types; type // Log level prefix string type TLogPrefix = string; // Log level class TLogLevel = (llVerbose, llDebug, llInfo, llWarning, llError, llFatalError); // Tag used to filter log messages on subsystem basis TLogTag = AnsiString; type // Method pointer which formats TLogFormatDelegate = function(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel): string of object; // Log appender metaclass CAppender = class of TAppender; // Abstract log appender TAppender = class(TObject) public // Format pattern for log timestamp. If empty no timestamps will be appended. TimeFormat: string; { Default appender constructor. Creates the appender of the specified log levels, initializes TimeFormat and Formatter to default values and registers the new appender in log system. } constructor Create(Level: TLogLevel); protected // Should be overridden to actually append log procedure AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); virtual; abstract; private FFormatter: TLogFormatDelegate; FLogLevel: TLogLevel; function GetPreparedStr(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel): string; procedure SetLevel(Level: TLogLevel); public // Set of levels which to include in the log property LogLevel: TLogLevel read FLogLevel write SetLevel; // String formatter delegate. It's recommended for descendant classes to use it. property Formatter: TLogFormatDelegate read FFormatter write FFormatter; end; // Filters by tag and calls all registered appenders to log the string with source location information procedure Log(const Tag: TLogTag; const Str: string; const CodeLoc: TCodeLocation; Level: TLogLevel); overload; // Calls all registered appenders to log the string with default log level procedure Log(const Str: string); overload; // Calls all registered appenders to log the verbose message procedure Verbose(const Str: string); overload; // Calls all registered appenders to log the debug message procedure Debug(const Str: string); overload; // Calls all registered appenders to log the info procedure Info(const Str: string); overload; // Calls all registered appenders to log the warning procedure Warning(const Str: string); overload; // Calls all registered appenders to log the error procedure Error(const Str: string); overload; // Calls all registered appenders to log the fatal error procedure Fatal(const Str: string); overload; // Calls all registered appenders to log the string with default log level procedure Log(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the verbose message procedure Verbose(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the debug message procedure Debug(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the info procedure Info(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the warning procedure Warning(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the error procedure Error(const Tag: TLogTag; const Str: string); overload; // Calls all registered appenders to log the fatal error procedure Fatal(const Tag: TLogTag; const Str: string); overload; // Prints to log the specified stack trace which can be obtained by some of BaseDebug unit routines procedure LogStackTrace(const StackTrace: TBaseStackTrace); { A special function-argument. Should be called ONLY as Assert() argument. Allows to log source file name and line number at calling location. Doesn't require any debug information to be included in binary module. The only requirement is inclusion of assertions code. Tested in Delphi 7+ and FPC 2.4.2+. Suggested usage: Assert(_Log(lkInfo), 'Log message'); This call will log the message with source filename and Line number Always returns False. } function _Log(Level: TLogLevel): Boolean; overload; function _Log(): Boolean; overload; // Adds an appender to list of registered appenders. All registered appenders will be destroyed on shutdown. procedure AddAppender(Appender: TAppender); // Removes an appender from list of registered appenders. Doesn't destroy the appender. procedure RemoveAppender(Appender: TAppender); // Returns a registered appender of the specified class function FindAppender(AppenderClass: CAppender): TAppender; { Initializes default appenders: TConsoleAppender if current application is a console application TWinDebugAppender for Delphi applications running under debugger in Windows OS } procedure AddDefaultAppenders(); // Removes all appenders added by AddDefaultAppenders() if any procedure RemoveDefaultAppenders(); type // Appends log messages to a system console. Application should be a console application. TSysConsoleAppender = class(TAppender) protected // Prints the log string to a system console procedure AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); override; end; // Use OutputsDebugString() for loging. Works only in Windows. TWinDebugAppender = class(TAppender) protected // Prints the log string with OutputsDebugString() procedure AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); override; end; // Appends log messages to a file. TFileAppender = class(TAppender) public // Creates the appender with the specified file name and log levels constructor Create(const Filename: string; ALevel: TLogLevel); protected // Appends file with the log string procedure AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); override; private LogFile: Text; end; implementation uses {$IFDEF MULTITHREADLOG} CEConcurrent, {$IFDEF UNIX} {$ENDIF} {$ENDIF} {$IFDEF WINDOWS}{$IFDEF DELPHI} {$IFDEF NAMESPACED_UNITS} Winapi.Windows, {$ELSE} Windows, {$ENDIF} {$ENDIF}{$ENDIF} SysUtils; const // Default level prefixes Prefix: array[TLogLevel] of string = (' (v) ', ' (d) ', ' (i) ', '(WW) ', '(EE) ', '(!!) '); { TAppender } constructor TAppender.Create(Level: TLogLevel); begin TimeFormat := 'dd"/"mm"/"yyyy hh":"nn":"ss"."zzz '; LogLevel := Level; FFormatter := GetPreparedStr; AddAppender(Self); Log('Appender of class ' + ClassName + ' initialized'); end; function TAppender.GetPreparedStr(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel): string; begin Result := FormatDateTime(TimeFormat, Now()) + Prefix[Level] + Str; if (CodeLoc <> nil) then Result := Concat(Result, ' --- ', CodeLocToStr(CodeLoc^)); end; procedure TAppender.SetLevel(Level: TLogLevel); begin FLogLevel := Level; end; { Logger } var FAppenders: array of TAppender; {$IFDEF MULTITHREADLOG} Mutex: TCEMutex; {$ENDIF} // LogLevelCount: array[TLogLevel] of Integer; procedure Lock(); begin {$IFDEF MULTITHREADLOG} MutexEnter(Mutex); {$ENDIF} end; procedure UnLock(); begin {$IFDEF MULTITHREADLOG} MutexLeave(Mutex); {$ENDIF} end; const EmptyCodeLoc: TCodeLocation = (Address: nil; SourceFilename: ''; UnitName: ''; ProcedureName: ''; LineNumber: -1); procedure Log(const Tag: TLogTag; const Str: string; const CodeLoc: TCodeLocation; Level: TLogLevel); overload; {$IFDEF LOG} var i: Integer; Time: TDateTime; SrcLocPtr: PCodeLocation; {$ENDIF} begin {$IFDEF LOG} Lock(); if CodeLoc.LineNumber = -1 then SrcLocPtr := nil else SrcLocPtr := @CodeLoc; Time := Now; for i := 0 to High(FAppenders) do if Level >= FAppenders[i].LogLevel then FAppenders[i].AppendLog(Time, Str, SrcLocPtr, Level); UnLock(); // Inc(LogLevelCount[Level]); {$ENDIF} end; procedure Log(const Str: string); begin Log('', Str, EmptyCodeLoc, llInfo); end; procedure Log(const Tag: TLogTag; const Str: string); overload; begin Log(Tag, Str, EmptyCodeLoc, llInfo); end; procedure Verbose(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llVerbose); {$ENDIF} end; procedure Verbose(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llVerbose); {$ENDIF} end; procedure Debug(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llDebug); {$ENDIF} end; procedure Debug(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llDebug); {$ENDIF} end; procedure Info(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llInfo); {$ENDIF} end; procedure Info(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llInfo); {$ENDIF} end; procedure Warning(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llWarning); {$ENDIF} end; procedure Warning(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llWarning); {$ENDIF} end; procedure Error(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llError); {$ENDIF} end; procedure Error(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llError); {$ENDIF} end; procedure Fatal(const Str: string); begin {$IFDEF LOG} Log('', Str, EmptyCodeLoc, llFatalError); {$ENDIF} end; procedure Fatal(const Tag: TLogTag; const Str: string); overload; begin {$IFDEF LOG} Log(Tag, Str, EmptyCodeLoc, llFatalError); {$ENDIF} end; procedure LogStackTrace(const StackTrace: TBaseStackTrace); var i: Integer; begin for i := 0 to High(StackTrace) do Log(' --- ' + IntToStr(i) + '. ' + CodeLocToStr(StackTrace[i])); end; var AssertLogLevel: TLogLevel; {$IFDEF FPC} procedure LogAssert(const Message, Filename: ShortString; LineNumber: LongInt; ErrorAddr: Pointer); {$ELSE} procedure LogAssert(const Message, Filename: string; LineNumber: Integer; ErrorAddr: Pointer); {$ENDIF} var CodeLocation: TCodeLocation; begin AssertRestore(); CodeLocation := GetCodeLoc(Filename, '', '', LineNumber, ErrorAddr); Log('', Message, CodeLocation, AssertLogLevel); end; function _Log(Level: TLogLevel): Boolean; overload; begin if AssertHook(@LogAssert) then begin AssertLogLevel := Level; Result := False; end else Result := True; // Prevent assertion error if hook failed end; function _Log(): Boolean; overload; begin Result := _Log(LLInfo); end; // Returns index of the appender or -1 if not found function IndexOfAppender(Appender: TAppender): Integer; begin Result := High(FAppenders); while (Result >= 0) and (FAppenders[Result] <> Appender) do Dec(Result); end; procedure AddAppender(Appender: TAppender); begin if not Assigned(Appender) then Exit; if IndexOfAppender(Appender) >= 0 then begin Warning('CELog', 'Duplicate appender of class "' + Appender.ClassName + '"'); Exit; end; Lock(); try SetLength(FAppenders, Length(FAppenders)+1); // Set default formatter if @Appender.Formatter = nil then Appender.Formatter := Appender.GetPreparedStr; FAppenders[High(FAppenders)] := Appender; finally Unlock(); end; end; procedure RemoveAppender(Appender: TAppender); var i: Integer; begin i := IndexOfAppender(Appender); // if found, replace it with last and resize array if i >= 0 then begin Lock(); try FAppenders[i] := FAppenders[High(FAppenders)]; SetLength(FAppenders, Length(FAppenders)-1); finally Unlock(); end; end; end; function FindAppender(AppenderClass: CAppender): TAppender; var i: Integer; begin i := High(FAppenders); while (i >= 0) and (FAppenders[i].ClassType <> AppenderClass) do Dec(i); if i >= 0 then Result := FAppenders[i] else Result := nil; end; {$WARN SYMBOL_PLATFORM OFF} procedure AddDefaultAppenders(); begin {$IFDEF WINDOWS}{$IFDEF DELPHI} if DebugHook > 0 then TWinDebugAppender.Create(llVerbose); {$ENDIF}{$ENDIF} if IsConsole then begin if Length(FAppenders) = 0 then TSysConsoleAppender.Create(llDebug) else TSysConsoleAppender.Create(llWarning) end; end; procedure RemoveDefaultAppenders(); begin if IsConsole then RemoveAppender(FindAppender(TSysConsoleAppender)); {$IFDEF WINDOWS}{$IFDEF DELPHI} if DebugHook > 0 then RemoveAppender(FindAppender(TWinDebugAppender)); {$ENDIF}{$ENDIF} end; procedure DestroyAppenders(); var i: Integer; begin Lock(); try for i := 0 to High(FAppenders) do begin FAppenders[i].Free; end; SetLength(FAppenders, 0); finally Unlock(); end; end; { TConsoleAppender } procedure TSysConsoleAppender.AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); begin if IsConsole then begin Writeln(Formatter(Time, Str, CodeLoc, Level)); Flush(Output); end; end; { TWinDebugAppender } procedure TWinDebugAppender.AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); begin {$IFDEF WINDOWS}{$IFDEF DELPHI} if DebugHook > 0 then {$IFDEF UNICODE} OutputDebugString(PWideChar(Formatter(Time, Str, CodeLoc, Level))); {$ELSE} OutputDebugStringA(PAnsiChar(Formatter(Time, Str, CodeLoc, Level))); {$ENDIF} {$ENDIF}{$ENDIF} end; { TFileAppender } constructor TFileAppender.Create(const Filename: string; ALevel: TLogLevel); begin if (Pos(':', Filename) > 0) or (Pos('/', Filename) = 1) then AssignFile(LogFile, Filename) else AssignFile(LogFile, ExtractFilePath(ParamStr(0)) + Filename); {$I-} Rewrite(LogFile); CloseFile(LogFile); //if IOResult <> 0 then LogLevels := []; inherited Create(ALevel); end; procedure TFileAppender.AppendLog(const Time: TDateTime; const Str: string; CodeLoc: PCodeLocation; Level: TLogLevel); begin {$I-} Append(LogFile); if IOResult <> 0 then Exit; WriteLn(LogFile, Formatter(Time, Str, CodeLoc, Level)); Flush(LogFile); CloseFile(LogFile); end; initialization {$IFDEF MULTITHREADLOG} MutexCreate(Mutex); {$ENDIF} // FillChar(LogLevelCount, SizeOf(LogLevelCount), 0); AddDefaultAppenders(); finalization Info('Log session shutdown'); { Log('Logged fatal errors: ' + IntToStr(LogLevelCount[lkFatalError]) + ', errors: ' + IntToStr(LogLevelCount[lkError]) + ', warnings: ' + IntToStr(LogLevelCount[lkWarning]) + ', titles: ' + IntToStr(LogLevelCount[lkNotice]) + ', infos: ' + IntToStr(LogLevelCount[lkInfo]) + ', debug info: ' + IntToStr(LogLevelCount[lkDebug]) );} DestroyAppenders(); {$IFDEF MULTITHREADLOG} MutexDelete(Mutex) {$ENDIF} end.
unit DmdDatabase_Ant; interface uses SysUtils, Classes, DBXpress, DB, SqlExpr, Forms, IniFiles, IdCoder, IdCoder3to4, IdCoderMIME, FMTBcd, IdBaseComponent, DBClient, Provider; type TdmDatabase_Ant = class(TDataModule) scoDados_Ant: TSQLConnection; Decoder64: TIdDecoderMIME; sdsExec: TSQLDataSet; procedure DataModuleCreate(Sender: TObject); private { Private declarations } function Fnc_ArquivoConfiguracao: string; public end; var dmDatabase_Ant: TdmDatabase_Ant; implementation uses DmdDatabase; {$R *.dfm} const cArquivoConfiguracao = 'Config.ini'; function TdmDatabase_Ant.Fnc_ArquivoConfiguracao: string; begin Result := ExtractFilePath(Application.ExeName) + cArquivoConfiguracao; end; procedure TdmDatabase_Ant.DataModuleCreate(Sender: TObject); var Config: TIniFile; begin {if not FileExists(Fnc_ArquivoConfiguracao) then Exit; Config := TIniFile.Create(Fnc_ArquivoConfiguracao); try try scoDados.Params.Values['DATABASE'] := Config.ReadString('CEBI', 'DATABASE', ''); scoDados.Params.Values['USER_NAME'] := Config.ReadString('CEBI', 'USERNAME', ''); scoDados.Params.Values['PASSWORD'] := Decoder64.DecodeString(Config.ReadString('CEBI', 'PASSWORD', '')); scoDados.Connected := True; except on E: exception do begin raise Exception.Create('Erro ao conectar ao banco de dados:' + #13 + 'Mensagem: ' + E.Message + #13 + 'Classe: ' + E.ClassName + #13 + #13 + 'Dados da Conexao ' + #13 + 'Banco de Dados: ' + scoDados.Params.Values['Database'] + #13 + 'Usuário: ' + scoDados.Params.Values['User_Name']); end; end; finally FreeAndNil(Config); end;} end; end.
unit typeDefGen; interface uses // Windows, SysUtils, // StdCtrls, Dialogs, typeDefBase, typeDefSucc, // ComCtrls, // operations, TypInfo; // Класс реализует очистку типов: TArrAppBaseFile, TAppFileArrayBM, TAppFileArrayJrnl type TErase = class(TObject) public class procedure Erase<T>(var a: T); static; end; type TItemOperation = class(TObject) public class procedure CreateObject<T>(var a: T); static; class procedure CreateArrayOfBaseClass<TArr, TItem>(var b: TArr; var a: TItem; i: Integer; str: string);static; class function IsObjectClear<T>(var a: T): Boolean; static; end; // Класс, используя возможности RTTI определяет тип объект. type TRTTI = class(TObject) public class function TypeInfo<T>: PTypeInfo; static; end; type TArrAppBaseFile = array of TAppFileBase; implementation uses mainUnit; class procedure TErase.Erase<T>(var a: T); var Info: PTypeInfo; i: Integer; begin { Лучше применять второй способ, т.к может попасться тип, не имеющий RTTI, например, Pointer } // Info := TypeInfo(T); Info := TRTTI.TypeInfo<T>; if Info = nil then Exit; if Info.Name = 'TArrAppBaseFile' then begin for i := Low(MultiFileArr) to High(MultiFileArr) do FreeAndNil(MultiFileArr[i]); Exit; end; if TObject(a) <> nil then FreeAndNil(a); end; class procedure TItemOperation.CreateObject<T>(var a: T); var Info: PTypeInfo; begin { Лучше применять второй способ, т.к может попасться тип, не имеющий RTTI, например, Pointer } // Info := TypeInfo(T); Info := TRTTI.TypeInfo<T>; if Info = nil then Exit; if Info.Name = 'TAppFileArrayBM' then begin TAppFileArrayBM(a) := TAppFileArrayBM.Create(fileName); TAppFileArrayBM(a).CreateFileArray(); // Закладки try TAppFileArrayBM(a).CreateListFromArray(); except ShowMessage('Ошибка создания TStringListBookMarks'); end; end else if Info.Name = 'TAppFileArrayJrnl' then begin TAppFileArrayJrnl(a) := TAppFileArrayJrnl.Create(fileName); TAppFileArrayJrnl(a).CreateFileArray(); // Закладки try TAppFileArrayJrnl(a).CreateListFromArray(); except ShowMessage('Ошибка создания TStringListJournal'); end; end; end; class procedure TItemOperation.CreateArrayOfBaseClass<TArr, TItem>(var b: TArr; var a: TItem; i: Integer; str: string); var InfoAr: PTypeInfo; InfoIt: PTypeInfo; tempArr: TArrAppBaseFile; ptr: Pointer; begin InfoAr := TRTTI.TypeInfo<TArr>; InfoIt := TRTTI.TypeInfo<TItem>; if (InfoAr = nil) or (InfoIt = nil) then Exit; ptr := @b; tempArr := TArrAppBaseFile(ptr^); if InfoIt.Name = 'TAppFileArrayBM' then begin TAppFileArrayBM(a) := TAppFileArrayBM.Create(str); tempArr[i] := TAppFileArrayBM(a); tempArr[i].CreateFileArray(); // Закладки try tempArr[i].CreateListFromArray(); except ShowMessage('Ошибка создания TStringListBookMarks'); end; end else if InfoIt.Name = 'TAppFileArrayJrnl' then begin TAppFileArrayJrnl(a) := TAppFileArrayJrnl.Create(str); tempArr[i] := TAppFileArrayJrnl(a); tempArr[i].CreateFileArray(); // Журнал try tempArr[i].CreateListFromArray(); except ShowMessage('Ошибка создания TStringListBookMarks'); end; end; end; class function TItemOperation.IsObjectClear<T>(var a: T): Boolean; var Info: PTypeInfo; tempArr: TArrAppBaseFile; ptr: Pointer; begin Result := False; Info := TRTTI.TypeInfo<T>; if Info.Name = 'TAppFileArrayBM' then begin if TAppFileArrayBM(a) = nil then Result := True; end else if Info.Name = 'TAppFileArrayJrnl' then begin if TAppFileArrayJrnl(a) = nil then Result := True; end else if Info.Name = 'TAppFileArrayBM' then begin ptr := @a; tempArr := TArrAppBaseFile(ptr^); if Length(tempArr) = 0 then Result := True; end end; class function TRTTI.TypeInfo<T>: PTypeInfo; begin Result := System.TypeInfo(T); end; end.
program interpreter_6502; uses Sysutils; const MEM_SIZE = 40; var mem: array[0..(MEM_SIZE-1)] of byte; // RAM PC: integer = 0; // program counter A, X, Y: byte; // accumulator, registers C, Z: boolean; // carry, zero flag UserInterrupt: boolean = False; CPUInterrupt: boolean = False; UserSkip: boolean = False; UserInput: string; token: byte; function CopyToMEM(filename: string):shortint; var source: file of byte; b: byte; i: integer; begin Assign(source, filename); Reset(source); i := 0; CopyToMEM := 0; while not eof(source) do begin read(source, b); mem[i] := b; inc(i); if i >= MEM_SIZE then begin writeln('ERROR -1: File is too big. Memory size: ', MEM_SIZE, 'B'); CopyToMEM := -1; break; end; end; Close(source); end; function HexToDec(s: string):byte; begin HexToDec := 0; if (s[1] >= 'A') and (s[1] <= 'F') then HexToDec := HextoDec + ord(s[1]) - ord('A') + 10 else HexToDec := HextoDec + StrToInt(s[1]); HexToDec := HexToDec * 16; if (s[2] >= 'A') and (s[2] <= 'F') then HexToDec := HextoDec + ord(s[2]) - ord('A') + 10 else HexToDec := HextoDec + StrToInt(s[2]); end; function ParseASM(sourceFN, targetFN: string):shortint; var source: file of char; target: file of byte; c1, c2: char; begin ParseASM := 0; Assign(source, sourceFN); Assign(target, targetFN); Reset(source); Rewrite(target); c1 := 'x'; c2 := 'x'; while not eof(source) do begin if c1 = 'x' then c1 := c2; read(source, c2); if c2 = ';' then while c2 <> #10 do read(source, c2); if (c2 = #10) or (c2 = ' ') then // newline c2 := 'x'; if (c1 <> 'x') and (c2 <> 'x') then begin blockwrite(target, HexToDec(Concat(c1, c2)),1); c1 := 'x'; c2 := 'x'; end; end; Close(source); Close(target); end; function ShowMEM():shortint; var i : integer; begin ShowMEM := 0; writeln(' Token: ', IntToHex(token, 2)); write(' RAM: '); for i := 0 to MEM_SIZE -1 do begin write(IntToHex(mem[i], 2)); end; writeln(); writeln(' PC: ', IntToHex(PC, 2), ' A: ', IntToHex(A, 2), ' X: ', IntToHex(X, 2), ' Y: ', IntToHex(Y, 2)); write(' C: ', C, ' Z: ', Z); end; begin ParseASM('source.asm', 'source.basm'); CopyToMEM('source.basm'); while (not UserInterrupt) and (not CPUInterrupt) do begin if not UserSkip then begin write('$', IntToHex(PC, 2), ': '); token := mem[PC]; if token = $EA then begin Write('NOP'); PC := PC + 1; end else if token = $A2 then begin // immediate Write('LDX $', IntToHex(mem[PC+1], 2)); X := mem[PC+1]; PC := PC + 2; end else if token = $A6 then begin // absolute address Write('LDX ($', IntToHex(mem[PC+1], 2), ')'); X := mem[mem[PC+1]]; PC := PC + 2; end else if token = $A9 then begin Write('LDA $', IntToHex(mem[PC+1], 2)); A := mem[PC+1]; PC := PC + 2; end else if token = $A5 then begin Write('LDA ($', IntToHex(mem[PC+1], 2), ')'); A := mem[mem[PC+1]]; PC := PC + 2; end else if token = $69 then begin Write('ADC $', IntToHex(mem[PC+1], 2)); A := A + mem[PC+1]; PC := PC + 2; end else if token = $E9 then begin Write('SBC $', IntToHex(mem[PC+1], 2)); A := A - mem[PC+1]; PC := PC + 2; end else if token = $85 then begin // absolute Write('STA $', IntToHex(mem[PC+1], 2)); mem[mem[PC+1]] := A; PC := PC + 2; end else if token = $95 then begin // relative to X Write('STA $', IntToHex(mem[PC+1], 2),'+X'); mem[mem[PC+1]+X] := A; PC := PC + 2; end else if token = $4C then begin Write('JMP $', IntToHex(mem[PC+1], 2)); PC := mem[PC+1]; end else if token = $6C then begin Write('JMP ($', IntToHex(mem[PC+1], 2), ')'); PC := mem[mem[PC+1]]; end else if token = $90 then begin Write('BCC $', IntToHex(mem[PC+1], 2)); if not C then PC := PC + 2 + shortint(mem[PC+1]) else PC := PC + 2; end else if token = $B0 then begin Write('BCS $', IntToHex(mem[PC+1], 2)); if C then PC := PC + 2 + shortint(mem[PC+1]) else PC := PC + 2; end else if token = $C9 then begin Write('CMP $', IntToHex(mem[PC+1], 2)); C := (A >= mem[PC+1]); PC := PC + 2; end else begin writeln('Token not implemented. '); ShowMEM(); writeln(); CPUInterrupt := True; end; end; UserSkip := False; if not CPUInterrupt then begin write(#9#9#9); readln(UserInput); if UserInput = 'q' then UserInterrupt := True else if UserInput = 'm' then begin UserSkip := True; ShowMEM(); end; end; end; end.
unit UPlayer; interface uses SysUtils, Classes, Generics.Collections, Generics.Defaults, UPiece, UBoard, UDie, USquare; type TPlayer = class private name: string; piece: TPiece; board: TBoard; dice: TList<TDie>; published constructor create(name: string; dice: TDie; board: TBoard); public procedure takeTurn; function GetLocation: TSquare; function getName: string; end; implementation { TPlayer } constructor TPlayer.create(name: string; dice: TDie; board: TBoard); begin self.name := name; //self.dice := dice; self.dice := TList<TDie>.create; self.dice.Add(dice); self.dice.Add(dice); self.board := board; piece := TPiece.create(board.getStartSquare); end; function TPlayer.GetLocation: TSquare; begin result := piece.GetLocation; end; function TPlayer.getName: string; begin result := name; end; procedure TPlayer.takeTurn; var rollTotal, i: integer; newLoc: TSquare; begin // бросание кубиков rollTotal := 0; for i := 0 to dice.Count-1 do begin // length = 2 dice.Items[i].roll; rollTotal := rollTotal + self.dice.Items[i].getFaceValue; end; newLoc := board.getSquare(piece.GetLocation, rollTotal); piece.setLocation(newLoc); end; end.
unit Card.Cards; interface uses ECMA.TypedArray, W3C.DOM4, W3C.HTML5, W3C.WebAudio, W3C.Canvas2DContext, Card.Framework, Card.Drawer; type TCardColor = (ccSpade, ccHeart, ccClub, ccDiamond); TCardValue = (cvA, cv2, cv3, cv4, cv5, cv6, cv7, cv8, cv9, cv10, cvJ, cvQ, cvK); TCard = class(TCanvas2DElement) private FColor: TCardColor; FValue: TCardValue; FIsConcealed: Boolean; FIsHighlighted: Boolean; FTransitionTime: Float; FPixelRatio: Float; FDrawerColor: TCustomCardColorDrawerClass; FDrawerValue: TCustomCardValueDrawerClass; procedure SetIsConcealed(Value: Boolean); procedure SetIsHighlighted(Value: Boolean); procedure SetTransitionTime(Value: Float); public constructor Create(Owner: IHtmlElementOwner; Color: TCardColor; Value: TCardValue); overload; virtual; procedure Resize; procedure Paint; property Color: TCardColor read FColor; property Value: TCardValue read FValue; property IsConcealed: Boolean read FIsConcealed write SetIsConcealed; property IsHighlighted: Boolean read FIsHighlighted write SetIsHighlighted; property TransitionTime: Float read FTransitionTime write SetTransitionTime; end; TArrayOfCard = array of TCard; implementation uses WHATWG.Console; { TCard } constructor TCard.Create(Owner: IHtmlElementOwner; Color: TCardColor; Value: TCardValue); const CDrawerColor: array [TCardColor] of TCustomCardColorDrawerClass = (TCardColorDrawerSpade, TCardColorDrawerHeart, TCardColorDrawerClub, TCardColorDrawerDiamond); CDrawerValue: array [TCardValue] of TCustomCardValueDrawerClass = (TCardValueDrawerA, TCardValueDrawer2, TCardValueDrawer3, TCardValueDrawer4, TCardValueDrawer5, TCardValueDrawer6, TCardValueDrawer7, TCardValueDrawer8, TCardValueDrawer9, TCardValueDrawer10, TCardValueDrawerJ, TCardValueDrawerQ, TCardValueDrawerK); begin inherited Create(Owner); FColor := Color; FValue := Value; FIsConcealed := True; FTransitionTime := 0; // determine pixel ratio FPixelRatio := 1; asm @FPixelRatio = window.devicePixelRatio || 1; end; FDrawerColor := CDrawerColor[Color]; FDrawerValue := CDrawerValue[Value]; Resize; end; procedure TCard.Resize; begin var R := CanvasElement.getBoundingClientRect; if (CanvasElement.width <> Round(FPixelRatio * R.width)) or (CanvasElement.height <> Round(FPixelRatio * R.height)) then begin CanvasElement.Width := Round(FPixelRatio * R.width); CanvasElement.Height := Round(FPixelRatio * R.height); Paint; end; end; procedure TCard.Paint; const CText: array [TCardValue] of String = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '=', 'J', 'Q', 'K'); begin var Large := CanvasElement.Width / 40; var Small := CanvasElement.Width / 60; var LargeFont := CanvasElement.Width / 12; var SmallFont := CanvasElement.Width / 36; Context.setTransform(1, 0, 0, 1, 0, 0); Context.ClearRect(0, 0, CanvasElement.Width, CanvasElement.Height); var Gradient := Context.createLinearGradient(0, 0, 0, CanvasElement.Height); Gradient.addColorStop(0, '#e1e1e1'); Gradient.addColorStop(1, '#fcfcfc'); Context.fillStyle := Gradient; Context.fillRect(1, 1, CanvasElement.Width, CanvasElement.Height); Context.clearRect(1, 1, 1, 1); if FIsConcealed then begin const CRoundWidth = 1.3; const CHalfLineWidth = 1; const CLineWidth = 1.3 * CHalfLineWidth; var Offset := 0.025 * CanvasElement.width; var TopLeft := TVector2F.Create(Offset + CHalfLineWidth, Offset + CHalfLineWidth); var BottomRight := TVector2F.Create(CanvasElement.Width - CHalfLineWidth - Offset, CanvasElement.Height - CHalfLineWidth - Offset); Context.strokeStyle := '#888'; Context.FillStyle := '#001381'; Context.LineWidth := CLineWidth; Context.BeginPath; Context.MoveTo(TopLeft.X + CRoundWidth, TopLeft.Y); Context.LineTo(BottomRight.X - CRoundWidth, TopLeft.Y); Context.arcTo(BottomRight.X, TopLeft.Y, BottomRight.X, TopLeft.Y + CRoundWidth, CRoundWidth); Context.LineTo(BottomRight.X, BottomRight.Y - CRoundWidth); Context.arcTo(BottomRight.X, BottomRight.Y, BottomRight.X - CRoundWidth, BottomRight.Y, CRoundWidth); Context.LineTo(TopLeft.X + CRoundWidth, BottomRight.Y); Context.arcTo(TopLeft.X, BottomRight.Y, TopLeft.X, BottomRight.Y - CRoundWidth, CRoundWidth); Context.LineTo(TopLeft.X, TopLeft.Y + CRoundWidth); Context.arcTo(TopLeft.X, TopLeft.Y, TopLeft.X + CRoundWidth, TopLeft.Y, CRoundWidth); Context.closePath; Context.Fill; Context.Stroke; Context.fillStyle := 'rgba(255,255,255,0.5)'; Offset *= 1.5; var Scale := (BottomRight.X - TopLeft.X - 2 * Offset) / TCardDrawerOrnament.Width; Context.Translate(TopLeft.X + Offset, TopLeft.Y + Offset); TCardDrawerOrnament.Draw(Context, Scale); Context.Translate(BottomRight.X - TopLeft.X - 2 * Offset, BottomRight.Y - TopLeft.Y - 2 * Offset); TCardDrawerOrnament.Draw(Context, Scale, True); Context.Translate(-BottomRight.X + Offset, -BottomRight.Y + Offset); Exit; end; if FIsHighlighted then begin Context.fillStyle := 'rgba(255,255,255,0.5)'; Context.fillRect(0, 0, CanvasElement.Width, CanvasElement.Height); end; Context.FillStyle := FDrawerColor.Color; Context.Translate(FPixelRatio * 6, FPixelRatio * 6); if Value in [cv2..cv9] then Context.Scale(1.4, 1); FDrawerValue.Draw(Context, SmallFont); if Value in [cv2..cv9] then Context.Scale(1 / 1.4, 1); Context.Translate(-FPixelRatio * 6, -FPixelRatio * 6); var w := 0.8 * CanvasElement.width; var h := 0.6 * CanvasElement.height; Context.translate(0.1 * CanvasElement.width, 0.2 * CanvasElement.height); case FValue of cvA: begin Context.beginPath; Context.translate(0.5 * w, 0.5 * h); FDrawerColor.Draw(Context, Large); Context.fill; end; cv2: begin Context.beginPath; Context.translate(0.5 * w, 0); FDrawerColor.Draw(Context, Small); Context.translate(0, h); FDrawerColor.Draw(Context, Small, True); Context.fill; end; cv3: begin Context.beginPath; Context.translate(0.5 * w, 0); for var Index := 1 to 3 do begin FDrawerColor.Draw(Context, Small, Index = 3); Context.translate(0, 0.5 * h); end; Context.fill; end; cv4: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 1 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, Y * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y = 1); Context.translate(-Offset.X, -Offset.Y); end; Context.fill; end; cv5: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 1 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, Y * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y = 1); Context.translate(-Offset.X, -Offset.Y); end; Context.translate(0.5 * w, 0.5 * h); FDrawerColor.Draw(Context, Small); Context.fill; end; cv6: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 2 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, 0.5 * Y * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y = 2); Context.translate(-Offset.X, -Offset.Y); end; Context.fill; end; cv7: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 2 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, 0.5 * Y * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y = 2); Context.translate(-Offset.X, -Offset.Y); end; Context.translate(0.5 * w, 0.25 * h); FDrawerColor.Draw(Context, Small); Context.fill; end; cv8: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 2 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, 0.5 * Y * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y = 2); Context.translate(-Offset.X, -Offset.Y); end; Context.translate(0.5 * w, 0.25 * h); FDrawerColor.Draw(Context, Small); Context.translate(0, 0.5 * h); FDrawerColor.Draw(Context, Small, True); Context.fill; end; cv9: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 3 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, Y / 3 * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y >= 2); Context.translate(-Offset.X, -Offset.Y); end; Context.translate(0.5 * w, h / 6); FDrawerColor.Draw(Context, Small); Context.fill; end; cv10: begin Context.beginPath; for var X := 0 to 1 do for var Y := 0 to 3 do begin var Offset := TVector2f.Create((0.25 + 0.5 * X) * w, Y / 3 * h); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small, Y >= 2); Context.translate(-Offset.X, -Offset.Y); end; Context.translate(0.5 * w, h / 6); FDrawerColor.Draw(Context, Small); Context.translate(0, 2 / 3 * h); FDrawerColor.Draw(Context, Small, True); Context.fill; end; cvJ: begin Context.beginPath; Context.Rect(0, 0, w, h); Context.Stroke; Context.beginPath; var Offset := TVector2f.Create(0.25 * w, 0); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small); Context.translate(-Offset.X, -Offset.Y); Context.fill; Context.translate(0.5 * w, 0.5 * h); FDrawerValue.Draw(Context, LargeFont, True); end; cvQ: begin Context.beginPath; Context.Rect(0, 0, w, h); Context.Stroke; Context.beginPath; var Offset := TVector2f.Create(0.25 * w, 0); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small); Context.translate(-Offset.X, -Offset.Y); Context.fill; Context.translate(0.5 * w, 0.5 * h); FDrawerValue.Draw(Context, LargeFont, True); end; cvK: begin Context.beginPath; Context.Rect(0, 0, w, h); Context.StrokeStyle := #888; Context.Stroke; Context.beginPath; var Offset := TVector2f.Create(0.25 * w, 0); Context.translate(Offset.X, Offset.Y); FDrawerColor.Draw(Context, Small); Context.translate(-Offset.X, -Offset.Y); Context.fill; Context.translate(0.5 * w, 0.5 * h); FDrawerValue.Draw(Context, LargeFont, True); end; end; end; procedure TCard.SetIsConcealed(Value: Boolean); begin if FIsConcealed <> Value then begin FIsConcealed := Value; Paint; end; end; procedure TCard.SetIsHighlighted(Value: Boolean); begin if FIsHighlighted <> Value then begin FIsHighlighted := Value; Paint; end; end; procedure TCard.SetTransitionTime(Value: Float); begin if FTransitionTime <> Value then begin FTransitionTime := Value; if FTransitionTime = 0 then begin Style.removeProperty('-webkit-transition'); Style.removeProperty('transition'); end else begin var s := FloatToStr(Value); s := 'left ' + s + 's, top ' + s + 's'; Style.setProperty('-webkit-transition', s); Style.setProperty('transition', s); end; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OpenGL, ExtCtrls; type TPoint3D = record//Описание структуры для хранения точки в пространстве x,y,z : double; end; TForm1 = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure drawQuad(p1, p2, p3: TPoint3D); private { Private declarations } hrc: HGLRC; public { Public declarations } end; var Form1: TForm1; DC : HDC; angel: real; ps : TPaintStruct; p1,p2,p3,p4: TPoint3D; implementation {$R *.dfm} { TForm1 } procedure SetDCPixelFormat(hdc: HDC); var pfd : TPIXELFORMATDESCRIPTOR; // данные формата пикселей nPixelFormat : Integer; Begin With pfd do begin nSize := sizeof (TPIXELFORMATDESCRIPTOR); // размер структуры nVersion := 1; // номер версии dwFlags := PFD_DRAW_TO_WINDOW OR PFD_SUPPORT_OPENGL OR PFD_DOUBLEBUFFER; // множество битовых флагов, определяющих устройство и интерфейс iPixelType := PFD_TYPE_RGBA; // режим для изображения цветов cColorBits := 16; // число битовых плоскостей в каждом буфере цвета cDepthBits := 32; // размер буфера глубины (ось z) iLayerType := PFD_MAIN_PLANE;// тип плоскости end; nPixelFormat := ChoosePixelFormat (hdc, @pfd); // запрос системе - поддерживается ли выбранный формат пикселей SetPixelFormat (hdc, nPixelFormat, @pfd); // устанавливаем формат пикселей в контексте устройства End; procedure TForm1.drawQuad(p1, p2, p3: TPoint3D); begin glBegin(GL_QUADS); glVertex3d(p1.x,p1.y,p1.z); glVertex3d(p2.x,p2.y,p2.z); glVertex3d(p3.x,p3.y,p3.z); glVertex3d(p1.x+p3.x-p2.x,p1.y+p3.y-p2.y,p1.z+p3.z-p2.z); glEnd; end; procedure TForm1.FormCreate(Sender: TObject); begin SetDCPixelFormat(Canvas.Handle);// устанавливаем формат пикселей hrc := wglCreateContext(Canvas.Handle);//создаём контекст воспроизведения wglMakeCurrent(Canvas.Handle, hrc);//устанавливаем контекст воспроизведения DC := GetDC(Handle); angel := 0; end; procedure TForm1.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); // освобождаем контекст воспроизведения wglDeleteContext (hrc); // удаление контекста OpenGL end; procedure TForm1.FormPaint(Sender: TObject); begin p1.x := 1; p1.y := 1; p1.z := 1; p2.x := -1.25; p2.y := 0; p2.z := 1; p3.x := -1.25; p3.y := 2.5; p3.z := 1; p4.x := -1.25; p4.y := 0; p4.z := 2.5; BeginPaint(Handle, ps); // очистка буфера цвета и буфера глубины glClearColor(1.0,1.0,1.0,1.0); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);//Очищаем также и буфер глубины glColor(1.0,1.0,0.0); // трехмерность glLoadIdentity; glTranslatef(0 , 0, -15.0);//Отодвигаем точку наблюдения на 15 единиц назад glRotatef(30,0,1,0);//Вращаем сцену относительно наблюдателя на 30 градусов вокруг //оси У. glRotatef(angel,0,1,0); //Выводим изображения 3-х квадратов glColor(1.0,0.0,0.0); drawQuad(p1,p2,p3); glColor(0.0,1.0,0.0); //drawQuad(p3,p2,p4); glColor(0.0,0.0,1.0); //drawQuad(p4,p3,p2); SwapBuffers(DC); // конец работы EndPaint(Handle, ps); end; procedure TForm1.FormResize(Sender: TObject); begin glMatrixMode(GL_PROJECTION);//Текущей матрицей устанавливается матрица проекций glLoadIdentity;//Замена текущей матрицы единичной gluPerspective(30.0, Width/Height, 1.0, 15.0);//Определение усеченного конуса //видимости в видовой системе координат. Первые 2 параметры задают углы //видимости относительно осей х и у, а последние 2 параметра - ближнюю и дальнюю //границы видимости glViewport(0, 0, Width, Height);//Определение области видимости glMatrixMode(GL_MODELVIEW);//Текущей матрицей устанавливается видовая матрица InvalidateRect(Handle, nil, False);//Принудительная перерисовка формы end; procedure TForm1.Timer1Timer(Sender: TObject); begin angel := round(angel + 1) mod 360;//изменение угла поворота сцены от 0 до 360 InvalidateRect(Handle,nil,False);//принудительная перерисовка окна end; end.
unit cn_sp_SpecUnit_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxCurrencyEdit, cxContainer, cxEdit, cxTextEdit, StdCtrls, cxControls, cxGroupBox, cxButtons, cnConsts, Buttons, cxCheckBox, cnConsts_Messages; type TfrmSpec_AE = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameStage_Label: TLabel; CnCode_Label: TLabel; NameStage_Edit: TcxTextEdit; ShortName_Edit: TcxTextEdit; Label1: TLabel; FullName_Edit: TcxTextEdit; FullNameStage_Label: TLabel; SpeedButton1: TSpeedButton; cxCheckDelete: TcxCheckBox; cnCode_Edit: TcxTextEdit; procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure NameStage_EditKeyPress(Sender: TObject; var Key: Char); procedure cnCode_EditKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char); procedure SpeedButton1Click(Sender: TObject); procedure NameStage_EditExit(Sender: TObject); private PLanguageIndex : byte; procedure FormIniLanguage(); public constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce; end; var frmSpec_AE: TfrmSpec_AE; implementation {$R *.dfm} constructor TfrmSpec_AE.Create(AOwner:TComponent; LanguageIndex : byte); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); PLanguageIndex:= LanguageIndex; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure TfrmSpec_AE.FormIniLanguage; begin NameStage_Label.caption:= cnConsts.cn_Name_Column[PLanguageIndex]; CnCode_Label.caption:= cnConsts.cn_roles_Kod[PLanguageIndex]; Label1.caption:= cnConsts.cn_ShortName[PLanguageIndex]; FullNameStage_Label.caption:= cnConsts.cn_Full_Name[PLanguageIndex]; OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex]; CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex]; end; procedure TfrmSpec_AE.OkButtonClick(Sender: TObject); begin if NameStage_Edit.Text = '' then begin ShowMessage(cnConsts_Messages.cn_Name_Need[PLanguageIndex]); NameStage_Edit.SetFocus; Exit; end; ModalResult:=mrOk; end; procedure TfrmSpec_AE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmSpec_AE.NameStage_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then cnCode_Edit.SetFocus; end; procedure TfrmSpec_AE.cnCode_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then ShortName_Edit.SetFocus; end; procedure TfrmSpec_AE.FormShow(Sender: TObject); begin NameStage_Edit.SetFocus; end; procedure TfrmSpec_AE.ShortName_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then OkButton.SetFocus; end; procedure TfrmSpec_AE.SpeedButton1Click(Sender: TObject); begin FullName_Edit.Text := NameStage_Edit.Text; end; procedure TfrmSpec_AE.NameStage_EditExit(Sender: TObject); begin if Caption = cnConsts.cn_InsertBtn_Caption[PLanguageIndex] then SpeedButton1Click(Sender); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLTexCombineShader<p> A shader that allows texture combiner setup.<p> <b>History : </b><font size=-1><ul> <li>24/07/09 - DaStr - TGLShader.DoInitialize() now passes rci (BugTracker ID = 2826217) <li>03/04/07 - DaStr - Added $I GLScene.inc <li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas <li>23/05/03 - EG - Added support for binding two extra texture units <li>16/05/03 - EG - Creation </ul></font> } unit GLTexCombineShader; interface {$I GLScene.inc} uses Classes, GLTexture, GLMaterial, GLRenderContextInfo; type // TGLTexCombineShader // {: A shader that can setup the texture combiner.<p> } TGLTexCombineShader = class (TGLShader) private { Protected Declarations } FCombiners : TStrings; FCombinerIsValid : Boolean; // to avoid reparsing invalid stuff FDesignTimeEnabled : Boolean; FMaterialLibrary : TGLMaterialLibrary; FLibMaterial3Name : TGLLibMaterialName; currentLibMaterial3 : TGLLibMaterial; FLibMaterial4Name : TGLLibMaterialName; currentLibMaterial4 : TGLLibMaterial; FApplied3, FApplied4 : Boolean; protected { Protected Declarations } procedure SetCombiners(const val : TStrings); procedure SetDesignTimeEnabled(const val : Boolean); procedure SetMaterialLibrary(const val : TGLMaterialLibrary); procedure SetLibMaterial3Name(const val : TGLLibMaterialName); procedure SetLibMaterial4Name(const val : TGLLibMaterialName); procedure NotifyLibMaterial3Destruction; procedure NotifyLibMaterial4Destruction; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci : TRenderContextInfo) : Boolean; override; procedure DoFinalize; override; public { Public Declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure NotifyChange(Sender : TObject); override; published { Published Declarations } property Combiners : TStrings read FCombiners write SetCombiners; property DesignTimeEnabled : Boolean read FDesignTimeEnabled write SetDesignTimeEnabled; property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; property LibMaterial3Name : TGLLibMaterialName read FLibMaterial3Name write SetLibMaterial3Name; property LibMaterial4Name : TGLLibMaterialName read FLibMaterial4Name write SetLibMaterial4Name; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils, GLTextureCombiners, OpenGL1x, OpenGLTokens, XOpenGL, GLCrossPlatform, GLUtils; // ------------------ // ------------------ TGLTexCombineShader ------------------ // ------------------ // Create // constructor TGLTexCombineShader.Create(AOwner : TComponent); begin inherited; ShaderStyle:=ssLowLevel; FCombiners:=TStringList.Create; TStringList(FCombiners).OnChange:=NotifyChange; FCombinerIsValid:=True; end; // Destroy // destructor TGLTexCombineShader.Destroy; begin if Assigned(currentLibMaterial3) then currentLibMaterial3.UnregisterUser(Self); if Assigned(currentLibMaterial4) then currentLibMaterial4.UnregisterUser(Self); inherited; FCombiners.Free; end; // Notification // procedure TGLTexCombineShader.Notification(AComponent: TComponent; Operation: TOperation); begin if (FMaterialLibrary=AComponent) and (Operation=opRemove) then begin NotifyLibMaterial3Destruction; NotifyLibMaterial4Destruction; FMaterialLibrary:=nil; end; inherited; end; // NotifyChange // procedure TGLTexCombineShader.NotifyChange(Sender : TObject); begin FCombinerIsValid:=True; inherited NotifyChange(Sender); end; // NotifyLibMaterial3Destruction // procedure TGLTexCombineShader.NotifyLibMaterial3Destruction; begin FLibMaterial3Name:=''; currentLibMaterial3:=nil; end; // NotifyLibMaterial4Destruction // procedure TGLTexCombineShader.NotifyLibMaterial4Destruction; begin FLibMaterial4Name:=''; currentLibMaterial4:=nil; end; // SetMaterialLibrary // procedure TGLTexCombineShader.SetMaterialLibrary(const val : TGLMaterialLibrary); begin FMaterialLibrary:=val; SetLibMaterial3Name(LibMaterial3Name); SetLibMaterial4Name(LibMaterial4Name); end; // SetLibMaterial3Name // procedure TGLTexCombineShader.SetLibMaterial3Name(const val : TGLLibMaterialName); var newLibMaterial : TGLLibMaterial; begin // locate new libmaterial if Assigned(FMaterialLibrary) then newLibMaterial:=MaterialLibrary.Materials.GetLibMaterialByName(val) else newLibMaterial:=nil; FLibMaterial3Name:=val; // unregister if required if newLibMaterial<>currentLibMaterial3 then begin // unregister from old if Assigned(currentLibMaterial3) then currentLibMaterial3.UnregisterUser(Self); currentLibMaterial3:=newLibMaterial; // register with new if Assigned(currentLibMaterial3) then currentLibMaterial3.RegisterUser(Self); NotifyChange(Self); end; end; // SetLibMaterial4Name // procedure TGLTexCombineShader.SetLibMaterial4Name(const val : TGLLibMaterialName); var newLibMaterial : TGLLibMaterial; begin // locate new libmaterial if Assigned(FMaterialLibrary) then newLibMaterial:=MaterialLibrary.Materials.GetLibMaterialByName(val) else newLibMaterial:=nil; FLibMaterial4Name:=val; // unregister if required if newLibMaterial<>currentLibMaterial4 then begin // unregister from old if Assigned(currentLibMaterial4) then currentLibMaterial4.UnregisterUser(Self); currentLibMaterial4:=newLibMaterial; // register with new if Assigned(currentLibMaterial4) then currentLibMaterial4.RegisterUser(Self); NotifyChange(Self); end; end; // DoInitialize // procedure TGLTexCombineShader.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); begin end; // DoApply // procedure TGLTexCombineShader.DoApply(var rci : TRenderContextInfo; Sender : TObject); var n, units : Integer; begin if not GL_ARB_multitexture then Exit; FApplied3:=False; FApplied4:=False; if FCombinerIsValid and (FDesignTimeEnabled or (not (csDesigning in ComponentState))) then begin try if Assigned(currentLibMaterial3) or Assigned(currentLibMaterial4) then begin glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, @n); units:=0; if Assigned(currentLibMaterial3) and (n>=3) then begin with currentLibMaterial3.Material.Texture do begin if Enabled then begin if currentLibMaterial3.TextureMatrixIsIdentity then ApplyAsTextureN(3, rci) else ApplyAsTextureN(3, rci, @currentLibMaterial3.TextureMatrix[0][0]); // ApplyAsTextureN(3, rci, currentLibMaterial3); Inc(units, 4); FApplied3:=True; end; end; end; if Assigned(currentLibMaterial4) and (n>=4) then begin with currentLibMaterial4.Material.Texture do begin if Enabled then begin if currentLibMaterial4.TextureMatrixIsIdentity then ApplyAsTextureN(4, rci) else ApplyAsTextureN(4, rci, @currentLibMaterial4.TextureMatrix[0][0]); // ApplyAsTextureN(4, rci, currentLibMaterial4); Inc(units, 8); FApplied4:=True; end; end; end; if units>0 then xglMapTexCoordToArbitraryAdd(units); end; SetupTextureCombiners(FCombiners.Text); except on E: Exception do begin FCombinerIsValid:=False; InformationDlg(E.ClassName+': '+E.Message); end; end; end; end; // DoUnApply // function TGLTexCombineShader.DoUnApply(var rci : TRenderContextInfo) : Boolean; begin if FApplied3 then with currentLibMaterial3.Material.Texture do UnApplyAsTextureN(3, rci, (not currentLibMaterial3.TextureMatrixIsIdentity)); if FApplied4 then with currentLibMaterial4.Material.Texture do UnApplyAsTextureN(4, rci, (not currentLibMaterial4.TextureMatrixIsIdentity)); Result:=False; end; // DoFinalize // procedure TGLTexCombineShader.DoFinalize; begin end; // SetCombiners // procedure TGLTexCombineShader.SetCombiners(const val : TStrings); begin if val<>FCombiners then begin FCombiners.Assign(val); NotifyChange(Self); end; end; // SetDesignTimeEnabled // procedure TGLTexCombineShader.SetDesignTimeEnabled(const val : Boolean); begin if val<>FDesignTimeEnabled then begin FDesignTimeEnabled:=val; NotifyChange(Self); end; end; end.
unit Chapter08._01_02_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.UString, DeepStar.Utils; // 17. Letter Combinations of a Phone Number // https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ // 时间复杂度: O(2^len(s)) // 空间复杂度: O(len(s)) type TSolution = class(TObject) public function letterCombinations(digits: UString): TList_str; end; procedure Main; implementation procedure Main; var res: TList_str; begin with TSolution.Create do begin res := letterCombinations('22'); TArrayUtils_str.Print(res.ToArray); res.Free; Free; end; end; { TSolution } function TSolution.letterCombinations(digits: UString): TList_str; const letterMap: TArr_str = ( ' ', //0 '', //1 'abc', //2 'def', //3 'ghi', //4 'jkl', //5 'mno', //6 'pqrs', //7 'tuv', //8 'wxyz'); //9 var res: TList_str; // s中保存了此时从digits[0...index-1]翻译得到的一个字母字符串 // 寻找和digits[index]匹配的字母, 获得digits[0...index]翻译得到的解 procedure __findCombination__(digits: UString; index: integer; s: UString); var c: UChar; letters: UString; i: integer; begin if index = digits.Length then begin res.AddLast(s); Exit; end; c := digits.Chars[index]; letters := letterMap[Ord(c) - Ord('0')]; for i := 0 to letters.Length - 1 do begin __findCombination__(digits, index + 1, s + letters.Chars[i]); end; end; begin res := TList_str.Create; if digits = '' then Exit(res); __findCombination__(digits, 0, ''); Result := res; end; end.
unit Proposal; interface uses System.Classes; function Bytes2TXT(const AFileJPG: string): string; function TXT2Bytes(const AContent: string): TStringStream; implementation uses System.SysUtils; function Bytes2TXT(const AFileJPG: string): string; var INFile : file of Byte; bFragment: Byte; begin AssignFile(INFile, AFileJPG); try Reset(INFile); Result := ''; while not Eof(INFile) do begin Read(INFile, bFragment); Result := Result + IntToHex(bFragment); end; finally CloseFile(INFile); end; end; function TXT2Bytes(const AContent: string): TStringStream; var aBuffer : TArray<Byte>; oContent: TStringStream; iLen : Integer; i : Integer; sSwap : string; begin oContent := TStringStream.Create(EmptyStr, TEncoding.GetEncoding('iso-8859-1')); iLen := Length(AContent) div 2; SetLength(aBuffer, iLen); for i := 0 to Pred(iLen) do begin sSwap := Copy(AContent, i * 2 + 1, 2); aBuffer[i] := StrToInt('$' + sSwap); end; oContent.WriteData(aBuffer, iLen); Result := oContent; end; end.
program poj1046; var n,m,a,b,c,l,i,j,k,aa,bb:int64; gg:int64; x,y:int64; d,t:int64; function exgcd(a,b:int64; var x,y:int64):longint; var t:int64; begin if b=0 then begin exgcd:=a; x:=1; y:=0; end else begin exgcd:=exgcd(b,a mod b,x,y); t:=x; x:=y; y:=t-(a div b)*y; end; end; begin read(aa,bb,m,n,l); if m>n then begin d:=bb-aa; a:=m-n; end else begin d:=aa-bb; a:=n-m; end; gg:=exgcd(a,l,x,y); if d mod gg<>0 then writeln('Impossible') else begin x:=x*d div gg; l:=l div gg; x:=(x mod l+l) mod l; writeln(x); end; end.
{..............................................................................} { Summary Demonstration of the PCB's Undo system. } { } { Three procedures to demonstrate how the Undo system works - } { as one large Undo or multiple smaller Undos, and create,modify and delete } { } { 1/ Execute UndoEach to undo each object repeatedly with several undos } { 2/ Execute UndoAll procedure to remove all objects with one Undo } { 3/ Create, Modify and Undo this new object } { } { Copyright (c) 2006 by Altium Limited } {..............................................................................} {..............................................................................} Procedure Create2PCBObjectsWithTwoUndos; Var Depth : Integer; Board : IPCB_Board; Fill1 : IPCB_Fill1; Fill2 : IPCB_Fill2; Begin If PCBServer = Nil Then Exit; CreateNewDocumentFromDocumentKind('PCB'); Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Exit; // Initialize robots in PCB Server PCBServer.PreProcess; Fill1 := PCBServer.PCBObjectFactory(eFillObject, eNoDimension, eCreate_Default); Fill1.X1Location := MilsToCoord(4000); Fill1.Y1Location := MilsToCoord(4000); Fill1.X2Location := MilsToCoord(4400); Fill1.Y2Location := MilsToCoord(4400); Fill1.Rotation := 0; Fill1.Layer := eTopLayer; Board.AddPCBObject(Fill1); // Notify the robots that the pcb object has been registered. PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Fill1.I_ObjectAddress); // Clean up robots in PCB Server PCBServer.PostProcess; // Initialize robots in PCB Server PCBServer.PreProcess; Fill2 := PCBServer.PCBObjectFactory(eFillObject, eNoDimension, eCreate_Default); Fill2.X1Location := MilsToCoord(5000); Fill2.Y1Location := MilsToCoord(3000); Fill2.X2Location := MilsToCoord(5500); Fill2.Y2Location := MilsToCoord(4000); Fill2.Rotation := 45; Fill2.Layer := eTopLayer; Board.AddPCBObject(Fill2); // Notify the robots that the pcb object has been registered. PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Fill2.I_ObjectAddress); // Clean up robots in PCB Server PCBServer.PostProcess; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); End; {..................................................................................................} {..................................................................................................} Procedure Create2PCBObjectsWithOneUndo; Var Board : IPCB_Board; Fill1 : IPCB_Fill1; Fill2 : IPCB_Fill2; Begin CreateNewDocumentFromDocumentKind('PCB'); Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Exit; PCBServer.PreProcess; Fill1 := PCBServer.PCBObjectFactory(eFillObject, eNoDimension, eCreate_Default); Fill1.X1Location := MilsToCoord(4000); Fill1.Y1Location := MilsToCoord(4000); Fill1.X2Location := MilsToCoord(4400); Fill1.Y2Location := MilsToCoord(4400); Fill1.Rotation := 0; Fill1.Layer := eTopLayer; Board.AddPCBObject(Fill1); // notify the event manager that the pcb object has been registered. PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Fill1.I_ObjectAddress); Fill2 := PCBServer.PCBObjectFactory(eFillObject, eNoDimension, eCreate_Default); Fill2.X1Location := MilsToCoord(5000); Fill2.Y1Location := MilsToCoord(3000); Fill2.X2Location := MilsToCoord(5500); Fill2.Y2Location := MilsToCoord(4000); Fill2.Rotation := 45; Fill2.Layer := eTopLayer; Board.AddPCBObject(Fill2); // notify the event manager that the pcb object has been registered. PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Fill2.I_ObjectAddress); PCBServer.PostProcess; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); End; {..................................................................................................} {..................................................................................................} Var Fill : IPCB_Fill; {..................................................................................................} {..................................................................................................} Procedure CreateObject(Dummy : Integer = 0); Begin PCBServer.PreProcess; Fill := PCBServer.PCBObjectFactory(eFillObject, eNoDimension, eCreate_Default); Fill.X1Location := MilsToCoord(4000); Fill.Y1Location := MilsToCoord(4000); Fill.X2Location := MilsToCoord(4400); Fill.Y2Location := MilsToCoord(4400); Fill.Rotation := 0; Fill.Layer := eTopLayer; // Adds the Fill object into the PCB database for the current PCB document. Board.AddPCBObject(Fill); PCBServer.PostProcess; End; {..................................................................................................} {..................................................................................................} Procedure ModifyObject(Dummy : Integer = 0); Begin PCBServer.PreProcess; //Undo the fill object. PCBServer.SendMessageToRobots(Fill.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData); Fill.Layer := eBottomLayer; PCBServer.SendMessageToRobots(Fill.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData); PCBServer.PostProcess; End; {..................................................................................................} {..................................................................................................} Procedure RemoveObject(Dummy : Integer = 0); Begin PCBServer.PreProcess; //Remove the fill object. Board.RemovePCBObject(Fill); PCBServer.PostProcess; End; {..................................................................................................} {..................................................................................................} Procedure CreateModifyRemoveAObject; Begin CreateNewDocumentFromDocumentKind('PCB'); Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Exit; ShowInfo('Creating an object'); CreateObject; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); ShowInfo('Modifying this object'); ModifyObject; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); ShowInfo('Undoing the modification'); RemoveObject; Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); End; {..................................................................................................} {..................................................................................................}
unit URepositorioEntEstoque; interface uses UEntradaEstoque, UEntidade, URepositorioDB, UDeposito, URepositorioDeposito, UProduto, URepositorioProduto, SqlExpr ; type TrepositorioEntEstoque = class (TRepositorioDB<TEntradaEstoque>) private FRepositorioDeposito: TRepositorioDeposito; FRepositorioProduto: TRepositorioProduto; public constructor Create; destructor Destroy; override; procedure AtribuiDBParaEntidade (const coEntradaEstoque: TENTRADAESTOQUE); override; procedure AtribuiEntidadeParaDB (const coEntradaEstoque: TENTRADAESTOQUE; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM ,SysUtils ; { TrepositorioEntEstoque } procedure TrepositorioEntEstoque.AtribuiDBParaEntidade(const coEntradaEstoque: TENTRADAESTOQUE); begin inherited; with FSQLSelect do begin coEntradaEstoque.DATAEMISSAO := FieldByName(FLD_ENTRADA_ESTOQUE_DATAEMISSAO).Asdatetime; coEntradaEstoque.DATAENTRADA := FieldByName(FLD_ENTRADA_ESTOQUE_DATAENTRADA).Asdatetime; coEntradaEstoque.NUMERODOCUMENTO := FieldByName(FLD_ENTRADA_ESTOQUE_NUMERODOCUMENTO).AsInteger; coEntradaEstoque.PRODUTO := TPRODUTO ( FRepositorioProduto.Retorna (FieldByName (FLD_ENTRADA_ESTOQUE_PRODUTO).AsInteger)); coEntradaEstoque.QUANTIDADE := FieldByName(FLD_ENTRADA_ESTOQUE_QUANTIDADE).AsInteger; coEntradaEstoque.CUSTOUNITARIO := FieldByName(FLD_ENTRADA_ESTOQUE_CUSTOUNITARIO).AsFloat; coEntradaEstoque.VALORTOTAL := FieldByName (FLD_ENTRADA_ESTOQUE_VALORTOTAL).AsFloat; coEntradaEstoque.DEPOSITO := TDEPOSITO ( FRepositorioProduto.Retorna (FieldByName (FLD_ENTRADA_ESTOQUE_DEPOSITO).AsInteger)); coEntradaEstoque.LOTE := FieldByName (FLD_ENTRADA_ESTOQUE_LOTE).AsInteger; coEntradaEstoque.LOTEVALIDADE := FieldByName (FLD_ENTRADA_ESTOQUE_LOTEVALIDADE).Asdatetime; end; end; procedure TrepositorioEntEstoque.AtribuiEntidadeParaDB( const coEntradaEstoque: TENTRADAESTOQUE; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName (FLD_ENTRADA_ESTOQUE_DATAEMISSAO).Asdatetime := coEntradaEstoque.DATAEMISSAO; ParamByName (FLD_ENTRADA_ESTOQUE_DATAENTRADA).Asdatetime := coEntradaEstoque.DATAENTRADA; ParamByName (FLD_ENTRADA_ESTOQUE_NUMERODOCUMENTO).AsInteger := coEntradaEstoque.NUMERODOCUMENTO; ParamByName (FLD_ENTRADA_ESTOQUE_PRODUTO).AsInteger := coEntradaEstoque.PRODUTO.ID; ParambyName (FLD_ENTRADA_ESTOQUE_QUANTIDADE).AsInteger := coEntradaEstoque.QUANTIDADE; ParambyName (FLD_ENTRADA_ESTOQUE_CUSTOUNITARIO).AsFloat := coEntradaEstoque.CUSTOUNITARIO; ParambyName (FLD_ENTRADA_ESTOQUE_VALORTOTAL).AsFloat := coEntradaEstoque.VALORTOTAL; ParambyName (FLD_ENTRADA_ESTOQUE_DEPOSITO).AsInteger := coEntradaEstoque.DEPOSITO.ID; ParambyName (FLD_ENTRADA_ESTOQUE_LOTE).AsInteger := coEntradaEstoque.LOTE; ParambyName (FLD_ENTRADA_ESTOQUE_LOTEVALIDADE).Asdatetime := coEntradaEstoque.LOTEVALIDADE; end; end; constructor TrepositorioEntEstoque.Create; begin inherited Create (TENTRADAESTOQUE, TBL_ENTRADA_ESTOQUE, FLD_ENTIDADE_ID, STR_ENTRADAESTOQUE); FRepositorioDeposito := TRepositorioDeposito.Create; FRepositorioProduto := TRepositorioProduto.Create; end; destructor TrepositorioEntEstoque.Destroy; begin FreeAndNil (FRepositorioDeposito); FreeAndNil (FRepositorioProduto); inherited; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PaxRegister.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PaxDllImport; interface uses {$I uses.def} TypInfo; type TRegisterNamespace = function (LevelId: Integer; const Name: String): Integer; TRegisterConstant = function(LevelId: Integer; const Name: String; const Value: Variant): Integer; TRegisterVariable = function(LevelId: Integer; const Name: String; TypeId: Integer; Address: Pointer): Integer; TRegisterHeader = function(LevelId: Integer; const Header: String; Address: Pointer; MethodIndex: Integer = 0; Visibility: Integer = 0): Integer; TRegisterProperty = function(LevelId: Integer; const Header: String): Integer; TRegisterClassType = function(LevelId: Integer; C: TClass; DoRegisterClass: Boolean = false): Integer; TRegisterClassReferenceType = function(LevelID: Integer; const TypeName, OriginalTypeName: String): Integer; TRegisterClassTypeField = function(TypeId: Integer; const Declaration: String): Integer; TRegisterRecordType = function(LevelId: Integer; const TypeName: String; IsPacked: Boolean = false): Integer; TRegisterRecordTypeField = function(TypeId: Integer; const Declaration: String): Integer; TRegisterVariantRecordTypeField = function(LevelId: Integer; const Declaration: String; VarCount: Int64): Integer; TRegisterEnumType = function(LevelId: Integer; const TypeName: String; TypeBaseId: Integer = 7): Integer; TRegisterEnumValue = function(EnumTypeId: Integer; const FieldName: String; const Value: Integer): Integer; TRegisterSubrangeType = function(LevelId: Integer; const TypeName: String; TypeBaseId: Integer; B1, B2: Integer): Integer; TRegisterArrayType = function(LevelId: Integer; const TypeName: String; RangeTypeId, ElemTypeId: Integer; IsPacked: Boolean = false): Integer; TRegisterDynamicArrayType = function(LevelId: Integer; const TypeName: String; ElemTypeId: Integer): Integer; TRegisterPointerType = function(LevelId: Integer; const TypeName: String; OriginTypeId: Integer; const OrginTypeName: String = ''): Integer; TRegisterSetType = function(LevelId: Integer; const TypeName: String; OriginTypeId: Integer): Integer; TRegisterProceduralType = function(LevelId: Integer; const TypeName: String; SubId: Integer): Integer; TRegisterEventType = function(LevelId: Integer; const TypeName: String; SubId: Integer): Integer; TRegisterShortStringType = function(LevelId: Integer; const TypeName: String; L: Integer): Integer; TRegisterInterfaceType = function(LevelId: Integer; const TypeName: String; const GUID: TGUID; const ParentName: String; const ParentGUID: TGUID): Integer; TRegisterRTTIType = function(LevelId: Integer; pti: PTypeInfo): Integer; TRegisterTypeAlias = function(LevelId:Integer; const TypeName: String; OriginTypeId: Integer): Integer; TRegisterProcRec = record RegisterNamespace: TRegisterNamespace; RegisterConstant: TRegisterConstant; RegisterVariable: TRegisterVariable; RegisterHeader: TRegisterHeader; RegisterProperty: TRegisterProperty; RegisterClassType: TRegisterClassType; RegisterClassTypeField: TRegisterClassTypeField; RegisterClassReferenceType: TRegisterClassReferenceType; RegisterRecordType: TRegisterRecordType; RegisterRecordTypeField: TRegisterRecordTypeField; RegisterVariantRecordTypeField: TRegisterVariantRecordTypeField; RegisterEnumType: TRegisterEnumType; RegisterEnumValue: TRegisterEnumValue; RegisterSubrangeType: TRegisterSubrangeType; RegisterArrayType: TRegisterArrayType; RegisterDynamicArrayType: TRegisterDynamicArrayType; RegisterPointerType: TRegisterPointerType; RegisterSetType: TRegisterSetType; RegisterProceduralType: TRegisterProceduralType; RegisterEventType: TRegisterEventType; RegisterShortStringType: TRegisterShortStringType; RegisterInterfaceType: TRegisterInterfaceType; RegisterRTTIType: TRegisterRTTIType; RegisterTypeAlias: TRegisterTypeAlias; end; TRegisterDllProc = procedure (R: TRegisterProcRec); implementation end.
unit DzNoteEditorReg; interface uses DesignEditors, DesignIntf; type TDzNoteEditorStringsEdit = class(TPropertyEditor) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; end; TDzNotepadPropDbClick = class(TDefaultEditor) public procedure EditProperty(const Prop: IProperty; var Continue: Boolean); override; end; procedure Register; implementation uses System.Classes, Data.DB, Vcl.Forms, System.SysUtils, UFrmNoteEditor, DzNotepad; procedure Register; begin RegisterComponents('Digao', [TDzNotepad]); RegisterPropertyEditor(TypeInfo(TStrings), nil, '', TDzNoteEditorStringsEdit); RegisterPropertyEditor(TypeInfo(TStrings), TDataSet, 'SQL', TDzNoteEditorStringsEdit); RegisterPropertyEditor(TypeInfo(TStrings), TDzNotepad, 'Lines', TDzNoteEditorStringsEdit); RegisterComponentEditor(TDzNotepad, TDzNotepadPropDbClick); end; // procedure TDzNoteEditorStringsEdit.Edit; var Form: TFrmNoteEditor; C: TPersistent; begin C := GetComponent(0); Form := TFrmNoteEditor.Create(Application); try Form.Design := Designer; Form.PStr := TStrings(GetOrdValue); Form.LbTitle.Caption := Format('%s.%s (%s)', [C.GetNamePath, GetName, C.ClassName]); Form.ShowModal; finally Form.Free; end; end; function TDzNoteEditorStringsEdit.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly]; end; function TDzNoteEditorStringsEdit.GetValue: string; var S: TStrings; X: Integer; begin S := TStrings(GetOrdValue); X := S.Count; if X = 0 then Result := '(Empty)' else if X = 1 then Result := '(1 line)' else Result := Format('(%d lines)', [X]); end; // procedure TDzNotepadPropDbClick.EditProperty(const Prop: IProperty; var Continue: Boolean); begin if Prop.GetName = 'Lines' then begin Prop.Edit; Continue := False; end; end; end.
////////////////////////////////////////////////////////////////////////// // This file is a part of NotLimited.Framework.Wpf NuGet package. // You are strongly discouraged from fiddling with it. // If you do, all hell will break loose and living will envy the dead. ////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; namespace NotLimited.Framework.Wpf { public class ObservableWrapper<T> : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged { private readonly Func<IEnumerable<T>> _collectionAccessor; public ObservableWrapper(Func<IEnumerable<T>> collectionAccessor) { _collectionAccessor = collectionAccessor; } public IEnumerator<T> GetEnumerator() { return _collectionAccessor().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public event NotifyCollectionChangedEventHandler CollectionChanged; public virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { var handler = CollectionChanged; if (handler != null) handler(this, e); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
unit Forms.Config; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvGlowButton, AdvEdit, Vcl.StdCtrls, AdvEdBtn, AdvDirectoryEdit; type TFrmConfig = class(TForm) btCancel: TAdvGlowButton; btOK: TAdvGlowButton; txtFolderName: TAdvDirectoryEdit; txtURI: TAdvEdit; private function GetURI: String; procedure SetURI(const Value: String); function GetFolderName: String; procedure SetFolderName(const Value: String); { Private declarations } public { Public declarations } property URI: String read GetURI write SetURI; property FolderName: String read GetFolderName write SetFolderName; end; var FrmConfig: TFrmConfig; implementation {$R *.dfm} uses System.IOUtils; { TFrmConfig } function TFrmConfig.GetFolderName: String; begin Result := TRIM( txtFolderName.Text ); // only return valid directory if not TDirectory.Exists(Result) then begin Result := ''; end; end; function TFrmConfig.GetURI: String; begin Result := TRIM( txtURI.Text ); end; procedure TFrmConfig.SetFolderName(const Value: String); begin if TDirectory.Exists(Value) then begin txtFolderName.Text := Value; end else begin txtFoldername.Text := ''; end; end; procedure TFrmConfig.SetURI(const Value: String); begin if Value <> '' then begin txtURI.Text := Value; end; end; end.
unit ProdutoDAO; interface uses Classes, DBXCommon, SqlExpr, Produto, SysUtils, FornecedorProduto, Generics.Collections, Fornecedor, Validade; type {$MethodInfo ON} TProdutoDAO = class(TPersistent) private FComm: TDBXCommand; procedure PrepareCommand; public function List: TDBXReader; function NextCodigo: string; function NextCodigoBarras: string; function Insert(produto: TProduto): Boolean; function Update(produto: TProduto): Boolean; function Delete(produto: TProduto): Boolean; function FindByCodigo(Codigo: string): TProduto; function ListFornecedoresByProduto(Codigo: string): TList<TFornecedorProduto>; function ListValidadesByProduto(Codigo: string): TList<TValidade>; function ListagemProdutos(CodigoTipoProduto, CodigoFornecedor: string; Estoque: Integer): TDBXReader; function ExisteCodigoBarras(CodigoBarras: string): Boolean; function ListProdutosPertoVencimento: TDBXReader; end; implementation uses uSCPrincipal, StringUtils, TipoProduto; const TABELA: String = 'PRODUTOS'; { TProdutoDAO } procedure TProdutoDAO.PrepareCommand; begin if not(Assigned(FComm)) then begin if not(SCPrincipal.ConnTopCommerce.Connected) then SCPrincipal.ConnTopCommerce.Open; FComm := SCPrincipal.ConnTopCommerce.DBXConnection.CreateCommand; FComm.CommandType := TDBXCommandTypes.DbxSQL; if not(FComm.IsPrepared) then FComm.Prepare; end; end; function TProdutoDAO.List: TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT P.CODIGO, P.DESCRICAO, P.CODIGO_TIPO_PRODUTO, T.DESCRICAO AS DESCRICAO_TIPO_PRODUTO, '+ ' P.PRECO_VENDA, P.ESTOQUE_MINIMO, P.CODIGO_BARRAS, E.QUANTIDADE, P.ENDERECO, '+ ' P.MARGEM_LUCRO, P.DESCONTO_MAXIMO_VALOR, P.DESCONTO_MAXIMO_PERCENTUAL '+ 'FROM PRODUTOS P '+ 'INNER JOIN TIPOS_PRODUTO T ON T.CODIGO = P.CODIGO_TIPO_PRODUTO '+ 'LEFT JOIN ESTOQUE E ON E.CODIGO_PRODUTO = P.CODIGO'; Result := FComm.ExecuteQuery; end; function TProdutoDAO.ListagemProdutos(CodigoTipoProduto, CodigoFornecedor: string; Estoque: Integer): TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT P.CODIGO, P.CODIGO_TIPO_PRODUTO, P.DESCRICAO, P.CODIGO_BARRAS, P.PRECO_VENDA, '+ 'T.DESCRICAO AS DESCRICAO_TIPO_PRODUTO, FP.PRECO_COMPRA, F.NOME AS NOME_FORNECEDOR '+ 'FROM PRODUTOS P '+ 'INNER JOIN TIPOS_PRODUTO T ON T.CODIGO = P.CODIGO_TIPO_PRODUTO '+ 'LEFT JOIN FORNECEDORES_PRODUTO FP ON FP.CODIGO_PRODUTO = P.CODIGO '+ 'LEFT JOIN FORNECEDORES F ON F.CODIGO = FP.CODIGO_FORNECEDOR '+ 'WHERE P.CODIGO IS NOT NULL '; if (CodigoTipoProduto <> '') then FComm.Text := FComm.Text + 'AND P.CODIGO_TIPO_PRODUTO = '''+CodigoTipoProduto+''''; if (CodigoFornecedor <> '') then FComm.Text := FComm.Text + 'AND FP.CODIGO_FORNECEDOR = '''+CodigoFornecedor+''''; case Estoque of 1: FComm.Text := FComm.Text + 'AND (SELECT QUANTIDADE FROM ESTOQUE E WHERE E.CODIGO_PRODUTO = P.CODIGO) > 0'; 2: FComm.Text := FComm.Text + 'AND (SELECT QUANTIDADE FROM ESTOQUE E WHERE E.CODIGO_PRODUTO = P.CODIGO) = 0'; end; Result := FComm.ExecuteQuery; end; function TProdutoDAO.ListFornecedoresByProduto(Codigo: string): TList<TFornecedorProduto>; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT P.*, F.NOME FROM FORNECEDORES_PRODUTO P '+ 'INNER JOIN FORNECEDORES F ON F.CODIGO = P.CODIGO_FORNECEDOR '+ 'WHERE P.CODIGO_PRODUTO = :CODIGO_PRODUTO'; query.ParamByName('CODIGO_PRODUTO').AsString := Codigo; query.Open; query.First; Result := TList<TFornecedorProduto>.Create; while not(query.Eof) do begin Result.Add(TFornecedorProduto.Create(TFornecedor.Create(query.FieldByName('CODIGO_FORNECEDOR').AsString, query.FieldByName('NOME').AsString, ''), query.FieldByName('PRECO_COMPRA').AsCurrency)); query.Next; end; finally query.Free; end; end; function TProdutoDAO.ListValidadesByProduto(Codigo: string): TList<TValidade>; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT * FROM VALIDADES '+ 'WHERE CODIGO_PRODUTO = :CODIGO_PRODUTO'; query.ParamByName('CODIGO_PRODUTO').AsString := Codigo; query.Open; query.First; Result := TList<TValidade>.Create; while not(query.Eof) do begin Result.Add(TValidade.Create(query.FieldByName('DATA').AsDateTime)); query.Next; end; finally query.Free; end; end; function TProdutoDAO.NextCodigo: string; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT MAX(CODIGO) AS MAX_CODIGO FROM ' + TABELA; query.Open; if query.FieldByName('max_codigo').IsNull then Result := StrZero(1, 6) else Result := StrZero(query.FieldByName('max_codigo').AsInteger + 1, 6); finally query.Free; end; end; function TProdutoDAO.NextCodigoBarras: string; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT MAX(CODIGO) AS MAX_CODIGO FROM ' + TABELA; query.Open; if query.FieldByName('max_codigo').IsNull then Result := StrZero(1, 20) else Result := StrZero(query.FieldByName('max_codigo').AsInteger + 1, 20); finally query.Free; end; end; function TProdutoDAO.Insert(produto: TProduto): Boolean; var query: TSQLQuery; Fornecedor: TFornecedorProduto; Validade: TValidade; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; try query.SQL.Text := 'INSERT INTO ' + TABELA +' (CODIGO, CODIGO_TIPO_PRODUTO, DESCRICAO, CODIGO_BARRAS, PRECO_VENDA, ESTOQUE_MINIMO, ENDERECO, MARGEM_LUCRO, DESCONTO_MAXIMO_VALOR, DESCONTO_MAXIMO_PERCENTUAL) '+ 'VALUES (:CODIGO, :CODIGO_TIPO_PRODUTO, :DESCRICAO, :CODIGO_BARRAS, :PRECO_VENDA, :ESTOQUE_MINIMO, :ENDERECO, :MARGEM_LUCRO, :DESCONTO_MAXIMO_VALOR, :DESCONTO_MAXIMO_PERCENTUAL)'; query.ParamByName('CODIGO').AsString := produto.Codigo; query.ParamByName('CODIGO_TIPO_PRODUTO').AsString := produto.TipoProduto.Codigo; query.ParamByName('DESCRICAO').AsString := produto.Descricao; query.ParamByName('CODIGO_BARRAS').AsString := produto.CodigoBarras; query.ParamByName('PRECO_VENDA').AsCurrency := produto.PrecoVenda; query.ParamByName('ESTOQUE_MINIMO').AsInteger := produto.EstoqueMinimo; query.ParamByName('ENDERECO').AsString := produto.Endereco; query.ParamByName('MARGEM_LUCRO').AsCurrency := produto.MargemLucro; query.ParamByName('DESCONTO_MAXIMO_VALOR').AsCurrency := produto.DescontoMaximoValor; query.ParamByName('DESCONTO_MAXIMO_PERCENTUAL').AsCurrency := produto.DescontoMaximoPercentual; query.ExecSQL; query.SQL.Text := 'INSERT INTO FORNECEDORES_PRODUTO (CODIGO_PRODUTO, CODIGO_FORNECEDOR, PRECO_COMPRA) '+ 'VALUES (:CODIGO_PRODUTO, :CODIGO_FORNECEDOR, :PRECO_COMPRA)'; for Fornecedor in produto.Fornecedores do begin query.ParamByName('CODIGO_PRODUTO').AsString := produto.Codigo; query.ParamByName('CODIGO_FORNECEDOR').AsString := Fornecedor.Fornecedor.Codigo; query.ParamByName('PRECO_COMPRA').AsCurrency := Fornecedor.PrecoCompra; query.ExecSQL; end; query.SQL.Text := 'INSERT INTO VALIDADES (CODIGO_PRODUTO, DATA) '+ 'VALUES (:CODIGO_PRODUTO, :DATA)'; for Validade in produto.Validades do begin query.ParamByName('CODIGO_PRODUTO').AsString := produto.Codigo; query.ParamByName('DATA').AsDateTime := Validade.Data; query.ExecSQL; end; Result := True; except Result := False; end; finally query.Free; end; end; function TProdutoDAO.Update(produto: TProduto): Boolean; var query: TSQLQuery; Fornecedor: TFornecedorProduto; Validade: TValidade; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'UPDATE ' + TABELA + ' SET '+ ' CODIGO_TIPO_PRODUTO = :CODIGO_TIPO_PRODUTO, '+ ' DESCRICAO = :DESCRICAO, '+ ' CODIGO_BARRAS = :CODIGO_BARRAS, '+ ' PRECO_VENDA = :PRECO_VENDA, '+ ' ESTOQUE_MINIMO = :ESTOQUE_MINIMO, '+ ' ENDERECO = :ENDERECO, '+ ' MARGEM_LUCRO = :MARGEM_LUCRO, '+ ' DESCONTO_MAXIMO_VALOR = :DESCONTO_MAXIMO_VALOR, '+ ' DESCONTO_MAXIMO_PERCENTUAL = :DESCONTO_MAXIMO_PERCENTUAL '+ 'WHERE CODIGO = :CODIGO '; query.ParamByName('CODIGO_TIPO_PRODUTO').AsString := produto.TipoProduto.Codigo; query.ParamByName('DESCRICAO').AsString := produto.Descricao; query.ParamByName('CODIGO_BARRAS').AsString := produto.CodigoBarras; query.ParamByName('PRECO_VENDA').AsCurrency := produto.PrecoVenda; query.ParamByName('ESTOQUE_MINIMO').AsInteger := produto.EstoqueMinimo; query.ParamByName('ENDERECO').AsString := produto.Endereco; query.ParamByName('MARGEM_LUCRO').AsCurrency := produto.MargemLucro; query.ParamByName('DESCONTO_MAXIMO_VALOR').AsCurrency := produto.DescontoMaximoValor; query.ParamByName('DESCONTO_MAXIMO_PERCENTUAL').AsCurrency := produto.DescontoMaximoPercentual; query.ParamByName('CODIGO').AsString := produto.Codigo; try query.ExecSQL; query.SQL.Text := 'DELETE FROM FORNECEDORES_PRODUTO WHERE CODIGO_PRODUTO = '''+produto.Codigo+''''; query.ExecSQL; query.SQL.Text := 'INSERT INTO FORNECEDORES_PRODUTO (CODIGO_PRODUTO, CODIGO_FORNECEDOR, PRECO_COMPRA) '+ 'VALUES (:CODIGO_PRODUTO, :CODIGO_FORNECEDOR, :PRECO_COMPRA)'; for Fornecedor in produto.Fornecedores do begin query.ParamByName('CODIGO_PRODUTO').AsString := produto.Codigo; query.ParamByName('CODIGO_FORNECEDOR').AsString := Fornecedor.Fornecedor.Codigo; query.ParamByName('PRECO_COMPRA').AsCurrency := Fornecedor.PrecoCompra; query.ExecSQL; end; query.SQL.Text := 'DELETE FROM VALIDADES WHERE CODIGO_PRODUTO = '''+produto.Codigo+''''; query.ExecSQL; query.SQL.Text := 'INSERT INTO VALIDADES (CODIGO_PRODUTO, DATA) '+ 'VALUES (:CODIGO_PRODUTO, :DATA)'; for Validade in produto.Validades do begin query.ParamByName('CODIGO_PRODUTO').AsString := produto.Codigo; query.ParamByName('DATA').AsDateTime := Validade.Data; query.ExecSQL; end; Result := True; except Result := False; end; finally query.Free; end; end; function TProdutoDAO.Delete(produto: TProduto): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'DELETE FROM ESTOQUE WHERE CODIGO_PRODUTO = '''+produto.Codigo+''''; query.ExecSQL; query.SQL.Text := 'DELETE FROM FORNECEDORES_PRODUTO WHERE CODIGO_PRODUTO = '''+produto.Codigo+''''; query.ExecSQL; query.SQL.Text := 'DELETE FROM VALIDADES WHERE CODIGO_PRODUTO = '''+produto.Codigo+''''; query.ExecSQL; query.SQL.Text := 'DELETE FROM ' + TABELA + ' WHERE CODIGO = '''+produto.Codigo+''''; query.ExecSQL; Result := True; except Result := False; end; finally query.Free; end; end; function TProdutoDAO.FindByCodigo(Codigo: string): TProduto; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT P.*, T.DESCRICAO AS DESCRICAO_TIPO_PRODUTO FROM PRODUTOS P '+ 'INNER JOIN TIPOS_PRODUTO T ON T.CODIGO = P.CODIGO_TIPO_PRODUTO '+ 'WHERE P.CODIGO = ''' + Codigo + ''''; query.Open; Result := TProduto.Create(query.FieldByName('CODIGO').AsString, TTipoProduto.Create(query.FieldByName('CODIGO_TIPO_PRODUTO').AsString, query.FieldByName('DESCRICAO_TIPO_PRODUTO').AsString), query.FieldByName('DESCRICAO').AsString, query.FieldByName('CODIGO_BARRAS').AsString, query.FieldByName('PRECO_VENDA').AsCurrency, query.FieldByName('ESTOQUE_MINIMO').AsInteger, nil, nil, query.FieldByName('ENDERECO').AsString, query.FieldByName('MARGEM_LUCRO').AsCurrency, query.FieldByName('DESCONTO_MAXIMO_VALOR').AsCurrency, query.FieldByName('DESCONTO_MAXIMO_PERCENTUAL').AsCurrency); finally query.Free; end; end; function TProdutoDAO.ExisteCodigoBarras(CodigoBarras: string): Boolean; var query: TSQLQuery; begin query := TSQLQuery.Create(nil); try query.SQLConnection := SCPrincipal.ConnTopCommerce; query.SQL.Text := 'SELECT COUNT(*) QTD FROM PRODUTOS WHERE CODIGO_BARRAS = :CODIGO_BARRAS'; query.ParamByName('CODIGO_BARRAS').AsString := CodigoBarras; query.Open; Result := query.FieldByName('QTD').AsInteger > 0; finally query.Free; end; end; function TProdutoDAO.ListProdutosPertoVencimento: TDBXReader; begin PrepareCommand; FComm.Text := 'SELECT V.CODIGO_PRODUTO, P.DESCRICAO, V.DATA '+ 'FROM VALIDADES V '+ 'INNER JOIN PRODUTOS P ON P.CODIGO = V.CODIGO_PRODUTO '+ 'INNER JOIN ESTOQUE E ON E.CODIGO_PRODUTO = V.CODIGO_PRODUTO '+ 'AND E.QUANTIDADE > 0 '+ 'WHERE DATEDIFF(DAY,GETDATE(),DATA) >= 0 AND '+ 'DATEDIFF(MONTH,GETDATE(),DATA) <= 5'; Result := FComm.ExecuteQuery; end; end.
unit uFrmEstimatedInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DB, ADODB, PowerADOQuery, DBCtrls, DateBox, Mask, SuperComboADO, ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, SuperEdit, SuperEditCurrency; type TFrmEstimatedInfo = class(TFrmParentAll) quUpEstimated: TPowerADOQuery; quUpEstimatedIDEstimated: TIntegerField; quUpEstimatedIDDeliverType: TIntegerField; quUpEstimatedDeliverDate: TDateTimeField; quUpEstimatedDeliverAddress: TStringField; quUpEstimatedDeliverOBS: TStringField; quUpEstimatedTotalDiscount: TBCDField; quUpEstimatedConfirmed: TBooleanField; pgInfo: TPageControl; tsDeliver: TTabSheet; Label4: TLabel; cmbDelType: TDBSuperComboADO; pnlConfirmDeliver: TPanel; Label6: TLabel; Label5: TLabel; Label28: TLabel; EditDelDate: TDBDateBox; EditDelAddress: TDBEdit; edtDelOBS: TDBEdit; dsUpEstimated: TDataSource; btnSave: TButton; tsPayments: TTabSheet; Label1: TLabel; Label2: TLabel; grdBrowse: TcxGrid; grdBrowseDB: TcxGridDBTableView; grdBrowseLevel: TcxGridLevel; dsUpPayment: TDataSource; quUpPayment: TADODataSet; quUpPaymentIDPaymentCondition: TIntegerField; quUpPaymentIDMeioPag: TIntegerField; quUpPaymentMeioPag: TStringField; quUpPaymentImageIndex: TIntegerField; quUpPaymentAmount: TBCDField; quUpPaymentOBS: TStringField; grdBrowseDBMeioPag: TcxGridDBColumn; grdBrowseDBImageIndex: TcxGridDBColumn; grdBrowseDBAmount: TcxGridDBColumn; grdBrowseDBOBS: TcxGridDBColumn; Label12: TLabel; cmbPayType: TSuperComboADO; lbObs: TLabel; edtObs: TEdit; lbAmount: TLabel; btnAdd: TSpeedButton; EditSalePrice: TSuperEditCurrency; btnDell: TSpeedButton; cmdInsertPayment: TADOCommand; lbDate: TLabel; dtPayment: TDateBox; quUpPaymentEstimetedDate: TDateTimeField; grdBrowseDBEstimetedDate: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure EditSalePriceClick(Sender: TObject); procedure EditSalePriceEnter(Sender: TObject); procedure EditSalePriceKeyPress(Sender: TObject; var Key: Char); procedure btnAddClick(Sender: TObject); procedure btnDellClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private FClose : Boolean; FOpenSale : Boolean; FIDEstimated : Integer; FIDPreSale : Integer; FBalance : Currency; FInvoiceTotal : Currency; procedure OpenEstimated; procedure CloseEstimated; procedure SaveEstimated; procedure OpenEstimatedPayment; procedure CloseEstimatedPayment; procedure RefreshEstimatedPayment; function ValidadeInfo : Boolean; function ValidatePayment : Boolean; procedure CalculateBalance; public function Start(IDEstimated : Integer) : Boolean; function StartPreSale(IDPreSale : Integer; InvoiceTotal : Currency) : Boolean; end; implementation uses uDM, uMsgBox, uMsgConstant, uCharFunctions, uNumericFunctions; {$R *.dfm} { TFrmEstimatedInfo } function TFrmEstimatedInfo.Start(IDEstimated: Integer): Boolean; begin FIDEstimated := IDEstimated; FOpenSale := False; OpenEstimated; RefreshEstimatedPayment; ShowModal; Result := FClose; end; procedure TFrmEstimatedInfo.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; CloseEstimated; CloseEstimatedPayment; end; procedure TFrmEstimatedInfo.CloseEstimated; begin with quUpEstimated do if Active then Close; end; procedure TFrmEstimatedInfo.OpenEstimated; begin with quUpEstimated do if not Active then begin Parameters.ParamByName('IDEstimated').Value := FIDEstimated; Open; end; end; procedure TFrmEstimatedInfo.SaveEstimated; begin with quUpEstimated do if Active then begin if not (State in dsEditModes) then Edit; quUpEstimatedConfirmed.AsBoolean := True; Post; end; end; procedure TFrmEstimatedInfo.btCloseClick(Sender: TObject); begin inherited; Close; FClose := False; end; procedure TFrmEstimatedInfo.btnSaveClick(Sender: TObject); begin inherited; if ValidadeInfo then begin if not FOpenSale then SaveEstimated; FClose := True; Close; end; end; function TFrmEstimatedInfo.ValidadeInfo: Boolean; begin Result := False; if not FOpenSale then begin if quUpEstimatedIDDeliverType.AsString = '' then begin MsgBox(MSG_INF_DELIVER_TYPE_EMPTY, vbCritical + vbOkOnly); if cmbDelType.CanFocus then cmbDelType.SetFocus; Exit; end; { if quUpEstimatedDeliverDate.AsString = '' then begin MsgBox(MSG_CRT_NO_DATE, vbCritical + vbOkOnly); if EditDelDate.CanFocus then EditDelDate.SetFocus; Exit; end; if quUpEstimatedDeliverDate.AsDateTime < Date then begin MsgBox(MSG_CRT_DELIVER_DATE_SMALER, vbCritical + vbOkOnly); if EditDelDate.CanFocus then EditDelDate.SetFocus; Exit; end; } if quUpEstimatedDeliverAddress.AsString = '' then begin MsgBox(MSG_INF_NOT_EMPTY_ADDRESS, vbCritical + vbOkOnly); if EditDelAddress.CanFocus then EditDelAddress.SetFocus; Exit; end; end; if (FBalance <> 0) then begin MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly); pgInfo.ActivePage := tsPayments; EditSalePrice.Text := FormatFloat(DM.FQtyDecimalFormat, FBalance); Exit; end; Result := True; end; procedure TFrmEstimatedInfo.CloseEstimatedPayment; begin with quUpPayment do if Active then Close; end; procedure TFrmEstimatedInfo.OpenEstimatedPayment; begin with quUpPayment do if not Active then begin Parameters.ParamByName('IDEstimated').Value := FIDEstimated; Parameters.ParamByName('IDPreSale').Value := FIDPreSale; Open; end; end; procedure TFrmEstimatedInfo.EditSalePriceClick(Sender: TObject); begin inherited; EditSalePrice.SelectAll; end; procedure TFrmEstimatedInfo.EditSalePriceEnter(Sender: TObject); begin inherited; EditSalePrice.SelectAll; end; procedure TFrmEstimatedInfo.EditSalePriceKeyPress(Sender: TObject; var Key: Char); begin inherited; Key := ValidatePositiveCurrency(Key); end; procedure TFrmEstimatedInfo.btnAddClick(Sender: TObject); begin inherited; if ValidatePayment then with cmdInsertPayment do begin Parameters.ParamByName('IDPaymentCondition').Value := DM.GetNextID('Sal_PaymentCondition.IDPaymentCondition'); if not FOpenSale then begin Parameters.ParamByName('IDEstimated').Value := FIDEstimated; Parameters.ParamByName('IDPreSale').Value := Null; end else begin Parameters.ParamByName('IDEstimated').Value := Null; Parameters.ParamByName('IDPreSale').Value := FIDPreSale; end; Parameters.ParamByName('IDMeioPag').Value := StrToInt(cmbPayType.LookUpValue); Parameters.ParamByName('Amount').Value := MyStrToMoney(EditSalePrice.Text); Parameters.ParamByName('OBS').Value := edtObs.Text; Parameters.ParamByName('EstimetedDate').Value := dtPayment.Date; Execute; RefreshEstimatedPayment; cmbPayType.Clear; cmbPayType.SetFocus; edtObs.Clear; end; end; function TFrmEstimatedInfo.ValidatePayment: Boolean; begin Result := False; if cmbPayType.LookUpValue = '' then begin cmbPayType.SetFocus; MsgBox(MSG_CRT_NO_PAYMENT_TYPE, vbOKOnly + vbCritical); Exit; end; if (MyStrToMoney(EditSalePrice.Text) = 0) then begin MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly); if EditSalePrice.CanFocus then EditSalePrice.SetFocus; Exit; end; if MyStrToMoney(EditSalePrice.Text) > FBalance then begin MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly); EditSalePrice.Text := FormatFloat(DM.FQtyDecimalFormat, FBalance); if EditSalePrice.CanFocus then EditSalePrice.SetFocus; Exit; end; Result := True; end; procedure TFrmEstimatedInfo.CalculateBalance; var dTotalItem, dTotalPayment : Currency; begin if FOpenSale then dTotalItem := FInvoiceTotal else begin with DM.quFreeSQL do try if Active then Close; SQL.Clear; SQL.Add('SELECT SUM(Round(SalePrice * Qty, 2, 1)) as Amount FROM EstimatedItem'); SQL.Add('WHERE IDEstimated = :IDEstimated'); Parameters.ParamByName('IDEstimated').Value := FIDEstimated; Open; dTotalItem := FieldByName('Amount').AsCurrency; finally Close; end; end; with DM.quFreeSQL do try if Active then Close; SQL.Clear; SQL.Add('SELECT SUM(Amount) as Amount FROM Sal_PaymentCondition'); if not FOpenSale then begin SQL.Add('WHERE IDEstimated = :IDEstimated'); Parameters.ParamByName('IDEstimated').Value := FIDEstimated; end else begin SQL.Add('WHERE IDPreSale = :IDPreSale'); Parameters.ParamByName('IDPreSale').Value := FIDPreSale; end; Open; dTotalPayment := FieldByName('Amount').AsCurrency; finally Close; end; FBalance := dTotalItem - dTotalPayment; EditSalePrice.Text := FormatFloat(DM.FQtyDecimalFormat, FBalance); end; procedure TFrmEstimatedInfo.btnDellClick(Sender: TObject); var ID : Integer; begin inherited; if quUpPayment.Active and (not quUpPayment.IsEmpty) then begin ID := quUpPaymentIDPaymentCondition.AsInteger; DM.RunSQL('DELETE Sal_PaymentCondition WHERE IDPaymentCondition = ' + IntToStr(ID)); RefreshEstimatedPayment; end; end; procedure TFrmEstimatedInfo.RefreshEstimatedPayment; begin CloseEstimatedPayment; OpenEstimatedPayment; CalculateBalance; end; function TFrmEstimatedInfo.StartPreSale(IDPreSale: Integer; InvoiceTotal : Currency): Boolean; begin FIDPreSale := IDPreSale; FInvoiceTotal := InvoiceTotal; tsDeliver.TabVisible := False; FOpenSale := True; OpenEstimated; RefreshEstimatedPayment; ShowModal; Result := FClose; end; procedure TFrmEstimatedInfo.FormShow(Sender: TObject); begin inherited; dtPayment.Date := Now; end; procedure TFrmEstimatedInfo.FormCreate(Sender: TObject); begin inherited; EditSalePrice.DisplayFormat := DM.FQtyDecimalFormat; end; end.
namespace proholz.xsdparser; interface type XsdAnnotationVisitor = public class(XsdAbstractElementVisitor) private // * // * The {@link XsdAnnotation} instance which owns this {@link XsdAnnotationVisitor} instance. This way this visitor // * instance can perform changes in the {@link XsdAnnotation} object. // // var owner: XsdAnnotation; public constructor(aowner: XsdAnnotation); method visit(element: XsdAppInfo); override; method visit(element: XsdDocumentation); override; end; implementation constructor XsdAnnotationVisitor(aowner: XsdAnnotation); begin inherited constructor(aowner); self.owner := aowner; end; method XsdAnnotationVisitor.visit(element: XsdAppInfo); begin inherited visit(element); owner.add(element); end; method XsdAnnotationVisitor.visit(element: XsdDocumentation); begin inherited visit(element); owner.add(element); end; end.
(* ----------------------------------------------------------------------------------------------------- Version : (288 - 279) Date : 01.17.2011 Author : Antonio Marcos Fernandes de Souza (amfsouza) Issue : ( Changes ) buttons add and remove are missing Solution: redraw screen. Version : (288 - 280) ----------------------------------------------------------------------------------------------------- Version : (287 - 275) Date : 11.24.2010 Author : Antonio Marcos Fernandes de Souza (amfsouza) Issue : ( Changes ) - To override description to Notes. Solution: override to Notes. Version : (287 - 276) ----------------------------------------------------------------------------------------------------- *) unit uFrmInventoryAdjust; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, Mask, SuperComboADO, DateBox, DB, ADODB, DBClient, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, mrBarCodeEdit; const INV_TYPE_NONE = 0; INV_TYPE_STORE_LOST = 1; INV_TYPE_STORE_USE = 2; INV_TYPE_ADJUST_INV = 3; type TFrmInventoryAdjust = class(TFrmParentAll) btnSave: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label6: TLabel; Label7: TLabel; scStore: TSuperComboADO; scUser: TSuperComboADO; btnSearchDesc: TBitBtn; dtMov: TDateBox; edtQty: TEdit; memOBS: TMemo; rgAdjustType: TRadioGroup; spAdjustInventory: TADOStoredProc; Label8: TLabel; Label9: TLabel; Label12: TLabel; btnAdd: TBitBtn; dsItems: TDataSource; cdsItems: TClientDataSet; cdsItemsIDUser: TIntegerField; cdsItemsUser: TStringField; cdsItemsIDStore: TIntegerField; cdsItemsStore: TStringField; cdsItemsIDMovType: TIntegerField; cdsItemsIDModel: TIntegerField; cdsItemsModel: TStringField; cdsItemsMovDate: TDateTimeField; cdsItemsQty: TFloatField; cdsItemsOBS: TStringField; grdItems: TcxGrid; grdItemsDB: TcxGridDBTableView; grdItemsLevel: TcxGridLevel; cdsItemsID: TIntegerField; grdItemsDBModel: TcxGridDBColumn; grdItemsDBMovDate: TcxGridDBColumn; grdItemsDBQty: TcxGridDBColumn; grdItemsDBOBS: TcxGridDBColumn; cdsItemsMovType: TStringField; grdItemsDBMovType: TcxGridDBColumn; quInventory: TADOQuery; quInventoryDataContagem: TDateTimeField; quInventoryCategory: TStringField; quInventoryQtyOnPreSale: TFloatField; quInventoryQtyOnHand: TFloatField; quInventoryQtyOnOrder: TFloatField; quInventoryQtyOnRepair: TFloatField; cdsItemsQtyOnHand: TFloatField; cdsItemsQtyReplace: TFloatField; Label11: TLabel; edtBarCode: TmrBarCodeEdit; Label10: TLabel; Label14: TLabel; edtQtyOnHand: TEdit; Label13: TLabel; scReason: TSuperComboADO; cdsItemsIDMovReason: TIntegerField; cdsItemsReason: TStringField; grdItemsDBReason: TcxGridDBColumn; scModel: TSuperComboADO; Label15: TLabel; rgMoveType: TRadioGroup; btnDel: TBitBtn; procedure btCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSearchDescClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure edtQtyKeyPress(Sender: TObject; var Key: Char); procedure btnSaveClick(Sender: TObject); procedure scModelSelectItem(Sender: TObject); procedure edtBarCodeAfterSearchBarcode(Sender: TObject); procedure quInventoryAfterOpen(DataSet: TDataSet); procedure edtBarCodeEnter(Sender: TObject); procedure edtBarCodeExit(Sender: TObject); procedure rgMoveTypeClick(Sender: TObject); procedure btnDelClick(Sender: TObject); private FInc : Integer; FAdjustType : Integer; function ValidateItem : Boolean; procedure InsertItem; procedure SaveItems; procedure RefreshInventory; procedure OpenInventory; procedure CloseInventory; public function Start(AdjustType:Integer) : Boolean; end; implementation uses uMsgBox, uDM, uMsgConstant, uDMGlobal, uFrmBarcodeSearch, uCharFunctions, Math, uSystemConst, uNumericFunctions; {$R *.dfm} { TFrmInventoryAdjust } function TFrmInventoryAdjust.Start(AdjustType: Integer): Boolean; begin FAdjustType := AdjustType; scUser.LookUpValue := IntToStr(DM.fUser.ID); scStore.LookUpValue := IntToStr(DM.fStore.ID); dtMov.Date := Now; edtQty.Text := '1'; FInc := 1; scReason.ShowBtnUpdate := (DM.fUser.IDUserType in [USER_TYPE_ADMINISTRATOR, USER_TYPE_MANAGER]); scReason.ShowBtnAddNew := (DM.fUser.IDUserType in [USER_TYPE_ADMINISTRATOR, USER_TYPE_MANAGER]); memOBS.Clear; cdsItems.Close; cdsItems.CreateDataSet; cdsItems.Open; Result := (ShowModal = mrOK); end; procedure TFrmInventoryAdjust.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmInventoryAdjust.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; CloseInventory; cdsItems.Close; Action := caFree; end; procedure TFrmInventoryAdjust.btnSearchDescClick(Sender: TObject); var R: integer; begin inherited; with TFrmBarcodeSearch.Create(Self) do begin R := Start; if R <> -1 then begin scModel.LookUpValue := IntToStr(R); scModelSelectItem(Self); end; end; end; procedure TFrmInventoryAdjust.FormCreate(Sender: TObject); begin inherited; DM.imgSmall.GetBitmap(BTN18_SEARCH, btnSearchDesc.Glyph); end; procedure TFrmInventoryAdjust.btnAddClick(Sender: TObject); begin inherited; if ValidateItem then InsertItem; end; procedure TFrmInventoryAdjust.InsertItem; var IDMovType : Integer; Qty, OnHand, QtyReplace : Double; begin Qty := StrToFloatDef(edtQty.Text,1); OnHand := 0; QtyReplace := 0; case rgMoveType.ItemIndex of 0 : IDMovType := 26; //Usado 1 : IDMovType := 6; //Roubado 2 : begin case rgAdjustType.ItemIndex of 0 : begin IDMovType := INV_MOVTYPE_PHYSICALINCREASE; end; 1 : begin IDMovType := INV_MOVTYPE_PHYSICALDECREASE; end; 2 : begin OnHand := quInventoryQtyOnHand.AsFloat; if (Qty - OnHand) > 0 then IDMovType := INV_MOVTYPE_PHYSICALINCREASE else IDMovType := INV_MOVTYPE_PHYSICALDECREASE; QtyReplace := Abs(Qty - OnHand); end; end; end; else IDMovType := 26; end; with cdsItems do if Active then begin Append; FieldByName('ID').AsInteger := FInc; FieldByName('IDUser').AsInteger := DM.fUser.ID; FieldByName('IDStore').AsInteger := DM.fStore.ID; FieldByName('IDMovType').AsInteger := IDMovType; FieldByName('IDModel').AsInteger := StrToInt(scModel.LookUpValue); FieldByName('User').AsString := scUser.Text; FieldByName('Store').AsString := scStore.Text; FieldByName('MovType').AsString := rgMoveType.Items.Strings[rgMoveType.ItemIndex]; FieldByName('Model').AsString := scModel.Text; FieldByName('MovDate').AsDateTime := dtMov.Date; FieldByName('Qty').AsFloat := Qty; FieldByName('QtyReplace').AsFloat := QtyReplace; FieldByName('QtyOnHand').AsFloat := OnHand; FieldByName('Obs').AsString := memOBS.Text; FieldByName('IDMovReason').AsInteger := StrToInt(scReason.LookUpValue); FieldByName('Reason').AsString := scReason.Text; Post; end; Inc(FInc); memOBS.Clear; edtQtyOnHand.Clear; edtBarCode.Clear; scModel.Text := ''; scModel.LookUpValue := ''; edtQty.Text := '1'; dtMov.Date := Now; edtBarCode.SetFocus; end; function TFrmInventoryAdjust.ValidateItem: Boolean; begin Result := False; if (scModel.LookUpValue = '') then begin scModel.SetFocus; MsgBox(MSG_CRT_NO_MODEL, vbOKOnly + vbCritical); Exit; end; if Trim(dtMov.Text) = '' then begin dtMov.SetFocus; MsgBox(MSG_CRT_NO_DATE, vbOKOnly + vbCritical); Exit; end; if Trim(edtQty.Text) = '' then begin edtQty.SetFocus; MsgBox(MSG_CRT_QTY_POSITIVE, vbOKOnly + vbCritical); Exit; end; if (rgMoveType.ItemIndex = -1) then begin MsgBox(MSG_CRT_NO_EMPTY_REASON, vbOKOnly + vbCritical); Exit; end; if (rgMoveType.ItemIndex = 2) then begin if (cdsItems.Active) and (cdsItems.Locate('IDModel', scModel.LookUpValue, [])) then begin memOBS.SetFocus; MsgBox(MSG_CRT_NO_DUPLICATE_MODEL, vbOKOnly + vbCritical); Exit; end; end; if Trim(scReason.Text) = '' then begin scReason.SetFocus; MsgBox(MSG_CRT_NO_EMPTY_REASON, vbOKOnly + vbCritical); Exit; end; Result := True; end; procedure TFrmInventoryAdjust.edtQtyKeyPress(Sender: TObject; var Key: Char); begin inherited; Key := ValidateDouble(Key); end; procedure TFrmInventoryAdjust.btnSaveClick(Sender: TObject); begin inherited; if not cdsItems.IsEmpty then begin SaveItems; Close; end; end; procedure TFrmInventoryAdjust.SaveItems; var Qty : Double; begin with cdsItems do try DisableControls; First; while not EOF do begin if FieldByName('QtyReplace').AsFloat = 0 then Qty := FieldByName('Qty').AsFloat else Qty := FieldByName('QtyReplace').AsFloat; spAdjustInventory.Parameters.ParamByName('@IDMovType').Value := FieldByName('IDMovType').AsInteger; spAdjustInventory.Parameters.ParamByName('@IDModel').Value := FieldByName('IDModel').AsInteger; spAdjustInventory.Parameters.ParamByName('@IDStore').Value := FieldByName('IDStore').AsInteger; spAdjustInventory.Parameters.ParamByName('@Qty').Value := Qty; spAdjustInventory.Parameters.ParamByName('@IDUser').Value := FieldByName('IDUser').AsInteger; spAdjustInventory.Parameters.ParamByName('@Date').Value := FieldByName('MovDate').AsDateTime; spAdjustInventory.Parameters.ParamByName('@Notes').Value := FieldByName('Obs').AsString; spAdjustInventory.Parameters.ParamByName('@IDMovReason').Value := FieldByName('IDMovReason').AsInteger; spAdjustInventory.ExecProc; Next; end; finally EnableControls; end; end; procedure TFrmInventoryAdjust.scModelSelectItem(Sender: TObject); begin inherited; //if rgMoveType.ItemIndex = 2 then RefreshInventory; end; procedure TFrmInventoryAdjust.CloseInventory; begin with quInventory do if Active then Close; end; procedure TFrmInventoryAdjust.OpenInventory; begin with quInventory do if not Active then begin Parameters.ParamByName('IDModel').Value := StrToInt(scModel.LookUpValue); Parameters.ParamByName('IDStore').Value := StrToInt(scStore.LookUpValue); Open; end; end; procedure TFrmInventoryAdjust.RefreshInventory; begin CloseInventory; OpenInventory; end; procedure TFrmInventoryAdjust.edtBarCodeAfterSearchBarcode( Sender: TObject); var iIDModel : integer; begin inherited; with edtBarcode do begin if SearchResult then begin iIDModel := GetFieldValue('IDModel'); scModel.LookUpValue := IntToStr(iIDModel); scModelSelectItem(Self); edtQty.SetFocus; end end; end; procedure TFrmInventoryAdjust.quInventoryAfterOpen(DataSet: TDataSet); begin inherited; edtQtyOnHand.Text := quInventoryQtyOnHand.AsString; end; procedure TFrmInventoryAdjust.edtBarCodeEnter(Sender: TObject); begin inherited; btnAdd.Default := False; end; procedure TFrmInventoryAdjust.edtBarCodeExit(Sender: TObject); begin inherited; btnAdd.Default := True; end; procedure TFrmInventoryAdjust.rgMoveTypeClick(Sender: TObject); begin inherited; rgAdjustType.Visible := (rgMoveType.ItemIndex = 2); if rgAdjustType.Visible then begin if scModel.LookUpValue <> '' then RefreshInventory; end else CloseInventory; end; procedure TFrmInventoryAdjust.btnDelClick(Sender: TObject); begin inherited; with cdsItems do if Active and (not IsEmpty) then begin Edit; Delete; end; end; end.
unit mymetafile; {$MODE Delphi} interface uses Windows, Classes, SysUtils, Graphics, dialogs; type TLRMetafile = class; { TMetafileCanvas } TLRMetafileCanvas = class(TCanvas) private FMetafile: TLRMetafile; public constructor Create(AMetafile: TLRMetafile; ReferenceDevice: HDC); constructor CreateWithComment(AMetafile: TLRMetafile; ReferenceDevice: HDC; const CreatedBy, Description: String); destructor Destroy; override; end; { TMetafile } TLRMetafile = class(TGraphic) private FImageHandle: HENHMETAFILE; FImageMMWidth: Integer; // are in 0.01 mm logical pixels FImageMMHeight: Integer; // are in 0.01 mm logical pixels FImagePxWidth: Integer; // in device pixels FImagePxHeight: Integer; // in device pixels procedure DeleteImage; function GetAuthor: String; function GetDescription: String; function GetEmpty: Boolean; override; function GetHandle: HENHMETAFILE; function GetMMHeight: Integer; function GetMMWidth: Integer; procedure SetHandle(Value: HENHMETAFILE); procedure SetMMHeight(Value: Integer); procedure SetMMWidth(Value: Integer); protected procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; function GetHeight: Integer; override; function GetWidth: Integer; override; procedure SetHeight(Value: Integer); override; procedure SetWidth(Value: Integer); override; public constructor Create; override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; procedure LoadFromFile(const Filename: String); override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToFile(const Filename: String); override; procedure SaveToStream(Stream: TStream); override; function ReleaseHandle: HENHMETAFILE; property Handle: HENHMETAFILE read GetHandle write SetHandle; property Empty: boolean read GetEmpty; property CreatedBy: String read GetAuthor; property Description: String read GetDescription; property MMWidth: Integer read GetMMWidth write SetMMWidth; property MMHeight: Integer read GetMMHeight write SetMMHeight; end; implementation { TLRMetafile } procedure TLRMetafile.DeleteImage; begin if FImageHandle <> 0 then DeleteEnhMetafile(FImageHandle); end; function TLRMetafile.GetAuthor: String; var NC: Integer; begin Result := ''; if FImageHandle = 0 then Exit; NC := GetEnhMetafileDescription(FImageHandle, 0, nil); if NC <= 0 then Exit else begin SetLength(Result, NC); GetEnhMetafileDescription(FImageHandle, NC, PChar(Result)); SetLength(Result, StrLen(PChar(Result)) ); end; end; function TLRMetafile.GetDescription: String; var NC: Integer; begin Result := ''; if FImageHandle = 0 then Exit; NC := GetEnhMetafileDescription(FImageHandle, 0, nil); if NC <= 0 then Exit else begin SetLength(Result, NC); GetEnhMetafileDescription(FImageHandle, NC, PChar(Result)); Delete(Result, 1, StrLen(PChar(Result))+1); SetLength(Result, StrLen(PChar(Result))); end; end; function TLRMetafile.GetEmpty: Boolean; begin Result := (FImageHandle = 0); end; function TLRMetafile.GetHandle: HENHMETAFILE; begin Result := FImageHandle end; function TLRMetafile.GetMMHeight: Integer; begin Result := FImageMMHeight; end; function TLRMetafile.GetMMWidth: Integer; begin Result := FImageMMWidth; end; procedure TLRMetafile.SetHandle(Value: HENHMETAFILE); var EnhHeader: TEnhMetaHeader; begin if (Value <> 0) and (GetEnhMetafileHeader(Value, sizeof(EnhHeader), @EnhHeader) = 0) then raise EInvalidImage.Create('Invalid Metafile');; if FImageHandle <> 0 then DeleteImage; FImageHandle := Value; FImagePxWidth := 0; FImagePxHeight := 0; FImageMMWidth := EnhHeader.rclFrame.Right - EnhHeader.rclFrame.Left; FImageMMHeight := EnhHeader.rclFrame.Bottom - EnhHeader.rclFrame.Top; end; procedure TLRMetafile.SetMMHeight(Value: Integer); begin FImagePxHeight := 0; if FImageMMHeight <> Value then FImageMMHeight := Value; end; procedure TLRMetafile.SetMMWidth(Value: Integer); begin FImagePxWidth := 0; if FImageMMWidth <> Value then FImageMMWidth := Value; end; procedure TLRMetafile.Draw(ACanvas: TCanvas; const Rect: TRect); var RT: TRect; begin if FImageHandle = 0 then Exit; RT := Rect; PlayEnhMetaFile(ACanvas.Handle, FImageHandle, RT); end; function TLRMetafile.GetHeight: Integer; var EMFHeader: TEnhMetaHeader; begin if FImageHandle = 0 then Result := FImagePxHeight else begin // convert 0.01mm units to device pixels GetEnhMetaFileHeader(FImageHandle, Sizeof(EMFHeader), @EMFHeader); Result := MulDiv(FImageMMHeight, // metafile height in 0.01mm EMFHeader.szlDevice.cy, // device height in pixels EMFHeader.szlMillimeters.cy*100); // device height in mm end end; function TLRMetafile.GetWidth: Integer; var EMFHeader: TEnhMetaHeader; begin if FImageHandle = 0 then Result := FImagePxWidth else begin // convert 0.01mm units to device pixels GetEnhMetaFileHeader(FImageHandle, Sizeof(EMFHeader), @EMFHeader); Result := MulDiv(FImageMMWidth, // metafile width in 0.01mm EMFHeader.szlDevice.cx, // device width in pixels EMFHeader.szlMillimeters.cx*100); // device width in 0.01mm end end; procedure TLRMetafile.SetHeight(Value: Integer); var EMFHeader: TEnhMetaHeader; begin if FImageHandle = 0 then FImagePxHeight := Value else begin // convert device pixels to 0.01mm units GetEnhMetaFileHeader(FImageHandle, Sizeof(EMFHeader), @EMFHeader); MMHeight := MulDiv(Value, // metafile height in pixels EMFHeader.szlMillimeters.cy*100, // device height in 0.01mm EMFHeader.szlDevice.cy); // device height in pixels end end; procedure TLRMetafile.SetWidth(Value: Integer); var EMFHeader: TEnhMetaHeader; begin if FImageHandle = 0 then FImagePxWidth := Value else begin // convert device pixels to 0.01mm units GetEnhMetaFileHeader(FImageHandle, Sizeof(EMFHeader), @EMFHeader); MMWidth := MulDiv(Value, // metafile width in pixels EMFHeader.szlMillimeters.cx*100, // device width in mm EMFHeader.szlDevice.cx); // device width in pixels end end; constructor TLRMetafile.Create; begin inherited Create; FImageHandle := 0; end; destructor TLRMetafile.Destroy; begin DeleteImage; inherited Destroy; end; procedure TLRMetafile.Assign(Source: TPersistent); begin if (Source = nil) or (Source is TLRMetafile) then begin if FImageHandle <> 0 then DeleteImage; if Assigned(Source) then begin FImageHandle := TLRMetafile(Source).Handle; FImageMMWidth := TLRMetafile(Source).MMWidth; FImageMMHeight := TLRMetafile(Source).MMHeight; FImagePxWidth := TLRMetafile(Source).Width; FImagePxHeight := TLRMetafile(Source).Height; end end else inherited Assign(Source); end; procedure TLRMetafile.Clear; begin DeleteImage; end; procedure TLRMetafile.LoadFromFile(const Filename: String); begin raise EComponentError.Create('Not Implemented'); end; procedure TLRMetafile.SaveToFile(const Filename: String); begin raise EComponentError.Create('Not Implemented'); end; procedure TLRMetafile.LoadFromStream(Stream: TStream); begin raise EComponentError.Create('Not Implemented'); end; procedure TLRMetafile.SaveToStream(Stream: TStream); begin raise EComponentError.Create('Not Implemented'); end; function TLRMetafile.ReleaseHandle: HENHMETAFILE; begin DeleteImage; Result := FImageHandle; FImageHandle := 0; end; { TLRMetafileCanvas } constructor TLRMetafileCanvas.Create(AMetafile: TLRMetafile; ReferenceDevice: HDC); begin CreateWithComment(AMetafile, ReferenceDevice, AMetafile.CreatedBy, AMetafile.Description); end; constructor TLRMetafileCanvas.CreateWithComment(AMetafile: TLRMetafile; ReferenceDevice: HDC; const CreatedBy, Description: String); var RefDC: HDC; R: TRect; Temp: HDC; P: PChar; begin inherited Create; FMetafile := AMetafile; if ReferenceDevice = 0 then RefDC := GetDC(0) else RefDC := ReferenceDevice; try if FMetafile.MMWidth = 0 then begin if FMetafile.Width = 0 then //if no width get RefDC height FMetafile.MMWidth := GetDeviceCaps(RefDC, HORZSIZE)*100 else FMetafile.MMWidth := MulDiv(FMetafile.Width, //else convert GetDeviceCaps(RefDC, HORZSIZE)*100, GetDeviceCaps(RefDC, HORZRES)); end; if FMetafile.MMHeight = 0 then begin if FMetafile.Height = 0 then //if no height get RefDC height FMetafile.MMHeight := GetDeviceCaps(RefDC, VERTSIZE)*100 else FMetafile.MMHeight := MulDiv(FMetafile.Height, //else convert GetDeviceCaps(RefDC, VERTSIZE)*100, GetDeviceCaps(RefDC, VERTRES)); end; R := Rect(0,0,FMetafile.MMWidth,FMetafile.MMHeight); //lpDescription stores both author and description if (Length(CreatedBy) > 0) or (Length(Description) > 0) then P := PChar(CreatedBy+#0+Description+#0#0) else P := nil; Temp := CreateEnhMetafile(RefDC, nil, @R, P); if Temp = 0 then raise EOutOfResources.Create('Out of Resources');; Handle := Temp; finally if ReferenceDevice = 0 then ReleaseDC(0, RefDC); end; end; destructor TLRMetafileCanvas.Destroy; begin FMetafile.Handle := CloseEnhMetafile(Handle); inherited Destroy; end; end.
(* * Copyright (c) 2004 * HouSisong@gmail.com * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * *) //------------------------------------------------------------------------------ // 具现化的IInterface类型的声明 // Create by HouSisong, 2004.09.04 //------------------------------------------------------------------------------ unit DGL_Interface; interface uses SysUtils; {$I DGLCfg.inc_h} type _ValueType = IInterface; const _NULL_Value:_ValueType=nil; {$define _DGL_NotHashFunction} {$define _DGL_Compare} function _IsEqual(const a,b :_ValueType):boolean;//{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b); function _IsLess(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则 {$I DGL.inc_h} type TIntfAlgorithms = _TAlgorithms; IIntfIterator = _IIterator; IIntfContainer = _IContainer; IIntfSerialContainer = _ISerialContainer; IIntfVector = _IVector; IIntfList = _IList; IIntfDeque = _IDeque; IIntfStack = _IStack; IIntfQueue = _IQueue; IIntfPriorityQueue = _IPriorityQueue; IIntfSet = _ISet; IIntfMultiSet = _IMultiSet; TIntfVector = _TVector; TIntfDeque = _TDeque; TIntfList = _TList; IIntfVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:) IIntfDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:) IIntfListIterator = _IListIterator; //速度比_IIterator稍快一点:) TIntfStack = _TStack; TIntfQueue = _TQueue; TIntfPriorityQueue = _TPriorityQueue; IIntfMapIterator = _IMapIterator; IIntfMap = _IMap; IIntfMultiMap = _IMultiMap; TIntfSet = _TSet; TIntfMultiSet = _TMultiSet; TIntfMap = _TMap; TIntfMultiMap = _TMultiMap; TIntfHashSet = _THashSet; TIntfHashMultiSet = _THashMultiSet; TIntfHashMap = _THashMap; TIntfHashMultiMap = _THashMultiMap; implementation uses HashFunctions; function _IsEqual(const a,b :_ValueType):boolean; begin result:=(a=b); end; function _IsLess(const a,b :_ValueType):boolean; begin result:=(Cardinal(a)<Cardinal(b)); end; {$I DGL.inc_pas} end.
{ Mandel / Julia Explorer Copyright 2000 Hugh Allen Hugh.Allen@oz.quest.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. } unit Fractal; interface uses Controls, Classes, Messages // , FastDIB ; type TFractal = class(TCustomControl) private //dib: TFastDIB; FIsJulia: Boolean; FCx, FCy: Real; FChanged: Boolean; FOnPaint: TNotifyEvent; FMaxIters:Integer; procedure SetCx(const Value: Real); procedure SetCy(const Value: Real); procedure SetIsJulia(const Value: Boolean); procedure SetMaxIters(const Value: Integer); function GetDIBPalette: PFColorTable; procedure Render(); procedure WMEraseBackGround(var message: TMessage); message WM_ERASEBKGND; protected procedure Paint(); override; procedure Resize(); override; public ViewLeft: real; ViewTop: real; ViewWidth: real; ViewHeight: real; constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure SetChanged(); function PixelToViewX(const x: integer): Real; function PixelToViewY(const y: integer): Real; function ViewToPixelX(const x: Real): integer; function ViewToPixelY(const y: Real): integer; property Canvas; property Palette: PFColorTable read GetDIBPalette; procedure MakePalette(Seed: Longint); published property IsJulia: Boolean read FIsJulia write SetIsJulia; property Cx: Real read FCx write SetCx; property Cy: Real read FCy write SetCy; property OnPaint: TNotifyEvent read FOnPaint write FOnPaint; property MaxIterations:Integer read FMaxIters write SetMaxIters default 200; property Align; property Anchors; property AutoSize; property BiDiMode; property BorderWidth; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; procedure Register(); // Complex Square Root procedure CplxSqrt(a, b: Real; out x, y: Real); implementation procedure Register(); begin RegisterComponents('Fractal', [TFractal]); end; procedure CplxSqrt(a, b: Real; out x, y: Real); var r: Real; begin r := sqrt(a*a + b*b); x := sqrt(0.5 * (r + a)); if b < 0.0 then y := -sqrt(0.5 * (r - a)) else y := sqrt(0.5 * (r - a)); end; { TFractal } constructor TFractal.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; dib := TFastDIB.Create; ViewLeft := -2.0; ViewTop := -2.0; {-1.2} ViewWidth := 4.0; {3.2} ViewHeight := 4.0; {2.4} dib.SetSize(2, 2, 8, 0); MakePalette(43); MaxIterations := 200; FChanged := True; FOnPaint := nil; end; destructor TFractal.Destroy; begin dib.Free; inherited; end; Procedure TFractal.MakePalette(Seed: Longint); var i : integer; r0, g0, b0: integer; r1, g1, b1: integer; s: real; begin RandSeed := Seed; r0 := 64; g0 := 64; b0 := 64; //r1 := 255; //g1 := 200; //b1 := 64; r1 := random(256); g1 := random(256); b1 := random(256); s := 0; for i := 0 to 255 do begin s := s + 0.02 + 0.03 * (255-i)/255; if s >= 1.0 then begin r0 := r1; g0 := g1; b0 := b1; repeat r1 := random(256); g1 := random(256); b1 := random(256); until abs(r1-r0) + abs(g1-g0) + abs(b1-b0) > 200; // fixme s := 0; end; dib.colors[i].r := trunc((1-s) * r0 + s * r1); dib.colors[i].g := trunc((1-s) * g0 + s * g1); dib.colors[i].b := trunc((1-s) * b0 + s * b1); end; dib.colors[255].r := 0;//255; dib.colors[255].g := 0;//255; dib.colors[255].b := 0;//255; end; procedure TFractal.Paint; begin if FChanged then Render; FChanged := False; dib.Draw(integer(Canvas.Handle), 0, 0); if Assigned(FOnPaint) then FOnPaint(Self); end; procedure TFractal.Render(); var x, y, i, j: integer; vx, vy: real; vx2: real; tx1, ty1: real; //tx2, ty2: real; lake: boolean; dx, dy: real; d, ld: real; label done; begin dib.SetSize(Width, Height, 8, 0); if IsJulia then begin // see if it has a lake vx := 0; vy := 0; for i := 1 to 500 do begin if (vx * vx + vy * vy) > 4.0 then break; vx2 := vx * vx - vy * vy + FCx; vy := vx * vy * 2.0 + FCy; vx := vx2; end; lake := i > 500; tx1 := vx; ty1 := vy; // trap point end else lake := false; for y := 0 to Height - 1 do for x := 0 to Width - 1 do begin j := 255; if IsJulia then begin vx := PixelToViewX(x); vy := PixelToViewY(y); ld := 0.0; for i := 0 to FMaxIters do begin if (vx * vx + vy * vy) > 4.0 then begin j := i; break; end; vx2 := vx * vx - vy * vy + FCx; vy := vx * vy * 2.0 + FCy; vx := vx2; if lake and (i > 9) then begin dx := vx - tx1; dy := vy - ty1; d := (dx * dx + dy * dy); if d < 0.001 then begin if d < ld then begin j := 255;//4 - 4*i; break; end; ld := d * 0.999; end else ld := ld * 0.99; end; end; end else // Mandelbrot begin vx := 0; vy := 0; FCx := PixelToViewX(x); FCy := PixelToViewY(y); // is point in main cardioid? // calculate stable fixed point tx1 := 1 - 4 * FCx; ty1 := 0 - 4 * FCy; CplxSqrt(tx1, ty1, tx1, ty1); //tx2 := 0.5 + 0.5 * tx1; this one not used because //ty2 := 0.0 + 0.5 * ty1; it's not a stable fixed-point //tx1 := 0.5 - 0.5 * tx1; //ty1 := 0.0 - 0.5 * ty1; tx1 := 1.0 - tx1; // doubling it //ty1 := - ty1; // not needed; it'll be squared d := (tx1 * tx1 + ty1 * ty1); // square of magnitude of derivative at fixed-point if d < 1.0 then begin j := 255; goto done; end; // is point in circle to left of main cardioid? dx := FCx + 1.0; d := dx * dx + FCy * FCy; if d < 0.0625 then begin j := 255; goto done; end; for i := 0 to FMaxIters do begin if (vx * vx + vy * vy) > 4.0 then begin j := i; break; end; vx2 := vx * vx - vy * vy + FCx; vy := vx * vy * 2.0 + FCy; vx := vx2; end; end; done: dib.Pixels8[y, x] := j; end; end; procedure TFractal.SetCx(const Value: real); begin FCx := Value; SetChanged(); end; procedure TFractal.SetCy(const Value: real); begin FCy := Value; SetChanged(); end; procedure TFractal.SetIsJulia(const Value: Boolean); begin FIsJulia := Value; FCx := 0.28; FCy := 0.00; SetChanged(); end; function TFractal.GetDIBPalette: PFColorTable; begin Result := dib.Colors; end; procedure TFractal.SetChanged(); begin FChanged := True; Invalidate; end; procedure TFractal.WMEraseBackGround(var message: TMessage); begin // don't do it. It makes them flicker! end; procedure TFractal.Resize; begin inherited; FChanged := True; end; function TFractal.PixelToViewX(const x: integer): Real; begin Result := ViewLeft + x * ViewWidth / Width; end; function TFractal.PixelToViewY(const y: integer): Real; begin Result := ViewTop + y * ViewHeight / Height; end; function TFractal.ViewToPixelX(const x: Real): integer; begin Result := round((x - ViewLeft) * Width / ViewWidth); end; function TFractal.ViewToPixelY(const y: Real): integer; begin Result := round((y - ViewTop) * Height / ViewHeight); end; procedure TFractal.SetMaxIters(const Value: Integer); begin FMaxIters := Value; SetChanged; end; end.
unit frm_ImportRecord; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, HCEmrView, HCEmrViewLite; type TfrmImportRecord = class(TForm) pnl1: TPanel; btnImportAll: TButton; btnImportSelect: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnImportAllClick(Sender: TObject); procedure btnImportSelectClick(Sender: TObject); private { Private declarations } FEmrViewLite: THCEmrView; FOnImportAsText: THCImportAsTextEvent; public { Public declarations } property EmrView: THCEmrView read FEmrViewLite; property OnImportAsText: THCImportAsTextEvent read FOnImportAsText write FOnImportAsText; end; var frmImportRecord: TfrmImportRecord; implementation {$R *.dfm} procedure TfrmImportRecord.btnImportAllClick(Sender: TObject); begin if Assigned(FOnImportAsText) then FOnImportAsText(FEmrViewLite.SaveToText); end; procedure TfrmImportRecord.btnImportSelectClick(Sender: TObject); begin if Assigned(FOnImportAsText) then FOnImportAsText(FEmrViewLite.ActiveSection.ActiveData.GetSelectText); end; procedure TfrmImportRecord.FormCreate(Sender: TObject); begin FEmrViewLite := THCEmrView.Create(Self); FEmrViewLite.Align := alClient; FEmrViewLite.Parent := Self; end; procedure TfrmImportRecord.FormDestroy(Sender: TObject); begin FreeAndNil(FEmrViewLite); end; end.
unit luaAssociativeArray; {$mode objfpc}{$H+} interface uses Lua, Classes, SysUtils, uAssociativeArray; procedure RegisterAssociativeArray(L : Plua_State); procedure RegisterExistingAssociativeArray(L : Plua_State; ar : TAssociativeArray; instanceName : AnsiString); implementation uses pLua, pLuaObject; var AssociativeArrayInfo : TLuaClassInfo; function newAssociativeArray(l : PLua_State; paramidxstart, paramcount : Integer; InstanceInfo : PLuaInstanceInfo) : TObject; begin result := TAssociativeArray.Create; end; function _indexAssociativeArray(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var vName : AnsiString; begin vName := plua_tostring(l, paramidxstart-1); plua_pushvariant(l, TAssociativeArray(target).Values[vName]); result := 1; end; function _newindexAssociativeArray(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer; var vName : AnsiString; vValue: Variant; begin vName := plua_tostring(l, paramidxstart-1); vValue := plua_tovariant(l, paramidxstart); TAssociativeArray(target).Values[vName] := vValue; result := 0; end; procedure RegisterAssociativeArray(L: Plua_State); begin plua_registerclass(L, AssociativeArrayInfo); end; procedure RegisterExistingAssociativeArray(L: Plua_State; ar: TAssociativeArray; instanceName: AnsiString); begin plua_registerExisting(l, instanceName, ar, @AssociativeArrayInfo, false); end; function setAssociativeArrayInfo : TLuaClassInfo; begin plua_initClassInfo(result); result.ClassName := 'TAssociativeArray'; result.New := @newAssociativeArray; result.UnhandledReader := @_indexAssociativeArray; result.UnhandledWriter := @_newindexAssociativeArray; end; initialization AssociativeArrayInfo := setAssociativeArrayInfo; end.
unit DPM.IDE.Details.Interfaces; interface uses Vcl.Themes, ToolsApi, Spring.Container, Spring.Collections, VSoft.Awaitable, DPM.Core.Types, DPM.Core.Configuration.Interfaces, DPM.Core.Package.Interfaces, DPM.Core.Options.Search, DPM.Core.Dependency.Interfaces, DPM.IDE.IconCache, DPM.IDE.Types; {$I ..\DPMIDE.inc} type //implemented by the EditorViewFrame //TODO : This is far to convoluted - we should not need to use options here. // we never actually want more than 1 searchresult so this needs to change to // just get the get the package metadata - which might actually come from the // package cache! IDetailsHost = interface ['{4FBB9E7E-886A-4B7D-89FF-FA5DBC9D93FD}'] function GetPackageReferences : IPackageReference; procedure BeginInstall(const projectCount : integer); procedure PackageInstalled; procedure EndInstall; end; IPackageDetailsView = interface ['{B4B48A9A-D04A-4316-B3FB-B03E4BD763F3}'] procedure Init(const container : TContainer; const iconCache : TDPMIconCache; const config : IConfiguration; const host : IDetailsHost; const projectOrGroup : IOTAProject); procedure SetPackage(const package : IPackageSearchResultItem; const preRelease : boolean; const fetchVersions : boolean = true); procedure SetPlatform(const platform : TDPMPlatform); procedure ViewClosing; procedure ProjectReloaded; procedure ThemeChanged(const StyleServices : TCustomStyleServices {$IFDEF THEMESERVICES}; const ideThemeSvc : IOTAIDEThemingServices{$ENDIF}); end; implementation end.
unit uFMXMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.Edit , uObserver , uTickTockTimer , uFactory; type TFormFMXMain = class(TForm, IVMObserver) EditClock: TEdit; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); public procedure UpdateObserver(const Sender: TObject); end; var FormFMXMain: TFormFMXMain; implementation {$R *.fmx} procedure TFormFMXMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin gClockTimer.Detach(self); end; procedure TFormFMXMain.FormCreate(Sender: TObject); begin gClockTimer.Attach(self); end; procedure TFormFMXMain.UpdateObserver(const Sender: TObject); begin if Sender is TClockTimer then EditClock.Text := (gClockTimer as TClockTimer).Time; end; initialization System.ReportMemoryLeaksOnShutdown := True; gClockTimer := TFactoryClass.CreateClockTimer; finalization gClockTimer := nil; end.
unit ibSHKeywordsManager; interface uses Classes, Graphics, SysUtils, Forms, Contnrs, SHDesignIntf, ibSHDesignIntf, ibSHConsts, pSHIntf, pSHHighlighter; type TibBTKeywordsManager = class(TSHComponent, IpSHKeywordsManager, IibSHKeywordsList) private FSubSQLDialect: TSQLSubDialect; FHighlighters: TObjectList; FDataTypeList: TStringList; FFunctionList: TStringList; FKeywordList: TStringList; FAllKeywordList: TStringList; protected function DataRootPath(ABranch: TGUID): string; {IpSHKeywordsManager} procedure InitializeKeywordLists(Sender: TObject; SubDialect: TSQLSubDialect; EnumerateKeywordsProc: TEnumerateKeywordsProc); procedure ChangeSubSQLDialectTo(ASubSQLDialect: TSQLSubDialect); procedure AddHighlighter(AHighlighter: TComponent); procedure RemoveHighlighter(AHighlighter: TComponent); function IsKeyword(AWord: string): Boolean; {IibSHKeywordsList} function GetFunctionList: TStrings; function GetDataTypeList: TStrings; function GetKeywordList: TStrings; function GetAllKeywordList: TStrings; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; class function GetClassIIDClassFnc: TGUID; override; end; implementation procedure Register; begin SHRegisterComponents([TibBTKeywordsManager]); end; { TibBTKeywordsManager } type TKWType = (kwtUnknown, kwtDataTypes, kwtInternalFunctions, kwtKeyWords); constructor TibBTKeywordsManager.Create(AOwner: TComponent); begin inherited; FDataTypeList := TStringList.Create; FFunctionList := TStringList.Create; FKeywordList := TStringList.Create; FAllKeywordList := TStringList.Create; FHighlighters := TObjectList.Create; FHighlighters.OwnsObjects := False; FSubSQLDialect := -1; end; destructor TibBTKeywordsManager.Destroy; begin FAllKeywordList.Free; FDataTypeList.Free; FFunctionList.Free; FKeywordList.Free; FHighlighters.Free; inherited; end; function TibBTKeywordsManager.DataRootPath(ABranch: TGUID): string; var vDataRootDirectory: ISHDataRootDirectory; begin Result := EmptyStr; if Supports(Designer.GetDemon(ABranch), ISHDataRootDirectory, vDataRootDirectory) then Result := vDataRootDirectory.DataRootDirectory; end; procedure TibBTKeywordsManager.InitializeKeywordLists(Sender: TObject; SubDialect: TSQLSubDialect; EnumerateKeywordsProc: TEnumerateKeywordsProc); var KWFileName: string; CurrentKW: TStringList; vBranch: TGUID; function LoadKWStrings(AKWType: TKWType): string; var I: Integer; SList: TStrings; begin Result := ''; case AKWType of kwtDataTypes: SList := FDataTypeList; kwtInternalFunctions: SList := FFunctionList; kwtKeyWords: SList := FKeywordList; else SList := nil; end; if Assigned(SList) then for I := 0 to SList.Count - 1 do Result := Result + ',' + SList.Names[I]; // SHint := SList.ValueFromIndex[I]; // FProposalKWItemList.Add(Format(sProposalTemplate, // [GetColorStringFor(AKWType), SType, SItem, SHint])); // FProposalKWInsertList.Add(SItem); end; procedure PharseList; var I: Integer; vPos: Integer; S: string; vKWType: TKWType; begin vKWType := kwtUnknown; for I := 0 to CurrentKW.Count - 1 do begin S := Trim(CurrentKW[I]); if (Length(S) > 0) and (S[1] <> ';') then if (S[1] = '[') and (S[Length(S)] = ']') then begin Delete(S, 1, 1); SetLength(S, Length(S)-1); if SameText(S, sSectionDataTypes) then vKWType := kwtDataTypes else if SameText(S, sSectionFunctions) then vKWType := kwtInternalFunctions else if SameText(S, sSectionKeyWords) then vKWType := kwtKeyWords else vKWType := kwtUnknown; end else begin case vKWType of kwtDataTypes: FDataTypeList.Add(S); kwtInternalFunctions: FFunctionList.Add(S); kwtKeyWords: FKeywordList.Add(S); end; S := Trim(CurrentKW.Names[I]); vPos := Pos(' ', S); if vPos > 0 then begin FAllKeywordList.Add(S); FAllKeywordList.Add(Copy(S, 1, vPos - 1)); FAllKeywordList.Add(Copy(S, vPos + 1, Length(S) - vPos)); end else FAllKeywordList.Add(S); end; end; end; begin if FSubSQLDialect <> SubDialect then begin FSubSQLDialect := SubDialect; case SubDialect of ibdInterBase6, ibdInterBase65: begin vBranch := IibSHBranch; KWFileName := InterBase6KWFileName; end; ibdInterBase7: begin vBranch := IibSHBranch; KWFileName := InterBase7KWFileName; end; ibdInterBase75: begin vBranch := IibSHBranch; KWFileName := InterBase75KWFileName; end; ibdFirebird1: begin vBranch := IfbSHBranch; KWFileName := Firebird1KWFileName; end; ibdFirebird15: begin vBranch := IfbSHBranch; KWFileName := Firebird15KWFileName; end; ibdFirebird20: begin vBranch := IfbSHBranch; KWFileName := Firebird20KWFileName; end; ibdInterBase2007: begin vBranch := IibSHBranch; KWFileName := InterBase2007KWFileName; end; ibdFirebird21: begin vBranch := IfbSHBranch; KWFileName := Firebird21KWFileName; end; else begin vBranch := IibSHBranch; KWFileName := ''; end; end; FDataTypeList.Clear; FFunctionList.Clear; FKeywordList.Clear; FAllKeywordList.Clear; FAllKeywordList.Sorted := False; CurrentKW := TStringList.Create; try // if FileExists(DataRootPath(vBranch) + InterBaseDefaultKWFileName) then //Дефолтный файл для Firebird грузится из "основной" ветки InterBase if FileExists(DataRootPath(IibSHBranch) + InterBaseDefaultKWFileName) then begin CurrentKW.LoadFromFile(DataRootPath(IibSHBranch) + InterBaseDefaultKWFileName); PharseList; end; if (Length(KWFileName) > 0) and FileExists(DataRootPath(vBranch) + KWFileName) then begin CurrentKW.LoadFromFile(DataRootPath(vBranch) + KWFileName); PharseList; end; finally CurrentKW.Free; end; FDataTypeList.Sort; FFunctionList.Sort; FKeywordList.Sort; FAllKeywordList.Sorted := True; EnumerateKeywordsProc(Ord(tkDatatype), LoadKWStrings(kwtDataTypes)); EnumerateKeywordsProc(Ord(tkFunction), LoadKWStrings(kwtInternalFunctions)); EnumerateKeywordsProc(Ord(tkKey), LoadKWStrings(kwtKeyWords)); end else begin EnumerateKeywordsProc(Ord(tkDatatype), LoadKWStrings(kwtDataTypes)); EnumerateKeywordsProc(Ord(tkFunction), LoadKWStrings(kwtInternalFunctions)); EnumerateKeywordsProc(Ord(tkKey), LoadKWStrings(kwtKeyWords)); end; end; procedure TibBTKeywordsManager.ChangeSubSQLDialectTo( ASubSQLDialect: TSQLSubDialect); var I: Integer; begin for I := 0 to FHighlighters.Count - 1 do if FHighlighters[I] is TpSHHighlighter then TpSHHighlighter(FHighlighters[I]).SQLSubDialect := ASubSQLDialect; end; procedure TibBTKeywordsManager.AddHighlighter(AHighlighter: TComponent); begin if (FHighlighters.IndexOf(AHighlighter) = -1) and (AHighlighter is TpSHHighlighter) then begin FHighlighters.Add(AHighlighter); AHighlighter.FreeNotification(Self); end; end; procedure TibBTKeywordsManager.RemoveHighlighter(AHighlighter: TComponent); var I: Integer; begin I := FHighlighters.IndexOf(AHighlighter); if I <> -1 then FHighlighters.Delete(I); end; function TibBTKeywordsManager.IsKeyword(AWord: string): Boolean; var Index:Integer; begin // Result := FAllKeywordList.IndexOf(AnsiUpperCase(AWord)) > -1; Result := FAllKeywordList.Find(AWord,Index) end; function TibBTKeywordsManager.GetFunctionList: TStrings; begin Result := FFunctionList; end; function TibBTKeywordsManager.GetDataTypeList: TStrings; begin Result := FDataTypeList; end; function TibBTKeywordsManager.GetKeywordList: TStrings; begin Result := FKeywordList; end; function TibBTKeywordsManager.GetAllKeywordList: TStrings; begin Result := FAllKeywordList; end; procedure TibBTKeywordsManager.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then RemoveHighlighter(AComponent); inherited Notification(AComponent, Operation); end; class function TibBTKeywordsManager.GetClassIIDClassFnc: TGUID; begin Result := IpSHKeywordsManager; end; initialization Register; end.