text
stringlengths
14
6.51M
unit uClassicStringConverter; {$I ..\Include\IntXLib.inc} interface uses uStringConverterBase, uIStringConverter, uDigitOpHelper, uIntXLibTypes; type /// <summary> /// Classic ToString converting algorithm using division (O[n^2]). /// </summary> TClassicStringConverter = class sealed(TStringConverterBase) public /// <summary> /// Creates new <see cref="ClassicStringConverter" /> instance. /// </summary> /// <param name="pow2StringConverter">Converter for pow2 case.</param> constructor Create(pow2StringConverter: IIStringConverter); /// <summary> /// Converts digits from internal representaion into given base. /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength">Big integer length.</param> /// <param name="numberBase">Base to use for output.</param> /// <param name="outputLength">Calculated output length (will be corrected inside).</param> /// <returns>Conversion result (later will be transformed to string).</returns> function ToString(digits: TIntXLibUInt32Array; mlength: UInt32; numberBase: UInt32; var outputLength: UInt32) : TIntXLibUInt32Array; override; end; implementation constructor TClassicStringConverter.Create(pow2StringConverter : IIStringConverter); begin inherited Create(pow2StringConverter); end; function TClassicStringConverter.ToString(digits: TIntXLibUInt32Array; mlength: UInt32; numberBase: UInt32; var outputLength: UInt32) : TIntXLibUInt32Array; var outputArray, digitsCopy: TIntXLibUInt32Array; outputIndex: UInt32; begin outputArray := inherited ToString(digits, mlength, numberBase, outputLength); // Maybe base method already converted this number if (outputArray <> Nil) then begin result := outputArray; Exit; end; // Create an output array for storing of number in other base SetLength(outputArray, outputLength + 1); // Make a copy of initial data SetLength(digitsCopy, mlength); Move(digits[0], digitsCopy[0], mlength * SizeOf(UInt32)); // Calculate output numbers by dividing outputIndex := 0; while (mlength) > 0 do begin mlength := TDigitOpHelper.DivMod(digitsCopy, mlength, numberBase, digitsCopy, outputArray[outputIndex]); Inc(outputIndex); end; outputLength := outputIndex; result := outputArray; end; end.
unit OTFEBestCrypt_U; // Description: Delphi BestCrypt Component // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, SysUtils, Windows, forms, controls, OTFE_U, OTFEConsts_U, OTFEBestCryptStructures_U; type TOTFEBestCrypt = class(TOTFE) private function RegistryOnlyVersion(): boolean; // INI file versions - don't call these! Used by the general routines function INIGetAutomountContainerNum(volumeFilename: string): integer; function INIGetDefaultDrive(volumeFilename: string): char; function INISetDefaultDriveAutomount(volumeFilename: string; driveLetter: ansichar; automount: boolean = FALSE): boolean; function INIDeleteDefaultDrive(volumeFilename: string): boolean; // Registry versions - don't call these! Used by the general routines function RegistryVolumeSetDefaultDrive(volumeFilename: string; driveLetter: ansichar): boolean; function RegistryVolumeSetAutomounted(volumeFilename: string; automount: boolean): boolean; function GetFilenameASCIIHash(volumeFilename: string): string; protected hBestCryptVxD : THandle; FPasswordPrompt: ansistring; kBestCryptINIFileAutoOpenKey: string; function LoadDLL(DLLFilename: string): THandle; function Connect(): boolean; function ConnectAttempt(driverName: string; var handle: THandle): boolean; function Disconnect(): boolean; procedure SetActive(AValue : Boolean); override; function GetDriveInfoOLD(driveLetter: ansichar; var volInfo: TDISKINFO_BUFFER_driverOLD): boolean; function GetDriveInfoNEW(driveLetter: ansichar; var volInfo: TDISKINFO_BUFFER_driverNEW): boolean; function MountDriverOLD(volumeFilename: ansistring; readonly: boolean; driveLetter: ansichar; diskSizeLow, diskSizeHigh: DWORD; readInHeader: THiddenSector): ansichar; function MountDriverNEW(volumeFilename: ansistring; readonly: boolean; driveLetter: ansichar; diskSizeLow, diskSizeHigh: DWORD; readInHeader: THiddenSector): ansichar; // This function is ported from the code segment (function) received by // email from Sergey Frolov (Jetico) function GetCurrentUserID(): DWORD; public function GetBestCryptFileHeader(volumeFilename: string; var header: THiddenSector): boolean; function VolumeIsAutomounted(volumeFilename: string): boolean; function GetDefaultDrive(volumeFilename: string): char; function SetDefaultDriveAutomount(volumeFilename: string; driveLetter: ansichar; automount: boolean = FALSE): boolean; function DeleteDefaultDrive(volumeFilename: string): boolean; function CreateKeyHandle(volumeFilename: ansistring; var keyHandle: KEY_HANDLE): boolean; procedure GetAllAlgorithmIDs(algIDs: TStrings); function GetAlgorithmName(algorithmID: DWORD): Ansistring; // just calls GetAlgorithmRegDetails function GetAlgorithmDriverName(algorithmID: DWORD): ansistring; // just calls GetAlgorithmRegDetails function GetAlgorithmKeyLength(algorithmID: DWORD): integer; // just calls GetAlgorithmRegDetails function GetAlgorithmVersion(algorithmID: DWORD): cardinal; function GetAlgorithmRegDetails(algorithmID: DWORD; var dispName: string; var driverName: string; var keyLen: integer): boolean; procedure GetAllKeyGenIDs(keyGenIDs: TStrings); function GetKeyGenName(keyGenID: DWORD): ansistring; // just calls GetKeyGenRegDetails function GetKeyGenDLLName(keyGenID: DWORD): string; // just calls GetKeyGenRegDetails function GetKeyGenVersion(keyGenID: DWORD): cardinal; function GetKeyGenRegDetails(keyGenID: DWORD; var dispName: string; var DLLName: string): boolean; property PasswordPrompt: ansistring read FPasswordPrompt write FPasswordPrompt; constructor Create(AOwner : TComponent); override; destructor Destroy; override; // Determine if the specified volume was previously mounted, and then only // "half dismounted" (i.e. a dismount was forced, even though the drive was // in use at the time) function VolumeInternallyMounted(volumeFilename: string): ansichar; // Return a list of drive letters for all drives the BestCrypt driver // *claims* are mounted; i.e. including drives that have been // "half dismounted" (i.e. a dismount was forced, even though the drive was // in use at the time) function InternalDrivesMounted(): ansistring; // TOTFE functions... function Title(): string; overload; override; function Version(): cardinal; override; function VersionStr(): string; override; function Mount(volumeFilename: ansistring; readonly: boolean = FALSE): Ansichar; overload; override; function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; overload; override; function MountDevices(): Ansistring; override; function CanMountDevice(): boolean; override; function Dismount(driveLetter: Ansichar; emergency: boolean = FALSE): boolean; overload; override; function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; override; function DrivesMounted(): ansistring; override; function GetVolFileForDrive(driveLetter: Ansichar): string; override; function GetDriveForVolFile(volumeFilename: string): Ansichar; override; function IsEncryptedVolFile(volumeFilename: string): boolean; override; function GetMainExe(): string; override; function GetVolumeInfo(volumeFilename: ansistring; var info: TBCDiskInfo): boolean; overload; function GetVolumeInfo(driveLetter: Ansichar; var info: TBCDiskInfo): boolean; overload; end; procedure Register; type // Function declarations for DLL functions TBCGetNameAndVersion = function(Name: PAnsiChar; // module name nameSize: UINT; // size of Name string in bytes Major: pDword; // module’s major version number Minor: pDword // module’s minor version number ): boolean; stdcall; TBCCreateKeyHandle = function(AlgServiceName: PAnsiChar; // what Encryption Algorithm will use the encryption key AlgId: DWORD; // Encryption Algorithm Identificator AlgKeyLength: DWORD; // encryption key length for the Encryption Algorithm Text: PAnsiChar; // Any information text (optional parameter) Caption: PAnsiChar; // Caption of the "get password" dialog window (optional parameter) CreateFlag: DWORD; // whether to create new key or open existing vDataBlock: ppByte; // block of data that is stored inside file-container in encrypted form DataSize: pDWORD; // size of the block of data KeyHandle: pDWORD; // returned Key Handle ErrorCode: pDWORD; // if the function returns FALSE, look at the Error code hWndParent: HWND // parent Window for any dialogs drawn by the DLL (optional parameter, may be NULL)) ): boolean; stdcall; TBCFreeDataBlock = function(vDataBlock: ppByte): DWORD; stdcall; TBCFreeKeyHandle = function(AlgServiceName: PAnsiChar; KeyHandle: DWORD ): DWORD; stdcall; implementation uses ShellAPI, Messages, dialogs, Registry, RegStr, OTFEBestCryptGetDriveLetter_U, INIFiles, SDUGeneral, HashValue_U, HashAlg_U, HashAlgSHA1_U, OTFEBestCryptBytesToString_U, math; // required for "power(...)" function const CRLF = #10+#13; procedure Register; begin RegisterComponents('OTFE', [TOTFEBestCrypt]); end; constructor TOTFEBestCrypt.Create(AOwner : TComponent); const MAX_USERNAME_LENGTH = 256; var usernameLength: cardinal; arrUserName: array [1..MAX_USERNAME_LENGTH] of char; begin inherited create(AOwner); FPasswordPrompt := 'Enter password'; kBestCryptINIFileAutoOpenKey := 'AutoOpen'; usernameLength := MAX_USERNAME_LENGTH; GetUserName(@arrUserName, usernameLength); if usernameLength>0 then begin kBestCryptINIFileAutoOpenKey := kBestCryptINIFileAutoOpenKey + ' ' + copy(arrUserName, 1, usernameLength) end; end; destructor TOTFEBestCrypt.Destroy; begin if FActive then CloseHandle(hBestCryptVxD); inherited Destroy; end; function TOTFEBestCrypt.Connect(): boolean; var attemptOK: boolean; begin Result := Active; FLastErrCode:= OTFE_ERR_SUCCESS; if not(Active) then begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin // Windows NT/2000/XP driver if Win32MajorVersion>=5 then begin // Windows 2000/XP driver attemptOK := ConnectAttempt(BESTCRYPT_2KXP_DRIVER, hBestCryptVxD); // Previous versions don't have a specific name for Windows 2000/XP // - in which case, fall back to the NT name if (not(attemptOK)) then begin attemptOK := ConnectAttempt(BESTCRYPT_NT_DRIVER, hBestCryptVxD); end; end else begin // Windows NT driver attemptOK := ConnectAttempt(BESTCRYPT_NT_DRIVER, hBestCryptVxD); end; end else begin // Windows 95/98 attemptOK := ConnectAttempt(BESTCRYPT_9598_DRIVER, hBestCryptVxD); end; if not(attemptOK) then begin FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; raise EBestCryptVxdNotFound.Create('BestCrypt device driver not found'); end; Result := attemptOK; end; end; // driverName - the name of the driver to attempt a connectoin to // handle - if successful, this will be set to the handle // Returns TRUE/FALSE on success/failure function TOTFEBestCrypt.ConnectAttempt(driverName: string; var handle: THandle): boolean; begin handle:= INVALID_HANDLE_VALUE; handle := CreateFile(PChar(driverName), GENERIC_READ OR GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Result := (handle <> INVALID_HANDLE_VALUE); end; function TOTFEBestCrypt.Title(): string; begin Result := 'BestCrypt'; end; function TOTFEBestCrypt.Version(): cardinal; var dwBytesReturned : DWORD; query: TVERSION_BUFFER; begin CheckActive(); Result := $FFFFFFFF; query.Signature := INPUT_SIGNATURE; DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_GET_VERSION_INFO, @query, sizeof(query), @query, sizeof(query), dwBytesReturned, nil); LastErrorCode := query.status; if query.signature<>OUTPUT_SIGNATURE then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end; if query.status=0 then begin Result := (query.Major_version * $100) + query.Minor_version; end; end; function TOTFEBestCrypt.DrivesMounted(): ansistring; var retVal: ansistring; i: integer; logicalDrives: DWORD; internalMountedDrvs: ansistring; currDrv: integer; begin retVal := ''; internalMountedDrvs:= InternalDrivesMounted(); // logicalDrivesAvailable is required as BestCrypt will quite happily claim // that volumes that have been half unmounted (e.g. forced dismount while // the volume was still in use) are still mounted. logicalDrives := GetLogicalDrives(); for i:=1 to length(internalMountedDrvs) do begin currDrv := (ord(internalMountedDrvs[i]))-(ord('A')); if ((logicalDrives AND (trunc(power(2, currDrv))))>0) then begin retVal:= retVal + internalMountedDrvs[i]; end; end; Result := retVal; end; function TOTFEBestCrypt.InternalDrivesMounted(): ansistring; var dwBytesReturned : DWORD; queryOLD: TGETMASK_BUFFER_driverOLD; queryNEW: TGETMASK_BUFFER_driverNEW; retVal: ansistring; i: integer; mask: DWORD; maskFromQuery: DWORD; signatureFromQuery: Ansistring; statusFromQuery: UCHAR; begin CheckActive(); if (Version() < DRIVER_VERSION_GETMASK_NEW) then begin // HANDLE FOR v2 DRIVERS... queryOLD.Signature := INPUT_SIGNATURE; queryOLD.status := 0; queryOLD.Mask := 0; DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_GET_BCDISK_MASK, @queryOLD, sizeof(queryOLD), @queryOLD, sizeof(queryOLD), dwBytesReturned, nil); maskFromQuery:= queryOLD.mask; signatureFromQuery:= queryOLD.signature; statusFromQuery:= queryOLD.status; end else begin // HANDLE FOR v3 DRIVERS... queryNEW.Signature := INPUT_SIGNATURE; queryNEW.status := 0; queryNEW.Mask := 0; DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_GET_BCDISK_MASK, @queryNEW, sizeof(queryNEW), @queryNEW, sizeof(queryNEW), dwBytesReturned, nil); maskFromQuery:= queryNEW.mask; signatureFromQuery:= queryNEW.signature; statusFromQuery:= queryNEW.status; end; LastErrorCode := statusFromQuery; if signatureFromQuery<>OUTPUT_SIGNATURE then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end; retVal := ''; mask := 1; for i:=0 to 31 do begin if ((maskFromQuery AND mask)>0) then begin retVal := retVal + AnsiChar(ord('A')+i); end; mask := mask * 2; end; // We don't need to sort retVal into alphabetical order, as it will be anyway // as it's already sorted Result := retVal; end; function TOTFEBestCrypt.Disconnect(): boolean; begin FLastErrCode:= OTFE_ERR_SUCCESS; if Active then begin CloseHandle(hBestCryptVxD); end; Result := TRUE; end; procedure TOTFEBestCrypt.SetActive(AValue : Boolean); var allOK: boolean; begin FLastErrCode:= OTFE_ERR_SUCCESS; allOK := FALSE; if AValue <> Active then begin if AValue then begin allOK := Connect(); end else begin allOK := Disconnect(); end; end; if allOK then begin inherited; end; end; function TOTFEBestCrypt.GetDriveInfoOLD(driveLetter: ansichar; var volInfo: TDISKINFO_BUFFER_driverOLD): boolean; var dwBytesReturned : DWORD; query: TDISKINFO_BUFFER_driverOLD; begin CheckActive(); query.Signature := INPUT_SIGNATURE; query.diskNumber := ord(upcase(driveLetter))-ord('A'); query.process := GetCurrentProcessID(); query.thread := GetCurrentThreadID(); DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_GET_BCDISK_INFO, @query, sizeof(query), @query, sizeof(query), dwBytesReturned, nil); if (query.signature<>OUTPUT_SIGNATURE) then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end else if (query.status<>BCSTATUS_SUCCESS) then begin LastErrorCode := OTFE_ERR_INVALID_DRIVE; end else begin LastErrorCode := OTFE_ERR_SUCCESS; end; volInfo := query; Result := (LastErrorCode = OTFE_ERR_SUCCESS); end; function TOTFEBestCrypt.GetDriveInfoNEW(driveLetter: ansichar; var volInfo: TDISKINFO_BUFFER_driverNEW): boolean; var dwBytesReturned : DWORD; query: TDISKINFO_BUFFER_driverNEW; begin CheckActive(); query.Signature := INPUT_SIGNATURE; query.diskNumber := ord(upcase(driveLetter))-ord('A'); query.process := GetCurrentProcessID(); query.thread := GetCurrentThreadID(); DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_GET_BCDISK_INFO, @query, sizeof(query), @query, sizeof(query), dwBytesReturned, nil); if (query.signature<>OUTPUT_SIGNATURE) then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end else if (query.status<>BCSTATUS_SUCCESS) then begin LastErrorCode := OTFE_ERR_INVALID_DRIVE; end else begin LastErrorCode := OTFE_ERR_SUCCESS; end; volInfo := query; Result := (LastErrorCode = OTFE_ERR_SUCCESS); end; function TOTFEBestCrypt.Dismount(driveLetter: ansichar; emergency: boolean = FALSE): boolean; var dwBytesReturned : DWORD; query: TDISCONNECT_BUFFER; NTDriveHandle: THandle; NTDriveStr: string; NTOKToDismount: boolean; begin CheckActive(); driveLetter := upcase(driveLetter); query.Signature := INPUT_SIGNATURE; query.diskNumber := ord(driveLetter)-ord('A'); query.fulldismounted := TRUE; // set to 1 query.status := BCSTATUS_SUCCESS; query.dummy[1] := $00; query.dummy[2] := $00; query.dummy[3] := $00; query.dummy2[1] := $00; query.dummy2[2] := $00; query.dummy2[3] := $00; // query.dummy3[1] := $00; // query.dummy3[2] := $00; // query.dummy3[3] := $00; // If running under NT if Win32Platform = VER_PLATFORM_WIN32_NT then begin // try and lock the drive NTDriveStr := '\\.\'+upcase(driveLetter)+':'; NTDriveHandle := CreateFile(PChar(NTDriveStr), (GENERIC_READ or GENERIC_WRITE), (FILE_SHARE_READ or FILE_SHARE_WRITE), nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); try FlushFileBuffers(NTDriveHandle); NTOKToDismount := DeviceIoControl(NTDriveHandle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, dwBytesReturned, nil); try DeviceIoControl(NTDriveHandle, FSCTL_DISMOUNT_VOLUME, nil, 0, nil, 0, dwBytesReturned, nil); finally DeviceIoControl(NTDriveHandle, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0, dwBytesReturned, nil); end; finally CloseHandle(NTDriveHandle); end; if (NTOKToDismount) then begin // We can do a straight dismount query.fulldismounted := TRUE; // set to 1 end else if (not(emergency)) then begin // Files open on the volume, and no emergency; abort dismount Result := FALSE; exit; end else begin // Files open on the volume, but it's an emergency; perform dismount, // but not full dismount query.fulldismounted := FALSE; // set to 1 end; end else begin // Under 9x/Me, we just do a full dismount query.fulldismounted := TRUE; // set to 1 end; DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_DISCONNECT_BCDISK, @query, sizeof(query), @query, sizeof(query), dwBytesReturned, nil); LastErrorCode := query.status; if query.signature<>OUTPUT_SIGNATURE then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end; SDUPause(500); Result := (query.status=BCSTATUS_SUCCESS); if not(Result) then begin FLastErrCode:= OTFE_ERR_DISMOUNT_FAILURE; end else begin BroadcastDriveChangeMessage(FALSE, driveLetter); end; end; function TOTFEBestCrypt.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; begin CheckActive(); Result := Dismount(GetDriveForVolFile(volumeFilename), emergency); end; function TOTFEBestCrypt.IsEncryptedVolFile(volumeFilename: string): boolean; var readInHeader: THiddenSector; begin CheckActive(); Result := FALSE; if GetBestCryptFileHeader(volumeFilename, readInHeader) then begin // Check the OEMid in the Bootrecord to see if this is a BestCrypt volume // file. // Note that this probably won't work if the user has change the boot record // OEM ID on their BestCrypt drive! Result := (readInHeader.BootRecord.OEMid = BESTCRYPT_VOLUME_DESCRIPTOR); end; end; function TOTFEBestCrypt.GetBestCryptFileHeader(volumeFilename: string; var header: THiddenSector): boolean; var testFile: TFileStream; begin Result := FALSE; try testFile := TFileStream.Create(volumeFilename, fmOpenRead OR fmShareDenyNone); try testFile.Read(header, sizeof(header)); Result := TRUE; finally testFile.Free(); end; except // Nothing - Result already = FALSE end; end; function TOTFEBestCrypt.GetVolFileForDrive(driveLetter: ansichar): string; var queryOLD: TDISKINFO_BUFFER_driverOLD; queryNEW: TDISKINFO_BUFFER_driverNEW; filename: string; begin CheckActive(); filename := ''; if (Version() < DRIVER_VERSION_DISKINFO_NEW) then begin if GetDriveInfoOLD(driveLetter, queryOLD) then begin // Start copying from the 2nd char to avoid the extra "\" at the start // Only copy up to the #0, i.e. only the number of chars 2 less than the // #0's pos filename := SDUConvertSFNtoLFN(copy(queryOLD.filename, 2, (pos(#0, queryOLD.filename)-2))); end; end else begin if GetDriveInfoNEW(driveLetter, queryNEW) then begin // Start copying from the 2nd char to avoid the extra "\" at the start // Only copy up to the #0, i.e. only the number of chars 2 less than the // #0's pos filename := SDUConvertSFNtoLFN(copy(queryNEW.filename, 2, (pos(#0, queryNEW.filename)-2))); end; end; Result := filename; end; function TOTFEBestCrypt.GetDriveForVolFile(volumeFilename: string): Ansichar; var i: integer; mountedDrives: ansistring; queryOLD: TDISKINFO_BUFFER_driverOLD; queryNEW: TDISKINFO_BUFFER_driverNEW; begin mountedDrives := DrivesMounted(); Result := #0; volumeFilename := uppercase(volumeFilename); for i:=1 to length(mountedDrives) do begin if uppercase(GetVolFileForDrive(mountedDrives[i]))=volumeFilename then begin if (Version() < DRIVER_VERSION_DISKINFO_NEW) then begin // HANDLE FOR v2 DRIVERS... if GetDriveInfoOLD(mountedDrives[i], queryOLD) then begin Result := AnsiChar(ord('A')+queryOLD.diskNumber); break; end; end else begin // HANDLE FOR v3 DRIVERS... if GetDriveInfoNEW(mountedDrives[i], queryNEW) then begin Result := AnsiChar(ord('A')+queryNEW.diskNumber); break; end; end; end; end; end; function TOTFEBestCrypt.GetAlgorithmName(algorithmID: DWORD): Ansistring; var dispName: string; driverName: string; keyLen: integer; begin Result := ''; if GetAlgorithmRegDetails(algorithmID, dispName, driverName, keyLen) then begin Result := dispName; { TODO 1 -otdk -cerror checking : check ansi } end; end; function TOTFEBestCrypt.GetAlgorithmDriverName(algorithmID: DWORD): ansistring; var dispName: string; driverName: string; keyLen: integer; begin Result := ''; if GetAlgorithmRegDetails(algorithmID, dispName, driverName, keyLen) then begin Result := driverName; { TODO 1 -otdk -cerror checking : check ansi } end; end; function TOTFEBestCrypt.GetAlgorithmKeyLength(algorithmID: DWORD): integer; var dispName: string; driverNAme: string; keyLen: integer; begin Result := -1; if GetAlgorithmRegDetails(algorithmID, dispName, driverName, keyLen) then begin Result := keyLen; end; end; function TOTFEBestCrypt.GetKeyGenDLLName(keyGenID: DWORD): string; var dispName: string; DLLName: string; begin Result := ''; if GetKeyGenRegDetails(keyGenID, dispName, DLLName) then begin Result := DLLName; end; end; function TOTFEBestCrypt.GetKeyGenName(keyGenID: DWORD): Ansistring; var dispName: string; DLLName: string; begin Result := ''; if GetKeyGenRegDetails(keyGenID, dispName, DLLName) then begin Result := dispName; { TODO 1 -otdk -cerror checking : check ansi } end; end; // Returns $FFFFFFFF on error function TOTFEBestCrypt.GetKeyGenVersion(keyGenID: DWORD): cardinal; var keyGenDLL: THandle; keyGenFilename: string; GetNameAndVersion: TBCGetNameAndVersion; majorVersion: DWORD; minorVersion: DWORD; keyGenName: string; nameBuffer: array [1..MAX_KEYGEN_NAME_LENGTH] of char; begin FLastErrCode:= OTFE_ERR_SUCCESS; Result := $FFFFFFFF; keyGenFilename := GetKeyGenDLLName(keyGenID); if keyGenFilename = '' then begin // Just quit; Result already set to error value exit; end; keyGenDLL := LoadDLL(keyGenFilename); try @GetNameAndVersion := GetProcAddress(keyGenDLL, 'GetNameAndVersion'); if @GetNameAndVersion=nil then begin raise EBestCryptBadDLL.Create(E_BESTCRYPT_BAD_DLL+ ' ('+ keyGenFilename+ '; GetNameAndVersion)'); end else begin if not(GetNameAndVersion(@nameBuffer, MAX_KEYGEN_NAME_LENGTH, @majorVersion, @minorVersion)) then begin raise EBestCryptDLLFailure.Create(E_BESTCRYPT_DLL_FAILURE+ ' ('+ keyGenFilename+ '; GetNameAndVersion)'); end else begin Result := (majorVersion * $100) + minorVersion; end; end; finally FreeLibrary(keyGenDLL); end; // The DLL's name as it is returned from the DLL. It would be nice to sanity // check here and verify this against the information held in the registry, // but it doesn't really matter that much keyGenName := copy(nameBuffer, 1, pos(#0, nameBuffer)); if Result=$FFFFFFFF then begin FLastErrCode:= OTFE_ERR_UNKNOWN_ALGORITHM; end; end; function TOTFEBestCrypt.CreateKeyHandle(volumeFilename: ansistring; var keyHandle: KEY_HANDLE): boolean; var keyGenDLLFilename: string; keyGenDLL: THandle; CreateKeyHandle: TBCCreateKeyHandle; hiSe: THiddenSector; algorithmName: Ansistring; algorithmKeyLength: integer; keyReturned: KEY_HANDLE; errorCode: DWORD; pDataBlock: Pointer; dataBlockSize: DWORD; tmpFile: TFileStream; memBlock: Pointer; begin FLastErrCode:= OTFE_ERR_SUCCESS; Result := FALSE; GetBestCryptFileHeader(volumeFilename, hiSe); algorithmKeyLength := GetAlgorithmKeyLength(hiSe.algorithmId); algorithmName := GetAlgorithmDriverName(hiSe.algorithmId); if (algorithmKeyLength=-1) OR (algorithmName='') then begin // Error code set in relevant function call above exit; end; dataBlockSize:= hiSe.dwKeySize; // Read the keyblock in from the volume file GetMem(memBlock, dataBlockSize); try tmpFile := TFileStream.Create(volumeFilename, fmOpenRead OR fmShareDenyNone); try tmpFile.Seek(HIDDEN_SECTOR_SIZE, soFromBeginning); tmpFile.Read(memBlock^, dataBlockSize); finally tmpFile.Free(); end; pDataBlock:= memBlock; keyGenDLLFilename := GetKeyGenDLLName(hiSe.keyGenId); keyGenDLL := LoadDLL(keyGenDLLFilename); try @CreateKeyHandle := GetProcAddress(keyGenDLL, 'CreateKeyHandle'); if @CreateKeyHandle=nil then begin MessageDlg( 'Unable to locate CreateKeyHandle within BestCrypt Key '+#13+#10+'generator DLL "'+keyGenDLLFilename+'"', mtError, [mbOK], 0 ); FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; end else begin if CreateKeyHandle(PAnsiChar(algorithmName), hiSe.algorithmId, DWORD(algorithmKeyLength), PAnsiChar(volumeFilename), PAnsiChar(FPasswordPrompt), CFLAG_VERIFY_AND_LOAD_KEY, @pDataBlock, @dataBlockSize, @keyReturned, @errorCode, HWND(nil) ) then begin keyHandle := keyReturned; Result := TRUE; end else begin if errorCode<>BCKEYGEN_ERROR_NO then begin Result := FALSE; FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; if errorCode=BCKEYGEN_ERROR_INCORRECT_PASSWORD then begin FLastErrCode:= OTFE_ERR_WRONG_PASSWORD; end else if errorCode=BCKEYGEN_ERROR_CANCELLED_BY_USER then begin FLastErrCode:= OTFE_ERR_USER_CANCEL; end end; end; end; finally FreeLibrary(keyGenDLL); end; finally FreeMem(memBlock); end; end; function TOTFEBestCrypt.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; var i: integer; tmpDrv: ansichar; begin mountedAs := ''; Result := FALSE; for i:=0 to (volumeFilenames.count-1) do begin // Don't ask, just don't ask... // (kludge because for loop doesn't always terminate when it should, // causing a "List out of bounds" error when trying to get a filename // that doesn't exist - first noticed after installing BestCrypt v6.07.2) // xxx - this should be sorted out properly... { TODO 3 -otdk -ccleanup : check} if (i>(volumeFilenames.count-1)) then begin exit; end; tmpDrv := Mount(volumeFilenames[i], readonly); mountedAs := mountedAs + tmpDrv; if tmpDrv<>#0 then begin Result := TRUE; end; end; end; function TOTFEBestCrypt.Mount(volumeFilename: ansistring; readonly: boolean = FALSE): Ansichar; var readInHeader: THiddenSector; volFileHandle: THandle; previousSizeLow: DWORD; driveDlg: TGetDriveLetter_F; defDrv: char; driveLetter: ansichar; diskSizeLow, diskSizeHigh: DWORD; begin CheckActive(); FLastErrCode:= OTFE_ERR_UNKNOWN_ERROR; Result := #0; driveLetter := #0; // If we were not supplied with a drive letter and either we are not using // the default volume drive letter assignment, or such an assignment doesn't // exist, prompt the user for the drive letter for the volume file to be // mounted on driveDlg := TGetDriveLetter_F.Create(nil); try driveDlg.Filename := volumeFilename; defDrv := GetDefaultDrive(volumeFilename); driveDlg.DefaultDrive := defDrv; driveDlg.cbAlwaysThisDrive.checked := (defDrv<>#0); driveDlg.ForceDriveLetter := VolumeInternallyMounted(volumeFilename); driveDlg.ProhibitedDriveLetters := InternalDrivesMounted(); driveDlg.AutoMountOptionAlwaysEnabled := RegistryOnlyVersion(); driveDlg.cbAutomount.checked := VolumeIsAutomounted(volumeFilename); if driveDlg.ShowModal()=mrOK then begin driveLetter := AnsiChar( driveDlg.cbDriveLetter.text[1]); if driveDlg.cbAlwaysThisDrive.checked then begin SetDefaultDriveAutomount(volumeFilename, driveLetter, driveDlg.cbAutomount.checked); end else begin SetDefaultDriveAutomount(volumeFilename, #0, driveDlg.cbAutomount.checked); end; end else begin FLastErrCode:= OTFE_ERR_USER_CANCEL; end; finally driveDlg.Free(); end; if driveLetter=#0 then begin // Result already set to #0, so just exit exit; end; GetBestCryptFileHeader(volumeFilename, readInHeader); volFileHandle := CreateFile(PWideChar(WideString(volumeFilename)), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (volFileHandle <> INVALID_HANDLE_VALUE) then begin diskSizeLow := GetFileSize(volFileHandle, @diskSizeHigh); CloseHandle(volFileHandle); // Now subtract the start of the data from the file's size // This needs to be done as follows to ensure that it is done correctly; // if the start of the encrypted disk data is > the low DWORD of the file size previousSizeLow := diskSizeLow; diskSizeLow := diskSizeLow-readInHeader.dwDataOffset; if previousSizeLow<=diskSizeLow then begin dec(diskSizeHigh) end; if (Version() < DRIVER_VERSION_DISKINFO_NEW) then begin // HANDLE FOR v2 DRIVERS... Result := MountDriverOLD(volumeFilename, readonly, driveLetter, diskSizeLow, diskSizeHigh, readInHeader); end else begin // HANDLE FOR v3 DRIVERS... Result := MountDriverNEW(volumeFilename, readonly, driveLetter, diskSizeLow, diskSizeHigh, readInHeader); end; end; end; function TOTFEBestCrypt.MountDriverOLD(volumeFilename: ansistring; readonly: boolean; driveLetter: ansichar; diskSizeLow, diskSizeHigh: DWORD; readInHeader: THiddenSector): ansichar; var dwBytesReturned : DWORD; queryOLD: TDISKINFO_BUFFER_driverOLD; i: integer; algorithmName: ansistring; keyHandle: KEY_HANDLE; volumeOnDrive: string; bytesPerSector: DWORD; junk1: DWORD; junk2: DWORD; junk3: DWORD; mountedDriveLetter: ansichar; begin CheckActive(); Result := #0; queryOLD.Signature := INPUT_SIGNATURE; if not(CreateKeyHandle(volumeFilename, keyHandle)) then begin // FLastErrCode set in the above function call, if needed end else begin queryOLD.keyHandle := keyHandle; queryOLD.diskSizeLow := diskSizeLow; queryOLD.diskSizeHigh := diskSizeHigh; queryOLD.dummy[1] := $5c; queryOLD.dummy[2] := $3f; queryOLD.dummy[3] := $3f; volumeOnDrive := copy(volumeFilename, 1, 3); volumeFilename := '\' + volumeFilename; for i:=1 to length(volumeFilename) do begin queryOLD.filename[i] := volumeFilename[i]; end; queryOLD.filename[length(volumeFilename)+1] := #0; queryOLD.diskNumber := ord(upcase(driveLetter))-ord('A'); algorithmName := '\Device\' + GetAlgorithmDriverName(readInHeader.algorithmId); for i:=1 to length(algorithmName) do begin queryOLD.algDevice[i] := algorithmName[i]; end; queryOLD.algDevice[length(algorithmName)+1] := #0; queryOLD.algorithmID := readInHeader.algorithmId; if readonly then begin queryOLD.readOnly := BESTCRYPT_DWORD_TRUE; end else begin queryOLD.readOnly := BESTCRYPT_DWORD_FALSE; end; queryOLD.process := 0; // BestCrypt v6.06 control panel sets this to 0 when it mounts volumes queryOLD.thread := 0; // BestCrypt v6.06 control panel sets this to 0 when it mounts volumes // query.sectorSize := readInHeader.bootRecord.bpb.sectSize; // that last query.sectorSize is wrong; it should be set to the sectorsize of // the *host* drive if GetDiskFreeSpace(PChar(volumeOnDrive), junk1, bytesPerSector, junk2, junk3) then begin queryOLD.sectorSize := bytesPerSector; end else begin // xxx - set error code here MessageDlg( 'Unable to obtain sectorsize for drive: '+volumeOnDrive+CRLF+ CRLF+ 'Assuming 512 bytes/sector.', mtWarning, [mbOK], 0 ); // <shrugs> Well, no harm in giving it a go, I guess... queryOLD.sectorSize := 512; end; queryOLD.fullDismounted := TRUE; // set to 1 queryOLD.dataOffset := readInHeader.dwDataOffset; DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_MAP_BCDISK, @queryOLD, sizeof(queryOLD), @queryOLD, sizeof(queryOLD), dwBytesReturned, nil); FLastErrCode := OTFE_ERR_DRIVER_FAILURE; if (queryOLD.signature<>OUTPUT_SIGNATURE) then begin raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end else if (queryOLD.status=BCSTATUS_SUCCESS) then begin mountedDriveLetter := Ansichar(queryOLD.diskNumber+ord('A')); BroadcastDriveChangeMessage(TRUE, mountedDriveLetter); FLastErrCode:= OTFE_ERR_SUCCESS; Result := mountedDriveLetter; end; end; end; function TOTFEBestCrypt.MountDriverNEW(volumeFilename: ansistring; readonly: boolean; driveLetter: ansichar; diskSizeLow, diskSizeHigh: DWORD; readInHeader: THiddenSector): ansichar; var dwBytesReturned : DWORD; queryNEW: TDISKINFO_BUFFER_driverNEW; i: integer; algorithmName: Ansistring; keyHandle: KEY_HANDLE; volumeOnDrive: string; bytesPerSector: DWORD; junk1: DWORD; junk2: DWORD; junk3: DWORD; mountedDriveLetter: Ansichar; begin CheckActive(); Result := #0; queryNEW.Signature := INPUT_SIGNATURE; if not(CreateKeyHandle(volumeFilename, keyHandle)) then begin // FLastErrCode set in the above function call, if needed end else begin queryNEW.keyHandle := keyHandle; queryNEW.diskSizeLow := diskSizeLow; queryNEW.diskSizeHigh := diskSizeHigh; queryNEW.dummy[1] := $5c; queryNEW.dummy[2] := $3f; queryNEW.dummy[3] := $3f; volumeOnDrive := copy(volumeFilename, 1, 3); volumeFilename := '\' + volumeFilename; for i:=1 to length(volumeFilename) do begin queryNEW.filename[i] := volumeFilename[i]; end; queryNEW.filename[length(volumeFilename)+1] := #0; queryNEW.diskNumber := ord(upcase(driveLetter))-ord('A'); algorithmName := '\Device\' + GetAlgorithmDriverName(readInHeader.algorithmId); for i:=1 to length(algorithmName) do begin queryNEW.algDevice[i] := algorithmName[i]; end; queryNEW.algDevice[length(algorithmName)+1] := #0; queryNEW.algorithmID := readInHeader.algorithmId; if readonly then begin queryNEW.readOnly := BESTCRYPT_DWORD_TRUE; end else begin queryNEW.readOnly := BESTCRYPT_DWORD_FALSE; end; queryNEW.process := 0; // BestCrypt v6.06 control panel sets this to 0 when it mounts volumes queryNEW.thread := 0; // BestCrypt v6.06 control panel sets this to 0 when it mounts volumes // query.sectorSize := readInHeader.bootRecord.bpb.sectSize; // that last query.sectorSize is wrong; it should be set to the sectorsize of // the *host* drive if GetDiskFreeSpace(PChar(volumeOnDrive), junk1, bytesPerSector, junk2, junk3) then begin queryNEW.sectorSize := bytesPerSector; end else begin // xxx - set error code here MessageDlg( 'Unable to obtain sectorsize for drive: '+volumeOnDrive+CRLF+ CRLF+ 'Assuming 512 bytes/sector.', mtWarning, [mbOK], 0 ); // <shrugs> Well, no harm in giving it a go, I guess... queryNEW.sectorSize := 512; end; queryNEW.fullDismounted := TRUE; // set to 1 queryNEW.dataOffset := readInHeader.dwDataOffset; // New items for v3 drivers and later... queryNEW.UserId := GetCurrentUserID(); queryNEW.HarddiskVolumeNumber := 0; // xxx - ??? DeviceIoControl(hBestCryptVxD, IOCTL_PRIVATE_MAP_BCDISK, @queryNEW, sizeof(queryNEW), @queryNEW, sizeof(queryNEW), dwBytesReturned, nil); FLastErrCode := OTFE_ERR_DRIVER_FAILURE; if (queryNEW.signature<>OUTPUT_SIGNATURE) then begin raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end else if (queryNEW.status=BCSTATUS_SUCCESS) then begin mountedDriveLetter := Ansichar(queryNEW.diskNumber+ord('A')); BroadcastDriveChangeMessage(TRUE, mountedDriveLetter); FLastErrCode:= OTFE_ERR_SUCCESS; Result := mountedDriveLetter; end; end; end; // This is ported from the function received in email from Sergey Frolov function TOTFEBestCrypt.GetCurrentUserID(): DWORD; const // This algorithm only uses up to a max of 32 chars MAX_USERNAME_CHARS_USED = 32; var currentUserId: DWORD; position: DWORD; i: integer; usernameLength: DWORD; arrUserName: array [1..MAX_USERNAME_CHARS_USED] of char; begin currentUserId := USER_ID_SUITABLE_FOR_ALL_USERS; usernameLength := MAX_USERNAME_CHARS_USED; if GetUserName(@arrUserName, usernameLength) then begin position := 1; for i:=0 to 9 do begin // calculate user Id if (arrUserName[i+1] = #0) then begin break; end; currentUserId := currentUserId + ord(arrUserName[i+1]) + position; position := position * 10; end; // for i:=0 to 9 do end; // if GetUserName(@arrUserName, usernameLength) then Result := currentUserId; end; function TOTFEBestCrypt.LoadDLL(DLLFilename: string): THandle; var theDLL: THandle; loadFilename: string; begin loadFilename := DLLFilename; theDLL := LoadLibrary(PChar(loadFilename)); if theDLL=0 then begin // DLL couldn't be loaded; maybe it isn't on the path? Try again, looking // in the BestCrypt directory loadFilename := ExtractFilePath(GetMainExe())+DLLFilename; theDLL := LoadLibrary(PChar(loadFilename)); if theDLL=0 then begin FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLNotFound.Create(E_BESTCRYPT_DLL_NOT_FOUND+ ' ('+ DLLFilename+ ')'); end; end; Result := theDLL; end; // Returns default drive letter volume gets mounted as // If the letter is in UPPERCASE, it's automounted // If the letter is in LOWERCASE, it's NOT automounted // Returns #0 if there is no default drive // WARNING: If were running with a version of BestCrypt that stores all of // it's settings in the registry, and nothing in an INI file // (BestCrypt later than v6.07.2), this function will call // VolumeIsAutomounted(...) function TOTFEBestCrypt.GetDefaultDrive(volumeFilename: string): char; var registry: TRegistry; keyName: string; tmpDriveString: string; driveLetter: char; filenameASCIIHash: string; begin if RegistryOnlyVersion() then begin filenameASCIIHash := GetFilenameASCIIHash(volumeFilename); driveLetter := #0; registry := TRegistry.create(); try registry.RootKey := HKEY_CURRENT_USER; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\MountPoint'; if registry.OpenKeyReadOnly(keyName) then begin tmpDriveString := registry.ReadString(filenameASCIIHash); registry.CloseKey(); if (tmpDriveString<>'') then begin // Ensure that it's always lowercase (no automount) tmpDriveString := lowercase(tmpDriveString); driveLetter := tmpDriveString[1]; end; end; finally registry.Free(); end; // Default is lowercase (see above); uppercase the driveletter is // AutoMounted if VolumeIsAutomounted(volumeFilename) then begin driveLetter := upcase(driveLetter); end; Result := driveLetter; end else begin Result := INIGetDefaultDrive(volumeFilename); end; end; // For old versions of BestCrypt, returns default drive letter volume gets // mounted as // Returns #0 if there is no default drive // NOTE: If the letter is in UPPERCASE, it's automounted // If the letter is in LOWERCASE, it's NOT automounted // WARNING: If were running with a version of BestCrypt that stores some of // it's settings in an INI file (BestCrypt prior to v6.07.2), this // function will be called by VolumeIsAutomounted(...) function TOTFEBestCrypt.INIGetDefaultDrive(volumeFilename: string): char; var iniFile: TINIFile; strTemp: string; containerNum: integer; begin Result := #0; iniFile := TINIFile.Create(BESTCRYPT_INI_FILENAME); try containerNum := INIGetAutomountContainerNum(volumeFilename); if containerNum<>-1 then begin strTemp := iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), ''); Result := strTemp[1]; end; finally iniFile.Free(); end; end; // Setup wether the specified volume filename is automounted, and it's default // driver (#0 for no default drive) function TOTFEBestCrypt.SetDefaultDriveAutomount(volumeFilename: string; driveLetter: ansichar; automount: boolean): boolean; begin if RegistryOnlyVersion() then begin Result := TRUE; if not(RegistryVolumeSetDefaultDrive(volumeFilename, driveLetter)) then begin MessageDlg( 'Unable to set default drive for container "'+volumeFilename+'"', mtError, [mbOK], 0 ); Result := FALSE; end; if not(RegistryVolumeSetAutomounted(volumeFilename, automount)) then begin MessageDlg( 'Unable to set container to be auto-opened for container "'+volumeFilename+'"', mtError, [mbOK], 0 ); Result := FALSE; end; end else begin // If there's no default driveletter, delete default drive (automount // irrelevant) if (driveLetter=#0) then begin Result := DeleteDefaultDrive(volumeFilename); end else begin Result := INISetDefaultDriveAutomount(volumeFilename, driveLetter, automount); end; end; end; function TOTFEBestCrypt.INISetDefaultDriveAutomount(volumeFilename: string; driveLetter: ansichar; automount: boolean): boolean; var iniFile: TINIFile; containerNum: integer; keyValue: string; begin Result := TRUE; if automount then begin driveLetter := upcase(driveLetter); end else begin driveLetter := AnsiString((LowerCase(driveLetter)))[1]; end; iniFile := TINIFile.Create(BESTCRYPT_INI_FILENAME); try containerNum := INIGetAutomountContainerNum(volumeFilename); if containerNum<>-1 then begin iniFile.WriteString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), driveLetter+volumeFilename); end else begin // Create a new key containerNum := 0; keyValue := iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), ''); while keyValue<>'' do begin inc(containerNum); keyValue := iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), ''); end; iniFile.WriteString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), driveLetter+volumeFilename); end; finally iniFile.Free(); end; end; function TOTFEBestCrypt.INIGetAutomountContainerNum(volumeFilename: string): integer; var sectionKeys: TStringList; i: integer; iniFile: TINIFile; strTemp: string; begin Result := -1; volumeFilename := uppercase(volumeFilename); sectionKeys := TStringList.Create(); try iniFile := TINIFile.Create(BESTCRYPT_INI_FILENAME); try // This would be considerably neater if it just used // TINIFile.ReadSectionValues - but for some strange reason, using this // causes it to choke later on... Weird... // iniFile.ReadSectionValues(kBestCryptINIFileAutoOpenKey, sectionKeys); i:=0; while i<>-1 do begin strTemp := uppercase(iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(i), '')); if strTemp='' then begin i:=-1 end else begin sectionKeys.add(strTemp); inc(i); end; end; finally iniFile.Free(); end; for i:=0 to (sectionKeys.count-1) do begin if pos(volumeFilename, sectionKeys[i])=2 then begin Result := i; end; end; finally sectionKeys.Free(); end; end; function TOTFEBestCrypt.DeleteDefaultDrive(volumeFilename: string): boolean; begin Result := INIDeleteDefaultDrive(volumeFilename); end; function TOTFEBestCrypt.INIDeleteDefaultDrive(volumeFilename: string): boolean; var iniFile: TINIFile; containerNum: integer; keyValue: string; begin Result := TRUE; iniFile := TINIFile.Create(BESTCRYPT_INI_FILENAME); try containerNum := INIGetAutomountContainerNum(volumeFilename); keyValue := iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum+1), ''); while keyValue<>'' do begin iniFile.WriteString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum), keyValue); inc(containerNum); keyValue := iniFile.ReadString(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum+1), ''); end; iniFile.DeleteKey(kBestCryptINIFileAutoOpenKey, 'Container'+inttostr(containerNum)); finally iniFile.Free(); end; end; procedure TOTFEBestCrypt.GetAllAlgorithmIDs(algIDs: TStrings); var registry: TRegistry; subKeys: TStringList; i: integer; currID: DWORD; keyName: string; begin CheckActive(); registry := TRegistry.create(); try registry.RootKey := HKEY_LOCAL_MACHINE; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\Algorithms'; if registry.OpenKeyReadOnly(keyName) then begin subKeys := TStringList.Create(); try registry.GetKeyNames(subKeys); registry.CloseKey(); for i:=0 to (subKeys.count-1) do begin registry.OpenKeyReadOnly(keyName + '\' + subKeys[i]); currID := registry.ReadInteger('AlgorithmID'); algIDs.add(inttostr(currID)); registry.CloseKey(); end; finally subKeys.Free(); end; end; finally registry.Free(); end; end; procedure TOTFEBestCrypt.GetAllKeyGenIDs(keyGenIDs: TStrings); var registry: TRegistry; subKeys: TStringList; i: integer; currID: DWORD; keyName: string; begin CheckActive(); registry := TRegistry.create(); try registry.RootKey := HKEY_LOCAL_MACHINE; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\KeyGenerators'; if registry.OpenKeyReadOnly(keyName) then begin subKeys := TStringList.Create(); try registry.GetKeyNames(subKeys); registry.CloseKey(); for i:=0 to (subKeys.count-1) do begin registry.OpenKeyReadOnly(keyName + '\' + subKeys[i]); currID := registry.ReadInteger('KeyGenID'); keyGenIDs.add(inttostr(currID)); registry.CloseKey(); end; finally subKeys.Free(); end; end; finally registry.Free(); end; end; function TOTFEBestCrypt.GetAlgorithmVersion(algorithmID: DWORD): cardinal; var dwBytesReturned : DWORD; query: TVERSION_BUFFER; algHandle: THandle; begin CheckActive(); algHandle := CreateFile(PChar(WideString('\\.\'+GetAlgorithmDriverName(algorithmID))), GENERIC_READ OR GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if algHandle = INVALID_HANDLE_VALUE then begin FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; raise EBestCryptVxdNotFound.Create('BestCrypt algorithm device driver not found'); end; Result := $FFFFFFFF; query.Signature := INPUT_SIGNATURE; DeviceIoControl(algHandle, IOCTL_PRIVATE_GET_VERSION_INFO, @query, sizeof(query), @query, sizeof(query), dwBytesReturned, nil); LastErrorCode := query.status; if query.signature<>OUTPUT_SIGNATURE then begin FLastErrCode := OTFE_ERR_DRIVER_FAILURE; raise EBestCryptDLLBadSignature.Create(E_BESTCRYPT_DLL_SIGNATURE_FAILURE); end; FLastErrCode:= OTFE_ERR_DRIVER_FAILURE; if query.status=0 then begin FLastErrCode:= OTFE_ERR_SUCCESS; Result := (query.Major_version * $100) + query.Minor_version; end; end; function TOTFEBestCrypt.GetVolumeInfo(volumeFilename: ansistring; var info: TBCDiskInfo): boolean; var hi: THiddenSector; diOLD: TDISKINFO_BUFFER_driverOLD; diNEW: TDISKINFO_BUFFER_driverNEW; mtdAs: ansichar; tmpFile: TFileStream; begin volumeFilename := SDUConvertSFNToLFN(volumeFilename); info.volumeFilename := volumeFilename; mtdAs := GetDriveForVolFile(volumeFilename); info.mountedAs := mtdAs; info.readOnly := FALSE; if mtdAs<>#0 then begin if (Version() < DRIVER_VERSION_DISKINFO_NEW) then begin // HANDLE FOR v2 DRIVERS... GetDriveInfoOLD(mtdAs, diOLD); info.readOnly := (diOLD.readOnly<>0); end else begin // HANDLE FOR v3 DRIVERS... GetDriveInfoNEW(mtdAs, diNEW); info.readOnly := (diNEW.readOnly<>0); end; end; tmpFile := TFileStream.Create(volumeFilename, fmOpenRead OR fmShareDenyNone); try tmpFile.Seek(BC_FILE_ERRORS_IN_MOUNTING_OFFSET, soFromBeginning); tmpFile.Read(info.errsInMounting, 1); finally tmpFile.Free(); end; GetBestCryptFileHeader(volumeFilename, hi); info.algorithmID := hi.algorithmId; info.algorithmName := GetAlgorithmName(hi.algorithmId); info.algorithmKeyLen := GetAlgorithmKeyLength(hi.algorithmId); info.keyGenID := hi.keyGenId; info.keyGenName := GetKeyGenName(hi.keyGenId); info.description := hi.description; info.extent := hi.extent; info.version := hi.version; info.fileSystemID := hi.fileSystemId; Result := TRUE; end; function TOTFEBestCrypt.GetVolumeInfo(driveLetter: Ansichar; var info: TBCDiskInfo): boolean; var volumeFilename: Ansistring; begin Result := FALSE; volumeFilename := GetVolFileForDrive(driveLetter); { TODO 1 -otdk -cerror checking : check ansi } if (volumeFilename<>'') then begin Result := GetVolumeInfo(volumeFilename, info); end; end; function TOTFEBestCrypt.VersionStr(): string; var verNo: cardinal; majorVer: integer; minorVer: integer; begin verNo := Version(); majorVer := (verNo AND $FF00) div $FF; minorVer := (verNo AND $FF); Result := Format('v%d.%d', [majorVer, minorVer]); end; function TOTFEBestCrypt.GetAlgorithmRegDetails(algorithmID: DWORD; var dispName: string; var driverName: string; var keyLen: integer): boolean; var registry: TRegistry; subKeys: TStringList; i: integer; currID: DWORD; keyName: string; begin Result := FALSE; FLastErrCode:= OTFE_ERR_UNKNOWN_ALGORITHM; registry := TRegistry.Create(); try registry.RootKey := HKEY_LOCAL_MACHINE; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\Algorithms'; if registry.OpenKeyReadOnly(keyName) then begin subKeys := TStringList.Create(); try registry.GetKeyNames(subKeys); registry.CloseKey(); for i:=0 to (subKeys.count-1) do begin registry.OpenKeyReadOnly(keyName + '\' + subKeys[i]); currID := registry.ReadInteger('AlgorithmID'); if currID = algorithmID then begin dispName := registry.ReadString('DisplayName'); driverName := subKeys[i]; keyLen := registry.ReadInteger('KeyLength'); Result := TRUE end; registry.CloseKey(); end; finally subKeys.Free(); end; end; finally registry.Free(); end; if Result then begin FLastErrCode:= OTFE_ERR_SUCCESS; end; end; function TOTFEBestCrypt.GetKeyGenRegDetails(keyGenID: DWORD; var dispName: string; var DLLName: string): boolean; var registry: TRegistry; subKeys: TStringList; i: integer; currID: DWORD; keyName: string; begin Result := FALSE; FLastErrCode:= OTFE_ERR_UNKNOWN_KEYGEN; registry := TRegistry.Create(); try registry.RootKey := HKEY_LOCAL_MACHINE; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\KeyGenerators'; if registry.OpenKeyReadOnly(keyName) then begin subKeys := TStringList.Create(); try registry.GetKeyNames(subKeys); registry.CloseKey(); for i:=0 to (subKeys.count-1) do begin registry.OpenKeyReadOnly(keyName + '\' + subKeys[i]); currID := registry.ReadInteger('KeyGenID'); if currID = keyGenID then begin dispName := registry.ReadString('DisplayName'); DLLName := registry.ReadString('ImagePath'); Result := TRUE; end; registry.CloseKey(); end; finally subKeys.Free(); end; end; finally registry.Free(); end; if Result then begin FLastErrCode:= OTFE_ERR_SUCCESS; end; end; function TOTFEBestCrypt.GetMainExe(): string; var registry: TRegistry; keyName: string; appName: string; begin FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE; Result := ''; appName := BESTCRYPT_APP_EXE_NAME; registry := TRegistry.create(); try registry.RootKey := HKEY_LOCAL_MACHINE; keyName := REGSTR_PATH_APPPATHS + '\' + appName; if registry.OpenKeyReadOnly(keyName) then begin Result := registry.ReadString(''); registry.CloseKey; end; finally registry.Free(); end; if Result<>'' then begin FLastErrCode:= OTFE_ERR_SUCCESS; end; end; // 17-November-2000 release, BestCrypt Control Panel v.6.07.2, Windows 95/98 // driver v2.40, Windows NT driver v2.18 - from Jetico WWW site function TOTFEBestCrypt.RegistryOnlyVersion(): boolean; var ver: cardinal; begin ver := Version(); Result := ( ((Win32Platform = VER_PLATFORM_WIN32_NT) and (ver>=$212)) or ((Win32Platform <> VER_PLATFORM_WIN32_NT) and (ver>=$229)) ); end; // Return TRUE if the volume specified is automounted, otherwise FALSE // WARNING: If were running with a version of BestCrypt that stores some of // it's settings in an INI file (BestCrypt prior to v6.07.2), this // function will call INIGetDefaultDrive function TOTFEBestCrypt.VolumeIsAutomounted(volumeFilename: string): boolean; var defDrv: char; registry: TRegistry; subKeys: TStringList; i: integer; keyName: string; begin Result := FALSE; if not(RegistryOnlyVersion()) then begin defDrv := INIGetDefaultDrive(volumeFilename); if defDrv<>#0 then begin Result := (defDrv=uppercase(defDrv)); end; end else begin volumeFilename := uppercase(volumeFilename); registry := TRegistry.create(); try registry.RootKey := HKEY_CURRENT_USER; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\AutoMount'; if registry.OpenKeyReadOnly(keyName) then begin subKeys := TStringList.Create(); try registry.GetValueNames(subKeys); registry.CloseKey(); for i:=0 to (subKeys.count-1) do begin if (uppercase(subKeys[i]) = volumeFilename) then begin Result := TRUE; exit; end; end; finally subKeys.Free(); end; end; finally registry.Free(); end; end; end; // Set the default drive for the specified volume (later, registry-only versions // of BestCrypt; with no INI file) // If driveLetter is #0, delete the default drive function TOTFEBestCrypt.RegistryVolumeSetDefaultDrive(volumeFilename: string; driveLetter: ansichar): boolean; var registry: TRegistry; keyName: string; filenameASCIIHash: string; driveString: string; begin Result := FALSE; filenameASCIIHash := GetFilenameASCIIHash(volumeFilename); registry := TRegistry.create(); try registry.RootKey := HKEY_CURRENT_USER; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\MountPoint'; if registry.OpenKey(keyName, TRUE) then begin if (driveLetter=#0) then begin registry.deletevalue(filenameASCIIHash); end else begin driveString := uppercase(driveLetter)+':\'; registry.WriteString(filenameASCIIHash, driveString); end; registry.CloseKey(); Result := TRUE; end; finally registry.Free(); end; end; // Set the specified volume to be automounted (later, registry-only versions // of BestCrypt; with no INI file) function TOTFEBestCrypt.RegistryVolumeSetAutomounted(volumeFilename: string; automount: boolean): boolean; var registry: TRegistry; keyName: string; nothingBuffer: string; begin Result := FALSE; if (VolumeIsAutomounted(volumeFilename) = automount) then begin // Nothing to do - all dome already! Result := TRUE; exit; end; volumeFilename := SDUConvertSFNToLFN(volumeFilename); registry := TRegistry.create(); try registry.RootKey := HKEY_CURRENT_USER; keyName := BESTCRYPT_REGKEY_BESTCRYPT + '\AutoMount'; if registry.OpenKey(keyName, TRUE) then begin if (automount) then begin nothingBuffer := ''; registry.WriteBinaryData(volumeFilename, nothingBuffer, 0); end else begin registry.DeleteValue(volumeFilename); end; registry.CloseKey(); Result := TRUE; end; finally registry.Free(); end; end; // Return the SHA-1 hash of the specified filename, for use with the registry // settings introduced in BestCrypt v6.07.2 function TOTFEBestCrypt.GetFilenameASCIIHash(volumeFilename: string): string; var hashBuffSize: integer; written: integer; codedHash: string; digest: THashArray; hashSHA1: THashAlgSHA1; begin // BestCrypt registry settings use LFNs volumeFilename := SDUConvertSFNtoLFN(volumeFilename); hashSHA1:= THashAlgSHA1.Create(nil); try digest := hashSHA1.HashString(volumeFilename); hashBuffSize := ( (hashSHA1.HashLength div 8) // BestCrypt hashSize in bytes * 2 + 1 ); written := hashBuffSize; if not(SE_EncodeString(codedHash, written, digest, (hashSHA1.HashLength div 8))) then begin raise EOTFEException.Create(E_BESTCRYPT_UNABLE_TO_CREATE_FILENAME_HASH); end; Result := codedHash; finally hashSHA1.Free(); end; end; function TOTFEBestCrypt.VolumeInternallyMounted(volumeFilename: string): ansichar; var diOLD: TDISKINFO_BUFFER_driverOLD; diNEW: TDISKINFO_BUFFER_driverNEW; drv: ansichar; begin CheckActive(); volumeFilename := SDUConvertSFNtoLFN(volumeFilename); Result := #0; for drv:='A' to 'Z' do begin if (Version() < DRIVER_VERSION_DISKINFO_NEW) then begin // HANDLE FOR v2 DRIVERS... if GetDriveInfoOLD(drv, diOLD) then begin // Start copying from the 2nd char to avoid the extra "\" at the start // Only copy up to the #0, i.e. only the number of chars 2 less than the // #0's pos if (volumeFilename=SDUConvertSFNtoLFN(copy(diOLD.filename, 2, (pos(#0, diOLD.filename)-2)))) then begin Result := drv; break; end; end; end else begin // HANDLE FOR v3 DRIVERS... if GetDriveInfoNEW(drv, diNEW) then begin // Start copying from the 2nd char to avoid the extra "\" at the start // Only copy up to the #0, i.e. only the number of chars 2 less than the // #0's pos if (volumeFilename=SDUConvertSFNtoLFN(copy(diNEW.filename, 2, (pos(#0, diNEW.filename)-2)))) then begin Result := drv; break; end; end; end; end; end; // ----------------------------------------------------------------------------- // Prompt the user for a device (if appropriate) and password (and drive // letter if necessary), then mount the device selected // Returns the drive letter of the mounted devices on success, #0 on failure function TOTFEBestCrypt.MountDevices(): Ansistring; begin // Not supported... Result := #0; end; // ----------------------------------------------------------------------------- // Determine if OTFE component can mount devices. // Returns TRUE if it can, otherwise FALSE function TOTFEBestCrypt.CanMountDevice(): boolean; begin // Not supported... Result := FALSE; end; // ----------------------------------------------------------------------------- END.
unit ImportarBase.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Base.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, cxControls, cxContainer, cxEdit, cxLabel, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, Vcl.Grids, Vcl.ComCtrls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Datasnap.DBClient, dxGDIPlusClasses, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver, dxSkinVS2010; type TFImportarView = class(TFBaseView) BtSalvar: TcxButton; BtBuscar: TcxButton; OpPlanilha: TOpenDialog; PbProgresso: TProgressBar; DbDados: TcxGrid; VwDados: TcxGridDBTableView; LvDados: TcxGridLevel; DsDados: TDataSource; StGrid: TcxStyleRepository; StHeader: TcxStyle; StBackground: TcxStyle; StContentOdd: TcxStyle; StContentEven: TcxStyle; StSelection: TcxStyle; StInactive: TcxStyle; CdDados: TClientDataSet; LbLegenda: TcxLabel; procedure BtSalvarClick(Sender: TObject); private { Private declarations } protected function formatarTextoEmValor(AValue: string): string; function removerEspacoesExtrasDeUmTexto(AValue: string): string; function removerCaracteresEspeciais(AValue: string): string; public { Public declarations } end; var FImportarView: TFImportarView; implementation {$R *.dfm} { TFImportarView } procedure TFImportarView.BtSalvarClick(Sender: TObject); begin inherited; Close; end; function TFImportarView.formatarTextoEmValor(AValue: string): string; begin AValue := StringReplace(AValue, '.', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, '', '0,00', [rfReplaceAll, rfIgnoreCase]); Result := AValue; end; function TFImportarView.removerCaracteresEspeciais(AValue: string): string; var I, tamanhoTexto: Integer; begin tamanhoTexto := Length(AValue); for I := 0 to Pred(tamanhoTexto) do begin AValue := StringReplace(AValue, '.', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, '/', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, '-', '', [rfReplaceAll, rfIgnoreCase]); end; Result := AValue; end; function TFImportarView.removerEspacoesExtrasDeUmTexto(AValue: string): string; var I, tamanhoTexto: Integer; begin tamanhoTexto := Length(AValue); for I := 0 to Pred(tamanhoTexto) do begin AValue := StringReplace(AValue, ' ', '', [rfReplaceAll, rfIgnoreCase]); AValue := StringReplace(AValue, ';', '', [rfReplaceAll, rfIgnoreCase]); end; Result := AValue; end; end.
unit About_Window; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { TAboutWindow } TAboutWindow = class(TForm) buttonClose: TButton; imageAbout: TImage; labelProgSystem: TLabel; labelCopyright: TLabel; labelVersion: TLabel; labelAboutAppName: TLabel; panelAboutImage: TPanel; panelClose: TPanel; procedure buttonCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormShow(Sender: TObject); procedure panelAboutImageResize(Sender: TObject); private public end; var AboutWindow: TAboutWindow; implementation {$R *.lfm} uses UscaleDPI, System_Settings, Version_Info; { TAboutWindow } // -------------------------------------------------------------------------------- procedure TAboutWindow.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin SystemSettings.saveFormState(TForm(self)); CloseAction := caFree; end; // -------------------------------------------------------------------------------- procedure TAboutWindow.buttonCloseClick(Sender: TObject); begin Close; end; // -------------------------------------------------------------------------------- procedure TAboutWindow.FormShow(Sender: TObject); begin SystemSettings.restoreFormState(TForm(self)); ScaleDPI(self, 96); labelVersion.Caption := 'Version: ' + GetFileVersion; labelProgSystem.Caption := GetOS + ' ' + GetLCLVersion + ' & ' + GetCompilerInfo; self.SetAutoSize(True); Constraints.MinWidth := Width; Constraints.MaxWidth := Width; Constraints.MinHeight := Height; Constraints.MaxHeight := Height; end; // -------------------------------------------------------------------------------- procedure TAboutWindow.panelAboutImageResize(Sender: TObject); begin imageAbout.Left := (panelAboutImage.Width - imageAbout.Width) shr 1; imageAbout.Top := (panelAboutImage.Height - imageAbout.Height) shr 1; end; // -------------------------------------------------------------------------------- end.
unit Pospolite.View.DOM.Window; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, Forms; type TPLDOMWindowDisplay = (wdStandalone, wdMinimalUI, wdBrowser); { TPLDOMWindow } TPLDOMWindow = packed record private FDisplay: TPLDOMWindowDisplay; FHook: TCustomForm; public constructor Create(AHook: TCustomForm); function closed: boolean; property Hook: TCustomForm read FHook write FHook; property Display: TPLDOMWindowDisplay read FDisplay write FDisplay; end; implementation { TPLDOMWindow } constructor TPLDOMWindow.Create(AHook: TCustomForm); begin Hook := AHook; FDisplay := wdStandalone; end; function TPLDOMWindow.closed: boolean; begin if Assigned(FHook) then Result := FHook.Visible else Result := false; end; end.
unit uBuildMenu; interface Uses Menus, Forms, ADOdb, db, Classes, extctrls, dxBar, Sysutils, dxBarExtItems; Type TmyBarButton = class(TdxBarButton) Public Form : TForm; // Ponteiro para o TForm Title : String; // Titulo que o modulo possuira quando aberto Loaded : boolean; // O TForm esta na memoria Ready : boolean; // Este IDMenuItem foi incluido no menu do usuario IDMenuItem : integer; // IDMenuitem que chamou o form UserRights : String; // Guarda quais operações podem ser executadas pelo usuario FormClassName : String; // Nome da classe do form que será chamado Parametro : String; LoaderType : integer; //Loader Type FormID : integer; //Form Number end; TmyBarButtonControl = class(TdxBarButtonControl); TBuildMenu = Class Private //Menu Normal lList : TStringList; FStartUpModulo : TNotifyEvent; FConnection : TADOConnection; FBarManager : TdxBarManager; FMenuOwner : TComponent; LocalOwner : TComponent; fIDLanguage : Integer; procedure AddNewMenu(AOwner: TComponent; ALinks: TdxBarItemLinks; aQuery: TDataSet); Function GetButtonByID(aIDMenuItem:Integer):TmyBarButton; Function GetSubItemByID(aIDMenuItem:Integer):TdxBarSubItem; Function GetNewQuery(AFirstIDMenuItem: Integer):TADOQuery; Function CreateSubItem(AOwner: TComponent; ALinks: TdxBarItemLinks; ABeginGroup: Integer): TdxBarSubItem; Function CreateButton(AOwner: TComponent; ALinks: TdxBarItemLinks; ABeginGroup: Integer): TmyBarButton; Public //Normal Menu function GetButton(iIDMenu:Integer):TmyBarButton; procedure ConstructMenu(AFirstIDMenuItem, IDLanguage: integer); procedure ClearModules; procedure ClearModule(Const AIDMenuItem: Integer); Constructor Create; Virtual; Destructor Destroy; Override; Property OnClick : TNotifyEvent Read FStartUpModulo Write FStartUpModulo; Property Connection : TADOConnection Read FConnection Write FConnection; Property BarManager : TdxBarManager Read FBarManager Write FBarManager; Property MenuOwner : TComponent Read FMenuOwner Write FMenuOwner; end; procedure Register; implementation procedure Register; begin RegisterNoIcon([TMyBarButton]); end; Constructor TBuildMenu.Create; begin Inherited Create; lList := TStringList.Create; LocalOwner := nil; end; Destructor TBuildMenu.Destroy; begin lList.Clear; FreeAndNil(lList); if Assigned(LocalOwner) then FreeAndNil(LocalOwner); Inherited Destroy; end; Function TBuildMenu.GetNewQuery(AFirstIDMenuItem: Integer):TADOQuery; begin Result := TADOQuery.Create(Nil); with Result do begin SQL.Add('SELECT '); SQL.Add(' CAST(M.MenuBarBefore as Integer) as MenuBarBefore,'); SQL.Add(' M.LoaderType, '); SQL.Add(' M.IDMenuItem as IDMenu, '); SQL.Add(' MML.MenuItem as MenuName, '); SQL.Add(' M.FormID, '); SQL.Add(' M.IDMenuItemParent as IDMenuParent, '); SQL.Add(' M.Priority, '); SQL.Add(' M.ClassName, '); SQL.Add(' M.Parametro, '); SQL.Add(' IsNull(M.ImageIndex,-1) as ImageIndex, '); SQL.Add(' COUNT(MP.IDMenuItem) as CountOfChild '); SQL.Add('FROM '); SQL.Add(' Sis_MainMenu M '); SQL.Add(' JOIN Sis_MainMenuLanguage MML '); SQL.Add(' ON (M.IDMenuItem = MML.IDMenuItem) '); SQL.Add(' LEFT OUTER JOIN Sis_MainMenu MP '); SQL.Add(' ON (MP.IDMenuItemParent = M.IDMenuItem) '); SQL.Add(' JOIN #Sis_MainMenuP MMP '); SQL.Add(' ON (MMP.IDMenuItemP = M.IDMenuItem) '); SQL.Add('WHERE '); SQl.Add(' M.IDMenuItem <> '+ IntToStr(AFirstIDMenuItem)+' '); SQl.Add(' AND '); SQl.Add(' MML.IDLanguage = '+ IntToStr(fIDlanguage)+' '); SQL.Add('GROUP BY '); SQL.Add(' M.IDMenuItemParent, '); SQL.Add(' M.IDMenuItem, '); SQL.Add(' CAST(M.MenuBarBefore as Integer), '); SQL.Add(' M.LoaderType, '); SQL.Add(' MML.MenuItem, '); SQL.Add(' M.FormID, '); SQL.Add(' M.ClassName, '); SQL.Add(' M.Parametro, '); SQL.Add(' M.ImageIndex, '); SQL.Add(' M.Priority '); SQL.Add('ORDER BY '); SQL.Add(' M.IDMenuItemParent, '); SQl.Add(' M.Priority '); end; Result.Connection := FConnection; end; procedure TBuildMenu.AddNewMenu(AOwner: TComponent; ALinks: TdxBarItemLinks; aQuery: TDataSet); var BarButton: TmyBarButton; BarSubItem: TdxBarSubItem; begin if aQuery.FieldByName('CountOfChild').AsInteger > 0 then begin // E um subMenu BarSubItem := CreateSubItem(AOwner, ALinks, aQuery.FieldByName('MenuBarBefore').AsInteger); with BarSubItem do begin Caption := aQuery.FieldByName('MenuName').AsString; ImageIndex := aQuery.FieldByName('ImageIndex').AsInteger; end; // Adiciono o SubItem a Lista para facilitar a procura depois lList.AddObject(aQuery.FieldByName('IDMenu').AsString, BarSubItem); end else begin // E um item de menu BarButton := CreateButton(AOwner, ALinks, aQuery.FieldByName('MenuBarBefore').AsInteger); with BarButton do begin OnClick := FStartUpModulo; Caption := aQuery.FieldByName('MenuName').AsString; Title := aQuery.FieldByName('MenuName').AsString; IDMenuItem := aQuery.FieldByName('IDMenu').AsInteger; FormClassName := aQuery.FieldByName('ClassName').AsString; LoaderType := aQuery.FieldByName('LoaderType').AsInteger; Parametro := aQuery.FieldByName('Parametro').AsString; FormID := aQuery.FieldByName('FormID').AsInteger; ImageIndex := aQuery.FieldByName('ImageIndex').AsInteger; Ready := True; Loaded := False; end; // Adiciono o SubItem a Lista para facilitar a procura depois lList.AddObject(aQuery.FieldByName('IDMenu').AsString, BarButton); end; end; function TBuildMenu.GetButton(iIDMenu:Integer):TmyBarButton; begin Result := GetButtonByID(iIDMenu); end; Function TBuildMenu.GetButtonByID(aIDMenuItem:Integer):TmyBarButton; begin with lList do if (IndexOf(IntToStr(aIdMenuItem)) <> -1) then Result := TMyBarButton(Objects[IndexOf(IntToStr(aIdMenuItem))]) else Result := Nil; end; Function TBuildMenu.GetSubItemByID(aIDMenuItem:Integer):TdxBarSubItem; begin with lList do if (IndexOf(IntToStr(aIdMenuItem)) <> -1) then Result := TdxBarSubItem(Objects[IndexOf(IntToStr(aIdMenuItem))]) else Result := Nil; end; function TBuildMenu.CreateSubItem(AOwner: TComponent; ALinks: TdxBarItemLinks; ABeginGroup: Integer): TdxBarSubItem; var NewItemLink : TdxBarItemLink; begin Result := TdxBarSubItem.Create(AOwner); NewItemLink := ALinks.Add; NewItemLink.Item := Result; NewItemLink.BeginGroup := (ABeginGroup=1); end; function TBuildMenu.CreateButton(AOwner: TComponent; ALinks: TdxBarItemLinks; ABeginGroup: Integer): TmyBarButton; var NewItemLink : TdxBarItemLink; begin Result := TmyBarButton.Create(AOwner); NewItemLink := ALinks.Add; NewItemLink.Item := Result; NewItemLink.BeginGroup := (ABeginGroup=1); end; procedure TBuildMenu.ConstructMenu(AFirstIDMenuItem, IDLanguage: integer); var fDataSet : TADOQuery; CurrentMenuParent: TdxBarSubItem; begin if (FConnection <> nil) then begin fIDLanguage := IDLanguage; if LocalOwner <> nil then begin ClearModules; LocalOwner.Free; end; LocalOwner := TPanel.Create(FMenuOwner); lList.Clear; fDataSet := GetNewQuery(AFirstIDMenuItem); // Abre todos os items deste menu if fDataSet <> Nil then with fDataSet do begin Close; Open; Try while not fDataSet.eof do Try BarManager.MainMenuBar.LockUpdate := True; // Verifico se existe o Parent CurrentMenuParent := GetSubItemByID(fDataSet.FieldByName('IDMenuParent').AsInteger); if CurrentMenuParent <> nil then AddNewMenu(LocalOwner, CurrentMenuParent.ItemLinks, fDataSet) else AddNewMenu(LocalOwner, FBarManager.MainMenuBar.ItemLinks, fDataSet); Finally fDataSet.Next; end Finally // Adiciono Menu Help BarManager.MainMenuBar.LockUpdate := False; fDataSet.Close; fDataSet.Free; end; end; end else Raise Exception.Create('Property TCreateMenu::ADO Connection not defined'); end; procedure TBuildMenu.ClearModules; var Loop : Integer; begin for Loop := 0 to lList.Count - 1 do ClearModule(StrToInt(lList[Loop])); end; procedure TBuildMenu.ClearModule(Const AIDMenuItem: Integer); var myBarButton : TmyBarButton; begin try myBarButton := GetButtonByID(aIDMenuItem); except myBarButton := nil; end; if myBarButton <> nil then with myBarButton do begin // Destroi o Form try if Form <> nil then begin Form.Close; (* 001 *) Form.Free; end; finally Form := nil; end; Loaded := False; end; end; initialization dxBarRegisterItem(TmyBarButton, TmyBarButtonControl, True); finalization dxBarUnregisterItem(TMyBarButton); end.
unit ucds; {$mode delphi} interface uses Classes, SysUtils, Types, JS, Web, DB, JSONDataSet, Controls, WebCtrls; type { TFieldDataLink } TFieldDataLink = class(TDataLink) private { private declarations } FOnDataChange: TNotifyEvent; FOnUpdateData: TNotifyEvent; FOnActiveChange: TNotifyEvent; FField: TField; FFieldName: String; FModified: Boolean; protected { protected declarations } // set current field //procedure SetFieldName(const Value: string); procedure UpdateField; procedure ActiveChanged; override; //procedure EditingChanged; override; //procedure LayoutChanged; override; procedure RecordChanged(Field: TField); override; procedure UpdateData; override; //procedure FocusControl(aField: TFieldRef); Override; public { public declarations } // for control intitiating db changes etc //function Edit: Boolean; procedure Modified; //procedure Reset; published { published declarations } // Attached control //property Control: TComponent read FControl write FControl; // Basic DB interfaces //property Field: TField read FField; property FieldName: string read FFieldName write FFieldName {SetFieldName}; // Current State of DB //property CanModify: Boolean read GetCanModify; //property Editing: Boolean read FEditing; // Our Callbacks property OnDataChange: TNotifyEvent read FOnDataChange write FOnDataChange; //property OnEditingChange: TNotifyEvent read FOnEditingChange write FOnEditingChange; property OnUpdateData: TNotifyEvent read FOnUpdateData write FOnUpdateData; property OnActiveChange: TNotifyEvent read FOnActiveChange write FOnActiveChange; end; type TControl = TCustomControl; type { TWDataSource } TWDataSource = class(TDataSource) private { private declarations } FParent: TControl; FLeft: Integer; FTop: Integer; protected { protected declarations } public { public declarations } published { published declarations } property Parent: TControl read FParent write FParent; property Left: Integer read FLeft write FLeft; property Top: Integer read FTop write FTop; end; type TConnectErrorEvent = procedure(Sender: TObject; ErrorCode: Integer); type TDataSet = class; type { TConnection } TConnection = class(TComponent) private { private declarations } FReq: TJSXMLHttpRequest; FDS: TDataSet; FParent: TControl; FLeft: Integer; FTop: Integer; FActive: Boolean; FDataNode: String; FURI: String; FAfterConnect: TNotifyEvent; FBeforeConnect: TNotifyEvent; FOnConnectError: TConnectErrorEvent; protected { protected declarations } procedure SetActive(AValue: boolean); public { public declarations } function onLoad(Event: TEventListenerEvent): boolean; procedure RegisterDataSet(value: TDataSet); procedure DoBeforeConnect; procedure DoAfterConnect; procedure DoError(ErrorCode: Integer); constructor Create(AOwner: TComponent); override; published { published declarations } property Parent: TControl read FParent write FParent; property Left: Integer read FLeft write FLeft; property Top: Integer read FTop write FTop; property Active: Boolean read FActive write SetActive; property DataNode: String read FDataNode write FDataNode; property URI: String read FURI write FURI; property AfterConnect: TNotifyEvent read FAfterConnect write FAfterConnect; property BeforeConnect: TNotifyEvent read FBeforeConnect write FBeforeConnect; property OnConnectError: TConnectErrorEvent read FOnConnectError write FOnConnectError; end; type { TDataSet } TDataSet = class(TBaseJSONDataSet) private { private declarations } FConnection: TConnection; FParent: TControl; FLeft: Integer; FTop: Integer; protected { protected declarations } procedure SetConnection(Value: TConnection); Function CreateFieldMapper : TJSONFieldMapper; override; public { public declarations } published { published declarations } // Can be set directly if the dataset is closed. If metadata is set, it must match the data. Property Rows; property Parent: TControl read FParent write FParent; property Left: Integer read FLeft write FLeft; property Top: Integer read FTop write FTop; property Connection: TConnection read FConnection write SetConnection; end; type { TDBLabel } TDBLabel = class(TWLabel) private { private declarations } FDataLink: TFieldDataLink; procedure DataUpdate(Sender: TObject); procedure DataChange(Sender: TObject); procedure ActiveChange(Sender: TObject); procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); function GetDataSource: TDataSource; function GetDataField: String; protected { protected declarations } function CheckDataSet: boolean; //function GetDisplayText: String; override; //procedure CreateInitialize; override; public { public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; published { published declarations } property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; end; implementation { TDBLabel } procedure TDBLabel.SetDataField(const Value: string); begin FDataLink.FFieldName := Value; FDataLink.UpdateField(); end; procedure TDBLabel.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; end; function TDBLabel.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TDBLabel.GetDataField: String; begin Result := FDataLink.FFieldName; end; function TDBLabel.CheckDataSet: boolean; begin Result := false; if (((assigned(DataSource)) and DataSource.Enabled) and (GetDataField() <> '')) then begin if ((assigned(FDataLink.Dataset)) and FDataLink.Dataset.Active) then result := true; end; end; (*function TDBLabel.GetDisplayText: String; begin if (not CheckDataSet()) then Result := '' else Result := inherited GetDisplayText end;*) procedure TDBLabel.DataUpdate(Sender: TObject); begin // empty; end; procedure TDBLabel.DataChange(Sender: TObject); begin if (not(assigned(FDataLink.Dataset))) then exit; if (not(assigned(FDataLink.FField))) then FDataLink.UpdateField(); Caption := (FDataLink.FField.DisplayText); end; procedure TDBLabel.ActiveChange(Sender: TObject); begin if (assigned(FDataLink.Dataset)) then begin if (not FDataLink.Dataset.Active or not DataSource.Enabled) then Caption := ('') else DataChange(Self); end; end; (*procedure TDBLabel.CreateInitialize; begin inherited; //CreateInitialize; FDataLink := TFieldDataLink.Create; FDataLink.FOnUpdateData := @DataUpdate; FDataLink.FOnDataChange := @DataChange; FDataLink.FOnActiveChange := @ActiveChange; end; *) constructor TDBLabel.Create(Owner: TComponent); begin inherited Create(Owner); FDataLink := TFieldDataLink.Create; FDataLink.FOnUpdateData := @DataUpdate; FDataLink.FOnDataChange := @DataChange; FDataLink.FOnActiveChange := @ActiveChange; end; destructor TDBLabel.Destroy; begin FDataLink.Free; inherited; //Destroy; end; { TFieldDataLink } procedure TFieldDataLink.UpdateField; begin FField := nil; if (((assigned(DataSource)) and (assigned(DataSource.DataSet))) and (FFieldName <> '')) then if (DataSource.DataSet.Active) then FField := DataSource.DataSet.FieldByName(FFieldName); end; procedure TFieldDataLink.ActiveChanged; begin //inherited; //ActiveChanged; if (assigned(FOnActiveChange)) then FOnActiveChange(Self); end; procedure TFieldDataLink.RecordChanged(Field: TField); begin //inherited; //RecordChanged(Field); if ((Field = nil) or (Field = FField)) then if (assigned(FOnDataChange)) then FOnDataChange(Self); end; procedure TFieldDataLink.UpdateData; begin //inherited; //UpdateData; if (FModified) then begin if ((assigned(FField)) and (assigned(FOnUpdateData))) then FOnUpdateData(Self); FModified := false; end; end; procedure TFieldDataLink.Modified; begin FModified := true; end; { TConnection } procedure TConnection.SetActive(AValue: boolean); begin if ((FURI <> '') and AValue) then begin DoBeforeConnect(); FActive := AValue; FReq := TJSXMLHttpRequest.new; FReq.addEventListener('load', @onLoad); FReq.open('GET',FURI,true); FReq.send(); end; end; function TConnection.onLoad(Event: TEventListenerEvent): boolean; var J: JSValue; JA: JSValue; begin if (FReq.status = 200) then begin J := TJSJSON.parse(FReq.responseText); JA := TJSObject(J).Properties[FDataNode]; DoAfterConnect(); if (assigned(FDS)) then begin FDS.Rows := TJSArray(JA); FDS.Open(); end else DoError(FReq.status); end; end; procedure TConnection.RegisterDataSet(value: TDataSet); begin FDS := value; end; procedure TConnection.DoBeforeConnect; begin if (assigned(FBeforeConnect)) then FBeforeConnect(Self); end; procedure TConnection.DoAfterConnect; begin if (assigned(FAfterConnect)) then FAfterConnect(Self); end; procedure TConnection.DoError(ErrorCode: Integer); begin if (assigned(FOnConnectError)) then FOnConnectError(Self, ErrorCode); end; constructor TConnection.Create(AOwner: TComponent); begin inherited; //Create(AOwner); FDS := nil; end; { TDataSet } procedure TDataSet.SetConnection(Value: TConnection); begin if (assigned(Value)) then Value.RegisterDataSet(Self); end; Function TDataSet.CreateFieldMapper : TJSONFieldMapper; begin Result := TJSONObjectFieldMapper.Create; end; end.
unit E_CurRate; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, CurrEdit, RxLookup, Mask, ToolEdit, Db, DBTables, uCommonForm, OilStd,uOilQuery,Ora, uOilStoredProc, MemDS, DBAccess; type TE_CurRateForm = class(TCommonForm) Panel2: TPanel; bbOk: TBitBtn; bbCancel: TBitBtn; Panel1: TPanel; deDate: TDateEdit; Label1: TLabel; Label2: TLabel; calcRate: TRxCalcEdit; Label3: TLabel; qCurrency: TOilQuery; qCurrencyID: TFloatField; qCurrencyNAME: TStringField; q: TOilQuery; qWork: TOilQuery; cbCurrency: TComboBox; procedure TestSave(Id_CurRate: integer; p_Date: TDateTime; p_CurrencyId: integer; p_Rate: real; var Id_CurRate_New: integer; var bNext: boolean); procedure Save(Id: integer; p_Date: TDateTime; p_CurrencyId: integer; p_Rate: real); procedure bbOkClick(Sender: TObject); private public Id: integer; end; var E_CurRateForm: TE_CurRateForm; bNext: boolean; procedure AddCurRate; procedure EditCurRate(p_ID, p_INST: integer); procedure OpenCurrency(cb: TComboBox; ID: integer=0; CbEnabled: boolean=false); implementation {$R *.DFM} uses E_Var, UDbFunc, Main; //============================================================================== procedure AddCurRate; var F: TE_CurRateForm; begin F := TE_CurRateForm.Create(Application); F.deDate.Date := Date; OpenCurrency(F.cbCurrency, 2, false); F.Id := 0; F.ShowModal; F.Free; end; //============================================================================== procedure EditCurRate(p_ID, p_INST:integer); var F: TE_CurRateForm; begin F := TE_CurRateForm.Create(Application); F.q.ParamByName('id').Value := p_ID; F.q.ParamByName('inst').Value := p_INST; F.q.Open; F.deDate.Date := F.q.FieldByName('date_').Value; OpenCurrency(F.cbCurrency, F.q.FieldByName('currency_id').AsInteger, false); F.calcRate.Value := F.q.FieldByName('rate').AsFloat; F.Id := F.q.FieldByName('id').AsInteger; F.q.Close; F.ShowModal; F.Free; end; //============================================================================== // заносимо компонент TComboBox, на якого чіпляти всі курси валют і можемо занести позицію, // яку нам треба вибрати по замовчуванню procedure OpenCurrency(cb: TComboBox; ID: integer=0; CbEnabled: boolean=false); var E_CurRateForm: TE_CurRateForm; begin E_CurRateForm := TE_CurRateForm.Create(Application); E_CurRateForm.qCurrency.Open; cb.Clear; while not E_CurRateForm.qCurrency.Eof do begin cb.Items.Add(E_CurRateForm.qCurrencyName.AsString); E_CurRateForm.qCurrency.Next; end; if ID <> 0 then begin cb.ItemIndex := ID - 1; cb.Text := cb.Items.Strings[ID - 1]; cb.Enabled := CbEnabled; cb.Tag := ID; end; end; //============================================================================== procedure TE_CurRateForm.TestSave(Id_CurRate: integer; p_Date: TDateTime; p_CurrencyId: integer; p_Rate: real; var Id_CurRate_New: integer; var bNext: boolean); begin bNext := true; if p_Rate = 0 then begin MessageDlg(TranslateText('Не введен курс!'), mtError, [mbOk], 0); bNext := false; end; if (Id_CurRate = 0) and (bNext = true) then begin if qWork.Active then qWork.Close; qWork.ParamByName('currency_id').AsInteger := p_CurrencyId; qWork.ParamByName('date_').Value := p_Date; qWork.ParamByName('inst').Value := INST; qWork.Open; if qWork.RecordCount > 0 then if qWork.FieldByName('rate').Value = p_Rate then begin MessageDlg(TranslateText('Курс за ')+ DateToStr(p_Date) +TranslateText(' уже есть и совпадает с вводимым!'), mtError, [mbOk], 0); bNext := false; end else if MessageDlg(TranslateText('Курс за ')+ DateToStr(p_Date) +TranslateText(' уже вводился и равен ') + qWork.FieldByName('rate').AsString + #13#10 + TranslateText('Отредактировать?'), mtWarning, [mbYes, mbNo], 0) = mrNo then begin MessageDlg(TranslateText('Редактирование отменено!'), mtError, [mbOk], 0); bNext := false; end else begin Id_CurRate_New := qWork.FieldByName('Id').AsInteger; bNext := true; end; end; end; //============================================================================== procedure TE_CurRateForm.Save(Id: integer; p_Date: TDateTime; p_CurrencyId: integer; p_Rate: real); begin InsOrUpdRecord('E_CURRENCY_RATE', ['ID', Id, 'INST', INST, 'STATE', 'Y', 'DATE_', p_Date, 'CURRENCY_ID', p_CurrencyId, 'RATE', p_Rate ]); CommitSqlOra; end; //============================================================================== procedure TE_CurRateForm.bbOkClick(Sender: TObject); begin TestSave(Id, deDate.Date, cbCurrency.Tag, calcRate.Value, Id, bNext); if bNext then Save(Id, deDate.Date, cbCurrency.Tag, calcRate.Value) else exit; if DayOfWeek(deDate.Date) = 6 then if MessageDlg(TranslateText('Следующие два дня - выходные. ')+#13#10+TranslateText('Перенести на них курс автоматически?'), mtInformation, [mbYes,mbNo], 0) = mrYes then begin Id := 0; TestSave(Id, deDate.Date+1, cbCurrency.Tag, calcRate.Value, Id, bNext); if bNext then Save(Id, deDate.Date+1, cbCurrency.Tag, calcRate.Value); Id := 0; TestSave(Id, deDate.Date+2, cbCurrency.Tag, calcRate.Value, Id, bNext); if bNext then Save(Id, deDate.Date+2, cbCurrency.Tag, calcRate.Value); end; ModalResult := mrOk; end; //============================================================================== end.
unit Font8x8; { Модуль содержит русский (+английский шрифт, потом) размером 8х8. Сделано в форме массива, каждая буква имеет символьное имя. Этот модуль не предназначен для компиляции в составе Font_Creator } interface type /// Тип описывает литеры цифр tDig = class public d0: array[0..7] of byte = (0, 62, 67, 69, 73, 81, 97, 62); d1: array[0..7] of byte = (0, 1, 3, 5, 1, 1, 1, 1); d2: array[0..7] of byte = (0, 62, 65, 2, 4, 8, 48, 127); d3: array[0..7] of byte = (0, 127, 2, 28, 2, 1, 65, 62); d4: array[0..7] of byte = (0, 3, 5, 9, 17, 33, 127, 1); d5: array[0..7] of byte = (0, 127, 64, 126, 1, 1, 65, 62); d6: array[0..7] of byte = (0, 62, 64, 64, 126, 65, 65, 62); d7: array[0..7] of byte = (0, 127, 1, 2, 4, 8, 8, 8); d8: array[0..7] of byte = (0, 62, 65, 65, 62, 65, 65, 62); d9: array[0..7] of byte = (0, 62, 65, 65, 66, 1, 1, 62); end; /// Специальные литеры tSpez = class public /// пробел space: array[0..7] of byte = (0, 0, 0, 0, 0, 0, 0, 0); /// подчёркивание strike: array[0..7] of byte = (0, 0, 0, 0, 0, 0, 0, 62); /// минус minus: array[0..7] of byte = (0, 0, 0, 0, 127, 0, 0, 0); /// плюс plus: array[0..7] of byte = (0, 8, 8, 8, 127, 8, 8, 8); /// умножить multi: array[0..7] of byte = (0, 0, 42, 28, 62, 28, 42, 0); /// деление _div: array[0..7] of byte = (0, 8, 0, 0, 127, 0, 0, 8); /// запятая comma: array[0..7] of byte = (0, 0, 7, 7, 7, 1, 1, 3); /// точка dot: array[0..7] of byte = (0, 0, 0, 0, 0, 28, 28, 28); /// левая круглая скобка lrb: array[0..7] of byte = (0, 4, 8, 24, 24, 24, 8, 4); /// правая круглая скобка rrb: array[0..7] of byte = (0, 16, 8, 12, 12, 12, 8, 16); /// левая квадратная скобка lsb: array[0..7] of byte = (0, 28, 16, 16, 16, 16, 16, 28); /// правая квадратная скобка rsb: array[0..7] of byte = (0, 28, 4, 4, 4, 4, 4, 28); /// двойные кавычки dqt: array[0..7] of byte = (0, 102, 102, 102, 0, 0, 0, 0); /// одиночные кавычки sqt: array[0..7] of byte = (0, 24, 24, 24, 0, 0, 0, 0); /// апостроф apo: array[0..7] of byte = (0, 96, 120, 60, 12, 0, 0, 0); /// тильда tilda: array[0..7] of byte = (0, 0, 0, 0, 50, 76, 0, 0); /// восклицательный знак hlp_akk: array[0..7] of byte = (0, 0, 24, 24, 24, 24, 0, 24); /// решётка bang: array[0..7] of byte = (0, 18, 127, 18, 36, 127, 36, 0); /// номер numer: array[0..7] of byte = (0, 72, 106, 109, 106, 88, 91, 72); /// доллар dol: array[0..7] of byte = (0, 62, 73, 72, 62, 9, 73, 62); /// точка с запятой cdot: array[0..7] of byte = (0, 28, 28, 0, 28, 28, 4, 12); /// процент percent: array[0..7] of byte = (0, 33, 82, 36, 8, 18, 37, 66); /// двоеточие ddot: array[0..7] of byte = (0, 24, 24, 0, 0, 0, 24, 24); /// амперсанд amp: array[0..7] of byte = (0, 24, 36, 40, 16, 42, 36, 27); /// вопрос qst: array[0..7] of byte = (0, 30, 33, 2, 4, 8, 0, 8); /// равно equ: array[0..7] of byte = (0, 0, 127, 0, 0, 127, 0, 0); /// слэш hlp_slh: array[0..7] of byte = (0, 1, 2, 4, 8, 16, 32, 64); /// обратный слэш bslh: array[0..7] of byte = (0, 64, 32, 16, 8, 4, 2, 1); /// меньше lequ: array[0..7] of byte = (0, 3, 12, 48, 64, 48, 12, 3); /// больше requ: array[0..7] of byte = (0, 96, 24, 6, 1, 6, 24, 96); /// степень exp: array[0..7] of byte = (0, 8, 20, 34, 65, 0, 0, 0); /// левая фигурная скобка lfb: array[0..7] of byte = (0, 12, 16, 16, 112, 16, 16, 12); /// правая фигурная скобка rfb: array[0..7] of byte = (0, 48, 8, 8, 14, 8, 8, 48); end; /// Английские буквы tLetEn = class public bA: array[0..7] of byte = (0, 8, 20, 34, 65, 127, 65, 65); sA: array[0..7] of byte = (0, 0, 30, 1, 31, 33, 35, 29); bB: array[0..7] of byte = (0, 126, 65, 65, 126, 65, 65, 126); sB: array[0..7] of byte = (0, 0, 32, 32, 62, 33, 33, 30); bC: array[0..7] of byte = (0, 62, 65, 64, 64, 64, 65, 62); sC: array[0..7] of byte = (0, 0, 30, 33, 32, 32, 33, 30); bD: array[0..7] of byte = (0, 124, 66, 65, 65, 65, 66, 124); sD: array[0..7] of byte = (0, 0, 1, 1, 31, 33, 33, 31); bE: array[0..7] of byte = (0, 127, 64, 64, 124, 64, 64, 127); sE: array[0..7] of byte = (0, 0, 30, 33, 38, 56, 33, 30); bF: array[0..7] of byte = (0, 127, 64, 64, 124, 64, 64, 64); sF: array[0..7] of byte = (0, 0, 6, 9, 8, 28, 8, 8); bG: array[0..7] of byte = (0, 62, 64, 64, 79, 65, 65, 62); sG: array[0..7] of byte = (0, 0, 30, 33, 33, 31, 1, 30); bH: array[0..7] of byte = (0, 65, 65, 65, 127, 65, 65, 65); sH: array[0..7] of byte = (0, 0, 32, 32, 62, 33, 33, 33); bI: array[0..7] of byte = (0, 24, 24, 24, 24, 24, 24, 24); sI: array[0..7] of byte = (0, 0, 12, 0, 12, 12, 12, 12); bJ: array[0..7] of byte = (0, 127, 1, 1, 1, 1, 65, 62); sJ: array[0..7] of byte = (0, 0, 12, 0, 12, 12, 44, 28); bK: array[0..7] of byte = (0, 65, 66, 68, 120, 68, 66, 65); sK: array[0..7] of byte = (0, 0, 33, 38, 56, 36, 34, 33); bL: array[0..7] of byte = (0, 64, 64, 64, 64, 64, 64, 127); sL: array[0..7] of byte = (0, 0, 16, 16, 16, 16, 16, 14); bM: array[0..7] of byte = (0, 65, 99, 85, 73, 65, 65, 65); sM: array[0..7] of byte = (0, 0, 52, 42, 42, 42, 42, 42); bN: array[0..7] of byte = (0, 65, 97, 81, 73, 69, 67, 65); sN: array[0..7] of byte = (0, 0, 46, 49, 33, 33, 33, 33); bO: array[0..7] of byte = (0, 62, 65, 65, 65, 65, 65, 62); sO: array[0..7] of byte = (0, 0, 30, 33, 33, 33, 33, 30); bP: array[0..7] of byte = (0, 126, 65, 65, 65, 126, 64, 64); sP: array[0..7] of byte = (0, 0, 62, 33, 33, 62, 32, 32); bQ: array[0..7] of byte = (0, 60, 66, 66, 66, 74, 70, 61); sQ: array[0..7] of byte = (0, 0, 30, 34, 34, 30, 3, 2); bR: array[0..7] of byte = (0, 126, 65, 65, 126, 80, 76, 67); sR: array[0..7] of byte = (0, 0, 38, 41, 40, 48, 32, 32); bS: array[0..7] of byte = (0, 62, 65, 64, 62, 1, 65, 62); sS: array[0..7] of byte = (0, 0, 30, 33, 28, 2, 33, 30); bT: array[0..7] of byte = (0, 127, 8, 8, 8, 8, 8, 8); sT: array[0..7] of byte = (0, 0, 8, 8, 28, 8, 9, 6); bU: array[0..7] of byte = (0, 65, 65, 65, 65, 65, 65, 62); sU: array[0..7] of byte = (0, 0, 34, 34, 34, 34, 34, 29); bV: array[0..7] of byte = (0, 65, 65, 34, 34, 20, 20, 8); sV: array[0..7] of byte = (0, 0, 34, 34, 20, 20, 8, 8); bW: array[0..7] of byte = (0, 73, 73, 85, 85, 54, 34, 34); sW: array[0..7] of byte = (0, 0, 42, 42, 42, 42, 20, 20); bX: array[0..7] of byte = (0, 65, 34, 20, 8, 20, 34, 65); sX: array[0..7] of byte = (0, 0, 33, 18, 12, 12, 18, 33); bY: array[0..7] of byte = (0, 65, 34, 20, 8, 8, 8, 8); sY: array[0..7] of byte = (0, 0, 34, 34, 26, 6, 34, 28); bZ: array[0..7] of byte = (0, 127, 2, 4, 8, 16, 32, 127); sZ: array[0..7] of byte = (0, 0, 63, 2, 4, 8, 16, 63); end; /// Русские буквы tLetRu = class public /// Литера А bA: array[0..7] of byte = (0, 3, 5, 9, 17, 63, 65, 65); /// Литера а sA: array[0..7] of byte = (0, 0, 28, 2, 30, 34, 34, 29); /// Литера Б bB: array[0..7] of byte = (0, 126, 64, 126, 65, 65, 65, 126); /// Литера б sB: array[0..7] of byte = (0, 1, 30, 32, 62, 33, 33, 30); /// Литера В bW: array[0..7] of byte = (0, 124, 66, 68, 126, 65, 65, 126); /// Литера в sW: array[0..7] of byte = (0, 0, 30, 33, 62, 33, 33, 30); /// Литера Г bG: array[0..7] of byte = (0, 127, 65, 64, 64, 64, 64, 64); /// Литера г sG: array[0..7] of byte = (0, 0, 30, 33, 6, 24, 33, 30); /// Литера Д bD: array[0..7] of byte = (0, 62, 18, 18, 18, 34, 127, 65); /// Литера д sD: array[0..7] of byte = (0, 0, 14, 10, 10, 18, 63, 63); /// Литера Е bE: array[0..7] of byte = (0, 127, 64, 124, 64, 64, 64, 127); /// Литера е sE: array[0..7] of byte = (0, 0, 30, 33, 63, 32, 33, 30); /// Литера Ё bE2: array[0..7] of byte = (0, 18, 127, 64, 124, 64, 64, 127); /// Литера ё sE2: array[0..7] of byte = (0, 18, 30, 33, 63, 32, 33, 30); /// Литера Ж bZh: array[0..7] of byte = (0, 73, 42, 28, 42, 73, 73, 73); /// Литера ж sZh: array[0..7] of byte = (0, 0, 21, 21, 14, 21, 21, 21); /// Литера З bZ: array[0..7] of byte = (0, 62, 65, 14, 1, 1, 65, 62); /// Литера з sZ: array[0..7] of byte = (0, 0, 30, 33, 14, 1, 33, 30); /// Литера И bI: array[0..7] of byte = (0, 65, 67, 69, 73, 81, 97, 65); /// Литера и sI: array[0..7] of byte = (0, 0, 33, 35, 37, 41, 49, 33); /// Литера Й bI2: array[0..7] of byte = (0, 89, 65, 67, 69, 73, 81, 97); /// Литера й sI2: array[0..7] of byte = (0, 0, 12, 33, 35, 37, 41, 49); /// Литера К bK: array[0..7] of byte = (0, 67, 76, 112, 72, 68, 66, 65); /// Литера к sK: array[0..7] of byte = (0, 0, 33, 34, 60, 34, 33, 33); /// Литера Л bL: array[0..7] of byte = (0, 15, 17, 17, 17, 17, 17, 97); /// Литера л sL: array[0..7] of byte = (0, 0, 15, 17, 17, 17, 17, 33); /// Литера М bM: array[0..7] of byte = (0, 65, 99, 99, 85, 85, 73, 73); /// Литера м sM: array[0..7] of byte = (0, 0, 17, 27, 27, 31, 21, 21); /// Литера Н bN: array[0..7] of byte = (0, 65, 65, 65, 127, 65, 65, 65); /// Литера н sN: array[0..7] of byte = (0, 0, 33, 33, 63, 33, 33, 33); /// Литера О bO: array[0..7] of byte = (0, 62, 65, 65, 65, 65, 65, 62); /// Литера о sO: array[0..7] of byte = (0, 0, 30, 33, 33, 33, 33, 30); /// Литера П bP: array[0..7] of byte = (0, 127, 65, 65, 65, 65, 65, 65); /// Литера п sP: array[0..7] of byte = (0, 0, 63, 33, 33, 33, 33, 33); /// Литера Р bR: array[0..7] of byte = (0, 126, 65, 65, 65, 126, 64, 64); /// Литера р sR: array[0..7] of byte = (0, 0, 62, 63, 33, 62, 32, 32); /// Литера С bS: array[0..7] of byte = (0, 62, 65, 64, 64, 64, 65, 62); /// Литера с sS: array[0..7] of byte = (0, 0, 30, 33, 32, 32, 33, 30); /// Литера Т bT: array[0..7] of byte = (0, 127, 8, 8, 8, 8, 8, 8); /// Литера т sT: array[0..7] of byte = (0, 0, 31, 4, 4, 4, 4, 4); /// Литера У bU: array[0..7] of byte = (0, 65, 65, 65, 63, 1, 65, 62); /// Литера у sU: array[0..7] of byte = (0, 0, 33, 33, 31, 1, 33, 30); /// Литера Ф bF: array[0..7] of byte = (0, 62, 73, 73, 73, 62, 8, 8); /// Литера ф sF: array[0..7] of byte = (0, 0, 14, 21, 21, 21, 14, 4); /// Литера Х bKh: array[0..7] of byte = (0, 65, 34, 20, 8, 20, 34, 65); /// Литера А sKh: array[0..7] of byte = (0, 0, 33, 18, 12, 12, 18, 33); /// Литера Ц bTc: array[0..7] of byte = (0, 66, 66, 66, 66, 66, 127, 1); /// Литера ц sTc: array[0..7] of byte = (0, 0, 34, 34, 34, 34, 31, 1); /// Литера Ч bCh: array[0..7] of byte = (0, 65, 65, 65, 63, 1, 1, 1); /// Литера ч sCh: array[0..7] of byte = (0, 0, 33, 33, 33, 31, 1, 1); /// Литера Ш bSh: array[0..7] of byte = (0, 73, 73, 73, 73, 73, 73, 127); /// Литера ш sSh: array[0..7] of byte = (0, 21, 21, 21, 21, 21, 21, 31); /// Литера Щ bShh: array[0..7] of byte = (0, 84, 84, 84, 84, 84, 126, 2); /// Литера щ sShh: array[0..7] of byte = (0, 0, 42, 42, 42, 42, 63, 1); /// Литера Ъ bHz: array[0..7] of byte = (0, 96, 32, 32, 62, 33, 33, 62); /// Литера ъ sHz: array[0..7] of byte = (0, 0, 48, 16, 30, 17, 17, 30); /// Литера Ы bY: array[0..7] of byte = (0, 65, 65, 65, 121, 69, 69, 121); /// Литера ы sY: array[0..7] of byte = (0, 0, 33, 33, 57, 37, 37, 57); /// Литера Ь bSz: array[0..7] of byte = (0, 64, 64, 64, 126, 65, 65, 126); /// Литера ь sSz: array[0..7] of byte = (0, 0, 32, 32, 62, 33, 33, 62); /// Литера Э bEh: array[0..7] of byte = (0, 62, 65, 1, 31, 1, 65, 62); /// Литера э sEh: array[0..7] of byte = (0, 0, 30, 33, 15, 1, 33, 30); /// Литера Ю bYu: array[0..7] of byte = (0, 78, 81, 81, 113, 81, 81, 78); /// Литера ю sYu: array[0..7] of byte = (0, 0, 38, 41, 57, 41, 41, 38); /// Литера Я bJa: array[0..7] of byte = (0, 63, 65, 65, 63, 9, 17, 97); /// Литера я sJa: array[0..7] of byte = (0, 0, 31, 33, 33, 31, 9, 49); end; implementation begin end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [GUIAS_ACUMULADAS] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit GuiasAcumuladasVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TGuiasAcumuladasVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FGPS_TIPO: String; FGPS_COMPETENCIA: String; FGPS_VALOR_INSS: Extended; FGPS_VALOR_OUTRAS_ENT: Extended; FGPS_DATA_PAGAMENTO: TDateTime; FIRRF_COMPETENCIA: String; FIRRF_CODIGO_RECOLHIMENTO: Integer; FIRRF_VALOR_ACUMULADO: Extended; FIRRF_DATA_PAGAMENTO: TDateTime; FPIS_COMPETENCIA: String; FPIS_VALOR_ACUMULADO: Extended; FPIS_DATA_PAGAMENTO: TDateTime; //Transientes published property Id: Integer read FID write FID; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property GpsTipo: String read FGPS_TIPO write FGPS_TIPO; property GpsCompetencia: String read FGPS_COMPETENCIA write FGPS_COMPETENCIA; property GpsValorInss: Extended read FGPS_VALOR_INSS write FGPS_VALOR_INSS; property GpsValorOutrasEnt: Extended read FGPS_VALOR_OUTRAS_ENT write FGPS_VALOR_OUTRAS_ENT; property GpsDataPagamento: TDateTime read FGPS_DATA_PAGAMENTO write FGPS_DATA_PAGAMENTO; property IrrfCompetencia: String read FIRRF_COMPETENCIA write FIRRF_COMPETENCIA; property IrrfCodigoRecolhimento: Integer read FIRRF_CODIGO_RECOLHIMENTO write FIRRF_CODIGO_RECOLHIMENTO; property IrrfValorAcumulado: Extended read FIRRF_VALOR_ACUMULADO write FIRRF_VALOR_ACUMULADO; property IrrfDataPagamento: TDateTime read FIRRF_DATA_PAGAMENTO write FIRRF_DATA_PAGAMENTO; property PisCompetencia: String read FPIS_COMPETENCIA write FPIS_COMPETENCIA; property PisValorAcumulado: Extended read FPIS_VALOR_ACUMULADO write FPIS_VALOR_ACUMULADO; property PisDataPagamento: TDateTime read FPIS_DATA_PAGAMENTO write FPIS_DATA_PAGAMENTO; //Transientes end; TListaGuiasAcumuladasVO = specialize TFPGObjectList<TGuiasAcumuladasVO>; implementation initialization Classes.RegisterClass(TGuiasAcumuladasVO); finalization Classes.UnRegisterClass(TGuiasAcumuladasVO); end.
unit BitmapRgn; (* * 양병규님이 공개해주신 소스를 조금 수정한 버전입니다. * 제거할 컬러의 위치 또는 컬러를 직접 지정할 수 있도록 하였습니다. procedure TfmSelectWhiteBoardTool.FormCreate(Sender: TObject); var Rgn : HRGN; begin Image.Picture.Bitmap.PixelFormat := pf32bit; Rgn := CreateBitmapRgn32(Image.Picture.Bitmap, clBlack); try SetWindowRgn(Handle, Rgn, true); finally DeleteObject(Rgn); end; end; *) interface uses Windows, Classes, SysUtils, Graphics; function CreateBitmapRgn(Bitmap:TBitmap; TransparentColorX,TransparentColorY:integer):HRGN; function CreateBitmapRgn32(Bitmap:TBitmap; TransparentColor:TColor):HRGN; implementation const DEFAULTRECTCOUNT = 50; procedure GetTransparentPixel(var ATransparentPixel:pointer; ABitmap:TBitmap; AX,AY:integer); var pByte : ^byte; PicxelSize : integer; begin GetMem(ATransparentPixel, 4); case ABitmap.PixelFormat of pf8Bit : PicxelSize := 1; pf16Bit: PicxelSize := 2; pf24Bit: PicxelSize := 3; else PicxelSize := 4; end; pByte := ABitmap.ScanLine[0]; Dec(pByte, (AY*ABitmap.Width + AX)*PicxelSize); Move(pByte^, ATransparentPixel^, PicxelSize); end; function CreateBitmapRgn(Bitmap: TBitmap; TransparentColorX,TransparentColorY:integer): HRGN; type TPixels08 = array[0..0] of Byte; TPixels16 = array[0..0] of Word; TPixels24 = array[0..0] of TRGBTriple; TPixels32 = array[0..0] of Cardinal; var PixelFormat: TPixelFormat; Pixels: Pointer; TransparentPixel: Pointer; RegionData: PRgnData; RegionBufferSize: Integer; RectCount, NewRectLeft: Integer; X, Y: Integer; function IsTransparent(X: Integer): Boolean; begin case PixelFormat of pf8Bit : Result := TPixels08( Pixels^ )[ X ] = PByte( TransparentPixel )^; pf16Bit: Result := TPixels16( Pixels^ )[ X ] = PWord( TransparentPixel )^; pf24Bit: Result := ( TPixels24( Pixels^ )[ X ].rgbtRed = PRGBTriple( TransparentPixel )^.rgbtRed ) and ( TPixels24( Pixels^ )[ X ].rgbtGreen = PRGBTriple( TransparentPixel )^.rgbtGreen ) and ( TPixels24( Pixels^ )[ X ].rgbtBlue = PRGBTriple( TransparentPixel )^.rgbtBlue ); pf32Bit: Result := TPixels32( Pixels^ )[ X ] = PCardinal( TransparentPixel )^; else Result := False; end; end; procedure AddRect(LastCol: Boolean = False); type PRectBuffer = ^TRectBuffer; TRectBuffer = array[0..0] of TRect; begin if ( RegionBufferSize div SizeOf( TRect ) ) = RectCount then begin Inc( RegionBufferSize, SizeOf( TRect ) * DEFAULTRECTCOUNT ); ReallocMem( RegionData, SizeOf( TRgnDataHeader ) + RegionBufferSize + 3 ); end; if LastCol then Inc( X ); PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Left := NewRectLeft; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Top := Y; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Right := X; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Bottom := Y + 1; Inc( RectCount ); NewRectLeft := -1; end; begin PixelFormat := Bitmap.PixelFormat; Pixels := Bitmap.ScanLine[ 0 ]; GetTransparentPixel(TransparentPixel, Bitmap, TransparentColorX, TransparentColorY); RectCount := 0; RegionBufferSize := SizeOf( TRect ) * DEFAULTRECTCOUNT; GetMem( RegionData, SizeOf( TRgnDataHeader ) + RegionBufferSize + 3 ); try for Y := 0 to Bitmap.Height - 1 do begin Pixels := Bitmap.ScanLine[ Y ]; NewRectLeft := -1; for X := 0 to Bitmap.Width - 1 do if IsTransparent( X ) then begin if NewRectLeft >= 0 then AddRect; end else begin if NewRectLeft = -1 then NewRectLeft := X; if ( X = Bitmap.Width - 1 ) and ( NewRectLeft >= 0 ) then AddRect( True ); end; end; RegionData^.rdh.dwSize := SizeOf( TRgnDataHeader ); RegionData^.rdh.iType := RDH_RECTANGLES; RegionData^.rdh.nCount := RectCount; RegionData^.rdh.nRgnSize := RectCount * SizeOf( TRect ); Result := ExtCreateRegion( nil, RegionData^.rdh.dwSize + RegionData^.rdh.nRgnSize, RegionData^ ); finally FreeMem( RegionData ); FreeMem( TransparentPixel ); end; end; function CreateBitmapRgn32(Bitmap:TBitmap; TransparentColor:TColor):HRGN; var pPixel : PCardinal; TransparentPixel : Cardinal; RegionData: PRgnData; RegionBufferSize: Integer; RectCount, NewRectLeft: Integer; X, Y: Integer; procedure AddRect(LastCol: Boolean = False); type PRectBuffer = ^TRectBuffer; TRectBuffer = array[0..0] of TRect; begin if ( RegionBufferSize div SizeOf( TRect ) ) = RectCount then begin Inc( RegionBufferSize, SizeOf( TRect ) * DEFAULTRECTCOUNT ); ReallocMem( RegionData, SizeOf( TRgnDataHeader ) + RegionBufferSize + 3 ); end; if LastCol then Inc( X ); PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Left := NewRectLeft; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Top := Y; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Right := X; PRectBuffer( @RegionData^.Buffer )^[ RectCount ].Bottom := Y + 1; Inc( RectCount ); NewRectLeft := -1; end; begin if Bitmap.PixelFormat <> pf32bit then raise Exception.Create('CreateBitmapRgn32: pf32bit 포멧만 지원합니다.'); TransparentPixel := GetRValue(TransparentColor) shl 16 + GetGValue(TransparentColor) shl 8 + GetBValue(TransparentColor); RectCount := 0; RegionBufferSize := SizeOf(TRect) * DEFAULTRECTCOUNT; GetMem(RegionData, SizeOf(TRgnDataHeader) + RegionBufferSize + 3); try for Y := 0 to Bitmap.Height - 1 do begin pPixel := Bitmap.ScanLine[Y]; NewRectLeft := -1; for X := 0 to Bitmap.Width - 1 do begin if pPixel^ = TransparentPixel then begin if NewRectLeft >= 0 then AddRect; end else begin if NewRectLeft = -1 then NewRectLeft := X; if ( X = Bitmap.Width - 1 ) and ( NewRectLeft >= 0 ) then AddRect( True ); end; Inc(pPixel); end end; RegionData^.rdh.dwSize := SizeOf( TRgnDataHeader ); RegionData^.rdh.iType := RDH_RECTANGLES; RegionData^.rdh.nCount := RectCount; RegionData^.rdh.nRgnSize := RectCount * SizeOf( TRect ); Result := ExtCreateRegion( nil, RegionData^.rdh.dwSize + RegionData^.rdh.nRgnSize, RegionData^ ); finally FreeMem( RegionData ); end; end; end.
unit SpecFunX; {Special functions (extended precision)} interface {$i std.inc} {$ifdef BIT16} {$N+} {$endif} uses sfBasic; {Basic common code} (************************************************************************* DESCRIPTION : Special functions (extended precision) REQUIREMENTS : TP5.5-7, D2-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REMARK : The unit can be compiled with TP5 but some functions generate invalid operations due to TP5's brain-damaged usage of the FPU REFERENCES : See unit sfBasic Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 15.01.10 W.Ehrhardt Initial version: lngammax 0.11 17.01.10 we invgammax 0.12 18.01.10 we psix 0.13 18.01.10 we lnbetax 0.14 18.01.10 we betax 0.15 20.01.10 we Elliptic integrals (Carlson style) 0.16 21.01.10 we Elliptic integrals (Bulirsch style) 0.17 23.01.10 we Elliptic integrals (Maple style) 0.18 23.01.10 we sfc_signgammax returns extended 0.19 23.01.10 we agmx 0.20 24.01.10 we sncndnx 0.21 24.01.10 we erfx, erfcx 0.22 24.01.10 we normstd_pdfx, normstd_cdfx, normstd_invx 0.23 27.01.10 we gammax 0.24 10.02.10 we zetax, zeta1px 0.25 14.02.10 we e1x 0.26 15.02.10 we eix, lix 0.27 18.02.10 we enx 0.28 02.03.10 we chix, shix 0.29 03.03.10 we cix, six, ssix 0.30 06.03.10 we dawsonx 0.31 11.03.10 we erf_invx, erfc_invx 0.32 16.03.10 we dilogx 0.33 06.04.10 we bessel_j0x/j1x/jnx/y0x/y1x/ynx 0.34 06.04.10 we bessel_i0x/i0ex/i1x/i1ex 0.35 06.04.10 we bessel_k0x/k0ex/k1x/k1ex 0.36 08.04.10 we cinx, cinhx 0.37 10.04.10 we facx 0.38 11.04.10 we bessel_inx/knx 0.39 12.04.10 we ti2x 0.40 17.04.10 we gamma1pm1x 0.41 22.04.10 we cl2x 0.42 19.05.10 we Fresnelx 0.43 20.05.10 we LambertWx, LambertW1x 0.44 11.07.10 we ibetax, beta distribution functions 0.45 13.07.10 we t_pdfx, t_cdfx, t_invx 0.46 16.07.10 we f_pdfx, f_cdfx, f_invx 1.00.00 17.08.10 we Common version number after split 1.00.01 18.08.10 we gammastarx 1.00.02 24.08.10 we incgammax, igammapx, igammaqx 1.00.03 05.09.10 we inverse normalised incomplete gamma functions 1.00.04 05.09.10 we chi2_pdfx/cdfx/invx 1.00.05 07.09.10 we gamma_pdfx/cdfx/invx 1.00.06 10.09.10 we trigammax 1.00.07 15.09.10 we etax, etam1x, zetam1x 1.01.00 06.10.10 we dfacx 1.01.01 08.10.10 we legendre_px, legendre_qx, legendre_plmx 1.01.02 10.10.10 we chebyshev_tx, chebyshev_ux 1.01.03 11.10.10 we gegenbauer_cx 1.01.04 15.10.10 we jacobi_px 1.01.05 16.10.10 we hermite_hx 1.01.06 17.10.10 we laguerrex 1.01.07 19.10.10 we gamma_delta_ratiox, gamma_ratiox, pochhammerx 1.01.08 20.10.10 we laguerre_assx, laguerre_lx 1.01.09 20.10.10 we spherical_harmonicx 1.01.10 22.10.10 we zernike_rx 1.01.11 23.10.10 we zetahx 1.02.00 01.11.10 we bessel_jvx, bessel_yvx 1.02.01 04.11.10 we bessel_ivx, bessel_kvx 1.02.02 05.11.10 we Airy functions Ai, Ai', Bi, Bi' 1.02.03 06.11.10 we sph_bessel_jnx, sph_bessel_ynx 1.02.04 15.11.10 we bessel_ivex, bessel_kvex 1.03.00 03.12.10 we polylogx 1.03.01 05.12.10 we bernoullix, zetaintx 1.03.02 07.12.10 we debyex 1.03.03 15.12.10 we tetragammax, pentagammax, polygammax 1.03.04 31.12.10 we binomialx 1.04.00 12.02.11 we Goodwin-Staton integral gsix 1.04.01 13.02.11 we expint3x 1.04.02 14.02.11 we erfix 1.04.03 17.02.11 we RiemannRx 1.05.00 11.04.11 we Zero order Kelvin functions berx,beix,kerx,keix 1.05.01 13.04.11 we cauchy_pdfx/cdfx/invx 1.05.02 14.04.11 we normal_pdfx/cdfx/invx 1.05.03 14.04.11 we exp_pdfx/cdfx/invx 1.05.04 15.04.11 we lognormal_pdfx/cdfx/invx 1.05.05 16.04.11 we logistic_pdfx/cdfx/invx 1.05.06 16.04.11 we weibull_pdfx/cdfx/invx 1.05.07 17.04.11 we laplace_pdfx/cdfx/invx 1.05.08 17.04.11 we changed sh,sc to a,b in gamma_pdfx/cdfx/invx 1.05.09 19.04.11 we pareto_pdfx/cdfx/invx 1.05.10 20.04.11 we uniform_pdfx/cdfx/invx 1.06.00 08.05.11 we Struve functions struve_h0x/h1x/l0x,l1x 1.06.01 13.05.11 we theta2x,theta3x,theta4x 1.06.02 14.05.11 we theta1px 1.06.03 17.05.11 we jacobi_thetax 1.06.04 19.05.11 we EllipticModulusx 1.06.05 19.05.11 we replaced misleading kc by k in EllipticCKx and EllipticCEx 1.06.06 20.05.11 we EllipticNomex 1.07.00 01.06.11 we einx 1.07.01 04.06.11 we ellint_1x, ellint_2x 1.07.02 05.06.11 we comp_ellint_1x/2x/3x 1.07.03 06.06.11 we jacobi_amx 1.07.04 07.06.11 we jacobi_zetax 1.07.05 08.06.11 we ellint_3x 1.07.06 10.06.11 we erfcex 1.07.07 17.06.11 we jacobi_arcsnx/cnx/dnx 1.07.08 18.06.11 we jacobi_snx/cnx/dnx 1.07.09 23.06.11 we heuman_lambdax 1.08.00 03.08.11 we invgamma renamed to rgamma 1.09.00 05.10.11 we lngamma1px 1.10.00 10.12.11 we triangular_pdfx/cdfx/invx 1.10.01 14.12.11 we binomial_cdfx/pmfx 1.10.02 15.12.11 we poisson_cdfx/pmfx 1.10.03 16.12.11 we lnfacx 1.10.04 18.12.11 we negbinom_cdfx/pmfx 1.10.05 21.12.11 we primezetax 1.10.06 27.12.11 we hypergeo_cdfx/pmfx 1.10.07 28.12.11 we sph_bessel_inx, sph_bessel_inex 1.10.08 29.12.11 we sph_bessel_knx, sph_bessel_knex 1.11.00 05.02.12 we LerchPhix 1.11.01 06.02.12 we DirichletBetax 1.11.02 06.02.12 we DirichletLambdax 1.11.03 07.02.12 we LegendreChix 1.11.04 08.02.12 we polylogrx 1.12.00 22.03.12 we poch1x 1.12.01 11.04.12 we igammax (non-normalised upper incomplete gamma) 1.12.02 22.04.12 we igammalx (non-normalised lower incomplete gamma) 1.12.03 23.04.12 we lngammasx 1.12.04 27.04.12 we legendre_qlmx 1.12.05 16.05.12 we toroidal_qlmx 1.12.06 20.05.12 we toroidal_plmx 1.13.00 10.06.12 we fermi_diracx 1.13.01 13.06.12 we fermi_dirac_m05x/p05x 1.13.02 15.06.12 we dawson2x 1.13.03 16.06.12 we inerfcx 1.13.04 23.06.12 we geix 1.13.05 26.06.12 we erfgx 1.13.06 30.06.12 we igammatx 1.16.00 14.03.13 we Remaining Jacobi elliptic functions 1.16.01 25.03.13 we Remaining inverse Jacobi elliptic functions 1.16.02 28.03.13 we trilogx 1.17.00 11.04.13 we fermi_dirac_p15x 1.17.01 13.04.13 we k changed to longint in poisson_pmfx 1.17.02 14.04.13 we rayleigh_pdfx/cdfx/invx 1.17.03 17.04.13 we beta3x 1.17.04 19.04.13 we maxwell_pdfx/cdfx/invx 1.17.05 20.04.13 we evt1_pdfx/cdfx/invx 1.17.06 01.05.13 we FresnelCx/FresnelSx 1.18.00 09.05.13 we Airy/Scorer functions Gi/Hi 1.18.01 19.05.13 we hyperg_2F1x 1.18.02 22.05.13 we hyperg_2F1rx 1.18.03 24.05.13 we hyperg_1F1x, hyperg_1F1rx 1.18.03 30.05.13 we hyperg_ux 1.19.00 16.06.13 we Whittaker functions 1.19.01 27.06.13 we hyperg_0F1x 1.19.02 01.07.13 we hyperg_0F1rx 1.20.00 15.08.13 we kumaraswamy_pdfx/cdfx/invx 1.20.01 18.08.13 we erf_px, erf_qx, erf_zx 1.21.00 11.09.13 we Bernoulli polynomials bernpolyx 1.21.01 17.09.13 we chebyshev_vx/wx 1.21.02 24.09.13 we cosintx, sinintx 1.21.03 25.09.13 we BatemanGx 1.22.00 19.10.13 we moyal_pdfx/cdfx/invx 1.22.01 23.10.13 we EllipticKimx,EllipticECimx 1.23.00 26.12.13 we fermi_dirac_p25x 1.25.00 01.05.14 we harmonicx 1.25.01 03.05.14 we harmonic2x 1.25.02 04.05.14 we zipf_pmfx/cdfx 1.26.00 24.05.14 we li_invx 1.26.01 30.05.14 we lobachevsky_cx/sx 1.26.02 02.06.14 we fibpolyx, lucpolyx 1.26.03 05.06.14 we levy_pdfx/cdfx/invx 1.27.00 22.06.14 we lngamma_invx 1.27.01 25.06.14 we psi_invx 1.27.02 02.07.14 we ibeta_invx 1.27.03 12.07.14 we CylinderDx, CylinderUx, HermiteHx 1.28.00 17.08.14 we catalanx 1.28.01 19.08.14 we CylinderVx 1.31.00 23.12.14 we invgamma_pdfx/cdfx/invx 1.31.01 26.12.14 we logseries_cdfx/pmfx: logarithmic (series) distribution 1.31.02 03.01.15 we wald_cdfx/pdfx/invx 1.31.03 09.01.15 we Euler numbers 1.32.00 25.01.15 we ei_invx 1.32.01 28.03.15 we comp_ellint_dx, ellint_dx 1.33.00 04.06.15 we keplerx 1.33.01 10.06.15 we struve_hx, struve_lx 1.33.02 19.06.15 we airy_aisx, airy_bisx 1.33.03 22.06.15 we ell_rgx 1.36.00 26.09.15 we lemniscate functions sin_lemnx, cos_lemnx ***************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2009-2015 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) const SpecFunX_Version = SF_BaseVersion+'-X'; {#Z+} {---------------------------------------------------------------------------} {--------------------------- Bessel functions ------------------------------} {---------------------------------------------------------------------------} {#Z-} function airy_aix(x: extended): extended; {-Return the Airy function Ai(x)} function airy_aipx(x: extended): extended; {-Return the Airy function Ai'(x)} function airy_aisx(x: extended): extended; {-Return the scaled Airy function Ai(x) if x <= 0, Ai(x)*exp(2/3*x^1.5) for x > 0} function airy_bix(x: extended): extended; {-Return the Airy function Bi(x)} function airy_bipx(x: extended): extended; {-Return the Airy function Bi'(x)} function airy_bisx(x: extended): extended; {-Return the scaled Airy function Bi(x) if x <= 0, Bi(x)*exp(-2/3*x^1.5) for x > 0} function airy_gix(x: extended): extended; {-Return the Airy/Scorer function Gi(x) = 1/Pi*integral(sin(x*t+t^3/3), t=0..INF)} function airy_hix(x: extended): extended; {-Return the Airy/Scorer function Hi(x) = 1/Pi*integral(exp(x*t-t^3/3), t=0..INF)} function bessel_i0x(x: extended): extended; {-Return I0(x), the modified Bessel function of the 1st kind, order zero} function bessel_i0ex(x: extended): extended; {-Return I0(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order zero} function bessel_i1x(x: extended): extended; {-Return I1(x), the modified Bessel function of the 1st kind, order one} function bessel_i1ex(x: extended): extended; {-Return I1(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order one} function bessel_inx(n: integer; x: extended): extended; {-Return I_n(x), the modified Bessel function of the 1st kind, order n.} function bessel_ivx(v, x: extended): extended; {-Return I_v(x), the modified Bessel function of the 1st kind, order v.} function bessel_ivex(v, x: extended): extended; {-Return I_v(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order v.} function bessel_j0x(x: extended): extended; {-Return J0(x), the Bessel function of the 1st kind, order zero} function bessel_j1x(x: extended): extended; {-Return J1(x), the Bessel function of the 1st kind, order one} function bessel_jnx(n: integer; x: extended): extended; {-Return J_n(x), the Bessel function of the 1st kind, order n; not suitable for large n or x.} function bessel_jvx(v, x: extended): extended; {-Return J_v(x), the Bessel function of the 1st kind, order v; not suitable for large v.} function bessel_k0x(x: extended): extended; {-Return K0(x), the modified Bessel function of the 2nd kind, order zero, x>0} function bessel_k0ex(x: extended): extended; {-Return K0(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order zero, x>0} function bessel_k1x(x: extended): extended; {-Return K1(x), the modified Bessel function of the 2nd kind, order one, x>0} function bessel_k1ex(x: extended): extended; {-Return K1(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order one, x>0} function bessel_knx(n: integer; x: extended): extended; {-Return K_n(x), the modified Bessel function of the 2nd kind, order n, x>0, not suitable for large n} function bessel_kvx(v, x: extended): extended; {-Return K_v(x), the modified Bessel function of the 2nd kind, order v, x>0} function bessel_kvex(v, x: extended): extended; {-Return K_v(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order v, x>0} function bessel_y0x(x: extended): extended; {-Return Y0(x), the Bessel function of the 2nd kind, order zero; x>0} function bessel_y1x(x: extended): extended; {-Return Y1(x), the Bessel function of the 2nd kind, order one; x>0} function bessel_ynx(n: integer; x: extended): extended; {-Return Y_n(x), the Bessel function of the 2nd kind, order n, x>0, not suitable for large n or x} function bessel_yvx(v, x: extended): extended; {-Return Y_v(x), the Bessel function of the 2nd kind, order v; x > 0; not suitable for large v.} function kelvin_berx(x: extended): extended; {-Return the Kelvin function ber(x)} function kelvin_beix(x: extended): extended; {-Return the Kelvin function bei(x)} function kelvin_kerx(x: extended): extended; {-Return the Kelvin function ker(x), x > 0} function kelvin_keix(x: extended): extended; {-Return the Kelvin function kei(x), x >= 0} procedure kelvin_kerkeix(x: extended; var kr, ki: extended); {-Return the Kelvin functions kr=ker(x), ki=kei(x), x > 0} procedure kelvin_berbeix(x: extended; var br, bi: extended); {-Return the Kelvin functions br=ber(x), bi=bei(x)} function sph_bessel_jnx(n: integer; x: extended): extended; {-Return j_n(x), the spherical Bessel function of the 1st kind, order n} function sph_bessel_ynx(n: integer; x: extended): extended; {-Return y_n(x), the spherical Bessel function of the 2nd kind, order n >=0 , x<>0} function sph_bessel_inx(n: integer; x: extended): extended; {-Return i_n(x), the modified spherical Bessel function of the 1st/2nd kind, order n} function sph_bessel_inex(n: integer; x: extended): extended; {-Return i_n(x)*exp(-|x|), the exponentially scaled modified spherical Bessel function of the 1st/2nd kind, order n} function sph_bessel_knx(n: integer; x: extended): extended; {-Return k_n(x), the modified spherical Bessel function of the 3rd kind, order n, x>0} function sph_bessel_knex(n: integer; x: extended): extended; {-Return k_n(x)*exp(x), the exponentially scaled modified spherical Bessel function of the 3rd kind, order n, x>0} function struve_h0x(x: extended): extended; {-Return H0(x), the Struve function of order 0} function struve_h1x(x: extended): extended; {-Return H1(x), the Struve function of order 1} function struve_l0x(x: extended): extended; {-Return L0(x), the modified Struve function of order 0} function struve_l1x(x: extended): extended; {-Return L1(x), the modified Struve function of order 1} function struve_hx(v, x: extended): extended; {-Return H_v(x), the Struve function of order v, x < 0 only if v is an integer.} function struve_lx(v, x: extended): extended; {-Return L_v(x), the modified Struve function of order v, x < 0 only if v is an integer.} {#Z+} {---------------------------------------------------------------------------} {---------------------- Gamma function and related -------------------------} {---------------------------------------------------------------------------} {#Z-} const MAXGAMX = 1755.455; {max. argument for gammax} MAXLGMX = 1.0484814683901952E4928; {max. argument for lngammax} MAXDFACX = 3209; {max. argument for dfacx} function gammax(x: extended): extended; {-Return gamma(x), x <= MAXGAMX; invalid if x is a non-positive integer} function gamma1pm1x(x: extended): extended; {-Return gamma(1+x)-1 with increased accuracy for x near 0} function gammastarx(x: extended): extended; {-Return Temme's gammastar(x) = gamma(x)/(sqrt(2*Pi)*x^(x-0.5)*exp(-x)), x>0.} { For large x the asymptotic expansion is gammastar(x) = 1 + 1/12x + O(1/x^2)} function gamma_delta_ratiox(x,d: extended): extended; {-Return gamma(x)/gamma(x+d), accurate even for |d| << |x|} function gamma_ratiox(x,y: extended): extended; {-Return gamma(x)/gamma(y)} function pochhammerx(a,x: extended): extended; {-Return the Pochhammer symbol gamma(a+x)/gamma(a)} function poch1x(a,x: extended): extended; {-Return (pochhammer(a,x)-1)/x, psi(a) if x=0; accurate even for small |x|} function binomialx(n,k: integer): extended; {-Return the binomial coefficient 'n choose k'} function facx(n: integer): extended; {-Return the factorial n!, n<MAXGAM-1; INF if n<0} function dfacx(n: integer): extended; {-Return the double factorial n!!, n<=MAXDFACX; INF for even n<0} function lnfacx(n: longint): extended; {-Return ln(n!), INF if n<0} function lngammax(x: extended): extended; {-Return ln(|gammax(x)|), |x| <= MAXLGM, invalid if x is a non-positive integer.} { Function signgammax can be used if the sign of gammax(x) is needed.} function lngammasx(x: extended; var s: integer): extended; {-Return ln(|gamma(x)|), |x| <= MAXLGM, s=-1,1 is the sign of gamma} function lngamma1px(x: extended): extended; {-Return ln(|gamma(1+x)|) with increased accuracy for x near 0} function lngamma_invx(y: extended): extended; {-Inverse of lngamma: return x with lngamma(x) = y, y >= -0.12142, x > 1.4616} function signgammax(x: extended): extended; {-Return sign(gamma(x)), useless for 0 or negative integer} function rgammax(x: extended): extended; {-Return the reciprocal gamma function rgamma = 1/gamma(x)} procedure incgammax(a,x: extended; var p,q: extended); {-Return the normalised incomplete gamma functions P and Q, a>=0, x>=0} { P(a,x) = integral(exp(-t)*t^(a-1), t=0..x )/gamma(a)} { Q(a,x) = integral(exp(-t)*t^(a-1), t=x..Inf)/gamma(a)} function igammapx(a,x: extended): extended; {-Return the normalised lower incomplete gamma function P(a,x), a>=0, x>=0} { P(a,x) = integral(exp(-t)*t^(a-1), t=0..x)/gamma(a)} function igammaqx(a,x: extended): extended; {-Return the normalised upper incomplete gamma function Q(a,x), a>=0, x>=0} { Q(a,x) = integral(exp(-t)*t^(a-1), t=x..Inf)/gamma(a)} function igammax(a,x: extended): extended; {-Return the non-normalised upper incomplete gamma function} { GAMMA(a,x) = integral(exp(-t)*t^(a-1), t=x..Inf), x>=0} function igammalx(a,x: extended): extended; {-Return the non-normalised lower incomplete gamma function} { gamma(a,x) = integral(exp(-t)*t^(a-1), t=0..x); x>=0, a<>0,-1,-2,..} function igammatx(a,x: extended): extended; {-Return Tricomi's entire incomplete gamma function igammatx(a,x)} { = igammal(a,x)/gamma(a)/x^a = P(a,x)/x^a } procedure incgamma_invx(a,p,q: extended; var x: extended; var ierr: integer); {-Return the inverse normalised incomplete gamma function, i.e. calculate} { x with P(a,x)=p and Q(a,x)=q. Input parameter a>0, p>=0, q>0 and p+q=1.} { ierr is >= 0 for success, < 0 for input errors or iterations failures. } function igamma_invx(a,p,q: extended): extended; {-Return the inverse normalised incomplete gamma function, i.e. calculate} { x with P(a,x)=p and Q(a,x)=q. Input parameter a>0, p>=0, q>0 and p+q=1.} function igammap_invx(a,p: extended): extended; {-Inverse incomplete gamma: return x with P(a,x)=p, a>=0, 0<=p<1} function igammaq_invx(a,q: extended): extended; {-Inverse complemented incomplete gamma: return x with Q(a,x)=q, a>=0, 0<q<=1} function psix(x: extended): extended; {-Return the psi (digamma) function of x, INF if x is a non-positive integer} function psi_invx(y: extended): extended; {-Inverse of psi, return x with psi(x)=y, y <= ln_MaxExt} function trigammax(x: extended): extended; {-Return the trigamma function of x, INF if x is a negative integer} function tetragammax(x: extended): extended; {-Return the tetragamma function psi''(x), NAN/RTE if x is a negative integer} function pentagammax(x: extended): extended; {-Return the pentagamma function psi'''(x), INF if x is a negative integer} function polygammax(n: integer; x: extended): extended; {-Return the polygamma function: n'th derivative of psi; n>=0, x>0 for n>MAXGAMX} { Note: The accuracy may be reduced for n >= MAXGAMX due to ln/exp operations.} function BatemanGx(x: extended): extended; {-Return the Bateman function G(x) = psi((x+1)/2) - psi(x/2), x<>0,-1,-2,...} function lnbetax(x,y: extended): extended; {-Return the logarithm of |beta(x,y)|=|gamma(x)*gamma(y)/gamma(x+y)|} function betax(x,y: extended): extended; {-Return the function beta(x,y)=gamma(x)*gamma(y)/gamma(x+y)} function ibetax(a, b, x: extended): extended; {-Return the normalised incomplete beta function, a>0, b>0, 0 <= x <= 1} { ibetax = integral(t^(a-1)*(1-t)^(b-1) / betax(a,b), t=0..x)} function ibeta_invx(a, b, y: extended): extended; {-Return the functional inverse of the normalised incomplete beta function} { with a > 0, b > 0, and 0 <= y <= 1.} function beta3x(a, b, x: extended): extended; {-Return the non-normalised incomplete beta function B_x(a,b)} { for 0<=x<=1, B_x = integral(t^(a-1)*(1-t)^(b-1), t=0..x). } {#Z+} {---------------------------------------------------------------------------} {------------------- Zeta functions and polylogarithms -------------------} {---------------------------------------------------------------------------} {#Z-} function zetax(s: extended): extended; {-Return the Riemann zeta function at s, s<>1} function zeta1px(x: extended): extended; {-Return the Riemann zeta function at 1+x, x<>0} function zetaintx(n: integer): extended; {-Return zeta(n) for integer arguments, n<>1} function zetam1x(s: extended): extended; {-Return Riemann zeta(s)-1, s<>1} function zetahx(s,a: extended): extended; {-Return the Hurwitz zeta function zetah(s,a) = sum(1/(i+a)^s, i=0..INF), s<>1, a>0} function LerchPhix(z,s,a: extended): extended; {-Return the Lerch transcendent Phi(z,s,a) = sum(z^n/(n+a)^s, n=0..INF), |z|<=1, s >= -1, a>0; s<>1 if z=1} function DirichletBetax(s: extended): extended; {-Return the Dirichlet beta function sum((-1)^n/(2n+1)^s, n=0..INF)} function DirichletLambdax(s: extended): extended; {-Return the Dirichlet lambda function sum(1/(2n+1)^s, n=0..INF), s<>1} function LegendreChix(s, x: extended): extended; {-Return Legendre's Chi-function chi(s,x); s>=0, |x|<=1, x<>1 if s<=1} function etax(s: extended): extended; {-Return the Dirichlet eta function} function etaintx(n: integer): extended; {-Return the Dirichlet function eta(n) for integer arguments} function etam1x(s: extended): extended; {-Return Dirichlet eta(s)-1} function primezetax(x: extended): extended; {-Return the prime zeta function P(x) = sum(1/p^x, p prime), x > 1/5; } { for x<1 the real part of P(x) is returned.} function harmonicx(x: extended): extended; {-Return the harmonic number function H(x) = psi(x+1) + EulerGamma} function harmonic2x(x,r: extended): extended; {-Return the generalized harmonic function H(x,r) = zeta(r)-zetah(r,x+1); x >= -1} function cl2x(x: extended): extended; {-Return the Clausen function: integral(-ln(2*|sin(t/2)|),t=0..x) = Im(Li_2(exp(ix)))} function ti2x(x: extended): extended; {-Return the inverse tangent integral, ti2(x) = integral(arctan(t)/t, t=0..x)} function lobachevsky_cx(x: extended): extended; {-Return the Lobachevski function L(x) = integral(-ln(|cos(t)|), t=0..x)} function lobachevsky_sx(x: extended): extended; {-Return the Lobachevski function Lambda(x) = integral(-ln(|2sin(t)|), t=0..x)} function dilogx(x: extended): extended; {-Return dilog(x) = Re(Li_2(x)), Li_2(x) = -integral(ln(1-t)/t, t=0..x)} function trilogx(x: extended): extended; {-Return the trilogarithm function trilog(x) = Re(Li_3(x))} function polylogx(n: integer; x: extended): extended; {-Return the polylogarithm Li_n(x) of integer order; x<1 for n >= 0} function polylogrx(s, x: extended): extended; {-Return the polylogarithm Li_s(x) of real order; s >= -1, |x|<=1, x<>1 if s=1} function fermi_diracx(n: integer; x: extended): extended; {-Return the integer order Fermi-Dirac integral F_n(x) = 1/n!*integral(t^n/(exp(t-x)+1), t=0..INF)} function fermi_dirac_m05x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(-1/2,x)} function fermi_dirac_p05x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(1/2,x)} function fermi_dirac_p15x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(3/2,x)} function fermi_dirac_p25x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(5/2,x)} {#Z+} {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Legendre style) -------------------} {---------------------------------------------------------------------------} {#Z-} {---------------------------------------------------------------------------} function comp_ellint_1x(k: extended): extended; {-Return the complete elliptic integral of the 1st kind, |k| < 1} function comp_ellint_2x(k: extended): extended; {-Return the complete elliptic integral of the 2nd kind, |k| <= 1} function comp_ellint_3x(nu,k: extended): extended; {-Return the complete elliptic integral of the 3rd kind, |k|<1, nu<>1} function comp_ellint_dx(k: extended): extended; {-Return the complete elliptic integral D(k) = (K(k) - E(k))/k^2, |k| < 1} function ellint_1x(phi,k: extended): extended; {-Return the Legendre elliptic integral F(phi,k) of the 1st kind} { = integral(1/sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1} function ellint_2x(phi,k: extended): extended; {-Return the Legendre elliptic integral E(phi,k) of the 2nd kind} { = integral(sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1} function ellint_3x(phi,nu,k: extended): extended; {-Return the Legendre elliptic integral PI(phi,nu,k) of the 3rd kind} { = integral(1/sqrt(1-k^2*sin(x)^2)/(1-nu*sin(x)^2),x=0..phi) with } { |k*sin(phi)|<=1, returns Cauchy principal value if nu*sin(phi)^2>1} function ellint_dx(phi,k: extended): extended; {-Return the Legendre elliptic integral D(phi,k) = (F(phi,k) - E(phi,k))/k^2 } { = integral(sin(x)^2/sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1 } function heuman_lambdax(phi,k: extended): extended; {-Return Heuman's function Lambda_0(phi,k) = F(phi,k')/K(k') + 2/Pi*K(k)*Z(phi,k'), |k|<=1} function jacobi_zetax(phi,k: extended): extended; {-Return the Jacobi Zeta function Z(phi,k) = E(phi,k) - E(k)/K(k)*F(phi,k), |k|<=1} {#Z+} {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Carlson style) --------------------} {---------------------------------------------------------------------------} {#Z-} function ell_rcx(x,y: extended): extended; {-Return Carlson's degenerate elliptic integral RC; x>=0, y<>0} function ell_rfx(x,y,z: extended): extended; {-Return Carlson's elliptic integral of the 1st kind; x,y,z >=0, at most one =0} function ell_rdx(x,y,z: extended): extended; {-Return Carlson's elliptic integral of the 2nd kind; z>0; x,y >=0, at most one =0} function ell_rgx(x,y,z: extended): extended; {-Return Carlson's completely symmetric elliptic integral of the 2nd kind; x,y,z >= 0} function ell_rjx(x,y,z,r: extended): extended; {-Return Carlson's elliptic integral of the 3rd kind; r<>0; x,y,z >=0, at most one =0} {#Z+} {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Bulirsch style) -------------------} {---------------------------------------------------------------------------} {#Z-} function cel1x(kc: extended): extended; {-Return Bulirsch's complete elliptic integral of the 1st kind, kc<>0} function cel2x(kc, a, b: extended): extended; {-Return Bulirsch's complete elliptic integral of the 2nd kind, kc<>0} function celx(kc, p, a, b: extended): extended; {-Return Bulirsch's general complete elliptic integral, kc<>0, Cauchy principle value if p<0} function el1x(x,kc: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 1st kind} function el2x(x,kc,a,b: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 2nd kind, kc<>0} function el3x(x,kc,p: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 3rd kind, 1+p*x^2<>0} {#Z+} {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Maple V style) --------------------} {---------------------------------------------------------------------------} {#Z-} function EllipticFx(z,k: extended): extended; {-Return the incomplete elliptic integral of the 1st kind; |z|<=1, |k*z|<1} function EllipticKx(k: extended): extended; {-Return the complete elliptic integral of the 1st kind, |k| < 1} function EllipticKimx(k: extended): extended; {-Return K(i*k), the complete elliptic integral of the 1st kind with} { imaginary modulus = integral(1/sqrt(1-x^2)/sqrt(1+k^2*x^2),x=0..1)} function EllipticCKx(k: extended): extended; {-Return the complementary complete elliptic integral of the 1st kind, k<>0} function EllipticEx(z,k: extended): extended; {-Return the incomplete elliptic integrals of the 2nd kind, |z|<=1, |k*z| <= 1} function EllipticECx(k: extended): extended; {-Return the complete elliptic integral of the 2nd kind, |k| <= 1} function EllipticECimx(k: extended): extended; {-Return E(i*k), the complete elliptic integral of the 2nd kind with} { imaginary modulus = integral(sqrt(1+k^2*x^2)/sqrt(1-x^2),x=0..1) } function EllipticCEx(k: extended): extended; {-Return the complementary complete elliptic integral of the 2nd kind} function EllipticPix(z,nu,k: extended): extended; {-Return the incomplete elliptic integral of the 3rd kind, |z|<=1, |k*z|<1} function EllipticPiCx(nu,k: extended): extended; {-Return the complete elliptic integral of the 3rd kind, |k|<1, nu<>1} function EllipticCPix(nu,k: extended): extended; {-Return the complementary complete elliptic integral of the 3rd kind, k<>0, nu<>1} {#Z+} {---------------------------------------------------------------------------} {------------------- Jacobi elliptic and theta functions -------------------} {---------------------------------------------------------------------------} {#Z-} function EllipticModulusx(q: extended): extended; {-Return the elliptic modulus k(q) = theta_2(q)^2/theta_3(q)^2, 0 <= q <= 1} function EllipticNomex(k: extended): extended; {-Return the elliptic nome q(k) = exp(-Pi*EllipticCK(k)/EllipticK(k)), |k| < 1} function jacobi_amx(x,k: extended): extended; {-Return the Jacobi amplitude am(x,k)} function jacobi_arccnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccn(x,k), |x| <= 1, x >= sqrt(1 - 1/k^2) if k >= 1} function jacobi_arccdx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccd(x,k); |x| <= 1 if |k| < 1; |x| >= 1 if |k| > 1 } function jacobi_arccsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccs(x,k), |x| >= sqrt(k^2-1) for |k|>1} function jacobi_arcdcx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcdc(x,k); |x| >= 1 if |k| < 1; |x| <= 1 if |k| > 1 } function jacobi_arcdnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcdn(x,k), 0 <= x <= 1, x^2 + k^2 > 1 if |k| < 1; |x| <= 1 if |k| > 1} function jacobi_arcdsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcds(x,k), x^2 + k^2 >= 1} function jacobi_arcncx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcnc(x,k), x >= 1, x^2 <= k^2/(k^2-1) for |k|>1} function jacobi_arcndx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcnd(x,k), x >= 1, x^2 <= k^2/(1-k^2) if k < 1} function jacobi_arcnsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcns(x,k), |x| >= 1, |x| >= k if k>=1} function jacobi_arcscx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsc(x,k), |x| <= 1/sqrt(k^2-1) for |k|>1} function jacobi_arcsdx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsd(x,k), x^2*(1-k^2) <= 1} function jacobi_arcsnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsn(x,k), |x| <= 1 and |x*k| <= 1} function jacobi_snx(x,k: extended): extended; {-Return the Jacobi elliptic function sn(x,k)} function jacobi_cnx(x,k: extended): extended; {-Return the Jacobi elliptic function cn(x,k)} function jacobi_dnx(x,k: extended): extended; {-Return the Jacobi elliptic function dn(x,k)} function jacobi_ncx(x,k: extended): extended; {-Return the Jacobi elliptic function nc(x,k)} function jacobi_scx(x,k: extended): extended; {-Return the Jacobi elliptic function sc(x,k)} function jacobi_dcx(x,k: extended): extended; {-Return the Jacobi elliptic function dc(x,k)} function jacobi_ndx(x,k: extended): extended; {-Return the Jacobi elliptic function nd(x,k)} function jacobi_sdx(x,k: extended): extended; {-Return the Jacobi elliptic function sd(x,k)} function jacobi_cdx(x,k: extended): extended; {-Return the Jacobi elliptic function cd(x,k)} function jacobi_nsx(x,k: extended): extended; {-Return the Jacobi elliptic function ns(x,k)} function jacobi_csx(x,k: extended): extended; {-Return the Jacobi elliptic function cs(x,k)} function jacobi_dsx(x,k: extended): extended; {-Return the Jacobi elliptic function ds(x,k)} function jacobi_thetax(n: integer; x,q: extended): extended; {-Return the Jacobi theta function theta_n(x,q), n=1..4, 0 <= q < 1} procedure sncndnx(x,mc: extended; var sn,cn,dn: extended); {-Return the Jacobi elliptic functions sn,cn,dn for argument x and} { complementary parameter mc.} function theta1px(q: extended): extended; {-Return the derivative theta1p(q) := d/dx(theta_1(x,q)) at x=0,} { = 2*q^(1/4)*sum((-1)^n*(2n+1)*q^(n*(n+1)),n=0..Inf), 0 <= q < 1} function theta2x(q: extended): extended; {-Return Jacobi theta_2(q) = 2*q^(1/4)*sum(q^(n*(n+1)),n=0..Inf) 0 <= q < 1} function theta3x(q: extended): extended; {-Return Jacobi theta_3(q) = 1 + 2*sum(q^(n*n)),n=1..Inf); |q| < 1} function theta4x(q: extended): extended; {-Return Jacobi theta_4(q) = 1 + 2*sum((-1)^n*q^(n*(n+1)),n=1..Inf); |q| < 1} procedure sincos_lemnx(x: extended; var sl,cl: extended); {-Return the lemniscate functions sl = sin_lemn(x), cl = cos_lemn(x)} function sin_lemnx(x: extended): extended; {-Return the lemniscate sine functions sl = sin_lemn(x)} function cos_lemnx(x: extended): extended; {-Return the lemniscate cosine functions cl = cos_lemn(x)} {#Z+} {---------------------------------------------------------------------------} {----------------------- Error function and related ------------------------} {---------------------------------------------------------------------------} {#Z-} function dawsonx(x: extended): extended; {-Return Dawson's integral: dawson(x) = exp(-x^2)*integral(exp(t^2), t=0..x)} function dawson2x(p,x: extended): extended; {-Return the generalized Dawson integral F(p,x) = exp(-x^p)*integral(exp(t^p), t=0..x); x,p >= 0} function erfx(x: extended): extended; {-Return the error function erf(x) = 2/sqrt(Pi)*integral((exp(-t^2), t=0..x)} function erfcx(x: extended): extended; {-Return the complementary error function erfc(x) = 1-erf(x)} function erfcex(x: extended): extended; {-Return the exponentially scaled complementary error function erfce(x) = exp(x^2)*erfc(x)} function inerfcx(n: integer; x: extended): extended; {-Return the repeated integrals of erfc, n >= -1; scaled with exp(x^2) for x>0} function erfgx(p,x: extended): extended; {-Return the generalized error function integral(exp(-t^p), t=0..x); x,p >= 0} function erfix(x: extended): extended; {-Return the imaginary error function erfi(x) = erf(ix)/i} function erf_invx(x: extended): extended; {-Return the inverse function of erf, erf(erf_inv(x)) = x, -1 < x < 1} function erfc_invx(x: extended): extended; {-Return the inverse function of erfc, erfc(erfc_inv(x)) = x, 0 < x < 2} function erf_px(x: extended): extended; {-Return the probability function erf_p = integral(exp(-t^2/2)/sqrt(2*Pi), t=-Inf..x)} function erf_qx(x: extended): extended; {-Return the probability function erf_q = integral(exp(-t^2/2)/sqrt(2*Pi), t=x..Inf)} function erf_zx(x: extended): extended; {-Return the probability function erf_z = exp(-x^2/2)/sqrt(2*Pi)} function FresnelCx(x: extended): extended; {-Return the Fresnel integral C(x)=integral(cos(Pi/2*t^2),t=0..x)} function FresnelSx(x: extended): extended; {-Return the Fresnel integral S(x)=integral(sin(Pi/2*t^2),t=0..x)} procedure Fresnelx(x: extended; var s,c: extended); {-Return the Fresnel integrals S(x)=integral(sin(Pi/2*t^2),t=0..x) and C(x)=integral(cos(Pi/2*t^2),t=0..x)} function gsix(x: extended): extended; {-Return the Goodwin-Staton integral = integral(exp(-t*t)/(t+x), t=0..Inf), x > 0} function expint3x(x: extended): extended; {-Return the integral(exp(-t^3), t=0..x), x >= 0} {#Z+} {---------------------------------------------------------------------------} {------------------- Exponential integrals and related ---------------------} {---------------------------------------------------------------------------} {#Z-} function chix(x: extended): extended; {-Return the hyperbolic cosine integral = EulerGamma + ln(|x|) + integral((cosh(t)-1)/t, t=0..|x|)} function cix(x: extended): extended; {-Return the cosine integral, ci(x) = EulerGamma + ln(|x|) + integral((cos(t)-1)/t, t=0..|x|)} function cinx(x: extended): extended; {-Return the entire cosine integral, cin(x) = integral((1-cos(t))/t, t=0..x)} function cinhx(x: extended): extended; {-Return the entire hyperbolic cosine integral, cinh(x) = integral((cosh(t)-1)/t, t=0..x)} function e1x(x: extended): extended; {-Return the exponential integral E1(x) = integral(exp(-x*t)/t, t=1..Inf), x <> 0} function eix(x: extended): extended; {-Return the exponential integral Ei(x) = PV-integral(exp(t)/t, t=-Inf..x)} function einx(x: extended): extended; {-Return the entire exponential integral ein(x) = integral((1-exp(-t))/t, t=0..x)} function ei_invx(x: extended): extended; {-Return the functional inverse of Ei(x), ei_inv(ei(x))=x} function enx(n: longint; x: extended): extended; {-Return the exponential integral E_n(x) = integral(exp(-x*t)/t^n, t=1..Inf), x > 0} function geix(p,x: extended): extended; {-Return the generalized exponential integral E_p(x) = integral(exp(-x*t)/t^p, t=1..Inf), x >= 0} function lix(x: extended): extended; {-Return the logarithmic integral li(x) = PV-integral(1/ln(t), t=0..x), x >= 0, x <> 1} function li_invx(x: extended): extended; {-Return the functional inverse of li(x), li(li_inv(x))=x} function shix(x: extended): extended; {-Return the hyperbolic sine integral, shi(x) = integral(sinh(t)/t, t=0..x)} function six(x: extended): extended; {-Return the sine integral, si(x) = integral(sin(t)/t, t=0..x)} function ssix(x: extended): extended; {-Return the shifted sine integral, ssix(x) = six(x) - Pi/2} {#Z+} {---------------------------------------------------------------------------} {------------------ Orthogonal polynomials and related ---------------------} {---------------------------------------------------------------------------} {#Z-} function chebyshev_tx(n: integer; x: extended): extended; {-Return T_n(x), the Chebyshev polynomial of the first kind, degree n} function chebyshev_ux(n: integer; x: extended): extended; {-Return U_n(x), the Chebyshev polynomial of the second kind, degree n} function chebyshev_vx(n: integer; x: extended): extended; {-Return V_n(x), the Chebyshev polynomial of the third kind, degree n>=0} function chebyshev_wx(n: integer; x: extended): extended; {-Return W_n(x), the Chebyshev polynomial of the fourth kind, degree n>=0} function gegenbauer_cx(n: integer; a,x: extended): extended; {-Return Cn(a,x), the nth Gegenbauer (ultraspherical) polynomial with} { parameter a. The degree n must be non-negative; a should be > -0.5 } { When a = 0, C0(0,x) = 1, and Cn(0,x) = 2/n*Tn(x) for n <> 0.} function hermite_hx(n: integer; x: extended): extended; {-Return Hn(x), the nth Hermite polynomial, degree n >= 0} function jacobi_px(n: integer; a,b,x: extended): extended; {-Return Pn(a,b,x), the nth Jacobi polynomial with parameters a,b. Degree n} { must be >= 0; a,b should be > -1 (a+b must not be an integer < -1).} function laguerrex(n: integer; a,x: extended): extended; {-Return Ln(a,x), the nth generalized Laguerre polynomial with parameter a;} { degree n must be >= 0. x >=0 and a > -1 are the standard ranges.} function laguerre_assx(n,m: integer; x: extended): extended; {-Return the associated Laguerre polynomial Ln(m,x); n,m >= 0} function laguerre_lx(n: integer; x: extended): extended; {-Return the nth Laguerre polynomial Ln(0,x); n >= 0} function legendre_px(l: integer; x: extended): extended; {-Return P_l(x), the Legendre polynomial/function P_l, degree l} function legendre_qx(l: integer; x: extended): extended; {-Return Q_l(x), the Legendre function of the 2nd kind, degree l >=0, |x| <> 1} function legendre_plmx(l,m: integer; x: extended): extended; {-Return the associated Legendre polynomial P_lm(x)} function legendre_qlmx(l,m: integer; x: extended): extended; {-Return Q(l,m,x), the associated Legendre function of the second kind; l >= 0, l+m >= 0, |x|<>1} procedure spherical_harmonicx(l, m: integer; theta, phi: extended; var yr,yi: extended); {-Return Re and Im of the spherical harmonic function Y_lm(theta,phi)} function toroidal_plmx(l,m: integer; x: extended): extended; {-Return the toroidal harmonic function P(l-0.5,m,x); l,m=0,1; x >= 1} function toroidal_qlmx(l,m: integer; x: extended): extended; {-Return the toroidal harmonic function Q(l-0.5,m,x); l=0,1; x > 1} function zernike_rx(n,m: integer; r: extended): extended; {-Return the Zernike radial polynomial Rnm(r), r >= 0, n >= m >= 0, n-m even} {#Z+} {---------------------------------------------------------------------------} {---------------------- Statistical distributions --------------------------} {---------------------------------------------------------------------------} {#Z-} function beta_pdfx(a, b, x: extended): extended; {-Return the probability density function of the beta distribution with} { parameters a and b: sfc_beta_pdf = x^(a-1)*(1-x)^(b-1) / beta(a,b)} function beta_cdfx(a, b, x: extended): extended; {-Return the cumulative beta distribution function, a>0, b>0} function beta_invx(a, b, y: extended): extended; {-Return the functional inverse of the beta distribution function. a>0, b>0;} { 0 <= y <= 1. Given y the function finds x such that beta_cdf(a, b, x) = y} function binomial_cdfx(p: extended; n, k: longint): extended; {-Return the cumulative binomial distribution function with number} { of trials n >= 0 and success probability 0 <= p <= 1} function binomial_pmfx(p: extended; n, k: longint): extended; {-Return the binomial distribution probability mass function with number} { of trials n >= 0 and success probability 0 <= p <= 1} function cauchy_pdfx(a, b, x: extended): extended; {-Return the Cauchy probability density function with location a } { and scale b > 0, 1/(Pi*b*(1+((x-a)/b)^2))} function cauchy_cdfx(a, b, x: extended): extended; {-Return the cumulative Cauchy distribution function with location a} { and scale b > 0, = 1/2 + arctan((x-a)/b)/Pi} function cauchy_invx(a, b, y: extended): extended; {-Return the functional inverse of Cauchy distribution function} { with location a and scale b > 0} function chi2_pdfx(nu: longint; x: extended): extended; {-Return the probability density function of the chi-square distribution, nu>0} function chi2_cdfx(nu: longint; x: extended): extended; {-Return the cumulative chi-square distribution with nu>0 degrees of freedom, x >= 0} function chi2_invx(nu: longint; p: extended): extended; {-Return the functional inverse of the chi-square distribution, nu>0, 0 <= p < 1} function evt1_pdfx(a, b, x: extended): extended; {-Return the probability density function of the Extreme Value Type I distribution} { with location a and scale b > 0, result = exp(-(x-a)/b)/b * exp(-exp(-(x-a)/b)) } function evt1_cdfx(a, b, x: extended): extended; {-Return the cumulative Extreme Value Type I distribution function} { with location a and scale b > 0; result = exp(-exp(-(x-a)/b)). } function evt1_invx(a, b, y: extended): extended; {-Return the functional inverse of the Extreme Value Type I distribution} { function with location a and scale b > 0; result = a - b*ln(ln(-y)). } function exp_pdfx(a, alpha, x: extended): extended; {-Return the exponential probability density function with location a } { and rate alpha > 0, = alpha*exp(-alpha*(x-a)) if x >= a, 0 if x < a.} function exp_cdfx(a, alpha, x: extended): extended; {-Return the cumulative exponential distribution function with location a} { and rate alpha > 0, = 1 - exp(-alpha*(x-a)) if x >= a, 0 if x < a.} function exp_invx(a, alpha, y: extended): extended; {-Return the functional inverse of exponential distribution function with} { location a and rate alpha > 0} function f_pdfx(nu1, nu2: longint; x: extended): extended; {-Return the probability density function of the F distribution; x >= 0, nu1, nu2 > 0} function f_cdfx(nu1, nu2: longint; x: extended): extended; {-Return the cumulative F distribution function; x >= 0, nu1, nu2 > 0} function f_invx(nu1, nu2: longint; y: extended): extended; {-Return the functional inverse of the F distribution, nu1, nu2 > 0, 0 <= y <= 1} function gamma_pdfx(a, b, x: extended): extended; {-Return the probability density function of a gamma distribution with shape} { a>0, scale b>0: gamma_pdf = x^(a-1)*exp(-x/b)/gamma(a)/b^a, x>0} function gamma_cdfx(a, b, x: extended): extended; {-Return the cumulative gamma distribution function, shape a>0, scale b>0} function gamma_invx(a, b, p: extended): extended; {-Return the functional inverse of the gamma distribution function, shape a>0,} { scale b>0, 0 <= p <= 1, i.e. finds x such that gamma_cdf(a, b, x) = p} function hypergeo_pmfx(n1,n2,n,k: longint): extended; {-Return the hypergeometric distribution probability mass function; n,n1,n2 >= 0, n <= n1+n2;} { i.e. the probability that among n randomly chosen samples from a container} { with n1 type1 objects and n2 type2 objects are exactly k type1 objects:} function invgamma_pdfx(a, b, x: extended): extended; {-Return the probability density function of an inverse gamma distribution} { with shape a>0, scale b>0: result = (b/x)^a/x*exp(-b/x)/Gamma(a), x >= 0} function invgamma_cdfx(a, b, x: extended): extended; {-Return the cumulative inverse gamma distribution function, shape a>0, scale} { b>0: result = Gamma(a,b/x)/Gamma(a) = Q(a,b/x) = igammaq(a,b/x), x >= 0} function invgamma_invx(a, b, y: extended): extended; {-Return the functional inverse of the inverse gamma distribution function, shape} { a>0, scale b>0, 0 <= y <= 1, i.e. find x such that invgamma_cdfx(a, b, x) = y } function hypergeo_cdfx(n1,n2,n,k: longint): extended; {-Return the cumulative hypergeometric distribution function; n,n1,n2 >= 0, n <= n1+n2} function kumaraswamy_pdfx(a, b, x: extended): extended; {-Return the Kumaraswamy probability density function with shape} { parameters a,b>0, 0<=x<=1; result = a*b*x^(a-1)*(1-x^a)^(b-1) } function kumaraswamy_cdfx(a, b, x: extended): extended; {-Return the cumulative Kumaraswamy distribution function with} { shape parameters a,b > 0, 0 <= x <= 1; result = 1-(1-x^a)^b} function kumaraswamy_invx(a, b, y: extended): extended; {-Return the functional inverse of the Kumaraswamy distribution} { with shape parameters a,b > 0; result = [1-(1-y)^(1/b)]^(1/a)} function laplace_cdfx(a, b, x: extended): extended; {-Return the cumulative Laplace distribution function with location a and scale b > 0} function laplace_invx(a, b, y: extended): extended; {-Return the functional inverse of the Laplace distribution with location a and scale b > 0} function laplace_pdfx(a, b, x: extended): extended; {-Return the Laplace probability density function with location a} { and scale b > 0, result = exp(-abs(x-a)/b) / (2*b)} function levy_pdfx(a, b, x: extended): extended; {-Return the Levy probability density function with} { location a and scale parameter b > 0} function levy_cdfx(a, b, x: extended): extended; {-Return the cumulative Levy distribution function with} { location a and scale parameter b > 0} function levy_invx(a, b, y: extended): extended; {-Return the functional inverse of the Levy distribution} { with location a and scale parameter b > 0} function logistic_pdfx(a, b, x: extended): extended; {-Return the logistic probability density function with location a} { and scale parameter b > 0, exp(-(x-a)/b)/b/(1+exp(-(x-a)/b))^2} function logistic_cdfx(a, b, x: extended): extended; {-Return the cumulative logistic distribution function with} { location a and scale parameter b > 0} function logistic_invx(a, b, y: extended): extended; {-Return the functional inverse of the logistic distribution} { with location a and scale parameter b > 0} function lognormal_pdfx(a, b, x: extended): extended; {-Return the log-normal probability density function with} { location a and scale parameter b > 0, zero for x <= 0.} function lognormal_cdfx(a, b, x: extended): extended; {-Return the cumulative log-normal distribution function with} { location a and scale parameter b > 0, zero for x <= 0.} function lognormal_invx(a, b, y: extended): extended; {-Return the functional inverse of the log-normal distribution} { with location a and scale parameter b > 0, 0 < y < 1.} function logseries_pmfx(a: extended; k: longint): extended; {-Return the logarithmic (series) probability mass function} { with shape 0 < a < 1, k > 0; result = -a^k/(k*ln(1-a)) } function logseries_cdfx(a: extended; k: longint): extended; {-Return the cumulative logarithmic (series) distribution function with shape 0 < a < 1, k > 0} function maxwell_pdfx(b, x: extended): extended; {-Return the Maxwell probability density function with scale b > 0, x >= 0} function maxwell_cdfx(b, x: extended): extended; {-Return the cumulative Maxwell distribution function with scale b > 0, x >= 0} function maxwell_invx(b, y: extended): extended; {-Return the functional inverse of the Maxwell distribution with scale b > 0} function moyal_pdfx(a, b, x: extended): extended; {-Return the Moyal probability density function with} { location a and scale parameter b > 0} function moyal_cdfx(a, b, x: extended): extended; {-Return the cumulative Moyal distribution function with} { location a and scale parameter b > 0} function moyal_invx(a, b, y: extended): extended; {-Return the functional inverse of the Moyal distribution} { with location a and scale parameter b > 0} function negbinom_cdfx(p,r: extended; k: longint): extended; {-Return the cumulative negative binomial distribution function with target} { for number of successful trials r > 0 and success probability 0 <= p <= 1} function negbinom_pmfx(p,r: extended; k: longint): extended; {-Return the negative binomial distribution probability mass function with target} { for number of successful trials r > 0 and success probability 0 <= p <= 1} function normal_pdfx(mu, sd, x: extended): extended; {-Return the normal (Gaussian) probability density function with mean mu} { and standard deviation sd>0, exp(-0.5*(x-mu)^2/sd^2) / sqrt(2*Pi*sd^2)} function normal_cdfx(mu, sd, x: extended): extended; {-Return the normal (Gaussian) distribution function} { with mean mu and standard deviation sd > 0 } function normal_invx(mu, sd, y: extended): extended; {-Return the functional inverse of normal (Gaussian) distribution} { with mean mu and standard deviation sd > 0, 0 < y < 1.} function normstd_pdfx(x: extended): extended; {-Return the std. normal probability density function exp(-x^2/2)/sqrt(2*Pi)} function normstd_cdfx(x: extended): extended; {-Return the standard normal distribution function} function normstd_invx(y: extended): extended; {-Return the inverse standard normal distribution function, 0 < y < 1.} { For x=normstd_inv(y) and y from (0,1), normstd_cdf(x) = y} function pareto_pdfx(k, a, x: extended): extended; {-Return the Pareto probability density function with minimum value k > 0} { and shape a, x >= a > 0, result = (a/x)*(k/x)^a} function pareto_cdfx(k, a, x: extended): extended; {-Return the cumulative Pareto distribution function minimum value k > 0} { and shape a, x >= a > 0, result = 1-(k/x)^a} function pareto_invx(k, a, y: extended): extended; {-Return the functional inverse of the Pareto distribution with minimum} { value k > 0 and shape a, x >= a > 0, result = k/(1-x)^(1/a)} function poisson_cdfx(mu: extended; k: longint): extended; {-Return the cumulative Poisson distribution function with mean mu >= 0} function poisson_pmfx(mu: extended; k: longint): extended; {-Return the Poisson distribution probability mass function with mean mu >= 0} function rayleigh_pdfx(b, x: extended): extended; {-Return the Rayleigh probability density function with} { scale b > 0, x >= 0; result = x*exp(-0.5*(x/b)^2)/b^2} function rayleigh_cdfx(b, x: extended): extended; {-Return the cumulative Rayleigh distribution function with scale b > 0, x >= 0} function rayleigh_invx(b, y: extended): extended; {-Return the functional inverse of the Rayleigh distribution with scale b > 0} function t_pdfx(nu: longint; x: extended): extended; {-Return the probability density function of Student's t distribution, nu>0} function t_cdfx(nu: longint; t: extended): extended; {-Return the cumulative Student t distribution with nu>0 degrees of freedom} function t_invx(nu: longint; p: extended): extended; {-Return the functional inverse of Student's t distribution, nu>0, 0 <= p <= 1} function triangular_pdfx(a, b, c, x: extended): extended; {-Return the triangular probability density function with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b} function triangular_cdfx(a, b, c, x: extended): extended; {-Return the cumulative triangular distribution function with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b} function triangular_invx(a, b, c, y: extended): extended; {-Return the functional inverse of the triangular distribution with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b, 0 <= y <= 1} function uniform_pdfx(a, b, x: extended): extended; {-Return the uniform probability density function on [a,b], a<b} function uniform_cdfx(a, b, x: extended): extended; {-Return the cumulative uniform distribution function on [a,b], a<b} function uniform_invx(a, b, y: extended): extended; {-Return the functional inverse of the uniform distribution on [a,b], a<b} function wald_pdfx(mu, b, x: extended): extended; {-Return the Wald (inverse Gaussian) probability density} { function with mean mu > 0, scale b > 0 for x >= 0 } function wald_cdfx(mu, b, x: extended): extended; {-Return the Wald (inverse Gaussian) distribution } { function with mean mu > 0, scale b > 0 for x >= 0} function wald_invx(mu, b, y: extended): extended; {-Return the functional inverse of the Wald (inverse Gaussian)} { distribution with mean mu > 0, scale b > 0, 0 <= y < 1. } function weibull_pdfx(a, b, x: extended): extended; {-Return the Weibull probability density function with shape a > 0} { and scale b > 0, result = a*x^(a-1)*exp(-(x/b)^a)/ b^a, x > 0} function weibull_cdfx(a, b, x: extended): extended; {-Return the cumulative Weibull distribution function with} { shape parameter a > 0 and scale parameter b > 0} function weibull_invx(a, b, y: extended): extended; {-Return the functional inverse of the Weibull distribution} { shape parameter a > 0 and scale parameter b > 0} function zipf_pmfx(r: extended; k: longint): extended; {-Return the Zipf distribution probability mass function k^(-(r+1))/zeta(r+1), r>0, k>0} function zipf_cdfx(r: extended; k: longint): extended; {-Return the cumulative Zipf distribution function H(k,r+1)/zeta(r+1), r>0, k>0} {#Z+} {---------------------------------------------------------------------------} {-------------------- Hypergeometric functions -----------------------------} {---------------------------------------------------------------------------} {#Z-} function hyperg_1F1x(a,b,x: extended): extended; {-Return the confluent hypergeometric function 1F1(a,b,x); Kummer's function M(a,b,x)} function hyperg_1F1rx(a,b,x: extended): extended; {-Return the regularized Kummer hypergeometric function 1F1(a,b,x)/Gamma(b)} function hyperg_ux(a,b,x: extended): extended; {-Return Tricomi's confluent hypergeometric function U(a,b,x). If} { x<0, then a must be an integer and a<0 or 1+a-b an integer < 0.} function hyperg_2F1x(a,b,c,x: extended): extended; {-Return the Gauss hypergeometric function 2F1(a,b;c;x)} function hyperg_2F1rx(a,b,c,x: extended): extended; {-Return the regularized Gauss hypergeometric function 2F1(a,b,c,x)/Gamma(c)} function WhittakerMx(k,m,x: extended): extended; {-Return the Whittaker M function = exp(-x/2)*x^(0.5+m) * 1F1(m-k-0.5,2m+1,x)} function WhittakerWx(k,m,x: extended): extended; {-Return the Whittaker W function = exp(-x/2)*x^(0.5+m) * U(m-k-0.5,2m+1,x)} function hyperg_0F1x(b,x: extended): extended; {-Return the confluent hypergeometric limit function 0F1(;b;x)} function hyperg_0F1rx(b,x: extended): extended; {-Return the regularized confluent hypergeometric limit function 0F1(;b;x)/Gamma(b)} function CylinderDx(v,x: extended): extended; {-Return Whittaker's parabolic cylinder function D_v(x)} function CylinderUx(a,x: extended): extended; {-Return the parabolic cylinder function U(a,x)} function CylinderVx(a,x: extended): extended; {-Return the parabolic cylinder function V(a,x) with 2a integer} function HermiteHx(v,x: extended): extended; {-Return the Hermite function H_v(x) of degree v} {#Z+} {---------------------------------------------------------------------------} {--------------------------- Other functions -------------------------------} {---------------------------------------------------------------------------} {#Z-} function agmx(x,y: extended): extended; {-Return the arithmetic-geometric mean of |x| and |y|; |x|,|y| < sqrt(MaxExtended)} function bernoullix(n: integer): extended; {-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3} function bernpolyx(n: integer; x: extended): extended; {-Return the Bernoulli polynomial B_n(x), 0 <= n <= MaxBernoulli} function catalanx(x: extended): extended; {-Return the Catalan function C(x) = binomial(2x,x)/(x+1)} function cosintx(n: integer; x: extended): extended; {-Return cosint(n, x) = integral(cos(t)^n, t=0..x), n>=0} function debyex(n: integer; x: extended): extended; {-Return the Debye function D(n,x) = n/x^n*integral(t^n/(exp(t)-1),t=0..x) of order n>0, x>=0} function eulerx(n: integer): extended; {-Return the nth Euler number, 0 if n<0 or odd n} function fibpolyx(n: integer; x: extended): extended; {-Return the Fibonacci polynomial F_n(x)} function keplerx(M,e: extended): extended; {-Solve Kepler's equation, result x is the eccentric anomaly from the mean anomaly M and the } { eccentricity e >= 0; x - e*sin(x) = M, x + x^3/3 = M, or e*sinh(x) - x = M for e <1, =1, >1} function lucpolyx(n: integer; x: extended): extended; {-Return the Lucas polynomial L_n(x)} function LambertWx(x: extended): extended; {-Return the Lambert W function (principal branch), x >= -1/e} function LambertW1x(x: extended): extended; {-Return the Lambert W function (-1 branch), -1/e <= x < 0} function RiemannRx(x: extended): extended; {-Return the Riemann prime counting function R(x), x >= 1/16} function sinintx(n: integer; x: extended): extended; {-Return sinint(n, x) = integral(sin(t)^n, t=0..x), n>=0} implementation uses AMath, sfGamma, {Gamma function and related} sfGamma2, {inverse/incomplete Gamma/Beta} sfZeta, {Zeta functions and polylogarithms} sfZeta2, {Zeta functions part 2 (less common)} sfErf, {Error function and related} sfBessel, {Bessel functions} sfEllInt, {Elliptic integrals} sfExpInt, {Exponential integrals and related} sfSDist, {Statistical distributions} sfPoly, {Orthogonal polynomials and related} sfHyperG, {Hypergeometric functions} sfMisc; {Other functions} {---------------------------------------------------------------------------} {--------------------------- Bessel functions ------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function bessel_i0x(x: extended): extended; {-Return I0(x), the modified Bessel function of the 1st kind, order zero} begin bessel_i0x := sfc_i0(x); end; {---------------------------------------------------------------------------} function bessel_i0ex(x: extended): extended; {-Return I0(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order zero} begin bessel_i0ex := sfc_i0e(x); end; {---------------------------------------------------------------------------} function bessel_i1x(x: extended): extended; {-Return I1(x), the modified Bessel function of the 1st kind, order one} begin bessel_i1x := sfc_i1(x); end; {---------------------------------------------------------------------------} function bessel_i1ex(x: extended): extended; {-Return I1(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order one} begin bessel_i1ex := sfc_i1e(x); end; {---------------------------------------------------------------------------} function bessel_inx(n: integer; x: extended): extended; {-Return I_n(x), the modified Bessel function of the 1st kind, order n.} begin bessel_inx := sfc_in(n,x); end; {---------------------------------------------------------------------------} function bessel_ivx(v, x: extended): extended; {-Return I_v(x), the modified Bessel function of the 1st kind, order v.} begin bessel_ivx := sfc_iv(v,x); end; {---------------------------------------------------------------------------} function bessel_ivex(v, x: extended): extended; {-Return I_v(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order v.} begin bessel_ivex := sfc_ive(v,x); end; {---------------------------------------------------------------------------} function bessel_j0x(x: extended): extended; {-Return J0(x), the Bessel function of the 1st kind, order zero} begin bessel_j0x := sfc_j0(x); end; {---------------------------------------------------------------------------} function bessel_j1x(x: extended): extended; {-Return J1(x), the Bessel function of the 1st kind, order one} begin bessel_j1x := sfc_j1(x); end; {---------------------------------------------------------------------------} function bessel_jnx(n: integer; x: extended): extended; {-Return J_n(x), the Bessel function of the 1st kind, order n; not suitable for large n or x.} begin bessel_jnx := sfc_jn(n,x); end; {---------------------------------------------------------------------------} function bessel_jvx(v, x: extended): extended; {-Return J_v(x), the Bessel function of the 1st kind, order v; not suitable for large v.} begin bessel_jvx := sfc_jv(v,x); end; {---------------------------------------------------------------------------} function bessel_k0x(x: extended): extended; {-Return K0(x), the modified Bessel function of the 2nd kind, order zero, x>0} begin bessel_k0x := sfc_k0(x); end; {---------------------------------------------------------------------------} function bessel_k0ex(x: extended): extended; {-Return K0(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order zero, x>0} begin bessel_k0ex := sfc_k0e(x); end; {---------------------------------------------------------------------------} function bessel_k1x(x: extended): extended; {-Return K1(x), the modified Bessel function of the 2nd kind, order one, x>0} begin bessel_k1x := sfc_k1(x); end; {---------------------------------------------------------------------------} function bessel_k1ex(x: extended): extended; {-Return K1(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order one, x>0} begin bessel_k1ex := sfc_k1e(x); end; {---------------------------------------------------------------------------} function bessel_knx(n: integer; x: extended): extended; {-Return K_n(x), the modified Bessel function of the 2nd kind, order n, x>0, not suitable for large n} begin bessel_knx := sfc_kn(n,x); end; {---------------------------------------------------------------------------} function bessel_kvx(v, x: extended): extended; {-Return K_v(x), the modified Bessel function of the 2nd kind, order v, x>0} begin bessel_kvx := sfc_kv(v,x); end; {---------------------------------------------------------------------------} function bessel_kvex(v, x: extended): extended; {-Return K_v(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order v, x>0} begin bessel_kvex := sfc_kve(v,x); end; {---------------------------------------------------------------------------} function bessel_y0x(x: extended): extended; {-Return Y0(x), the Bessel function of the 2nd kind, order zero; x>0} begin bessel_y0x := sfc_y0(x); end; {---------------------------------------------------------------------------} function bessel_y1x(x: extended): extended; {-Return Y1(x), the Bessel function of the 2nd kind, order one; x>0} begin bessel_y1x := sfc_y1(x); end; {---------------------------------------------------------------------------} function bessel_ynx(n: integer; x: extended): extended; {-Return Y_n(x), the Bessel function of the 2nd kind, order n, x>0, not suitable for large n or x} begin bessel_ynx := sfc_yn(n,x); end; {---------------------------------------------------------------------------} function bessel_yvx(v, x: extended): extended; {-Return Y_v(x), the Bessel function of the 2nd kind, order v; x > 0; not suitable for large v.} begin bessel_yvx := sfc_yv(v,x); end; {---------------------------------------------------------------------------} function airy_aix(x: extended): extended; {-Return the Airy function Ai(x)} begin airy_aix := sfc_airy_ai(x); end; {---------------------------------------------------------------------------} function airy_aipx(x: extended): extended; {-Return the Airy function Ai'(x)} begin airy_aipx := sfc_airy_aip(x); end; {---------------------------------------------------------------------------} function airy_aisx(x: extended): extended; {-Return the scaled Airy function Ai(x) if x <= 0, Ai(x)*exp(2/3*x^1.5) for x > 0} begin airy_aisx := sfc_airy_ais(x); end; {---------------------------------------------------------------------------} function airy_bix(x: extended): extended; {-Return the Airy function Bi(x)} begin airy_bix := sfc_airy_bi(x); end; {---------------------------------------------------------------------------} function airy_bipx(x: extended): extended; {-Return the Airy function Bi'(x)} begin airy_bipx := sfc_airy_bip(x); end; {---------------------------------------------------------------------------} function airy_bisx(x: extended): extended; {-Return the scaled Airy function Bi(x) if x <= 0, Bi(x)*exp(-2/3*x^1.5) for x > 0} begin airy_bisx := sfc_airy_bis(x); end; {---------------------------------------------------------------------------} function airy_gix(x: extended): extended; {-Return the Airy/Scorer function Gi(x) = 1/Pi*integral(sin(x*t+t^3/3), t=0..INF)} begin airy_gix := sfc_airy_gi(x); end; {---------------------------------------------------------------------------} function airy_hix(x: extended): extended; {-Return the Airy/Scorer function Hi(x) = 1/Pi*integral(exp(x*t-t^3/3), t=0..INF)} begin airy_hix := sfc_airy_hi(x); end; {---------------------------------------------------------------------------} function kelvin_berx(x: extended): extended; {-Return the Kelvin function ber(x)} begin kelvin_berx := sfc_ber(x); end; {---------------------------------------------------------------------------} function kelvin_beix(x: extended): extended; {-Return the Kelvin function bei(x)} begin kelvin_beix := sfc_bei(x); end; {---------------------------------------------------------------------------} function kelvin_kerx(x: extended): extended; {-Return the Kelvin function ker(x), x > 0} begin kelvin_kerx := sfc_ker(x); end; {---------------------------------------------------------------------------} function kelvin_keix(x: extended): extended; {-Return the Kelvin function kei(x), x >= 0} begin kelvin_keix := sfc_kei(x); end; {---------------------------------------------------------------------------} procedure kelvin_kerkeix(x: extended; var kr, ki: extended); {-Return the Kelvin functions kr=ker(x), ki=kei(x), x > 0} begin sfc_ker_kei(x,kr,ki); end; {---------------------------------------------------------------------------} procedure kelvin_berbeix(x: extended; var br, bi: extended); {-Return the Kelvin functions br=ber(x), bi=bei(x)} begin sfc_ber_bei(x,br,bi); end; {---------------------------------------------------------------------------} function sph_bessel_jnx(n: integer; x: extended): extended; {-Return j_n(x), the spherical Bessel function of the 1st kind, order n} begin sph_bessel_jnx := sfc_sph_jn(n,x); end; {---------------------------------------------------------------------------} function sph_bessel_ynx(n: integer; x: extended): extended; {-Return y_n(x), the spherical Bessel function of the 2nd kind, order n >=0 , x<>0} begin sph_bessel_ynx := sfc_sph_yn(n,x); end; {---------------------------------------------------------------------------} function sph_bessel_inx(n: integer; x: extended): extended; {-Return i_n(x), the modified spherical Bessel function of the 1st/2nd kind, order n} begin sph_bessel_inx := sfc_sph_in(n,x); end; {---------------------------------------------------------------------------} function sph_bessel_inex(n: integer; x: extended): extended; {-Return i_n(x)*exp(-|x|), the exponentially scaled modified spherical Bessel function of the 1st/2nd kind, order n} begin sph_bessel_inex := sfc_sph_ine(n,x); end; {---------------------------------------------------------------------------} function sph_bessel_knx(n: integer; x: extended): extended; {-Return k_n(x), the modified spherical Bessel function of the 3rd kind, order n, x>0} begin sph_bessel_knx := sfc_sph_kn(n,x); end; {---------------------------------------------------------------------------} function sph_bessel_knex(n: integer; x: extended): extended; {-Return k_n(x)*exp(x), the exponentially scaled modified spherical Bessel function of the 3rd kind, order n, x>0} begin sph_bessel_knex := sfc_sph_kne(n,x); end; {---------------------------------------------------------------------------} function struve_h0x(x: extended): extended; {-Return H0(x), the Struve function of order 0} begin struve_h0x := sfc_struve_h0(x); end; {---------------------------------------------------------------------------} function struve_h1x(x: extended): extended; {-Return H1(x), the Struve function of order 1} begin struve_h1x := sfc_struve_h1(x); end; {---------------------------------------------------------------------------} function struve_l0x(x: extended): extended; {-Return L0(x), the modified Struve function of order 0} begin struve_l0x := sfc_struve_l0(x); end; {---------------------------------------------------------------------------} function struve_l1x(x: extended): extended; {-Return L1(x), the modified Struve function of order 1} begin struve_l1x := sfc_struve_l1(x); end; {---------------------------------------------------------------------------} function struve_hx(v, x: extended): extended; {-Return H_v(x), the Struve function of order v, x < 0 only if v is an integer.} begin struve_hx := sfc_struve_h(v,x); end; {---------------------------------------------------------------------------} function struve_lx(v, x: extended): extended; {-Return L_v(x), the modified Struve function of order v, x < 0 only if v is an integer.} begin struve_lx := sfc_struve_l(v,x); end; {---------------------------------------------------------------------------} {---------------------- Gamma function and related -------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function signgammax(x: extended): extended; {-Return sign(gamma(x)), useless for 0 or negative integer} begin signgammax := sfc_signgamma(x); end; {---------------------------------------------------------------------------} function gammax(x: extended): extended; {-Return gamma(x), x <= MAXGAMX; invalid if x is a non-positive integer} begin gammax := sfc_gamma(x); end; {---------------------------------------------------------------------------} function gamma1pm1x(x: extended): extended; {-Return gamma(1+x)-1 with increased accuracy for x near 0} begin gamma1pm1x := sfc_gamma1pm1(x); end; {---------------------------------------------------------------------------} function gammastarx(x: extended): extended; {-Return Temme's gammastar(x) = gamma(x)/(sqrt(2*Pi)*x^(x-0.5)*exp(-x)), x>0.} { For large x the asymptotic expansion is gammastar(x) = 1 + 1/12x + O(1/x^2)} begin gammastarx := sfc_gstar(x); end; {---------------------------------------------------------------------------} function gamma_delta_ratiox(x,d: extended): extended; {-Return gamma(x)/gamma(x+d), accurate even for |d| << |x|} begin gamma_delta_ratiox := sfc_gamma_delta_ratio(x,d); end; {---------------------------------------------------------------------------} function gamma_ratiox(x,y: extended): extended; {-Return gamma(x)/gamma(y)} begin gamma_ratiox := sfc_gamma_ratio(x,y); end; {---------------------------------------------------------------------------} function pochhammerx(a,x: extended): extended; {-Return the Pochhammer symbol gamma(a+x)/gamma(a)} begin pochhammerx := sfc_pochhammer(a,x); end; {---------------------------------------------------------------------------} function poch1x(a,x: extended): extended; {-Return (pochhammer(a,x)-1)/x, psi(a) if x=0; accurate even for small |x|} begin poch1x := sfc_poch1(a,x); end; {---------------------------------------------------------------------------} function binomialx(n,k: integer): extended; {-Return the binomial coefficient 'n choose k'} begin binomialx := sfc_binomial(n,k,false); end; {---------------------------------------------------------------------------} function facx(n: integer): extended; {-Return the factorial n!, n<MAXGAM-1; INF if n<0} begin facx := sfc_fac(n); end; {---------------------------------------------------------------------------} function dfacx(n: integer): extended; {-Return the double factorial n!!, n<=MAXDFACX; INF for even n<0} begin dfacx := sfc_dfac(n); end; {---------------------------------------------------------------------------} function lnfacx(n: longint): extended; {-Return ln(n!), INF if n<0} begin lnfacx := sfc_lnfac(n); end; {---------------------------------------------------------------------------} function lngammax(x: extended): extended; {-Return ln(|gamma(x)|), |x| <= MAXLGM, invalid if x is a non-positive integer} { Function signgamma can be used if the sign of gamma(x) is needed.} begin if IsNanOrInf(x) then lngammax := x else if abs(x) > MAXLGMX then lngammax := PosInf_x else lngammax := sfc_lngamma(x); end; {---------------------------------------------------------------------------} function lngammasx(x: extended; var s: integer): extended; {-Return ln(|gamma(x)|), |x| <= MAXLGM, s=-1,1 is the sign of gamma} begin lngammasx := sfc_lngammas(x,s); end; {---------------------------------------------------------------------------} function lngamma1px(x: extended): extended; {-Return ln(|gamma(1+x)|) with increased accuracy for x near 0} begin if IsNanOrInf(x) then lngamma1px := x else if abs(x) > MAXLGMX then lngamma1px := PosInf_x else lngamma1px := sfc_lngamma1p(x); end; {---------------------------------------------------------------------------} function rgammax(x: extended): extended; {-Return the reciprocal gamma function rgamma = 1/gamma(x)} begin if x>=1755.5 then rgammax := 0.0 else rgammax := sfc_rgamma(x); end; {---------------------------------------------------------------------------} procedure incgammax(a,x: extended; var p,q: extended); {-Return the normalised incomplete gamma functions P and Q, a>=0, x>=0} { P(a,x) = integral(exp(-t)*t^(a-1), t=0..x )/gamma(a)} { Q(a,x) = integral(exp(-t)*t^(a-1), t=x..Inf)/gamma(a)} begin sfc_incgamma(a,x,p,q); end; {---------------------------------------------------------------------------} function igammapx(a,x: extended): extended; {-Return the normalised lower incomplete gamma function P(a,x), a>=0, x>=0} { P(a,x) = integral(exp(-t)*t^(a-1), t=0..x)/gamma(a)} begin igammapx := sfc_igammap(a,x); end; {---------------------------------------------------------------------------} function igammaqx(a,x: extended): extended; {-Return the normalised upper incomplete gamma function Q(a,x), a>=0, x>=0} { Q(a,x) = integral(exp(-t)*t^(a-1), t=x..Inf)/gamma(a)} begin igammaqx := sfc_igammaq(a,x); end; {---------------------------------------------------------------------------} function igammax(a,x: extended): extended; {-Return the non-normalised lower incomplete gamma function} { gamma(a,x) = integral(exp(-t)*t^(a-1), t=0..x); x>=0, a<>0,-1,-2,..} begin igammax := sfc_igamma(a,x); end; {---------------------------------------------------------------------------} function igammalx(a,x: extended): extended; {-Return the non-normalised lower incomplete gamma function} { gamma(a,x) = integral(exp(-t)*t^(a-1), t=0..x); x>=0, a<>0,-1,-2,..} begin igammalx := sfc_igammal(a,x); end; {---------------------------------------------------------------------------} function igammatx(a,x: extended): extended; {-Return Tricomi's entire incomplete gamma function igammatx(a,x)} { = igammal(a,x)/gamma(a)/x^a = P(a,x)/x^a } begin igammatx := sfc_git(a,x); end; {---------------------------------------------------------------------------} procedure incgamma_invx(a,p,q: extended; var x: extended; var ierr: integer); {-Return the inverse normalised incomplete gamma function, i.e. calculate} { x with P(a,x)=p and Q(a,x)=q. Input parameter a>0, p>=0, q>0 and p+q=1.} { ierr is >= 0 for success, < 0 for input errors or iterations failures. } begin sfc_incgamma_inv(a,p,q,x,ierr); end; {---------------------------------------------------------------------------} function igamma_invx(a,p,q: extended): extended; {-Return the inverse normalised incomplete gamma function, i.e. calculate} { x with P(a,x)=p and Q(a,x)=q. Input parameter a>0, p>=0, q>0 and p+q=1.} begin igamma_invx := sfc_igamma_inv(a,p,q); end; {---------------------------------------------------------------------------} function igammap_invx(a,p: extended): extended; {-Inverse incomplete gamma: return x with P(a,x)=p, a>=0, 0<=p<1} begin igammap_invx := sfc_igammap_inv(a,p); end; {---------------------------------------------------------------------------} function igammaq_invx(a,q: extended): extended; {-Inverse complemented incomplete gamma: return x with Q(a,x)=q, a>=0, 0<q<=1} begin igammaq_invx := sfc_igammaq_inv(a,q); end; {---------------------------------------------------------------------------} function lngamma_invx(y: extended): extended; {-Inverse of lngamma: return x with lngamma(x) = y, y >= -0.12142, x > 1.4616} begin lngamma_invx := sfc_ilng(y); end; {---------------------------------------------------------------------------} function psix(x: extended): extended; {-Return the psi (digamma) function of x, INF if x is a non-positive integer} begin if x=PosInf_x then psix := x else psix := sfc_psi(x); end; {---------------------------------------------------------------------------} function psi_invx(y: extended): extended; {-Inverse of psi, return x with psi(x)=y, y <= ln_MaxExt} begin psi_invx := sfc_ipsi(y); end; {---------------------------------------------------------------------------} function trigammax(x: extended): extended; {-Return the trigamma function of x, INF if x is a negative integer} begin trigammax := sfc_trigamma(x); end; {---------------------------------------------------------------------------} function tetragammax(x: extended): extended; {-Return the tetragamma function psi''(x), NAN/RTE if x is a negative integer} begin tetragammax := sfc_tetragamma(x); end; {---------------------------------------------------------------------------} function pentagammax(x: extended): extended; {-Return the pentagamma function psi'''(x), INF if x is a negative integer} begin pentagammax := sfc_pentagamma(x); end; {---------------------------------------------------------------------------} function polygammax(n: integer; x: extended): extended; {-Return the polygamma function: n'th derivative of psi; n>=0, x>0 for n>MAXGAMX} { Note: The accuracy may be reduced for n >= MAXGAMX due to ln/exp operations.} begin polygammax := sfc_polygamma(n,x); end; {---------------------------------------------------------------------------} function BatemanGx(x: extended): extended; {-Return the Bateman function G(x) = psi((x+1)/2) - psi(x/2), x<>0,-1,-2,...} begin BatemanGx := sfc_batemang(x); end; {---------------------------------------------------------------------------} function lnbetax(x,y: extended): extended; {-Return the logarithm of |beta(x,y)|=|gamma(x)*gamma(y)/gamma(x+y)|} begin lnbetax := sfc_lnbeta(x,y); end; {---------------------------------------------------------------------------} function betax(x,y: extended): extended; {-Return the function beta(x,y)=gamma(x)*gamma(y)/gamma(x+y)} begin betax := sfc_beta(x,y); end; {---------------------------------------------------------------------------} function ibetax(a, b, x: extended): extended; {-Return the normalised incomplete beta function, a>0, b>0, 0 <= x <= 1} { ibetax = integral(t^(a-1)*(1-t)^(b-1) / betax(a,b), t=0..x)} begin ibetax := sfc_ibeta(a,b,x); end; {---------------------------------------------------------------------------} function ibeta_invx(a, b, y: extended): extended; {-Return the functional inverse of the normalised incomplete beta function} { with a > 0, b > 0, and 0 <= y <= 1.} begin ibeta_invx := sfc_ibeta_inv(a,b,y); end; {---------------------------------------------------------------------------} function beta3x(a, b, x: extended): extended; {-Return the non-normalised incomplete beta function B_x(a,b)} { for 0<=x<=1, B_x = integral(t^(a-1)*(1-t)^(b-1), t=0..x). } begin beta3x := sfc_nnbeta(a,b,x); end; {---------------------------------------------------------------------------} {------------------- Zeta functions and polylogarithms -------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function zetax(s: extended): extended; {-Return the Riemann zeta function at s, s<>1} begin zetax := sfc_zeta(s); end; {---------------------------------------------------------------------------} function zetaintx(n: integer): extended; {-Return zeta(n) for integer arguments, n<>1} begin zetaintx := sfc_zetaint(n); end; {---------------------------------------------------------------------------} function zeta1px(x: extended): extended; {-Return the Riemann zeta function at 1+x, x<>0} begin zeta1px := sfc_zeta1p(x); end; {---------------------------------------------------------------------------} function etax(s: extended): extended; {-Return the Dirichlet eta function} begin etax := sfc_eta(s); end; {---------------------------------------------------------------------------} function etaintx(n: integer): extended; {-Return the Dirichlet function eta(n) for integer arguments} begin etaintx := sfc_etaint(n); end; {---------------------------------------------------------------------------} function etam1x(s: extended): extended; {-Return Dirichlet eta(s)-1} begin etam1x := sfc_etam1(s); end; {---------------------------------------------------------------------------} function zetam1x(s: extended): extended; {-Return Riemann zeta(s)-1, s<>1} begin zetam1x := sfc_zetam1(s); end; {---------------------------------------------------------------------------} function zetahx(s,a: extended): extended; {-Return the Hurwitz zeta function zetah(s,a) = sum(1/(i+a)^s, i=0..INF), s<>1, a>0} begin zetahx := sfc_zetah(s,a); end; {---------------------------------------------------------------------------} function LerchPhix(z,s,a: extended): extended; {-Return the Lerch transcendent Phi(z,s,a) = sum(z^n/(n+a)^s, n=0..INF), |z|<=1, s >= -1, a>0; s<>1 if z=1} begin LerchPhix := sfc_lerch(z,s,a); end; {---------------------------------------------------------------------------} function DirichletBetax(s: extended): extended; {-Return the Dirichlet beta function sum((-1)^n/(2n+1)^s, n=0..INF)} begin DirichletBetax := sfc_dbeta(s); end; {---------------------------------------------------------------------------} function DirichletLambdax(s: extended): extended; {-Return the Dirichlet lambda function sum(1/(2n+1)^s, n=0..INF), s<>1} begin DirichletLambdax := sfc_dlambda(s); end; {---------------------------------------------------------------------------} function LegendreChix(s, x: extended): extended; {-Return Legendre's Chi-function chi(s,x); s>=0, |x|<=1, x<>1 if s<=1} begin LegendreChix := sfc_lchi(s, x); end; {---------------------------------------------------------------------------} function primezetax(x: extended): extended; {-Return the prime zeta function P(x) = sum(1/p^x, p prime), x > 1/5; } { for x<1 the real part of P(x) is returned.} begin primezetax := sfc_pz(x); end; {---------------------------------------------------------------------------} function harmonicx(x: extended): extended; {-Return the harmonic number function H(x) = psi(x+1) + EulerGamma} begin harmonicx := sfc_harmonic(x); end; {---------------------------------------------------------------------------} function harmonic2x(x,r: extended): extended; {-Return the generalized harmonic function H(x,r) = zeta(r)-zetah(r,x+1); x >= -1} begin harmonic2x := sfc_harmonic2(x,r); end; {---------------------------------------------------------------------------} function cl2x(x: extended): extended; {-Return the Clausen function: integral(-ln(2*|sin(t/2)|),t=0..x) = Im(Li_2(exp(ix)))} begin cl2x := sfc_cl2(x); end; {---------------------------------------------------------------------------} function ti2x(x: extended): extended; {-Return the inverse tangent integral, ti2(x) = integral(arctan(t)/t, t=0..x)} begin ti2x := sfc_ti2(x); end; {---------------------------------------------------------------------------} function lobachevsky_cx(x: extended): extended; {-Return the Lobachevski function L(x) = integral(-ln(|cos(t)|), t=0..x)} begin lobachevsky_cx := sfc_llci(x); end; {---------------------------------------------------------------------------} function lobachevsky_sx(x: extended): extended; {-Return the Lobachevski function Lambda(x) = integral(-ln(|2sin(t)|), t=0..x)} begin lobachevsky_sx := sfc_llsi(x); end; {---------------------------------------------------------------------------} function dilogx(x: extended): extended; {-Return dilog(x) = Re(Li_2(x)), Li_2(x) = -integral(ln(1-t)/t, t=0..x)} begin dilogx := sfc_dilog(x); end; {---------------------------------------------------------------------------} function trilogx(x: extended): extended; {-Return the trilogarithm function trilog(x) = Re(Li_3(x))} begin trilogx := sfc_trilog(x); end; {---------------------------------------------------------------------------} function polylogx(n: integer; x: extended): extended; {-Return the polylogarithm Li_n(x) of integer order; x<1 for n >= 0} begin polylogx := sfc_polylog(n,x); end; {---------------------------------------------------------------------------} function polylogrx(s, x: extended): extended; {-Return the polylogarithm Li_s(x) of real order; s >= -1, |x|<=1, x<>1 if s=1} begin polylogrx := sfc_polylogr(s,x); end; {---------------------------------------------------------------------------} function fermi_diracx(n: integer; x: extended): extended; {-Return the integer order Fermi-Dirac integral F_n(x) = 1/n!*integral(t^n/(exp(t-x)+1), t=0..INF)} begin fermi_diracx := sfc_fermi_dirac(n,x); end; {---------------------------------------------------------------------------} function fermi_dirac_m05x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(-1/2,x)} begin fermi_dirac_m05x := sfc_fdm05(x); end; {---------------------------------------------------------------------------} function fermi_dirac_p05x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(1/2,x)} begin fermi_dirac_p05x := sfc_fdp05(x); end; {---------------------------------------------------------------------------} function fermi_dirac_p15x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(3/2,x)} begin fermi_dirac_p15x := sfc_fdp15(x); end; {---------------------------------------------------------------------------} function fermi_dirac_p25x(x: extended): extended; {-Return the complete Fermi-Dirac integral F(5/2,x)} begin fermi_dirac_p25x := sfc_fdp25(x); end; {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Legendre style) -------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function comp_ellint_1x(k: extended): extended; {-Return the complete elliptic integral of the 1st kind, |k| < 1} begin comp_ellint_1x := sfc_EllipticK(k); end; {---------------------------------------------------------------------------} function comp_ellint_2x(k: extended): extended; {-Return the complete elliptic integral of the 2nd kind, |k| <= 1} begin comp_ellint_2x := sfc_EllipticEC(k); end; {---------------------------------------------------------------------------} function comp_ellint_3x(nu,k: extended): extended; {-Return the complete elliptic integral of the 3rd kind, |k|<1, nu<>1} begin comp_ellint_3x := sfc_EllipticPiC(nu,k); end; {---------------------------------------------------------------------------} function comp_ellint_dx(k: extended): extended; {-Return the complete elliptic integral D(k) = (K(k) - E(k))/k^2, |k| < 1} begin comp_ellint_dx := sfc_cel_d(k); end; {---------------------------------------------------------------------------} function ellint_1x(phi,k: extended): extended; {-Return the Legendre elliptic integral F(phi,k) of the 1st kind} { = integral(1/sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1} begin ellint_1x := sfc_ellint_1(phi,k); end; {---------------------------------------------------------------------------} function ellint_2x(phi,k: extended): extended; {-Return the Legendre elliptic integral E(phi,k) of the 2nd kind} { = integral(sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1} begin ellint_2x := sfc_ellint_2(phi,k); end; {---------------------------------------------------------------------------} function ellint_3x(phi,nu,k: extended): extended; {-Return the Legendre elliptic integral PI(phi,nu,k) of the 3rd kind} { = integral(1/sqrt(1-k^2*sin(x)^2)/(1-nu*sin(x)^2),x=0..phi) with } { |k*sin(phi)|<=1, returns Cauchy principal value if nu*sin(phi)^2>1} begin ellint_3x := sfc_ellint_3(phi,nu,k); end; {---------------------------------------------------------------------------} function ellint_dx(phi,k: extended): extended; {-Return the Legendre elliptic integral D(phi,k) = (F(phi,k) - E(phi,k))/k^2 } { = integral(sin(x)^2/sqrt(1-k^2*sin(x)^2),x=0..phi), |k*sin(phi)| <= 1 } begin ellint_dx := sfc_ellint_d(phi,k); end; {---------------------------------------------------------------------------} function heuman_lambdax(phi,k: extended): extended; {-Return Heuman's function Lambda_0(phi,k) = F(phi,k')/K(k') + 2/Pi*K(k)*Z(phi,k'), |k|<=1} begin heuman_lambdax := sfc_hlambda(phi,k); end; {---------------------------------------------------------------------------} function jacobi_zetax(phi,k: extended): extended; {-Return the Jacobi Zeta function Z(phi,k) = E(phi,k) - E(k)/K(k)*F(phi,k), |k|<=1} begin jacobi_zetax := sfc_jzeta(phi,k); end; {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Carlson style) --------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function ell_rcx(x,y: extended): extended; {-Return Carlson's degenerate elliptic integral RC; x>=0, y<>0} begin ell_rcx := sfc_ell_rc(x,y); end; {---------------------------------------------------------------------------} function ell_rfx(x,y,z: extended): extended; {-Return Carlson's elliptic integral of the 1st kind; x,y,z >=0, at most one =0} begin ell_rfx := sfc_ell_rf(x,y,z); end; {---------------------------------------------------------------------------} function ell_rdx(x,y,z: extended): extended; {-Return Carlson's elliptic integral of the 2nd kind; z>0; x,y >=0, at most one =0} begin ell_rdx := sfc_ell_rd(x,y,z); end; {---------------------------------------------------------------------------} function ell_rgx(x,y,z: extended): extended; {-Return Carlson's completely symmetric elliptic integral of the 2nd kind; x,y,z >= 0} begin ell_rgx := sfc_ell_rg(x,y,z); end; {---------------------------------------------------------------------------} function ell_rjx(x,y,z,r: extended): extended; {-Return Carlson's elliptic integral of the 3rd kind; r<>0; x,y,z >=0, at most one =0} begin ell_rjx := sfc_ell_rj(x,y,z,r); end; {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Bulirsch style) -------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function cel1x(kc: extended): extended; {-Return Bulirsch's complete elliptic integral of the 1st kind, kc<>0} begin cel1x := sfc_cel1(kc); end; {---------------------------------------------------------------------------} function cel2x(kc, a, b: extended): extended; {-Return Bulirsch's complete elliptic integral of the 2nd kind, kc<>0} begin cel2x := sfc_cel2(kc,a,b); end; {---------------------------------------------------------------------------} function celx(kc, p, a, b: extended): extended; {-Return Bulirsch's general complete elliptic integral, kc<>0, Cauchy principle value if p<0} begin celx := sfc_cel(kc,p,a,b); end; {---------------------------------------------------------------------------} function el1x(x,kc: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 1st kind} begin el1x := sfc_el1(x,kc); end; {---------------------------------------------------------------------------} function el2x(x,kc,a,b: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 2nd kind, kc<>0} begin el2x := sfc_el2(x,kc,a,b); end; {---------------------------------------------------------------------------} function el3x(x,kc,p: extended): extended; {-Return Bulirsch's incomplete elliptic integral of the 3rd kind, 1+p*x^2<>0} begin el3x := sfc_el3(x,kc,p); end; {---------------------------------------------------------------------------} {------------------- Elliptic integrals (Maple V style) --------------------} {---------------------------------------------------------------------------} function EllipticFx(z,k: extended): extended; {-Return the incomplete elliptic integral of the 1st kind; |z|<=1, |k*z|<1} begin EllipticFx := sfc_EllipticF(z,k); end; {---------------------------------------------------------------------------} function EllipticKx(k: extended): extended; {-Return the complete elliptic integral of the 1st kind, |k| < 1} begin EllipticKx := sfc_EllipticK(k); end; {---------------------------------------------------------------------------} function EllipticKimx(k: extended): extended; {-Return K(i*k), the complete elliptic integral of the 1st kind with} { imaginary modulus = integral(1/sqrt(1-x^2)/sqrt(1+k^2*x^2),x=0..1)} begin EllipticKimx := sfc_EllipticKim(k); end; {---------------------------------------------------------------------------} function EllipticCKx(k: extended): extended; {-Return the complementary complete elliptic integral of the 1st kind, k<>0} begin EllipticCKx := sfc_EllipticCK(k); end; {---------------------------------------------------------------------------} function EllipticEx(z,k: extended): extended; {-Return the incomplete elliptic integrals of the 2nd kind, |z|<=1, |k*z| <= 1} begin EllipticEx := sfc_EllipticE(z,k); end; {---------------------------------------------------------------------------} function EllipticECx(k: extended): extended; {-Return the complete elliptic integral of the 2nd kind, |k| <= 1} begin EllipticECx := sfc_EllipticEC(k); end; {---------------------------------------------------------------------------} function EllipticECimx(k: extended): extended; {-Return E(i*k), the complete elliptic integral of the 2nd kind with} { imaginary modulus = integral(sqrt(1+k^2*x^2)/sqrt(1-x^2),x=0..1) } begin EllipticECimx := sfc_EllipticECim(k); end; {---------------------------------------------------------------------------} function EllipticCEx(k: extended): extended; {-Return the complementary complete elliptic integral of the 2nd kind} begin EllipticCEx := sfc_EllipticCE(k); end; {---------------------------------------------------------------------------} function EllipticPix(z,nu,k: extended): extended; {-Return the incomplete elliptic integral of the 3rd kind, |z|<=1, |k*z|<1} begin EllipticPix := sfc_EllipticPi(z,nu,k); end; {---------------------------------------------------------------------------} function EllipticPiCx(nu,k: extended): extended; {-Return the complete elliptic integral of the 3rd kind, |k|<1, nu<>1} begin EllipticPiCx := sfc_EllipticPiC(nu,k); end; {---------------------------------------------------------------------------} function EllipticCPix(nu,k: extended): extended; {-Return the complementary complete elliptic integral of the 3rd kind, k<>0, nu<>1} begin EllipticCPix := sfc_EllipticCPi(nu,k); end; {---------------------------------------------------------------------------} {------------------- Jacobi elliptic and theta functions -------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function EllipticModulusx(q: extended): extended; {-Return the elliptic modulus k(q) = theta_2(q)^2/theta_3(q)^2, 0 <= q <= 1} begin EllipticModulusx := sfc_ellmod(q); end; {---------------------------------------------------------------------------} function EllipticNomex(k: extended): extended; {-Return the elliptic nome q(k) = exp(-Pi*EllipticCK(k)/EllipticK(k)), |k| < 1} begin EllipticNomex := sfc_nome(k); end; {---------------------------------------------------------------------------} function jacobi_amx(x,k: extended): extended; {-Return the Jacobi amplitude am(x,k)} begin jacobi_amx := sfc_jam(x,k); end; {---------------------------------------------------------------------------} function jacobi_thetax(n: integer; x,q: extended): extended; {-Return the Jacobi theta function theta_n(x,q), n=1..4, 0 <= q < 1} begin jacobi_thetax := sfc_jtheta(n,x,q); end; {---------------------------------------------------------------------------} procedure sncndnx(x,mc: extended; var sn,cn,dn: extended); {-Return the Jacobi elliptic functions sn,cn,dn for argument x and} { complementary parameter mc.} begin sfc_sncndn(x,mc,sn,cn,dn); end; {---------------------------------------------------------------------------} function jacobi_snx(x,k: extended): extended; {-Return the Jacobi elliptic function sn(x,k)} begin jacobi_snx := sfc_jacobi_sn(x,k); end; {---------------------------------------------------------------------------} function jacobi_cnx(x,k: extended): extended; {-Return the Jacobi elliptic function cn(x,k)} begin jacobi_cnx := sfc_jacobi_cn(x,k); end; {---------------------------------------------------------------------------} function jacobi_dnx(x,k: extended): extended; {-Return the Jacobi elliptic function dn(x,k)} begin jacobi_dnx := sfc_jacobi_dn(x,k); end; {---------------------------------------------------------------------------} function jacobi_ncx(x,k: extended): extended; {-Return the Jacobi elliptic function nc(x,k)} begin jacobi_ncx := sfc_jacobi_nc(x,k); end; {---------------------------------------------------------------------------} function jacobi_scx(x,k: extended): extended; {-Return the Jacobi elliptic function sc(x,k)} begin jacobi_scx := sfc_jacobi_sc(x,k); end; {---------------------------------------------------------------------------} function jacobi_dcx(x,k: extended): extended; {-Return the Jacobi elliptic function dc(x,k)} begin jacobi_dcx := sfc_jacobi_dc(x,k); end; {---------------------------------------------------------------------------} function jacobi_ndx(x,k: extended): extended; {-Return the Jacobi elliptic function nd(x,k)} begin jacobi_ndx := sfc_jacobi_nd(x,k); end; {---------------------------------------------------------------------------} function jacobi_sdx(x,k: extended): extended; {-Return the Jacobi elliptic function sd(x,k)} begin jacobi_sdx := sfc_jacobi_sd(x,k); end; {---------------------------------------------------------------------------} function jacobi_cdx(x,k: extended): extended; {-Return the Jacobi elliptic function cd(x,k)} begin jacobi_cdx := sfc_jacobi_cd(x,k); end; {---------------------------------------------------------------------------} function jacobi_nsx(x,k: extended): extended; {-Return the Jacobi elliptic function ns(x,k)} begin jacobi_nsx := sfc_jacobi_ns(x,k); end; {---------------------------------------------------------------------------} function jacobi_csx(x,k: extended): extended; {-Return the Jacobi elliptic function cs(x,k)} begin jacobi_csx := sfc_jacobi_cs(x,k); end; {---------------------------------------------------------------------------} function jacobi_dsx(x,k: extended): extended; {-Return the Jacobi elliptic function ds(x,k)} begin jacobi_dsx := sfc_jacobi_ds(x,k); end; {---------------------------------------------------------------------------} function jacobi_arccnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccn(x,k), |x| <= 1, x >= sqrt(1 - 1/k^2) if k >= 1} begin jacobi_arccnx := sfc_jacobi_arccn(x,k); end; {---------------------------------------------------------------------------} function jacobi_arccdx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccd(x,k); |x| <= 1 if |k| < 1; |x| >= 1 if |k| > 1 } begin jacobi_arccdx := sfc_jacobi_arccd(x,k); end; {---------------------------------------------------------------------------} function jacobi_arccsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arccs(x,k), |x| >= sqrt(k^2-1) for |k|>1} begin jacobi_arccsx := sfc_jacobi_arccs(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcdcx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcdc(x,k); |x| >= 1 if |k| < 1; |x| <= 1 if |k| > 1 } begin jacobi_arcdcx := sfc_jacobi_arcdc(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcdnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcdn(x,k), 0 <= x <= 1, x^2 + k^2 > 1 if |k| < 1; |x| <= 1 if |k| > 1} begin jacobi_arcdnx := sfc_jacobi_arcdn(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcdsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcds(x,k), x^2 + k^2 >= 1} begin jacobi_arcdsx := sfc_jacobi_arcds(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcncx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcnc(x,k), x >= 1, x^2 <= k^2/(k^2-1) for |k|>1} begin jacobi_arcncx := sfc_jacobi_arcnc(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcndx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcnd(x,k), x >= 1, x^2 <= k^2/(1-k^2) if k < 1} begin jacobi_arcndx := sfc_jacobi_arcnd(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcnsx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcns(x,k), |x| >= 1, |x| >= k if k>=1} begin jacobi_arcnsx := sfc_jacobi_arcns(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcscx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsc(x,k), |x| <= 1/sqrt(k^2-1) for |k|>1} begin jacobi_arcscx := sfc_jacobi_arcsc(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcsdx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsd(x,k), x^2*(1-k^2) <= 1} begin jacobi_arcsdx := sfc_jacobi_arcsd(x,k); end; {---------------------------------------------------------------------------} function jacobi_arcsnx(x,k: extended): extended; {-Return the inverse Jacobi elliptic function arcsn(x,k), |x| <= 1 and |x*k| <= 1} begin jacobi_arcsnx := sfc_jacobi_arcsn(x,k); end; {---------------------------------------------------------------------------} function theta1px(q: extended): extended; {-Return the derivative theta1p(q) := d/dx(theta_1(x,q)) at x=0,} { = 2*q^(1/4)*sum((-1)^n*(2n+1)*q^(n*(n+1)),n=0..Inf), 0 <= q < 1} begin theta1px := sfc_theta1p(q); end; {---------------------------------------------------------------------------} function theta2x(q: extended): extended; {-Return Jacobi theta_2(q) = 2*q^(1/4)*sum(q^(n*(n+1)),n=0..Inf) 0 <= q < 1} begin theta2x := sfc_theta2(q); end; {---------------------------------------------------------------------------} function theta3x(q: extended): extended; {-Return Jacobi theta_3(q) = 1 + 2*sum(q^(n*n)),n=1..Inf); |q| < 1} begin theta3x := sfc_theta3(q); end; {---------------------------------------------------------------------------} function theta4x(q: extended): extended; {-Return Jacobi theta_4(q) = 1 + 2*sum((-1)^n*q^(n*(n+1)),n=1..Inf); |q| < 1} begin theta4x := sfc_theta4(q); end; {---------------------------------------------------------------------------} procedure sincos_lemnx(x: extended; var sl,cl: extended); {-Return the lemniscate functions sl = sin_lemn(x), cl = cos_lemn(x)} begin sfc_lemn(x,sl,cl); end; {---------------------------------------------------------------------------} function sin_lemnx(x: extended): extended; {-Return the lemniscate sine functions sl = sin_lemn(x)} var sl,cl: extended; begin sfc_lemn(x,sl,cl); sin_lemnx := sl; end; {---------------------------------------------------------------------------} function cos_lemnx(x: extended): extended; {-Return the lemniscate cosine functions cl = cos_lemn(x)} var sl,cl: extended; begin sfc_lemn(x,sl,cl); cos_lemnx := cl; end; {---------------------------------------------------------------------------} {----------------------- Error function and related ------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function dawsonx(x: extended): extended; {-Return Dawson's integral: dawson(x) = exp(-x^2)*integral(exp(t^2), t=0..x)} begin dawsonx := sfc_dawson(x); end; {---------------------------------------------------------------------------} function dawson2x(p,x: extended): extended; {-Return the generalized Dawson integral F(p,x) = exp(-x^p)*integral(exp(t^p), t=0..x); x,p >= 0} begin dawson2x := sfc_gendaw(p,x); end; {---------------------------------------------------------------------------} function erfx(x: extended): extended; {-Return the error function erf(x) = 2/sqrt(Pi)*integral((exp(-t^2), t=0..x)} begin erfx := sfc_erf(x); end; {---------------------------------------------------------------------------} function erfcx(x: extended): extended; {-Return the complementary error function erfc(x) = 1-erf(x)} begin erfcx := sfc_erfc(x); end; {---------------------------------------------------------------------------} function erfcex(x: extended): extended; {-Return the exponentially scaled complementary error function erfce(x) = exp(x^2)*erfc(x)} begin erfcex := sfc_erfce(x); end; {---------------------------------------------------------------------------} function inerfcx(n: integer; x: extended): extended; {-Return the repeated integrals of erfc, n >= -1; scaled with exp(x^2) for x>0} begin inerfcx := sfc_inerfc(n,x); end; {---------------------------------------------------------------------------} function erfgx(p,x: extended): extended; {-Return the generalized error function integral(exp(-t^p), t=0..x); x,p >= 0} begin erfgx := sfc_erfg(p,x); end; {---------------------------------------------------------------------------} function erfix(x: extended): extended; {-Return the imaginary error function erfi(x) = erf(ix)/i} begin erfix := sfc_erfi(x); end; {---------------------------------------------------------------------------} function erf_invx(x: extended): extended; {-Return the inverse function of erf, erf(erf_inv(x)) = x, -1 < x < 1} begin erf_invx := sfc_erf_inv(x); end; {---------------------------------------------------------------------------} function erfc_invx(x: extended): extended; {-Return the inverse function of erfc, erfc(erfc_inv(x)) = x, 0 < x < 2} begin erfc_invx := sfc_erfc_inv(x); end; {---------------------------------------------------------------------------} function erf_px(x: extended): extended; {-Return the probability function erf_p = integral(exp(-t^2/2)/sqrt(2*Pi), t=-Inf..x)} begin erf_px := sfc_erf_p(x); end; {---------------------------------------------------------------------------} function erf_qx(x: extended): extended; {-Return the probability function erf_q = integral(exp(-t^2/2)/sqrt(2*Pi), t=x..Inf)} begin erf_qx := sfc_erf_q(x); end; {---------------------------------------------------------------------------} function erf_zx(x: extended): extended; {-Return the probability function erf_z = exp(-x^2/2)/sqrt(2*Pi)} begin erf_zx := sfc_erf_z(x); end; {---------------------------------------------------------------------------} function expint3x(x: extended): extended; {-Return the integral(exp(-t^3), t=0..x), x >= 0} begin expint3x := sfc_expint3(x); end; {---------------------------------------------------------------------------} procedure Fresnelx(x: extended; var s,c: extended); {-Return the Fresnel integrals S(x)=integral(sin(Pi/2*t^2),t=0..x) and C(x)=integral(cos(Pi/2*t^2),t=0..x)} begin sfc_fresnel(x,s,c); end; {---------------------------------------------------------------------------} function FresnelCx(x: extended): extended; {-Return the Fresnel integral C(x)=integral(cos(Pi/2*t^2),t=0..x)} var s,c: extended; begin sfc_fresnel(x,s,c); FresnelCx := c; end; {---------------------------------------------------------------------------} function FresnelSx(x: extended): extended; {-Return the Fresnel integral S(x)=integral(sin(Pi/2*t^2),t=0..x)} var s,c: extended; begin sfc_fresnel(x,s,c); FresnelSx := s; end; {---------------------------------------------------------------------------} function gsix(x: extended): extended; {-Return the Goodwin-Staton integral = integral(exp(-t*t)/(t+x), t=0..Inf), x > 0} begin gsix := sfc_gsi(x); end; {---------------------------------------------------------------------------} {------------------- Exponential integrals and related ---------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function chix(x: extended): extended; {-Return the hyperbolic cosine integral = EulerGamma + ln(|x|) + integral((cosh(t)-1)/t, t=0..|x|)} begin chix := sfc_chi(x); end; {---------------------------------------------------------------------------} function cix(x: extended): extended; {-Return the cosine integral, ci(x) = EulerGamma + ln(|x|) + integral((cos(t)-1)/t, t=0..|x|)} begin cix := sfc_ci(x); end; {---------------------------------------------------------------------------} function cinx(x: extended): extended; {-Return the entire cosine integral, cin(x) = integral((1-cos(t))/t, t=0..x)} begin cinx := sfc_cin(x); end; {---------------------------------------------------------------------------} function cinhx(x: extended): extended; {-Return the entire hyperbolic cosine integral, cinh(x) = integral((cosh(t)-1)/t, t=0..x)} begin cinhx := sfc_cinh(x); end; {---------------------------------------------------------------------------} function e1x(x: extended): extended; {-Return the exponential integral E1(x) = integral(exp(-x*t)/t, t=1..Inf), x <> 0} begin e1x := sfc_e1(x); end; {---------------------------------------------------------------------------} function eix(x: extended): extended; {-Return the exponential integral Ei(x) = PV-integral(exp(t)/t, t=-Inf..x)} begin eix := sfc_ei(x); end; {---------------------------------------------------------------------------} function einx(x: extended): extended; {-Return the entire exponential integral ein(x) = integral((1-exp(-t))/t, t=0..x)} begin einx := sfc_ein(x); end; {---------------------------------------------------------------------------} function ei_invx(x: extended): extended; {-Return the functional inverse of Ei(x), ei_inv(ei(x))=x} begin ei_invx := sfc_ei_inv(x); end; {---------------------------------------------------------------------------} function enx(n: longint; x: extended): extended; {-Return the exponential integral E_n(x) = integral(exp(-x*t)/t^n, t=1..Inf), x > 0} begin enx := sfc_en(n,x); end; {---------------------------------------------------------------------------} function geix(p,x: extended): extended; {-Return the generalized exponential integral E_p(x) = integral(exp(-x*t)/t^p, t=1..Inf), x >= 0} begin geix := sfc_gei(p,x); end; {---------------------------------------------------------------------------} function lix(x: extended): extended; {-Return the logarithmic integral li(x) = PV-integral(1/ln(t), t=0..x), x >= 0, x <> 1} begin lix := sfc_li(x); end; {---------------------------------------------------------------------------} function shix(x: extended): extended; {-Return the hyperbolic sine integral, shi(x) = integral(sinh(t)/t, t=0..x)} begin shix := sfc_shi(x); end; {---------------------------------------------------------------------------} function six(x: extended): extended; {-Return the sine integral, si(x) = integral(sin(t)/t, t=0..x)} begin six := sfc_si(x); end; {---------------------------------------------------------------------------} function ssix(x: extended): extended; {-Return the shifted sine integral, ssi(x) = six(x) - Pi/2} begin ssix := sfc_ssi(x); end; {---------------------------------------------------------------------------} {---------------------- Statistical distributions --------------------------} {---------------------------------------------------------------------------} function beta_pdfx(a, b, x: extended): extended; {-Return the probability density function of the beta distribution with} { parameters a and b: beta_pdf = x^(a-1)*(1-x)^(b-1) / beta(a,b)} begin beta_pdfx := sfc_beta_pdf(a, b, x); end; {---------------------------------------------------------------------------} function beta_cdfx(a, b, x: extended): extended; {-Return the cumulative beta distribution function, a>0, b>0} begin beta_cdfx := sfc_beta_cdf(a, b, x); end; {---------------------------------------------------------------------------} function beta_invx(a, b, y: extended): extended; {-Return the functional inverse of the beta distribution function. a>0, b>0;} { 0 <= y <= 1. Given y the function finds x such that beta_cdf(a, b, x) = y} begin beta_invx := sfc_beta_inv(a, b, y); end; {---------------------------------------------------------------------------} function binomial_cdfx(p: extended; n, k: longint): extended; {-Return the cumulative binomial distribution function with number} { of trials n >= 0 and success probability 0 <= p <= 1} begin binomial_cdfx := sfc_binomial_cdf(p,n,k); end; {---------------------------------------------------------------------------} function binomial_pmfx(p: extended; n, k: longint): extended; {-Return the binomial distribution probability mass function with number} { of trials n >= 0 and success probability 0 <= p <= 1} begin binomial_pmfx := sfc_binomial_pmf(p,n,k); end; {---------------------------------------------------------------------------} function cauchy_pdfx(a, b, x: extended): extended; {-Return the Cauchy probability density function with location a } { and scale b > 0, 1/(Pi*b*(1+((x-a)/b)^2))} begin cauchy_pdfx := sfc_cauchy_pdf(a, b, x); end; {---------------------------------------------------------------------------} function cauchy_cdfx(a, b, x: extended): extended; {-Return the cumulative Cauchy distribution function with location a} { and scale b > 0, = 1/2 + arctan((x-a)/b)/Pi} begin cauchy_cdfx := sfc_cauchy_cdf(a, b, x); end; {---------------------------------------------------------------------------} function cauchy_invx(a, b, y: extended): extended; {-Return the functional inverse of Cauchy distribution function} { with location a and scale b > 0} begin cauchy_invx := sfc_cauchy_inv(a, b, y); end; {---------------------------------------------------------------------------} function chi2_pdfx(nu: longint; x: extended): extended; {-Return the probability density function of the chi-square distribution, nu>0} begin chi2_pdfx := sfc_chi2_pdf(nu,x); end; {---------------------------------------------------------------------------} function chi2_cdfx(nu: longint; x: extended): extended; {-Return the cumulative chi-square distribution with nu>0 degrees of freedom, x >= 0} begin chi2_cdfx := sfc_chi2_cdf(nu,x); end; {---------------------------------------------------------------------------} function chi2_invx(nu: longint; p: extended): extended; {-Return the functional inverse of the chi-square distribution, nu>0, 0 <= p < 1} begin chi2_invx := sfc_chi2_inv(nu,p); end; {---------------------------------------------------------------------------} function evt1_pdfx(a, b, x: extended): extended; {-Return the probability density function of the Extreme Value Type I distribution} { with location a and scale b > 0, result = exp(-(x-a)/b)/b * exp(-exp(-(x-a)/b)) } begin evt1_pdfx := sfc_evt1_pdf(a, b, x); end; {---------------------------------------------------------------------------} function evt1_cdfx(a, b, x: extended): extended; {-Return the cumulative Extreme Value Type I distribution function} { with location a and scale b > 0; result = exp(-exp(-(x-a)/b)). } begin evt1_cdfx := sfc_evt1_cdf(a, b, x); end; {---------------------------------------------------------------------------} function evt1_invx(a, b, y: extended): extended; {-Return the functional inverse of the Extreme Value Type I distribution} { function with location a and scale b > 0; result = a - b*ln(ln(-y)). } begin evt1_invx := sfc_evt1_inv(a, b, y); end; {---------------------------------------------------------------------------} function exp_pdfx(a, alpha, x: extended): extended; {-Return the exponential probability density function with location a } { and rate alpha > 0, = alpha*exp(-alpha*(x-a)) if x >= a, 0 if x < a.} begin exp_pdfx := sfc_exp_pdf(a, alpha, x); end; {---------------------------------------------------------------------------} function exp_cdfx(a, alpha, x: extended): extended; {-Return the cumulative exponential distribution function with location a} { and rate alpha > 0, = 1 - exp(-alpha*(x-a)) if x >= a, 0 if x < a.} begin exp_cdfx := sfc_exp_cdf(a, alpha, x); end; {---------------------------------------------------------------------------} function exp_invx(a, alpha, y: extended): extended; {-Return the functional inverse of exponential distribution function with} { location a and rate alpha > 0} begin exp_invx := sfc_exp_inv(a, alpha, y); end; {---------------------------------------------------------------------------} function f_pdfx(nu1, nu2: longint; x: extended): extended; {-Return the probability density function of the F distribution; x >= 0, nu1, nu2 > 0} begin f_pdfx := sfc_f_pdf(nu1, nu2, x); end; {---------------------------------------------------------------------------} function f_cdfx(nu1, nu2: longint; x: extended): extended; {-Return the cumulative F distribution function; x >= 0, nu1, nu2 > 0} begin f_cdfx := sfc_f_cdf(nu1, nu2, x); end; {---------------------------------------------------------------------------} function f_invx(nu1, nu2: longint; y: extended): extended; {-Return the functional inverse of the F distribution, nu1, nu2 > 0, 0 <= y <= 1} begin f_invx := sfc_f_inv(nu1, nu2, y); end; {---------------------------------------------------------------------------} function gamma_pdfx(a, b, x: extended): extended; {-Return the probability density function of a gamma distribution with shape} { a>0, scale b>0: gamma_pdf = x^(a-1)*exp(-x/b)/gamma(a)/b^a, x>0} begin gamma_pdfx := sfc_gamma_pdf(a, b, x); end; {---------------------------------------------------------------------------} function gamma_cdfx(a, b, x: extended): extended; {-Return the cumulative gamma distribution function, shape a>0, scale b>0} begin gamma_cdfx := sfc_gamma_cdf(a, b, x); end; {---------------------------------------------------------------------------} function gamma_invx(a, b, p: extended): extended; {-Return the functional inverse of the gamma distribution function, shape a>0,} { scale b>0, 0 <= p <= 1, i.e. finds x such that gamma_cdf(a, b, x) = p} begin gamma_invx := sfc_gamma_inv(a, b, p); end; {---------------------------------------------------------------------------} function hypergeo_pmfx(n1,n2,n,k: longint): extended; {-Return the hypergeometric distribution probability mass function; n,n1,n2 >= 0, n <= n1+n2;} { i.e. the probability that among n randomly chosen samples from a container} { with n1 type1 objects and n2 type2 objects are exactly k type1 objects:} begin hypergeo_pmfx := sfc_hypergeo_pmf(n1,n2,n,k); end; {---------------------------------------------------------------------------} function hypergeo_cdfx(n1,n2,n,k: longint): extended; {-Return the cumulative hypergeometric distribution function; n,n1,n2 >= 0, n <= n1+n2} begin hypergeo_cdfx := sfc_hypergeo_cdf(n1,n2,n,k); end; {---------------------------------------------------------------------------} function invgamma_pdfx(a, b, x: extended): extended; {-Return the probability density function of an inverse gamma distribution} { with shape a>0, scale b>0: result = (b/x)^a/x*exp(-b/x)/Gamma(a), x >= 0} begin invgamma_pdfx := sfc_invgamma_pdf(a, b, x); end; {---------------------------------------------------------------------------} function invgamma_cdfx(a, b, x: extended): extended; {-Return the cumulative inverse gamma distribution function, shape a>0, scale} { b>0: result = Gamma(a,b/x)/Gamma(a) = Q(a,b/x) = igammaq(a,b/x), x >= 0} begin invgamma_cdfx := sfc_invgamma_cdf(a, b, x); end; {---------------------------------------------------------------------------} function invgamma_invx(a, b, y: extended): extended; {-Return the functional inverse of the inverse gamma distribution function, shape} { a>0, scale b>0, 0 <= y <= 1, i.e. find x such that invgamma_cdf(a, b, x) = y } begin invgamma_invx := sfc_invgamma_inv(a, b, y); end; {---------------------------------------------------------------------------} function kumaraswamy_pdfx(a, b, x: extended): extended; {-Return the Kumaraswamy probability density function with shape} { parameters a,b>0, 0<=x<=1; result = a*b*x^(a-1)*(1-x^a)^(b-1) } begin kumaraswamy_pdfx := sfc_kumaraswamy_pdf(a,b,x); end; {---------------------------------------------------------------------------} function kumaraswamy_cdfx(a, b, x: extended): extended; {-Return the cumulative Kumaraswamy distribution function with} { shape parameters a,b > 0, 0 <= x <= 1; result = 1-(1-x^a)^b} begin kumaraswamy_cdfx := sfc_kumaraswamy_cdf(a,b,x); end; {---------------------------------------------------------------------------} function kumaraswamy_invx(a, b, y: extended): extended; {-Return the functional inverse of the Kumaraswamy distribution} { with shape parameters a,b > 0; result = [1-(1-y)^(1/b)]^(1/a)} begin kumaraswamy_invx := sfc_kumaraswamy_inv(a,b,y) end; {---------------------------------------------------------------------------} function laplace_cdfx(a, b, x: extended): extended; {-Return the cumulative Laplace distribution function with location a and scale b > 0} begin laplace_cdfx := sfc_laplace_cdf(a,b,x); end; {---------------------------------------------------------------------------} function laplace_invx(a, b, y: extended): extended; {-Return the functional inverse of the Laplace distribution with location a and scale b > 0} begin laplace_invx := sfc_laplace_inv(a,b,y); end; {---------------------------------------------------------------------------} function laplace_pdfx(a, b, x: extended): extended; {-Return the Laplace probability density function with location a} { and scale b > 0, result = exp(-abs(x-a)/b) / (2*b)} begin laplace_pdfx := sfc_laplace_pdf(a,b,x); end; {---------------------------------------------------------------------------} function levy_pdfx(a, b, x: extended): extended; {-Return the Levy probability density function with} { location a and scale parameter b > 0} begin levy_pdfx := sfc_levy_pdf(a, b, x); end; {---------------------------------------------------------------------------} function levy_cdfx(a, b, x: extended): extended; {-Return the cumulative Levy distribution function with} { location a and scale parameter b > 0} begin levy_cdfx := sfc_levy_cdf(a, b, x); end; {---------------------------------------------------------------------------} function levy_invx(a, b, y: extended): extended; {-Return the functional inverse of the Levy distribution} { with location a and scale parameter b > 0} begin levy_invx := sfc_levy_inv(a, b, y); end; {---------------------------------------------------------------------------} function logistic_pdfx(a, b, x: extended): extended; {-Return the logistic probability density function with location a} { and scale parameter b > 0, exp(-(x-a)/b)/b/(1+exp(-(x-a)/b))^2} begin logistic_pdfx := sfc_logistic_pdf(a,b,x); end; {---------------------------------------------------------------------------} function logistic_cdfx(a, b, x: extended): extended; {-Return the cumulative logistic distribution function with} { location a and scale parameter b > 0} begin logistic_cdfx := sfc_logistic_cdf(a,b,x); end; {---------------------------------------------------------------------------} function logistic_invx(a, b, y: extended): extended; {-Return the functional inverse of the logistic distribution} { with location a and scale parameter b > 0} begin logistic_invx := sfc_logistic_inv(a,b,y); end; {---------------------------------------------------------------------------} function lognormal_pdfx(a, b, x: extended): extended; {-Return the log-normal probability density function with} { location a and scale parameter b > 0, zero for x <= 0.} begin lognormal_pdfx := sfc_lognormal_pdf(a,b,x); end; {---------------------------------------------------------------------------} function lognormal_cdfx(a, b, x: extended): extended; {-Return the cumulative log-normal distribution function with} { location a and scale parameter b > 0, zero for x <= 0.} begin lognormal_cdfx := sfc_lognormal_cdf(a,b,x); end; {---------------------------------------------------------------------------} function lognormal_invx(a, b, y: extended): extended; {-Return the functional inverse of the log-normal distribution} { with location a and scale parameter b > 0, 0 < y < 1.} begin lognormal_invx := sfc_lognormal_inv(a,b,y); end; {---------------------------------------------------------------------------} function logseries_pmfx(a: extended; k: longint): extended; {-Return the logarithmic (series) probability mass function} { with shape 0 < a < 1, k > 0; result = -a^k/(k*ln(1-a)) } begin logseries_pmfx := sfc_ls_pmf(a,k); end; {---------------------------------------------------------------------------} function logseries_cdfx(a: extended; k: longint): extended; {-Return the cumulative logarithmic (series) distribution function with shape 0 < a < 1, k > 0} begin logseries_cdfx := sfc_ls_cdf(a,k); end; {---------------------------------------------------------------------------} function maxwell_pdfx(b, x: extended): extended; {-Return the Maxwell probability density function with scale b > 0, x >= 0} begin maxwell_pdfx := sfc_maxwell_pdf(b,x); end; {---------------------------------------------------------------------------} function maxwell_cdfx(b, x: extended): extended; {-Return the cumulative Maxwell distribution function with scale b > 0, x >= 0} begin maxwell_cdfx := sfc_maxwell_cdf(b,x); end; {---------------------------------------------------------------------------} function maxwell_invx(b, y: extended): extended; {-Return the functional inverse of the Maxwell distribution with scale b > 0} begin maxwell_invx := sfc_maxwell_inv(b,y); end; {---------------------------------------------------------------------------} function moyal_pdfx(a, b, x: extended): extended; {-Return the Moyal probability density function with} { location a and scale parameter b > 0} begin moyal_pdfx := sfc_moyal_pdf(a, b, x); end; {---------------------------------------------------------------------------} function moyal_cdfx(a, b, x: extended): extended; {-Return the cumulative Moyal distribution function with} { location a and scale parameter b > 0} begin moyal_cdfx := sfc_moyal_cdf(a, b, x); end; {---------------------------------------------------------------------------} function moyal_invx(a, b, y: extended): extended; {-Return the functional inverse of the Moyal distribution} { with location a and scale parameter b > 0} begin moyal_invx := sfc_moyal_inv(a, b, y); end; {---------------------------------------------------------------------------} function negbinom_cdfx(p,r: extended; k: longint): extended; {-Return the cumulative negative binomial distribution function with target} { for number of successful trials r > 0 and success probability 0 <= p <= 1} begin negbinom_cdfx := sfc_negbinom_cdf(p,r,k); end; {---------------------------------------------------------------------------} function negbinom_pmfx(p,r: extended; k: longint): extended; {-Return the negative binomial distribution probability mass function with target} { for number of successful trials r > 0 and success probability 0 <= p <= 1} begin negbinom_pmfx := sfc_negbinom_pmf(p,r,k); end; {---------------------------------------------------------------------------} function normal_pdfx(mu, sd, x: extended): extended; {-Return the normal (Gaussian) probability density function with mean mu} { and standard deviation sd>0, exp(-0.5*(x-mu)^2/sd^2) / sqrt(2*Pi*sd^2)} begin normal_pdfx := sfc_normal_pdf(mu,sd,x); end; {---------------------------------------------------------------------------} function normal_cdfx(mu, sd, x: extended): extended; {-Return the normal (Gaussian) distribution function} { with mean mu and standard deviation sd > 0 } begin normal_cdfx := sfc_normal_cdf(mu,sd,x); end; {---------------------------------------------------------------------------} function normal_invx(mu, sd, y: extended): extended; {-Return the functional inverse of normal (Gaussian) distribution} { with mean mu and standard deviation sd > 0, 0 < y < 1.} begin normal_invx := sfc_normal_inv(mu, sd, y); end; {---------------------------------------------------------------------------} function normstd_pdfx(x: extended): extended; {-Return the std. normal probability density function exp(-x^2/2)/sqrt(2*Pi)} begin normstd_pdfx := sfc_normstd_pdf(x); end; {---------------------------------------------------------------------------} function normstd_cdfx(x: extended): extended; {-Return the standard normal distribution function} begin normstd_cdfx := sfc_normstd_cdf(x); end; {---------------------------------------------------------------------------} function normstd_invx(y: extended): extended; {-Return the inverse standard normal distribution function, 0 <= y <= 1.} { For x=normstd_inv(y) and y from [0,1], normstd_cdf(x) = y} begin if y <= 0.0 then normstd_invx := -MaxExtended else if y >= 1.0 then normstd_invx := MaxExtended else normstd_invx := sfc_normstd_inv(y); end; {---------------------------------------------------------------------------} function pareto_pdfx(k, a, x: extended): extended; {-Return the Pareto probability density function with minimum value k > 0} { and shape a, x >= a > 0, result = (a/x)*(k/x)^a} begin pareto_pdfx := sfc_pareto_pdf(k,a,x); end; {---------------------------------------------------------------------------} function pareto_cdfx(k, a, x: extended): extended; {-Return the cumulative Pareto distribution function minimum value k > 0} { and shape a, x >= a > 0, result = 1-(k/x)^a} begin pareto_cdfx := sfc_pareto_cdf(k,a,x); end; {---------------------------------------------------------------------------} function pareto_invx(k, a, y: extended): extended; {-Return the functional inverse of the Pareto distribution with minimum} { value k > 0 and shape a, x >= a > 0, result = k/(1-x)^(1/a)} begin pareto_invx := sfc_pareto_inv(k,a,y); end; {---------------------------------------------------------------------------} function poisson_cdfx(mu: extended; k: longint): extended; {-Return the cumulative Poisson distribution function with mean mu >= 0} begin poisson_cdfx := sfc_poisson_cdf(mu,k); end; {---------------------------------------------------------------------------} function poisson_pmfx(mu: extended; k: longint): extended; {-Return the Poisson distribution probability mass function with mean mu >= 0} begin poisson_pmfx := sfc_poisson_pmf(mu,k); end; {---------------------------------------------------------------------------} function rayleigh_pdfx(b, x: extended): extended; {-Return the Rayleigh probability density function with} { scale b > 0, x >= 0; result = x*exp(-0.5*(x/b)^2)/b^2} begin rayleigh_pdfx := sfc_rayleigh_pdf(b,x); end; {---------------------------------------------------------------------------} function rayleigh_cdfx(b, x: extended): extended; {-Return the cumulative Rayleigh distribution function with scale b > 0, x >= 0} begin rayleigh_cdfx := sfc_rayleigh_cdf(b,x); end; {---------------------------------------------------------------------------} function rayleigh_invx(b, y: extended): extended; {-Return the functional inverse of the Rayleigh distribution with scale b > 0} begin rayleigh_invx := sfc_rayleigh_inv(b,y); end; {---------------------------------------------------------------------------} function t_pdfx(nu: longint; x: extended): extended; {-Return the probability density function of Student's t distribution, nu>0} begin t_pdfx := sfc_t_pdf(nu,x); end; {---------------------------------------------------------------------------} function t_cdfx(nu: longint; t: extended): extended; {-Return the cumulative Student t distribution with nu>0 degrees of freedom} begin t_cdfx := sfc_t_cdf(nu,t); end; {---------------------------------------------------------------------------} function t_invx(nu: longint; p: extended): extended; {-Return the functional inverse of Student's t distribution, nu>0, 0 <= p <= 1} begin t_invx := sfc_t_inv(nu,p); end; {---------------------------------------------------------------------------} function triangular_pdfx(a, b, c, x: extended): extended; {-Return the triangular probability density function with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b} begin triangular_pdfx := sfc_triangular_pdf(a,b,c,x); end; {---------------------------------------------------------------------------} function triangular_cdfx(a, b, c, x: extended): extended; {-Return the cumulative triangular distribution function with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b} begin triangular_cdfx := sfc_triangular_cdf(a,b,c,x); end; {---------------------------------------------------------------------------} function triangular_invx(a, b, c, y: extended): extended; {-Return the functional inverse of the triangular distribution with} { lower limit a, upper limit b, mode c; a<b, a <= c <= b, 0 <= y <= 1} begin triangular_invx := sfc_triangular_inv(a,b,c,y); end; {---------------------------------------------------------------------------} function uniform_pdfx(a, b, x: extended): extended; {-Return the uniform probability density function on [a,b], a<b} begin uniform_pdfx := sfc_uniform_pdf(a,b,x); end; {---------------------------------------------------------------------------} function uniform_cdfx(a, b, x: extended): extended; {-Return the cumulative uniform distribution function on [a,b], a<b} begin uniform_cdfx := sfc_uniform_cdf(a,b,x); end; {---------------------------------------------------------------------------} function uniform_invx(a, b, y: extended): extended; {-Return the functional inverse of the uniform distribution on [a,b], a<b} begin uniform_invx := sfc_uniform_inv(a,b,y); end; {---------------------------------------------------------------------------} function weibull_pdfx(a, b, x: extended): extended; {-Return the Weibull probability density function with shape a > 0} { and scale b > 0, result = a*x^(a-1)*exp(-(x/b)^a)/ b^a, x > 0} begin weibull_pdfx := sfc_weibull_pdf(a,b,x); end; {---------------------------------------------------------------------------} function weibull_cdfx(a, b, x: extended): extended; {-Return the cumulative Weibull distribution function with} { shape parameter a > 0 and scale parameter b > 0} begin weibull_cdfx := sfc_weibull_cdf(a,b,x); end; {---------------------------------------------------------------------------} function weibull_invx(a, b, y: extended): extended; {-Return the functional inverse of the Weibull distribution} { shape parameter a > 0 and scale parameter b > 0} begin weibull_invx := sfc_weibull_inv(a,b,y); end; {---------------------------------------------------------------------------} function wald_pdfx(mu, b, x: extended): extended; {-Return the Wald (inverse Gaussian) probability density} { function with mean mu > 0, scale b > 0 for x >= 0 } begin wald_pdfx := sfc_wald_pdf(mu, b, x); end; {---------------------------------------------------------------------------} function wald_cdfx(mu, b, x: extended): extended; {-Return the Wald (inverse Gaussian) distribution } { function with mean mu > 0, scale b > 0 for x >= 0} begin wald_cdfx := sfc_wald_cdf(mu, b, x); end; {---------------------------------------------------------------------------} function wald_invx(mu, b, y: extended): extended; {-Return the functional inverse of the Wald (inverse Gaussian)} { distribution with mean mu > 0, scale b > 0, 0 <= y < 1. } begin wald_invx := sfc_wald_inv(mu, b, y); end; {---------------------------------------------------------------------------} function zipf_pmfx(r: extended; k: longint): extended; {-Return the Zipf distribution probability mass function k^(-(r+1))/zeta(r+1), r>0, k>0} begin zipf_pmfx := sfc_zipf_pmf(r,k); end; {---------------------------------------------------------------------------} function zipf_cdfx(r: extended; k: longint): extended; {-Return the cumulative Zipf distribution function H(k,r+1)/zeta(r+1), r>0, k>0} begin zipf_cdfx := sfc_zipf_cdf(r,k); end; {---------------------------------------------------------------------------} {------------------ Orthogonal polynomials and related ---------------------} {---------------------------------------------------------------------------} function chebyshev_tx(n: integer; x: extended): extended; {-Return Tn(x), the Chebyshev polynomial of the first kind, degree n} begin chebyshev_tx := sfc_chebyshev_t(n,x); end; {---------------------------------------------------------------------------} function chebyshev_ux(n: integer; x: extended): extended; {-Return Un(x), the Chebyshev polynomial of the second kind, degree n} begin chebyshev_ux := sfc_chebyshev_u(n,x); end; {---------------------------------------------------------------------------} function chebyshev_vx(n: integer; x: extended): extended; {-Return V_n(x), the Chebyshev polynomial of the third kind, degree n>=0} begin chebyshev_vx := sfc_chebyshev_v(n,x); end; {---------------------------------------------------------------------------} function chebyshev_wx(n: integer; x: extended): extended; {-Return W_n(x), the Chebyshev polynomial of the fourth kind, degree n>=0} begin chebyshev_wx := sfc_chebyshev_w(n,x); end; {---------------------------------------------------------------------------} function gegenbauer_cx(n: integer; a,x: extended): extended; {-Return Cn(a,x), the nth Gegenbauer (ultraspherical) polynomial with} { parameter a. The degree n must be non-negative; a should be > -0.5 } { When a = 0, C0(0,x) = 1, and Cn(0,x) = 2/n*Tn(x) for n <> 0.} begin gegenbauer_cx := sfc_gegenbauer_c(n,a,x); end; {---------------------------------------------------------------------------} function hermite_hx(n: integer; x: extended): extended; {-Return Hn(x), the nth Hermite polynomial, degree n >= 0} begin hermite_hx := sfc_hermite_h(n,x); end; {---------------------------------------------------------------------------} function jacobi_px(n: integer; a,b,x: extended): extended; {-Return Pn(a,b,x), the nth Jacobi polynomial with parameters a,b. Degree n} { must be >= 0; a,b should be > -1 (a+b must not be an integer < -1).} begin jacobi_px := sfc_jacobi_p(n,a,b,x); end; {---------------------------------------------------------------------------} function laguerrex(n: integer; a,x: extended): extended; {-Return Ln(a,x), the nth generalized Laguerre polynomial with parameter a;} { degree n must be >= 0. x >=0 and a > -1 are the standard ranges.} begin laguerrex := sfc_laguerre(n,a,x); end; {---------------------------------------------------------------------------} function laguerre_assx(n,m: integer; x: extended): extended; {-Return the associated Laguerre polynomial Ln(m,x); n,m >= 0} begin laguerre_assx := sfc_laguerre_ass(n,m,x); end; {---------------------------------------------------------------------------} function laguerre_lx(n: integer; x: extended): extended; {-Return the nth Laguerre polynomial Ln(0,x); n >= 0} begin laguerre_lx := sfc_laguerre_l(n,x); end; {---------------------------------------------------------------------------} function legendre_px(l: integer; x: extended): extended; {-Return P_l(x), the Legendre polynomial/function P_l, degree l} begin legendre_px := sfc_legendre_p(l,x); end; {---------------------------------------------------------------------------} function legendre_qx(l: integer; x: extended): extended; {-Return Q_l(x), the Legendre function of the 2nd kind, degree l >=0, |x| <> 1} begin legendre_qx := sfc_legendre_q(l,x); end; {---------------------------------------------------------------------------} function legendre_plmx(l,m: integer; x: extended): extended; {-Return the associated Legendre polynomial P_lm(x)} begin legendre_plmx := sfc_legendre_plm(l,m,x); end; {---------------------------------------------------------------------------} function legendre_qlmx(l,m: integer; x: extended): extended; {-Return Q(l,m,x), the associated Legendre function of the second kind; l >= 0, l+m >= 0, |x|<>1} begin legendre_qlmx := sfc_legendre_qlm(l,m,x); end; {---------------------------------------------------------------------------} procedure spherical_harmonicx(l, m: integer; theta, phi: extended; var yr,yi: extended); {-Return Re and Im of the spherical harmonic function Y_lm(theta,phi)} begin sfc_spherical_harmonic(l,m,theta,phi,yr,yi); end; {---------------------------------------------------------------------------} function toroidal_plmx(l,m: integer; x: extended): extended; {-Return the toroidal harmonic function P(l-0.5,m,x); l,m=0,1; x >= 1} begin toroidal_plmx := sfc_thp(l,m,x); end; {---------------------------------------------------------------------------} function toroidal_qlmx(l,m: integer; x: extended): extended; {-Return the toroidal harmonic function Q(l-0.5,m,x); l=0,1; x > 1} begin toroidal_qlmx := sfc_thq(l,m,x); end; {---------------------------------------------------------------------------} function zernike_rx(n,m: integer; r: extended): extended; {-Return the Zernike radial polynomial Rnm(r), r >= 0, n >= m >= 0, n-m even} begin zernike_rx := sfc_zernike_r(n,m,r); end; {---------------------------------------------------------------------------} {-------------------- Hypergeometric functions -----------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function hyperg_1F1x(a,b,x: extended): extended; {-Return the confluent hypergeometric function 1F1(a,b,x); Kummer's function M(a,b,x)} begin hyperg_1F1x := sfc_1f1(a,b,x); end; {---------------------------------------------------------------------------} function hyperg_1F1rx(a,b,x: extended): extended; {-Return the regularized Kummer hypergeometric function 1F1(a,b,x)/Gamma(b)} begin hyperg_1F1rx := sfc_1f1r(a,b,x); end; {---------------------------------------------------------------------------} function hyperg_ux(a,b,x: extended): extended; {-Return Tricomi's confluent hypergeometric function U(a,b,x). If} { x<0, then a must be an integer and a<0 or 1+a-b an integer < 0.} begin hyperg_ux := sfc_chu(a,b,x); end; {---------------------------------------------------------------------------} function hyperg_2F1x(a,b,c,x: extended): extended; {-Return the Gauss hypergeometric function 2F1(a,b;c;x)} begin hyperg_2F1x := sfc_2f1(a,b,c,x); end; {---------------------------------------------------------------------------} function hyperg_2F1rx(a,b,c,x: extended): extended; {-Return the regularized Gauss hypergeometric function 2F1(a,b,c,x)/Gamma(c)} begin hyperg_2F1rx := sfc_2f1r(a,b,c,x); end; {---------------------------------------------------------------------------} function WhittakerMx(k,m,x: extended): extended; {-Return the Whittaker M function = exp(-x/2)*x^(0.5+m) * 1F1(m-k-0.5,2m+1,x)} begin WhittakerMx := sfc_whitm(k,m,x); end; {---------------------------------------------------------------------------} function WhittakerWx(k,m,x: extended): extended; {-Return the Whittaker W function = exp(-x/2)*x^(0.5+m) * U(m-k-0.5,2m+1,x)} begin WhittakerWx := sfc_whitw(k,m,x); end; {---------------------------------------------------------------------------} function hyperg_0F1x(b,x: extended): extended; {-Return the confluent hypergeometric limit function 0F1(;b;x)} begin hyperg_0F1x := sfc_0f1(b,x); end; {---------------------------------------------------------------------------} function hyperg_0F1rx(b,x: extended): extended; {-Return the regularized confluent hypergeometric limit function 0F1(;b;x)/Gamma(b)} begin hyperg_0F1rx := sfc_0f1r(b,x); end; {---------------------------------------------------------------------------} function CylinderDx(v,x: extended): extended; {-Return Whittaker's parabolic cylinder function D_v(x)} begin CylinderDx := sfc_pcfd(v,x); end; {---------------------------------------------------------------------------} function CylinderUx(a,x: extended): extended; {-Return the parabolic cylinder function U(a,x)} begin CylinderUx := sfc_pcfu(a,x); end; {---------------------------------------------------------------------------} function CylinderVx(a,x: extended): extended; {-Return the parabolic cylinder function V(a,x) with 2a integer} begin CylinderVx := sfc_pcfv(a,x); end; {---------------------------------------------------------------------------} function HermiteHx(v,x: extended): extended; {-Return the Hermite function H_v(x) of degree v} begin HermiteHx := sfc_pcfhh(v,x); end; {---------------------------------------------------------------------------} {--------------------------- Other functions -------------------------------} {---------------------------------------------------------------------------} function bernoullix(n: integer): extended; {-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3} begin bernoullix := sfc_bernoulli(n); end; {---------------------------------------------------------------------------} function bernpolyx(n: integer; x: extended): extended; {-Return the Bernoulli polynomial B_n(x), 0 <= n <= MaxBernoulli} begin bernpolyx := sfc_bernpoly(n,x); end; {---------------------------------------------------------------------------} function catalanx(x: extended): extended; {-Return the Catalan function C(x) = binomial(2x,x)/(x+1)} begin catalanx := sfc_catf(x); end; {---------------------------------------------------------------------------} function agmx(x,y: extended): extended; {-Return the arithmetic-geometric mean of |x| and |y|; |x|,|y| < sqrt(MaxExtended)} begin agmx := sfc_agm(x,y); end; {---------------------------------------------------------------------------} function debyex(n: integer; x: extended): extended; {-Return the Debye function D(n,x) = n/x^n*integral(t^n/(exp(t)-1),t=0..x) of order n>0, x>=0} begin debyex := sfc_debye(n,x); end; {---------------------------------------------------------------------------} function eulerx(n: integer): extended; {-Return the nth Euler number, 0 if n<0 or odd n} begin eulerx := sfc_euler(n); end; {---------------------------------------------------------------------------} function fibpolyx(n: integer; x: extended): extended; {-Return the Fibonacci polynomial F_n(x)} begin fibpolyx := sfc_fpoly(n,x); end; {---------------------------------------------------------------------------} function lucpolyx(n: integer; x: extended): extended; {-Return the Lucas polynomial L_n(x)} begin lucpolyx := sfc_lpoly(n,x); end; {---------------------------------------------------------------------------} function keplerx(M,e: extended): extended; {-Solve Kepler's equation, result x is the eccentric anomaly from the mean anomaly M and the } { eccentricity e >= 0; x - e*sin(x) = M, x + x^3/3 = M, or e*sinh(x) - x = M for e <1, =1, >1} begin keplerx := sfc_kepler(M, e); end; {---------------------------------------------------------------------------} function LambertWx(x: extended): extended; {-Return the Lambert W function (principal branch), x >= -1/e} begin LambertWx := sfc_LambertW(x); end; {---------------------------------------------------------------------------} function LambertW1x(x: extended): extended; {-Return the Lambert W function (-1 branch), -1/e <= x < 0} begin LambertW1x := sfc_LambertW1(x); end; {---------------------------------------------------------------------------} function li_invx(x: extended): extended; {-Return the functional inverse of li(x), li(li_inv(x))=x} begin li_invx := sfc_ali(x); end; {---------------------------------------------------------------------------} function RiemannRx(x: extended): extended; {-Return the Riemann prime counting function R(x), x >= 1/16} begin RiemannRx := sfc_ri(x); end; {---------------------------------------------------------------------------} function cosintx(n: integer; x: extended): extended; {-Return cosint(n, x) = integral(cos(t)^n, t=0..x), n>=0} begin cosintx := sfc_cosint(n,x); end; {---------------------------------------------------------------------------} function sinintx(n: integer; x: extended): extended; {-Return sinint(n, x) = integral(sin(t)^n, t=0..x), n>=0} begin sinintx := sfc_sinint(n,x); end; end.
{ project euler #1 in pascal by antekone http://anadoxin.org/blog usage: $ fpc 1.pas $ ./1 } program euler1; var sum, i: UInt32; begin sum := 0; for i := 0 to 999 do if (i mod 3 = 0) or (i mod 5 = 0) then sum := sum + i; writeln(sum) end.
program USBLister; {$mode objfpc}{$H+} { Raspberry Pi 3 Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } {$define use_tftp} uses RaspberryPi3, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, SysUtils, Classes, uLog, USB, Devices, {$ifdef use_tftp} uTFTP, Winsock2, {$endif} Ultibo, Console { Add additional units here }; var Console1, Console2, Console3 : TWindowHandle; {$ifdef use_tftp} IPAddress : string; {$endif} USBDriver : PUSBDriver; procedure Log1 (s : string); begin ConsoleWindowWriteLn (Console1, s); end; procedure Log2 (s : string); begin ConsoleWindowWriteLn (Console2, s); end; procedure Log3 (s : string); begin ConsoleWindowWriteLn (Console3, s); end; procedure Msg3 (Sender : TObject; s : string); begin Log3 (s); end; {$ifdef use_tftp} function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1000); Result := TCP.LocalAddress; end; end; TCP.Free; end; {$endif} procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; function USBDriverBind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; var i, j : integer; s : string; begin Result := USB_STATUS_DEVICE_UNSUPPORTED; if Device = nil then exit; if Interrface <> nil then exit; ConsoleWindowClear (Console1); Log ('VID : ' + Device^.Descriptor^.idVendor.ToHexString (4)); Log ('PID : ' + Device^.Descriptor^.idProduct.ToHexString (4)); Log ('Product : ' + Device^.Product); Log ('SNo : ' + Device^.SerialNumber); Log ('Device Class : ' + USBClassCodeToString (Device^.Descriptor^.bDeviceClass)); Log ('Device Subclass : ' + Device^.Descriptor^.bDeviceSubClass.ToHexString (2)); Log ('Device Protocol : ' + Device^.Descriptor^.bDeviceProtocol.ToHexString (2)); Log ('Configurations : ' + length (Device^.Configurations).ToString); Log ('First Configuration ----'); Log (' Interfaces : ' + length (Device^.Configuration^.Interfaces).ToString); for j := low (Device^.Configuration^.Interfaces) to high (Device^.Configuration^.Interfaces) do begin Log (' ---- Interface ' + j.ToString + ' ---- '); Log (' Class : ' + USBClassCodeToString (Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceClass)); Log (' SubClass : ' + Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceSubClass.ToHexString (2)); Log (' Protocol : ' + Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceProtocol.ToHexString (2)); for i := low (Device^.Configuration^.Interfaces[j]^.Endpoints) to high (Device^.Configuration^.Interfaces[j]^.Endpoints) do begin s := USBTransferTypeToString (Device^.Configuration^.Interfaces[j]^.Endpoints[i]^.bmAttributes); s := s + ' ' + USBDirectionToString ((Device^.Configuration^.Interfaces[j]^.Endpoints[i]^.bEndpointAddress shr 7) and $01); Log (' Endpoint ' + i.ToString + ' : ' + s + ' #' + (Device^.Configuration^.Interfaces[j]^.Endpoints[i]^.bEndpointAddress and $0f).ToString); end; end; end; function USBDriverUnbind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; begin Result := USB_STATUS_INVALID_PARAMETER; end; begin Console1 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_LEFT, true); Console2 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_TOPRIGHT, false); Console3 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_BOTTOMRIGHT, false); SetLogProc (@Log1); Log2 ('USB Lister.'); Log2 ('Plug in device to list information'); Log2 (''); {$ifdef use_tftp} IPAddress := WaitForIPComplete; Log3 ('TFTP Usage : tftp -i ' + IPAddress + ' PUT kernel7.img'); SetOnMsg (@Msg3); {$endif} USBDriver := USBDriverCreate; if USBDriver = nil then ThreadHalt (0); USBDriver^.Driver.DriverName := 'GENERIC USB'; USBDriver^.DriverBind := @USBDriverBind; USBDriver^.DriverUnbind := @USBDriverUnbind; USBDriverRegister (USBDriver); ThreadHalt (0); end.
unit Model.Book; interface uses System.JSON, DataAccess.Books; Type TBookListKind = (blkAll, blkOnShelf, blkAvaliable); TBook = class private FIsbn: string; procedure SetIsbn(const Value: string); public Status: string; Title: string; Author: string; ReleseDate: TDateTime; Pages: integer; Price: currency; Currency: string; Imported: TDateTime; Description: string; procedure Validate; property Isbn: string read FIsbn write SetIsbn; constructor Create(Books: IBooksDAO); overload; procedure LoadFromJSON (jsBook: TJSONObject); end; implementation { TBook } uses Utils.General, System.Classes, System.SysUtils; constructor TBook.Create(Books: IBooksDAO); begin inherited Create; self.isbn := Books.fldISBN.Value; self.title := Books.fldTitle.Value; self.author := Books.fldAuthors.Value; self.status := Books.fldStatus.Value; self.releseDate := Books.fldReleseDate.Value; self.pages := Books.fldPages.Value; self.price := Books.fldPrice.Value; self.currency := Books.fldCurrency.Value; self.imported := Books.fldImported.Value; self.description := Books.fldDescription.Value; end; procedure TBook.LoadFromJSON(jsBook: TJSONObject); begin Status := jsBook.Values['status'].Value; Title := jsBook.Values['title'].Value; Isbn := jsBook.Values['isbn'].Value; Author := jsBook.Values['author'].Value; // ReleseDate := BooksToDateTime(jsBook.Values['date'].Value); Pages := (jsBook.Values['pages'] as TJSONNumber).AsInt; Price := StrToCurr(jsBook.Values['price'].Value); Currency := jsBook.Values['currency'].Value; Description := jsBook.Values['description'].Value; Imported := Now(); end; procedure TBook.SetIsbn(const Value: string); begin FIsbn := Value; end; procedure TBook.Validate; var lValidateInfoMessage: TStringList; begin lValidateInfoMessage := TStringList.Create; try //Reguły walidacji dla książki if not TValidateLibrary.IsNotEmpty(Isbn) then lValidateInfoMessage.Add('Warość pola ISBN nie może być pusta!'); if not TValidateLibrary.CheckIBAN(Isbn) then lValidateInfoMessage.Add('Warość pola ISBN ma nieprawidłowy format!'); if lValidateInfoMessage.Count <> 0 then raise Exception.Create(lValidateInfoMessage.Text); finally lValidateInfoMessage.Free; end; end; end.
unit ideSHComponentPageFrm; interface uses SHDesignIntf, ideSHDesignIntf, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ToolWin, ComCtrls, Contnrs, VirtualTrees, Menus, ActnList; type TComponentPageForm = class(TSHComponentForm) PopupMenu1: TPopupMenu; CreateInstance1: TMenuItem; Panel1: TPanel; Tree: TVirtualStringTree; Panel2: TPanel; procedure CreateInstance1Click(Sender: TObject); private { Private declarations } function FindCategoryNode(const ACategory: string): PVirtualNode; { Tree } procedure SetTreeEvents(ATree: TVirtualStringTree); procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeIncrementalSearch( Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeDblClick(Sender: TObject); procedure TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); // procedure TreeGetHint(Sender: TBaseVirtualTree; Node: PVirtualNode; // Column: TColumnIndex; var LineBreakStyle: TVTTooltipLineBreakStyle; // var HintText: WideString); protected procedure DoOnEnter; function GetTreePopup: TPopupMenu; procedure DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure BringToTop; override; procedure ReloadComponents; end; //var // PaletteForm: TPaletteForm; implementation uses ideSHConsts, ideSHSystem, ideSHSysUtils; {$R *.dfm} type TNodeType = (ntFolder, ntServer, ntDatabase, ntObject); PTreeRec = ^TTreeRec; TTreeRec = record NormalText: string; StaticText: string; Action: TSHAction; NodeType: TNodeType; ImageIndex: Integer; end; { TPaletteForm } constructor TComponentPageForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); if Assigned(ModalForm) then begin Caption := Format(ACallString, [Component.Caption]); ModalForm.OnAfterModalClose := DoOnAfterModalClose; Panel1.BevelInner := bvLowered; Panel2.Visible := False; Tree.Color := clWindow; end; SetTreeEvents(Tree); end; destructor TComponentPageForm.Destroy; begin inherited Destroy; end; procedure TComponentPageForm.BringToTop; begin if Tree.CanFocus then Tree.SetFocus; end; procedure TComponentPageForm.ReloadComponents; var I: Integer; Node: PVirtualNode; NodeData: PTreeRec; begin Tree.BeginUpdate; Tree.Clear; try for I := 0 to Pred(DesignerIntf.ActionList.ActionCount) do if Supports(DesignerIntf.ActionList.Actions[I], ISHAction) and ((DesignerIntf.ActionList.Actions[I] as ISHAction).CallType = actCallPalette) and (DesignerIntf.ActionList.Actions[I] as ISHAction).SupportComponent(Component.ClassIID) then begin DesignerIntf.ActionList.Actions[I].Update; Node := FindCategoryNode(DesignerIntf.ActionList.Actions[I].Category); if not Assigned(Node) then begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); if Assigned(NodeData) then begin NodeData.NormalText := DesignerIntf.ActionList.Actions[I].Category; NodeData.ImageIndex := IMG_PACKAGE; NodeData.NodeType := ntFolder; end; end; Node := Tree.AddChild(Node); NodeData := Tree.GetNodeData(Node); if Assigned(NodeData) then begin NodeData.NormalText := TAction(DesignerIntf.ActionList.Actions[I]).Caption; NodeData.Action := TSHAction(DesignerIntf.ActionList.Actions[I]); NodeData.ImageIndex := TAction(DesignerIntf.ActionList.Actions[I]).ImageIndex; NodeData.NodeType := ntObject; NodeData.StaticText := Format('%s', [ShortCutToText(TAction(DesignerIntf.ActionList.Actions[I]).ShortCut)]); if NodeData.StaticText = '()' then NodeData.StaticText := EmptyStr; end; if Assigned(ModalForm) then if Assigned(Node.Parent) then Tree.Expanded[Node.Parent] := True; end; finally Tree.EndUpdate; if Tree.GetFirst <> nil then begin Tree.FocusedNode := Tree.GetFirst; Tree.Selected[Tree.FocusedNode] := True; end; end; end; function TComponentPageForm.FindCategoryNode(const ACategory: string): PVirtualNode; var Node: PVirtualNode; NodeData: PTreeRec; begin Result := nil; Node:= Tree.GetFirst; while not Assigned(Result) and Assigned(Node) do begin NodeData := Tree.GetNodeData(Node); if Assigned(NodeData) then begin if (NodeData.NodeType = ntFolder) and AnsiSameText(NodeData.NormalText, ACategory) then Result := Node; end; Node := Tree.GetNextSibling(Node); end; end; procedure TComponentPageForm.DoOnEnter; var NodeData: PTreeRec; begin if Assigned(Tree.FocusedNode) then begin NodeData := Tree.GetNodeData(Tree.FocusedNode); if Assigned(NodeData) and (NodeData.NodeType = ntObject) and Assigned(NodeData.Action) and (NodeData.Action.Enabled) then NodeData.Action.Execute; end; end; function TComponentPageForm.GetTreePopup: TPopupMenu; var NodeData: PTreeRec; begin Result := nil; if Assigned(Tree.FocusedNode) then begin NodeData := Tree.GetNodeData(Tree.FocusedNode); if Assigned(NodeData) then ; end; end; procedure TComponentPageForm.DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); begin if ModalResult = mrOK then DoOnEnter; end; procedure TComponentPageForm.CreateInstance1Click(Sender: TObject); begin DoOnEnter; end; { Tree } procedure TComponentPageForm.SetTreeEvents(ATree: TVirtualStringTree); begin ATree.Images := Designer.ImageList; ATree.OnGetNodeDataSize := TreeGetNodeDataSize; ATree.OnFreeNode := TreeFreeNode; ATree.OnGetImageIndex := TreeGetImageIndex; ATree.OnGetText := TreeGetText; ATree.OnPaintText := TreePaintText; ATree.OnIncrementalSearch := TreeIncrementalSearch; ATree.OnKeyDown := TreeKeyDown; ATree.OnDblClick := TreeDblClick; ATree.OnGetPopupMenu := TreeGetPopupMenu; ATree.OnCompareNodes := TreeCompareNodes; // ATree.OnGetHint := TreeGetHint; end; procedure TComponentPageForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TComponentPageForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var NodeData: PTreeRec; begin NodeData := Sender.GetNodeData(Node); if Assigned(NodeData) then Finalize(NodeData^); end; procedure TComponentPageForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData: PTreeRec; begin ImageIndex := -1; NodeData := Sender.GetNodeData(Node); if Assigned(NodeData) then begin if Assigned(NodeData.Action) then begin NodeData.Action.Update; if NodeData.Action.Enabled then Node.States := Node.States - [vsDisabled] else Node.States := Node.States + [vsDisabled]; end; if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := NodeData.ImageIndex; end; end; procedure TComponentPageForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var NodeData: PTreeRec; begin NodeData := Sender.GetNodeData(Node); if Assigned(NodeData) then begin case TextType of ttNormal: CellText := NodeData.NormalText; ttStatic: begin if Node.ChildCount > 0 then CellText := Format('%d', [Node.ChildCount]) else CellText := EmptyStr; if Assigned(NodeData.Action) and not Assigned(ModalForm) then CellText := NodeData.StaticText; end; end; end; end; procedure TComponentPageForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); begin case TextType of ttNormal: if Node.ChildCount <> 0 then TargetCanvas.Font.Style := [fsBold]; ttStatic: if Sender.Focused and (vsSelected in Node.States) then TargetCanvas.Font.Color := clWindow else TargetCanvas.Font.Color := clGray; end; end; procedure TComponentPageForm.TreeIncrementalSearch( Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); var NodeData: PTreeRec; begin NodeData := Sender.GetNodeData(Node); if Assigned(NodeData) then if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(NodeData.NormalText)) <> 1 then Result := 1; end; procedure TComponentPageForm.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Assigned(Tree.FocusedNode) and (Key = VK_RETURN) then DoOnEnter; end; procedure TComponentPageForm.TreeDblClick(Sender: TObject); var HT: THitInfo; P: TPoint; NodeData: PTreeRec; begin GetCursorPos(P); if Assigned(Tree.FocusedNode) then begin NodeData := Tree.GetNodeData(Tree.FocusedNode); P := Tree.ScreenToClient(P); Tree.GetHitTestInfoAt(P.X, P.Y, True, HT); if (HT.HitNode = Tree.FocusedNode) and not (hiOnItemButton in HT.HitPositions) then begin if Assigned(ModalForm) then begin if Assigned(NodeData) and (NodeData.NodeType = ntObject) then ModalForm.ModalResultCode := mrOK end else DoOnEnter; end; end; end; procedure TComponentPageForm.TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); var HT: THitInfo; begin AskParent := False; PopupMenu := nil; if Assigned(Tree.FocusedNode) then begin Tree.GetHitTestInfoAt(P.X, P.Y, True, HT); if HT.HitNode = Sender.FocusedNode then PopupMenu := GetTreePopup; if not Assigned(PopupMenu) then Exit; end; end; procedure TComponentPageForm.TreeCompareNodes( Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PTreeRec; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); Result := CompareStr(Data1.NormalText, Data2.NormalText); end; //procedure TComponentPageForm.TreeGetHint(Sender: TBaseVirtualTree; Node: PVirtualNode; // Column: TColumnIndex; var LineBreakStyle: TVTTooltipLineBreakStyle; // var HintText: WideString); //var // NodeData: PTreeRec; //begin // NodeData := Sender.GetNodeData(Node); // if Assigned(NodeData) and (NodeData.NodeType = ntObject) then // if Length(NodeData.StaticText) > 0 then // HintText := Format('%s (%s)', [NodeData.NormalText, NodeData.StaticText]) // else // HintText := Format('%s', [NodeData.NormalText]); //end; end.
unit TpDb; interface uses SysUtils, Classes, Db, AdoDb, TypInfo, ThHtmlDocument, ThHeaderComponent, ThNotifierList, ThTag, ThListSource, ThDbData, ThDataConnection, ThRegExpr, TpControls, TpInterfaces; type TTpDb = class(TThHeaderComponent, ITpIncludeLister) private FDesignConnection: TThDataConnection; FDebug: Boolean; protected procedure SetDesignConnection(const Value: TThDataConnection); protected procedure ListPhpIncludes(inIncludes: TStringList); virtual; procedure Tag(inTag: TThTag); override; public constructor Create(inOwner: TComponent); override; public property DesignConnection: TThDataConnection read FDesignConnection write SetDesignConnection; published property Debug: Boolean read FDebug write FDebug; end; // TTpDataSource = class(TThHeaderComponent, IThListSource) private FDataSource: TDataSource; FDb: TTpDb; FDebug: Boolean; FDesignOnly: Boolean; FItems: TStringList; FUpdating: Boolean; FNotifiers: TThNotifierList; FOnBeforeExecute: TTpEvent; FOnFailure: TTpEvent; FOnSuccess: TTpEvent; FWantsActive: Boolean; protected function GetActive: Boolean; function GetDataSet: TCustomADODataSet; virtual; abstract; function GetItems: TStrings; function GetNotifiers: TThNotifierList; procedure SetActive(const Value: Boolean); procedure SetDataSet(const Value: TCustomADODataSet); procedure SetDb(const Value: TTpDb); virtual; procedure SetDesignOnly(const Value: Boolean); protected procedure DataChange(Sender: TObject; Field: TField); procedure DbChanged; virtual; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Tag(inTag: TThTag); override; procedure UpdateItems; protected property Active: Boolean read GetActive write SetActive default false; property Db: TTpDb read FDb write SetDb; public constructor Create(inOwner: TComponent); override; destructor Destroy; override; public property DataSet: TCustomADODataSet read GetDataSet write SetDataSet; property DataSource: TDataSource read FDataSource; property DesignOnly: Boolean read FDesignOnly write SetDesignOnly default false; property OnBeforeExecute: TTpEvent read FOnBeforeExecute write FOnBeforeExecute; property OnFailure: TTpEvent read FOnFailure write FOnFailure; property OnSuccess: TTpEvent read FOnSuccess write FOnSuccess; published property Debug: Boolean read FDebug write FDebug; end; // TTpDataTable = class(TTpDataSource) private FTable: TAdoTable; protected function GetDataSet: TCustomADODataSet; override; function GetTableName: string; procedure SetTableName(const Value: string); protected procedure Tag(inTag: TThTag); override; public constructor Create(inOwner: TComponent); override; published property Active; property Db; property DesignOnly; property OnBeforeExecute; property OnFailure; property OnSuccess; property TableName: string read GetTableName write SetTableName; end; // TTpDataQuery = class(TTpDataSource) private FParams: TStringList; FQuery: TAdoQuery; FSQL: TStringList; protected function GetDataSet: TCustomADODataSet; override; procedure SetParams(const Value: TStringList); procedure SetSQL(const Value: TStringList); protected function DoParamReplace(ARegExpr: TRegExpr): string; function ParamsReplace(const inText: string): string; procedure SqlChange(inSender: TObject); procedure Tag(inTag: TThTag); override; public constructor Create(inOwner: TComponent); override; destructor Destroy; override; published property Active; property Db; property DesignOnly; property OnBeforeExecute; property OnFailure; property OnSuccess; property Params: TStringList read FParams write SetParams; property SQL: TStringList read FSQL write SetSQL; end; procedure TpSetDataSource(inOwner: TComponent; Value: TTpDataSource; var ioSrcProp: TTpDataSource; inDataProp: TThDbData); implementation uses DCPbase64; const cTpParamExpression = '\{%([^}]*)\}'; procedure TpSetDataSource(inOwner: TComponent; Value: TTpDataSource; var ioSrcProp: TTpDataSource; inDataProp: TThDbData); begin if ioSrcProp <> nil then ioSrcProp.RemoveFreeNotification(inOwner); // ioSrcProp := Value; // if ioSrcProp <> nil then ioSrcProp.FreeNotification(inOwner); // if ioSrcProp <> nil then inDataProp.DataSource := ioSrcProp.DataSource else inDataProp.DataSource := nil; end; { TTpDb } constructor TTpDb.Create(inOwner: TComponent); begin inherited; FDesignConnection := TThDataConnection.Create(Self); end; procedure TTpDb.SetDesignConnection(const Value: TThDataConnection); begin FDesignConnection.Assign(Value); end; procedure TTpDb.ListPhpIncludes(inIncludes: TStringList); begin inIncludes.Add('TpDb.php'); end; procedure TTpDb.Tag(inTag: TThTag); begin inTag.Attributes.Add('tpDebugFlag', Debug); end; { TTpDataSource } constructor TTpDataSource.Create(inOwner: TComponent); begin inherited; FDataSource := TDataSource.Create(Self); FDataSource.OnDataChange := DataChange; FNotifiers := TThNotifierList.Create; end; destructor TTpDataSource.Destroy; begin FNotifiers.Free; FItems.Free; inherited; end; procedure TTpDataSource.Loaded; begin inherited; Active := FWantsActive; end; procedure TTpDataSource.DbChanged; begin if (Db <> nil) and (DataSet <> nil) then DataSet.Connection := Db.DesignConnection.Connection; end; procedure TTpDataSource.SetDb(const Value: TTpDb); begin if FDb <> Value then begin if FDb <> nil then FDb.RemoveFreeNotification(Self); FDb := Value; if FDb <> nil then FDb.FreeNotification(Self); DbChanged; end; end; procedure TTpDataSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then if AComponent = FDb then begin FDb := nil; DbChanged; end; end; function TTpDataSource.GetActive: Boolean; begin if (DataSet = nil) then Result := false else Result := DataSet.Active; end; procedure TTpDataSource.SetActive(const Value: Boolean); begin if (Active <> Value) then if csLoading in ComponentState then FWantsActive := true else if not Value then DataSet.Active := false else if (Db <> nil) and (DataSet <> nil) then try Db.DesignConnection.Connected := true; DataSet.Active := Db.DesignConnection.Connected; except end; end; procedure TTpDataSource.SetDataSet(const Value: TCustomADODataSet); begin FDataSource.DataSet := Value; end; procedure TTpDataSource.SetDesignOnly(const Value: Boolean); begin FDesignOnly := Value; end; procedure TTpDataSource.Tag(inTag: TThTag); begin with inTag do begin if Db <> nil then Add('tpDb', Db.Name); Attributes.Add('tpDebugFlag', Debug); Add('tpOnBeforeExecute', OnBeforeExecute); Add('tpOnFailure', OnFailure); Add('tpOnSuccess', OnSuccess); Add('tpName', Name); end; end; procedure TTpDataSource.DataChange(Sender: TObject; Field: TField); begin if not FUpdating then begin UpdateItems; FNotifiers.Notify; end; end; procedure TTpDataSource.UpdateItems; var b: TBookmark; begin if FItems <> nil then begin //ItemsLoaded := false; FItems.BeginUpdate; FUpdating := true; try FItems.Clear; if Active and (DataSet.FieldCount > 0) then begin b := DataSet.GetBookmark; DataSet.First; while not DataSet.Eof do begin FItems.Add(DataSet.Fields[0].AsString); DataSet.Next; end; DataSet.GotoBookmark(b); DataSet.FreeBookmark(b); //ItemsLoaded := true; end; finally FUpdating := false; FItems.EndUpdate; end; //Notifiers.Notify; end; end; function TTpDataSource.GetItems: TStrings; begin if FItems = nil then begin FItems := TStringList.Create; UpdateItems; end; Result := FItems; end; function TTpDataSource.GetNotifiers: TThNotifierList; begin Result := FNotifiers; end; { TTpDataTable } constructor TTpDataTable.Create(inOwner: TComponent); begin inherited; FTable := TAdoTable.Create(Self); DataSet := FTable; end; procedure TTpDataTable.SetTableName(const Value: string); begin FTable.TableName := Value; end; function TTpDataTable.GetDataSet: TCustomADODataSet; begin Result := FTable; end; function TTpDataTable.GetTableName: string; begin Result := FTable.TableName; end; procedure TTpDataTable.Tag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpDataTable'); Add('tpSQL', Base64EncodeStr('SELECT * from ' + TableName)); end; end; { TTpDataQuery } constructor TTpDataQuery.Create(inOwner: TComponent); begin inherited; FSql := TStringList.Create; FSql.OnChange := SqlChange; FParams := TStringList.Create; FParams.OnChange := SqlChange; FQuery := TAdoQuery.Create(Self); DataSet := FQuery; end; destructor TTpDataQuery.Destroy; begin FParams.Free; FSql.Free; inherited; end; function TTpDataQuery.GetDataSet: TCustomADODataSet; begin Result := FQuery; end; procedure TTpDataQuery.SetParams(const Value: TStringList); begin FParams.Assign(Value); end; procedure TTpDataQuery.SetSQL(const Value: TStringList); begin FSql.Assign(Value); end; function TTpDataQuery.DoParamReplace(ARegExpr: TRegExpr): string; begin try Result := FParams.Values[ARegExpr.Match[1]]; except Result := ''; end; //ThFindContent(Owner, ARegExpr.Match[1], Result); end; function TTpDataQuery.ParamsReplace(const inText: string): string; begin with TRegExpr.Create do try Expression := cTpParamExpression; Result := ReplaceEx(inText, DoParamReplace); finally Free; end; end; procedure TTpDataQuery.SqlChange(inSender: TObject); begin //FQuery.SQL.Assign(Sql); FQuery.SQL.Text := ParamsReplace(Sql.Text); end; procedure TTpDataQuery.Tag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpDataQuery'); Add('tpSQL', Base64EncodeStr(FSql.Text)); //Add('tpParams', Base64EncodeStr(FParams.Text)); end; end; end.
{ * * Copyright (C) 2014-2015 ozok <ozok26@gmail.com> * * This file is part of InstagramSaver. * * InstagramSaver 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. * * InstagramSaver 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 InstagramSaver. If not, see <http://www.gnu.org/licenses/>. * * } unit UnitImageTypeExtractor; interface uses Classes, Windows, SysUtils, Messages, StrUtils, MediaInfoDll; type TImageTypeEx = class(TObject) private FType: string; FErrorCode: integer; function ReadType(const ImagePath: string; const DeepCheck: Boolean): string; public property ImageType: string read FType; property ErrorCode: integer read FErrorCode; constructor Create(const ImagePath: string; const DeepCheck: Boolean); destructor Destroy; override; end; implementation const ERROR_OK = 0; ERROR_UNKKOWN_TYPE = 1; ERROR_EMPTY_FILE = 2; ERROR_INVALID_FILE = 3; { TImageTypeEx } constructor TImageTypeEx.Create(const ImagePath: string; const DeepCheck: Boolean); begin FErrorCode := 0; if FileExists(ImagePath) then begin FType := ReadType(ImagePath, DeepCheck); end else begin FType := ''; end; end; destructor TImageTypeEx.Destroy; begin inherited; end; function TImageTypeEx.ReadType(const ImagePath: string; const DeepCheck: Boolean): string; var MediaInfoHandle: Cardinal; LFormat: string; LSize: string; LSizeInt: integer; begin Result := ''; if (FileExists(ImagePath)) then begin MediaInfoHandle := MediaInfo_New(); if MediaInfoHandle <> 0 then begin try MediaInfo_Open(MediaInfoHandle, PWideChar(ImagePath)); MediaInfo_Option(0, 'Complete', '1'); LFormat := MediaInfo_Get(MediaInfoHandle, Stream_General, 0, 'Format', Info_Text, Info_Name); if LFormat = 'JPEG' then begin Result := '.jpg' end else if LFormat = 'MPEG-4' then begin Result := '.mp4' end else begin FErrorCode := ERROR_UNKKOWN_TYPE; //FileSize LSize := MediaInfo_Get(MediaInfoHandle, Stream_General, 0, 'FileSize', Info_Text, Info_Name); if Length(LSize) > 0 then begin if TryStrToInt(LSize, LSizeInt) then begin if LSizeInt = 0 then begin FErrorCode := ERROR_EMPTY_FILE; end; end else begin FErrorCode := ERROR_EMPTY_FILE; end; end; end; finally MediaInfo_Close(MediaInfoHandle); end; end; end; end; end.
unit uInterface; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, ExtCtrls, StdCtrls, uPageObject, Forms, uSearch, uNotifier; type TInterface = class private is_wide: Boolean; SearchPnl, ControlPnl: TPanel; MainPnl: TScrollBox; ImportLbl, ExportLbl, ArchiveLbl: TLabel; ImportIcn, ExportIcn, ArchiveIcn: TImage; HeaderLbl: TLabel; Search: TSearch; PageTop, PageGap: Integer; PageObjects: array of TPageObject; Notifier: TNotifier; procedure LblMouseClick(Sender: TObject); procedure LblMouseEnter(Sender: TObject); procedure LblMouseLeave(Sender: TObject); procedure FormResize(Sender: TObject); procedure LoadNotes; procedure LoadPage(Path: String); procedure ClearPage; public procedure SetNotification(Text: String); constructor Create(WC: TWinControl); end; implementation uses Dialogs, Graphics, uGlobal, FileUtil, uPostObject, uAddObject, uListObject; constructor TInterface.Create(WC: TWinControl); begin is_wide := False; SearchPnl := TPanel.Create(Nil); with SearchPnl do begin Parent := WC; AnchorToParent(TControl(SearchPnl), [akLeft, akTop, akRight]); Height := 64; Color := $00D6D6D6; BorderStyle := bsNone; BevelOuter := bvNone; end; Search := TSearch.Create(SearchPnl, WC.Width); ControlPnl := TPanel.Create(Nil); with ControlPnl do begin Parent := WC; AnchorToParent(TControl(ControlPnl), [akLeft, akTop, akRight]); AnchorSide[akTop].Side:= asrBottom; AnchorSide[akTop].Control:= SearchPnl; Height := 34; Color := $00343434; BorderStyle := bsNone; BevelOuter := bvNone; end; MainPnl := TScrollBox.Create(Nil); with MainPnl do begin Parent := WC; AnchorToParent(TControl(MainPnl), [akLeft, akTop, akRight, akBottom]); AnchorSide[akTop].Side:= asrBottom; AnchorSide[akTop].Control:= ControlPnl; Width := WC.Width; Color := $00EBEBEB; BorderStyle := bsNone; HorzScrollBar.Visible := False; VertScrollBar.Increment := 32; ChildSizing.TopBottomSpacing := 16; OnResize := @FormResize; end; HeaderLbl := TLabel.Create(Nil); with HeaderLbl do begin Parent := SearchPnl; Caption := 'Storyboard'; Font.Size := 18; Font.Color := $00343434; Font.Quality := fqCleartype; Top := (SearchPnl.Height - Canvas.TextHeight(Caption)) div 2; Left := Top; end; // Import ImportIcn := TImage.Create(Nil); with ImportIcn do begin Parent := ControlPnl; Picture.LoadFromFile('./src/icons/import_g.png'); Width := 16; Height := 16; Top := (ControlPnl.Height - Height) div 2; Left := HeaderLbl.Left; Tag := 0; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; ImportLbl := TLabel.Create(Nil); with ImportLbl do begin Parent := ControlPnl; Caption := ' Import'; Font.Size := 10; Font.Color := $00747474; Font.Quality := fqCleartype; Top := (ControlPnl.Height - Canvas.TextHeight(Caption)) div 2; Left := ImportIcn.Left + ImportIcn.Width; Tag := 0; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; // Export ExportIcn := TImage.Create(Nil); with ExportIcn do begin Parent := ControlPnl; Picture.LoadFromFile('./src/icons/export_g.png'); Width := 16; Height := 16; Top := (ControlPnl.Height - Height) div 2; Left := ImportLbl.Left + ImportLbl.Width; Tag := 1; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; ExportLbl := TLabel.Create(Nil); with ExportLbl do begin Parent := ControlPnl; Caption := ' Export'; Font.Size := 10; Font.Color := $00747474; Font.Quality := fqCleartype; Top := (ControlPnl.Height - Canvas.TextHeight(Caption)) div 2; Left := ExportIcn.Left + ExportIcn.Width; Tag := 1; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; // Archive ArchiveIcn := TImage.Create(Nil); with ArchiveIcn do begin Parent := ControlPnl; Picture.LoadFromFile('./src/icons/archive_g.png'); Width := 16; Height := 16; Top := (ControlPnl.Height - Height) div 2; Left := ExportLbl.Left + ExportLbl.Width; Tag := 2; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; ArchiveLbl := TLabel.Create(Nil); with ArchiveLbl do begin Parent := ControlPnl; Caption := ' Archive'; Font.Size := 10; Font.Color := $00747474; Font.Quality := fqCleartype; Top := (ControlPnl.Height - Canvas.TextHeight(Caption)) div 2; Left := ArchiveIcn.Left + ArchiveIcn.Width; Tag := 2; Cursor := crHandPoint; OnClick := @LblMouseClick; OnMouseEnter := @LblMouseEnter; OnMouseLeave := @LblMouseLeave; end; //LoadNotes; //ClearPage; PageTop := 16; PageGap := 8; Notifier := TNotifier.Create(MainPnl, PageTop); LoadNotes; LoadPage(LIVE_DATA + 'Page_items.psv'); end; procedure TInterface.SetNotification(Text: String); begin // Hide notification object, update if state change if (Text = '') and not (Notifier.Text = '') then begin Notifier.Text := Text; Notifier.Hide; PageTop := 16; FormResize(Nil); end else if not (Text = '') then begin Notifier.Text := Text; Notifier.Show; PageTop := Notifier.Bottom + PageGap; FormResize(Nil); end; end; procedure TInterface.LoadNotes; var Posts, Contents: TStringList; k, Top: Integer; begin // Add button if Length(PageObjects) = 0 then Top := PageTop else Top := PageObjects[Length(PageObjects)-1].Bottom + PageGap; SetLength(PageObjects, Length(PageObjects)+1); PageObjects[Length(PageObjects)-1] := TAddObject.Create(MainPnl, Top, MainPnl.Parent.Width); Top := PageObjects[Length(PageObjects)-1].Bottom + PageGap; // Add posts Posts := TStringList.Create; Contents := TStringList.Create; FindAllFiles(Posts, LIVE_DATA, '*.psv', true); for k := Posts.Count - 1 downto 0 do begin Contents.LoadFromFile(Posts.Strings[k]); if not (PSV(Contents.Strings[0])[0] = 'Post') then Posts.Delete(k); end; for k := 0 to Posts.Count - 1 do begin SetLength(PageObjects, Length(PageObjects)+1); PageObjects[Length(PageObjects)-1] := TPostObject.Create(MainPnl, Top, MainPnl.Parent.Width, Basename(Posts.Strings[k])); Top := PageObjects[Length(PageObjects)-1].Bottom + PageGap; end; end; procedure TInterface.LoadPage(Path: String); var k, Top: Integer; Contents: TStringList; begin if Length(PageObjects) = 0 then Top := PageTop else Top := PageObjects[Length(PageObjects)-1].Bottom + PageGap; Contents := TStringList.Create; Contents.LoadFromFile(Path); for k := 0 to Contents.Count - 1 do begin SetLength(PageObjects, Length(PageObjects) + 1); case PSV(Contents.Strings[k])[0] of 'List': PageObjects[Length(PageObjects) - 1] := TListObject.Create(MainPnl, Top, MainPnl.Parent.Width, Contents.Strings[k]); end; end; end; procedure TInterface.ClearPage; var k: Integer; begin for k := 0 to Length(PageObjects) - 1 do PageObjects[k].Destroy; SetLength(PageObjects, 0); end; procedure TInterface.FormResize(Sender: TObject); var k, Top: Integer; begin Top := PageTop; for k := 0 to Length(PageObjects)-1 do begin PageObjects[k].Top := Top; Top := Top+PageObjects[k].Height+8; end; end; procedure TInterface.LblMouseClick(Sender: TObject); begin case (Sender as TControl).Tag of 0: ShowMessage('Import'); 1: ShowMessage('Export'); 2: ShowMessage('Archive'); end end; procedure TInterface.LblMouseEnter(Sender: TObject); begin case (Sender as TControl).Tag of 0: begin ImportLbl.Font.Color := $00EBEBEB; ImportIcn.Picture.LoadFromFile('./src/icons/import_w.png') end; 1: begin ExportLbl.Font.Color := $00EBEBEB; ExportIcn.Picture.LoadFromFile('./src/icons/export_w.png') end; 2: begin ArchiveLbl.Font.Color := $00EBEBEB; ArchiveIcn.Picture.LoadFromFile('./src/icons/archive_w.png') end; end end; procedure TInterface.LblMouseLeave(Sender: TObject); begin case (Sender as TControl).Tag of 0: begin ImportLbl.Font.Color := $00747474; ImportIcn.Picture.LoadFromFile('./src/icons/import_g.png') end; 1: begin ExportLbl.Font.Color := $00747474; ExportIcn.Picture.LoadFromFile('./src/icons/export_g.png') end; 2: begin ArchiveLbl.Font.Color := $00747474; ArchiveIcn.Picture.LoadFromFile('./src/icons/archive_g.png') end; end end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_VENDA_CABECALHO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit EcfVendaCabecalhoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TEcfVendaCabecalhoVO = class(TVO) private FID: Integer; FNOME_CAIXA: String; FID_GERADO_CAIXA: Integer; FID_EMPRESA: Integer; FID_CLIENTE: Integer; FID_ECF_FUNCIONARIO: Integer; FID_ECF_MOVIMENTO: Integer; FID_ECF_DAV: Integer; FID_ECF_PRE_VENDA_CABECALHO: Integer; FSERIE_ECF: String; FCFOP: Integer; FCOO: Integer; FCCF: Integer; FDATA_VENDA: TDateTime; FHORA_VENDA: String; FVALOR_VENDA: Extended; FTAXA_DESCONTO: Extended; FDESCONTO: Extended; FTAXA_ACRESCIMO: Extended; FACRESCIMO: Extended; FVALOR_FINAL: Extended; FVALOR_RECEBIDO: Extended; FTROCO: Extended; FVALOR_CANCELADO: Extended; FTOTAL_PRODUTOS: Extended; FTOTAL_DOCUMENTO: Extended; FBASE_ICMS: Extended; FICMS: Extended; FICMS_OUTRAS: Extended; FISSQN: Extended; FPIS: Extended; FCOFINS: Extended; FACRESCIMO_ITENS: Extended; FDESCONTO_ITENS: Extended; FSTATUS_VENDA: String; FNOME_CLIENTE: String; FCPF_CNPJ_CLIENTE: String; FCUPOM_CANCELADO: String; FLOGSS: String; FDATA_SINCRONIZACAO: TDateTime; FHORA_SINCRONIZACAO: String; published property Id: Integer read FID write FID; property NomeCaixa: String read FNOME_CAIXA write FNOME_CAIXA; property IdGeradoCaixa: Integer read FID_GERADO_CAIXA write FID_GERADO_CAIXA; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE; property IdEcfFuncionario: Integer read FID_ECF_FUNCIONARIO write FID_ECF_FUNCIONARIO; property IdEcfMovimento: Integer read FID_ECF_MOVIMENTO write FID_ECF_MOVIMENTO; property IdEcfDav: Integer read FID_ECF_DAV write FID_ECF_DAV; property IdEcfPreVendaCabecalho: Integer read FID_ECF_PRE_VENDA_CABECALHO write FID_ECF_PRE_VENDA_CABECALHO; property SerieEcf: String read FSERIE_ECF write FSERIE_ECF; property Cfop: Integer read FCFOP write FCFOP; property Coo: Integer read FCOO write FCOO; property Ccf: Integer read FCCF write FCCF; property DataVenda: TDateTime read FDATA_VENDA write FDATA_VENDA; property HoraVenda: String read FHORA_VENDA write FHORA_VENDA; property ValorVenda: Extended read FVALOR_VENDA write FVALOR_VENDA; property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; property Desconto: Extended read FDESCONTO write FDESCONTO; property TaxaAcrescimo: Extended read FTAXA_ACRESCIMO write FTAXA_ACRESCIMO; property Acrescimo: Extended read FACRESCIMO write FACRESCIMO; property ValorFinal: Extended read FVALOR_FINAL write FVALOR_FINAL; property ValorRecebido: Extended read FVALOR_RECEBIDO write FVALOR_RECEBIDO; property Troco: Extended read FTROCO write FTROCO; property ValorCancelado: Extended read FVALOR_CANCELADO write FVALOR_CANCELADO; property TotalProdutos: Extended read FTOTAL_PRODUTOS write FTOTAL_PRODUTOS; property TotalDocumento: Extended read FTOTAL_DOCUMENTO write FTOTAL_DOCUMENTO; property BaseIcms: Extended read FBASE_ICMS write FBASE_ICMS; property Icms: Extended read FICMS write FICMS; property IcmsOutras: Extended read FICMS_OUTRAS write FICMS_OUTRAS; property Issqn: Extended read FISSQN write FISSQN; property Pis: Extended read FPIS write FPIS; property Cofins: Extended read FCOFINS write FCOFINS; property AcrescimoItens: Extended read FACRESCIMO_ITENS write FACRESCIMO_ITENS; property DescontoItens: Extended read FDESCONTO_ITENS write FDESCONTO_ITENS; property StatusVenda: String read FSTATUS_VENDA write FSTATUS_VENDA; property NomeCliente: String read FNOME_CLIENTE write FNOME_CLIENTE; property CpfCnpjCliente: String read FCPF_CNPJ_CLIENTE write FCPF_CNPJ_CLIENTE; property CupomCancelado: String read FCUPOM_CANCELADO write FCUPOM_CANCELADO; property Logss: String read FLOGSS write FLOGSS; property DataSincronizacao: TDateTime read FDATA_SINCRONIZACAO write FDATA_SINCRONIZACAO; property HoraSincronizacao: String read FHORA_SINCRONIZACAO write FHORA_SINCRONIZACAO; end; TListaEcfVendaCabecalhoVO = specialize TFPGObjectList<TEcfVendaCabecalhoVO>; implementation initialization Classes.RegisterClass(TEcfVendaCabecalhoVO); finalization Classes.UnRegisterClass(TEcfVendaCabecalhoVO); end.
unit InflatablesList_ShownPicturesManager; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Graphics, Controls, ExtCtrls, InflatablesList_Types, InflatablesList_ItemPictures, InflatablesList_Manager; type TILShownPicturesManagerEntry = record PictureKind: TLIItemPictureKind; OldPicture: TBitmap; Picture: TBitmap; Image: TImage; Background: TControl; end; TILShownPicturesManager = class(TObject) private fILManager: TILManager; fRightAnchor: Integer; fLeft: TControl; fRight: TControl; fImages: array[0..2] of TILShownPicturesManagerEntry; fPictures: TILItemPictures; public constructor Create(ILManager: TILManager; RightAnchor: Integer; Left,Right: TControl; ImgA,ImgB,ImgC: TImage; BcgrA,BcgrB,BcgrC: TControl); Function Kind(Image: TImage): TLIItemPictureKind; virtual; Function Image(PictureKind: TLIItemPictureKind): TImage; virtual; procedure ShowPictures(Pictures: TILItemPictures); procedure UpdateSecondary; virtual; end; implementation uses InflatablesList_Utils, InflatablesList_Item; constructor TILShownPicturesManager.Create(ILManager: TILManager; RightAnchor: Integer; Left,Right: TControl; ImgA,ImgB,ImgC: TImage; BcgrA,BcgrB,BcgrC: TControl); begin inherited Create; fILManager := ILManager; fRightAnchor := RightAnchor; fLeft := Left; fRight := Right; Fillchar(fImages,SizeOf(fImages),0); fImages[0].Image := ImgC; fImages[0].Background := BcgrC; fImages[1].Image := ImgB; fImages[1].Background := BcgrB; fImages[2].Image := ImgA; fImages[2].Background := BcgrA; fPictures := nil; end; //------------------------------------------------------------------------------ Function TILShownPicturesManager.Kind(Image: TImage): TLIItemPictureKind; var i: Integer; begin Result := ilipkUnknown; For i := Low(fImages) to High(fImages) do If fImages[i].Image = Image then begin Result := fImages[i].PictureKind; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILShownPicturesManager.Image(PictureKind: TLIItemPictureKind): TImage; var i: Integer; begin Result := nil; For i := Low(fImages) to High(fImages) do If fImages[i].PictureKind = PictureKind then begin Result := fImages[i].Image; Break{For i}; end; end; //------------------------------------------------------------------------------ procedure TILShownPicturesManager.ShowPictures(Pictures: TILItemPictures); const SPACING = 8; var i: Integer; TempInt: Integer; ArrowsVisible: Boolean; SecCount: Integer; Function AssignPic(Index: Integer; PictureKind: TLIItemPictureKind): Boolean; begin Result := False; If fPictures.CheckIndex(Index) then begin fImages[i].PictureKind := PictureKind; fImages[i].Picture := fPictures[Index].Thumbnail; Result := True; end end; begin fPictures := Pictures; If Assigned(fPictures) then begin For i := Low(fImages) to High(fImages) do begin fImages[i].PictureKind := ilipkUnknown; fImages[i].OldPicture := fImages[i].Picture; fImages[i].Picture := nil; end; i := Low(fImages); // assign pictures If AssignPic(fPictures.IndexOfPackagePicture,ilipkPackage) then Inc(i); If AssignPic(fPictures.CurrentSecondary,ilipkSecondary) then Inc(i); If AssignPic(fPictures.IndexOfItemPicture,ilipkMain) then Inc(i); For i := Low(fImages) to High(fImages) do begin If not Assigned(fImages[i].Picture) and (fImages[i].PictureKind <> ilipkUnknown) then begin If fImages[i].PictureKind = ilipkMain then fImages[i].Picture := fILManager.DataProvider.ItemDefaultPictures[TILItem(fPictures.Owner).ItemType] else fImages[i].Picture := fILManager.DataProvider.EmptyPicture; end; If fImages[i].Picture <> fImages[i].OldPicture then begin fImages[i].Image.Picture.Assign(fImages[i].Picture); fImages[i].Image.ShowHint := fImages[i].PictureKind <> ilipkUnknown; fImages[i].Background.Visible := not Assigned(fImages[i].Picture); end; If (fImages[i].PictureKind = ilipkSecondary) and (fPictures.SecondaryCount(False) > 1) then fImages[i].Image.Hint := IL_ItemPictureKindToStr(fImages[i].PictureKind,True) + IL_Format(' %d/%d', [fPictures.SecondaryIndex(fPictures.CurrentSecondary) + 1,fPictures.SecondaryCount(False)]) else fImages[i].Image.Hint := IL_ItemPictureKindToStr(fImages[i].PictureKind,True); end; // realign TempInt := fRightAnchor; ArrowsVisible := False; SecCount := fPictures.SecondaryCount(False); For i := Low(fImages) to High(fImages) do begin If (fImages[i].PictureKind = ilipkSecondary) and (SecCount > 1) then begin fRight.Left := TempInt - fRight.Width; fImages[i].Image.Left := fRight.Left - fImages[i].Image.Width - SPACING; fLeft.Left := fImages[i].Image.Left - fLeft.Width - SPACING; TempInt := fLeft.Left - SPACING; ArrowsVisible := True; end else begin fImages[i].Image.Left := TempInt - fImages[i].Image.Width; TempInt := fImages[i].Image.Left - SPACING; end; fImages[i].Background.Left := fImages[i].Image.Left + (fImages[i].Image.Width - fImages[i].Background.Width) div 2; end; fLeft.Visible := ArrowsVisible; fRight.Visible := ArrowsVisible; end else begin TempInt := fRightAnchor; For i := Low(fImages) to High(fImages) do begin fImages[i].PictureKind := ilipkUnknown; fImages[i].Picture := nil; fImages[i].Image.Picture.Assign(nil); fImages[i].Image.ShowHint := False; fImages[i].Image.Left := TempInt - fImages[i].Image.Width; fImages[i].Background.Visible := True; fImages[i].Background.Left := fImages[i].Image.Left + (fImages[i].Image.Width - fImages[i].Background.Width) div 2; Dec(TempInt,fImages[i].Image.Width + SPACING); end; end; end; //------------------------------------------------------------------------------ procedure TILShownPicturesManager.UpdateSecondary; var i: Integer; begin // find where is secondary assigned If Assigned(fPictures) then For i := Low(fImages) to High(fImages) do If fImages[i].PictureKind = ilipkSecondary then begin If fPictures.CheckIndex(fPictures.CurrentSecondary) then begin If fImages[i].Picture <> fPictures[fPictures.CurrentSecondary].Thumbnail then begin If Assigned(fPictures[fPictures.CurrentSecondary].Thumbnail) then fImages[i].Picture := fPictures[fPictures.CurrentSecondary].Thumbnail else fImages[i].Picture := fILManager.DataProvider.EmptyPicture; fImages[i].Image.Picture.Assign(fImages[i].Picture); end; If fPictures.SecondaryCount(False) > 1 then fImages[i].Image.Hint := IL_ItemPictureKindToStr(fImages[i].PictureKind,True) + IL_Format(' %d/%d', [fPictures.SecondaryIndex(fPictures.CurrentSecondary) + 1,fPictures.SecondaryCount(False)]) else fImages[i].Image.Hint := IL_ItemPictureKindToStr(fImages[i].PictureKind,True); end; Break{For i}; end; end; end.
unit OpenCV.Utils; interface uses Winapi.Windows, System.SysUtils, Vcl.Graphics, OpenCV.Core, OpenCV.ImgProc, OpenCV.ObjDetect, OpenCV.Legacy, OpenCV.HighGUI, uMemory; procedure Bitmap2IplImage(IplImg: PIplImage; Bitmap: TBitmap); procedure IplImage2Bitmap(IplImg: PIplImage; Bitmap: TBitmap); procedure SavePIplImageAsBitmap(IplImg: PIplImage; FileName: string); function HasOpenCV: Boolean; function LoadOpenCV: Boolean; implementation var FOpenCVState: TOpenCVPrecent = ocvUndevined; function LoadOpenCV: Boolean; begin if FOpenCVState = ocvUndevined then begin if CvLoadCoreLib and CvLoadImgProcLib and CvLoadObjDetectLib and CvLoadLegacyLib and CvLoadHighGUILib then FOpenCVState := ocvAvailable else FOpenCVState := ocvUnavailable; end; Result := FOpenCVState = ocvAvailable; end; function HasOpenCV: Boolean; begin Result := True; end; procedure SavePIplImageAsBitmap(IplImg: PIplImage; FileName: string); var B: TBitmap; begin B := TBitmap.Create; try B.PixelFormat := pf24bit; B.SetSize(IplImg.width, IplImg.height); IplImage2Bitmap(IplImg, B); B.SaveToFile(FileName); finally F(B); end; end; {----------------------------------------------------------------------------- Procedure: IplImage2Bitmap Author: De Sanctis Date: 23-set-2005 Arguments: iplImg: PIplImage; bitmap: TBitmap Description: convert a IplImage to a Windows bitmap ----------------------------------------------------------------------------- } procedure Bitmap2IplImage(IplImg: PIplImage; Bitmap: TBitmap); const IPL_ORIGIN_TL = 0; IPL_ORIGIN_BL = 1; var I: INTEGER; J: INTEGER; Offset: Longint; DataByte: PByteArray; RowIn: PByteArray; IsBGR, IsGray: Boolean; function ToString(A: TA4CVChar): string; var I: Integer; begin SetLength(Result, 4); for I := 0 to 3 do Result[I + 1] := Char(A[I]); Result := Trim(Result); end; begin Assert((iplImg.Depth = 8) and (iplImg.NChannels in [1,3]), 'IplImage2Bitmap: Not a 24 bit color iplImage!'); Bitmap.Height := IplImg.Height; Bitmap.Width := IplImg.Width; IsBGR := ToString(IplImg.ChannelSeq) = 'BGR'; IsGray := ToString(IplImg.ChannelSeq) = 'GRAY'; for J := 0 to Bitmap.Height - 1 do begin // origin BL = Bottom-Left if (Iplimg.Origin = IPL_ORIGIN_BL) then RowIn := Bitmap.Scanline[Bitmap.Height - 1 - J] else RowIn := Bitmap.Scanline[J]; Offset := Longint(Iplimg.ImageData) + IplImg.WidthStep * J; DataByte := Pbytearray(Offset); if IsBGR then begin { direct copy of the iplImage row bytes to bitmap row } CopyMemory(DataByte, Rowin, IplImg.WidthStep); end else if IsGray then begin if Bitmap.PixelFormat = pf24Bit then for I := 0 to Bitmap.Width - 1 do Databyte[I] := (RowIn[3 * I] * 77 + RowIn[3 * I + 1] * 151 + RowIn[3 * I + 2] * 28) shr 8; if Bitmap.PixelFormat = pf8Bit then for I := 0 to Bitmap.Width - 1 do Databyte[I] := RowIn[I]; end else begin for I := 0 to 3 * Bitmap.Width - 1 do begin Databyte[I + 2] := RowIn[I]; Databyte[I + 1] := RowIn[I + 1]; Databyte[I] := RowIn[I + 2]; end; end; end; end; { IplImage2Bitmap } {----------------------------------------------------------------------------- Procedure: IplImage2Bitmap Author: De Sanctis Date: 23-set-2005 Arguments: iplImg: PIplImage; bitmap: TBitmap Description: convert a IplImage to a Windows bitmap ----------------------------------------------------------------------------- } procedure IplImage2Bitmap(IplImg: PIplImage; Bitmap: TBitmap); const IPL_ORIGIN_TL = 0; IPL_ORIGIN_BL = 1; var I: INTEGER; J: INTEGER; Offset: Longint; DataByte: PByteArray; RowIn: PByteArray; IsBGR, IsGray: Boolean; function ToString(A: TA4CVChar): string; var I: Integer; begin SetLength(Result, 4); for I := 0 to 3 do Result[I + 1] := Char(A[I]); Result := Trim(Result); end; begin Assert((iplImg.Depth in [8]) and (iplImg.NChannels in [1,3]), 'IplImage2Bitmap: Not a 24 bit color iplImage!'); Bitmap.SetSize(IplImg.Width, IplImg.Height); IsBGR := ToString(IplImg.ChannelSeq) = 'BGR'; IsGray := ToString(IplImg.ChannelSeq) = 'GRAY'; for J := 0 to Bitmap.Height - 1 do begin // origin BL = Bottom-Left if (Iplimg.Origin = IPL_ORIGIN_BL) then RowIn := Bitmap.Scanline[Bitmap.Height - 1 - J] else RowIn := Bitmap.Scanline[J]; Offset := Longint(Iplimg.ImageData) + IplImg.WidthStep * J; DataByte := Pbytearray(Offset); if IsBGR then begin { direct copy of the iplImage row bytes to bitmap row } CopyMemory(Rowin, DataByte, IplImg.WidthStep); end else if IsGray then begin if Bitmap.PixelFormat = pf24Bit then for I := 0 to Bitmap.Width - 1 do begin RowIn[3 * I] := Databyte[I]; RowIn[3 * I + 1] := Databyte[I]; RowIn[3 * I + 2] := Databyte[I]; end; if Bitmap.PixelFormat = pf8Bit then for I := 0 to Bitmap.Width - 1 do RowIn[I] := Databyte[I]; end else begin for I := 0 to 3 * Bitmap.Width - 1 do begin RowIn[I] := Databyte[I + 2]; RowIn[I + 1] := Databyte[I + 1]; RowIn[I + 2] := Databyte[I]; end; end; end; end; { IplImage2Bitmap } end.
{..............................................................................} { Summary Extract source library files out of an integrated library } { Version 1.0 } { } { Copyright (c) 2005 by Altium Limited } {..............................................................................} {..............................................................................} Program ExtractSourceLibsFromIntLibs; Var SourceFolder : String; FilesList : TStringList; i : Integer; Begin If IntegratedLibraryManager = Nil then Exit; If (InputQuery('Extract IntLib Files','Enter folder containing IntLib files',SourceFolder)) Then Begin If (SourceFolder <> '') Then If (SourceFolder[Length(SourceFolder)] <> '\') Then SourceFolder := SourceFolder + '\'; If (DirectoryExists(SourceFolder)) Then Begin Try FilesList := TStringList.Create; FilesList.Sorted := True; FilesList.Duplicates := dupIgnore; // FindFiles function is a built in function from Scripting... FindFiles(SourceFolder,'*.IntLib',faAnyFile,False,FilesList); For i := 0 To FilesList.Count - 1 Do IntegratedLibraryManager.ExtractSources(FilesList.Strings[i]); Finally FilesList.Free; End; End; End; End. {..............................................................................} {..............................................................................}
unit InfoDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TInfoDialog = class(TForm) // function ShowDialog : longint;\ private { Private declarations } protected { Protected declarations } public { Public declarations } PushButton : String; procedure AddText( X, Y : integer; Text, NameFont : string; SizeFont : integer; Color : TColor ); procedure AddButton( X, Y : integer; Text : string ); procedure ButtonClick(Sender: TObject); constructor CreateNew(AOwner: TComponent); published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Losev Controls', [TInfoDialog]); end; constructor TInfoDialog.CreateNew(AOwner: TComponent); begin //FD:=TForm.Create(nil); inherited CreateNew(AOwner); Position:=poScreenCenter; Scaled:=false; BorderStyle:=bsDialog; BorderIcons:=[]; end; procedure TInfoDialog.AddText( X, Y : integer; Text, NameFont : string; SizeFont : integer; Color : TColor ); var l : TLabel; begin l:=TLabel.Create(Self); l.AutoSize:=true; l.Font.Name:=NameFont; l.Font.Size:=SizeFont; l.Font.Color:=Color; l.Caption:=Text; if X=0 then l.Left:=(Width-l.Width) div 2 else l.Left:=X; if Y=0 then l.Top:=(Height-l.Height) div 2 else l.Top:=Y; InsertControl(l); //InsertComponent(l); end; procedure TInfoDialog.AddButton( X, Y : integer; Text : string ); var b : TButton; begin b:=TButton.Create(Self); b.Left:=X; b.Top:=Y; b.Width:=100; b.Height:=25; b.Caption:=Text; b.OnClick:=ButtonClick; InsertControl(b); //InsertComponent(b); end; procedure TInfoDialog.ButtonClick(Sender: TObject); begin PushButton:=TButton(Sender).Caption; Close; end; //function TInfoDialog.ShowDialog : longint; //begin //FD.Height:=Height; //FD.Width:=Width; {with EnterDialogForm do begin EnterDialogForm:=TEnterDialogForm.Create(nil); Caption:=FCaption; Label1.Caption:=FText; Edit1.PasswordChar:=FPasswordChar; Edit1.Text:=FInputText; case FButtons of MB_OK : begin Button1.Visible:=true; Button1.Caption:='Ok'; Button1.Left:=(Width-Button1.Width) div 2; Button2.Visible:=false; Button2.Caption:=''; end; MB_OKCANCEL : begin Button1.Visible:=true; Button1.Caption:='Ok'; Button1.Left:=(Width-Button1.Width-Button2.Width-20) div 2; Button2.Visible:=true; Button2.Caption:='Отмена'; Button2.Left:=Button1.Left+Button1.Width+20; end; end; Enter:=EnterDialogForm.ShowModal; FInputText:=Edit1.Text; EnterDialogForm.Free; end;} //f.Free; //end; end.
unit ojVirtualTreesDesign; interface uses classes, ojVirtualTrees, DesignEditors, DesignMenus, ColnEdit; type TojVirtualTreeEditor = class(TDefaultEditor) protected procedure ShowColumnsDesigner; procedure ShowTreeDesigner; public procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetComponent: TojBaseVirtualTree; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; implementation uses dialogs, ojVirtualStringTreeDesign, ojVirtualDrawTreeDesign; type TVirtualTreeCast = class(TojBaseVirtualTree); procedure TojVirtualTreeEditor.Edit; begin ShowColumnsDesigner; end; procedure TojVirtualTreeEditor.ExecuteVerb(Index: Integer); var v_inh, v_local: integer; begin v_inh:= inherited GetVerbCount; if Index < v_inh then inherited ExecuteVerb(Index) else begin v_local:= Index - v_inh; case v_local of 0: {---}; 1: ShowColumnsDesigner; 2: ShowTreeDesigner; end; end; Designer.Modified; end; function TojVirtualTreeEditor.GetComponent: TojBaseVirtualTree; begin result:= TojBaseVirtualTree(inherited GetComponent); end; function TojVirtualTreeEditor.GetVerb(Index: Integer): string; var v_inh, v_local: integer; begin v_inh:= inherited GetVerbCount; if Index < v_inh then result:= inherited GetVerb(Index) else begin v_local:= Index - v_inh; case v_local of 0: result:= '-'; 1: result:= 'Columns'; 2: result:= 'Advanced'; end; end; end; function TojVirtualTreeEditor.GetVerbCount: Integer; begin result:= (inherited GetVerbCount) + 3; end; procedure TojVirtualTreeEditor.ShowColumnsDesigner; begin ShowCollectionEditor(Designer, Component, TVirtualTreeCast(Component).Header.Columns, 'Columns'); end; procedure TojVirtualTreeEditor.ShowTreeDesigner; begin if GetComponent.InheritsFrom(TojCustomVirtualStringTree) then TojVirtualStringTreeDesignForm.ShowDesigner(TojCustomVirtualStringTree(GetComponent)) else if GetComponent.InheritsFrom(TojCustomVirtualDrawTree) then TojVirtualDrawTreeDesignForm.ShowDesigner(TojCustomVirtualDrawTree(GetComponent)); end; end.
unit U_User; interface Uses Graphics, Forms, Classes; type TConnectState = (CS_CONNECT=0, CS_DISCONNECT=1, CS_HIDDEN=2); TUser = class private FNick: String; FMail: String; FConnectState : TConnectState; FImage: TBitMap; FUserID: Integer; procedure SetNick (value: String); procedure SetMail (Value:String); procedure SetConnectState (Value: TConnectState); procedure SetImage (Value: TBitMap); procedure SetUserID (Value: Integer); Public Destructor Destroy; Constructor Create; procedure LoadAvatarFromFile (URL: String); published property Nick: string read FNick write SetNick; property Mail: String read FMail write SetMail; property ConnectState: TConnectState read FConnectState write SetConnectState; property Avatar: TBitmap read FImage write SetImage; property UserId: Integer read FUserID write SetUserID; end; TContactList = TList; TContact = class (TUser) private FIsActive: Boolean; ///----> no me acuerdo para que era FIndex: Integer; procedure SetIsActive (value: Boolean); procedure SetIndex (Value: Integer); public WDW_Conversation: TForm; Constructor Create (_idx: integer); destructor Destroy; function GetIndex: Integer; published property IsActive: Boolean read FIsActive write SetIsActive; property UserIndex: Integer read FIndex write SetIndex; end; implementation //////////////////////////////////////////////////////////////////////////////// /////////// TUSER IMPLEMENTATIONS //////////////////////////////////////////////////////////////////////////////// //GETTERS & SETTERS procedure TUser.SetNick (value: String); begin self.FNick:=value; end; procedure TUser.SetMail (Value:String); begin self.FMail:=value; end; procedure TUser.SetConnectState (Value: TConnectState); begin self.FConnectState:=value; end; procedure TUser.SetImage (Value: TBitMap); begin self.FImage:=value; end; procedure TUser.SetUserID (Value: Integer); begin self.FUserID:=value; end; //PUBLIC IMPLEMENTATIONS Destructor TUser.Destroy; Begin Self.FImage.Free; End; Constructor TUser.Create; Begin Self.FImage:= TBitMap.Create; End; procedure TUser.LoadAvatarFromFile (URL: String); Begin ////----FALTA COMPROBAR SI EL ARCHIVO EXISTE if self.FImage<>nil then self.FImage.LoadFromFile(URL); End; //////////////////////////////////////////////////////////////////////////////// /////////// TCONTACT IMPLEMENTATIONS //////////////////////////////////////////////////////////////////////////////// //GETTERS & SETTERS procedure TContact.SetIsActive (value: Boolean); begin self.FIsActive:=value; end; procedure TContact.SetIndex (Value: Integer); begin FIndex:= value; end; //PUBLIC IMPLEMENTATIONS constructor TContact.Create(_idx: integer); begin self.FIndex:= _idx; //FWDW_Conversation:=TForm.Create(nil); end; function TContact.GetIndex: Integer; begin result:= FIndex; end; destructor TContact.Destroy; begin self.WDW_Conversation.Free; end; end. //End U_User
unit GLDRotateXYZParamsFrame; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDSystem, GLDUpDown; type TGLDRotateXYZParamsFrame = class(TFrame) GB_Rotate: TGroupBox; L_AngleX: TLabel; L_AngleY: TLabel; L_AngleZ: TLabel; E_AngleX: TEdit; E_AngleY: TEdit; E_AngleZ: TEdit; UD_AngleX: TGLDUpDown; UD_AngleY: TGLDUpDown; UD_AngleZ: TGLDUpDown; procedure ValueChangeUD(Sender: TObject); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; function HaveRotateXYZ: GLboolean; function GetParams: TGLDRotateXYZParams; procedure SetParams(const Params: TGLDRotateXYZParams); procedure SetParamsFrom(Source: TPersistent); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX, GLDModify; constructor TGLDRotateXYZParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; function TGLDRotateXYZParamsFrame.HaveRotateXYZ: GLboolean; begin Result := True; if Assigned(FDrawer) and Assigned(FDrawer.EditedModify) and (FDrawer.EditedModify is TGLDRotateXYZ) then Result := True; end; function TGLDRotateXYZParamsFrame.GetParams: TGLDRotateXYZParams; begin if HaveRotateXYZ then Result.Center := TGLDRotateXYZ(FDrawer.EditedModify).Center.Vector3f else Result.Center := GLD_VECTOR3F_ZERO; Result.AngleX := UD_AngleX.Position; Result.AngleY := UD_AngleY.Position; Result.AngleZ := UD_AngleZ.Position; end; procedure TGLDRotateXYZParamsFrame.SetParams(const Params: TGLDRotateXYZParams); begin UD_AngleX.Position := Params.AngleX; UD_AngleY.Position := Params.AngleY; UD_AngleZ.Position := Params.AngleZ; end; procedure TGLDRotateXYZParamsFrame.SetParamsFrom(Source: TPersistent); begin if Assigned(Source) and (Source is TGLDRotateXYZ) then SetParams(TGLDRotateXYZ(Source).Params); end; procedure TGLDRotateXYZParamsFrame.ApplyParams; begin if HaveRotateXYZ then TGLDRotateXYZ(FDrawer.EditedModify).Params := GetParams; end; procedure TGLDRotateXYZParamsFrame.ValueChangeUD(Sender: TObject); begin if HaveRotateXYZ then with TGLDRotateXYZ(FDrawer.EditedModify) do if Sender = UD_AngleX then AngleX := UD_AngleX.Position else if Sender = UD_AngleY then AngleY := UD_AngleY.Position else if Sender = UD_AngleZ then AngleZ := UD_AngleZ.Position; end; procedure TGLDRotateXYZParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDRotateXYZParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDRotateXYZParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; if Assigned(FDrawer) then SetParamsFrom(FDrawer.EditedModify); end; end.
unit UnitTimers; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, UnitTypesAndVars, UnitGlobal, UnitConsts, Math, UnitClasses; type TFormTimers = class(TForm) TimerWork: TTimer; TimerDoTransaction: TTimer; TimerReadMapInfo: TTimer; procedure TimerWorkTimer(Sender: TObject); procedure TimerDoTransactionTimer(Sender: TObject); procedure TimerReadMapInfoTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FLocateHwnd: HWND; FForgeOldTime: TDateTime; FReadMapInfoCounter: integer; public { Public declarations } end; var FormTimers: TFormTimers; implementation uses ClsMaps, ClsGames, UnitShowWGs, UnitGeneralSet, UnitSetWGAttr, UnitMain, UnitShowWorkTransactions, UnitShowPets, UnitShowStuffs, UnitDevelop, UnitShowUniverseStove; {$R *.dfm} procedure TFormTimers.TimerWorkTimer(Sender: TObject); var tmpTransaction: TTransaction; begin // 如果不能工作,禁用工作时钟,并结束工作 if not ThisWork.CanWork then begin TimerWork.Enabled:=False; FormMain.EndWork; exit; end; // 获取当前事务 tmpTransaction := ThisWork.GetCurrTransaction; // 当前事务正在工作,并且不是刚开始工作,退出 if tmpTransaction.IsWorking and (not ThisWork.IsFirstTime) then exit; if ThisWork.IsFirstTime then // 如果是本轮中的刚开始,还没有做任何步骤,那么不可能是已做完本步骤的情况 ThisWork.IsFirstTime := False else // 现在是应该已经做完本步骤的情况,进入下一步 ThisWork.GotoNextTrans; if ThisWork.GetNextTransToDo then // 还有Transaction要完成 begin tmpTransaction := ThisWork.GetCurrTransaction; tmpTransaction.Init; tmpTransaction.IsWorking := True; TimerDoTransaction.Enabled := True; TimerWork.Enabled := False; end else // 全部步骤已经完成 begin ThisWork.RepeatCounter := ThisWork.RepeatCounter + 1; // 执行数加 1 if (ThisWork.RepeatCount = -1) or (ThisWork.RepeatCounter < ThisWork.RepeatCount) then // 循环 ThisWork.GotoTrans(0, True) else // 停止工作 ThisWork.CanWork := False; end; // 刷新工作状态显示 FormShowWorkTransactions.ShowTransactions; end; procedure TFormTimers.TimerDoTransactionTimer(Sender: TObject); var tmpStep, tmpTransStep: TStepInfo; myhwnd: HWND; tmpTransaction: TTransaction; tmpCurrMap, tmpMap: TMapInfo; tmpWin: TWindowInfo; tmpNode: TNodeInfo; i, tmpint: Integer; tmpDWORD: DWORD; tmpBoolean: Boolean; tmpStove: StoveInfo; tmpString: String; Buffer: DWORD; tmpPharmMap, tmpPharmName: String; prevMap: DWORD; prevX, prevY: DWORD; tmpHealTransaction: TTransaction; tmpReturnTransNum: Integer; setHealIter: Integer; begin tmpTransaction := ThisWork.GetCurrTransaction; // 获得当前子任务 if (not ThisWork.CanWork) then // 如果任务无法工作,善后处理 begin tmpTransaction.IsWorking := False; TimerDoTransaction.Enabled := False; TimerWork.Enabled := True; exit; end; Sleep(TimeToSleep); // 延时,由基本设置窗口决定 if tmpTransaction.IsFinish then // 如果子任务完成,善后 begin tmpTransaction.IsWorking := False; tmpTransaction.State := 1; TimerDoTransaction.Enabled := False; if GetUserEnvState = UserEnvDialog then CancelNPCDialog; TimerWork.Enabled := True; exit; end; //---------------------------------------------------------------------------- tmpStep := tmpTransaction.GetCurrStep; // 获得当前步骤 case tmpStep.Action of //-------------------------------------------------------------------------- // 左键单击,选择对话框的内容 //-------------------------------------------------------------------------- ActLeftClick: begin if tmpStep.SubStepIndex = 0 then // 最一开始,要按一次 begin if GetUserEnvState = UserEnvDialog then // 只有在Dialog状态才能按左键 begin tmpTransaction.SetOldTime; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then Exit; // 没有找到 LeftClickOnSomeWindow_Send(tmpWin.Window, StrToIntDef(tmpStep.X, 0), StrToIntDef(tmpStep.Y, 0)); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; Exit; end; end; if ((tmpStep.Z = 'BattleState') and (GetUserEnvState = UserEnvBattle)) or ((tmpStep.Z = 'NormalState') and (GetUserEnvState = UserEnvNormal)) or (((Pos(WideString(tmpStep.Z), GetNPCDialog) > 0) or (tmpStep.Z = '')) and (GetUserEnvState = UserEnvDialog)) then // 满足条件,到下一步 begin tmpStep.SubStepIndex := 0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; end else if GetUserEnvState=UserEnvDialog then // 只有在Dialog状态才能按左键 begin if not tmpTransaction.HasPassedInterval(5000) then exit; tmpTransaction.SetOldTime; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then Exit; // 没有找到 LeftClickOnSomeWindow_Send(tmpWin.Window, StrToIntDef(tmpStep.X, 0), StrToIntDef(tmpStep.Y, 0)); end; end; //-------------------------------------------------------------------------- // 右键单击 //-------------------------------------------------------------------------- ActRightClick: begin if tmpStep.SubStepIndex = 0 then // 最一开始,要按一次 begin if GetUserEnvState = UserEnvDialog then begin // 如果是NPC对话状态,取消对话 CancelNPCDialog; end else if GetUserEnvState = UserEnvNormal then begin // 如果是普通状态,记录当前时间,在指定位置点击右键,并进入下一步。 tmpTransaction.SetOldTime; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then exit; // 没有找到 RightClickOnSomeWindow_Send(tmpWin.Window, StrToIntDef(tmpStep.X, 0), StrToIntDef(tmpStep.Y, 0)); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; exit; end; case GetUserEnvState of // 判断当前状态 UserEnvDialog: // 对话状态 if (Pos(WideString(tmpStep.Z), GetNPCDialog) > 0) or (tmpStep.Z = '') then begin // 符合指定对话 tmpStep.SubStepIndex := 0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; end else begin // 不符合指定对话------------------ 0.90 add tmpTransaction.Init; TimerDoTransaction.Enabled := False; TimerWork.Enabled := True; tmpTransaction.State := 1; if GetUserEnvState = UserEnvDialog then CancelNPCDialog; ThisWork.GotoTrans(0, True); FormShowWorkTransactions.ShowTransactions; end; UserEnvNormal: // 只有在Normal状态才能按右键 begin if not tmpTransaction.HasPassedInterval(5000) then exit; tmpTransaction.SetOldTime; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then Exit; // 没有找到 RightClickOnSomeWindow_Send(tmpWin.Window, StrToIntDef(tmpStep.X, 0), StrToIntDef(tmpStep.Y, 0)); end; end; end; //-------------------------------------------------------------------------- // 移动位置:移动到地图内的某个坐标 //-------------------------------------------------------------------------- ActMoveToPos: begin //check current pos? GetCurrPosXY(prevX,prevY); if (prevX <> StrToInt(tmpStep.X)) or (prevY <> StrToInt(tmpStep.Y)) then begin tmpTransaction.PosX := StrToInt(tmpStep.X); tmpTransaction.PosY := StrToInt(tmpStep.Y); MoveToHL_Pos(tmpTransaction.PosX, tmpTransaction.PosY, true); // 移动到指定坐标点 Sleep(200); end else begin tmpTransaction.GotoNextStep; // 时间延迟 end; end; //-------------------------------------------------------------------------- // 来到地图:瞬移到某个地图:X-地图的ID //-------------------------------------------------------------------------- ActGoToMap: begin tmpDWORD := ReadCurrMapID; // 获得当前地图标识 if tmpDWORD = 0 then Exit; // 正在切换地图中 tmpCurrMap := GameMaps.ItemOfMapID(tmpDWORD); // 获取当前地图信息 if tmpCurrMap = nil then begin ThisWork.CanWork := False; ShowMessage('Unable to find map: '); Exit; end; tmpMap := GameMaps.ItemOfMapID(StrToIntDef(tmpStep.X, 0)); // 获取目的地图信息 if tmpMap = tmpCurrMap then // 已经瞬移到了 begin tmpStep.SubStepIndex := 0; ThisMove.Free; ThisMove := Nil; tmpTransaction.GotoNextStep; Exit; end; case tmpStep.SubStepIndex of 0: // Initialize, find path begin ThisMove.Free; ThisMove := TMove.Create; if not ThisMove.Init(tmpCurrMap.PosInMapList, tmpMap.PosInMapList) then begin ThisMove.Free; ThisMove := Nil; ThisWork.CanWork := False; ShowMessage('No path found, movement canceled'); Exit; end; tmpTransaction.ClearOldTime; tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 1: begin // 路径走完,退出 if ThisMove.GetCurrPathNodeIndex = ThisMove.PathNodeCount then Exit; // 获得当前路径节点 tmpNode := ThisMove.GetCurrPathNode; // 如果当前地图 = 路径节点出口一致,跳至下一路径节点,并退出。 if tmpCurrMap.ID = tmpNode.OutMapID then begin tmpTransaction.ClearOldTime; ThisMove.GotoNextPathNode; Exit; end; if tmpNode.InHL_X <> -1 then // 普通移动 begin if not tmpTransaction.HasPassedInterval(5000) then Exit; tmpTransaction.SetOldTime; MoveToHL_Pos(tmpNode.InHL_X, tmpNode.InHL_Y, false); // 移动到指定坐标点 end else // 要做Trans begin ThisTrans := GameMaps.TransportList.ItemOfTransportID(tmpNode.InHL_Y); // 返回指定标识的传送点信息 ThisTrans.StepIndex := 0; ThisTrans.OldNPCDialog := GetNPCDialog; // 返回NPC对话信息 tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; end; 2: // 这个是专门给Tran做的,发出动作 begin If ThisTrans.StepIndex = ThisTrans.Count then // Trans的步骤已经做完 begin if GetUserEnvState = UserEnvDialog then // 还有残余对话框 begin CancelNPCDialog; end else // 已经没有残余对话框了 begin tmpNode := ThisMove.GetCurrPathNode; if tmpCurrMap.ID = tmpNode.OutMapID then begin tmpTransaction.ClearOldTime; ThisMove.GotoNextPathNode; tmpStep.SubStepIndex := 1; Exit; end; end; Exit; end; tmpTransStep := ThisTrans.Items[ThisTrans.StepIndex]; case tmpTransStep.Action of 0: // Left-Click begin if GetUserEnvState = UserEnvDialog then // 必须得是对话框情况下才能按左键 begin tmpTransaction.SetOldTime; tmpTransaction.OldNPCDialog := GetNPCDialog; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then Exit; // 没有找到; myhwnd := tmpWin.Window; EnableWindow(myhwnd, False); Sleep(100); LeftClickOnSomeWindow_Send(myhwnd, StrToIntDef(tmpTransStep.X, 0) + PlayLeftJust, StrToIntDef(tmpTransStep.Y, 0)+ PlayTopJust); Sleep(100); EnableWindow(myhwnd, True); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end else begin // ThisTrans.StepIndex := 0; end; end; 1: // Right-Click begin if GetUserEnvState = UserEnvNormal then // Must be in normal state to right-click begin tmpTransaction.SetOldTime; tmpTransaction.OldNPCDialog := GetNPCDialog; HLInfoList.GlobalHL.LocateToPlayWindow(tmpWin); if tmpWin = nil then Exit; myhwnd := tmpWin.Window; EnableWindow(myhwnd, False); Sleep(100); RightClickOnSomeWindow_Send(myhwnd, StrToIntDef(tmpTransStep.X, 0) + PlayLeftJust, StrToIntDef(tmpTransStep.Y, 0) + PlayTopJust); Sleep(100); EnableWindow(myhwnd, True); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end else begin // If the network delay fails because it is judged whether or not the previous step is completed // The NPC dialog may have been called out here (exception handling) CancelNPCDialog; // 取消对话 ThisTrans.StepIndex := 0; end; end; 10: // Trigger Movement begin MoveToHL_Pos(StrToIntDef(tmpTransStep.X, 0), StrToIntDef(tmpTransStep.Y, 0), false); ThisTrans.StepIndex := ThisTrans.StepIndex + 1; end; end; end; 3: // 也是专门给Trans用的,检测是否完成了Trans中的一个Step begin if tmpTransaction.OldNPCDialog <> GetNPCDialog then // 切换了对话框 begin tmpTransaction.OldNPCDialog := GetNPCDialog; tmpStep.SubStepIndex := 2; ThisTrans.StepIndex := ThisTrans.StepIndex + 1; end else // 等待超时,然后回去重做 begin if not tmpTransaction.HasPassedInterval(5000) then Exit; tmpStep.SubStepIndex := 2; end; end; end; end; //-------------------------------------------------------------------------- // Battle //-------------------------------------------------------------------------- ActInBattle: case tmpStep.SubStepIndex of 0: begin if GetUserEnvState<>UserEnvBattle then Exit; ThisBattle.Free; ThisBattle:=TBattle.Create; case FormGeneralSet.RadioGroupHumanAct.ItemIndex of 0: ThisBattle.OrderHumanAction:=BattleAttack; 1: ThisBattle.OrderHumanAction:=BattleDefence; 2: ThisBattle.OrderHumanAction:=BattleCapture; end; case FormGeneralSet.RadioGroupPetAct.ItemIndex of 0: ThisBattle.OrderPetAction:=BattleAttack; 1: ThisBattle.OrderPetAction:=BattleDefence; end; case FormGeneralSet.RadioGroupWhatToDoWhenNoMonsterToCapture.ItemIndex of 0: ThisBattle.EscapeWhenNoMonsterToCapture:=False; 1: ThisBattle.EscapeWhenNoMonsterToCapture:=True; end; ThisBattle.MonsterNameToCapture:=FormMain.EditMonsterToCapture.Text; ThisBattle.CaptureLevelFrom:=StrToInt(FormMain.EditCaptureLevelFrom.Text); ThisBattle.CaptureLevelTo:=StrToInt(FormMain.EditCaptureLevelTo.Text); tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; 1: begin tmpint:=GetUserEnvState; if ((tmpStep.Y='Dialogue') and (tmpint=UserEnvDialog) and (Pos(WideString(tmpStep.Z), GetNPCDialog)>0)) // 战斗后应当是对话状态 or ((tmpStep.Y='Ordinary') and (tmpint=UserEnvNormal)) // 战斗后应当是普通状态 then begin if ThisBattle.HasBegin // 已经开始过,说明是战斗完毕了 then begin ThisBattle.Free; ThisBattle:=Nil; if tmpStep.X='Ordinary' then // End of battle begin tmpStep.SubStepIndex:=0; tmpTransaction.GotoNextStep; FormMain.UpdateMarchingPetInfo; end else if tmpStep.X='Overjob' then begin ThisUser.GetAttr; if (ThisUser.Level div 100)*100=ThisUser.Level then // User official upgrade? begin // End of battle tmpStep.SubStepIndex:=0; tmpTransaction.GotoNextStep; FormMain.UpdateMarchingPetInfo; end else if ((ThisUser.Level div 100)*100<>ThisUser.Level) and (((ThisUser.Level+1) div 100)*100 <> ThisUser.Level+1) then // The robery failed and the battle ended begin ThisWork.CanWork:=False; tmpStep.SubStepIndex:=0; ShowMessage('Failure to rob, stop working'); end; end; end; end else if tmpint=UserEnvBattle then // 正在战斗 begin FormShowPets.ShowPets; ThisBattle.DoBattle; ThisBattle.HasBegin:=True; end; end; end; //-------------------------------------------------------------------------- // 购买物品 //-------------------------------------------------------------------------- ActBuyStuff: begin FormShowStuffs.ShowStuffs; if tmpStep.SubStepIndex=0 then begin ThisBuyStuff.Free; ThisBuyStuff:=TBuyStuff.Create; ThisBuyStuff.PatchShop; if not ThisBuyStuff.InitShop then Exit; if tmpStep.Z='' then ThisBuyStuff.WriteStuffInfo(tmpStep.X, tmpStep.Y, 1000) else ThisBuyStuff.WriteStuffInfo(tmpStep.X, tmpStep.Y, strtointdef(tmpStep.Z, 0)); ThisBuyStuff.GetAllStuffCount; tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; if ThisBuyStuff.IsSatisfied then // 不用再买了 begin ThisBuyStuff.UnPatchShop; ThisBuyStuff.Free; ThisBuyStuff:=Nil; tmpStep.SubStepIndex:=0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; Exit; end; case tmpStep.SubStepIndex of 1: begin ThisBuyStuff.GetAllStuffCount; tmpTransaction.SetOldTime; if ThisBuyStuff.DoBuyStuff then tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; 2: begin if ThisBuyStuff.HasBoughtStuff then // 买到了药 begin tmpStep.SubStepIndex:=1; end else // 还没有得到药 begin if not tmpTransaction.HasPassedInterval(5000) then Exit; // 如果还没有到5秒,就等等 // 现在,过了5秒,还没有得到药,说明不会再得到了,所以就得重买 tmpStep.SubStepIndex:=1; end; end; end; end; //-------------------------------------------------------------------------- // 开物品栏 //-------------------------------------------------------------------------- ActOpenItemWindow: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment'); if tmpWin = nil then // 没有找到物品/装备窗口 begin for i := 0 to HLInfoList.GlobalHL.Count-1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then PostMessage(tmpWin.Window, WM_COMMAND, IDM_Item, 0); end; end else begin if IsWindowEnabled(tmpWin.Window) then EnableWindow(tmpWin.Window, False); if IsWindowVisible(tmpWin.Window) then ShowWindow(tmpWin.Window, SW_HIDE); tmpTransaction.GotoNextStep; end; end; //-------------------------------------------------------------------------- // 关物品栏 //-------------------------------------------------------------------------- ActCloseItemWindow: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment'); if tmpWin=Nil then begin tmpTransaction.GotoNextStep; end else begin Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0); end; end; //-------------------------------------------------------------------------- // 使用物品 //-------------------------------------------------------------------------- ActUseItem: begin FormShowStuffs.ShowStuffs; if tmpStep.SubStepIndex=0 then begin ThisUser.OldItemID:=ThisUser.FindItemID(tmpStep.X, tmpStep.Y); tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; case tmpStep.SubStepIndex of 1: begin tmpTransaction.SetOldTime; if ThisUser.UseItem(ThisUser.OldItemID) then tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1 else begin ThisWork.CanWork:=False; tmpStep.SubStepIndex:=0; ShowMessage('Unable to use item: '+tmpStep.X+','+tmpStep.Y+'['+IntToHex(ThisUser.OldItemID, 8)+']'); Exit; end; end; 2: begin if (ThisUser.FindItemPosByID(ThisUser.OldItemID)=0) or (tmpStep.Z = 'Skip') then // 已经完成使用物品 begin tmpStep.SubStepIndex:=0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; Exit; end else // 还没有完成使用物品 begin if not tmpTransaction.HasPassedInterval(5000) then Exit; // 如果还没有到5秒,就等等 // 现在,过了5秒,还没有完成,说明不会再完成,所以就得重使用 tmpStep.SubStepIndex:=1; end; end; end; end; ActDropItem: begin FormShowStuffs.ShowStuffs; if tmpStep.SubStepIndex=0 then begin //ThisUser.OldItemID:=ThisUser.FindItemID(tmpStep.X, tmpStep.Y); ThisUser.OldItemCount := ThisUser.FindItemCount(tmpStep.X, tmpStep.Y); tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; case tmpStep.SubStepIndex of 1: begin tmpTransaction.SetOldTime; if ThisUser.DropItem(ThisUser.FindItemID(tmpStep.X, tmpStep.Y)) then tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1 else begin //Item not owned tmpStep.SubStepIndex:=0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; Exit; end; end; 2: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Are you sure?'); if tmpWin = nil then Exit; myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(tmpWin.Window, 'OK(&O)', True); PostMessage(myhwnd, WM_LBUTTONDOWN, MK_LBUTTON, 0); PostMessage(myhwnd, WM_LBUTTONUP, 0, 0); tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1 end; 3: begin ThisUser.OldItemID := ThisUser.FindItemID(tmpStep.X, tmpStep.Y); if (ThisUser.OldItemID=0) or ((StrToIntDef(tmpStep.Z, 0) > 0) and (StrToIntDef(tmpStep.Z, 0) <= (ThisUser.OldItemCount - ThisUser.FindItemCount(tmpStep.X, tmpStep.Y)))) then begin tmpStep.SubStepIndex:=0; tmpTransaction.ClearOldTime; tmpTransaction.GotoNextStep; Exit; end else // 还没有完成使用物品 begin if not tmpTransaction.HasPassedInterval(5000) then Exit; // 如果还没有到5秒,就等等 // 现在,过了5秒,还没有完成,说明不会再完成,所以就得重使用 tmpStep.SubStepIndex:=1; end; end; end; end; //-------------------------------------------------------------------------- // 离开商店 //-------------------------------------------------------------------------- ActQuitShop: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Monster&Me - Store'); if tmpWin = nil then begin tmpTransaction.GotoNextStep; end else begin Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0); end; end; //-------------------------------------------------------------------------- // 点击按钮 //-------------------------------------------------------------------------- ActPressButton: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.Z); if tmpWin<>Nil then begin tmpTransaction.GotoNextStep; end else begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.Y); if tmpWin=Nil then Exit; myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(tmpWin.Window, tmpStep.X, True); PostMessage(myhwnd, WM_LBUTTONDOWN, MK_LBUTTON, 0); PostMessage(myhwnd, WM_LBUTTONUP, 0, 0); end; end; //-------------------------------------------------------------------------- // Wuxing //-------------------------------------------------------------------------- ActDoForge: case tmpStep.SubStepIndex of 0: // Init begin ThisUser.GetItems; if ThisUser.ItemCount >= 15 then begin ThisWork.CanWork:=False; ShowMessage('Your inventory is full! Unable to wux.'); Exit; end; tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Wuxing Oven'); if tmpWin=Nil then // Did not find the wuxing oven begin for i := 0 to HLInfoList.GlobalHL.Count - 1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then PostMessage(tmpWin.Window, WM_COMMAND, IDM_UniverseStove, 0); end; Exit; end else begin if IsWindowEnabled(tmpWin.Window) then EnableWindow(tmpWin.Window, False); if IsWindowVisible(tmpWin.Window) then ShowWindow(tmpWin.Window, SW_HIDE); end; ThisForge.Free; ThisForge := TForge.Create; ThisForge.PatchUniverseStove; ThisForge.Init; tmpStep.SubStepIndex := tmpStep.SubStepIndex+1; end; 1: // Handle Wuxing begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Wuxing Oven'); if tmpWin = nil then Exit; myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(tmpWin.Window, 'Start', True); if myhwnd = 0 then Exit; FormShowStuffs.ShowStuffs; FormShowUniverseStove.ShowUniverseStove; tmpint := Round((GetTime - FForgeOldTime) * 24 * 3600 * 1000); tmpint := FormShowUniverseStove.TrackBarForgeDelay.Position - tmpint; // Elapsed time and rated dif if tmpint > 0 then begin FormShowUniverseStove.LabelAnimator.Caption := 'Delay ' + Format('%d', [tmpint]) + 'MS'; Exit; end; tmpStove := ThisForge.GetCurrStove; ThisForge.InitStoveStuffsToBeChozen; tmpStove.tmpID1 := 0; tmpStove.tmpID2 := 0; For i := 0 to 7 do begin tmpStove.Rooms[i].Stuff.StuffID := 0; tmpStove.Rooms[i].Stuff.StuffAttr := $4d2; end; if not ThisForge.FillStove then Exit; // Items do not meet refining condition ThisForge.WriteStoveInstruction; SendMessage(myhwnd, WM_LBUTTONDOWN, MK_LBUTTON, 0); SendMessage(myhwnd, WM_LBUTTONUP, 0, 0); FForgeOldTime := GetTime; tmpStep.SubStepIndex:=tmpStep.SubStepIndex+1; end; 2: // Cleanup begin FormShowStuffs.ShowStuffs; FormShowUniverseStove.ShowUniverseStove; FormShowUniverseStove.LabelAnimator.Caption := '炼化中..'; if ThisForge.HasCurrStoveFinished then begin FormShowUniverseStove.LabelAnimator.Caption := '炼化完成'; ThisForge.GotoNextStove; if ThisForge.IsFinish then begin // 完成了 ThisForge.Clean; tmpStep.SubStepIndex:=0; ThisForge.UnPatchUniverseStove; ThisForge.Free; ThisForge:=Nil; tmpTransaction.GotoNextStep; end else tmpStep.SubStepIndex:=1; end; end; end; //-------------------------------------------------------------------------- // 呼叫 NPC //-------------------------------------------------------------------------- ActCallNPC: case tmpStep.SubStepIndex of 0: // 找到NPC并开始呼叫 begin for i := 0 to Ord(High(TNPCID)) do begin if NPCs[i].Name = tmpStep.X then // 比较 NPC 名字 begin tmpStep.CalledNPCID := TNPCID(i);// NPCIDsArray[i]; BeginCallNPC(tmpStep.CalledNPCID); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; Exit; end; end; end; 1: // 等待 SatisfiedCond,结束呼叫NPC begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle( NPCs[Ord(tmpStep.CalledNPCID)].SatisfiedCond); if tmpWin <> Nil then begin EndCallNPC; tmpStep.SubStepIndex := 0; tmpTransaction.GotoNextStep; end; end; end; //-------------------------------------------------------------------------- // 停止工作 //-------------------------------------------------------------------------- ActTerminate: begin tmpTransaction.State := 1; // 无论如何,这个大步骤都算完成了 ThisWork.CanWork := False; ShowMessage('Script stopped: ' + tmpStep.X); end; //-------------------------------------------------------------------------- // 拥有物品:等待满足此物品,达到指定数量级 //-------------------------------------------------------------------------- ActHaveStuff: // 等待满足此物品 begin if StrToIntDef(tmpStep.Z, 0) <= ThisUser.FindItemCount(tmpStep.X, tmpStep.Y) then tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 物品数目:等待满足此物品,等于指定数量级 //-------------------------------------------------------------------------- ActStuffNum: // 与ActHaveStuff不同的是,严格限制物品数目 begin if StrToIntDef(tmpStep.Z, 0) = ThisUser.FindItemCount(tmpStep.X, tmpStep.Y) then tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 跳至步骤 N //-------------------------------------------------------------------------- ActJumpToTransN: begin tmpTransaction.Init; TimerDoTransaction.Enabled := False; TimerWork.Enabled := True; tmpTransaction.State := 1; if GetUserEnvState = UserEnvDialog then CancelNPCDialog; ThisWork.GotoTrans(StrToIntDef(tmpStep.X, 0), True); FormShowWorkTransactions.ShowTransactions; if tmpHealTransaction <> nil then begin ThisWork.DeleteTransaction(ThisWork.GetSize() - 1); tmpHealTransaction := nil; end; end; //-------------------------------------------------------------------------- // 拥有宠物:等待满足此宠物,达到指定数量级 //-------------------------------------------------------------------------- ActHavePet: // 等待满足此宠物 begin if StrToIntDef(tmpStep.Z, 0) <= ThisUser.FindPetCount(tmpStep.X, StrToIntDef(tmpStep.Y, 0)) then tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 宠物数目:等待满足此宠物,等于指定数量级 //-------------------------------------------------------------------------- ActPetNum: // 与ActHavePet不同的是,严格限制宠物数目 begin if StrToIntDef(tmpStep.Z, 0) = ThisUser.FindPetCount(tmpStep.X, StrToIntDef(tmpStep.Y,0)) then tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 取消对话 //-------------------------------------------------------------------------- ActCancelNPCDialog: begin CancelNPCDialog; tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 等待延时 //-------------------------------------------------------------------------- ActDelay: case tmpStep.SubStepIndex of 0: begin tmpTransaction.SetOldTime; tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 1: begin if not tmpTransaction.HasPassedInterval(StrToIntDef(tmpStep.X, 0)) then Exit; tmpTransaction.ClearOldTime; tmpStep.SubStepIndex := 0; tmpTransaction.GotoNextStep; end; end; //-------------------------------------------------------------------------- // 进入战斗 //-------------------------------------------------------------------------- ActActiveBattle: case tmpStep.SubStepIndex of 0: begin //Initialize battle FormMain.UpdateMarchingPetInfo; if (tmpStep.X = 'Atk') or (tmpStep.X = 'Attack') then FormGeneralSet.RadioGroupHumanAct.ItemIndex := 0 else if (tmpStep.X = 'Def') or (tmpStep.X = 'Defend') then FormGeneralSet.RadioGroupHumanAct.ItemIndex := 1 else if (tmpStep.X = 'Capture') then FormGeneralSet.RadioGroupHumanAct.ItemIndex := 2; if (tmpStep.Y = 'Atk') or (tmpStep.Y = 'Attack') then FormGeneralSet.RadioGroupPetAct.ItemIndex := 0 else if (tmpStep.Y = 'Def') or (tmpStep.Y = 'Defend') then FormGeneralSet.RadioGroupPetAct.ItemIndex := 1; if tmpStep.Z = 'Fight' then FormGeneralSet.RadioGroupWhatToDoWhenNoMonsterToCapture.ItemIndex := 0 else if tmpStep.Z = 'Run' then FormGeneralSet.RadioGroupWhatToDoWhenNoMonsterToCapture.ItemIndex := 1; //Verify healing settings if not FormGeneralSet.CheckBoxNoHeal.Checked then begin if ThisUser.FindItemByType(700) = 0 then begin if ThisUser.ItemCount = 16 then begin //end here, inventory is full tmpTransaction.State := 1; // 无论如何,这个大步骤都算完成了 ThisWork.CanWork := False; ShowMessage('Script Aborted, Battle Failed, Inventory Full'); end else begin //insert healing steps tmpReturnTransNum := ThisWork.FTransactionIndex; tmpHealTransaction := ThisWork.AddTransaction('Get Potions'); if FormGeneralSet.cmbStore.Text = 'WaterCity Pharmacy' then tmpPharmMap := '100000'; if FormGeneralSet.cmbStore.Text = 'TreeCity Pharmacy' then tmpPharmMap := '100006'; if FormGeneralSet.cmbStore.Text = 'HillCity Pharmacy' then tmpPharmMap := '100059'; if FormGeneralSet.cmbStore.Text = 'SandCity Pharmacy' then tmpPharmMap := '200000'; if FormGeneralSet.cmbStore.Text = 'SnowCity Pharmacy' then tmpPharmMap := '300000'; if FormGeneralSet.cmbStore.Text = 'OceanCity Pharmacy' then tmpPharmMap := '400000'; tmpHealTransaction.AddStep(ActGotoMap,tmpPharmMap,'',''); tmpHealTransaction.AddStep(ActCallNPC,FormGeneralSet.cmbStore.Text,'',''); tmpHealTransaction.AddStep(ActBuyStuff,FormGeneralSet.ComboBoxMed.Text,'TQ-Anonym',''); tmpHealTransaction.AddStep(ActQuitShop,'','',''); //return to previous prevMap := ReadCurrMapID(); GetCurrPosXY(prevX, prevY); tmpHealTransaction.AddStep(ActGotoMap,IntToStr(prevMap),'',''); tmpHealTransaction.AddStep(ActMoveToPos,IntToStr(prevX),IntToStr(prevY),''); tmpHealTransaction.AddStep(ActJumpToTransN,IntToStr(tmpReturnTransNum),'',''); ThisWork.FTransactionIndex := ThisWork.GetSize() - 1; end; end; end; tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 1: begin //Initiate Battle for i := 0 to HLInfoList.GlobalHL.Count - 1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then SendMessage(tmpWin.Window, WM_COMMAND, IDM_Battle, 0); end; tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 2: begin if GetUserEnvState = UserEnvBattle then begin tmpStep.SubStepIndex := 0; tmpTransaction.GotoNextStep; end; end; end; //-------------------------------------------------------------------------- // 捉宠设置 //-------------------------------------------------------------------------- ActSetCapture: begin FormMain.EditMonsterToCapture.Text := tmpStep.X; FormMain.EditCaptureLevelFrom.Text := IntToStr(StrToIntDef(tmpStep.Y, 0)); FormMain.EditCaptureLevelTo.Text := IntToStr(StrToIntDef(tmpStep.Z, 0)); tmpTransaction.GotoNextStep; end; ActSetHeal: begin if tmpStep.X = 'Store' then begin for setHealIter := 0 to FormGeneralSet.cmbStore.Items.Count do begin if FormGeneralSet.cmbStore.Items[setHealIter] = tmpStep.Y then begin FormGeneralSet.cmbStore.ItemIndex := setHealIter; Break; end; end; end; if tmpStep.X = 'Medicine' then begin for setHealIter := 0 to FormGeneralSet.ComboBoxMed.Items.Count do begin if FormGeneralSet.ComboBoxMed.Items[setHealIter] = tmpStep.Y then begin FormGeneralSet.ComboBoxMed.ItemIndex := setHealIter; Break; end; end; end; if tmpStep.X = 'Level' then begin if tmpStep.Y = 'True' then begin FormGeneralSet.CheckBoxFullBlood.Checked := true; end; if tmpStep.Y = 'False' then begin FormGeneralSet.CheckBoxFullBlood.Checked := false; end; end; if tmpStep.X = 'Disable' then begin if tmpStep.Y = 'True' then begin FormGeneralSet.CheckBoxNoHeal.Checked := true; end; if tmpStep.Y = 'False' then begin FormGeneralSet.CheckBoxNoHeal.Checked := false; end; end; if tmpStep.X = 'Player' then begin FormGeneralSet.EditPlayerLife.Text := tmpStep.Y; end; if tmpStep.X = 'Pet' then begin FormGeneralSet.EditPetLife.Text := tmpStep.Y; end; tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 定位窗口 //-------------------------------------------------------------------------- ActLocateWindow: begin tmpStep.X := StringReplace(tmpStep.X, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); tmpStep.Y := StringReplace(tmpStep.Y, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); if tmpStep.Y = '' then myhwnd := 0 // 没有父窗口 else begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.Y); if tmpWin = Nil then begin ThisWork.CanWork := False; ShowMessage('Parent Window not found:' + tmpStep.Y + ',script stopped.'); Exit; end else myhwnd := tmpWin.Window; end; if tmpStep.Z = 'Indirect' then tmpBoolean := False else tmpBoolean := True; myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(myhwnd, tmpStep.X, tmpBoolean); if myhwnd = 0 then begin ThisWork.CanWork := False; ShowMessage('Window not found:' + tmpStep.Y + ',script stopped.'); Exit; end; FLocateHwnd := myhwnd; // 保护窗口句柄 tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 窗口单击 //-------------------------------------------------------------------------- ActWinLeftClick: begin tmpStep.X := StringReplace(tmpStep.X, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); if tmpStep.X <> '※' then tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.X) else // 使用“定位窗口”中的窗口句柄 tmpWin := HLInfoList.GlobalHL.ItemOfWindowID(FLocateHwnd); if tmpWin = nil then Exit; myhwnd := tmpWin.Window; LeftClickOnSomeWindow_Post(myhwnd, StrToIntDef(tmpStep.Y, 0), StrToIntDef(tmpStep.Z, 0)); Sleep(200); tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 窗口双击 //-------------------------------------------------------------------------- ActWinLeftDblClick: begin tmpStep.X := StringReplace(tmpStep.X, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); if tmpStep.X <> '※' then tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.X) else // 使用“定位窗口”中的窗口句柄 tmpWin := HLInfoList.GlobalHL.ItemOfWindowID(FLocateHwnd); if tmpWin = nil then Exit; myhwnd := tmpWin.Window; LeftDblClickOnSomeWindow_Post(myhwnd, StrToIntDef(tmpStep.Y, 0), StrToIntDef(tmpStep.Z, 0)); Sleep(200); tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 窗口右键 //-------------------------------------------------------------------------- ActWinRightClick: begin tmpStep.X := StringReplace(tmpStep.X, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); if tmpStep.X <> '※' then tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.X) else // 使用“定位窗口”中的窗口句柄 tmpWin := HLInfoList.GlobalHL.ItemOfWindowID(FLocateHwnd); if tmpWin = nil then Exit; myhwnd := tmpWin.Window; RightClickOnSomeWindow_Post(myhwnd, StrToIntDef(tmpStep.Y, 0), StrToIntDef(tmpStep.Z, 0)); Sleep(200); tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // 等待窗口 //-------------------------------------------------------------------------- ActWaitWindow: begin tmpStep.X := StringReplace(tmpStep.X, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); tmpStep.Y := StringReplace(tmpStep.Y, '[username]', HLInfoList.GlobalHL.UserName, [rfReplaceAll, rfIgnoreCase]); if tmpStep.Y = '' then myhwnd := 0 // 没有父窗口 else begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(tmpStep.Y); if tmpWin = Nil then Exit // 返回,下次再来判断 else myhwnd := tmpWin.Window; end; if tmpStep.Z = 'Indirect' then tmpBoolean := False else tmpBoolean := True; if HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(myhwnd, tmpStep.X, tmpBoolean) = 0 then Exit; tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // Kungfu //-------------------------------------------------------------------------- ActSetWGAttr: // 设置武功属性(名称、内、系数等) begin ThisWGAttrs.MC := tmpStep.X; ThisWGAttrs.XS := tmpStep.Y; ThisWGAttrs.NL := tmpStep.Z; tmpString := CanCreateWG; if (tmpString <> '') and (tmpString <> 'Full') then begin ThisWGAttrs.MC := ''; ThisWGAttrs.XS := ''; ThisWGAttrs.NL := ''; ThisWork.CanWork := False; ShowMessage(tmpString); end else tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // Kungfu Appearance //-------------------------------------------------------------------------- ActSetWGDisp: // 显示形式 begin if (StrToIntDef(tmpStep.X, -1) < 1) or (StrToIntDef(tmpStep.X, -1) > 8) then begin ShowMessage('The starting position cannot be ' + tmpStep.X); ThisWork.CanWork := False; Exit; end; if (StrToIntDef(tmpStep.Y, -1) < 1) or (StrToIntDef(tmpStep.Y, -1) > 19) then begin ShowMessage('Flight trajectory cannot be ' + tmpStep.Y); ThisWork.CanWork := False; Exit; end; if (StrToIntDef(tmpStep.Z, -1) < 1) or (StrToIntDef(tmpStep.Z, -1) > 20) then begin ShowMessage('Explosion cannot be ' + tmpStep.Z); ThisWork.CanWork := False; Exit; end; ThisWGAttrs.QS := tmpStep.X; ThisWGAttrs.GJ := tmpStep.Y; ThisWGAttrs.BZ := tmpStep.Z; tmpTransaction.GotoNextStep; end; //-------------------------------------------------------------------------- // Create Kungfu //-------------------------------------------------------------------------- ActCreateWG: begin FormShowWGs.ShowWGs; tmpString := CanCreateWG; if tmpString <> '' then begin tmpStep.SubStepIndex := 0; tmpTransaction.GotoNextStep; Exit; end; case tmpStep.SubStepIndex of 0: // 打开创招窗口 begin ThisCreateWG.Free; ThisCreateWG := TCreateWG.Create; ThisCreateWG.PatchCreateWG; tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu'); if tmpWin=Nil then // 没有找到自创绝招窗口 begin for i := 0 to HLInfoList.GlobalHL.Count - 1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then PostMessage(tmpWin.Window, WM_COMMAND, IDM_CreateWG, 0); end; end else begin if IsWindowEnabled(tmpWin.Window) then EnableWindow(tmpWin.Window, False); if IsWindowVisible(tmpWin.Window) then ShowWindow(tmpWin.Window, SW_HIDE); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; end; 1: // 创招 begin if not ThisCreateWG.DoCreateWG then Exit else tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 2: // 等待创招窗口消失 begin if HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu') <> nil then Exit; tmpStep.SubStepIndex := 0; FormShowWGs.ShowWGs; ThisCreateWG.UnPatchCreateWG; ThisCreateWG.Free; ThisCreateWG := Nil; tmpTransaction.GotoNextStep; end; end; end; //-------------------------------------------------------------------------- // 删除武功 //-------------------------------------------------------------------------- ActDeleteWGs: begin FormShowWGs.ShowWGs; if tmpStep.SubStepIndex = 0 then // 初始化 begin end; case tmpStep.SubStepIndex of 0: // 初始化 begin tmpint := StrToIntDef(tmpStep.X, 0); if (tmpint < 1) or (tmpint > 10) then begin ShowMessage('Deletion setting is wrong,you cannot start delete from ' + tmpStep.X + ' 招开始删招'); ThisWork.CanWork := False; Exit; end; ThisCreateWG.Free; ThisCreateWG := TCreateWG.Create; ThisCreateWG.PatchCreateWG; ThisCreateWG.DeleteFrom := tmpint; if tmpStep.Y = 'Easy' then ThisCreateWG.DeleteWGRemainIndicator := DelWGRemainEasyWG else if tmpStep.Y = '※保留系数' then ThisCreateWG.DeleteWGRemainIndicator := StrToFloatDef(tmpStep.Z, DelWGNoIndicator) else ThisCreateWG.DeleteWGRemainIndicator := DelWGNoIndicator; if HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Character''s Status') = nil then begin for i := 0 to HLInfoList.GlobalHL.Count - 1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then PostMessage(tmpWin.Window, WM_COMMAND, IDM_HumanAttr, 0); end; end; tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 1: // 找到删招窗口 begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Kungfu'); if tmpWin = Nil then begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Other Info'); if tmpWin = Nil then Exit; myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(tmpWin.Window, 'Kungfu(&M)', False); if myhwnd = 0 then Exit; LeftClickOnSomeWindow_Post(myhwnd, 0, 0); end else begin if IsWindowVisible(tmpWin.Window) then ShowWindow(tmpWin.Window, SW_HIDE); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; end; 2: // 删招 begin ThisUser.GetWGs; if ThisCreateWG.DeleteFrom > ThisUser.WGCount then begin tmpStep.SubStepIndex := 4; Exit; end; if not ThisCreateWG.DoDeleteWGs then Exit else tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 3: // 等待武功真正被删掉 begin ThisUser.GetWGs; if ThisCreateWG.OldWGCount <> ThisUser.WGCount + 1 then Exit; FormShowWGs.ShowWGs; tmpStep.SubStepIndex := 2; end; 4: // 收尾工作 begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Kungfu'); if tmpWin <> nil then begin Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0); Exit; end; tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Character''s Status'); if tmpWin <> nil then begin Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0); Exit; end; ThisCreateWG.UnPatchCreateWG; ThisCreateWG.Free; ThisCreateWG := Nil; tmpStep.SubStepIndex := 0; FormShowWGs.ShowWGs; tmpTransaction.GotoNextStep; end; end; end; ActSetAttr: begin case tmpStep.SubStepIndex of 0: begin ThisUser.GetAttr; ThisUser.OldRemaining := ThisUser.RemainingPoints; if ((tmpStep.X <> 'Life') and (tmpStep.X <> 'Attack') and (tmpStep.X <> 'Defense') and (tmpStep.X <> 'Defence') and (tmpStep.X <> 'Mana') and (tmpStep.X <> 'Dexterity')) or (tmpStep.Y = '') then begin // Unhandled action, skip step tmpTransaction.GotoNextStep; Exit; end; if (StrToInt(tmpStep.Y) > ThisUser.OldRemaining) then begin ShowMessage('Script ended because it tried to add more stats then existed: ' + tmpStep.X + ' ' + tmpStep.Y); ThisWork.CanWork := False; Exit; end; if HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Character''s Status') = nil then begin for i := 0 to HLInfoList.GlobalHL.Count - 1 do begin tmpWin := HLInfoList.GlobalHL.Items[i]; if tmpWin.ClassName = 'TPUtilWindow' then PostMessage(tmpWin.Window, WM_COMMAND, IDM_HumanAttr, 0); end; end else tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 1: begin tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Character''s Status'); myhwnd := HLInfoList.GlobalHL. LocateChildWindowWNDByTitle(tmpWin.Window, 'Attribute', False); if myhwnd = 0 then Exit; LeftClickOnSomeWindow_Post(myhwnd, 0, 0); tmpStep.SubStepIndex := tmpStep.SubStepIndex + 1; end; 2: begin //add stats and close window ThisUser.AddStats(tmpStep.X, StrToInt(tmpStep.Y)); tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Character''s Status'); if tmpWin <> nil then begin Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0); end; tmpStep.SubStepIndex := 0; tmpTransaction.GotoNextStep; Sleep(100); FormMain.ResetAttributes; end; end; end; //-------------------------------------------------------------------------- // 未知指令 //-------------------------------------------------------------------------- ActUnknown: begin ThisWork.CanWork := False; ShowMessage('Encounted an unknown command: ' + tmpStep.X + ',script stopped'); end; end; end; procedure TFormTimers.TimerReadMapInfoTimer(Sender: TObject); var tmpMap: TMapInfo; begin if (FormMain.Handle <> GetForeGroundWindow) and (FormGeneralSet.Handle <> GetForeGroundWindow) and (FormSetWGAttr.Handle <> GetForeGroundWindow) then SetWindowPos(FormMain.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE OR SWP_NOSIZE OR SWP_NOACTIVATE); if FReadMapInfoCounter >= GameMaps.Count then begin TimerReadMapInfo.Interval := 500; Exit; end; while (FReadMapInfoCounter < GameMaps.Count) do begin tmpMap := GameMaps.Items[FReadMapInfoCounter]; if tmpMap.ID = 0 then begin GameMaps.ReadOneMap(tmpMap.PosInMapList); Exit; end else FReadMapInfoCounter := FReadMapInfoCounter + 1; end; end; procedure TFormTimers.FormCreate(Sender: TObject); begin FForgeOldTime := 0; end; end.
unit ideSHSplashFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, jpeg, IniFiles; type TSplashForm = class(TForm) bvlTop: TBevel; bvlLeft: TBevel; bvlRight: TBevel; bvlBottom: TBevel; Panel1: TPanel; Label1: TLabel; Bevel1: TBevel; Panel2: TPanel; Bevel2: TBevel; Bevel3: TBevel; Panel3: TPanel; Image1: TImage; Timer1: TTimer; Panel4: TPanel; Memo1: TMemo; Panel5: TPanel; ProgressBar1: TProgressBar; Panel6: TPanel; private { Private declarations } public { Public declarations } procedure SplashTrace(const AText: string); procedure SplashTraceDone; end; procedure CreateSplashForm; procedure ShowSplashForm; procedure DestroySplashForm; var SplashForm: TSplashForm; I, Count: Integer; implementation {$R *.dfm} function CanShowSplash: Boolean; // !!! HACK var IniFile: TIniFile; FileName: string; begin FileName := Format('%s..\Data\Environment\Options.txt', [IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))]); IniFile := TIniFile.Create(FileName); try Result := StrToBool(IniFile.ReadString('OPTIONS', 'TideSHSystemOptions.ShowSplashWindow', 'True')); finally IniFile.Free; end; end; procedure CreateSplashForm; begin I := 0; Count := 5; if CanShowSplash then begin SplashForm := TSplashForm.Create(Application); SplashForm.Panel1.Color := clWhite; SplashForm.Panel2.Color := clWhite; SplashForm.Panel3.Color := clWhite; SplashForm.Panel5.Color := clWhite; SplashForm.Panel6.Color := clWhite; SplashForm.Memo1.Color := clWhite; end; end; procedure ShowSplashForm; begin if Assigned(SplashForm) then begin SplashForm.SplashTrace('Initialize...'); SplashForm.Show; SplashForm.SplashTraceDone; Application.ProcessMessages; SplashForm.Invalidate; Application.ProcessMessages; end; end; procedure DestroySplashForm; begin if Assigned(SplashForm) then begin SplashForm.Free; SplashForm := nil; end; end; { TBTSplashForm } procedure TSplashForm.SplashTrace(const AText: string); begin Memo1.Lines.Add(Format('%s', [AText])); Application.ProcessMessages; end; procedure TSplashForm.SplashTraceDone; begin Memo1.Lines[Pred(Memo1.Lines.Count)] := Format('%s done', [Memo1.Lines[Pred(Memo1.Lines.Count)]]); // ProgressBar1.Position := ProgressBar1.Position + 10; ProgressBar1.Position := 100 * I div Count; I := I + 1; Application.ProcessMessages; end; initialization { if CanShowSplash then begin end; } end.
unit exception; interface type Integer = Integer; TException = class field: Integer; end; implementation function print(E: TException): TException; begin end; begin try except on E: TException do begin print(E.field); end; on TException do print(nil); end; try except print(nil); end; end.
unit Invoice.Controller.TabForm; interface uses Invoice.Controller.Interfaces, Vcl.ComCtrls, Vcl.ActnList; type TControllerTabForm = class(TInterfacedObject, iControllerTabForm) public constructor Create; destructor Destroy; Override; class function New: iControllerTabForm; function CreateTab(aAction: TAction; aPageControl: TPageControl): TTabSheet; end; implementation { TControllerTabForm } constructor TControllerTabForm.Create; begin // end; function TControllerTabForm.CreateTab(aAction: TAction; aPageControl: TPageControl): TTabSheet; var aTabSheet: TTabSheet; TabName: String; begin aAction.Enabled := False; // Result:= nil; // TabName := 'Tab' + aAction.Name; // aTabSheet := aPageControl.FindComponent(TabName) as TTabSheet; // if not Assigned(aTabSheet) then begin aTabSheet := TTabSheet.Create(aPageControl); aTabSheet.Name := TabName; aTabSheet.Caption := aAction.Caption; aTabSheet.PageControl := aPageControl; aTabSheet.ImageIndex := 0; aTabSheet.Hint := ''; end; // aPageControl.ActivePage := aTabSheet; // Result:= aTabSheet; // aAction.Enabled := True; end; destructor TControllerTabForm.Destroy; begin inherited; end; class function TControllerTabForm.New: iControllerTabForm; begin Result := Self.Create; end; end.
unit Unit2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.strutils, System.inifiles, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TabControl, FMX.Edit, FMX.ComboEdit, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.ScrollBox, FMX.Memo, System.ImageList, FMX.ImgList; type TFormFileEditor = class(TForm) Panel2: TPanel; Panel1: TPanel; Panel3: TPanel; gb_sequential: TGroupBox; rb_sequential: TRadioButton; rb_unsequential: TRadioButton; Panel4: TPanel; Label1: TLabel; edt_start_files: TEdit; edt_end_files: TEdit; Label2: TLabel; Panel5: TPanel; Label3: TLabel; ListBox1: TListBox; Panel6: TPanel; Button1: TButton; Button2: TButton; Label4: TLabel; Line1: TLine; Label5: TLabel; Line2: TLine; edt_num_files: TEdit; btn_change_num_files: TButton; Panel7: TPanel; Panel8: TPanel; Label6: TLabel; Panel9: TPanel; Label7: TLabel; edt_File_Location: TEdit; Button3: TButton; Memo1: TMemo; Panel10: TPanel; Panel11: TPanel; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; Panel12: TPanel; Panel13: TPanel; SpeedButton4: TSpeedButton; SpeedButton5: TSpeedButton; ComboEdit1: TComboEdit; ToolBar1: TToolBar; SpeedButton6: TSpeedButton; Panel14: TPanel; ProgressBar1: TProgressBar; SpeedButton1: TSpeedButton; Panel15: TPanel; procedure rb_unsequentialChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure edt_start_filesKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); function IsNumber(N: String): Boolean; procedure edt_end_filesKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure rb_sequentialChange(Sender: TObject); procedure addItemToListBox(); procedure Button2Click(Sender: TObject); procedure ChangeNumofFiles(); function doesRepeat(ReceivedValue: String): Boolean; function ParseValue(Value: String): String; procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure btn_change_num_filesClick(Sender: TObject); procedure SpeedButton5Click(Sender: TObject); procedure SpeedButton4Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ChangeFileType(); procedure ChangeFileLocation(); procedure Button3Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton6Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var FormFileEditor: TFormFileEditor; FStartNumber, FEndNumber: Integer; CancelPressed: Boolean; FSettingsFilePath: String; inifile: TMemIniFile; FileLocation: String; implementation {$R *.fmx} {$R *.Windows.fmx MSWINDOWS} procedure TFormFileEditor.addItemToListBox; var UserInputString: String; begin CancelPressed := false; UserInputString := inputbox('Add New', 'Please eneter the last 1 to 4 numbers of the file name:', 'e.g. 20'); if IsNumber(UserInputString) then begin if doesRepeat(UserInputString) then begin ListBox1.Items.Add(ParseValue(UserInputString)); end else begin showmessage('File: ' + ParseValue(UserInputString) + '.config, already exists in the list!'); end; end else if UserInputString = '' then begin showmessage('Please enter the last few numbers of the serial number:'); addItemToListBox; end else if UserInputString = 'e.g. 20' then begin showmessage('No file name was added to list'); CancelPressed := true; end; end; procedure TFormFileEditor.btn_change_num_filesClick(Sender: TObject); var I: Integer; NumberofFilesNeeded: Integer; begin if IsNumber(edt_num_files.Text) then begin NumberofFilesNeeded := strtoint(edt_num_files.Text); for I := ListBox1.Items.count downto NumberofFilesNeeded do begin ListBox1.Items.Delete(I); end; end else showmessage('Please enter the number of files needed'); end; procedure TFormFileEditor.Button1Click(Sender: TObject); begin addItemToListBox; ChangeNumofFiles; end; procedure TFormFileEditor.Button2Click(Sender: TObject); begin // Listbox1.ItemIndex[listbox1.Selected.Index]; if ListBox1.Items.count = 0 then begin showmessage('There are no items to be removed'); end else if ListBox1.ItemIndex > -1 then // always check if something is selected begin ListBox1.Items.Delete(ListBox1.ItemIndex); end else showmessage('Please Select an Item to remove'); ChangeNumofFiles; end; procedure TFormFileEditor.Button3Click(Sender: TObject); var I: Integer; begin ChangeFileType; ChangeFileLocation; if FileLocation <> '' then begin if NOT(ListBox1.count = 0) then begin ProgressBar1.Max := ListBox1.count; ProgressBar1.Value := 0; for I := 0 to ListBox1.count - 1 do begin ProgressBar1.Value := I + 1; Memo1.Lines.SaveToFile(FileLocation + '\' + ListBox1.Items.Strings[I] + ComboEdit1.Text); end; if ProgressBar1.Value = ProgressBar1.Max then begin showmessage('Files have been made!'); ProgressBar1.Value := 0; end else begin showmessage('Please add files to the list!'); end; end; end; end; procedure TFormFileEditor.ChangeNumofFiles; begin edt_num_files.Text := inttostr(ListBox1.Items.count); end; procedure TFormFileEditor.ChangeFileLocation; begin inifile := TMemIniFile.create(FSettingsFilePath + 'Configurations.ini'); inifile.writestring('System', 'FileLocation', edt_File_Location.Text); FileLocation := edt_File_Location.Text; inifile.UpdateFile; inifile.Free; end; procedure TFormFileEditor.ChangeFileType; begin inifile := TMemIniFile.create(FSettingsFilePath + 'Configurations.ini'); inifile.writestring('System', 'FileType', ComboEdit1.Text); inifile.UpdateFile; inifile.Free; end; function TFormFileEditor.doesRepeat(ReceivedValue: String): Boolean; var I: Integer; InList: Boolean; begin InList := true; if ListBox1.Items.count > 0 then begin for I := 0 to ListBox1.Items.count - 1 do begin if ListBox1.Items.Strings[I] = ParseValue(ReceivedValue) then begin InList := false; result := false; break; end; end; if InList then begin result := true; end; end; end; procedure TFormFileEditor.edt_start_filesKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (NOT(edt_start_files.Text = '')) AND (NOT(IsNumber(edt_start_files.Text))) then begin showmessage('ONLY USE NUMBERS!'); edt_start_files.Text := copy(edt_start_files.Text, 0, (Length(edt_start_files.Text) - 1)); end else if NOT(edt_start_files.Text = '') then begin FStartNumber := strtoint(edt_start_files.Text); end; end; procedure TFormFileEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin ProgressBar1.Value := 0; end; procedure TFormFileEditor.FormCreate(Sender: TObject); var I: Integer; jumpstring: string; begin FSettingsFilePath := Extractfilepath(ParamStr(0)); inifile := TMemIniFile.create(FSettingsFilePath + 'Configurations.ini'); ComboEdit1.Text := inifile.ReadString('System', 'FileType', ''); FileLocation := inifile.ReadString('System', 'FileLocation', ''); edt_File_Location.Text := FileLocation; I := 1; while true do begin if NOT(inifile.ReadString('FileExtensions', 'Type' + inttostr(I), '') = '') then begin jumpstring := inifile.ReadString('FileExtensions', 'Type' + inttostr(I), ''); ComboEdit1.Items.Add(jumpstring); end else break; I := I + 1; end; end; procedure TFormFileEditor.edt_end_filesKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (NOT(edt_end_files.Text = '')) AND (NOT(IsNumber(edt_end_files.Text))) then begin showmessage('ONLY USE NUMBERS!'); edt_end_files.Text := copy(edt_end_files.Text, 0, (Length(edt_end_files.Text) - 1)); end else if NOT(edt_end_files.Text = '') then begin FEndNumber := strtoint(edt_end_files.Text); end; end; function TFormFileEditor.IsNumber(N: String): Boolean; var I: Integer; begin result := true; if Trim(N) = '' then exit(false); if (Length(Trim(N)) > 1) and (Trim(N)[1] = '0') then exit(false); for I := 1 to Length(N) do begin if not(N[I] in ['0' .. '9']) then begin result := false; break; end; end; end; function TFormFileEditor.ParseValue(Value: String): String; begin case Value.Length of 1: result := ('1000000' + Value); 2: result := ('100000' + Value); 3: result := ('10000' + Value); 4: result := ('1000' + Value); else showmessage('Cannot enter more than 4 numbers'); result := '0'; end; end; procedure TFormFileEditor.rb_sequentialChange(Sender: TObject); begin if rb_sequential.IsChecked then begin Panel4.Enabled := true; edt_start_files.Text := inttostr(FStartNumber); edt_end_files.Text := inttostr(FEndNumber); end; end; procedure TFormFileEditor.rb_unsequentialChange(Sender: TObject); begin if rb_unsequential.IsChecked then begin Panel4.Enabled := false; edt_start_files.Text := '0'; edt_end_files.Text := '0'; end; end; procedure TFormFileEditor.SpeedButton1Click(Sender: TObject); var Caption: String; Root: String; Directory: String; begin Caption := 'Select a Folder'; selectdirectory(Caption, FileLocation, Directory); edt_File_Location.Text := Directory; ChangeFileLocation; end; procedure TFormFileEditor.SpeedButton2Click(Sender: TObject); var buttonSelected: Integer; MSGString: String; begin MSGString := 'Do you want to remove all of the items in the list.'; case messagedlg(MSGString, TMsgDlgType.mtConfirmation, mbokcancel, 0) of mrOK: begin ListBox1.Items.Clear; end; end; ChangeNumofFiles; end; procedure TFormFileEditor.SpeedButton3Click(Sender: TObject); var I, count: Integer; NumofFilesS: String; begin CancelPressed := false; // does it alot of times NumofFilesS := inputbox('Number of Files', 'Please eneter the Amount of Files to be added to the list:', 'e.g. 20'); if IsNumber(NumofFilesS) then begin count := strtoint(NumofFilesS); end; for I := 0 to count - 1 do begin if CancelPressed then begin break; end else begin addItemToListBox; ChangeNumofFiles end; end; end; procedure TFormFileEditor.SpeedButton4Click(Sender: TObject); var buttonSelected: Integer; MSGString: String; begin MSGString := 'Do you want to remove all of the items in the list.'; case messagedlg(MSGString, TMsgDlgType.mtConfirmation, mbokcancel, 0) of mrOK: begin ListBox1.Items.Clear; edt_start_files.Text := '0'; edt_end_files.Text := '0'; end; end; ChangeNumofFiles; end; procedure TFormFileEditor.SpeedButton5Click(Sender: TObject); var I, Start, Stop: Integer; begin Start := strtoint(edt_start_files.Text); Stop := strtoint(edt_end_files.Text); ListBox1.Items.Clear; if Start >= Stop then begin showmessage('Please Check your values'); edt_start_files.Text := '0'; edt_end_files.Text := '0'; end else begin for I := Start to Stop do begin ListBox1.Items.Add(ParseValue(inttostr(I))); end; ChangeNumofFiles; end; end; procedure TFormFileEditor.SpeedButton6Click(Sender: TObject); begin FormFileEditor.Hide; ProgressBar1.Value := 0; end; end.
{ ****************************************************************************** } { * json object library for delphi/objfpc * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit ZJson; {$INCLUDE zDefine.inc} interface uses SysUtils, {$IFDEF DELPHI} ZS_JsonDataObjects, {$ELSE DELPHI} FPCGenericStructlist, fpjson, jsonparser, jsonscanner, {$ENDIF DELPHI} CoreClasses, PascalStrings, DoStatusIO, UnicodeMixedLib, MemoryStream64; type TZ_JsonObject = class; {$IFDEF DELPHI} TZ_Instance_JsonArray = TJsonArray; TZ_Instance_JsonObject = TJsonObject; {$ELSE DELPHI} TZ_Instance_JsonArray = TJsonArray; TZ_Instance_JsonObject = TJsonObject; {$ENDIF DELPHI} TZ_JsonBase = class protected FParent: TZ_JsonBase; FList: TCoreClassObjectList; public property Parent: TZ_JsonBase read FParent; constructor Create(Parent_: TZ_JsonBase); virtual; destructor Destroy; override; end; TZ_JsonArray = class(TZ_JsonBase) private FInstance: TZ_Instance_JsonArray; public property Instance: TZ_Instance_JsonArray read FInstance; constructor Create(Parent_: TZ_JsonBase); override; destructor Destroy; override; procedure Clear; procedure Delete(Index: Integer); procedure Add(const v_: string); overload; procedure Add(const v_: TPascalString); overload; procedure Add(const v_: Integer); overload; procedure Add(const v_: Int64); overload; procedure Add(const v_: UInt64); overload; procedure AddF(const v_: Double); overload; procedure Add(const v_: TDateTime); overload; procedure Add(const v_: Boolean); overload; function AddArray: TZ_JsonArray; function AddObject: TZ_JsonObject; overload; procedure Insert(Index: Integer; const v_: string); overload; procedure Insert(Index: Integer; const v_: Integer); overload; procedure Insert(Index: Integer; const v_: Int64); overload; procedure Insert(Index: Integer; const v_: UInt64); overload; procedure Insert(Index: Integer; const v_: Double); overload; procedure Insert(Index: Integer; const v_: TDateTime); overload; procedure Insert(Index: Integer; const v_: Boolean); overload; function InsertArray(Index: Integer): TZ_JsonArray; function InsertObject(Index: Integer): TZ_JsonObject; overload; function GetString(Index: Integer): string; procedure SetString(Index: Integer; const Value: string); function GetInt(Index: Integer): Integer; procedure SetInt(Index: Integer; const Value: Integer); function GetLong(Index: Integer): Int64; procedure SetLong(Index: Integer; const Value: Int64); function GetULong(Index: Integer): UInt64; procedure SetULong(Index: Integer; const Value: UInt64); function GetFloat(Index: Integer): Double; procedure SetFloat(Index: Integer; const Value: Double); function GetDateTime(Index: Integer): TDateTime; procedure SetDateTime(Index: Integer; const Value: TDateTime); function GetBool(Index: Integer): Boolean; procedure SetBool(Index: Integer; const Value: Boolean); function GetArray(Index: Integer): TZ_JsonArray; function GetObject(Index: Integer): TZ_JsonObject; property S[Index: Integer]: string read GetString write SetString; property I[Index: Integer]: Integer read GetInt write SetInt; property I32[Index: Integer]: Integer read GetInt write SetInt; property L[Index: Integer]: Int64 read GetLong write SetLong; property I64[Index: Integer]: Int64 read GetLong write SetLong; property U[Index: Integer]: UInt64 read GetULong write SetULong; property U64[Index: Integer]: UInt64 read GetULong write SetULong; property F[Index: Integer]: Double read GetFloat write SetFloat; property D[Index: Integer]: TDateTime read GetDateTime write SetDateTime; property B[Index: Integer]: Boolean read GetBool write SetBool; property A[Index: Integer]: TZ_JsonArray read GetArray; property O[Index: Integer]: TZ_JsonObject read GetObject; function GetCount: Integer; property Count: Integer read GetCount; end; TZ_JsonObject = class(TZ_JsonBase) private FInstance: TZ_Instance_JsonObject; FTag: Integer; public property Tag: Integer read FTag write FTag; property Instance: TZ_Instance_JsonObject read FInstance; constructor Create(Parent_: TZ_JsonBase); overload; override; constructor Create(); overload; destructor Destroy; override; procedure Assign(source_: TZ_JsonObject); procedure Clear; function IndexOf(const Name: string): Integer; function GetString(const Name: string): string; procedure SetString(const Name, Value: string); function GetInt(const Name: string): Integer; procedure SetInt(const Name: string; const Value: Integer); function GetLong(const Name: string): Int64; procedure SetLong(const Name: string; const Value: Int64); function GetULong(const Name: string): UInt64; procedure SetULong(const Name: string; const Value: UInt64); function GetFloat(const Name: string): Double; procedure SetFloat(const Name: string; const Value: Double); function GetDateTime(const Name: string): TDateTime; procedure SetDateTime(const Name: string; const Value: TDateTime); function GetBool(const Name: string): Boolean; procedure SetBool(const Name: string; const Value: Boolean); function GetArray(const Name: string): TZ_JsonArray; function GetObject(const Name: string): TZ_JsonObject; property S[const Name: string]: string read GetString write SetString; property I[const Name: string]: Integer read GetInt write SetInt; property I32[const Name: string]: Integer read GetInt write SetInt; property L[const Name: string]: Int64 read GetLong write SetLong; property I64[const Name: string]: Int64 read GetLong write SetLong; property U[const Name: string]: UInt64 read GetULong write SetULong; property U64[const Name: string]: UInt64 read GetULong write SetULong; property F[const Name: string]: Double read GetFloat write SetFloat; property D[const Name: string]: TDateTime read GetDateTime write SetDateTime; property B[const Name: string]: Boolean read GetBool write SetBool; property A[const Name: string]: TZ_JsonArray read GetArray; property O[const Name: string]: TZ_JsonObject read GetObject; function GetName(Index: Integer): string; property Names[Index: Integer]: string read GetName; default; function GetCount: Integer; property Count: Integer read GetCount; procedure SaveToStream(stream: TCoreClassStream; Formated_: Boolean); overload; procedure SaveToStream(stream: TCoreClassStream); overload; procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToLines(L_: TCoreClassStrings); procedure LoadFromLines(L_: TCoreClassStrings); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure ParseText(Text_: TPascalString); function ToJSONString(Formated_: Boolean): TPascalString; overload; function ToJSONString: TPascalString; overload; property ToJson: TPascalString read ToJSONString; class procedure Test; end; TZ_JsonObject_List_Decl = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TZ_JsonObject>; TZ_JsonObject_List = class(TZ_JsonObject_List_Decl) public AutoFreeObj: Boolean; constructor Create(AutoFreeObj_: Boolean); destructor Destroy; override; function AddFromText(Text_: TPascalString): TZ_JsonObject; function AddFromStream(stream: TCoreClassStream): TZ_JsonObject; procedure Remove(obj: TZ_JsonObject); procedure Delete(Index: Integer); procedure Clear; procedure Clean; end; TZJArry = TZ_JsonArray; TZJ = TZ_JsonObject; TZJList = TZ_JsonObject_List; TZJL = TZ_JsonObject_List; implementation {$IFDEF DELPHI} {$INCLUDE ZJson_delphi.inc} {$ELSE DELPHI} {$INCLUDE ZJson_fpc.inc} {$ENDIF DELPHI} constructor TZ_JsonBase.Create(Parent_: TZ_JsonBase); begin inherited Create; FParent := Parent_; if FParent <> nil then FParent.FList.Add(self); FList := TCoreClassObjectList.Create; FList.AutoFreeObj := True; end; destructor TZ_JsonBase.Destroy; begin FList.Free; inherited Destroy; end; constructor TZ_JsonArray.Create(Parent_: TZ_JsonBase); begin inherited Create(Parent_); end; destructor TZ_JsonArray.Destroy; begin inherited Destroy; end; constructor TZ_JsonObject.Create(Parent_: TZ_JsonBase); begin inherited Create(Parent_); FTag := 0; if Parent = nil then FInstance := TZ_Instance_JsonObject.Create; end; constructor TZ_JsonObject.Create; begin Create(nil); end; destructor TZ_JsonObject.Destroy; begin if Parent = nil then FInstance.Free; inherited Destroy; end; procedure TZ_JsonObject.Assign(source_: TZ_JsonObject); var m64: TMS64; begin m64 := TMS64.Create; source_.SaveToStream(m64); m64.Position := 0; LoadFromStream(m64); disposeObject(m64); end; procedure TZ_JsonObject.SaveToStream(stream: TCoreClassStream); begin SaveToStream(stream, True); end; procedure TZ_JsonObject.SaveToLines(L_: TCoreClassStrings); var m64: TMS64; begin m64 := TMS64.Create; SaveToStream(m64); m64.Position := 0; {$IFDEF FPC} L_.LoadFromStream(m64); {$ELSE} L_.LoadFromStream(m64, TEncoding.UTF8); {$ENDIF} m64.Free; end; procedure TZ_JsonObject.LoadFromLines(L_: TCoreClassStrings); var m64: TMS64; begin m64 := TMS64.Create; {$IFDEF FPC} L_.SaveToStream(m64); {$ELSE} L_.SaveToStream(m64, TEncoding.UTF8); {$ENDIF} m64.Position := 0; LoadFromStream(m64); m64.Free; end; procedure TZ_JsonObject.SaveToFile(FileName: SystemString); var m64: TMS64; begin m64 := TMS64.Create; try SaveToStream(m64); m64.SaveToFile(FileName); finally disposeObject(m64); end; end; procedure TZ_JsonObject.LoadFromFile(FileName: SystemString); var m64: TMS64; begin m64 := TMS64.Create; try m64.LoadFromFile(FileName); except disposeObject(m64); Exit; end; try LoadFromStream(m64); finally disposeObject(m64); end; end; procedure TZ_JsonObject.ParseText(Text_: TPascalString); var buff: TBytes; m64: TMS64; begin buff := Text_.Bytes; m64 := TMS64.Create; if length(buff) > 0 then m64.SetPointerWithProtectedMode(@buff[0], length(buff)); LoadFromStream(m64); m64.Free; SetLength(buff, 0); end; function TZ_JsonObject.ToJSONString(Formated_: Boolean): TPascalString; var m64: TMS64; begin m64 := TMS64.Create; SaveToStream(m64, Formated_); Result.Bytes := m64.ToBytes; m64.Free; end; function TZ_JsonObject.ToJSONString: TPascalString; var m64: TMS64; begin m64 := TMS64.Create; SaveToStream(m64, True); Result.Bytes := m64.ToBytes; m64.Free; end; class procedure TZ_JsonObject.Test; var js: TZ_JsonObject; ii: Integer; m64: TMS64; begin js := TZ_JsonObject.Create(); js.S['abc'] := '123'; DoStatus(js.S['abc']); for ii := 1 to 3 do js.A['arry'].Add(ii); for ii := 0 to js.A['arry'].Count - 1 do begin DoStatus(js.A['arry'].I[ii]); end; js.A['arry'].AddObject.S['tt'] := 'inobj'; js.O['obj'].S['fff'] := '999'; DoStatus(js.ToJSONString(True)); m64 := TMS64.Create; js.SaveToStream(m64); m64.Position := 0; js.LoadFromStream(m64); DoStatus(js.ToJSONString(True)); js.Free; end; constructor TZ_JsonObject_List.Create(AutoFreeObj_: Boolean); begin inherited Create; AutoFreeObj := AutoFreeObj_; end; destructor TZ_JsonObject_List.Destroy; begin Clear; inherited Destroy; end; function TZ_JsonObject_List.AddFromText(Text_: TPascalString): TZ_JsonObject; begin Result := TZ_JsonObject.Create(nil); Result.ParseText(Text_); Add(Result); end; function TZ_JsonObject_List.AddFromStream(stream: TCoreClassStream): TZ_JsonObject; begin Result := TZ_JsonObject.Create(nil); Result.LoadFromStream(stream); Add(Result); end; procedure TZ_JsonObject_List.Remove(obj: TZ_JsonObject); begin if AutoFreeObj then disposeObject(obj); inherited Remove(obj); end; procedure TZ_JsonObject_List.Delete(Index: Integer); begin if (index >= 0) and (index < Count) then begin if AutoFreeObj then disposeObject(Items[index]); inherited Delete(index); end; end; procedure TZ_JsonObject_List.Clear; var I: Integer; begin if AutoFreeObj then for I := 0 to Count - 1 do disposeObject(Items[I]); inherited Clear; end; procedure TZ_JsonObject_List.Clean; var I: Integer; begin for I := 0 to Count - 1 do disposeObject(Items[I]); inherited Clear; end; initialization end.
unit FSettings; (*==================================================================== Dialog box for DiskBase general settings ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages,ComCtrls, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, {TabNotBk,} Spin, Grids, UTypes, UApiTypes {$ifdef LOGFONT} , ComCtrls , UFont {my font dialog box} {$endif} ; const clQSelectedBack = clGray; clQSelectedText = clHighlightText; clQDeletedText = clGray; type TPanelHeaderWidths = array[0..2] of Integer; TUserCommand = record m_wKey : Word; m_bShift : boolean; m_bControl : boolean; m_bAlt : boolean; m_sDll : AnsiString; m_sParams : AnsiString; m_bTestExist: boolean; end; TPUserCommand = ^TUserCommand; TGlobalOptions = class { -Display tab- } ShowTree : boolean; ExpandTree : boolean; SortCrit : TSortCrit; ShowInKb : boolean; {RadioGroupSizeDisplay} FileDisplayType : TFileDisplayType; ShowSize : boolean; ShowTime : boolean; ShowDescr : boolean; ShowIcons : boolean; ShowSeconds : boolean; SystemDateFormat: boolean; OneKbIs1024 : boolean; ShowFileHints : boolean; ReversedSort : boolean; {neni nikde zobrazovano, ani ukladano} { -Fonts tab- } {$ifndef LOGFONT} DiskFont : TFont; TreeFont : TFont; FileFont : TFont; FoundFont : TFont; DescFont : TFont; PrintFont : TFont; {$else} DiskLogFont : TLogFont; TreeLogFont : TLogFont; FileLogFont : TLogFont; FoundLogFont : TLogFont; DescLogFont : TLogFont; PrintLogFont : TLogFont; DiskLogFontSize : Integer; TreeLogFontSize : Integer; FileLogFontSize : Integer; FoundLogFontSize: Integer; DescLogFontSize : Integer; PrintLogFontSize: Integer; {$endif} { -Print tab- } PrintHeader : ShortString; AdjustNameWidth : boolean; TopMargin : Integer; BottomMargin : Integer; LeftMargin : Integer; RightMargin : Integer; { -Other tab- } AutoLoadDBase : ShortString; OpenLastOpened : boolean; FoundToNewWin : boolean; AutoSave : boolean; BackupDBase : boolean; PersistentBlocks : boolean; NotScanDriveNames : boolean; EnableShellExecute: boolean; PanelHeaderWidths : TPanelHeaderWidths; EnableUTFConvert : boolean; constructor Create; destructor Destroy; override; end; { TFormSettings } TFormSettings = class(TForm) CheckBoxEnableUTFConvert: TCheckBox; GroupBoxMargins: TGroupBox; ///TabbedNotebook: TTabbedNotebook; TabbedNotebook: TPageControl; Page1: TTabSheet; Page2: TTabSheet; Page3: TTabSheet; Page4: TTabSheet; Page5: TTabSheet; ButtonOK: TButton; RadioGroupSortCrit: TRadioGroup; GroupBoxFileDisplay: TGroupBox; RadioButtonBrief: TRadioButton; RadioButtonDetailed: TRadioButton; CheckBoxShowSize: TCheckBox; CheckBoxShowTime: TCheckBox; CheckBoxShowDescr: TCheckBox; FontDialogDisk: TFontDialog; FontDialogTree: TFontDialog; FontDialogFile: TFontDialog; FontDialogFound: TFontDialog; RadioGroupSizeDisplay: TRadioGroup; CheckBoxShowIcons: TCheckBox; GroupBoxTree: TGroupBox; CheckBoxExpandTree: TCheckBox; CheckBoxShowTree: TCheckBox; ButtonCancel: TButton; SpinEditTop: TSpinEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; SpinEditBottom: TSpinEdit; SpinEditLeft: TSpinEdit; SpinEditRight: TSpinEdit; ButtonChangePrintFont: TButton; FontDialogPrint: TFontDialog; LabelPrintFont: TLabel; EditPrintHeader: TEdit; Label5: TLabel; OpenDialogDBase: TOpenDialog; ButtonHelp: TButton; ButtonChangeDiskFont: TButton; LabelDiskFont: TLabel; Label8: TLabel; LabelTreeFont: TLabel; ButtonChangeTreeFont: TButton; Label9: TLabel; LabelFileFont: TLabel; ButtonChangeFileFont: TButton; Label10: TLabel; ButtonChangeFoundFont: TButton; LabelFoundFont: TLabel; Label11: TLabel; ButtonChangeDescFont: TButton; LabelDescFont: TLabel; Label12: TLabel; FontDialogDesc: TFontDialog; EditAutoLoadDBase: TEdit; Label6: TLabel; ButtonBrowse: TButton; CheckBoxShowSeconds: TCheckBox; CheckBoxWinDateFormat: TCheckBox; CheckBoxOneKbIs1024: TCheckBox; CheckBoxBackupDBase: TCheckBox; CheckBoxFoundToNewWin: TCheckBox; CheckBoxAutoSave: TCheckBox; GroupBoxPrintFont: TGroupBox; CheckBoxNotScanDriveNames: TCheckBox; CheckBoxShowFileHints: TCheckBox; CheckBoxPersistentBlocks: TCheckBox; CheckBoxOpenLastOpened: TCheckBox; CheckBoxAdjustNameWidth: TCheckBox; CheckBoxEnableShellExecute: TCheckBox; CheckBoxDisableCdAutoRun: TCheckBox; CheckBoxEjectAfterCdScan: TCheckBox; CheckBoxScanAfterCdInsert: TCheckBox; CheckBoxNoQueries: TCheckBox; procedure ButtonOKClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure RadioButtonBriefClick(Sender: TObject); procedure RadioButtonDetailedClick(Sender: TObject); procedure ButtonChangeDiskFontClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ButtonChangeTreeFontClick(Sender: TObject); procedure ButtonChangeFileFontClick(Sender: TObject); procedure ButtonSaveClick(Sender: TObject); procedure ButtonChangeFoundFontClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure CheckBoxShowTreeClick(Sender: TObject); procedure ButtonChangePrintFontClick(Sender: TObject); procedure ButtonBrowseClick(Sender: TObject); procedure ButtonHelpClick(Sender: TObject); procedure ButtonChangeDescFontClick(Sender: TObject); procedure CheckBoxOpenLastOpenedClick(Sender: TObject); procedure CheckBoxDisableCdAutoRunClick(Sender: TObject); procedure CheckBoxEjectAfterCdScanClick(Sender: TObject); procedure CheckBoxScanAfterCdInsertClick(Sender: TObject); procedure CheckBoxNoQueriesClick(Sender: TObject); private {$ifndef LOGFONT} DiskFont : TFont; TreeFont : TFont; FileFont : TFont; FoundFont : TFont; DescFont : TFont; PrintFont : TFont; {$else} DiskLogFont : TLogFont; TreeLogFont : TLogFont; FileLogFont : TLogFont; FoundLogFont : TLogFont; DescLogFont : TLogFont; PrintLogFont : TLogFont; DiskLogFontSize : Integer; TreeLogFontSize : Integer; FileLogFontSize : Integer; FoundLogFontSize: Integer; DescLogFontSize : Integer; PrintLogFontSize: Integer; {$endif} SaveOptions: TGlobalOptions; {AlreadyWarned: boolean;} procedure SaveToIni; procedure LoadFromIni; procedure UpdateFontLabels; public HeaderWidths: TPanelHeaderWidths; procedure SetOptions(GlobalOptions: TGlobalOptions); procedure GetOptions(GlobalOptions: TGlobalOptions); procedure UpdateGlobalFormatSettings; procedure DefaultHandler(var Message); override; end; var FormSettings: TFormSettings; g_CommonOptions: record bDisableCdAutorun : boolean; bEjectAfterCdScan : boolean; bScanAfterCdInsert : boolean; bNoQueries : boolean; dwQueryCancelAutoPlay: DWORD; end; g_UserCommandList: TList; g_sTempFolder : AnsiString; implementation uses IniFiles, FMain, UBaseUtils, ULang, UDrives, FSelectDrive{, FDBase}; {$R *.dfm} //===TGlobalOptions============================================================ constructor TGlobalOptions.Create; begin {$ifndef LOGFONT} DiskFont := TFont.Create; TreeFont := TFont.Create; FileFont := TFont.Create; FoundFont := TFont.Create; DescFont := TFont.Create; PrintFont := TFont.Create; {$endif} end; //----------------------------------------------------------------------------- destructor TGlobalOptions.Destroy; begin {$ifndef LOGFONT} PrintFont.Free; DescFont.Free; FoundFont.Free; FileFont.Free; TreeFont.Free; DiskFont.Free; {$endif} end; //===TFormSettings============================================================= procedure TFormSettings.ButtonOKClick(Sender: TObject); begin SaveToIni; ModalResult := mrOK; UsePersistentBlocks := CheckBoxPersistentBlocks.Checked; ScanAllDriveNames := not CheckBoxNotScanDriveNames.Checked; {in the QDRIVES unit} UpdateGlobalFormatSettings; end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonCancelClick(Sender: TObject); begin SetOptions(SaveOptions); CheckBoxPersistentBlocks.Checked := UsePersistentBlocks; CheckBoxNotScanDriveNames.Checked := not ScanAllDriveNames; ModalResult := mrCancel; end; //----------------------------------------------------------------------------- procedure TFormSettings.RadioButtonBriefClick(Sender: TObject); begin CheckBoxShowSize.Enabled := false; CheckBoxShowTime.Enabled := false; CheckBoxShowDescr.Enabled := false; RadioGroupSizeDisplay.Enabled := false; end; //----------------------------------------------------------------------------- procedure TFormSettings.RadioButtonDetailedClick(Sender: TObject); begin CheckBoxShowSize.Enabled := true; CheckBoxShowTime.Enabled := true; CheckBoxShowDescr.Enabled := true; RadioGroupSizeDisplay.Enabled := true; end; //----------------------------------------------------------------------------- // global settings are used for export to text format procedure TFormSettings.UpdateGlobalFormatSettings; begin gFormatSettings.SortCrit := TSortCrit(RadioGroupSortCrit.ItemIndex); gFormatSettings.bShowInKb := RadioGroupSizeDisplay.ItemIndex = 1; gFormatSettings.bShowSeconds := CheckBoxShowSeconds.Checked; gFormatSettings.bReversedSort := false; // nedoreseno! end; //----------------------------------------------------------------------------- procedure TFormSettings.FormCreate(Sender: TObject); begin {$ifndef LOGFONT} DiskFont := TFont.Create; TreeFont := TFont.Create; FileFont := TFont.Create; FoundFont := TFont.Create; DescFont := TFont.Create; PrintFont := TFont.Create; {$endif} SaveOptions := TGlobalOptions.Create; LoadFromIni; UpdateFontLabels; TabbedNotebook.ActivePage := TabbedNotebook.Pages[0]; end; //----------------------------------------------------------------------------- procedure TFormSettings.FormDestroy(Sender: TObject); begin if CheckBoxAutoSave.Checked then SaveToIni; SaveOptions.Free; {$ifndef LOGFONT} PrintFont.Free; DescFont.Free; FoundFont.Free; FileFont.Free; TreeFont.Free; DiskFont.Free; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.UpdateFontLabels; {$ifndef LOGFONT} function GetFontDescription(var Font: TFont): ShortString; var S: ShortString; begin with Font do begin S := ''; if fsBold in Style then S := S + lsBold; if fsItalic in Style then S := S + lsItalics; Result := Name + ', ' + IntToStr(Size) + S; end; end; {$else} function GetLogFontDescription(var LogFont: TLogFont; Size: Integer): ShortString; var S: ShortString; begin with LogFont do begin S := ''; if lfWeight = FW_BOLD then S := S + lsBold; if lfItalic = 1 then S := S + lsItalics; Result := StrPas(lfFaceName) + ', ' + QGetScriptString(lfCharSet) + ', ' + IntToStr(Size) + S; end; end; {$endif} begin {$ifndef LOGFONT} LabelDiskFont.Caption := GetFontDescription(DiskFont); LabelTreeFont.Caption := GetFontDescription(TreeFont); LabelFileFont.Caption := GetFontDescription(FileFont); LabelFoundFont.Caption := GetFontDescription(FoundFont); LabelDescFont.Caption := GetFontDescription(DescFont); LabelPrintFont.Caption := GetFontDescription(PrintFont); {$else} LabelDiskFont.Caption := GetLogFontDescription(DiskLogFont, DiskLogFontSize); LabelTreeFont.Caption := GetLogFontDescription(TreeLogFont, TreeLogFontSize); LabelFileFont.Caption := GetLogFontDescription(FileLogFont, FileLogFontSize); LabelFoundFont.Caption := GetLogFontDescription(FoundLogFont, FoundLogFontSize); LabelDescFont.Caption := GetLogFontDescription(DescLogFont, DescLogFontSize); LabelPrintFont.Caption := GetLogFontDescription(PrintLogFont, PrintLogFontSize); {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangeDiskFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogDisk.Font.Assign(DiskFont); if FontDialogDisk.Execute then begin DiskFont.Assign(FontDialogDisk.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(DiskLogFont, 6, 24, false, DiskLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangeTreeFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogTree.Font.Assign(TreeFont); if FontDialogTree.Execute then begin TreeFont.Assign(FontDialogTree.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(TreeLogFont, 6, 24, false, TreeLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangeFileFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogFile.Font.Assign(FileFont); if FontDialogFile.Execute then begin FileFont.Assign(FontDialogFile.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(FileLogFont, 6, 24, false, FileLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangeFoundFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogFound.Font.Assign(FoundFont); if FontDialogFound.Execute then begin FoundFont.Assign(FontDialogFound.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(FoundLogFont, 6, 24, false, FoundLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangeDescFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogDesc.Font.Assign(DescFont); if FontDialogDesc.Execute then begin DescFont.Assign(FontDialogDesc.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(DescLogFont, 6, 24, false, DescLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonChangePrintFontClick(Sender: TObject); begin {$ifndef LOGFONT} FontDialogPrint.Font.Assign(PrintFont); if FontDialogPrint.Execute then begin PrintFont.Assign(FontDialogPrint.Font); UpdateFontLabels; end; {$else} if QSelectLogFontDialog(PrintLogFont, 6, 24, true, PrintLogFontSize) then UpdateFontLabels; {$endif} end; //----------------------------------------------------------------------------- procedure TFormSettings.SaveToIni; var IniFile: TIniFile; sIniFileName: AnsiString; {$ifndef LOGFONT} procedure WriteFont(var Font: TFont; Section: ShortString); begin with Font do begin IniFile.WriteString (Section, 'FontName', Name); IniFile.WriteInteger(Section, 'FontSize', Size); IniFile.WriteBool (Section, 'Bold', fsBold in Style); IniFile.WriteBool (Section, 'Italic', fsItalic in Style); end; end; {$else} procedure WriteLogFont(var LogFont: TLogFont; LogFontSize: ShortInt; Section: ShortString); begin with LogFont do begin IniFile.WriteString (Section, 'FontName', StrPas(lfFaceName)); IniFile.WriteString (Section, 'FontScript', QGetScriptString(lfCharSet)); IniFile.WriteInteger(Section, 'FontSize', LogFontSize); IniFile.WriteBool (Section, 'Bold', lfWeight = FW_BOLD); IniFile.WriteBool (Section, 'Italic', lfItalic = 1); end; end; {$endif} begin sIniFileName := ChangeFileExt(ParamStr(0), '.ini'); if not FileExists(sIniFileName) then // test file creation begin if not TestFileCreation(sIniFileName) then exit; end else begin // check if it is read-only ///if ((GetFileAttributes(PChar(sIniFileName)) and FILE_ATTRIBUTE_READONLY) <> 0) then exit; end; IniFile := TIniFile.Create(sIniFileName); IniFile.WriteBool ('General', 'Autosave', CheckBoxAutoSave.Checked); IniFile.WriteBool ('General', 'FoundToNewWin', CheckBoxFoundToNewWin.Checked); IniFile.WriteBool ('General', 'BackupDBase', CheckBoxBackupDBase.Checked); {IniFile.WriteBool ('General', 'UseWinLocale', CheckBoxUseWinLocale.Checked);} IniFile.WriteBool ('General', 'NotScanDriveNames', CheckBoxNotScanDriveNames.Checked); IniFile.WriteBool ('General', 'EnableShellExecute', CheckBoxEnableShellExecute.Checked); IniFile.WriteString ('General', 'AutoLoad', EditAutoLoadDBase.Text); IniFile.WriteBool ('General', 'AutoLoadLast', CheckBoxOpenLastOpened.Checked); IniFile.WriteBool ('General', 'DisableAutorun', CheckBoxDisableCdAutoRun.Checked); IniFile.WriteBool ('General', 'EjectAfterScan', CheckBoxEjectAfterCdScan.Checked); IniFile.WriteBool ('General', 'ScanAfterInsert', CheckBoxScanAfterCdInsert.Checked); IniFile.WriteBool ('General', 'NoQueries', CheckBoxNoQueries.Checked); IniFile.WriteBool ('General', 'EnableUTFConvert',CheckBoxEnableUTFConvert.Checked); IniFile.WriteBool ('Display', 'ShowTree', CheckBoxShowTree.Checked); IniFile.WriteBool ('Display', 'ExpandTree', CheckBoxExpandTree.Checked); IniFile.WriteBool ('Display', 'DetailedDisplay', RadioButtonDetailed.Checked); IniFile.WriteBool ('Display', 'ShowSize', CheckBoxShowSize.Checked); IniFile.WriteBool ('Display', 'ShowTime', CheckBoxShowTime.Checked); IniFile.WriteBool ('Display', 'ShowDescr', CheckBoxShowDescr.Checked); IniFile.WriteInteger ('Display', 'SortCrit', RadioGroupSortCrit.ItemIndex); IniFile.WriteInteger ('Display', 'SizeDisplay', RadioGroupSizeDisplay.ItemIndex); IniFile.WriteBool ('Display', 'ShowSeconds', CheckBoxShowSeconds.Checked); IniFile.WriteBool ('Display', 'ShowIcons', CheckBoxShowIcons.Checked); IniFile.WriteBool ('Display', 'WinDateFormat', CheckBoxWinDateFormat.Checked); IniFile.WriteBool ('Display', 'OneKbIs1024', CheckBoxOneKbIs1024.Checked); IniFile.WriteBool ('Display', 'ShowFileHints', CheckBoxShowFileHints.Checked); IniFile.WriteBool ('Display', 'PersistentBlocks',CheckBoxPersistentBlocks.Checked); {$ifndef LOGFONT} WriteFont(DiskFont, 'DiskPanel'); WriteFont(TreeFont, 'TreePanel'); WriteFont(FileFont, 'FilePanel'); WriteFont(FoundFont, 'SearchWindow'); WriteFont(DescFont, 'DescriptionWindow'); WriteFont(PrintFont, 'PrintPanel'); {$else} WriteLogFont(DiskLogFont, DiskLogFontSize, 'DiskPanel'); WriteLogFont(TreeLogFont, TreeLogFontSize, 'TreePanel'); WriteLogFont(FileLogFont, FileLogFontSize, 'FilePanel'); WriteLogFont(FoundLogFont, FoundLogFontSize, 'SearchWindow'); WriteLogFont(DescLogFont, DescLogFontSize, 'DescriptionWindow'); WriteLogFont(PrintLogFont, PrintLogFontSize, 'PrintPanel'); {$endif} IniFile.WriteInteger ('Print', 'TopMargin', SpinEditTop.Value); IniFile.WriteInteger ('Print', 'BottomMargin', SpinEditBottom.Value); IniFile.WriteInteger ('Print', 'LeftMargin', SpinEditLeft.Value); IniFile.WriteInteger ('Print', 'RightMargin', SpinEditRight.Value); IniFile.WriteString ('Print', 'Header', EditPrintHeader.Text); IniFile.WriteBool ('Print', 'AdjustNameWidth', CheckBoxAdjustNameWidth.Checked); IniFile.Free; end; //----------------------------------------------------------------------------- procedure TFormSettings.LoadFromIni; var IniFile: TIniFile; sIniFileName: AnsiString; {$ifndef LOGFONT} procedure ReadFont(var Font: TFont; Section: ShortString; DefaultName: ShortString; DefaultSize: Integer); begin with Font do begin Name := IniFile.ReadString (Section, 'FontName', DefaultName); Size := IniFile.ReadInteger(Section, 'FontSize', DefaultSize); Style := []; if IniFile.ReadBool (Section, 'Bold', false) then Style := Style + [fsBold]; if IniFile.ReadBool (Section, 'Italic', false) then Style := Style + [fsItalic]; end; end; procedure SetFont(var Font: TFont; Section: ShortString; DefaultName: ShortString; DefaultSize: Integer); begin with Font do begin Name := DefaultName; Size := DefaultSize; Style := []; end; end; {$else} procedure ReadLogFont(var LogFont: TLogFont; var LogFontSize: Integer; Section: ShortString; DefaultName: ShortString; DefaultSize: Integer); var Name, Script: ShortString; Bold, Italics : boolean; begin with LogFont do begin Name := IniFile.ReadString (Section, 'FontName', DefaultName); Script := IniFile.ReadString (Section, 'FontScript', lsScript); LogFontSize := IniFile.ReadInteger(Section, 'FontSize', DefaultSize); Bold := IniFile.ReadBool (Section, 'Bold', false); Italics := IniFile.ReadBool (Section, 'Italic', false); InitLogFontStruct (LogFont, Name, LogFontSize, Bold, Italics, Script); end; end; procedure SetLogFont(var LogFont: TLogFont; var LogFontSize: Integer; Section: ShortString; DefaultName: ShortString; DefaultSize: Integer); var Name, Script: ShortString; Bold, Italics : boolean; begin with LogFont do begin Name := DefaultName; Script := lsScript; LogFontSize := DefaultSize; Bold := false; Italics := false; InitLogFontStruct (LogFont, Name, LogFontSize, Bold, Italics, Script); end; end; {$endif} begin sIniFileName := ChangeFileExt(ParamStr(0), '.ini'); if not FileExists(sIniFileName) then begin CheckBoxAutoSave.Checked := false; CheckBoxFoundToNewWin.Checked := false; CheckBoxBackupDBase.Checked := false; CheckBoxNotScanDriveNames.Checked := false; CheckBoxEnableShellExecute.Checked := false; CheckBoxDisableCdAutoRun.Checked := g_CommonOptions.bDisableCdAutorun; CheckBoxEjectAfterCdScan.Checked := g_CommonOptions.bEjectAfterCdScan; CheckBoxScanAfterCdInsert.Checked := g_CommonOptions.bScanAfterCdInsert; CheckBoxNoQueries.Checked := g_CommonOptions.bNoQueries; EditAutoLoadDBase.Text := ''; CheckBoxOpenLastOpened.Checked := true; CheckBoxEnableUTFConvert.Checked := false; CheckBoxShowTree.Checked := true; CheckBoxExpandTree.Checked := false; CheckBoxExpandTree.Enabled := CheckBoxShowTree.Checked; RadioButtonBrief.Checked := true; RadioButtonBriefClick(Self); CheckBoxShowSize.Checked := true; CheckBoxShowTime.Checked := true; CheckBoxShowDescr.Checked := true; RadioGroupSortCrit.ItemIndex := 0; RadioGroupSizeDisplay.ItemIndex := 1; CheckBoxShowSeconds.Checked := false; CheckBoxShowIcons.Checked := true; CheckBoxWinDateFormat.Checked := false; CheckBoxOneKbIs1024.Checked := true; CheckBoxShowFileHints.Checked := true; CheckBoxPersistentBlocks.Checked := true; {$ifndef LOGFONT} SetFont(DiskFont, 'DiskPanel', lsMSSansSerif, 9); SetFont(TreeFont, 'TreePanel', lsMSSansSerif, 9); SetFont(FileFont, 'FilePanel', lsMSSansSerif, 9); SetFont(FoundFont, 'SearchWindow', lsMSSansSerif, 9); SetFont(DescFont, 'DescriptionWindow', lsMSSansSerif, 9); SetFont(PrintFont, 'PrintPanel', lsArial, 9); {$else} SetLogFont(DiskLogFont, DiskLogFontSize, 'DiskPanel', lsMSSansSerif, 9); SetLogFont(TreeLogFont, TreeLogFontSize, 'TreePanel', lsMSSansSerif, 9); SetLogFont(FileLogFont, FileLogFontSize, 'FilePanel', lsMSSansSerif, 9); SetLogFont(FoundLogFont, FoundLogFontSize, 'SearchWindow', lsMSSansSerif, 9); SetLogFont(DescLogFont, DescLogFontSize, 'DescriptionWindow', lsMSSansSerif, 9); SetLogFont(PrintLogFont, PrintLogFontSize, 'PrintPanel', lsArial, 9); {$endif} SpinEditTop.Value := 15; SpinEditBottom.Value := 15; SpinEditLeft.Value := 15; SpinEditRight.Value := 15; EditPrintHeader.Text := ''; CheckBoxAdjustNameWidth.Checked := true; HeaderWidths[0] := 93; HeaderWidths[1] := 152; HeaderWidths[2] := 242; g_PanelHeaderWidths := HeaderWidths; end else begin IniFile := TIniFile.Create(sIniFileName); CheckBoxAutoSave.Checked := IniFile.ReadBool ('General', 'Autosave', false); CheckBoxFoundToNewWin.Checked := IniFile.ReadBool ('General', 'FoundToNewWin', false); CheckBoxBackupDBase.Checked := IniFile.ReadBool ('General', 'BackupDBase', false); {CheckBoxUseWinLocale.Checked := IniFile.ReadBool('General', 'UseWinLocale', true);} CheckBoxNotScanDriveNames.Checked := IniFile.ReadBool ('General', 'NotScanDriveNames', false); CheckBoxEnableShellExecute.Checked := IniFile.ReadBool ('General', 'EnableShellExecute', false); CheckBoxDisableCdAutoRun.Checked := IniFile.ReadBool ('General', 'DisableAutorun', true); CheckBoxEjectAfterCdScan.Checked := IniFile.ReadBool ('General', 'EjectAfterScan', true); CheckBoxScanAfterCdInsert.Checked := IniFile.ReadBool ('General', 'ScanAfterInsert', false); CheckBoxNoQueries.Checked := IniFile.ReadBool ('General', 'NoQueries', false); EditAutoLoadDBase.Text := IniFile.ReadString('General', 'AutoLoad', ''); CheckBoxOpenLastOpened.Checked := IniFile.ReadBool ('General', 'AutoLoadLast', true); CheckBoxEnableUTFConvert.Checked := IniFile.ReadBool ('General', 'EnableUTFConvert', false); CheckBoxShowTree.Checked := IniFile.ReadBool('Display', 'ShowTree', true); CheckBoxExpandTree.Checked := IniFile.ReadBool('Display', 'ExpandTree', false); CheckBoxExpandTree.Enabled := CheckBoxShowTree.Checked; if IniFile.ReadBool('Display', 'DetailedDisplay', false) then begin RadioButtonDetailed.Checked := true; RadioButtonDetailedClick(Self); end else begin RadioButtonBrief.Checked := true; RadioButtonBriefClick(Self); end; CheckBoxShowSize.Checked := IniFile.ReadBool('Display', 'ShowSize', true); CheckBoxShowTime.Checked := IniFile.ReadBool('Display', 'ShowTime', true); CheckBoxShowDescr.Checked := IniFile.ReadBool('Display', 'ShowDescr', true); RadioGroupSortCrit.ItemIndex := IniFile.ReadInteger ('Display', 'SortCrit', 0); RadioGroupSizeDisplay.ItemIndex := IniFile.ReadInteger ('Display', 'SizeDisplay', 1); CheckBoxShowSeconds.Checked := IniFile.ReadBool('Display', 'ShowSeconds', false); CheckBoxShowIcons.Checked := IniFile.ReadBool('Display', 'ShowIcons', true); CheckBoxWinDateFormat.Checked := IniFile.ReadBool('Display', 'WinDateFormat', false); CheckBoxOneKbIs1024.Checked := IniFile.ReadBool('Display', 'OneKbIs1024', true); CheckBoxShowFileHints.Checked := IniFile.ReadBool('Display', 'ShowFileHints', true); CheckBoxPersistentBlocks.Checked := IniFile.ReadBool('Display', 'PersistentBlocks', true); {$ifndef LOGFONT} {$ifdef DELPHI1} ReadFont(DiskFont, 'DiskPanel', lsMSSansSerif, 8); ReadFont(TreeFont, 'TreePanel', lsMSSansSerif, 9); ReadFont(FileFont, 'FilePanel', lsMSSansSerif, 8); ReadFont(FoundFont, 'SearchWindow', lsMSSansSerif, 8); ReadFont(DescFont, 'DescriptionWindow', lsMSSansSerif, 8); ReadFont(PrintFont, 'PrintPanel', lsArial, 9); {$else} ReadFont(DiskFont, 'DiskPanel', lsMSSansSerif, 8); ReadFont(TreeFont, 'TreePanel', lsMSSansSerif, 9); ReadFont(FileFont, 'FilePanel', lsMSSansSerif, 8); ReadFont(FoundFont, 'SearchWindow', lsMSSansSerif, 8); ReadFont(DescFont, 'DescriptionWindow', lsMSSansSerif, 8); ReadFont(PrintFont, 'PrintPanel', lsArial, 9); {$endif} {$else} ReadLogFont(DiskLogFont, DiskLogFontSize, 'DiskPanel', lsMSSansSerif, 8); ReadLogFont(TreeLogFont, TreeLogFontSize, 'TreePanel', lsMSSansSerif, 9); ReadLogFont(FileLogFont, FileLogFontSize, 'FilePanel', lsMSSansSerif, 8); ReadLogFont(FoundLogFont, FoundLogFontSize, 'SearchWindow', lsMSSansSerif, 8); ReadLogFont(DescLogFont, DescLogFontSize, 'DescriptionWindow', lsMSSansSerif, 8); ReadLogFont(PrintLogFont, PrintLogFontSize, 'PrintPanel', lsArial, 9); {$endif} SpinEditTop.Value := IniFile.ReadInteger ('Print', 'TopMargin', 15); SpinEditBottom.Value := IniFile.ReadInteger ('Print', 'BottomMargin', 15); SpinEditLeft.Value := IniFile.ReadInteger ('Print', 'LeftMargin', 15); SpinEditRight.Value := IniFile.ReadInteger ('Print', 'RightMargin', 15); EditPrintHeader.Text := IniFile.ReadString ('Print', 'Header', ''); CheckBoxAdjustNameWidth.Checked := IniFile.ReadBool ('Print', 'AdjustNameWidth', true); HeaderWidths[0] := IniFile.ReadInteger('Application', 'MDIChildHeader0', 93); if (HeaderWidths[0] < 5) then HeaderWidths[0] := 5; HeaderWidths[1] := IniFile.ReadInteger('Application', 'MDIChildHeader1', 152); if (HeaderWidths[1] < 5) then HeaderWidths[1] := 5; HeaderWidths[2] := IniFile.ReadInteger('Application', 'MDIChildHeader2', 242); if (HeaderWidths[2] < 5) then HeaderWidths[2] := 5; g_PanelHeaderWidths := HeaderWidths; IniFile.Free; end; UsePersistentBlocks := CheckBoxPersistentBlocks.Checked; ScanAllDriveNames := not CheckBoxNotScanDriveNames.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonSaveClick(Sender: TObject); begin SaveToIni; UsePersistentBlocks := CheckBoxPersistentBlocks.Checked; ScanAllDriveNames := not CheckBoxNotScanDriveNames.Checked; ModalResult := mrOK; end; //----------------------------------------------------------------------------- procedure TFormSettings.SetOptions(GlobalOptions: TGlobalOptions); begin with GlobalOptions do begin RadioGroupSortCrit.ItemIndex := Integer(SortCrit); case FileDisplayType of fdBrief : RadioButtonBrief.Checked := true; fdDetailed: RadioButtonDetailed.Checked := true; end; CheckBoxShowSize.Checked := ShowSize; CheckBoxShowTime.Checked := ShowTime; CheckBoxShowDescr.Checked := ShowDescr; if ShowInKb then RadioGroupSizeDisplay.ItemIndex := 1 else RadioGroupSizeDisplay.ItemIndex := 0; CheckBoxShowSeconds.Checked := ShowSeconds; CheckBoxShowIcons.Checked := ShowIcons; CheckBoxOneKbIs1024.Checked := OneKbIs1024; CheckBoxShowFileHints.Checked := ShowFileHints; CheckBoxWinDateFormat.Checked := SystemDateFormat; CheckBoxShowTree.Checked := ShowTree and (PanelHeaderWidths[1] > 0); CheckBoxExpandTree.Checked := ExpandTree; {$ifndef LOGFONT} Self.DiskFont.Assign (DiskFont); Self.TreeFont.Assign (TreeFont); Self.FileFont.Assign (FileFont); Self.FoundFont.Assign(FoundFont); Self.DescFont.Assign (DescFont); Self.PrintFont.Assign(PrintFont); {$else} Self.DiskLogFont := DiskLogFont; Self.TreeLogFont := TreeLogFont; Self.FileLogFont := FileLogFont; Self.FoundLogFont := FoundLogFont; Self.DescLogFont := DescLogFont; Self.PrintLogFont := PrintLogFont; Self.DiskLogFontSize := DiskLogFontSize; Self.TreeLogFontSize := TreeLogFontSize; Self.FileLogFontSize := FileLogFontSize; Self.FoundLogFontSize := FoundLogFontSize; Self.DescLogFontSize := DescLogFontSize; Self.PrintLogFontSize := PrintLogFontSize; {$endif} CheckBoxAutoSave.Checked := AutoSave; CheckBoxFoundToNewWin.Checked := FoundToNewWin; SpinEditTop.Value := TopMargin; SpinEditBottom.Value := BottomMargin; SpinEditLeft.Value := LeftMargin; SpinEditRight.Value := RightMargin; EditPrintHeader.Text := PrintHeader; CheckBoxAdjustNameWidth.Checked := AdjustNameWidth; HeaderWidths := PanelHeaderWidths; g_PanelHeaderWidths := HeaderWidths; EditAutoLoadDBase.Text := AutoLoadDBase; CheckBoxOpenLastOpened.Checked := OpenLastOpened; CheckBoxBackupDBase.Checked := BackupDBase; CheckBoxPersistentBlocks.Checked := PersistentBlocks; CheckBoxNotScanDriveNames.Checked := NotScanDriveNames; CheckBoxEnableShellExecute.Checked := EnableShellExecute; CheckBoxDisableCdAutoRun.Checked := g_CommonOptions.bDisableCdAutorun; CheckBoxEjectAfterCdScan.Checked := g_CommonOptions.bEjectAfterCdScan; CheckBoxScanAfterCdInsert.Checked := g_CommonOptions.bScanAfterCdInsert; CheckBoxNoQueries.Checked := g_CommonOptions.bNoQueries; end; {with Options} UpdateFontLabels; end; //----------------------------------------------------------------------------- procedure TFormSettings.GetOptions(GlobalOptions: TGlobalOptions); begin with GlobalOptions do begin SortCrit := TSortCrit(RadioGroupSortCrit.ItemIndex); if RadioButtonBrief.Checked then FileDisplayType := fdBrief else FileDisplayType := fdDetailed; ShowSize := CheckBoxShowSize.Checked; ShowTime := CheckBoxShowTime.Checked; ShowDescr := CheckBoxShowDescr.Checked; ShowInKb := RadioGroupSizeDisplay.ItemIndex = 1; ShowSeconds := CheckBoxShowSeconds.Checked; ShowIcons := CheckBoxShowIcons.Checked; OneKbIs1024 := CheckBoxOneKbIs1024.Checked; ShowFileHints := CheckBoxShowFileHints.Checked; SystemDateFormat := CheckBoxWinDateFormat.Checked; ShowTree := CheckBoxShowTree.Checked and (HeaderWidths[1] > 0); ExpandTree := CheckBoxExpandTree.Checked; ReversedSort := false; {$ifndef LOGFONT} DiskFont.Assign (Self.DiskFont); TreeFont.Assign (Self.TreeFont); FileFont.Assign (Self.FileFont); FoundFont.Assign(Self.FoundFont); DescFont.Assign (Self.DescFont); PrintFont.Assign(Self.PrintFont); {$else} DiskLogFont := Self.DiskLogFont; TreeLogFont := Self.TreeLogFont; FileLogFont := Self.FileLogFont; FoundLogFont := Self.FoundLogFont; DescLogFont := Self.DescLogFont; PrintLogFont := Self.PrintLogFont; DiskLogFontSize := Self.DiskLogFontSize; TreeLogFontSize := Self.TreeLogFontSize; FileLogFontSize := Self.FileLogFontSize; FoundLogFontSize := Self.FoundLogFontSize; DescLogFontSize := Self.DescLogFontSize; PrintLogFontSize := Self.PrintLogFontSize; {$endif} AutoSave := CheckBoxAutoSave.Checked; FoundToNewWin := CheckBoxFoundToNewWin.Checked; TopMargin := SpinEditTop.Value; BottomMargin := SpinEditBottom.Value; LeftMargin := SpinEditLeft.Value; RightMargin := SpinEditRight.Value; PrintHeader := EditPrintHeader.Text; AdjustNameWidth := CheckBoxAdjustNameWidth.Checked; PanelHeaderWidths := HeaderWidths; g_PanelHeaderWidths := HeaderWidths; {exceptional - the following settings are really global} If SystemDateFormat then WinDateFormat := wd_WinShort {is in QB_Utils} else WinDateFormat := SaveWinDateFormat; If OneKbIs1024 then KbDivider := 1024 else KbDivider := 1000; {up to here} AutoLoadDBase := EditAutoLoadDBase.Text; OpenLastOpened := CheckBoxOpenLastOpened.Checked; BackupDBase := CheckBoxBackupDBase.Checked; PersistentBlocks := CheckBoxPersistentBlocks.Checked; NotScanDriveNames := CheckBoxNotScanDriveNames.Checked; EnableShellExecute := CheckBoxEnableShellExecute.Checked; EnableUTFConvert := CheckBoxEnableUTFConvert.Checked; end; end; //----------------------------------------------------------------------------- procedure TFormSettings.FormShow(Sender: TObject); begin ActiveControl := ButtonOK; {AlreadyWarned := false;} GetOptions(SaveOptions); CheckBoxNoQueries.Checked := g_CommonOptions.bNoQueries; // because it can be changed alsofrom FormSelectDrive end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxShowTreeClick(Sender: TObject); begin CheckBoxExpandTree.Enabled := CheckBoxShowTree.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonBrowseClick(Sender: TObject); begin if OpenDialogDBase.Execute then begin EditAutoLoadDBase.Text := OpenDialogDBase.FileName; end; end; //----------------------------------------------------------------------------- procedure TFormSettings.ButtonHelpClick(Sender: TObject); begin Application.HelpContext(290); end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxOpenLastOpenedClick(Sender: TObject); begin EditAutoLoadDBase.Enabled := not CheckBoxOpenLastOpened.Checked; ButtonBrowse.Enabled := not CheckBoxOpenLastOpened.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxDisableCdAutoRunClick(Sender: TObject); begin g_CommonOptions.bDisableCdAutorun := CheckBoxDisableCdAutoRun.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxEjectAfterCdScanClick(Sender: TObject); begin g_CommonOptions.bEjectAfterCdScan := CheckBoxEjectAfterCdScan.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxScanAfterCdInsertClick(Sender: TObject); begin g_CommonOptions.bScanAfterCdInsert := CheckBoxScanAfterCdInsert.Checked; end; //----------------------------------------------------------------------------- procedure TFormSettings.CheckBoxNoQueriesClick(Sender: TObject); begin g_CommonOptions.bNoQueries := CheckBoxNoQueries.Checked; end; //----------------------------------------------------------------------------- // Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay // to the top window, so we must have this handler in all forms. procedure TFormSettings.DefaultHandler(var Message); begin with TMessage(Message) do if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and g_CommonOptions.bDisableCdAutorun then Result := 1 else inherited DefaultHandler(Message) end; //----------------------------------------------------------------------------- var TempBuf: array [1..500] of char; begin g_CommonOptions.bDisableCdAutorun := true; g_CommonOptions.bEjectAfterCdScan := true; g_CommonOptions.bScanAfterCdInsert:= false; g_CommonOptions.bNoQueries := false; ///g_CommonOptions.dwQueryCancelAutoPlay := RegisterWindowMessage('QueryCancelAutoPlay'); g_UserCommandList := TList.Create(); ///GetTempPath(500, @TempBuf); g_sTempFolder := TempBuf; end.
unit UDMCadEnsaio; interface uses SysUtils, Classes, FMTBcd, DB, DBClient, Provider, SqlExpr, LogTypes; type TDMCadEnsaio = class(TDataModule) sdsEnsaio: TSQLDataSet; dspEnsaio: TDataSetProvider; cdsEnsaio: TClientDataSet; dsEnsaio: TDataSource; sdsEnsaioID: TIntegerField; sdsEnsaioNOME: TStringField; cdsEnsaioID: TIntegerField; cdsEnsaioNOME: TStringField; sdsEnsaioINATIVO: TStringField; cdsEnsaioINATIVO: TStringField; procedure DataModuleCreate(Sender: TObject); procedure dspEnsaioUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); procedure cdsEnsaioNewRecord(DataSet: TDataSet); private { Private declarations } procedure DoLogAdditionalValues(ATableName: string; var AValues: TArrayLogData; var UserName: string); public { Public declarations } vMsgErro: String; ctCommand: String; procedure prc_Localizar(ID: Integer); //-1 = Inclusão procedure prc_Inserir; procedure prc_Gravar; procedure prc_Excluir; end; var DMCadEnsaio: TDMCadEnsaio; implementation uses DmdDatabase, LogProvider, uUtilPadrao; {$R *.dfm} { TDMCadEnsaio } procedure TDMCadEnsaio.prc_Inserir; var vAux: Integer; begin if not cdsEnsaio.Active then prc_Localizar(-1); vAux := dmDatabase.ProximaSequencia('ENSAIO_OS',0); cdsEnsaio.Insert; cdsEnsaioID.AsInteger := vAux; end; procedure TDMCadEnsaio.prc_Excluir; begin if not(cdsEnsaio.Active) or (cdsEnsaio.IsEmpty) then exit; cdsEnsaio.Delete; cdsEnsaio.ApplyUpdates(0); end; procedure TDMCadEnsaio.prc_Gravar; begin vMsgErro := ''; if trim(cdsEnsaioNOME.AsString) = '' then vMsgErro := '*** Nome não informado!'; if vMsgErro <> '' then exit; cdsEnsaio.Post; cdsEnsaio.ApplyUpdates(0); end; procedure TDMCadEnsaio.prc_Localizar(ID: Integer); begin cdsEnsaio.Close; sdsEnsaio.CommandText := ctCommand; if ID <> 0 then sdsEnsaio.CommandText := sdsEnsaio.CommandText + ' WHERE ID = ' + IntToStr(ID); cdsEnsaio.Open; end; procedure TDMCadEnsaio.DataModuleCreate(Sender: TObject); var i, x: Integer; vIndices: string; aIndices: array of string; begin ctCommand := sdsEnsaio.CommandText; LogProviderList.OnAdditionalValues := DoLogAdditionalValues; for i := 0 to (Self.ComponentCount - 1) do begin if (Self.Components[i] is TClientDataSet) then begin SetLength(aIndices, 0); vIndices := TClientDataSet(Components[i]).IndexFieldNames; while (vIndices <> EmptyStr) do begin SetLength(aIndices, Length(aIndices) + 1); x := Pos(';', vIndices); if (x = 0) then begin aIndices[Length(aIndices) - 1] := vIndices; vIndices := EmptyStr; end else begin aIndices[Length(aIndices) - 1] := Copy(vIndices, 1, x - 1); vIndices := Copy(vIndices, x + 1, MaxInt); end; end; LogProviderList.AddProvider(TClientDataSet(Self.Components[i]), TClientDataSet(Self.Components[i]).Name, aIndices); end; end; end; procedure TDMCadEnsaio.dspEnsaioUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); begin dmDatabase.prc_UpdateError(DataSet.Name,UpdateKind,E); end; procedure TDMCadEnsaio.DoLogAdditionalValues(ATableName: string; var AValues: TArrayLogData; var UserName: string); begin UserName := vUsuario; end; procedure TDMCadEnsaio.cdsEnsaioNewRecord(DataSet: TDataSet); begin cdsEnsaioINATIVO.AsString := 'N'; end; end.
unit gr_Current_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, GlobalSpr, IBase, PackageLoad, Dates, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, ActnList, ExtCtrls, cxLabel, Unit_NumericConsts, gr_uMessage, gr_uCommonConsts, gr_uCommonProc, gr_uCommonLoader, Gr_AccDepart; type TgrCurrentFilter = record Is_Smeta:boolean; Is_Department:boolean; Is_Man:boolean; Is_VidOpl:boolean; Is_KodSetup:boolean; Is_OperationsFilter:boolean; Is_Prikaz:boolean; Id_smeta:integer; Kod_Smeta:integer; Name_Smeta:String; Id_department:integer; Kod_department:string[10]; Name_Department:String; Id_man:integer; Tn:integer; FIO:string; Id_VidOpl:integer; Kod_VidOpl:integer; Name_VidOpl:string; Kod_Setup1:integer; Kod_Setup2:integer; Prikaz:string[50]; ModalResult:TModalResult; end; type TfzCurrentFilter = class(TForm) BoxSmeta: TcxGroupBox; EditSmeta: TcxButtonEdit; YesBtn: TcxButton; CancelBtn: TcxButton; BoxKodSetup: TcxGroupBox; MonthesList1: TcxComboBox; YearSpinEdit1: TcxSpinEdit; CheckBoxKodSetup: TcxCheckBox; CheckBoxDepartment: TcxCheckBox; BoxDepartment: TcxGroupBox; EditDepartment: TcxButtonEdit; CheckBoxSmeta: TcxCheckBox; CheckBoxIdMan: TcxCheckBox; BoxIdMan: TcxGroupBox; EditMan: TcxButtonEdit; CheckBoxVidOpl: TcxCheckBox; BoxVidOpl: TcxGroupBox; EditVidOpl: TcxButtonEdit; LabelManData: TcxLabel; LabelVidOplData: TcxLabel; LabelDepartmentData: TcxLabel; LabelSmetaData: TcxLabel; ActionList: TActionList; Action1: TAction; MonthesList2: TcxComboBox; YearSpinEdit2: TcxSpinEdit; cxLabel1: TcxLabel; CheckBoxOperationsFilter: TcxCheckBox; Bevel: TBevel; CheckBoxPrikaz: TcxCheckBox; BoxPrikaz: TcxGroupBox; EditPrikaz: TcxMaskEdit; procedure CheckBoxKodSetupClick(Sender: TObject); procedure CheckBoxDepartmentClick(Sender: TObject); procedure CheckBoxSmetaClick(Sender: TObject); procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure CancelBtnClick(Sender: TObject); procedure k(Sender: TObject); procedure EditManPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure CheckBoxVidOplClick(Sender: TObject); procedure EditVidOplExit(Sender: TObject); procedure EditVidOplPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditDepartmentExit(Sender: TObject); procedure EditSmetaExit(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure CheckBoxOperationsFilterClick(Sender: TObject); procedure EditPrikazKeyPress(Sender: TObject; var Key: Char); procedure CheckBoxPrikazClick(Sender: TObject); procedure EditManPropertiesEditValueChanged(Sender: TObject); procedure ActionEnterExecute(Sender: TObject); private PParameter:TgrCurrentFilter; PDb_Handle:TISC_DB_HANDLE; PLanguageIndex:byte; public constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TgrCurrentFilter);reintroduce; property Parameter:TgrCurrentFilter read PParameter; end; function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TgrCurrentFilter):TgrCurrentFilter;stdcall; implementation {$R *.dfm} function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TgrCurrentFilter):TgrCurrentFilter;stdcall; var Filter:TfzCurrentFilter; Res:TgrCurrentFilter; begin Filter := TfzCurrentFilter.Create(AOwner,ADB_Handle,AParameter); if Filter.ShowModal=mrYes then Res:=Filter.Parameter else Res:=AParameter; Res.ModalResult:=Filter.ModalResult; Filter.Free; ViewFilter:=Res; end; constructor TfzCurrentFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TgrCurrentFilter); begin inherited Create(AOwner); PParameter:=AParameter; PDb_Handle:=ADB_Handle; PLanguageIndex:=IndexLanguage; //****************************************************************************** Caption := FilterBtn_Caption[PLanguageIndex]; CheckBoxKodSetup.Properties.Caption := LabelPeriod_Caption[PLanguageIndex]; CheckBoxDepartment.Properties.Caption := LabelDepartment_Caption[PLanguageIndex]; CheckBoxVidOpl.Properties.Caption := LabelVidOpl_Caption[PLanguageIndex]; CheckBoxSmeta.Properties.Caption := LabelSmeta_Caption[PLanguageIndex]; CheckBoxIdMan.Properties.Caption := LabelStudent_Caption[PLanguageIndex]; CheckBoxPrikaz.Properties.Caption := LabelPrikaz_Caption[PLanguageIndex]; CheckBoxOperationsFilter.Properties.Caption := LabelOperationsFilter_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; MonthesList1.Properties.Items.Text := MonthesList_Text[PLanguageIndex]; MonthesList2.Properties.Items.Text := MonthesList_Text[PLanguageIndex]; //****************************************************************************** CheckBoxKodSetup.Checked := PParameter.Is_KodSetup; CheckBoxDepartment.Checked := PParameter.Is_Department; CheckBoxSmeta.Checked := PParameter.Is_Smeta; CheckBoxIdMan.Checked := PParameter.Is_Man; CheckBoxVidOpl.Checked := PParameter.Is_VidOpl; CheckBoxOperationsFilter.Checked := PParameter.Is_OperationsFilter; CheckBoxPrikaz.Checked := PParameter.Is_Prikaz; BoxPrikaz.Enabled := CheckBoxPrikaz.Checked; BoxKodSetup.Enabled := CheckBoxKodSetup.Checked; BoxSmeta.Enabled := CheckBoxSmeta.Checked; BoxDepartment.Enabled := CheckBoxDepartment.Checked; BoxIdMan.Enabled := CheckBoxIdMan.Checked; BoxVidOpl.Enabled := CheckBoxVidOpl.Checked; LabelManData.Caption := PParameter.FIO; LabelVidOplData.Caption := PParameter.Name_VidOpl; LabelDepartmentData.Caption := PParameter.Name_Department; LabelSmetaData.Caption := PParameter.Name_Smeta; EditSmeta.Text := grIfThen(PParameter.Kod_Smeta=0,'',IntToStr(PParameter.Kod_Smeta)); EditDepartment.Text := PParameter.Kod_department; EditMan.Text := grIfThen(PParameter.Tn=0,'',IntToStr(PParameter.Tn)); EditVidOpl.Text := grIfThen(PParameter.Kod_VidOpl=0,'',IntToStr(PParameter.Kod_VidOpl)); //****************************************************************************** if PParameter.Kod_Setup1=0 then PParameter.Kod_Setup1:=grKodSetup(PDb_Handle); YearSpinEdit1.Value := YearMonthFromKodSetup(PParameter.Kod_Setup1); MonthesList1.ItemIndex := YearMonthFromKodSetup(PParameter.Kod_Setup1,False)-1; if PParameter.Kod_Setup2=0 then PParameter.Kod_Setup2:=grKodSetup(PDb_Handle); YearSpinEdit2.Value := YearMonthFromKodSetup(PParameter.Kod_Setup2); MonthesList2.ItemIndex := YearMonthFromKodSetup(PParameter.Kod_Setup2,False)-1; end; procedure TfzCurrentFilter.CheckBoxKodSetupClick(Sender: TObject); begin BoxKodSetup.Enabled := not BoxKodSetup.Enabled; end; procedure TfzCurrentFilter.CheckBoxDepartmentClick(Sender: TObject); begin BoxDepartment.Enabled := not BoxDepartment.Enabled; end; procedure TfzCurrentFilter.CheckBoxSmetaClick(Sender: TObject); begin BoxSmeta.Enabled := not BoxSmeta.Enabled; end; procedure TfzCurrentFilter.cxButtonEdit1PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var Department:Variant; ViewForm:TfGrAccDepart; begin ViewForm:=TfGrAccDepart.Create(self,PDB_Handle); ViewForm.NKodSetup:=PeriodToKodSetup(YearSpinEdit1.EditValue,MonthesList1.ItemIndex+1); if ViewForm.ShowModal=mrYes then Department:=ViewForm.Result; if VarArrayDimCount(Department)> 0 then if Department[0]<>NULL then begin PParameter.Id_department := Department[0]; PParameter.Name_Department := VarToStr(Department[2]); PParameter.Kod_department := VarToStr(Department[1]); LabelDepartmentData.Caption := PParameter.Name_Department; EditDepartment.Text := PParameter.Kod_department; end; end; procedure TfzCurrentFilter.EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Smeta:Variant; begin Smeta:=GetSmets(self,PDB_Handle,Date,psmSmet); if VarArrayDimCount(Smeta)> 0 then If Smeta[0]<>NULL then begin PParameter.Id_smeta := Smeta[0]; PParameter.Name_Smeta := Smeta[2]; PParameter.Kod_Smeta := Smeta[3]; EditSmeta.Text := IntToStr(PParameter.Kod_Smeta); LabelSmetaData.Caption := PParameter.Name_Smeta; end; end; procedure TfzCurrentFilter.CancelBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TfzCurrentFilter.k(Sender: TObject); begin BoxIdMan.Enabled := not BoxIdMan.Enabled; end; procedure TfzCurrentFilter.EditManPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var man:Variant; AParameter: TgrSimpleParam; begin AParameter:=TgrSimpleParam.Create; AParameter.Owner:=Self; AParameter.DB_Handle:=PDb_Handle; man:=DoFunctionFromPackage(AParameter,Stud_StudentCards); if VarArrayDimCount(man)> 0 then if man[0]<>NULL then begin PParameter.Id_man:=man[0]; PParameter.Tn:=grifThen(VarIsNull(Man[1]),0,Man[1]); PParameter.FIO:=man[2]; LabelManData.Caption := PParameter.FIO; EditMan.Text := IntToStr(PParameter.Tn); end; end; procedure TfzCurrentFilter.CheckBoxVidOplClick(Sender: TObject); begin BoxVidOpl.Enabled := CheckBoxVidOpl.Checked; end; procedure TfzCurrentFilter.EditVidOplExit(Sender: TObject); var VidOpl:Variant; begin if EditVidOpl.Text<>'' then begin if StrToInt(EditVidOpl.Text)=PParameter.Kod_VidOpl then Exit; VidOpl:=grVoByKod(StrToInt(EditVidOpl.Text),date,PDb_Handle); if VarArrayDimCount(VidOpl)>0 then begin PParameter.Id_VidOpl:=VidOpl[0]; PParameter.Kod_VidOpl:=VidOPl[1]; PParameter.Name_VidOpl:=VidOpl[2]; LabelVidOplData.Caption := PParameter.Name_VidOpl; end else EditVidOpl.SetFocus; end; end; procedure TfzCurrentFilter.EditVidOplPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var VidOpl:Variant; begin VidOPl:=ShowSpVidOpl(self,PDb_Handle); if VarArrayDimCount(VidOpl)>0 then begin PParameter.Id_VidOpl:=VidOpl[0]; PParameter.Kod_VidOpl:=VidOPl[2]; PParameter.Name_VidOpl:=VidOpl[1]; LabelVidOplData.Caption := PParameter.Name_VidOpl; EditVidOpl.Text := IntToStr(PParameter.Kod_VidOpl); end else EditVidOpl.SetFocus; end; procedure TfzCurrentFilter.EditDepartmentExit(Sender: TObject); var Department:Variant; begin if EditDepartment.Text<>'' then begin if EditDepartment.Text=PParameter.Kod_department then Exit; Department:=grDepartmentByKod(EditDepartment.Text,PDb_Handle); if VarArrayDimCount(Department)>0 then begin PParameter.Id_department:=Department[0]; PParameter.Kod_department:=Department[1]; PParameter.Name_Department:=Department[2]; LabelDepartmentData.Caption := PParameter.Name_Department; end else EditDepartment.SetFocus; end; end; procedure TfzCurrentFilter.EditSmetaExit(Sender: TObject); var Smeta:Variant; begin if EditSmeta.Text<>'' then begin if StrToInt(EditSmeta.Text)=PParameter.Kod_Smeta then Exit; Smeta:=grSmetaByKod(StrToInt(EditSmeta.Text),PDb_Handle); if VarArrayDimCount(Smeta)>0 then begin PParameter.Id_smeta:=Smeta[0]; PParameter.Kod_Smeta:=Smeta[1]; PParameter.Name_Smeta:=Smeta[2]; LabelSmetaData.Caption := PParameter.Name_Smeta; end else EditSmeta.SetFocus; end; end; procedure TfzCurrentFilter.Action1Execute(Sender: TObject); begin if PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1)> PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1) then begin MonthesList1.SetFocus; Exit; end; YesBtn.SetFocus; PParameter.Prikaz := EditPrikaz.Text; if PParameter.Id_smeta=0 then CheckBoxSmeta.Checked:=False; if PParameter.Id_department=0 then CheckBoxDepartment.Checked:=False; if PParameter.Id_man=0 then CheckBoxIdMan.Checked:=False; if PParameter.Id_VidOpl=0 then CheckBoxVidOpl.Checked:=False; if PParameter.Prikaz='' then CheckBoxPrikaz.Enabled:=False; PParameter.Is_Department := CheckBoxDepartment.Checked; PParameter.Is_Smeta := CheckBoxSmeta.Checked; PParameter.Is_Man := CheckBoxIdMan.Checked; PParameter.Is_VidOpl := CheckBoxVidOpl.Checked; PParameter.Is_KodSetup := CheckBoxKodSetup.Checked; PParameter.Is_OperationsFilter := CheckBoxOperationsFilter.Checked; PParameter.Is_Prikaz:= CheckBoxPrikaz.Checked; PParameter.Kod_Setup1:=PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1); PParameter.Kod_Setup2:=PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1); if (not PParameter.Is_Smeta) and (not PParameter.Is_Department) and (not PParameter.Is_VidOpl) and (not PParameter.Is_KodSetup) and (not PParameter.Is_Man) then grShowMessage(ECaption[PLanguageIndex],EnotInputData_Text[PLanguageIndex],mtWarning,[mbOK]) else ModalResult:=mrYes; end; procedure TfzCurrentFilter.CheckBoxOperationsFilterClick(Sender: TObject); begin PParameter.Is_OperationsFilter := CheckBoxOperationsFilter.Checked; end; procedure TfzCurrentFilter.EditPrikazKeyPress(Sender: TObject; var Key: Char); begin if (Length(EditPrikaz.Text)=50) and (key<>#7) and (Key<>#8) then Key:=#0; end; procedure TfzCurrentFilter.CheckBoxPrikazClick(Sender: TObject); begin BoxPrikaz.Enabled := not BoxPrikaz.Enabled; end; procedure TfzCurrentFilter.EditManPropertiesEditValueChanged( Sender: TObject); var man:Variant; begin if EditMan.Text<>'' then begin if StrToInt(EditMan.Text)=PParameter.Tn then Exit; man:=grManByShifr(StrToInt(EditMan.Text),PDb_Handle); if VarArrayDimCount(man)>0 then begin PParameter.Id_man:=man[0]; PParameter.Tn:=man[1]; PParameter.FIO:=man[2]; LabelManData.Caption := PParameter.FIO; end else EditMan.SetFocus; end; end; procedure TfzCurrentFilter.ActionEnterExecute(Sender: TObject); begin if CancelBtn.Focused then ModalResult :=mrCancel; if YesBtn.Focused then Action1.Execute; if CheckBoxOperationsFilter.Focused then YesBtn.SetFocus; if EditPrikaz.Focused then CheckBoxOperationsFilter.SetFocus; if (CheckBoxPrikaz.Checked) and (CheckBoxPrikaz.Focused) then EditPrikaz.SetFocus else if CheckBoxPrikaz.Focused then CheckBoxOperationsFilter.SetFocus; if (EditSmeta.Focused) and (CheckBoxPrikaz.Checked) then EditPrikaz.SetFocus else if EditSmeta.Focused then CheckBoxPrikaz.SetFocus; if (CheckBoxSmeta.Focused) and (CheckBoxSmeta.Checked) then EditSmeta.SetFocus else if CheckBoxSmeta.Focused then CheckBoxPrikaz.SetFocus; if (EditDepartment.Focused) and (CheckBoxSmeta.Checked) then EditSmeta.SetFocus else if EditDepartment.Focused then CheckBoxSmeta.SetFocus; if CheckBoxDepartment.Focused and CheckBoxDepartment.Checked then EditDepartment.SetFocus else if CheckBoxDepartment.Focused then CheckBoxSmeta.SetFocus; if EditVidOpl.Focused and CheckBoxDepartment.Checked then EditDepartment.SetFocus else if EditVidOpl.Focused then CheckBoxDepartment.SetFocus; if CheckBoxVidOpl.Focused and CheckBoxVidOpl.Checked then EditVidOpl.SetFocus else if CheckBoxVidOpl.Focused then CheckBoxDepartment.SetFocus; if EditMan.Focused and CheckBoxVidOpl.Checked then EditVidOpl.SetFocus else if EditMan.Focused then CheckBoxVidOpl.SetFocus; if CheckBoxIdMan.Focused and CheckBoxIdMan.Checked then EditMan.SetFocus else if CheckBoxIdMan.Focused then CheckBoxVidOpl.SetFocus; if (YearSpinEdit2.Focused) and (CheckBoxIdMan.Checked) then EditMan.SetFocus else if YearSpinEdit2.Focused then CheckBoxIdMan.SetFocus; if MonthesList2.Focused then YearSpinEdit2.SetFocus; if YearSpinEdit1.Focused then MonthesList2.SetFocus; if MonthesList1.Focused then YearSpinEdit1.SetFocus; end; end.
;; -*- lisp-version: "9.0 [Windows] (Sep 7, 2012 15:37)"; cg: "9.0"; -*- (in-package :cg-user) (define-project :name :|AlgoMergulhadores| :modules (list (make-instance 'module :name "EspacoBusca2D0011.lisp") (make-instance 'module :name "main.lisp")) :projects nil :libraries nil :editable-files nil :distributed-files nil :internally-loaded-files nil :project-package-name :common-graphics-user :main-form nil :compilation-unit t :concatenate-project-fasls t :verbose nil :runtime-modules (list :cg.yes-no-string :cg.yes-no-list :cg.wrap-string :cg.web-browser :cg.utility-dialog :cg.up-down-control :cg.tray :cg.trackbar :cg.tooltip :cg.toolbar :cg.toggling-widget :cg.timer :cg.text-widget :cg.text-or-combo :cg.text-edit-pane.mark :cg.text-edit-pane.file-io :cg.text-edit-pane :cg.template-string :cg.tab-control :cg.string-dialog :cg.status-bar :cg.static-text :cg.split-bar :cg.shortcut-menu :cg.selected-object :cg.scrolling-static-text :cg.scroll-bar-mixin :cg.scroll-bar :cg.scaling-stream :cg.sample-file-menu :cg.rich-edit-pane.printing :cg.rich-edit-pane.clipboard :cg.rich-edit-pane :cg.rich-edit :cg.radio-button :cg.property :cg.project-window :cg.progress-indicator :cg.printing :cg.plot-widget :cg.pixmap.rotate :cg.pixmap.printing :cg.pixmap.file-io :cg.pixmap-widget :cg.pixmap :cg.picture-widget.palette :cg.picture-widget :cg.paren-matching :cg.palette :cg.outline.edit-in-place :cg.outline.drag-and-drop :cg.outline :cg.os-window :cg.os-widget :cg.nodes :cg.multi-picture-button.tooltip :cg.multi-picture-button.drag-and-drop :cg.multi-picture-button :cg.multi-line-lisp-text :cg.multi-line-editable-text :cg.message-dialog :cg.menu.tooltip :cg.menu :cg.list-view :cg.lisp-widget :cg.lisp-text :cg.lisp-edit-pane :cg.lettered-menu :cg.layout :cg.lamp :cg.keyboard-shortcuts :cg.item-list :cg.intersect.posbox :cg.intersect :cg.icon-pixmap :cg.icon :cg.html-widget :cg.html-dialog :cg.hotspot :cg.header-control :cg.group-box :cg.grid-widget.drag-and-drop :cg.grid-widget :cg.graphics-context :cg.get-position :cg.get-pixmap :cg.gesture-emulation :cg.font-dialog :cg.find-string-dialog :cg.fill-texture :cg.file-dialog :cg.editable-text :cg.edit-in-place :cg.dropping-outline :cg.drawable.clipboard :cg.drawable :cg.drag-and-drop-image :cg.drag-and-drop :cg.directory-dialog-os :cg.directory-dialog :cg.dialog-item :cg.curve :cg.cursor-pixmap :cg.comtab :cg.common-control :cg.combo-box :cg.color-dialog :cg.clipboard.pixmap :cg.clipboard-stack :cg.clipboard :cg.class-support :cg.class-slot-grid :cg.choose-printer :cg.choice-list :cg.check-box :cg.chart-widget :cg.chart-or-plot :cg.caret :cg.button :cg.bitmap-stream :cg.bitmap-pane.clipboard :cg.bitmap-pane :cg.base :cg-dde-utils) :splash-file-module (make-instance 'build-module :name "") :icon-file-module (make-instance 'build-module :name "") :include-flags (list :top-level :debugger) :build-flags (list :allow-runtime-debug :runtime-bundle) :autoload-warning nil :full-recompile-for-runtime-conditionalizations nil :include-manifest-file-for-visual-styles t :default-command-line-arguments "+M +t \"Console for Debugging\"" :additional-build-lisp-image-arguments (list :read-init-files nil) :old-space-size 256000 :new-space-size 6144 :runtime-build-option :standard :build-number 0 :run-with-console nil :project-file-version-info (list :product-version "0001" :product-name "Algoritmo dos Mergulhadores" :file-version "2D0010" :file-description "implementação de algorimos de busca" :company-name "UPE" :comments "desenvolvimento dos operadores") :on-initialization 'default-init-function :default-error-handler-for-delivery 'report-unexpected-error-and-exit :on-restart 'do-default-restart) ;; End of Project Definition
unit Core.PinPadOLE; { Краткое описание функций Функция SРaram Функция SParam (Name, Value) предназначена для задания входных параметров. Name - имя входного параметра. Value - значение входного параметра. Возвращает S_OK при удачной реализации. Функция GРaramString Функция GParamString(Name, Value) предназначена для получения выходных параметров. Name - имя выходных параметра. Value - значение выходного параметра. Можно вызывать 2 способами: 1. GParamString(Name, Value) 2. Value =GParamString(Name) Возвращает значение параметра с именем Name. Функция NFun Функция NFun(func) предназначена для запуска определенной функции в библиотеке (после того как необходимые входные параметры будут заданы). Параметр func задает номер вызываемой функции. Подробное описание номеров функций библиотеки приводится в Приложении. Возвращает код ошибки. 0 – успешное выполнение, любое другое – ошибка. Функция Clear Функция Clear() предназначена очистки списка параметров. Возвращает S_OK при удачной реализации. } interface uses ActiveX, Windows, SysUtils, ComObj, Classes, Variants; const OleName: string = 'SBRFSRV.Server'; type TSberFunc = (fnSuspendTran = 6003, fnCommitTran = 6001, fnRollbackTran = 6004, fnPayInfo = 7005, fnCardAuth = 4000, fnReturn = 4002, fnAnnulate = 4003, fnTestPinPad = 13, fnSberCloseDay = 6000, fnSberXReport = 6002, fnSberShiftAll = 7000, fnReadTrack2 = 5002, fnServiceMenu = 10); TPinPadOLE = class strict private FPinPad: Variant; FAuthCode: string; FCheque: string; FPayInfo: string; FAmount: UINT; function SParam(name, Value: string): integer; procedure Clear; function GParamString(name: string): string; function NFun(func: TSberFunc): integer; public constructor Create; destructor Destroy; function CardAuth7(Amount: Double; Operation: TSberFunc): integer; function CommitTrx: integer; function RollbackTrx: integer; function SuspendTrx: integer; function TestPinPad: boolean; procedure PinpadClear; function SberShift: integer; function CloseDay: integer; function Return(Amount: Double): integer; function ReadTrack2: string; function ServiceMenu: integer; published property PayInfo: string read FPayInfo write FPayInfo; property Cheque: string read FCheque; property AuthCode: string read FAuthCode; end; implementation { TPinPadOLE } function TPinPadOLE.CardAuth7(Amount: Double; Operation: TSberFunc): integer; var Sum: UINT; begin Sum := Round(Amount * 100); Clear; FAmount := Sum; SParam('Amount', Inttostr(Sum)); Result := NFun(fnCardAuth); if (FPayInfo <> '') and (Result = 0) then begin SParam('PayInfo', FPayInfo); Result := NFun(fnPayInfo); end; FCheque := GParamString('Cheque'); FAuthCode := GParamString('AuthCode'); end; procedure TPinPadOLE.PinpadClear; begin FPinPad.Clear; end; procedure TPinPadOLE.Clear; begin FAmount := 0; FAuthCode := ''; FCheque := ''; FPayInfo := ''; FPinPad.Clear; end; function TPinPadOLE.CloseDay: integer; begin Clear; Result := NFun(fnSberCloseDay); FCheque := GParamString('Cheque'); end; function TPinPadOLE.CommitTrx: integer; begin SParam('Amount', Inttostr(FAmount)); SParam('AuthCode', FAuthCode); Result := NFun(fnCommitTran); end; constructor TPinPadOLE.Create; begin CoInitializeEx(nil, COINIT_MULTITHREADED); inherited Create; if VarIsEmpty(FPinPad) then try FPinPad := CreateOLEObject(OleName); except on E: exception do; end; end; destructor TPinPadOLE.Destroy; begin if not VarIsEmpty(FPinPad) then FPinPad := 0; inherited Destroy; CoUninitialize; end; function TPinPadOLE.GParamString(name: string): string; begin Result := FPinPad.GParamString(name); end; function TPinPadOLE.NFun(func: TSberFunc): integer; begin Result := FPinPad.NFun(integer(func)); end; function TPinPadOLE.ReadTrack2: string; begin if NFun(fnReadTrack2) = 0 then Result := GParamString('Track2') // GParamString('ClientCard') else Result := ''; end; function TPinPadOLE.Return(Amount: Double): integer; var Sum: UINT; begin Sum := Round(Amount * 100); Clear; SParam('Amount', Inttostr(Sum)); SParam('AuthCode', FAuthCode); Result := NFun(fnAnnulate); if (FPayInfo <> '') and (Result = 0) then begin SParam('PayInfo', FPayInfo); Result := NFun(fnPayInfo); end; FCheque := GParamString('Cheque'); end; function TPinPadOLE.RollbackTrx: integer; begin SParam('Amount', Inttostr(FAmount)); SParam('AuthCode', FAuthCode); Result := NFun(fnRollbackTran); end; // Контрольная лента смены function TPinPadOLE.SberShift: integer; begin Clear; Result := NFun(fnSberShiftAll); FCheque := GParamString('Cheque'); end; function TPinPadOLE.ServiceMenu: integer; begin Result := NFun(fnServiceMenu); end; function TPinPadOLE.SParam(name, Value: string): integer; begin Result := FPinPad.SParam(name, Value); end; function TPinPadOLE.SuspendTrx: integer; begin SParam('Amount', Inttostr(FAmount)); SParam('AuthCode', FAuthCode); Result := NFun(fnSuspendTran); end; function TPinPadOLE.TestPinPad: boolean; begin Result := NFun(fnTestPinPad) = 0; end; end.
unit CurrentDateDisplay; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TformCurrentDateDisplay = class(TForm) lblCurrentDate: TLabel; lblCurrentTime: TLabel; timerUpdateDate: TTimer; procedure FormShow(Sender: TObject); procedure timerUpdateDateTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; var formCurrentDateDisplay: TformCurrentDateDisplay; implementation {$R *.dfm} procedure TformCurrentDateDisplay.FormShow(Sender: TObject); begin timerUpdateDate.Enabled := true; end; procedure TformCurrentDateDisplay.timerUpdateDateTimer(Sender: TObject); var today : TDateTime; begin today := Now; lblCurrentDate.Caption := DateToStr(today); lblCurrentTime.Caption := TimeToStr(today); end; end.
unit libsqlite; {$IFDEF FPC} {$MODE Delphi} {$H+} {$ELSE} {$IFNDEF LINUX} {$DEFINE WIN32} {$ELSE} {$DEFINE UNIX} {$ENDIF} {$IF CompilerVersion >= 12} // Unicode strings {$DEFINE WIDESTRING_DEFAULT} {$ENDIF} {$ENDIF} //libsql.dll api interface //initial code by Ben Hochstrasser //updated and put in seperate unit by Rene Tegel (* Thanks to Ben Hochstrasser for doing the api interface stuff. *) { simple class interface for SQLite. Hacked in by Ben Hochstrasser (bhoc@surfeu.ch) Thanks to Roger Reghin (RReghin@scelectric.ca) for his idea to ValueList. } // for documentation on these constants and functions, please look at // http://www.sqlite.org/c_interface.html interface uses {$IFNDEF FPC}{$IFDEF WIN32}Windows{$ELSE}SysUtils{$ENDIF}{$ELSE}Dynlibs{$ENDIF}; const SQLITE_OK = 0; // Successful result SQLITE_ERROR = 1; // SQL error or missing database SQLITE_INTERNAL = 2; // An internal logic error in SQLite SQLITE_PERM = 3; // Access permission denied SQLITE_ABORT = 4; // Callback routine requested an abort SQLITE_BUSY = 5; // The database file is locked SQLITE_LOCKED = 6; // A table in the database is locked SQLITE_NOMEM = 7; // A malloc() failed SQLITE_READONLY = 8; // Attempt to write a readonly database SQLITE_INTERRUPT = 9; // Operation terminated by sqlite_interrupt() SQLITE_IOERR = 10; // Some kind of disk I/O error occurred SQLITE_CORRUPT = 11; // The database disk image is malformed SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found SQLITE_FULL = 13; // Insertion failed because database is full SQLITE_CANTOPEN = 14; // Unable to open the database file SQLITE_PROTOCOL = 15; // Database lock protocol error SQLITE_EMPTY = 16; // (Internal Only) Database table is empty SQLITE_SCHEMA = 17; // The database schema changed SQLITE_TOOBIG = 18; // Too much data for one row of a table SQLITE_CONSTRAINT = 19; // Abort due to contraint violation SQLITE_MISMATCH = 20; // Data type mismatch //some new types (not supported in real old versions of sqlite) SQLITE_MISUSE = 21; //* Library used incorrectly */ SQLITE_NOLFS = 22; //* Uses OS features not supported on host */ SQLITE_AUTH = 23; //* Authorization denied */ SQLITE_ROW = 100; //* sqlite_step() has another row ready */ SQLITE_DONE = 101; //* sqlite_step() has finished executing */ SQLITEDLL: PAnsiChar = {$IFDEF LINUX}'libsqlite.so'{$ENDIF}{$IFDEF WIN32}'sqlite.dll'{$ENDIF}{$IFDEF darwin}'libsqlite.dylib'{$ENDIF}; function LoadLibSqlite2 (var LibraryPath: String): Boolean; type PSQLite = Pointer; TSqlite_Func = record P:Pointer; end; PSQLite_Func = ^TSQLite_Func; //untested: procProgressCallback = procedure (UserData:Integer); cdecl; //untested: Tsqlite_create_function= function (db: Pointer; {const}zName:PAnsiChar; nArg: Integer; xFunc : PSqlite_func{*,int,const char**}; UserData: Integer):Integer; cdecl; var SQLite_Open: function(dbname: PAnsiChar; mode: Integer; var ErrMsg: PAnsiChar): Pointer; cdecl; SQLite_Close: procedure(db: Pointer); cdecl; SQLite_Exec: function(db: Pointer; SQLStatement: PAnsiChar; CallbackPtr: Pointer; Sender: TObject; var ErrMsg: PAnsiChar): integer; cdecl; SQLite_Version: function(): PAnsiChar; cdecl; SQLite_Encoding: function(): PAnsiChar; cdecl; SQLite_ErrorString: function(ErrNo: Integer): PAnsiChar; cdecl; SQLite_GetTable: function(db: Pointer; SQLStatement: PAnsiChar; var ResultPtr: Pointer; var RowCount: Cardinal; var ColCount: Cardinal; var ErrMsg: PAnsiChar): integer; cdecl; SQLite_FreeTable: procedure(Table: PAnsiChar); cdecl; SQLite_FreeMem: procedure(P: PAnsiChar); cdecl; SQLite_Complete: function(P: PAnsiChar): boolean; cdecl; SQLite_LastInsertRow: function(db: Pointer): integer; cdecl; SQLite_Cancel: procedure(db: Pointer); cdecl; SQLite_BusyHandler: procedure(db: Pointer; CallbackPtr: Pointer; Sender: TObject); cdecl; SQLite_BusyTimeout: procedure(db: Pointer; TimeOut: integer); cdecl; SQLite_Changes: function(db: Pointer): integer; cdecl; //untested: sqlite_progress_handler: procedure (db: Pointer; VMCyclesPerCallback: Integer; ProgressCallBack: Pointer; UserData: Integer{? Pointer?}); cdecl; { int sqlite_compile( sqlite *db, /* The open database */ const char *zSql, /* SQL statement to be compiled */ const char **pzTail, /* OUT: uncompiled tail of zSql */ sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */ char **pzErrmsg /* OUT: Error message. */ ); int sqlite_step( sqlite_vm *pVm, /* The virtual machine to execute */ int *pN, /* OUT: Number of columns in result */ const char ***pazValue, /* OUT: Column data */ const char ***pazColName /* OUT: Column names and datatypes */ ); int sqlite_finalize( sqlite_vm *pVm, /* The virtual machine to be finalized */ char **pzErrMsg /* OUT: Error message */ ); } sqlite_compile: function( db: Pointer; //* The open database */ Sql: PAnsiChar; //* SQL statement to be compiled */ var Tail: PAnsiChar; //* OUT: uncompiled tail of zSql */ var Vm: Pointer; //* OUT: the virtual machine to execute zSql */ var Errmsg: PAnsiChar //* OUT: Error message. */ ): Integer; cdecl; sqlite_step: function( Vm: Pointer; //* The virtual machine to execute */ var N: Integer; //* OUT: Number of columns in result */ var pazValue: Pointer; //* OUT: Column data */ var pazColName: Pointer //* OUT: Column names and datatypes */ ): Integer; cdecl; sqlite_finalize: function( Vm: Pointer; //* The virtual machine to be finalized */ var ErrMsg: PAnsiChar //* OUT: Error message */ ): Integer; cdecl; Libs2Loaded: Boolean = False; DLLHandle: {$IFDEF FPC}TLibHandle{$ELSE}THandle{$ENDIF}; MsgNoError: String; implementation function LoadLibSqlite2 (var LibraryPath: String): Boolean; var libname: String; begin Result := Libs2Loaded; if Result then //alread loaded exit; if libraryPath = '' then libname := SQLITEDLL else libname := libraryPath; {$IFNDEF FPC} //DLLHandle := GetModuleHandle(LibraryPath); {$ENDIF} {$IFDEF FPC} DLLHandle := LoadLibrary(libname); {$ELSE} {$IFNDEF WIDESTRING_DEFAULT} DLLHandle := LoadLibrary(PAnsiChar(libname)); {$ELSE} DLLHandle := LoadLibrary(PWideChar(libname)); {$ENDIF} {$ENDIF} {$IFNDEF WIN32} // try other possible library name if DLLHandle = 0 then begin libname := libname + '.0'; {$IFDEF FPC} DLLHandle := LoadLibrary(libname); {$ELSE} {$IFNDEF WIDESTRING_DEFAULT} DLLHandle := LoadLibrary(PAnsiChar(libname)); {$ELSE} DLLHandle := LoadLibrary(PWideChar(libname)); {$ENDIF} {$ENDIF} end; {$ENDIF} if DLLHandle <> 0 then begin Result := True; //assume everything ok unless.. LibraryPath := LibName; // FPC GetProc differs a little {$IFNDEF FPC} @SQLite_Open := GetProcAddress(DLLHandle, 'sqlite_open'); if not Assigned(@SQLite_Open) then Result := False; @SQLite_Close := GetProcAddress(DLLHandle, 'sqlite_close'); if not Assigned(@SQLite_Close) then Result := False; @SQLite_Exec := GetProcAddress(DLLHandle, 'sqlite_exec'); if not Assigned(@SQLite_Exec) then Result := False; @SQLite_Version := GetProcAddress(DLLHandle, 'sqlite_libversion'); if not Assigned(@SQLite_Version) then Result := False; @SQLite_Encoding := GetProcAddress(DLLHandle, 'sqlite_libencoding'); if not Assigned(@SQLite_Encoding) then Result := False; @SQLite_ErrorString := GetProcAddress(DLLHandle, 'sqlite_error_string'); if not Assigned(@SQLite_ErrorString) then Result := False; @SQLite_GetTable := GetProcAddress(DLLHandle, 'sqlite_get_table'); if not Assigned(@SQLite_GetTable) then Result := False; @SQLite_FreeTable := GetProcAddress(DLLHandle, 'sqlite_free_table'); if not Assigned(@SQLite_FreeTable) then Result := False; @SQLite_FreeMem := GetProcAddress(DLLHandle, 'sqlite_freemem'); if not Assigned(@SQLite_FreeMem) then Result := False; @SQLite_Complete := GetProcAddress(DLLHandle, 'sqlite_complete'); if not Assigned(@SQLite_Complete) then Result := False; @SQLite_LastInsertRow := GetProcAddress(DLLHandle, 'sqlite_last_insert_rowid'); if not Assigned(@SQLite_LastInsertRow) then Result := False; @SQLite_Cancel := GetProcAddress(DLLHandle, 'sqlite_interrupt'); if not Assigned(@SQLite_Cancel) then Result := False; @SQLite_BusyTimeout := GetProcAddress(DLLHandle, 'sqlite_busy_timeout'); if not Assigned(@SQLite_BusyTimeout) then Result := False; @SQLite_BusyHandler := GetProcAddress(DLLHandle, 'sqlite_busy_handler'); if not Assigned(@SQLite_BusyHandler) then Result := False; @SQLite_Changes := GetProcAddress(DLLHandle, 'sqlite_changes'); if not Assigned(@SQLite_Changes) then Result := False; sqlite_progress_handler := GetProcAddress (DLLHandle, 'sqlite_progress_handler'); sqlite_compile := GetProcAddress (DLLHandle, 'sqlite_compile'); sqlite_step := GetProcAddress (DLLHandle, 'sqlite_step'); sqlite_finalize := GetProcAddress (DLLHandle, 'sqlite_finalize'); {$ELSE} @SQLite_Open := GetProcedureAddress(DLLHandle, 'sqlite_open'); if not Assigned(@SQLite_Open) then Result := False; @SQLite_Close := GetProcedureAddress(DLLHandle, 'sqlite_close'); if not Assigned(@SQLite_Close) then Result := False; @SQLite_Exec := GetProcedureAddress(DLLHandle, 'sqlite_exec'); if not Assigned(@SQLite_Exec) then Result := False; @SQLite_Version := GetProcedureAddress(DLLHandle, 'sqlite_libversion'); if not Assigned(@SQLite_Version) then Result := False; @SQLite_Encoding := GetProcedureAddress(DLLHandle, 'sqlite_libencoding'); if not Assigned(@SQLite_Encoding) then Result := False; @SQLite_ErrorString := GetProcedureAddress(DLLHandle, 'sqlite_error_string'); if not Assigned(@SQLite_ErrorString) then Result := False; @SQLite_GetTable := GetProcedureAddress(DLLHandle, 'sqlite_get_table'); if not Assigned(@SQLite_GetTable) then Result := False; @SQLite_FreeTable := GetProcedureAddress(DLLHandle, 'sqlite_free_table'); if not Assigned(@SQLite_FreeTable) then Result := False; @SQLite_FreeMem := GetProcedureAddress(DLLHandle, 'sqlite_freemem'); if not Assigned(@SQLite_FreeMem) then Result := False; @SQLite_Complete := GetProcedureAddress(DLLHandle, 'sqlite_complete'); if not Assigned(@SQLite_Complete) then Result := False; @SQLite_LastInsertRow := GetProcedureAddress(DLLHandle, 'sqlite_last_insert_rowid'); if not Assigned(@SQLite_LastInsertRow) then Result := False; @SQLite_Cancel := GetProcedureAddress(DLLHandle, 'sqlite_interrupt'); if not Assigned(@SQLite_Cancel) then Result := False; @SQLite_BusyTimeout := GetProcedureAddress(DLLHandle, 'sqlite_busy_timeout'); if not Assigned(@SQLite_BusyTimeout) then Result := False; @SQLite_BusyHandler := GetProcedureAddress(DLLHandle, 'sqlite_busy_handler'); if not Assigned(@SQLite_BusyHandler) then Result := False; @SQLite_Changes := GetProcedureAddress(DLLHandle, 'sqlite_changes'); if not Assigned(@SQLite_Changes) then Result := False; sqlite_progress_handler := GetProcedureAddress (DLLHandle, 'sqlite_progress_handler'); {$ENDIF} if not (Result) then begin {$IFNDEF FPC}FreeLibrary (DllHandle){$ELSE}UnloadLibrary(DllHandle){$ENDIF}; DllHandle := 0; //todo: nil all vars again... end; end; end; initialization //Let component or user do it //LibsLoaded := LoadLibs; // MsgNoError := SystemErrorMsg(0); finalization if DLLHandle <> 0 then {$IFNDEF FPC}FreeLibrary (DllHandle){$ELSE}UnloadLibrary(DllHandle){$ENDIF}; { ToDo : callback functions typedef struct sqlite_func sqlite_func; int sqlite_create_function( sqlite *db, const char *zName, int nArg, void (*xFunc)(sqlite_func*,int,const char**), void *pUserData ); int sqlite_create_aggregate( sqlite *db, const char *zName, int nArg, void (*xStep)(sqlite_func*,int,const char**), void (*xFinalize)(sqlite_func*), void *pUserData ); char *sqlite_set_result_string(sqlite_func*,const char*,int); void sqlite_set_result_int(sqlite_func*,int); void sqlite_set_result_double(sqlite_func*,double); void sqlite_set_result_error(sqlite_func*,const char*,int); void *sqlite_user_data(sqlite_func*); void *sqlite_aggregate_context(sqlite_func*, int nBytes); int sqlite_aggregate_count(sqlite_func*); The sqlite_create_function() interface is used to create regular functions and sqlite_create_aggregate() is used to create new aggregate functions. In both cases, the db parameter is an open SQLite database on which the functions should be registered, zName is the name of the new function, nArg is the number of arguments, and pUserData is a pointer which is passed through unchanged to the C implementation of the function. Both routines return 0 on success and non-zero if there are any errors. The length of a function name may not exceed 255 characters. Any attempt to create a function whose name exceeds 255 characters in length will result in an error. For regular functions, the xFunc callback is invoked once for each function call. The implementation of xFunc should call one of the sqlite_set_result_... interfaces to return its result. The sqlite_user_data() routine can be used to retrieve the pUserData pointer that was passed in when the function was registered. For aggregate functions, the xStep callback is invoked once for each row in the result and then xFinalize is invoked at the end to compute a final answer. The xStep routine can use the sqlite_aggregate_context() interface to allocate memory that will be unique to that particular instance of the SQL function. This memory will be automatically deleted after xFinalize is called. The sqlite_aggregate_count() routine can be used to find out how many rows of data were passed to the aggregate. The xFinalize callback should invoke one of the sqlite_set_result_... interfaces to set the final result of the aggregate. SQLite now implements all of its built-in functions using this interface. For additional information and examples on how to create new SQL functions, review the SQLite source code in the file func.c. } end.
unit GlobalVars; interface var // define variables GAME_TITLE: string = 'FIFA Online4 - Developed by SPEARHEAD'; GARENA_SIGNOUT_TITLE: string = 'Garena - Your Ultimate Game Platform'; GARENA_SIGNIN_TITLE: string = 'Garena - Game Center'; GAME_PROCESS_NAME: string = ''; GARENA_PROCESS_NAME: string = ''; STR_CONFIRM_OUTAUTO: string = 'Bạn có chắc muốn thoát Fo4A ?'; STR_CONFIRM_OUTGAME: string = 'Bạn có chắc muốn thoát game ?'; // button click POSCLICK_SIGNIN_X: integer = 578; POSCLICK_SIGNIN_Y: integer = 434; implementation end.
Unit TicTac; { TicTac.pas Unit for implement abstract data types Move, Location, Game Bye Bruce F. Webster, Last update 12 Dec 87 } Interface { Definitions for abstract data Type Move } Type Move = (Blank, X, O); Function Opposite(M : Move) : Move; Const GLim = 9; Type Location = 1..GLim; { Definitions for abstract data type Game } Type Board = Array[Location] of Move; Game = Record Grid : Board; Next,Win : Move; Moves : Integer; End; Function GetLoc(Var G : Game; L : Location) : Move; Function NextMove(G:Game) : Move; Function MovesMade(G:Game) : Integer; Function GameOver(Var G : Game) : Boolean; Function Winner(G:Game) : Move; Procedure DoMove(Var G : Game; L : Location); Procedure NewGame(Var G : Game;First : Move); Implementation Function Opposite(M:Move):Move; { Purpose Return opposite of value passed. Pre m has a value of X, O, or Blank. Post If M = X, Then returns O If M = O, Then returns X Else returns Blank } Begin Case M of Blank : Opposite := Blank; X : Opposite := O; O : Opposite := X; End ; End; { Procedure Opposite } Procedure SetLoc(Var G: Game; L : Location; M : Move ); { Purpose Sets a location in the game to a given value Pre L is in the range 1..9 M has a value of X, O, or Blank Post Location L in the game has the value M. } Begin G.Grid[L] := M; End; { Procedure SetLoc } Function GetLoc(Var G : Game; L : Location) : Move; { Purpose Returns the value of a given location in the game. Pre G has been initialized, L is in the range of 1..9 Post Returns the value of G, at a location. } Begin GetLoc := G.Grid[L]; End; { Function GetLoc } Function NextMove(G:Game):Move; { Purpose Returns the next move Pre G has been initialized Post If the game is not over then it returns X or O or Blank. } Begin NextMove := G.Next; End; { Function NextMove } Function MovesMade(G:Game):Integer; { Purpose Returns number of moves made in the game so far Pre G has been initialized Post Returns a value in the range of 0..9 } Begin MovesMade := G.Moves; End; { Function MovesMade } Procedure InARow(Var G : Game; I,J,K : Location); { Purpose Checks for three X's or O's in a row Pre G has been initialized, O or More moves made Post If Locations I, J, K all have the same value and that value is not Blank, then the winner is set to that value } Begin With G Do Begin If Win = Blank Then Begin If (Grid[I] = Grid[J]) and (Grid[J] = Grid[K]) And (Grid[I] <> Blank) Then Win := Grid[I]; End; End; End; { Procedure InARow } Procedure CheckForWin(Var G : Game; L : Location); { Purpose See if last move won the game Pre G has been initialized, 1 or more moves made, L is in the range 1..9, Location L has X or O, Last move was made at location L. Post If L forms 3 X's or O's in a row, Then the winner is set to that value. } Begin Case L of 1 : Begin InARow(G,1,2,3); InARow(G,1,5,9); InARow(G,1,4,7); End; 2 : Begin InARow(G,1,2,3); InARow(G,2,5,8); End; 3 : Begin InARow(G,1,2,3); InARow(G,3,5,7); InARow(G,3,6,9); End; 4 : Begin InARow(G,1,4,7); InARow(G,4,5,6); End; 5 : Begin InARow(G,1,5,9); InARow(G,2,5,8); InARow(G,3,5,7); InARow(G,4,5,6); End; 6 : Begin InARow(G,3,6,9); InARow(G,4,5,6); End; 7 : Begin InARow(G,1,4,7); InARow(G,3,5,7); InARow(G,7,8,9); End; 8 : Begin InARow(G,2,5,8); InARow(G,7,8,9); End; 9 : Begin InARow(G,1,5,9); InARow(G,3,6,9); InARow(G,7,8,9); End; End; End; { Procedure CheckForWin } Function GameOver(Var G: Game) : Boolean; { Purpose Returns the status of the Game (Over or Not) Pre G has been initialized, O or more moves have been made. Post If Game is over, Then Returns True Else returns False. } Begin GameOver := (G.Win <> Blank) Or (G.Moves = Glim) End; { Function GameOver } Function Winner(G:Game):Move; { Purpose Returns Winner of Game Pre G has been initialized, The game is over Post If there are 3 X's in a row, Returns X If there are 3 O's in a row, Returns O Else returns Blank (Draw) } Begin Winner := G.Win; End; { Function Winner } Procedure DoMove(Var G:Game;L:Location); { Purpose Make next move in game Pre G has been initialized, O or more moves made, the game is not over, L is in the range 1..9, Getloc(G,L) is Blank Post The next move is made at location L a possible win is checked If game is not over, Then move is toggled Else the next move is set to Blank } Begin With G Do Begin SetLoc(G,L,G.Next); Moves := Moves + 1; CheckForWin(G,L); If not GameOver(G) Then Next := Opposite(Next) Else Next := Blank End; End; { Procedure DoMove } Procedure NewGame(Var G: Game; First : Move); { Purpose Initialize a new game Pre First has a value of X or O Post G has been initialized: Locations 1..9 are setBto Blank the next move is set to first the winner is set to Blank the number of moves is set to 0 } Var I : Integer ; Begin With G Do Begin For I := 1 to Glim Do SetLoc(G,I,Blank); Next := First; Win := Blank; Moves := 0; End; End; { Procedure NewGame } End. { Unit TicTac } 
{: Rendering to a TMemoryViewer and using the render as texture.<p> This sample illustrates use of the TGLMemoryViewer to render to a texture. The simple scene features a lone cube, when rendered to the memory viewer, a red background is used (the TGLSceneViewer uses a gray background).<p> After each main viewer render, the scene is rendered to the memory viewer and the result is copied to the texture of the cube (a "BlankImage" was defined at runtime, because we only need to specify the texture size). Most of the time, you won't need to render textures at each frame, and a set options illustrates that. The 1:2 mode is significantly faster and visually equivalent (even with VSync on, to limit the framerate).<p> Never forget a memory viewer will use 3D board memory, thus reducing available space for VectorGeometry and textures... try using only one memory viewer and maximize its use. This sample will only work on 3D boards that support WGL_ARB_pbuffer, which should be the case for all of the modern boards, and even some of the older ones. } unit unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, StdCtrls, GLObjects, ExtCtrls, GLCadencer, GLTexture, GLViewer, OpenGL1x, GLCrossPlatform, GLCoordinates; type TForm1 = class(TForm) Timer1: TTimer; CheckBox1: TCheckBox; GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; DummyCube1: TGLDummyCube; Cube1: TGLCube; GLLightSource1: TGLLightSource; GLMemoryViewer1: TGLMemoryViewer; GLCadencer1: TGLCadencer; Label1: TLabel; RB1to1: TRadioButton; RB1to2: TRadioButton; RB1to10: TRadioButton; Label2: TLabel; procedure Timer1Timer(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure CheckBox1Click(Sender: TObject); procedure GLSceneViewer1AfterRender(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RB1to1Click(Sender: TObject); private { Private declarations } textureFramerateRatio, n : Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.lfm} procedure TForm1.FormCreate(Sender: TObject); begin textureFramerateRatio:=1; n:=0; end; procedure TForm1.RB1to1Click(Sender: TObject); begin textureFramerateRatio:=(Sender as TRadioButton).Tag; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then GLSceneViewer1.VSync:=vsmSync else GLSceneViewer1.VSync:=vsmNoSync; end; procedure TForm1.GLSceneViewer1AfterRender(Sender: TObject); begin if not (WGL_ARB_pbuffer or GLX_VERSION_1_3 or GLX_VERSION_1_4) then begin ShowMessage( 'WGL_ARB_pbuffer not supported...'#13#10#13#10 +'Get newer graphics hardware or try updating your drivers!'); GLSceneViewer1.AfterRender:=nil; Exit; end; Inc(n); try if n>=textureFramerateRatio then begin // render to the viewer GLMemoryViewer1.Render; // copy result to the textures GLMemoryViewer1.CopyToTexture(Cube1.Material.Texture); n:=0; end; except // pbuffer not supported... catchall for exotic ICDs... GLSceneViewer1.AfterRender:=nil; raise; end; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin DummyCube1.TurnAngle:=newTime*60; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
unit JsEditCPF1; interface uses SysUtils, Classes, Controls, StdCtrls, Graphics, Windows, Messages, Forms, contnrs, Dialogs, Buttons, Mask, JsEdit1; type JsEditCPF = class(TMaskEdit) private valida : boolean; function strnum(num : string) : string; protected { Protected declarations } public constructor Create(AOwner: TComponent);override; procedure KeyPress(var Key: Char);override; procedure KeyDown(var Key: Word; shift : TShiftState);override; function ValidaCPF() : boolean; function CompletaString(parcial : string) : string; published property ValidaCampo :boolean read valida write valida default false; end; procedure Register; implementation var lista : TObjectList; primeiroCampo : TObject; procedure Register; begin RegisterComponents('JsEdit', [JsEditCPF]); end; constructor JsEditCPF.Create(AOwner: TComponent); begin Inherited; JsEdit.AdicionaComponente(Self); Self.EditMask := '!999.999.999-99;1;_'; lista := JsEdit.GetLista(); end; procedure JsEditCPF.KeyPress(var Key: Char); var ok : boolean; begin inherited KeyPress(Key); if (Key = #27) then begin JsEdit.LimpaCampos(self.Owner.Name); end; //if ((Key <> #13) and (Key <> #27)) then //inherited KeyPress(Key); {if Key = #8 then begin Text := '___.___.___-__'; ReformatText(EditMask); key := #0; end;} if (Key = #13) then begin //ShowMessage('1'); ok := false; if (Self.Text = '___.___.___-__') then begin //se valida campo, não deixa passar em branco if (Self.valida) then begin ok := false; ShowMessage('Campo de preenchimento obrigatório'); Self.SetFocus; end; end else if self.valida then begin if (validaCPF = false) then begin MessageDlg('CPF Inválido!', mtError, [mbOK], 1); Self.SelectAll; Self.SetFocus; ok := false; Key := #0; end else ok := true; end else ok := true; if ok then PostMessage((Owner as TWinControl).Handle, WM_NEXTDLGCTL, 0, 0) end; if ((Key = #27) and (self <> lista.First) ) then JsEdit.LimpaCampos(self.Owner.Name); end; function JsEditCPF.validaCPF() : boolean; var i:integer; Want:char; Wvalid:boolean; Wdigit1,Wdigit2:integer; cpf : String; begin cpf := strnum(Text); Result := false; if length(cpf) <> 11 then exit; Wdigit1:=0; Wdigit2:=0; Want:=cpf[1];//variavel para testar se o cpf é repetido como 111.111.111-11 Delete(cpf,ansipos('.',cpf),1); //retira as mascaras se houver Delete(cpf,ansipos('.',cpf),1); Delete(cpf,ansipos('-',cpf),1); //testar se o cpf é repetido como 111.111.111-11 for i:=1 to length(cpf) do begin if cpf[i] <> Want then begin Wvalid:=true; // se o cpf possui um digito diferente ele passou no primeiro teste break end; end; // se o cpf é composto por numeros repetido retorna falso if not Wvalid then begin result:=false; exit; end; //executa o calculo para o primeiro verificador for i:=1 to 9 do begin wdigit1:=Wdigit1+(strtoint(cpf[10-i])*(I+1)); end; Wdigit1:= ((11 - (Wdigit1 mod 11))mod 11) mod 10; {formula do primeiro verificador soma=1°*2+2°*3+3°*4.. até 9°*10 digito1 = 11 - soma mod 11 se digito > 10 digito1 =0 } //verifica se o 1° digito confere if IntToStr(Wdigit1) <> cpf[10] then begin result:=false; exit; end; for i:=1 to 10 do begin wdigit2:=Wdigit2+(strtoint(cpf[11-i])*(I+1)); end; Wdigit2:= ((11 - (Wdigit2 mod 11))mod 11) mod 10; {formula do segundo verificador soma=1°*2+2°*3+3°*4.. até 10°*11 digito1 = 11 - soma mod 11 se digito > 10 digito1 =0 } // confere o 2° digito verificador if IntToStr(Wdigit2) <> cpf[11] then begin result:=false; exit; end; //se chegar até aqui o cpf é valido result:=true; end; procedure JsEditCPF.KeyDown(var Key: Word; shift : TShiftState); begin if Key = 46 then begin Text := '___.___.___-__'; ReformatText(EditMask); key := 0; end; //teclas PgUp e PgDown - passam o foco para o çprimeiro botão if ((Key = 33) or (Key = 34)) then JsEdit.SetFocusNoPrimeiroBotao; //seta acima - sobe até o primeiro componente if (Key = 38) then begin if TEdit(lista.First).Enabled then primeiroCampo := lista.First else primeiroCampo := lista.Items[1]; if (self <> primeiroCampo) then PostMessage((Owner as TWinControl).Handle, WM_NEXTDLGCTL, 1, 0); end; //seta abaixo - não passa do primeiro e nem do último para baixo if ((Key = 40) and (self <> lista.Last)) then PostMessage((Owner as TWinControl).Handle, WM_NEXTDLGCTL, 0, 0); inherited KeyDown(key, shift); end; function JsEditCPF.CompletaString(parcial : string) : string; var ini : integer; atual, ret : string; begin atual := datetostr(date); ret := ''; for ini := 1 to length(atual) do begin if (copy(parcial, ini, 1) = ' ') then ret := ret + copy(atual, ini, 1) else ret := ret + copy(parcial, ini, 1); end; result := ret; end; function JsEditCPF.strnum(num : string) : string; var cont : integer; begin Result := ''; for cont := 1 to length(num) do begin if pos(num[cont], '1234567890') > 0 then Result := Result + num[cont]; end; if Result = '' then Result := '0'; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Base classes and interface for GLScene Sound System } unit VXS.Sound; interface uses System.Classes, System.SysUtils, System.Types, VXS.VectorTypes, VXS.SoundFileObjects, VXS.Scene, VXS.XCollection, VXS.VectorGeometry, VXS.Cadencer, VXS.BaseClasses, VXS.CrossPlatform, VXS.Utils; {$I VXScene.inc} type { Stores a single PCM coded sound sample. } TVXSoundSample = class(TCollectionItem) private FName: string; FData: TVXSoundFile; FTag: Integer; protected procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Stream: TStream); virtual; procedure WriteData(Stream: TStream); virtual; function GetDisplayName: string; override; procedure SetData(const val: TVXSoundFile); public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure LoadFromFile(const fileName: string); procedure PlayOnWaveOut; function Sampling: TVXSoundSampling; function LengthInBytes: Integer; function LengthInSamples: Integer; function LengthInSec: Single; // This Tag is reserved for sound manager use only property ManagerTag: Integer read FTag write FTag; published property Name: string read FName write FName; property Data: TVXSoundFile read FData write SetData stored False; end; TVXSoundSamples = class(TCollection) protected owner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TVXSoundSample); function GetItems(index: Integer): TVXSoundSample; public constructor Create(AOwner: TComponent); function Add: TVXSoundSample; function FindItemID(ID: Integer): TVXSoundSample; property Items[index: Integer]: TVXSoundSample read GetItems write SetItems; default; function GetByName(const aName: string): TVXSoundSample; function AddFile(const fileName: string; const sampleName: string = ''): TVXSoundSample; end; TVXSoundLibrary = class(TComponent) private FSamples: TVXSoundSamples; protected procedure SetSamples(const val: TVXSoundSamples); procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Samples: TVXSoundSamples read FSamples write SetSamples; end; TVXSoundSourceChange = (sscTransformation, sscSample, sscStatus); TVXSoundSourceChanges = set of TVXSoundSourceChange; TVXBSoundEmitter = class; { Base class for origin of sound playback. } TVXBaseSoundSource = class(TCollectionItem) private FBehaviourToNotify: TVXBSoundEmitter; // private only, NOT persistent, not assigned FPriority: Integer; FOrigin: TVXBaseSceneObject; // NOT persistent FVolume: Single; FMinDistance, FMaxDistance: Single; FInsideConeAngle, FOutsideConeAngle: Single; FConeOutsideVolume: Single; FSoundLibraryName: string; // used for persistence FSoundLibrary: TVXSoundLibrary; // persistence via name FSoundName: string; FMute: Boolean; FPause: Boolean; FChanges: TVXSoundSourceChanges; // NOT persistent, not assigned FNbLoops: Integer; FTag: Cardinal; // NOT persistent, not assigned FFrequency: Integer; protected procedure WriteToFiler(writer: TWriter); procedure ReadFromFiler(reader: TReader); function GetDisplayName: string; override; procedure SetPriority(const val: Integer); procedure SetOrigin(const val: TVXBaseSceneObject); procedure SetVolume(const val: Single); procedure SetMinDistance(const val: Single); procedure SetMaxDistance(const val: Single); procedure SetInsideConeAngle(const val: Single); procedure SetOutsideConeAngle(const val: Single); procedure SetConeOutsideVolume(const val: Single); function GetSoundLibrary: TVXSoundLibrary; procedure SetSoundLibrary(const val: TVXSoundLibrary); procedure SetSoundName(const val: string); procedure SetMute(const val: Boolean); procedure SetPause(const val: Boolean); procedure SetNbLoops(const val: Integer); procedure SetFrequency(const val: Integer); public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property Changes: TVXSoundSourceChanges read FChanges; function Sample: TVXSoundSample; // This Tag is reserved for sound manager use only property ManagerTag: Cardinal read FTag write FTag; { Origin object for the sound sources. Absolute object position/orientation are taken into account, the object's TVXBInertia is considered if any. If origin is nil, the source is assumed to be static at the origin. Note : since TCollectionItem do not support the "Notification" scheme, it is up to the Origin object to take care of updating this property prior to release/destruction. } property Origin: TVXBaseSceneObject read FOrigin write SetOrigin; published property SoundLibrary: TVXSoundLibrary read GetSoundLibrary write SetSoundLibrary; property SoundName: string read FSoundName write SetSoundName; { Volume of the source, [0.0; 1.0] range } property Volume: Single read FVolume write SetVolume; { Nb of playing loops. } property NbLoops: Integer read FNbLoops write SetNbLoops default 1; property Mute: Boolean read FMute write SetMute default False; property Pause: Boolean read FPause write SetPause default False; { Sound source priority, the higher the better. When maximum number of sound sources is reached, only the sources with the highest priority will continue to play, however, even non-playing sources should be tracked by the manager, thus allowing an "unlimited" amount of sources from the application point of view. } property Priority: Integer read FPriority write SetPriority default 0; { Min distance before spatial attenuation occurs. 1.0 by default } property MinDistance: Single read FMinDistance write SetMinDistance; { Max distance, if source is further away, it will not be heard. 100.0 by default } property MaxDistance: Single read FMaxDistance write SetMaxDistance; { Inside cone angle, [0°; 360°]. Sound volume is maximal within this cone. See DirectX SDK for details. } property InsideConeAngle: Single read FInsideConeAngle write SetInsideConeAngle; { Outside cone angle, [0°; 360°]. Between inside and outside cone, sound volume decreases between max and cone outside volume. See DirectX SDK for details. } property OutsideConeAngle: Single read FOutsideConeAngle write SetOutsideConeAngle; { Cone outside volume, [0.0; 1.0] range. See DirectX SDK for details. } property ConeOutsideVolume: Single read FConeOutsideVolume write SetConeOutsideVolume; { Sample custom playback frequency. Values null or negative are interpreted as 'default frequency'. } property Frequency: Integer read FFrequency write SetFrequency default -1; end; { Origin of sound playback. Just publishes the 'Origin' property. Note that the "orientation" is the the source's Direction, ie. the "Z" vector. } TVXSoundSource = class(TVXBaseSoundSource) public destructor Destroy; override; published property Origin; end; TVXSoundSources = class(TCollection) protected owner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TVXSoundSource); function GetItems(index: Integer): TVXSoundSource; function Add: TVXSoundSource; function FindItemID(ID: Integer): TVXSoundSource; public constructor Create(AOwner: TComponent); property Items[index: Integer]: TVXSoundSource read GetItems write SetItems; default; end; { EAX standard sound environments. } TVXSoundEnvironment = (seDefault, sePaddedCell, seRoom, seBathroom, seLivingRoom, seStoneroom, seAuditorium, seConcertHall, seCave, seArena, seHangar, seCarpetedHallway, seHallway, seStoneCorridor, seAlley, seForest, seCity, seMountains, seQuarry, sePlain, seParkingLot, seSewerPipe, seUnderWater, seDrugged, seDizzy, sePsychotic); { Base class for sound manager components. The sound manager component is the interface to a low-level audio API (like DirectSound), there can only be one active manager at any time (this class takes care of this). Subclass should override the DoActivate and DoDeActivate protected methods to "initialize/unitialize" their sound layer, actual data releases should occur in destructor however. } TVXSoundManager = class(TVXCadenceAbleComponent) private FActive: Boolean; FMute: Boolean; FPause: Boolean; FMasterVolume: Single; FListener: TVXBaseSceneObject; FLastListenerPosition: TVector; FSources: TVXSoundSources; FMaxChannels: Integer; FOutputFrequency: Integer; FUpdateFrequency: Single; FDistanceFactor: Single; FRollOffFactor: Single; FDopplerFactor: Single; FSoundEnvironment: TVXSoundEnvironment; FLastUpdateTime, FLastDeltaTime: Single; // last time UpdateSources was fired, not persistent FCadencer: TVXCadencer; procedure SetActive(const val: Boolean); procedure SetMute(const val: Boolean); procedure SetPause(const val: Boolean); procedure WriteDoppler(writer: TWriter); procedure ReadDoppler(reader: TReader); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetSources(const val: TVXSoundSources); procedure SetMasterVolume(const val: Single); procedure SetListener(const val: TVXBaseSceneObject); procedure SetMaxChannels(const val: Integer); procedure SetOutputFrequency(const val: Integer); procedure SetUpdateFrequency(const val: Single); function StoreUpdateFrequency: Boolean; procedure SetCadencer(const val: TVXCadencer); procedure SetDistanceFactor(const val: Single); function StoreDistanceFactor: Boolean; procedure SetRollOffFactor(const val: Single); function StoreRollOffFactor: Boolean; procedure SetDopplerFactor(const val: Single); procedure SetSoundEnvironment(const val: TVXSoundEnvironment); procedure Loaded; override; procedure DefineProperties(Filer: TFiler); override; procedure ListenerCoordinates(var position, velocity, direction, up: TVector); function DoActivate: Boolean; virtual; // Invoked AFTER all sources have been stopped procedure DoDeActivate; virtual; { Effect mute of all sounds. Default implementation call MuteSource for all non-muted sources with "True" as parameter. } function DoMute: Boolean; virtual; { Effect un-mute of all sounds. Default implementation call MuteSource for all non-muted sources with "False" as parameter. } procedure DoUnMute; virtual; { Effect pause of all sounds. Default implementation call PauseSource for all non-paused sources with "True" as parameter. } function DoPause: Boolean; virtual; { Effect un-pause of all sounds. Default implementation call PauseSource for all non-paused sources with "True" as parameter. } procedure DoUnPause; virtual; procedure NotifyMasterVolumeChange; virtual; procedure Notify3DFactorsChanged; virtual; procedure NotifyEnvironmentChanged; virtual; // Called when a source will be freed procedure KillSource(aSource: TVXBaseSoundSource); virtual; { Request to update source's data in low-level sound API. Default implementation just clears the "Changes" flags. } procedure UpdateSource(aSource: TVXBaseSoundSource); virtual; procedure MuteSource(aSource: TVXBaseSoundSource; muted: Boolean); virtual; procedure PauseSource(aSource: TVXBaseSoundSource; paused: Boolean); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Manual request to update all sources to reflect changes. Default implementation invokes UpdateSource for all known sources. } procedure UpdateSources; virtual; { Stop and free all sources. } procedure StopAllSources; { Progress notification for time synchronization. This method will call UpdateSources depending on the last time it was performed and the value of the UpdateFrequency property. } procedure DoProgress(const progressTime: TVXProgressTimes); override; { Sound manager API reported CPU Usage. Returns -1 when unsupported. } function CPUUsagePercent: Single; virtual; { True if EAX is supported. } function EAXSupported: Boolean; virtual; published { Activation/deactivation of the low-level sound API } property Active: Boolean read FActive write SetActive default False; { Maximum number of sound output channels. While some drivers will just ignore this value, others cannot dynamically adjust the maximum number of channels (you need to de-activate and re-activate the manager for this property to be taken into account). } property MaxChannels: Integer read FMaxChannels write SetMaxChannels default 8; { Sound output mixing frequency. Commonly used values ar 11025, 22050 and 44100. Note that most driver cannot dynamically adjust the output frequency (you need to de-ativate and re-activate the manager for this property to be taken into account). } property OutputFrequency: Integer read FOutputFrequency write SetOutputFrequency default 44100; { Request to mute all sounds. All sound requests should be handled as if sound is unmuted though, however drivers should try to take a CPU advantage of mute over MasterVolume=0 } property Mute: Boolean read FMute write SetMute default False; { Request to pause all sound, sound output should be muted too. When unpausing, all sound should resume at the point they were paused. } property Pause: Boolean read FPause write SetPause default False; { Master Volume adjustement in the [0.0; 1.0] range. Driver should take care of properly clamping the master volume. } property MasterVolume: Single read FMasterVolume write SetMasterVolume; { Scene object that materializes the listener. The sceneobject's AbsolutePosition and orientation are used to define the listener coordinates, velocity is automatically calculated (if you're using DoProgress or connected the manager to a cadencer). If this property is nil, the listener is assumed to be static at the NullPoint coordinate, facing Z axis, with up being Y (ie. the default orientation). } property Listener: TVXBaseSceneObject read FListener write SetListener; { Currently active and playing sound sources. } property Sources: TVXSoundSources read FSources write SetSources; { Update frequency for time-based control (DoProgress). Default value is 10 Hz (frequency is clamped in the 1Hz-60Hz range). } property UpdateFrequency: Single read FUpdateFrequency write SetUpdateFrequency stored StoreUpdateFrequency; { Cadencer for time-based control. } property Cadencer: TVXCadencer read FCadencer write SetCadencer; { Engine relative distance factor, compared to 1.0 meters. Equates to 'how many units per meter' your engine has. } property DistanceFactor: Single read FDistanceFactor write SetDistanceFactor stored StoreDistanceFactor; { Sets the global attenuation rolloff factor. Normally volume for a sample will scale at 1 / distance. This gives a logarithmic attenuation of volume as the source gets further away (or closer). Setting this value makes the sound drop off faster or slower. The higher the value, the faster volume will fall off. } property RollOffFactor: Single read FRollOffFactor write SetRollOffFactor stored StoreRollOffFactor; { Engine relative Doppler factor, compared to 1.0 meters. Equates to 'how many units per meter' your engine has. } property DopplerFactor: Single read FDopplerFactor write SetDopplerFactor stored False; { Sound environment (requires EAX compatible soundboard). } property Environment: TVXSoundEnvironment read FSoundEnvironment write SetSoundEnvironment default seDefault; end; { A sound emitter behaviour, plug it on any object to make it noisy. This behaviour is just an interface to a TVXSoundSource, for editing convenience. } TVXBSoundEmitter = class(TVXBehaviour) private FPlaying: Boolean; // used at design-time ONLY FSource: TVXBaseSoundSource; FPlayingSource: TVXSoundSource; protected procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; procedure Loaded; override; procedure SetSource(const val: TVXBaseSoundSource); procedure SetPlaying(const val: Boolean); function GetPlaying: Boolean; procedure NotifySourceDestruction(aSource: TVXSoundSource); public constructor Create(aOwner: TXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: Boolean; override; procedure DoProgress(const progressTime: TVXProgressTimes); override; property PlayingSource: TVXSoundSource read FPlayingSource; published property Source: TVXBaseSoundSource read FSource write SetSource; property Playing: Boolean read GetPlaying write SetPlaying default False; end; function ActiveSoundManager: TVXSoundManager; function GetSoundLibraryByName(const aName: string): TVXSoundLibrary; function GetOrCreateSoundEmitter(behaviours: TVXBehaviours): TVXBSoundEmitter; overload; function GetOrCreateSoundEmitter(obj: TVXBaseSceneObject): TVXBSoundEmitter; overload; var // If this variable is true, errors in GLSM may be displayed to the user vVerboseGLSMErrors: Boolean = True; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ var vActiveSoundManager: TVXSoundManager; vSoundLibraries: TList; function ActiveSoundManager: TVXSoundManager; begin Result := vActiveSoundManager; end; function GetSoundLibraryByName(const aName: string): TVXSoundLibrary; var i: Integer; begin Result := nil; if Assigned(vSoundLibraries) then for i := 0 to vSoundLibraries.Count - 1 do if TVXSoundLibrary(vSoundLibraries[i]).Name = aName then begin Result := TVXSoundLibrary(vSoundLibraries[i]); Break; end; end; function GetOrCreateSoundEmitter(behaviours: TVXBehaviours): TVXBSoundEmitter; var i: Integer; begin i := behaviours.IndexOfClass(TVXBSoundEmitter); if i >= 0 then Result := TVXBSoundEmitter(behaviours[i]) else Result := TVXBSoundEmitter.Create(behaviours); end; function GetOrCreateSoundEmitter(obj: TVXBaseSceneObject): TVXBSoundEmitter; begin Result := GetOrCreateSoundEmitter(obj.Behaviours); end; // ------------------ // ------------------ TVXSoundSample ------------------ // ------------------ constructor TVXSoundSample.Create(Collection: TCollection); begin inherited Create(Collection); end; destructor TVXSoundSample.Destroy; begin FData.Free; inherited Destroy; end; procedure TVXSoundSample.Assign(Source: TPersistent); begin if Source is TVXSoundSample then begin FName := TVXSoundSample(Source).Name; FData.Free; FData := TVXSoundFile(TVXSoundSample(Source).Data.CreateCopy(Self)); end else inherited Assign(Source); // Assign error end; procedure TVXSoundSample.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('BinData', ReadData, WriteData, Assigned(FData)); end; procedure TVXSoundSample.ReadData(Stream: TStream); var n: Integer; clName: AnsiString; begin with Stream do begin Read(n, SizeOf(Integer)); SetLength(clName, n); if n > 0 then Read(clName[1], n); FData := TVXSoundFileClass(FindClass(string(clName))).Create(Self); FData.LoadFromStream(Stream); end; end; procedure TVXSoundSample.WriteData(Stream: TStream); var n: Integer; buf: AnsiString; begin with Stream do begin n := Length(FData.ClassName); Write(n, SizeOf(Integer)); buf := AnsiString(FData.ClassName); if n > 0 then Write(buf[1], n); FData.SaveToStream(Stream); end; end; function TVXSoundSample.GetDisplayName: string; var s: string; begin if Assigned(FData) then begin if Data.Sampling.NbChannels > 1 then s := 's' else s := ''; Result := Format('%s (%d Hz, %d bits, %d channel%s, %.2f sec)', [Name, Data.Sampling.Frequency, Data.Sampling.BitsPerSample, Data.Sampling.NbChannels, s, LengthInSec]) end else Result := Format('%s (empty)', [Name]); end; procedure TVXSoundSample.LoadFromFile(const fileName: string); var sfc: TVXSoundFileClass; begin FData.Free; sfc := GetGLSoundFileFormats.FindExt(ExtractFileExt(fileName)); if Assigned(sfc) then begin FData := sfc.Create(Self); FData.LoadFromFile(fileName); end else FData := nil; Assert(Data <> nil, 'Could not load ' + fileName + ', make sure you include the unit required to load this format in your uses clause.'); Name := ExtractFileName(fileName); end; procedure TVXSoundSample.PlayOnWaveOut; begin if Assigned(FData) then FData.PlayOnWaveOut; end; // TVXSoundSample // function TVXSoundSample.Sampling: TVXSoundSampling; begin if Assigned(FData) then Result := FData.Sampling else Result := nil; end; function TVXSoundSample.LengthInBytes: Integer; begin if Assigned(FData) then Result := FData.LengthInBytes else Result := 0; end; function TVXSoundSample.LengthInSamples: Integer; begin if Assigned(FData) then Result := FData.LengthInSamples else Result := 0; end; function TVXSoundSample.LengthInSec: Single; begin if Assigned(FData) then Result := FData.LengthInSec else Result := 0; end; procedure TVXSoundSample.SetData(const val: TVXSoundFile); begin FData.Free; if Assigned(val) then FData := TVXSoundFile(val.CreateCopy(Self)) else FData := nil; end; // ------------------ // ------------------ TVXSoundSamples ------------------ // ------------------ constructor TVXSoundSamples.Create(AOwner: TComponent); begin Owner := AOwner; inherited Create(TVXSoundSample); end; function TVXSoundSamples.GetOwner: TPersistent; begin Result := Owner; end; procedure TVXSoundSamples.SetItems(index: Integer; const val: TVXSoundSample); begin inherited Items[index] := val; end; function TVXSoundSamples.GetItems(index: Integer): TVXSoundSample; begin Result := TVXSoundSample(inherited Items[index]); end; function TVXSoundSamples.Add: TVXSoundSample; begin Result := (inherited Add) as TVXSoundSample; end; function TVXSoundSamples.FindItemID(ID: Integer): TVXSoundSample; begin Result := (inherited FindItemID(ID)) as TVXSoundSample; end; function TVXSoundSamples.GetByName(const aName: string): TVXSoundSample; var i: Integer; begin Result := nil; for i := 0 to Count - 1 do if CompareText(Items[i].Name, aName) = 0 then begin Result := Items[i]; Break; end; end; function TVXSoundSamples.AddFile(const fileName: string; const sampleName: string = ''): TVXSoundSample; begin Result := Add; Result.LoadFromFile(fileName); if sampleName <> '' then Result.Name := sampleName; end; // ------------------ // ------------------ TVXSoundLibrary ------------------ // ------------------ constructor TVXSoundLibrary.Create(AOwner: TComponent); begin inherited Create(AOwner); FSamples := TVXSoundSamples.Create(Self); vSoundLibraries.Add(Self); end; destructor TVXSoundLibrary.Destroy; begin vSoundLibraries.Remove(Self); FSamples.Free; inherited Destroy; end; procedure TVXSoundLibrary.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; end; procedure TVXSoundLibrary.SetSamples(const val: TVXSoundSamples); begin FSamples.Assign(val); end; // ------------------ // ------------------ TVXBaseSoundSource ------------------ // ------------------ constructor TVXBaseSoundSource.Create(Collection: TCollection); begin inherited Create(Collection); FChanges := [sscTransformation, sscSample, sscStatus]; FVolume := 1.0; FMinDistance := 1.0; FMaxDistance := 100.0; FInsideConeAngle := 360; FOutsideConeAngle := 360; FConeOutsideVolume := 0.0; FNbLoops := 1; FFrequency := -1; end; destructor TVXBaseSoundSource.Destroy; begin inherited Destroy; end; function TVXBaseSoundSource.GetDisplayName: string; begin Result := Format('%s', [FSoundName]); end; procedure TVXBaseSoundSource.Assign(Source: TPersistent); begin if Source is TVXBaseSoundSource then begin FPriority := TVXBaseSoundSource(Source).FPriority; FOrigin := TVXBaseSoundSource(Source).FOrigin; FVolume := TVXBaseSoundSource(Source).FVolume; FMinDistance := TVXBaseSoundSource(Source).FMinDistance; FMaxDistance := TVXBaseSoundSource(Source).FMaxDistance; FInsideConeAngle := TVXBaseSoundSource(Source).FInsideConeAngle; FOutsideConeAngle := TVXBaseSoundSource(Source).FOutsideConeAngle; FConeOutsideVolume := TVXBaseSoundSource(Source).FConeOutsideVolume; FSoundLibraryName := TVXBaseSoundSource(Source).FSoundLibraryName; FSoundLibrary := TVXBaseSoundSource(Source).FSoundLibrary; FSoundName := TVXBaseSoundSource(Source).FSoundName; FMute := TVXBaseSoundSource(Source).FMute; FPause := TVXBaseSoundSource(Source).FPause; FChanges := [sscTransformation, sscSample, sscStatus]; FNbLoops := TVXBaseSoundSource(Source).FNbLoops; FFrequency := TVXBaseSoundSource(Source).FFrequency; end else inherited Assign(Source); end; procedure TVXBaseSoundSource.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive Version 0 WriteInteger(FPriority); WriteFloat(FVolume); WriteFloat(FMinDistance); WriteFloat(FMaxDistance); WriteFloat(FInsideConeAngle); WriteFloat(FOutsideConeAngle); WriteFloat(FConeOutsideVolume); if Assigned(FSoundLibrary) then WriteString(FSoundLibrary.Name) else WriteString(FSoundLibraryName); WriteString(FSoundName); WriteBoolean(FMute); WriteBoolean(FPause); WriteInteger(FNbLoops); // WriteInteger(FFrequency); end; end; procedure TVXBaseSoundSource.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FPriority := ReadInteger; FVolume := ReadFloat; FMinDistance := ReadFloat; FMaxDistance := ReadFloat; FInsideConeAngle := ReadFloat; FOutsideConeAngle := ReadFloat; FConeOutsideVolume := ReadFloat; FSoundLibraryName := ReadString; FSoundLibrary := nil; FSoundName := ReadString; FMute := ReadBoolean; FPause := ReadBoolean; FChanges := [sscTransformation, sscSample, sscStatus]; FNbLoops := ReadInteger; // FFrequency:=ReadInteger; end; end; function TVXBaseSoundSource.Sample: TVXSoundSample; begin if SoundLibrary <> nil then Result := FSoundLibrary.Samples.GetByName(FSoundName) else Result := nil; end; procedure TVXBaseSoundSource.SetPriority(const val: Integer); begin if val <> FPriority then begin FPriority := val; Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetOrigin(const val: TVXBaseSceneObject); begin if val <> FOrigin then begin FOrigin := val; Include(FChanges, sscTransformation); end; end; procedure TVXBaseSoundSource.SetVolume(const val: Single); begin if val <> FVolume then begin FVolume := ClampValue(val, 0, 1); Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetMinDistance(const val: Single); begin if val <> FMinDistance then begin FMinDistance := ClampValue(val, 0); Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetMaxDistance(const val: Single); begin if val <> FMaxDistance then begin FMaxDistance := ClampValue(val, 0); Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetInsideConeAngle(const val: Single); begin if val <> FInsideConeAngle then begin FInsideConeAngle := ClampValue(val, 0, 360); Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetOutsideConeAngle(const val: Single); begin if val <> FOutsideConeAngle then begin FOutsideConeAngle := ClampValue(val, 0, 360); Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetConeOutsideVolume(const val: Single); begin if val <> FConeOutsideVolume then begin FConeOutsideVolume := ClampValue(val, 0, 1); Include(FChanges, sscStatus); end; end; function TVXBaseSoundSource.GetSoundLibrary: TVXSoundLibrary; begin if (FSoundLibrary = nil) and (FSoundLibraryName <> '') then FSoundLibrary := GetSoundLibraryByName(FSoundLibraryName); Result := FSoundLibrary; end; procedure TVXBaseSoundSource.SetSoundLibrary(const val: TVXSoundLibrary); begin if val <> FSoundLibrary then begin FSoundLibrary := val; if Assigned(FSoundLibrary) then FSoundLibraryName := FSoundLibrary.Name else FSoundLibraryName := ''; Include(FChanges, sscSample); end; end; procedure TVXBaseSoundSource.SetSoundName(const val: string); begin if val <> FSoundName then begin FSoundName := val; Include(FChanges, sscSample); end; end; procedure TVXBaseSoundSource.SetPause(const val: Boolean); begin if val <> FPause then begin FPause := val; if Collection <> nil then TVXSoundManager(TVXSoundSources(Collection).owner).PauseSource(Self, FPause); end; end; procedure TVXBaseSoundSource.SetNbLoops(const val: Integer); begin if val <> FNbLoops then begin FNbLoops := val; Include(FChanges, sscSample); end; end; procedure TVXBaseSoundSource.SetFrequency(const val: integer); begin if val <> FFrequency then begin FFrequency := val; Include(FChanges, sscStatus); end; end; procedure TVXBaseSoundSource.SetMute(const val: Boolean); begin if val <> FMute then begin FMute := val; if Collection <> nil then TVXSoundManager(TVXSoundSources(Collection).owner).MuteSource(Self, FMute); end; end; // ------------------ // ------------------ TVXSoundSource ------------------ // ------------------ destructor TVXSoundSource.Destroy; begin if Assigned(FBehaviourToNotify) then FBehaviourToNotify.NotifySourceDestruction(Self); if Collection <> nil then ((Collection as TVXSoundSources).Owner as TVXSoundManager).KillSource(Self); inherited; end; // ------------------ // ------------------ TVXSoundSources ------------------ // ------------------ constructor TVXSoundSources.Create(AOwner: TComponent); begin Owner := AOwner; inherited Create(TVXSoundSource); end; function TVXSoundSources.GetOwner: TPersistent; begin Result := Owner; end; procedure TVXSoundSources.SetItems(index: Integer; const val: TVXSoundSource); begin inherited Items[index] := val; end; function TVXSoundSources.GetItems(index: Integer): TVXSoundSource; begin Result := TVXSoundSource(inherited Items[index]); end; function TVXSoundSources.Add: TVXSoundSource; begin Result := (inherited Add) as TVXSoundSource; end; function TVXSoundSources.FindItemID(ID: Integer): TVXSoundSource; begin Result := (inherited FindItemID(ID)) as TVXSoundSource; end; // ------------------ // ------------------ TVXSoundManager ------------------ // ------------------ constructor TVXSoundManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FSources := TVXSoundSources.Create(Self); FMasterVolume := 1.0; FOutputFrequency := 44100; FMaxChannels := 8; FUpdateFrequency := 10; FLastUpdateTime := -1e30; FDistanceFactor := 1.0; FRollOffFactor := 1.0; FDopplerFactor := 1.0; end; destructor TVXSoundManager.Destroy; begin Active := False; Listener := nil; FSources.Free; inherited Destroy; end; procedure TVXSoundManager.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation = opRemove then begin if AComponent = FListener then Listener := nil; if AComponent = FCadencer then Cadencer := nil; end; inherited; end; procedure TVXSoundManager.SetActive(const val: Boolean); begin if (csDesigning in ComponentState) or (csLoading in ComponentState) then FActive := val else if val <> FActive then begin if val then begin if Assigned(vActiveSoundManager) then vActiveSoundManager.Active := False; if DoActivate then begin FActive := True; vActiveSoundManager := Self; end; end else begin try StopAllSources; DoDeActivate; finally FActive := val; vActiveSoundManager := nil; end; end; end; end; function TVXSoundManager.DoActivate: Boolean; begin Result := True; end; procedure TVXSoundManager.DoDeActivate; begin StopAllSources; end; procedure TVXSoundManager.SetMute(const val: Boolean); begin if val <> FMute then begin if val then begin if DoMute then FMute := True end else begin DoUnMute; FMute := False; end; end; end; function TVXSoundManager.DoMute: Boolean; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Mute then MuteSource(Sources[i], True); Result := True; end; procedure TVXSoundManager.DoUnMute; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Mute then MuteSource(Sources[i], False); end; procedure TVXSoundManager.SetPause(const val: Boolean); begin if val <> FPause then begin if val then begin if DoPause then FPause := True end else begin DoUnPause; FPause := False; end; end; end; procedure TVXSoundManager.Loaded; begin inherited; if Active and (not (csDesigning in ComponentState)) then begin FActive := False; Active := True; end; end; procedure TVXSoundManager.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Doppler', ReadDoppler, WriteDoppler, (DopplerFactor <> 1)); end; procedure TVXSoundManager.WriteDoppler(writer: TWriter); begin writer.WriteFloat(DopplerFactor); end; procedure TVXSoundManager.ReadDoppler(reader: TReader); begin FDopplerFactor := reader.ReadFloat; end; function TVXSoundManager.DoPause: Boolean; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Pause then PauseSource(Sources[i], True); Result := True; end; procedure TVXSoundManager.DoUnPause; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Pause then PauseSource(Sources[i], False); end; procedure TVXSoundManager.SetMasterVolume(const val: Single); begin if val < 0 then FMasterVolume := 0 else if val > 1 then FMasterVolume := 1 else FMasterVolume := val; NotifyMasterVolumeChange; end; procedure TVXSoundManager.SetMaxChannels(const val: Integer); begin if val <> FMaxChannels then begin if val < 1 then FMaxChannels := 1 else FMaxChannels := val; end; end; procedure TVXSoundManager.SetOutputFrequency(const val: Integer); begin if val <> FOutputFrequency then begin if val < 11025 then FOutputFrequency := 11025 else FOutputFrequency := val; end; end; procedure TVXSoundManager.SetUpdateFrequency(const val: Single); begin FUpdateFrequency := ClampValue(val, 1, 60); end; function TVXSoundManager.StoreUpdateFrequency: Boolean; begin Result := (FUpdateFrequency <> 10); end; procedure TVXSoundManager.SetCadencer(const val: TVXCadencer); begin if val <> FCadencer then begin if Assigned(FCadencer) then FCadencer.UnSubscribe(Self); FCadencer := val; if Assigned(FCadencer) then FCadencer.Subscribe(Self); end; end; procedure TVXSoundManager.SetDistanceFactor(const val: Single); begin if val <= 0 then FDistanceFactor := 1 else FDistanceFactor := val; Notify3DFactorsChanged; end; function TVXSoundManager.StoreDistanceFactor: Boolean; begin Result := (FDistanceFactor <> 1); end; procedure TVXSoundManager.SetRollOffFactor(const val: Single); begin if val <= 0 then FRollOffFactor := 1 else FRollOffFactor := val; Notify3DFactorsChanged; end; function TVXSoundManager.StoreRollOffFactor: Boolean; begin Result := (FRollOffFactor <> 1); end; procedure TVXSoundManager.SetDopplerFactor(const val: Single); begin if val < 0 then FDopplerFactor := 0 else if val > 10 then FDopplerFactor := 10 else FDopplerFactor := val; Notify3DFactorsChanged; end; procedure TVXSoundManager.SetSoundEnvironment(const val: TVXSoundEnvironment); begin if val <> FSoundEnvironment then begin FSoundEnvironment := val; NotifyEnvironmentChanged; end; end; procedure TVXSoundManager.ListenerCoordinates(var position, velocity, direction, up: TVector); var right: TVector; begin if Listener <> nil then begin position := Listener.AbsolutePosition; if FLastDeltaTime <> 0 then begin velocity := VectorSubtract(position, FLastListenerPosition); ScaleVector(velocity, 1 / FLastDeltaTime); end; FLastListenerPosition := position; if (Listener is TVXCamera) and (TVXCamera(Listener).TargetObject <> nil) then begin // special case of the camera targeting something direction := TVXCamera(Listener).AbsoluteVectorToTarget; NormalizeVector(direction); up := Listener.AbsoluteYVector; right := VectorCrossProduct(direction, up); up := VectorCrossProduct(right, direction); end else begin direction := Listener.AbsoluteZVector; up := Listener.AbsoluteYVector; end; end else begin position := NullHmgPoint; velocity := NullHmgVector; direction := ZHmgVector; up := YHmgVector; end; end; procedure TVXSoundManager.NotifyMasterVolumeChange; begin // nothing end; procedure TVXSoundManager.Notify3DFactorsChanged; begin // nothing end; procedure TVXSoundManager.NotifyEnvironmentChanged; begin // nothing end; procedure TVXSoundManager.SetListener(const val: TVXBaseSceneObject); begin if Assigned(FListener) then FListener.RemoveFreeNotification(Self); FListener := val; if Assigned(FListener) then FListener.FreeNotification(Self); end; procedure TVXSoundManager.SetSources(const val: TVXSoundSources); begin FSources.Assign(val); end; procedure TVXSoundManager.KillSource(aSource: TVXBaseSoundSource); begin // nothing end; procedure TVXSoundManager.UpdateSource(aSource: TVXBaseSoundSource); begin aSource.FChanges := []; end; procedure TVXSoundManager.MuteSource(aSource: TVXBaseSoundSource; muted: Boolean); begin // nothing end; procedure TVXSoundManager.PauseSource(aSource: TVXBaseSoundSource; paused: Boolean); begin // nothing end; procedure TVXSoundManager.UpdateSources; var i: Integer; begin for i := Sources.Count - 1 downto 0 do UpdateSource(Sources[i]); end; procedure TVXSoundManager.StopAllSources; var i: Integer; begin for i := Sources.Count - 1 downto 0 do Sources.Delete(i); end; procedure TVXSoundManager.DoProgress(const progressTime: TVXProgressTimes); begin if not Active then Exit; with progressTime do if newTime - FLastUpdateTime > 1 / FUpdateFrequency then begin FLastDeltaTime := newTime - FLastUpdateTime; FLastUpdateTime := newTime; UpdateSources; end; end; function TVXSoundManager.CPUUsagePercent: Single; begin Result := -1; end; function TVXSoundManager.EAXSupported: Boolean; begin Result := False; end; // ------------------ // ------------------ TVXBSoundEmitter ------------------ // ------------------ constructor TVXBSoundEmitter.Create(aOwner: TXCollection); begin inherited Create(aOwner); FSource := TVXSoundSource.Create(nil); end; destructor TVXBSoundEmitter.Destroy; begin if Assigned(FPlayingSource) then FPlayingSource.Free; FSource.Free; inherited Destroy; end; procedure TVXBSoundEmitter.Assign(Source: TPersistent); begin if Source is TVXBSoundEmitter then begin FSource.Assign(TVXBSoundEmitter(Source).FSource); end; inherited Assign(Source); end; procedure TVXBSoundEmitter.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive Version 0 FSource.WriteToFiler(writer); WriteBoolean(FPlaying); end; end; procedure TVXBSoundEmitter.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FSource.ReadFromFiler(reader); FPlaying := ReadBoolean; end; end; procedure TVXBSoundEmitter.Loaded; begin inherited; if not (csDesigning in OwnerBaseSceneObject.ComponentState) then SetPlaying(FPlaying); end; class function TVXBSoundEmitter.FriendlyName: string; begin Result := 'Sound Emitter'; end; class function TVXBSoundEmitter.FriendlyDescription: string; begin Result := 'A simple sound emitter behaviour'; end; class function TVXBSoundEmitter.UniqueItem: Boolean; begin Result := False; end; procedure TVXBSoundEmitter.DoProgress(const progressTime: TVXProgressTimes); begin // nothing, yet end; procedure TVXBSoundEmitter.SetSource(const val: TVXBaseSoundSource); begin FSource.Assign(val); end; procedure TVXBSoundEmitter.SetPlaying(const val: Boolean); begin if csDesigning in OwnerBaseSceneObject.ComponentState then FPlaying := val else if ActiveSoundManager <> nil then begin if val <> Playing then begin if val then begin FPlayingSource := ActiveSoundManager.Sources.Add; FPlayingSource.FBehaviourToNotify := Self; FPlayingSource.Assign(FSource); FPlayingSource.Origin := OwnerBaseSceneObject; end else FPlayingSource.Free; end; end else if vVerboseGLSMErrors then InformationDlg('No Active Sound Manager.'#13#10'Make sure manager is created before emitter'); end; function TVXBSoundEmitter.GetPlaying: Boolean; begin if csDesigning in OwnerBaseSceneObject.ComponentState then Result := FPlaying else Result := Assigned(FPlayingSource); end; procedure TVXBSoundEmitter.NotifySourceDestruction(aSource: TVXSoundSource); begin Assert(FPlayingSource = aSource); FPlayingSource := nil; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // class registrations RegisterClasses([TVXSoundLibrary]); RegisterXCollectionItemClass(TVXBSoundEmitter); vSoundLibraries := TList.Create; // ------------------------------------------------------------------ finalization // ------------------------------------------------------------------ if Assigned(vActiveSoundManager) then vActiveSoundManager.Active := False; vSoundLibraries.Free; vSoundLibraries := nil; UnregisterXCollectionItemClass(TVXBSoundEmitter); end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Base The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit UBase; {$MODE Delphi} interface uses BrookHTTPClient, BrookFCLHTTPClientBroker, BrookHTTPUtils, BrookUtils, LCLIntf, LCLType, LMessages, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SessaoUsuario, Buttons, Tipos, UDataModule, ActnList, Menus, FPJson, DB, BufDataset; type TFBase = class(TForm) private function GetSessaoUsuario: TSessaoUsuario; function GetCustomKeyPreview: Boolean; procedure SetCustomKeyPreview(const Value: Boolean); { Private declarations } public { Public declarations } property Sessao: TSessaoUsuario read GetSessaoUsuario; property CustomKeyPreview: Boolean read GetCustomKeyPreview write SetCustomKeyPreview default False; procedure FechaFormulario; procedure AtualizaGridJsonInterna(pDadosJson: TJSONData; pDataSet: TBufDataSet); end; var FBase: TFBase; implementation uses UMenu, ComCtrls; {$R *.lfm} { TFBase } procedure TFBase.FechaFormulario; begin if (Self.Owner is TTabSheet) and (Assigned(FMenu)) then FMenu.FecharAba(TTabSheet(Self.Owner)) else Self.Close; end; function TFBase.GetCustomKeyPreview: Boolean; begin Result := Self.KeyPreview; end; procedure TFBase.SetCustomKeyPreview(const Value: Boolean); begin Self.KeyPreview := Value; if (Self.Owner is TTabSheet) and (Assigned(FMenu)) then begin FMenu.KeyPreview := Value; end; end; function TFBase.GetSessaoUsuario: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; procedure TFBase.AtualizaGridJsonInterna(pDadosJson: TJSONData; pDataSet: TBufDataSet); var VIsObject: Boolean; VJSONCols: TJSONObject; VRecord: TJSONData = nil; I, J: Integer; begin pDataSet.Close; pDataSet.Open; if not Assigned(pDadosJson) then begin Exit; end; VJSONCols := TJSONObject(pDadosJson.Items[0]); VIsObject := VJSONCols.JSONType = jtObject; if VIsObject and (VJSONCols.Count < 1) then begin Exit; end; try for I := 0 to Pred(pDadosJson.Count) do begin pDataSet.Append; VJSONCols := TJSONObject(pDadosJson.Items[I]); for J := 0 to Pred(VJSONCols.Count) do begin VRecord := VJSONCols.Items[J]; case VRecord.JSONType of jtNumber: begin if VRecord is TJSONFloatNumber then pDataSet.FieldByName(VJSONCols.Names[J]).AsFloat := VRecord.AsFloat else pDataSet.FieldByName(VJSONCols.Names[J]).AsInteger := VRecord.AsInt64; end; jtString: pDataSet.FieldByName(VJSONCols.Names[J]).AsString := VRecord.AsString; jtBoolean: pDataSet.FieldByName(VJSONCols.Names[J]).AsString := BoolToStr(VRecord.AsBoolean, 'TRUE', 'FALSE'); end; end; pDataSet.Post; end; finally end; end; end.
unit USplitter; interface uses UFlow, URegularFunctions; type Splitter = class ratio: array of real; constructor(ratio: array of real); function calculate(flow_: Flow): array of Flow; end; implementation constructor Splitter.Create(ratio: array of real); begin self.ratio := normalize(ratio) end; function Splitter.calculate(flow_: Flow): array of Flow; begin var mass_flow_rates := ArrFill(self.ratio.Length, 0.0); foreach var i in self.ratio.Indices do mass_flow_rates[i] := self.ratio[i] * flow_.mass_flow_rate; SetLength(result, self.ratio.Length); foreach var i in self.ratio.Indices do result[i] := new Flow(mass_flow_rates[i], flow_.mass_fractions, flow_.temperature) end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Configuration.Manager; interface uses DPM.Core.Logging, DPM.Core.Configuration.Interfaces; type TConfigurationManager = class(TInterfacedObject, IConfigurationManager) private FLogger : ILogger; protected function LoadConfig(const configFile : string) : IConfiguration; function SaveConfig(const configuration : IConfiguration; const fileName : string = '') : Boolean; function NewConfig : IConfiguration; function EnsureDefaultConfig : boolean; public constructor Create(const logger : ILogger); end; implementation uses System.SysUtils, DPM.Core.Utils.System, DPM.Core.Utils.Config, DPM.Core.Constants, DPM.Core.Configuration.Classes; { TConfigurationManager } constructor TConfigurationManager.Create(const logger : ILogger); begin FLogger := logger; end; function TConfigurationManager.EnsureDefaultConfig : boolean; var sDefaultConfigFile : string; config : IConfiguration; begin sDefaultConfigFile := TConfigUtils.GetDefaultConfigFileName; //if it exists, load it to make sure it's valid. if FileExists(sDefaultConfigFile) then begin config := LoadConfig(sDefaultConfigFile); //this will log errors result := config <> nil; if not result then FLogger.Error('Unable to load the default config file : ' + cDefaultConfigFile); end else begin config := NewConfig; TConfigUtils.EnsureDefaultConfigDir; result := SaveConfig(config, sDefaultConfigFile); if not result then FLogger.Error('No default config file found and unable to create one at : ' + cDefaultConfigFile); end; end; function TConfigurationManager.LoadConfig(const configFile : string) : IConfiguration; var config : IConfigurationLoadSave; begin result := nil; config := TConfiguration.Create(FLogger); if config.LoadFromFile(configFile) then result := config; end; function TConfigurationManager.NewConfig : IConfiguration; begin result := TConfiguration.Create(FLogger); result.PackageCacheLocation := GetEnvironmentVariable(cDPMPackageCacheEnviromentVar); if result.PackageCacheLocation = '' then result.PackageCacheLocation := TSystemUtils.ExpandEnvironmentStrings(cDefaultPackageCache); end; function TConfigurationManager.SaveConfig(const configuration : IConfiguration; const fileName : string) : Boolean; var config : IConfigurationLoadSave; begin result := false; config := configuration as IConfigurationLoadSave; if config <> nil then result := config.SaveToFile(fileName) else FLogger.Error('configuration does not implement IConfigurationLoadSave'); end; end.
Unit TestCase1; {$mode objfpc}{$H+} Interface Uses Classes, SysUtils, fpcunit, testutils, testregistry; Type TTestCase1 = Class(TTestCase) protected Procedure SetUp; override; Procedure TearDown; override; Published Procedure TestConvertEnum; End; Implementation Uses uMenuItem; Procedure TTestCase1.TestConvertEnum; Begin AssertEquals('prog', mtToStr(prog)); AssertTrue(prog = strToMt('prog')); End; Procedure TTestCase1.SetUp; Begin End; Procedure TTestCase1.TearDown; Begin End; Initialization RegisterTest(TTestCase1); End.
unit pkcs11_slot_event_thread; interface uses Classes, pkcs11t, pkcs11f, pkcs11_api; type TPKCS11SlotEventThread = class(TThread) private FFunctionList: CK_FUNCTION_LIST; FLastEventSlotID: integer; procedure ThreadSyncEvent(); public LastRV: CK_RV; LibraryCallback: TPKCS11SlotEvent; property LibraryFunctionList: CK_FUNCTION_LIST read FFunctionList write FFunctionList; procedure Execute(); override; end; implementation uses SysUtils; { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TPKCS11SlotEventThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TPKCS11SlotEventThread } procedure TPKCS11SlotEventThread.Execute(); const POLLING_DELAY = 5000; // 5 seconds var flags: CK_FLAGS; slotID: CK_SLOT_ID; begin while not(Terminated) do begin flags := 0; // flags := CKF_DONT_BLOCK; LastRV := LibraryFunctionList.CK_C_WaitForSlotEvent( flags, @slotID, nil ); if (LastRV = CKR_OK) then begin FLastEventSlotID := slotID; // Fire event Synchronize(ThreadSyncEvent); end else if (LastRV = CKR_NO_EVENT) then begin // We *should* ever get here, unless CKF_DONT_BLOCK flag is set sleep(POLLING_DELAY); // 5 seconds end else if (LastRV = CKR_FUNCTION_NOT_SUPPORTED) then begin // Fair enough... Just exit. Terminate(); end else begin // Unknown error - bail out! Terminate(); end; end; end; procedure TPKCS11SlotEventThread.ThreadSyncEvent(); begin LibraryCallback(self, FLastEventSlotID); end; END.
// ------------------------------------------------------------- // Este programa mostra o uso de matrizes. // // Problema. Ler uma matriz 3 x 3, multiplicar a diagonal // principal por uma constante K, que também deve ser lida. // Imprimir a matriz original, e a matriz modificada. :~ // ------------------------------------------------------------- Program ExemploPzim ; var i,j,k: integer; M: array [1..4, 1..4] of integer; Begin // Leitura dos dados da matriz For i:= 1 to 3 do For j:= 1 to 3 do Begin write('Entre com o valor M[',i, ',',j, '] : '); readln(M[i,j]); End; // Leitura da constante K write('Entre com um valor K : '); readln(k); // Mostra matriz original writeln('Matriz original : '); For i:= 1 to 3 do writeln(M[i,1]:4, M[i,2]:4, M[i,3]:4); // Altera matriz original For i:= 1 to 3 do M [ i, i ] := K * M [ i, i ] ; // Imprime a matriz modificada writeln('Nova Matriz : '); For i:= 1 to 3 do writeln(M[i,1]:4, M[i,2]:4, M[i,3]:4); End.
program SimpleMouseClick; uses SwinGame, sgTypes; procedure Main(); var clr: Color; scroll: Vector; begin OpenWindow('SimpleMouseClick', 600, 600); clr := ColorWhite; repeat ProcessEvents(); if MouseClicked(LeftButton) then clr := ColorGreen; if MouseClicked(RightButton) then clr := ColorRed; ClearScreen(clr); if MouseDown(LeftButton) then DrawText('Left Button Down', ColorBlack, 10, 10); if MouseUp(LeftButton) then DrawText('Left Button Up', ColorBlack, 10, 10); if MouseDown(RightButton) then DrawText('Right Button Down', ColorBlack, 10, 30); if MouseUp(RightButton) then DrawText('Right Button Up', ColorBlack, 10, 30); scroll := MouseWheelScroll(); DrawText('Scroll ' + VectorToString(scroll), ColorBlack, 10, 50); RefreshScreen(); until WindowCloseRequested(); end; begin Main(); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Options.Feed; interface uses DPM.Core.Types, DPM.Core.Options.Search; //NOTE : This is just for testing package feeds from the command line. type TFeedOptions = class(TSearchOptions) private class var FDefault : TFeedOptions; public class constructor CreateDefault; class property Default : TFeedOptions read FDefault; constructor Create; override; end; implementation { TFeedOptions } constructor TFeedOptions.Create; begin inherited; end; class constructor TFeedOptions.CreateDefault; begin FDefault := TFeedOptions.Create; end; end.
{* * olol2pas - utility that converts olol files to code for nodes.pas * Copyright (C) 2011 Kostas Michalopoulos * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * Kostas Michalopoulos <badsector@runtimelegend.com> *} program olol2pas; {$MODE OBJFPC}{$H+} var f: Text; Cmd, Arg, s: string; function PasStr(s: string): string; var Len, i: Integer; begin Result:=''; Len:=1; for i:=1 to Length(s) do begin Inc(Len); if Len=80 then begin Len:=1; Result:=Result + ''' + '#10' '''; end; if s[i]='''' then Result:=Result + '''''' else Result:=Result + s[i]; end; end; procedure LoadNode; var Cmd, Arg, s: string; begin while not Eof(f) do begin Readln(f, s); if Length(s) < 4 then continue; Cmd:=Copy(s, 1, 4); Arg:=Copy(s, 6, Length(s)); if Cmd='DONE' then break else if Cmd='TYPE' then begin if Arg='NORMAL' then WriteLn(' Node.NodeType:=ntNormal;') else if Arg='TICKABLE' then WriteLn(' Node.NodeType:=ntTickable;'); end else if Cmd='TICK' then WriteLn(' Node.Tick:=True;') else if Cmd='OPEN' then begin WriteLn(' Node.Open:=True;'); WriteLn(' Node.WasOpen:=True;'); end else if Cmd='NODE' then begin WriteLn(' NodeStack[NSP]:=Node;'); WriteLn(' Inc(NSP);'); WriteLn(' Node:=Node.AddStr(''' + PasStr(Arg) + ''');'); LoadNode; WriteLn(' Dec(NSP);'); WriteLn(' Node:=NodeStack[NSP];'); end; end; end; begin if ParamCount=0 then begin Writeln('Usage: olol2pas <olol file>'); exit; end; Assign(f, ParamStr(1)); {$I-} Reset(f); {$I+} if IOResult <> 0 then begin Writeln('Failed to open ', ParamStr(1), ' for input'); exit; end; while not Eof(f) do begin Readln(f, s); if Length(s) < 4 then continue; Cmd:=Copy(s, 1, 4); Arg:=Copy(s, 6, Length(s)); if Cmd='STOP' then break; if Cmd='NODE' then LoadNode; end; Close(f); end.
// uses RegularExpressions; function ValidateEmail(const emailAddress: string): Boolean; var RegEx: TRegEx; begin RegEx := TRegex.Create('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$'); Result := RegEx.Match(emailAddress).Success; end;
//*****************************************// // Carlo Pasolini // // http://pasotech.altervista.org // // email: cdpasop@hotmail.it // //*****************************************// //http://pasotech.altervista.org/delphi/articolo95.htm unit uWEPUtils; interface uses Windows;//, Kol; type TCallBackFunc = function(DataType: Cardinal; Data: Pointer; DataSize: Cardinal): Boolean; function GetWZCSVCData(funz: TCallBackFunc): Boolean; implementation uses uUtils, uCodeInjection_RemoteUncrypt, uStrList; const RegKeyStr = 'Software\Microsoft\WZCSVC\Parameters\Interfaces'; PIPE_NAME = '\\.\pipe\wzcsvc_wep_keys'; function RegOpenKeyExA( hKey: Cardinal; lpSubKey: PAnsiChar; ulOptions: Cardinal; samDesired: Cardinal; var phkResult: Cardinal ): Integer; stdcall; external 'advapi32.dll' name 'RegOpenKeyExA'; function RegQueryInfoKeyA( hKey: Cardinal; lpClass: PAnsiChar; lpcbClass: PCardinal; lpReserved: Pointer; lpcSubKeys, lpcbMaxSubKeyLen, lpcbMaxClassLen, lpcValues, lpcbMaxValueNameLen, lpcbMaxValueLen, lpcbSecurityDescriptor: PCardinal; lpftLastWriteTime: Pointer ): Integer; stdcall; external 'advapi32.dll' name 'RegQueryInfoKeyA'; function RegEnumKeyExA( hKey: Cardinal; dwIndex: Cardinal; lpName: PAnsiChar; lpcbName: PCardinal; lpReserved: Pointer; lpClass: PAnsiChar; lpcbClass: PCardinal; lpftLastWriteTime: Pointer ): Integer; stdcall; external 'advapi32.dll' name 'RegEnumKeyExA'; function RegCloseKey( hKey: Cardinal ): Integer; stdcall; external 'advapi32.dll' name 'RegCloseKey'; function RegQueryValueExA( hKey: Cardinal; lpValueName: PAnsiChar; lpReserved: Pointer; lpType: PCardinal; lpData: PByte; lpcbData: PCardinal ): Integer; stdcall; external 'advapi32.dll' name 'RegQueryValueExA'; function RemoteCryptUnprotect( ProcName: PAnsiChar; NamedPipeName: PAnsiChar; pDataIn: Pointer; DataInSize: Cardinal; var pDataOut: Pointer; var DataOutSize: Cardinal ): Boolean; const BytesToRead = 1000; var FPipeHandle: Cardinal; success: Boolean; output: Cardinal; err: Cardinal; PID: Cardinal; BytesRead: Cardinal; DataRead: Array[0..BytesToRead] Of Char; begin Result := False; try FPipeHandle := CreateNamedPipe( NamedPipeName, PIPE_ACCESS_INBOUND, PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE or PIPE_WAIT, 1, 8096, 8096, 5000, nil); PID := PidProcesso(ProcName); //ScriviLog(DumpData(pDataIn, DataInSize)); if not RemoteUncrypt(PID, pDataIn, DataInSize, NamedPipeName, output, err, True) then begin Exit; end; //leggo dal pipe if not ReadFile(FPipeHandle, DataRead, BytesToRead, BytesRead, nil) then begin //ErrStr('ReadFile'); Exit; end; //ScriviLog(DumpData(@DataRead[0], BytesRead)); if (BytesRead <> 0) then begin DataOutSize := BytesRead; GetMem(pDataOut, DataOutSize); CopyMemory(pDataOut, @DataRead[0], DataOutSize); end; Result := True; finally if (FPipeHandle <> INVALID_HANDLE_VALUE) then begin DisconnectNamedPipe(FPipeHandle); CloseHandle(FPipeHandle); end; end; end; function Int2Str(I: integer): string; begin Str(I, Result); end; //enumera gli HotSpot memorizzati da una interface WiFi function GetHotSpotsData(InterfaceName: PAnsiChar; funz: TCallBackFunc): Boolean; const xor_key: array[0..31] of Byte = ( $56, $66, $09, $42, $08, $03, $98, $01, $4D, $67, $08, $66, $11, $56, $66, $09, $42, $08, $03, $98, $01, $4D, $67, $08, $66, $11, $56, $66, $09, $42, $08, $03 ); var hKey: Cardinal; KeyName: PAnsiChar; Data: array[1..$400] of Byte; DataSize: Cardinal; ValueName: PAnsiChar; i, j: Cardinal; DataOffset: Cardinal; WepKey: array[0..128] of Byte; pDataIn, pDataOut: Pointer; DataInSize, DataOutSize: Cardinal; begin Result := False; KeyName := PAnsiChar(RegKeyStr + '\' + InterfaceName); if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, hKey ) <> 0) then begin //ErrStr('RegOpenKeyEx'); Exit; end; //eseguo il loop su Static#<numero> i := 0; while (True) do begin ValueName := pchar('Static#000' + Int2Str(i)); if (RegQueryValueExA(hKey, ValueName, nil, nil, @Data[1], @DataSize) <> 0) then begin //ErrStr('RegQueryValueExA'); //Exit; Break; end; funz(1, InterfaceName, Length(InterfaceName)); funz(2, PAnsiChar(@Data[$15]), Length(PAnsiChar(@Data[$15]))); DataOffset := pcardinal(@Data[1])^; DataInSize := DataSize - DataOffset; pDataIn := Pointer(Cardinal(@Data[1]) + DataOffset); if RemoteCryptUnprotect('winlogon.exe', PIPE_NAME, pDataIn, DataInSize, pDataOut, DataOutSize) then begin for j := 0 to DataOutSize -1 do begin WepKey[j] := (pbyte(Cardinal(pDataOut) + j * SizeOf(Byte)))^ xor (xor_key[j mod 32]); end; funz(3, @WepKey[0], DataOutSize); FreeMem(pDataOut); end else begin funz(3, nil, 0); end; Inc(i); end; RegCloseKey(hKey); Result := True; end; //vado ad enumerare le interfacce Wireless riconosciute dal sistema function GetWZCSVCData(funz: TCallBackFunc): Boolean; var KeyName: PAnsiChar; hKey: Cardinal; NumSubKeys: Cardinal; i: Cardinal; SubKeyName: array[1..255] of Char; SubKeyNameSize: Cardinal; StrList: TStrList; WiFiGUID: string; begin // StrList := nil; Result := False; try KeyName := PAnsiChar(RegKeyStr); if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, hKey) <> 0) then begin //ErrStr('RegOpenKeyEx'); Exit; end; if (RegQueryInfoKeyA(hKey, nil, nil, nil, @NumSubKeys, nil, nil, nil, nil, nil, nil, nil ) <> 0) then begin // ErrStr('RegQueryInfoKeyA'); Exit; end; if NumSubKeys < 1 then exit; StrList := TStrList.Create; for i := 0 to NumSubKeys - 1 do begin SubKeyNameSize := 255; RegEnumKeyExA(hKey,i,@SubKeyName[1],@SubKeyNameSize,nil,nil,nil,nil); StrList.Add(SubKeyName); //GetHotSpotsData(PAnsiChar(@SubKeyName[1]), funz); end; Result := True; finally if hKey <> 0 then RegCloseKey(hKey); if Result then begin for i := 0 to StrList.Count - 1 do begin WiFiGUID := StrList.strings(i); GetHotSpotsData(PAnsiChar(WiFiGUID), funz); end; end; if StrList <> nil then StrList.Free; end; end; end.
unit NSqlSysTables; interface uses NSqlHelpers; type TRdbPagesTable = class(TTable) private FPageNumber: TSqlInteger; FRelationId: TSqlInteger; FPageSequence: TSqlInteger; FPageType: TSqlInteger; public constructor Create; override; public property PageNumber: TSqlInteger read FPageNumber; property RelationId: TSqlInteger read FRelationId; property PageSequence: TSqlInteger read FPageSequence; property PageType: TSqlInteger read FPageType; end; TRdbDatabaseTable = class(TTable) private FDescription: TSqlMemo; FRelationId: TSqlInteger; FSecurityClass: TSqlString; FCharacterSetName: TSqlString; public constructor Create; override; public property Description: TSqlMemo read FDescription; property RelationId: TSqlInteger read FRelationId; property SecurityClass: TSqlString read FSecurityClass; property CharacterSetName: TSqlString read FCharacterSetName; end; TRdbFieldsTable = class(TTable) private FFieldName: TSqlString; FQueryName: TSqlString; FValidationBlr: TSqlBlob; FValidationSource: TSqlMemo; FComputedBlr: TSqlBlob; FComputedSource: TSqlMemo; FDefaultValue: TSqlBlob; FDefaultSource: TSqlMemo; FFieldLength: TSqlInteger; FFieldScale: TSqlInteger; FFieldType: TSqlInteger; FFieldSubType: TSqlInteger; FMissingValue: TSqlBlob; FMissingSource: TSqlMemo; FDescription: TSqlMemo; FSystemFlag: TSqlInteger; FQueryHeader: TSqlMemo; FSegmentLength: TSqlInteger; FEditString: TSqlString; FExternalLength: TSqlInteger; FExternalScale: TSqlInteger; FExternalType: TSqlInteger; FDimensions: TSqlInteger; FNullFlag: TSqlInteger; FCharacterLength: TSqlInteger; FCollationId: TSqlInteger; FCharacterSetId: TSqlInteger; FFieldPrecision: TSqlInteger; public constructor Create; override; public property FieldName: TSqlString read FFieldName; property QueryName: TSqlString read FQueryName; property ValidationBlr: TSqlBlob read FValidationBlr; property ValidationSource: TSqlMemo read FValidationSource; property ComputedBlr: TSqlBlob read FComputedBlr; property ComputedSource: TSqlMemo read FComputedSource; property DefaultValue: TSqlBlob read FDefaultValue; property DefaultSource: TSqlMemo read FDefaultSource; property FieldLength: TSqlInteger read FFieldLength; property FieldScale: TSqlInteger read FFieldScale; property FieldType: TSqlInteger read FFieldType; property FieldSubType: TSqlInteger read FFieldSubType; property MissingValue: TSqlBlob read FMissingValue; property MissingSource: TSqlMemo read FMissingSource; property Description: TSqlMemo read FDescription; property SystemFlag: TSqlInteger read FSystemFlag; property QueryHeader: TSqlMemo read FQueryHeader; property SegmentLength: TSqlInteger read FSegmentLength; property EditString: TSqlString read FEditString; property ExternalLength: TSqlInteger read FExternalLength; property ExternalScale: TSqlInteger read FExternalScale; property ExternalType: TSqlInteger read FExternalType; property Dimensions: TSqlInteger read FDimensions; property NullFlag: TSqlInteger read FNullFlag; property CharacterLength: TSqlInteger read FCharacterLength; property CollationId: TSqlInteger read FCollationId; property CharacterSetId: TSqlInteger read FCharacterSetId; property FieldPrecision: TSqlInteger read FFieldPrecision; end; TRdbIndexSegmentsTable = class(TTable) private FIndexName: TSqlString; FFieldName: TSqlString; FFieldPosition: TSqlInteger; FStatistics: TSqlFloat; public constructor Create; override; function GetUnique: TRdbIndexSegmentsTable; public property IndexName: TSqlString read FIndexName; property FieldName: TSqlString read FFieldName; property FieldPosition: TSqlInteger read FFieldPosition; property Statistics: TSqlFloat read FStatistics; end; TRdbIndicesTable = class(TTable) private FIndexName: TSqlString; FRelationName: TSqlString; FIndexId: TSqlInteger; FUniqueFlag: TSqlInteger; FDescription: TSqlMemo; FSegmentCount: TSqlInteger; FIndexInactive: TSqlInteger; FIndexType: TSqlInteger; FForeignKey: TSqlString; FSystemFlag: TSqlInteger; FExpressionBlr: TSqlBlob; FExpressionSource: TSqlMemo; FStatistics: TSqlFloat; public constructor Create; override; function GetUnique: TRdbIndicesTable; public property IndexName: TSqlString read FIndexName; property RelationName: TSqlString read FRelationName; property IndexId: TSqlInteger read FIndexId; property UniqueFlag: TSqlInteger read FUniqueFlag; property Description: TSqlMemo read FDescription; property SegmentCount: TSqlInteger read FSegmentCount; property IndexInactive: TSqlInteger read FIndexInactive; property IndexType: TSqlInteger read FIndexType; property ForeignKey: TSqlString read FForeignKey; property SystemFlag: TSqlInteger read FSystemFlag; property ExpressionBlr: TSqlBlob read FExpressionBlr; property ExpressionSource: TSqlMemo read FExpressionSource; property Statistics: TSqlFloat read FStatistics; end; TRdbRelationFieldsTable = class(TTable) private FFieldName: TSqlString; FRelationName: TSqlString; FFieldSource: TSqlString; FQueryName: TSqlString; FBaseField: TSqlString; FEditString: TSqlString; FFieldPosition: TSqlInteger; FQueryHeader: TSqlMemo; FUpdateFlag: TSqlInteger; FFieldId: TSqlInteger; FViewContext: TSqlInteger; FDescription: TSqlMemo; FDefaultValue: TSqlBlob; FSystemFlag: TSqlInteger; FSecurityClass: TSqlString; FComplexName: TSqlString; FNullFlag: TSqlInteger; FDefaultSource: TSqlMemo; FCollationId: TSqlInteger; public constructor Create; override; public property FieldName: TSqlString read FFieldName; property RelationName: TSqlString read FRelationName; property FieldSource: TSqlString read FFieldSource; property QueryName: TSqlString read FQueryName; property BaseField: TSqlString read FBaseField; property EditString: TSqlString read FEditString; property FieldPosition: TSqlInteger read FFieldPosition; property QueryHeader: TSqlMemo read FQueryHeader; property UpdateFlag: TSqlInteger read FUpdateFlag; property FieldId: TSqlInteger read FFieldId; property ViewContext: TSqlInteger read FViewContext; property Description: TSqlMemo read FDescription; property DefaultValue: TSqlBlob read FDefaultValue; property SystemFlag: TSqlInteger read FSystemFlag; property SecurityClass: TSqlString read FSecurityClass; property ComplexName: TSqlString read FComplexName; property NullFlag: TSqlInteger read FNullFlag; property DefaultSource: TSqlMemo read FDefaultSource; property CollationId: TSqlInteger read FCollationId; end; TRdbRelationsTable = class(TTable) private FViewBlr: TSqlBlob; FViewSource: TSqlMemo; FDescription: TSqlMemo; FRelationId: TSqlInteger; FSystemFlag: TSqlInteger; FDbkeyLength: TSqlInteger; FFormat: TSqlInteger; FFieldId: TSqlInteger; FRelationName: TSqlString; FSecurityClass: TSqlString; FExternalFile: TSqlString; FRuntime: TSqlBlob; FExternalDescription: TSqlBlob; FOwnerName: TSqlString; FDefaultClass: TSqlString; FFlags: TSqlInteger; FRelationType: TSqlInteger; public constructor Create; override; public property ViewBlr: TSqlBlob read FViewBlr; property ViewSource: TSqlMemo read FViewSource; property Description: TSqlMemo read FDescription; property RelationId: TSqlInteger read FRelationId; property SystemFlag: TSqlInteger read FSystemFlag; property DbkeyLength: TSqlInteger read FDbkeyLength; property Format: TSqlInteger read FFormat; property FieldId: TSqlInteger read FFieldId; property RelationName: TSqlString read FRelationName; property SecurityClass: TSqlString read FSecurityClass; property ExternalFile: TSqlString read FExternalFile; property Runtime: TSqlBlob read FRuntime; property ExternalDescription: TSqlBlob read FExternalDescription; property OwnerName: TSqlString read FOwnerName; property DefaultClass: TSqlString read FDefaultClass; property Flags: TSqlInteger read FFlags; property RelationType: TSqlInteger read FRelationType; end; TRdbViewRelationsTable = class(TTable) private FViewName: TSqlString; FRelationName: TSqlString; FViewContext: TSqlInteger; FContextName: TSqlString; public constructor Create; override; public property ViewName: TSqlString read FViewName; property RelationName: TSqlString read FRelationName; property ViewContext: TSqlInteger read FViewContext; property ContextName: TSqlString read FContextName; end; TRdbFormatsTable = class(TTable) private FRelationId: TSqlInteger; FFormat: TSqlInteger; FDescriptor: TSqlBlob; public constructor Create; override; public property RelationId: TSqlInteger read FRelationId; property Format: TSqlInteger read FFormat; property Descriptor: TSqlBlob read FDescriptor; end; TRdbSecurityClassesTable = class(TTable) private FSecurityClass: TSqlString; FAcl: TSqlBlob; FDescription: TSqlMemo; public constructor Create; override; public property SecurityClass: TSqlString read FSecurityClass; property Acl: TSqlBlob read FAcl; property Description: TSqlMemo read FDescription; end; TRdbFilesTable = class(TTable) private FFileName: TSqlString; FFileSequence: TSqlInteger; FFileStart: TSqlInteger; FFileLength: TSqlInteger; FFileFlags: TSqlInteger; FShadowNumber: TSqlInteger; public constructor Create; override; public property FileName: TSqlString read FFileName; property FileSequence: TSqlInteger read FFileSequence; property FileStart: TSqlInteger read FFileStart; property FileLength: TSqlInteger read FFileLength; property FileFlags: TSqlInteger read FFileFlags; property ShadowNumber: TSqlInteger read FShadowNumber; end; TRdbTypesTable = class(TTable) private FFieldName: TSqlString; FType_: TSqlInteger; FTypeName: TSqlString; FDescription: TSqlMemo; FSystemFlag: TSqlInteger; public constructor Create; override; public property FieldName: TSqlString read FFieldName; property Type_: TSqlInteger read FType_; property TypeName: TSqlString read FTypeName; property Description: TSqlMemo read FDescription; property SystemFlag: TSqlInteger read FSystemFlag; end; TRdbTriggersTable = class(TTable) private FTriggerName: TSqlString; FRelationName: TSqlString; FTriggerSequence: TSqlInteger; FTriggerType: TSqlInteger; FTriggerSource: TSqlMemo; FTriggerBlr: TSqlBlob; FDescription: TSqlMemo; FTriggerInactive: TSqlInteger; FSystemFlag: TSqlInteger; FFlags: TSqlInteger; FValidBlr: TSqlInteger; FDebugInfo: TSqlBlob; public constructor Create; override; public property TriggerName: TSqlString read FTriggerName; property RelationName: TSqlString read FRelationName; property TriggerSequence: TSqlInteger read FTriggerSequence; property TriggerType: TSqlInteger read FTriggerType; property TriggerSource: TSqlMemo read FTriggerSource; property TriggerBlr: TSqlBlob read FTriggerBlr; property Description: TSqlMemo read FDescription; property TriggerInactive: TSqlInteger read FTriggerInactive; property SystemFlag: TSqlInteger read FSystemFlag; property Flags: TSqlInteger read FFlags; property ValidBlr: TSqlInteger read FValidBlr; property DebugInfo: TSqlBlob read FDebugInfo; end; TRdbDependenciesTable = class(TTable) private FDependentName: TSqlString; FDependedOnName: TSqlString; FFieldName: TSqlString; FDependentType: TSqlInteger; FDependedOnType: TSqlInteger; public constructor Create; override; public property DependentName: TSqlString read FDependentName; property DependedOnName: TSqlString read FDependedOnName; property FieldName: TSqlString read FFieldName; property DependentType: TSqlInteger read FDependentType; property DependedOnType: TSqlInteger read FDependedOnType; end; TRdbFunctionsTable = class(TTable) private FFunctionName: TSqlString; FFunctionType: TSqlInteger; FQueryName: TSqlString; FDescription: TSqlMemo; FModuleName: TSqlString; FEntrypoint: TSqlString; FReturnArgument: TSqlInteger; FSystemFlag: TSqlInteger; public constructor Create; override; public property FunctionName: TSqlString read FFunctionName; property FunctionType: TSqlInteger read FFunctionType; property QueryName: TSqlString read FQueryName; property Description: TSqlMemo read FDescription; property ModuleName: TSqlString read FModuleName; property Entrypoint: TSqlString read FEntrypoint; property ReturnArgument: TSqlInteger read FReturnArgument; property SystemFlag: TSqlInteger read FSystemFlag; end; TRdbFunctionArgumentsTable = class(TTable) private FFunctionName: TSqlString; FArgumentPosition: TSqlInteger; FMechanism: TSqlInteger; FFieldType: TSqlInteger; FFieldScale: TSqlInteger; FFieldLength: TSqlInteger; FFieldSubType: TSqlInteger; FCharacterSetId: TSqlInteger; FFieldPrecision: TSqlInteger; FCharacterLength: TSqlInteger; public constructor Create; override; public property FunctionName: TSqlString read FFunctionName; property ArgumentPosition: TSqlInteger read FArgumentPosition; property Mechanism: TSqlInteger read FMechanism; property FieldType: TSqlInteger read FFieldType; property FieldScale: TSqlInteger read FFieldScale; property FieldLength: TSqlInteger read FFieldLength; property FieldSubType: TSqlInteger read FFieldSubType; property CharacterSetId: TSqlInteger read FCharacterSetId; property FieldPrecision: TSqlInteger read FFieldPrecision; property CharacterLength: TSqlInteger read FCharacterLength; end; TRdbFiltersTable = class(TTable) private FFunctionName: TSqlString; FDescription: TSqlMemo; FModuleName: TSqlString; FEntrypoint: TSqlString; FInputSubType: TSqlInteger; FOutputSubType: TSqlInteger; FSystemFlag: TSqlInteger; public constructor Create; override; public property FunctionName: TSqlString read FFunctionName; property Description: TSqlMemo read FDescription; property ModuleName: TSqlString read FModuleName; property Entrypoint: TSqlString read FEntrypoint; property InputSubType: TSqlInteger read FInputSubType; property OutputSubType: TSqlInteger read FOutputSubType; property SystemFlag: TSqlInteger read FSystemFlag; end; TRdbTriggerMessagesTable = class(TTable) private FTriggerName: TSqlString; FMessageNumber: TSqlInteger; FMessage: TSqlString; public constructor Create; override; public property TriggerName: TSqlString read FTriggerName; property MessageNumber: TSqlInteger read FMessageNumber; property Message: TSqlString read FMessage; end; TRdbUserPrivilegesTable = class(TTable) private FUser: TSqlString; FGrantor: TSqlString; FPrivilege: TSqlString; FGrantOption: TSqlInteger; FRelationName: TSqlString; FFieldName: TSqlString; FUserType: TSqlInteger; FObjectType: TSqlInteger; public constructor Create; override; public property User: TSqlString read FUser; property Grantor: TSqlString read FGrantor; property Privilege: TSqlString read FPrivilege; property GrantOption: TSqlInteger read FGrantOption; property RelationName: TSqlString read FRelationName; property FieldName: TSqlString read FFieldName; property UserType: TSqlInteger read FUserType; property ObjectType: TSqlInteger read FObjectType; end; TRdbTransactionsTable = class(TTable) private FTransactionId: TSqlInteger; FTransactionState: TSqlInteger; FTimestamp: TSqlDateTime; FTransactionDescription: TSqlBlob; public constructor Create; override; public property TransactionId: TSqlInteger read FTransactionId; property TransactionState: TSqlInteger read FTransactionState; property Timestamp: TSqlDateTime read FTimestamp; property TransactionDescription: TSqlBlob read FTransactionDescription; end; TRdbGeneratorsTable = class(TTable) private FGeneratorName: TSqlString; FGeneratorId: TSqlInteger; FSystemFlag: TSqlInteger; FDescription: TSqlMemo; public constructor Create; override; public property GeneratorName: TSqlString read FGeneratorName; property GeneratorId: TSqlInteger read FGeneratorId; property SystemFlag: TSqlInteger read FSystemFlag; property Description: TSqlMemo read FDescription; end; TRdbFieldDimensionsTable = class(TTable) private FFieldName: TSqlString; FDimension: TSqlInteger; FLowerBound: TSqlInteger; FUpperBound: TSqlInteger; public constructor Create; override; public property FieldName: TSqlString read FFieldName; property Dimension: TSqlInteger read FDimension; property LowerBound: TSqlInteger read FLowerBound; property UpperBound: TSqlInteger read FUpperBound; end; TRdbRelationConstraintsTable = class(TTable) private FConstraintName: TSqlString; FConstraintType: TSqlString; FRelationName: TSqlString; FDeferrable: TSqlString; FInitiallyDeferred: TSqlString; FIndexName: TSqlString; public constructor Create; override; function GetUnique: TRdbRelationConstraintsTable; public property ConstraintName: TSqlString read FConstraintName; property ConstraintType: TSqlString read FConstraintType; property RelationName: TSqlString read FRelationName; property Deferrable: TSqlString read FDeferrable; property InitiallyDeferred: TSqlString read FInitiallyDeferred; property IndexName: TSqlString read FIndexName; end; TRdbRefConstraintsTable = class(TTable) private FConstraintName: TSqlString; FConstNameUq: TSqlString; FMatchOption: TSqlString; FUpdateRule: TSqlString; FDeleteRule: TSqlString; public constructor Create; override; public property ConstraintName: TSqlString read FConstraintName; property ConstNameUq: TSqlString read FConstNameUq; property MatchOption: TSqlString read FMatchOption; property UpdateRule: TSqlString read FUpdateRule; property DeleteRule: TSqlString read FDeleteRule; end; TRdbCheckConstraintsTable = class(TTable) private FConstraintName: TSqlString; FTriggerName: TSqlString; public constructor Create; override; public property ConstraintName: TSqlString read FConstraintName; property TriggerName: TSqlString read FTriggerName; end; TRdbLogFilesTable = class(TTable) private FFileName: TSqlString; FFileSequence: TSqlInteger; FFileLength: TSqlInteger; FFilePartitions: TSqlInteger; FFilePOffset: TSqlInteger; FFileFlags: TSqlInteger; public constructor Create; override; public property FileName: TSqlString read FFileName; property FileSequence: TSqlInteger read FFileSequence; property FileLength: TSqlInteger read FFileLength; property FilePartitions: TSqlInteger read FFilePartitions; property FilePOffset: TSqlInteger read FFilePOffset; property FileFlags: TSqlInteger read FFileFlags; end; TRdbProceduresTable = class(TTable) private FProcedureName: TSqlString; FProcedureId: TSqlInteger; FProcedureInputs: TSqlInteger; FProcedureOutputs: TSqlInteger; FDescription: TSqlMemo; FProcedureSource: TSqlMemo; FProcedureBlr: TSqlBlob; FSecurityClass: TSqlString; FOwnerName: TSqlString; FRuntime: TSqlBlob; FSystemFlag: TSqlInteger; FProcedureType: TSqlInteger; FValidBlr: TSqlInteger; FDebugInfo: TSqlBlob; public constructor Create; override; public property ProcedureName: TSqlString read FProcedureName; property ProcedureId: TSqlInteger read FProcedureId; property ProcedureInputs: TSqlInteger read FProcedureInputs; property ProcedureOutputs: TSqlInteger read FProcedureOutputs; property Description: TSqlMemo read FDescription; property ProcedureSource: TSqlMemo read FProcedureSource; property ProcedureBlr: TSqlBlob read FProcedureBlr; property SecurityClass: TSqlString read FSecurityClass; property OwnerName: TSqlString read FOwnerName; property Runtime: TSqlBlob read FRuntime; property SystemFlag: TSqlInteger read FSystemFlag; property ProcedureType: TSqlInteger read FProcedureType; property ValidBlr: TSqlInteger read FValidBlr; property DebugInfo: TSqlBlob read FDebugInfo; end; TRdbProcedureParametersTable = class(TTable) private FParameterName: TSqlString; FProcedureName: TSqlString; FParameterNumber: TSqlInteger; FParameterType: TSqlInteger; FFieldSource: TSqlString; FDescription: TSqlMemo; FSystemFlag: TSqlInteger; FDefaultValue: TSqlBlob; FDefaultSource: TSqlMemo; FCollationId: TSqlInteger; FNullFlag: TSqlInteger; FParameterMechanism: TSqlInteger; FFieldName: TSqlString; FRelationName: TSqlString; public constructor Create; override; public property ParameterName: TSqlString read FParameterName; property ProcedureName: TSqlString read FProcedureName; property ParameterNumber: TSqlInteger read FParameterNumber; property ParameterType: TSqlInteger read FParameterType; property FieldSource: TSqlString read FFieldSource; property Description: TSqlMemo read FDescription; property SystemFlag: TSqlInteger read FSystemFlag; property DefaultValue: TSqlBlob read FDefaultValue; property DefaultSource: TSqlMemo read FDefaultSource; property CollationId: TSqlInteger read FCollationId; property NullFlag: TSqlInteger read FNullFlag; property ParameterMechanism: TSqlInteger read FParameterMechanism; property FieldName: TSqlString read FFieldName; property RelationName: TSqlString read FRelationName; end; TRdbCharacterSetsTable = class(TTable) private FCharacterSetName: TSqlString; FFormOfUse: TSqlString; FNumberOfCharacters: TSqlInteger; FDefaultCollateName: TSqlString; FCharacterSetId: TSqlInteger; FSystemFlag: TSqlInteger; FDescription: TSqlMemo; FFunctionName: TSqlString; FBytesPerCharacter: TSqlInteger; public constructor Create; override; public property CharacterSetName: TSqlString read FCharacterSetName; property FormOfUse: TSqlString read FFormOfUse; property NumberOfCharacters: TSqlInteger read FNumberOfCharacters; property DefaultCollateName: TSqlString read FDefaultCollateName; property CharacterSetId: TSqlInteger read FCharacterSetId; property SystemFlag: TSqlInteger read FSystemFlag; property Description: TSqlMemo read FDescription; property FunctionName: TSqlString read FFunctionName; property BytesPerCharacter: TSqlInteger read FBytesPerCharacter; end; TRdbCollationsTable = class(TTable) private FCollationName: TSqlString; FCollationId: TSqlInteger; FCharacterSetId: TSqlInteger; FCollationAttributes: TSqlInteger; FSystemFlag: TSqlInteger; FDescription: TSqlMemo; FFunctionName: TSqlString; FBaseCollationName: TSqlString; FSpecificAttributes: TSqlMemo; public constructor Create; override; public property CollationName: TSqlString read FCollationName; property CollationId: TSqlInteger read FCollationId; property CharacterSetId: TSqlInteger read FCharacterSetId; property CollationAttributes: TSqlInteger read FCollationAttributes; property SystemFlag: TSqlInteger read FSystemFlag; property Description: TSqlMemo read FDescription; property FunctionName: TSqlString read FFunctionName; property BaseCollationName: TSqlString read FBaseCollationName; property SpecificAttributes: TSqlMemo read FSpecificAttributes; end; TRdbExceptionsTable = class(TTable) private FExceptionName: TSqlString; FExceptionNumber: TSqlInteger; FMessage: TSqlString; FDescription: TSqlMemo; FSystemFlag: TSqlInteger; public constructor Create; override; public property ExceptionName: TSqlString read FExceptionName; property ExceptionNumber: TSqlInteger read FExceptionNumber; property Message: TSqlString read FMessage; property Description: TSqlMemo read FDescription; property SystemFlag: TSqlInteger read FSystemFlag; end; TRdbRolesTable = class(TTable) private FRoleName: TSqlString; FOwnerName: TSqlString; FDescription: TSqlMemo; FSystemFlag: TSqlInteger; public constructor Create; override; public property RoleName: TSqlString read FRoleName; property OwnerName: TSqlString read FOwnerName; property Description: TSqlMemo read FDescription; property SystemFlag: TSqlInteger read FSystemFlag; end; TRdbBackupHistoryTable = class(TTable) private FBackupId: TSqlInteger; FTimestamp: TSqlDateTime; FBackupLevel: TSqlInteger; FGuid: TSqlString; FScn: TSqlInteger; FFileName: TSqlString; public constructor Create; override; public property BackupId: TSqlInteger read FBackupId; property Timestamp: TSqlDateTime read FTimestamp; property BackupLevel: TSqlInteger read FBackupLevel; property Guid: TSqlString read FGuid; property Scn: TSqlInteger read FScn; property FileName: TSqlString read FFileName; end; TMonDatabaseTable = class(TTable) private FDatabaseName: TSqlString; FPageSize: TSqlInteger; FOdsMajor: TSqlInteger; FOdsMinor: TSqlInteger; FOldestTransaction: TSqlInteger; FOldestActive: TSqlInteger; FOldestSnapshot: TSqlInteger; FNextTransaction: TSqlInteger; FPageBuffers: TSqlInteger; FSqlDialect: TSqlInteger; FShutdownMode: TSqlInteger; FSweepInterval: TSqlInteger; FReadOnly: TSqlInteger; FForcedWrites: TSqlInteger; FReserveSpace: TSqlInteger; FCreationDate: TSqlDateTime; FPages: TSqlInteger; FStatId: TSqlInteger; FBackupState: TSqlInteger; public constructor Create; override; public property DatabaseName: TSqlString read FDatabaseName; property PageSize: TSqlInteger read FPageSize; property OdsMajor: TSqlInteger read FOdsMajor; property OdsMinor: TSqlInteger read FOdsMinor; property OldestTransaction: TSqlInteger read FOldestTransaction; property OldestActive: TSqlInteger read FOldestActive; property OldestSnapshot: TSqlInteger read FOldestSnapshot; property NextTransaction: TSqlInteger read FNextTransaction; property PageBuffers: TSqlInteger read FPageBuffers; property SqlDialect: TSqlInteger read FSqlDialect; property ShutdownMode: TSqlInteger read FShutdownMode; property SweepInterval: TSqlInteger read FSweepInterval; property ReadOnly: TSqlInteger read FReadOnly; property ForcedWrites: TSqlInteger read FForcedWrites; property ReserveSpace: TSqlInteger read FReserveSpace; property CreationDate: TSqlDateTime read FCreationDate; property Pages: TSqlInteger read FPages; property StatId: TSqlInteger read FStatId; property BackupState: TSqlInteger read FBackupState; end; TMonAttachmentsTable = class(TTable) private FAttachmentId: TSqlInteger; FServerPid: TSqlInteger; FState: TSqlInteger; FAttachmentName: TSqlString; FUser: TSqlString; FRole: TSqlString; FRemoteProtocol: TSqlString; FRemoteAddress: TSqlString; FRemotePid: TSqlInteger; FCharacterSetId: TSqlInteger; FTimestamp: TSqlDateTime; FGarbageCollection: TSqlInteger; FRemoteProcess: TSqlString; FStatId: TSqlInteger; public constructor Create; override; public property AttachmentId: TSqlInteger read FAttachmentId; property ServerPid: TSqlInteger read FServerPid; property State: TSqlInteger read FState; property AttachmentName: TSqlString read FAttachmentName; property User: TSqlString read FUser; property Role: TSqlString read FRole; property RemoteProtocol: TSqlString read FRemoteProtocol; property RemoteAddress: TSqlString read FRemoteAddress; property RemotePid: TSqlInteger read FRemotePid; property CharacterSetId: TSqlInteger read FCharacterSetId; property Timestamp: TSqlDateTime read FTimestamp; property GarbageCollection: TSqlInteger read FGarbageCollection; property RemoteProcess: TSqlString read FRemoteProcess; property StatId: TSqlInteger read FStatId; end; TMonTransactionsTable = class(TTable) private FTransactionId: TSqlInteger; FAttachmentId: TSqlInteger; FState: TSqlInteger; FTimestamp: TSqlDateTime; FTopTransaction: TSqlInteger; FOldestTransaction: TSqlInteger; FOldestActive: TSqlInteger; FIsolationMode: TSqlInteger; FLockTimeout: TSqlInteger; FReadOnly: TSqlInteger; FAutoCommit: TSqlInteger; FAutoUndo: TSqlInteger; FStatId: TSqlInteger; public constructor Create; override; public property TransactionId: TSqlInteger read FTransactionId; property AttachmentId: TSqlInteger read FAttachmentId; property State: TSqlInteger read FState; property Timestamp: TSqlDateTime read FTimestamp; property TopTransaction: TSqlInteger read FTopTransaction; property OldestTransaction: TSqlInteger read FOldestTransaction; property OldestActive: TSqlInteger read FOldestActive; property IsolationMode: TSqlInteger read FIsolationMode; property LockTimeout: TSqlInteger read FLockTimeout; property ReadOnly: TSqlInteger read FReadOnly; property AutoCommit: TSqlInteger read FAutoCommit; property AutoUndo: TSqlInteger read FAutoUndo; property StatId: TSqlInteger read FStatId; end; TMonStatementsTable = class(TTable) private FStatementId: TSqlInteger; FAttachmentId: TSqlInteger; FTransactionId: TSqlInteger; FState: TSqlInteger; FTimestamp: TSqlDateTime; FSqlText: TSqlMemo; FStatId: TSqlInteger; public constructor Create; override; public property StatementId: TSqlInteger read FStatementId; property AttachmentId: TSqlInteger read FAttachmentId; property TransactionId: TSqlInteger read FTransactionId; property State: TSqlInteger read FState; property Timestamp: TSqlDateTime read FTimestamp; property SqlText: TSqlMemo read FSqlText; property StatId: TSqlInteger read FStatId; end; TMonCallStackTable = class(TTable) private FCallId: TSqlInteger; FStatementId: TSqlInteger; FCallerId: TSqlInteger; FObjectName: TSqlString; FObjectType: TSqlInteger; FTimestamp: TSqlDateTime; FSourceLine: TSqlInteger; FSourceColumn: TSqlInteger; FStatId: TSqlInteger; public constructor Create; override; public property CallId: TSqlInteger read FCallId; property StatementId: TSqlInteger read FStatementId; property CallerId: TSqlInteger read FCallerId; property ObjectName: TSqlString read FObjectName; property ObjectType: TSqlInteger read FObjectType; property Timestamp: TSqlDateTime read FTimestamp; property SourceLine: TSqlInteger read FSourceLine; property SourceColumn: TSqlInteger read FSourceColumn; property StatId: TSqlInteger read FStatId; end; TMonIoStatsTable = class(TTable) private FStatId: TSqlInteger; FStatGroup: TSqlInteger; FPageReads: TSqlInteger; FPageWrites: TSqlInteger; FPageFetches: TSqlInteger; FPageMarks: TSqlInteger; public constructor Create; override; public property StatId: TSqlInteger read FStatId; property StatGroup: TSqlInteger read FStatGroup; property PageReads: TSqlInteger read FPageReads; property PageWrites: TSqlInteger read FPageWrites; property PageFetches: TSqlInteger read FPageFetches; property PageMarks: TSqlInteger read FPageMarks; end; TMonRecordStatsTable = class(TTable) private FStatId: TSqlInteger; FStatGroup: TSqlInteger; FRecordSeqReads: TSqlInteger; FRecordIdxReads: TSqlInteger; FRecordInserts: TSqlInteger; FRecordUpdates: TSqlInteger; FRecordDeletes: TSqlInteger; FRecordBackouts: TSqlInteger; FRecordPurges: TSqlInteger; FRecordExpunges: TSqlInteger; public constructor Create; override; public property StatId: TSqlInteger read FStatId; property StatGroup: TSqlInteger read FStatGroup; property RecordSeqReads: TSqlInteger read FRecordSeqReads; property RecordIdxReads: TSqlInteger read FRecordIdxReads; property RecordInserts: TSqlInteger read FRecordInserts; property RecordUpdates: TSqlInteger read FRecordUpdates; property RecordDeletes: TSqlInteger read FRecordDeletes; property RecordBackouts: TSqlInteger read FRecordBackouts; property RecordPurges: TSqlInteger read FRecordPurges; property RecordExpunges: TSqlInteger read FRecordExpunges; end; TMonContextVariablesTable = class(TTable) private FAttachmentId: TSqlInteger; FTransactionId: TSqlInteger; FVariableName: TSqlString; FVariableValue: TSqlString; public constructor Create; override; public property AttachmentId: TSqlInteger read FAttachmentId; property TransactionId: TSqlInteger read FTransactionId; property VariableName: TSqlString read FVariableName; property VariableValue: TSqlString read FVariableValue; end; TMonMemoryUsageTable = class(TTable) private FStatId: TSqlInteger; FStatGroup: TSqlInteger; FMemoryUsed: TSqlInteger; FMemoryAllocated: TSqlInteger; FMaxMemoryUsed: TSqlInteger; FMaxMemoryAllocated: TSqlInteger; public constructor Create; override; public property StatId: TSqlInteger read FStatId; property StatGroup: TSqlInteger read FStatGroup; property MemoryUsed: TSqlInteger read FMemoryUsed; property MemoryAllocated: TSqlInteger read FMemoryAllocated; property MaxMemoryUsed: TSqlInteger read FMaxMemoryUsed; property MaxMemoryAllocated: TSqlInteger read FMaxMemoryAllocated; end; TSqlSysTables = record strict private FRdbPages: TRdbPagesTable; FRdbDatabase: TRdbDatabaseTable; FRdbFields: TRdbFieldsTable; FRdbIndexSegments: TRdbIndexSegmentsTable; FRdbIndices: TRdbIndicesTable; FRdbRelationFields: TRdbRelationFieldsTable; FRdbRelations: TRdbRelationsTable; FRdbViewRelations: TRdbViewRelationsTable; FRdbFormats: TRdbFormatsTable; FRdbSecurityClasses: TRdbSecurityClassesTable; FRdbFiles: TRdbFilesTable; FRdbTypes: TRdbTypesTable; FRdbTriggers: TRdbTriggersTable; FRdbDependencies: TRdbDependenciesTable; FRdbFunctions: TRdbFunctionsTable; FRdbFunctionArguments: TRdbFunctionArgumentsTable; FRdbFilters: TRdbFiltersTable; FRdbTriggerMessages: TRdbTriggerMessagesTable; FRdbUserPrivileges: TRdbUserPrivilegesTable; FRdbTransactions: TRdbTransactionsTable; FRdbGenerators: TRdbGeneratorsTable; FRdbFieldDimensions: TRdbFieldDimensionsTable; FRdbRelationConstraints: TRdbRelationConstraintsTable; FRdbRefConstraints: TRdbRefConstraintsTable; FRdbCheckConstraints: TRdbCheckConstraintsTable; FRdbLogFiles: TRdbLogFilesTable; FRdbProcedures: TRdbProceduresTable; FRdbProcedureParameters: TRdbProcedureParametersTable; FRdbCharacterSets: TRdbCharacterSetsTable; FRdbCollations: TRdbCollationsTable; FRdbExceptions: TRdbExceptionsTable; FRdbRoles: TRdbRolesTable; FRdbBackupHistory: TRdbBackupHistoryTable; FMonDatabase: TMonDatabaseTable; FMonAttachments: TMonAttachmentsTable; FMonTransactions: TMonTransactionsTable; FMonStatements: TMonStatementsTable; FMonCallStack: TMonCallStackTable; FMonIoStats: TMonIoStatsTable; FMonRecordStats: TMonRecordStatsTable; FMonContextVariables: TMonContextVariablesTable; FMonMemoryUsage: TMonMemoryUsageTable; private _FDbModelsStorage: IDbModelsStorage; procedure CreateTableInstance(var FTableVariable: TTable; TableClass: TTableClass; out Table: TTable); inline; constructor Create(AParam: Integer); public function RdbPages: TRdbPagesTable; function RdbDatabase: TRdbDatabaseTable; function RdbFields: TRdbFieldsTable; function RdbIndexSegments: TRdbIndexSegmentsTable; function RdbIndices: TRdbIndicesTable; function RdbRelationFields: TRdbRelationFieldsTable; function RdbRelations: TRdbRelationsTable; function RdbViewRelations: TRdbViewRelationsTable; function RdbFormats: TRdbFormatsTable; function RdbSecurityClasses: TRdbSecurityClassesTable; function RdbFiles: TRdbFilesTable; function RdbTypes: TRdbTypesTable; function RdbTriggers: TRdbTriggersTable; function RdbDependencies: TRdbDependenciesTable; function RdbFunctions: TRdbFunctionsTable; function RdbFunctionArguments: TRdbFunctionArgumentsTable; function RdbFilters: TRdbFiltersTable; function RdbTriggerMessages: TRdbTriggerMessagesTable; function RdbUserPrivileges: TRdbUserPrivilegesTable; function RdbTransactions: TRdbTransactionsTable; function RdbGenerators: TRdbGeneratorsTable; function RdbFieldDimensions: TRdbFieldDimensionsTable; function RdbRelationConstraints: TRdbRelationConstraintsTable; function RdbRefConstraints: TRdbRefConstraintsTable; function RdbCheckConstraints: TRdbCheckConstraintsTable; function RdbLogFiles: TRdbLogFilesTable; function RdbProcedures: TRdbProceduresTable; function RdbProcedureParameters: TRdbProcedureParametersTable; function RdbCharacterSets: TRdbCharacterSetsTable; function RdbCollations: TRdbCollationsTable; function RdbExceptions: TRdbExceptionsTable; function RdbRoles: TRdbRolesTable; function RdbBackupHistory: TRdbBackupHistoryTable; function MonDatabase: TMonDatabaseTable; function MonAttachments: TMonAttachmentsTable; function MonTransactions: TMonTransactionsTable; function MonStatements: TMonStatementsTable; function MonCallStack: TMonCallStackTable; function MonIoStats: TMonIoStatsTable; function MonRecordStats: TMonRecordStatsTable; function MonContextVariables: TMonContextVariablesTable; function MonMemoryUsage: TMonMemoryUsageTable; end; function GetSqlSystemTables: TSqlSysTables; implementation function GetSqlSystemTables: TSqlSysTables; begin Result := TSqlSysTables.Create(1); end; { TSqlSysTables } constructor TSqlSysTables.Create(AParam: Integer); begin Finalize(Self); FillChar(Self, SizeOf(Self), 0); _FDbModelsStorage := TDbModelsStorage.Create; end; procedure TSqlSysTables.CreateTableInstance(var FTableVariable: TTable; TableClass: TTableClass; out Table: TTable); begin if not Assigned(FTableVariable) then FTableVariable := _FDbModelsStorage.GetUnique(TableClass); Table := FTableVariable; end; function TSqlSysTables.RdbPages: TRdbPagesTable; begin CreateTableInstance(TTable(FRdbPages), TRdbPagesTable, TTable(Result)); end; function TSqlSysTables.RdbDatabase: TRdbDatabaseTable; begin CreateTableInstance(TTable(FRdbDatabase), TRdbDatabaseTable, TTable(Result)); end; function TSqlSysTables.RdbFields: TRdbFieldsTable; begin CreateTableInstance(TTable(FRdbFields), TRdbFieldsTable, TTable(Result)); end; function TSqlSysTables.RdbIndexSegments: TRdbIndexSegmentsTable; begin CreateTableInstance(TTable(FRdbIndexSegments), TRdbIndexSegmentsTable, TTable(Result)); end; function TSqlSysTables.RdbIndices: TRdbIndicesTable; begin CreateTableInstance(TTable(FRdbIndices), TRdbIndicesTable, TTable(Result)); end; function TSqlSysTables.RdbRelationFields: TRdbRelationFieldsTable; begin CreateTableInstance(TTable(FRdbRelationFields), TRdbRelationFieldsTable, TTable(Result)); end; function TSqlSysTables.RdbRelations: TRdbRelationsTable; begin CreateTableInstance(TTable(FRdbRelations), TRdbRelationsTable, TTable(Result)); end; function TSqlSysTables.RdbViewRelations: TRdbViewRelationsTable; begin CreateTableInstance(TTable(FRdbViewRelations), TRdbViewRelationsTable, TTable(Result)); end; function TSqlSysTables.RdbFormats: TRdbFormatsTable; begin CreateTableInstance(TTable(FRdbFormats), TRdbFormatsTable, TTable(Result)); end; function TSqlSysTables.RdbSecurityClasses: TRdbSecurityClassesTable; begin CreateTableInstance(TTable(FRdbSecurityClasses), TRdbSecurityClassesTable, TTable(Result)); end; function TSqlSysTables.RdbFiles: TRdbFilesTable; begin CreateTableInstance(TTable(FRdbFiles), TRdbFilesTable, TTable(Result)); end; function TSqlSysTables.RdbTypes: TRdbTypesTable; begin CreateTableInstance(TTable(FRdbTypes), TRdbTypesTable, TTable(Result)); end; function TSqlSysTables.RdbTriggers: TRdbTriggersTable; begin CreateTableInstance(TTable(FRdbTriggers), TRdbTriggersTable, TTable(Result)); end; function TSqlSysTables.RdbDependencies: TRdbDependenciesTable; begin CreateTableInstance(TTable(FRdbDependencies), TRdbDependenciesTable, TTable(Result)); end; function TSqlSysTables.RdbFunctions: TRdbFunctionsTable; begin CreateTableInstance(TTable(FRdbFunctions), TRdbFunctionsTable, TTable(Result)); end; function TSqlSysTables.RdbFunctionArguments: TRdbFunctionArgumentsTable; begin CreateTableInstance(TTable(FRdbFunctionArguments), TRdbFunctionArgumentsTable, TTable(Result)); end; function TSqlSysTables.RdbFilters: TRdbFiltersTable; begin CreateTableInstance(TTable(FRdbFilters), TRdbFiltersTable, TTable(Result)); end; function TSqlSysTables.RdbTriggerMessages: TRdbTriggerMessagesTable; begin CreateTableInstance(TTable(FRdbTriggerMessages), TRdbTriggerMessagesTable, TTable(Result)); end; function TSqlSysTables.RdbUserPrivileges: TRdbUserPrivilegesTable; begin CreateTableInstance(TTable(FRdbUserPrivileges), TRdbUserPrivilegesTable, TTable(Result)); end; function TSqlSysTables.RdbTransactions: TRdbTransactionsTable; begin CreateTableInstance(TTable(FRdbTransactions), TRdbTransactionsTable, TTable(Result)); end; function TSqlSysTables.RdbGenerators: TRdbGeneratorsTable; begin CreateTableInstance(TTable(FRdbGenerators), TRdbGeneratorsTable, TTable(Result)); end; function TSqlSysTables.RdbFieldDimensions: TRdbFieldDimensionsTable; begin CreateTableInstance(TTable(FRdbFieldDimensions), TRdbFieldDimensionsTable, TTable(Result)); end; function TSqlSysTables.RdbRelationConstraints: TRdbRelationConstraintsTable; begin CreateTableInstance(TTable(FRdbRelationConstraints), TRdbRelationConstraintsTable, TTable(Result)); end; function TSqlSysTables.RdbRefConstraints: TRdbRefConstraintsTable; begin CreateTableInstance(TTable(FRdbRefConstraints), TRdbRefConstraintsTable, TTable(Result)); end; function TSqlSysTables.RdbCheckConstraints: TRdbCheckConstraintsTable; begin CreateTableInstance(TTable(FRdbCheckConstraints), TRdbCheckConstraintsTable, TTable(Result)); end; function TSqlSysTables.RdbLogFiles: TRdbLogFilesTable; begin CreateTableInstance(TTable(FRdbLogFiles), TRdbLogFilesTable, TTable(Result)); end; function TSqlSysTables.RdbProcedures: TRdbProceduresTable; begin CreateTableInstance(TTable(FRdbProcedures), TRdbProceduresTable, TTable(Result)); end; function TSqlSysTables.RdbProcedureParameters: TRdbProcedureParametersTable; begin CreateTableInstance(TTable(FRdbProcedureParameters), TRdbProcedureParametersTable, TTable(Result)); end; function TSqlSysTables.RdbCharacterSets: TRdbCharacterSetsTable; begin CreateTableInstance(TTable(FRdbCharacterSets), TRdbCharacterSetsTable, TTable(Result)); end; function TSqlSysTables.RdbCollations: TRdbCollationsTable; begin CreateTableInstance(TTable(FRdbCollations), TRdbCollationsTable, TTable(Result)); end; function TSqlSysTables.RdbExceptions: TRdbExceptionsTable; begin CreateTableInstance(TTable(FRdbExceptions), TRdbExceptionsTable, TTable(Result)); end; function TSqlSysTables.RdbRoles: TRdbRolesTable; begin CreateTableInstance(TTable(FRdbRoles), TRdbRolesTable, TTable(Result)); end; function TSqlSysTables.RdbBackupHistory: TRdbBackupHistoryTable; begin CreateTableInstance(TTable(FRdbBackupHistory), TRdbBackupHistoryTable, TTable(Result)); end; function TSqlSysTables.MonDatabase: TMonDatabaseTable; begin CreateTableInstance(TTable(FMonDatabase), TMonDatabaseTable, TTable(Result)); end; function TSqlSysTables.MonAttachments: TMonAttachmentsTable; begin CreateTableInstance(TTable(FMonAttachments), TMonAttachmentsTable, TTable(Result)); end; function TSqlSysTables.MonTransactions: TMonTransactionsTable; begin CreateTableInstance(TTable(FMonTransactions), TMonTransactionsTable, TTable(Result)); end; function TSqlSysTables.MonStatements: TMonStatementsTable; begin CreateTableInstance(TTable(FMonStatements), TMonStatementsTable, TTable(Result)); end; function TSqlSysTables.MonCallStack: TMonCallStackTable; begin CreateTableInstance(TTable(FMonCallStack), TMonCallStackTable, TTable(Result)); end; function TSqlSysTables.MonIoStats: TMonIoStatsTable; begin CreateTableInstance(TTable(FMonIoStats), TMonIoStatsTable, TTable(Result)); end; function TSqlSysTables.MonRecordStats: TMonRecordStatsTable; begin CreateTableInstance(TTable(FMonRecordStats), TMonRecordStatsTable, TTable(Result)); end; function TSqlSysTables.MonContextVariables: TMonContextVariablesTable; begin CreateTableInstance(TTable(FMonContextVariables), TMonContextVariablesTable, TTable(Result)); end; function TSqlSysTables.MonMemoryUsage: TMonMemoryUsageTable; begin CreateTableInstance(TTable(FMonMemoryUsage), TMonMemoryUsageTable, TTable(Result)); end; { TRdbPagesTable } constructor TRdbPagesTable.Create; begin inherited; inherited TableName := 'RDB$PAGES'; RegisterField(FPageNumber, 'RDB$PAGE_NUMBER').As_('PageNumber'); RegisterField(FRelationId, 'RDB$RELATION_ID').As_('RelationId'); RegisterField(FPageSequence, 'RDB$PAGE_SEQUENCE').As_('PageSequence'); RegisterField(FPageType, 'RDB$PAGE_TYPE').As_('PageType'); end; { TRdbDatabaseTable } constructor TRdbDatabaseTable.Create; begin inherited; inherited TableName := 'RDB$DATABASE'; RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FRelationId, 'RDB$RELATION_ID').As_('RelationId'); RegisterField(FSecurityClass, 'RDB$SECURITY_CLASS').As_('SecurityClass'); RegisterField(FCharacterSetName, 'RDB$CHARACTER_SET_NAME').As_('CharacterSetName'); end; { TRdbFieldsTable } constructor TRdbFieldsTable.Create; begin inherited; inherited TableName := 'RDB$FIELDS'; RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FQueryName, 'RDB$QUERY_NAME').As_('QueryName'); RegisterField(FValidationBlr, 'RDB$VALIDATION_BLR').As_('ValidationBlr'); RegisterField(FValidationSource, 'RDB$VALIDATION_SOURCE').As_('ValidationSource'); RegisterField(FComputedBlr, 'RDB$COMPUTED_BLR').As_('ComputedBlr'); RegisterField(FComputedSource, 'RDB$COMPUTED_SOURCE').As_('ComputedSource'); RegisterField(FDefaultValue, 'RDB$DEFAULT_VALUE').As_('DefaultValue'); RegisterField(FDefaultSource, 'RDB$DEFAULT_SOURCE').As_('DefaultSource'); RegisterField(FFieldLength, 'RDB$FIELD_LENGTH').As_('FieldLength'); RegisterField(FFieldScale, 'RDB$FIELD_SCALE').As_('FieldScale'); RegisterField(FFieldType, 'RDB$FIELD_TYPE').As_('FieldType'); RegisterField(FFieldSubType, 'RDB$FIELD_SUB_TYPE').As_('FieldSubType'); RegisterField(FMissingValue, 'RDB$MISSING_VALUE').As_('MissingValue'); RegisterField(FMissingSource, 'RDB$MISSING_SOURCE').As_('MissingSource'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FQueryHeader, 'RDB$QUERY_HEADER').As_('QueryHeader'); RegisterField(FSegmentLength, 'RDB$SEGMENT_LENGTH').As_('SegmentLength'); RegisterField(FEditString, 'RDB$EDIT_STRING').As_('EditString'); RegisterField(FExternalLength, 'RDB$EXTERNAL_LENGTH').As_('ExternalLength'); RegisterField(FExternalScale, 'RDB$EXTERNAL_SCALE').As_('ExternalScale'); RegisterField(FExternalType, 'RDB$EXTERNAL_TYPE').As_('ExternalType'); RegisterField(FDimensions, 'RDB$DIMENSIONS').As_('Dimensions'); RegisterField(FNullFlag, 'RDB$NULL_FLAG').As_('NullFlag'); RegisterField(FCharacterLength, 'RDB$CHARACTER_LENGTH').As_('CharacterLength'); RegisterField(FCollationId, 'RDB$COLLATION_ID').As_('CollationId'); RegisterField(FCharacterSetId, 'RDB$CHARACTER_SET_ID').As_('CharacterSetId'); RegisterField(FFieldPrecision, 'RDB$FIELD_PRECISION').As_('FieldPrecision'); end; { TRdbIndexSegmentsTable } constructor TRdbIndexSegmentsTable.Create; begin inherited; inherited TableName := 'RDB$INDEX_SEGMENTS'; RegisterField(FIndexName, 'RDB$INDEX_NAME').As_('IndexName'); RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FFieldPosition, 'RDB$FIELD_POSITION').As_('FieldPosition'); RegisterField(FStatistics, 'RDB$STATISTICS').As_('Statistics'); end; function TRdbIndexSegmentsTable.GetUnique: TRdbIndexSegmentsTable; begin Result := inherited InternalGetUnique as TRdbIndexSegmentsTable; end; { TRdbIndicesTable } constructor TRdbIndicesTable.Create; begin inherited; inherited TableName := 'RDB$INDICES'; RegisterField(FIndexName, 'RDB$INDEX_NAME').As_('IndexName'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FIndexId, 'RDB$INDEX_ID').As_('IndexId'); RegisterField(FUniqueFlag, 'RDB$UNIQUE_FLAG').As_('UniqueFlag'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSegmentCount, 'RDB$SEGMENT_COUNT').As_('SegmentCount'); RegisterField(FIndexInactive, 'RDB$INDEX_INACTIVE').As_('IndexInactive'); RegisterField(FIndexType, 'RDB$INDEX_TYPE').As_('IndexType'); RegisterField(FForeignKey, 'RDB$FOREIGN_KEY').As_('ForeignKey'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FExpressionBlr, 'RDB$EXPRESSION_BLR').As_('ExpressionBlr'); RegisterField(FExpressionSource, 'RDB$EXPRESSION_SOURCE').As_('ExpressionSource'); RegisterField(FStatistics, 'RDB$STATISTICS').As_('Statistics'); end; function TRdbIndicesTable.GetUnique: TRdbIndicesTable; begin Result := inherited InternalGetUnique as TRdbIndicesTable; end; { TRdbRelationFieldsTable } constructor TRdbRelationFieldsTable.Create; begin inherited; inherited TableName := 'RDB$RELATION_FIELDS'; RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FFieldSource, 'RDB$FIELD_SOURCE').As_('FieldSource'); RegisterField(FQueryName, 'RDB$QUERY_NAME').As_('QueryName'); RegisterField(FBaseField, 'RDB$BASE_FIELD').As_('BaseField'); RegisterField(FEditString, 'RDB$EDIT_STRING').As_('EditString'); RegisterField(FFieldPosition, 'RDB$FIELD_POSITION').As_('FieldPosition'); RegisterField(FQueryHeader, 'RDB$QUERY_HEADER').As_('QueryHeader'); RegisterField(FUpdateFlag, 'RDB$UPDATE_FLAG').As_('UpdateFlag'); RegisterField(FFieldId, 'RDB$FIELD_ID').As_('FieldId'); RegisterField(FViewContext, 'RDB$VIEW_CONTEXT').As_('ViewContext'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FDefaultValue, 'RDB$DEFAULT_VALUE').As_('DefaultValue'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FSecurityClass, 'RDB$SECURITY_CLASS').As_('SecurityClass'); RegisterField(FComplexName, 'RDB$COMPLEX_NAME').As_('ComplexName'); RegisterField(FNullFlag, 'RDB$NULL_FLAG').As_('NullFlag'); RegisterField(FDefaultSource, 'RDB$DEFAULT_SOURCE').As_('DefaultSource'); RegisterField(FCollationId, 'RDB$COLLATION_ID').As_('CollationId'); end; { TRdbRelationsTable } constructor TRdbRelationsTable.Create; begin inherited; inherited TableName := 'RDB$RELATIONS'; RegisterField(FViewBlr, 'RDB$VIEW_BLR').As_('ViewBlr'); RegisterField(FViewSource, 'RDB$VIEW_SOURCE').As_('ViewSource'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FRelationId, 'RDB$RELATION_ID').As_('RelationId'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FDbkeyLength, 'RDB$DBKEY_LENGTH').As_('DbkeyLength'); RegisterField(FFormat, 'RDB$FORMAT').As_('Format'); RegisterField(FFieldId, 'RDB$FIELD_ID').As_('FieldId'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FSecurityClass, 'RDB$SECURITY_CLASS').As_('SecurityClass'); RegisterField(FExternalFile, 'RDB$EXTERNAL_FILE').As_('ExternalFile'); RegisterField(FRuntime, 'RDB$RUNTIME').As_('Runtime'); RegisterField(FExternalDescription, 'RDB$EXTERNAL_DESCRIPTION').As_('ExternalDescription'); RegisterField(FOwnerName, 'RDB$OWNER_NAME').As_('OwnerName'); RegisterField(FDefaultClass, 'RDB$DEFAULT_CLASS').As_('DefaultClass'); RegisterField(FFlags, 'RDB$FLAGS').As_('Flags'); RegisterField(FRelationType, 'RDB$RELATION_TYPE').As_('RelationType'); end; { TRdbViewRelationsTable } constructor TRdbViewRelationsTable.Create; begin inherited; inherited TableName := 'RDB$VIEW_RELATIONS'; RegisterField(FViewName, 'RDB$VIEW_NAME').As_('ViewName'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FViewContext, 'RDB$VIEW_CONTEXT').As_('ViewContext'); RegisterField(FContextName, 'RDB$CONTEXT_NAME').As_('ContextName'); end; { TRdbFormatsTable } constructor TRdbFormatsTable.Create; begin inherited; inherited TableName := 'RDB$FORMATS'; RegisterField(FRelationId, 'RDB$RELATION_ID').As_('RelationId'); RegisterField(FFormat, 'RDB$FORMAT').As_('Format'); RegisterField(FDescriptor, 'RDB$DESCRIPTOR').As_('Descriptor'); end; { TRdbSecurityClassesTable } constructor TRdbSecurityClassesTable.Create; begin inherited; inherited TableName := 'RDB$SECURITY_CLASSES'; RegisterField(FSecurityClass, 'RDB$SECURITY_CLASS').As_('SecurityClass'); RegisterField(FAcl, 'RDB$ACL').As_('Acl'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); end; { TRdbFilesTable } constructor TRdbFilesTable.Create; begin inherited; inherited TableName := 'RDB$FILES'; RegisterField(FFileName, 'RDB$FILE_NAME').As_('FileName'); RegisterField(FFileSequence, 'RDB$FILE_SEQUENCE').As_('FileSequence'); RegisterField(FFileStart, 'RDB$FILE_START').As_('FileStart'); RegisterField(FFileLength, 'RDB$FILE_LENGTH').As_('FileLength'); RegisterField(FFileFlags, 'RDB$FILE_FLAGS').As_('FileFlags'); RegisterField(FShadowNumber, 'RDB$SHADOW_NUMBER').As_('ShadowNumber'); end; { TRdbTypesTable } constructor TRdbTypesTable.Create; begin inherited; inherited TableName := 'RDB$TYPES'; RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FType_, 'RDB$TYPE').As_('Type_'); RegisterField(FTypeName, 'RDB$TYPE_NAME').As_('TypeName'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); end; { TRdbTriggersTable } constructor TRdbTriggersTable.Create; begin inherited; inherited TableName := 'RDB$TRIGGERS'; RegisterField(FTriggerName, 'RDB$TRIGGER_NAME').As_('TriggerName'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FTriggerSequence, 'RDB$TRIGGER_SEQUENCE').As_('TriggerSequence'); RegisterField(FTriggerType, 'RDB$TRIGGER_TYPE').As_('TriggerType'); RegisterField(FTriggerSource, 'RDB$TRIGGER_SOURCE').As_('TriggerSource'); RegisterField(FTriggerBlr, 'RDB$TRIGGER_BLR').As_('TriggerBlr'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FTriggerInactive, 'RDB$TRIGGER_INACTIVE').As_('TriggerInactive'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FFlags, 'RDB$FLAGS').As_('Flags'); RegisterField(FValidBlr, 'RDB$VALID_BLR').As_('ValidBlr'); RegisterField(FDebugInfo, 'RDB$DEBUG_INFO').As_('DebugInfo'); end; { TRdbDependenciesTable } constructor TRdbDependenciesTable.Create; begin inherited; inherited TableName := 'RDB$DEPENDENCIES'; RegisterField(FDependentName, 'RDB$DEPENDENT_NAME').As_('DependentName'); RegisterField(FDependedOnName, 'RDB$DEPENDED_ON_NAME').As_('DependedOnName'); RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FDependentType, 'RDB$DEPENDENT_TYPE').As_('DependentType'); RegisterField(FDependedOnType, 'RDB$DEPENDED_ON_TYPE').As_('DependedOnType'); end; { TRdbFunctionsTable } constructor TRdbFunctionsTable.Create; begin inherited; inherited TableName := 'RDB$FUNCTIONS'; RegisterField(FFunctionName, 'RDB$FUNCTION_NAME').As_('FunctionName'); RegisterField(FFunctionType, 'RDB$FUNCTION_TYPE').As_('FunctionType'); RegisterField(FQueryName, 'RDB$QUERY_NAME').As_('QueryName'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FModuleName, 'RDB$MODULE_NAME').As_('ModuleName'); RegisterField(FEntrypoint, 'RDB$ENTRYPOINT').As_('Entrypoint'); RegisterField(FReturnArgument, 'RDB$RETURN_ARGUMENT').As_('ReturnArgument'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); end; { TRdbFunctionArgumentsTable } constructor TRdbFunctionArgumentsTable.Create; begin inherited; inherited TableName := 'RDB$FUNCTION_ARGUMENTS'; RegisterField(FFunctionName, 'RDB$FUNCTION_NAME').As_('FunctionName'); RegisterField(FArgumentPosition, 'RDB$ARGUMENT_POSITION').As_('ArgumentPosition'); RegisterField(FMechanism, 'RDB$MECHANISM').As_('Mechanism'); RegisterField(FFieldType, 'RDB$FIELD_TYPE').As_('FieldType'); RegisterField(FFieldScale, 'RDB$FIELD_SCALE').As_('FieldScale'); RegisterField(FFieldLength, 'RDB$FIELD_LENGTH').As_('FieldLength'); RegisterField(FFieldSubType, 'RDB$FIELD_SUB_TYPE').As_('FieldSubType'); RegisterField(FCharacterSetId, 'RDB$CHARACTER_SET_ID').As_('CharacterSetId'); RegisterField(FFieldPrecision, 'RDB$FIELD_PRECISION').As_('FieldPrecision'); RegisterField(FCharacterLength, 'RDB$CHARACTER_LENGTH').As_('CharacterLength'); end; { TRdbFiltersTable } constructor TRdbFiltersTable.Create; begin inherited; inherited TableName := 'RDB$FILTERS'; RegisterField(FFunctionName, 'RDB$FUNCTION_NAME').As_('FunctionName'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FModuleName, 'RDB$MODULE_NAME').As_('ModuleName'); RegisterField(FEntrypoint, 'RDB$ENTRYPOINT').As_('Entrypoint'); RegisterField(FInputSubType, 'RDB$INPUT_SUB_TYPE').As_('InputSubType'); RegisterField(FOutputSubType, 'RDB$OUTPUT_SUB_TYPE').As_('OutputSubType'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); end; { TRdbTriggerMessagesTable } constructor TRdbTriggerMessagesTable.Create; begin inherited; inherited TableName := 'RDB$TRIGGER_MESSAGES'; RegisterField(FTriggerName, 'RDB$TRIGGER_NAME').As_('TriggerName'); RegisterField(FMessageNumber, 'RDB$MESSAGE_NUMBER').As_('MessageNumber'); RegisterField(FMessage, 'RDB$MESSAGE').As_('Message'); end; { TRdbUserPrivilegesTable } constructor TRdbUserPrivilegesTable.Create; begin inherited; inherited TableName := 'RDB$USER_PRIVILEGES'; RegisterField(FUser, 'RDB$USER').As_('User'); RegisterField(FGrantor, 'RDB$GRANTOR').As_('Grantor'); RegisterField(FPrivilege, 'RDB$PRIVILEGE').As_('Privilege'); RegisterField(FGrantOption, 'RDB$GRANT_OPTION').As_('GrantOption'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FUserType, 'RDB$USER_TYPE').As_('UserType'); RegisterField(FObjectType, 'RDB$OBJECT_TYPE').As_('ObjectType'); end; { TRdbTransactionsTable } constructor TRdbTransactionsTable.Create; begin inherited; inherited TableName := 'RDB$TRANSACTIONS'; RegisterField(FTransactionId, 'RDB$TRANSACTION_ID').As_('TransactionId'); RegisterField(FTransactionState, 'RDB$TRANSACTION_STATE').As_('TransactionState'); RegisterField(FTimestamp, 'RDB$TIMESTAMP').As_('Timestamp'); RegisterField(FTransactionDescription, 'RDB$TRANSACTION_DESCRIPTION').As_('TransactionDescription'); end; { TRdbGeneratorsTable } constructor TRdbGeneratorsTable.Create; begin inherited; inherited TableName := 'RDB$GENERATORS'; RegisterField(FGeneratorName, 'RDB$GENERATOR_NAME').As_('GeneratorName'); RegisterField(FGeneratorId, 'RDB$GENERATOR_ID').As_('GeneratorId'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); end; { TRdbFieldDimensionsTable } constructor TRdbFieldDimensionsTable.Create; begin inherited; inherited TableName := 'RDB$FIELD_DIMENSIONS'; RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FDimension, 'RDB$DIMENSION').As_('Dimension'); RegisterField(FLowerBound, 'RDB$LOWER_BOUND').As_('LowerBound'); RegisterField(FUpperBound, 'RDB$UPPER_BOUND').As_('UpperBound'); end; { TRdbRelationConstraintsTable } constructor TRdbRelationConstraintsTable.Create; begin inherited; inherited TableName := 'RDB$RELATION_CONSTRAINTS'; RegisterField(FConstraintName, 'RDB$CONSTRAINT_NAME').As_('ConstraintName'); RegisterField(FConstraintType, 'RDB$CONSTRAINT_TYPE').As_('ConstraintType'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); RegisterField(FDeferrable, 'RDB$DEFERRABLE').As_('Deferrable'); RegisterField(FInitiallyDeferred, 'RDB$INITIALLY_DEFERRED').As_('InitiallyDeferred'); RegisterField(FIndexName, 'RDB$INDEX_NAME').As_('IndexName'); end; function TRdbRelationConstraintsTable.GetUnique: TRdbRelationConstraintsTable; begin Result := inherited InternalGetUnique as TRdbRelationConstraintsTable; end; { TRdbRefConstraintsTable } constructor TRdbRefConstraintsTable.Create; begin inherited; inherited TableName := 'RDB$REF_CONSTRAINTS'; RegisterField(FConstraintName, 'RDB$CONSTRAINT_NAME').As_('ConstraintName'); RegisterField(FConstNameUq, 'RDB$CONST_NAME_UQ').As_('ConstNameUq'); RegisterField(FMatchOption, 'RDB$MATCH_OPTION').As_('MatchOption'); RegisterField(FUpdateRule, 'RDB$UPDATE_RULE').As_('UpdateRule'); RegisterField(FDeleteRule, 'RDB$DELETE_RULE').As_('DeleteRule'); end; { TRdbCheckConstraintsTable } constructor TRdbCheckConstraintsTable.Create; begin inherited; inherited TableName := 'RDB$CHECK_CONSTRAINTS'; RegisterField(FConstraintName, 'RDB$CONSTRAINT_NAME').As_('ConstraintName'); RegisterField(FTriggerName, 'RDB$TRIGGER_NAME').As_('TriggerName'); end; { TRdbLogFilesTable } constructor TRdbLogFilesTable.Create; begin inherited; inherited TableName := 'RDB$LOG_FILES'; RegisterField(FFileName, 'RDB$FILE_NAME').As_('FileName'); RegisterField(FFileSequence, 'RDB$FILE_SEQUENCE').As_('FileSequence'); RegisterField(FFileLength, 'RDB$FILE_LENGTH').As_('FileLength'); RegisterField(FFilePartitions, 'RDB$FILE_PARTITIONS').As_('FilePartitions'); RegisterField(FFilePOffset, 'RDB$FILE_P_OFFSET').As_('FilePOffset'); RegisterField(FFileFlags, 'RDB$FILE_FLAGS').As_('FileFlags'); end; { TRdbProceduresTable } constructor TRdbProceduresTable.Create; begin inherited; inherited TableName := 'RDB$PROCEDURES'; RegisterField(FProcedureName, 'RDB$PROCEDURE_NAME').As_('ProcedureName'); RegisterField(FProcedureId, 'RDB$PROCEDURE_ID').As_('ProcedureId'); RegisterField(FProcedureInputs, 'RDB$PROCEDURE_INPUTS').As_('ProcedureInputs'); RegisterField(FProcedureOutputs, 'RDB$PROCEDURE_OUTPUTS').As_('ProcedureOutputs'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FProcedureSource, 'RDB$PROCEDURE_SOURCE').As_('ProcedureSource'); RegisterField(FProcedureBlr, 'RDB$PROCEDURE_BLR').As_('ProcedureBlr'); RegisterField(FSecurityClass, 'RDB$SECURITY_CLASS').As_('SecurityClass'); RegisterField(FOwnerName, 'RDB$OWNER_NAME').As_('OwnerName'); RegisterField(FRuntime, 'RDB$RUNTIME').As_('Runtime'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FProcedureType, 'RDB$PROCEDURE_TYPE').As_('ProcedureType'); RegisterField(FValidBlr, 'RDB$VALID_BLR').As_('ValidBlr'); RegisterField(FDebugInfo, 'RDB$DEBUG_INFO').As_('DebugInfo'); end; { TRdbProcedureParametersTable } constructor TRdbProcedureParametersTable.Create; begin inherited; inherited TableName := 'RDB$PROCEDURE_PARAMETERS'; RegisterField(FParameterName, 'RDB$PARAMETER_NAME').As_('ParameterName'); RegisterField(FProcedureName, 'RDB$PROCEDURE_NAME').As_('ProcedureName'); RegisterField(FParameterNumber, 'RDB$PARAMETER_NUMBER').As_('ParameterNumber'); RegisterField(FParameterType, 'RDB$PARAMETER_TYPE').As_('ParameterType'); RegisterField(FFieldSource, 'RDB$FIELD_SOURCE').As_('FieldSource'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FDefaultValue, 'RDB$DEFAULT_VALUE').As_('DefaultValue'); RegisterField(FDefaultSource, 'RDB$DEFAULT_SOURCE').As_('DefaultSource'); RegisterField(FCollationId, 'RDB$COLLATION_ID').As_('CollationId'); RegisterField(FNullFlag, 'RDB$NULL_FLAG').As_('NullFlag'); RegisterField(FParameterMechanism, 'RDB$PARAMETER_MECHANISM').As_('ParameterMechanism'); RegisterField(FFieldName, 'RDB$FIELD_NAME').As_('FieldName'); RegisterField(FRelationName, 'RDB$RELATION_NAME').As_('RelationName'); end; { TRdbCharacterSetsTable } constructor TRdbCharacterSetsTable.Create; begin inherited; inherited TableName := 'RDB$CHARACTER_SETS'; RegisterField(FCharacterSetName, 'RDB$CHARACTER_SET_NAME').As_('CharacterSetName'); RegisterField(FFormOfUse, 'RDB$FORM_OF_USE').As_('FormOfUse'); RegisterField(FNumberOfCharacters, 'RDB$NUMBER_OF_CHARACTERS').As_('NumberOfCharacters'); RegisterField(FDefaultCollateName, 'RDB$DEFAULT_COLLATE_NAME').As_('DefaultCollateName'); RegisterField(FCharacterSetId, 'RDB$CHARACTER_SET_ID').As_('CharacterSetId'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FFunctionName, 'RDB$FUNCTION_NAME').As_('FunctionName'); RegisterField(FBytesPerCharacter, 'RDB$BYTES_PER_CHARACTER').As_('BytesPerCharacter'); end; { TRdbCollationsTable } constructor TRdbCollationsTable.Create; begin inherited; inherited TableName := 'RDB$COLLATIONS'; RegisterField(FCollationName, 'RDB$COLLATION_NAME').As_('CollationName'); RegisterField(FCollationId, 'RDB$COLLATION_ID').As_('CollationId'); RegisterField(FCharacterSetId, 'RDB$CHARACTER_SET_ID').As_('CharacterSetId'); RegisterField(FCollationAttributes, 'RDB$COLLATION_ATTRIBUTES').As_('CollationAttributes'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FFunctionName, 'RDB$FUNCTION_NAME').As_('FunctionName'); RegisterField(FBaseCollationName, 'RDB$BASE_COLLATION_NAME').As_('BaseCollationName'); RegisterField(FSpecificAttributes, 'RDB$SPECIFIC_ATTRIBUTES').As_('SpecificAttributes'); end; { TRdbExceptionsTable } constructor TRdbExceptionsTable.Create; begin inherited; inherited TableName := 'RDB$EXCEPTIONS'; RegisterField(FExceptionName, 'RDB$EXCEPTION_NAME').As_('ExceptionName'); RegisterField(FExceptionNumber, 'RDB$EXCEPTION_NUMBER').As_('ExceptionNumber'); RegisterField(FMessage, 'RDB$MESSAGE').As_('Message'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); end; { TRdbRolesTable } constructor TRdbRolesTable.Create; begin inherited; inherited TableName := 'RDB$ROLES'; RegisterField(FRoleName, 'RDB$ROLE_NAME').As_('RoleName'); RegisterField(FOwnerName, 'RDB$OWNER_NAME').As_('OwnerName'); RegisterField(FDescription, 'RDB$DESCRIPTION').As_('Description'); RegisterField(FSystemFlag, 'RDB$SYSTEM_FLAG').As_('SystemFlag'); end; { TRdbBackupHistoryTable } constructor TRdbBackupHistoryTable.Create; begin inherited; inherited TableName := 'RDB$BACKUP_HISTORY'; RegisterField(FBackupId, 'RDB$BACKUP_ID').As_('BackupId'); RegisterField(FTimestamp, 'RDB$TIMESTAMP').As_('Timestamp'); RegisterField(FBackupLevel, 'RDB$BACKUP_LEVEL').As_('BackupLevel'); RegisterField(FGuid, 'RDB$GUID').As_('Guid'); RegisterField(FScn, 'RDB$SCN').As_('Scn'); RegisterField(FFileName, 'RDB$FILE_NAME').As_('FileName'); end; { TMonDatabaseTable } constructor TMonDatabaseTable.Create; begin inherited; inherited TableName := 'MON$DATABASE'; RegisterField(FDatabaseName, 'MON$DATABASE_NAME').As_('DatabaseName'); RegisterField(FPageSize, 'MON$PAGE_SIZE').As_('PageSize'); RegisterField(FOdsMajor, 'MON$ODS_MAJOR').As_('OdsMajor'); RegisterField(FOdsMinor, 'MON$ODS_MINOR').As_('OdsMinor'); RegisterField(FOldestTransaction, 'MON$OLDEST_TRANSACTION').As_('OldestTransaction'); RegisterField(FOldestActive, 'MON$OLDEST_ACTIVE').As_('OldestActive'); RegisterField(FOldestSnapshot, 'MON$OLDEST_SNAPSHOT').As_('OldestSnapshot'); RegisterField(FNextTransaction, 'MON$NEXT_TRANSACTION').As_('NextTransaction'); RegisterField(FPageBuffers, 'MON$PAGE_BUFFERS').As_('PageBuffers'); RegisterField(FSqlDialect, 'MON$SQL_DIALECT').As_('SqlDialect'); RegisterField(FShutdownMode, 'MON$SHUTDOWN_MODE').As_('ShutdownMode'); RegisterField(FSweepInterval, 'MON$SWEEP_INTERVAL').As_('SweepInterval'); RegisterField(FReadOnly, 'MON$READ_ONLY').As_('ReadOnly'); RegisterField(FForcedWrites, 'MON$FORCED_WRITES').As_('ForcedWrites'); RegisterField(FReserveSpace, 'MON$RESERVE_SPACE').As_('ReserveSpace'); RegisterField(FCreationDate, 'MON$CREATION_DATE').As_('CreationDate'); RegisterField(FPages, 'MON$PAGES').As_('Pages'); RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); RegisterField(FBackupState, 'MON$BACKUP_STATE').As_('BackupState'); end; { TMonAttachmentsTable } constructor TMonAttachmentsTable.Create; begin inherited; inherited TableName := 'MON$ATTACHMENTS'; RegisterField(FAttachmentId, 'MON$ATTACHMENT_ID').As_('AttachmentId'); RegisterField(FServerPid, 'MON$SERVER_PID').As_('ServerPid'); RegisterField(FState, 'MON$STATE').As_('State'); RegisterField(FAttachmentName, 'MON$ATTACHMENT_NAME').As_('AttachmentName'); RegisterField(FUser, 'MON$USER').As_('User'); RegisterField(FRole, 'MON$ROLE').As_('Role'); RegisterField(FRemoteProtocol, 'MON$REMOTE_PROTOCOL').As_('RemoteProtocol'); RegisterField(FRemoteAddress, 'MON$REMOTE_ADDRESS').As_('RemoteAddress'); RegisterField(FRemotePid, 'MON$REMOTE_PID').As_('RemotePid'); RegisterField(FCharacterSetId, 'MON$CHARACTER_SET_ID').As_('CharacterSetId'); RegisterField(FTimestamp, 'MON$TIMESTAMP').As_('Timestamp'); RegisterField(FGarbageCollection, 'MON$GARBAGE_COLLECTION').As_('GarbageCollection'); RegisterField(FRemoteProcess, 'MON$REMOTE_PROCESS').As_('RemoteProcess'); RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); end; { TMonTransactionsTable } constructor TMonTransactionsTable.Create; begin inherited; inherited TableName := 'MON$TRANSACTIONS'; RegisterField(FTransactionId, 'MON$TRANSACTION_ID').As_('TransactionId'); RegisterField(FAttachmentId, 'MON$ATTACHMENT_ID').As_('AttachmentId'); RegisterField(FState, 'MON$STATE').As_('State'); RegisterField(FTimestamp, 'MON$TIMESTAMP').As_('Timestamp'); RegisterField(FTopTransaction, 'MON$TOP_TRANSACTION').As_('TopTransaction'); RegisterField(FOldestTransaction, 'MON$OLDEST_TRANSACTION').As_('OldestTransaction'); RegisterField(FOldestActive, 'MON$OLDEST_ACTIVE').As_('OldestActive'); RegisterField(FIsolationMode, 'MON$ISOLATION_MODE').As_('IsolationMode'); RegisterField(FLockTimeout, 'MON$LOCK_TIMEOUT').As_('LockTimeout'); RegisterField(FReadOnly, 'MON$READ_ONLY').As_('ReadOnly'); RegisterField(FAutoCommit, 'MON$AUTO_COMMIT').As_('AutoCommit'); RegisterField(FAutoUndo, 'MON$AUTO_UNDO').As_('AutoUndo'); RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); end; { TMonStatementsTable } constructor TMonStatementsTable.Create; begin inherited; inherited TableName := 'MON$STATEMENTS'; RegisterField(FStatementId, 'MON$STATEMENT_ID').As_('StatementId'); RegisterField(FAttachmentId, 'MON$ATTACHMENT_ID').As_('AttachmentId'); RegisterField(FTransactionId, 'MON$TRANSACTION_ID').As_('TransactionId'); RegisterField(FState, 'MON$STATE').As_('State'); RegisterField(FTimestamp, 'MON$TIMESTAMP').As_('Timestamp'); RegisterField(FSqlText, 'MON$SQL_TEXT').As_('SqlText'); RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); end; { TMonCallStackTable } constructor TMonCallStackTable.Create; begin inherited; inherited TableName := 'MON$CALL_STACK'; RegisterField(FCallId, 'MON$CALL_ID').As_('CallId'); RegisterField(FStatementId, 'MON$STATEMENT_ID').As_('StatementId'); RegisterField(FCallerId, 'MON$CALLER_ID').As_('CallerId'); RegisterField(FObjectName, 'MON$OBJECT_NAME').As_('ObjectName'); RegisterField(FObjectType, 'MON$OBJECT_TYPE').As_('ObjectType'); RegisterField(FTimestamp, 'MON$TIMESTAMP').As_('Timestamp'); RegisterField(FSourceLine, 'MON$SOURCE_LINE').As_('SourceLine'); RegisterField(FSourceColumn, 'MON$SOURCE_COLUMN').As_('SourceColumn'); RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); end; { TMonIoStatsTable } constructor TMonIoStatsTable.Create; begin inherited; inherited TableName := 'MON$IO_STATS'; RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); RegisterField(FStatGroup, 'MON$STAT_GROUP').As_('StatGroup'); RegisterField(FPageReads, 'MON$PAGE_READS').As_('PageReads'); RegisterField(FPageWrites, 'MON$PAGE_WRITES').As_('PageWrites'); RegisterField(FPageFetches, 'MON$PAGE_FETCHES').As_('PageFetches'); RegisterField(FPageMarks, 'MON$PAGE_MARKS').As_('PageMarks'); end; { TMonRecordStatsTable } constructor TMonRecordStatsTable.Create; begin inherited; inherited TableName := 'MON$RECORD_STATS'; RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); RegisterField(FStatGroup, 'MON$STAT_GROUP').As_('StatGroup'); RegisterField(FRecordSeqReads, 'MON$RECORD_SEQ_READS').As_('RecordSeqReads'); RegisterField(FRecordIdxReads, 'MON$RECORD_IDX_READS').As_('RecordIdxReads'); RegisterField(FRecordInserts, 'MON$RECORD_INSERTS').As_('RecordInserts'); RegisterField(FRecordUpdates, 'MON$RECORD_UPDATES').As_('RecordUpdates'); RegisterField(FRecordDeletes, 'MON$RECORD_DELETES').As_('RecordDeletes'); RegisterField(FRecordBackouts, 'MON$RECORD_BACKOUTS').As_('RecordBackouts'); RegisterField(FRecordPurges, 'MON$RECORD_PURGES').As_('RecordPurges'); RegisterField(FRecordExpunges, 'MON$RECORD_EXPUNGES').As_('RecordExpunges'); end; { TMonContextVariablesTable } constructor TMonContextVariablesTable.Create; begin inherited; inherited TableName := 'MON$CONTEXT_VARIABLES'; RegisterField(FAttachmentId, 'MON$ATTACHMENT_ID').As_('AttachmentId'); RegisterField(FTransactionId, 'MON$TRANSACTION_ID').As_('TransactionId'); RegisterField(FVariableName, 'MON$VARIABLE_NAME').As_('VariableName'); RegisterField(FVariableValue, 'MON$VARIABLE_VALUE').As_('VariableValue'); end; { TMonMemoryUsageTable } constructor TMonMemoryUsageTable.Create; begin inherited; inherited TableName := 'MON$MEMORY_USAGE'; RegisterField(FStatId, 'MON$STAT_ID').As_('StatId'); RegisterField(FStatGroup, 'MON$STAT_GROUP').As_('StatGroup'); RegisterField(FMemoryUsed, 'MON$MEMORY_USED').As_('MemoryUsed'); RegisterField(FMemoryAllocated, 'MON$MEMORY_ALLOCATED').As_('MemoryAllocated'); RegisterField(FMaxMemoryUsed, 'MON$MAX_MEMORY_USED').As_('MaxMemoryUsed'); RegisterField(FMaxMemoryAllocated, 'MON$MAX_MEMORY_ALLOCATED').As_('MaxMemoryAllocated'); end; end.
{===================================================================================== Copyright (C) combit GmbH -------------------------------------------------------------------------------------- Module : DOM List & Label sample Descr. : D: Dieses Beispiel demonstriert die dynamische Erzeugung von List & Label Projekten US: This example shows the dynamic creation of List & Label projects ======================================================================================} unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Registry, Dialogs, L28, L28db, cmbtll28, L28dom, DB, ADODB, ExtCtrls, StdCtrls, ComCtrls, ActnList, System.Actions {$If CompilerVersion >=28} // >=XE7 , System.UITypes {$ENDIF} ; type TfrmMain = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; PageControl1: TPageControl; TbShtCrosstabData: TTabSheet; TbShtCorsstabProperties: TTabSheet; TbShtGeneralSettings: TTabSheet; TbShtFinish: TTabSheet; btnNext1: TButton; btnPrev2: TButton; btnNext2: TButton; btnPrev3: TButton; btnNext: TButton; btnDesign: TButton; btnPreview: TButton; Label5: TLabel; Label6: TLabel; Label8: TLabel; Label9: TLabel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Label15: TLabel; Label16: TLabel; Label17: TLabel; Label18: TLabel; GroupBox3: TGroupBox; GroupBox4: TGroupBox; Label21: TLabel; dtReportTitle: TEdit; CmbxPageFormat: TComboBox; FontDialog1: TFontDialog; ColorDialog1: TColorDialog; ADOConnection1: TADOConnection; LL: TDBL28_; btnColorCell1: TButton; lblColorCell1: TLabel; lblColorCell2: TLabel; lblColorRow1: TLabel; lblColorRow2: TLabel; btnColorCell2: TButton; btnColorRow1: TButton; btnColorRow2: TButton; btnDefaultFont: TButton; Panel1: TPanel; lblSampleText: TLabel; ActionList1: TActionList; ctnNextTab: TAction; ctnPreviosTab: TAction; dsCustomers: TDataSource; dsOrders: TDataSource; TblCustomers: TADOTable; TblOrders: TADOTable; TblOrderDetails: TADOTable; RdGrpCellSortOrder: TRadioGroup; RdGrpRowSortOrder: TRadioGroup; Panel2: TPanel; Label22: TLabel; Image1: TImage; Label24: TLabel; Label23: TLabel; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label28: TLabel; lbl_Schema: TLabel; lbl_title: TLabel; lbl_Cell: TLabel; lbl_Row: TLabel; lbl_Project: TLabel; lbl_Font: TLabel; rdbtnCrosstab: TRadioButton; rdbtnPieChart: TRadioButton; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; dtTitle2: TEdit; Label14: TLabel; Label19: TLabel; rdbtnBarChart: TRadioButton; Label20: TLabel; Label29: TLabel; Label30: TLabel; dtTitle3: TEdit; Label31: TLabel; procedure btnColorCell1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnColorCell2Click(Sender: TObject); procedure btnColorRow1Click(Sender: TObject); procedure btnColorRow2Click(Sender: TObject); procedure btnDefaultFontClick(Sender: TObject); procedure ctnNextTabExecute(Sender: TObject); procedure ctnPreviosTabExecute(Sender: TObject); procedure btnDesignClick(Sender: TObject); procedure btnPreviewClick(Sender: TObject); procedure TbShtFinishShow(Sender: TObject); private workingPath: String; function GenerateLLProject(): integer; procedure UpdateInfo(); function TColorToRGB(oColor: TColor): string; procedure AddCrosstab(container: TLlDOMObjectReportContainer); procedure AddPieChart(container: TLlDOMObjectReportContainer); procedure AddBarChart(container: TLlDOMObjectReportContainer); public { Public declarations } end; var frmMain: TfrmMain; lldomproj: TLlDomProjectList; llFont: TFont; implementation {$R *.dfm} procedure TfrmMain.btnColorCell1Click(Sender: TObject); begin ColorDialog1.Execute(); lblColorCell1.Color := ColorDialog1.Color; end; procedure TfrmMain.btnColorCell2Click(Sender: TObject); begin ColorDialog1.Execute(); lblColorCell2.Color := ColorDialog1.Color; end; procedure TfrmMain.btnColorRow1Click(Sender: TObject); begin ColorDialog1.Execute(); lblColorRow1.Color := ColorDialog1.Color; end; procedure TfrmMain.btnColorRow2Click(Sender: TObject); begin ColorDialog1.Execute(); lblColorRow2.Color := ColorDialog1.Color; end; procedure TfrmMain.btnDefaultFontClick(Sender: TObject); begin FontDialog1.Execute(); lblSampleText.Font := FontDialog1.Font; llFont := FontDialog1.Font; end; procedure TfrmMain.btnDesignClick(Sender: TObject); var nRet: integer; begin LL.AutoDesignerFile := workingPath + 'dynamic.lst'; LL.AutoProjectType := ptListProject; LL.AutoMasterMode := mmAsFields; LL.AutoShowSelectFile := No; //D: List & Label Projekt anhand Einstellungen erstellen //US: Create List & Label project based on the settings nRet := GenerateLLProject(); if nRet <> 0 then MessageDlg(LL.LlGetErrortext(nRet), mtInformation, [mbOK], 0) else //D: Designer aufrufen //US: Call the designer LL.AutoDesign('Dynamically created project...'); end; procedure TfrmMain.btnPreviewClick(Sender: TObject); var nRet: integer; begin LL.AutoDesignerFile := workingPath + 'dynamic.lst'; LL.AutoShowSelectFile := No; LL.AutoProjectType := ptListProject; LL.AutoMasterMode := mmAsFields; LL.AutoDestination := adPreview; LL.AutoShowPrintOptions := No; //D: List & Label Projekt anhand Einstellungen erstellen //US: Create List & Label project based on the settings nRet := GenerateLLProject(); if nRet <> 0 then MessageDlg(LL.LlGetErrortext(nRet), mtInformation, [mbOK], 0) else //D: Designer aufrufen //US: Call the designer LL.AutoPrint('Dynamically created project...', ''); end; procedure TfrmMain.ctnNextTabExecute(Sender: TObject); begin PageControl1.ActivePageIndex := PageControl1.ActivePageIndex + 1; end; procedure TfrmMain.ctnPreviosTabExecute(Sender: TObject); begin PageControl1.ActivePageIndex := PageControl1.ActivePageIndex - 1; end; procedure TfrmMain.FormCreate(Sender: TObject); var registry: TRegistry; var regKeyPath: String; var dbPath: String; var tmp: String; begin PageControl1.ActivePageIndex := 0; lblColorCell1.Color := 65484; lblColorCell2.Color := 16777215; lblColorRow1.Color := 16777215; lblColorRow2.Color := 3381759; llFont := TFont.Create(); llFont.Name := 'Verdana'; llFont.Size := 10; rdbtnCrosstab.Checked := true; // D: Datenbankpfad auslesen // US: Read database path registry := TRegistry.Create(); registry.RootKey := HKEY_CURRENT_USER; regKeyPath := 'Software\combit\cmbtll\'; if registry.KeyExists(regKeyPath) then begin if registry.OpenKeyReadOnly(regKeyPath) then begin dbPath := registry.ReadString('NWINDPath'); tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir'); if (tmp[Length(tmp)] = '\') then begin workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\'; end else workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\'; registry.CloseKey(); end; end; registry.Free(); if (dbPath = '') OR (workingPath = '') then begin ShowMessage('Unable to find sample database. Make sure List & Label is installed correctly.'); exit; end; // D: Verzeichnis setzen // US: Set current dir workingPath := GetCurrentDir() + '\'; if not ADOConnection1.Connected then begin ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' + 'User ID=Admin;' + 'Data Source=' + dbPath + ';' + 'Mode=Share Deny None;' + 'Extended Properties="";' + 'Jet OLEDB:Engine Type=4;'; ADOConnection1.Connected := true; TblCustomers.Filter := 'CustomerID<''D'''; TblCustomers.Filtered := true; TblCustomers.Active := true; TblOrders.Active := true; TblOrderDetails.Active := true; end; end; function TfrmMain.GenerateLLProject: integer; var llobjText: TLlDOMObjectText; llobjParagraph: TLlDOMParagraph; llobjDrawing: TLlDOMObjectDrawing; container: TLlDOMObjectReportContainer; llobjHelper: TLlDOMObjectRectangle; Height, Width: integer; begin //D: Das DOM Objekt an ein List & Label Objekt binden //US: Bind the DOM object to a List & Label object lldomproj := TLlDomProjectList.Create(LL); //D: Ein neues Listen Projekt mit dem Namen 'dynamic.lst' erstellen //US: Create a new listproject called 'dynamic.lst' result := lldomproj.Open(workingPath + 'dynamic.lst', fmCreate, amReadWrite); if result <> 0 then exit; //D: Mit dieser Eigenschaft kann die Seitenausrichtung bestimmt werden //US: With this property you can set the page orientation lldomproj.Regions[0].Paper.Orientation := IntToStr(CmbxPageFormat.ItemIndex+1); //D: Eine neue Projektbeschreibung dem Projekt zuweisen //US: Assign new project description to the project lldomproj.ProjectParameterList.ItemName['LL.ProjectDescription'].Contents := 'Dynamically created Project'; //D: Ein leeres Text Objekt erstellen //US: Create an empty text object llobjText := TLlDOMObjectText.Create(lldomproj.ObjectList); //D: Auslesen der Seitenkoordinaten der ersten Seite //US: Get the coordinates for the first page Height := StrToInt(lldomproj.Regions[0].Paper.Extent.Vertical); Width := StrToInt(lldomproj.Regions[0].Paper.Extent.Horizontal); //D: Setzen von Eigenschaften für das Textobjekt //US: Set some properties for the text object llobjText.Position.Define(10000, 10000, Width-65000, 27000); llobjText.LayerID := '1'; //D: Hinzufügen eines Paragraphen und setzen diverser Eigenschaften //US: Add a paragraph to the text object and set some properties llobjParagraph := TLlDOMParagraph.Create(llobjText.Paragraphs); llobjParagraph.Contents := '"' + dtReportTitle.Text + '"'; llobjParagraph.Font.Bold := 'True'; //D: Ändern der Standard Schriftart im Projekt //US: Change the default font for the project lldomproj.Settings.DefaultFont.SetFont(llFont); lldomproj.Settings.DefaultFont.Color := IntToStr(ColorToRGB(lblSampleText.Font.Color));; //D: Hinzufügen eines Grafikobjekts //US: Add a drawing object llobjDrawing := TLlDOMObjectDrawing.Create(lldomproj.ObjectList); llobjDrawing.Source.Fileinfo.Filename := 'sunshine.gif'; llobjDrawing.Position.Define(Width - 50000, 10000, Width - (Width - 40000), 27000); llobjDrawing.LayerID := '1'; //D: Hinzufügen eines Tabellencontainers und setzen diverser Eigenschaften //US: Add a table container and set some properties container := TLlDOMObjectReportContainer.Create(lldomproj.ObjectList); container.Position.Define(10000, 40000, Width - 20000, Height - 44000); if rdbtnCrosstab.Checked then AddCrosstab(container); if rdbtnPieChart.Checked then AddPieChart(container); if rdbtnBarChart.Checked then AddBarChart(container); //D: Hinzufügen eines Hilfs-Rechtecks. Wird verwendet um den Tabellencontainer auf der ersten Seite unterhalb der Überschrift anzuzeigen //US: Add a helper rectangle. This will be used for showing the tablecontainer at the first page under the title llobjHelper := TLlDOMObjectRectangle.Create(lldomproj.ObjectList); //D: Setzen von Eigenschaften für das Rechteck //US: Set some properties for the rectangle llobjHelper.Position.Define(10000, 10000, 1, 30000); llobjHelper.LayerID := '1'; llobjHelper.Frame.Color := 'RGB(255, 255, 255)'; //D: Den Berichtscontainer mit dem Rechteck Objekt verketten, so dass der Container auf den Folgeseiten mehr Platz einnimmt //US: Link the report container to the rectangle object in order to fill up space on following pages container.LinkTo(llobjHelper, TLlDOMVerticalLinkType.RelativeToEnd, TLlDOMVerticalSizeAdaptionType.Inverse); //D: Projekt Liste als Datei speichern //US: Save projectlist to file lldomproj.Save(workingPath + 'dynamic.lst'); //D: Projekt Liste schliessen //US: Close project list lldomproj.Close(); end; procedure TfrmMain.TbShtFinishShow(Sender: TObject); begin UpdateInfo(); end; function TfrmMain.TColorToRGB(oColor: TColor): string; begin result := ('RGB(' + IntToStr( GetRValue( oColor ) ) + ',' + IntToStr( GetGValue( oColor ) ) + ',' + IntToStr( GetBValue( oColor ) ) + ')' ); end; procedure TfrmMain.AddCrosstab(container: TLlDOMObjectReportContainer); var crosstab: TLlDOMSubItemCrosstab; curr: TLlDOMPropertyOutputFormatterCurrency; begin //D: In dem Container eine Kreuztabelle hinzufügen. //US: Add a crosstab into the container. crosstab := TLlDOMSubItemCrosstab.Create(container.SubItems); //D: Die Tabelle festlegen, aus der die Daten stammen sollen. Als Datenquelle wird die Tabelle "Order_Details" verwendet. //US: Define the source table. We use the "Order_Details" table as data source. crosstab.SourceTablePath := 'Customers;Orders(Customers2Orders);Order_Details(Orders2Order Details)'; //D: Hier lassen sich die Daten festlegen, welche für die Zeilen verwendet werden sollen //US: Define the data which should be used for the rows crosstab.Definition.Rows.Groupings.Add('Customers.CustomerID'); //D: Hier lassen sich die Daten festlegen, welche für die Spalten verwendet werden sollen //US: Define the data which should be used for the columns crosstab.Definition.Columns.Groupings.Add('Year(Orders.OrderDate)'); crosstab.Definition.Columns.Groupings.Add('Month(Orders.OrderDate)'); //D: Die Überschrift der Spalten kann hier angegeben werden //US: Define the cell tiltle with the following line crosstab.Definition.Columns.GroupLabel[1].Formula := 'Year$(Orders.OrderDate)'; crosstab.Definition.Columns.GroupLabel[0].Formula := 'Month$(Orders.OrderDate)'; //D: Die Überschrift der äussersten Spalten / Zeilen kann hier angegeben werden //US: Define the outside cell / row tiltle with the following line crosstab.Definition.Columns.GroupLabel.Items[2].Formula := '"Column title"'; crosstab.Definition.Rows.GroupLabel.Items[1].Formula := '"Row title"'; //D: Text und Wert, welcher in allen Zellen angezeigt werden soll //US: Text and value which should be used for all cells crosstab.Definition.Cells.All.Formula := 'Sum(Order_Details.Quantity*Order_Details.UnitPrice)'; crosstab.Definition.Cells.All.Value := 'Sum(Order_Details.Quantity*Order_Details.UnitPrice)'; // D: Spaltenüberschriften auf Folgeseiten wiederholen // US: Repeat column labels on following pages crosstab.Definition.RowWrapping.RepeatLabels := 'True'; //D: Formatierung für die Zellen festlegen (Währungsformat) //US: Apply currency formatter to the cells curr := TLlDOMPropertyOutputFormatterCurrency.Create(crosstab.Definition.Cells.All.OutputFormatter); curr.CountOfDecimals := '2'; //D: Diverse Einstellungen für die Farbgebung der Zeilen setzen //US: Define properties for the row color schema crosstab.Definition.Rows.GroupLabel[0].Filling.Style := '3'; crosstab.Definition.Rows.GroupLabel[0].Filling.Color := TColorToRGB(lblColorRow1.Color); crosstab.Definition.Rows.GroupLabel[0].Filling.Color2 := TColorToRGB(lblColorRow2.Color); //D: Festlegen, ob die Zeilen aufsteigend oder absteigend sortiert werden sollen //US: Define whether the rows should be sorted ascending or descending case RdGrpCellSortOrder.ItemIndex of 0: crosstab.Definition.Rows.GroupLabel[0].SortOrderAscending.SortOrder := '0'; 1: crosstab.Definition.Rows.GroupLabel[0].SortOrderAscending.SortOrder := '1'; end; //D: Diverse Einstellungen für die Farbgebung der Spalten setzen //US: Define properties for the column color schema crosstab.Definition.Columns.GroupLabel[0].Filling.Style := '3'; crosstab.Definition.Columns.GroupLabel[0].Filling.Color := TColorToRGB(lblColorCell1.Color); crosstab.Definition.Columns.GroupLabel[0].Filling.Color2:= TColorToRGB(lblColorCell2.Color); //D: Festlegen, ob die Spalten aufsteigend oder absteigend sortiert werden sollen //US: Define whether the columns should be sorted ascending or descending case RdGrpRowSortOrder.ItemIndex of 0: crosstab.Definition.Columns.GroupLabel[0].SortOrderAscending.SortOrder := '0'; 1: crosstab.Definition.Columns.GroupLabel[0].SortOrderAscending.SortOrder := '1'; end; end; //**** D: Erstellen eines Kreisdiagramms **** //**** US: Create a pie-chart **** procedure TfrmMain.AddPieChart(container: TLlDOMObjectReportContainer); var chart: TLlDOMSubItemChart; engine: TLlDOMPropertyChartEnginePie3D; curr: TLlDOMPropertyOutputFormatterCurrency; begin //D: In dem Container ein Chart-Objekt hinzufügen und dessen Namen vergeben. //US: Add a chart into the container and define its name. chart := TLlDOMSubItemChart.Create(ctPie3D, container.SubItems); chart.Name := 'Pie3D'; //D: Die Tabelle festlegen, aus der die Daten stammen sollen. Als Datenquelle wird die Tabelle "Order_Details" verwendet. //US: Define the source table. We use the "Order_Details" table as data source. chart.SourceTablePath := 'Customers;Orders(Customers2Orders);Order_Details(Orders2Order Details)'; //D: Um Zugriff auf die Chart-Engine zu bekommen, muss diese zunächst in den passenden Typ konvertiert werden //US: To access the chart-engine, it is necessary to convert it in the suitable type at first engine := chart.Definition.ChartEngine as TLlDOMPropertyChartEnginePie3D; //D: In den folgenden Zeilen wird die Datenquelle angegeben //US: In the following lines, the data source is defined engine.XAxis.Value := 'Customers.CustomerID'; engine.YAxis[0].Value := 'Order_Details.UnitPrice*Order_Details.Quantity'; engine.YAxis[0].CoordinateLabelOnObject.Placement := '1'; engine.YAxis[0].CoordinateLabelOnObject.Formula := 'LL.ChartObject.ArcValue'; //D: Die Überschrift des Charts kann hier angegeben werden //US: Define the chart title with the following line chart.Definition.Title.Contents := '"' + dtTitle2.Text + '"'; //D: Formatierung für die Legende //US: Define the legend format curr := TLlDOMPropertyOutputFormatterCurrency.Create(engine.YAxis[0].CoordinateLabelOnObject.OutputFormatter); //D: Eine Anzahl von zwei Nachkommastellen //US: A number of two decimal places curr.CountOfDecimals := '2'; end; //**** D: Erstellen eines Balkendiagramms **** //**** US: Create a bar-chart **** procedure TfrmMain.AddBarChart(container: TLlDOMObjectReportContainer); var currBar: TLlDOMPropertyOutputFormatterCurrency; engineBar: TLlDOMPropertyChartEngineBar3D; chartBar: TLlDOMSubItemChart; begin //D: In dem Container ein Chart-Objekt hinzufügen und dessen Namen vergeben. //US: Add a chart into the container and define its name. chartBar := TLlDOMSubItemChart.Create(ctBar3D, container.SubItems); chartBar.Name := 'Bar3D'; //D: Die Tabelle festlegen, aus der die Daten stammen sollen. Als Datenquelle wird die Tabelle "Order_Details" verwendet. //US: Define the source table. We use the "Order_Details" table as data source. chartBar.SourceTablePath := 'Customers;Orders(Customers2Orders);Order_Details(Orders2Order Details)'; //D: Um Zugriff auf die Chart-Engine zu bekommen, muss diese zunächst in den passenden Typ konvertiert werden //US: To access the chart-engine, it is necessary to convert it in the suitable type at first engineBar := chartBar.Definition.ChartEngine as TLlDOMPropertyChartEngineBar3D; //D: In den folgenden Zeilen wird die Datenquelle angegeben //US: In the following lines, the data source is defined engineBar.XAxis.Value := 'Customers.CustomerID'; engineBar.YAxes[0].Value := 'Order_Details.UnitPrice*Order_Details.Quantity'; engineBar.YAxes[0].CoordinateLabelOnObject.Placement := '1'; //D: Die Überschrift des Charts kann hier angegeben werden //US: Define the chart title with the following line chartBar.Definition.Title.Contents := '"' + dtTitle3.Text + '"'; //D: Formatierung für die Legende //US: Define the legend format currBar := TLlDOMPropertyOutputFormatterCurrency.Create(engineBar.YAxes[0].CoordinateLabelOnObject.OutputFormatter); //D: Eine Anzahl von zwei Nachkommastellen //US: A number of two decimal places currBar.CountOfDecimals := '2'; end; procedure TfrmMain.UpdateInfo; begin lbl_Schema.Caption := Label9.Caption; lbl_Cell.Caption := TColorToRGB(lblColorCell1.Color) + ' - ' + TColorToRGB(lblColorCell2.Color) + ', ' + RdGrpCellSortOrder.Items[RdGrpCellSortOrder.ItemIndex]; lbl_Row.Caption := TColorToRGB(lblColorRow1.Color) + ' - ' + TColorToRGB(lblColorRow2.Color) + ', ' + RdGrpRowSortOrder.Items[RdGrpRowSortOrder.ItemIndex]; lbl_Project.Caption := Label4.Caption; lbl_Font.Caption := llFont.Name + ', ' + IntToStr(llFont.Size); end; end.
unit uLine; interface { For serialization } type LineRecord = record p1, p2: integer; // index end; type LineRecordList = Array of LineRecord; { Provides containers for lines } type Line = class(TObject) p1, p2: integer; // index constructor Create(f, t: integer); end; type LineList = Array of Line; function lToClass(r: LineRecord): Line; function lToRecord(l: Line): LineRecord; function lCopy(l: Line): Line; implementation // Line constructor Line.Create(f, t: integer); begin self.p1 := f; self.p2 := t; end; function lToRecord(l: Line): LineRecord; var r: LineRecord; begin r.p1 := l.p1; r.p2 := l.p2; lToRecord := r; end; function lToClass(r: LineRecord): Line; begin lToClass := Line.Create(r.p1, r.p2); end; function lCopy(l: Line): Line; begin lCopy := Line.Create(l.p1, l.p2); end; end.
unit DPM.Core.Compiler.ProjectSettings; interface uses System.Classes, DPM.Core.Types, DPM.Core.MSXML; type IProjectSettingsLoader = interface ['{83E9EEA4-02E5-4D13-9C13-21D7F7219F4A}'] function GetSearchPath : string; end; TDPMProjectSettingsLoader = class(TInterfacedObject, IProjectSettingsLoader) private FConfigKeys : TStringList; FConfigParents : TStringList; FConfigName : string; FXMLDoc : IXMLDOMDocument; FPlatform : string; function GetConfigParent(const key: string): string; protected procedure LoadConfigs; function GetStringProperty(const propName, defaultValue: string): string; function DoGetStringProperty(const configKey, propName, defaultValue: string): string; function GetSearchPath : string; public constructor Create(const projectFile : string; const configName : string; const platform : TDPMPlatform); destructor Destroy;override; end; implementation uses System.StrUtils, System.SysUtils; const PropertyXPathFormatStr = '/def:Project/def:PropertyGroup[@Condition="''$(%s)''!=''''"]/def:%s'; { TDOMProjectSettingsLoader } constructor TDPMProjectSettingsLoader.Create(const projectFile, configName: string; const platform : TDPMPlatform); begin FConfigName := configName; FXMLDoc := CoDOMDocument60.Create; if not FXMLDoc.load(projectFile) then raise Exception.Create('Error loading dproj [' + projectFile + '] : ' + FXMLDoc.parseError.reason); (FXMLDoc as IXMLDOMDocument2).setProperty('SelectionLanguage', 'XPath'); (FXMLDoc as IXMLDOMDocument2).setProperty('SelectionNamespaces', 'xmlns:def=''http://schemas.microsoft.com/developer/msbuild/2003'''); FConfigKeys := TStringList.Create; FConfigParents := TStringList.Create; FPlatform := DPMPlatformToBDString(platform); LoadConfigs; end; destructor TDPMProjectSettingsLoader.Destroy; begin FConfigKeys.Free; FConfigParents.Free; FXMLDoc := nil; inherited; end; function GetXPath(const sPath, PropertyName: string): string; begin result := Format(PropertyXPathFormatStr,[sPath,PropertyName]); end; function IncludeTrailingChar(const sValue :string; const AChar : Char) : string; var l : integer; begin result := sValue; l := Length(result); if l > 0 then if result[l] <> AChar then result := result + AChar end; function ExcludeTrailingChar(const sValue :string; const AChar : Char) : string; var l : integer; begin result := sValue; l := Length(result); if l > 0 then if result[l] = AChar then Delete(result,l,1); end; function TDPMProjectSettingsLoader.GetConfigParent(const key: string): string; begin if key = 'Base' then exit(''); result := FConfigParents.Values[key]; if result = '' then begin //if we didn't find a parent then try and remove the platform result := StringReplace(key,'_' + FPlatform,'',[rfIgnoreCase]); end; end; function TDPMProjectSettingsLoader.DoGetStringProperty(const configKey, propName, defaultValue : string) : string; var tmpElement : IXMLDOMElement; sParentConfig : string; sInherit : string; bInherit : boolean; sParentValue : string; begin bInherit := False; sInherit := '$(' + propName + ')'; tmpElement := FXMLDoc.selectSingleNode(GetXPath(configKey, propName)) as IXMLDOMElement; if tmpElement <> nil then begin result := tmpElement.text; if not bInherit then if Pos(sInherit,result) > 0 then bInherit := True; end else begin bInherit := True; //didn't find a value so we will look at it's base config for a value result := ''; end; if bInherit then begin if sInherit <> '' then result := StringReplace(Result,sInherit,'',[rfIgnoreCase]); sParentConfig := GetConfigParent(configKey); if sParentConfig <> '' then begin sParentValue := DoGetStringProperty(sParentConfig,propName, defaultValue); result := IncludeTrailingChar(sParentValue,';') + result; end else result := StringReplace(Result,sInherit,'',[rfIgnoreCase]); end; if result = '' then result := defaultValue; result := ExcludeTrailingChar(Result,';'); end; function TDPMProjectSettingsLoader.GetSearchPath: string; begin result := GetStringProperty('DCC_UnitSearchPath', '$(DCC_UnitSearchPath)' ); end; function TDPMProjectSettingsLoader.GetStringProperty(const propName, defaultValue: string): string; var sConfigKey : string; begin sConfigKey := FConfigKeys.Values[FConfigName]; result := DoGetStringProperty(sConfigKey, propName, defaultValue); end; procedure TDPMProjectSettingsLoader.LoadConfigs; var configs : IXMLDOMNodeList; tmpElement : IXMLDOMElement; keyElement : IXMLDOMElement; parentElement : IXMLDOMElement; i : integer; sName : string; sKey : string; sParent : string; begin //Avert your eyes, ugly code ahead to deal with how config inheritance works in //dproj files.. sometimes the intermediate configs are not present in the dproj //so we have to fudge things to make the tree correct. //TODO : find a neater way to do this. configs := FXMLDoc.selectNodes('/def:Project/def:ItemGroup/def:BuildConfiguration'); if configs.length > 0 then begin for i := 0 to configs.length - 1 do begin sName := ''; sKey := ''; sParent := ''; tmpElement := configs.item[i] as IXMLDOMElement; if tmpElement <> nil then begin sName := tmpElement.getAttribute('Include'); keyElement := tmpElement.selectSingleNode('def:Key') as IXMLDOMElement; if keyElement <> nil then sKey := keyElement.text; parentElement := tmpElement.selectSingleNode('def:CfgParent') as IXMLDOMElement; if parentElement <> nil then sParent := parentElement.text; FConfigKeys.Add(sName + '=' + sKey); FConfigParents.Add(sKey + '=' + sParent); //This is a hack to deal with Platforms.. not enough info in the dproj to walk the inheritance tree fully if (sKey <> 'Base') and (sParent <> '') then FConfigParents.Add(sKey + '_' + FPlatform + '=' + sParent + '_' + FPlatform); end; end; end; for i := 0 to FConfigKeys.Count - 1 do begin sKey := FConfigKeys.ValueFromIndex[i]; //get the parent that we retrieved from the project file sParent := GetConfigParent(sKey); //remap the parents to inject the platform parents FConfigParents.Add(sKey + '_' + FPlatform + '=' + sKey); if sParent <> '' then begin FConfigParents.Add(sKey + '=' + sParent + '_' + FPlatform); FConfigParents.Add(sParent + '_' + FPlatform + '=' + sParent); end; end; 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_CLASSLST.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_CLASSLST; interface uses {$I uses.def} TypInfo, SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS; type TPropRec = class public PropInfo: Pointer; PropOffset: Integer; constructor Create; destructor Destroy; override; end; TPropList = class(TTypedList) private function GetInfo(I: Integer): PPropInfo; public procedure Add(P: Pointer; S: Integer); function Top: TPropRec; property Infos[I: Integer]: PPropInfo read GetInfo; default; end; TIntfMethodRec = class public MethodOffset: IntPax; InterfaceToObjectOffset: Integer; FullMethodName: String; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); end; TIntfMethodList = class(TTypedList) private function GetRecord(I: Integer): TIntfMethodRec; function AddRecord: TIntfMethodRec; public function AddMethod(const FullMethodName: String; MethodOffset: IntPax; InterfaceToObjectOffset: Integer): TIntfMethodRec; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); property Records[I: Integer]: TIntfMethodRec read GetRecord; default; end; TIntfRec = class private fBuffSize: Integer; public GUID: TGUID; Buff: PPointers; IntfMethods: TIntfMethodList; constructor Create; destructor Destroy; override; procedure AllocBuff; procedure SetupBuff(CodePtr: Pointer); procedure DeallocBuff; procedure SaveToStream(P: TStream); procedure LoadFromStream(P: TStream); property BuffSize: Integer read fBuffSize; end; TIntfList = class(TTypedList) private function GetRecord(I: Integer): TIntfRec; public function Add: TIntfRec; procedure Setup(CodePtr: Pointer); procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function Lookup(const GUID: TGUID): TIntfRec; function IndexOf(const GUID: TGUID): Integer; property Records[I: Integer]: TIntfRec read GetRecord; default; end; TClassRec = class private procedure AddPropInfos; public PClass: TClass; PClass_pti: PTypeInfo; PropInfos: TPropList; Offset: Integer; SizeOfScriptClassFields: Integer; Host: Boolean; DestructorProgOffset: Integer; AfterConstructionProgOffset: Integer; BeforeDestructionProgOffset: Integer; SafeCallExceptionProgOffset: Integer; DispatchProgOffset: Integer; DefaultHandlerProgOffset: Integer; NewInstanceProgOffset: Integer; FreeInstanceProgOffset: Integer; {$IFDEF UNIC} ToStringProgOffset: Integer; GetHashCodeProgOffset: Integer; EqualsProgOffset: Integer; {$ENDIF} InstSize: Integer; FullName: String; ParentFullName: String; IntfList: TIntfList; ByteCodeMethodEntryList: TIntegerDynArray; VirtualMethodEntryList: array[1..100] of Integer; constructor Create(i_PClass: TClass; i_Offset: Integer; i_Host: Boolean); destructor Destroy; override; procedure SetupInterfaces(CodePtr: Pointer); function GetIntfOffset(const GUID: TGUID): Integer; function GetIntfTableSize: Integer; end; TClassList = class private L: TStringList; function GetClassRec(I: Integer): TClassRec; function GetName(I: Integer): String; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Clear; function IndexOf(const S: String): Integer; function FindClass(C: TClass): Integer; function Add(const FullName: String; Host: Boolean): TClassRec; function AddEx(const FullName: String; ClassIndex: Integer): TClassRec; function AddClass(C: TClass; const FullName: String; Host: Boolean; Offset: Integer): TClassRec; function AddClassEx(C: TClass; const FullName: String; Host: Boolean; Offset: Integer; ClassIndex: Integer): TClassRec; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream; Version: Integer); function GetSize: Integer; procedure SetupInterfaces(CodePtr: Pointer); function Lookup(const FullName: String): TClassRec; function LookupClassRec(C: TClass): TClassRec; function GetByteCodeMethodEntryIndex(N: Integer): Integer; property Count: Integer read GetCount; property Names[I: Integer]: String read GetName; property Records[I: Integer]: TClassRec read GetClassRec; default; end; var AddPropInfosDRTTI: procedure(C: TClass; PropInfos: TPropList) = nil; implementation // TIntfMethodRec -------------------------------------------------------------- procedure TIntfMethodRec.SaveToStream(S: TStream); begin S.Write(MethodOffset, SizeOf(MethodOffset)); S.Write(InterfaceToObjectOffset, SizeOf(InterfaceToObjectOffset)); SaveStringToStream(FullMethodName, S); end; procedure TIntfMethodRec.LoadFromStream(S: TStream); begin S.Read(MethodOffset, SizeOf(MethodOffset)); S.Read(InterfaceToObjectOffset, SizeOf(InterfaceToObjectOffset)); FullMethodName := LoadStringFromStream(S); end; // TIntfMethodList ------------------------------------------------------------- function TIntfMethodList.GetRecord(I: Integer): TIntfMethodRec; begin result := TIntfMethodRec(L[I]); end; function TIntfMethodList.AddRecord: TIntfMethodRec; begin result := TIntfMethodRec.Create; L.Add(result); end; function TIntfMethodList.AddMethod(const FullMethodName: String; MethodOffset: IntPax; InterfaceToObjectOffset: Integer): TIntfMethodRec; begin result := AddRecord; result.FullMethodName := FullMethodName; result.MethodOffset := MethodOffset; result.InterfaceToObjectOffset := InterfaceToObjectOffset; end; procedure TIntfMethodList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(Integer)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TIntfMethodList.LoadFromStream(S: TStream); var I, K: Integer; begin S.Read(K, SizeOf(Integer)); for I := 0 to K - 1 do AddRecord.LoadFromStream(S); end; // -- TIntfRec ----------------------------------------------------------------- constructor TIntfRec.Create; begin inherited; IntfMethods := TIntfMethodList.Create; fBuffSize := 0; end; destructor TIntfRec.Destroy; begin FreeAndNil(IntfMethods); if Buff <> nil then DeallocBuff; inherited; end; procedure TIntfRec.SaveToStream(P: TStream); begin P.Write(GUID, SizeOf(GUID)); IntfMethods.SaveToStream(P); end; procedure TIntfRec.LoadFromStream(P: TStream); begin P.Read(GUID, SizeOf(GUID)); IntfMethods.LoadFromStream(P); end; procedure TIntfRec.AllocBuff; begin if Buff <> nil then DeallocBuff; fBuffSize := MAX_INTERFACE_IMPLEMENT_METHODS * SizeOf(Pointer) * 2; Buff := AllocMem(fBuffSize); end; procedure TIntfRec.SetupBuff(CodePtr: Pointer); var I, Offset, InterfaceToObjectOffset: Integer; Adr: Pointer; begin for I:=0 to IntfMethods.Count - 1 do begin Offset := IntfMethods[I].MethodOffset; InterfaceToObjectOffset := IntfMethods[I].InterfaceToObjectOffset; if CodePtr <> nil then begin Adr := ShiftPointer(CodePtr, Offset); end else begin Adr := Pointer(Offset); end; Buff^[I] := Adr; Buff^[MAX_INTERFACE_IMPLEMENT_METHODS + I] := Pointer(InterfaceToObjectOffset); end; end; procedure TIntfRec.DeallocBuff; begin if Buff <> nil then FreeMem(Buff, fBuffSize); end; // -- TIntfList ---------------------------------------------------------------- function TIntfList.Lookup(const GUID: TGUID): TIntfRec; var I: Integer; begin result := nil; for I:=0 to Count - 1 do if GuidsAreEqual(Records[I].GUID, GUID) then begin result := Records[I]; Exit; end; end; function TIntfList.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; procedure TIntfList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(Integer)); for I:=0 to K - 1 do Records[I].SaveToStream(S); end; procedure TIntfList.LoadFromStream(S: TStream); var I, K: Integer; IntfRec: TIntfRec; begin S.Read(K, SizeOf(Integer)); for I:=0 to K - 1 do begin IntfRec := TIntfRec.Create; IntfRec.LoadFromStream(S); L.Add(IntfRec); end; end; procedure TIntfList.Setup(CodePtr: Pointer); var I: Integer; R: TIntfRec; begin for I:=0 to Count - 1 do begin R := Records[I]; R.AllocBuff; R.SetupBuff(CodePtr); end; end; function TIntfList.GetRecord(I: Integer): TIntfRec; begin result := TIntfRec(L[I]); end; function TIntfList.Add: TIntfRec; begin result := TIntfRec.Create; L.Add(result); end; // -- TPropRec ----------------------------------------------------------------- constructor TPropRec.Create; begin inherited; end; destructor TPropRec.Destroy; begin inherited; end; // -- TPropList ---------------------------------------------------------------- procedure TPropList.Add(P: Pointer; S: Integer); var R: TPropRec; begin R := TPropRec.Create; R.PropInfo := P; R.PropOffset := S; L.Add(R); end; function TPropList.GetInfo(I: Integer): PPropInfo; begin result := TPropRec(L[I]).PropInfo; end; function TPropList.Top: TPropRec; begin if Count = 0 then result := nil else result := TPropRec(L[Count - 1]); end; // -- TClassRec ---------------------------------------------------------------- constructor TClassRec.Create(i_PClass: TClass; i_Offset: Integer; i_Host: Boolean); begin inherited Create; PClass := i_PClass; Offset := i_Offset; PropInfos := TPropList.Create; Host := i_Host; if PClass <> nil then begin PClass_pti := PClass.ClassInfo; AddPropInfos; end; IntfList := TIntfList.Create; end; destructor TClassRec.Destroy; begin FreeAndNil(PropInfos); FreeAndNil(IntfList); inherited; end; procedure TClassRec.SetupInterfaces(CodePtr: Pointer); begin IntfList.Setup(CodePtr); end; procedure TClassRec.AddPropInfos; var pti: PTypeInfo; ptd: PTypeData; Loop, nProps: Integer; pProps: PPropList; ppi: PPropInfo; PropOffset: Integer; begin PropInfos.Clear; pti := PClass.ClassInfo; if pti = nil then Exit; ptd := GetTypeData(pti); nProps := ptd^.PropCount; if nProps > 0 then begin GetMem(pProps, SizeOf(PPropInfo) * nProps); try GetPropInfos(pti, pProps); for Loop:=0 to nProps - 1 do begin {$ifdef fpc} ppi := pProps^[Loop]; {$else} ppi := pProps[Loop]; {$endif} PropOffset := Offset + (Loop + 1) * SizeOf(Pointer); PropInfos.Add(ppi, PropOffset); end; finally FreeMem(pProps, SizeOf(PPropInfo) * nProps); end; end; if Assigned(AddPropInfosDRTTI) then AddPropInfosDRTTI(PClass, PropInfos); end; function TClassRec.GetIntfOffset(const GUID: TGUID): Integer; var I: Integer; begin result := 0; I := IntfList.IndexOf(GUID); if I = -1 then Exit; result := InstSize - SizeOf(Pointer) - IntfList.Count * SizeOf(Pointer) + I * SizeOf(Pointer); end; function TClassRec.GetIntfTableSize: Integer; begin result := SizeOf(Integer) + // EntryCount IntfList.Count * SizeOf(TInterfaceEntry); end; // -- TClassList --------------------------------------------------------------- constructor TClassList.Create; begin inherited; L := TStringList.Create; end; function TClassList.GetCount: Integer; begin result := L.Count; end; function TClassList.GetClassRec(I: Integer): TClassRec; begin result := TClassRec(L.Objects[I]); end; function TClassList.GetName(I: Integer): String; begin result := L[I]; end; function TClassList.IndexOf(const S: String): Integer; begin result := L.IndexOf(S); end; function TClassList.Add(const FullName: String; Host: Boolean): TClassRec; begin result := TClassRec.Create(nil, 0, false); result.FullName := FullName; result.Host := Host; L.AddObject(ExtractName(FullName), result); end; function TClassList.AddEx(const FullName: String; ClassIndex: Integer): TClassRec; begin while L.Count < ClassIndex + 1 do L.Add(''); if Assigned(L.Objects[ClassIndex]) then {$IFDEF ARC} L.Objects[ClassIndex] := nil; {$ELSE} L.Objects[ClassIndex].Free; {$ENDIF} result := TClassRec.Create(nil, 0, false); result.FullName := FullName; L.Objects[ClassIndex] := result; end; function TClassList.AddClass(C: TClass; const FullName: String; Host: Boolean; Offset: Integer): TClassRec; var I: Integer; S: String; begin S := C.ClassName; I := L.IndexOf(S); if I = -1 then begin result := TClassRec.Create(C, Offset, Host); L.AddObject(S, result); end else begin result := TClassRec(L.Objects[I]); if Assigned(result) then begin if result.PClass = nil then begin FreeAndNil(result); result := TClassRec.Create(C, Offset, Host); end else result.AddPropInfos; end else result := TClassRec.Create(C, Offset, Host); L.Objects[I] := result; end; result.FullName := FullName; end; function TClassList.AddClassEx(C: TClass; const FullName: String; Host: Boolean; Offset: Integer; ClassIndex: Integer): TClassRec; begin while L.Count < ClassIndex + 1 do L.AddObject('', nil); result := TClassRec(L.Objects[ClassIndex]); if Assigned(result) then begin if result.PClass = nil then begin FreeAndNil(result); result := TClassRec.Create(C, Offset, Host); end else result.AddPropInfos; end else result := TClassRec.Create(C, Offset, Host); L.Objects[ClassIndex] := result; result.FullName := FullName; end; procedure TClassList.SetupInterfaces(CodePtr: Pointer); var I: Integer; begin for I:=0 to Count - 1 do Records[I].SetupInterfaces(CodePtr); end; procedure TClassList.Clear; var I: Integer; begin for I:=0 to L.Count - 1 do begin if L.Objects[I] <> nil then {$IFDEF ARC} L.Objects[I] := nil; {$ELSE} L.Objects[I].Free; {$ENDIF} end; L.Clear; end; destructor TClassList.Destroy; begin Clear; FreeAndNil(L); inherited; end; function TClassList.FindClass(C: TClass): Integer; var I: Integer; begin result := -1; for I:=0 to L.Count - 1 do if Records[I].PClass = C then begin result := I; Exit; end; end; function TClassList.Lookup(const FullName: String): TClassRec; var I: Integer; ClassRec: TClassRec; begin result := nil; for I:=0 to Count - 1 do begin ClassRec := Records[I]; if StrEql(ClassRec.FullName, FullName) then begin result := ClassRec; Exit; end; end; end; function TClassList.LookupClassRec(C: TClass): TClassRec; var I: Integer; ClassRec: TClassRec; begin result := nil; for I:=0 to Count - 1 do begin ClassRec := Records[I]; if StrEql(ClassRec.PClass.ClassName, C.ClassName) then begin result := ClassRec; Exit; end; end; end; function TClassList.GetSize: Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try SaveToStream(S); result := S.Size; finally FreeAndNil(S); end; end; type TSaveClassRec = packed record Offset: Integer; SizeOfScriptClassFields: Integer; DestructorProgOffset: Integer; AfterConstructionProgOffset: Integer; BeforeDestructionProgOffset: Integer; SafeCallExceptionProgOffset: Integer; DispatchProgOffset: Integer; DefaultHandlerProgOffset: Integer; NewInstanceProgOffset: Integer; FreeInstanceProgOffset: Integer; InstSize: Integer; {$IFDEF UNIC} ToStringProgOffset: Integer; GetHashCodeProgOffset: Integer; EqualsProgOffset: Integer; {$ENDIF} Host: Boolean; end; procedure PackRec(var S: TSaveClassRec; const R: TClassRec); begin S.Offset := R.Offset; S.InstSize := R.InstSize; S.DestructorProgOffset := R.DestructorProgOffset; S.AfterConstructionProgOffset := R.AfterConstructionProgOffset; S.BeforeDestructionProgOffset := R.BeforeDestructionProgOffset; S.SafeCallExceptionProgOffset := R.SafeCallExceptionProgOffset; S.DispatchProgOffset := R.DispatchProgOffset; S.DefaultHandlerProgOffset := R.DefaultHandlerProgOffset; S.NewInstanceProgOffset := R.NewInstanceProgOffset; S.FreeInstanceProgOffset := R.FreeInstanceProgOffset; S.SizeOfScriptClassFields := R.SizeOfScriptClassFields; S.Host := R.Host; {$IFDEF UNIC} S.ToStringProgOffset := R.ToStringProgOffset; S.GetHashCodeProgOffset := R.GetHashCodeProgOffset; S.EqualsProgOffset := R.EqualsProgOffset; {$ENDIF} end; procedure UnPackRec(S: TClassRec; const R: TSaveClassRec); begin S.Offset := R.Offset; S.InstSize := R.InstSize; S.DestructorProgOffset := R.DestructorProgOffset; S.AfterConstructionProgOffset := R.AfterConstructionProgOffset; S.BeforeDestructionProgOffset := R.BeforeDestructionProgOffset; S.SafeCallExceptionProgOffset := R.SafeCallExceptionProgOffset; S.DispatchProgOffset := R.DispatchProgOffset; S.DefaultHandlerProgOffset := R.DefaultHandlerProgOffset; S.NewInstanceProgOffset := R.NewInstanceProgOffset; S.FreeInstanceProgOffset := R.FreeInstanceProgOffset; S.SizeOfScriptClassFields := R.SizeOfScriptClassFields; S.Host := R.Host; {$IFDEF UNIC} S.ToStringProgOffset := R.ToStringProgOffset; S.GetHashCodeProgOffset := R.GetHashCodeProgOffset; S.EqualsProgOffset := R.EqualsProgOffset; {$ENDIF} end; procedure TClassList.SaveToStream(S: TStream); var I: Integer; SR: TSaveClassRec; begin SaveStringListToStream(L, S); for I:=0 to L.Count - 1 do begin PackRec(SR, Records[I]); with Records[I] do begin SaveStringToStream(FullName, S); SaveStringToStream(ParentFullName, S); S.Write(SR, SizeOf(SR)); IntfList.SaveToStream(S); if not Host then begin SaveIntDynarrayToStream(BytecodeMethodEntryList, S); S.Write(VirtualMethodEntryList, SizeOf(VirtualMethodEntryList)); end; end; end; end; procedure TClassList.LoadFromStream(S: TStream; Version: Integer); var I: Integer; RI: TClassRec; SR: TSaveClassRec; begin Clear; LoadStringListFromStream(L, S); for I:=0 to L.Count - 1 do begin L.Objects[I] := TClassRec.Create(nil, 0, false); RI := Records[I]; with RI do begin FullName := LoadStringFromStream(S); ParentFullName := LoadStringFromStream(S); S.Read(SR, SizeOf(SR)); UnPackRec(RI, SR); IntfList.LoadFromStream(S); if not Host then begin BytecodeMethodEntryList := LoadIntDynarrayFromStream(S); S.Read(VirtualMethodEntryList, SizeOf(VirtualMethodEntryList)); end; PClass := nil; end; end; end; function TClassList.GetByteCodeMethodEntryIndex(N: Integer): Integer; var I, J, V, L: Integer; R: TClassRec; begin result := -1; for I := Count - 1 downto 0 do begin R := Records[I]; L := System.Length(R.ByteCodeMethodEntryList); for J := 0 to L - 1 do begin V := R.ByteCodeMethodEntryList[J]; if V = 0 then break; if V = N then begin result := J; Exit; end; end; end; end; end.
unit DmMemo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TDmMemo = class(TMemo) private { Private declarations } FTransparentMouse: Boolean; procedure Wm_mousedown(var Msg: TMessage); message WM_LBUTTONDOWN; procedure Wm__mousedown(var Msg: TMessage); message WM_RBUTTONDOWN; procedure Wm_mouseUp(var Msg: TMessage); message WM_RBUTTONUP; procedure Wm__mouseUp(var Msg: TMessage); message WM_LBUTTONUP; procedure Wm_butondblclick(var Msg: TMessage); message WM_LBUTTONDBLCLK; procedure SetTransparentMouse(const Value: Boolean); public { Protected declarations } constructor Create(AOwner: TComponent); override; public { Public declarations } published { Published declarations } property TransparentMouse: Boolean read FTransparentMouse write SetTransparentMouse; end; procedure Register; implementation procedure Register; begin RegisterComponents('Dm', [TDmMemo]); end; { TDmMemo } constructor TDmMemo.Create(AOwner: TComponent); begin inherited; TransparentMouse := False; end; procedure TDmMemo.SetTransparentMouse(const Value: Boolean); begin FTransparentMouse := Value; end; procedure TDmMemo.Wm_butondblclick(var Msg: Tmessage); begin if TransparentMouse then (Owner as TWincontrol).Perform(WM_LBUTTONDBLCLK, Msg.Wparam, Msg.Lparam); end; procedure TDmMemo.Wm_mousedown(var Msg: Tmessage); begin if TransparentMouse then (Owner as TWincontrol).Perform(Wm_lbuttondown, Msg.Wparam, Msg.Lparam); end; procedure TDmMemo.Wm_mouseUp(var Msg: Tmessage); begin Screen.Cursor := crDefault; if TransparentMouse then (Owner as TWincontrol).Perform(Wm_lbuttonUp, Msg.Wparam, Msg.Lparam); end; procedure TDmMemo.Wm__mousedown(var Msg: Tmessage); begin if TransparentMouse then (Owner as TWincontrol).Perform(Wm_rbuttondown, Msg.Wparam, Msg.Lparam); end; procedure TDmMemo.Wm__mouseUp(var Msg: Tmessage); begin Screen.Cursor := crDefault; if TransparentMouse then (Owner as TWincontrol).Perform(Wm_RbuttonUp, Msg.Wparam, Msg.Lparam); end; end.
unit AppContxt; interface uses Classes,SysUtils,UniEngine,Uni,UniConnct,Class_Work,Class_Prod; type TAppContxt=class(TUniEngine) private FListWork:TStringList; FListDoct:TStringList; FListProd:TStringList; public procedure UpdateWork; procedure UpdateDoct; procedure UpdateProd; public function GetObjtWork(AWorkIdex:Integer;AUnitLink:string='-1';IsCreate:Boolean=False):TWORK; function GetWorkName(AWorkIdex:Integer):string; function GetObjtDoct(ADoctIdex:Integer;AUnitLink:string='-1';IsCreate:Boolean=False):TWORK; function GetDoctName(ADoctIdex:Integer):string; function GetObjtProd(AProdIdex:Integer;AUnitLink:string='-1';isCreate:Boolean=False):TProd; function GetProdName(AProdIdex:Integer):string; public constructor Create; destructor Destroy; override; end; const CONST_PATH_PRINT_SUIT='Ì×´ò.fr3'; var AppContxtEx:TAppContxt; implementation uses Class_AppUtil,Class_KzUtils; { TAppContxt } constructor TAppContxt.Create; begin FListWork:=nil; FListDoct:=nil; end; destructor TAppContxt.Destroy; begin if FListWork<>nil then TKzUtils.TryFreeAndNil(FListWork); if FListDoct<>nil then TKzUtils.TryFreeAndNil(FListDoct); if FListProd<>nil then TKzUtils.TryFreeAndNil(FListProd); inherited; end; function TAppContxt.GetDoctName(ADoctIdex: Integer): string; var WorkA:TWORK; begin Result:=''; WorkA:=GetObjtDoct(ADoctIdex); if WorkA<>nil then begin Result:=WorkA.WORKNAME; end; end; function TAppContxt.GetObjtDoct(ADoctIdex: Integer;AUnitLink:string;IsCreate:Boolean): TWORK; var IdexA:Integer; begin Result:=nil; IdexA:=-1; if FListDoct=nil then begin UpdateDoct; end; if (FListDoct=nil) or (FListDoct.Count=0) then Exit; IdexA:=FListDoct.IndexOf(Format('%S-%D',[AUnitLink,ADoctIdex])); if IdexA<>-1 then begin if IsCreate then begin Result:=TWORK.CopyIt(TWORK(FListDoct.Objects[IdexA])); end else begin Result:=TWORK(FListDoct.Objects[IdexA]); end; end; end; function TAppContxt.GetObjtProd(AProdIdex: Integer; AUnitLink: string; isCreate: Boolean): TProd; var IdexA:Integer; begin Result:=nil; IdexA:=-1; if FListProd=nil then begin UpdateProd; end; if (FListProd=nil) or (FListProd.Count=0) then Exit; IdexA:=FListProd.IndexOf(Format('%S-%D',[AUnitLink,AProdIdex])); if IdexA<>-1 then begin if IsCreate then begin Result:=TProd.CopyIt(TProd(FListProd.Objects[IdexA])); end else begin Result:=TProd(FListProd.Objects[IdexA]); end; end; end; function TAppContxt.GetObjtWork(AWorkIdex: Integer;AUnitLink:string;IsCreate:Boolean): TWORK; var IdexA:Integer; begin Result:=nil; IdexA:=-1; if FListWork=nil then begin UpdateWork; end; if (FListWork=nil) or (FListWork.Count=0) then Exit; IdexA:=FListWork.IndexOf(Format('%S-%D',[AUnitLink,AWorkIdex])); if IdexA<>-1 then begin if IsCreate then begin Result:=TWORK.CopyIt(TWORK(FListWork.Objects[IdexA])); end else begin Result:=TWORK(FListWork.Objects[IdexA]); end; end; end; function TAppContxt.GetProdName(AProdIdex: Integer): string; var ProdA:TProd; begin Result:=''; ProdA:=GetObjtProd(AProdIdex); if ProdA<>nil then begin Result:=ProdA.ProdName; end; end; function TAppContxt.GetWorkName(AWorkIdex: Integer): string; var WorkA:TWORK; begin Result:=''; WorkA:=GetObjtWork(AWorkIdex); if WorkA<>nil then begin Result:=WorkA.WORKNAME; end; end; procedure TAppContxt.UpdateDoct; var SQLA:string; UniConnct:TUniConnection; begin if FListDoct=nil then begin FListDoct:=TStringList.Create; end; SQLA:='SELECT * FROM TBL_DOCT ORDER BY WORK_IDEX'; try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA); //-< TWork.ListDB(SQLA,UniConnct,FListDoct); //-> finally FreeAndNil(UniConnct); end; end; procedure TAppContxt.UpdateProd; var SQLA:string; UniConnct:TUniConnection; begin if FListProd=nil then begin FListProd:=TStringList.Create; end; SQLA:='SELECT * FROM TBL_PROD ORDER BY PROD_ORDR'; try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA); //-< TProd.ListDB(SQLA,UniConnct,FListProd); //-> finally FreeAndNil(UniConnct); end; end; procedure TAppContxt.UpdateWork; var SQLA:string; UniConnct:TUniConnection; begin if FListWork=nil then begin FListWork:=TStringList.Create; end; SQLA:='SELECT * FROM TBL_WORK ORDER BY WORK_IDEX'; try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA); //-< TWork.ListDB(SQLA,UniConnct,FListWork); //-> finally FreeAndNil(UniConnct); end; end; initialization begin AppContxtEx:=TAppContxt.Create; end; finalization begin if AppContxtEx<>nil then FreeAndNil(AppContxtEx); end; end.
{+------------------------------------------------------------ | Unit Textcontainer | | Version: 1.0 Created: 12.03.99 | Last Modified: 12.03.99 | Author : P. Below | Project: Common components | Description: | Implements a simple component to import textfiles into | a project at design-time via clipboard. | | http://www.delphigroups.info/2/2a/314010.html +------------------------------------------------------------} {$IFDEF FPC} {$mode delphi}{$H+} {$ELSE} {$I \pas-win\switches.inc} {$ENDIF} Unit TextContainerU; Interface Uses SysUtils, Classes; Type TTextContainer = Class(TComponent) Private { Private declarations } FLines: TStrings; Procedure SetLines( aList: TStrings ); Function GetText: String; Public { Public declarations } Constructor Create( aOwner: TComponent ); override; Destructor Destroy; override; Property Text: String read GetText; Published { Published declarations } Property Lines: TStrings read FLines write SetLines; End; Procedure Register; Implementation {$IFDEF FPC} uses LResources; {$ENDIF} Procedure Register; Begin RegisterComponents('Samples', [TTextContainer]); End; {+--------------------------- | Methods of TTextContainer +--------------------------} Procedure TTextContainer.SetLines( aList: TStrings ); Begin FLines.Assign( aList ); End; { TTextContainer.SetLines } Function TTextContainer.GetText: String; Begin Result := FLines.Text; End; { TTextContainer.GetText } Constructor TTextContainer.Create( aOwner: TComponent ); Begin inherited Create( aOwner ); FLines := TStringlist.create; End; { TTextContainer.Create } Destructor TTextContainer.Destroy; Begin FLines.Free; inherited Destroy; End; { TTextContainer.Destroy } {$IFDEF FPC} initialization {$I textcontainer.lrs} {$ENDIF} End.
unit FmGCE; interface uses WinProcs, WinTypes, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Spin, GifDecl; type TGCEDialog = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; PackedFieldsEdit: TSpinEdit; DelaytimeEdit: TSpinEdit; TransparentColorIndexEdit: TSpinEdit; TerminatorEdit: TSpinEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; private { Private declarations } public { Public declarations } constructor Create(GCE: TGraphicControlExtension); function GetGCE: TGraphicControlExtension; end; { TGCEDialog } var GCEDialog: TGCEDialog; implementation {$R *.DFM} constructor TGCEDialog.Create(GCE: TGraphicControlExtension); begin { TGCEDialog.Create } inherited Create(nil); with GCE do begin PackedFieldsEdit.Value := PackedFields; DelayTimeEdit.Value := DelayTime; TransparentColorIndexEdit.Value := TransparentColorIndex; TerminatorEdit.Value := Terminator; end; end; { TGCEDialog.Create } function TGCEDialog.GetGCE: TGraphicControlExtension; begin { TGCEDialog.GetGCE } with Result do begin PackedFields := PackedFieldsEdit.Value; DelayTime := DelayTimeEdit.Value; TransparentColorIndex := TransparentColorIndexEdit.Value; Terminator := TerminatorEdit.Value; end; end; { TGCEDialog.GetGCE } end. { unit FmGCE }
// glwin32fullscreenviewer {: win32 specific full-screen viewer.<p> Currently TForm+TGLSceneViewer based, may be made into a standalone Win32 control someday, so don't assume there is a TForm in your code.<p> <b>History : </b><font size=-1><ul> <li>24/07/03 - EG - Creation from GLWin32Viewer split </ul></font> } unit GLLCLFullscreenViewer; interface {$i GLScene.inc} uses forms, lcltype, messages, classes, glscene, controls, menus ,glviewer//, gllinuxcontext {$ifdef LCLGTK} , gllingtkcontext {$endif} {$ifdef LCLGTK2} , GLWidgetContext {$endif} {$ifdef LCLWIN32} ,windows {$endif} ; type // TGLScreenDepth // TGLScreenDepth = (sd8bits, sd16bits, sd24bits, sd32bits); // TGLFullScreenViewer // {: A FullScreen viewer.<p> This non visual viewer will, when activated, use the full screen as rendering surface. It will also switch/restore videomode depending on the required width/height.<br> This is performed by creating an underlying TForm and using its surface for rendering OpenGL, "decent" ICDs will automatically use PageFlipping instead of BlockTransfer (slower buffer flipping mode used for windowed OpenGL).<br> Note: if you terminate the application either via a kill or in the IDE, the original resolution isn't restored. } TGLFullScreenViewer = class (TGLNonVisualViewer) private { Private Declarations } FForm : TForm; FScreenDepth : TGLScreenDepth; FActive : Boolean; FSwitchedResolution : Boolean; FUpdateCount : Integer; FOnMouseDown : TMouseEvent; FOnMouseUp : TMouseEvent; FOnMouseMove : TMouseMoveEvent; FOnMouseWheel : TMouseWheelEvent; FOnClick, FOnDblClick : TNotifyEvent; FOnKeyDown : TKeyEvent; FOnKeyUp : TKeyEvent; FOnKeyPress : TKeyPressEvent; FOnClose : TCloseEvent; FOnCloseQuery : TCloseQueryEvent; FOldWndProc : TWndMethod; FStayOnTop : Boolean; FVSync : TVSyncMode; FRefreshRate : Integer; FCursor : TCursor; FPopupMenu : TPopupMenu; protected { Protected Declarations } procedure SetScreenDepth(const val : TGLScreenDepth); procedure SetActive(const val : Boolean); procedure SetOnMouseDown(const val : TMouseEvent); procedure SetOnMouseUp(const val : TMouseEvent); procedure SetOnMouseMove(const val : TMouseMoveEvent); procedure SetOnMouseWheel(const val : TMouseWheelEvent); procedure SetOnClick(const val : TNotifyEvent); procedure SetOnDblClick(const val : TNotifyEvent); procedure SetOnCloseQuery(const val : TCloseQueryEvent); procedure SetOnClose(const val : TCloseEvent); procedure SetOnKeyUp(const val : TKeyEvent); procedure SetOnKeyDown(const val : TKeyEvent); procedure SetOnKeyPress(const val : TKeyPressEvent); procedure SetStayOnTop(const val : Boolean); procedure SetCursor(const val : TCursor); procedure SetPopupMenu(const val : TPopupMenu); function GetHandle : HWND; procedure DoBeforeRender(Sender : TObject); procedure DoBufferChange(Sender : TObject); override; procedure DoBufferStructuralChange(Sender : TObject); override; procedure PrepareGLContext; override; procedure Startup; procedure Shutdown; procedure BindFormEvents; procedure DoCloseQuery(Sender: TObject; var CanClose: Boolean); procedure DoPaint(Sender : TObject); procedure WndProc(var Message: TMessage); procedure DoActivate(Sender : TObject); procedure DoDeactivate(Sender : TObject); public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Render(baseObject : TGLBaseSceneObject = nil); override; {: Adjusts property so that current resolution will be used.<p> Call this method if you want to make sure video mode isn't switched. } procedure UseCurrentResolution; procedure BeginUpdate; procedure EndUpdate; {: Activates/deactivates full screen mode.<p> } property Active : Boolean read FActive write SetActive; {: Read access to the underlying form handle.<p> Returns 0 (zero) if the viewer is not active or has not yet instantiated its form. } property Handle : HWND read GetHandle; published { Public Declarations } {: Requested ScreenDepth. } property ScreenDepth : TGLScreenDepth read FScreenDepth write SetScreenDepth default sd32bits; {: Specifies if the underlying form is "fsStayOnTop".<p> The benefit of StayOnTop is that it hides the windows bar and other background windows. The "fsStayOnTop" is automatically switched off/on when the underlying form loses/gains focus.<p> It is recommended not to use StayOnTop while running in the IDE or during the debugging phase.<p> } property StayOnTop : Boolean read FStayOnTop write SetStayOnTop default False; {: Specifies if the refresh should be synchronized with the VSync signal.<p> If the underlying OpenGL ICD does not support the WGL_EXT_swap_control extension, this property is ignored. } property VSync : TVSyncMode read FVSync write FVSync default vsmSync; {: Screen refresh rate.<p> Use zero for system default. This property allows you to work around the winxp bug that limits uses a refresh rate of 60hz when changeing resolution. it is however suggested to give the user the opportunity to adjust it instead of having a fixed value (expecially beyond 75hz or for resolutions beyond 1024x768).<p> the value will be automatically clamped to the highest value *reported* compatible with the monitor. } property refreshrate : integer read frefreshrate write frefreshrate; property Cursor : TCursor read FCursor write SetCursor default crDefault; property PopupMenu : TPopupMenu read FPopupMenu write SetPopupMenu; property OnClose : TCloseEvent read FOnClose write SetOnClose; property OnKeyUp : TKeyEvent read FOnKeyUp write SetOnKeyUp; property OnKeyDown : TKeyEvent read FOnKeyDown write SetOnKeyDown; property OnKeyPress : TKeyPressEvent read FOnKeyPress write SetOnKeyPress; property OnCloseQuery : TCloseQueryEvent read FOnCloseQuery write SetOnCloseQuery; property OnClick : TNotifyEvent read FOnClick write SetOnClick; property OnDblClick : TNotifyEvent read FOnDblClick write SetOnDblClick; property OnMouseDown : TMouseEvent read FOnMouseDown write SetOnMouseDown; property OnMouseUp : TMouseEvent read FOnMouseUp write SetOnMouseUp; property OnMouseMove : TMouseMoveEvent read FOnMouseMove write SetOnMouseMove; property OnMouseWheel : TMouseWheelEvent read FOnMouseWheel write SetOnMouseWheel; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses opengl1x, sysutils, glcrossplatform, glscreen; const cScreenDepthToBPP : array [sd8bits..sd32bits] of Integer = (8, 16, 24, 32); // ------------------ // ------------------ TGLFullScreenViewer ------------------ // ------------------ // Create // constructor TGLFullScreenViewer.Create(AOwner: TComponent); begin inherited Create(AOwner); Width:=800; Height:=600; FScreenDepth:=sd32bits; FVSync:=vsmSync; FCursor:=crDefault; Buffer.ViewerBeforeRender:=DoBeforeRender; end; // Destroy // destructor TGLFullScreenViewer.Destroy; begin Active:=False; inherited Destroy; end; // DoBeforeRender // procedure TGLFullScreenViewer.DoBeforeRender(Sender : TObject); begin SetupVSync(VSync); end; // DoBufferChange // procedure TGLFullScreenViewer.DoBufferChange(Sender : TObject); begin if Assigned(FForm) and (not Buffer.Rendering) then begin FForm.Invalidate; end; end; // DoBufferStructuralChange // procedure TGLFullScreenViewer.DoBufferStructuralChange(Sender : TObject); begin if Active and (FUpdateCount=0) then begin Shutdown; Startup; end; end; // PrepareGLContext // procedure TGLFullScreenViewer.PrepareGLContext; begin // nothing yet end; // Render // procedure TGLFullScreenViewer.Render(baseObject : TGLBaseSceneObject = nil); begin LoadOpenGL; if Buffer.RenderingContext=nil then begin Buffer.CreateRC(0, False); end; Buffer.Render(baseObject); end; // BeginUpdate // procedure TGLFullScreenViewer.BeginUpdate; begin Inc(FUpdateCount); end; // EndUpdate // procedure TGLFullScreenViewer.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount=0 then begin if Active then DoBufferStructuralChange(Self) end else if FUpdateCount<0 then begin FUpdateCount:=0; Assert(False, 'Unbalanced Begin/EndUpdate'); end; end; // UseCurrentResolution // procedure TGLFullScreenViewer.UseCurrentResolution; begin BeginUpdate; try Width:=Screen.Width; Height:=Screen.Height; case GetCurrentColorDepth of 24 : ScreenDepth:=sd24bits; 16 : ScreenDepth:=sd16bits; 8 : ScreenDepth:=sd8bits; else // highest depth possible otherwise ScreenDepth:=sd32bits; end; finally EndUpdate; end; end; // SetActive // procedure TGLFullScreenViewer.SetActive(const val : Boolean); begin if val<>FActive then begin if FActive then ShutDown else Startup; end; end; // Startup // procedure TGLFullScreenViewer.Startup; var res : TResolution; dc : HDC; begin Assert(FForm=nil); res:=GetIndexFromResolution(Width, Height, cScreenDepthToBPP[ScreenDepth]); if res=0 then raise Exception.Create('Unsupported video mode'); FForm:=TForm.Create(nil); with FForm do begin if StayOnTop then FormStyle:=fsStayOnTop else FormStyle:=fsNormal; // Following lines doesn't seem to work on ATI hardware, // so we do it via API calls // BorderStyle:=bsNone; BorderStyle:=bsSizeable; {$IFDEF WINDOWS} SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) and not WS_CAPTION); {$ENDIF} Cursor:=Self.Cursor; PopupMenu:=Self.PopupMenu; ClientWidth:=Self.Width; ClientHeight:=Self.Height; WindowState:=wsMaximized; BindFormEvents; FOldWndProc:=WindowProc; WindowProc:=WndProc; end; // Hides Taskbar {$IFDEF WINDOWS} ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_HIDE); {$ENDIF} // Switch video mode if (Screen.Width<>Width) or (Screen.Height<>Height) or (GetCurrentColorDepth<>cScreenDepthToBPP[ScreenDepth]) then begin SetFullscreenMode(res, FRefreshRate); FSwitchedResolution:=True; end else FSwitchedResolution:=False; FForm.Show; Buffer.Resize(Width, Height); {$IFDEF WINDOWS} dc:=GetDC(FForm.Handle); {$ENDIF} Buffer.CreateRC(dc, False); // todo FActive:=True; end; // Shutdown // procedure TGLFullScreenViewer.Shutdown; var f : TForm; begin try Buffer.DestroyRC; f:=FForm; FForm:=nil; f.WindowProc:=FOldWndProc; f.Release; finally // attempt that, at the very least... if FSwitchedResolution then RestoreDefaultMode; end; // Restore Taskbar {$IFDEF WINDOWS} ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_SHOWNA); {$ENDIF} FActive:=False; end; // BindFormEvents // procedure TGLFullScreenViewer.BindFormEvents; begin if Assigned(FForm) then with FForm do begin OnMouseDown:=FOnMouseDown; OnMouseUp:=FOnMouseUp; OnMouseMove:=FOnMouseMove; OnMouseWheel:=FOnMouseWheel; OnClick:=FOnClick; // OnDblClick:=FOnDblClick; //Dont know why but this gives an AV OnCloseQuery:=DoCloseQuery; OnClose:=FOnClose; OnKeyUp:=FOnKeyUp; OnKeyDown:=FOnKeyDown; OnKeyPress:=FOnKeyPress; OnActivate:=DoActivate; OnDeactivate:=DoDeactivate; OnPaint:=DoPaint; end; end; // DoCloseQuery // procedure TGLFullScreenViewer.DoCloseQuery(Sender: TObject; var CanClose: Boolean); begin if Assigned(FOnCloseQuery) then FOnCloseQuery(Sender, CanClose); if CanClose then Shutdown; end; // DoPaint // procedure TGLFullScreenViewer.DoPaint(Sender : TObject); begin if Assigned(FForm) then Render; end; // WndProc // procedure TGLFullScreenViewer.WndProc(var Message: TMessage); begin case Message.Msg of WM_ERASEBKGND : begin Message.Result:=1; // do nothing! end; else FOldWndProc(Message); end; end; // DoActivate // procedure TGLFullScreenViewer.DoActivate(Sender : TObject); begin if Assigned(FForm) and StayOnTop then FForm.FormStyle:=fsStayOnTop; end; // DoDeactivate // procedure TGLFullScreenViewer.DoDeactivate(Sender : TObject); begin if Assigned(FForm) and StayOnTop then FForm.FormStyle:=fsNormal; end; // SetScreenDepth // procedure TGLFullScreenViewer.SetScreenDepth(const val : TGLScreenDepth); begin if FScreenDepth<>val then begin FScreenDepth:=val; DoBufferStructuralChange(Self); end; end; // SetStayOnTop // procedure TGLFullScreenViewer.SetStayOnTop(const val : Boolean); begin if val<>FStayOnTop then begin FStayOnTop:=val; DoBufferStructuralChange(Self); end; end; // SetOnCloseQuery // procedure TGLFullScreenViewer.SetOnCloseQuery(const val : TCloseQueryEvent); begin fonclosequery:=val; // this one uses a special binding end; // SetOnClose // procedure TGLFullScreenViewer.SetOnClose(const val : TCloseEvent); begin FOnClose:=val; BindFormEvents; end; // SetOnKeyPress // procedure TGLFullScreenViewer.SetOnKeyPress(const val : TKeyPressEvent); begin FOnKeyPress:=val; BindFormEvents; end; // SetOnKeyUp // procedure TGLFullScreenViewer.SetOnKeyUp(const val : TKeyEvent); begin FOnKeyUp:=val; BindFormEvents; end; // SetOnKeyDown // procedure TGLFullScreenViewer.SetOnKeyDown(const val : TKeyEvent); begin FOnKeyDown:=val; BindFormEvents; end; // SetOnMouseWheel // procedure TGLFullScreenViewer.SetOnMouseWheel(const val : TMouseWheelEvent); begin FOnMouseWheel:=val; BindFormEvents; end; // SetOnClick // procedure TGLFullScreenViewer.SetOnClick(const val : TNotifyEvent); begin FOnClick:=val; BindFormEvents; end; // SetOnDblClick // procedure TGLFullScreenViewer.SetOnDblClick(const val : TNotifyEvent); begin FOnDblClick:=val; BindFormEvents; end; // SetOnMouseMove // procedure TGLFullScreenViewer.SetOnMouseMove(const val : TMouseMoveEvent); begin FOnMouseMove:=val; BindFormEvents; end; // SetOnMouseDown // procedure TGLFullScreenViewer.SetOnMouseDown(const val : TMouseEvent); begin FOnMouseDown:=val; BindFormEvents; end; // SetOnMouseUp // procedure TGLFullScreenViewer.SetOnMouseUp(const val : TMouseEvent); begin FOnMouseUp:=val; BindFormEvents; end; // SetCursor // procedure TGLFullScreenViewer.SetCursor(const val : TCursor); begin if val<>FCursor then begin FCursor:=val; if Assigned(FForm) then FForm.Cursor:=val; end; end; // SetPopupMenu // procedure TGLFullScreenViewer.SetPopupMenu(const val : TPopupMenu); begin if val<>FPopupMenu then begin FPopupMenu:=val; if Assigned(FForm) then FForm.PopupMenu:=val; end; end; // GetHandle // function TGLFullScreenViewer.GetHandle : HWND; begin if Assigned(FForm) then Result:=FForm.Handle else Result:=0; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClasses([TGLFullScreenViewer]); end.
{ (R) \ÜÜÜÜÜ \Ü \Ü \ÜÜ \Ü \ÜÜÜÜ \ÜÜÜÜÜÜ \ÜÜÜÜ \ÜÜ \Ü \Ü \Ü \Ü \Ü \Ü\Ü \Ü \Ü \Ü \Ü \Ü \Ü\Ü \Ü \Ü \Ü \Ü \Ü \Ü \Ü\Ü \Ü \ÜÜ \ÜÜÜ \Ü \Ü \Ü \Ü\Ü \Ü \Ü \Ü \Ü \Ü \ÜÜ \Ü \Ü \Ü \Ü \Ü \Ü \ÜÜ \ÜÜÜÜÜ \ÜÜÜÜ \Ü \Ü \ÜÜÜÜ \ÜÜÜÜÜÜ \ÜÜÜÜ \Ü \Ü ÚÄÄ ÚÄÄ ÚÄÄÄÄ ÚÄÄ ÚÄÄ ÚÄ ÚÄ ÚÄÄ ÚÄÄ ÚÄÄÄÄ ÚÄÄ ÚÄÄ ÚÄ ÚÄ ÚÄÄÄÄÄÄ ÚÄÄ ÚÄÄÄÄ } {$G+} Unit Dungeon; interface uses dos,crt,graph; var winnbr : word; const inof = false ; outof = true ; type rgb = record r : byte; g : byte; b : byte; end; mouse = object function start : word ; procedure show ; procedure hide ; function button (wht : byte) : boolean ; function x : word ; function y : word ; function area(x1,y1,x2,y2: word) : boolean; procedure setxy (xi,yi : word) ; procedure setarea (x1,y1,x2,y2 : word) ; procedure setnoarea (x1,y1,x2,y2 : word) ; procedure sethandle (pt:pointer;evt:word) ; end; paletype = array[0..255,1..3] of shortint ; headtype = record signature : array[1..2] of char; nfiles : byte; end; entrytype = record filename : string[12]; startentry : longint; length : longint; end; {FUNCTIONS} function ifbyte (valor : boolean; v1,v2 : byte ) : byte; {IF's} function ifword (valor : boolean; v1,v2 : word ) : word; function ifchar (valor : boolean; v1,v2 : char ) : char; function ifstring(valor : boolean; v1,v2 : string ) : string; function ifint (valor : boolean; v1,v2 : integer) : integer; function getpoint(x,y : word) : byte; function replicate(ch : char; qtd : byte) : string; function space(qtd : byte) : string; function alltrim(strini : string) : string; function upper(str:string) : string; function byteval(str : string) : byte; function wordval(str : string) : word; function min(a,b : integer) : integer; function max(a,b : integer) : integer; function exist(fname : string) : boolean; function fsize(fname : string) : longint; function openbigfile(nfin : string; var fin : file) : byte; {PROCEDURES} procedure swapbyte(var v1,v2 : byte); procedure swapword(var v1,v2 : word); procedure cursor(lin_ini,lin_fin : byte); procedure pchar(x,y : byte; ch : char); procedure say(x,y : byte; msg : string); procedure modifycolor(x,y,cor : byte); procedure box(x1,y1,x2,y2 : byte; frame : string); procedure setrgb(cor,r,g,b : byte); procedure getrgb(color : word; var trgb : rgb); procedure setcolorfill(x : word); procedure box3d(x1,y1,x2,y2 : word; elev : byte; efct : boolean; int : word); procedure win(x1,y1,x2,y2 : word; title : string); procedure init320x200; procedure textmode; procedure video(est : byte); procedure putpoint(x,y : word; cor : byte); procedure putline(x,y,x1,y1 : word; cor : byte); procedure closingpalette(tempo : word); procedure wait; procedure filebiginfo(var fin : file; var entry : entrytype; arq : byte); procedure filebigpos(var fin : file; arq : byte); implementation { Object Mouse } function mouse.start; assembler; asm xor ax,ax int 33h cmp ax,0FFFFh jnz @naodiz mov ax,bx jmp @fim @naodiz: xor ax,ax @fim : end; {mouse.start} procedure mouse.show; assembler; asm mov ax,0001h int 33h end; {mouse.show} procedure mouse.hide; assembler; asm mov ax,0002h int 33h end; {mouse.hide} function mouse.button(wht : byte) : boolean; assembler; asm mov ax,0003h int 33h mov cl, wht shr bx, cl jc @1 @0: xor ax,ax jmp @fim @1: mov ax,0001 @fim: end; {mouse.button} function mouse.x : word; assembler; asm mov ax,0003h int 33h mov ax,cx end; {mouse.x} function mouse.y : word; assembler; asm mov ax,0003h int 33h mov ax,dx end; {mouse.y} function mouse.area(x1,y1,x2,y2 : word) : boolean; var resptmp : boolean; begin if ((mouse.x > x1) and (mouse.y > y1)) and ((mouse.x < x2) and (mouse.y < y2)) then resptmp := true else resptmp := false; area := resptmp; end; {mouse.area} procedure mouse.setxy(xi,yi : word); assembler; asm mov ax, 0004h mov cx, xi mov dx, yi int 33h end; {mouse.setxy} procedure mouse.setarea(x1,y1,x2,y2 : word); assembler; asm mov ax, 0007h mov cx, x1 mov dx, x2 int 33h mov ax, 0008h mov cx, y1 mov dx, y2 int 33h end; {mouse.setarea} procedure mouse.setnoarea(x1,y1,x2,y2 : word); assembler; asm mov ax,0010h mov cx, x1 mov dx, y1 mov si, x2 mov di, y2 int 33h end; {mouse.setnoarea} procedure mouse.sethandle(pt : pointer;evt : word); assembler; asm les dx, pt mov ax, 000Ch mov cx, evt int 33h end; {mouse.sethandle} {=====================================================} { Funcoes de tela texto } {=====================================================} procedure cursor(lin_ini,lin_fin : byte); assembler; asm mov ah, 01h mov ch, lin_ini mov cl, lin_fin int 10h end; {cursor} procedure pchar(x,y : byte; ch : char); begin dec(x); dec(y); mem[$B800:(y*80+x)*2] := ord(ch); end; procedure say(x,y : byte; msg : string); var aux : word; begin dec(x); dec(y); for aux := 1 to length(msg) do mem[$B800:((y*80+x)*2)+(aux*2)-2] := ord(msg[aux]); end; procedure modifycolor(x,y,cor : byte); begin dec(x); dec(y); mem[$B800:(((y*80) + x) shl 1) + 1] := cor; end; procedure box(x1,y1,x2,y2 : byte; frame : string); var aux : byte; begin if length(frame) < 8 then frame := frame + space(8-length(frame)); if x1 > x2 then swapbyte(x1,x2); if y1 > y2 then swapbyte(y1,y2); pchar(x1,y1,ifchar(y1=y2, frame[2], ifchar(x1=x2, frame[4], frame[1]))); pchar(x2,y1,ifchar(y1=y2, frame[2], ifchar(x1=x2, frame[4], frame[3]))); pchar(x1,y2,ifchar(y1=y2, frame[2], ifchar(x1=x2, frame[4], frame[7]))); pchar(x2,y2,ifchar(y1=y2, frame[2], ifchar(x1=x2, frame[4], frame[5]))); if x2 > x1 then for aux := x1 + 1 to x2 - 1 do begin pchar(aux,y1,frame[2]); pchar(aux,y2,frame[6]); end; if y2 > y1 then for aux := y1 + 1 to y2 - 1 do begin pchar(x1,aux,frame[8]); pchar(x2,aux,frame[4]); end; end; {=====================================================} { Funcoes de tela grafica } {=====================================================} procedure setrgb(cor,r,g,b : byte); begin port[$03C8] := cor; port[$03C9] := r; port[$03C9] := g; port[$03C9] := b; end; procedure getrgb(color : word; var trgb : rgb); var regs : registers; begin regs.ax := $1015 ; regs.bx := color ; intr($10,regs) ; trgb.r := regs.dh ; trgb.g := regs.ch ; trgb.b := regs.cl ; end; procedure setcolorfill(x : word); begin setfillstyle(solidfill,x); end; procedure box3d(x1,y1,x2,y2 : word; elev : byte; efct : boolean; int : word); begin if x1 > x2 then swapword(x1,x2); if y1 > y2 then swapword(y1,y2); if (elev > x2-x1) or (elev > y2-y1) then elev := min(x2-x1,y2-y1); setcolorfill (white) ; bar (x1,y1,x2,y2) ; setcolorfill (int) ; bar (x1+elev,y1+elev,x2-elev,y2-elev); setcolor (black) ; rectangle (x1,y1,x2,y2) ; rectangle (x1+elev,y1+elev,x2-elev,y2-elev); line (x1,y1,x1+elev,y1+elev) ; line (x2,y1,x2-elev,y1+elev) ; line (x1,y2,x1+elev,y2-elev) ; line (x2,y2,x2-elev,y2-elev) ; setcolorfill (darkgray); if efct = outof then begin floodfill(x2 - 1,y2 - 2,black); floodfill(x2 - 2,y2 - 1,black); end else begin floodfill(x1 + 1,y1 + 2,black); floodfill(x1 + 2,y1 + 1,black); end; end; procedure win(x1,y1,x2,y2 : word; title : string); var alltitle : string; begin inc (winnbr ) ; str (winnbr:3,alltitle) ; alltitle := alltitle + ': ' + title; settextstyle (defaultfont,horizdir,1) ; settextjustify (lefttext,toptext) ; box3d (x1,y1,x2,y2,3,outof,lightgray) ; box3d(x1+6,y1+6,x2-6,y1+textheight(alltitle)+13,2,outof,blue); setcolor(black); outtextxy(x1+21,y1+11,alltitle); setcolor(white); outtextxy(x1+20,y1+10,alltitle); box3d(x1+6,y1+24,x2-6,y2-6,3,inof,black); end; procedure init320x200; assembler; asm mov ax, 19 int 10h end; procedure textmode; assembler; asm mov ax, 3 int 10h end; procedure video(est : byte); assembler; asm cmp est,1 je @cont mov est,1 jmp @do @cont: mov est,0 @do: mov ah,12h mov al,est mov bl,36h int 10h end; procedure putpoint(x,y : word; cor : byte); assembler; asm MOV CX, y MOV DX, x MOV AX, CX SHL AX, 8 SHL CX, 6 ADD CX, AX ADD CX, DX MOV AX, 0A000h MOV ES, AX MOV SI, CX MOV AL, cor MOV [ES:SI], AL end; function getpoint(x,y : word) : byte; assembler; asm MOV CX, y MOV DX, x MOV AX, CX SHL AX, 8 SHL CX, 6 ADD CX, AX ADD CX, DX MOV AX, 0A000h MOV ES, AX MOV SI, CX MOV al, [ES:SI] end; procedure putline(x,y,x1,y1 : word; cor : byte); assembler; var xd, dy, ddx, ddy, l, b : word; asm PUSH x PUSH y MOV AL,cor MOV AH,0 PUSH AX CALL putpoint MOV AX, x1 SUB AX, x JNC @naonega1 NEG AX MOV BX, -1h JMP @guarda1 @naonega1: MOV BX, 01h @guarda1: MOV xd, BX MOV x1, AX MOV AX, y1 SUB AX, y JNC @naonega2 NEG AX MOV BX, -1h JMP @guarda2 @naonega2: MOV BX, 01h @guarda2: MOV dy, BX MOV y1, AX CMP AX, x1 JC @op1 JZ @op1 MOV b, AX MOV AX, x1 MOV l, AX XOR AX, AX MOV ddx, AX MOV AX, dy MOV ddy, AX JMP @calc @op1: OR AX, x1 JZ @fim MOV AX, y1 MOV l, AX MOV AX, x1 MOV b, AX XOR AX, AX MOV ddy, AX MOV AX, xd MOV ddx, AX @calc: MOV SI, b MOV BX, SI SHR SI, 1 @ciclo: ADD SI, l CMP SI, b JC @dd SUB SI, b MOV CX, dy MOV DX, xd JMP @pponto @dd: MOV CX, ddy MOV DX, ddx @pponto: OR DX, DX JZ @ok1 DEC DX JNZ @nega1 INC x JMP @ok1 @nega1: DEC x @ok1: MOV DX, x OR CX, CX JZ @ok2 DEC CX JNZ @nega2 INC y JMP @ok2 @nega2: DEC y @ok2: MOV CX, y PUSH SI MOV AX, CX SHL CX, 8 SHL AX, 6 ADD CX, AX ADD CX, DX MOV AX, 0A000h MOV ES, AX MOV SI, CX MOV al,cor MOV [ES:SI], AL POP SI DEC BX JNZ @ciclo @fim: end; procedure closingpalette(tempo : word); assembler; var palini : paletype; maior : byte; asm PUSH DS PUSH ES MOV AX, 1017h XOR BX, BX MOV CX, 255 PUSH DS POP ES LEA DX, palini INT 10h CLD MOV CX, 3*256 MOV maior, 0 LEA SI, palini @ler: LODSB CMP maior, AL JL @seta LOOP @ler JMP @fim @seta: MOV maior, AL LOOP @ler @fim: XOR CX, CX MOV CL, maior @0: PUSH CX LEA SI, palini MOV DI, SI XOR AX, AX XOR BX, BX @1: MOV DX, 3C8h MOV CX, 3 MOV AX, BX OUT DX, AL INC DX @2: LODSB OR AX, AX JZ @3 DEC AX @3: STOSB OUT DX, AL LOOP @2 CMP BX, 255 JE @4 INC BX JMP @1 @4: MOV CX, tempo @5: LOOP @5 POP CX LOOP @0 POP ES POP DS end; {=====================================================} { Funcoes de teclado } {=====================================================} procedure wait; assembler; asm push ax xor ax,ax int 16h pop ax end; {=====================================================} { Funcoes de string } {=====================================================} function replicate(ch : char; qtd : byte) : string; var aux : string; tmp : byte ; begin aux := ''; for tmp := 0 to qtd do aux := aux + ch; replicate := aux; end; function space(qtd : byte) : string; begin space := replicate(#32,qtd); end; function alltrim(strini : string) : string; var inicio : byte ; fim : byte ; begin inicio := 1; fim := length(strini); while (inicio <= length(strini)) and (strini[inicio] = #32) do inc(inicio); while (fim > 0) and (strini[fim] = #32) do dec(fim); alltrim := copy(strini,inicio,fim - inicio + 1); end; function upper(str:string) : string; var loopi : byte; begin for loopi := 1 to length(str) do str[loopi] := upcase(str[loopi]); upper := str; end; {=====================================================} { Funcoes de Tipos } {=====================================================} function ifbyte(valor : boolean; v1,v2 : byte) : byte; begin if valor then ifbyte := v1 else ifbyte := v2; end; function ifword(valor : boolean; v1,v2 : word) : word; begin if valor then ifword := v1 else ifword := v2; end; function ifchar(valor : boolean; v1,v2 : char) : char; begin if valor then ifchar := v1 else ifchar := v2; end; function ifstring(valor : boolean; v1,v2 : string) : string; begin if valor then ifstring := v1 else ifstring := v2; end; function ifint(valor : boolean; v1,v2 : integer) : integer; begin if valor then ifint := v1 else ifint := v2; end; procedure swapbyte(var v1,v2 : byte); var v3 : byte; begin v3 := v1 ; v1 := v2 ; v2 := v3 ; end; procedure swapword(var v1,v2 : word); var v3 : word; begin v3 := v1 ; v1 := v2 ; v2 := v3 ; end; function byteval(str : string) : byte; var resp : byte; err : integer; begin val(str,resp,err); if err <> 0 then resp := 0; byteval := resp; end; function wordval(str : string) : word; var resp : word; err : integer; begin val(str,resp,err); if err <> 0 then resp := 0; wordval := resp; end; function min(a,b : integer) : integer; begin if a < b then min := a else min := b; end; function max(a,b : integer) : integer; begin if a > b then max := a else max := b; end; {=====================================================} { Funcoes de Arquivos } {=====================================================} function exist(fname : string) : boolean; var f : file; begin {i-} assign(f,fname); reset(f); {$i+} if ioresult <> 0 then exist := false else begin close(f); exist := true; end; end; function fsize(fname : string) : longint; var f : file; begin {i-} assign(f,fname); reset(f,1); {$i+} if ioresult <> 0 then fsize := -1 else begin fsize := filesize(f); close(f); end; end; function openbigfile(nfin : string; var fin : file) : byte; var header : headtype; begin assign(fin,nfin); {$i-} reset(fin,1); {$i+} if ioresult <> 0 then openbigfile := 0 else begin blockread(fin,header,sizeof(header)); if header.signature <> 'SC' then openbigfile := 0 else openbigfile := header.nfiles; end; end; procedure filebiginfo(var fin : file; var entry : entrytype; arq : byte); var reads : word; posant: longint; begin posant := filepos(fin); seek(fin,(arq-1)*sizeof(entrytype)+sizeof(headtype)); {$i-} blockread(fin,entry,sizeof(entry),reads); {$i+} seek(fin,posant); if reads <> sizeof(entry) then entry.filename := ''; end; procedure filebigpos(var fin : file; arq : byte); var entry : entrytype; begin filebiginfo(fin,entry,arq); seek(fin,entry.startentry); end; begin end.
{ * opCode * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit OpCode; {$INCLUDE zDefine.inc} interface uses SysUtils, Variants, Math, CoreClasses, PascalStrings, DoStatusIO, ListEngine, UnicodeMixedLib; type TOpValueType = ( ovtBool, ovtInt, ovtInt64, ovtUInt64, ovtWord, ovtByte, ovtSmallInt, ovtShortInt, ovtUInt, ovtSingle, ovtDouble, ovtCurrency, ovtString, ovtProc, ovtUnknow); TOpCode = class; TOpCustomRunTime = class; TOpParam = array of Variant; TOnOpCall = function(var OP_Param: TOpParam): Variant; TOnOpMethod = function(var OP_Param: TOpParam): Variant of object; TOnObjectOpCall = function(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; TOnObjectOpMethod = function(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant of object; {$IFDEF FPC} TOnOpProc = function(var OP_Param: TOpParam): Variant is nested; TOnObjectOpProc = function(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant is nested; {$ELSE FPC} TOnOpProc = reference to function(var OP_Param: TOpParam): Variant; TOnObjectOpProc = reference to function(Sender: TOpCustomRunTime; var OP_Param: TOpParam): Variant; {$ENDIF FPC} TOpRTData = record Param: TOpParam; Name, Description, Category: SystemString; OnOpCall: TOnOpCall; OnOpMethod: TOnOpMethod; OnOpProc: TOnOpProc; OnObjectOpCall: TOnObjectOpCall; OnObjectOpMethod: TOnObjectOpMethod; OnObjectOpProc: TOnObjectOpProc; procedure Init; end; POpRTData = ^TOpRTData; TOpCustomRunTime = class(TCoreClassObject) protected procedure FreeNotifyProc(p: Pointer); function DoInt(var OP_Param: TOpParam): Variant; function DoFrac(var OP_Param: TOpParam): Variant; function DoExp(var OP_Param: TOpParam): Variant; function DoCos(var OP_Param: TOpParam): Variant; function DoSin(var OP_Param: TOpParam): Variant; function DoLn(var OP_Param: TOpParam): Variant; function DoArcTan(var OP_Param: TOpParam): Variant; function DoSqrt(var OP_Param: TOpParam): Variant; function DoSqr(var OP_Param: TOpParam): Variant; function DoTan(var OP_Param: TOpParam): Variant; function DoRound(var OP_Param: TOpParam): Variant; function DoTrunc(var OP_Param: TOpParam): Variant; function DoDeg(var OP_Param: TOpParam): Variant; function DoPower(var OP_Param: TOpParam): Variant; function DoSingle(var OP_Param: TOpParam): Variant; function DoDouble(var OP_Param: TOpParam): Variant; function DoExtended(var OP_Param: TOpParam): Variant; function DoByte(var OP_Param: TOpParam): Variant; function DoWord(var OP_Param: TOpParam): Variant; function DoCardinal(var OP_Param: TOpParam): Variant; function DoUInt64(var OP_Param: TOpParam): Variant; function DoShortInt(var OP_Param: TOpParam): Variant; function DoSmallInt(var OP_Param: TOpParam): Variant; function DoInteger(var OP_Param: TOpParam): Variant; function DoInt64(var OP_Param: TOpParam): Variant; function DoROL8(var OP_Param: TOpParam): Variant; function DoROL16(var OP_Param: TOpParam): Variant; function DoROL32(var OP_Param: TOpParam): Variant; function DoROL64(var OP_Param: TOpParam): Variant; function DoROR8(var OP_Param: TOpParam): Variant; function DoROR16(var OP_Param: TOpParam): Variant; function DoROR32(var OP_Param: TOpParam): Variant; function DoROR64(var OP_Param: TOpParam): Variant; function DoEndian16(var OP_Param: TOpParam): Variant; function DoEndian32(var OP_Param: TOpParam): Variant; function DoEndian64(var OP_Param: TOpParam): Variant; function DoEndianU16(var OP_Param: TOpParam): Variant; function DoEndianU32(var OP_Param: TOpParam): Variant; function DoEndianU64(var OP_Param: TOpParam): Variant; function DoSAR16(var OP_Param: TOpParam): Variant; function DoSAR32(var OP_Param: TOpParam): Variant; function DoSAR64(var OP_Param: TOpParam): Variant; function DoPI(var OP_Param: TOpParam): Variant; function DoBool(var OP_Param: TOpParam): Variant; function DoTrue(var OP_Param: TOpParam): Variant; function DoFalse(var OP_Param: TOpParam): Variant; function DoRColor(var OP_Param: TOpParam): Variant; function DoVec2(var OP_Param: TOpParam): Variant; function DoVec3(var OP_Param: TOpParam): Variant; function DoVec4(var OP_Param: TOpParam): Variant; function DoRandom(var OP_Param: TOpParam): Variant; function DoRandomFloat(var OP_Param: TOpParam): Variant; function DoMax(var OP_Param: TOpParam): Variant; function DoMin(var OP_Param: TOpParam): Variant; function DoClamp(var OP_Param: TOpParam): Variant; function DoIfThen(var OP_Param: TOpParam): Variant; function DoStr(var OP_Param: TOpParam): Variant; function DoMultiple(var OP_Param: TOpParam): Variant; public ProcList: THashList; Trigger: POpRTData; UserObject: TCoreClassObject; UserData: Pointer; constructor Create; constructor CustomCreate(maxHashSiz_: Integer); virtual; destructor Destroy; override; procedure Clean; virtual; procedure PrepareRegistation; virtual; function GetProcDescription(ProcName: SystemString): SystemString; overload; function GetAllProcDescription(): TPascalStringList; overload; function GetAllProcDescription(Category: U_String): TPascalStringList; overload; function RegOpC(ProcName: SystemString; OnProc: TOnOpCall): POpRTData; overload; function RegOpC(ProcName, ProcDescription: SystemString; OnProc: TOnOpCall): POpRTData; overload; function RegOpM(ProcName: SystemString; OnProc: TOnOpMethod): POpRTData; overload; function RegOpM(ProcName, ProcDescription: SystemString; OnProc: TOnOpMethod): POpRTData; overload; function RegObjectOpC(ProcName: SystemString; OnProc: TOnObjectOpCall): POpRTData; overload; function RegObjectOpC(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpCall): POpRTData; overload; function RegObjectOpM(ProcName: SystemString; OnProc: TOnObjectOpMethod): POpRTData; overload; function RegObjectOpM(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpMethod): POpRTData; overload; function RegOpP(ProcName: SystemString; OnProc: TOnOpProc): POpRTData; overload; function RegOpP(ProcName, ProcDescription: SystemString; OnProc: TOnOpProc): POpRTData; overload; function RegObjectOpP(ProcName: SystemString; OnProc: TOnObjectOpProc): POpRTData; overload; function RegObjectOpP(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpProc): POpRTData; overload; end; opClass = class of TOpCode; TOpCode = class(TCoreClassObject) private type POpData = ^opData; opData = record Op: TOpCode; Value: Variant; ValueType: TOpValueType; end; protected FParam: TCoreClassList; FAutoFreeLink: Boolean; function DoExecute(opRT: TOpCustomRunTime): Variant; virtual; function GetParam(index: Integer): POpData; procedure EvaluateParam(opRT: TOpCustomRunTime); overload; procedure EvaluateParam(printLog: Boolean; opRT: TOpCustomRunTime); overload; public Owner: TOpCode; ParsedInfo: SystemString; ParsedLineNo: Integer; constructor Create(AFreeLink: Boolean); destructor Destroy; override; procedure SaveToStream(stream: TCoreClassStream); class function LoadFromStream(stream: TCoreClassStream; out LoadedOp: TOpCode): Boolean; function AddValue(v: Variant): Integer; overload; function AddValueT(v: Variant; VT: TOpValueType): Integer; overload; function AddLink(Obj: TOpCode): Integer; function CloneNewSelf: TOpCode; property Param[index: Integer]: POpData read GetParam; default; function Count: Integer; function Execute: Variant; overload; function Execute(opRT: TOpCustomRunTime): Variant; overload; function OwnerRoot: TOpCode; property AutoFreeLink: Boolean read FAutoFreeLink write FAutoFreeLink; end; op_Value = class sealed(TOpCode) private // a function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Proc = class sealed(TOpCode) private // proc(a,b,c...) function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Add_Prefix = class sealed(TOpCode) private // +proc function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Sub_Prefix = class sealed(TOpCode) private // -proc function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Add = class sealed(TOpCode) private // a + b + n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Sub = class sealed(TOpCode) private // a - b - n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Mul = class sealed(TOpCode) private // a * b * n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Div = class sealed(TOpCode) private // a / b / n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_IntDiv = class sealed(TOpCode) private // a div b div n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Pow = class sealed(TOpCode) private // a pow b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Mod = class sealed(TOpCode) private // a mod b mod n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Or = class sealed(TOpCode) private // a or b or n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_And = class sealed(TOpCode) private // a and b and n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Xor = class sealed(TOpCode) private // a xor b xor n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Shl = class sealed(TOpCode) private // a shl b shl n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Shr = class sealed(TOpCode) private // a shr b shr n... function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Equal = class sealed(TOpCode) private // a = b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_LessThan = class sealed(TOpCode) private // a < b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_EqualOrLessThan = class sealed(TOpCode) private // a <= b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_GreaterThan = class sealed(TOpCode) private // a > b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_EqualOrGreaterThan = class sealed(TOpCode) private // a >= b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_NotEqual = class sealed(TOpCode) private // a <> b function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Symbol_Sub = class sealed(TOpCode) private // -a function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; op_Symbol_Add = class sealed(TOpCode) private // +a function DoExecute(opRT: TOpCustomRunTime): Variant; override; end; function LoadOpFromStream(stream: TCoreClassStream; out LoadedOp: TOpCode): Boolean; var DefaultOpRT: TOpCustomRunTime; implementation uses Geometry2DUnit, Geometry3DUnit, DataFrameEngine; type opRegData = record opClass: opClass; OpName: TPascalString; hash: Cardinal; end; POpRegData = ^opRegData; var OpList: TCoreClassList; procedure TOpRTData.Init; begin SetLength(Param, 0); Name := ''; Description := ''; Category := ''; OnOpCall := nil; OnOpMethod := nil; OnOpProc := nil; OnObjectOpCall := nil; OnObjectOpMethod := nil; OnObjectOpProc := nil; end; function GetRegistedOp(Name: TPascalString): POpRegData; var i: Integer; p: POpRegData; hash: Cardinal; begin Result := nil; hash := FastHashPPascalString(@Name); for i := 0 to OpList.Count - 1 do begin p := OpList[i]; if (p^.hash = hash) and (SameText(Name, p^.OpName)) then Exit(p); end; end; procedure RegisterOp(c: opClass); var p: POpRegData; begin if GetRegistedOp(c.ClassName) <> nil then raise Exception.Create('same op ' + c.ClassName); new(p); p^.opClass := c; p^.OpName := p^.opClass.ClassName; p^.hash := FastHashPPascalString(@p^.OpName); OpList.Add(p); end; procedure _FreeOp; var i: Integer; p: POpRegData; begin for i := 0 to OpList.Count - 1 do begin p := OpList[i]; Dispose(p); end; DisposeObject(OpList); end; function LoadOpFromStream(stream: TCoreClassStream; out LoadedOp: TOpCode): Boolean; function LoadFromDataFrame_(CurDataEng: TDataFrameEngine): TOpCode; var AName: SystemString; RegPtr: POpRegData; i, cnt: Integer; NeedNewOp: Boolean; newDataEng: TDataFrameEngine; v: Variant; VT: TOpValueType; begin AName := CurDataEng.Reader.ReadString; RegPtr := GetRegistedOp(AName); if RegPtr <> nil then begin Result := RegPtr^.opClass.Create(True); Result.ParsedInfo := CurDataEng.Reader.ReadString; Result.ParsedLineNo := CurDataEng.Reader.ReadInteger; cnt := CurDataEng.Reader.ReadInteger; for i := 0 to cnt - 1 do begin NeedNewOp := CurDataEng.Reader.ReadBool; if NeedNewOp then begin // create new TOpCode newDataEng := TDataFrameEngine.Create; CurDataEng.Reader.ReadDataFrame(newDataEng); Result.AddLink(LoadFromDataFrame_(newDataEng)); DisposeObject(newDataEng); end else begin v := CurDataEng.Reader.ReadVariant; VT := TOpValueType(CurDataEng.Reader.ReadInteger); Result.AddValueT(v, VT); end; end; end else raise Exception.Create('opCode failed'); end; var DataEng: TDataFrameEngine; DataEdition: Integer; begin Result := False; DataEng := TDataFrameEngine.Create; try DataEng.DecodeFrom(stream, True); DataEdition := DataEng.Reader.ReadInteger; if DataEdition = 1 then begin LoadedOp := LoadFromDataFrame_(DataEng); Result := True; end else LoadedOp := nil; except end; DisposeObject(DataEng); end; procedure TOpCustomRunTime.FreeNotifyProc(p: Pointer); begin POpRTData(p)^.Init; Dispose(POpRTData(p)); end; function TOpCustomRunTime.DoInt(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Int(v); end; function TOpCustomRunTime.DoFrac(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Frac(v); end; function TOpCustomRunTime.DoExp(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Exp(v); end; function TOpCustomRunTime.DoCos(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Cos(v); end; function TOpCustomRunTime.DoSin(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Sin(v); end; function TOpCustomRunTime.DoLn(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := ln(v); end; function TOpCustomRunTime.DoArcTan(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := ArcTan(v); end; function TOpCustomRunTime.DoSqrt(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Sqrt(v); end; function TOpCustomRunTime.DoSqr(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Sqr(v); end; function TOpCustomRunTime.DoTan(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Tan(v); end; function TOpCustomRunTime.DoRound(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Round(Double(v)); end; function TOpCustomRunTime.DoTrunc(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := Trunc(Double(v)); end; function TOpCustomRunTime.DoDeg(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; Result := NormalizeDegAngle(TGeoFloat(v)); end; function TOpCustomRunTime.DoPower(var OP_Param: TOpParam): Variant; var v: Variant; i: Integer; begin if length(OP_Param) = 2 then Result := Power(OP_Param[0], OP_Param[1]) else Result := 0; end; function TOpCustomRunTime.DoSingle(var OP_Param: TOpParam): Variant; begin Result := Single(OP_Param[0]); end; function TOpCustomRunTime.DoDouble(var OP_Param: TOpParam): Variant; begin Result := Double(OP_Param[0]); end; function TOpCustomRunTime.DoExtended(var OP_Param: TOpParam): Variant; begin Result := Extended(OP_Param[0]); end; function TOpCustomRunTime.DoByte(var OP_Param: TOpParam): Variant; begin Result := Byte(OP_Param[0]); end; function TOpCustomRunTime.DoWord(var OP_Param: TOpParam): Variant; begin Result := Word(OP_Param[0]); end; function TOpCustomRunTime.DoCardinal(var OP_Param: TOpParam): Variant; begin Result := Cardinal(OP_Param[0]); end; function TOpCustomRunTime.DoUInt64(var OP_Param: TOpParam): Variant; begin Result := UInt64(OP_Param[0]); end; function TOpCustomRunTime.DoShortInt(var OP_Param: TOpParam): Variant; begin Result := ShortInt(OP_Param[0]); end; function TOpCustomRunTime.DoSmallInt(var OP_Param: TOpParam): Variant; begin Result := SmallInt(OP_Param[0]); end; function TOpCustomRunTime.DoInteger(var OP_Param: TOpParam): Variant; begin Result := Integer(OP_Param[0]); end; function TOpCustomRunTime.DoInt64(var OP_Param: TOpParam): Variant; begin Result := Int64(OP_Param[0]); end; function TOpCustomRunTime.DoROL8(var OP_Param: TOpParam): Variant; begin Result := ROL8(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROL16(var OP_Param: TOpParam): Variant; begin Result := ROL16(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROL32(var OP_Param: TOpParam): Variant; begin Result := ROL32(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROL64(var OP_Param: TOpParam): Variant; begin Result := ROL64(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROR8(var OP_Param: TOpParam): Variant; begin Result := ROR8(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROR16(var OP_Param: TOpParam): Variant; begin Result := ROR16(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROR32(var OP_Param: TOpParam): Variant; begin Result := ROR32(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoROR64(var OP_Param: TOpParam): Variant; begin Result := ROR64(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoEndian16(var OP_Param: TOpParam): Variant; begin Result := Endian(SmallInt(OP_Param[0])); end; function TOpCustomRunTime.DoEndian32(var OP_Param: TOpParam): Variant; begin Result := Endian(Integer(OP_Param[0])); end; function TOpCustomRunTime.DoEndian64(var OP_Param: TOpParam): Variant; begin Result := Endian(Int64(OP_Param[0])); end; function TOpCustomRunTime.DoEndianU16(var OP_Param: TOpParam): Variant; begin Result := Endian(Word(OP_Param[0])); end; function TOpCustomRunTime.DoEndianU32(var OP_Param: TOpParam): Variant; begin Result := Endian(Cardinal(OP_Param[0])); end; function TOpCustomRunTime.DoEndianU64(var OP_Param: TOpParam): Variant; begin Result := Endian(UInt64(OP_Param[0])); end; function TOpCustomRunTime.DoSAR16(var OP_Param: TOpParam): Variant; begin Result := SAR16(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoSAR32(var OP_Param: TOpParam): Variant; begin Result := SAR32(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoSAR64(var OP_Param: TOpParam): Variant; begin Result := SAR64(OP_Param[0], OP_Param[1]); end; function TOpCustomRunTime.DoPI(var OP_Param: TOpParam): Variant; begin Result := PI; end; function TOpCustomRunTime.DoBool(var OP_Param: TOpParam): Variant; function v2b(const v: Variant): Boolean; var n: TPascalString; begin if VarIsStr(v) then begin n := VarToStr(v); n := n.DeleteChar(#32#9); if n.Same('True') or n.Same('Yes') or n.Same('1') then Result := True else Result := False; end else if VarIsOrdinal(v) then Result := Boolean(v) else if VarIsFloat(v) then Result := Boolean(Round(Double(v))) else Result := Boolean(v); end; var n: Boolean; i: Integer; begin n := True; for i := low(OP_Param) to high(OP_Param) do n := n and v2b(OP_Param[i]); Result := n; end; function TOpCustomRunTime.DoTrue(var OP_Param: TOpParam): Variant; begin Result := True; end; function TOpCustomRunTime.DoFalse(var OP_Param: TOpParam): Variant; begin Result := False; end; function TOpCustomRunTime.DoRColor(var OP_Param: TOpParam): Variant; var buff: array [0 .. 3] of SystemString; i: Integer; begin for i := 0 to 2 do buff[i] := '0.0'; buff[3] := '1.0'; for i := Low(OP_Param) to high(OP_Param) do buff[i] := VarToStr(OP_Param[i]); Result := Format('RColor(%s,%s,%s,%s)', [buff[0], buff[1], buff[2], buff[3]]); end; function TOpCustomRunTime.DoVec2(var OP_Param: TOpParam): Variant; var buff: array [0 .. 1] of SystemString; i: Integer; begin for i := Low(buff) to high(buff) do buff[i] := '0.0'; for i := Low(OP_Param) to high(OP_Param) do buff[i] := VarToStr(OP_Param[i]); Result := Format('Vec2(%s,%s)', [buff[0], buff[1]]); end; function TOpCustomRunTime.DoVec3(var OP_Param: TOpParam): Variant; var buff: array [0 .. 2] of SystemString; i: Integer; begin for i := Low(buff) to high(buff) do buff[i] := '0.0'; for i := Low(OP_Param) to high(OP_Param) do buff[i] := VarToStr(OP_Param[i]); Result := Format('Vec3(%s,%s,%s)', [buff[0], buff[1], buff[2]]); end; function TOpCustomRunTime.DoVec4(var OP_Param: TOpParam): Variant; var buff: array [0 .. 3] of SystemString; i: Integer; begin for i := Low(buff) to high(buff) do buff[i] := '0.0'; for i := Low(OP_Param) to high(OP_Param) do buff[i] := VarToStr(OP_Param[i]); Result := Format('Vec4(%s,%s,%s,%s)', [buff[0], buff[1], buff[2], buff[3]]); end; function TOpCustomRunTime.DoRandom(var OP_Param: TOpParam): Variant; var v: Integer; i: Integer; begin v := 0; for i := low(OP_Param) to high(OP_Param) do v := v + OP_Param[i]; if v <> 0 then Result := MT19937Rand32(v) else Result := MT19937Rand32(MaxInt); end; function TOpCustomRunTime.DoRandomFloat(var OP_Param: TOpParam): Variant; begin Result := MT19937RandF; end; function TOpCustomRunTime.DoMax(var OP_Param: TOpParam): Variant; var i: Integer; begin if length(OP_Param) = 0 then begin Result := NULL; Exit; end; Result := OP_Param[0]; for i := 1 to length(OP_Param) - 1 do if OP_Param[i] > Result then Result := OP_Param[i]; end; function TOpCustomRunTime.DoMin(var OP_Param: TOpParam): Variant; var i: Integer; begin if length(OP_Param) = 0 then begin Result := NULL; Exit; end; Result := OP_Param[0]; for i := 1 to length(OP_Param) - 1 do if OP_Param[i] < Result then Result := OP_Param[i]; end; function TOpCustomRunTime.DoClamp(var OP_Param: TOpParam): Variant; var minv_, maxv_: Variant; begin if length(OP_Param) <> 3 then begin if length(OP_Param) > 0 then Result := OP_Param[0] else Result := NULL; Exit; end; if OP_Param[1] > OP_Param[2] then begin minv_ := OP_Param[2]; maxv_ := OP_Param[1]; end else begin minv_ := OP_Param[1]; maxv_ := OP_Param[2]; end; if OP_Param[0] < minv_ then Result := minv_ else if OP_Param[0] > maxv_ then Result := maxv_ else Result := OP_Param[0]; end; function TOpCustomRunTime.DoIfThen(var OP_Param: TOpParam): Variant; begin if length(OP_Param) <> 3 then begin Result := NULL; Exit; end; if Boolean(OP_Param[0]) = True then Result := OP_Param[1] else Result := OP_Param[2]; end; function TOpCustomRunTime.DoStr(var OP_Param: TOpParam): Variant; var n: TPascalString; i: Integer; begin n := ''; for i := low(OP_Param) to high(OP_Param) do n.Append(VarToStr(OP_Param[i])); Result := n; end; function TOpCustomRunTime.DoMultiple(var OP_Param: TOpParam): Variant; var i: Integer; begin if length(OP_Param) >= 2 then begin Result := True; for i := 1 to length(OP_Param) - 1 do Result := Result and umlMultipleMatch(VarToStr(OP_Param[0]), VarToStr(OP_Param[i])); end else Result := True; end; constructor TOpCustomRunTime.Create; begin CustomCreate(1024); end; constructor TOpCustomRunTime.CustomCreate(maxHashSiz_: Integer); begin inherited Create; ProcList := THashList.CustomCreate(maxHashSiz_); ProcList.AutoFreeData := True; ProcList.AccessOptimization := True; ProcList.OnFreePtr := {$IFDEF FPC}@{$ENDIF FPC}FreeNotifyProc; Trigger := nil; UserObject := nil; UserData := nil; PrepareRegistation; end; destructor TOpCustomRunTime.Destroy; begin DisposeObject(ProcList); inherited Destroy; end; procedure TOpCustomRunTime.Clean; begin ProcList.Clear; end; procedure TOpCustomRunTime.PrepareRegistation; begin RegOpM('Int', 'Int(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoInt)^.Category := 'Base Math'; RegOpM('Frac', 'Frac(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoFrac)^.Category := 'Base Math'; RegOpM('Exp', 'Exp(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoExp)^.Category := 'Base Math'; RegOpM('Cos', 'Cos(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoCos)^.Category := 'Base Math'; RegOpM('Sin', 'Sin(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSin)^.Category := 'Base Math'; RegOpM('Ln', 'Ln(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoLn)^.Category := 'Base Math'; RegOpM('ArcTan', 'ArcTan(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoArcTan)^.Category := 'Base Math'; RegOpM('Sqrt', 'Sqrt(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSqrt)^.Category := 'Base Math'; RegOpM('Sqr', 'Sqr(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSqr)^.Category := 'Base Math'; RegOpM('Tan', 'Tan(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoTan)^.Category := 'Base Math'; RegOpM('Round', 'Round(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoRound)^.Category := 'Base Math'; RegOpM('Trunc', 'Trunc(0..n): math function', {$IFDEF FPC}@{$ENDIF FPC}DoTrunc)^.Category := 'Base Math'; RegOpM('Deg', 'Deg(0..n): NormalizeDegAngle function', {$IFDEF FPC}@{$ENDIF FPC}DoDeg)^.Category := 'Base Math'; RegOpM('Power', 'Power(float,float): Power: Raise base to any power function', {$IFDEF FPC}@{$ENDIF FPC}DoPower)^.Category := 'Base Math'; RegOpM('Single', 'Single(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSingle)^.Category := 'Base Math'; RegOpM('Double', 'Double(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoDouble)^.Category := 'Base Math'; RegOpM('Float', 'Float(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoDouble)^.Category := 'Base Math'; RegOpM('Extended', 'Extended(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoExtended)^.Category := 'Base Math'; RegOpM('Byte', 'Byte(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoByte)^.Category := 'Base Math'; RegOpM('Word', 'Word(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoWord)^.Category := 'Base Math'; RegOpM('Cardinal', 'Cardinal(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoCardinal)^.Category := 'Base Math'; RegOpM('UInt64', 'UInt64(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoUInt64)^.Category := 'Base Math'; RegOpM('ShortInt', 'ShortInt(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoShortInt)^.Category := 'Base Math'; RegOpM('SmallInt', 'SmallInt(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSmallInt)^.Category := 'Base Math'; RegOpM('Integer', 'Integer(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoInteger)^.Category := 'Base Math'; RegOpM('Int64', 'Int64(value): math function', {$IFDEF FPC}@{$ENDIF FPC}DoInt64)^.Category := 'Base Math'; RegOpM('ROL8', 'ROL8(byte,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROL8)^.Category := 'Base Math'; RegOpM('ROL16', 'ROL16(word,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROL16)^.Category := 'Base Math'; RegOpM('ROL32', 'ROL32(cardinal,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROL32)^.Category := 'Base Math'; RegOpM('ROL64', 'ROL64(uint64,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROL64)^.Category := 'Base Math'; RegOpM('ROR8', 'ROR8(byte,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROR8)^.Category := 'Base Math'; RegOpM('ROR16', 'ROR16(word,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROR16)^.Category := 'Base Math'; RegOpM('ROR32', 'ROR32(cardinal,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROR32)^.Category := 'Base Math'; RegOpM('ROR64', 'ROR64(uint64,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoROR64)^.Category := 'Base Math'; RegOpM('Endian16', 'Endian16(smallint): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndian16)^.Category := 'Base Math'; RegOpM('Endian32', 'Endian32(integer): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndian32)^.Category := 'Base Math'; RegOpM('Endian64', 'Endian64(int64): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndian64)^.Category := 'Base Math'; RegOpM('EndianU16', 'EndianU16(word): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndianU16)^.Category := 'Base Math'; RegOpM('EndianU32', 'EndianU32(cardinal): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndianU32)^.Category := 'Base Math'; RegOpM('EndianU64', 'EndianU64(uint64): math function', {$IFDEF FPC}@{$ENDIF FPC}DoEndianU64)^.Category := 'Base Math'; RegOpM('SAR16', 'SAR16(word,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSAR16)^.Category := 'Base Math'; RegOpM('SAR32', 'SAR32(cardinal,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSAR32)^.Category := 'Base Math'; RegOpM('SAR64', 'SAR64(uint64,Shift): math function', {$IFDEF FPC}@{$ENDIF FPC}DoSAR64)^.Category := 'Base Math'; RegOpM('PI', 'PI(): return PI', {$IFDEF FPC}@{$ENDIF FPC}DoPI)^.Category := 'Base Math'; RegOpM('Bool', 'Bool(n..n): convert any variant as bool', {$IFDEF FPC}@{$ENDIF FPC}DoBool)^.Category := 'Base Math'; RegOpM('Boolean', 'Boolean(n..n): convert any variant as bool', {$IFDEF FPC}@{$ENDIF FPC}DoBool)^.Category := 'Base Math'; RegOpM('True', 'True(): return true', {$IFDEF FPC}@{$ENDIF FPC}DoTrue)^.Category := 'Base Math'; RegOpM('False', 'False(): return false', {$IFDEF FPC}@{$ENDIF FPC}DoFalse)^.Category := 'Base Math'; RegOpM('RColor', 'RColor(R,G,B,A): return RColor string', {$IFDEF FPC}@{$ENDIF FPC}DoRColor)^.Category := 'Base Math'; RegOpM('Vec2', 'Vec2(X,Y): return Vec2 string', {$IFDEF FPC}@{$ENDIF FPC}DoVec2)^.Category := 'Base Math'; RegOpM('Vec3', 'Vec3(X,Y,Z): return Vec3 string', {$IFDEF FPC}@{$ENDIF FPC}DoVec3)^.Category := 'Base Math'; RegOpM('Vec4', 'Vec4(X,Y,Z,W): return Vec4 string', {$IFDEF FPC}@{$ENDIF FPC}DoVec4)^.Category := 'Base Math'; RegOpM('Random', 'Random(0..n): return number', {$IFDEF FPC}@{$ENDIF FPC}DoRandom)^.Category := 'Base Math'; RegOpM('RandomFloat', 'RandomFloat(): return float', {$IFDEF FPC}@{$ENDIF FPC}DoRandomFloat)^.Category := 'Base Math'; RegOpM('RandomF', 'RandomF(): return float', {$IFDEF FPC}@{$ENDIF FPC}DoRandomFloat)^.Category := 'Base Math'; RegOpM('Max', 'Max(0..n): return max value', {$IFDEF FPC}@{$ENDIF FPC}DoMax)^.Category := 'Base Math'; RegOpM('Min', 'Min(0..n): return min value', {$IFDEF FPC}@{$ENDIF FPC}DoMin)^.Category := 'Base Math'; RegOpM('Clamp', 'Clamp(value, min, max): return clamp value', {$IFDEF FPC}@{$ENDIF FPC}DoClamp)^.Category := 'Base Math'; RegOpM('IfThen', 'IfThen(bool, if true then of value, if false then of value): return if value', {$IFDEF FPC}@{$ENDIF FPC}DoIfThen)^.Category := 'Base Math'; RegOpM('Str', 'Str(n..n): convert any variant as string', {$IFDEF FPC}@{$ENDIF FPC}DoStr)^.Category := 'Base String'; RegOpM('String', 'String(n..n): convert any variant as string', {$IFDEF FPC}@{$ENDIF FPC}DoStr)^.Category := 'Base String'; RegOpM('Text', 'Text(n..n): convert any variant as string', {$IFDEF FPC}@{$ENDIF FPC}DoStr)^.Category := 'Base String'; RegOpM('MultipleMatch', 'MultipleMatch(multile exp, n..n): return bool', {$IFDEF FPC}@{$ENDIF FPC}DoMultiple)^.Category := 'Base String'; RegOpM('Multiple', 'MultipleMatch(multile exp, n..n): return bool', {$IFDEF FPC}@{$ENDIF FPC}DoMultiple)^.Category := 'Base String'; end; function TOpCustomRunTime.GetProcDescription(ProcName: SystemString): SystemString; var p: POpRTData; begin Result := ProcName + '(): no Descripion'; p := ProcList[ProcName]; if p <> nil then if p^.Description <> '' then Result := p^.Description; end; function TOpCustomRunTime.GetAllProcDescription(): TPascalStringList; begin Result := GetAllProcDescription('*'); end; function TOpCustomRunTime.GetAllProcDescription(Category: U_String): TPascalStringList; var arry: THashDataArray; hl: THashObjectList; ns, tmp: TPascalStringList; i, j: Integer; p: POpRTData; n: TPascalString; begin Result := TPascalStringList.Create; arry := ProcList.GetHashDataArray(); hl := THashObjectList.CustomCreate(True, 256); for i := Low(arry) to High(arry) do begin p := arry[i]^.Data; if not hl.Exists(p^.Category) then hl.FastAdd(p^.Category, TPascalStringList.Create); tmp := hl[p^.Category] as TPascalStringList; if p^.Description <> '' then n := p^.Description else n := p^.Name + '(): no Descripion'; tmp.Add(n); end; SetLength(arry, 0); ns := TPascalStringList.Create; hl.GetListData(ns); for i := 0 to ns.Count - 1 do if umlMultipleMatch(Category, ns[i]) then begin Result.Add(PFormat('%s:', [ns[i].Text])); tmp := ns.Objects[i] as TPascalStringList; for j := 0 to tmp.Count - 1 do Result.Add(' ' + tmp[j]); Result.Add(''); end; n := ''; DisposeObject(ns); DisposeObject(hl); end; function TOpCustomRunTime.RegOpC(ProcName: SystemString; OnProc: TOnOpCall): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnOpCall := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegOpC(ProcName, ProcDescription: SystemString; OnProc: TOnOpCall): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnOpCall := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegOpM(ProcName: SystemString; OnProc: TOnOpMethod): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnOpMethod := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegOpM(ProcName, ProcDescription: SystemString; OnProc: TOnOpMethod): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnOpMethod := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpC(ProcName: SystemString; OnProc: TOnObjectOpCall): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnObjectOpCall := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpC(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpCall): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnObjectOpCall := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpM(ProcName: SystemString; OnProc: TOnObjectOpMethod): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnObjectOpMethod := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpM(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpMethod): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnObjectOpMethod := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegOpP(ProcName: SystemString; OnProc: TOnOpProc): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnOpProc := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegOpP(ProcName, ProcDescription: SystemString; OnProc: TOnOpProc): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnOpProc := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpP(ProcName: SystemString; OnProc: TOnObjectOpProc): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.OnObjectOpProc := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCustomRunTime.RegObjectOpP(ProcName, ProcDescription: SystemString; OnProc: TOnObjectOpProc): POpRTData; var p: POpRTData; begin new(p); p^.Init; p^.Name := ProcName; p^.Description := ProcDescription; p^.OnObjectOpProc := OnProc; ProcList.Add(ProcName, p, True); Result := p; end; function TOpCode.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := NULL; end; function TOpCode.GetParam(index: Integer): POpData; begin Result := FParam[index]; end; procedure TOpCode.EvaluateParam(opRT: TOpCustomRunTime); begin EvaluateParam(False, opRT); end; procedure TOpCode.EvaluateParam(printLog: Boolean; opRT: TOpCustomRunTime); var i: Integer; p: POpData; begin for i := 0 to FParam.Count - 1 do begin p := FParam[i]; if p^.Op <> nil then begin try p^.Op.EvaluateParam(printLog, opRT); except end; try p^.Value := p^.Op.DoExecute(opRT); if printLog then DoStatus('%s value:%s', [ClassName, VarToStr(p^.Value)]); except end; end; end; end; constructor TOpCode.Create(AFreeLink: Boolean); begin inherited Create; Owner := nil; FParam := TCoreClassList.Create; FAutoFreeLink := AFreeLink; ParsedInfo := ''; ParsedLineNo := 0; end; destructor TOpCode.Destroy; var i: Integer; p: POpData; begin if FParam <> nil then begin for i := 0 to FParam.Count - 1 do begin p := FParam[i]; if (FAutoFreeLink) and (p^.Op <> nil) then DisposeObject(p^.Op); Dispose(p); end; FParam.Clear; DisposeObject(FParam); end; inherited Destroy; end; procedure TOpCode.SaveToStream(stream: TCoreClassStream); procedure SaveToDataFrame(Op: TOpCode; CurDataEng: TDataFrameEngine); var i: Integer; p: POpData; newDataEng: TDataFrameEngine; begin CurDataEng.WriteString(Op.ClassName); CurDataEng.WriteString(Op.ParsedInfo); CurDataEng.WriteInteger(Op.ParsedLineNo); CurDataEng.WriteInteger(Op.Count); for i := 0 to Op.Count - 1 do begin p := Op[i]; if p^.Op <> nil then begin CurDataEng.WriteBool(True); newDataEng := TDataFrameEngine.Create; SaveToDataFrame(p^.Op, newDataEng); CurDataEng.WriteDataFrame(newDataEng); DisposeObject(newDataEng); end else begin CurDataEng.WriteBool(False); CurDataEng.WriteVariant(p^.Value); CurDataEng.WriteInteger(Integer(p^.ValueType)); end; end; end; var DataEng: TDataFrameEngine; begin DataEng := TDataFrameEngine.Create; DataEng.WriteInteger(1); SaveToDataFrame(Self, DataEng); DataEng.EncodeTo(stream, True); DisposeObject(DataEng); end; class function TOpCode.LoadFromStream(stream: TCoreClassStream; out LoadedOp: TOpCode): Boolean; begin Result := LoadOpFromStream(stream, LoadedOp); end; function TOpCode.AddValue(v: Variant): Integer; var p: POpData; begin new(p); p^.Op := nil; p^.Value := v; case VarType(v) of varSmallInt: p^.ValueType := ovtSmallInt; varInteger: p^.ValueType := ovtInt; varSingle: p^.ValueType := ovtSingle; varDouble: p^.ValueType := ovtDouble; varCurrency: p^.ValueType := ovtCurrency; varBoolean: p^.ValueType := ovtBool; varShortInt: p^.ValueType := ovtShortInt; varByte: p^.ValueType := ovtByte; varWord: p^.ValueType := ovtWord; varLongWord: p^.ValueType := ovtUInt; varInt64: p^.ValueType := ovtInt64; varUInt64: p^.ValueType := ovtUInt64; else begin if VarIsStr(v) then p^.ValueType := ovtString else p^.ValueType := ovtUnknow; end; end; Result := FParam.Add(p); end; function TOpCode.AddValueT(v: Variant; VT: TOpValueType): Integer; var p: POpData; begin new(p); p^.Op := nil; p^.Value := v; p^.ValueType := VT; Result := FParam.Add(p); end; function TOpCode.AddLink(Obj: TOpCode): Integer; var p: POpData; begin new(p); if Obj.Owner <> nil then p^.Op := Obj.CloneNewSelf else p^.Op := Obj; p^.Op.Owner := Self; p^.Value := NULL; p^.ValueType := ovtUnknow; Result := FParam.Add(p); end; function TOpCode.CloneNewSelf: TOpCode; var i: Integer; p: POpData; begin Result := opClass(Self.ClassType).Create(True); Result.ParsedInfo := Self.ParsedInfo; Result.ParsedLineNo := Self.ParsedLineNo; for i := 0 to FParam.Count - 1 do begin p := FParam[i]; if p^.Op <> nil then Result.AddLink(p^.Op.CloneNewSelf) else Result.AddValueT(p^.Value, p^.ValueType); end; end; function TOpCode.Count: Integer; begin Result := FParam.Count; end; function TOpCode.Execute: Variant; begin Result := Execute(DefaultOpRT); end; function TOpCode.Execute(opRT: TOpCustomRunTime): Variant; begin try EvaluateParam(opRT); except Result := NULL; Exit; end; try Result := DoExecute(opRT); except Result := NULL; end; end; function TOpCode.OwnerRoot: TOpCode; begin if Owner = nil then Result := Self else Result := Owner.OwnerRoot; end; { op_Value } function op_Value.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value; end; { op_Proc } function op_Proc.DoExecute(opRT: TOpCustomRunTime): Variant; var p: POpRTData; i: Integer; begin Result := NULL; if (opRT = nil) then opRT := DefaultOpRT; p := opRT.ProcList[VarToStr(Param[0]^.Value)]; if p = nil then begin if opRT = DefaultOpRT then Exit; p := DefaultOpRT.ProcList[VarToStr(Param[0]^.Value)]; if p = nil then Exit; end; if length(p^.Param) <> Count - 1 then SetLength(p^.Param, Count - 1); for i := 1 to Count - 1 do p^.Param[i - 1] := Param[i]^.Value; opRT.Trigger := p; if Assigned(p^.OnOpCall) then Result := p^.OnOpCall(p^.Param); if Assigned(p^.OnOpMethod) then Result := p^.OnOpMethod(p^.Param); if Assigned(p^.OnOpProc) then Result := p^.OnOpProc(p^.Param); if Assigned(p^.OnObjectOpCall) then Result := p^.OnObjectOpCall(opRT, p^.Param); if Assigned(p^.OnObjectOpMethod) then Result := p^.OnObjectOpMethod(opRT, p^.Param); if Assigned(p^.OnObjectOpProc) then Result := p^.OnObjectOpProc(opRT, p^.Param); end; { op_Add_Prefix } function op_Add_Prefix.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result + Param[i]^.Value; Result := - - Result; end; { op_Sub_Prefix } function op_Sub_Prefix.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result + Param[i]^.Value; Result := -Result; end; { op_Add } function op_Add.DoExecute(opRT: TOpCustomRunTime): Variant; function Fast_VarIsStr(var v: Variant): Boolean; {$IFDEF INLINE_ASM} inline; {$ENDIF} var p: pVarData; begin // optimized p := @TVarData(v); while p^.VType = varByRef or varVariant do p := pVarData(p^.VPointer); Result := (p^.VType = varOleStr) or (p^.VType = varString) or (p^.VType = varUString); end; var i: Integer; n1, n2: TPascalString; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; if Fast_VarIsStr(Result) then begin // optimized n1 := VarToStr(Result); for i := 1 to Count - 1 do begin try n1.Append(VarToStr(Param[i]^.Value)); except end; end; Result := n1.Text; end else begin for i := 1 to Count - 1 do begin try if Fast_VarIsStr(Result) then begin // SystemString combine n1 := VarToStr(Result); if not umlIsNumber(n1) then begin Result := n1 + VarToStr(Param[i]^.Value); Continue; end end; if Fast_VarIsStr(Param[i]^.Value) then begin // SystemString combine n2 := VarToStr(Param[i]^.Value); if not umlIsNumber(n2) then begin Result := VarToStr(Result) + n2; Continue; end end; // logic compute Result := Result + Param[i]^.Value; except end; end; end; end; { op_Sub } function op_Sub.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result - Param[i]^.Value; end; { op_Mul } function op_Mul.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result * Param[i]^.Value; end; { op_Div } function op_Div.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result / Param[i]^.Value; end; { op_IntDiv } function op_IntDiv.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result div Param[i]^.Value; end; { op_Pow } function op_Pow.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Power(Result, Param[i]^.Value); end; { op_Mod } function op_Mod.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result mod Param[i]^.Value; end; { op_Or } function op_Or.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result or Param[i]^.Value; end; { op_And } function op_And.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result and Param[i]^.Value; end; { op_Xor } function op_Xor.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := Result xor Param[i]^.Value; end; { op_shl } function op_Shl.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := UInt64(Result) shl UInt64(Param[i]^.Value); end; { op_shr } function op_Shr.DoExecute(opRT: TOpCustomRunTime): Variant; var i: Integer; begin if Count = 0 then Exit(NULL); Result := Param[0]^.Value; for i := 1 to Count - 1 do Result := UInt64(Result) shr UInt64(Param[i]^.Value); end; { op_Equal } function op_Equal.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value = Param[1]^.Value; end; { op_LessThan } function op_LessThan.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value < Param[1]^.Value; end; { op_EqualOrLessThan } function op_EqualOrLessThan.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value <= Param[1]^.Value; end; { op_GreaterThan } function op_GreaterThan.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value > Param[1]^.Value; end; { op_EqualOrGreaterThan } function op_EqualOrGreaterThan.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value >= Param[1]^.Value; end; { op_NotEqual } function op_NotEqual.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value <> Param[1]^.Value; end; { op_Symbol_Sub } function op_Symbol_Sub.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := -Param[0]^.Value; end; { op_Symbol_Add } function op_Symbol_Add.DoExecute(opRT: TOpCustomRunTime): Variant; begin Result := Param[0]^.Value; end; initialization DefaultOpRT := TOpCustomRunTime.Create; OleVariantInt64AsDouble := True; OpList := TCoreClassList.Create; RegisterOp(op_Value); RegisterOp(op_Proc); RegisterOp(op_Add_Prefix); RegisterOp(op_Sub_Prefix); RegisterOp(op_Add); RegisterOp(op_Sub); RegisterOp(op_Mul); RegisterOp(op_Div); RegisterOp(op_IntDiv); RegisterOp(op_Mod); RegisterOp(op_Or); RegisterOp(op_And); RegisterOp(op_Xor); RegisterOp(op_Shl); RegisterOp(op_Shr); RegisterOp(op_Equal); RegisterOp(op_LessThan); RegisterOp(op_EqualOrLessThan); RegisterOp(op_GreaterThan); RegisterOp(op_EqualOrGreaterThan); RegisterOp(op_NotEqual); RegisterOp(op_Symbol_Sub); RegisterOp(op_Symbol_Add); finalization DisposeObject(DefaultOpRT); _FreeOp; end.
unit UnitConsts; interface Uses Messages; resourcestring IDS_InfoFilesPath = '.\Info\'; IDS_ScriptFilesPath = '.\Scripts\'; IDS_UsersPath = '.\Users\'; IDS_StoreFilename = 'Store.ini'; IDS_DefaultMapFileName = 'Map.ini'; RS_UpDateTime = '2019.10.17'; IDS_MainHotKeyInfo = 'MainHotKeyInfo'; IDS_WinInfoHotKeyInfo = 'WinInfoHotKeyInfo'; IDS_VirtualKey = 'VirtualKey'; IDS_Modifiers = 'Modifiers'; IDS_ShowText = 'ShowText'; IDS_FormTopStr = 'Top'; IDS_FormLeftStr = 'Left'; IDS_MainFormName = 'Main'; IDS_ImageFormName = 'Image'; IDS_GeneralSetFormName = 'Settings'; IDS_StuffsFormName = 'Inventory'; IDS_PetsFormName = 'Pets'; IDS_UniverseStoveFormName = 'Wuxing Oven'; IDS_WorkTransactionsFormName = 'Script'; IDS_WGsFormName = 'Create Kungfu'; IDS_WGAttrFormName = 'Basic Settings'; IDS_WG_Name = 'Name'; IDS_WG_NameDef = 'DivinePalm'; IDS_WG_XiShu = 'Destructive Index'; IDS_WG_NeiLi = 'Mana Consumed'; IDS_WG_ZiShi = 'Starting Posture'; IDS_WG_GuiJi = 'Flying Track'; IDS_WG_BaoZha = 'Explosion Type'; const // AddrHumanBase = $006C21FC; // AddrBattleState = $006C51DC; CustomMouseMsg = WM_USER + 1; CustomIID = 100; // 定义的动作代码,用在Work.ini里面 ActUnknown = -1; // 未知指令--------------------------------------- ActLeftClick = 0; // 左键单击 ActRightClick = 1; // 右键单击 ActMoveToPos = 10; // 移动位置:移动到地图内的某个坐标 ActGoToMap = 20; // 来到地图:移动到指定地图 ActInBattle = 30; // 正在战斗 ActBuyStuff = 40; // 购买物品 ActDoForge = 50; // 进行锻造 ActQuitShop = 60; // 离开商店 ActPressButton = 70; // 点击按钮 ActCallNPC = 80; // 呼叫 NPC ActTerminate = 90; // 停止工作 ActHaveStuff = 100; // 拥有物品:等待满足此物品,达到指定数量级 ActStuffNum = 110; // 物品数目:等待满足此物品,等于指定数量级 ActJumpToTransN = 120; // 跳至步骤 N ActHavePet = 130; // 拥有宠物:等待满足此宠物,达到指定数量级 ActPetNum = 140; // 宠物数目:等待满足此宠物,等于指定数量级 ActCancelNPCDialog = 150; // 取消对话 ActWinLeftClick = 160; // 窗口单击 ActWinLeftDblClick = 170; // 窗口双击 ActDelay = 180; // 等待延时 ActActiveBattle = 190; // 进入战斗 ActSetCapture = 200; // 捉宠设置 ActLocateWindow = 210; // 定位窗口 ActWinRightClick = 220; // 窗口右键 ActWaitWindow = 230; // 等待窗口 ActCreateWG = 240; // 自创武功 ActUseItem = 250; // 使用物品 ActOpenItemWindow = 260; // 开物品栏 ActCloseItemWindow = 270; // 关物品栏 ActSetWGAttr = 280; // 武功参数 ActSetWGDisp = 290; // 武功外观 ActDeleteWGs = 300; // 删除武功 ActSetHeal = 310; // Set heal settings ActDropItem = 320; // Drop an item ActSetAttr = 330; // Set user Attributes ActSetMarch = 340; // Set the marching pet ActRecordPetStats = 350; // Record to file pet stats at level 1 by ID ActLoadPetStats = 360; // load pet stats for growth tracking ActRenamePet = 370; // Change pet name // UserIDAddr = $006c2200; // Old HL_Base_Address HL_EXE_Name = 'HL_Client.exe'; //UserNameAddress = $006c2244; CN //UserNickAddress = $006c2254; //UserSpouseAddress = $006c2264; UserNameAddress = $006BB974; UserNickAddress = $006BB984; UserSpouseAddress = $006BB994; UserNameSize = 16; UserIdAddress = $006BB930; //UserMoneyAddress = $6c2214; UserMoneyAddress = $6BB944; // Level, cultivation(?) //UserLevelAddr = $006c2206; // WORD CN //UserBaseXiuAddr = $006C3478; // DWORD UserLevelAddr = $6BB936; // WORD UserBaseXiuAddr = $6BCBA8; // DWORD // User rank: master=5 // UserRankAddr = $006c2208; // WORD CN UserRankAddr = $6BB938; // WORD // 人物仙魔地址:仙=1,魔=2, 凡人/散仙=0 //UserXianmo_1Xian_2Mo = $006C346C; // WORD CN UserXianmo_1Xian_2Mo = $6BCB9C; // WORD UserAttrXian = 1; // 仙 UserAttrMo = 2; // 魔 // 人物五转职业: //User5TurnCareer = $006C3470; // WORD User5TurnCareer = $6BCBA0; // WORD // Life current/max //UserLifeCurrAddr = $006c220A; // WORD CN //UserLifeMAXAddr = $006c220c; //WORD UserLifeCurrAddr = $6BB93A; // WORD UserLifeMAXAddr = $6BB93C; //WORD // Mana current/max //UserNeiliCurrAddr = $006c220e; // WORD CN //UserNeiliMAXAddr = $006c2210; // WORD UserNeiliCurrAddr = $6BB93E; // WORD UserNeiliMAXAddr = $6BB940; // WORD // 5 attributes //UserAttribTiliAddr = $006c2230; // WORD CN //UserAttribNeigongAddr = $006c2238; // WORD //UserAttribGongjiAddr = $006c2234; // WORD //UserAttribFangyuAddr = $006c2232; // WORD //UserAttribQinggongAddr = $006c2236; // WORD UserAttribTiliAddr = $6BB960; // WORD hp UserAttribNeigongAddr = $6BB968; // WORD mp UserAttribGongjiAddr = $6BB964; // WORD atk UserAttribFangyuAddr = $6BB962; // WORD def UserAttribQinggongAddr = $6BB966; // WORD dex UserAttribRemainingAddr = $6BCCF4; // WORD unused attributes // User coordinates on map //UserPosXAdress = $006c22a8; CN //UserPosYAdress = $006c22ac; UserPosXAdress = $006BB9D8; UserPosYAdress = $006BB9DC; UserRealXAddress = $006BB9E8; UserRealYAddress = $006BB9EC; // 用户所在的地图的ID、名称的地址 //UserCurMapAddress = $006c4630; // DWORD //UserCurMapNameAddress = $006c45A0; // 16 Bytes UserCurMapAddress = $006BDD60; // DWORD UserCurMapNameAddress = $006BDCD0; // 16 Bytes // 用户所处环境状态地址;状态:3f1-战斗,3f2-平时,3f3-与NPC对话 UserEnvironmentAdress = $0066C0B8; // WORD UserEnvSwitchMap = $3f0; UserEnvBattle = $3f1; UserEnvNormal = $3f2; UserEnvDialog = $3f3; UserEnvSomeAboutDealingPostClickMessage = $3f4; // 用户身上武器、衣服、鞋子、身饰、头饰的偏移 //UserWuqiOnBodyAddress = $006c39a4; //UserHujiaOnBodyAddress = $006c39a8; //UserXieziOnBodyAddress = $006c39ac; //UserShenshiOnBodyAddress = $006c39b0; //UserToushiOnBodyAddress = $006c39b4; UserWuqiOnBodyAddress = $6BD0D4; UserHujiaOnBodyAddress = $6BD0D8; UserXieziOnBodyAddress = $6BD0DC; UserShenshiOnBodyAddress = $6BD0E0; UserToushiOnBodyAddress = $6BD0E4; // 与对话指针的指针 //NPCDialogAddressAddress = $6c6f60; NPCDialogAddressAddress = $6C06C0; // 对话数据的长度 NPCDialogLength = $200; // $006c39a0($006c39c0) 是一个指针的指针的base地址 // 用户物品栏里面物品数目的地址 //UserItemCountAddress = $006c39ec; UserItemCountAddress = $6BD11C; // 用户物品指针的指针 //UserFirstItemAddressAddress = $006c39c4; UserFirstItemAddressAddress = $006BD0F4; // 宠物指针的指针 //UserFirstPetAddressAddress = $006C3A0C; UserFirstPetAddressAddress = $6BD13C; // 宠物数据的大小 UserPetSize = $B4; // 宠物数目的地址 //UserPetCountAddress = $006c3a34; UserPetCountAddress = $6BD164; // 物品信息数据大小 UserItemInfoSize=$60; // 以下是物品类型 ItemJian = 0; // 剑 ItemDao = 1; // 刀 ItemChui = 2; // 锤 ItemTui = 3; // 腿 ItemHuan = 4; // 环 ItemShan = 5; // 扇 ItemZhang = 6; // 杖 ItemCha = 7; // 叉 ItemGou = 8; // 钩 ItemHujia = 100; // 护甲 ItemXiezi = 200; // 鞋子 ItemShenshi = 300; // 身饰 ItemToushi = 400; // 头饰 ItemAnqi = 500; // 暗器 ItemDuyao = 600; // 毒药 ItemLiaoshangyao = 700; // 疗伤药,注:内药和血药 ItemUnknown = 800; // 不知道是什么,估计是任务用品 // 老虎机 投币 位置 TigerMachinePutCoinX = '263'; TigerMachinePutCoinY = '84'; // 老虎机 "3" 位置 TigerMachineCheckX = '426'; TigerMachineCheckY = '151'; // 游戏主窗口 PlayLeftJust = 29; PlayRightJust = -31; PlayTopJust = 58; PlayBottomJust = -132; // 主面板窗口 PnlMainTitle = 'pnlMain'; // 物品/装备窗口 ItemWindowTitle = 'Item/Equipment'; // “装备” 按钮 ItemButtonX = 630; ItemButtonY = 450; // 以下是物品栏内15个位置 Item1X = 395; Item1Y = 75; Item2X = 440; Item2Y = 75; Item3X = 485; Item3Y = 75; Item4X = 535; Item4Y = 75; Item5X = 395; Item5Y = 120; Item6X = 440; Item6Y = 120; Item7X = 485; Item7Y = 120; Item8X = 530; Item8Y = 120; Item9X = 395; Item9Y = 170; Item10X = 440; Item10Y = 170; Item11X = 490; Item11Y = 170; Item12X = 530; Item12Y = 170; Item13X = 395; Item13Y = 215; Item14X = 440; Item14Y = 215; Item15X = 485; Item15Y = 210; // 用户招的数目地址 //UserWGCountAddress = $006c3a7c; UserWGCountAddress = $6BD1AC; // 用户招式指针的指针 //UserFirstWGAddressAddress = $006c3a54; UserFirstWGAddressAddress = $6BD184; // 招式数据 // 名称[16];创招人[16];[4];武功ID[4];起手[4];轨迹[4];爆炸[4];等级[4];内力[4];显示系数*100[4];[12];实际系数与显示系数的比值[4];[16];[8];经验[4];... // 招式数据长度 UserWGDataLength = $6c; // 创招 招式名称 CreateWG_MC_LeftJust = 112; CreateWG_MC_RightJust = -50; CreateWG_MC_TopJust = 54; CreateWG_MC_BottomJust = -343; // 创招 杀伤系数 CreateWG_XS_LeftJust = 112; CreateWG_XS_RightJust = -50; CreateWG_XS_TopJust = 78; CreateWG_XS_BottomJust = -319; // 创招 使用内力 CreateWG_NL_LeftJust = 112; CreateWG_NL_RightJust = -50; CreateWG_NL_TopJust = 102; CreateWG_NL_BottomJust = -295; // 创招 起手姿势 CreateWG_QS_LeftJust = 112; CreateWG_QS_RightJust = -50; CreateWG_QS_TopJust = 239; CreateWG_QS_BottomJust = -158; // 创招 飞行轨迹 CreateWG_GJ_LeftJust = 112; CreateWG_GJ_RightJust = -50; CreateWG_GJ_TopJust = 265; CreateWG_GJ_BottomJust = -132; // 创招 爆炸方式 CreateWG_BZ_LeftJust = 112; CreateWG_BZ_RightJust = -50; CreateWG_BZ_TopJust = 291; CreateWG_BZ_BottomJust = -106; // 炼化菜单 IDM_UniverseStove = 20; // 创招菜单ID IDM_CreateWG = 22; // 人物属性菜单ID IDM_HumanAttr = 73; // 战斗菜单ID IDM_Battle = 88; // 物品菜单ID IDM_Item = 74; // 战斗状态的地址 // BattleStateAddr = $006c51dc; BattleStateAddr = $6BE90C; // 战斗指令的地址 // BattleOrderAddr = $006c6018; BattleOrderAddr = $6BF748; // 战斗指令数据的大小 BattleOrderSize = $1c; // 战斗指令状态[4], 人物动作[4],人物动作对象[4],[4],宠物动作[4],宠物动作对象[4],[4] //Combat command status [4], character action [4], character action object [4], [4], pet action [4], pet action object [4], [4] // Autofight 0-no 1-yes // BattleIsAutoFightAddr = $006c6260; BattleIsAutoFightAddr = $6BF990; // 是否快速战斗 0-不是,1-是 // BattleIsFastFightAddr = $006c6478; BattleIsFastFightAddr = $6BFBA8; // 战斗时生物的数据大小 CreatureInfoSize = $70; // 战斗怪物数(不大于5)地址 // 6c627c // 战斗死掉的怪物数地址 // DeadMonsterCountAddr = $6c626c; DeadMonsterCountAddr = $6BF99C; // 战斗时生物的数目(包括自己和宠)的地址 // BattleCreatureCountAddress = $006c5144; BattleCreatureCountAddress = $6BE874; // 战斗时生物指针的指针 // BattleFirstCreatureAddressAddress = $006c511c; BattleFirstCreatureAddressAddress = $6BE84C; // 战斗时的动作 BattleAttack = 0; BattleMagic = 1; // 这个时候,BattleBufferRemain1就是要练的拳 BattleDefence = 2; BattleCapture = 6; BattleEscape = 5; BattleIdle = 3; BattleEat = 9; // 这个时候,BattleBufferRemain1就是要吃的药的ID DelWGRemainEasyWG = -1; DelWGNoIndicator = -2; // 用户炼化经验地址 //UserLianhuaExpAddr = $006c2220; UserLianhuaExpAddr = $6BB950; // Oven item type StoveRoomVide = $4D2; StoveRoomPet = $4D4; StoveRoomItem = $4D6; //DialogControlAddr = $6c6d40; DialogControlAddr = $6c04a0; // 控制是否是对话框状态的地址 //6c6f60 > 6C06C0 // 从Exported Entry可得到 // 幻灵FormMain // HL_FormMainAddrAddrAddr = $006ab338; // 幻灵UniverseStoveForm //HL_UniverseStoveFormAddressAddress = $006abb08; HL_UniverseStoveFormAddressAddress = $006A8568; HL_HeroStatsFormAddressAddress = $006a4ec8; AttrOffset_Rem = $4bc; AttrOffset_Life = $4d4; AttrOffset_Mana = $4d8; AttrOffset_Attack = $4dc; AttrOffset_Defense = $4e0; AttrOffset_Dexterity = $4e4; implementation end.
unit Odontologia.Modelo.Departamento; interface uses Data.DB, SimpleDAO, SimpleInterface, SimpleQueryRestDW, System.SysUtils, Odontologia.Modelo.Departamento.Interfaces, Odontologia.Modelo.Entidades.Departamento, Odontologia.Modelo.Conexion.RestDW, Odontologia.Modelo.Pais, Odontologia.Modelo.Pais.Interfaces; type TModelDepartamento = class(TInterfacedOBject, iModelDepartamento) private FEntidad : TDDEPARTAMENTO; FDAO : iSimpleDao<TDDEPARTAMENTO>; FDataSource : TDataSource; FPais : iModelPais; public constructor Create; destructor Destroy; override; class function New : iModelDepartamento; function Entidad : TDDEPARTAMENTO; overload; function Entidad(aEntidad: TDDEPARTAMENTO) : iModelDepartamento; overload; function DAO : iSimpleDao<TDDEPARTAMENTO>; function DataSource(aDataSource: TDataSource) : iModelDepartamento; function Pais : iModelPais; end; implementation { TModelDepartamento } constructor TModelDepartamento.Create; begin FEntidad := TDDEPARTAMENTO.Create; FDAO := TSimpleDAO<TDDEPARTAMENTO> .New(TSimpleQueryRestDW<TDDEPARTAMENTO> .New(ModelConexion.RESTDWDataBase1)); FPais := TModelPais.New; end; function TModelDepartamento.DAO: iSimpleDao<TDDEPARTAMENTO>; begin Result := FDAO; end; function TModelDepartamento.DataSource(aDataSource: TDataSource): iModelDepartamento; begin Result := Self; FDataSource := aDataSource; FDAO.DataSource(FDataSource); end; destructor TModelDepartamento.Destroy; begin FreeAndNil(FEntidad); inherited; end; function TModelDepartamento.Entidad(aEntidad: TDDEPARTAMENTO): iModelDepartamento; begin Result := Self; FEntidad := aEntidad; end; function TModelDepartamento.Pais: iModelPais; begin Result := FPais; end; function TModelDepartamento.Entidad: TDDEPARTAMENTO; begin Result := FEntidad; end; class function TModelDepartamento.New: iModelDepartamento; begin Result := Self.Create; end; end.
unit uneTypes; {******************************************************************************* * * * Название модуля : * * * * uneTypes * * * * Назначение модуля : * * * * Централизованное хранение пользовательских типов, констант и пр. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Classes, Controls, DB, IBase; resourcestring //Сообщения пользовательских исключительных ситуаций sELoadMethod = 'Не удалось получить адрес метода '; sELoadPackage = 'Не удалось загрузить пакет '; sEFileNotFound = 'Файл не найден'; sEConvertError = 'Некорректное преобразование типов'; sEFileNotFound1 = 'Файл '; sEFileNotFound2 = ' не найден'; sEIniFileNotFound = 'Конфигурационный файл не найден'; sEInvalidConnectParams = 'Параметры соединения отсутствуют или заданы некорректно'; sEInvalidExpMethodParams = 'Входящие параметры для экспортируемого метода не найдены'; //Составляющие сообщения об ошибке sErrorText = ' Ошибка: '; sErrorCode = 'Код ошибки: '; sErrorAddr = 'Адрес ошибки: '; sErrorSearch = ' не найден'; sErrorTextExt = 'Ошибка: '; sMsgCaptionErr = 'Ошибка'; sMsgCaptionWrn = 'Предупреждение'; sMsgCaptionInf = 'Информация'; sMsgCaptionQst = 'Подтверждение'; sErrorTextRUS = ' Ошибка: '; sErrorCodeRUS = 'Код ошибки: '; sErrorAddrRUS = 'Адрес ошибки: '; sErrorSearchRUS = ' не найден'; sErrorTextExtRUS = 'Ошибка: '; sErrorTextUA = ' Помилка: '; sErrorCodeUA = 'Код помилки: '; sErrorAddrUA = 'Адреса помилки: '; sErrorSearchUA = ' не знайдено'; sErrorTextExtUA = 'Помилка: '; sMsgCaptionErrRUS = 'Ошибка'; sMsgCaptionWrnRUS = 'Предупреждение'; sMsgCaptionInfRUS = 'Информация'; sMsgCaptionQstRUS = 'Подтверждение'; sMsgCaptionErrUA = 'Помилка'; sMsgCaptionWrnUA = 'Попередження'; sMsgCaptionInfUA = 'Інформація'; sMsgCaptionQstUA = 'Підтвердження'; //Имя конфигурационного файла sLOG_FILE_NAME = 'JO5Errors.log'; sINI_FILE_NAME = 'Config.ini'; //Название ключей в главной секции конфигурационного INI - файла sPATH = 'Path'; sSERVER = 'Server'; sPASSWORD = 'Password'; sUSER_NAME = 'User'; sCHAR_SET = 'CharSet'; sSQL_DIALECT = 'SQLDialect'; sLOG_FILE_PATH = 'PathLog'; //Сообщения для ИС сторонних разработчиков sMsgKernelError = 'Ошибка ядра: '; //Названия месяцев на русском языке sMAY_RUS = 'Май'; sJUNE_RUS = 'Июнь'; sJULY_RUS = 'Июль'; sMARCH_RUS = 'Март'; sAPRIL_RUS = 'Апрель'; sAUGEST_RUS = 'Август'; sOCTOBER_RUS = 'Октябрь'; sJANUARY_RUS = 'Январь'; sFEBRUARY_RUS = 'Февраль'; sNOVEMBER_RUS = 'Ноябрь'; sDECEMBER_RUS = 'Декабрь'; sSEPTEMBER_RUS = 'Сентябрь'; //Названия месяцев на украинском языке sMAY_UA = 'Травень'; sJUNE_UA = 'Червень'; sJULY_UA = 'Липень'; sMARCH_UA = 'Березень'; sAPRIL_UA = 'Квітень'; sAUGEST_UA = 'Серпень'; sOCTOBER_UA = 'Жовтень'; sJANUARY_UA = 'Січень'; sNOVEMBER_UA = 'Листопад'; sDECEMBER_UA = 'Грудень'; sFEBRUARY_UA = 'Лютий'; sSEPTEMBER_UA = 'Вересень'; //Текст для секции "соединение" строки состояния sStatusBarConnectionUA = 'База даних: '; sStatusBarConnectionRUS = 'База данных: '; //Текст для секции "пользователь" строки состояния sStatusBarUserUA = 'Користувач: '; sStatusBarUserRUS = 'Пользователь: '; //Текст для секции "текущий период" строки состояния sMMenuCurrPeriodUA = 'Поточний період: '; sMMenuCurrPeriodRUS = 'Текущий период: '; type //Перечисляемый тип для определения типа параметров печати журнала //НЕ ИЗМЕНЯТЬ ПОСЛЕДОВАТЕЛЬНОСТЬ ЭЛ-ОВ!!! TEnm_PrtJrnlParams = ( jpSch, jpSubSch, jpGrSmet, jpSmet, jpRazd, jpStat, jpKekv ); //Перечисляемый тип для определения типа загружаемой из пакета формы TEnm_LanguageId = ( liUa, liRus, liEng ); //Перечисляемый тип для установки различных режимов заполнения списка допустимых месяцев TFillMode = ( fmNone, fmInc, fmDec, fmFull ); //Перечисляемый тип для определения типа отображения параметров корреспонденции TEnm_KorParamsTypeInfo = ( kpNumber, kpTitle ); //Перечисляемый тип для определения типа загружаемой из пакета формы TEnm_FormType = ( ftNone, ftForm, ftDBForm ); //Перечисляемый тип для определения стиля формы TEnm_FormStyle = ( fsDefault, fsModal, fsMDIChild ); //Перечисляемый тип для установки различных режимов проведения документов через ядро TKernelMode = ( kmNone, kmAdd, kmDelete, kmEdit ); //Перечисляемый тип для установки различных режимов запуска менеджера счетов TManegerSchMode = ( mmNone, mmCloseSch, mmOpenSch, mmBlockSch ); //Перечисляемый тип для расшифровки возвращаемых менеджером счетов результатов TManegerSchResult = ( msrError, msrOK ); //Перечисляемый тип для установки различных режимов закрытия (отката) системы TSystemMode = ( smOpen, smClose ); //Перечисляемый тип для расшифровки ошибок проверки при подготовке к импорту TImportCheckError = ( ectNone, ectParamsNotFound, ectFNUnknown, ectFTIcompatible ); //Перечисляемый тип для определения параметров формы редактирования TActionType = ( actAdd, actEdit, actDelete, actWatch, actNone, actDetAdd, actDetEdit, actDetDelete, actDetWatch, actDetNone ); //Перечисляемый тип для установки различных режимов запуска справочников TSelectionMode = ( smNone, smSingleSelect, smMultiSelect ); //Перечисляемый тип для организации ф-ций мультивыбора TSelectionType = ( stpSelectAll, stpUnSelectAll, stpInvert ); //Перечисляемый тип для определения кол-ва помеченных записей TCheckedRecCount = ( crcNone, crcSome, crcAll ); //Перечисляемый тип для определения кол-ва используемых для фильтрации CheckBox - ов TCheckedBoxes = ( cbNone, cbFrom, cbTill, cbBoth ); //Перечисляемый тип для хранения названий системных процедур (возвращающие настройки системы) TIniStProcName = ( NDS_INI_SETUP_SEL, NDS_INI_PERCENT_RATE_SEL, NDS_INI_PERCENT_RATE_SEL_ACT ); //Множество параметров печати журнала TSet_PrtJrnlParams = set of TEnm_PrtJrnlParams; //Динамический массив для хранения целых чисел TIntArray = array of Integer; //Динамический массив для хранения денежных единиц TCurrArray = array of Currency; //Запись для хранения параметров соединения TParams = packed record Name : String; Value : String; end; TPtr_SysOptions = ^TRec_SysOptions; //Запись для хранения умалчиваемых системных настроек TRec_SysOptions = packed record IdUser : Int64; UsrFIO : String; IsValid : Boolean; UsrLogin : String; UsrPassword : String; KodSystem : Integer; DefRegUch : Int64; DateSetUp : TDate; LangugeId : TEnm_LanguageId; DefCaseKey : Integer; NameSystem : String; RootTypeObj : Integer; AppHandle : THandle; AppExePath : String; LogFileName : String; ConnectionStr : String; KodCurrPeriod : Integer; DateCurrPeriod : TDate; DateFirstImport : TDate; end; TPtr_SchParams = ^TRec_SchParams; //Запись для хранения параметров для получения оборотов по счетам TRec_SchParams = packed record KodSystem : Integer; DefRegUch : Int64; RootTypeObj : Integer; KodSysPeriod : Integer; KodCurrPeriod : Integer; DateSysPeriod : TDate; DateCurrPeriod : TDate; end; TPtr_KorParams = ^TRec_KorParams; //Запись для хранения параметров для получения корреспонденции TRec_KorParams = packed record IdSch : Int64; SchName : String; IdKorSch : Int64; IdRegUch : Int64; CurrPeriod : TDate; HasChildren : Boolean; IsKorrespondKR : Boolean; end; //Запись для хранения параметров полей импорта TFieldRec = packed record FieldName : String; FieldType : TFieldType; end; //Запись для хранения параметров загрузки модуля Ярика TRec_SmRzSt = packed record IdUser : Int64; ActualDate : TDate; end; //Запись для хранения значений границ периода TRec_PeriodBorders = packed record DateBeg : TDate; DateEnd : TDate; end; TPtr_FMParams = ^TRec_FMParams; //Запись для хранения параметров загрузки формы TRec_FMParams = packed record Owner : TComponent; Style : TEnm_FormStyle; end; TPtr_DBFMParams = ^TRec_DBFMParams; //Запись для хранения параметров загрузки справочника TRec_DBFMParams = packed record Owner : TComponent; Style : TEnm_FormStyle; DBHandle : TISC_DB_HANDLE; TRRHandle : TISC_TR_HANDLE; end; //Запись для хранения значений параметров визуализации корреспонденции TRec_KorParamsTypeInfo = packed record Checked : Boolean; TypeInfo : TEnm_KorParamsTypeInfo; end; TPtr_KorParamsInfo = ^TRec_KorParamsInfo; //Запись для хранения параметров визуализации корреспонденции TRec_KorParamsInfo = packed record ModRes : TModalResult; GrSmet : TRec_KorParamsTypeInfo; Smet : TRec_KorParamsTypeInfo; Razd : TRec_KorParamsTypeInfo; Stat : TRec_KorParamsTypeInfo; Kekv : TRec_KorParamsTypeInfo; end; TPtr_MTDParams = ^TRec_MTDParams; //Запись для хранения параметров экспортируемых из пакета методов TRec_MTDParams = packed record SmRzSt : TRec_SmRzSt; KorParams : TRec_KorParams; SysOptions : TRec_SysOptions; KorParamsInfo : TRec_KorParamsInfo; case TEnm_FormType of ftForm : ( FMParams : TRec_FMParams ); ftDBForm : ( DBFMParams : TRec_DBFMParams ); end; TPtr_BPLParams = ^TRec_BPLParams; //Запись для хранения параметров загрузки пакета TRec_BPLParams = packed record MethodName : String; PackageName : String; end; const cCRLF = #13#10; //Символы окончания строки и перехода на следующую cTICK = ''''; //Символ кавычка cLINE = '-'; //Символ дефис cEQUAL = '='; //Символ равно cSPACE = ' '; //Символ пробел cDEF_DAY = 15; //Дата по умолчанию для текущего периода cDEF_MODE = smNone; //Режим запуска справочника по умолчанию cSEMICOLON = ','; //Символ запятая cBRAKET_OP = '('; //Символ открывающая скобка cBRAKET_CL = ')'; //Символ закрывающая скобка cDEF_CHAR_SET = 'win1251'; //Кодировка БД по умолчанию cDEF_EDIT_MODE = actAdd; //Режим редактирования по умолчанию cYEAR_UA_SHORT = ' р.'; //Год (сокр.) по-украински cYEAR_RUS_SHORT = ' г.'; //Год (сокр.) по-русски cDEF_SQL_DIALECT = '3'; //Диалект БД по умолчанию cFIRST_DAY_OF_MONTH = 1; //Первый день месяца cDEF_IS_CLOSE_PERIOD = 0; //Логическое значение по умолчанию для закрытия журнала в текущем периоде cDEF_LANGUGE_ID = liRus; //Умалчиваемый идентификатор языка //Названия полей DBF-таблицы документов, подлежащих проверке при импорте cDOC_FN_FIO = 'FIO'; cDOC_FN_NOTE = 'NOTE'; cDOC_FN_SUMMA = 'SUMMA'; cDOC_FN_ID_DOC = 'ID_DOC'; cDOC_FN_NUM_DOC = 'NUM_DOC'; cDOC_FN_DATE_DOC = 'DATE_DOC'; cDOC_FN_DATE_REG = 'DATE_REG'; cDOC_FN_DATE_PROV = 'DATE_PROV'; cDOC_FN_ID_TYPE_DOC = 'TYPE_DOC'; //Типы полей DBF-таблицы документов, подлежащих проверке при импорте cDOC_FT_FIO = ftString; cDOC_FT_NOTE = ftString; cDOC_FT_SUMMA = ftFloat; cDOC_FT_ID_DOC = ftInteger; cDOC_FT_NUM_DOC = ftString; cDOC_FT_DATE_DOC = ftDate; cDOC_FT_DATE_REG = ftDate; cDOC_FT_DATE_PROV = ftDate; cDOC_FT_ID_TYPE_DOC = ftInteger; //Названия полей DBF-таблицы проводок, подлежащих проверке при импорте cPROV_FN_SUMMA = 'SUMMA'; cPROV_FN_STORNO = 'STORNO'; cPROV_FN_ID_PROV = 'ID_PROV'; cPROV_FN_DATE_REG = 'DATE_REG'; cPROV_FN_CR_BY_DT = 'CR_BY_DT'; cPROV_FN_TABLE_NUM = 'TN'; cPROV_FN_DB_ID_DOC = 'DB_ID_DOC'; cPROV_FN_KR_ID_DOC = 'KR_ID_DOC'; cPROV_FN_DB_BAL_ID = 'DB_BAL_ID'; cPROV_FN_DB_SUB_ID = 'DB_SUB_ID'; cPROV_FN_KR_BAL_ID = 'KR_BAL_ID'; cPROV_FN_KR_SUB_ID = 'KR_SUB_ID'; cPROV_FN_DB_DT_PROV = 'DB_DT_PROV'; cPROV_FN_KR_DT_PROV = 'KR_DT_PROV'; cPROV_FN_DB_KOD_SMET = 'DB_KOD_SM'; cPROV_FN_KR_KOD_SMET = 'KR_KOD_SM'; cPROV_FN_DB_KOD_RAZD = 'DB_KOD_RAZ'; cPROV_FN_KR_KOD_RAZD = 'KR_KOD_RAZ'; cPROV_FN_DB_KOD_STAT = 'DB_KOD_ST'; cPROV_FN_KR_KOD_STAT = 'KR_KOD_ST'; //Типы полей DBF-таблицы проводок, подлежащих проверке при импорте cPROV_FT_SUMMA = ftFloat; cPROV_FT_STORNO = ftBoolean; cPROV_FT_ID_PROV = ftInteger; cPROV_FT_DATE_REG = ftDate; cPROV_FT_CR_BY_DT = ftBoolean; cPROV_FT_TABLE_NUM = ftInteger; cPROV_FT_DB_ID_DOC = ftInteger; cPROV_FT_KR_ID_DOC = ftInteger; cPROV_FT_DB_BAL_ID = ftInteger; cPROV_FT_DB_SUB_ID = ftSmallInt; cPROV_FT_KR_BAL_ID = ftInteger; cPROV_FT_KR_SUB_ID = ftSmallInt; cPROV_FT_DB_DT_PROV = ftDate; cPROV_FT_KR_DT_PROV = ftDate; cPROV_FT_DB_KOD_SMET = ftSmallInt; cPROV_FT_KR_KOD_SMET = ftSmallInt; cPROV_FT_DB_KOD_RAZD = ftSmallInt; cPROV_FT_KR_KOD_RAZD = ftSmallInt; cPROV_FT_DB_KOD_STAT = ftSmallInt; cPROV_FT_KR_KOD_STAT = ftSmallInt; //Массив названий месяцев на украинском языке cMonthUA : array[0..11] of String = ( sJANUARY_UA, sFEBRUARY_UA, sMARCH_UA, sAPRIL_UA, sMAY_UA, sJUNE_UA, sJULY_UA, sAUGEST_UA, sSEPTEMBER_UA, sOCTOBER_UA, sNOVEMBER_UA, sDECEMBER_UA ); //Массив названий месяцев на русском языке cMonthRUS : array[0..11] of String = ( sJANUARY_RUS, sFEBRUARY_RUS, sMARCH_RUS, sAPRIL_RUS, sMAY_RUS, sJUNE_RUS, sJULY_RUS, sAUGEST_RUS, sSEPTEMBER_RUS, sOCTOBER_RUS, sNOVEMBER_RUS, sDECEMBER_RUS ); //Вспомогательный массив основных параметров соединения cMainParams : array[0..3] of String = ( sSERVER, sPATH, sUSER_NAME, sPASSWORD ); //Вспомогательный массив дополнительных параметров соединения cAdditionalParams : array[0..2] of TParams = ( ( Name: sCHAR_SET; Value: cDEF_CHAR_SET ), ( Name: sSQL_DIALECT; Value: cDEF_SQL_DIALECT ), ( Name: sLOG_FILE_PATH; Value: sLOG_FILE_NAME ) ); //Массив параметров полей DBF-таблицы документов cProcImpDocFields : array[0..8] of TFieldRec = ( ( FieldName: cDOC_FN_ID_DOC; FieldType: cDOC_FT_ID_DOC ), ( FieldName: cDOC_FN_DATE_DOC; FieldType: cDOC_FT_DATE_DOC ), ( FieldName: cDOC_FN_NUM_DOC; FieldType: cDOC_FT_NUM_DOC ), ( FieldName: cDOC_FN_DATE_PROV; FieldType: cDOC_FT_DATE_PROV ), ( FieldName: cDOC_FN_SUMMA; FieldType: cDOC_FT_SUMMA ), ( FieldName: cDOC_FN_NOTE; FieldType: cDOC_FT_NOTE ), ( FieldName: cDOC_FN_FIO; FieldType: cDOC_FT_FIO ), ( FieldName: cDOC_FN_DATE_REG; FieldType: cDOC_FT_DATE_REG ), ( FieldName: cDOC_FN_ID_TYPE_DOC; FieldType: cDOC_FT_ID_TYPE_DOC ) ); //Массив параметров полей DBF-таблицы проводок cProcImpProvFields : array[0..19] of TFieldRec = ( ( FieldName: cPROV_FN_ID_PROV; FieldType: cPROV_FT_ID_PROV ), ( FieldName: cPROV_FN_CR_BY_DT; FieldType: cPROV_FT_CR_BY_DT ), ( FieldName: cPROV_FN_STORNO; FieldType: cPROV_FT_STORNO ), ( FieldName: cPROV_FN_SUMMA; FieldType: cPROV_FT_SUMMA ), ( FieldName: cPROV_FN_TABLE_NUM; FieldType: cPROV_FT_TABLE_NUM ), ( FieldName: cPROV_FN_DB_BAL_ID; FieldType: cPROV_FT_DB_BAL_ID ), ( FieldName: cPROV_FN_DB_SUB_ID; FieldType: cPROV_FT_DB_SUB_ID ), ( FieldName: cPROV_FN_KR_BAL_ID; FieldType: cPROV_FT_KR_BAL_ID ), ( FieldName: cPROV_FN_KR_SUB_ID; FieldType: cPROV_FT_KR_SUB_ID ), ( FieldName: cPROV_FN_DB_DT_PROV; FieldType: cPROV_FT_DB_DT_PROV ), ( FieldName: cPROV_FN_KR_DT_PROV; FieldType: cPROV_FT_KR_DT_PROV ), ( FieldName: cPROV_FN_DB_KOD_SMET; FieldType: cPROV_FT_DB_KOD_SMET ), ( FieldName: cPROV_FN_KR_KOD_SMET; FieldType: cPROV_FT_KR_KOD_SMET ), ( FieldName: cPROV_FN_DB_KOD_RAZD; FieldType: cPROV_FT_DB_KOD_RAZD ), ( FieldName: cPROV_FN_KR_KOD_RAZD; FieldType: cPROV_FT_KR_KOD_RAZD ), ( FieldName: cPROV_FN_DB_KOD_STAT; FieldType: cPROV_FT_DB_KOD_STAT ), ( FieldName: cPROV_FN_KR_KOD_STAT; FieldType: cPROV_FT_KR_KOD_STAT ), ( FieldName: cPROV_FN_DATE_REG; FieldType: cPROV_FT_DATE_REG ), ( FieldName: cPROV_FN_DB_ID_DOC; FieldType: cPROV_FT_DB_ID_DOC ), ( FieldName: cPROV_FN_KR_ID_DOC; FieldType: cPROV_FT_KR_ID_DOC ) ); implementation end.
unit OTFEE4MScramDiskPasswordEntry_U; // Description: Password Entry Dialog // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, KeyboardDialog_U; type TOTFEE4MScramDiskPasswordEntry_F = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; pbOK: TButton; pbCancel: TButton; mePassword1: TMaskEdit; mePassword3: TMaskEdit; mePassword2: TMaskEdit; mePassword4: TMaskEdit; pbKeydisk: TButton; pbKeyboard1: TButton; pbKeyboard3: TButton; pbKeyboard4: TButton; pbKeyboard2: TButton; KeyboardDialog: TKeyboardDialog; ckHidePasswords: TCheckBox; cbDrives: TComboBox; Label5: TLabel; procedure FormDestroy(Sender: TObject); procedure pbKeydiskClick(Sender: TObject); procedure pbKeyboard1Click(Sender: TObject); procedure pbKeyboard2Click(Sender: TObject); procedure pbKeyboard3Click(Sender: TObject); procedure pbKeyboard4Click(Sender: TObject); procedure ckHidePasswordsClick(Sender: TObject); public FDefaultDrive: Ansichar; procedure ClearEnteredPasswords(); procedure SetDrivesAllowed(drvs: Ansistring); procedure SetDrive(dfltDrv: Ansichar); function GetDrive(): Ansichar; published property Drive: Ansichar read GetDrive write SetDrive; property DrivesAllowed: Ansistring write SetDrivesAllowed; end; implementation {$R *.DFM} uses Math, SDUGeneral; const ONE_PASSWORD_LENGTH = 40; // Presumably this should be enough to overwrite the relevant strings in memory? procedure TOTFEE4MScramDiskPasswordEntry_F.ClearEnteredPasswords(); var junkString : string; i : integer; begin // Create a string 1024 chars long... (assumes that user won't try to enter // a password more than this length; anything more than 40 is probably // overkill anyway) junkString := ''; randomize; for i:=0 to 1024 do begin junkString := junkString + chr(random(255)); end; // ...overwrite any passwords entered... mePassword1.text := junkString; mePassword2.text := junkString; mePassword3.text := junkString; mePassword4.text := junkString; // ...and then reset to a zero length string, just to be tidy. mePassword1.text := ''; mePassword2.text := ''; mePassword3.text := ''; mePassword4.text := ''; end; procedure TOTFEE4MScramDiskPasswordEntry_F.FormDestroy(Sender: TObject); begin ClearEnteredPasswords(); end; procedure TOTFEE4MScramDiskPasswordEntry_F.pbKeydiskClick(Sender: TObject); var openDialog: TOpenDialog; fileHandle: TextFile; aPassword: string; begin openDialog := TOpenDialog.Create(nil); try if openDialog.Execute() then begin AssignFile(fileHandle, openDialog.Filename); Reset(fileHandle); Readln(fileHandle, aPassword); mePassword1.text := aPassword; Readln(fileHandle, aPassword); mePassword2.text := aPassword; Readln(fileHandle, aPassword); mePassword3.text := aPassword; Readln(fileHandle, aPassword); mePassword4.text := aPassword; Readln(fileHandle, aPassword); if aPassword<>'KeepDialog' then begin ModalResult := mrOK; end; end; // OpenDialog.Execute() finally CloseFile(fileHandle); openDialog.Free(); end; end; { // This is a binary version of the above function procedure TPasswordEntry_F.pbKeydiskClick(Sender: TObject); var openDialog: TOpenDialog; fileHandle: TFileStream; blankingBytes: array [0..ONE_PASSWORD_LENGTH] of byte; i: integer; bytesRead: integer; begin openDialog := TOpenDialog.Create(nil); try if openDialog.Execute() then begin fileHandle := TFileStream.Create(openDialog.Filename, fmOpenRead); bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH); mePassword1.text := ''; for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do begin mePassword1.text := mePassword1.text + char(blankingBytes[i-1]); end; bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH); mePassword2.text := ''; for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do begin mePassword2.text := mePassword2.text + char(blankingBytes[i-1]); end; bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH); mePassword3.text := ''; for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do begin mePassword3.text := mePassword3.text + char(blankingBytes[i-1]); end; bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH); mePassword4.text := ''; for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do begin mePassword4.text := mePassword4.text + char(blankingBytes[i-1]); end; ModalResult := mrOK; end; // OpenDialog.Execute() finally fileHandle.free; openDialog.Free(); end; end; } procedure TOTFEE4MScramDiskPasswordEntry_F.pbKeyboard1Click(Sender: TObject); begin if KeyboardDialog.execute() then begin mePassword1.text := KeyboardDialog.password; end; KeyboardDialog.BlankPassword(); end; procedure TOTFEE4MScramDiskPasswordEntry_F.pbKeyboard2Click(Sender: TObject); begin if KeyboardDialog.execute() then begin mePassword2.text := KeyboardDialog.password; end; KeyboardDialog.BlankPassword(); end; procedure TOTFEE4MScramDiskPasswordEntry_F.pbKeyboard3Click(Sender: TObject); begin if KeyboardDialog.execute() then begin mePassword3.text := KeyboardDialog.password; end; KeyboardDialog.BlankPassword(); end; procedure TOTFEE4MScramDiskPasswordEntry_F.pbKeyboard4Click(Sender: TObject); begin if KeyboardDialog.execute() then begin mePassword4.text := KeyboardDialog.password; end; KeyboardDialog.BlankPassword(); end; procedure TOTFEE4MScramDiskPasswordEntry_F.ckHidePasswordsClick(Sender: TObject); var passwordChar: char; begin passwordChar := #0; if ckHidePasswords.checked then begin passwordChar := '*'; end; mePassword1.passwordchar := passwordChar; mePassword2.passwordchar := passwordChar; mePassword3.passwordchar := passwordChar; mePassword4.passwordchar := passwordChar; end; procedure TOTFEE4MScramDiskPasswordEntry_F.SetDrive(dfltDrv: Ansichar); begin FDefaultDrive:= dfltDrv; dfltDrv := AnsiString((uppercase(dfltDrv)))[1]; // This will ensure that we either have the default drive selected, or the // first drive if cbDrives.items.IndexOf(dfltDrv+':')>-1 then begin cbDrives.itemindex := cbDrives.items.IndexOf(dfltDrv+':'); end else begin cbDrives.itemindex := 0; end; end; function TOTFEE4MScramDiskPasswordEntry_F.GetDrive(): Ansichar; begin if cbDrives.items.count<1 then begin Result := #0 end else begin Result :=AnsiChar( cbDrives.text[1]); end; end; procedure TOTFEE4MScramDiskPasswordEntry_F.SetDrivesAllowed(drvs: Ansistring); var i: integer; begin // Setup the drives the user is allowed to select for i:=1 to length(drvs) do begin cbDrives.items.Add(drvs[i]+':'); end; cbDrives.sorted := TRUE; SetDrive(FDefaultDrive); end; END.
unit SynHighlighterText; {$I SynEdit.inc} interface uses SysUtils, Windows, Messages, Classes, Controls, Graphics, Registry, SynEditHighlighter, SynEditTypes; type TtkTokenKind = ( tkNull, tkUnknown); // TRangeState = (rsANil, rsAnsi, rsPasStyle, rsCStyle, rsUnKnown); TProcTableProc = procedure of Object; type TSynTextSyn = class(TSynCustomHighLighter) private fSpaceAttri :TSynHighlighterAttributes; fTokenID: TtkTokenKind; Run: LongInt; fTokenPos: Integer; fLine: PChar; fLineNumber : Integer; fProcTable: array[#0..#255] of TProcTableProc; // fRange: TRangeState; procedure MakeMethodTables; procedure NullProc; procedure UnknownProc; protected function GetIdentChars: TSynIdentChars; override; public // class function GetCapability: THighlighterCapability; override; //gp 2000-01-20 class function GetLanguageName: string; override; //gp 2000-01-20 public constructor Create(AOwner: TComponent); override; // procedure ExportNext; override; destructor Destroy; override; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; //mh 2000-01-17 override; function GetEol: Boolean; override; // function GetRange: Pointer; override; function GetTokenID: TtkTokenKind; procedure SetLine(NewValue: String; LineNumber:Integer); override; function GetToken: String; override; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; procedure Next; override; // procedure SetLineForExport(NewValue: String); override; // procedure SetRange(Value: Pointer); override; // procedure ReSetRange; override; published property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; end; procedure Register; implementation uses SynEditStrConst; const INDENT_CHARS :TSynIdentChars = [#33..#255]- ['!','"','#','$','%','&','/','(',')','=','?','*','+',';',',',':','.','-','>','<','\','|','[',']','@','{','}']; procedure Register; begin RegisterComponents(SYNS_HighlightersPage, [TSynTextSyn]); end; //class function TSynTextSyn.GetCapability: THighlighterCapability; //gp 2000-01-20 //begin // Result := inherited GetCapability + [hcExportable]; //end; constructor TSynTextSyn.Create(AOwner: TComponent); begin {begin} //mh 2000-01-14 inherited Create(AOwner); fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace); AddAttribute(fSpaceAttri); {end} //mh 2000-01-14 SetAttributesOnChange(DefHighlightChange); MakeMethodTables; end; { Create } destructor TSynTextSyn.Destroy; begin inherited Destroy; end; { Destroy } procedure TSynTextSyn.MakeMethodTables; var I: Char; begin for I := #0 to #255 do case I of #0: fProcTable[I] := NullProc; else fProcTable[I] := UnknownProc; end; end; procedure TSynTextSyn.NullProc; begin fTokenID := tkNull; end; procedure TSynTextSyn.SetLine(NewValue: String; LineNumber:Integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; Next; end; { SetLine } procedure TSynTextSyn.UnknownProc; begin Run:=Length(fLine); fTokenID := tkUnKnown; end; procedure TSynTextSyn.Next; begin fTokenPos := Run; fProcTable[fLine[Run]]; end; function TSynTextSyn.GetIdentChars: TSynIdentChars; begin Result := INDENT_CHARS; end; class function TSynTextSyn.GetLanguageName: string; //gp 2000-01-20 begin Result := 'Text files'; end; {begin} //mh 2000-01-17 function TSynTextSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin result:=fSpaceAttri; end; {end} //mh 2000-01-17 function TSynTextSyn.GetTokenKind: integer; begin Result := ord(tkUnKnown); end; function TSynTextSyn.GetTokenPos: Integer; begin Result := 0; end; function TSynTextSyn.GetEol: Boolean; begin Result := fTokenId = tkNull; end; //function TSynTextSyn.GetRange: Pointer; //begin // Result := Pointer(fRange); //end; function TSynTextSyn.GetToken: String; var Len: LongInt; begin Len := Length(fLine); SetString(Result, FLine, Len); end; function TSynTextSyn.GetTokenID: TtkTokenKind; begin Result := tkUnKnown; end; function TSynTextSyn.GetTokenAttribute: TSynHighlighterAttributes; begin Result := fSpaceAttri; end; //procedure TSynTextSyn.SetRange(Value: Pointer); //begin //end; //procedure TSynTextSyn.ReSetRange; //begin // fRange := rsUnknown; //end; //procedure TSynTextSyn.ExportNext; //begin // Next; // if Assigned(Exporter) then // with TmwCustomExport(Exporter) do begin // FormatToken(GetToken, fSpaceAttri, False, True); // end; //with //end; initialization RegisterPlaceableHighlighter(TSynTextSyn); //gp 2000-01-20 end.
unit glRegistry; interface uses SysUtils, Classes, Registry, Variants, Windows; type TmyValue = record mValue: Variant; mType: TVarType; end; TglRegistry = class(TComponent) private fCompanyName, fProjectName: string; protected { Protected declarations } public procedure SaveParam(KEY: HKEY; Name: string; Value: Variant; ValueType: TVarType); function LoadParam(KEY: HKEY; Name: string; ValueType: TVarType): TmyValue; function CheckExistKey(KEY: HKEY; Name: string): boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property CompanyName: string read fCompanyName write fCompanyName; property ProjectName: string read fProjectName write fProjectName; end; procedure Register; implementation // {$R glRegistry} procedure Register; begin RegisterComponents('Golden Line', [TglRegistry]); end; { TglRegistry } function TglRegistry.CheckExistKey(KEY: HKEY; Name: string): boolean; var R: TRegistry; begin result := false; R := TRegistry.Create; R.RootKey := KEY; if R.OpenKey('Software\' + CompanyName + '\' + ProjectName + '\', false) then if R.ValueExists(Name) then result := true; end; constructor TglRegistry.Create(AOwner: TComponent); begin inherited; fCompanyName := 'Icarus.Empire'; fProjectName := 'NewProject'; end; destructor TglRegistry.Destroy; begin fCompanyName := ''; fProjectName := ''; inherited; end; function TglRegistry.LoadParam(KEY: HKEY; Name: string; ValueType: TVarType) : TmyValue; var R: TRegistry; begin R := TRegistry.Create; R.RootKey := KEY; R.OpenKey('Software\' + CompanyName + '\' + ProjectName + '\', false); if not R.ValueExists(Name) then begin result.mType := varError; exit; end; result.mType := ValueType; case ValueType of varInteger: result.mValue := R.ReadInteger(Name); varString: result.mValue := R.ReadString(Name); varBoolean: result.mValue := R.ReadBool(Name); varDate: result.mValue := R.ReadDateTime(Name); varDouble: result.mValue := R.ReadFloat(Name); end; R.CloseKey; R.Free; end; procedure TglRegistry.SaveParam(KEY: HKEY; Name: string; Value: Variant; ValueType: TVarType); var R: TRegistry; begin R := TRegistry.Create; R.RootKey := KEY; R.OpenKey('Software\' + CompanyName + '\' + ProjectName + '\', true); case ValueType of varInteger: R.WriteInteger(Name, Value); varString: R.WriteString(Name, Value); varBoolean: R.WriteBool(Name, Value); varDate: R.WriteDateTime(Name, Value); varDouble: R.WriteFloat(Name, Value); end; R.CloseKey; R.Free; end; end.
Program charReplace; VAR ch: CHAR; charsRead, charsWritten:LONGINT; BEGIN charsRead :=0; charsWritten :=0; REPEAT (* input ist die mit Eingabelenkung eingegebene Datei *) Read(input, ch); charsRead:=charsRead+1; IF ch='Ä' THEN BEGIN Write(output, 'Ae'); charsWritten:=charsWritten+2; END ELSE IF ch='ä' THEN BEGIN Write(output, 'ae'); charsWritten:=charsWritten+2; END ELSE IF ch='Ö' THEN BEGIN Write(output, 'Oe'); charsWritten:=charsWritten+2; END ELSE IF ch='ö' THEN BEGIN Write(output, 'oe'); charsWritten:=charsWritten+2; END ELSE IF ch='Ü' THEN BEGIN Write(output, 'Ue'); charsWritten:=charsWritten+2; END ELSE IF ch='ü' THEN BEGIN Write(output, 'ue'); charsWritten:=charsWritten+2; END ELSE IF ch='ß' THEN BEGIN Write(output, 'ss'); charsWritten:=charsWritten+2; END ELSE IF ch='«' THEN BEGIN Write(output, '<<'); charsWritten:=charsWritten+2; END ELSE IF ch='»' THEN BEGIN Write(output, '>>'); charsWritten:=charsWritten+2; END ELSE BEGIN Write(output, ch); charsWritten:=charsWritten+1; END; UNTIL Eof(input); Writeln(); WriteLn('chars read = ', charsRead, ' chars Written = ', charsWritten,'.'); END.
program LightFileStreamBenchmark; {$mode Delphi}{$H+}{$J-}{$I-}{$R-} uses SysUtils, Classes, EpikTimer, LightFileStream; const QC: QWord = 1844674407370955; var QV, I, J: QWord; TimeA, TimeB, TimeC, TimeD: String; Timer: TEpikTimer; begin Timer := TEpikTimer.Create(nil); Timer.Start(); with TFileStream.Create('OutputA.bin', fmCreate) do begin for I := 0 to 2999999 do WriteQWord(QC); Free(); end; Timer.Stop(); TimeA := Timer.ElapsedStr(); Timer.Clear(); Timer.Start(); with TLightFileStream.Create('OutputB.bin') do begin for J := 0 to 2999999 do WriteQWord(QC); Close(); end; Timer.Stop(); TimeB := Timer.ElapsedStr(); Timer.Clear(); Timer.Start(); with TFileStream.Create('OutputA.bin', fmOpenRead) do begin for I := 0 to 2999999 do QV := ReadQWord(); Free(); end; Timer.Stop(); TimeC := Timer.ElapsedStr(); Timer.Clear(); Timer.Start(); with TLightFileStream.Open('OutputB.bin', fsReading) do begin for J := 0 to 2999999 do ReadQWord(QV); Close(); end; Timer.Stop(); TimeD := Timer.ElapsedStr(); Timer.Free(); WriteLn('TFileStream Write: ', TimeA); WriteLn('TLightFileStream Write: ', TimeB); WriteLn('TFileStream Read: ', TimeC); WriteLn('TLightFileStream Read: ', TimeD); DeleteFile('OutputA.bin'); DeleteFile('OutputB.bin'); end.
{La sala de un teatro tiene N filas con M butacas cada una y ha representado la ocupación para una función en T(matriz entera). Cada elemento T[fila,butaca] almacena el código 1,2 o 3, para indicar: 1. Disponible 2. Vendida 3. Vendida con Descuento. Los datos N y M viene en la primer linea del archivo Teatro.TXT . El precio de cada entrada es X y el descuento es del D%, ambos datos vienen en la segunda línea del archivo. Se pide leer la información y a partir de la matriz T de NxM, calcular e informar: A) Cuantas filas registran al menos una butaca disponible. B) Fila con importe máximo(obtenido de las butacas vendidas con y sin descuento). N=4 M=5 X=500 D=20 2 3 1 3 2 T=2 2 2 2 3 2 1 2 2 1 3 3 3 3 2 Respuestas: A) 2 filas. B) Fila 2(con $2400). } Program Teatro; Type TM = array[1..100,1..100] of integer; Procedure LeerArchivo(Var T:TM; Var N,M:byte; Var X,D:real); Var i,j:byte; arch:text; begin assign(arch,'Teatro.txt');reset(arch); readln(arch,N,M); readln(arch,X,D); For i:= 1 to N do begin For j:= 1 to M do read(arch,T[i,j]); readln(arch); end; close(arch); end; Function CuantasFilas(T:TM; N,M:byte):byte; Var i,j,Cont:byte; begin Cont:= 0; For i:= 1 to N do begin j:= 1; while (j <= M) and (T[i,j] <> 1) do j:= j + 1; If (j > M) then Cont:= Cont + 1; end; CuantasFilas:= Cont; end; Procedure MaximaFila(T:TM; N,M:byte; X,D:real); Var i,j,PosMax:byte; Acum,Max,Desc:real; begin Max:= 0; Desc:= (100 - D) /100; For i:= 1 to N do begin Acum:= 0; For j:= 1 to M do begin If (T[i,j] = 2) then Acum:= Acum + X Else if (T[i,j] = 3) then Acum:= Acum + (X * Desc); end; If (Acum > Max) then begin Max:= Acum; PosMax:= i; end; end; writeln('B- Fila ',PosMax,' tiene el importe maximo con $',Max:6:2); end; Var T:TM; N,M:byte; X,D:real; Begin LeerArchivo(T,N,M,X,D); writeln('A- Cantidad de filas con al menos una butaca disponible: ',CuantasFilas(T,N,M)); writeln; writeln; MaximaFila(T,N,M,X,D); end.
unit TpTable; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThWebControl, TpControls; type TTpTable = class(TThWebControl) private FColCount: Integer; FRowCount: Integer; FOnCell: TTpEvent; FBorder: Integer; FOnGenerate: TTpEvent; procedure SetOnGenerate(const Value: TTpEvent); protected procedure SetBorder(const Value: Integer); procedure SetColCount(const Value: Integer); procedure SetOnCell(const Value: TTpEvent); procedure SetRowCount(const Value: Integer); public constructor Create(AOwner: TComponent); override; function GetHtmlAsString: string; override; procedure Paint; override; published property Align; property Border: Integer read FBorder write SetBorder; property ColCount: Integer read FColCount write SetColCount default 3; property OnCell: TTpEvent read FOnCell write SetOnCell; property OnGenerate: TTpEvent read FOnGenerate write SetOnGenerate; property RowCount: Integer read FRowCount write SetRowCount default 3; property Style; property StyleClass; property Visible; end; implementation constructor TTpTable.Create(AOwner: TComponent); begin inherited; FColCount := 3; FRowCount := 3; end; procedure TTpTable.Paint; begin inherited; ThPaintOutline(Canvas, AdjustedClientRect, clBlue, psDot); end; function TTpTable.GetHtmlAsString: string; begin Result := '<table' + TpAttr('border', Border) + TpAttr(tpClass, 'TTpTable') + TpAttr('tpName', Name) + TpAttr('tpCols', ColCount) + TpAttr('tpRows', RowCount) + TpAttr('tpOnGenerate', OnGenerate) + TpAttr('tpOnCell', OnCell) + CtrlStyle.StyleAttribute + '>'#13 + ' <tr><td>Dynamic Table</td></tr>'#13 + '</table>'#13 ; end; procedure TTpTable.SetColCount(const Value: Integer); begin FColCount := Value; end; procedure TTpTable.SetOnCell(const Value: TTpEvent); begin FOnCell := Value; end; procedure TTpTable.SetRowCount(const Value: Integer); begin FRowCount := Value; end; procedure TTpTable.SetBorder(const Value: Integer); begin FBorder := Value; end; procedure TTpTable.SetOnGenerate(const Value: TTpEvent); begin FOnGenerate := Value; end; end.
unit UBackTrack; interface Const MaxN = 20; type TRing = array [1..MaxN] of string; TUsed = array [1..MaxN] of boolean; procedure Solve (var Elements : TRing; len : integer; var MaxCount : integer; var MaxRing : TRing); implementation procedure Solve (var Elements : TRing; len : integer; var MaxCount : integer; var MaxRing : TRing); var Count : integer; Ring : TRing; Used : TUsed; vowels : set of char; consonants : set of char; function CheckWord(w : string):boolean; var vow, con, j : integer; begin vow := 0; con := 0; for j := 1 to Length(w) do begin if (w[j] in vowels) then inc(vow) else if (w[j] in consonants) then inc(con); end; result := vow = con; if ((Count <> 0) and result) then result := w[1] = Ring[count][length(Ring[count])] end; function CheckRing:boolean; begin result := Count <> 0; if (result) then result := Ring[1][1] = Ring[Count][Length(Ring[Count])]; end; procedure ClearUsed; var j : integer; begin for j := 1 to MaxN do Used[j] := false; end; procedure TryPut (i : integer); var j : integer; begin if (CheckRing) then begin if (MaxCount < Count) then begin MaxCount := Count; MaxRing := Ring; end; end; if (i <= len) then begin used[i] := true; if (CheckWord(Elements[i])) then begin inc(Count); Ring[Count] := Elements[i]; for j := 1 to len + 1 do if (not used[j]) then TryPut(j); dec(Count); end; for j := 1 to len + 1 do if (not used[j]) then TryPut(j); used[i] := false; end; end; begin count := 0; ClearUsed; vowels := ['À', 'Î', 'Ó', 'Û', 'Ý', '¨', 'Þ', 'È', 'Å']; consonants := ['Á', 'Â', 'Ã', 'Ä', 'Æ', 'Ç', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Ü']; TryPut(1); end; end.
program HowToMoveAPanel; uses SwinGame, sgTypes, sgUserInterface; procedure Main(); var p : Panel; begin OpenGraphicsWindow('How To Move A Panel', 800, 600); LoadDefaultColors(); p := LoadPanel('panelwithlabel.txt'); ShowPanel(p); repeat // The game loop... ProcessEvents(); ClearScreen(ColorWhite); DrawInterface(); PanelSetDraggable(p, true); GUISetBackgroundColor(ColorGreen); UpdateInterface(); RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
unit EdictTests; // Requires EDICT in the same folder interface uses TestFramework; type TEdictTests = class(TTestCase) published procedure EdictRead; procedure EdictLoad; end; TEdictSpeedTests = class(TTestCase) public FReader: TEdictTests; procedure SetUp; override; procedure TearDown; override; published procedure EdictReadTime; procedure EdictLoadTime; end; implementation uses SysUtils, Classes, Windows, TestingCommon, JWBIO, EdictReader, Edict; procedure TEdictTests.EdictRead; var AInput: TStreamDecoder; ed: TEdictArticle; ln: string; begin AInput := OpenTextFile(CommonDataDir+'\EDICT2'); AInput.Rewind(); while AInput.ReadLn(ln) do begin ln := Trim(ln); if ln='' then continue; ParseEdict2Line(ln, @ed); end; end; procedure TEdictTests.EdictLoad; var Edict: TEdict; begin Edict := TEdict.Create; Edict.LoadFromFile(CommonDataDir+'\EDICT2'); FreeAndNil(Edict); end; const EDICT_ITER_CNT: integer = 1; procedure TEdictSpeedTests.SetUp; begin FReader := TEdictTests.Create(''); end; procedure TEdictSpeedTests.TearDown; begin FreeAndNil(FReader); end; procedure TEdictSpeedTests.EdictReadTime; var i: integer; tm: cardinal; begin tm := GetTickCount; for i := 0 to EDICT_ITER_CNT-1 do FReader.EdictRead(); tm := GetTickCount-tm; Status('x'+IntToStr(EDICT_ITER_CNT)+' = '+IntToStr(tm)+' ticks.'); end; procedure TEdictSpeedTests.EdictLoadTime; var i: integer; tm: cardinal; begin tm := GetTickCount; for i := 0 to EDICT_ITER_CNT-1 do FReader.EdictLoad(); tm := GetTickCount-tm; Status('x'+IntToStr(EDICT_ITER_CNT)+' = '+IntToStr(tm)+' ticks.'); end; initialization RegisterTest(TNamedTestSuite.Create('Edict', TEdictTests)); RegisterSpeedTest(TNamedTestSuite.Create('Edict', TEdictSpeedTests)); end.
unit ufrmDialogViewInvoice; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, StdCtrls, ufraFooterDialog2Button, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.Menus, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxButtons; type TfrmDialogViewInvoice = class(TfrmMasterDialog) pnl1: TPanel; pnl2: TPanel; lbl1: TLabel; edtInvoiceNo: TEdit; lbl2: TLabel; edtCustomer: TEdit; btnSearch: TcxButton; lbl3: TLabel; edtAgreementNo: TEdit; lbl4: TLabel; curredtTotalAgreement: TcxCurrencyEdit; lbl5: TLabel; edtNoJadwal: TEdit; lbl6: TLabel; edtInvoiceDate: TEdit; lbl10: TLabel; lbl11: TLabel; lbl12: TLabel; lbl13: TLabel; curredtTotal: TcxCurrencyEdit; curredtTotalPPH23: TcxCurrencyEdit; curredtTotalPPN: TcxCurrencyEdit; curredtTotalSubTotal: TcxCurrencyEdit; lbl8: TLabel; edtStatus: TEdit; lbl9: TLabel; edtDescription: TEdit; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; cxcolCode: TcxGridDBColumn; cxcolDescription: TcxGridDBColumn; cxcolQTY: TcxGridDBColumn; cxlvMaster: TcxGridLevel; cxcolUOM: TcxGridDBColumn; cxcolTotal: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure edtInvoiceNoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSearchClick(Sender: TObject); private FAgreementId: string; FAgreementJadwalId: string; // function GetSQLUpDown(aKey: Word; aAgrJdlID: string): string; procedure ParseDataHeader; procedure ParseDataHeaderUpDown(Key: Word); procedure ParseDataAgreementDetil; public property AgreementId: string read FAgreementId write FAgreementId; property AgreementJadwalId: string read FAgreementJadwalId write FAgreementJadwalId; end; var frmDialogViewInvoice: TfrmDialogViewInvoice; implementation {$R *.dfm} uses uRetnoUnit; procedure TfrmDialogViewInvoice.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogViewInvoice.FormDestroy(Sender: TObject); begin inherited; frmDialogViewInvoice := nil; end; procedure TfrmDialogViewInvoice.ParseDataHeader; var // isPPH23: Boolean; s: string; begin s:= 'SELECT CUST.CUST_CODE || '' | '' || CUST.CUST_NAME AS CUST_NAME,' + ' A.AGR_NO, SUM(AD.AGRD_TOTAL) AS TOTAL_AGREEMENT,' + ' AJ.AGRJDWL_INV_TERM_NO, AJ.AGRJDWL_INV_DATE,' + ' AJ.AGRJDWL_INV_DESCRIPTION, A.AGR_IS_PPH23, AJ.AGRJDWL_ID,' + ' P.PJK_PPN, SP.STAPRO_NAME, A.AGR_ID, AJ.AGRJDWL_INV_TOTAL FROM AGREEMENT_JADWAL AJ' + ' LEFT JOIN AGREEMENT A ON A.AGR_ID = AJ.AGRJDWL_AGR_ID' + ' AND A.AGR_UNT_ID = AJ.AGRJDWL_AGR_UNT_ID' + ' LEFT JOIN AGREEMENT_DETIL AD ON AD.AGRD_AGR_ID = A.AGR_ID' + ' AND AD.AGRD_AGR_UNT_ID = A.AGR_UNT_ID' + ' LEFT JOIN CUSTOMER CUST ON CUST.CUST_CODE = A.AGR_CUST_CODE' + ' AND CUST.CUST_UNT_ID = A.AGR_CUST_UNT_ID' + ' LEFT JOIN REF$PAJAK P ON P.PJK_ID = A.AGR_PJK_ID' + ' AND P.PJK_UNT_ID = A.AGR_PJK_UNT_ID' + ' LEFT JOIN REF$STATUS_PROSES SP ON SP.STAPRO_ID = AJ.AGRJDWL_STAPRO_ID_INV' + ' AND SP.STAPRO_UNT_ID = AJ.AGRJDWL_STAPRO_UNT_ID_INV' + ' WHERE AJ.AGRJDWL_INV_NO = '+ QuotedStr(edtInvoiceNo.Text) + ' AND AJ.AGRJDWL_UNT_ID = '+ IntToStr(DialogUnit) + ' GROUP BY A.AGR_ID, A.AGR_NO, CUST.CUST_CODE, CUST.CUST_NAME,' + ' AJ.AGRJDWL_INV_TERM_NO, AJ.AGRJDWL_INV_DATE,' + ' AJ.AGRJDWL_INV_DESCRIPTION, A.AGR_IS_PPH23, AJ.AGRJDWL_ID,' + ' P.PJK_PPN, SP.STAPRO_NAME, AJ.AGRJDWL_INV_TOTAL '; // with cOpenQuery(s) do // begin // try // if not IsEmpty then // begin // edtCustomer.Text := fieldbyname('CUST_NAME').AsString; // edtAgreementNo.Text := fieldbyname('AGR_NO').AsString; // edtNoJadwal.Text := fieldbyname('AGRJDWL_INV_TERM_NO').AsString; // edtInvoiceDate.Text := fieldbyname('AGRJDWL_INV_DATE').AsString; // edtStatus.Text := fieldbyname('STAPRO_NAME').AsString; // edtDescription.Text := fieldbyname('AGRJDWL_INV_DESCRIPTION').AsString; // curredtTotalAgreement.Value := fieldbyname('TOTAL_AGREEMENT').AsCurrency; // curredtTotalSubTotal.Value := fieldbyname('AGRJDWL_INV_TOTAL').AsCurrency; // // if FieldByName('AGR_IS_PPH23').AsInteger = 0 then // isPPH23 := False // else // isPPH23 := True; // // curredtTotalPPN.Value := (curredtTotalSubTotal.Value * FieldByName('PJK_PPN').AsCurrency) / 100; // // if isPPH23 then // curredtTotalPPH23.Value := curredtTotalPPN.Value // else // curredtTotalPPH23.Value := 0; // // curredtTotal.Value := curredtTotalSubTotal.Value + curredtTotalPPN.Value - curredtTotalPPH23.Value; // AgreementId := fieldbyname('AGR_ID').AsString; // AgreementJadwalId := fieldbyname('AGRJDWL_ID').AsString; // // end // else // begin // edtCustomer.Clear; // edtAgreementNo.Clear; // edtNoJadwal.Clear; // edtInvoiceDate.Clear; // edtStatus.Clear; // edtDescription.Clear; // curredtTotalAgreement.Value := 0; // curredtTotalSubTotal.Value := 0; // curredtTotalPPN.Value := 0; // curredtTotalPPH23.Value := 0; // curredtTotal.Value := 0; // end; // // finally // Free; // end; // end; end; procedure TfrmDialogViewInvoice.edtInvoiceNoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F5 then btnSearchClick(Self); if Key = VK_RETURN then begin ParseDataHeader; ParseDataAgreementDetil; end; if (Key = VK_PRIOR) or (Key = VK_NEXT) then begin ParseDataHeaderUpDown(Key); ParseDataAgreementDetil; end; end; procedure TfrmDialogViewInvoice.ParseDataHeaderUpDown(Key: Word); //var // isPPH23: Boolean; begin // with cOpenQuery(GetSQLUpDown(Key, AgreementJadwalId)) do // begin // try // if not IsEmpty then // begin // edtInvoiceNo.Text := fieldbyname('AGRJDWL_INV_NO').AsString; // edtCustomer.Text := fieldbyname('CUST_NAME').AsString; // edtAgreementNo.Text := fieldbyname('AGR_NO').AsString; // edtNoJadwal.Text := fieldbyname('AGRJDWL_INV_TERM_NO').AsString; // edtInvoiceDate.Text := fieldbyname('AGRJDWL_INV_DATE').AsString; // edtStatus.Text := fieldbyname('STAPRO_NAME').AsString; // edtDescription.Text := fieldbyname('AGRJDWL_INV_DESCRIPTION').AsString; // curredtTotalAgreement.Value := fieldbyname('TOTAL_AGREEMENT').AsCurrency; // curredtTotalSubTotal.Value := fieldbyname('AGRJDWL_INV_TOTAL').AsCurrency; // // if FieldByName('AGR_IS_PPH23').AsInteger = 0 then // isPPH23 := False // else // isPPH23 := True; // // curredtTotalPPN.Value := (curredtTotalSubTotal.Value * FieldByName('PJK_PPN').AsCurrency) / 100; // // if isPPH23 then // curredtTotalPPH23.Value := curredtTotalPPN.Value // else // curredtTotalPPH23.Value := 0; // // curredtTotal.Value := curredtTotalSubTotal.Value + curredtTotalPPN.Value - curredtTotalPPH23.Value; // AgreementId := fieldbyname('AGR_ID').AsString; // AgreementJadwalId := fieldbyname('AGRJDWL_ID').AsString; // end // else // begin // edtInvoiceNo.Clear; // edtCustomer.Clear; // edtAgreementNo.Clear; // edtNoJadwal.Clear; // edtInvoiceDate.Clear; // edtStatus.Clear; // edtDescription.Clear; // curredtTotalAgreement.Value := 0; // curredtTotalSubTotal.Value := 0; // curredtTotalPPN.Value := 0; // curredtTotalPPH23.Value := 0; // curredtTotal.Value := 0; // end; // // finally // Free; // end; // end; end; procedure TfrmDialogViewInvoice.ParseDataAgreementDetil; var // i: Integer; s: string; begin s:= 'SELECT AGRD.AGRD_PROJAS_CODE, PROJAS.PROJAS_NAME, AGRD.AGRD_QTY,' + ' PROJAS.PROJAS_SATNBD_CODE, SATNBD.SATNBD_NAME,' + ' AGRD.AGRD_QTY * AGRD.AGRD_SUBTOTAL AS AGRD_SUBTOTAL' + ' FROM AGREEMENT_DETIL AGRD' + ' LEFT JOIN AGREEMENT AGR ON AGR.AGR_ID = AGRD.AGRD_AGR_ID' + ' AND AGR.AGR_UNT_ID = AGRD.AGRD_AGR_UNT_ID' + ' LEFT JOIN PRODUK_JASA PROJAS ON PROJAS.PROJAS_CODE = AGRD.AGRD_PROJAS_CODE' + ' AND PROJAS.PROJAS_UNT_ID = AGRD.AGRD_PROJAS_UNT_ID' + ' LEFT JOIN REF$SATUAN_NBD SATNBD ON SATNBD.SATNBD_CODE = PROJAS.PROJAS_SATNBD_CODE' + ' AND SATNBD.SATNBD_UNT_ID = PROJAS.PROJAS_SATNBD_UNT_ID' + ' WHERE AGRD.AGRD_AGR_ID = '+ QuotedStr(AgreementId) + ' AND AGRD.AGRD_UNT_ID = '+ IntToStr(DialogUnit); // with strgGrid do // begin // with cOpenQuery(s, False) do // begin // try // if not IsEmpty then // begin // Last; // strgGrid.RowCount := RecordCount + 1; // // i := 1; // First; // while not Eof do // begin // Cells[0, i] := FieldByName('AGRD_PROJAS_CODE').AsString; // Cells[1, i] := FieldByName('AGRD_QTY').AsString // + ' ' + FieldByName('SATNBD_NAME').AsString // + ' ' + FieldByName('PROJAS_NAME').AsString; // Cells[2, i] := FieldByName('AGRD_QTY').AsString; // Cells[3, i] := FieldByName('PROJAS_SATNBD_CODE').AsString; // Cells[4, i] := FieldByName('AGRD_SUBTOTAL').AsString; // Alignments[4, i] := taRightJustify; // Cells[5, i] := FieldByName('SATNBD_NAME').AsString; // // Inc(i); // Next; // end; // end // else // begin // RowCount := 2; // Cells[0, 1] := ''; // Cells[1, 1] := ''; // Cells[2, 1] := ''; // Cells[3, 1] := ''; // Cells[4, 1] := ''; // Cells[5, 1] := ''; // end; // // finally // Free; // end; // end; // // AutoSize := True; // FixedRows := 1; // end; end; procedure TfrmDialogViewInvoice.btnSearchClick(Sender: TObject); begin inherited; // if not Assigned(frmDialogSearchInvoice) then // frmDialogSearchInvoice := TfrmDialogSearchInvoice.Create(Application); // // frmDialogSearchInvoice.DialogCompany := DialogCompany; // frmDialogSearchInvoice.DialogUnit := DialogUnit; // // frmDialogSearchInvoice.ShowModal; // edtInvoiceNo.Text := frmDialogSearchInvoice.InvoiceNo; // edtInvoiceNo.SetFocus; // // frmDialogSearchInvoice.Free; end; //function TfrmDialogViewInvoice.GetSQLUpDown(aKey: Word; aAgrJdlID: string): // string; //var // s: string; // sOrder: string; //begin // s:= 'SELECT AJ.AGRJDWL_INV_NO, CUST.CUST_CODE || '' | '' || CUST.CUST_NAME AS CUST_NAME,' // + ' A.AGR_NO, SUM(AD.AGRD_TOTAL) AS TOTAL_AGREEMENT,' // + ' AJ.AGRJDWL_INV_TERM_NO, AJ.AGRJDWL_INV_DATE,' // + ' AJ.AGRJDWL_INV_DESCRIPTION, A.AGR_IS_PPH23, AJ.AGRJDWL_ID,' // + ' P.PJK_PPN, SP.STAPRO_NAME, A.AGR_ID, AJ.AGRJDWL_INV_TOTAL FROM AGREEMENT_JADWAL AJ' // + ' LEFT JOIN AGREEMENT A ON A.AGR_ID = AJ.AGRJDWL_AGR_ID' // + ' AND A.AGR_UNT_ID = AJ.AGRJDWL_AGR_UNT_ID' // + ' LEFT JOIN AGREEMENT_DETIL AD ON AD.AGRD_AGR_ID = A.AGR_ID' // + ' AND AD.AGRD_AGR_UNT_ID = A.AGR_UNT_ID' // + ' LEFT JOIN CUSTOMER CUST ON CUST.CUST_CODE = A.AGR_CUST_CODE' // + ' AND CUST.CUST_UNT_ID = A.AGR_CUST_UNT_ID' // + ' LEFT JOIN REF$PAJAK P ON P.PJK_ID = A.AGR_PJK_ID' // + ' AND P.PJK_UNT_ID = A.AGR_PJK_UNT_ID' // + ' LEFT JOIN REF$STATUS_PROSES SP ON SP.STAPRO_ID = AJ.AGRJDWL_STAPRO_ID_INV' // + ' AND SP.STAPRO_UNT_ID = AJ.AGRJDWL_STAPRO_UNT_ID_INV'; // // if aKey = VK_PRIOR then // begin // s:= s // + ' WHERE AJ.AGRJDWL_ID < '+ aAgrJdlID; // // sOrder:= ' ORDER BY AJ.AGRJDWL_ID DESC ROWS 1 TO 1 '; // end // else if aKey = VK_NEXT then // begin // s:= s // + ' WHERE AJ.AGRJDWL_ID > '+ aAgrJdlID; // // sOrder:= 'ORDER BY AJ.AGRJDWL_ID ASC ROWS 1 TO 1 '; // end; // // Result:= s // + ' AND AJ.AGRJDWL_UNT_ID = '+ IntToStr(DialogUnit) // + ' GROUP BY A.AGR_ID, A.AGR_NO, CUST.CUST_CODE, CUST.CUST_NAME,' // + ' AJ.AGRJDWL_INV_TERM_NO, AJ.AGRJDWL_INV_DATE,' // + ' AJ.AGRJDWL_INV_DESCRIPTION, A.AGR_IS_PPH23, AJ.AGRJDWL_ID,' // + ' P.PJK_PPN, SP.STAPRO_NAME, AJ.AGRJDWL_INV_NO, AJ.AGRJDWL_INV_TOTAL' // + sOrder; //end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CTE_AEREO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CteAereoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TCteAereoVO = class(TVO) private FID: Integer; FID_CTE_CABECALHO: Integer; FNUMERO_MINUTA: Integer; FNUMERO_CONHECIMENTO: Integer; FDATA_PREVISTA_ENTREGA: TDateTime; FID_EMISSOR: String; FID_INTERNA_TOMADOR: String; FTARIFA_CLASSE: String; FTARIFA_CODIGO: String; FTARIFA_VALOR: Extended; FCARGA_DIMENSAO: String; FCARGA_INFORMACAO_MANUSEIO: Integer; FCARGA_ESPECIAL: String; //Transientes published property Id: Integer read FID write FID; property IdCteCabecalho: Integer read FID_CTE_CABECALHO write FID_CTE_CABECALHO; property NumeroMinuta: Integer read FNUMERO_MINUTA write FNUMERO_MINUTA; property NumeroConhecimento: Integer read FNUMERO_CONHECIMENTO write FNUMERO_CONHECIMENTO; property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA; property IdEmissor: String read FID_EMISSOR write FID_EMISSOR; property IdInternaTomador: String read FID_INTERNA_TOMADOR write FID_INTERNA_TOMADOR; property TarifaClasse: String read FTARIFA_CLASSE write FTARIFA_CLASSE; property TarifaCodigo: String read FTARIFA_CODIGO write FTARIFA_CODIGO; property TarifaValor: Extended read FTARIFA_VALOR write FTARIFA_VALOR; property CargaDimensao: String read FCARGA_DIMENSAO write FCARGA_DIMENSAO; property CargaInformacaoManuseio: Integer read FCARGA_INFORMACAO_MANUSEIO write FCARGA_INFORMACAO_MANUSEIO; property CargaEspecial: String read FCARGA_ESPECIAL write FCARGA_ESPECIAL; //Transientes end; TListaCteAereoVO = specialize TFPGObjectList<TCteAereoVO>; implementation initialization Classes.RegisterClass(TCteAereoVO); finalization Classes.UnRegisterClass(TCteAereoVO); end.
unit DXPGradients; interface uses Windows, Graphics, Classes, DXPControl, Controls, Types; type TDXPGradientColors = 2..255; TDXPGradientStyle = (gsLeft, gsTop, gsRight, gsBottom); TDXPGradient = class(TPersistent) private FColors: TDXPGradientColors; FDithered: Boolean; FEnabled: Boolean; FEndColor: TColor; FStartColor: TColor; FGradientStyle: TDXPGradientStyle; FBitmap: TBitmap; { Private declarations } protected Parent: TDXPCustomControl; procedure SetDithered(Value: Boolean); virtual; procedure SetColors(Value: TDXPGradientColors); virtual; procedure SetEnabled(Value: Boolean); virtual; procedure SetEndColor(Value: TColor); virtual; procedure SetGradientStyle(Value: TDXPGradientStyle); virtual; procedure SetStartColor(Value: TColor); virtual; { Protected declarations } public property Bitmap: TBitmap read FBitmap; // constructor Create(AOwner: TControl); destructor Destroy; override; procedure RecreateBands; virtual; { Public declarations } published property Dithered: Boolean read FDithered write SetDithered default True; property Colors: TDXPGradientColors read FColors write SetColors default 16; property Enabled: Boolean read FEnabled write SetEnabled default False; property EndColor: TColor read FEndColor write SetEndColor default clSilver; property StartColor: TColor read FStartColor write SetStartColor default clGray; property Style: TDXPGradientStyle read FGradientStyle write SetGradientStyle default gsLeft; { Published declarations } end; // procedure CreateGradientRect(const aWidth, aHeight: integer; const StartColor, EndColor: TColor; const Colors: TDXPGradientColors; const Style: TDXPGradientStyle; const aDithered: Boolean; var aBitmap: TBitmap); implementation { TDXPGradient } constructor TDXPGradient.Create(AOwner: TControl); begin inherited Create; Parent := TDXPCustomControl( AOwner ); FBitmap := TBitmap.Create; FColors := 16; FDithered := true; FEnabled := false; FEndColor := clSilver; FGradientStyle := gsLeft; FStartColor := clGray; end; destructor TDXPGradient.Destroy; begin FBitmap.Free; inherited Destroy; end; procedure TDXPGradient.RecreateBands; begin if Assigned( FBitmap ) then CreateGradientRect( Parent.Width, Parent.Height, FStartColor, FEndColor, FColors, FGradientStyle, FDithered, FBitmap ); end; procedure TDXPGradient.SetColors(Value: TDXPGradientColors); begin if FColors <> Value then begin FColors := Value; RecreateBands; Parent.Redraw; end; end; procedure TDXPGradient.SetDithered(Value: Boolean); begin if FDithered <> Value then begin FDithered := Value; RecreateBands; Parent.Redraw; end; end; procedure TDXPGradient.SetEnabled(Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; Parent.Redraw; end; end; procedure TDXPGradient.SetEndColor(Value: TColor); begin if FEndColor <> Value then begin FEndColor := Value; RecreateBands; Parent.Redraw; end; end; procedure TDXPGradient.SetGradientStyle(Value: TDXPGradientStyle); begin if FGradientStyle <> Value then begin FGradientStyle := Value; RecreateBands; Parent.Redraw; end; end; procedure TDXPGradient.SetStartColor(Value: TColor); begin if FStartColor <> Value then begin FStartColor := Value; RecreateBands; Parent.Redraw; end; end; { Static Methods } procedure CreateGradientRect(const aWidth, aHeight: integer; const StartColor, EndColor: TColor; const Colors: TDXPGradientColors; const Style: TDXPGradientStyle; const aDithered: Boolean; var aBitmap: TBitmap); // const PixelCountMax = 32768; // type TGradientBand = array[0..255] of TColor; TRGBMap = packed record case boolean of true: ( RGBVal: DWord ); false: ( R, G, B, D: Byte ); end; // PRGBTripleArray = ^TRGBTripleArray; TRGBTripleArray = array[0..PixelCountMax-1] of TRGBTriple; // const DitherDepth = 16; var iLoop, xLoop, yLoop, XX, YY: Integer; iBndS, iBndE: Integer; GBand: TGradientBand; Row: pRGBTripleArray; // procedure CalculateGradientBand; var rR, rG, rB: Real; lCol, hCol: TRGBMap; iStp: Integer; begin if Style in [gsLeft, gsTop] then begin lCol.RGBVal := ColorToRGB( StartColor ); hCol.RGBVal := ColorToRGB( EndColor ); end else begin lCol.RGBVal := ColorToRGB( EndColor ); hCol.RGBVal := ColorToRGB( StartColor ); end; // rR := ( hCol.R - lCol.R ) / ( Colors - 1 ); rG := ( hCol.G - lCol.G ) / ( Colors - 1 ); rB := ( hCol.B - lCol.B ) / ( Colors - 1 ); // for iStp := 0 to ( Colors - 1 ) do GBand[iStp] := RGB( lCol.R + Round( rR * iStp ), lCol.G + Round( rG * iStp ), lCol.B + Round( rB * iStp ) ); end; // begin aBitmap.Height := AHeight; aBitmap.Width := AWidth; // if aBitmap.PixelFormat <> pf24bit then aBitmap.PixelFormat := pf24bit; // CalculateGradientBand; // aBitmap.Canvas.Brush.Color := StartColor; aBitmap.Canvas.FillRect( Bounds( 0, 0, aWidth, aHeight ) ); // if Style in [gsLeft, gsRight] then begin for iLoop := 0 to Colors - 1 do begin iBndS := MulDiv( iLoop, aWidth, Colors ); iBndE := MulDiv( iLoop + 1, aWidth, Colors ); aBitmap.Canvas.Brush.Color := GBand[iLoop]; PatBlt( aBitmap.Canvas.Handle, iBndS, 0, iBndE, AHeight, PATCOPY ); // if ( iLoop > 0 ) and ( aDithered ) then for yLoop := 0 to DitherDepth - 1 do if ( yLoop < aHeight ) then begin Row := aBitmap.Scanline[yLoop]; // for xLoop := 0 to aWidth div ( Colors - 1 ) do begin XX := iBndS + Random( xLoop ); // if ( XX < aWidth ) and ( XX > -1 ) then with Row[XX] do begin rgbtRed := GetRValue( GBand[iLoop - 1] ); rgbtGreen := GetGValue( GBand[iLoop - 1] ); rgbtBlue := GetBValue( GBand[iLoop - 1] ); end; end; end; end; // for yLoop := 1 to aHeight div DitherDepth do aBitmap.Canvas.CopyRect( Bounds( 0, yLoop * DitherDepth, aWidth, DitherDepth ), aBitmap.Canvas, Bounds( 0, 0, aWidth, DitherDepth ) ); end else begin for iLoop := 0 to Colors - 1 do begin iBndS := MulDiv( iLoop, aHeight, Colors ); iBndE := MulDiv( iLoop + 1, aHeight, Colors ); aBitmap.Canvas.Brush.Color := GBand[iLoop]; PatBlt( aBitmap.Canvas.Handle, 0, iBndS, aWidth, iBndE, PATCOPY ); // if ( iLoop > 0 ) and ( aDithered ) then for yLoop := 0 to aHeight div ( Colors - 1 ) do begin YY := iBndS + Random( yLoop ); // if ( YY < aHeight ) and ( YY > -1 ) then begin Row := aBitmap.Scanline[YY]; // for xLoop := 0 to DitherDepth - 1 do if ( xLoop < aWidth ) then with Row[xLoop] do begin rgbtRed := GetRValue( GBand[iLoop - 1] ); rgbtGreen := GetGValue( GBand[iLoop - 1] ); rgbtBlue := GetBValue( GBand[iLoop - 1] ); end; end; end; end; // for xLoop := 0 to aWidth div DitherDepth do aBitmap.Canvas.CopyRect( Bounds( xLoop * DitherDepth, 0, DitherDepth, aHeight ), aBitmap.Canvas, Bounds(0, 0, DitherDepth, aHeight ) ); end; end; end.
unit Common.Entities.GameType; interface uses Spring.Collections.Dictionaries; type TTeamKind=(tkPair,tkSolo,tkOuvert,tkAllOuvert,tkSinglePlayer); TTalon=(tkNoTalon,tk3Talon,tk6Talon); TWinCondition=(wc12Rounds,wc0Trick,wc1Trick,wc2Trick,wc3Trick,wcT1Trick,wcT2Trick,wcT3Trick,wcT4Trick); TGameType=class(TObject) private FPositive: Boolean; FValue: Smallint; FTeamKind: TTeamKind; FName: String; FGameTypeid: String; FByFirstPlayer: Boolean; FJustColors: Boolean; FTalon: TTalon; FWinCondition: TWinCondition; public property GameTypeid:String read FGameTypeid; property Name:String read FName; property ByFirstPlayer:Boolean read FByFirstPlayer; property Positive:Boolean read FPositive; property JustColors:Boolean read FJustColors; property Talon:TTalon read FTalon; property TeamKind:TTeamKind read FTeamKind; property Value:Smallint read FValue; property WinCondition:TWinCondition read FWinCondition; function Clone:TGameType; end; TGameTypes=class(TDictionary<String,TGameType>) public function AddItem(const AID:String; const AName:String; const AValue:Smallint; const APositive:Boolean=True; const ATeamKind:TTeamKind=tkPair; const AByFirstPlayer:Boolean=False; const ATalon:TTalon=tk3Talon; const AWinCondition:TWinCondition=wc12Rounds;const AJustColors:Boolean=False):TGameType; function Find(const AID:String):TGameType; end; var ALLGAMES:TGameTypes; procedure Initialize; procedure TearDown; implementation { TGameTypes } function TGameTypes.AddItem(const AID:String; const AName:String; const AValue:Smallint; const APositive:Boolean=True; const ATeamKind:TTeamKind=tkPair; const AByFirstPlayer:Boolean=False; const ATalon:TTalon=tk3Talon; const AWinCondition:TWinCondition=wc12Rounds ;const AJustColors:Boolean=False): TGameType; begin Result:=TGameType.Create; Result.FGameTypeID:=AID; REsult.FName:=AName; Result.FPositive:=APositive; Result.FTalon:=ATalon; Result.FJustColors:=AJustColors; Result.FTeamKind:=ATeamKind; Result.FByFirstPlayer:=AByFirstPlayer; Result.FValue:=AValue; Result.FWinCondition:=AWinCondition; Add(AID,Result); end; procedure Initialize; begin ALLGames:=TGameTypes.Create; ALLGames.AddItem('RUFER','Königrufer',1,True,tkPair,True); ALLGames.AddItem('TRISCH','Trischaken',1,False,tkSinglePlayer,True,tkNoTalon); ALLGames.AddItem('63','Sechser-Dreier',1,True,tkSolo,True,tk6Talon); ALLGames.AddItem('SUPRA','Solorufer',2,True,tkPair,False,tkNoTalon); ALLGames.AddItem('PICC','Piccolo',2,False,tkSolo,False,tkNoTalon,wc1Trick); ALLGames.AddItem('GRANDE','Zwiccolo',2,False,tkSolo,False,tkNoTalon,wc2Trick); ALLGames.AddItem('TRICC','Triccolo',2,False,tkSolo,False,tkNoTalon,wc3Trick); AllGames.AddItem('VOGEL1','Pagatrufer', 3,True,tkPair,False,tk3Talon,wcT1Trick); ALLGames.AddItem('BETTL','Bettel',4,False,tkSolo,False,tkNoTalon,wc0Trick); AllGames.AddItem('PICC_OU','Piccolo Ouvert',4,False,tkOuvert,False,tkNoTalon,wc1Trick); AllGames.AddItem('GRAND_OU','Zwiccolo Ouvert',4,False,tkOuvert,False,tkNoTalon,wc2Trick); AllGames.AddItem('TRICC_OU','Triccolo Ouvert',4,False,tkOuvert,False,tkNoTalon,wc3Trick); AllGames.AddItem('VOGEL2','Uhurufer',5,True,tkPair,False,tk3Talon,wcT2Trick); ALLGames.AddItem('FARB3','Farben-Dreier',5,True,tkSolo,False,tk3Talon,wc12Rounds,True); ALLGames.AddItem('SOLO','Dreier',6, True,tkSolo); ALLGames.AddItem('BETT_OU','Bettel Ouvert',6,False,tkOuvert,False,tkNoTalon,wc0Trick); AllGames.AddItem('PICC_POU','Piccolo Plauderer',6,False,tkAllOuvert,False,tkNoTalon,wc1Trick); AllGames.AddItem('GRAND_POU','Zwiccolo Plauderer',6,False,tkAllOuvert,False,tkNoTalon,wc2Trick); AllGames.AddItem('TRICCR_POU','Triccolo Plauderer',6,False,tkAllOuvert,False,tkNoTalon,wc3Trick); AllGames.AddItem('VOGEL3','Kakadurufer',7,True,tkPair,False,tk3Talon,wcT3Trick); AllGames.AddItem('SVOGEL1','Pagatdreier',8,True,tkSolo,False,tk3Talon,wcT1Trick); ALLGames.AddItem('BETT_POU','Bettel Plauderer',8,False,tkAllOuvert,False,tkNoTalon,wc0Trick); AllGames.AddItem('VOGEL4','Quapilrufer',9,True,tkPair,False,tk3Talon,wcT4Trick); AllGames.AddItem('SVOGEL2','Uhudreier',10,True,tkSolo,False,tk3Talon,wcT2Trick); ALLGames.AddItem('FARBSOLO','Farben-Solo',10,True,tkSolo,False,tkNoTalon,wc12Rounds,True); AllGames.AddItem('SVOGEL3','Kakadudreier',12,True,tkSolo,False,tk3Talon,wcT3Trick); ALLGames.AddItem('SOLLIS','Solo Dreier',12,True,tkSolo,False,tkNoTalon); AllGames.AddItem('SVOGEL4','Quapildreier',14,True,tkSolo,False,tk3Talon,wcT4Trick); (* Wiener VAriante ALLGames.AddItem('ENTRO','Entro (Königsrufer)',1,True,tkPair,True); ALLGames.AddItem('63','Sechser-Dreier',2,True,tkSolo,True); ALLGames.AddItem('SUPRA','Supra (Solorufer)',2,True,tkPair,False,tkNoTalon); ALLGames.AddItem('PICC','Piccolo',2,False,tkSolo); ALLGames.AddItem('GRANDE','Grande (Zwiccolo)',2,False,tkSolo); ALLGames.AddItem('BETTL','Bettel',3,False,tkSolo); AllGames.AddItem('VOGEL1','Vogel I (Besser Rufer)', 3); ALLGames.AddItem('SOLO','Solo (Dreier)',4,True,tkSolo); AllGames.AddItem('VOGEL2','Vogel II (Besser Rufer)',4); AllGames.AddItem('VOGEL3','Vogel III (Besser Rufer)',5); AllGames.AddItem('SVOGEL1','Solo Vogel I (Besser Dreier)',5,True,tkSolo); AllGames.AddItem('PICCOU','Piccolo Ouvert',5,False,tkOuvert); AllGames.AddItem('GRANDOU','Grande (Zwiccolo) Ouvert',5,False,tkOuvert); AllGames.AddItem('VOGEL4','Vogel IV (Besser Rufer)',6); AllGames.AddItem('SVOGEL2','Solo Vogel II (Besser Dreier)',6,True,tkSolo); ALLGames.AddItem('FARB3','Farben-Solo',6,True,tkSolo,False,tkNoTalon); ALLGames.AddItem('BETTOU','Bettel Ouvert',6,False,tkOuvert); AllGames.AddItem('SVOGEL3','Solo Vogel III (Besser Dreier)',7,True,tkSolo); ALLGames.AddItem('SOLLIS','Solissimo (Solo Dreier)',8,True,tkSolo,False,tkNoTalon); AllGames.AddItem('SVOGEL4','Solo Vogel IV (Besser Dreier)',8,True,tkSolo); *) end; procedure TearDown; begin ALLGAMES.Free; ALLGAMES:=nil; end; function TGameTypes.Find(const AID: String): TGameType; begin try Result:=GetItem(AID); except Result:=nil; end; end; { TGameType } function TGameType.Clone: TGameType; begin Result:=TGameType.Create; Result.FGameTypeid:=FGameTypeId; Result.FName:=FName; Result.FByFirstPlayer:=FByFirstPlayer; Result.FPositive:=FPositive; Result.FJustColors:=FJustColors; Result.FTalon:=FTalon; Result.FTeamKind:=FTeamKind; Result.FValue:=FValue; Result.FWinCondition:=FWincondition; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083117 //////////////////////////////////////////////////////////////////////////////// unit android.hardware.biometrics.BiometricPrompt_Builder; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, java.util.concurrent.Executor, android.content.DialogInterface_OnClickListener, android.hardware.biometrics.BiometricPrompt; type JBiometricPrompt_Builder = interface; JBiometricPrompt_BuilderClass = interface(JObjectClass) ['{B0A75EDE-C760-4E42-AD46-22DF664A8C47}'] function build : JBiometricPrompt; cdecl; // ()Landroid/hardware/biometrics/BiometricPrompt; A: $1 function init(context : JContext) : JBiometricPrompt_Builder; cdecl; // (Landroid/content/Context;)V A: $1 function setDescription(description : JCharSequence) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setNegativeButton(text : JCharSequence; executor : JExecutor; listener : JDialogInterface_OnClickListener) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;Ljava/util/concurrent/Executor;Landroid/content/DialogInterface$OnClickListener;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setSubtitle(subtitle : JCharSequence) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setTitle(title : JCharSequence) : JBiometricPrompt_Builder; cdecl; // (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 end; [JavaSignature('android/hardware/biometrics/BiometricPrompt_Builder')] JBiometricPrompt_Builder = interface(JObject) ['{492C8840-BC60-463B-BA70-27E43FD486E8}'] function build : JBiometricPrompt; cdecl; // ()Landroid/hardware/biometrics/BiometricPrompt; A: $1 function setDescription(description : JCharSequence) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setNegativeButton(text : JCharSequence; executor : JExecutor; listener : JDialogInterface_OnClickListener) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;Ljava/util/concurrent/Executor;Landroid/content/DialogInterface$OnClickListener;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setSubtitle(subtitle : JCharSequence) : JBiometricPrompt_Builder; cdecl;// (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 function setTitle(title : JCharSequence) : JBiometricPrompt_Builder; cdecl; // (Ljava/lang/CharSequence;)Landroid/hardware/biometrics/BiometricPrompt$Builder; A: $1 end; TJBiometricPrompt_Builder = class(TJavaGenericImport<JBiometricPrompt_BuilderClass, JBiometricPrompt_Builder>) end; implementation end.
//------------------------------------------------------------------------------ //ZoneSend UNIT //------------------------------------------------------------------------------ // What it does - // On events executing internally, or by other characters on the server, we // will have to send information to the client to tell it what happened. This // unit houses the routines to do so. // // Changes - // January 18th, 2007 - RaX - Created Header; // [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide. // May 1st, 2007 - Tsusai - Added const to the parameters of almost all // routines // [2007/10/25] Aeomin - major clean up #1 // June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength // in various calls // //------------------------------------------------------------------------------ unit ZoneSend; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} Classes, Types, {Project} GameObject, Being, GameTypes, Character, PacketTypes, Mailbox, Inventory, Item, ItemInstance, ChatRoom, {Third Party} IdContext ; procedure SendCharID( const Who:TCharacter ); procedure DuplicateSessionKick( InBuffer : TBuffer ); procedure Kick( const Who:TCharacter ); procedure KickAll; procedure SendAreaChat( const Chat : String; const Length : Word; const ACharacter : TCharacter ); procedure SendCharacterSelectResponse( const ACharacter : TCharacter ); procedure SendGMAnnounce( AClient : TIdContext; const Announce:String; const Blue:boolean=False ); procedure SendGMAnnounceColor( AClient : TIdContext; const Announce:String; Color:Integer ); procedure SendQuitGameResponse( const ACharacter : TCharacter ); procedure SendStatUPResult( const AChara:TCharacter; const Failed:Boolean; const Amount:Byte ); procedure SendDeleteFriend( AClient : TIdContext; const AccID : LongWord; const CharID : LongWord ); procedure SendWhisper( const FromName,Whisper: String; AClient : TIdContext ); procedure SendWhisperReply( const AChara:TCharacter; const Code : Byte ); procedure SendSpecialEffect( const Who:TBeing; AClient : TIdContext; const BeingID:LongWord; const EffectID : LongWord ); procedure SendEmotion( const ID:LongWord; AClient : TIdContext; const EmotionID : Byte ); procedure ZoneDisappearBeing( const Who:TBeing; AClient : TIdContext; const Effect:Byte=0; const BeingID : LongWord=0 ); procedure ZoneSendBeing( const Who:TBeing; const AClient : TCharacter; const Spawn:Boolean=False ); procedure ZoneSendCharacterMessage( const ACharacter : TCharacter; const AMessage : String ); procedure ZoneSendConnectionsCount( AClient : TIdContext ); procedure ZoneSendMapConnectReply( const ACharacter : TCharacter ); procedure ZoneSendMapConnectDeny( AClient : TIdContext ); procedure ZoneSendObjectNameAndIDBasic( Const ACharacter : TCharacter; const ID : LongWord; const Name : String ); procedure ZoneSendTickToClient( const ACharacter : TCharacter ); procedure ZoneSendWalkReply( const ACharacter : TCharacter; const DestPoint : TPoint ); function ZoneSendWarp( const ACharacter : TCharacter; MapName : String; const X : Word; const Y : Word ):Boolean; procedure ZoneWalkingBeing( const Who:TBeing; const Source,Dest:TPoint; AClient : TIdContext ); procedure ZoneUpdateDirection( const Who:TBeing; AClient : TIdContext ); procedure SendAddFriendRequest( AClient : TIdContext; const ReqAID, ReqID : LongWord; const ReqName : String ); procedure SendAddFriendRequestReply( AClient : TIdContext; const AccID : LongWord; const CharID : LongWord; const CharName : String; const Reply : Byte ); procedure SendFirendOnlineStatus( AClient : TIdContext; const AID : LongWord; const CID : LongWord; const Offline : Byte ); procedure DoAction( AClient : TIdContext; SourceID : LongWord; TargetID : LongWord; SourceSpeed : LongWord; TargetSpeed : LongWord; ActionType : Byte; Parameter1 : Word; Parameter2 : Word; Parameter3 : Word ); procedure SendCompass( AClient : TIdContext; const NPCID : LongWord; const PointID : Byte; const X : LongWord; const Y : LongWord; const PointType : LongWord; const Color : LongWord ); procedure SendCutin( AClient : TIdContext; const Image : String; const ImageType : Byte ); procedure ToggleMailWindow( const AChara : TCharacter; const Open : Boolean ); procedure SendMailList( const AChara : TCharacter ); procedure SendMailContent( AClient : TIdContext; const Mail : TMail ); procedure SendDeleteMailResult( const AChara : TCharacter; const MailID:LongWord; const Flag : Boolean ); procedure SendMailResult( const AChara : TCharacter; const Fail :Boolean ); procedure SendNewMailNotify( const AChara : TCharacter; const MailID : LongWord; const Sender : String; const Title : String ); procedure SendInventory( AClient : TIdContext; const AInventory : TInventory ); procedure SendNewItem( AClient : TIdContext; const AInventory : TItemInstance; const Index : Word; const Amount : Word ); procedure SendNewItemFailed( AClient : TIdContext; const Flag : Byte ); procedure SendStatusIcon( const AChara : TCharacter; const IconID : Word; const Active : Boolean ); procedure SendUpdatedLook( const AChara : TCharacter; const CharacterID : LongWord; const AType : TLookTypes; const Value1 : Word; const Value2 : Word ); procedure SendEncryptKeys( AClient : TIdContext; const Key1,Key2 : LongWord ); procedure SendDropItem( const AChara : TCharacter; const AnItem : TItemInstance; const AQuantity : Word ); procedure SendDeleteItem( const AChara : TCharacter; const Index : Word; const Quantity : Word ); procedure SendGroundItem( const AChara : TCharacter; const AnItem : TItemInstance ); procedure SendRemoveGroundItem( const AChara : TCharacter; const ID : LongWord ); procedure SendPickUpItemAnimation( const AChara : TCharacter; const CharID : LongWord; const ItemID : LongWord ); procedure SendEquipItemResult( const AChara : TCharacter; const Index : Word; const Location:Word; const Success:Boolean ); procedure SendUnequipItemResult( const AChara : TCharacter; const Index : Word; const Location:Word; const Success:Boolean ); procedure SendNPCDialog( const AChara : TCharacter; const NPCID : LongWord; const NPCMessage : string ); procedure SendNPCNext( const AChara : TCharacter; const NPCID : LongWord ); procedure SendNPCClose( const AChara : TCharacter; const NPCID : LongWord ); procedure SendNPCMenu( const AChara : TCharacter; const NPCID : LongWord; const MenuString : string ); procedure SendNPCInput( const AChara : TCharacter; const NPCID : LongWord ); procedure SendNPCInputStr( const AChara : TCharacter; const NPCID : LongWord ); procedure SendSkillGroundUnit( const AChara : TCharacter; const ID : LongWord; const SrcID : LongWord; const X,Y: Word; const SkillType: Byte ); procedure SendCreateChatRoomResult( const AChara : TCharacter; const Fail : Boolean ); procedure DisplayChatroomBar( const AChara : TCharacter; const ChatRoom : TChatRoom ); procedure SendQuitChat( const AChara : TCharacter; const Name : String; const Count : Word; const Kicked : Boolean ); procedure SendClearChat( const AChara : TCharacter; const ChatRoom : TChatRoom ); procedure SendChangeChatOwner( const AChara : TCharacter; const OldOwner : String; const NewOwner : String ); procedure SendJoinChatFailed( const AChara : TCharacter; const Flag : Byte ); procedure SendJoinChatOK( const AChara : TCharacter; const AChatRoom : TChatRoom ); procedure SendNotifyJoinChat( const AChara : TCharacter; const NewUsers : Word; const Name : String ); procedure UpdateChatroom( const AChara : TCharacter; const Chatroom : TChatRoom ); implementation uses {RTL/VCL} Math, SysUtils, {Project} BufferIO, GameConstants, Globals, Main, ItemTypes, UseableItem, EquipmentItem, MiscItem, NPC, TCPServerRoutines, WinLinux {3rd Party} //none ; //------------------------------------------------------------------------------ //SendCharID PROCEDURE //------------------------------------------------------------------------------ // What it does - // Old client uses padding, this is for new client, which send // right after zone auth. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/0608] Aeomin - Created //------------------------------------------------------------------------------ procedure SendCharID( const Who:TCharacter ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0283, OutBuffer); WriteBufferLongWord(2, Who.ID, OutBuffer); SendBuffer(Who.ClientInfo,OutBuffer,PacketDB.GetLength($0283,Who.ClientVersion)); end;{SendCharID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DuplicateSessionKick PROCEDURE //------------------------------------------------------------------------------ // What it does - // Show "Someone has already logged in with this ID" and DC. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // April 12th, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure DuplicateSessionKick( InBuffer : TBuffer ); var OutBuffer : TBuffer; CharID : LongWord; Idx : Integer; Chara : TCharacter; begin CharID := BufferReadLongWord(2,InBuffer); Idx := MainProc.ZoneServer.CharacterList.IndexOf(CharID); if Idx > -1 then begin Chara := MainProc.ZoneServer.CharacterList[Idx] as TCharacter; WriteBufferWord(0, $0081, OutBuffer); WriteBufferByte(2, 2, OutBuffer); SendBuffer(Chara.ClientInfo,OutBuffer,PacketDB.GetLength($0081)); Chara.DelayDisconnect(10000); end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Kick PROCEDURE //------------------------------------------------------------------------------ // What it does - // Kick one player //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 27th, 2007 - Aeomin - Created Header // April 5th, 2007 - Aeomin - Added DelayDisconnect to kill connect if still there. //------------------------------------------------------------------------------ procedure Kick( const Who:TCharacter ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $018B, OutBuffer); WriteBufferWord(2, 0, OutBuffer); SendBuffer(Who.ClientInfo,OutBuffer,PacketDB.GetLength($018B,Who.ClientVersion)); Who.DelayDisconnect(GetTick + 10000); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //KickAll PROCEDURE //------------------------------------------------------------------------------ // What it does - // Kick all players in current zone server //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 27th, 2007 - Aeomin - Created Header // March 29th, 2007 - Tsusai - Reversed loop to prevent Index out of Bounds. //------------------------------------------------------------------------------ procedure KickAll; var Idx : Integer; Chara : TCharacter; begin for Idx := MainProc.ZoneServer.CharacterList.Count-1 downto 0 do begin if MainProc.ZoneServer.CharacterList.Count > Idx then begin Chara := MainProc.ZoneServer.CharacterList[Idx] as TCharacter; Kick(Chara); end; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendAreaChat PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send chat message to local area //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - Aeomin - Created // May 1st, 2007 - Tsusai - Added const to the parameters // May 25th, 2007 - Tsusai - Removed ABeing, changed to // APerson, and added TCharacter conditionals // [2008/06/08] Aeomin - Updated packet structure //------------------------------------------------------------------------------ procedure SendAreaChat( const Chat : String; const Length : Word; const ACharacter : TCharacter ); var OutBuffer : TBuffer; APerson : TCharacter; idxY : SmallInt; idxX : SmallInt; BeingIdx : integer; begin if Assigned(ACharacter.ChatRoom) then begin for BeingIdx := 0 to ACharacter.ChatRoom.Characters.Count - 1 do begin APerson := ACharacter.ChatRoom.Characters.Items[BeingIdx] as TCharacter; if APerson = ACharacter then begin ZoneSendCharacterMessage(ACharacter, Chat); end else begin WriteBufferWord(0, $008d, OutBuffer); WriteBufferWord(2, Length+9, OutBuffer); WriteBufferLongWord(4, ACharacter.ID, OutBuffer); WriteBufferString(8, Chat+#0, Length+1, OutBuffer); Sendbuffer(APerson.ClientInfo, OutBuffer, Length+9); end; end; end else begin //16 covers the old 15x15 grid for idxY := Max(ACharacter.Position.Y-MainProc.ZoneServer.Options.CharShowArea,0) to Min(ACharacter.Position.Y+MainProc.ZoneServer.Options.CharShowArea,ACharacter.MapInfo.Size.Y - 1) do begin for idxX := Max(ACharacter.Position.X-MainProc.ZoneServer.Options.CharShowArea,0) to Min(ACharacter.Position.X+MainProc.ZoneServer.Options.CharShowArea,ACharacter.MapInfo.Size.X - 1) do begin for BeingIdx := ACharacter.MapInfo.Cell[idxX,idxY].Beings.Count - 1 downto 0 do begin if not (ACharacter.MapInfo.Cell[idxX,idxY].Beings.Objects[BeingIdx] is TCharacter) then begin Continue; end; APerson := ACharacter.MapInfo.Cell[idxX,idxY].Beings.Objects[BeingIdx] as TCharacter; if APerson = ACharacter then begin ZoneSendCharacterMessage(ACharacter, Chat); end else begin if NOT Assigned(APerson.ChatRoom) then begin WriteBufferWord(0, $008d, OutBuffer); WriteBufferWord(2, Length+9, OutBuffer); WriteBufferLongWord(4, ACharacter.ID, OutBuffer); WriteBufferString(8, Chat+#0, Length+1, OutBuffer); Sendbuffer(APerson.ClientInfo, OutBuffer, Length+9); end; end; end; end; end; end; end;{SendAreaChat} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCharacterSelectResponse PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tells the client to return to character select. Triggered by ZoneRecv -> // ReturnToCharacterSelect. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 17th, 2007 - RaX - Created; // April 10th, 2007 - Aeomin - Add DelayDisconnect // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure SendCharacterSelectResponse( const ACharacter : TCharacter ); var OutBuffer : TBuffer; begin ACharacter.DcAndKeepData := True; //send leave 2 WriteBufferWord(0, $00b3,OutBuffer); WriteBufferByte(2, 1,OutBuffer); SendBuffer(ACharacter.ClientInfo, OutBuffer, PacketDB.GetLength($00b3,ACharacter.ClientVersion)); ACharacter.DelayDisconnect(10000); end;//SendCharacterSelectResponse //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendGMAnnounce PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a GM announcement =p //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/08/09] Aeomin - Created. // //------------------------------------------------------------------------------ procedure SendGMAnnounce( AClient : TIdContext; const Announce:String; const Blue:boolean=False ); var OutBuffer : TBuffer; Size : Word; OffSet : Byte; begin Size := StrLen(PChar(Announce)); if Blue then Offset := 8 else Offset := 4; WriteBufferWord(0, $009a, OutBuffer); WriteBufferWord(2, Size + Offset, OutBuffer); if Blue then WriteBufferLongWord(4, $65756c62, OutBuffer); WriteBufferString(Offset, Announce, Size, OutBuffer); SendBuffer(AClient, OutBuffer, Size + Offset); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendGMAnnounceColor PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a GM announcement in color. // Should probably combine with SendGMAnnounce later. // // Changes - // [2007/11/12] RabidChocobo - Created. // //------------------------------------------------------------------------------ procedure SendGMAnnounceColor( AClient : TIdContext; const Announce : String; Color : Integer ); var OutBuffer : TBuffer; Size : Word; OffSet : Byte; begin Size := StrLen(PChar(Announce)) + 1; Offset := 16; WriteBufferWord(0, $01c3, OutBuffer); WriteBufferWord(2, Size + Offset, OutBuffer); WriteBufferLongWord(4, Color, OutBuffer); WriteBufferWord(8, $0190, OutBuffer); WriteBufferWord(10, $000c, OutBuffer); WriteBufferLongWord(12, 0, OutBuffer); WriteBufferString(Offset, Announce, Size, OutBuffer); SendBuffer(AClient, OutBuffer, Offset + Size); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendQuitGameResponse PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tells the client to "Exit to windows". Triggered by ZoneRecv -> // QuitGame. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 17th, 2007 - RaX - Created; // April 10th, 2007 - Aeomin - Add DelayDisconnect // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure SendQuitGameResponse( const ACharacter : TCharacter ); var OutBuffer : TBuffer; begin //ACharacter.DcAndKeepData := False; //send leave 2 WriteBufferWord(0, $018b, OutBuffer); WriteBufferWord(2, 0, OutBuffer); Sendbuffer(ACharacter.ClientInfo, OutBuffer, PacketDB.GetLength($018b, ACharacter.ClientVersion)); ACharacter.DelayDisconnect(GetTick + 10000); end;{SendQuitGameResponse} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendStatUPResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell client if stat up was success or not //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/08/20] Aeomin - Created. // //------------------------------------------------------------------------------ procedure SendStatUPResult( const AChara:TCharacter; const Failed:Boolean; const Amount:Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00bc, OutBuffer); if Failed then WriteBufferByte(2, 0, OutBuffer) else WriteBufferByte(2, 1, OutBuffer); WriteBufferByte(3, Amount, OutBuffer); SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($00bc)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendDeleteFriend PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell client to delete a friend from friend list. //-- // Pre: // Post: // TODO //-- // Changes - // [2007/12/06] Aeomin - Created. // //------------------------------------------------------------------------------ procedure SendDeleteFriend( AClient : TIdContext; const AccID : LongWord; const CharID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $020a, OutBuffer); WriteBufferLongWord(2, AccID, OutBuffer); WriteBufferLongWord(6, CharID, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($020a)); end;{SendDeleteFriend} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendWhisper PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send whisper to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/10/25] Aeomin - Added header // //------------------------------------------------------------------------------ procedure SendWhisper( const FromName,Whisper: String; AClient : TIdContext ); var OutBuffer : TBuffer; Len : Integer; begin Len := StrLen(PChar(Whisper)); WriteBufferWord(0, $0097, OutBuffer); WriteBufferWord(2, Len + 29, OutBuffer); WriteBufferString(4, FromName, 24, OutBuffer); WriteBufferString(28, Whisper, Len + 1, OutBuffer); SendBuffer(AClient,OutBuffer, Len + 29); end;{SendWhisper} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendWhisperReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send whisper status to client (success or fail) //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/10/25] Aeomin - Added header // //------------------------------------------------------------------------------ procedure SendWhisperReply( const AChara:TCharacter; const Code : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0098, OutBuffer); WriteBufferByte(2, Code, OutBuffer); SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($0098)); end;{SendWhisperReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendSpecialEffect PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send effect packet // // Changes- // [2007/11/24] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendSpecialEffect( const Who:TBeing; AClient : TIdContext; const BeingID:LongWord; const EffectID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $01f3, OutBuffer); WriteBufferLongWord(2, BeingID, OutBuffer); WriteBufferLongWord(6, EffectID, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($01f3)); end;{SendSpecialEffec} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendEmotion PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send emotion packet // // Changes- // [2007/11/24] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendEmotion( const ID:LongWord; AClient : TIdContext; const EmotionID : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00c0, OutBuffer); WriteBufferLongWord(2, ID, OutBuffer); WriteBufferByte(6, EmotionID, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($00c0)); end;{SendEmotion} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneDisappearBeing PROCEDURE //------------------------------------------------------------------------------ // What it does - // Make character disappear //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - Aeomin - Created Header // March 23th, 2007 - Aeomin - Renamed from ZoneWalkingChar to ZoneWalkingBeing // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneDisappearBeing( const Who:TBeing; AClient : TIdContext; const Effect:Byte=0; const BeingID : LongWord=0 ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $0080, ReplyBuffer); if BeingID >0 then WriteBufferLongWord(2, BeingID, ReplyBuffer) else WriteBufferLongWord(2, Who.ID, ReplyBuffer); WriteBufferByte(6, Effect, ReplyBuffer); SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($0080)); end;{ZoneDisappearBeing} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendBeing PROCEDURE //------------------------------------------------------------------------------ // What it does - // make character visible //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - Aeomin - Created Header // March 23th, 2007 - Aeomin - Renamed from ZoneSendChar to ZoneSendBeing // and support for Npc/Mob etc // May 1st, 2007 - Tsusai - Added const to the parameters // May 25th, 2007 - Tsusai - Invisible npcs aren't sent // [2008/06/08] Aeomin - Redo! //------------------------------------------------------------------------------ procedure ZoneSendBeing( const Who:TBeing; const AClient : TCharacter; const Spawn:Boolean=False ); var ReplyBuffer : TBuffer; Chara : TCharacter; procedure SubSendPlayer; begin if Spawn then begin WriteBufferWord(0, $022b, ReplyBuffer); end else begin WriteBufferWord(0, $022a, ReplyBuffer); end; WriteBufferLongWord(2, Who.ID, ReplyBuffer); WriteBufferWord(6, Who.Speed, ReplyBuffer); WriteBufferWord(8, Who.Status, ReplyBuffer); WriteBufferWord(10, Who.Ailments, ReplyBuffer); WriteBufferWord(12, Who.Option, ReplyBuffer); {2 bytes shiftload} WriteBufferWord(16, Who.JID, ReplyBuffer); WriteBufferWord(34, Who.Direction, ReplyBuffer); Chara:=TCharacter(Who); {Todo: Hair stlye, head bottom needed for Pet...} WriteBufferWord(18, Chara.Hair, ReplyBuffer); WriteBufferWord(20, Chara.Equipment.EquipmentID[RIGHTHAND], ReplyBuffer); //Weapon WriteBufferWord(22, Chara.Equipment.EquipmentID[LEFTHAND], ReplyBuffer); //Shield WriteBufferWord(24, Chara.Equipment.EquipmentID[HEADLOWER], ReplyBuffer); //Head bottom WriteBufferWord(26, Chara.Equipment.EquipmentID[HEADUPPER], ReplyBuffer); //Head top WriteBufferWord(28, Chara.Equipment.EquipmentID[HEADMID], ReplyBuffer); //head mid WriteBufferWord(30, Chara.HairColor, ReplyBuffer); WriteBufferWord(32, Chara.ClothesColor, ReplyBuffer); WriteBufferWord(34, Chara.HeadDirection, ReplyBuffer); WriteBufferLongWord(36, Chara.GuildID, ReplyBuffer); WriteBufferWord(40, 0, ReplyBuffer); //Emblem ID WriteBufferWord(42, 0, ReplyBuffer); //Manner WriteBufferLongWord(44, 0, ReplyBuffer); //opt3? {2 more shiftload} WriteBufferByte(48, Chara.Karma, ReplyBuffer); WriteBufferByte(49, TClientLink(Chara.ClientInfo.Data).AccountLink.GenderNum, ReplyBuffer); //WriteBufferByte(44, 0, ReplyBuffer); //Normal/Ready to fight WriteBufferPointAndDirection(50, Who.Position, ReplyBuffer,Who.Direction); WriteBufferByte(53, 5, ReplyBuffer); WriteBufferByte(54, 5, ReplyBuffer); if Spawn then begin WriteBufferWord(55, Who.BaseLV, ReplyBuffer); SendBuffer(AClient.ClientInfo,ReplyBuffer,PacketDB.GetLength($022b,AClient.ClientVersion)); end else begin WriteBufferByte(55, 0, ReplyBuffer); //Standing/Dead/Sit WriteBufferWord(56, Who.BaseLV, ReplyBuffer); SendBuffer(AClient.ClientInfo,ReplyBuffer,PacketDB.GetLength($022a,AClient.ClientVersion)); end; end; procedure SubSendNPC; begin FillChar(ReplyBuffer,PacketDB.GetLength($0078),0); WriteBufferWord(0, $0078, ReplyBuffer); WriteBufferByte(2, 0, ReplyBuffer); WriteBufferLongWord(3, Who.ID, ReplyBuffer); WriteBufferWord(7, Who.Speed, ReplyBuffer); WriteBufferWord(9, 0, ReplyBuffer); //bstate? WriteBufferWord(11, 0, ReplyBuffer);//hstate? WriteBufferWord(13, Who.Option, ReplyBuffer); WriteBufferWord(15, Who.JID, ReplyBuffer); WriteBufferWord(17, 0, ReplyBuffer); //hair_style WriteBufferWord(19, 0, ReplyBuffer); //Weapon WriteBufferWord(21, 0, ReplyBuffer); //Shield WriteBufferWord(23, 0, ReplyBuffer); //headbottom WriteBufferPointAndDirection(47, Who.Position, ReplyBuffer,Who.Direction); WriteBufferByte(50, 5, ReplyBuffer); WriteBufferByte(51, 5, ReplyBuffer); SendBuffer(AClient.ClientInfo,ReplyBuffer,PacketDB.GetLength($0078,AClient.ClientVersion)); end; procedure SubSendMob; begin FillChar(ReplyBuffer,PacketDB.GetLength($007c),0); WriteBufferWord(0, $007c, ReplyBuffer); WriteBufferByte(2, 0, ReplyBuffer); WriteBufferLongWord(3, Who.ID, ReplyBuffer); WriteBufferWord(7, Who.Speed, ReplyBuffer); WriteBufferWord(9, 0, ReplyBuffer); //bstate? WriteBufferWord(11, 0, ReplyBuffer);//hstate? WriteBufferWord(13, Who.Option, ReplyBuffer); WriteBufferWord(21, Who.JID, ReplyBuffer); WriteBufferWord(17, 0, ReplyBuffer); //hair_style WriteBufferWord(19, 0, ReplyBuffer); //Weapon // WriteBufferWord(21, 0, ReplyBuffer); //Shield // WriteBufferLongWord(23, 0, ReplyBuffer);//emblem ID // WriteBufferLongWord(27, 0, ReplyBuffer); //Guild id WriteBufferPointAndDirection(37, Who.Position, ReplyBuffer,Who.Direction); WriteBufferByte(50, 5, ReplyBuffer); WriteBufferByte(51, 5, ReplyBuffer); WriteBufferWord(53, 99, ReplyBuffer); //Level SendBuffer(AClient.ClientInfo,ReplyBuffer,PacketDB.GetLength($007c,AClient.ClientVersion)); end; begin if Who.JID = NPC_INVISIBLE then begin Exit; end; //Old Packet Version // FillChar(ReplyBuffer,54,0); if Who is TCharacter then SubSendPlayer else if Who is TNPC then SubSendNPC else SubSendMob; end;{ZoneSendBeing} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendGMCommandResultToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the received gm command to the inter server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 19th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendCharacterMessage( const ACharacter : TCharacter; const AMessage : String ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $008e, OutBuffer); WriteBufferWord(2, Length(AMessage)+5, OutBuffer); WriteBufferString(4, AMessage+#0, Length(AMessage)+1, OutBuffer); Sendbuffer(ACharacter.ClientInfo, OutBuffer, Length(AMessage)+5); end;{ZoneSendCharacterMessage} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendConnectionsCount PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send total online count to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // April 6th, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure ZoneSendConnectionsCount( AClient : TIdContext ); var ReplyBuffer : TBuffer; begin FillChar(ReplyBuffer,PacketDB.GetLength($00C2),0); WriteBufferWord(0, $00C2, ReplyBuffer); WriteBufferLongWord(2, MainProc.ZoneServer.TotalOnlinePlayers, ReplyBuffer); SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($00C2)); end;{ZoneSendConnectionsCount} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendMapConnectReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Replies to a clients map connect request, sends the clients position and // direction. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // January 18th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendMapConnectReply( const ACharacter : TCharacter ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $0073, ReplyBuffer); WriteBufferLongWord(2, GetTick, ReplyBuffer); WriteBufferPointAndDirection(6, ACharacter.Position,ReplyBuffer,ACharacter.Direction); WriteBufferByte(9, 5, ReplyBuffer); WriteBufferByte(10, 5, ReplyBuffer); SendBuffer(ACharacter.ClientInfo,ReplyBuffer,PacketDB.GetLength($0073,ACharacter.ClientVersion)); end;{ZoneSendMapConnectReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendMapConnectDeny PROCEDURE //------------------------------------------------------------------------------ // What it does - // Denys a client access to the map server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // January 18th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendMapConnectDeny( AClient : TIdContext ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $0074, ReplyBuffer); WriteBufferByte(2, 0 , ReplyBuffer); SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($0074)); end;{ZoneSendMapConnectReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendObjectNameAndIDBasic PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a characters name and ID to the client. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // January 18th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendObjectNameAndIDBasic( const ACharacter : TCharacter; const ID : LongWord; const Name : String ); var OutBuffer : TBuffer; begin WriteBufferWord (0, $0095, OutBuffer); WriteBufferLongWord(2, ID, OutBuffer); WriteBufferString (6, Name, 24, OutBuffer); SendBuffer(ACharacter.ClientInfo, OutBuffer, PacketDB.GetLength($0095,ACharacter.ClientVersion)); end;{ZoneSendObjectNameAndIDBasic} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendTickToClient PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a ping or "tick" to the client to make sure that it's still there. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // January 18th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendTickToClient( const ACharacter : TCharacter ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $007f, ReplyBuffer); WriteBufferLongWord(2, GetTick, ReplyBuffer); SendBuffer(ACharacter.ClientInfo, ReplyBuffer, PacketDB.GetLength($007f,ACharacter.ClientVersion)); end;{ZoneSendTickToClient} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendWalkReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a packet that tells the client to go ahead and walk. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // February 27th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters // Halloween 2008 - Tsusai - Updated WriteBufferTwoPoints settings //------------------------------------------------------------------------------ procedure ZoneSendWalkReply( const ACharacter : TCharacter; const DestPoint : TPoint ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $0087, ReplyBuffer); WriteBufferLongWord(2, ACharacter.MoveTick, ReplyBuffer); WriteBufferTwoPoints( 6, ACharacter.Position, DestPoint, ReplyBuffer); WriteBufferByte(11, 0, ReplyBuffer); SendBuffer(ACharacter.ClientInfo, ReplyBuffer, PacketDB.GetLength($0087, ACharacter.ClientVersion)); end;{ZoneSendWalkReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendWarp PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a request to the inter server that asks if it's ok for a character // to warp to the specified zone, or warp them within // the current zone. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // April 26th, 2007 - RaX - Created. // May 1st, 2007 - Tsusai - Renamed, and modified parameters recieved. // May 25th, 2007 - Tsusai - Removes player from current cell //------------------------------------------------------------------------------ function ZoneSendWarp( const ACharacter : TCharacter; MapName : String; const X : Word; const Y : Word ):boolean; var OutBuffer : TBuffer; Size : Word; MapNameSize : Word; ClientIPSize : Word; MapZoneID : SmallInt; IsInstance : Boolean; begin IsInstance := False; if Pos('#', MapName) > 0 then begin if MainProc.ZoneServer.MapList.IndexOf(MapName) > -1 then begin MapZoneID := MainProc.ZoneServer.Options.ID; IsInstance := True; end else begin MapZoneID := TThreadLink(ACharacter.ClientInfo.Data).DatabaseLink.Map.GetZoneID(MapName); end; end else begin MapZoneID := TThreadLink(ACharacter.ClientInfo.Data).DatabaseLink.Map.GetZoneID(MapName); end; if MapZoneID < 0 then begin Result := False; end else begin ACharacter.EventList.DeleteMovementEvents; if Cardinal(MapZoneID) = MainProc.ZoneServer.Options.ID then begin ACharacter.RemoveFromMap; ACharacter.ShowTeleportOut; ACharacter.ZoneStatus := isOffline; ACharacter.Map := MapName; ACharacter.Position := Point(X,Y); WriteBufferWord(0, $0091, OutBuffer); if IsInstance then Delete(MapName,1, Pos('#', MapName)); WriteBufferString(2, MapName+'.rsw', 16, OutBuffer); WriteBufferWord(18, X, OutBuffer); WriteBufferWord(20, Y, OutBuffer); SendBuffer(ACharacter.ClientInfo, OutBuffer, 22); end else begin MapNameSize := Length(MapName); ClientIPSize := Length(ACharacter.ClientInfo.Binding.PeerIP); Size := ClientIPSize + MapNameSize + 16; //<id>,<size>,<cid>,<mapnamesize>,<mapname>,<clientipsize>,<clientip> WriteBufferWord(0, $2208, OutBuffer); WriteBufferWord(2, Size, OutBuffer); WriteBufferLongWord(4, ACharacter.ID, OutBuffer); WriteBufferWord(8, X, OutBuffer); WriteBufferWord(10, Y, OutBuffer); WriteBufferWord(12, MapNameSize, OutBuffer); WriteBufferString(14, MapName, Length(MapName), OutBuffer); WriteBufferWord(14+MapNameSize, ClientIPSize, OutBuffer); WriteBufferString( 16+MapNameSize, ACharacter.ClientInfo.Binding.PeerIP, Length(ACharacter.ClientInfo.Binding.PeerIP), OutBuffer ); SendBuffer(MainProc.ZoneServer.ToInterTCPClient,OutBuffer,Size); end; Result := True; end; end;{ZoneSendWarp} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneWalkingBeing PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send the destination of charater. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - Aeomin - Created Header // March 23th, 2007 - Aeomin - Renamed from ZoneWalkingChar to ZoneWalkingBeing // May 1st, 2007 - Tsusai - Added const to the parameters // Halloween 2008 - Tsusai - Updated WriteBufferTwoPoints settings //------------------------------------------------------------------------------ procedure ZoneWalkingBeing( const Who:TBeing; const Source,Dest:TPoint; AClient : TIdContext ); var ReplyBuffer : TBuffer; begin FillChar(ReplyBuffer,PacketDB.GetLength($0086),0); WriteBufferWord(0, $0086, ReplyBuffer); WriteBufferLongWord(2, Who.ID, ReplyBuffer); WriteBufferTwoPoints(6, Source, Dest, ReplyBuffer); WriteBufferLongWord(12, GetTick, ReplyBuffer); SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($0086)); end;{ZoneWalkingBeing} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneUpdateDirection PROCEDURE //------------------------------------------------------------------------------ // What it does - // Update Character Direction to other characters //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 20th, 2007 - Aeomin - Created Header // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneUpdateDirection( Const Who:TBeing; AClient : TIdContext ); var ReplyBuffer : TBuffer; begin WriteBufferWord(0, $009c, ReplyBuffer); WriteBufferLongWord(2, Who.ID, ReplyBuffer); WriteBufferWord(6, Who.HeadDirection, ReplyBuffer); WriteBufferByte(8, Who.Direction, ReplyBuffer); SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($009c)); end;{ZoneUpdateDirection} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendAddFriendRequest PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send client request... //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/07] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendAddFriendRequest( AClient : TIdContext; const ReqAID, ReqID : LongWord; const ReqName : String ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0207, OutBuffer); WriteBufferLongWord(2, ReqAID, OutBuffer); WriteBufferLongWord(6, ReqID, OutBuffer); WriteBufferString(10, ReqName, NAME_LENGTH, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($0207)); end;{ZoneSendAddFriendRequest} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendAddFriendRequestReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send reply to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/08] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendAddFriendRequestReply( AClient : TIdContext; const AccID : LongWord; const CharID : LongWord; const CharName : String; const Reply : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0209, OutBuffer); WriteBufferWord(2, Reply, OutBuffer); WriteBufferLongWord(4, AccID, OutBuffer); WriteBufferLongWord(8, CharID, OutBuffer); WriteBufferString(12, CharName, NAME_LENGTH, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($0209)); end;{SendAddFriendRequestReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendFirendOnlineStatus PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send online status of a friend to client. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/??] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendFirendOnlineStatus( AClient : TIdContext; const AID : LongWord; const CID : LongWord; const Offline : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0206, OutBuffer); WriteBufferLongWord(2, AID, OutBuffer); WriteBufferLongWord(6, CID, OutBuffer); WriteBufferByte(10, Offline, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($0206)); end;{SendFirendOnlineStatus} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DoAction PROCEDURE //------------------------------------------------------------------------------ // What it does - // tells a client to show an action made by another entity or itself. // SEE TACTIONTYPE FOR A LIST OF ACTIONS. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/24] RaX - Created. //------------------------------------------------------------------------------ procedure DoAction( AClient : TIdContext; SourceID : LongWord; TargetID : LongWord; SourceSpeed : LongWord; TargetSpeed : LongWord; ActionType : Byte; Parameter1 : Word; Parameter2 : Word; Parameter3 : Word ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $008a, OutBuffer); WriteBufferLongWord(2, SourceID, OutBuffer); WriteBufferLongWord(6, TargetID, OutBuffer); WriteBufferLongWord(10, GetTick(), OutBuffer); WriteBufferLongWord(14, SourceSpeed, OutBuffer); WriteBufferLongWord(18, TargetSpeed, OutBuffer); WriteBufferWord(22, Parameter1, OutBuffer); WriteBufferWord(24, Parameter2, OutBuffer); WriteBufferByte(26, ActionType, OutBuffer); WriteBufferWord(27, Parameter3, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($008a)); end;{DoAction} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCompass PROCEDURE //------------------------------------------------------------------------------ // What it does - // Add/Remove "+" mark in mini map //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/31] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendCompass( AClient : TIdContext; const NPCID : LongWord; const PointID : Byte; const X : LongWord; const Y : LongWord; const PointType : LongWord; const Color : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0144, OutBuffer); WriteBufferLongWord(2, NPCID, OutBuffer); WriteBufferLongWord(6, PointType, OutBuffer); WriteBufferLongWord(10, X, OutBuffer); WriteBufferLongWord(14, Y, OutBuffer); WriteBufferByte(18, PointID, OutBuffer); WriteBufferLongWord(19, Color, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($0144)); end;{SendCompass} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCutin PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send cutin thingy to client. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/31] Aeomin - Created. //------------------------------------------------------------------------------ procedure SendCutin( AClient : TIdContext; const Image : String; const ImageType : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $01b3, OutBuffer); WriteBufferString(2, Image, 64, OutBuffer); WriteBufferByte(66, ImageType, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($01b3)); end;{SendCutin} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ToggleMailWindow PROCEDURE //------------------------------------------------------------------------------ // What it does - // Open/Close mail window on client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/06/11] Aeomin - Created. //------------------------------------------------------------------------------ procedure ToggleMailWindow( const AChara : TCharacter; const Open : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0260, OutBuffer); WriteBufferLongWord(2, Byte(not Open), OutBuffer); {TODO:Packet version...} SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($0260,AChara.ClientVersion)); end;{ToggleMailWindow} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendMailList PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send a list of mails //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/06/12] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendMailList( const AChara : TCharacter ); var Index : Integer; Mail : TMail; OutBuffer : TBuffer; Len : Word; begin {This procedure will check if load from database was needed} AChara.Mails.LoadMails; if AChara.Mails.Mails > 0 then begin Len := (73*AChara.Mails.Mails) + 8; WriteBufferWord(0, $0240, OutBuffer); WriteBufferWord(2, Len, OutBuffer); WriteBufferLongWord(4, AChara.Mails.Mails, OutBuffer); for Index := 0 to AChara.Mails.Mails - 1 do begin Mail := AChara.Mails.Item[Index]; WriteBufferLongWord(73*Index+8, Mail.ID, OutBuffer); WriteBufferString(73*Index+12, Mail.Title, 40, OutBuffer); WriteBufferByte(73*Index+52, Byte(Mail.Read), OutBuffer); WriteBufferString(73*Index+53, Mail.SenderName, NAME_LENGTH, OutBuffer); WriteBufferLongWord(73*Index+77, Mail.SendTime, OutBuffer); end; SendBuffer(AChara.ClientInfo,OutBuffer,Len); end; end;{SendMailList} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendMailContent PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send a mail //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/06/12] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendMailContent( AClient : TIdContext; const Mail : TMail ); var MessageLen : Byte; Len : Word; OutBuffer : TBuffer; begin MessageLen := Length(Mail.Content); Len := MessageLen + 101; WriteBufferWord(0, $0242, OutBuffer); WriteBufferWord(2, Len, OutBuffer); WriteBufferLongWord(4, Mail.ID, OutBuffer); WriteBufferString(8, Mail.Title, 40, OutBuffer); WriteBufferString(48, Mail.SenderName, NAME_LENGTH, OutBuffer); WriteBufferLongWord(72, 0, OutBuffer);{??} WriteBufferLongWord(76, 0, OutBuffer);{Zeny} FillChar(OutBuffer[80],19,$0); {No item support yet} WriteBufferByte(99, MessageLen, OutBuffer); WriteBufferString(100, Mail.Content, MessageLen, OutBuffer); SendBuffer(AClient,OutBuffer,Len); end;{SendMailContent} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendDeleteMailResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send result of delete mail. // Packet size still need improve -.-" //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/08/09] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendDeleteMailResult( const AChara : TCharacter; const MailID:LongWord; const Flag : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0257, OutBuffer); WriteBufferLongWord(2, MailID, OutBuffer); WriteBufferWord(6, Byte(NOT Flag), OutBuffer); SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($0257,AChara.ClientVersion)); end;{SendDeleteMailResult} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendMailResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Is sending mail successful? //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/08/10] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendMailResult( const AChara : TCharacter; const Fail :Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0249, OutBuffer); WriteBufferByte(2,Byte(Fail), OutBuffer); SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($0249,AChara.ClientVersion)); end;{SendMailResult} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNewMailNotify PROCEDURE //------------------------------------------------------------------------------ // What it does - // Notify player a new mail arrived //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/08/11] - Aeomin - Created //------------------------------------------------------------------------------ procedure SendNewMailNotify( const AChara : TCharacter; const MailID : LongWord; const Sender : String; const Title : String ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $024a, OutBuffer); WriteBufferLongWord(2,MailID, OutBuffer); WriteBufferString(6, Sender, NAME_LENGTH, OutBuffer); WriteBufferString(6+NAME_LENGTH, Title, 40, OutBuffer); SendBuffer(AChara.ClientInfo,OutBuffer,PacketDB.GetLength($024a,AChara.ClientVersion)); end;{SendNewMailNotify} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendInventory PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send items in inventory //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/19] Aeomin - Created //------------------------------------------------------------------------------ procedure SendInventory( AClient : TIdContext; const AInventory : TInventory ); var OutBuffer : TBuffer; OutBufferEquip : TBuffer; Len : Word; Index : Word; OffSet : Word; OffSetEquip : Word; ItemCount : Word; EquipmentCount : Word; InventoryItem : TItemInstance; EquipmentItem : TEquipmentItem; begin ItemCount := 0; EquipmentCount := 0; OffSet := 4; OffSetEquip := 4; WriteBufferWord(0, $01ee, OutBuffer); WriteBufferWord(0, $02d0, OutBufferEquip); if AInventory.ItemList.Count > 0 then begin for Index := 0 to AInventory.ItemList.Count - 1 do begin InventoryItem := AInventory.ItemList.Items[Index]; if (InventoryItem.Item is TUseableItem) OR (InventoryItem.Item is TMiscItem) then begin with InventoryItem.Item do begin WriteBufferWord(OffSet, Index+1, OutBuffer); //Index WriteBufferWord(OffSet+2, ID, OutBuffer); //ID WriteBufferByte(OffSet+4, ItemTypeToByte(ItemType), OutBuffer); //Type WriteBufferByte(OffSet+5, 1, OutBuffer); //Identified? WriteBufferWord(OffSet+6, InventoryItem.Quantity, OutBuffer); //Amount WriteBufferWord(OffSet+8, 0, OutBuffer); //For ammo WriteBufferWord(OffSet+10, 0, OutBuffer); //Card 1 WriteBufferWord(OffSet+12, 0, OutBuffer); //2 WriteBufferWord(OffSet+14, 0, OutBuffer); //3 WriteBufferWord(OffSet+16, 0, OutBuffer); //4 Inc(OffSet,18); end; Inc(ItemCount); end else if InventoryItem.Item is TEquipmentItem then begin EquipmentItem := InventoryItem.Item as TEquipmentItem; WriteBufferWord(OffSetEquip, Index+1, OutBufferEquip); //Index WriteBufferWord(OffSetEquip+2, EquipmentItem.ID, OutBufferEquip); //ID WriteBufferByte(OffSetEquip+4, 5, OutBufferEquip); //Type WriteBufferByte(OffSetEquip+5, Byte(InventoryItem.Identified), OutBufferEquip); //Identified WriteBufferWord(OffSetEquip+6, EquipTypeToByte(EquipmentItem.EquipmentType), OutBufferEquip); if InventoryItem.Equipped then WriteBufferWord(OffSetEquip+8, EquipLocationsToByte(EquipmentItem.EquipmentLocation), OutBufferEquip) //Equiped location else WriteBufferWord(OffSetEquip+8, 0, OutBufferEquip); //Equiped? WriteBufferByte(OffSetEquip+10, 0, OutBufferEquip); //Broken? WriteBufferByte(OffSetEquip+11, InventoryItem.Refined, OutBufferEquip); WriteBufferWord(OffSetEquip+12, 0, OutBufferEquip); //Card 1 WriteBufferWord(OffSetEquip+14, 0, OutBufferEquip); //2 WriteBufferWord(OffSetEquip+16, 0, OutBufferEquip); //3 WriteBufferWord(OffSetEquip+18, 0, OutBufferEquip); //4 WriteBufferWord(OffSetEquip+24, 0, OutBufferEquip); //?? Inc(OffSetEquip,26); Inc(EquipmentCount); end; end; end; //Items Len := (ItemCount * 18) + 4; WriteBufferWord(2, Len, OutBuffer); SendBuffer(AClient, OutBuffer, Len); //Equipments Len := (EquipmentCount * 26) + 4; WriteBufferWord(2, Len, OutBufferEquip); SendBuffer(AClient, OutBufferEquip, Len); end;{SendInventory} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNewItem PROCEDURE //------------------------------------------------------------------------------ // What it does - // New item!! //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/20] Aeomin - Created //------------------------------------------------------------------------------ procedure SendNewItem( AClient : TIdContext; const AInventory : TItemInstance; const Index : Word; const Amount : Word ); var OutBuffer : TBuffer; begin with AInventory.Item do begin WriteBufferWord(0, $02d4, OutBuffer); WriteBufferWord(2, Index+1, OutBuffer); WriteBufferWord(4, Amount, OutBuffer); WriteBufferWord(6, ID, OutBuffer); WriteBufferByte(8, Byte(AInventory.Identified), OutBuffer); WriteBufferByte(9, 0, OutBuffer); //Broken? WriteBufferByte(10, AInventory.Refined, OutBuffer); WriteBufferWord(11, 0, OutBuffer); //Card 1 WriteBufferWord(13, 0, OutBuffer); //2 WriteBufferWord(15, 0, OutBuffer); //3 WriteBufferWord(17, 0, OutBuffer); //4 if AInventory.Item is TEquipmentItem then begin WriteBufferWord(19, EquipTypeToByte(TEquipmentItem(AInventory.Item).EquipmentType), OutBuffer); end; WriteBufferByte(21, ItemTypeToByte(ItemType), OutBuffer);; WriteBufferByte(22, 0, OutBuffer); //Fail? WriteBufferLongWord(23, 0, OutBuffer); WriteBufferLongWord(27, 0, OutBuffer); SendBuffer(AClient, OutBuffer, 29); end; end;{SendNewItem} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNewItemFailed PROCEDURE //------------------------------------------------------------------------------ // What it does - // Failed to add item //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/25] Aeomin - Created //------------------------------------------------------------------------------ procedure SendNewItemFailed( AClient : TIdContext; const Flag : Byte ); var OutBuffer : TBuffer; begin if Flag > 0 then begin WriteBufferWord(0, $02d4, OutBuffer); WriteBufferByte(22, Flag, OutBuffer); SendBuffer(AClient, OutBuffer, 29); end; end;{SendNewItemFailed} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendStatusIcon PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send icons on right side //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/25] Aeomin - Created //------------------------------------------------------------------------------ procedure SendStatusIcon( const AChara : TCharacter; const IconID : Word; const Active : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0196, OutBuffer); WriteBufferWord(2, IconID, OutBuffer); WriteBufferLongWord(4, AChara.AccountID, OutBuffer); WriteBufferByte(8, Byte(Active), OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($0196,AChara.ClientVersion)); end;{SendStatusIcon} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendUpdatedLook PROCEDURE //------------------------------------------------------------------------------ // What it does - // Updates the look of a character. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/27] RaX - Created. //------------------------------------------------------------------------------ procedure SendUpdatedLook( const AChara : TCharacter; const CharacterID : LongWord; const AType : TLookTypes; const Value1 : Word; const Value2 : Word ); var OutBuffer : TBuffer; begin //$1d7 charID Type classID WriteBufferWord(0, $01d7, OutBuffer); WriteBufferLongWord(2, CharacterID, OutBuffer); WriteBufferByte(6, Byte(AType), OutBuffer); WriteBufferWord(7, Value1, OutBuffer); WriteBufferWord(9, Value2, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($01d7,AChara.ClientVersion)); end;{SendUpdatedLook} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendEncryptKeys PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send keys for packet id encryption. // (Apparently KRO doesn't support it) //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/26] Aeomin - Created //------------------------------------------------------------------------------ procedure SendEncryptKeys( AClient : TIdContext; const Key1,Key2 : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $02AE, OutBuffer); WriteBufferLongWord(2, Key1, OutBuffer); WriteBufferLongWord(6, Key2, OutBuffer); SendBuffer(AClient, OutBuffer, 10); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendDropItem PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send drop item. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/28] Aeomin - Created //------------------------------------------------------------------------------ procedure SendDropItem( const AChara : TCharacter; const AnItem : TItemInstance; const AQuantity : Word ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $009e, OutBuffer); WriteBufferLongWord(2, AnItem.ID, OutBuffer); WriteBufferWord(6, AnItem.Item.ID, OutBuffer); WriteBufferByte(8, Byte(AnItem.Identified), OutBuffer); WriteBufferWord(9, AnItem.Position.X, OutBuffer); WriteBufferWord(11, AnItem.Position.Y, OutBuffer); WriteBufferByte(13, AnItem.SubX, OutBuffer); WriteBufferByte(14, AnItem.SubY, OutBuffer); WriteBufferWord(15, AQuantity, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($009e,AChara.ClientVersion)); end;{SendDropItem} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendDeleteItem PROCEDURE //------------------------------------------------------------------------------ // What it does - // Delete an item //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/29] Aeomin - Created //------------------------------------------------------------------------------ procedure SendDeleteItem( const AChara : TCharacter; const Index : Word; const Quantity : Word ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00af, OutBuffer); WriteBufferWord(2, Index+1, OutBuffer); WriteBufferWord(4, Quantity, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($00af,AChara.ClientVersion)); end;{SendDeleteItem} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendGroundItem PROCEDURE //------------------------------------------------------------------------------ // What it does - // Item appears on ground. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/09/30] Aeomin - Created //------------------------------------------------------------------------------ procedure SendGroundItem( const AChara : TCharacter; const AnItem : TItemInstance ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $009d, OutBuffer); WriteBufferLongWord(2, AnItem.ID, OutBuffer); WriteBufferWord(6, AnItem.Item.ID, OutBuffer); WriteBufferByte(8, Byte(AnItem.Identified), OutBuffer); WriteBufferWord(9, AnItem.Position.X, OutBuffer); WriteBufferWord(11, AnItem.Position.Y, OutBuffer); WriteBufferWord(13, AnItem.Quantity, OutBuffer); WriteBufferByte(15, AnItem.SubX, OutBuffer); WriteBufferByte(16, AnItem.SubY, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($009d,AChara.ClientVersion)); end;{SendGroundItem} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendRemoveGroundItem PROCEDURE //------------------------------------------------------------------------------ // What it does - // Remove item from ground //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/01] Aeomin - Created //------------------------------------------------------------------------------ procedure SendRemoveGroundItem( const AChara : TCharacter; const ID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00a1, OutBuffer); WriteBufferLongWord(2, ID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($00a1,AChara.ClientVersion)); end;{SendRemoveGroundItem} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendPickUpItemAnimation PROCEDURE //------------------------------------------------------------------------------ // What it does - // Wrapper for action packet, it sends pickup item animation //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/03] Aeomin - Created //------------------------------------------------------------------------------ procedure SendPickUpItemAnimation( const AChara : TCharacter; const CharID : LongWord; const ItemID : LongWord ); begin DoAction( AChara.ClientInfo, CharID, ItemID, 0, 0, ACTION_PICKUP_ITEM, 0, 0, 0 ); end;{SendPickUpItemAnimation} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendEquipItemResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell client to move an item from inventory to equipment window. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/05] Aeomin - Created //------------------------------------------------------------------------------ procedure SendEquipItemResult( const AChara : TCharacter; const Index : Word; const Location:Word; const Success:Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00aa, OutBuffer); WriteBufferWord(2, Index+1, OutBuffer); WriteBufferWord(4, Location, OutBuffer); WriteBufferByte(6, Byte(Success), OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($00aa,AChara.ClientVersion)); end;{SendEquipItemResult} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendUnequipItemResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Unequip an item //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/10] Aeomin - Created //------------------------------------------------------------------------------ procedure SendUnequipItemResult( const AChara : TCharacter; const Index : Word; const Location:Word; const Success:Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00ac, OutBuffer); WriteBufferWord(2, Index+1, OutBuffer); WriteBufferWord(4, Location, OutBuffer); WriteBufferByte(6, Byte(Success), OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($00ac,AChara.ClientVersion)); end;{SendUnequipItemResult} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCDialog PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends dialog text to a character //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/18] Tsusai - Created //------------------------------------------------------------------------------ procedure SendNPCDialog( const AChara : TCharacter; const NPCID : LongWord; const NPCMessage : string ); var OutBuffer : TBuffer; Len : integer; begin Len := Length(NPCMessage); WriteBufferWord(0, $00b4, OutBuffer); WriteBufferWord(2, Len + 8, OutBuffer); WriteBufferLongWord(4, NPCID, OutBuffer); WriteBufferString(8, NPCMessage, Len, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, len + 8); end;{SendNPCDialog} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCNext PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends Next button to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/19] Tsusai - Created //------------------------------------------------------------------------------ procedure SendNPCNext( const AChara : TCharacter; const NPCID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00b5, OutBuffer); WriteBufferLongWord(2, NPCID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, 6); end;{SendNPCWait} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCClose PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends close button to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/19] Tsusai - Created //------------------------------------------------------------------------------ procedure SendNPCClose( const AChara : TCharacter; const NPCID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00b6, OutBuffer); WriteBufferLongWord(2, NPCID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, 6); end;{SendNPCClose} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCMenu PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends a menu packet to the client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/19] Tsusai - Created //------------------------------------------------------------------------------ procedure SendNPCMenu( const AChara : TCharacter; const NPCID : LongWord; const MenuString : string ); var OutBuffer : TBuffer; Size : word; begin WriteBufferWord(0, $00b7, OutBuffer); Size := Length(MenuString); WriteBufferWord(2, Size + 8, OutBuffer); WriteBufferLongWord(4, NPCID, OutBuffer); WriteBufferString(8, MenuString, Size, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, Size + 8); end;{SendNPCMenu} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCInput PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send an integer input box to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/11] Aeomin - Created //------------------------------------------------------------------------------ procedure SendNPCInput( const AChara : TCharacter; const NPCID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $0142, OutBuffer); WriteBufferLongWord(2, NPCID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($0142,AChara.ClientVersion)); end;{SendNPCInput} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNPCInputStr PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send a string input box to client //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/10/11] Aeomin - Created //------------------------------------------------------------------------------ procedure SendNPCInputStr( const AChara : TCharacter; const NPCID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $01d4, OutBuffer); WriteBufferLongWord(2, NPCID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($01d4,AChara.ClientVersion)); end;{SendNPCInput} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendSkillGroundUnit PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send a skill unit to specific coordinate // // Changes - // [2009/01/16] Aeomin - Created //------------------------------------------------------------------------------ procedure SendSkillGroundUnit( const AChara : TCharacter; const ID : LongWord; const SrcID : LongWord; const X,Y: Word; const SkillType: Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $011f, OutBuffer); WriteBufferLongWord(2, ID, OutBuffer); WriteBufferLongWord(6, SrcID, OutBuffer); WriteBufferWord(10, X, OutBuffer); WriteBufferWord(12, Y, OutBuffer); WriteBufferWord(14, SkillType, OutBuffer); WriteBufferByte(16, 1, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($011f,AChara.ClientVersion)); end;{SendSkillGroundUnit} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCreateChatRoomResult PROCEDURE //------------------------------------------------------------------------------ // What it does - // Create success or not. // // Changes - // [2009/01/17] Aeomin - Created //------------------------------------------------------------------------------ procedure SendCreateChatRoomResult( const AChara : TCharacter; const Fail : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00d6, OutBuffer); WriteBufferByte(2, Byte(Fail), OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, PacketDB.GetLength($00d6,AChara.ClientVersion)); end;{SendCreateChatRoomResult} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DisplayChatroomBar PROCEDURE //------------------------------------------------------------------------------ // What it does - // Display a bar thingy above chatroom owner. // // Changes - // [2009/01/17] Aeomin - Created //------------------------------------------------------------------------------ procedure DisplayChatroomBar( const AChara : TCharacter; const ChatRoom : TChatRoom ); var OutBuffer : TBuffer; Len : Word; begin if NOT Assigned(AChara.ChatRoom) OR (AChara.ChatRoom <> ChatRoom) then begin Len := Length(ChatRoom.Title); WriteBufferWord(0, $00d7, OutBuffer); WriteBufferWord(2, Len + 17, OutBuffer); WriteBufferLongWord(4, ChatRoom.Owner.ID, OutBuffer); WriteBufferLongWord(8, ChatRoom.ID, OutBuffer); WriteBufferWord(12, ChatRoom.Limit, OutBuffer); WriteBufferWord(14, ChatRoom.Characters.Count, OutBuffer); WriteBufferByte(16, Byte(ChatRoom.isPublic), OutBuffer); WriteBufferString(17,ChatRoom.Title,Len,OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, Len + 17); end; end;{DisplayChatroomBar} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendQuitChat PROCEDURE //------------------------------------------------------------------------------ // What it does - // Notify that someone left chatroom. // // Changes - // [2009/01/18] Aeomin - Created //------------------------------------------------------------------------------ procedure SendQuitChat( const AChara : TCharacter; const Name : String; const Count : Word; const Kicked : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00dd, OutBuffer); WriteBufferWord(2, Count, OutBuffer); WriteBufferString(4,Name,NAME_LENGTH,OutBuffer); WriteBufferByte(28, Byte(Kicked), OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00dd,AChara.ClientVersion)); end;{SendQuitChat} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendClearChat PROCEDURE //------------------------------------------------------------------------------ // What it does - // Remove chat from public eyes // // Changes - // [2009/01/18] Aeomin - Created //------------------------------------------------------------------------------ procedure SendClearChat( const AChara : TCharacter; const ChatRoom : TChatRoom ); var OutBuffer : TBuffer; begin if NOT Assigned(AChara.ChatRoom) OR (AChara.ChatRoom <> ChatRoom) then begin WriteBufferWord(0, $00d8, OutBuffer); WriteBufferLongWord(2, ChatRoom.ID, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00d8,AChara.ClientVersion)); end; end;{SendClearChat} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendChangeChatOwner PROCEDURE //------------------------------------------------------------------------------ // What it does - // Change chat owner // // Changes - // [2009/01/18] Aeomin - Created //------------------------------------------------------------------------------ procedure SendChangeChatOwner( const AChara : TCharacter; const OldOwner : String; const NewOwner : String ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00e1, OutBuffer); WriteBufferLongWord(2, 1, OutBuffer); WriteBufferString(6,OldOwner,NAME_LENGTH,OutBuffer); //SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00e1,AChara.ClientVersion)); //FillChar(OutBuffer, PacketDB.GetLength($00e1,AChara.ClientVersion), 0); WriteBufferWord(30, $00e1, OutBuffer); WriteBufferLongWord(32, 0, OutBuffer); WriteBufferString(36,NewOwner,NAME_LENGTH,OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00e1,AChara.ClientVersion)*2); end;{SendChangeChatOwner} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendJoinChatFailed PROCEDURE //------------------------------------------------------------------------------ // What it does - // Failed to join chatroom // // Changes - // [2009/01/18] Aeomin - Created //------------------------------------------------------------------------------ procedure SendJoinChatFailed( const AChara : TCharacter; const Flag : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00da, OutBuffer); WriteBufferByte(2, Flag, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00da,AChara.ClientVersion)); end;{SendJoinChatFailed} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendJoinChatOK PROCEDURE //------------------------------------------------------------------------------ // What it does - // Join chatroom OK, send player list // // Changes - // [2009/04/16] Aeomin - Created //------------------------------------------------------------------------------ procedure SendJoinChatOK( const AChara : TCharacter; const AChatRoom : TChatRoom ); var OutBuffer : TBuffer; Index : Word; begin WriteBufferWord(0, $00db, OutBuffer); WriteBufferWord(2, 28*AChatRoom.Characters.Count + 8, OutBuffer); WriteBufferLongWord(4, AChatRoom.ID, OutBuffer); for Index := 0 to AChatRoom.Characters.Count - 1 do begin WriteBufferLongWord(Index * 28 + 8, Byte((Index > 0)OR(AChatRoom.Owner is TNPC)), OutBuffer); WriteBufferString(Index * 28 + 12,AChatRoom.Characters.Items[Index].Name ,NAME_LENGTH, OutBuffer); end; SendBuffer(AChara.ClientInfo, OutBuffer,28*AChatRoom.Characters.Count + 8); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendNotifyJoinChat PROCEDURE //------------------------------------------------------------------------------ // What it does - // Notify players when someone joins the chatroom // // Changes - // [2009/04/16] Aeomin - Created //------------------------------------------------------------------------------ procedure SendNotifyJoinChat( const AChara : TCharacter; const NewUsers : Word; const Name : String ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $00dc, OutBuffer); WriteBufferWord(2, NewUsers, OutBuffer); WriteBufferString(4, Name ,NAME_LENGTH, OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer,PacketDB.GetLength($00dc,AChara.ClientVersion)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //UpdateChatroom PROCEDURE //------------------------------------------------------------------------------ // What it does - // Update chatroom stuff // // Changes - // [2009/06/27] Aeomin - Created //------------------------------------------------------------------------------ procedure UpdateChatroom( const AChara : TCharacter; const Chatroom : TChatRoom ); var OutBuffer : TBuffer; Len : Word; begin Len := Length(ChatRoom.Title); WriteBufferWord(0, $00df, OutBuffer); WriteBufferWord(2, Len + 17, OutBuffer); WriteBufferLongWord(4, ChatRoom.Owner.ID, OutBuffer); WriteBufferLongWord(8, ChatRoom.ID, OutBuffer); WriteBufferWord(12, ChatRoom.Limit, OutBuffer); WriteBufferWord(14, ChatRoom.Characters.Count, OutBuffer); WriteBufferByte(16, Byte(ChatRoom.isPublic), OutBuffer); WriteBufferString(17,ChatRoom.Title,Len,OutBuffer); SendBuffer(AChara.ClientInfo, OutBuffer, Len + 17); end;{UpdateChatroom} //------------------------------------------------------------------------------ end{ZoneSend}.
unit Classes.Entities; interface uses cxLabel,Vcl.ExtCtrls,Generics.Collections; type TBaseObjClass=class of TBaseObj; TBaseObj=Class(TObject) public constructor Create; end; TBoardPosition=(bpDown,bpLeft,bpUp,bpRight); TCardPosition=(cpMyCards,cpFirstPlayer,cpSecondPlayer,cpThirdPlayer); TPlayer=class(TBaseObj) private FName:String; FPosition:TBoardPosition; FCardImage: TImage; FPlayerLabel: TcxLabel; FCardPosition: TCardPosition; public property Name:String read FName write FName; property Position:TBoardPosition read FPosition write FPosition; property PlayerLabel:TcxLabel read FPlayerLabel write FPlayerLabel; property CardImage:TImage read FCardImage write FCardImage; property CardPosition:TCardPosition read FCardPosition write FCardPosition; end; TPlayers=class(TObjectList<TPlayer>) public function Find(const APlayerName:String):TPlayer; end; implementation { TBaseObj } constructor TBaseObj.Create; begin inherited; end; { TPlayers } function TPlayers.Find(const APlayerName: String): TPlayer; var itm:TPlayer; begin Result:=Nil; for itm in Self do begin if itm.Name=APlayerName then begin Result:=itm; Break; end; end; end; end.
unit docs.institution; interface uses Horse, Horse.GBSwagger; procedure registry(); implementation uses schemas.classes; procedure registry(); begin Swagger .Path('instituicao/{id_instituicao}') .Tag('Instituições') .GET('listar uma instituição', 'listar um instituição especifica') .AddParamPath('id_instituicao', 'id_instituicao') .Schema(SWAG_INTEGER) .Required(true) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TInstitution) .&End .AddResponse(404, 'instituição não encontrada') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('instituicao') .Tag('Instituições') .GET('listar instituições com paginação', 'listagem de instituição com paginação e filtros') .Description('o query param find representa o nome de uma coluna do banco e value o valor que sera colocado no criterio de filtro exemplo: find=id&value=10') .AddParamQuery('page', 'page') .Schema(SWAG_INTEGER) .&End .AddParamQuery('limit', 'limit') .Schema(SWAG_INTEGER) .&End .AddParamQuery('find', 'find') .Schema(SWAG_STRING) .&End .AddParamQuery('value', 'value') .Schema(SWAG_STRING) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TInstitutionPagination) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('instituicao') .Tag('Instituições') .Post('criar instiuição', 'criar uma nova instituição') .AddParamBody .Schema(TInstitution) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(201) .Schema(TRegion) .&End .AddResponse(404, 'instituição não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('instituicao/{id_instituicao}') .Tag('Instituições') .Put('alterar instituição', 'alteração de uma instituição') .AddParamPath('id_instituicao', 'id_instituicao') .Schema(SWAG_INTEGER) .&end .AddParamBody .Schema(TInstitution) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TRegion) .&End .AddResponse(404, 'comunidade não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('instituicao/{id_instituicao}') .Tag('Instituições') .Delete('deletar instituição', 'deletar uma instituição') .AddParamPath('id_instituicao', 'id_instituicao') .Schema(SWAG_INTEGER) .&end .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200, 'instituição deletada com sucesso') .Schema(TMessage) .&End .AddResponse(404, 'instituição não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido, não foi possivel deletar a instituição') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; end; end.
unit UnitManage; interface //type {TThreadInfo = record nRunFlag :Integer; //0x00 boActived :BOOL; //0x04 dwRunTick :LongWord; //0x08 Config :pTConfig; //0x0C boTerminaled :BOOL; //0x10 hThreadHandle:THandle; //0x14 dwThreadID :LongWord; //0x18 n1C :Integer; //0x1C n20 :Integer; //0x20 n24 :integer; //0x24 end; pTThreadInfo = ^TThreadInfo; } //procedure StartRegThread(Config:pTConfig;ThreadInfo:pTThreadInfo); //procedure RegServerThread(ThreadInfo:pTThreadInfo);stdcall; implementation {procedure StartRegThread(Config:pTConfig;ThreadInfo:pTThreadInfo); begin ThreadInfo.Config:=Config; ThreadInfo.hThreadHandle:=CreateThread(nil, 0, @RegServerThread, ThreadInfo, 0, ThreadInfo.dwThreadID); end; procedure RegServerThread(ThreadInfo:pTThreadInfo);stdcall; begin end; } end.
unit stmDetector1; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses util1,stmdef,stmObj,stmVec1,NcDef2,stmPg,debug0; type Tdetector= class(typeUO) private mode: integer; { 1: crossings 2: Timer } hhUp,hhDw:single; stateUp:boolean; dlInhib,dlInhib0:integer; Fup,Fdw:boolean; lastI:integer; // last processed sample Vsource,Vdest:Tvector; // source and destination Fdisp:boolean; // if true, we display the new samples of dest OnDetect:array of Tpg2Event; FDetDelay:array of float; DetDelayI:array of integer; Idet:array of integer; DTtimer,T0Timer: float; DT,T0: integer; ILastDet: integer; procedure SetDetDelay(n:integer;w:float); function GetDetDelay(n:integer):float; procedure SetAllLengths(n:integer); procedure SetSecondVars; procedure updateCrossings(ind:integer); procedure updateTimer(ind:integer); public constructor create;override; destructor destroy;override; class function STMClassName:AnsiString;override; procedure processMessage(id:integer;source:typeUO;p:pointer);override; property DetDelay[n:integer]:float read getDetDelay write SetDetDelay; procedure initCrossings(src,dest:Tvector;Fup1,Fdw1:boolean; h1,h2,linhib:float;yinit:float;Fdisp1:boolean); procedure InitTimer(src: Tvector; DT1,T1:float); procedure update(ind:integer); procedure setThUp(w:float); procedure setThDw(w:float); procedure Reinit(x:float); function getAcqChannel:integer; end; procedure proTdetector_create(var pu:typeUO);pascal; procedure proTdetector_InitCrossings(var src, dest: Tvector;Fup1,Fdw1:boolean;h1,h2,linhib:float;yinit:float;Fdisp1:boolean;var pu:typeUO);pascal; procedure proTdetector_InitTimer(var src1: Tvector;DT1: float;var pu:typeUO);pascal; procedure proTdetector_InitTimer_1(var src1: Tvector;DT1,T1: float;var pu:typeUO);pascal; procedure proTdetector_Update(index: integer;var pu:typeUO);pascal; procedure proTdetector_Reinit(x:float;var pu:typeUO);pascal; procedure proTdetector_ThresholdUp(w:float;var pu:typeUO);pascal; function fonctionTdetector_ThresholdUp(var pu:typeUO):float;pascal; procedure proTdetector_ThresholdDw(w:float;var pu:typeUO);pascal; function fonctionTdetector_ThresholdDw(var pu:typeUO):float;pascal; procedure proTdetector_AddEvent(p:integer; w:float; var pu:typeUO);pascal; procedure proTdetector_OnDetect(p:integer;var pu:typeUO);pascal; function fonctionTdetector_OnDetect(var pu:typeUO):integer;pascal; procedure proTdetector_Delay(w:float;var pu:typeUO);pascal; function fonctionTdetector_Delay(var pu:typeUO):float;pascal; implementation { Tdetector } constructor Tdetector.create; begin inherited; end; destructor Tdetector.destroy; begin derefObjet(typeUO(Vsource)); derefObjet(typeUO(Vdest)); inherited; end; class function Tdetector.STMClassName: AnsiString; begin result:='Integrator'; end; procedure Tdetector.processMessage(id: integer; source: typeUO; p: pointer); begin case id of UOmsg_destroy: begin if Vsource=source then begin Vsource:=nil; derefObjet(source); end; if Vdest=source then begin Vdest:=nil; derefObjet(source); end; end; end; end; procedure Tdetector.initCrossings(src, dest: Tvector; Fup1,Fdw1:boolean;h1,h2,linhib:float;yinit:float;Fdisp1:boolean); var i:integer; begin mode:=1; Vsource:=src; refObjet(src); Vdest:=dest; refObjet(dest); Vdest.initEventList(G_longint,Vsource.Dxu); Vdest.Fexpand:=true; Vdest.invalidate; Fdisp:=Fdisp1; Fup:=Fup1; Fdw:=Fdw1; hhUp:=h1; hhDw:=h2; stateUp:=(yinit>=hhUp); dlinhib0:=Vsource.invConvX(lInhib)-Vsource.invConvX(0); dlInhib:=0; setSecondVars; lastI:=Vsource.Istart-1; end; procedure Tdetector.initTimer(src: Tvector; DT1,T1:float); begin mode:=2; Vsource:=src; refObjet(src); DTtimer:=DT1; T0Timer:=T1; setSecondVars; lastI:=Vsource.Istart-1; end; procedure Tdetector.Reinit(x: float); var i:integer; begin lastI:=Vsource.invconvx(x); if not assigned(Vdest) then exit; Vdest.initEventList(G_longint,Vsource.Dxu); Vdest.Fexpand:=true; Vdest.invalidate; for i:=0 to high(OnDetect) do Idet[i]:=Vdest.Istart; stateUp:=(Vsource[lastI]>=hhUp); end; procedure Tdetector.updateCrossings(ind:integer); var i:integer; ii:integer; w:single; begin if not assigned(Vsource) or not assigned(Vdest) then exit; for ii:=lastI+1 to ind do begin w:=Vsource.data.getE(ii); if not stateUp then begin if w>=hhUp then begin stateUp:=true; if Fup and (dlInhib<=0) then begin Vdest.addToList(Vsource.convx(ii)); dlInhib:=dlInhib0+1; end; end; end else begin if w<hhDw then begin stateUp:=false; if Fdw and (dlInhib<=0) then begin Vdest.addToList(Vsource.convx(ii)); dlInhib:=dlInhib0+1; end; end; end; dec(dlinhib); for i:=0 to high(OnDetect) do with onDetect[i] do if valid and (Idet[i]>=Vdest.Istart) and (Idet[i]<=Vdest.Iend) and (Vsource.invconvx(Vdest[Idet[i]])=ii-DetDelayI[i]) then begin pg.executerProcedure1(ad,Idet[i]); if pg.LastError<>0 then finExe:=true; inc(Idet[i]); end; if finExe then exit; end; if Fdisp then Vdest.doImDisplay; lastI:=Ind; end; procedure Tdetector.updateTimer(ind:integer); var i:integer; ii:integer; w:single; begin if not assigned(Vsource) then exit; for ii:=lastI+1 to ind do begin if (ii>0) and (ii>=T0) and ((ii-T0) mod DT=0) then ILastDet:=ii; if IlastDet>0 then for i:=0 to high(OnDetect) do with onDetect[i] do if valid and (ii = IlastDet+DetDelayI[i]) then begin inc(Idet[i]); pg.executerProcedure1(ad,Idet[i]); if pg.LastError<>0 then finExe:=true; end; if finExe then exit; end; if Fdisp then Vdest.doImDisplay; lastI:=Ind; end; procedure Tdetector.update(ind:integer); begin case mode of 1: updateCrossings(ind); 2: updateTimer(ind); end; end; procedure Tdetector.setThUp(w: float); begin hhUp:=w; if assigned(Vsource) and (lastI>=Vsource.Istart) and (lastI<=Vsource.Iend) and (Vsource[lastI]>=hhUp) then stateUp:=true; { on ne provoque pas le changement d'état vers le bas } end; procedure Tdetector.setThDw(w: float); begin hhDw:=w; if assigned(Vsource) and (lastI>=Vsource.Istart) and (lastI<=Vsource.Iend) and (Vsource[lastI]<hhDw) then stateUp:=false; { on ne provoque pas le changement d'état vers le haut } end; procedure Tdetector.SetDetDelay(n: integer; w: float); begin FDetDelay[n]:=w; if assigned(Vsource) then DetDelayI[n]:=Vsource.invConvX(FDetDelay[n])-Vsource.invConvX(0); end; function Tdetector.GetDetDelay(n: integer): float; begin if (n>=0) and (n<length(FdetDelay)) then result:= FdetDelay[n] else result:=0; end; procedure Tdetector.SetAllLengths(n: integer); begin setlength(Ondetect, n); OnDetect[n-1].numero:=0; setlength(FDetDelay, n); FdetDelay[n-1]:=0; setlength(DetDelayI, n); DetDelayI[n-1]:=0; setlength(Idet, n); if assigned(Vdest) then Idet[n-1]:=Vdest.Istart else Idet[n-1]:=0; end; procedure Tdetector.SetSecondVars; var i:integer; begin for i:=0 to high(OnDetect) do if assigned(Vsource) then DetDelayI[i]:= Vsource.invConvX(FDetDelay[i])-Vsource.invConvX(0); for i:=0 to high(OnDetect) do if assigned(Vdest) then Idet[i]:=Vdest.Istart else Idet[i]:=0; if assigned(Vsource) then begin DT:= Vsource.invConvX(DTtimer); T0:= Vsource.invConvX(T0Timer); end; end; function Tdetector.getAcqChannel: integer; begin end; {*************************** Méthodes STM **************************} procedure proTdetector_create(var pu:typeUO); begin createPgObject('',pu,Tdetector); end; procedure proTdetector_InitCrossings(var src, dest: Tvector; Fup1,Fdw1:boolean;h1,h2,linhib:float;yinit:float;Fdisp1:boolean ;var pu:typeUO); const max=10000000; begin verifierObjet(pu); verifierObjet(typeUO(src)); verifierVecteurTemp(dest); with Tdetector(pu) do initCrossings(src,dest,Fup1,Fdw1,h1,h2,linhib,yinit,Fdisp1); end; procedure proTdetector_InitTimer_1(var src1: Tvector;DT1,T1: float;var pu:typeUO); begin verifierObjet(pu); verifierObjet(typeUO(src1)); if (DT1<src1.Dxu) or (T1<0) then sortieErreur('Tdetector.InitTimer : bad parameter'); with Tdetector(pu) do initTimer(src1,DT1,T1); end; procedure proTdetector_InitTimer(var src1: Tvector;DT1: float;var pu:typeUO); begin proTdetector_InitTimer_1(src1 ,DT1, 0, pu); end; procedure proTdetector_Update(index: integer;var pu:typeUO); begin verifierObjet(pu); Tdetector(pu).update(index); end; procedure proTdetector_ThresholdUp(w:float;var pu:typeUO); begin verifierObjet(pu); Tdetector(pu).setThUp(w); end; function fonctionTdetector_ThresholdUp(var pu:typeUO):float; begin verifierObjet(pu); result:=Tdetector(pu).hhUp; end; procedure proTdetector_ThresholdDw(w:float;var pu:typeUO); begin verifierObjet(pu); Tdetector(pu).setThDw(w); end; function fonctionTdetector_ThresholdDw(var pu:typeUO):float; begin verifierObjet(pu); result:=Tdetector(pu).hhDw; end; procedure proTdetector_OnDetect(p:integer;var pu:typeUO); begin verifierObjet(pu); with Tdetector(pu) do begin if length(OnDetect)=0 then setAllLengths(1); onDetect[0].setAd(p); end; end; function fonctionTdetector_OnDetect(var pu:typeUO):integer; begin verifierObjet(pu); with Tdetector(pu) do if length(OnDetect)>0 then result:=OnDetect[0].ad else result:=0; end; procedure proTdetector_Delay(w:float;var pu:typeUO); begin verifierObjet(pu); with Tdetector(pu) do begin if length(OnDetect)=0 then setAllLengths(1); DetDelay[0]:=w; end; end; function fonctionTdetector_Delay(var pu:typeUO):float; begin verifierObjet(pu); with Tdetector(pu) do if length(OnDetect)>0 then result:=Tdetector(pu).DetDelay[0] else result:=0; end; procedure proTdetector_AddEvent(p:integer; w:float; var pu:typeUO); begin verifierObjet(pu); with Tdetector(pu) do begin setAlllengths( length(OnDetect)+1); onDetect[high(OnDetect)].setAd(p); detDelay[high(FdetDelay)]:=w; setSecondVars; end; end; procedure proTdetector_Reinit(x:float;var pu:typeUO);pascal; begin verifierObjet(pu); Tdetector(pu).Reinit(x); end; Initialization AffDebug('Initialization stmDetector1',0); registerObject(Tdetector,data); end.
(* Stack ADT 2 19.04.2017 *) (* ---------- *) (* implementing the stack as abstract data type - version 2 *) (* ========================================================= *) UNIT StackADT2; INTERFACE CONST max = 100; TYPE Stack = ^StackRec; StackRec = Record data: Array[1..max] OF INTEGER; top: INTEGER; END; PROCEDURE NewStack(VAR s: Stack); PROCEDURE DisposeStack(VAR s: Stack); PROCEDURE Push(VAR s: Stack; e: INTEGER); PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER); (* VAR not nice, but consistent with prev version FUNCTION Empty(VAR s: Stack): BOOLEAN; *) FUNCTION Empty(s: Stack): BOOLEAN; IMPLEMENTATION PROCEDURE NewStack(VAR s: Stack); BEGIN New(s); s^.top := 0; END; PROCEDURE DisposeStack(VAR s: Stack); BEGIN Dispose(s); s := NIL; END; PROCEDURE Push(VAR s: Stack; e: INTEGER); BEGIN IF s^.top = max THEN BEGIN WriteLn('Stack overflow'); END ELSE BEGIN s^.top := s^.top + 1; s^.data[s^.top] := e; END; END; PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER); BEGIN IF s^.top = 0 THEN BEGIN WriteLn('Stack underflow'); END ELSE BEGIN e := s^.data[s^.top]; s^.top := s^.top - 1; END; END; FUNCTION Empty(s: Stack): BOOLEAN; BEGIN Empty := s^.top = 0; END; BEGIN END. (* StackADT2 *)
//============================================================================== // Product name: ZipForge // Copyright ComponentAce, 2003 //============================================================================== {$I ZFVer.inc} {$DEFINE ZF_VERSION} unit ZFReg; interface uses Classes, {$IFDEF D6H} DesignIntf, DesignEditors {$ELSE} DSGNINTF {$ENDIF} ; type // file open dialog - for selecting archive file TZFArchiveFileName = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; // TZFArchiveFileName // file open dialog - for selecting SFX stub TZFSFXFileName = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; // TZFSFXFileName // folder open dialog - for selecting paths TZFDirectory = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; //TZFDirectory procedure Register; // register implementation uses {$IFNDEF D16H} Forms, Dialogs, {$ELSE} VCL.Forms, VCL.Dialogs, {$ENDIF} ZipForge, ZFFolderDialog; //////////////////////////////////////////////////////////////////////////////// // TZFArchiveFileName //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ // file name editor (extension is subtracted from name) //------------------------------------------------------------------------------ procedure TZFArchiveFileName.Edit; var td: TOpenDialog; s: string; begin td := TOpenDialog.Create(Application); td.Options := [ofFileMustExist]; {$IFDEF ZF_VERSION} td.Filter := 'ZIP files (*.zip)|*.ZIP'; {$ENDIF} if (td.Execute) then begin s := td.FileName; SetStrValue(s); end; td.Free; end; // TZFArchiveFileName.Edit //------------------------------------------------------------------------------ // file name editor's attributes (paDialog - for ... button in design mode) //------------------------------------------------------------------------------ function TZFArchiveFileName.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; //TZFArchiveFileName.GetAttributes //////////////////////////////////////////////////////////////////////////////// // TZFSFXFileName //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ // file name editor (extension is subtracted from name) //------------------------------------------------------------------------------ procedure TZFSFXFileName.Edit; var td: TOpenDialog; s: string; begin td := TOpenDialog.Create(Application); td.Options := [ofFileMustExist]; td.Filter := 'Executable files (*.exe)|*.EXE'; if (td.Execute) then begin s := td.FileName; SetStrValue(s); end; td.Free; end; // TZFSFXFileName.Edit //------------------------------------------------------------------------------ // file name editor's attributes (paDialog - for ... button in design mode) //------------------------------------------------------------------------------ function TZFSFXFileName.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; //TZFSFXFileName.GetAttributes //////////////////////////////////////////////////////////////////////////////// // TZFZIPDirectory //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ // path property editor //------------------------------------------------------------------------------ procedure TZFDirectory.Edit; var fb: TPBFolderDialog; begin fb := TPBFolderDialog.Create(Application); fb.Flags := [ShowPath]; // fb.BrowseFlags := [bfDirsOnly]; fb.Folder := GetStrValue; if (fb.Execute) then SetStrValue(fb.Folder); fb.Free; end; // TZFDirectory.Edit //------------------------------------------------------------------------------ // file name editor's attributes (paDialog - for ... button in design mode) //------------------------------------------------------------------------------ function TZFDirectory.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; //TZFDirectory.GetAttributes procedure Register; begin {$IFDEF ZF_VERSION} RegisterComponents('ComponentAce Compression', [TZipForge]); {$ENDIF} RegisterPropertyEditor(TypeInfo(string), TZFBaseArchiver, 'FileName', TZFArchiveFileName); RegisterPropertyEditor(TypeInfo(string), TZFBaseArchiver, 'SFXStub', TZFSFXFileName); RegisterPropertyEditor(TypeInfo(string), TZFBaseArchiver, 'BaseDir', TZFDirectory); RegisterPropertyEditor(TypeInfo(string), TZFBaseArchiver, 'TempDir', TZFDirectory); end; end.
unit TransformAnimation; interface uses BasicMathsTypes, Geometry; {$INCLUDE source/Global_Conditionals.inc} type TTransformAnimation = class protected FNumSectors: integer; public Name: string; TransformMatrices: array of TGLMatrixf4; // Constructors and Destructors constructor Create(const _Name: string; _NumSectors: integer); overload; constructor Create(_NumSectors: integer); overload; constructor Create(const _Name: string; _NumSectors, _NumFrames: integer); overload; constructor Create(_NumSectors, _NumFrames: integer); overload; constructor Create(const _Source: TTransformAnimation); overload; destructor Destroy; override; procedure InitializeTransforms(_NumSectors, _NumFrames: integer); // Execute procedure ApplyMatrix(_Section : Integer; _Frame: integer); overload; procedure ApplyMatrix(_Scale : TVector3f; _Section : Integer; _Frame: integer); overload; // Sets procedure SetScale(_Scale : TVector3f; _Section : Integer; _Frame: integer); procedure SetMatrix(const _M : TMatrix; _Frame,_Section : Integer); // Copy procedure Assign(const _Source: TTransformAnimation); end; implementation uses BasicFunctions, dglOpenGL; // Constructors and Destructors constructor TTransformAnimation.Create(const _Name: string; _NumSectors: integer); begin Name := copyString(_Name); InitializeTransforms(_NumSectors, 1); end; constructor TTransformAnimation.Create(_NumSectors: integer); begin Name := 'Movement'; InitializeTransforms(_NumSectors, 1); end; constructor TTransformAnimation.Create(const _Name: string; _NumSectors, _NumFrames: integer); begin Name := copyString(_Name); InitializeTransforms(_NumSectors, _NumFrames); end; constructor TTransformAnimation.Create(_NumSectors, _NumFrames: integer); begin Name := 'Movement'; InitializeTransforms(_NumSectors, _NumFrames); end; constructor TTransformAnimation.Create(const _Source: TTransformAnimation); begin Assign(_Source); end; destructor TTransformAnimation.Destroy; begin Name := ''; SetLength(TransformMatrices, 0); inherited Destroy; end; procedure TTransformAnimation.InitializeTransforms(_NumSectors, _NumFrames: Integer); var i: integer; begin FNumSectors := _NumSectors; SetLength(TransformMatrices, _NumSectors * _NumFrames); for i := Low(TransformMatrices) to High(TransformMatrices) do begin TransformMatrices[i][0,0] := 1; TransformMatrices[i][0,1] := 0; TransformMatrices[i][0,2] := 0; TransformMatrices[i][0,3] := 0; TransformMatrices[i][1,0] := 0; TransformMatrices[i][1,1] := 1; TransformMatrices[i][1,2] := 0; TransformMatrices[i][1,3] := 0; TransformMatrices[i][2,0] := 0; TransformMatrices[i][2,1] := 0; TransformMatrices[i][2,2] := 1; TransformMatrices[i][2,3] := 0; TransformMatrices[i][3,0] := 0; TransformMatrices[i][3,1] := 0; TransformMatrices[i][3,2] := 0; TransformMatrices[i][3,3] := 1; end; end; // Execute procedure TTransformAnimation.ApplyMatrix(_Scale : TVector3f; _Section : Integer; _Frame: integer); var Matrix : TGLMatrixf4; index: integer; begin index := (_Frame * FNumSectors) + _Section; if Index > High(TransformMatrices) then exit; Matrix[0,0] := TransformMatrices[index][0,0]; Matrix[0,1] := TransformMatrices[index][1,0]; Matrix[0,2] := TransformMatrices[index][2,0]; Matrix[0,3] := TransformMatrices[index][3,0]; Matrix[1,0] := TransformMatrices[index][0,1]; Matrix[1,1] := TransformMatrices[index][1,1]; Matrix[1,2] := TransformMatrices[index][2,1]; Matrix[1,3] := TransformMatrices[index][3,1]; Matrix[2,0] := TransformMatrices[index][0,2]; Matrix[2,1] := TransformMatrices[index][1,2]; Matrix[2,2] := TransformMatrices[index][2,2]; Matrix[2,3] := TransformMatrices[index][3,2]; Matrix[3,0] := TransformMatrices[index][0,3] * _Scale.X; Matrix[3,1] := TransformMatrices[index][1,3] * _Scale.Y; Matrix[3,2] := TransformMatrices[index][2,3] * _Scale.Z; Matrix[3,3] := TransformMatrices[index][3,3]; glMultMatrixf(@Matrix[0,0]); end; procedure TTransformAnimation.ApplyMatrix(_Section : Integer; _Frame: integer); var Matrix : TGLMatrixf4; index: integer; begin index := (_Frame * FNumSectors) + _Section; if Index > High(TransformMatrices) then exit; Matrix[0,0] := TransformMatrices[index][0,0]; Matrix[0,1] := TransformMatrices[index][1,0]; Matrix[0,2] := TransformMatrices[index][2,0]; Matrix[0,3] := TransformMatrices[index][3,0]; Matrix[1,0] := TransformMatrices[index][0,1]; Matrix[1,1] := TransformMatrices[index][1,1]; Matrix[1,2] := TransformMatrices[index][2,1]; Matrix[1,3] := TransformMatrices[index][3,1]; Matrix[2,0] := TransformMatrices[index][0,2]; Matrix[2,1] := TransformMatrices[index][1,2]; Matrix[2,2] := TransformMatrices[index][2,2]; Matrix[2,3] := TransformMatrices[index][3,2]; Matrix[3,0] := TransformMatrices[index][0,3]; Matrix[3,1] := TransformMatrices[index][1,3]; Matrix[3,2] := TransformMatrices[index][2,3]; Matrix[3,3] := TransformMatrices[index][3,3]; glMultMatrixf(@Matrix[0,0]); end; // Sets procedure TTransformAnimation.SetScale(_Scale : TVector3f; _Section : Integer; _Frame: integer); var index: integer; begin index := (_Frame * FNumSectors) + _Section; if Index > High(TransformMatrices) then exit; TransformMatrices[index][0,3] := TransformMatrices[index][0,3] * _Scale.X; TransformMatrices[index][1,3] := TransformMatrices[index][1,3] * _Scale.Y; TransformMatrices[index][2,3] := TransformMatrices[index][2,3] * _Scale.Z; end; procedure TTransformAnimation.SetMatrix(const _M : TMatrix; _Frame,_Section : Integer); var x,y : integer; index: integer; begin index := (_Frame * FNumSectors) + _Section; for x := 0 to 3 do for y := 0 to 3 do TransformMatrices[index][x][y] := _M[x][y]; end; procedure TTransformAnimation.Assign(const _Source: TTransformAnimation); var i,x,y: integer; begin Name := CopyString(_Source.Name); FNumSectors := _Source.FNumSectors; SetLength(TransformMatrices, High(_Source.TransformMatrices) + 1); for i := Low(TransformMatrices) to High(TransformMatrices) do begin for x := 0 to 3 do for y := 0 to 3 do begin TransformMatrices[i][x,y] := _Source.TransformMatrices[i][x,y]; end; end; end; end.
unit API_DB; interface uses FireDAC.Comp.Client, FireDAC.DApt, FireDAC.Stan.Async, FireDAC.Stan.Def; type TConnectParams = record CharacterSet: string; DataBase: string; Host: string; Login: string; Password: string; public procedure GetFromFile(aFileName: string); end; TDBEngine = class abstract private FIsConnected: Boolean; protected FDConnection: TFDConnection; FConnectParams: TConnectParams; procedure SetConnectParams; virtual; public function GetLastInsertedID: Integer; virtual; abstract; procedure CloseConnection; procedure ExecQuery(aQuery: TFDQuery); virtual; procedure ExecSQL(const aSQLString: string); procedure OpenConnection; procedure OpenQuery(aQuery: TFDQuery; aIsFetchAll: Boolean = True); constructor Create(aConnectParams: TConnectParams); destructor Destroy; override; property IsConnected: Boolean read FIsConnected; end; TDBEngineClass = class of TDBEngine; implementation uses System.Classes; procedure TDBEngine.ExecSQL(const aSQLString: string); var dsQuery: TFDQuery; begin dsQuery := TFDQuery.Create(nil); try dsQuery.SQL.Text := aSQLString; ExecQuery(dsQuery); finally dsQuery.Free; end; end; procedure TConnectParams.GetFromFile(aFileName: string); var SL: TStringList; begin SL := TStringList.Create; try SL.LoadFromFile(aFileName); Self.Host := SL.Values['Host']; Self.DataBase := SL.Values['DataBase']; Self.Login := SL.Values['Login']; Self.Password := SL.Values['Password']; Self.CharacterSet := SL.Values['CharacterSet']; finally SL.Free; end; end; constructor TDBEngine.Create(aConnectParams: TConnectParams); begin FConnectParams := aConnectParams; end; procedure TDBEngine.ExecQuery(aQuery: TFDQuery); begin aQuery.Connection := FDConnection; aQuery.ExecSQL; end; procedure TDBEngine.OpenQuery(aQuery: TFDQuery; aIsFetchAll: Boolean = True); begin aQuery.Connection := FDConnection; aQuery.Open; if aIsFetchAll then aQuery.FetchAll; end; procedure TDBEngine.SetConnectParams; begin FDConnection.Params.Values['Server'] := FConnectParams.Host; FDConnection.Params.Values['Database'] := FConnectParams.DataBase; FDConnection.Params.Values['User_Name'] := FConnectParams.Login; FDConnection.Params.Values['Password'] := FConnectParams.Password; FDConnection.Params.Values['CharacterSet'] := FConnectParams.CharacterSet; end; procedure TDBEngine.CloseConnection; begin FDConnection.Connected := False; FDConnection.Free; FIsConnected := False; end; destructor TDBEngine.Destroy; begin if FIsConnected then CloseConnection; inherited; end; procedure TDBEngine.OpenConnection; begin FDConnection := TFDConnection.Create(nil); SetConnectParams; FDConnection.LoginPrompt := False; FDConnection.ResourceOptions.SilentMode := True; FDConnection.Connected := True; FIsConnected := True; end; end.
{ ************************************************************ } { } { XML Data Binding } { } { Generated on: 2015-02-10 21:10:38 } { Generated from: C:\Users\admin\Downloads\fr\fr.xml } { Settings stored in: C:\Users\admin\Downloads\fr\fr.xdb } { } { ************************************************************ } unit uTVDBBind; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLTVDBDataType = interface; IXMLTVDBSeriesType = interface; IXMLTVDBSeriesTypeList = interface; IXMLTVDBEpisodeType = interface; IXMLTVDBEpisodeTypeList = interface; { IXMLTVDBDataType } IXMLTVDBDataType = interface(IXMLNode) ['{23D9F943-4538-4FA2-B097-1DC7BC6BA33B}'] { Property Accessors } function GetSeries: IXMLTVDBSeriesTypeList; function GetEpisode: IXMLTVDBEpisodeTypeList; { Methods & Properties } property Series: IXMLTVDBSeriesTypeList read GetSeries; property Episode: IXMLTVDBEpisodeTypeList read GetEpisode; end; { IXMLTVDBSeriesType } IXMLTVDBSeriesType = interface(IXMLNode) ['{ACEC8900-E7D3-4DFE-8426-35EA2DAC8136}'] { Property Accessors } function GetId: Integer; function GetActors: UnicodeString; function GetAirs_DayOfWeek: UnicodeString; function GetAirs_Time: TTime; function GetContentRating: UnicodeString; function GetFirstAired: UnicodeString; function GetGenre: UnicodeString; function GetIMDB_ID: UnicodeString; function GetLanguage: UnicodeString; function GetNetwork: UnicodeString; function GetNetworkID: UnicodeString; function GetOverview: UnicodeString; function GetRating: double; function GetRatingCount: Integer; function GetRuntime: Integer; function GetSeriesID: UnicodeString; function GetSeriesName: UnicodeString; function GetStatus: UnicodeString; function GetAdded: TDateTime; function GetAddedBy: Integer; function GetBanner: UnicodeString; function GetFanart: UnicodeString; function GetLastupdated: Integer; function GetPoster: UnicodeString; function GetTms_wanted_old: Integer; function GetZap2it_id: Integer; { Methods & Properties } property Id: Integer read GetId; property Actors: UnicodeString read GetActors; property Airs_DayOfWeek: UnicodeString read GetAirs_DayOfWeek; property Airs_Time: TTime read GetAirs_Time; property ContentRating: UnicodeString read GetContentRating; property FirstAired: UnicodeString read GetFirstAired; property Genre: UnicodeString read GetGenre; property IMDB_ID: UnicodeString read GetIMDB_ID; property Language: UnicodeString read GetLanguage; property Network: UnicodeString read GetNetwork; property NetworkID: UnicodeString read GetNetworkID; property Overview: UnicodeString read GetOverview; property Rating: double read GetRating; property RatingCount: Integer read GetRatingCount; property Runtime: Integer read GetRuntime; property SeriesID: UnicodeString read GetSeriesID; property SeriesName: UnicodeString read GetSeriesName; property Status: UnicodeString read GetStatus; property Added: TDateTime read GetAdded; property AddedBy: Integer read GetAddedBy; property Banner: UnicodeString read GetBanner; property Fanart: UnicodeString read GetFanart; property Lastupdated: Integer read GetLastupdated; property Poster: UnicodeString read GetPoster; property Tms_wanted_old: Integer read GetTms_wanted_old; property Zap2it_id: Integer read GetZap2it_id; end; { IXMLTVDBSeriesTypeList } IXMLTVDBSeriesTypeList = interface(IXMLNodeCollection) ['{70B9DDDD-FF14-4624-BCB0-D0D737C8A4C3}'] { Methods & Properties } function Add: IXMLTVDBSeriesType; function Insert(const Index: Integer): IXMLTVDBSeriesType; function GetItem(Index: Integer): IXMLTVDBSeriesType; property Items[Index: Integer]: IXMLTVDBSeriesType read GetItem; default; end; { IXMLTVDBEpisodeType } IXMLTVDBEpisodeType = interface(IXMLNode) ['{61379FC9-68AA-4E95-A6FA-31438B2E2C61}'] { Property Accessors } function GetId: Integer; function GetCombined_episodenumber: Integer; function GetCombined_season: Integer; function GetDVD_chapter: UnicodeString; function GetDVD_discid: UnicodeString; function GetDVD_episodenumber: UnicodeString; function GetDVD_season: UnicodeString; function GetDirector: UnicodeString; function GetEpImgFlag: UnicodeString; function GetEpisodeName: UnicodeString; function GetEpisodeNumber: UnicodeString; function GetFirstAired: UnicodeString; function GetGuestStars: UnicodeString; function GetIMDB_ID: UnicodeString; function GetLanguage: UnicodeString; function GetOverview: UnicodeString; function GetProductionCode: UnicodeString; function GetRating: double; function GetRatingCount: Integer; function GetSeasonNumber: UnicodeString; function GetWriter: UnicodeString; function GetAbsolute_number: UnicodeString; function GetAirsafter_season: UnicodeString; function GetAirsbefore_episode: UnicodeString; function GetAirsbefore_season: UnicodeString; function GetFilename: UnicodeString; function GetLastupdated: Integer; function GetSeasonid: Integer; function GetSeriesID: Integer; function GetThumb_added: UnicodeString; function GetThumb_height: UnicodeString; function GetThumb_width: UnicodeString; { Methods & Properties } property Id: Integer read GetId; property Combined_episodenumber: Integer read GetCombined_episodenumber; property Combined_season: Integer read GetCombined_season; property DVD_chapter: UnicodeString read GetDVD_chapter; property DVD_discid: UnicodeString read GetDVD_discid; property DVD_episodenumber: UnicodeString read GetDVD_episodenumber; property DVD_season: UnicodeString read GetDVD_season; property Director: UnicodeString read GetDirector; property EpImgFlag: UnicodeString read GetEpImgFlag; property EpisodeName: UnicodeString read GetEpisodeName; property EpisodeNumber: UnicodeString read GetEpisodeNumber; property FirstAired: UnicodeString read GetFirstAired; property GuestStars: UnicodeString read GetGuestStars; property IMDB_ID: UnicodeString read GetIMDB_ID; property Language: UnicodeString read GetLanguage; property Overview: UnicodeString read GetOverview; property ProductionCode: UnicodeString read GetProductionCode; property Rating: double read GetRating; property RatingCount: Integer read GetRatingCount; property SeasonNumber: UnicodeString read GetSeasonNumber; property Writer: UnicodeString read GetWriter; property Absolute_number: UnicodeString read GetAbsolute_number; property Airsafter_season: UnicodeString read GetAirsafter_season; property Airsbefore_episode: UnicodeString read GetAirsbefore_episode; property Airsbefore_season: UnicodeString read GetAirsbefore_season; property Filename: UnicodeString read GetFilename; property Lastupdated: Integer read GetLastupdated; property Seasonid: Integer read GetSeasonid; property SeriesID: Integer read GetSeriesID; property Thumb_added: UnicodeString read GetThumb_added; property Thumb_height: UnicodeString read GetThumb_height; property Thumb_width: UnicodeString read GetThumb_width; end; { IXMLTVDBEpisodeTypeList } IXMLTVDBEpisodeTypeList = interface(IXMLNodeCollection) ['{7DE8BC0B-0C2E-434D-823F-7E3E798C004F}'] { Methods & Properties } function Add: IXMLTVDBEpisodeType; function Insert(const Index: Integer): IXMLTVDBEpisodeType; function GetItem(Index: Integer): IXMLTVDBEpisodeType; property Items[Index: Integer]: IXMLTVDBEpisodeType read GetItem; default; end; { Forward Decls } TXMLTVDBDataType = class; TXMLTVDBSeriesType = class; TXMLTVDBSeriesTypeList = class; TXMLTVDBEpisodeType = class; TXMLTVDBEpisodeTypeList = class; { TXMLTVDBDataType } TXMLTVDBDataType = class(TXMLNode, IXMLTVDBDataType) private FSeries: IXMLTVDBSeriesTypeList; FEpisode: IXMLTVDBEpisodeTypeList; protected { IXMLTVDBDataType } function GetSeries: IXMLTVDBSeriesTypeList; function GetEpisode: IXMLTVDBEpisodeTypeList; public procedure AfterConstruction; override; end; { TXMLTVDBSeriesType } TXMLTVDBSeriesType = class(TXMLNode, IXMLTVDBSeriesType) protected { IXMLTVDBSeriesType } function GetId: Integer; function GetActors: UnicodeString; function GetAirs_DayOfWeek: UnicodeString; function GetAirs_Time: TTime; function GetContentRating: UnicodeString; function GetFirstAired: UnicodeString; function GetGenre: UnicodeString; function GetIMDB_ID: UnicodeString; function GetLanguage: UnicodeString; function GetNetwork: UnicodeString; function GetNetworkID: UnicodeString; function GetOverview: UnicodeString; function GetRating: double; function GetRatingCount: Integer; function GetRuntime: Integer; function GetSeriesID: UnicodeString; function GetSeriesName: UnicodeString; function GetStatus: UnicodeString; function GetAdded: TDateTime; function GetAddedBy: Integer; function GetBanner: UnicodeString; function GetFanart: UnicodeString; function GetLastupdated: Integer; function GetPoster: UnicodeString; function GetTms_wanted_old: Integer; function GetZap2it_id: Integer; end; { TXMLTVDBSeriesTypeList } TXMLTVDBSeriesTypeList = class(TXMLNodeCollection, IXMLTVDBSeriesTypeList) protected { IXMLTVDBSeriesTypeList } function Add: IXMLTVDBSeriesType; function Insert(const Index: Integer): IXMLTVDBSeriesType; function GetItem(Index: Integer): IXMLTVDBSeriesType; end; { TXMLTVDBEpisodeType } TXMLTVDBEpisodeType = class(TXMLNode, IXMLTVDBEpisodeType) protected { IXMLTVDBEpisodeType } function GetId: Integer; function GetCombined_episodenumber: Integer; function GetCombined_season: Integer; function GetDVD_chapter: UnicodeString; function GetDVD_discid: UnicodeString; function GetDVD_episodenumber: UnicodeString; function GetDVD_season: UnicodeString; function GetDirector: UnicodeString; function GetEpImgFlag: UnicodeString; function GetEpisodeName: UnicodeString; function GetEpisodeNumber: UnicodeString; function GetFirstAired: UnicodeString; function GetGuestStars: UnicodeString; function GetIMDB_ID: UnicodeString; function GetLanguage: UnicodeString; function GetOverview: UnicodeString; function GetProductionCode: UnicodeString; function GetRating: double; function GetRatingCount: Integer; function GetSeasonNumber: UnicodeString; function GetWriter: UnicodeString; function GetAbsolute_number: UnicodeString; function GetAirsafter_season: UnicodeString; function GetAirsbefore_episode: UnicodeString; function GetAirsbefore_season: UnicodeString; function GetFilename: UnicodeString; function GetLastupdated: Integer; function GetSeasonid: Integer; function GetSeriesID: Integer; function GetThumb_added: UnicodeString; function GetThumb_height: UnicodeString; function GetThumb_width: UnicodeString; end; { TXMLTVDBEpisodeTypeList } TXMLTVDBEpisodeTypeList = class(TXMLNodeCollection, IXMLTVDBEpisodeTypeList) protected { IXMLTVDBEpisodeTypeList } function Add: IXMLTVDBEpisodeType; function Insert(const Index: Integer): IXMLTVDBEpisodeType; function GetItem(Index: Integer): IXMLTVDBEpisodeType; end; { Global Functions } function GetData(Doc: IXMLDocument): IXMLTVDBDataType; function LoadData(const Filename: string): IXMLTVDBDataType; function NewData: IXMLTVDBDataType; const TargetNamespace = ''; implementation uses System.Variants; { Global Functions } function GetData(Doc: IXMLDocument): IXMLTVDBDataType; begin Result := Doc.GetDocBinding('Data', TXMLTVDBDataType, TargetNamespace) as IXMLTVDBDataType; end; function LoadData(const Filename: string): IXMLTVDBDataType; begin Result := LoadXMLDocument(Filename).GetDocBinding('Data', TXMLTVDBDataType, TargetNamespace) as IXMLTVDBDataType; end; function NewData: IXMLTVDBDataType; begin Result := NewXMLDocument.GetDocBinding('Data', TXMLTVDBDataType, TargetNamespace) as IXMLTVDBDataType; end; { TXMLTVDBDataType } procedure TXMLTVDBDataType.AfterConstruction; begin RegisterChildNode('Series', TXMLTVDBSeriesType); RegisterChildNode('Episode', TXMLTVDBEpisodeType); FSeries := CreateCollection(TXMLTVDBSeriesTypeList, IXMLTVDBSeriesType, 'Series') as IXMLTVDBSeriesTypeList; FEpisode := CreateCollection(TXMLTVDBEpisodeTypeList, IXMLTVDBEpisodeType, 'Episode') as IXMLTVDBEpisodeTypeList; inherited; end; function TXMLTVDBDataType.GetSeries: IXMLTVDBSeriesTypeList; begin Result := FSeries; end; function TXMLTVDBDataType.GetEpisode: IXMLTVDBEpisodeTypeList; begin Result := FEpisode; end; { TXMLTVDBSeriesType } function TXMLTVDBSeriesType.GetId: Integer; begin Result := ChildNodes['id'].NodeValue; end; function TXMLTVDBSeriesType.GetActors: UnicodeString; begin Result := ChildNodes['Actors'].Text; end; function TXMLTVDBSeriesType.GetAirs_DayOfWeek: UnicodeString; begin Result := ChildNodes['Airs_DayOfWeek'].Text; end; function TXMLTVDBSeriesType.GetAirs_Time: TTime; begin Result := ChildNodes['Airs_Time'].NodeValue; end; function TXMLTVDBSeriesType.GetContentRating: UnicodeString; begin Result := ChildNodes['ContentRating'].Text; end; function TXMLTVDBSeriesType.GetFirstAired: UnicodeString; begin Result := ChildNodes['FirstAired'].Text; end; function TXMLTVDBSeriesType.GetGenre: UnicodeString; begin Result := ChildNodes['Genre'].Text; end; function TXMLTVDBSeriesType.GetIMDB_ID: UnicodeString; begin Result := ChildNodes['IMDB_ID'].Text; end; function TXMLTVDBSeriesType.GetLanguage: UnicodeString; begin Result := ChildNodes['Language'].Text; end; function TXMLTVDBSeriesType.GetNetwork: UnicodeString; begin Result := ChildNodes['Network'].Text; end; function TXMLTVDBSeriesType.GetNetworkID: UnicodeString; begin Result := ChildNodes['NetworkID'].Text; end; function TXMLTVDBSeriesType.GetOverview: UnicodeString; begin Result := ChildNodes['Overview'].Text; end; function TXMLTVDBSeriesType.GetRating: double; begin Result := ChildNodes['Rating'].NodeValue; end; function TXMLTVDBSeriesType.GetRatingCount: Integer; begin Result := ChildNodes['RatingCount'].NodeValue; end; function TXMLTVDBSeriesType.GetRuntime: Integer; begin Result := ChildNodes['Runtime'].NodeValue; end; function TXMLTVDBSeriesType.GetSeriesID: UnicodeString; begin if Assigned(ChildNodes['seriesid']) then Result := ChildNodes['seriesid'].Text else Result := ChildNodes['SeriesID'].Text; end; function TXMLTVDBSeriesType.GetSeriesName: UnicodeString; begin Result := ChildNodes['SeriesName'].Text; end; function TXMLTVDBSeriesType.GetStatus: UnicodeString; begin Result := ChildNodes['Status'].Text; end; function TXMLTVDBSeriesType.GetAdded: TDateTime; begin Result := ChildNodes['added'].NodeValue; end; function TXMLTVDBSeriesType.GetAddedBy: Integer; begin Result := ChildNodes['addedBy'].NodeValue; end; function TXMLTVDBSeriesType.GetBanner: UnicodeString; begin Result := ChildNodes['banner'].Text; end; function TXMLTVDBSeriesType.GetFanart: UnicodeString; begin Result := ChildNodes['fanart'].Text; end; function TXMLTVDBSeriesType.GetLastupdated: Integer; begin Result := ChildNodes['lastupdated'].NodeValue; end; function TXMLTVDBSeriesType.GetPoster: UnicodeString; begin Result := ChildNodes['poster'].Text; end; function TXMLTVDBSeriesType.GetTms_wanted_old: Integer; begin Result := ChildNodes['tms_wanted_old'].NodeValue; end; function TXMLTVDBSeriesType.GetZap2it_id: Integer; begin Result := ChildNodes['zap2it_id'].NodeValue; end; { TXMLTVDBSeriesTypeList } function TXMLTVDBSeriesTypeList.Add: IXMLTVDBSeriesType; begin Result := AddItem(-1) as IXMLTVDBSeriesType; end; function TXMLTVDBSeriesTypeList.Insert(const Index: Integer): IXMLTVDBSeriesType; begin Result := AddItem(Index) as IXMLTVDBSeriesType; end; function TXMLTVDBSeriesTypeList.GetItem(Index: Integer): IXMLTVDBSeriesType; begin Result := List[Index] as IXMLTVDBSeriesType; end; { TXMLTVDBEpisodeType } function TXMLTVDBEpisodeType.GetId: Integer; begin Result := ChildNodes['id'].NodeValue; end; function TXMLTVDBEpisodeType.GetCombined_episodenumber: Integer; begin Result := ChildNodes['Combined_episodenumber'].NodeValue; end; function TXMLTVDBEpisodeType.GetCombined_season: Integer; begin Result := ChildNodes['Combined_season'].NodeValue; end; function TXMLTVDBEpisodeType.GetDVD_chapter: UnicodeString; begin Result := ChildNodes['DVD_chapter'].Text; end; function TXMLTVDBEpisodeType.GetDVD_discid: UnicodeString; begin Result := ChildNodes['DVD_discid'].Text; end; function TXMLTVDBEpisodeType.GetDVD_episodenumber: UnicodeString; begin Result := ChildNodes['DVD_episodenumber'].Text; end; function TXMLTVDBEpisodeType.GetDVD_season: UnicodeString; begin Result := ChildNodes['DVD_season'].Text; end; function TXMLTVDBEpisodeType.GetDirector: UnicodeString; begin Result := ChildNodes['Director'].Text; end; function TXMLTVDBEpisodeType.GetEpImgFlag: UnicodeString; begin Result := ChildNodes['EpImgFlag'].Text; end; function TXMLTVDBEpisodeType.GetEpisodeName: UnicodeString; begin Result := ChildNodes['EpisodeName'].Text; end; function TXMLTVDBEpisodeType.GetEpisodeNumber: UnicodeString; begin Result := ChildNodes['EpisodeNumber'].Text; end; function TXMLTVDBEpisodeType.GetFirstAired: UnicodeString; begin Result := ChildNodes['FirstAired'].Text; end; function TXMLTVDBEpisodeType.GetGuestStars: UnicodeString; begin Result := ChildNodes['GuestStars'].Text; end; function TXMLTVDBEpisodeType.GetIMDB_ID: UnicodeString; begin Result := ChildNodes['IMDB_ID'].Text; end; function TXMLTVDBEpisodeType.GetLanguage: UnicodeString; begin Result := ChildNodes['Language'].Text; end; function TXMLTVDBEpisodeType.GetOverview: UnicodeString; begin Result := ChildNodes['Overview'].Text; end; function TXMLTVDBEpisodeType.GetProductionCode: UnicodeString; begin Result := ChildNodes['ProductionCode'].Text; end; function TXMLTVDBEpisodeType.GetRating: double; begin Result := ChildNodes['Rating'].NodeValue; end; function TXMLTVDBEpisodeType.GetRatingCount: Integer; begin Result := ChildNodes['RatingCount'].NodeValue; end; function TXMLTVDBEpisodeType.GetSeasonNumber: UnicodeString; begin Result := ChildNodes['SeasonNumber'].Text; end; function TXMLTVDBEpisodeType.GetWriter: UnicodeString; begin Result := ChildNodes['Writer'].Text; end; function TXMLTVDBEpisodeType.GetAbsolute_number: UnicodeString; begin Result := ChildNodes['absolute_number'].Text; end; function TXMLTVDBEpisodeType.GetAirsafter_season: UnicodeString; begin Result := ChildNodes['airsafter_season'].Text; end; function TXMLTVDBEpisodeType.GetAirsbefore_episode: UnicodeString; begin Result := ChildNodes['airsbefore_episode'].Text; end; function TXMLTVDBEpisodeType.GetAirsbefore_season: UnicodeString; begin Result := ChildNodes['airsbefore_season'].Text; end; function TXMLTVDBEpisodeType.GetFilename: UnicodeString; begin Result := ChildNodes['filename'].Text; end; function TXMLTVDBEpisodeType.GetLastupdated: Integer; begin Result := ChildNodes['lastupdated'].NodeValue; end; function TXMLTVDBEpisodeType.GetSeasonid: Integer; begin Result := ChildNodes['seasonid'].NodeValue; end; function TXMLTVDBEpisodeType.GetSeriesID: Integer; begin Result := ChildNodes['seriesid'].NodeValue; end; function TXMLTVDBEpisodeType.GetThumb_added: UnicodeString; begin Result := ChildNodes['thumb_added'].Text; end; function TXMLTVDBEpisodeType.GetThumb_height: UnicodeString; begin Result := ChildNodes['thumb_height'].Text; end; function TXMLTVDBEpisodeType.GetThumb_width: UnicodeString; begin Result := ChildNodes['thumb_width'].Text; end; { TXMLTVDBEpisodeTypeList } function TXMLTVDBEpisodeTypeList.Add: IXMLTVDBEpisodeType; begin Result := AddItem(-1) as IXMLTVDBEpisodeType; end; function TXMLTVDBEpisodeTypeList.Insert(const Index: Integer): IXMLTVDBEpisodeType; begin Result := AddItem(Index) as IXMLTVDBEpisodeType; end; function TXMLTVDBEpisodeTypeList.GetItem(Index: Integer): IXMLTVDBEpisodeType; begin Result := List[Index] as IXMLTVDBEpisodeType; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ActnList, Menus, StdCtrls, MixiPageObserver, Settings; const SAVE_FILE = 'pages.txt'; type TForm1 = class(TForm) TrayIcon1: TTrayIcon; PopupMenu1: TPopupMenu; MenuClose: TMenuItem; ActionList1: TActionList; CloseForm: TAction; ShowForm: TAction; ListBox1: TListBox; Initialize: TAction; Finalize: TAction; CheckUpdates: TAction; MenuCheckUpdates: TMenuItem; Timer1: TTimer; procedure CloseFormExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ShowFormExecute(Sender: TObject); procedure InitializeExecute(Sender: TObject); procedure FinalizeExecute(Sender: TObject); procedure CheckUpdatesExecute(Sender: TObject); private FObserver: TMixiPageObserver; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.CheckUpdatesExecute(Sender: TObject); var i: Integer; updates: TObserveUpdates; begin FObserver.Synchronize; ListBox1.Clear; if FObserver.Updates.Count = 0 then begin ListBox1.Items.Add('更新はありません'); end else begin for i := 0 to FObserver.Updates.Count - 1 do begin updates := TObserveUpdates(FObserver.Updates[i]); ListBox1.Items.Add(updates.Message); end; end; Self.ClientWidth := ListBox1.Width; Self.ClientHeight := Listbox1.Height; ShowForm.Execute; end; procedure TForm1.CloseFormExecute(Sender: TObject); begin Application.Terminate; end; procedure TForm1.FinalizeExecute(Sender: TObject); begin FObserver.Free; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if Sender = Self then begin CanClose := False; Self.Hide; Exit; end; end; procedure TForm1.InitializeExecute(Sender: TObject); var i, pageId: Integer; SL: TStringList; begin FObserver := TMixiPageObserver.Create(CONSUMER_KEY, CONSUMER_SECRET); SL := TStringList.Create; try SL.LoadFromFile(SAVE_FILE); for i := 0 to SL.Count - 1 do begin pageId := StrToIntDef(SL[i], 0); if pageId = 0 then Continue; FObserver.AddObserve(pageId); end; finally SL.Free; end; FObserver.Synchronize; end; procedure TForm1.ShowFormExecute(Sender: TObject); var rect: TRect; begin SystemParametersInfo(SPI_GETWORKAREA, 0, @rect, 0); Self.Show; Self.Left := rect.Right - Self.Width; Self.Top := rect.Bottom - Self.Height; end; end.
unit uDaoAlunoPreVenda; interface uses uClassConexao,uClassAlunoPreVenda, ADODB,DBClient,Classes,SysUtils; type TDaoAlunoPreVenda = class private FConexao : TConexao; public constructor Create( Conexao : TConexao ); procedure Incluir( AlunoPreVenda : TAlunoPreVenda ); procedure Excluir(AlunoPreVenda : TAlunoPrevenda); function BuscarPorPreVenda(IdPreVenda : Integer) : TClientDataSet; end; implementation { TDaoAlunoPreVenda } function TDaoAlunoPreVenda.BuscarPorPreVenda( IdPreVenda: Integer): TClientDataSet; var Parametros : TStringList; begin Parametros := TStringList.Create; try Result := FConexao.BuscarDadosAdo('Select PreVenda.*, Aluno.Descricao '+ 'from AlunosPreVenda PreVenda, T_Alunos Aluno '+ 'where Aluno.Codigo=PreVenda.IdAluno and IdPreVenda='+IntToStr(idPreVenda),Parametros); finally FreeAndNil(Parametros); end; end; constructor TDaoAlunoPreVenda.Create(Conexao: TConexao); begin Fconexao := Conexao; end; procedure TDaoAlunoPreVenda.Excluir(AlunoPreVenda: TAlunoPrevenda); begin FConexao.adoConection.Execute('delete from AlunosPrevenda where IdPrevenda='+IntToStr(AlunoPrevenda.IdPreVenda)+' and IdAluno='+IntToStr(AlunoPrevenda.IdAluno)); end; procedure TDaoAlunoPreVenda.Incluir(AlunoPreVenda: TAlunoPreVenda); var qryInclusao : TadoQuery; begin qryInclusao := TadoQuery.Create(nil); qryInclusao.Connection := fConexao.adoConection; qryInclusao.SQL.Text := 'Insert Into AlunosPreVenda ( IdPreVenda,IdAluno,IDProduto,Quantidade ) Values ' + ' ( :parIdPreVenda,:parIdAluno,:parIDProduto,:parQuantidade )'; qryInclusao.Parameters.ParamValues['parIdPrevenda'] := AlunoPreVenda.IdPreVenda; qryInclusao.Parameters.ParamValues['parIDProduto'] := AlunoPreVenda.IdProduto; qryInclusao.Parameters.ParamValues['parIdAluno'] := AlunoPreVenda.IdAluno; qryInclusao.Parameters.ParamValues['parQuantidade'] := AlunoPreVenda.Quantidade; qryInclusao.ExecSQL; end; end.
unit ModflowGAG_WriterUnit; interface uses SysUtils, Classes, CustomModflowWriterUnit, ModflowSfrWriterUnit; type TModflowGAG_Writer = class(TCustomModflowWriter) private FSfrWriter: TModflowSFR_Writer; FNameOfFile: string; procedure Evaluate(Gages: TStrings); protected class function Extension: string; override; public procedure WriteFile(const AFileName: string; Gages: TStrings; SfrWriter: TModflowSFR_Writer); end; implementation uses Contnrs , RbwParser, GoPhastTypes, ModflowCellUnit, ModflowUnitNumbers, frmProgressUnit, DataSetUnit, frmGoPhastUnit, ScreenObjectUnit, SubscriptionUnit; resourcestring StrWritingGAGEPackage = 'Writing GAGE Package input.'; { TModflowGAG_Writer } procedure TModflowGAG_Writer.Evaluate(Gages: TStrings); var Index: Integer; List: TList; DataArray: TDataArray; ScreenObject: TScreenObject; Segment: TSegment; ReachIndex: Integer; Reach: TValueCell; DataArray0: TDataArray; DataArray1: TDataArray; DataArray2: TDataArray; DataArray3: TDataArray; DataArray5: TDataArray; DataArray6: TDataArray; DataArray7: TDataArray; GAGESEG: Integer; GAGERCH: Integer; SubSegIndex: Integer; SubSeg: TSubSegment; procedure WriteGage(OUTTYPE: integer); var UNIT_Number: Integer; Line: string; OutputName: string; begin UNIT_Number := Model.ParentModel.UnitNumbers.SequentialUnitNumber; Line := IntToStr(GAGESEG) + ' ' + IntToStr(GAGERCH) + ' ' + IntToStr(UNIT_Number) + ' ' + IntToStr(OUTTYPE); Gages.Add(Line); // Inc(StartUnitNumber); OutputName := ChangeFileExt(FNameOfFile, '.sfrg'); OutputName := OutputName + IntToStr(Gages.Count); WriteToNameFile(StrDATA, UNIT_Number, OutputName, foOutput, Model); end; procedure WriteReach; begin if DataArray0.BooleanData[Reach.Layer, Reach.Row, Reach.Column] and DataArray1.BooleanData[Reach.Layer, Reach.Row, Reach.Column] and DataArray2.BooleanData[Reach.Layer, Reach.Row, Reach.Column] and DataArray3.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(4); end else begin if DataArray0.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(0); end; if DataArray1.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(1); end; if DataArray2.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(2); end; if DataArray3.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(3); end; end; if DataArray5.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(5); end; if DataArray6.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(6); end; if DataArray7.BooleanData[Reach.Layer, Reach.Row, Reach.Column] then begin WriteGage(7); end; end; begin if (Model.ModflowPackages = nil) or (Model.ModflowPackages.SfrPackage = nil) or not Model.ModflowPackages.SfrPackage.IsSelected then begin Exit; end; if Model.ModflowPackages.SfrPackage.GageOverallBudget then begin GAGESEG := 1; GAGERCH := 1; WriteGage(8); end; List := TObjectList.Create; try for Index := 1 to 7 do begin DataArray := TDataArray.Create(Model); List.Add(DataArray); DataArray.Orientation := dso3D; DataArray.EvaluatedAt := eaBlocks; DataArray.DataType := rdtBoolean; DataArray.UpdateDimensions(Model.Grid.LayerCount, Model.Grid.RowCount, Model.Grid.ColumnCount, True); end; for Index := 0 to Model.ScreenObjectCount - 1 do begin ScreenObject := Model.ScreenObjects[Index]; if (ScreenObject.ModflowStreamGage <> nil) and ScreenObject.ModflowStreamGage.Used then begin ScreenObject.ModflowStreamGage.Evaluate(List, Model); end; end; for Index := 0 to List.Count - 1 do begin DataArray := List[Index]; DataArray.UpToDate := True; end; DataArray0 := List[0]; DataArray1 := List[1]; DataArray2 := List[2]; DataArray3 := List[3]; DataArray5 := List[4]; DataArray6 := List[5]; DataArray7 := List[6]; for Index := 0 to FSfrWriter.SegmentCount - 1 do begin Segment := FSfrWriter.Segments[Index]; GAGESEG := Segment.NewSegmentNumber; if Segment.SubSegmentList.Count = 0 then begin for ReachIndex := 0 to Segment.ReachCount - 1 do begin GAGERCH := ReachIndex + 1; Reach := Segment.Reaches[ReachIndex]; WriteReach; end; end else begin for SubSegIndex := 0 to Segment.SubSegmentList.Count - 1 do begin SubSeg := Segment.SubSegmentList[SubSegIndex]; GAGESEG := SubSeg.SegmentNumber; for ReachIndex := 0 to SubSeg.ReachCount - 1 do begin GAGERCH := ReachIndex + 1; Reach := SubSeg.Reaches[ReachIndex]; WriteReach; end; end; end; end; finally List.Free; end; end; class function TModflowGAG_Writer.Extension: string; begin result := '.gag'; end; procedure TModflowGAG_Writer.WriteFile(const AFileName: string; Gages: TStrings; SfrWriter: TModflowSFR_Writer); var NUMGAGES: integer; begin if Model.PackageGeneratedExternally(StrGAG) then begin Exit; end; FSfrWriter := SfrWriter; FNameOfFile := FileName(AFileName); Evaluate(Gages); if Gages.Count > 0 then begin frmProgressMM.AddMessage(StrWritingGAGEPackage); NUMGAGES := Gages.Count; Gages.Insert(0, IntToStr(NUMGAGES)); WriteToNameFile(StrGAG, Model.UnitNumbers.UnitNumber(StrGAG), FNameOfFile, foInput, Model); Gages.SaveToFile(FNameOfFile); end; end; end.
unit ufrmDialogPrintPreview; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls, DB, frxClass, frxPreview, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMemo; type TfrmDialogPrintPreview = class(TfrmMasterDialog) pnlTop: TPanel; dlgSaveFile: TSaveDialog; mmoPreview: TcxMemo; fpwPreview: TfrxPreview; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSaveClick(Sender: TObject); private FFilePath: string; FListParams: TStringList; FRecordSet: TDataSet; FIsTextReport: Boolean; FMainSQL: string; FSecondarySQL: string; FTextReportFile: string; procedure LoadDataPrintPreview; procedure SetFilePath(const Value: string); procedure SetListParams(const Value: TStringList); procedure SetRecordSet(const Value: TDataSet); public IsReportLama: Boolean; function IsBisaDesignReport: Boolean; procedure ShowReport(aReportFile : String; aMainSQL : String; aSecondarySQL : String; aIsTextReport : Boolean = False); property FilePath: string read FFilePath write SetFilePath; property IsTextReport: Boolean read FIsTextReport write FIsTextReport; property ListParams: TStringList read FListParams write SetListParams; property MainSQL: string read FMainSQL write FMainSQL; property RecordSet: TDataSet read FRecordSet write SetRecordSet; property SecondarySQL: string read FSecondarySQL write FSecondarySQL; property TextReportFile: string read FTextReportFile write FTextReportFile; end; const DEFAULT_HEIGHT = 640; DEFAULT_WIDTH = 800; var frmDialogPrintPreview: TfrmDialogPrintPreview; implementation uses uRetnounit, frxDBSet, uTSCommonDlg, TypInfo; {$R *.dfm} procedure TfrmDialogPrintPreview.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; IsReportLama := True; Action := caFree; end; procedure TfrmDialogPrintPreview.FormDestroy(Sender: TObject); begin inherited; frmDialogPrintPreview := nil; end; procedure TfrmDialogPrintPreview.LoadDataPrintPreview; begin {with dmReport do begin Params := ListParams; frxDBDataset.DataSet := RecordSet; pMainReport.LoadFromFile(FilePath); pMainReport.PrepareReport; pMainReport.Preview := fpwPreview; end; if IsTextReport then begin with dmReport do begin //frxeText.ShowDialog := False; frxeText.EmptyLines := True; frxeText.PrintAfter := False; frxeText.LeadSpaces := False; TextReportFile := StringReplace(FilePath,ExtractFileExt(FilePath),'.txt',[rfReplaceAll]); frxeText.FileName := TextReportFile; pMainReport.Export(frxeText); end; mmoPreview.Clear; mmoPreview.Lines.LoadFromFile(TextReportFile); fpwPreview.Visible := False; mmoPreview.Visible := True; Exit; end; mmoPreview.Visible := False; fpwPreview.Visible := True; with dmReport do begin Params := ListParams; frxDBDataset.DataSet := RecordSet; pMainReport.LoadFromFile(FilePath); pMainReport.PrepareReport; pMainReport.Preview := fpwPreview; Self.Show; pMainReport.ShowReport; end; } end; procedure TfrmDialogPrintPreview.SetFilePath(const Value: string); begin FFilePath := Value; end; procedure TfrmDialogPrintPreview.SetListParams(const Value: TStringList); begin FListParams := Value; end; procedure TfrmDialogPrintPreview.SetRecordSet(const Value: TDataSet); begin FRecordSet := Value; end; procedure TfrmDialogPrintPreview.FormShow(Sender: TObject); begin inherited; if IsReportLama then begin frmDialogPrintPreview.Height := DEFAULT_HEIGHT; frmDialogPrintPreview.Width := DEFAULT_WIDTH; LoadDataPrintPreview; end; end; procedure TfrmDialogPrintPreview.btnSaveClick(Sender: TObject); begin inherited; { if savetoexcel then with dmReport do begin pMainReport.Export(frxmlxprt1); end else if savetofile then begin dlgSaveFile.InitialDir := ExtractFilePath(Application.ExeName); if dlgSaveFile.Execute then begin with dmReport do begin frxeText.PrintAfter := False; frxeText.ShowDialog := False; frxeText.OEMCodepage := True; if dlgSaveFile.FilterIndex = 1 then frxeText.FileName := dlgSaveFile.FileName + '.txt' else frxeText.FileName := dlgSaveFile.FileName; dmReport.pMainReport.Export(frxeText); end; end; end else if cetaktoprinter then dmReport.pMainReport.Print; } end; function TfrmDialogPrintPreview.IsBisaDesignReport: Boolean; begin Result := True; end; procedure TfrmDialogPrintPreview.ShowReport(aReportFile : String; aMainSQL : String; aSecondarySQL : String; aIsTextReport : Boolean = False); var sReportFile: string; begin IsReportLama := False; sReportFile := GetReportPath + aReportFile+ '.fr3'; { with dmReport do begin Params := TStringList.Create; Params.Clear; frxDBDataset.DataSet := cOpenQuery(aMainSQL); pMainReport.DataSets.Clear; pMainReport.DataSets.Add(frxDBDataset); if not pMainReport.LoadFromFile(sReportFile) then begin pMainReport.FileName := sReportFile; pMainReport.DesignReport; end; if IsBisaDesignReport then begin if (CommonDlg.Confirm('Anda Punya Hak Untuk Mendesain Table' + #13 + 'Apakah Anda Akan Melakukan Desain Laporan?') = mrYES) then begin pMainReport.DesignReport ; Exit; end else begin if aIsTextReport then begin pMainReport.PrepareReport; frxeText.EmptyLines := True; frxeText.PrintAfter := False; frxeText.LeadSpaces := False; TextReportFile := StringReplace(sReportFile,ExtractFileExt(sReportFile),'.txt',[rfReplaceAll]); frxeText.FileName := TextReportFile; pMainReport.Export(frxeText); pMainReport.Preview := fpwPreview; mmoPreview.Clear; mmoPreview.Lines.LoadFromFile(TextReportFile); fpwPreview.Visible := False; mmoPreview.Visible := True; end else begin pMainReport.PrepareReport; fpwPreview.Visible := True; pMainReport.Preview := fpwPreview; pMainReport.ShowReport; pMainReport.Export(frxeText); end; ShowModal; end; end; end; } end; procedure TfrmDialogPrintPreview.FormCreate(Sender: TObject); begin inherited; IsReportLama := True; end; end.