text stringlengths 14 6.51M |
|---|
unit ExternalOperationUnit;
// Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\ExternalOperationUnit.pas"
// Стереотип: "Interfaces"
// Элемент модели: "ExternalOperation" MUID: (45EEA4890342)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, BaseTypesUnit
, BaseTreeSupportUnit
;
const
EOI_ESTIMATION: Cardinal = 1;
{* Оценить ответ }
EOI_PAYMENT_CONFIRM: Cardinal = 2;
{* Подтверждение оплаты }
EOI_PAYMENT_REFUSAL: Cardinal = 3;
{* Оплата отклонена }
EOI_OPEN_ATTRIBUTE_CARD: Cardinal = 4;
EOI_SHOW_HELP_TOPIC: Cardinal = 5;
EOI_CHANGE_COLLAPSED: Cardinal = 6;
EOI_CHECK_LEGAL_ADVISE_AVAILABLE: Cardinal = 7;
EOI_CONSULTATION_CALL_GARANT: Cardinal = 8;
{* Ссылка на www.garant.ru в уведомлении о консалтинге }
EOI_SHOW_CONSULTATION_LIST: Cardinal = 9;
{* показать список к консультации }
EOI_SHOW_LC_HELP: Cardinal = 10;
{* Ссылка на Справка-описание Правового календаря }
EOI_CHANGES_INSIDE_TABLE: Cardinal = 11;
type
IExternalOperation = interface
{* Ссылки на операции }
['{71ECDD4A-0455-4800-BD55-7ECB739949A7}']
function GetId: TObjectId; stdcall;
property Id: TObjectId
read GetId;
end;//IExternalOperation
implementation
uses
l3ImplUses
;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Abbrevia
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* Abbrevia: Abconst.pas 3.05 *}
{*********************************************************}
{* Abbrevia: Constants *}
{*********************************************************}
unit AbConst;
interface
const
AbVersion = '3.05';
Ab_MessageLen = 255;
Ab_CaptionLen = 80;
AB_ZIPPATHDELIM = '/';
const
AbZipVersionNeeded = 1;
AbUnknownCompressionMethod = 2;
AbNoExtractionMethod = 3;
AbInvalidPassword = 4;
AbNoInsertionMethod = 5;
AbInvalidFactor = 6;
AbDuplicateName = 7;
AbUnsupportedCompressionMethod = 8;
AbUserAbort = 9;
AbArchiveBusy = 10;
AbDiskRequest = 11;
AbLastDiskRequest = 12;
AbBadSpanStream = 13;
AbDiskNumRequest = 14;
AbNoOverwriteSpanStream = 15;
AbNoSpannedSelfExtract = 16;
AbBlankDisk = 17;
AbStreamFull = 18;
AbNoSuchDirectory = 19;
AbInflateBlockError = 20;
AbBadStreamType = 21;
AbTruncateError = 22;
AbZipBadCRC = 23;
AbZipBadStub = 24;
AbFileNotFound = 25;
AbInvalidLFH = 26;
AbNoArchive = 27;
AbErrZipInvalid = 28;
AbReadError = 29;
AbInvalidIndex = 30;
AbInvalidThreshold = 31;
AbNthImageRequest = 32;
AbLastImageRequest = 33;
AbImageRequest = 34;
AbUnhandledFileType = 35;
AbSpanningNotSupported = 36;
AbImageNumRequest = 37;
AbLogCreateError = 38;
AbBBSReadTooManyBytes = 40;
AbBBSSeekOutsideBuffer = 41;
AbBBSInvalidOrigin = 42;
AbBBSWriteTooManyBytes = 43;
AbNoCabinetDllError = 50;
AbFCIFileOpenError = 51;
AbFCIFileReadError = 52;
AbFCIFileWriteError = 53;
AbFCIFileCloseError = 54;
AbFCIFileSeekError = 55;
AbFCIFileDeleteError = 56;
AbFCIAddFileError = 57;
AbFCICreateError = 58;
AbFCIFlushCabinetError = 59;
AbFCIFlushFolderError = 60;
AbFDICopyError = 61;
AbFDICreateError = 62;
AbInvalidCabTemplate = 63;
AbInvalidCabFile = 64;
AbSWSNotEndofStream = 80;
AbSWSSeekFailed = 81;
AbSWSWriteFailed = 82;
AbSWSInvalidOrigin = 83;
AbSWSInvalidNewOrigin = 84;
AbVersionFormat = 100;
AbMethod = 101; {base for later ids, don't add to array!}
AbMethod0 = 101;
AbMethod1 = 102;
AbMethod2 = 103;
AbMethod3 = 104;
AbMethod4 = 105;
AbMethod5 = 106;
AbMethod6 = 107;
AbMethod7 = 108;
AbMethod8 = 109;
AbMethod9 = 110;
AbMethod10 = 111;
AbMethod11 = 112;
AbCompressedSizeFormat = 113;
AbUncompressedSizeFormat = 114;
AbCompressionMethodFormat = 115;
AbCompressionRatioFormat = 116;
AbCRCFormat = 117;
AbReadOnly = 118;
AbHidden = 119;
AbSystem = 120;
AbArchived = 121;
AbEFAFormat = 122;
AbIFAFormat = 123;
AbText = 124;
AbBinary = 125;
AbEncryptionFormat = 126;
AbEncrypted = 127;
AbNotEncrypted = 128;
AbUnknown = 129;
AbTimeStampFormat = 130;
AbMadeByFormat = 131;
AbNeededFormat = 132;
AbCommentFormat = 133;
AbDefaultExt = 134;
AbFilter = 135;
AbFileNameTitle = 136;
AbOK = 137;
AbCancel = 138;
AbSelectDirectory = 139;
AbEnterPassword = 140;
AbPassword = 141;
AbVerify = 142;
AbCabExt = 150;
AbCabFilter = 151;
AbLogExt = 152;
AbLogFilter = 153;
AbExeExt = 154;
AbExeFilter = 155;
AbVMSReadTooManyBytes = 200;
AbVMSInvalidOrigin = 201;
AbVMSErrorOpenSwap = 202;
AbVMSSeekFail = 203;
AbVMSReadFail = 204;
AbVMSWriteFail = 205;
AbVMSWriteTooManyBytes = 206;
AbDefColHeadings = 250;
AbItemNameHeading = 250;
AbPackedHeading = 251;
AbMethodHeading = 252;
AbRatioHeading = 253;
AbCRCHeading = 254;
AbFileAttrHeading = 255;
AbFileFormatHeading = 256;
AbEncryptionHeading = 257;
AbTimeStampHeading = 258;
AbFileSizeHeading = 259;
AbVersionMadeHeading = 260;
AbVersionNeededHeading = 261;
AbPathHeading = 262;
AbPartialHeading = 263;
AbExecutableHeading = 264;
AbCabMethod0 = 290;
AbCabMethod1 = 291;
AbLtAdd = 310;
AbLtDelete = 311;
AbLtExtract = 312;
AbLtFreshen = 313;
AbLtMove = 314;
AbLtReplace = 315;
AbLtStart = 316;
AbGZipInvalid = 400;
AbGzipBadCRC = 401;
AbGzipBadFileSize = 402;
AbUnhandledEntity = 513;
resourcestring
AbErrZipInvalidS = 'Invalid file - not a PKZip file';
AbZipVersionNeededS = 'Cannot extract file - newer version required';
AbUnknownCompressionMethodS = 'Cannot extract file - unsupported compression method';
AbNoExtractionMethodS = 'Cannot extract file - no extraction support provided';
AbInvalidPasswordS = 'Cannot extract file - invalid password';
AbNoInsertionMethodS = 'Cannot insert file - no insertion support provided';
AbInvalidFactorS = 'Invalid Reduce Factor';
AbDuplicateNameS = 'Cannot insert file - duplicates stored name';
AbUnsupportedCompressionMethodS = 'Cannot insert file - unsupported compression method';
AbUserAbortS = 'Process aborted by user';
AbArchiveBusyS = 'Archive is busy - cannot process new requests';
AbLastDiskRequestS = 'Insert the last disk in the spanned disk set';
AbDiskRequestS = 'Insert floppy';
AbNthImageRequestS = 'Specify spanned image file # ';
AbLastImageRequestS = 'Specify the last file name in the spanned image set';
AbImageRequestS = 'Image file name';
AbBadSpanStreamS = 'Spanned archives must be opened as file streams';
AbDiskNumRequestS = 'Insert disk number %d of the spanned disk set';
AbImageNumRequestS = 'Insert span number %d of the spanned file set';
AbNoOverwriteSpanStreamS = 'Cannot update an existing spanned disk set';
AbNoSpannedSelfExtractS = 'Cannot make a self-extracting spanned disk set';
AbBlankDiskS = 'Insert a blank floppy disk';
AbStreamFullS = 'Stream write error';
AbNoSuchDirectoryS = 'Directory does not exist';
AbInflateBlockErrorS = 'Cannot inflate block';
AbBadStreamTypeS = 'Invalid Stream';
AbTruncateErrorS = 'Error truncating Zip File';
AbZipBadCRCS = 'Failed CRC Check';
AbZipBadStubS = 'Stub must be an executable';
AbFileNotFoundS = 'File not found';
AbInvalidLFHS = 'Invalid Local File Header entry';
AbNoArchiveS = 'Archive does not exist - Filename is blank';
AbReadErrorS = 'Error reading archive';
AbInvalidIndexS = 'Invalid archive item index';
AbInvalidThresholdS = 'Invalid archive size threshold';
AbUnhandledFileTypeS = 'Unhandled Archive Type';
AbSpanningNotSupportedS = 'Spanning not supported by this Archive type';
AbLogCreateErrorS = 'Error creating Log File';
abMoveFileErrorS = 'Error Moving File %s to %s';
AbNoCabinetDllErrorS = 'Cannot load cabinet.dll';
AbFCIFileOpenErrorS = 'FCI cannot open file';
AbFCIFileReadErrorS = 'FCI cannot read file';
AbFCIFileWriteErrorS = 'FCI cannot write file';
AbFCIFileCloseErrorS = 'FCI close file error';
AbFCIFileSeekErrorS = 'FCI file seek error';
AbFCIFileDeleteErrorS = 'FCI file delete error';
AbFCIAddFileErrorS = 'FCI cannot add file';
AbFCICreateErrorS = 'FCI cannot create context';
AbFCIFlushCabinetErrorS = 'FCI cannot flush cabinet';
AbFCIFlushFolderErrorS = 'FCI cannot flush folder';
AbFDICopyErrorS = 'FDI cannot enumerate files';
AbFDICreateErrorS = 'FDI cannot create context';
AbInvalidCabTemplateS = 'Invalid cab file template';
AbInvalidCabFileS = 'Invalid file - not a cabinet file';
AbMethod0S = 'Stored';
AbMethod1S = 'Shrunk';
AbMethod2S = 'Reduced';
AbMethod3S = 'Reduced';
AbMethod4S = 'Reduced';
AbMethod5S = 'Reduced';
AbMethod6S = 'Imploded';
AbMethod7S = 'Tokenized';
AbMethod8S = 'Deflated';
AbMethod9S = 'Enhanced Deflation';
AbMethod10S = 'DCL Imploded';
AbMethod11S = 'Best Method';
AbVersionFormatS = 'Version %s';
AbCompressedSizeFormatS = 'Compressed Size: %d';
AbUncompressedSizeFormatS = 'Uncompressed Size: %d';
AbCompressionMethodFormatS = 'Compression Method: %s';
AbCompressionRatioFormatS = 'Compression Ratio: %2.0f%%';
AbCRCFormatS = 'CRC: %x';
AbReadOnlyS = 'r';
AbHiddenS = 'h';
AbSystemS = 's';
AbArchivedS = 'a';
AbEFAFormatS = 'External File Attributes: %s';
AbIFAFormatS = 'File Type: %s';
AbTextS = 'Text';
AbBinaryS = 'Binary';
AbEncryptionFormatS = 'Encryption: %s';
AbEncryptedS = 'Encrypted';
AbNotEncryptedS = 'Not Encrypted';
AbUnknownS = 'Unknown';
AbTimeStampFormatS = 'Time Stamp: %s';
AbMadeByFormatS = 'Made by Version: %f';
AbNeededFormatS = 'Version Needed to Extract: %f';
AbCommentFormatS = 'Comment: %s';
AbDefaultExtS = '*.zip';
AbFilterS = 'PKZip Archives (*.zip)|*.zip|Self Extracting Archives (*.exe)|*.exe|All Files (*.*)|*.*';
AbFileNameTitleS = 'Select File Name';
AbOKS = 'OK';
AbCancelS = 'Cancel';
AbSelectDirectoryS = 'Select Directory';
AbEnterPasswordS = 'Enter Password';
AbPasswordS = '&Password';
AbVerifyS = '&Verify';
AbCabExtS = '*.cab';
AbCabFilterS = 'Cabinet Archives (*.cab)|*.CAB|All Files (*.*)|*.*';
AbLogExtS = '*.txt';
AbLogFilterS = 'Text Files (*.txt)|*.TXT|All Files (*.*)|*.*';
AbExeExtS = '*.exe';
AbExeFilterS = 'Self-Extracting Zip Files (*.exe)|*.EXE|All Files (*.*)|*.*';
AbVMSReadTooManyBytesS = 'VMS: request to read too many bytes [%d]';
AbVMSInvalidOriginS = 'VMS: invalid origin %d, should be 0, 1, 2';
AbVMSErrorOpenSwapS = 'VMS: Cannot open swap file %s';
AbVMSSeekFailS = 'VMS: Failed to seek in swap file %s';
AbVMSReadFailS = 'VMS: Failed to read %d bytes from swap file %s';
AbVMSWriteFailS = 'VMS: Failed to write %d bytes to swap file %s';
AbVMSWriteTooManyBytesS = 'VMS: request to write too many bytes [%d]';
AbBBSReadTooManyBytesS = 'BBS: request to read too many bytes [%d]';
AbBBSSeekOutsideBufferS = 'BBS: New position is outside the buffer';
AbBBSInvalidOriginS = 'BBS: Invalid Origin value';
AbBBSWriteTooManyBytesS = 'BBS: request to write too many bytes [%d]';
AbSWSNotEndofStreamS = 'TabSlidingWindowStream.Write: Not at end of stream';
AbSWSSeekFailedS = 'TabSlidingWindowStream.bsWriteChunk: seek failed';
AbSWSWriteFailedS = 'TabSlidingWindowStream.bsWriteChunk: write failed';
AbSWSInvalidOriginS = 'TabSlidingWindowStream.Seek: invalid origin';
AbSWSInvalidNewOriginS = 'TabSlidingWindowStream.Seek: invalid new position';
AbItemNameHeadingS = 'Name';
AbPackedHeadingS = 'Packed';
AbMethodHeadingS = 'Method';
AbRatioHeadingS = 'Ratio (%)';
AbCRCHeadingS = 'CRC32';
AbFileAttrHeadingS = 'Attributes';
AbFileFormatHeadingS = 'Format';
AbEncryptionHeadingS = 'Encrypted';
AbTimeStampHeadingS = 'Time Stamp';
AbFileSizeHeadingS = 'Size';
AbVersionMadeHeadingS = 'Version Made';
AbVersionNeededHeadingS = 'Version Needed';
AbPathHeadingS = 'Path';
AbPartialHeadingS = 'Partial';
AbExecutableHeadingS = 'Executable';
AbCabMethod0S = 'None';
AbCabMethod1S = 'MSZip';
AbLtAddS = ' added ';
AbLtDeleteS = ' deleted ';
AbLtExtractS = ' extracted ';
AbLtFreshenS = ' freshened ';
AbLtMoveS = ' moved ';
AbLtReplaceS = ' replaced ';
AbLtStartS = ' logging ';
AbGzipInvalidS = 'Invalid Gzip';
AbGzipBadCRCS = 'Bad CRC';
AbGzipBadFileSizeS = 'Bad File Size';
AbUnhandledEntityS = 'Unhandled Entity';
{ pre-defined "operating system" (really more FILE system) identifiers for the
Gzip header }
AbGzOsFat = 'FAT File System (MS-DOS, OS/2, NT/Win32)';
AbGzOsAmiga = 'Amiga';
AbGzOsVMS = 'VMS (or OpenVMS)';
AbGzOsUnix = 'Unix';
AbGzOsVM_CMS = 'VM/CMS';
AbGzOsAtari = 'Atari TOS';
AbGzOsHPFS = 'HPFS File System (OS/2, NT)';
AbGzOsMacintosh = 'Macintosh';
AbGzOsZ_System = 'Z-System';
AbGzOsCP_M = 'CP/M';
AbGzOsTOPS_20 = 'TOPS-20';
AbGzOsNTFS = 'NTFS File System (NT)';
AbGzOsQDOS = 'QDOS';
AbGzOsAcornRISCOS = 'Acorn RISCOS';
AbGzOsunknown = 'unknown';
AbGzOsUndefined = 'ID undefined by gzip';
{!!.03 - Moved from AbCompnd.inc }
{ Compound File specific error messages }
resourcestring
AbCmpndIndexOutOfBounds = 'Index out of bounds';
AbCmpndBusyUpdating = 'Compound file is busy updating';
AbCmpndInvalidFile = 'Invalid compound file';
AbCmpndFileNotFound = 'File/Directory not found';
AbCmpndFolderNotEmpty = 'Folder not empty';
AbCmpndExceedsMaxFileSize = 'File size exceeds maximum allowable';
{!!.03 - End Moved }
type
AbStrRec = record
ID: Integer;
Str: string;
end;
const
AbStrArray : array [0..145] of AbStrRec = (
(ID: AbZipVersionNeeded; Str: AbZipVersionNeededS),
(ID: AbUnknownCompressionMethod; Str: AbUnknownCompressionMethodS),
(ID: AbNoExtractionMethod; Str: AbNoExtractionMethodS),
(ID: AbInvalidPassword; Str: AbInvalidPasswordS),
(ID: AbNoInsertionMethod; Str: AbNoInsertionMethodS),
(ID: AbInvalidFactor; Str: AbInvalidFactorS),
(ID: AbDuplicateName; Str: AbDuplicateNameS),
(ID: AbUnsupportedCompressionMethod; Str: AbUnsupportedCompressionMethodS),
(ID: AbUserAbort; Str: AbUserAbortS),
(ID: AbArchiveBusy; Str: AbArchiveBusyS),
(ID: AbDiskRequest; Str: AbDiskRequestS),
(ID: AbLastDiskRequest; Str: AbLastDiskRequestS),
(ID: AbBadSpanStream; Str: AbBadSpanStreamS),
(ID: AbDiskNumRequest; Str: AbDiskNumRequestS),
(ID: AbNoOverwriteSpanStream; Str: AbNoOverwriteSpanStreamS),
(ID: AbNoSpannedSelfExtract; Str: AbNoSpannedSelfExtractS),
(ID: AbBlankDisk; Str: AbBlankDiskS),
(ID: AbStreamFull; Str: AbStreamFullS),
(ID: AbNoSuchDirectory; Str: AbNoSuchDirectoryS),
(ID: AbInflateBlockError; Str: AbInflateBlockErrorS),
(ID: AbBadStreamType; Str: AbBadStreamTypeS),
(ID: AbTruncateError; Str: AbTruncateErrorS),
(ID: AbZipBadCRC; Str: AbZipBadCRCS),
(ID: AbZipBadStub; Str: AbZipBadStubS),
(ID: AbFileNotFound; Str: AbFileNotFoundS),
(ID: AbInvalidLFH; Str: AbInvalidLFHS),
(ID: AbNoArchive; Str: AbNoArchiveS),
(ID: AbErrZipInvalid; Str: AbErrZipInvalidS),
(ID: AbReadError; Str: AbReadErrorS),
(ID: AbInvalidIndex; Str: AbInvalidIndexS),
(ID: AbInvalidThreshold; Str: AbInvalidThresholdS),
(ID: AbNthImageRequest; Str: AbNthImageRequestS),
(ID: AbLastImageRequest; Str: AbLastImageRequestS),
(ID: AbImageRequest; Str: AbImageRequestS),
(ID: AbUnhandledFileType; Str: AbUnhandledFileTypeS),
(ID: AbSpanningNotSupported; Str: AbSpanningNotSupportedS),
(ID: AbLogCreateError; Str: AbLogCreateErrorS),
(ID: AbImageNumRequest; Str: AbImageNumRequestS),
(ID: AbBBSReadTooManyBytes; Str: AbBBSReadTooManyBytesS),
(ID: AbBBSSeekOutsideBuffer; Str: AbBBSSeekOutsideBufferS),
(ID: AbBBSInvalidOrigin; Str: AbBBSInvalidOriginS),
(ID: AbBBSWriteTooManyBytes; Str: AbBBSWriteTooManyBytesS),
(ID: AbNoCabinetDllError; Str: AbNoCabinetDllErrorS),
(ID: AbFCIFileOpenError; Str: AbFCIFileOpenErrorS),
(ID: AbFCIFileReadError; Str: AbFCIFileReadErrorS),
(ID: AbFCIFileWriteError; Str: AbFCIFileWriteErrorS),
(ID: AbFCIFileCloseError; Str: AbFCIFileCloseErrorS),
(ID: AbFCIFileSeekError; Str: AbFCIFileSeekErrorS),
(ID: AbFCIFileDeleteError; Str: AbFCIFileDeleteErrorS),
(ID: AbFCIAddFileError; Str: AbFCIAddFileErrorS),
(ID: AbFCICreateError; Str: AbFCICreateErrorS),
(ID: AbFCIFlushCabinetError; Str: AbFCIFlushCabinetErrorS),
(ID: AbFCIFlushFolderError; Str: AbFCIFlushFolderErrorS),
(ID: AbFDICopyError; Str: AbFDICopyErrorS),
(ID: AbFDICreateError; Str: AbFDICreateErrorS),
(ID: AbInvalidCabTemplate; Str: AbInvalidCabTemplateS),
(ID: AbInvalidCabFile; Str: AbInvalidCabFileS),
(ID: AbSWSNotEndofStream; Str: AbSWSNotEndofStreamS),
(ID: AbSWSSeekFailed; Str: AbSWSSeekFailedS),
(ID: AbSWSWriteFailed; Str: AbSWSWriteFailedS),
(ID: AbSWSInvalidOrigin; Str: AbSWSInvalidOriginS),
(ID: AbSWSInvalidNewOrigin; Str: AbSWSInvalidNewOriginS),
(ID: AbVersionFormat; Str: AbVersionFormatS),
(ID: AbMethod0; Str: AbMethod0S),
(ID: AbMethod1; Str: AbMethod1S),
(ID: AbMethod2; Str: AbMethod2S),
(ID: AbMethod3; Str: AbMethod3S),
(ID: AbMethod4; Str: AbMethod4S),
(ID: AbMethod5; Str: AbMethod5S),
(ID: AbMethod6; Str: AbMethod6S),
(ID: AbMethod7; Str: AbMethod7S),
(ID: AbMethod8; Str: AbMethod8S),
(ID: AbMethod9; Str: AbMethod9S),
(ID: AbMethod10; Str: AbMethod10S),
(ID: AbMethod11; Str: AbMethod11S),
(ID: AbCompressedSizeFormat; Str: AbCompressedSizeFormatS),
(ID: AbUncompressedSizeFormat; Str: AbUncompressedSizeFormatS),
(ID: AbCompressionMethodFormat; Str: AbCompressionMethodFormatS),
(ID: AbCompressionRatioFormat; Str: AbCompressionRatioFormatS),
(ID: AbCRCFormat; Str: AbCRCFormatS),
(ID: AbReadOnly; Str: AbReadOnlyS),
(ID: AbHidden; Str: AbHiddenS),
(ID: AbSystem; Str: AbSystemS),
(ID: AbArchived; Str: AbArchivedS),
(ID: AbEFAFormat; Str: AbEFAFormatS),
(ID: AbIFAFormat; Str: AbIFAFormatS),
(ID: AbText; Str: AbTextS),
(ID: AbBinary; Str: AbBinaryS),
(ID: AbEncryptionFormat; Str: AbEncryptionFormatS),
(ID: AbEncrypted; Str: AbEncryptedS),
(ID: AbNotEncrypted; Str: AbNotEncryptedS),
(ID: AbUnknown; Str: AbUnknownS),
(ID: AbTimeStampFormat; Str: AbTimeStampFormatS),
(ID: AbMadeByFormat; Str: AbMadeByFormatS),
(ID: AbNeededFormat; Str: AbNeededFormatS),
(ID: AbCommentFormat; Str: AbCommentFormatS),
(ID: AbDefaultExt; Str: AbDefaultExtS),
(ID: AbFilter; Str: AbFilterS),
(ID: AbFileNameTitle; Str: AbFileNameTitleS),
(ID: AbOK; Str: AbOKS),
(ID: AbCancel; Str: AbCancelS),
(ID: AbSelectDirectory; Str: AbSelectDirectoryS),
(ID: AbEnterPassword; Str: AbEnterPasswordS),
(ID: AbPassword; Str: AbPasswordS),
(ID: AbVerify; Str: AbVerifyS),
(ID: AbCabExt; Str: AbCabExtS),
(ID: AbCabFilter; Str: AbCabFilterS),
(ID: AbLogExt; Str: AbLogExtS),
(ID: AbLogFilter; Str: AbLogFilterS),
(ID: AbExeExt; Str: AbExeExtS),
(ID: AbExeFilter; Str: AbExeFilterS),
(ID: AbVMSReadTooManyBytes; Str: AbVMSReadTooManyBytesS),
(ID: AbVMSInvalidOrigin; Str: AbVMSInvalidOriginS),
(ID: AbVMSErrorOpenSwap; Str: AbVMSErrorOpenSwapS),
(ID: AbVMSSeekFail; Str: AbVMSSeekFailS),
(ID: AbVMSReadFail; Str: AbVMSReadFailS),
(ID: AbVMSWriteFail; Str: AbVMSWriteFailS),
(ID: AbVMSWriteTooManyBytes; Str: AbVMSWriteTooManyBytesS),
(ID: AbItemNameHeading; Str: AbItemNameHeadingS),
(ID: AbPackedHeading; Str: AbPackedHeadingS),
(ID: AbMethodHeading; Str: AbMethodHeadingS),
(ID: AbRatioHeading; Str: AbRatioHeadingS),
(ID: AbCRCHeading; Str: AbCRCHeadingS),
(ID: AbFileAttrHeading; Str: AbFileAttrHeadingS),
(ID: AbFileFormatHeading; Str: AbFileFormatHeadingS),
(ID: AbEncryptionHeading; Str: AbEncryptionHeadingS),
(ID: AbTimeStampHeading; Str: AbTimeStampHeadingS),
(ID: AbFileSizeHeading; Str: AbFileSizeHeadingS),
(ID: AbVersionMadeHeading; Str: AbVersionMadeHeadingS),
(ID: AbVersionNeededHeading; Str: AbVersionNeededHeadingS),
(ID: AbPathHeading; Str: AbPathHeadingS),
(ID: AbPartialHeading; Str: AbPartialHeadingS),
(ID: AbExecutableHeading; Str: AbExecutableHeadingS),
(ID: AbCabMethod0; Str: AbCabMethod0S),
(ID: AbCabMethod1; Str: AbCabMethod1S),
(ID: AbLtAdd; Str: AbLtAddS),
(ID: AbLtDelete; Str: AbLtDeleteS),
(ID: AbLtExtract; Str: AbLtExtractS),
(ID: AbLtFreshen; Str: AbLtFreshenS),
(ID: AbLtMove; Str: AbLtMoveS),
(ID: AbLtReplace; Str: AbLtReplaceS),
(ID: AbLtStart; Str: AbLtStartS),
(ID: AbGzipInvalid; Str: AbGzipInvalidS),
(ID: AbGzipBadCRC; Str: AbGzipBadCRCS),
(ID: AbGzipBadFileSize; Str: AbGzipBadFileSizeS),
(ID: AbUnhandledEntity; Str: AbUnhandledEntityS)
);
function AbStrRes(Index : Integer) : string;
implementation
function AbStrRes(Index : Integer) : string;
var
i : Integer;
begin
for i := Low(AbStrArray) to High(AbStrArray) do
if AbStrArray[i].ID = Index then
Result := AbStrArray[i].Str;
end;
end.
|
unit TestFileUploadingSamplesUnit;
interface
uses
TestFramework, Classes, SysUtils,
BaseTestOnlineExamplesUnit;
type
TTestFileUploadingSamples = class(TTestOnlineExamples)
private
published
procedure Preview;
procedure UploadFileGeocoding;
procedure Upload;
end;
implementation
uses
VehicleUnit;
procedure TTestFileUploadingSamples.Preview;
var
ErrorString: String;
FileId: String;
Content: TStringList;
begin
FileId := 'b2130b5fc36ae1109ef63b6db73781f6';
Content := FRoute4MeManager.Uploading.Preview(FileId, ErrorString);
try
CheckEquals(EmptyStr, ErrorString);
CheckNotNull(Content);
CheckTrue(Content.Count > 0);
finally
FreeAndNil(Content);
end;
FileId := 'random_id_dDFsd2@D3d';
Content := FRoute4MeManager.Uploading.Preview(FileId, ErrorString);
try
// '{"status":false,"errors":["Upload not found"]}'
CheckNotEquals(EmptyStr, ErrorString);
CheckNotNull(Content);
CheckTrue(Content.Count = 0);
finally
FreeAndNil(Content);
end;
end;
procedure TTestFileUploadingSamples.Upload;
var
ErrorString: String;
Content: String;
Stream: TFileStream;
begin
Stream := TFileStream.Create('', fmOpenRead);
try
Content := FRoute4MeManager.Uploading.Upload(Stream, ErrorString);
finally
FreeAndNil(Stream);
end;
CheckEquals(EmptyStr, ErrorString);
CheckNotEquals(EmptyStr, Content);
Stream := TFileStream.Create('', fmOpenRead);
try
Content := FRoute4MeManager.Uploading.Upload(Stream, ErrorString);
finally
FreeAndNil(Stream);
end;
CheckNotEquals(EmptyStr, ErrorString);
CheckEquals(EmptyStr, Content);
end;
procedure TTestFileUploadingSamples.UploadFileGeocoding;
var
ErrorString: String;
FileId: String;
Content: TStringList;
begin
FileId := 'b2130b5fc36ae1109ef63b6db73781f6';
Content := FRoute4MeManager.Uploading.UploadFileGeocoding(FileId, ErrorString);
// '{'#$A' "optimization_problem_id": "F27753EA3D0734E854A35215B6712DA2",'#$A' "address_count": 10,'#$A' "status": true'#$A'}'
CheckEquals(EmptyStr, ErrorString);
CheckNotNull(Content);
CheckTrue(Content.Count > 0);
FileId := 'random_id_dDFsd2@D3d';
Content := FRoute4MeManager.Uploading.UploadFileGeocoding(FileId, ErrorString);
//'{"errors":["Upload not found"],"timestamp":1487595853}'
CheckNotEquals(EmptyStr, ErrorString);
CheckNotNull(Content);
CheckTrue(Content.Count = 0);
end;
initialization
RegisterTest('Examples\Online\FileUploading\', TTestFileUploadingSamples.Suite);
end.
|
unit DataTypes;
interface
const
dtOneSecond=1/(24*60*60);
dtOneMinute=1/(24*60);
dtOneHour=1/24;
dtOneDay=1;
dtY2K=36526.0;
const
// PIP-file flags
pfOkData=$02;
pfNoCarr=$04;
pfEndDay=$80;
type
TPipFileTime = packed object
Year,Month,Day,Hour,Min,Sec:Byte;
end;
TPipTime = packed object(TPipFileTime)
Sec100:Byte;
end;
TSclRec=packed record
Number:Byte;
Time:TPipTime;
p:Single;
end;
TSclRecN=packed record
Number:Byte;
Time:TPipTime;
p:array[0..255] of Single;
end;
TPipFileRec = packed record
F1,F2:Byte;
Time:TPipFileTime;
p1,p2:Single;
end;
TPressure=packed record
Flags:Byte;
Pressure:Single;
end;
PPressure=^TPressure;
procedure NextPipTime(var PT:TPipTime; const Step:TPipTime);
implementation
procedure NextPipTime(var PT:TPipTime; const Step:TPipTime);
var
Tmp:Integer;
begin
// Sec100
Tmp:=PT.Sec100+Step.Sec100;
if Tmp<100 then begin PT.Sec100:=Tmp; Tmp:=0; end
else begin PT.Sec100:=Tmp-100; Tmp:=1; end;
// Sec
Inc(Tmp,PT.Sec+Step.Sec);
if Tmp<60 then begin PT.Sec:=Tmp; Tmp:=0; end
else begin PT.Sec:=Tmp-60; Tmp:=1; end;
// Min
Inc(Tmp,PT.Min+Step.Min);
if Tmp<60 then begin PT.Min:=Tmp; Tmp:=0; end
else begin PT.Min:=Tmp-60; Tmp:=1; end;
// Hour
Inc(Tmp,PT.Hour+Step.Hour);
if Tmp<60 then begin PT.Hour:=Tmp; Tmp:=0; end
else begin PT.Min:=Tmp-60; Tmp:=1; end;
// Day
Inc(PT.Day,Step.Day+Tmp);
end;
end.
|
unit ExcMemMap;
interface
uses
Windows, SysUtils, Classes;
type
EMMFileError = class( Exception );
TMMFileStream = class( TStream )
private
FFile : THandle;
FMode : Dword;
FFileSize : Dword;
FCurOffset: Dword;
FMapping : THandle;
FView : Pointer;
FViewOfs : Dword;
FViewSize : Dword;
FGranula : Dword;
FMaxView : Dword;
FReviews : Dword;
procedure ReView(DesiredOffset,DesiredDataSize: Dword );
function GetRawData(Offset: Dword): Pointer;
property RawData[Offset: Dword]: Pointer read GetRawData;
public
constructor Create( FileName: String; Mode: Longint; MapName: String );
destructor Destroy; override;
function MapData( Offset,Size: Dword ): Pointer;
procedure UnMapData;
function ReadByte: Byte;
function ReadWord: Word;
function ReadDword: Dword;
function ReadPointer: Pointer;
public
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
end;
implementation
uses ExcMagicUtils;
const
VIEW_SIZE = 1; // in granulas (each granula on all current win32 platforms = 64K)
{ TMMFileStream }
constructor TMMFileStream.Create( FileName: String; Mode: Longint; MapName: String );
const
AccessMode: array[0..2] of DWord = (
GENERIC_READ,
GENERIC_WRITE,
GENERIC_READ or GENERIC_WRITE
);
ShareMode: array[0..4] of DWord = (
0,
0,
FILE_SHARE_READ,
FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE
);
MapProtect: array[0..2] of Dword = (
PAGE_READONLY,
0,
PAGE_READWRITE
);
var
si: TSystemInfo;
begin
inherited Create;
if (Mode and 3) = fmOpenWrite then
raise EMMFileError.Create( 'Invalid file mode: fmOpenWrite' );
GetSystemInfo( si );
FGranula := si.dwAllocationGranularity;
FMode := Mode;
FMaxView := 0;
FReviews := 0;
{$IFDEF EXCMAGIC_DEBUG}
DebugMsg( Format('MMF: granula 0x%X, viewsize 0x%X, creating %s',[FGranula,FGranula*VIEW_SIZE,FileName]) );
{$ENDIF}
FFile := CreateFile( PChar(FileName),
AccessMode[Mode and 3],
ShareMode[(Mode and $F0) shr 4],
nil,
OPEN_EXISTING,
0,
0 );
if FFile <> INVALID_HANDLE_VALUE then
begin
FFileSize := GetFileSize( FFile, nil );
FCurOffset:= 0;
{$IFDEF EXCMAGIC_DEBUG}
DebugMsg( Format('MMF: F_handle %X, mapping %s',[FFile,MapName]) );
{$ENDIF}
FMapping := CreateFileMapping( FFile,
nil,
MapProtect[Mode and 3],
0,
0,
PChar(StrChar2Char(MapName,'\','_')) );
if FMapping = 0 then
begin
CloseHandle( FFile );
raise EMMFileError.Create( 'Can''t create file mapping for ' +
FileName + ': ' + SysErrorMessage(GetLastError) );
end;
{$IFDEF EXCMAGIC_DEBUG}
DebugMsg( Format('MMF: M_handle %X, result %X',[FMapping,GetLastError]) );
{$ENDIF}
end
else
raise EMMFileError.Create( 'Can''t open file ' +
FileName + ': ' + SysErrorMessage(GetLastError) );
end;
destructor TMMFileStream.Destroy;
begin
{$IFDEF EXCMAGIC_DEBUG}
DebugMsg( Format('MMF: destroying. file %X, map %X, view %p',[FFile,FMapping,FView]) );
DebugMsg( Format(' stat: maxviewsize %d, reviews %d', [FMaxView,FReviews]) );
{$ENDIF}
if FView <> nil then UnmapViewOfFile( FView );
CloseHandle( FMapping );
CloseHandle( FFile );
inherited;
end;
procedure TMMFileStream.ReView( DesiredOffset,DesiredDataSize: Dword );
const
DesiredAccess: array[0..2] of Dword = (
FILE_MAP_READ,
FILE_MAP_WRITE,
FILE_MAP_WRITE
);
begin
if (FView <> nil) and
(DesiredOffset >= FViewOfs) and
(DesiredOffset + DesiredDataSize <= FViewOfs + FViewSize) then Exit;
{
view offset
/
| | | | | | |
| | | | | | |
|###|
|###|
^
desired offset and size
}
UnMapData;
{ move left to nearest granula }
FViewOfs := (DesiredOffset div FGranula) * FGranula;
{ }
FViewSize := ((DesiredOffset + DesiredDataSize - FViewOfs) div (FGranula*VIEW_SIZE) + 1) * (FGranula*VIEW_SIZE);
if Dword(FViewOfs + FViewSize) > FFileSize then FViewSize := FFileSize - Dword(FViewOfs);
// some statistics
if FViewSize > FMaxView then FMaxView := FViewSize;
Inc( FReviews );
FView := MapViewOfFile( FMapping,
DesiredAccess[FMode and 3],
0,
FViewOfs,
FViewSize
);
if FView = nil then
begin
raise EMMFileError.Create( 'Can''t create file view: ' + SysErrorMessage(GetLastError) );
end;
end;
function TMMFileStream.GetRawData(Offset: Dword): Pointer;
begin
Result := Pointer( Dword(FView) + Offset - FViewOfs );
end;
function TMMFileStream.MapData(Offset,Size: Dword): Pointer;
begin
ReView( Offset, Size );
Result := RawData[Offset];
end;
procedure TMMFileStream.UnMapData;
begin
if FView <> nil then UnmapViewOfFile( FView );
FView := nil;
end;
function TMMFileStream.Seek(Offset: Integer; Origin: Word): Longint;
begin
case Origin of
soFromBeginning : FCurOffset := Offset;
soFromCurrent : FCurOffset := Longint(FCurOffset) + Offset;
soFromEnd : FCurOffset := Longint(FFileSize) + Offset;
end;
Result := FCurOffset;
end;
function TMMFileStream.Write(const Buffer; Count: Integer): Longint;
begin
Inc( FCurOffset, Count );
Result := Count;
end;
function TMMFileStream.Read(var Buffer; Count: Integer): Longint;
begin
ReView( FCurOffset, Count );
Move( RawData[FCurOffset]^, Buffer, Count );
Inc( FCurOffset, Count );
Result := Count;
end;
function TMMFileStream.ReadByte: Byte;
begin
ReView( FCurOffset, SizeOf(Byte) );
Result := PByte( RawData[FCurOffset] )^;
Inc( FCurOffset, SizeOf(Byte) );
end;
function TMMFileStream.ReadDword: Dword;
begin
ReView( FCurOffset, SizeOf(Dword) );
Result := PDword( RawData[FCurOffset] )^;
Inc( FCurOffset, SizeOf(Dword) );
end;
function TMMFileStream.ReadPointer: Pointer;
type
PPointer = ^Pointer;
begin
ReView( FCurOffset, SizeOf(Pointer) );
Result := PPointer( RawData[FCurOffset] )^;
Inc( FCurOffset, SizeOf(Pointer) );
end;
function TMMFileStream.ReadWord: Word;
begin
ReView( FCurOffset, SizeOf(Word) );
Result := PWord( RawData[FCurOffset] )^;
Inc( FCurOffset, SizeOf(Word) );
end;
end.
|
unit m3BaseObject;
{* Базовая реализация объекта хранилища. }
// Модуль: "w:\common\components\rtl\Garant\m3\m3BaseObject.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tm3BaseObject" MUID: (4742DC5C0219)
{$Include w:\common\components\rtl\Garant\m3\m3Define.inc}
interface
uses
l3IntfUses
, l3CProtoObject
, m3DBInterfaces
, m3PrimDB
;
type
Tm3BaseObject = {abstract} class(Tl3CProtoObject, Im3DBObject)
{* Базовая реализация объекта хранилища. }
private
f_f_DB: Tm3PrimDB;
protected
function DB: Im3DB;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aDB: Tm3PrimDB); reintroduce;
protected
property f_DB: Tm3PrimDB
read f_f_DB;
end;//Tm3BaseObject
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *4742DC5C0219impl_uses*
//#UC END# *4742DC5C0219impl_uses*
;
constructor Tm3BaseObject.Create(aDB: Tm3PrimDB);
//#UC START# *555B269800C2_4742DC5C0219_var*
//#UC END# *555B269800C2_4742DC5C0219_var*
begin
//#UC START# *555B269800C2_4742DC5C0219_impl*
inherited Create;
aDB.SetRefTo(f_f_DB);
//#UC END# *555B269800C2_4742DC5C0219_impl*
end;//Tm3BaseObject.Create
function Tm3BaseObject.DB: Im3DB;
//#UC START# *4720847C026F_4742DC5C0219_var*
//#UC END# *4720847C026F_4742DC5C0219_var*
begin
//#UC START# *4720847C026F_4742DC5C0219_impl*
Result := f_DB.AsDB;
//#UC END# *4720847C026F_4742DC5C0219_impl*
end;//Tm3BaseObject.DB
procedure Tm3BaseObject.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4742DC5C0219_var*
//#UC END# *479731C50290_4742DC5C0219_var*
begin
//#UC START# *479731C50290_4742DC5C0219_impl*
FreeAndNil(f_f_DB);
inherited;
//#UC END# *479731C50290_4742DC5C0219_impl*
end;//Tm3BaseObject.Cleanup
end.
|
unit stListPrintAndExportFontSizeItem;
{* Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" }
// Модуль: "w:\common\components\SandBox\VCM\View\List\stListPrintAndExportFontSizeItem.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TstListPrintAndExportFontSizeItem" MUID: (DC3F98FB9EF9)
{$Include w:\common\components\SandBox\VCM\sbDefine.inc}
interface
uses
l3IntfUses
, ddAppConfigTypes
;
type
TstListPrintAndExportFontSizeItem = class(TddComboBoxConfigItem)
{* Визуализатор для настройки "Использовать для экспорта и печати следующий размер шрифта" }
public
constructor Create(aMasterItem: TddBaseConfigItem = nil); reintroduce;
end;//TstListPrintAndExportFontSizeItem
implementation
uses
l3ImplUses
, ListPrintAndExportFontSizeSettingRes
, l3Base
, ddAppConfigConst
;
constructor TstListPrintAndExportFontSizeItem.Create(aMasterItem: TddBaseConfigItem = nil);
var
l_Value : TddConfigValue;
begin
l3FillChar(l_Value, SizeOf(l_Value));
l_Value.Kind := dd_vkInteger;
l_Value.AsInteger := dv_List_PrintAndExportFontSize;
inherited Create(pi_List_PrintAndExportFontSize,
str_PrintAndExportFontSize.AsStr,
l_Value, TPrintAndExportFontSizeValuesMapImpl.Make, aMasterItem);
end;//TstListPrintAndExportFontSizeItem.Create
end.
|
unit DialMessages;
interface
uses
Windows, Forms;
procedure InfoMsg(const Msg: string);
procedure ErrorMsg(const Msg: string);
procedure WarningMsg(const Msg: string);
function QuestionMsg(const Msg: string): Byte;
implementation
resourcestring
rsInfo = 'Information';
rsError = 'Error';
rsWarning = 'Warning';
rsQuestion = 'Question';
procedure InfoMsg(const Msg: string);
begin
MessageBox(Application.Handle, PChar(Msg), PChar(rsInfo), MB_ICONINFORMATION or MB_OK);
end;
procedure ErrorMsg(const Msg: string);
begin
MessageBox(Application.Handle, PChar(Msg), PChar(rsError), MB_ICONERROR or MB_OK);
end;
procedure WarningMsg(const Msg: string);
begin
MessageBox(Application.Handle, PChar(Msg), PChar(rsWarning), MB_ICONWARNING or MB_OK);
end;
function QuestionMsg(const Msg: string): Byte;
begin
Result := MessageBox(Application.Handle, PChar(Msg), PChar(rsQuestion), MB_ICONQUESTION or MB_YESNOCANCEL);
end;
end.
|
unit FilesListForm;
interface
{$WARN UNIT_PLATFORM OFF}
uses
SysUtils, Types, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, FileCtrl;
type
TForm1 = class(TForm)
lbFiles: TListBox;
btnSource: TButton;
cbRecurse: TCheckBox;
procedure btnSourceClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
CurrentDir: string;
procedure AddFilesToList (Filter, Folder: string; Recurse: Boolean);
public
procedure AddDelphiFiles;
end;
var
Form1: TForm1;
procedure GetSubDirs (Folder: string; sList: TStringList);
implementation
{$R *.dfm}
procedure TForm1.AddFilesToList(Filter, Folder: string; Recurse: Boolean);
var
sr: TSearchRec;
sDirList: TStringList;
i: Integer;
begin
if FindFirst (Folder + Filter, faAnyFile, sr) = 0 then
repeat
lbFiles.Items.Add (Folder + sr.Name);
until FindNext(sr) <> 0;
FindClose(sr);
if Recurse then
begin
sDirList := TStringList.Create;
try
GetSubDirs (Folder, sDirList);
for i := 0 to sDirList.Count - 1 do
if (sDirList[i] <> '.') and (sDirList[i] <> '..') then
begin
Update;
lbFiles.Refresh;
AddFilesToList (Filter,
IncludeTrailingPathDelimiter (Folder + sDirList[i]),
Recurse);
end;
finally
sDirList.Free;
end;
end;
end;
procedure TForm1.btnSourceClick(Sender: TObject);
var
Dir: string;
begin
Dir := CurrentDir;
if SelectDirectory ('Choose Folder', '', Dir) then
begin
CurrentDir := Dir; // change current
AddDelphiFiles;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CurrentDir := ExtractFilePath (Application.ExeName);
end;
procedure GetSubDirs (Folder: string; sList: TStringList);
var
sr: TSearchRec;
begin
if FindFirst (Folder + '*.*', faDirectory, sr) = 0 then
try
repeat
if (sr.Attr and faDirectory) = faDirectory then
sList.Add (sr.Name);
until FindNext(sr) <> 0;
finally
FindClose(sr);
end;
end;
procedure TForm1.AddDelphiFiles;
begin
Screen.Cursor := crHourGlass;
try
lbFiles.Clear;
CurrentDir := IncludeTrailingPathDelimiter(CurrentDir);
AddFilesToList ('*.dpr', CurrentDir, cbRecurse.Checked);
AddFilesToList ('*.pas', CurrentDir, cbRecurse.Checked);
AddFilesToList ('*.dfm', CurrentDir, cbRecurse.Checked);
finally
Screen.Cursor := crDefault;
end;
end;
end.
|
unit m3FileStream;
// Модуль: "w:\common\components\rtl\Garant\m3\m3FileStream.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tm3FileStream" MUID: (4FA276920090)
{$Include w:\common\components\rtl\Garant\m3\m3Define.inc}
interface
uses
l3IntfUses
, m3BaseStream
, Windows
, ActiveX
, m3FileStreamMapView
, Classes
;
type
Tm3FileStream = class(Tm3BaseStream)
private
FHandle: THandle;
f_Name: WideString;
f_SharedMode: LongWord;
private
procedure SysCheck(AResult: LongBool);
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure DoRead(aBuff: Pointer;
aSize: Integer;
var theResult: Integer;
var theReturn: hResult); override;
procedure DoWrite(aBuff: Pointer;
aSize: Integer;
var theResult: Integer;
var theReturn: hResult); override;
procedure DoSeek(anOffset: Int64;
anOrigin: TSeekOrigin;
var theResult: Int64;
var theReturn: hResult); override;
procedure DoSetSize(aSize: Int64;
var theReturn: hResult); override;
procedure LockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult); override;
procedure UnlockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult); override;
function DoGetSize: Int64; override;
function DoGetLocksSupported: Integer; override;
function DoGetName: WideString; override;
public
constructor Create(const AName: WideString;
AAccess: LongWord;
ASharedMode: LongWord;
ADistribution: LongWord;
AFlags: LongWord); reintroduce;
class function Make(const AName: WideString;
AAccess: LongWord;
ASharedMode: LongWord;
ADistribution: LongWord;
AFlags: LongWord): IStream; reintroduce;
function CreateMapView(AProtect: LongWord;
AAccess: LongWord): Tm3FileStreamMapView;
procedure Commit(aFlags: Integer;
var theReturn: hResult); override;
end;//Tm3FileStream
implementation
uses
l3ImplUses
, ComObj
, SysUtils
, l3Base
, m2AddPrc
, StrUtils
//#UC START# *4FA276920090impl_uses*
//#UC END# *4FA276920090impl_uses*
;
procedure Tm3FileStream.SysCheck(AResult: LongBool);
//#UC START# *5481A7080336_4FA276920090_var*
var
LError : Integer;
l_ErrorPrim : Integer;
//#UC END# *5481A7080336_4FA276920090_var*
begin
//#UC START# *5481A7080336_4FA276920090_impl*
if not(AResult) then
begin
l_ErrorPrim := GetLastError;
LError:=Integer(l_ErrorPrim and $0000ffff);
case LError of
ERROR_SUCCESS: ;
ERROR_INVALID_FUNCTION,
ERROR_FILE_NOT_FOUND,
ERROR_PATH_NOT_FOUND,
ERROR_TOO_MANY_OPEN_FILES,
ERROR_ACCESS_DENIED,
ERROR_NOT_ENOUGH_MEMORY,
ERROR_WRITE_FAULT,
ERROR_READ_FAULT,
ERROR_SHARING_VIOLATION,
ERROR_LOCK_VIOLATION,
ERROR_DISK_FULL:
OleError(MakeResult(SEVERITY_ERROR,FACILITY_STORAGE,LError));
else
begin
l3System.Stack2Log(Format('! Системная ошибка %d %d', [l_ErrorPrim,LError]));
OleError(MakeResult(SEVERITY_ERROR,FACILITY_WIN32,LError));
end;//else
end;//case LError
end;//not(AResult)
//#UC END# *5481A7080336_4FA276920090_impl*
end;//Tm3FileStream.SysCheck
constructor Tm3FileStream.Create(const AName: WideString;
AAccess: LongWord;
ASharedMode: LongWord;
ADistribution: LongWord;
AFlags: LongWord);
//#UC START# *5481A82803BB_4FA276920090_var*
function lGetAccess(const AAccess: LongWord): LongInt;
begin
if ((AAccess and (GENERIC_READ or GENERIC_WRITE)) = (GENERIC_READ or GENERIC_WRITE)) then
Result := STGM_READWRITE
else
begin
if ((AAccess and GENERIC_WRITE) <> 0) then
Result := STGM_WRITE
else
Result := STGM_READ;
end;
end;
function __CreateFile(const AName: WideString;
const AAccess: DWORD;
const ASharedMode: DWORD;
const ADistribution: DWORD;
const AFlags: DWORD;
var AHandle: THandle): BOOL;
function __CheckLastError : LongWord;
begin
Result := GetLastError;
SetLastError(Result);
end;
resourcestring
SInfValue = 'File operation';
const
CSharedMask = $ffffffff;
const
Cm3BasClaDefaultTimeOut = 60 * 1000;
//Cm3BasClaDefaultTimeOut = 300000;
var
LString : AnsiString;
LTickCount : LongWord;
LTimeOut : LongInt;
begin
LTickCount := GetTickCount;
repeat
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
AHandle := CreateFileW(PWideChar(AName),AAccess,(ASharedMode and CSharedMask),nil,ADistribution,AFlags,0)
else
AHandle := CreateFileA(m2MakeAnsiString(LString,AName),AAccess,(ASharedMode and CSharedMask),nil,ADistribution,AFlags,0);
Result := (AHandle <> INVALID_HANDLE_VALUE);
if (Result or (__CheckLastError <> ERROR_SHARING_VIOLATION)) then
Exit;
LTimeOut := LongInt(GetTickCount - LTickCount);
if (LTimeOut > Cm3BasClaDefaultTimeOut) then
Break;
Sleep(0);
until False;
end;
//#UC END# *5481A82803BB_4FA276920090_var*
begin
//#UC START# *5481A82803BB_4FA276920090_impl*
f_Name := aName;
f_SharedMode := ASharedMode;
inherited Create(lGetAccess(AAccess));
try
SysCheck(__CreateFile(AName,AAccess,ASharedMode,ADistribution,AFlags,FHandle));
except
on E: EOleSysError do
begin
if (E.ErrorCode = STG_E_FILENOTFOUND) OR (E.ErrorCode = STG_E_PATHNOTFOUND) then
raise EOleSysError.Create(ANSIReplaceStr(E.Message, '%1', '"' + AName + '"'), E.ErrorCode, E.HelpContext)
else
raise;
end;//on E: EOleSysError
end;//try..except
//#UC END# *5481A82803BB_4FA276920090_impl*
end;//Tm3FileStream.Create
class function Tm3FileStream.Make(const AName: WideString;
AAccess: LongWord;
ASharedMode: LongWord;
ADistribution: LongWord;
AFlags: LongWord): IStream;
var
l_Inst : Tm3FileStream;
begin
l_Inst := Create(AName, AAccess, ASharedMode, ADistribution, AFlags);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tm3FileStream.Make
function Tm3FileStream.CreateMapView(AProtect: LongWord;
AAccess: LongWord): Tm3FileStreamMapView;
//#UC START# *5481A8860001_4FA276920090_var*
//#UC END# *5481A8860001_4FA276920090_var*
begin
//#UC START# *5481A8860001_4FA276920090_impl*
Win32Check(FlushFileBuffers(FHandle));
if (LongInt(GetFileSize(FHandle, nil)) <> 0) then
Result := Tm3FileStreamMapView.Create(Self, FHandle, AProtect, AAccess)
else
Result := nil;
//#UC END# *5481A8860001_4FA276920090_impl*
end;//Tm3FileStream.CreateMapView
procedure Tm3FileStream.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4FA276920090_var*
//#UC END# *479731C50290_4FA276920090_var*
begin
//#UC START# *479731C50290_4FA276920090_impl*
if (FHandle <> 0) and (FHandle <> INVALID_HANDLE_VALUE) then
begin
SysCheck(CloseHandle(FHandle));
FHandle := 0;
end;
inherited;
//#UC END# *479731C50290_4FA276920090_impl*
end;//Tm3FileStream.Cleanup
procedure Tm3FileStream.DoRead(aBuff: Pointer;
aSize: Integer;
var theResult: Integer;
var theReturn: hResult);
//#UC START# *4FA27CF501C4_4FA276920090_var*
//#UC END# *4FA27CF501C4_4FA276920090_var*
begin
//#UC START# *4FA27CF501C4_4FA276920090_impl*
if SUCCEEDED(theReturn) then
SysCheck(Windows.ReadFile(FHandle,ABuff^,LongWord(ASize),LongWord(theResult), nil));
//#UC END# *4FA27CF501C4_4FA276920090_impl*
end;//Tm3FileStream.DoRead
procedure Tm3FileStream.DoWrite(aBuff: Pointer;
aSize: Integer;
var theResult: Integer;
var theReturn: hResult);
//#UC START# *4FA27D310344_4FA276920090_var*
//#UC END# *4FA27D310344_4FA276920090_var*
begin
//#UC START# *4FA27D310344_4FA276920090_impl*
if SUCCEEDED(theReturn) then
SysCheck(Windows.WriteFile(FHandle,ABuff^,LongWord(ASize),LongWord(theResult),nil));
//#UC END# *4FA27D310344_4FA276920090_impl*
end;//Tm3FileStream.DoWrite
procedure Tm3FileStream.DoSeek(anOffset: Int64;
anOrigin: TSeekOrigin;
var theResult: Int64;
var theReturn: hResult);
//#UC START# *4FA27D5302C5_4FA276920090_var*
function __SetFilePointer(AHandle : THandle;
AOrigin : TSeekOrigin;
AOffset : Int64;
var AResult: Int64): LongBool;
type
T64to32 = packed record
RLoLongWord: LongWord;
RHiLongWord: LongWord;
end;//T64to32
var
LOffset : Int64;
begin//__SetFilePointer
LOffset := AOffset;
with T64to32(LOffset) do
begin
RLoLongWord := SetFilePointer(AHandle,
LongInt(RLoLongWord),
@RHiLongWord,
Ord(AOrigin));
Result := (RLoLongWord <> LongWord(-1));
end;//with T64to32(LOffset)
AResult:=LOffset;
end;//__SetFilePointer
//#UC END# *4FA27D5302C5_4FA276920090_var*
begin
//#UC START# *4FA27D5302C5_4FA276920090_impl*
if SUCCEEDED(theReturn) then
SysCheck(__SetFilePointer(FHandle, anOrigin, anOffset, theResult));
//#UC END# *4FA27D5302C5_4FA276920090_impl*
end;//Tm3FileStream.DoSeek
procedure Tm3FileStream.DoSetSize(aSize: Int64;
var theReturn: hResult);
//#UC START# *4FA27DCD02B4_4FA276920090_var*
//#UC END# *4FA27DCD02B4_4FA276920090_var*
begin
//#UC START# *4FA27DCD02B4_4FA276920090_impl*
if SUCCEEDED(theReturn) then
begin
OleCheck(Self.IStreamSeek(ASize,STREAM_SEEK_SET,PInt64(nil)^));
SysCheck(SetEndOfFile(FHandle));
end;
//#UC END# *4FA27DCD02B4_4FA276920090_impl*
end;//Tm3FileStream.DoSetSize
procedure Tm3FileStream.LockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult);
//#UC START# *4FA27E100218_4FA276920090_var*
function __LockFile(const AHandle: THandle;
const AOffset: Int64;
const ASize: Int64): LongBool;
type
T64to32 = packed record
RLoLongWord: LongWord;
RHiLongWord: LongWord;
end;//T64to32
begin//__LockFile
Result:=LockFile(AHandle,T64to32(AOffset).RLoLongWord,T64to32(AOffset).RHiLongWord,T64to32(ASize).RLoLongWord,T64to32(ASize).RHiLongWord);
end;//__LockFile
//#UC END# *4FA27E100218_4FA276920090_var*
begin
//#UC START# *4FA27E100218_4FA276920090_impl*
if SUCCEEDED(theReturn) then
begin
if (ALockType = LOCK_EXCLUSIVE) then
begin
if (f_SharedMode <> 0) AND (f_SharedMode <> FILE_SHARE_READ) then
SysCheck(__LockFile(FHandle, anOffset, ASize))
end//ALockType = LOCK_EXCLUSIVE
else
theReturn := STG_E_INVALIDFUNCTION;
end;//SUCCEEDED(AReturn)
//#UC END# *4FA27E100218_4FA276920090_impl*
end;//Tm3FileStream.LockRegion
procedure Tm3FileStream.UnlockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult);
//#UC START# *4FA27E4C0342_4FA276920090_var*
function __UnlockFile(const AHandle: THandle;
const AOffset: Int64;
const ASize: Int64): LongBool;
type
T64to32 = packed record
RLoLongWord : LongWord;
RHiLongWord : LongWord;
end;//T64to32
begin//__UnlockFile
Result := UnlockFile(AHandle,T64to32(AOffset).RLoLongWord,T64to32(AOffset).RHiLongWord,T64to32(ASize).RLoLongWord,T64to32(ASize).RHiLongWord);
end;//__UnlockFile
//#UC END# *4FA27E4C0342_4FA276920090_var*
begin
//#UC START# *4FA27E4C0342_4FA276920090_impl*
if SUCCEEDED(theReturn) then
begin
if (ALockType = LOCK_EXCLUSIVE) then
begin
if (f_SharedMode <> 0) AND (f_SharedMode <> FILE_SHARE_READ) then
SysCheck(__UnlockFile(FHandle, anOffset, ASize));
end//ALockType = LOCK_EXCLUSIVE
else
theReturn := STG_E_INVALIDFUNCTION;
end;//SUCCEEDED(AReturn)
//#UC END# *4FA27E4C0342_4FA276920090_impl*
end;//Tm3FileStream.UnlockRegion
function Tm3FileStream.DoGetSize: Int64;
//#UC START# *4FA2802E0231_4FA276920090_var*
function __GetFileSize: Int64;
type
T64to32 = packed record
RLoLongWord: LongWord;
RHiLongWord: LongWord;
end;//T64to32
var
LSize : Int64;
LResult : T64to32 absolute LSize;
begin//__GetFileSize
LResult.RLoLongWord := Windows.GetFileSize(FHandle, @LResult.RHiLongWord);
SysCheck(LResult.RLoLongWord <> LongWord(-1));
Result := LSize;
end;//__GetFileSize
//#UC END# *4FA2802E0231_4FA276920090_var*
begin
//#UC START# *4FA2802E0231_4FA276920090_impl*
if (f_SharedMode = 0) OR (f_SharedMode = FILE_SHARE_READ) then
(* SysCheck(JwaWinBase.GetFileSizeEx(FHandle, LARGE_INTEGER(Result)))*)
Result := __GetFileSize
else
Result := __GetFileSize;
(* Result := inherited pm_GetSize;*)
//#UC END# *4FA2802E0231_4FA276920090_impl*
end;//Tm3FileStream.DoGetSize
function Tm3FileStream.DoGetLocksSupported: Integer;
//#UC START# *4FA2805002E3_4FA276920090_var*
//#UC END# *4FA2805002E3_4FA276920090_var*
begin
//#UC START# *4FA2805002E3_4FA276920090_impl*
if (f_SharedMode = 0) OR (f_SharedMode = FILE_SHARE_READ) then
Result := 0
else
Result := LOCK_EXCLUSIVE;
//#UC END# *4FA2805002E3_4FA276920090_impl*
end;//Tm3FileStream.DoGetLocksSupported
procedure Tm3FileStream.Commit(aFlags: Integer;
var theReturn: hResult);
//#UC START# *4FA280DB0288_4FA276920090_var*
//#UC END# *4FA280DB0288_4FA276920090_var*
begin
//#UC START# *4FA280DB0288_4FA276920090_impl*
if SUCCEEDED(theReturn) then
begin
if (AFlags = STGC_DEFAULT) then
SysCheck(FlushFileBuffers(FHandle))
else
theReturn := STG_E_INVALIDFLAG;
end;//SUCCEEDED(theReturn)
//#UC END# *4FA280DB0288_4FA276920090_impl*
end;//Tm3FileStream.Commit
function Tm3FileStream.DoGetName: WideString;
//#UC START# *5412FB880320_4FA276920090_var*
//#UC END# *5412FB880320_4FA276920090_var*
begin
//#UC START# *5412FB880320_4FA276920090_impl*
Result := f_Name;
//#UC END# *5412FB880320_4FA276920090_impl*
end;//Tm3FileStream.DoGetName
end.
|
unit graphicsx;
{$i delphidefs.inc}
interface
uses
{$IFDEF FMX}
system.UITypes, system.UIConsts,
{$ELSE}
graphics,
{$ENDIF}
sysutils,
typex,
types;
{$IFDEF FMX}
const
clBlack = claBlack;
clSilver = claSilver;
clGrey = claGrey;
clNavy = claNavy;
clBlue = claBlue;
clGreen = claGreen;
clLime = claLime;
clRed = claRed;
clMagenta = claMagenta;
clFuchia = claMagenta;
clCyan = claCyan;
{$ENDIF}
type
TXPixelFormat = (xpf8bit, xpf16bit, xpf24Bit, xpf32bit);
{$IFDEF FMX}
TColor = TAlphaColor;
TPixelFormat = (gpf8bit, gpf16bit, gpf24Bit, gpf32bit);
{$ELSE}
TColor = graphics.TColor;
TPixelFormat = graphics.Tpixelformat;
//(pfDevice, pf1bit, pf4bit, pf8bit, pf15bit, pf16bit, pf24bit, pf32bit, pfCustom);
{$ENDIF}
function PixelSize(pf: TPixelFormat): ni;overload;
function PixelSize(pf: TXPixelFormat): ni;overload;
implementation
function PixelSize(pf: TXPixelFormat): ni;
begin
result := 0;
case pf of
xpf8Bit: exit(1);
xpf16bit: exit(2);
xpf24bit: exit(3);
xpf32bit: exit(4);
else
raise ECritical.create('TXPixelFormat size not handled');
end;
raise ECritical.create('unhandled pixel type');
end;
function PixelSize(pf: TPixelFormat): ni;
begin
case pf of
{$IFDEF FMX}
gpf8Bit: exit(1);
gpf16bit: exit(2);
gpf24bit: exit(3);
gpf32bit: exit(4);
{$ELSE}
pf8Bit: exit(1);
pf16bit: exit(2);
pf24bit: exit(3);
pf32bit: exit(4);
{$ENDIF}
else
raise ECritical.create('pixel format not byte size. '+inttostr(ord(pf)));
end;
end;
end.
|
unit test1;
interface
// ***********************************
// classes for test1.proto
// generated by ProtoBufGenerator
// kami-soft 2016-2017
// ***********************************
uses
SysUtils,
Classes,
pbInput,
pbOutput,
pbPublic,
uAbstractProtoBufClasses;
type
//enumeration
TEnumG0=(
g1 = 1, //enum value 1
g2 = 2
);
//field of message type
TNestedMsg0 = class(TAbstractProtoBufClass)
public
const tag_NestedField1 = 1;
strict private
FNestedField1: Integer;
procedure SetNestedField1(Tag: Integer; const Value: Integer);
strict protected
function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override;
procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override;
public
property NestedField1: Integer index tag_NestedField1 read FNestedField1 write SetNestedField1;
end;
TTestMsg0 = class(TAbstractProtoBufClass)
public
strict private
strict protected
function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override;
procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override;
public
end;
TTestMsg1 = class(TAbstractProtoBufClass)
public
const tag_DefField1 = 1;
const tag_DefField2 = 2;
const tag_DefField3 = 3;
const tag_DefField4 = 4;
const tag_DefField5 = 5;
const tag_DefField6 = 6;
const tag_DefField7 = 7;
const tag_DefField8 = 8;
const tag_DefField9 = 9;
const tag_FieldMsg1 = 20;
const tag_FieldArr1List = 40;
const tag_FieldArr2List = 41;
const tag_FieldArr3List = 42;
const tag_FieldMArr2List = 44;
strict private
FDefField1: Integer;
FDefField2: Int64;
FDefField3: string;
FDefField4: Double;
FDefField5: Boolean;
FDefField6: TEnumG0;
FDefField7: Int64;
FDefField8: Integer;
FDefField9: Single;
FFieldMsg1: TTestMsg0;
FFieldArr1List: TPBList<Integer>;
FFieldArr2List: TPBList<Integer>;
FFieldArr3List: TPBList<string>;
FFieldMArr2List: TProtoBufClassList<TNestedMsg0>;
procedure SetDefField1(Tag: Integer; const Value: Integer);
procedure SetDefField2(Tag: Integer; const Value: Int64);
procedure SetDefField3(Tag: Integer; const Value: string);
procedure SetDefField4(Tag: Integer; const Value: Double);
procedure SetDefField5(Tag: Integer; const Value: Boolean);
procedure SetDefField6(Tag: Integer; const Value: TEnumG0);
procedure SetDefField7(Tag: Integer; const Value: Int64);
procedure SetDefField8(Tag: Integer; const Value: Integer);
procedure SetDefField9(Tag: Integer; const Value: Single);
strict protected
function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override;
procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override;
public
constructor Create; override;
destructor Destroy; override;
//fields with defaults
property DefField1: Integer index tag_DefField1 read FDefField1 write SetDefField1 default 2;
property DefField2: Int64 index tag_DefField2 read FDefField2 write SetDefField2 default -1;
property DefField3: string index tag_DefField3 read FDefField3 write SetDefField3; // default 'yes ''"it is';
property DefField4: Double index tag_DefField4 read FDefField4 write SetDefField4; // default 1.1;
property DefField5: Boolean index tag_DefField5 read FDefField5 write SetDefField5; // default true;
property DefField6: TEnumG0 index tag_DefField6 read FDefField6 write SetDefField6 default g2;
property DefField7: Int64 index tag_DefField7 read FDefField7 write SetDefField7 default 100;
property DefField8: Integer index tag_DefField8 read FDefField8 write SetDefField8 default 1;
property DefField9: Single index tag_DefField9 read FDefField9 write SetDefField9; // default 1.23e1;
property FieldMsg1: TTestMsg0 read FFieldMsg1;
//repeated fields
property FieldArr1List: TPBList<Integer> read FFieldArr1List;
property FieldArr2List: TPBList<Integer> read FFieldArr2List;
property FieldArr3List: TPBList<string> read FFieldArr3List;
property FieldMArr2List: TProtoBufClassList<TNestedMsg0> read FFieldMArr2List;
end;
implementation
{ TNestedMsg0 }
function TNestedMsg0.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean;
begin
Result := inherited;
if Result then
Exit;
Result := True;
case FieldNumber of
tag_NestedField1:
NestedField1 := ProtoBuf.readInt32;
else
Result := False;
end;
end;
procedure TNestedMsg0.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput);
begin
inherited;
if FieldHasValue[tag_NestedField1] then
ProtoBuf.writeInt32(tag_NestedField1, FNestedField1);
end;
procedure TNestedMsg0.SetNestedField1(Tag: Integer; const Value: Integer);
begin
FNestedField1:= Value;
FieldHasValue[Tag]:= True;
end;
{ TTestMsg0 }
function TTestMsg0.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean;
begin
Result := inherited;
end;
procedure TTestMsg0.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput);
begin
inherited;
end;
{ TTestMsg1 }
constructor TTestMsg1.Create;
begin
inherited;
DefField1 := 2;
DefField2 := -1;
RegisterRequiredField(tag_DefField2);
DefField3 := 'yes ''"it is';
DefField4 := 1.1;
DefField5 := true;
DefField6 := g2;
DefField7 := 100;
DefField8 := 1;
DefField9 := 1.23e1;
FFieldMsg1 := TTestMsg0.Create;
FFieldArr1List := TPBList<Integer>.Create;
FFieldArr2List := TPBList<Integer>.Create;
FFieldArr3List := TPBList<string>.Create;
FFieldMArr2List := TProtoBufClassList<TNestedMsg0>.Create;
end;
destructor TTestMsg1.Destroy;
begin
FFieldMsg1.Free;
FFieldArr1List.Free;
FFieldArr2List.Free;
FFieldArr3List.Free;
FFieldMArr2List.Free;
inherited;
end;
function TTestMsg1.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean;
var
tmpBuf: TProtoBufInput;
begin
Result := inherited;
if Result then
Exit;
Result := True;
tmpBuf:= nil;
try
case FieldNumber of
tag_DefField1:
DefField1 := ProtoBuf.readInt32;
tag_DefField2:
DefField2 := ProtoBuf.readInt64;
tag_DefField3:
DefField3 := ProtoBuf.readString;
tag_DefField4:
DefField4 := ProtoBuf.readDouble;
tag_DefField5:
DefField5 := ProtoBuf.readBoolean;
tag_DefField6:
DefField6 := TEnumG0(ProtoBuf.readEnum);
tag_DefField7:
DefField7 := ProtoBuf.readSInt64;
tag_DefField8:
DefField8 := ProtoBuf.readFixed32;
tag_DefField9:
DefField9 := ProtoBuf.readFloat;
tag_FieldMsg1:
begin
tmpBuf := ProtoBuf.ReadSubProtoBufInput;
FFieldMsg1.LoadFromBuf(tmpBuf);
end;
tag_FieldArr1List:
FFieldArr1List.Add(ProtoBuf.readInt32);
tag_FieldArr2List:
begin
if WireType = WIRETYPE_LENGTH_DELIMITED then
begin
tmpBuf:=ProtoBuf.ReadSubProtoBufInput;
while tmpBuf.getPos < tmpBuf.BufSize do
FFieldArr2List.Add(tmpBuf.readRawVarint32);
end else
FFieldArr2List.Add(ProtoBuf.readRawVarint32);
end;
tag_FieldArr3List:
FFieldArr3List.Add(ProtoBuf.readString);
tag_FieldMArr2List:
FFieldMArr2List.AddFromBuf(ProtoBuf, fieldNumber);
else
Result := False;
end;
finally
tmpBuf.Free
end;
end;
procedure TTestMsg1.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput);
var
tmpBuf: TProtoBufOutput;
i: Integer;
begin
inherited;
tmpBuf:= TProtoBufOutput.Create;
try
if FieldHasValue[tag_DefField1] then
ProtoBuf.writeInt32(tag_DefField1, FDefField1);
if FieldHasValue[tag_DefField2] then
ProtoBuf.writeInt64(tag_DefField2, FDefField2);
if FieldHasValue[tag_DefField3] then
ProtoBuf.writeString(tag_DefField3, FDefField3);
if FieldHasValue[tag_DefField4] then
ProtoBuf.writeDouble(tag_DefField4, FDefField4);
if FieldHasValue[tag_DefField5] then
ProtoBuf.writeBoolean(tag_DefField5, FDefField5);
if FieldHasValue[tag_DefField6] then
ProtoBuf.writeInt32(tag_DefField6, Integer(FDefField6));
if FieldHasValue[tag_DefField7] then
ProtoBuf.writeSInt64(tag_DefField7, FDefField7);
if FieldHasValue[tag_DefField8] then
ProtoBuf.writeFixed32(tag_DefField8, FDefField8);
if FieldHasValue[tag_DefField9] then
ProtoBuf.writeFloat(tag_DefField9, FDefField9);
if FieldHasValue[tag_FieldMsg1] then
SaveMessageFieldToBuf(FFieldMsg1, tag_FieldMsg1, tmpBuf, ProtoBuf);
if FieldHasValue[tag_FieldArr1List] then
for i := 0 to FFieldArr1List.Count-1 do
ProtoBuf.writeInt32(tag_FieldArr1List, FFieldArr1List[i]);
if FieldHasValue[tag_FieldArr2List] then
begin
tmpBuf.Clear;
for i := 0 to FFieldArr2List.Count-1 do
tmpBuf.writeRawVarint32(FFieldArr2List[i]);
ProtoBuf.writeMessage(tag_FieldArr2List, tmpBuf);
end;
if FieldHasValue[tag_FieldArr3List] then
for i := 0 to FFieldArr3List.Count-1 do
ProtoBuf.writeString(tag_FieldArr3List, FFieldArr3List[i]);
if FieldHasValue[tag_FieldMArr2List] then
FFieldMArr2List.SaveToBuf(ProtoBuf, tag_FieldMArr2List);
finally
tmpBuf.Free
end;
end;
procedure TTestMsg1.SetDefField1(Tag: Integer; const Value: Integer);
begin
FDefField1:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField2(Tag: Integer; const Value: Int64);
begin
FDefField2:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField3(Tag: Integer; const Value: string);
begin
FDefField3:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField4(Tag: Integer; const Value: Double);
begin
FDefField4:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField5(Tag: Integer; const Value: Boolean);
begin
FDefField5:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField6(Tag: Integer; const Value: TEnumG0);
begin
FDefField6:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField7(Tag: Integer; const Value: Int64);
begin
FDefField7:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField8(Tag: Integer; const Value: Integer);
begin
FDefField8:= Value;
FieldHasValue[Tag]:= True;
end;
procedure TTestMsg1.SetDefField9(Tag: Integer; const Value: Single);
begin
FDefField9:= Value;
FieldHasValue[Tag]:= True;
end;
end.
|
unit Model.CadastroGR;
interface
uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema;
type
TCadastroGR = class
private
FIDConsulta: Integer;
FID: Integer;
FConsulta: String;
FTipo: Integer;
FValidade: TDate;
FData: TDate;
FAcao: TAcao;
FConexao: TConexao;
FQuery: TFDQuery;
FEmpresa: String;
function Insert(): Boolean;
function Update(): Boolean;
function Delete(): Boolean;
public
property ID: Integer read FID write FId;
property IDConsulta: Integer read FIDConsulta write FIDConsulta;
property Tipo: Integer read FTipo write FTipo;
property Consulta: String read FConsulta write FConsulta;
property Data: TDate read FData write FData;
property Validade: TDate read FValidade write FValidade;
property Empresa: String read FEmpresa write FEmpresa;
property Query: TFDQuery read FQuery write FQuery;
property Acao: TAcao read FAcao write FAcao;
constructor Create();
function GetID(iID: Integer): Integer;
function Localizar(aParam: array of variant): boolean;
function Gravar(): Boolean;
function SetupClass(FDquery: TFDQuery): Boolean;
function ClearClass(): Boolean;
end;
const
TABLENAME = 'cadastro_GR';
implementation
{ TCadastroGR }
function TCadastroGR.ClearClass: Boolean;
begin
FIDConsulta := 0;
FID := 0;
FConsulta := '';
FTipo := 0;
FValidade := StrToDate('31/12/1899');
FData := StrToDate('31/12/1899');
end;
constructor TCadastroGR.Create;
begin
FConexao := TConexao.Create;
end;
function TCadastroGR.Delete: Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
if Self.IDConsulta = -1 then
begin
sSQL := 'delete drom ' + TABLENAME + ' ' +
'where id_cadastro = :pid_cadastro;';
FDQuery.ExecSQL(sSQL,[Self.ID]);
end
else
begin
sSQL := 'delete from ' + TABLENAME + ' ' +
'where id_cadastro = :pid_cadastro and id_consulta = :id_consulta;';
FDQuery.ExecSQL(sSQL,[Self.ID, Self.IDConsulta]);
end;
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGR.GetID(iID: Integer): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_consulta),0) + 1 from ' + TABLENAME + ' where id_cadastro = ' + iID.toString);
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGR.Gravar: Boolean;
begin
case FAcao of
tacIncluir: Result := Self.Insert();
tacAlterar: Result := Self.Update();
tacExcluir: Result := Self.Delete();
end;
end;
function TCadastroGR.Insert: Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
Self.IDConsulta := GetID(Self.ID);
sSQL := 'insert into ' + TABLENAME + '(' +
'id_cadastro, id_consulta, cod_tipo, des_empresa, num_consulta, dat_consulta, dat_validade) ' +
'values (' +
':pid_cadastro, :pid_consulta, :pcod_tipo, :pdes_empresa, :pnum_consulta, :pdat_consulta, :pdat_validade);';
FDQuery.ExecSQL(sSQL, [Self.ID, Self.IDConsulta, Self.Empresa, Self.Tipo, Self.Consulta, Self.Data, Self.Validade]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGR.Localizar(aParam: array of variant): boolean;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('whew id_cadastro = :id_cadastro');
FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1];
end;
if aParam[0] = 'SEQUENCIA' then
begin
FDQuery.SQL.Add('where id_cadastro = :id_cadastro and id_consulta = :id_consulta');
FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1];
FDQuery.ParamByName('id_consulta').AsInteger := aParam[2];
end;
if aParam[0] = 'NUMERO' then
begin
FDQuery.SQL.Add('where num_consulta like :num_consulta');
FDQuery.ParamByName('num_consulta').AsString := aParam[1];
end;
if aParam[0] = 'EMNPRESA' then
begin
FDQuery.SQL.Add('where des_empresa like :des_empresa');
FDQuery.ParamByName('des_empresa').AsString := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('where dat_consulta = :dat_consulta');
FDQuery.ParamByName('dat_consulta').AsDateTime := aParam[1];
end;
if aParam[0] = 'VALIDADE' then
begin
FDQuery.SQL.Add('where dat_validade = :dat_validade');
FDQuery.ParamByName('dat_validade').AsDateTime := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
if not FDQuery.isEmpty then
begin
FQuery := FDQuery;
end;
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGR.SetupClass(FDquery: TFDQuery): Boolean;
begin
Result := False;
FIDConsulta := FDquery.FieldByName('id_consulta').AsInteger;
FID := FDquery.FieldByName('id_cadastro').AsInteger;
FConsulta := FDquery.FieldByName('num_consulta').AsString;
FTipo := FDquery.FieldByName('cod_tipo').AsInteger;
FValidade := FDquery.FieldByName('dat_validade').AsDateTime;
FData := FDquery.FieldByName('dat_consulta').AsDateTime;
Result := True;
end;
function TCadastroGR.Update: Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
Self.IDConsulta := GetID(Self.ID);
sSQL := 'update ' + TABLENAME + ' set ' +
'cod_tipo = :cod_tipo, des_empresa = :des_empresa, num_consulta = :num_consulta, dat_consulta = :dat_consulta, ' +
'dat_validade = :dat_validade' +
'where ' +
'id_cadastro = :id_cadastro and id_consulta = :id_consulta;';
FDQuery.ExecSQL(sSQL,[Self.Tipo, Self.Empresa, Self.Consulta, Self.Data, Self.Validade, Self.ID, Self.IDConsulta]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
end.
|
// Arkanoid test game engine.
// developed for iPhone test samples
//
// Author: Dmitry 'skalogryz' Boyarintsev 2009
//
// Arkanoid is an arcade game developed by Taito in 1986
// http://en.wikipedia.org/wiki/Arkanoid
//
// You're free to use this unit in anyway you want
unit gameengine;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
ballVelocity = 18;
type
TGameItem = record
x, y : single; // coodinates
dx, dy : single; // velocity vector
sticked: Boolean;
end;
TBrick = record
bounds : TRect;
health : Integer;
flash : Integer;
end;
{ TArkanoid }
TArkanoid = class(TObject)
private
fPaddleX : single;
protected
procedure BallMove(var move: TGameItem; atime: single);
procedure ResetPaddle;
procedure SetPaddleX(const AValue: single);
public
bricks : array [0..99] of TBrick;
brickCount : Integer;
balls : array [0..9] of TGameItem;
ballcount : Integer;
width : Integer;
height : Integer;
PaddleY : single;
PaddleW : single;
constructor Create(awidth, aheight: Integer);
procedure InitBricks;
procedure Init;
procedure Move;
function AnySticked: Boolean;
procedure LaunchSticked;
property PaddleX: single read fPaddleX write SetPaddleX;
end;
type
TMoveRecord = packed record
sx, sy : single;
dx, dy : single;
k : single; // y = kx + b
divk : single;
b : single;
end;
THitSide = (hs_LeftRight, hs_TopBottom);
THitSides = set of THitSide;
procedure InitMoveRecord(sx, sy, dx, dy: single; var r: TMoveRecord);
function HitRect(const r: TRect; const mr: TMoveRecord; var hitpoint: TPoint; var HitSides: THitSides): Boolean;
implementation
{ TArkanoid }
procedure TArkanoid.SetPaddleX(const AValue: single);
var
dx : single;
i : integer;
begin
dx := fPaddleX - AValue;
for i := 0 to ballcount - 1 do begin
if balls[i].sticked then
balls[i].x:=balls[i].x-dx;
end;
fPaddleX := AValue;
end;
procedure InitMoveRecord(sx, sy, dx, dy: single; var r: TMoveRecord);
var
diff : single;
begin
r.sx:=sx;
r.sy:=sy;
r.dx:=dx;
r.dy:=dy;
diff:=dx-sx;
if diff<>0 then begin
r.k:=(dy-sy) / diff;
if r.k<>0 then r.divk:=1/r.k
else r.divk:=0;
end else begin
r.k:=0;
r.divk:=0;
end;
r.b:=sy-sx*r.k;
end;
function InRange(p, r1,r2: Integer): Boolean; overload; inline;
begin
if r1<r2 then Result:=(p>=r1) and (p<r2)
else Result:=(p>=r2) and (p<r1)
end;
function InRange(p: Integer; r1,r2: single): Boolean; overload; inline;
begin
if r1<r2 then Result:=(p>=r1) and (p<r2)
else Result:=(p>=r2) and (p<r1)
end;
function HitRect(const r: TRect; const mr: TMoveRecord; var hitpoint: TPoint; var HitSides: THitSides): Boolean;
var
c, ch : Integer;
hitside : Boolean;
hittop : Boolean;
begin
HitSides:=[];
with r, mr do begin
if sx<=dx then begin
c:=Left;
end else begin
c:=Right;
end;
ch:=Round(k*c+b);
hitside:=inRange(c, sx, dx) and (ch >= Top) and (ch < Bottom);
if hitside then begin
hitpoint:=Point(c, ch);
Include(HitSides, hs_LeftRight)
end;
if sy<=dy then begin
c:=Top
end else begin
c:=Bottom;
end;
if k <> 0 then
ch:=Round((c-b)/k)
else
ch:=Round(sx);
hittop:=inRange(c, sy, dy) and (ch>=Left) and (ch<Right);
if hittop then begin
hitpoint:=Point(ch, c);
Include(HitSides, hs_TopBottom)
end;
end;
Result:=hittop or hitside;
end;
function SqrLen(const p1, p2: TPoint): single;
var
x,y:single;
begin
x:=p1.x-p2.x;
y:=p1.y-p2.y;
Result:=x*x+y*y;
end;
procedure TArkanoid.BallMove(var move: TGameItem; atime: single);
var
cx, cy : single;
p : TPoint;
i : Integer;
t : single;
hitidx : Integer;
hsides : THitSides;
hitsides : THitSides;
hlen : single;
hitlen : single;
hpnt : TPoint;
hitpnt : TPoint;
mr : TMoveRecord;
br : TRect;
begin
with move do begin
if sticked then Exit;
cx := x + dx * atime;
cy := y + dy * atime;
if cy < 0 then begin
cy := 0;
dy := -dy;
end;
InitMoveRecord(x, y, cx, cy, mr);
if cx < 0 then begin
cx := 0;
dx := -dx;
end else if cx > width then begin
cx := width;
dx := -dx;
end;
p.x := Round(x);
p.y := Round(y);
hitidx:=-1;
hitlen:=0;
for i := 0 to brickCount - 1 do begin
if (bricks[i].health > 0) and HitRect(bricks[i].bounds, mr, hpnt, hsides) then begin
hlen:=SqrLen(hpnt, p);
if (hitidx<0) or (hlen<hitlen) then begin
hitidx:=i;
hitlen:=hlen;
hitsides:=hsides;
hitpnt:=hpnt;
end;
end;
end;
if hitidx>=0 then begin
if hs_TopBottom in hitsides then move.dy:=-move.dy;
if hs_LeftRight in hitsides then move.dx:=-move.dx;
bricks[hitidx].flash:=2;
cx:=hitpnt.x;
cy:=hitpnt.y;
dec(bricks[hitidx].health);
end;
br:=Bounds( Round(PaddleX), Round(PaddleY), Round(PaddleW), 2);
if HitRect(br, mr, hpnt, hsides) then begin
t := (hpnt.x - PaddleX) / PaddleW;
t:=pi*(1-(t*0.8+0.1));
dx := cos(t)*ballVelocity;
dy := -sin(t)*ballVelocity;
cy := hpnt.y;
cx := hpnt.x;
end else if cy > height then begin
ResetPaddle;
Exit;
end;
x:=cx;
y:=cy;
end;
end;
procedure TArkanoid.ResetPaddle;
var
i : integer;
a : single;
begin
PaddleW := width / 5;
PaddleY := height - 10;
fPaddleX := width / 2 - PaddleW / 2;
ballcount := 1;
for i := 0 to ballcount - 1 do
with Balls[i] do begin
x := PaddleX+PaddleW/2;
y := PaddleY-5;
a := random*pi/4 + (pi/2 - pi/8);
if cos(a)*5 < 0.1 then a := a + pi/5;
dx := ballVelocity*cos(a);
dy := ballVelocity*sin(a);
sticked:=true;
end;
end;
constructor TArkanoid.Create(awidth, aheight: Integer);
begin
width := awidth;
height := aheight;
end;
procedure TArkanoid.InitBricks;
var
i : Integer;
x, y : integer;
begin
brickCount := 8*8;
for i := 0 to brickCount - 1 do begin
x := (i mod 8) * 40;
y := (i div 8) * 20 + 40;
bricks[i].bounds:=Bounds(x,y,40,20);
end;
for i:=0 to brickCount - 1 do begin
bricks[i].health := random(4)+1;
bricks[i].flash:=0;
end;
end;
procedure TArkanoid.Init;
begin
InitBricks;
ResetPaddle;
end;
procedure TArkanoid.Move;
var
i : Integer;
const
time : single = 1;
begin
for i := 0 to ballcount - 1 do
BallMove(balls[i], time);
end;
function TArkanoid.AnySticked: Boolean;
var
i : Integer;
begin
Result := false;
for i := 0 to ballcount - 1 do
if balls[i].sticked then begin
Result:=true;
exit;
end;
end;
procedure TArkanoid.LaunchSticked;
var
i : integer;
begin
for i := 0 to ballcount - 1 do
if balls[i].sticked then begin
balls[i].sticked:=false;
if balls[i].dy > 0 then balls[i].dy := - balls[i].dy;
end;
end;
end.
|
unit FmWorksListEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GsDocument;
type
TFmWorksEditor = class(TForm)
mWorksList: TMemo;
btnOK: TButton;
btnCancel: TButton;
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FItem: TGsRow;
public
property Row: TGsRow read FItem write FItem;
end;
var
FmWorksEditor: TFmWorksEditor;
implementation
{$R *.dfm}
procedure TFmWorksEditor.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFmWorksEditor.btnOKClick(Sender: TObject);
var
I: Integer;
begin
if FItem <> nil then
begin
FItem.WorksList.Clear;
for I := 0 to mWorksList.Lines.Count - 1 do
FItem.AddWork(mWorksList.Lines[I]);
end;
Close;
end;
procedure TFmWorksEditor.FormShow(Sender: TObject);
var
I: Integer;
begin
mWorksList.Clear;
if FItem <> nil then
begin
for I := 0 to FItem.WorksList.Count - 1 do
begin
mWorksList.Lines.Add(FItem.WorksList[I].Attributes[Ord(GsDocument.dtaCaption)]);
end;
end;
end;
end.
|
unit FileUtils_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ FileUtils Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_FileUtils: TGUID = '{36349ED0-AF75-11D2-9764-008029EC1811}';
const
{ Component class GUIDs }
Class_FolderIterator: TGUID = '{36349ED2-AF75-11D2-9764-008029EC1811}';
type
{ Forward declarations: Interfaces }
IFolderIterator = interface;
IFolderIteratorDisp = dispinterface;
{ Forward declarations: CoClasses }
FolderIterator = IFolderIterator;
{ Dispatch interface for FolderIterator Object }
IFolderIterator = interface(IDispatch)
['{36349ED1-AF75-11D2-9764-008029EC1811}']
function FindFirst(path: WideString): WideString; safecall;
function FindNext: WideString; safecall;
procedure FindClose; safecall;
end;
{ DispInterface declaration for Dual Interface IFolderIterator }
IFolderIteratorDisp = dispinterface
['{36349ED1-AF75-11D2-9764-008029EC1811}']
function FindFirst(path: WideString): WideString; dispid 1;
function FindNext: WideString; dispid 2;
procedure FindClose; dispid 3;
end;
{ FolderIteratorObject }
CoFolderIterator = class
class function Create: IFolderIterator;
class function CreateRemote(const MachineName: string): IFolderIterator;
end;
implementation
uses ComObj;
class function CoFolderIterator.Create: IFolderIterator;
begin
Result := CreateComObject(Class_FolderIterator) as IFolderIterator;
end;
class function CoFolderIterator.CreateRemote(const MachineName: string): IFolderIterator;
begin
Result := CreateRemoteComObject(MachineName, Class_FolderIterator) as IFolderIterator;
end;
end.
|
program fontdraw;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, FPimage, FPImgCanv, ftfont, FPWritePNG, FPCanvas;
procedure TestFPImgFont;
var
Img: TFPMemoryImage;
Writer: TFPWriterPNG;
ms: TMemoryStream;
ImgCanvas: TFPImageCanvas;
fs: TFileStream;
AFont: TFreeTypeFont;
begin
Img:=nil;
ImgCanvas:=nil;
Writer:=nil;
ms:=nil;
fs:=nil;
AFont:=nil;
try
// initialize free type font manager
ftfont.InitEngine;
FontMgr.SearchPath:='/usr/share/fonts/truetype/dejavu/';
//FontMgr.SearchPath:='/usr/share/fonts/truetype/ttf-dejavu/';
AFont:=TFreeTypeFont.Create;
// create an image of width 200, height 100
Img:=TFPMemoryImage.Create(200,100);
Img.UsePalette:=false;
// create the canvas with the drawing operations
ImgCanvas:=TFPImageCanvas.create(Img);
// paint white background
ImgCanvas.Brush.FPColor:=colWhite;
ImgCanvas.Brush.Style:=bsSolid;
ImgCanvas.Rectangle(0,0,Img.Width,Img.Height);
// paint text
ImgCanvas.Font:=AFont;
ImgCanvas.Font.Name:='DejaVuSans';
ImgCanvas.Font.Size:=20;
ImgCanvas.TextOut(10,30,'Test');
// write image as png to memory stream
Writer:=TFPWriterPNG.create;
ms:=TMemoryStream.Create;
writer.ImageWrite(ms,Img);
// write memory stream to file
ms.Position:=0;
fs:=TFileStream.Create('testfont.png',fmCreate);
fs.CopyFrom(ms,ms.Size);
finally
AFont.Free;
ms.Free;
Writer.Free;
ImgCanvas.Free;
Img.Free;
fs.Free;
end;
end;
begin
TestFPImgFont;
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
(*
Version History
05/27/2001 (c) Akzhan Abdulin
This component fixes Color property design-time storing issue
of its ancestor, TGraphicControl (clWindow not stored)
*)
{$include elpack2.inc}
{$ifdef ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$else}
{$ifdef LINUX}
{$I ../ElPack.inc}
{$else}
{$I ..\ElPack.inc}
{$endif}
{$endif}
unit ElCGControl;
interface
uses
Controls;
type
TElCustomGraphicControl = class(TGraphicControl)
public
procedure Loaded; override;
published
property Color nodefault;
end;
implementation
{ TElCustomGraphicControl }
procedure TElCustomGraphicControl.Loaded;
begin
inherited;
if ParentColor then
begin
ParentColor := False;
ParentColor := True;
end;
end;
end.
|
unit InfoXLTRCLMTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXLTRCLMRecord = record
PCode: String[6];
PDescription: String[60];
PModCount: SmallInt;
End;
TInfoXLTRCLMClass2 = class
public
PCode: String[6];
PDescription: String[60];
PModCount: SmallInt;
End;
// function CtoRInfoXLTRCLM(AClass:TInfoXLTRCLMClass):TInfoXLTRCLMRecord;
// procedure RtoCInfoXLTRCLM(ARecord:TInfoXLTRCLMRecord;AClass:TInfoXLTRCLMClass);
TInfoXLTRCLMBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXLTRCLMRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXLTRCLM = (InfoXLTRCLMPrimaryKey);
TInfoXLTRCLMTable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetEnumIndex(Value: TEIInfoXLTRCLM);
function GetEnumIndex: TEIInfoXLTRCLM;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoXLTRCLMRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRCLMRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoXLTRCLM read GetEnumIndex write SetEnumIndex;
end; { TInfoXLTRCLMTable }
TInfoXLTRCLMQuery = class( TDBISAMQueryAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFTemplate: TBlobField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXLTRCLMRecord;
procedure StoreDataBuffer(ABuffer:TInfoXLTRCLMRecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFTemplate: TBlobField read FDFTemplate;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoXLTRCLMTable }
procedure Register;
implementation
procedure TInfoXLTRCLMTable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRCLMTable.CreateFields }
procedure TInfoXLTRCLMTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRCLMTable.SetActive }
procedure TInfoXLTRCLMTable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRCLMTable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRCLMTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRCLMTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRCLMTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRCLMTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoXLTRCLMTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 6, N');
Add('Description, String, 60, N');
Add('Template, Memo, 0, N');
Add('ModCount, SmallInt, 0, N');
end;
end;
procedure TInfoXLTRCLMTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoXLTRCLMTable.SetEnumIndex(Value: TEIInfoXLTRCLM);
begin
case Value of
InfoXLTRCLMPrimaryKey : IndexName := '';
end;
end;
function TInfoXLTRCLMTable.GetDataBuffer:TInfoXLTRCLMRecord;
var buf: TInfoXLTRCLMRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRCLMTable.StoreDataBuffer(ABuffer:TInfoXLTRCLMRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoXLTRCLMTable.GetEnumIndex: TEIInfoXLTRCLM;
var iname : string;
begin
result := InfoXLTRCLMPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXLTRCLMPrimaryKey;
end;
procedure TInfoXLTRCLMQuery.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXLTRCLMQuery.CreateFields }
procedure TInfoXLTRCLMQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXLTRCLMQuery.SetActive }
procedure TInfoXLTRCLMQuery.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXLTRCLMQuery.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXLTRCLMQuery.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoXLTRCLMQuery.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoXLTRCLMQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXLTRCLMQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
function TInfoXLTRCLMQuery.GetDataBuffer:TInfoXLTRCLMRecord;
var buf: TInfoXLTRCLMRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXLTRCLMQuery.StoreDataBuffer(ABuffer:TInfoXLTRCLMRecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXLTRCLMTable, TInfoXLTRCLMQuery, TInfoXLTRCLMBuffer ] );
end; { Register }
function TInfoXLTRCLMBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..3] of string = ('CODE','DESCRIPTION','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 3) and (flist[x] <> s) do inc(x);
if x <= 3 then result := x else result := 0;
end;
function TInfoXLTRCLMBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftSmallInt;
end;
end;
function TInfoXLTRCLMBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PModCount;
end;
end;
end.
|
unit IdDsnSASLListEditorFormNET;
interface
uses
System.Drawing, System.Collections, System.ComponentModel,
System.Windows.Forms, System.Data, IdObjs, IdSASLCollection;
type
TfrmSASLListEditor = class(System.Windows.Forms.Form)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
Components: System.ComponentModel.Container;
btnOk: System.Windows.Forms.Button;
btnCancel: System.Windows.Forms.Button;
lblAvailable: System.Windows.Forms.Label;
lblAssigned: System.Windows.Forms.Label;
lbAvailable: System.Windows.Forms.ListBox;
lbAssigned: System.Windows.Forms.ListBox;
btnRemove: System.Windows.Forms.Button;
btnAdd: System.Windows.Forms.Button;
btnUp: System.Windows.Forms.Button;
btnDown: System.Windows.Forms.Button;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
procedure lbAvailable_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
procedure btnAdd_Click(sender: System.Object; e: System.EventArgs);
procedure btnRemove_Click(sender: System.Object; e: System.EventArgs);
procedure btnUp_Click(sender: System.Object; e: System.EventArgs);
procedure btnDown_Click(sender: System.Object; e: System.EventArgs);
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(Disposing: Boolean); override;
private
{ Private Declarations }
FSASLList: TIdSASLEntries;
FAvailObjs : TIdList;
procedure LoadBitmaps;
procedure UpdateList;
procedure UpdateGUI;
public
constructor Create;
procedure SetList(const CopyFrom: TIdSASLEntries);
procedure GetList(const CopyTo: TIdSASLEntries);
procedure SetComponentName(const Name: string);
function Execute : Boolean;
end;
[assembly: RuntimeRequiredAttribute(TypeOf(TfrmSASLListEditor))]
implementation
uses System.Reflection, System.Resources,
IdDsnCoreResourceStrings,
IdResourceStrings,
IdSASL,
IdSys;
{$R IdSASLListEditorForm.resources}
const ResourceBaseName = 'IdSASLListEditorForm';
{$AUTOBOX ON}
{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TfrmSASLListEditor.InitializeComponent;
begin
Self.btnOk := System.Windows.Forms.Button.Create;
Self.btnCancel := System.Windows.Forms.Button.Create;
Self.lblAvailable := System.Windows.Forms.Label.Create;
Self.lblAssigned := System.Windows.Forms.Label.Create;
Self.lbAvailable := System.Windows.Forms.ListBox.Create;
Self.lbAssigned := System.Windows.Forms.ListBox.Create;
Self.btnAdd := System.Windows.Forms.Button.Create;
Self.btnRemove := System.Windows.Forms.Button.Create;
Self.btnUp := System.Windows.Forms.Button.Create;
Self.btnDown := System.Windows.Forms.Button.Create;
Self.SuspendLayout;
//
// btnOk
//
Self.btnOk.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Right)));
Self.btnOk.DialogResult := System.Windows.Forms.DialogResult.OK;
Self.btnOk.Location := System.Drawing.Point.Create(294, 323);
Self.btnOk.Name := 'btnOk';
Self.btnOk.TabIndex := 0;
//
// btnCancel
//
Self.btnCancel.DialogResult := System.Windows.Forms.DialogResult.Cancel;
Self.btnCancel.Location := System.Drawing.Point.Create(374, 323);
Self.btnCancel.Name := 'btnCancel';
Self.btnCancel.TabIndex := 1;
//
// lblAvailable
//
Self.lblAvailable.AutoSize := True;
Self.lblAvailable.Location := System.Drawing.Point.Create(8, 8);
Self.lblAvailable.Name := 'lblAvailable';
Self.lblAvailable.Size := System.Drawing.Size.Create(38, 16);
Self.lblAvailable.TabIndex := 2;
Self.lblAvailable.Text := 'Label1';
//
// lblAssigned
//
Self.lblAssigned.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Right)));
Self.lblAssigned.Location := System.Drawing.Point.Create(248, 8);
Self.lblAssigned.Name := 'lblAssigned';
Self.lblAssigned.Size := System.Drawing.Size.Create(168, 16);
Self.lblAssigned.TabIndex := 3;
Self.lblAssigned.Text := 'Label2';
//
// lbAvailable
//
Self.lbAvailable.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Bottom) or System.Windows.Forms.AnchorStyles.Left)));
Self.lbAvailable.Location := System.Drawing.Point.Create(8, 24);
Self.lbAvailable.Name := 'lbAvailable';
Self.lbAvailable.Size := System.Drawing.Size.Create(169, 277);
Self.lbAvailable.TabIndex := 4;
Include(Self.lbAvailable.SelectedIndexChanged, Self.lbAvailable_SelectedIndexChanged);
//
// lbAssigned
//
Self.lbAssigned.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Bottom) or System.Windows.Forms.AnchorStyles.Right)));
Self.lbAssigned.Location := System.Drawing.Point.Create(248, 24);
Self.lbAssigned.Name := 'lbAssigned';
Self.lbAssigned.Size := System.Drawing.Size.Create(169, 277);
Self.lbAssigned.TabIndex := 5;
Include(Self.lbAssigned.SelectedIndexChanged, Self.lbAvailable_SelectedIndexChanged);
//
// btnAdd
//
Self.btnAdd.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.btnAdd.Location := System.Drawing.Point.Create(184, 88);
Self.btnAdd.Name := 'btnAdd';
Self.btnAdd.Size := System.Drawing.Size.Create(57, 23);
Self.btnAdd.TabIndex := 6;
Include(Self.btnAdd.Click, Self.btnAdd_Click);
//
// btnRemove
//
Self.btnRemove.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.btnRemove.Location := System.Drawing.Point.Create(184, 128);
Self.btnRemove.Name := 'btnRemove';
Self.btnRemove.Size := System.Drawing.Size.Create(57, 23);
Self.btnRemove.TabIndex := 7;
Include(Self.btnRemove.Click, Self.btnRemove_Click);
//
// btnUp
//
Self.btnUp.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Right)));
Self.btnUp.Location := System.Drawing.Point.Create(424, 88);
Self.btnUp.Name := 'btnUp';
Self.btnUp.Size := System.Drawing.Size.Create(23, 23);
Self.btnUp.TabIndex := 8;
Include(Self.btnUp.Click, Self.btnUp_Click);
//
// btnDown
//
Self.btnDown.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Right)));
Self.btnDown.Location := System.Drawing.Point.Create(424, 128);
Self.btnDown.Name := 'btnDown';
Self.btnDown.Size := System.Drawing.Size.Create(23, 23);
Self.btnDown.TabIndex := 9;
Include(Self.btnDown.Click, Self.btnDown_Click);
//
// TfrmSASLListEditor
//
Self.AcceptButton := Self.btnOk;
Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13);
Self.CancelButton := Self.btnCancel;
Self.ClientSize := System.Drawing.Size.Create(454, 354);
Self.Controls.Add(Self.btnDown);
Self.Controls.Add(Self.btnUp);
Self.Controls.Add(Self.btnRemove);
Self.Controls.Add(Self.btnAdd);
Self.Controls.Add(Self.lbAssigned);
Self.Controls.Add(Self.lbAvailable);
Self.Controls.Add(Self.lblAssigned);
Self.Controls.Add(Self.lblAvailable);
Self.Controls.Add(Self.btnCancel);
Self.Controls.Add(Self.btnOk);
Self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
Self.MaximizeBox := False;
Self.MaximumSize := System.Drawing.Size.Create(460, 386);
Self.MinimizeBox := False;
Self.MinimumSize := System.Drawing.Size.Create(460, 386);
Self.Name := 'TfrmSASLListEditor';
Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterScreen;
Self.Text := 'WinForm';
Self.ResumeLayout(False);
end;
{$ENDREGION}
procedure TfrmSASLListEditor.Dispose(Disposing: Boolean);
begin
if Disposing then
begin
if Components <> nil then
Components.Dispose();
Sys.FreeAndNil(FSASLList);
Sys.FreeAndNil(FAvailObjs);
end;
inherited Dispose(Disposing);
end;
constructor TfrmSASLListEditor.Create;
begin
inherited Create;
//
// Required for Windows Form Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
//captions
Text := RSADlgSLCaption;
lblAvailable.Text := RSADlgSLAvailable;
lblAssigned.Text := RSADlgSLAssigned;
FSASLList := TIdSASLEntries.Create(Self);
FAvailObjs := TIdList.Create;
LoadBitmaps;
btnCancel.Text := RSCancel;
btnOk.Text := RSOk;
end;
function TfrmSASLListEditor.Execute: Boolean;
begin
Result := Self.ShowDialog = System.Windows.Forms.DialogResult.OK;
end;
procedure TfrmSASLListEditor.btnDown_Click(sender: System.Object; e: System.EventArgs);
var
sel: integer;
begin
sel := lbAssigned.SelectedIndex;
if (sel>=0) and (sel<lbAssigned.Items.Count-1) then begin
FSASLList.Items[sel].Index := sel+1;
Updatelist;
lbAssigned.SelectedIndex := sel+1;
end;
end;
procedure TfrmSASLListEditor.btnUp_Click(sender: System.Object; e: System.EventArgs);
var sel : Integer;
begin
sel := lbAssigned.SelectedIndex;
// >0 is intentional, can't move the top element up!!
if sel>0 then begin
FSASLList.Items[Sel].Index := sel-1;
UpdateList;
lbAssigned.SelectedIndex := sel -1;
end;
end;
procedure TfrmSASLListEditor.btnRemove_Click(sender: System.Object; e: System.EventArgs);
var sel : Integer;
begin
sel := lbAssigned.SelectedIndex;
if sel >= 0 then
begin
FSASLList.Delete(sel);
end;
UpdateList;
end;
procedure TfrmSASLListEditor.btnAdd_Click(sender: System.Object; e: System.EventArgs);
var
sel: integer;
LCI : TIdSASLListEntry;
begin
sel := lbAvailable.SelectedIndex ;
if sel >=0 then begin
LCI := FSASLList.Add;
LCI.SASL := TIdSASL(FAvailObjs[sel]);
// SASLList.Add(TIdSASL(lbAvailable.Items.Objects[sel]));
UpdateList;
end;
end;
procedure TfrmSASLListEditor.lbAvailable_SelectedIndexChanged(sender: System.Object;
e: System.EventArgs);
begin
UpdateGUI;
end;
procedure TfrmSASLListEditor.SetComponentName(const Name: string);
begin
Text := Sys.Format(RSADlgSLCaption, [Name]);
end;
procedure TfrmSASLListEditor.GetList(const CopyTo: TIdSASLEntries);
var
i: integer;
LCI : TIdSASLListEntry;
begin
CopyTo.Clear;
for i := 0 to FSASLList.Count -1 do
begin
LCI := CopyTo.Add;
LCI.Assign(FSASLList[i]);
end;
end;
procedure TfrmSASLListEditor.SetList(const CopyFrom: TIdSASLEntries);
var
i, idx: integer;
LCI : TIdSASLListEntry;
begin
FSASLList.Clear;
for i := 0 to CopyFrom.Count -1 do begin
LCI := FSASLList.Add;
LCI.Assign(CopyFrom[i]);
end;
for i:=0 to CopyFrom.Count-1 do begin
if Assigned(CopyFrom[i].SASL) then
begin
idx := lbAvailable.Items.IndexOf(CopyFrom[i].SASL.Name);
if idx>=0 then begin
lbAvailable.Items.Remove(idx);
end;
end;
// SASLList.Add(CopyFrom[i]);
end;
// FListOwner := CopyFrom.Owner;
UpdateList;
end;
procedure TfrmSASLListEditor.LoadBitmaps;
var
LR: System.Resources.ResourceManager;
LB : Bitmap;
begin
LR := System.Resources.ResourceManager.Create(ResourceBaseName, System.Reflection.Assembly.GetExecutingAssembly);
try
LB := Bitmap(LR.GetObject( 'ARROWLEFT.bmp'));
LB.MakeTransparent;
Self.btnRemove.Image := LB;
LB := Bitmap(LR.GetObject( 'ARROWRIGHT.bmp'));
LB.MakeTransparent;
Self.btnAdd.Image := LB;
LB := Bitmap(LR.GetObject( 'ARROWUP.bmp'));
LB.MakeTransparent;
Self.btnUp.Image := LB;
LB := Bitmap(LR.GetObject( 'ARROWDOWN.bmp'));
LB.MakeTransparent;
Self.btnDown.Image := LB;
finally
Sys.FreeAndNil(LR);
end;
end;
procedure TfrmSASLListEditor.UpdateList;
var
i: integer;
l : TIdList;
begin
lbAssigned.Items.Clear;
FAvailObjs.Clear;
for i := 0 to FSASLList.Count -1 do begin
if Assigned(FSASLList[i].SASL) then
begin
lbAssigned.Items.Add(FSASLList[i].SASL.Name+': '+FSASLList[i].SASL.ServiceName);
end;
end;
lbAvailable.Items.Clear;
l := GlobalSASLList.LockList;
try
for i:=0 to l.count-1 do begin
if FSASLList.IndexOfComp(TIdSASL(l[i])) < 0 then begin
if Assigned(l[i]) then
begin
FAvailObjs.Add(l[i]);
lbAvailable.Items.Add(TIdSASL(l[i]).Name+': '+TIdSASL(l[i]).ServiceName);
end;
end;
end;
finally
GlobalSASLList.UnlockList;
end;
UpdateGUI;
end;
procedure TfrmSASLListEditor.UpdateGUI;
//This is necessary because unlike VCL, WinForms does not
//have a native ActionList.
begin
btnAdd.Enabled := (lbAvailable.Items.Count <> 0) and
(lbAvailable.SelectedIndex <> -1);
btnRemove.Enabled := (lbAssigned.Items.Count <> 0) and
(lbAssigned.SelectedIndex <> -1);
btnUp.Enabled := (lbAssigned.Items.Count > 1) and
(lbAssigned.SelectedIndex > 0); // -1 not selected and 0 = top
btnDown.Enabled := (lbAssigned.Items.Count > 1) and
(lbAssigned.SelectedIndex <> -1) and (lbAssigned.SelectedIndex < (lbAssigned.Items.Count - 1));
end;
end.
|
unit K395658792;
{* [Requestlink:395658792] }
// Модуль: "w:\archi\source\projects\Archi\Tests\K395658792.pas"
// Стереотип: "TestCase"
// Элемент модели: "K395658792" MUID: (506ACB600085)
// Имя типа: "TK395658792"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3IntfUses
{$If NOT Defined(NoScripts)}
, ArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
;
type
TK395658792 = class({$If NOT Defined(NoScripts)}
TArchiInsiderTest
{$IfEnd} // NOT Defined(NoScripts)
)
{* [Requestlink:395658792] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK395658792
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *506ACB600085impl_uses*
//#UC END# *506ACB600085impl_uses*
;
{$If NOT Defined(NoScripts)}
function TK395658792.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'SelectionTests';
end;//TK395658792.GetFolder
function TK395658792.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '506ACB600085';
end;//TK395658792.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK395658792.Suite);
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest)
end.
|
object FormDireitosAcesso: TFormDireitosAcesso
Left = 466
Top = 219
ActiveControl = edGrupo
Caption = 'Direitos de Acesso'
ClientHeight = 547
ClientWidth = 551
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
OnClose = FormClose
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 14
object cxGroupBox1: TcxGroupBox
Left = 0
Top = 0
Align = alTop
Alignment = alTopCenter
Caption = 'Grupos de Acesso'
Style.LookAndFeel.SkinName = 'Blue'
StyleDisabled.LookAndFeel.SkinName = 'Blue'
StyleFocused.LookAndFeel.SkinName = 'Blue'
StyleHot.LookAndFeel.SkinName = 'Blue'
TabOrder = 0
Height = 85
Width = 551
object Label1: TLabel
Left = 3
Top = 15
Width = 89
Height = 14
Caption = 'Escolha o Grupo'
end
object btnSair: TcxButton
Left = 483
Top = 22
Width = 38
Height = 33
Cursor = crHandPoint
Hint = 'Sair'
LookAndFeel.NativeStyle = False
LookAndFeel.SkinName = 'Blue'
OptionsImage.Glyph.Data = {
76060000424D7606000000000000360400002800000018000000180000000100
08000000000040020000120B0000120B0000000100000000000000000000FFFF
FF00FF00FF004E1E1F00BF4C4D00BD4B4C00C04D4E00C14E4F00C4505100C24F
5000C5515200B64B4C00C9545500C7535400C6525300CA555600CB565700CE58
5900CC575800C5545500D05A5B00CF595A00D35C5D00D15B5C00D55E5F00D45D
5E00D8606200D75F6000AF4E4F00D9626300DD656600DC646500DA636400E067
6800DE666700E2696A00E1686900E56B6C00E36A6B00E96E6F00E76D6E00E66C
6D009F4B4C00EA6F7000A04C4D00EB707200A34E4F00EE737400ED7273009C4B
4C00F2767700F0757600EF747500E06D6E00A6515200F6797A00F4787900F377
7800A9535400F87B7D00F77A7B00FB7E7F00FA7D7E00AF585900AC5657009A4D
4E00FF818200FE808100FC7F8000F77E7F00B25B5C00EE7A7B00D56F7000B860
6200B6626300AF5E5F00FE8B8C0091515200FC929300EF909100FB9A9C00E690
9100EB959600FAA3A400F8AAAB00F2A9AA00EEA6A700F7B5B600A5505000994B
4B00AB555500B15A5A00B55D5D00B75F5F00914B4B00BB636300BF666600BD65
65008C4B4B00894B4B009F58580098555500824B4B00EB9C9C00F7B1B100EECE
AF00FFFFD300D9F6BD00B7EBAA0058A55B003F9E4C005ED3770045CA67001EBC
4C00000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000020202020202
02020202026603020202020202020202020202020202020202026666625E0302
020202020202020202020202020202666663310B052A03020202020202020202
02020202026666411C070604042A03596666666666666666020202020266130C
0D0E0A08092C034C4E505354685757660202020202661112100F0C0D0E2E036E
71717171717157660202020202661714151112100F58036E7171717171715766
0202020202661818191617141536036E7171717171715766020202020266201D
1A1B1819163A036E7171717171715766020202020266221E1F201D1A1B5A036E
71717171717157660202020202662324212235511F40036D7171717171715766
020202020266282925265601673F03696C6F6F70707057660202020202662D2B
27285501525B03696A6A6A6A6B6B5766020202020266342F302D2B4F28460369
6A6A6A6A6A6A576602020202026639393233342F305C03696A6A6A6A6A6A5766
0202020202663B3C37383932335D03696A6A6A6A6A6A5766020202020266443D
3E3B3C37384903696A6A6A6A6A6A576602020202026642424344443D3E5F0369
6A6A6A6A6A6A5766020202020266424242424243436103696A6A6A6A6A6A5766
020202020266454242424242426003696A6A6A6A6A6A5766020202020266664B
48424242426003696A6A6A6A6A6A57660202020202020266664D4A474260035E
6666666666666666020202020202020202026666656403020202020202020202
0202020202020202020202020266030202020202020202020202}
ParentShowHint = False
ShowHint = True
TabOrder = 0
OnClick = btnSairClick
end
object btnGravar: TcxButton
Left = 439
Top = 22
Width = 38
Height = 33
Cursor = crHandPoint
Hint = 'Gravar'
Enabled = False
LookAndFeel.NativeStyle = False
LookAndFeel.SkinName = 'Blue'
OptionsImage.Glyph.Data = {
76060000424D7606000000000000360400002800000018000000180000000100
08000000000040020000120B0000120B0000000100000000000000000000FFFF
FF00FF00FF000066000008790F000B7E130012A9200013AB220014AB2300118D
1D0013AB230014AC250014AB240015AC260017AE270018AE290019AF2B00148D
21001CB22F001EB432001FB534001A902A0020AA34001D952E001F99310021AB
360022AC380021A3350026BA3E0024AD3A0025AE3C0024A5390027AF3E0025A6
3B0028B0400029B1410027A73E002EC04A002FC14C002FB34A0037C8570031B0
4D0036BC55003ABF5B003FCE630040CF640048D56F0047CF6D004FDA790050DB
7B0055E0820059E289005BE48A00000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000020202020202
0202020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202020202020202
02020302020202020202020202020202020202020202020202031B0302020202
02020202020202020202020202020202031F0622030202020202020202020202
020202020202020324130F072003020202020202020202020202020202020318
251C14100A1E03020202020202020202020202020203172C28262103230B1D03
0202020202020202020202020315302E2D27030203120D1A0302020202020202
02020202033332312A0302020203110E1903020202020202020202020329342B
03020202020202030F160302020202020202020202032F030202020202020202
0310080302020202020202020202030202020202020202020203050C03020202
0202020202020202020202020202020202020203090302020202020202020202
0202020202020202020202020304030202020202020202020202020202020202
0202020202020303020202020202020202020202020202020202020202020202
0302020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202}
ParentShowHint = False
ShowHint = True
TabOrder = 1
OnClick = btnGravarClick
end
object edGrupo: TcxLookupComboBox
Left = 3
Top = 30
Properties.ButtonGlyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000120B0000120B0000000100000000000000000000FFFF
FF00FF00FF00623C230062442D005339240072503300CB925E00DAA97600836E
5800695A4600FFCF8900C2AC8600D4D0C9000A0A0900EDFFFF00F8FFFF0064A5
AD003692AD0051D4FF00EEFBFF000089BC0039CAFF005CD3FF00091114000493
C9000C96CF000FA1DC001CBFFF001EC1FF0021BCFB0021BAFA002BC2FE0031C2
FF002882A50057D0FF005DBAE0008CDDFF00C1EDFF00D0F2FF000075AA00027F
B600129DDD0017A1E0001CB1F2001BADEB001AA5E0001FB7F8001FB4F4001EAF
ED003FC5FE0045ABD7004AADD7004093B8007ACEF40072BBDD008AC5DE009DCC
E200D0EBF700006FA5000173AA000774AC00087AB5000B84C0001498D700148A
C5001697D50018445B0044ABDE0041A0D00099D3EF00AAD0E300BFE5F7000474
AF00056BA5000B5B88000C4B6D001680B8002182B60000578A00035A91000464
9E00046099000454860000518800002A470000243D0002558E0002416A000351
8800033E640006609A000E6096000D24330000447600013B650000386C00161D
2300000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000020202020202
0202020202020202020202020202020202020202020202020202020202020202
02505853020202020202020202020202572205184B0202020202020202020257
1C120B045D0260600202020202572D4232240807615C60605A02020257201345
460F0D094344340A0E5F524D1725263A3539374E1A212E0C0356595748101427
3329283B192F1D11065557475738362316313F3C151B1E2A4C5E025757574140
2C1F302B3D4F5B02020202020202024A513E4954020202020202020202020202
0202020202020202020202020202020202020202020202020202020202020202
0202020202020202020202020202020202020202020202020202}
Properties.DropDownRows = 60
Properties.DropDownWidth = 230
Properties.KeyFieldNames = 'GRUPO'
Properties.ListColumns = <
item
FieldName = 'GRUPO'
end
item
FieldName = 'NOME'
end>
Properties.ListOptions.SyncMode = True
Properties.ListSource = Dados.dsGrupoModulos
Properties.OnChange = edGrupoPropertiesChange
Style.LookAndFeel.SkinName = 'Blue'
StyleDisabled.LookAndFeel.SkinName = 'Blue'
StyleFocused.LookAndFeel.SkinName = 'Blue'
StyleHot.LookAndFeel.SkinName = 'Blue'
TabOrder = 2
OnExit = edGrupoExit
OnKeyPress = edGrupoKeyPress
Width = 88
end
object lbGrupo: TcxLabel
Left = 93
Top = 31
AutoSize = False
Style.BorderStyle = ebsOffice11
Style.LookAndFeel.SkinName = 'Blue'
Style.Shadow = True
Style.TextStyle = [fsBold]
StyleDisabled.LookAndFeel.SkinName = 'Blue'
StyleFocused.LookAndFeel.SkinName = 'Blue'
StyleHot.LookAndFeel.SkinName = 'Blue'
Height = 21
Width = 331
end
object cxMarcaTodos: TcxCheckBox
Left = 2
Top = 58
Cursor = crHandPoint
Caption = 'Marcar todos'
ParentFont = False
Properties.OnChange = cxMarcaTodosPropertiesChange
Style.Font.Charset = DEFAULT_CHARSET
Style.Font.Color = clWindowText
Style.Font.Height = -12
Style.Font.Name = 'Tahoma'
Style.Font.Style = []
Style.LookAndFeel.SkinName = 'Blue'
Style.Shadow = False
Style.IsFontAssigned = True
StyleDisabled.LookAndFeel.SkinName = 'Blue'
StyleFocused.LookAndFeel.SkinName = 'Blue'
StyleHot.LookAndFeel.SkinName = 'Blue'
TabOrder = 4
Width = 95
end
end
object cxGroupBox2: TcxGroupBox
Left = 0
Top = 85
Align = alClient
Alignment = alTopCenter
Caption = 'M'#243'dulos do Sistema'
Style.LookAndFeel.SkinName = 'Blue'
StyleDisabled.LookAndFeel.SkinName = 'Blue'
StyleFocused.LookAndFeel.SkinName = 'Blue'
StyleHot.LookAndFeel.SkinName = 'Blue'
TabOrder = 1
Height = 462
Width = 551
object cxGrid1: TcxGrid
Left = 2
Top = 19
Width = 547
Height = 441
Align = alClient
TabOrder = 0
LookAndFeel.SkinName = 'Black'
object cxGrid1DBTableView1: TcxGridDBTableView
Navigator.Buttons.CustomButtons = <>
Navigator.Buttons.Insert.Enabled = False
Navigator.Buttons.Insert.Visible = False
Navigator.Buttons.Append.Enabled = False
Navigator.Buttons.Delete.Enabled = False
Navigator.Buttons.Delete.Visible = False
Navigator.Buttons.Edit.Enabled = False
Navigator.Buttons.Edit.Visible = False
Navigator.Buttons.Post.Enabled = False
Navigator.Buttons.Post.Visible = False
Navigator.Buttons.Cancel.Enabled = False
Navigator.Buttons.Cancel.Visible = False
Navigator.Buttons.Refresh.Enabled = False
Navigator.Buttons.Refresh.Visible = False
Navigator.Buttons.SaveBookmark.Enabled = False
Navigator.Buttons.SaveBookmark.Visible = False
Navigator.Buttons.GotoBookmark.Enabled = False
Navigator.Buttons.GotoBookmark.Visible = False
Navigator.Buttons.Filter.Enabled = False
Navigator.Buttons.Filter.Visible = False
OnCellClick = cxGrid1DBTableView1CellClick
DataController.DataSource = dsVTModulos
DataController.KeyFieldNames = 'ID'
DataController.Summary.DefaultGroupSummaryItems = <>
DataController.Summary.FooterSummaryItems = <>
DataController.Summary.SummaryGroups = <>
OptionsCustomize.ColumnSorting = False
OptionsCustomize.ColumnsQuickCustomization = True
OptionsData.CancelOnExit = False
OptionsData.Deleting = False
OptionsData.DeletingConfirmation = False
OptionsData.Editing = False
OptionsData.Inserting = False
OptionsView.ColumnAutoWidth = True
object cxGrid1DBTableView1ID: TcxGridDBColumn
DataBinding.FieldName = 'ID'
Visible = False
Width = 31
end
object cxGrid1DBTableView1DESCGRUPO: TcxGridDBColumn
Caption = 'Grupo'
DataBinding.FieldName = 'DESCGRUPO'
Visible = False
GroupIndex = 0
Options.Editing = False
Width = 80
end
object cxGrid1DBTableView1ITEMMENU: TcxGridDBColumn
Caption = 'M'#243'dulos'
DataBinding.FieldName = 'ITEMMENU'
Options.Editing = False
Width = 224
end
object cxGrid1DBTableView1HABILITADO: TcxGridDBColumn
Caption = 'Permitir'
DataBinding.FieldName = 'HABILITADO'
PropertiesClassName = 'TcxCheckBoxProperties'
Properties.DisplayChecked = 'S'
Properties.DisplayUnchecked = 'N'
Properties.ImmediatePost = True
Properties.ValueChecked = 'S'
Properties.ValueUnchecked = 'N'
HeaderAlignmentHorz = taCenter
Width = 54
end
end
object cxGrid1Level1: TcxGridLevel
GridView = cxGrid1DBTableView1
end
end
end
object VTModulos: TVirtualTable
FieldDefs = <
item
Name = 'MODULO'
DataType = ftString
Size = 3
end
item
Name = 'GRUPO'
DataType = ftString
Size = 3
end
item
Name = 'DESCGRUPO'
DataType = ftString
Size = 20
end
item
Name = 'MENU'
DataType = ftInteger
end
item
Name = 'ITEMMENU'
DataType = ftString
Size = 30
end
item
Name = 'HABILITADO'
DataType = ftString
Size = 1
end>
Left = 436
Top = 65
Data = {
0300060006004D4F44554C4F01000300000000000500475255504F0100030000
000000090044455343475255504F010014000000000004004D454E5503000000
0000000008004954454D4D454E5501001E00000000000A00484142494C495441
444F0100010000000000000000000000}
object VTModulosID: TIntegerField
FieldName = 'ID'
end
object VTModulosMODULO: TStringField
FieldName = 'MODULO'
Size = 3
end
object VTModulosGRUPO: TStringField
FieldName = 'GRUPO'
Size = 3
end
object VTModulosMENU: TIntegerField
FieldName = 'MENU'
end
object VTModulosDESCGRUPO: TStringField
FieldName = 'DESCGRUPO'
end
object VTModulosITEMMENU: TStringField
FieldName = 'ITEMMENU'
Size = 30
end
object VTModulosHABILITADO: TStringField
FieldName = 'HABILITADO'
Size = 1
end
end
object dsVTModulos: TIBCDataSource
DataSet = VTModulos
Left = 484
Top = 65
end
end
|
{#(@)$Id: TestFramework.pas,v 1.57 2015/04/28 10:45:22 lulin Exp $ }
{ DUnit: An XTreme testing framework for Delphi programs. }
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is DUnit.
*
* The Initial Developers of the Original Code are Kent Beck, Erich Gamma,
* and Juancarlo Aсez.
* Portions created The Initial Developers are Copyright (C) 1999-2000.
* Portions created by The DUnit Group are Copyright (C) 2000-2004.
* All rights reserved.
*
* Contributor(s):
* Kent Beck <kentbeck@csi.com>
* Erich Gamma <Erich_Gamma@oti.com>
* Juanco Aсez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* Uberto Barbini <uberto@usa.net>
* Brett Shearer <BrettShearer@users.sourceforge.net>
* Kris Golko <neuromancer@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
{$IFDEF CLR}
{$UNSAFECODE ON}
{$ENDIF}
{$BOOLEVAL OFF}
unit TestFramework;
interface
uses
{$IFDEF CLR}
System.Reflection,
{$ENDIF}
SysUtils,
Classes,
IniFiles;
const
rcs_id: AnsiString = '#(@)$Id: TestFramework.pas,v 1.57 2015/04/28 10:45:22 lulin Exp $';
rcs_version : AnsiString = '$Revision: 1.57 $';
type
{$IFDEF CLR}
// Pointer = Borland.Delphi.System.Pointer;
IUnknown = interface(IInterface)
end;
TestAttribute = class(TCustomAttribute)
end;
{$ENDIF}
{$IFDEF CLR}
TTestMethod = AnsiString;
{$ELSE}
TTestMethod = procedure of object;
{$ENDIF}
TTestProc = procedure;
TTestCaseClass = class of TTestCase;
ITestListener = interface;
IStatusListener = interface;
TTestResult = class;
TAbstractTest = class;
TTestCase = class;
TTestSuite = class;
TTestFailure = class;
ExceptionClass = class of Exception;
ETestFailure = class(EAbort)
constructor Create; overload;
constructor Create(msg :AnsiString); overload;
end;
EDunitException = class(Exception);
ETestError = class(EDunitException);
EStopTestsFailure = class(ETestFailure);
EPostTestFailure = class(ETestFailure);
TAllowedLeakArray = array[0..3] of integer;
TListIterator = function: integer of object;
IMemLeakMonitor = interface(IUnknown)
['{041368CC-5B04-4111-9E2E-05A5908B3A58}']
function MemLeakDetected(out LeakSize: Integer): Boolean;
end;
IDUnitMemLeakMonitor = interface(IMemLeakMonitor)
['{45466FCA-1ADC-4457-A41C-88FA3F8D23F7}']
function MemLeakDetected(const AllowedLeakSize: Integer;
const FailOnMemoryRecovery: Boolean;
out LeakSize: Integer): Boolean; overload;
function MemLeakDetected(const AllowedValuesGetter: TListIterator;
const FailOnMemoryRecovery: Boolean;
out LeakIndex: integer;
out LeakSize: Integer): Boolean; overload;
function GetMemoryUseMsg(const FailOnMemoryRecovery: Boolean;
const TestProcChangedMem: Integer;
out ErrorMsg: AnsiString): Boolean; overload;
function GetMemoryUseMsg(const FailOnMemoryRecovery: boolean;
const TestSetupChangedMem: Integer;
const TestProcChangedMem: Integer;
const TestTearDownChangedMem: Integer;
const TestCaseChangedMem: Integer;
out ErrorMsg: AnsiString): boolean; overload;
procedure MarkMemInUse;
end;
{ thrown to force a debugger break on a test failure }
EBreakingTestFailure = class(EDunitException)
constructor Create; overload;
constructor Create(msg :AnsiString); overload;
end;
ITest = interface(IUnknown)
['{89CCD557-7DE1-4814-B033-ABAFE0870EC7}']
function GetFolder: AnsiString;
function GetName: AnsiString;
function GetDisplayName: AnsiString;
function TestClassName: AnsiString;
function GetSuffixName: AnsiString;
function CountTestCases: Integer;
function CountEnabledTestCases: Integer;
function Tests: IInterfaceList;
procedure SetUp;
procedure TearDown;
function Run : TTestResult; overload;
procedure Run(aTestResult: TTestResult; aRandom: Boolean); overload;
procedure RunWithFixture(aTestResult: TTestResult; aRandom: Boolean);
procedure RunTest(aTestResult: TTestResult; aRandom: Boolean);
function GetTestMethodInvoked: Boolean;
procedure SetTestMethodInvoked(const Value: Boolean);
property TestMethodInvoked: Boolean read GetTestMethodInvoked
write SetTestMethodInvoked;
procedure SetScriptName(const aName: AnsiString);
procedure ClearEtalons;
function GetEnabled: Boolean;
procedure SetEnabled(Value: Boolean);
procedure SetStartTime(Value :Int64);
function GetStartTime : Int64;
procedure SetStopTime(Value :Int64);
function GetStopTime : Int64;
function ElapsedTestTime: Cardinal;
procedure SetStatusListener(Listener :IStatusListener);
function GetStatus :AnsiString;
procedure LoadConfiguration(const iniFile :TCustomIniFile; const section :AnsiString); overload;
procedure LoadConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean); overload;
procedure SaveConfiguration(const iniFile :TCustomIniFile; const section :AnsiString); overload;
procedure SaveConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean); overload;
function GetSubFolder: AnsiString;
procedure SetGUIObject(const guiObject: TObject);
function GetGUIObject: TObject;
function HasScriptChildren: Boolean;
property Folder: AnsiString read GetFolder;
property Name: AnsiString read GetName;
property DisplayName: AnsiString read GetDisplayName;
property Enabled: Boolean read GetEnabled write SetEnabled;
property GUIObject: TObject read GetGUIObject write SetGUIObject;
property Status: AnsiString read GetStatus;
property StartTime: Int64 read GetStartTime write SetStartTime;
property StopTime: Int64 read GetStopTime write SetStopTime;
procedure SetFailsOnNoChecksExecuted(const Value: Boolean);
function GetFailsOnNoChecksExecuted: Boolean;
property FailsOnNoChecksExecuted: Boolean
read GetFailsOnNoChecksExecuted
write SetFailsOnNoChecksExecuted;
function GetFailsOnMemoryLeak: Boolean;
procedure SetFailsOnMemoryLeak(const Value: Boolean);
property FailsOnMemoryLeak: Boolean
read GetFailsOnMemoryLeak
write SetFailsOnMemoryLeak;
function GetAllowedMemoryLeakSize: Integer;
procedure SetAllowedMemoryLeakSize(const NewSize: Integer);
property AllowedMemoryLeakSize: Integer read GetAllowedMemoryLeakSize
write SetAllowedMemoryLeakSize;
function GetFailsOnMemoryRecovery: Boolean;
procedure SetFailsOnMemoryRecovery(const Value: Boolean);
property FailsOnMemoryRecovery: Boolean
read GetFailsOnMemoryRecovery
write SetFailsOnMemoryRecovery;
procedure SetAllowedLeakArray(AllowedList: array of Integer);
function GetIgnoreSetUpTearDownLeaks: Boolean;
procedure SetIgnoreSetUpTearDownLeaks(const Value: Boolean);
property IgnoreSetUpTearDownLeaks: Boolean
read GetIgnoreSetUpTearDownLeaks
write SetIgnoreSetUpTearDownLeaks;
function GetAllowedLeak: Integer;
function GetAllowedLeaksIterator: TListIterator;
property AllowedLeaksIterator: TListIterator read GetAllowedLeaksIterator;
end;
{: General interface for test decorators}
ITestDecorator = interface(ITest)
['{8B3FC229-3033-4590-AD5C-01914C6E2C9F}']
{: Get the decorated test
@return The decorated test }
function GetTest: ITest;
property Test: ITest read GetTest;
end;
{ IStatusListeners are notified of test status messages }
IStatusListener = interface
['{8681DC88-033C-4A42-84F4-4C52EF9ABAC0}']
procedure Status(test :ITest; const Msg :AnsiString);
end;
{ ITestListeners get notified of testing events.
See TTestResult.AddListener()
}
ITestListener = interface(IStatusListener)
['{114185BC-B36B-4C68-BDAB-273DBD450F72}']
procedure TestingStarts;
procedure StartTest(test: ITest);
procedure AddSuccess(const test: ITest);
procedure AddError(error: TTestFailure);
procedure AddFailure(Failure: TTestFailure);
procedure EndTest(test: ITest);
procedure TestingEnds(testResult :TTestResult);
function ShouldRunTest(test :ITest):Boolean;
end;
ITestListenerX = interface(ITestListener)
['{5C28B1BE-38B5-4D6F-AA96-A04E9302C317}']
procedure StartSuite(suite: ITest);
procedure EndSuite(suite: ITest);
end;
// a named collection of tests
ITestSuite = interface(ITest)
['{C20E38EF-7369-44D9-9D84-08E84EC1DCF0}']
procedure ReReadAbstractTests;
procedure AddTest(const aTest: ITest);
procedure AddSuite(aSuite : ITestSuite);
function GetDataFolder: AnsiString;
{* Папка с данными для авто-тестов. }
end;
{ Adapter to allow a TTestResult to receive status messages
from the running test }
TStatusToResultAdapter = class(TInterfacedObject, IStatusListener)
protected
FTestResult :TTestResult;
public
constructor Create(TestResult :TTestResult);
procedure Status(Test :ITest; const Msg :AnsiString);
end;
{ A TTestResult collects the results of executing a test case.
And notifies registered ITestListener of testing events. }
TTestResult = class(TObject)
private
FTotalTime: Int64;
protected
FFailures: TList;
FErrors: TList;
FOverRides: Integer;
FListeners: IInterfaceList;
FRootTest: ITest;
FRunTests: integer;
FStop: Boolean;
FBreakOnFailures :Boolean;
FFailsIfNoChecksExecuted: Boolean;
FIgnoresMemoryLeakInSetUpTearDown: Boolean;
FMemoryLeakIgnoredInSetupOrTearDown: boolean;
FFailsIfMemoryLeaked: Boolean;
FMethodPtr: Pointer;
FStatusAdapter :IStatusListener;
procedure Run(aTest: ITest; aRandom: Boolean); virtual;
function RunTestSetup(test: ITest):Boolean; virtual;
procedure RunTestTearDown(test: ITest); virtual;
function RunTestRun(aTest: ITest; aRandmom: Boolean): Boolean; virtual;
procedure TestingStarts; virtual;
procedure StartSuite(suite: ITest); virtual;
procedure StartTest(test: ITest); virtual;
function ShouldRunTest(aTest :ITest) :Boolean; virtual;
procedure Status(test :ITest; const Msg :AnsiString); virtual;
procedure EndSuite(suite: ITest); virtual;
procedure EndTest(test: ITest); virtual;
procedure TestingEnds; virtual;
public
constructor Create;
destructor Destroy; override;
procedure AddListener(listener: ITestListener); virtual;
procedure RunSuite(aTest: ITest; aRandom: Boolean); overload;
procedure AddSuccess(const test: ITest); virtual;
function AddFailure(test: ITest; e: Exception; Addrs :Pointer): TTestFailure; overload;
function AddFailure(test: ITest; Addrs :Pointer; msg :AnsiString = ''): TTestFailure; overload;
function AddError(test: ITest; e: Exception; Addrs :Pointer; msg :AnsiString = ''): TTestFailure; virtual;
procedure Stop; virtual;
function ShouldStop: Boolean; virtual;
function RunCount: integer; virtual;
function ErrorCount: integer; virtual;
function FailureCount: integer; virtual;
function GetError(idx :Integer) :TTestFailure;
function GetFailure(idx :Integer) :TTestFailure;
function WasStopped :Boolean; virtual;
function WasSuccessful: Boolean; virtual;
property BreakOnFailures :Boolean read FBreakOnFailures write FBreakOnFailures;
property FailsIfNoChecksExecuted :Boolean read fFailsIfNoChecksExecuted
write fFailsIfNoChecksExecuted;
property FailsIfMemoryLeaked :Boolean read fFailsIfMemoryLeaked
write fFailsIfMemoryLeaked;
property IgnoresMemoryLeakInSetUpTearDown: Boolean
read FIgnoresMemoryLeakInSetUpTearDown
write FIgnoresMemoryLeakInSetUpTearDown;
property MemoryLeakIgnoredInSetupOrTearDown: Boolean
read FMemoryLeakIgnoredInSetupOrTearDown
write FMemoryLeakIgnoredInSetupOrTearDown;
property TotalTime: Int64 read FTotalTime;
property Errors[i :Integer] :TTestFailure read GetError;
property Failures[i :Integer] :TTestFailure read GetFailure;
property OverRides: integer read FOverRides write FOverRides;
end;
TAbstractTest = class(TInterfacedObject, ITest)
protected
FTestName: AnsiString;
FEnabled: Boolean;
FStartTime: Int64;
FStopTime: Int64;
FStatusListener :IStatusListener;
FStatusStrings :TStrings;
FExpectedException: ExceptionClass;
FCheckCalled: Boolean;
FFailsOnNoChecksExecuted: Boolean;
FFailsOnMemoryLeak: Boolean;
FTestMethodInvoked: Boolean;
FFailsOnMemoryRecovery: Boolean;
FIgnoreSetUpTearDownLeaks: Boolean;
FMemoryLeakIgnoredInSetupTearDown: boolean;
FAllowedLeakList: TAllowedLeakArray;
FAllowedLeakListIndex: Word;
// Object used by the GUI to map the test onto a GUI object such as a tree node
FGUIObject: TObject;
procedure Invoke(AMethod: TTestMethod); virtual;
procedure RunWithFixture(aTestResult: TTestResult; aRandom: Boolean); virtual;
procedure RunTest(aTestResult: TTestResult; aRandom: Boolean); virtual;
procedure SetUp; virtual;
procedure TearDown; virtual;
procedure SetStartTime(Value :Int64); virtual;
function GetStartTime : Int64; virtual;
procedure SetStopTime(Value :Int64); virtual;
function GetStopTime : Int64; virtual;
procedure SetGUIObject(const guiObject: TObject);
function GetGUIObject: TObject;
procedure SetFailsOnNoChecksExecuted(const Value: Boolean);
function GetFailsOnNoChecksExecuted: Boolean;
function GetFailsOnMemoryLeak: Boolean;
procedure SetFailsOnMemoryLeak(const Value: Boolean);
{$IFNDEF CLR} // related to Check(Not)EqualsMem, pointer based, unsuitable for .NET
function GetMemDiffStr(expected, actual: pointer; size:longword; msg:AnsiString):AnsiString;
{$ENDIF}
function GetAllowedMemoryLeakSize: Integer;
procedure SetAllowedMemoryLeakSize(const NewSize: Integer);
function GetFailsOnMemoryRecovery: Boolean;
procedure SetFailsOnMemoryRecovery(const Value: Boolean);
function GetIgnoreSetUpTearDownLeaks: Boolean;
procedure SetIgnoreSetUpTearDownLeaks(const Value: Boolean);
function GetMemoryLeakIgnoredInSetupTearDown: Boolean;
procedure SetMemoryLeakIgnoredInSetupTearDown(const Value: Boolean);
procedure SetAllowedLeakArray(AllowedList: array of Integer);
function GetAllowedLeak: Integer; // Is the iterator returned below
function GetAllowedLeaksIterator: TListIterator;
procedure Cleanup; virtual;
procedure InitFields; virtual;
procedure DoSetScriptName(const aName: AnsiString); virtual;
function DoHasScriptChildren: Boolean; virtual;
function GetSubFolder: AnsiString;
function DoGetSubFolder: AnsiString; virtual; abstract;
procedure ClearEtalons;
procedure DoClearEtalon; virtual; abstract;
public
function HasScriptChildren: Boolean;
procedure SetScriptName(const aName: AnsiString);
function NotForTerminalSession: Boolean; virtual;
constructor Create(aName: AnsiString);
destructor Destroy; override;
function GetFolder: AnsiString; virtual;
function GetModelElementGUID: AnsiString; virtual;
function GetName: AnsiString; virtual;
function GetDisplayName: AnsiString; virtual;
function GetSuffixName: AnsiString;
function TestClassName: AnsiString;
function GetEnabled: Boolean; virtual;
procedure SetEnabled(value: Boolean); virtual;
function Tests: IInterfaceList; virtual;
function CountTestCases: Integer; virtual;
function CountEnabledTestCases: Integer; virtual;
function Run: TTestResult; overload;
procedure Run(aTestResult: TTestResult; aRandom: Boolean); overload;
function GetTestMethodInvoked: Boolean;
procedure SetTestMethodInvoked(const Value: Boolean);
function ElapsedTestTime: Cardinal; virtual;
procedure SetStatusListener(Listener :IStatusListener);
procedure Status(const Msg :AnsiString);
function GetStatus :AnsiString;
procedure LoadConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean); overload;
procedure LoadConfiguration(const iniFile :TCustomIniFile; const section :AnsiString); overload; virtual;
procedure SaveConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean); overload;
procedure SaveConfiguration(const iniFile :TCustomIniFile; const section :AnsiString); overload; virtual;
property Folder: AnsiString read GetFolder;
property Name: AnsiString read GetName;
property Enabled: Boolean read GetEnabled write SetEnabled;
function BoolToStr(ABool: Boolean): AnsiString;
procedure Check(condition: Boolean; msg: AnsiString = ''); virtual;
procedure CheckTrue(condition: Boolean; msg: AnsiString = ''); virtual;
procedure CheckFalse(condition: Boolean; msg: AnsiString = ''); virtual;
procedure CheckEquals(expected, actual: extended; msg: AnsiString = ''); overload; virtual;
procedure CheckEquals(expected, actual: extended; delta: extended; const msg: AnsiString = ''); overload; virtual;
procedure CheckEquals(expected, actual: integer; const msg: AnsiString = ''); overload; virtual;
procedure CheckEquals(expected, actual: AnsiString; const msg: AnsiString = ''); overload; virtual;
procedure CheckEqualsString(expected, actual: AnsiString; const msg: AnsiString = ''); virtual;
{$IFNDEF CLR}
procedure CheckEquals(expected, actual: WideString; msg: AnsiString = ''); overload; virtual;
procedure CheckEqualsWideString(expected, actual: WideString; msg: AnsiString = ''); virtual;
procedure CheckEqualsMem(expected, actual: pointer; size:longword; msg:AnsiString=''); virtual;
{$ENDIF}
procedure CheckEquals(expected, actual: Boolean; msg: AnsiString = ''); overload; virtual;
procedure CheckEqualsBin(expected, actual: longword; msg: AnsiString = ''; digits: integer=32); virtual;
procedure CheckEqualsHex(expected, actual: longword; msg: AnsiString = ''; digits: integer=8); virtual;
procedure CheckNotEquals(expected, actual: integer; msg: AnsiString = ''); overload; virtual;
procedure CheckNotEquals(expected: extended; actual: extended; delta: extended = 0; msg: AnsiString = ''); overload; virtual;
procedure CheckNotEquals(expected, actual: AnsiString; msg: AnsiString = ''); overload; virtual;
procedure CheckNotEqualsString(expected, actual: AnsiString; msg: AnsiString = ''); virtual;
{$IFNDEF CLR}
procedure CheckNotEquals(const expected, actual: WideString; msg: AnsiString = ''); overload; virtual;
procedure CheckNotEqualsWideString(const expected, actual: WideString; msg: AnsiString = ''); virtual;
procedure CheckNotEqualsMem(expected, actual: pointer; size:longword; msg:AnsiString=''); virtual;
{$ENDIF}
procedure CheckNotEquals(expected, actual: Boolean; msg: AnsiString = ''); overload; virtual;
procedure CheckNotEqualsBin(expected, actual: longword; msg: AnsiString = ''; digits: integer=32); virtual;
procedure CheckNotEqualsHex(expected, actual: longword; msg: AnsiString = ''; digits: integer=8); virtual;
procedure CheckNotNull(obj :IUnknown; msg :AnsiString = ''); overload; virtual;
procedure CheckNull(obj: IUnknown; msg: AnsiString = ''); overload; virtual;
procedure CheckSame(expected, actual: IUnknown; msg: AnsiString = ''); overload; virtual;
procedure CheckSame(expected, actual: TObject; msg: AnsiString = ''); overload; virtual;
procedure CheckNotNull(obj: TObject; msg: AnsiString = ''); overload; virtual;
procedure CheckNull(obj: TObject; msg: AnsiString = ''); overload; virtual;
procedure CheckException(AMethod: TTestMethod; AExceptionClass: TClass; const msg :AnsiString = '');
procedure CheckEquals( expected, actual: TClass; const msg: AnsiString = ''); overload; virtual;
procedure CheckInherits(expected, actual: TClass; const msg: AnsiString = ''); overload; virtual;
procedure CheckIs(AObject :TObject; AClass: TClass; const msg: AnsiString = ''); overload; virtual;
procedure Fail(const msg: AnsiString; ErrorAddrs: Pointer = nil); overload; virtual;
procedure FailEquals(expected, actual: WideString; const msg: AnsiString = ''; ErrorAddrs: Pointer = nil); virtual;
procedure FailNotEquals(expected, actual: WideString; const msg: AnsiString = ''; ErrorAddrs: Pointer = nil); virtual;
procedure FailNotSame(expected, actual: WideString; const msg: AnsiString = ''; ErrorAddrs: Pointer = nil); virtual;
function EqualsErrorMessage(expected, actual :WideString; msg: AnsiString): WideString;
function NotEqualsErrorMessage(expected, actual :WideString; msg: AnsiString): WideString;
function NotSameErrorMessage(expected, actual, msg: AnsiString): WideString;
procedure StopTests(msg: AnsiString = ''); virtual;
{$IFNDEF CLR}
procedure CheckMethodIsNotEmpty(MethodPointer: pointer);
{$ENDIF}
procedure StartExpectingException(e: ExceptionClass);
procedure StopExpectingException(msg :AnsiString = '');
property ExpectedException :ExceptionClass
read fExpectedException
write StartExpectingException;
published
property FailsOnNoChecksExecuted: Boolean
read GetFailsOnNoChecksExecuted
write SetFailsOnNoChecksExecuted;
property FailsOnMemoryLeak: Boolean
read GetFailsOnMemoryLeak
write SetFailsOnMemoryLeak;
property TestMethodInvoked: Boolean
read GetTestMethodInvoked
write SetTestMethodInvoked;
property AllowedMemoryLeakSize: Integer
read GetAllowedMemoryLeakSize
write SetAllowedMemoryLeakSize;
property AllowedLeaksIterator: TListIterator read GetAllowedLeaksIterator;
property FailsOnMemoryRecovery: Boolean
read GetFailsOnMemoryRecovery
write SetFailsOnMemoryRecovery;
property IgnoreSetUpTearDownLeaks: Boolean
read GetIgnoreSetUpTearDownLeaks
write SetIgnoreSetUpTearDownLeaks;
end;
TTestCase = class(TAbstractTest, ITest)
private
f_DataSubFolder : AnsiString;
f_TestResult : TTestResult;
protected
FMethod : TTestMethod;
protected
function ShouldStop: Boolean;
procedure Invoke(AMethod: TTestMethod); override;
procedure RunWithFixture(aTestResult: TTestResult; aRandom: Boolean); override;
procedure RunTest(aTestResult: TTestResult; aRandom: Boolean); override;
function FolderMode: Boolean;
{* - Тест для файлов из папки. }
function DoGetSubFolder: AnsiString; override;
procedure DoClearEtalon; override;
public
constructor Create(const aMethodName, aFolder: AnsiString); virtual;
class function TestNeedFolder: Boolean; virtual;
class function Suite: ITestSuite; virtual;
class function IsScript: Boolean; virtual;
procedure Run(aTestResult: TTestResult; aRandom: Boolean); overload;
public
property DataSubFolder: AnsiString
read f_DataSubFolder;
{* Папка с данными тестов для режима работы с файлами из папки. }
end;
TTestSuite = class(TAbstractTest, ITestSuite, ITest)
protected
FTests: IInterfaceList;
FSuffix : AnsiString;
procedure RunTest(aTestResult: TTestResult; aRandom: Boolean); override;
procedure DoAddTest(const aTest: ITest); virtual;
function GetDataFolder: AnsiString; virtual;
{* Возвращает папку с данными для создания тестов. }
function GetExt: AnsiString; virtual;
procedure DoReReadAbstractTests;
virtual;
procedure ReReadAbstractTests;
procedure DoClearEtalon; override;
public
function DoGetSubFolder: AnsiString; override;
function GetFolder: AnsiString; override;
function GetDisplayName: AnsiString; override;
constructor Create; overload;
constructor Create(aName: AnsiString); overload;
constructor Create(aTestClass: TTestCaseClass); overload;
constructor Create(aName: AnsiString; const aTests: array of ITest); overload;
function CountTestCases: Integer; override;
function CountEnabledTestCases: Integer; override;
function Tests: IInterfaceList; override;
procedure AddTest(const aTest: ITest);
procedure AddTests(aTestClass: TTestCaseClass); virtual;
procedure AddSuite(aSuite: ITestSuite); virtual;
procedure LoadConfiguration(const iniFile: TCustomIniFile; const section: AnsiString); override;
procedure SaveConfiguration(const iniFile: TCustomIniFile; const section: AnsiString); override;
end;
TTestFailure = class(TObject)
protected
FFailedTest: ITest;
FThrownExceptionClass: TClass;
FThrownExceptionMessage: AnsiString;
FThrownExceptionAddress: Pointer;
FStackTrace: AnsiString;
procedure CaptureStackTrace;
public
constructor Create(FailedTest: ITest; thrownException: Exception; Addrs: Pointer; msg: AnsiString = ''); overload;
constructor Create(FailedTest: ITest; Addrs: Pointer; msg: AnsiString); overload;
function FailedTest: ITest; virtual;
function ThrownExceptionClass: TClass; virtual;
function ThrownExceptionName: AnsiString; virtual;
function ThrownExceptionMessage: AnsiString; virtual;
function ThrownExceptionAddress: pointer; virtual;
function LocationInfo: AnsiString; virtual;
function AddressInfo: AnsiString; virtual;
function StackTrace: AnsiString; virtual;
end;
TMethodEnumerator = class
protected
FMethodNameList: array of AnsiString;
function GetNameOfMethod(idx: integer): AnsiString;
function GetMethodCount: Integer;
public
constructor Create(AClass: TClass);
property MethodCount: integer read GetMethodCount;
property NameOfMethod[idx: integer]: AnsiString read GetNameOfMethod;
end;
function TryDeleteSrciptExtention(const aName: AnsiString): AnsiString;
function CorrectScriptKPageName(const aTest: ITest): AnsiString;
// creating suites
function TestSuite(AName: AnsiString; const Tests: array of ITest): ITestSuite;
// test registry
procedure RegisterTest(SuitePath: AnsiString; test: ITest); overload;
procedure RegisterTest(test: ITest); overload;
procedure RegisterTests(SuitePath: AnsiString; const Tests: array of ITest); overload;
procedure RegisterTests(const Tests: array of ITest); overload;
function RegisteredTests: ITestSuite;
procedure ClearRegistry;
// running tests
function RunTest(suite: ITest; const listeners: array of ITestListener; aRandom: Boolean): TTestResult; overload;
function RunRegisteredTests(const listeners: array of ITestListener): TTestResult;
// utility routines
function CallerAddr: Pointer; {$IFNDEF CLR} assembler; {$ENDIF}
function PtrToStr(p: Pointer): AnsiString;
function PointerToLocationInfo(Addrs: Pointer): AnsiString;
function PointerToAddressInfo(Addrs: Pointer): AnsiString;
function IsTestMethod(aTest: ITest): Boolean;
function IsDecorator(aTest: ITest): Boolean;
function GetDUnitRegistryKey: AnsiString;
procedure SetDUnitRegistryKey(const NewKey: AnsiString);
{$IFNDEF CLR} // - unsuitable for .NET, pointer magic
function FirstByteDiff(p1, p2: pointer; size: longword; out b1, b2: byte): integer;
{$ENDIF}
function MemLeakMonitor: IMemLeakMonitor;
// strings, used in TAbstractTestCase.EqualsErrorMessage etc.:
const sExpButWasFmt = '%sexpected: <%s> but was: <%s>';
sExpAndActualFmt = '%sexpected and actual were: <%s>';
var
TestsExitCode : Integer = 0;
{$IfDef notDebugStackTrace}
{$Undef USE_JEDI_JCL}
{$EndIf notDebugStackTrace}
{$UNDEF DETECTMEMLEAKS}
{$IFDEF VER180}
{$IFNDEF CLR}
{$DEFINE DETECTMEMLEAKS}
{$ENDIF}
{$ENDIF}
{$IFDEF FASTMM}
{$DEFINE DETECTMEMLEAKS}
{$ENDIF}
///////////////////////////////////////////////////////////////////////////
implementation
uses
{$IFDEF LINUX}
Libc,
{$ELSE}
Windows,
Registry,
{$ENDIF}
{$IFDEF USE_JEDI_JCL}
JclDebug,
{$ENDIF}
{$IFDEF DETECTMEMLEAKS}
FastMMMemLeakMonitor,
{$ENDIF}
{$IFDEF madExcept}
madStackTrace,
{$ENDIF}
TypInfo,
l3Base,
ddPicturePathListner,
StrUtils,
l3BatchService
;
const
csSeparator = ' - ';
csIgnoreClassName = 'TBaseTest';
{$STACKFRAMES ON} // Required to retrieve caller's address
{$IFNDEF DETECTMEMLEAKS}
// Stub code for use when Memory Leak detection is disabled.
// See FastMM MemLeakMonitor.pas notes for invoking memory leak detection.
type
TMemLeakMonitor = class(TInterfacedObject, IMemLeakMonitor)
private
function MemLeakDetected(out LeakSize: Integer): Boolean; overload;
end;
{ TMemMonitor }
function TMemLeakMonitor.MemLeakDetected(out LeakSize: Integer): Boolean;
begin
LeakSize := 0;
Result := False;
end;
type
TDUnitMemLeakMonitor = class(TMemLeakMonitor, IDUnitMemLeakMonitor)
function MemLeakDetected(const AllowedLeakSize: Integer;
const FailOnMemoryRecovery: Boolean;
out LeakSize: Integer): Boolean; overload;
function MemLeakDetected(const AllowedValuesGetter: TListIterator;
const FailOnMemoryRecovery: Boolean;
out LeakIndex: integer;
out LeakSize: Integer): Boolean; overload;
function GetMemoryUseMsg(const FailOnMemoryRecovery: Boolean;
const TestProcChangedMem: Integer;
out ErrorMsg: AnsiString): Boolean; overload;
function GetMemoryUseMsg(const FailOnMemoryRecovery: boolean;
const TestSetupChangedMem: Integer;
const TestProcChangedMem: Integer;
const TestTearDownChangedMem: Integer;
const TestCaseChangedMem: Integer;
out ErrorMsg: AnsiString): boolean; overload;
procedure MarkMemInUse;
end;
{ TDUnitMemMonitor }
procedure TDUnitMemLeakMonitor.MarkMemInUse;
begin
// Do Nothing
end;
function TDUnitMemLeakMonitor.MemLeakDetected(const AllowedLeakSize: Integer;
const FailOnMemoryRecovery: Boolean;
out LeakSize: Integer): Boolean;
begin
inherited MemLeakDetected(LeakSize);
Result := (AllowedLeakSize <> 0);
end;
function TDUnitMemLeakMonitor.MemLeakDetected(const AllowedValuesGetter: TListIterator;
const FailOnMemoryRecovery: Boolean;
out LeakIndex: integer;
out LeakSize: Integer): Boolean;
begin
inherited MemLeakDetected(LeakSize);
LeakIndex := 0;
Result := (AllowedValuesGetter <> 0);
end;
function TDUnitMemLeakMonitor.GetMemoryUseMsg(const FailOnMemoryRecovery: Boolean;
const TestProcChangedMem: Integer;
out ErrorMsg: AnsiString): Boolean;
begin
ErrorMsg := '';
Result := True;
end;
function TDUnitMemLeakMonitor.GetMemoryUseMsg(const FailOnMemoryRecovery: boolean;
const TestSetupChangedMem: Integer;
const TestProcChangedMem: Integer;
const TestTearDownChangedMem: Integer;
const TestCaseChangedMem: Integer;
out ErrorMsg: AnsiString): boolean;
begin
ErrorMsg := '';
Result := True;
end;
{$ENDIF}
function MemLeakMonitor: IMemLeakMonitor;
begin
Result := TMemLeakMonitor.Create;
end;
type
TMemIniFileTrimmed = class(TMemIniFile)
public
// Override the read AnsiString method to trim the AnsiString for compatibility with TIniFile
function ReadString(const Section, Ident, DefaultStr: String): String; override;
end;
var
// SubKey of HKEY_CURRENT_USER for storing configurations in the registry (end with \)
DUnitRegistryKey: AnsiString = ''; // How about 'Software\DUnitTests\';
function TryDeleteSrciptExtention(const aName: AnsiString): AnsiString;
const
csScriptExt = '.script';
var
l_Len: Integer;
begin
Result := aName;
if AnsiEndsStr(csScriptExt, Result) then
begin
l_Len := Length(csScriptExt);
Delete(Result, Length(Result) - l_Len + 1, l_Len);
end; // if AnsiEndsStr('.script', Result) then
end;
function CorrectScriptKPageName(const aTest: ITest): AnsiString;
var
l_Len: Integer;
begin
if AnsiStartsStr('TK', Result) then
begin
Result := aTest.TestClassName;
Delete(Result, 1, 2);
end
else
begin
Result := aTest.Name;
if AnsiStartsStr('TK', Result) then
Delete(Result, 1, 2)
else
if AnsiStartsStr('K', Result) then
Delete(Result, 1, 1);
Result := TryDeleteSrciptExtention(Result);
end;
end;
{$IFDEF LINUX}
var
PerformanceCounterInitValue: Int64;
procedure InitPerformanceCounter;
var
TV : TTimeVal;
TZ : TTimeZone;
begin
gettimeofday(TV, TZ);
PerformanceCounterInitValue :=
LongWord(TV.tv_sec mod (24*60*60) * 1000) + (LongWord(TV.tv_usec) div 1000);
end;
function QueryPerformanceCounter(var PerformanceCounter: Int64): LongBool;
var
TV : TTimeVal;
TZ : TTimeZone;
begin
gettimeofday(TV, TZ);
PerformanceCounter := (TV.tv_sec mod (24*60*60) * 1000) +
(TV.tv_usec div 1000);
PerformanceCounter := PerformanceCounter - PerformanceCounterInitValue;
Result := true;
end;
function QueryPerformanceFrequency(var Frequency: Int64): LongBool;
begin
Frequency := 1000;
Result := true;
end;
{$ENDIF}
{: Convert a pointer into its AnsiString representation }
function PtrToStr(p: Pointer): AnsiString;
begin
Result := Format('%p', [p])
end;
function IsBadPointer(P: Pointer):Boolean; {$IFNDEF CLR} register; {$ENDIF}
begin
try
Result := (p = nil)
{$IFNDEF CLR}
or ((Pointer(P^) <> P) and (Pointer(P^) = P));
{$ENDIF}
except
Result := true;
end
end;
function CallerAddr: Pointer; {$IFNDEF CLR} assembler; {$ENDIF}
{$IFDEF CLR}
begin
Result := nil;
end;
{$ELSE}
const
CallerIP = $4;
asm
mov eax, ebp
call IsBadPointer
test eax,eax
jne @@Error
mov eax, [ebp].CallerIP
sub eax, 5 // 5 bytes for call
push eax
call IsBadPointer
test eax,eax
pop eax
je @@Finish
@@Error:
xor eax, eax
@@Finish:
end;
{$ENDIF}
{$IFNDEF USE_JEDI_JCL}
{$IFNDEF madExcept}
function PointerToLocationInfo(Addrs: Pointer): AnsiString;
begin
//Result := GetLocationInfoStr(Addrs);
Result := '';
end;
function PointerToAddressInfo(Addrs: Pointer): AnsiString;
begin
Result := '$'+PtrToStr(Addrs);
end;
{$ELSE}
function PointerToLocationInfo(Addrs: Pointer): AnsiString;
begin
Result := StackAddrToStr( Addrs );
end;
function PointerToAddressInfo(Addrs: Pointer): AnsiString;
begin
Result := StackAddrToStr( Addrs );
end;
{$ENDIF}
{$ELSE}
function PointerToLocationInfo(Addrs: Pointer): AnsiString;
(*var
_file,
_module,
_proc: AnsiString;
_line: integer;*)
begin
Result := GetLocationInfoStr(Addrs);
(* JclDebug.MapOfAddr(Addrs, _file, _module, _proc, _line);
if _file <> '' then
Result := Format('%s:%d', [_file, _line])
else
Result := _module;*)
end;
function PointerToAddressInfo(Addrs: Pointer): AnsiString;
var
_file,
_module,
_proc: String;
_line: integer;
begin
JclDebug.MapOfAddr(Addrs, _file, _module, _proc, _line);
Result := Format('%s$%p', [_proc, Addrs]);
end;
{$ENDIF}
function IsTestMethod(aTest: ITest): Boolean;
var
aTestSuite: ITestSuite;
aTestDecorator: ITestDecorator;
begin
Assert(Assigned(aTest));
// Initialize to be sure
aTestSuite := nil;
aTestDecorator := nil;
{ The test should be a normal testmethod
when the testcount = 1 }
Result := (aTest.CountTestCases = 1);
// But not when the test is a suite? (It could have one test.)
{$IFDEF CLR}
if Supports(aTest, ITestSuite) or Supports(aTest, ITestDecorator) then
Result := false;
{$ELSE}
aTest.QueryInterface(ITestSuite, aTestSuite);
if Assigned(aTestSuite) then
Result := false;
// And not when the test is a decorator?
aTest.QueryInterface(ITestDecorator, aTestDecorator);
if Assigned(aTestDecorator) then
Result := false;
{$ENDIF}
end;
function IsDecorator(aTest: ITest): Boolean;
var
aTestDecorator: ITestDecorator;
begin
Assert(Assigned(aTest));
// Initialize to be sure
aTestDecorator := nil;
{$IFDEF CLR}
Result := Supports(aTest, ItestDecorator);
{$ELSE}
aTest.QueryInterface(ITestDecorator, aTestDecorator);
Result := Assigned(aTestDecorator);
{$ENDIF}
end;
function GetDUnitRegistryKey: AnsiString;
begin
Result := DUnitRegistryKey;
end;
procedure SetDUnitRegistryKey(const NewKey: AnsiString);
begin
DUnitRegistryKey := NewKey;
end;
{$IFNDEF CLR} // KGS: not expected to work in .NET, pointer magic follows
function ByteAt(p: pointer; const Offset: integer): byte;
begin
Result:=pByte(integer(p)+Offset)^;
end;
function FirstByteDiff(p1, p2: pointer; size: longword; out b1, b2: byte): integer;
// Returns offset of first byte pair (left to right, incrementing address) that is unequal
// Returns -1 if no difference found, or if size=0
var
i: integer;
begin
Result:=-1;
if size>0 then
for i:=0 to size-1 do // Subject to optimisation for sure:
if ByteAt(p1,i)<>ByteAt(p2,i) then
begin
Result:=i;
b1:=ByteAt(p1,i);
b2:=ByteAt(p2,i);
break;
end;
end;
{$ENDIF}
{ TTestResult }
constructor TTestResult.Create;
begin
inherited Create;
FFailures := TList.Create;
FErrors := TList.Create;
FListeners := TInterfaceList.Create;
FRunTests := 0;
FStop := false;
FStatusAdapter := TStatusToResultAdapter.Create(Self);
end;
destructor TTestResult.destroy;
var
i: Integer;
begin
for i := 0 to fErrors.Count - 1 do
begin
TTestFailure(fErrors[i]).Free;
end;
FErrors.Free;
for i := 0 to fFailures.Count - 1 do
begin
TTestFailure(fFailures[i]).Free;
end;
FreeAndNil(FFailures);
inherited;
end;
procedure TTestResult.AddSuccess(const test: ITest);
var
i: integer;
begin
assert(assigned(test));
for i := 0 to fListeners.count - 1 do
begin
(fListeners[i] as ITestListener).AddSuccess(test);
end;
end;
function TTestResult.AddError(test: ITest; e: Exception; Addrs: Pointer; msg: AnsiString): TTestFailure;
var
i: integer;
TestFailureError: TTestFailure;
begin
assert(assigned(test));
assert(assigned(e));
assert(assigned(fErrors));
l3System.Exception2Log(e);
TestFailureError := TTestFailure.Create(test, e, Addrs, msg);
FErrors.add(TestFailureError);
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).AddError(TestFailureError);
end;
assert(assigned(TestFailureError));
Result := TestFailureError;
end;
function TTestResult.AddFailure(test: ITest; e: Exception; Addrs: Pointer): TTestFailure;
var
i: integer;
Failure: TTestFailure;
begin
assert(assigned(test));
assert(assigned(e));
assert(assigned(fFailures));
l3System.Exception2Log(e);
Failure := TTestFailure.Create(test, e, Addrs);
FFailures.add(Failure);
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).AddFailure(Failure);
end;
assert(assigned(Failure));
Result := Failure;
end;
procedure TTestResult.addListener(listener: ITestListener);
begin
assert(assigned(listener), 'listener is nil');
FListeners.add(listener);
end;
procedure TTestResult.EndTest(test: ITest);
var
i: integer;
begin
assert(assigned(FListeners));
try
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).EndTest(test);
end;
finally
test.SetStatusListener(nil);
end;
end;
procedure TTestResult.Status(test: ITest; const Msg: AnsiString);
var
i: integer;
begin
assert(assigned(FListeners));
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).Status(test, Msg);
end;
end;
function TTestResult.GetError(idx :Integer): TTestFailure;
begin
Result := TObject(FErrors[idx]) as TTestFailure;
end;
function TTestResult.GetFailure(idx :Integer): TTestFailure;
begin
Result := TObject(FFailures[idx]) as TTestFailure;
end;
function TTestResult.RunTestSetup(test: ITest):Boolean;
var
LTime :Int64;
begin
Result := false;
try
test.StopTime := 0;
QueryPerformanceCounter(LTime);
test.StartTime := LTime;
test.FailsOnNoChecksExecuted := FFailsIfNoChecksExecuted;
test.FailsOnMemoryLeak := FFailsIfMemoryLeaked;
test.IgnoreSetUpTearDownLeaks:= FIgnoresMemoryLeakInSetUpTearDown;
test.SetUp;
Result := true;
except
on e: Exception do
begin
AddError(test, e, ExceptAddr, 'SetUp FAILED: ');
end;
end;
end;
procedure TTestResult.RunTestTearDown(test: ITest);
var
LTime :Int64;
begin
try
test.TearDown;
except
on e: Exception do
AddError(test, e, ExceptAddr, 'TearDown FAILED: ');
end;
QueryPerformanceCounter(LTime);
test.StopTime := LTime;
end;
function TTestResult.RunTestRun(aTest: ITest; aRandmom: Boolean): Boolean;
var
l_Failure: TTestFailure;
begin
Result := False;
aTest.TestMethodInvoked := False;
l_Failure := nil;
{$IFDEF USE_JEDI_JCL}
try
JclStartExceptionTracking;
{$ENDIF}
try
aTest.RunTest(self, aRandmom);
if not Assigned(FRootTest) then
FRootTest := aTest;
FTotalTime := FRootTest.ElapsedTestTime;
Result := true;
except
on e: EStopTestsFailure do
begin
l_failure := AddFailure(aTest, e, ExceptAddr);
FStop := True;
end;
on e: ETestFailure do
begin
l_Failure := AddFailure(aTest, e, ExceptAddr);
end;
on e: EBreakingTestFailure do
begin
l_Failure := AddFailure(aTest, e, ExceptAddr);
end;
on e: Exception do
begin
l_Failure := AddError(aTest, e, ExceptAddr);
end;
end;
{$IFDEF USE_JEDI_JCL}
finally
JclStopExceptionTracking;
end;
{$ENDIF}
if BreakOnFailures And
(l_Failure <> nil) And
(l_Failure.FThrownExceptionClass.InheritsFrom(ETestFailure)) then
begin
try
raise EBreakingTestFailure.Create(l_Failure.ThrownExceptionMessage)
{$IFNDEF CLR}at l_Failure.ThrownExceptionAddress{$ENDIF};
except
end;
end;
end;
procedure TTestResult.Run(aTest: ITest; aRandom: Boolean);
var
TestProcExecuted: Boolean;
TestCaseMemLeakMonitor : IDUnitMemLeakMonitor;
TestProcMemLeakMonitor : IDUnitMemLeakMonitor;
TestProcMemdiff : Integer;
TestCaseMemdiff : Integer;
TestCasePassed : Boolean;
ErrorMessage : AnsiString;
MemImbalance : Boolean;
SetupMemDiff : Integer;
TearDownMemDiff : Integer;
LeakIndex : Integer;
begin
Assert(Assigned(aTest));
if not ShouldStop and ShouldRunTest(aTest) then
begin
StartTest(aTest);
aTest.AllowedMemoryLeakSize := 0;
try
TestProcExecuted := False;
TestCasePassed := False;
TestCaseMemdiff := 0;
TestProcMemdiff := 0;
ErrorMessage := '';
// Start monitoring memory allocation before Setup.
TestProcMemLeakMonitor := TDUnitMemLeakMonitor.Create;
TestCaseMemLeakMonitor := TDUnitMemLeakMonitor.Create;
if RunTestSetUp(aTest) then
begin
// See if Setup Leaked.
(TestCaseMemLeakMonitor as IMemLeakMonitor).MemLeakDetected(SetupMemDiff);
TestProcMemLeakMonitor.MarkMemInUse;
TestCasePassed := RunTestRun(aTest, aRandom);
//Not all calls to RunTestRun call aTest Procedures so check if this was.
TestProcExecuted := isTestMethod(aTest);
if TestProcExecuted and aTest.FailsOnMemoryLeak then
(TestProcMemLeakMonitor as IMemLeakMonitor).MemLeakDetected(TestProcMemdiff);
end;
TestProcMemLeakMonitor.MarkMemInUse;
RunTestTearDown(aTest);
(TestProcMemLeakMonitor as IMemLeakMonitor).MemLeakDetected(TearDownMemDiff);
// Reporting of aTest success is delayed from within RunTestRun so mem leak
// can be flagged as failure at testcase level encompasing all of
// SetUp, Run and TearDown.
if TestCasePassed then
begin
if not TestProcExecuted or not aTest.FailsOnMemoryLeak then
// Show non aTest Procedure call success or TestCase success if not
// showing failure on memory status change
AddSuccess(aTest)
else
begin
MemImbalance := TestCaseMemLeakMonitor.MemLeakDetected(aTest.AllowedLeaksIterator,
aTest.FailsOnMemoryRecovery,
LeakIndex,
TestCaseMemdiff);
FMemoryLeakIgnoredInSetupOrTearDown := IgnoresMemoryLeakInSetUpTearDown and
(TestProcMemdiff = 0) and MemImbalance;
if not FMemoryLeakIgnoredInSetupOrTearDown and (MemImbalance and
(not TestCaseMemLeakMonitor.GetMemoryUseMsg(aTest.FailsOnMemoryRecovery,
SetupMemDiff,
TestProcMemdiff,
TearDownMemDiff,
TestCaseMemdiff,
ErrorMessage))) then
AddFailure(aTest, FMethodPtr, ErrorMessage)
else
begin
AddSuccess(aTest);
//Report back allowed leak size actually used from list of sizes
if (TestCaseMemdiff <> 0) then
aTest.AllowedMemoryLeakSize := TestCaseMemdiff;
end;
end;
end;
finally
EndTest(aTest);
TestProcMemLeakMonitor := nil;
TestCaseMemLeakMonitor := nil;
end;
end;
end;
function TTestResult.RunCount: integer;
begin
Result := FRunTests;
end;
function TTestResult.ShouldStop: Boolean;
begin
Result := FStop;
end;
procedure TTestResult.StartTest(test: ITest);
var
i: integer;
begin
assert(assigned(test));
assert(assigned(FListeners));
test.SetStatusListener(FStatusAdapter);
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).StartTest(test);
end;
end;
procedure TTestResult.Stop;
begin
FStop := true;
end;
function TTestResult.ErrorCount: integer;
begin
assert(assigned(FErrors));
Result := FErrors.count;
end;
function TTestResult.FailureCount: integer;
begin
assert(assigned(FFailures));
Result := FFailures.count;
end;
function TTestResult.WasSuccessful: Boolean;
begin
Result := (FailureCount = 0) and (ErrorCount() = 0) and not WasStopped;
end;
procedure TTestResult.TestingStarts;
var
i: Integer;
begin
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).TestingStarts;
end;
end;
procedure TTestResult.TestingEnds;
var
i: Integer;
begin
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).TestingEnds(self);
end;
end;
function TTestResult.ShouldRunTest(aTest: ITest): Boolean;
var
i: Integer;
begin
Result := True;
for i := 0 to FListeners.Count - 1 do
begin
if not (FListeners[i] as ITestListener).ShouldRunTest(aTest) then
begin
Result := False;
Break;
end; // if not (FListeners[i] as ITestListener).ShouldRunTest(aTest) then
end; // if not (FListeners[i] as ITestListener).ShouldRunTest(aTest) then
end;
function TTestResult.WasStopped: Boolean;
begin
Result := FStop;
end;
procedure TTestResult.RunSuite(aTest: ITest; aRandom: Boolean);
begin
try
TestingStarts;
try
FRootTest := aTest;
aTest.RunWithFixture(Self, aRandom);
finally
TestingEnds;
end;
finally
FRootTest := nil;
end;//try..finally
end;
procedure TTestResult.EndSuite(suite: ITest);
var
i: Integer;
l: ITestListenerX;
begin
for i := 0 to FListeners.count - 1 do
begin
{$IFDEF CLR}
if Supports(FListeners[i], ITestListenerX, l) then
{$ELSE}
if FListeners[i].QueryInterface(ITestListenerX, l) = 0 then
{$ENDIF}
l.EndSuite(suite);
end;
end;
procedure TTestResult.StartSuite(suite: ITest);
var
i: Integer;
l: ITestListenerX;
begin
for i := 0 to FListeners.count - 1 do
begin
{$IFDEF CLR}
if Supports(FListeners[i], ITestListenerX, l) then
{$ELSE}
if FListeners[i].QueryInterface(ITestListenerX, l) = 0 then
{$ENDIF}
l.StartSuite(suite);
end;
end;
function TTestResult.AddFailure(test: ITest; Addrs: Pointer; msg :AnsiString = ''): TTestFailure;
var
i: integer;
Failure: TTestFailure;
begin
assert(assigned(test));
assert(assigned(FFailures));
Failure := TTestFailure.Create(test, Addrs, msg);
FFailures.add(Failure);
for i := 0 to FListeners.count - 1 do
begin
(FListeners[i] as ITestListener).AddFailure(Failure);
end;
assert(assigned(Failure));
Result := Failure;
end;
{ TStatusToResultAdapter }
constructor TStatusToResultAdapter.Create(TestResult: TTestResult);
begin
Assert(TestResult <> nil, 'Expected non nil TestResult');
inherited Create;
FTestResult := TestResult;
end;
procedure TStatusToResultAdapter.Status(Test: ITest; const Msg: AnsiString);
begin
FTestResult.Status(Test, Msg);
end;
{ TAbstractTest }
constructor TAbstractTest.Create(aName: AnsiString);
var
i: Integer;
begin
inherited Create;
FTestName := aName;
FEnabled := true;
for i := 0 to Length(FAllowedLeakList) - 1 do // Iterate
FAllowedLeakList[i] := 0;
InitFields;
end;
destructor TAbstractTest.Destroy;
begin
Cleanup;
FreeAndNil(FStatusStrings);
FStatusListener := nil;
inherited;
end;
procedure TAbstractTest.InitFields;
begin
end;
procedure TAbstractTest.Cleanup;
begin
end;
function TAbstractTest.GetSubFolder: AnsiString;
begin
Result := DoGetSubFolder;
end;
procedure TAbstractTest.Invoke(AMethod: TTestMethod);
begin
FTestMethodInvoked := False;
end;
procedure TAbstractTest.Run(aTestResult: TTestResult; aRandom: Boolean);
begin
FailsOnNoChecksExecuted := aTestResult.FailsIfNoChecksExecuted;
FailsOnMemoryLeak := aTestResult.FailsIfMemoryLeaked;
IgnoreSetUpTearDownLeaks := aTestResult.IgnoresMemoryLeakInSetUpTearDown;
aTestResult.RunSuite(Self, aRandom);
end;
function TAbstractTest.CountEnabledTestCases: integer;
begin
if GetEnabled then
Result := 1
else
Result := 0
end;
function TAbstractTest.CountTestCases: Integer;
begin
Result := 1;
end;
function TAbstractTest.getEnabled: Boolean;
begin
Result := FEnabled
end;
function TAbstractTest.GetFolder: AnsiString;
begin
Result := '';
end;
function TAbstractTest.GetModelElementGUID: AnsiString;
begin
Result := '';
end;
function TAbstractTest.GetName: AnsiString;
begin
Result := FTestName
end;
function TAbstractTest.TestClassName: AnsiString;
begin
Result := ClassName;
end;
procedure TAbstractTest.LoadConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean);
var
f: TCustomIniFile;
begin
{$IFNDEF LINUX}
if useRegistry then
f := TRegistryIniFile.Create(DUnitRegistryKey + fileName)
else
{$ENDIF}
if useMemIni then
f := TMemIniFileTrimmed.Create(fileName)
else
f := TIniFile.Create(fileName);
try
LoadConfiguration(f, 'Tests')
finally
f.free
end
end;
procedure TAbstractTest.LoadConfiguration(const iniFile: TCustomIniFile; const section: AnsiString);
begin
self.setEnabled(iniFile.readBool(section, self.GetName, True));
end;
procedure TAbstractTest.SaveConfiguration(const fileName: AnsiString; const useRegistry, useMemIni: Boolean);
var
f: TCustomIniFile;
begin
{$IFNDEF LINUX}
if useRegistry then
f := TRegistryIniFile.Create(DUnitRegistryKey + fileName)
else
{$ENDIF}
if useMemIni then
f := TMemIniFileTrimmed.Create(fileName)
else
f := TIniFile.Create(fileName);
try
SaveConfiguration(f, 'Tests');
f.UpdateFile;
finally
f.free
end
end;
procedure TAbstractTest.SaveConfiguration(const iniFile: TCustomIniFile; const section: AnsiString);
begin
if self.GetEnabled then
iniFile.deleteKey(section, self.GetName)
else
iniFile.writeBool(section, self.GetName, False);
end;
function TAbstractTest.Run: TTestResult;
var
testResult: TTestResult;
begin
testResult := TTestResult.Create;
try
testResult.FailsIfNoChecksExecuted := self.FailsOnNoChecksExecuted;
testResult.FailsIfMemoryLeaked := self.FailsOnMemoryLeak;
testResult.IgnoresMemoryLeakInSetUpTearDown := IgnoreSetUpTearDownLeaks;
testResult.RunSuite(Self, False);
except
testResult.Free;
raise;
end;
Result := testResult;
end;
procedure TAbstractTest.setEnabled(value: Boolean);
begin
FEnabled := value;
end;
var
EmptyTestList: IInterfaceList = nil;
function TAbstractTest.Tests: IInterfaceList;
begin
if EmptyTestList = nil then
EmptyTestList := TInterfaceList.Create;
Result := EmptyTestList;
end;
function TAbstractTest.GetStartTime: Int64;
begin
Result := FStartTime
end;
procedure TAbstractTest.SetStartTime(Value: Int64);
begin
FStartTime := Value;
end;
procedure TAbstractTest.SetStopTime(Value: Int64);
begin
FStopTime := Value;
end;
function TAbstractTest.GetStopTime: Int64;
begin
Result := FStopTime;
end;
function TAbstractTest.NotForTerminalSession: Boolean;
begin
Result := false;
end;
procedure TAbstractTest.SetUp;
function lp_CorrectTestName: Boolean; // Что-то не то у нас с поддержкой SetUp на помомках, поэтому пока здесь. При полном переносе на модель лучше куда-нибудь переместь...
begin
Result := False;
if Tests.Count <= 1 then
if (Tests.Count = 0) and (Name <> 'DoIt') then
Result := True
else
if (Tests.Count = 1) then
Result := True;
end;
var
l_Len : Integer;
l_Name: AnsiString;
begin
if lp_CorrectTestName then
begin
l_Name := TryDeleteSrciptExtention(Name);
TddPicturePathListner.Instance.TestName := l_Name;
end;
// do nothing
InitFields;
end;
procedure TAbstractTest.TearDown;
begin
// do nothing
Cleanup;
end;
procedure TAbstractTest.RunTest(aTestResult: TTestResult; aRandom: Boolean);
begin
// do nothing
end;
function TAbstractTest.ElapsedTestTime: Cardinal;
var
Freq, LTime: Int64;
begin
// returns TestTime in millisecs
if fStopTime > 0 then
LTime := FStopTime
else if FStartTime > 0 then
QueryPerformanceCounter(LTime)
else
LTime := 0;
LTime := LTime - FStartTime;
if QueryPerformanceFrequency(Freq) then
Result := (1000*LTime) div Freq
else
Result := 0;
end;
procedure TAbstractTest.SetStatusListener(Listener: IStatusListener);
begin
FStatusListener := Listener;
end;
function TAbstractTest.GetStatus: AnsiString;
begin
if FStatusStrings = nil then
Result := ''
else
Result := FStatusStrings.Text;
end;
procedure TAbstractTest.Status(const Msg: AnsiString);
begin
if FStatusStrings = nil then
FStatusStrings := TStringList.Create;
FStatusStrings.Add(Msg);
if FStatusListener <> nil then
FStatusListener.Status(self, Msg);
end;
procedure TAbstractTest.RunWithFixture(aTestResult: TTestResult; aRandom: Boolean);
begin
try
Assert(Assigned(aTestResult));
if aTestResult.ShouldRunTest(Self) then
aTestResult.Run(Self, aRandom);
finally
Tl3BatchService.Instance.ClearAnswers;
end;//try..finally
end;
procedure TAbstractTest.Check(condition: Boolean; msg: AnsiString);
begin
FCheckCalled := True;
if (not condition) then
Fail(msg, CallerAddr);
end;
procedure TAbstractTest.CheckTrue(condition: Boolean; msg: AnsiString);
begin
FCheckCalled := True;
if (not condition) then
FailNotEquals(BoolToStr(true), BoolToStr(false), msg, CallerAddr);
end;
procedure TAbstractTest.CheckFalse(condition: Boolean; msg: AnsiString);
begin
FCheckCalled := True;
if (condition) then
FailNotEquals(BoolToStr(false), BoolToStr(true), msg, CallerAddr);
end;
procedure TAbstractTest.Fail(const msg: AnsiString; ErrorAddrs: Pointer = nil);
begin
{$IFDEF CLR}
raise ETestFailure.Create(msg);
{$ELSE}
if ErrorAddrs = nil then
raise ETestFailure.Create(msg) at CallerAddr
else
raise ETestFailure.Create(msg) at ErrorAddrs;
{$ENDIF}
end;
procedure TAbstractTest.StopTests(msg: AnsiString);
begin
raise EStopTestsFailure.Create(msg);
end;
procedure TAbstractTest.FailNotEquals( expected,
actual : WideString;
const msg : AnsiString = '';
ErrorAddrs: Pointer = nil);
begin
Fail(notEqualsErrorMessage(expected, actual, msg), ErrorAddrs);
end;
procedure TAbstractTest.FailEquals( expected,
actual : WideString;
const msg : AnsiString = '';
ErrorAddrs: Pointer = nil);
begin
Fail(EqualsErrorMessage(expected, actual, msg), ErrorAddrs);
end;
procedure TAbstractTest.FailNotSame( expected,
actual : WideString;
const msg : AnsiString = '';
ErrorAddrs: Pointer = nil);
begin
Fail(NotSameErrorMessage(expected, actual, msg), ErrorAddrs);
end;
procedure TAbstractTest.CheckEquals( expected,
actual : extended;
delta : extended;
const msg : AnsiString = '');
begin
FCheckCalled := True;
if (abs(expected-actual) > delta) then
FailNotEquals(FloatToStr(expected), FloatToStr(actual), msg, CallerAddr);
end;
procedure TAbstractTest.CheckEquals(expected, actual: extended; msg: AnsiString);
begin
CheckEquals(expected, actual, 0, msg);
end;
procedure TAbstractTest.CheckNotNull(obj: IUnknown; msg: AnsiString);
begin
FCheckCalled := True;
if obj = nil then
Fail(msg, CallerAddr);
end;
procedure TAbstractTest.CheckNull(obj: IUnknown; msg: AnsiString);
begin
FCheckCalled := True;
if obj <> nil then
Fail(msg, CallerAddr);
end;
procedure TAbstractTest.CheckSame(expected, actual: IUnknown; msg: AnsiString = '');
begin
FCheckCalled := True;
if (expected <> actual) then
FailNotSame(PtrToStr(Pointer(expected)), PtrToStr(Pointer(actual)), msg, CallerAddr);
end;
procedure TAbstractTest.CheckEquals(expected, actual: AnsiString; const msg: AnsiString = '');
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(expected, actual, msg, CallerAddr);
end;
procedure TAbstractTest.CheckEqualsString(expected, actual: AnsiString; const msg: AnsiString = '');
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(expected, actual, msg, CallerAddr);
end;
{$IFNDEF CLR}
procedure TAbstractTest.CheckEquals(expected, actual: WideString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(expected, actual, msg, CallerAddr);
end;
procedure TAbstractTest.CheckEqualsWideString(expected, actual: WideString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(expected, actual, msg, CallerAddr);
end;
function TAbstractTest.GetMemDiffStr(expected, actual: pointer; size:longword; msg:AnsiString):AnsiString;
var
db1, db2: byte;
Offset: integer;
begin
Offset:=FirstByteDiff(expected,actual,size,db1,db2);
Result:=NotEqualsErrorMessage(IntToHex(db1,2),IntToHex(db2,2),msg);
Result:=Result+' at Offset = '+IntToHex(Offset,4)+'h';
end;
procedure TAbstractTest.CheckEqualsMem(expected, actual: pointer; size:longword; msg:AnsiString='');
begin
FCheckCalled := True;
if not CompareMem(expected, actual, size) then
Fail(GetMemDiffStr(expected, actual, size, msg), CallerAddr);
end;
{$ENDIF}
procedure TAbstractTest.CheckNotEquals(expected, actual: AnsiString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected = actual then
FailEquals(expected, actual, msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEqualsString(expected, actual: AnsiString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected = actual then
FailEquals(expected, actual, msg, CallerAddr);
end;
{$IFNDEF CLR}
procedure TAbstractTest.CheckNotEquals(const expected, actual: WideString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected = actual then
FailEquals(expected, actual, msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEqualsWideString(const expected, actual: WideString; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected = actual then
FailEquals(expected, actual, msg, CallerAddr);
end;
// Expected not to work under CLR (pointer based) - KGS
procedure TAbstractTest.CheckNotEqualsMem(expected, actual: pointer; size:longword; msg:AnsiString='');
begin
FCheckCalled := True;
if CompareMem(expected, actual, size) then
begin
if msg <>'' then msg := msg + ', ';
Fail(msg+'Memory content was identical', CallerAddr);
end;
end;
{$ENDIF}
procedure TAbstractTest.CheckEquals(expected, actual: integer; const msg: AnsiString);
begin
FCheckCalled := True;
if (expected <> actual) then
FailNotEquals(IntToStr(expected), IntToStr(actual), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEquals(expected, actual: integer; msg: AnsiString = '');
begin
FCheckCalled := True;
if expected = actual then
FailEquals(IntToStr(expected), IntToStr(actual), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEquals(expected: extended; actual: extended; delta: extended = 0; msg: AnsiString = '');
begin
FCheckCalled := True;
if (abs(expected-actual) <= delta) then
FailNotEquals(FloatToStr(expected), FloatToStr(actual), msg, CallerAddr);
end;
procedure TAbstractTest.CheckEquals(expected, actual: Boolean; msg: AnsiString);
begin
FCheckCalled := True;
if (expected <> actual) then
FailNotEquals(BoolToStr(expected), BoolToStr(actual), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEquals(expected, actual: Boolean; msg: AnsiString);
begin
FCheckCalled := True;
if (expected = actual) then
FailEquals(BoolToStr(expected), BoolToStr(actual), msg, CallerAddr);
end;
{ [KGS] IntToBin: Elected not to add to TestFrameWork interface,
many people already have a self made version: }
function IntToBin(const value, digits: longword): AnsiString;
const
ALL_32_BIT_0 = '00000000000000000000000000000000';
var
counter: integer;
pow: integer;
begin
Result := ALL_32_BIT_0;
SetLength(Result, digits);
pow := 1 shl (digits - 1);
if value <> 0 then
for counter := 0 to digits - 1 do
begin
if (value and (pow shr counter)) <> 0 then
Result[counter+1] := '1';
end;
end;
procedure TAbstractTest.CheckEqualsBin(expected, actual: longword;
msg: AnsiString = ''; digits: integer=32);
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(IntToBin(expected, digits), IntToBin(actual, digits), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEqualsBin(expected, actual: longword;
msg: AnsiString = ''; digits: integer=32);
begin
FCheckCalled := True;
if (expected = actual) then
FailEquals(IntToBin(expected, digits), IntToBin(actual, digits), msg, CallerAddr);
end;
procedure TAbstractTest.CheckEqualsHex(expected, actual: longword;
msg: AnsiString = ''; digits: integer=8);
begin
FCheckCalled := True;
if expected <> actual then
FailNotEquals(IntToHex(expected, digits), IntToHex(actual, digits), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotEqualsHex(expected, actual: longword;
msg: AnsiString = ''; digits: integer=8);
begin
FCheckCalled := True;
if (expected = actual) then
FailEquals(IntToHex(expected, digits), IntToHex(actual, digits), msg, CallerAddr);
end;
procedure TAbstractTest.CheckSame(expected, actual: TObject; msg: AnsiString);
begin
FCheckCalled := True;
if (expected <> actual) then
FailNotSame(PtrToStr(Pointer(expected)), PtrToStr(Pointer(actual)), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNotNull(obj: TObject; msg: AnsiString);
begin
FCheckCalled := True;
if obj = nil then
FailNotSame('object', PtrToStr(Pointer(obj)), msg, CallerAddr);
end;
procedure TAbstractTest.CheckNull(obj: TObject; msg: AnsiString);
begin
FCheckCalled := True;
if obj <> nil then
FailNotSame('nil', PtrToStr(Pointer(obj)), msg, CallerAddr);
end;
function TAbstractTest.NotEqualsErrorMessage(expected, actual: WideString; msg: AnsiString): WideString;
begin
if (msg <> '') then
msg := msg + ', ';
Result := Format( sExpButWasFmt , [msg, expected, actual])
end;
function TAbstractTest.EqualsErrorMessage(expected, actual: WideString; msg: AnsiString): WideString;
begin
if (msg <> '') then
msg := msg + ', ';
Result := Format( sExpAndActualFmt, [msg, expected])
end;
function TAbstractTest.NotSameErrorMessage(expected, actual, msg: AnsiString): WideString;
begin
if (msg <> '') then
msg := msg + ', ';
Result := Format( sExpButWasFmt, [msg, expected, actual])
end;
function TAbstractTest.BoolToStr(ABool: Boolean): AnsiString;
begin
Result := BooleanIdents[aBool];
end;
procedure TAbstractTest.StartExpectingException(e: ExceptionClass);
begin
StopExpectingException;
FExpectedException := e;
end;
procedure TAbstractTest.StopExpectingException(msg :AnsiString);
begin
try
if FExpectedException <> nil then
begin
Fail( Format( 'Expected exception "%s" but there was none. %s',
[FExpectedException.ClassName,
Msg]),
CallerAddr);
end;
finally
FExpectedException := nil;
end;
end;
{$IFNDEF CLR}
procedure TAbstractTest.CheckMethodIsNotEmpty(MethodPointer: pointer);
const
AssemblerRet = $C3;
begin
if byte(MethodPointer^) = AssemblerRet then
Fail('Empty test', MethodPointer);
end;
{$ENDIF}
procedure TAbstractTest.CheckException(AMethod: TTestMethod; AExceptionClass: TClass; const msg :AnsiString);
begin
FCheckCalled := True;
try
Invoke(AMethod);
except
on e :Exception do
begin
if not Assigned(AExceptionClass) then
raise
else if not e.ClassType.InheritsFrom(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, e.ClassName, msg, CallerAddr)
else
AExceptionClass := nil;
end;
end;
if Assigned(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, 'nothing', msg, CallerAddr)
end;
procedure TAbstractTest.CheckEquals(expected, actual: TClass; const msg: AnsiString);
begin
FCheckCalled := True;
if expected <> actual then
begin
if expected = nil then
FailNotEquals('nil', actual.ClassName, msg, CallerAddr)
else if actual = nil then
FailNotEquals(expected.ClassName, 'nil', msg, CallerAddr)
else
FailNotEquals(expected.ClassName, actual.ClassName, msg, CallerAddr)
end;
end;
procedure TAbstractTest.CheckInherits(expected, actual: TClass; const msg: AnsiString);
begin
FCheckCalled := True;
if expected = nil then
FailNotEquals('nil', actual.ClassName, msg, CallerAddr)
else if actual = nil then
FailNotEquals(expected.ClassName, 'nil', msg, CallerAddr)
else if not actual.InheritsFrom(expected) then
FailNotEquals(expected.ClassName, actual.ClassName, msg, CallerAddr)
end;
procedure TAbstractTest.CheckIs(AObject: TObject; AClass: TClass; const msg: AnsiString);
begin
FCheckCalled := True;
Assert(AClass <> nil);
if AObject = nil then
FailNotEquals(AClass.ClassName, 'nil', msg, CallerAddr)
else if not AObject.ClassType.InheritsFrom(AClass) then
FailNotEquals(AClass.ClassName, AObject.ClassName, msg, CallerAddr)
end;
function TAbstractTest.GetGUIObject: TObject;
begin
Result := FGUIObject;
end;
procedure TAbstractTest.SetGUIObject(const guiObject: TObject);
begin
FGUIObject := guiObject;
end;
function TAbstractTest.GetFailsOnNoChecksExecuted: Boolean;
begin
Result := FFailsOnNoChecksExecuted;
end;
procedure TAbstractTest.SetFailsOnNoChecksExecuted(const Value: Boolean);
begin
FFailsOnNoChecksExecuted := Value;
end;
function TAbstractTest.GetFailsOnMemoryLeak: Boolean;
begin
Result := FFailsOnMemoryLeak;
end;
procedure TAbstractTest.SetFailsOnMemoryLeak(const Value: Boolean);
begin
FFailsOnMemoryLeak := Value;
end;
function TAbstractTest.GetTestMethodInvoked: Boolean;
begin
Result := FTestMethodInvoked;
end;
procedure TAbstractTest.SetTestMethodInvoked(const Value: Boolean);
begin
FTestMethodInvoked := True;
end;
function TAbstractTest.GetAllowedMemoryLeakSize: Integer;
// Array[0] reserved for property AllowedLeakSize and remainder for values entered by SetAllowedLeakArray
var
i: Integer;
begin
Result := FAllowedLeakList[0];
if (result = 0) then
begin // The user may have set the values using SetAllowedLeakArray
for I := 0 to Length(FAllowedLeakList) - 1 do // Iterate
begin
if FAllowedLeakList[0] <> 0 then
begin
result := FAllowedLeakList[i];
break;
end;
end; // for
end;
end;
procedure TAbstractTest.SetAllowedMemoryLeakSize(const NewSize: Integer);
begin
FAllowedLeakList[0] := NewSize;
end;
function TAbstractTest.GetFailsOnMemoryRecovery: Boolean;
begin
Result := FFailsOnMemoryRecovery;
end;
procedure TAbstractTest.SetFailsOnMemoryRecovery(const Value: Boolean);
begin
FFailsOnMemoryRecovery := Value;
end;
procedure TAbstractTest.SetAllowedLeakArray(AllowedList: array of Integer);
var
I: Integer;
begin // Note the 0th element is reserved for old code value.
if Length(AllowedList) >= Length(FAllowedLeakList) then
fail('Too many values in for AllowedLeakArray. Limit = ' +
IntToStr(Length(FAllowedLeakList) - 1));
for I := 1 to Length(FAllowedLeakList) - 1 do
begin
if I <= Length(AllowedList) then
FAllowedLeakList[I] := AllowedList[I-1]
else
FAllowedLeakList[I] := 0;
end;
end;
function TAbstractTest.GetAllowedLeaksIterator: TListIterator;
begin
FAllowedLeakListIndex := 0;
result := GetAllowedLeak;
end;
function TAbstractTest.GetAllowedLeak: Integer;
begin // Auto Iterator
if FAllowedLeakListIndex >= Length(FAllowedLeakList) then
Result := 0
else
begin
Result := FAllowedLeakList[FAllowedLeakListIndex];
Inc(FAllowedLeakListIndex);
end;
end;
function TAbstractTest.GetIgnoreSetUpTearDownLeaks: Boolean;
begin
Result := FIgnoreSetUpTearDownLeaks;
end;
procedure TAbstractTest.SetIgnoreSetUpTearDownLeaks(const Value: Boolean);
begin
FIgnoreSetUpTearDownLeaks := Value;
end;
function TAbstractTest.GetMemoryLeakIgnoredInSetupTearDown: Boolean;
begin
Result := FMemoryLeakIgnoredInSetupTearDown;
end;
procedure TAbstractTest.SetMemoryLeakIgnoredInSetupTearDown(
const Value: Boolean);
begin
FMemoryLeakIgnoredInSetupTearDown := Value;
end;
function TAbstractTest.GetDisplayName: AnsiString;
begin
Result := GetName;
end;
function TAbstractTest.GetSuffixName: AnsiString;
var
l_Parent: TClass;
begin
l_Parent := ClassParent;
Result := '';
while (l_Parent <> nil) and
(l_Parent <> TAbstractTest) AND
(l_Parent.ClassName <> csIgnoreClassName) do
begin
if Result = '' then
Result := l_Parent.ClassName
else
Result := Result + csSeparator + l_Parent.ClassName;
l_Parent := l_Parent.ClassParent;
end;
end;
procedure TAbstractTest.SetScriptName(const aName: AnsiString);
begin
DoSetScriptName(aName);
end;
procedure TAbstractTest.DoSetScriptName(const aName: AnsiString);
begin
end;
function TAbstractTest.HasScriptChildren: Boolean;
begin
Result := DoHasScriptChildren;
end;
function TAbstractTest.DoHasScriptChildren: Boolean;
begin
Result := False;
end;
procedure TAbstractTest.ClearEtalons;
begin
DoClearEtalon;
end;
{ TTestCase }
constructor TTestCase.Create(const aMethodName, aFolder: AnsiString);
{$IFNDEF CLR}
var
l_RunMethod: TMethod;
{$ENDIF}
begin
f_DataSubFolder := aFolder;
Assert(Length(aMethodName) > 0);
{$IFNDEF CLR}
Assert(IsScript or (aFolder <> '') or Assigned(MethodAddress(aMethodName)));
{$ELSE}
Assert(aMethodName <> '');
{$ENDIF}
inherited Create(aMethodName);
{$IFDEF CLR}
FMethod := aMethodName;
{$ELSE}
if IsScript or (aFolder <> '') then
begin
l_RunMethod.Code := MethodAddress('DoIt');
l_RunMethod.Data := Self;
FMethod := TTestMethod(l_RunMethod);
Assert(Assigned(FMethod));
end // IsScript or aFolderMode
else
begin
l_RunMethod.Code := MethodAddress(aMethodName);
l_RunMethod.Data := Self;
FMethod := TTestMethod(l_RunMethod);
Assert(Assigned(FMethod));
end;//not IsScript
{$ENDIF}
end;
class function TTestCase.IsScript: Boolean;
begin
Result := False;
end;
function TTestCase.DoGetSubFolder: AnsiString;
begin
if FolderMode then
Result := f_DataSubFolder
else
Result := '';
end;
procedure TTestCase.DoClearEtalon; //override;
begin
Assert(false, 'Очистка эталонов не реализована');
end;
function TTestCase.FolderMode: Boolean;
begin
Result := (f_DataSubFolder <> '') and not IsScript;
end;
procedure TTestCase.Invoke(AMethod: TTestMethod);
{$IFDEF CLR}
var
Args: array of System.Object;
{$ENDIF}
begin
FTestMethodInvoked := True;
{$IFDEF CLR}
Args := nil;
try
GetType.InvokeMember(AMethod, BindingFlags.Public or BindingFlags.Instance or BindingFlags.InvokeMethod, nil, Self, Args);
except
on E:TargetInvocationException do
raise E.InnerException;
end;
{$ELSE}
AMethod;
{$ENDIF}
end;
class function TTestCase.TestNeedFolder: Boolean;
begin
Result := False;
end;
procedure TTestCase.RunWithFixture(aTestResult: TTestResult; aRandom: Boolean);
begin
Assert(Assigned(aTestResult));
FFailsOnNoChecksExecuted := aTestResult.FailsIfNoChecksExecuted;
FFailsOnMemoryLeak := aTestResult.FailsIfMemoryLeaked;
FIgnoreSetUpTearDownLeaks := aTestResult.IgnoresMemoryLeakInSetUpTearDown;
if aTestResult.ShouldRunTest(Self) then
begin
Inc(aTestResult.FRunTests);
inherited;
end; // if aTestResult.ShouldRunTest(self) then
end;
function TTestCase.ShouldStop: Boolean;
begin
Result := f_TestResult.ShouldStop;
end;
procedure TTestCase.RunTest(aTestResult: TTestResult; aRandom: Boolean);
begin
Assert(Assigned(FMethod), 'Method "' + FTestName + '" not found');
FExpectedException := nil;
try
try
{$IFDEF CLR}
aTestResult.FMethodPtr := nil;
{$ELSE}
CheckMethodIsNotEmpty(TMethod(FMethod).Code);
aTestResult.FMethodPtr := TMethod(FMethod).Code;
{$ENDIF}
FCheckCalled := False;
f_TestResult := aTestResult;
try
Invoke(FMethod);
finally
f_TestResult := nil;
end;
if FFailsOnNoChecksExecuted and (not FCheckCalled) then
Fail('No checks executed in TestCase', aTestResult.FMethodPtr);
StopExpectingException;
except
on E: ETestFailure do
begin
raise;
end;
on E: Exception do
begin
if not Assigned(FExpectedException) then
raise
else
if not E.ClassType.InheritsFrom(fExpectedException) then
FailNotEquals(fExpectedException.ClassName, E.ClassName, 'unexpected exception', ExceptAddr);
end
end;
finally
FExpectedException := nil;
end;
end;
procedure TTestCase.Run(aTestResult: TTestResult; aRandom: Boolean);
begin
aTestResult.RunSuite(Self, aRandom);
end;
class function TTestCase.Suite: ITestSuite;
begin
Result := TTestSuite.Create(Self);
end;
{ TTestFailure }
constructor TTestFailure.Create(FailedTest: ITest; thrownException: Exception; Addrs: Pointer; msg: AnsiString);
begin
assert(assigned(thrownException));
inherited Create;
FFailedTest := FailedTest;
FThrownExceptionClass := thrownException.ClassType;
FThrownExceptionMessage := msg + thrownException.message;
FThrownExceptionAddress := Addrs;
CaptureStackTrace;
end;
constructor TTestFailure.Create(FailedTest: ITest; Addrs: Pointer; msg: AnsiString);
begin
inherited Create;
FFailedTest := FailedTest;
FThrownExceptionClass := EPostTestFailure;
FThrownExceptionMessage := msg;
FThrownExceptionAddress := Addrs;
FStackTrace := '';
end;
function TTestFailure.FailedTest: ITest;
begin
Result := FFailedTest;
end;
function TTestFailure.ThrownExceptionName: AnsiString;
begin
Result := FThrownExceptionClass.ClassName;
end;
function TTestFailure.ThrownExceptionMessage: AnsiString;
begin
Result := FThrownExceptionMessage;
end;
function TTestFailure.ThrownExceptionAddress: pointer;
begin
Result := FThrownExceptionAddress;
end;
function TTestFailure.ThrownExceptionClass: TClass;
begin
Result := FThrownExceptionClass;
end;
function TTestFailure.LocationInfo: AnsiString;
begin
Result := PointerToLocationInfo(ThrownExceptionAddress);
end;
function TTestFailure.AddressInfo: AnsiString;
begin
Result := PointerToAddressInfo(ThrownExceptionAddress);
end;
function TTestFailure.StackTrace: AnsiString;
begin
Result := FStackTrace;
end;
procedure TTestFailure.CaptureStackTrace;
{$IFDEF USE_JEDI_JCL}
var
Trace :TStrings;
{$ENDIF}
begin
{$IFDEF USE_JEDI_JCL}
Trace := TStringList.Create;
try
JclDebug.JclLastExceptStackListToStrings(Trace, true);
FStackTrace := Trace.Text;
finally
Trace.Free;
end;
{$ELSE}
{$IFDEF madExcept}
FStackTrace := madStackTrace.StackTrace( false, false, false, nil,
FThrownExceptionAddress, false,
false, 0, 0, nil,
@FThrownExceptionAddress );
{$ELSE}
FStackTrace := '';
{$ENDIF}
{$ENDIF}
end;
{ TTestSuite }
constructor TTestSuite.Create;
begin
Create(TObject.ClassName);
end;
constructor TTestSuite.Create(aName: AnsiString);
begin
Assert(Length(aName) > 0);
inherited Create(aName);
FTests := TInterfaceList.Create;
end;
constructor TTestSuite.Create(aTestClass: TTestCaseClass);
begin
Self.Create(aTestClass.ClassName);
AddTests(aTestClass);
end;
constructor TTestSuite.Create(aName: AnsiString; const aTests: array of ITest);
var
i: Integer;
begin
Self.Create(aName);
for i := Low(aTests) to High(aTests) do
Self.AddTest(aTests[i])
end;
procedure TTestSuite.AddTest(const aTest: ITest);
begin
DoAddTest(aTest);
end;
procedure TTestSuite.AddSuite(aSuite: ITestSuite);
begin
AddTest(aSuite);
end;
procedure TTestSuite.AddTests(aTestClass: TTestCaseClass);
var
l_MethodIter : Integer;
l_NameOfMethod : AnsiString;
l_MethodEnumerator : TMethodEnumerator;
begin
{ call on the method enumerator to get the names of the test
cases in the testClass }
l_MethodEnumerator := nil;
try
l_MethodEnumerator := TMethodEnumerator.Create(aTestClass);
{ make sure we add each test case to the list of tests }
for l_MethodIter := 0 to l_MethodEnumerator.MethodCount - 1 do
begin
l_NameOfMethod := l_MethodEnumerator.NameOfMethod[l_MethodIter];
Self.AddTest(aTestClass.Create(l_NameOfMethod, GetDataFolder) as ITest);
end; // for l_MethodIter := 0 to l_MethodEnumerator.Methodcount - 1 do
finally
l_MethodEnumerator.Free;
end;
end;
function TTestSuite.DoGetSubFolder: AnsiString;
begin
Result := '';
end;
function TTestSuite.CountTestCases: Integer;
var
i : Integer;
l_Test : ITest;
l_Total : Integer;
begin
Assert(Assigned(FTests));
l_Total := 0;
for i := 0 to FTests.Count - 1 do
begin
l_Test := FTests[i] as ITest;
l_Total := l_Total + l_Test.CountTestCases;
end; // for i := 0 to FTests.Count - 1 do
Result := l_Total;
end;
function TTestSuite.CountEnabledTestCases: integer;
var
i : Integer;
l_Test : ITest;
l_Total : Integer;
begin
Assert(Assigned(FTests));
l_Total := 0;
if GetEnabled then
begin
for i := 0 to FTests.Count - 1 do
begin
l_Test := FTests[i] as ITest;
l_Total := l_Total + l_Test.CountEnabledTestCases;
end; // for i := 0 to FTests.Count - 1 do
end; // if GetEnabled then
Result := l_Total;
end;
procedure TTestSuite.RunTest(aTestResult: TTestResult; aRandom: Boolean);
var
i : Integer;
l_Index : Integer;
l_Test : ITest;
l_TestList : TList;
begin
Assert(Assigned(aTestResult));
Assert(Assigned(FTests));
aTestResult.StartSuite(Self);
if aRandom and (FTests.Count > 1) then
begin
l_TestList := TList.Create;
try
for i := 0 to FTests.Count - 1 do
l_TestList.Add(Pointer(FTests[i]));
while l_TestList.Count > 0 do
begin
l_Index := Random(l_TestList.Count);
l_Test := ITest(l_TestList[l_Index]);
l_Test.RunWithFixture(aTestResult, aRandom);
l_TestList.Delete(l_Index);
end; // while l_TestList.Count > 0 do
finally
l3Free(l_TestList);
end;
end // if aRandom then
else
for i := 0 to FTests.Count - 1 do
begin
if aTestResult.ShouldStop then Break;
l_Test := FTests[i] as ITest;
l_Test.RunWithFixture(aTestResult, aRandom);
end; // for i := 0 to FTests.Count - 1 do
aTestResult.EndSuite(Self);
end;
function TTestSuite.Tests: IInterfaceList;
begin
Result := FTests;
end;
procedure TTestSuite.LoadConfiguration(const iniFile: TCustomIniFile; const section: AnsiString);
var
i : integer;
LTests: IInterfaceList;
TestSection: AnsiString;
begin
inherited LoadConfiguration(iniFile, section);
LTests := self.Tests;
TestSection := section + '.' + self.GetName;
for i := 0 to LTests.count-1 do
(LTests[i] as ITest).LoadConfiguration(iniFile, TestSection);
end;
procedure TTestSuite.SaveConfiguration(const iniFile: TCustomIniFile; const section: AnsiString);
var
i : integer;
LTests: IInterfaceList;
TestSection: AnsiString;
begin
inherited SaveConfiguration(iniFile, section);
LTests := self.Tests;
TestSection := section + '.' + self.GetName;
for i := 0 to LTests.count-1 do
(LTests[i] as ITest).SaveConfiguration(iniFile, TestSection);
end;
function TTestSuite.GetDisplayName: AnsiString;
begin
Result := inherited GetDisplayName;
if ClassParent = TAbstractTest then
begin
if FSuffix <> '' then
Result := Result + csSeparator + FSuffix;
end // if ClassParent = TAbstractTest then
end;
function TTestSuite.GetFolder: AnsiString;
var
i : Integer;
l_Test : ITest;
begin
Result := inherited GetFolder;
for i := 0 to FTests.Count - 1 do
begin
l_Test := FTests[i] as ITest;
if l_Test.Folder <> '' then
begin
Result := l_Test.Folder;
Break;
end; // if l_Test.Folder <> '' then
end;
end;
procedure TTestSuite.DoAddTest(const aTest: ITest);
begin
Assert(Assigned(aTest));
if FSuffix = '' then
FSuffix := aTest.GetSuffixName;
FTests.Add(aTest);
end;
function TTestSuite.GetDataFolder: AnsiString;
begin
Result := '';
end;
function TTestSuite.GetExt: AnsiString;
begin
Result := '';
end;
procedure TTestSuite.ReReadAbstractTests;
begin
DoReReadAbstractTests;
end;
procedure TTestSuite.DoReReadAbstractTests;
begin
end;
procedure TTestSuite.DoClearEtalon;
var
i : Integer;
l_Test : ITest;
begin
for i := 0 to FTests.Count - 1 do
begin
l_Test := FTests[i] as ITest;
l_Test.ClearEtalons;
end;
end;
{ ETestFailure }
constructor ETestFailure.Create;
begin
inherited Create('')
end;
constructor ETestFailure.Create(msg: AnsiString);
begin
inherited Create(msg)
end;
{ EBreakingTestFailure }
constructor EBreakingTestFailure.Create;
begin
inherited Create('')
end;
constructor EBreakingTestFailure.Create(msg: AnsiString);
begin
inherited Create(msg)
end;
{ TMemIniFileTrimmed }
function TMemIniFileTrimmed.ReadString(const Section, Ident,
DefaultStr: String): String;
begin
// Trim the result for compatibility with TIniFile
Result := Trim(inherited ReadString(Section, Ident, DefaultStr));
end;
{ TMethodEnumerator }
constructor TMethodEnumerator.Create(AClass: TClass);
{$IFDEF CLR}
var
I, L: integer;
T: System.Type;
Methods: array of MethodInfo;
function IsTest(AMethod: MethodInfo): Boolean;
var
CustomAttr: array of System.Object;
I: integer;
begin
Result := false;
if AMethod.IsPublic then
begin
CustomAttr := AMethod.GetCustomAttributes(false);
for I := 0 to System.Array(CustomAttr).Length - 1 do
begin
if CustomAttr[I].ClassNameIs('TestAttribute') then
begin
Result := true;
Break;
end;;
end;
end;
end;
{$ELSE}
type
TMethodTable = packed record
count: SmallInt;
//[...methods...]
end;
var
table: ^TMethodTable;
AName: ^ShortString;
i, j: Integer;
{$ENDIF}
begin
inherited Create;
{$IFDEF CLR}
T := AClass.ClassInfo;
Methods := T.GetMethods();
L := 0;
SetLength(FMethodNameList, L);
for I := 0 to System.Array(Methods).Length - 1 do
if IsTest(Methods[I]) then
begin
L := L + 1;
SetLength(FMethodNameList, L);
FMethodNameList[L-1] := Methods[I].Name;
end;
{$ELSE}
while aclass <> nil do
begin
// *** HACK ALERT *** !!!
// Review System.MethodName to grok how this method works
asm
mov EAX, [aclass]
mov EAX,[EAX].vmtMethodTable { fetch pointer to method table }
mov [table], EAX
end;
if table <> nil then
begin
AName := Pointer(PAnsiChar(table) + 8);
for i := 1 to table.count do
begin
// check if we've seen the method name
j := Low(FMethodNameList);
while (j <= High(FMethodNameList))
and (AName^ <> FMethodNameList[j]) do
inc(j);
// if we've seen the name, then the method has probably been overridden
if j > High(FMethodNameList) then
begin
SetLength(FMethodNameList,length(FMethodNameList)+1);
FMethodNameList[j] := AName^;
end;
AName := Pointer(PAnsiChar(AName) + length(AName^) + 7)
end;
end;
aclass := aclass.ClassParent;
end;
{$ENDIF}
end;
function TMethodEnumerator.GetMethodCount: Integer;
begin
Result := Length(FMethodNameList);
end;
function TMethodEnumerator.GetNameOfMethod(idx: integer): AnsiString;
begin
Result := FMethodNameList[idx];
end;
{ Convenience routines }
function TestSuite(AName: AnsiString; const Tests: array of ITest): ITestSuite;
begin
Result := TTestSuite.Create(AName, Tests);
end;
{ test registry }
var
__TestRegistry: ITestSuite = nil;
procedure RegisterTestInSuite(rootSuite: ITestSuite; path: AnsiString; test: ITest);
var
pathRemainder: AnsiString;
suiteName: AnsiString;
targetSuite: ITestSuite;
suite: ITestSuite;
currentTest: ITest;
Tests: IInterfaceList;
dotPos: Integer;
i: Integer;
begin
if (path = '') then
begin
// End any recursion
rootSuite.addTest(test);
end
else
begin
// Split the path on the dot (.)
dotPos := Pos('.', Path);
if (dotPos <= 0) then dotPos := Pos('\', Path);
if (dotPos <= 0) then dotPos := Pos('/', Path);
if (dotPos > 0) then
begin
suiteName := Copy(path, 1, dotPos - 1);
pathRemainder := Copy(path, dotPos + 1, length(path) - dotPos);
end
else
begin
suiteName := path;
pathRemainder := '';
end;
Tests := rootSuite.Tests;
// Check to see if the path already exists
targetSuite := nil;
Tests := rootSuite.Tests;
for i := 0 to Tests.count -1 do
begin
currentTest := Tests[i] as ITest;
{$IFDEF CLR}
if Supports(currentTest, ITestSuite, suite) then
{$ELSE}
currentTest.queryInterface(ITestSuite, suite);
if Assigned(suite) then
{$ENDIF}
begin
if (currentTest.GetName = suiteName) then
begin
targetSuite := suite;
break;
end;
end;
end;
if not assigned(targetSuite) then
begin
targetSuite := TTestSuite.Create(suiteName);
rootSuite.addTest(targetSuite);
end;
RegisterTestInSuite(targetSuite, pathRemainder, test);
end;
end;
procedure CreateRegistry;
var
MyName :AnsiString;
begin
{$IFDEF CLR}
MyName := ExtractFileName(ParamStr(0));
{$ELSE}
SetLength(MyName, 1024);
GetModuleFileName(hInstance, PChar(MyName), Length(MyName));
MyName := Trim(PChar(MyName));
MyName := ExtractFileName(MyName);
{$ENDIF}
__TestRegistry := TTestSuite.Create(MyName);
end;
procedure RegisterTest(SuitePath: AnsiString; test: ITest);
begin
assert(assigned(test));
if __TestRegistry = nil then CreateRegistry;
RegisterTestInSuite(__TestRegistry, SuitePath, test);
end;
procedure RegisterTest(test: ITest);
begin
RegisterTest('', test);
end;
procedure RegisterTests(SuitePath: AnsiString; const Tests: array of ITest);
var
i: Integer;
begin
for i := Low(Tests) to High(Tests) do begin
TestFramework.RegisterTest(SuitePath, Tests[i])
end
end;
procedure RegisterTests(const Tests: array of ITest);
begin
RegisterTests('', Tests);
end;
function RegisteredTests: ITestSuite;
begin
Result := __TestRegistry;
end;
function RunTest(suite: ITest; const listeners: array of ITestListener; aRandom: Boolean): TTestResult; overload;
var
i : Integer;
begin
Result := TTestResult.Create;
for i := low(listeners) to high(listeners) do
result.addListener(listeners[i]);
if suite <> nil then
suite.Run(result, aRandom);
end;
function RunRegisteredTests(const listeners: array of ITestListener): TTestResult;
begin
Result := RunTest(RegisteredTests, listeners, False);
end;
procedure ClearRegistry;
begin
__TestRegistry := nil;
end;
initialization
{$IFDEF LINUX}
InitPerformanceCounter;
{$ENDIF}
l3System.AddExitProc(ClearRegistry);
(*finalization
ClearRegistry;*)
end.
|
unit WaitStatementParsingTest;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FpcUnit, TestRegistry,
ParserBaseTestCase,
WpcScriptCommons,
WpcStatements,
WpcScriptParser,
WpcExceptions;
type
{ TWaitStatementParsingTestCase }
TWaitStatementParsingTestCase = class(TParserBaseTestCase)
protected
WaitStatement : TWpcWaitStatement;
published
procedure ShouldParseWaitStatementWithDefaults();
procedure ShouldParseWaitStatementWithDefaultTimeUnit();
procedure ShouldParseBaseWaitStatement();
procedure ShouldParseWaitStatementWithProbabilityProperty();
procedure ShouldParseWaitStatementWithTimesProperty();
procedure ShouldParseWaitStatementWithDelayProperty();
procedure ShouldParseWaitStatementWithAllProperties();
procedure ShouldParseWaitStatementWithAllPropertiesExceptDelayPropertyWhichIsSimplified();
procedure SholudRaiseScriptParseExceptionWhenSetDelayPropertyAfterDelayValue();
procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase();
procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties();
procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties();
end;
implementation
{ TWaitStatementParsingTestCase }
// WAIT
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithDefaults();
begin
ScriptLines.Add(WAIT_KEYWORD);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, WaitStatement.GetProbability());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, WaitStatement.GetTimes(), DEFAULT_TIMES);
end;
// WAIT 5
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithDefaultTimeUnit();
begin
ScriptLines.Add(WAIT_KEYWORD + ' 5 '); // minutes should be default unit
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, WaitStatement.GetProbability());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_TIMES, WaitStatement.GetTimes());
end;
// WAIT 5m
procedure TWaitStatementParsingTestCase.ShouldParseBaseWaitStatement();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, WaitStatement.GetProbability());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_TIMES, WaitStatement.GetTimes());
end;
// WAIT 5m WITH PROBABILITY 50
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithProbabilityProperty();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + WITH_PROBABILITY_PROPERTY);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, WaitStatement.GetProbability());
end;
// WAIT 5m 4 TIMES
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithTimesProperty();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + X_TIMES_PROPERTY);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_TIMES_VALUE, WaitStatement.GetTimes());
end;
// WAIT FOR 5m
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithDelayProperty();
begin
ScriptLines.Add(WAIT_KEYWORD + DELAY_FOR_PROPERTY);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
end;
// WAIT FOR 5m WITH PROBABILITY 50 4 TIMES
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithAllProperties();
begin
ScriptLines.Add(WAIT_KEYWORD + DELAY_FOR_PROPERTY + WITH_PROBABILITY_PROPERTY + X_TIMES_PROPERTY);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, WaitStatement.GetProbability());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_TIMES_VALUE, WaitStatement.GetTimes());
end;
// WAIT 5m WITH PROBABILITY 50 4 TIMES
procedure TWaitStatementParsingTestCase.ShouldParseWaitStatementWithAllPropertiesExceptDelayPropertyWhichIsSimplified();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + WITH_PROBABILITY_PROPERTY + X_TIMES_PROPERTY);
WrapInMainBranch(ScriptLines);
ParseScriptLines();
ReadMainBranchStatementsList();
AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count);
AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId());
WaitStatement := TWpcWaitStatement(MainBranchStatements[0]);
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WaitStatement.GetDelay());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, WaitStatement.GetProbability());
AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_TIMES_VALUE, WaitStatement.GetTimes());
end;
// WAIT 5m FOR 5m
procedure TWaitStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenSetDelayPropertyAfterDelayValue();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + DELAY_FOR_PROPERTY);
WrapInMainBranch(ScriptLines);
AssertScriptParseExceptionOnParse(1, 2);
end;
// WAIT 5m QUICK
procedure TWaitStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + ' QUICK ');
WrapInMainBranch(ScriptLines);
AssertScriptParseExceptionOnParse(1, 2);
end;
// WAIT 5m TWICE WITH PROBABILITY 50
procedure TWaitStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + ' TWICE ' + WITH_PROBABILITY_PROPERTY);
WrapInMainBranch(ScriptLines);
AssertScriptParseExceptionOnParse(1, 2);
end;
// WAIT 5m 5 TIMES WITH PROBABILITY 50 BEFORE TOMORROW
procedure TWaitStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties();
begin
ScriptLines.Add(WAIT_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + X_TIMES_PROPERTY + WITH_PROBABILITY_PROPERTY + ' BEFORE TOMORROW ');
WrapInMainBranch(ScriptLines);
AssertScriptParseExceptionOnParse(1, 7);
end;
initialization
RegisterTest(PARSER_TEST_SUITE_NAME, TWaitStatementParsingTestCase);
end.
|
unit AddOrderToOptimizationUnit;
interface
uses SysUtils, BaseExampleUnit, RouteParametersUnit,
AddressUnit;
type
TAddOrderToOptimization = class(TBaseExample)
public
procedure Execute(OptimizationId: String; RouteParameters: TRouteParameters;
OrderedAddresses: TOrderedAddressArray);
end;
implementation
uses AddOrderToOptimizationRequestUnit;
procedure TAddOrderToOptimization.Execute(OptimizationId: String;
RouteParameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);
var
ErrorString: String;
Parameters: TAddOrderToOptimizationRequest;
Address: TOrderedAddress;
begin
Parameters := TAddOrderToOptimizationRequest.Create;
try
Parameters.OptimizationProblemId := OptimizationId;
Parameters.Redirect := False;
Parameters.Parameters := RouteParameters;
for Address in OrderedAddresses do
Parameters.AddAddress(Address);
Route4MeManager.Optimization.AddOrder(Parameters, ErrorString);
WriteLn('');
if (ErrorString = EmptyStr) then
WriteLn('AddOrderToOptimization executed successfully')
else
WriteLn(Format('AddOrderToOptimization error: "%s"', [ErrorString]));
finally
FreeAndNil(Parameters);
end;
end;
end.
|
unit View.AtualizacaoSistema;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses,
dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, dxLayoutControlAdapters, Vcl.Menus, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, Vcl.StdCtrls, cxButtons, cxProgressBar, IdException, IniFiles, ShellAPI, WinInet,
cxCustomListBox, cxListBox;
type
Tview_AtualizacaoSistema = class(TForm)
cxProgressBar1: TcxProgressBar;
IdFTP1: TIdFTP;
cxButton1: TcxButton;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
cxButton2: TcxButton;
cxLabel3: TcxLabel;
procedure IdFTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure IdFTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FnTamanhoTotal: integer;
public
{ Public declarations }
function ObterDiretorioDoExecutavel: string;
function ConectarAoServidorFTP: boolean;
function ObterNumeroVersaoLocal: integer;
function ObterNumeroVersaoFTP: integer;
function VerificarExisteConexaoComInternet: boolean;
procedure BaixarAtualizacao;
procedure DescompactarAtualizacao;
procedure AtualizarNumeroVersao;
end;
var
view_AtualizacaoSistema: Tview_AtualizacaoSistema;
bytesToTransfer: integer;
implementation
{$R *.dfm}
uses Data.SisGeF;
{ Tview_AtualizacaoSistema }
procedure Tview_AtualizacaoSistema.AtualizarNumeroVersao;
var
oArquivoLocal, oArquivoFTP: TIniFile;
sNumeroNovaVersao: string;
begin
// abre os dois arquivos INI
oArquivoFTP := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoFTP.ini');
oArquivoLocal := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoLocal.ini');
try
// obtém o número da nova versão no arquivo "VersaoFTP.ini"...
sNumeroNovaVersao := oArquivoFTP.ReadString('VersaoFTP', 'Numero', EmptyStr);
// ... e grava este número no arquivo "VersaoLocal.ini"
oArquivoLocal.WriteString('VersaoLocal', 'Numero', sNumeroNovaVersao);
finally
FreeAndNil(oArquivoFTP);
FreeAndNil(oArquivoLocal);
end;
end;
procedure Tview_AtualizacaoSistema.BaixarAtualizacao;
begin
try
// deleta o arquivo "Atualizacao.rar", caso exista,
// evitando erro de arquivo já existente
if FileExists(ObterDiretorioDoExecutavel + 'Atualizacao.rar') then
DeleteFile(ObterDiretorioDoExecutavel + 'Atualizacao.rar');
// obtém o tamanho da atualização e preenche a variável "FnTamanhoTotal"
FnTamanhoTotal := IdFTP1.Size('Download/SisGeF5/Atualizacao.rar');
// faz o download do arquivo "Atualizacao.rar"
IdFTP1.Get('Download/SisGeF5/Atualizacao.rar',
ObterDiretorioDoExecutavel + 'Atualizacao.rar', True, True);
except
On E:Exception do
begin
// ignora a exceção "Connection Closed Gracefully"
if E is EIdConnClosedGracefully then
Exit;
ShowMessage('Erro ao baixar a atualização: ' + E.Message);
// interrompe a atualização
Abort;
end;
end;
end;
function Tview_AtualizacaoSistema.ConectarAoServidorFTP: boolean;
begin
// desconecta, caso tenha sido conectado anteriormente
if IdFTP1.Connected then
IdFTP1.Disconnect;
try
IdFTP1.Connect;
result := True;
except
On E:Exception do
begin
ShowMessage('Erro ao acessar o servidor de atualização: ' + E.Message);
result := False;
end;
end;
end;
procedure Tview_AtualizacaoSistema.cxButton1Click(Sender: TObject);
begin
BaixarAtualizacao;
DescompactarAtualizacao;
AtualizarNumeroVersao;
ShowMessage('O sistema foi atualizado com sucesso!');
ShellExecute(Handle, nil, PChar(Application.ExeName), '', nil, SW_SHOWNORMAL);
Application.Terminate;
end;
procedure Tview_AtualizacaoSistema.cxButton2Click(Sender: TObject);
begin
Close;
end;
procedure Tview_AtualizacaoSistema.DescompactarAtualizacao;
var
sNomeArquivoAtualizacao: string;
begin
// deleta o backup anterior, ou melhor, da versão anterior,
// evitando erro de arquivo já existente
if FileExists(ObterDiretorioDoExecutavel + 'SisGeF5_Backup.exe') then
DeleteFile(ObterDiretorioDoExecutavel + 'SisGeF5_Backup.exe');
// Renomeia o executável atual (desatualizado) para "Sistema_Backup.exe"
RenameFile(ObterDiretorioDoExecutavel + 'SisGeF5.exe',
ObterDiretorioDoExecutavel + 'SisGeF5_Backup.exe');
// armazena o nome do arquivo de atualização em uma variável
sNomeArquivoAtualizacao := ObterDiretorioDoExecutavel + 'Atualizacao.rar';
// executa a linha de comando do 7-Zip para descompactar o arquivo baixado
ShellExecute(0, nil, '7z', PWideChar(' x -aoa ' +
sNomeArquivoAtualizacao + ' -o' + ObterDiretorioDoExecutavel), '', SW_SHOW);
end;
procedure Tview_AtualizacaoSistema.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
view_AtualizacaoSistema := nil;
end;
procedure Tview_AtualizacaoSistema.FormShow(Sender: TObject);
var
nNumeroVersaoLocal, nNumeroVersaoFTP: integer;
sMensagem: string;
begin
if not VerificarExisteConexaoComInternet then
begin
Close;
Exit;
end;
if not ConectarAoServidorFTP then
begin
Close;
Exit;
end;
nNumeroVersaoLocal := ObterNumeroVersaoLocal;
nNumeroVersaoFTP := ObterNumeroVersaoFTP;
if nNumeroVersaoLocal = nNumeroVersaoFTP then
begin
Close;
Exit;
end;
sMensagem := 'Existe uma atualização do sistema disponível. Clique em Atualizar para proceder com a atualização ou Sair para não atualizar.';
cxLabel3.Caption := sMensagem;
end;
procedure Tview_AtualizacaoSistema.IdFTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
nTamanhoTotal, nTransmitidos, nPorcentagem: real;
begin
if FnTamanhoTotal = 0 then
Exit;
Application.ProcessMessages;
// obtém o tamanho total do arquivo em bytes
nTamanhoTotal := FnTamanhoTotal div 1024;
// obtém a quantidade de bytes já baixados
nTransmitidos := AWorkCount div 1024;
// calcula a porcentagem de download
nPorcentagem := (nTransmitidos * 100) / nTamanhoTotal;
// atualiza o componente TLabel com a porcentagem
cxLabel1.Caption := Format('%s KB',
[FormatFloat('##,###,##0', nTransmitidos)]);
// atualiza a barra de preenchimento do componente TProgressBar
//cxProgressBar1.Position := AWorkCount div 1024;
cxProgressBar1.Position := nPorcentagem;
end;
procedure Tview_AtualizacaoSistema.IdFTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
cxProgressBar1.Properties.Max := FnTamanhoTotal div 1024;
end;
function Tview_AtualizacaoSistema.ObterDiretorioDoExecutavel: string;
begin
result := ExtractFilePath(Application.ExeName);
end;
function Tview_AtualizacaoSistema.ObterNumeroVersaoFTP: integer;
var
sNumeroVersao: string;
oArquivoINI: TIniFile;
begin
// deleta o arquivo "VersaoFTP.ini" do computador, caso exista,
// evitando erro de arquivo já existente
if FileExists(ObterDiretorioDoExecutavel + 'VersaoFTP.ini') then
DeleteFile(ObterDiretorioDoExecutavel + 'VersaoFTP.ini');
// baixa o arquivo "VersaoFTP.ini" para o computador
IdFTP1.Get('Download/SisGeF5/VersaoFTP.ini', ObterDiretorioDoExecutavel + 'VersaoFTP.ini', True, True);
// abre o arquivo "VersaoFTP.ini"
oArquivoINI := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoFTP.ini');
try
// lê o número da versão
sNumeroVersao := oArquivoINI.ReadString('VersaoFTP', 'Numero', EmptyStr);
// retira os pontos (exemplo: de "1.0.1" para "101")
sNumeroVersao := StringReplace(sNumeroVersao, '.', EmptyStr, [rfReplaceAll]);
// converte o número da versão para número
result := StrToIntDef(sNumeroVersao, 0);
finally
FreeAndNil(oArquivoINI);
end;
end;
function Tview_AtualizacaoSistema.ObterNumeroVersaoLocal: integer;
var
sNumeroVersao: string;
oArquivoINI: TIniFile;
begin
// abre o arquivo "VersaoLocal.ini"
oArquivoINI := TIniFile.Create(ObterDiretorioDoExecutavel + 'VersaoLocal.ini');
try
// lê o número da versão
sNumeroVersao := oArquivoINI.ReadString('VersaoLocal', 'Numero', EmptyStr);
// retira os pontos (exemplo: de "1.0.0" para "100")
sNumeroVersao := StringReplace(sNumeroVersao, '.', EmptyStr, [rfReplaceAll]);
// converte o número da versão para número
result := StrToIntDef(sNumeroVersao, 0);
finally
FreeAndNil(oArquivoINI);
end;
end;
function Tview_AtualizacaoSistema.VerificarExisteConexaoComInternet: boolean;
var
nFlags: Cardinal;
begin
result := InternetGetConnectedState(@nFlags, 0);
end;
end.
|
unit QRPageInfo;
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 6.0 for Delphi and C++Builder ::
:: ::
:: QRPageInfo.PAS - page link classes ::
:: ::
:: Copyright (c) 2016 QBS Software ::
:: All Rights Reserved ::
:: ::
:: web: http://www.quickreport.co.uk ::
::
:: 15/08/2016 added TQRPageInfoList.Initialise ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
interface
uses Windows, Classes, Controls, StdCtrls, Sysutils, Graphics, Buttons,
Forms, ExtCtrls, Dialogs;
type
TPageItemRec = class(TObject)
public
controlname : string;
controlclass : string;
recordnumber : integer;
left, top, width, height : double;
textcontent : string;
destructor Destroy;override;
end;
TQRLinkPage = class(TObject)
private
linkitems : TList;
public
pagenumber : integer;
constructor Create;
destructor Destroy;override;
function getItemRec( n : integer ): TPageItemRec;
procedure addItemRec( nirec : TPageItemRec);
function HitTest( px,py : integer) : TPageItemRec;
end;
TQRPageInfoList = class(TObject)
private
pilist : TList;
public
constructor Create;
destructor Destroy;override;
function getPageRec( n : integer ): TQRLinkPage;
procedure addPageRec( nirec : TQRLinkPage);
procedure Initialise;
end;
implementation
{TPageItemRec}
destructor TPageItemRec.Destroy;
begin
inherited Destroy;
end;
{TQRLinkPage}
constructor TQRLinkPage.Create;
begin
linkItems := TList.Create;
end;
destructor TQRLinkPage.Destroy;
var
n : integer;
begin
for n := 0 to linkitems.Count-1 do
TPageItemRec(linkitems[n]).destroy;
linkitems.Free;
inherited Destroy
end;
function TQRLinkPage.getItemRec( n : integer ): TPageItemRec;
begin
result := TPageItemRec(linkitems[n]);
end;
procedure TQRLinkPage.addItemRec( nirec : TPageItemRec);
begin
linkitems.Add(nirec);
end;
function TQRLinkPage.HitTest( px,py : integer) : TPageItemRec;
var
n : integer;
pirec : TPageItemRec;
begin
result := nil;
for n := 0 to linkitems.Count - 1 do
begin
pirec := self.getItemRec(n);
if (pirec.left < px) and(pirec.top < py) and( (pirec.left+pirec.width) > px)
and ((pirec.top+pirec.height) > py) then
begin
result := pirec;
break;
end;
end;
end;
{ TQRPageInfoList}
constructor TQRPageInfoList.Create;
begin
pilist := TList.Create;
end;
destructor TQRPageInfoList.Destroy;
begin
pilist.Clear;
pilist.Free;
inherited Destroy;
end;
procedure TQRPageInfoList.Initialise;
begin
pilist.Clear;
end;
function TQRPageInfoList.getPageRec( n : integer ): TQRLinkPage;
begin
result := nil;
if n < pilist.Count then
result := TQRLinkPage(pilist[n]);
end;
procedure TQRPageInfoList.addPageRec( nirec : TQRLinkPage);
begin
pilist.Add(nirec);
end;
end.
|
unit SendThread;
interface
uses
ncsMessageQueue, l3Base;
type
TSendThread = class(Tl3ThreadContainer)
private
f_Queue : TncsMessageQueue;
f_IterateCount: Integer;
f_FileName: String;
f_PartSize: Integer;
protected
procedure DoExecute; override;
protected
procedure Cleanup; override;
public
constructor Create(anQueue: TncsMessageQueue; anIterateCount: Integer; const aFileName: String; aPartSize: Integer);
end;
implementation
uses
ncsPushFilePart, SysUtils, Classes, l3Stream, l3Types, l3TempMemoryStream, ncsMessage;
{ TSendThread }
procedure TSendThread.Cleanup;
begin
FreeAndNil(f_Queue);
inherited;
end;
constructor TSendThread.Create(anQueue: TncsMessageQueue; anIterateCount: Integer; const aFileName: String; aPartSize: Integer);
begin
inherited Create;
anQueue.SetRefTo(f_Queue);
f_IterateCount := anIterateCount;
f_FileName := aFileName;
f_PartSize := aPartSize;
end;
procedure TSendThread.DoExecute;
var
l_Message: TncsPushFilePart;
// l_Message: TncsMessage;
l_Stream: TStream;
l_Stream2: TStream;
l_IDX: Integer;
begin
l_Stream := Tl3FileStream.Create(f_FileName, l3_fmRead);
try
for l_IDX := 0 to f_IterateCount - 1 do
begin
l_Stream.Seek(0, soBeginning);
// l_Message := TncsMessage.Create;
l_Message := TncsPushFilePart.Create;
try
l_Message.Data.CopyFrom(l_Stream, f_PartSize);
l_Stream2 := Tl3TempMemoryStream.Create;
try
l_Message.SaveToEVD(l_Stream2, nil);
finally
FreeAndNil(l_Stream2);
end;
f_Queue.Push(l_Message);
finally
FreeAndNil(l_Message);
end;
end;
finally
FreeAndNil(l_Stream);
end;
f_Queue.Processing := False;
end;
end.
|
unit Unt_Principal;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.StdCtrls,
Unt_FuncaoLog,
Unt_DiversasThreads;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
Button1: TButton;
Button2: TButton;
Button3: TButton;
StatusBar1: TStatusBar;
Timer1: TTimer;
Memo1: TMemo;
Label1: TLabel;
Button4: TButton;
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
/// <summary>
/// Instância do primeiro objeto
/// </summary>
FThread1: TDiversaThread;
/// <summary>
/// Instância do segundo objeto
/// </summary>
FThread2: TDiversaThread;
/// <summary>
/// Método que será associado ao evento OnTerminate de cada thread
/// </summary>
procedure EventoFinalizacaoThread(Sender: TObject);
/// <summary>
/// Método responsável por alimentar o memo com eventuais erros
/// </summary>
procedure AlimentarMemoErro(const AReferencia: string; const AErro: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.Diagnostics;
{$R *.dfm}
procedure TForm1.AlimentarMemoErro(const AReferencia, AErro: string);
var
sLinha: string;
begin
sLinha := Format('%s -> %s', [AReferencia, AErro]);
Memo1.Lines.Insert(0, sLinha);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Self.Button1.Enabled := False;
Self.FThread1 := TDiversaThread.Create(True);
Self.FThread1.Referencia := 'THREAD #1';
Self.FThread1.OnTerminate := Self.EventoFinalizacaoThread;
Self.FThread1.Start;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Self.Button2.Enabled := False;
Self.FThread2 := TDiversaThread.Create(True);
Self.FThread2.Referencia := 'THREAD #2';
Self.FThread2.OnTerminate := Self.EventoFinalizacaoThread;
Self.FThread2.Start;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
i : Integer;
rCronus: TStopwatch;
begin
try
rCronus := TStopwatch.StartNew;
for i := 1 to 1000 do
begin
TGeraLog.Instancia.GerarLog('MAIN THREAD', Now, 'Três pratos de trigo para três tigres tristes');
end;
rCronus.Stop;
Self.Label1.Caption := Format('Processado em: %d milisegundos', [rCronus.ElapsedMilliseconds]);
except
on E: EInOutError do
begin
Self.AlimentarMemoErro('MAIN THREAD', Format('Erro de I/O #%d - %s', [E.ErrorCode, SysErrorMessage(E.ErrorCode)]));
end;
on E: Exception do
begin
Self.AlimentarMemoErro('MAIN THREAD', Format('(%s) - %s', [E.ClassName, E.Message]));
end;
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
bRet: Boolean;
begin
bRet := TGeraLog.Instancia.TryGerarLog('Button4', Now, 'Testando o TryEnter ...');
ShowMessage(Format('Sucesso? [%s]', [BoolToStr(bRet, True)]));
end;
procedure TForm1.EventoFinalizacaoThread(Sender: TObject);
var
oThread: TDiversaThread;
begin
oThread := TDiversaThread(Sender);
Self.AlimentarMemoErro(oThread.Referencia, oThread.DescricaoErro);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if Assigned(Self.FThread1) and not(Self.FThread1.Finished) then
begin
Self.FThread1.Terminate;
Self.FThread1.WaitFor;
end;
if Assigned(Self.FThread2) and not(Self.FThread2.Finished) then
begin
Self.FThread2.Terminate;
Self.FThread2.WaitFor;
end;
if Assigned(Self.FThread1) then
begin
Self.FThread1.Free;
end;
if Assigned(Self.FThread2) then
begin
Self.FThread2.Free;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
StatusBar1.Panels[0].Text := DateTimeToStr(Now);
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uIniOptionsService.pas }
{ Описание: INI реализация IOptionsService }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uIniOptionsService;
interface
uses
uServices, uBaseOptionsService;
type
TIniOptionsService = class(TBaseOptionsService, IOptionsService)
private
function GetIniFileName(AScope: TOptionScope): string;
public
function ReadOption(AOptionName: String; ADefaultValue: Variant; AScope:
TOptionScope = opsDomainUser): Variant; override; stdcall;
procedure WriteOption(AOptionName: String; AValue: Variant; AScope:
TOptionScope = opsDomainUser); override; stdcall;
end;
implementation
uses
JclSysInfo, StrUtils, SysUtils, inifiles, Variants, JclFileUtils;
{
****************************** TIniOptionsService ******************************
}
function TIniOptionsService.GetIniFileName(AScope: TOptionScope): string;
var
Dir: string;
begin
Dir := ExtractFilePath(ParamStr(0));
case AScope of
opsDomainUser:
begin
Dir := '%APPDATA%';
ExpandEnvironmentVar(Dir);
end;
opsComputer:
begin
Dir := '%PROGRAMDATA%';
ExpandEnvironmentVar(Dir);
end;
end;
Result := PathAppend(Dir, ExtractFileName(ParamStr(0)) + '.ini');
end;
function TIniOptionsService.ReadOption(AOptionName: String; ADefaultValue:
Variant; AScope: TOptionScope = opsDomainUser): Variant;
var
FileName: string;
IniFile: TIniFile;
Scope: TOptionScope;
SectionName: string;
begin
IniFile := nil;
Result := ADefaultValue;
for Scope := AScope to High(TOptionScope) do
begin
FileName := GetIniFileName(Scope);
if IniFile <> nil then
begin
if IniFile.FileName <> FileName then
begin
IniFile.Free;
IniFile := nil;
end;
end;
if (IniFile = nil) and FileExists(FileName) then
IniFile := TIniFile.Create(FileName);
if IniFile <> nil then
begin
SectionName := GetScopeSectionName(Scope);
if IniFile.ValueExists(SectionName, AOptionName) then
begin
Result := IniFile.ReadString(SectionName, AOptionName, VarToStr(ADefaultValue));
if not VarIsNull(ADefaultValue) then
Result := VarAsType(Result, VarType(ADefaultValue));
Break;
end;
end;
end;
if IniFile <> nil then
IniFile.Free;
end;
procedure TIniOptionsService.WriteOption(AOptionName: String; AValue: Variant;
AScope: TOptionScope = opsDomainUser);
var
IniFile: TIniFile;
SectionName: string;
begin
IniFile := TIniFile.Create(GetIniFileName(AScope));
SectionName := GetScopeSectionName(AScope);
IniFile.WriteString(SectionName, AOptionName, VarToStr(AValue));
IniFile.Free;
end;
end.
|
unit TestScenario;
interface
uses
TestFramework, Classes, Scenario, ScenarioIntf, TestBaseClasses;
type
TestTScenario = class(TParseContext)
strict private
FScenario: IScenario;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure DeveriaSerInvalidoSeNaoPossuirAoMenosUmStepValido;
procedure DeveriaSerValidoSomenteSeStepsSaoValidos;
procedure DeveriaSerInvalidoSeNaoPossuiTitulo;
procedure DeveriaSerValidoSePossuirUmaClasseDeTesteAssociadaAoTitulo;
procedure DeveriaRetornarONomeDaClasseDeTesteCorretamente;
procedure DeveriaSerInvalidoSeNaoPossuiTestesAssociadosAosSteps;
end;
implementation
uses
Step, StepIntf, ValidationRuleIntf, DummyTests, SysUtils;
procedure TestTScenario.DeveriaSerValidoSomenteSeStepsSaoValidos;
begin
FScenario.Steps.Add(TStep.Create);
Specify.That((FScenario as IValidationRule).Valid).Should.Be.False;
end;
procedure TestTScenario.SetUp;
var
LTest: ITest;
begin
// FScenario := TUmCenarioValido.Create('');
// LTest := TUmCenarioValido.Suite as ITest;
LTest := TUmCenarioValido.Suite;
FScenario := LTest.Tests[0] as IScenario;
// FScenario := TUmCenarioValido.Create('DadoQueTenhoUmStepValido');
// FScenario := TUmCenarioValido.Suite as IScenario;
end;
procedure TestTScenario.TearDown;
begin
FScenario := nil;
end;
procedure TestTScenario.DeveriaSerValidoSePossuirUmaClasseDeTesteAssociadaAoTitulo;
begin
FScenario.Titulo := 'Um Cenário Valido';
FScenario.Steps.Add(TStep.Create);
(FScenario.Steps.First as IStep).Descricao := 'Dado que tenho um step valido';
Specify.That((FScenario as IValidationRule).Valid).Should.Be.True;
end;
procedure TestTScenario.DeveriaSerInvalidoSeNaoPossuiTitulo;
begin
FScenario.Steps.Add(TStep.Create);
(FScenario.Steps.First as IStep).Descricao := 'Dado que tenho um step valido';
Specify.That((FScenario as IValidationRule).Valid).Should.Be.False;
end;
procedure TestTScenario.DeveriaSerInvalidoSeNaoPossuiTestesAssociadosAosSteps;
var
LStep: IStep;
begin
FScenario := nil;
FScenario := (TUmCenarioInvalido.Suite.Tests[0] as IScenario);
FScenario.Titulo := 'Um Cenário Invalido';
FScenario.Steps.Add(TStep.Create);
LStep := (FScenario.Steps.First as IStep);
LStep.Descricao := 'Dado que tenho um step valido.';
Specify.That((FScenario as IValidationRule).Valid).Should.Be.False;
Specify.That((FScenario as ITest).Tests).Should.Not_.Be.Empty;
end;
procedure TestTScenario.DeveriaRetornarONomeDaClasseDeTesteCorretamente;
begin
FScenario.Titulo := 'Um Cenário Valido';
Specify.That(FScenario.TestName).Should.Equal('TUmCenarioValido');
end;
procedure TestTScenario.DeveriaSerInvalidoSeNaoPossuirAoMenosUmStepValido;
var
LCenarioValido: ITestSuite;
begin
LCenarioValido := TUmCenarioValido.Suite;
// RegisterTest(LCenarioValido);
// FScenario.TestSuite;
FScenario.Titulo := 'Um Cenário Valido';
FScenario.Steps.Add(TStep.Create);
(FScenario.Steps.First as IStep).Descricao := 'Dado que tenho um step valido';
Specify.That((FScenario as IValidationRule).Valid).Should.Be.True;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTScenario.Suite);
end.
|
{*****************************************************}
{ }
{ EldoS Themes Support Library }
{ }
{ (C) 2002-2003 EldoS Corporation }
{ http://www.eldos.com/ }
{ }
{*****************************************************}
{$include elpack2.inc}
{$IFDEF ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$ELSE}
{$IFDEF LINUX}
{$I ../ElPack.inc}
{$ELSE}
{$I ..\ElPack.inc}
{$ENDIF}
{$ENDIF}
unit ElThemesWindowsXPButton;
interface
{$IFDEF ELPACK_THEME_ENGINE}
uses
Windows, ElThemesGeneral, ElThemesWindowsXP;
type
TWindowsXPThemePushButtonDisabled = class(TWindowsXPThemePart)
protected
function GetStateRectIndex(StateID: integer): integer; override;
end;
TWindowsXPThemePushButton = class(TWindowsXPThemePart)
private
FDisabled: TWindowsXPThemePushButtonDisabled;
protected
function GetStateRectIndex(StateID: integer): integer; override;
public
constructor Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string); override;
destructor Destroy; override;
procedure DrawThemeBackground(DC: HDC; StateID: integer; const Rect: TRect;
ClipRect: PRect); override;
procedure DrawThemeText(DC: HDC; StateID: integer; Text: PWideChar;
CharCount: integer; TextFlags: cardinal; TextFlags2: cardinal;
var Rect: TRect); override;
end;
TWindowsXPThemeRadioButtonDisabled = class(TWindowsXPThemePart)
protected
function GetStateRectIndex(StateID: integer): integer; override;
end;
TWindowsXPThemeRadioButton = class(TWindowsXPThemePart)
private
FUncheckedDisabled: TWindowsXPThemeRadioButtonDisabled;
FCheckedDisabled: TWindowsXPThemeRadioButtonDisabled;
protected
function GetStateRectIndex(StateID: integer): integer; override;
public
constructor Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string); override;
destructor Destroy; override;
procedure DrawThemeBackground(DC: HDC; StateID: integer; const Rect: TRect;
ClipRect: PRect); override;
procedure DrawThemeText(DC: HDC; StateID: integer; Text: PWideChar;
CharCount: integer; TextFlags: cardinal; TextFlags2: cardinal;
var Rect: TRect); override;
end;
TWindowsXPThemeCheckBoxDisabled = class(TWindowsXPThemePart)
protected
function GetStateRectIndex(StateID: integer): integer; override;
end;
TWindowsXPThemeCheckBox = class(TWindowsXPThemePart)
private
FUncheckedDisabled: TWindowsXPThemeCheckBoxDisabled;
FCheckedDisabled: TWindowsXPThemeCheckBoxDisabled;
FMixedDisabled: TWindowsXPThemeCheckBoxDisabled;
protected
function GetStateRectIndex(StateID: integer): integer; override;
public
constructor Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string); override;
destructor Destroy; override;
procedure DrawThemeBackground(DC: HDC; StateID: integer; const Rect: TRect;
ClipRect: PRect); override;
procedure DrawThemeText(DC: HDC; StateID: integer; Text: PWideChar;
CharCount: integer; TextFlags: cardinal; TextFlags2: cardinal;
var Rect: TRect); override;
end;
TWindowsXPThemeGroupBox = class(TWindowsXPThemePart)
protected
function GetStateRectIndex(StateID: integer): integer; override;
end;
TWindowsXPThemeButton = class(TWindowsXPTheme)
public
constructor Create(Manager: TThemeManager); override;
end;
{$ENDIF}
implementation
{$IFDEF ELPACK_THEME_ENGINE}
uses
ElTmSchema;
{ TWindowsXPThemeButton }
constructor TWindowsXPThemeButton.Create(Manager: TThemeManager);
var
Part: TWindowsXPThemePart;
begin
inherited;
Part := TWindowsXPThemePushButton.Create(Self, nil, 'Button.PushButton');
AddPart(BP_PUSHBUTTON, Part);
Part := TWindowsXPThemeRadioButton.Create(Self, nil, 'Button.RadioButton');
AddPart(BP_RADIOBUTTON, Part);
Part := TWindowsXPThemeCheckBox.Create(Self, nil, 'Button.CheckBox');
AddPart(BP_CHECKBOX, Part);
Part := TWindowsXPThemeGroupBox.Create(Self, nil, 'Button.GroupBox');
AddPart(BP_GROUPBOX, Part);
end;
{ TWindowsXPThemePushButtonDisabled }
function TWindowsXPThemePushButtonDisabled.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= PBS_NORMAL) and (StateID <= PBS_DEFAULTED) then
Result := StateID - PBS_NORMAL
else
Result := 0;
end;
{ TWindowsXPThemePushButton }
constructor TWindowsXPThemePushButton.Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string);
begin
inherited;
FDisabled := TWindowsXPThemePushButtonDisabled.Create(Theme, Self,
'Button.PushButton(Disabled)');
end;
destructor TWindowsXPThemePushButton.Destroy;
begin
FDisabled.Free;
inherited;
end;
procedure TWindowsXPThemePushButton.DrawThemeBackground(DC: HDC;
StateID: integer; const Rect: TRect; ClipRect: PRect);
begin
if StateID = PBS_DISABLED then
FDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect)
else
inherited;
end;
procedure TWindowsXPThemePushButton.DrawThemeText(DC: HDC;
StateID: integer; Text: PWideChar; CharCount: integer; TextFlags,
TextFlags2: cardinal; var Rect: TRect);
begin
if StateID = PBS_DISABLED then
FDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect)
else
inherited;
end;
function TWindowsXPThemePushButton.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= PBS_NORMAL) and (StateID <= PBS_DEFAULTED) then
Result := StateID - PBS_NORMAL
else
Result := 0;
end;
{ TWindowsXPThemeRadioButtonDisabled }
function TWindowsXPThemeRadioButtonDisabled.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= RBS_UNCHECKEDNORMAL) and (StateID <= RBS_CHECKEDDISABLED) then
Result := StateID - RBS_UNCHECKEDNORMAL
else
Result := 0;
end;
{ TWindowsXPThemeRadioButton }
constructor TWindowsXPThemeRadioButton.Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string);
begin
inherited;
FUncheckedDisabled := TWindowsXPThemeRadioButtonDisabled.Create(Theme,
Self, 'Button.RadioButton(UncheckedDisabled)');
FCheckedDisabled := TWindowsXPThemeRadioButtonDisabled.Create(Theme,
Self, 'Button.RadioButton(CheckedDisabled)');
end;
destructor TWindowsXPThemeRadioButton.Destroy;
begin
FCheckedDisabled.Free;
FUncheckedDisabled.Free;
inherited;
end;
procedure TWindowsXPThemeRadioButton.DrawThemeBackground(DC: HDC;
StateID: integer; const Rect: TRect; ClipRect: PRect);
begin
case StateID of
RBS_UNCHECKEDDISABLED: FUncheckedDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect);
RBS_CHECKEDDISABLED : FCheckedDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect);
else
inherited;
end;
end;
procedure TWindowsXPThemeRadioButton.DrawThemeText(DC: HDC;
StateID: integer; Text: PWideChar; CharCount: integer; TextFlags,
TextFlags2: cardinal; var Rect: TRect);
begin
case StateID of
RBS_UNCHECKEDDISABLED: FUncheckedDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect);
RBS_CHECKEDDISABLED : FCheckedDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect);
else
inherited;
end;
end;
function TWindowsXPThemeRadioButton.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= RBS_UNCHECKEDNORMAL) and (StateID <= RBS_CHECKEDDISABLED) then
Result := StateID - RBS_UNCHECKEDNORMAL
else
Result := 0;
end;
{ TWindowsXPThemeCheckBoxDisabled }
function TWindowsXPThemeCheckBoxDisabled.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= CBS_UNCHECKEDNORMAL) and (StateID <= CBS_MIXEDDISABLED) then
Result := StateID - CBS_UNCHECKEDNORMAL
else
Result := 0;
end;
{ TWindowsXPThemeCheckBox }
constructor TWindowsXPThemeCheckBox.Create(Theme: TWindowsXPTheme;
Parent: TWindowsXPThemePart; Section: string);
begin
inherited;
FUncheckedDisabled := TWindowsXPThemeCheckBoxDisabled.Create(Theme,
Self, 'Button.CheckBox(UncheckedDisabled)');
FCheckedDisabled := TWindowsXPThemeCheckBoxDisabled.Create(Theme,
Self, 'Button.CheckBox(CheckedDisabled)');
FMixedDisabled := TWindowsXPThemeCheckBoxDisabled.Create(Theme,
Self, 'Button.CheckBox(MixedDisabled)');
end;
destructor TWindowsXPThemeCheckBox.Destroy;
begin
FMixedDisabled.Free;
FCheckedDisabled.Free;
FUncheckedDisabled.Free;
inherited;
end;
procedure TWindowsXPThemeCheckBox.DrawThemeBackground(DC: HDC;
StateID: integer; const Rect: TRect; ClipRect: PRect);
begin
case StateID of
CBS_UNCHECKEDDISABLED: FUncheckedDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect);
CBS_CHECKEDDISABLED : FCheckedDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect);
CBS_MIXEDDISABLED : FMixedDisabled.DrawThemeBackground(DC, StateID, Rect, ClipRect);
else
inherited;
end;
end;
procedure TWindowsXPThemeCheckBox.DrawThemeText(DC: HDC; StateID: integer;
Text: PWideChar; CharCount: integer; TextFlags, TextFlags2: cardinal;
var Rect: TRect);
begin
case StateID of
CBS_UNCHECKEDDISABLED: FUncheckedDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect);
CBS_CHECKEDDISABLED : FCheckedDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect);
CBS_MIXEDDISABLED : FMixedDisabled.DrawThemeText(DC, StateID, Text, CharCount, TextFlags, TextFlags2, Rect);
else
inherited;
end;
end;
function TWindowsXPThemeCheckBox.GetStateRectIndex(StateID: integer): integer;
begin
if (StateID >= CBS_UNCHECKEDNORMAL) and (StateID <= CBS_MIXEDDISABLED) then
Result := StateID - CBS_UNCHECKEDNORMAL
else
Result := 0;
end;
{ TWindowsXPThemeGroupBox }
function TWindowsXPThemeGroupBox.GetStateRectIndex(StateID: integer): integer;
begin
Result := 0;
end;
{$ENDIF}
end.
|
unit ChromeLikeFormFramePainter;
interface
uses
Controls,
Forms,
Messages,
Windows,
Graphics,
Types,
UxTheme,
vcmGlassForm;
type
TChromeLikeFormFramePainterStyle = (ffpsLegacy, ffpsThemed);
TChromeLikeFormFramePainterKind = (ffpkActive, ffpkInactive, ffpkDisabled);
TChromeLikeFormFrameElement = (ffeCaptionBody, ffeCaptionLeftCorner,
ffeCaptionRightCorner, ffeLeftEdge, ffeRightEdge, ffeBottomEdge,
ffeLeftBottomCorner, ffeRightBottomCorner);
TChromeLikeFormFrameElementRects = array[TChromeLikeFormFrameElement] of TRect;
TChromeLikeformFramePainter = class(TObject)
private
f_Form: TvcmGlassForm;
f_Theme: HTHEME;
f_CaptionHeight: Integer;
f_BorderWidth: Integer;
f_ThemeBitmap: TBitmap;
f_ThemeElementPlacements: TChromeLikeFormFrameElementRects;
f_Painted: Boolean;
f_FormActive: Boolean;
f_UpdateCount: Integer;
function GetPaintKind: TChromeLikeFormFramePainterKind;
function GetPaintStyle: TChromeLikeFormFramePainterStyle;
procedure PaintElementsInternal;
procedure MakePlacements;
function pm_GetTheme: HTHEME;
property Theme: HTHEME read pm_GetTheme;
public
procedure BeginUpdate;
procedure EndUpdate;
procedure PaintElement(aCanvas: TCanvas; aElement: TChromeLikeFormFrameElement;
const aRect: TRect);
procedure CopyElementPartOnCanvas(aCanvas: TCanvas; const aDestRect: TRect;
const aSrcRect: TRect);
procedure Repaint(aActive: Boolean);
procedure InvalidateState(aActive: Boolean);
procedure InvalidateTheme;
procedure InvalidateSize;
constructor Create(aForm: TvcmGlassForm; aCaptionHeight: Integer; aBorderWidth: Integer);
destructor Destroy; override;
end;
implementation
uses
SysUtils,
ChromeLikeTypes,
ChromeLikeWinUtils,
Themes,
l3Base;
{ TChromeLikeformFramePainter }
function TChromeLikeFormFramePainter.GetPaintKind: TChromeLikeFormFramePainterKind;
const
cActiveFormArr: array[Boolean] of TChromeLikeFormFramePainterKind =
(ffpkInActive, ffpkActive);
begin
if f_Form.Enabled then
Result := cActiveFormArr[f_FormActive]
else
Result := ffpkDisabled;
end;
function TChromeLikeformFramePainter.GetPaintStyle: TChromeLikeFormFramePainterStyle;
const
cPainterStyleArr: array[Boolean] of TChromeLikeFormFramePainterStyle =
(ffpsLegacy, ffpsThemed);
begin
Result := cPainterStyleArr[IsAppThemed];
end;
procedure TChromeLikeformFramePainter.PaintElementsInternal;
var
l_TotalRect: TRect;
procedure lp_PaintElementsThemed;
(* Рисует форму со стилями *)
const
cEdgeStateArr: array[Boolean] of Integer =
(FS_INACTIVE, FS_ACTIVE);
// - Состояния границ окна
cWindowStateArr: array[Boolean] of Integer =
(WP_CAPTION, WP_MAXCAPTION);
// - PartID в зависимости от состояния окна
cNormalCaptionStateArr: array[Boolean] of Integer =
(CS_INACTIVE, CS_ACTIVE);
// - StateID для заголовка нормального окна в зависимости от активности окна
cMaxCaptionStateArr: array[Boolean] of Integer =
(MXCS_INACTIVE, MXCS_ACTIVE);
// - StateID для заголовка развернутого окна в зависимости от активности окна
var
l_CaptionRect: TRect;
l_LeftEdgeRect: TRect;
l_RightEdgeRect: TRect;
l_BottomEdgeRect: TRect;
l_StateID: Integer;
l_PaintKind: TChromeLikeFormFramePainterKind;
begin
l_PaintKind := GetPaintKind;
UnionRect(l_CaptionRect, f_ThemeElementPlacements[ffeCaptionLeftCorner],
f_ThemeElementPlacements[ffeCaptionRightCorner]);
UnionRect(l_CaptionRect, l_CaptionRect,
f_ThemeElementPlacements[ffeCaptionBody]);
UnionRect(l_BottomEdgeRect, f_ThemeElementPlacements[ffeBottomEdge],
f_ThemeElementPlacements[ffeRightBottomCorner]);
UnionRect(l_BottomEdgeRect, l_BottomEdgeRect,
f_ThemeElementPlacements[ffeLeftBottomCorner]);
if (f_Form.WindowState <> wsMaximized) then
// - Для максимизированной формы границы не рисуем
begin
DrawThemeBackground(Theme,
f_ThemeBitmap.Canvas.Handle,
WP_FRAMELEFT,
cEdgeStateArr[f_FormActive],
f_ThemeElementPlacements[ffeLeftEdge],
nil);
// - Левая граница
DrawThemeBackground(Theme,
f_ThemeBitmap.Canvas.Handle,
WP_FRAMERIGHT,
cEdgeStateArr[f_FormActive],
f_ThemeElementPlacements[ffeRightEdge],
nil);
// - Правая граница
DrawThemeBackground(Theme,
f_ThemeBitmap.Canvas.Handle,
WP_FRAMEBOTTOM,
cEdgeStateArr[f_FormActive],
l_BottomEdgeRect,
nil);
// - Нидняя граница
end;
if (f_Form.WindowState = wsMaximized) then
l_StateID := cMaxCaptionStateArr[f_FormActive]
else
l_StateID := cNormalCaptionStateArr[f_FormActive];
DrawThemeBackground(Theme,
f_ThemeBitmap.Canvas.Handle,
cWindowStateArr[f_Form.WindowState = wsMaximized],
l_StateID,
l_CaptionRect,
nil);
// - Заголовок
end;
procedure lp_PaintElementsLegacy;
(* Рисует форму в классическом оформлении *)
type
TCaptionColorPair = record
rColorFrom: TColor;
rColorTo: TColor;
end;
const
cCaptionColors: array[Boolean] of TCaptionColorPair =
((rColorFrom: clInactiveCaption; rColorTo: clGradientInactiveCaption),
(rColorFrom: clActiveCaption; rColorTo: clGradientActiveCaption));
// - Цвета для рисования заголовка
cStyleArr: array[ffeCaptionLeftCorner..ffeRightBottomCorner] of UINT =
(BF_TOPLEFT, BF_TOPRIGHT, BF_LEFT, BF_RIGHT,
BF_BOTTOM, BF_BOTTOMLEFT, BF_BOTTOMRIGHT);
// - Виды границ окна
var
l_Index: TChromeLikeFormFrameElement;
l_BrushRecall: TBrushRecall;
l_GradientCaptionsEnabled: BOOL;
l_LegacyCaptionBlueStrip: TRect;
l_LegacyFrameTopEdge: TRect;
begin
f_ThemeBitmap.Canvas.Brush.Color := clBtnFace;
f_ThemeBitmap.Canvas.FillRect(l_TotalRect);
if (f_Form.WindowState <> wsMaximized) then
// - Для максимизированной формы границы не рисуем
begin
for l_Index := ffeCaptionLeftCorner to ffeRightBottomCorner do
DrawEdge(f_ThemeBitmap.Canvas.Handle,
f_ThemeElementPlacements[l_Index],
BDR_RAISEDINNER or BDR_RAISEDOUTER,
cStyleArr[l_Index]);
l_LegacyFrameTopEdge := f_ThemeElementPlacements[ffeCaptionLeftCorner];
l_LegacyFrameTopEdge.Right := f_ThemeElementPlacements[ffeCaptionRightCorner].Left;
l_LegacyFrameTopEdge.Bottom := f_BorderWidth * 2;
DrawEdge(f_ThemeBitmap.Canvas.Handle,
l_LegacyFrameTopEdge,
BDR_RAISEDINNER or BDR_RAISEDOUTER,
BF_TOP);
// - Нарисовали границы
end;
l_GradientCaptionsEnabled := False;
l_LegacyCaptionBlueStrip := f_ThemeElementPlacements[ffeCaptionBody];
Inc(l_LegacyCaptionBlueStrip.Top, f_BorderWidth);
SystemParametersInfo(SPI_GETGRADIENTCAPTIONS,
0,
@l_GradientCaptionsEnabled,
0);
if l_GradientCaptionsEnabled then
FillGradient(f_ThemeBitmap.Canvas.Handle,
l_LegacyCaptionBlueStrip,
255,
cCaptionColors[GetPaintKind = ffpkActive].rColorFrom,
cCaptionColors[GetPaintKind = ffpkActive].rColorTo,
gdHorizontal)
// - градиентный заголовок
else
begin
l_BrushRecall := TBrushRecall.Create(f_ThemeBitmap.Canvas.Brush);
try
f_ThemeBitmap.Canvas.Brush.Color := cCaptionColors[GetPaintKind = ffpkActive].rColorFrom;
f_ThemeBitmap.Canvas.FillRect(l_LegacyCaptionBlueStrip);
finally
FreeAndNil(l_BrushRecall);
end;
// - неградиентный заголовок
end;
end;
begin
if (f_UpdateCount = 0) then
begin
l_TotalRect := Rect(0, 0, f_Form.Width, f_Form.Height);
if (GetPaintStyle = ffpsThemed) then
lp_PaintElementsThemed
else
lp_PaintElementsLegacy;
end;
end;
procedure TChromeLikeformFramePainter.MakePlacements;
var
l_FormRect: TRect;
l_CaptionRect: TRect;
l_BottomEdgeTop: Integer;
begin
l3FillChar(f_ThemeElementPlacements, SizeOf(f_ThemeElementPlacements), 0);
l_FormRect := Rect(0, 0, f_Form.Width, f_Form.Height);
l_CaptionRect := Rect(0, 0, f_Form.Width, f_CaptionHeight);
f_ThemeElementPlacements[ffeCaptionBody] := l_CaptionRect;
Inc(f_ThemeElementPlacements[ffeCaptionBody].Left, f_BorderWidth);
Dec(f_ThemeElementPlacements[ffeCaptionBody].Right, f_BorderWidth);
// - тело заголовка
f_ThemeElementPlacements[ffeCaptionLeftCorner] := Rect(0, 0, f_BorderWidth,
f_BorderWidth);
// - левый угол заголовка
f_ThemeElementPlacements[ffeCaptionRightCorner] := l_CaptionRect;
f_ThemeElementPlacements[ffeCaptionRightCorner].Left := l_CaptionRect.Right - f_BorderWidth;
// - правый угол заголовка
l_BottomEdgeTop := l_FormRect.Bottom - f_BorderWidth;
// - Y-координата верха нижней границы формы
f_ThemeElementPlacements[ffeLeftEdge] := Rect(0, f_BorderWidth, f_BorderWidth,
l_BottomEdgeTop);
// - левая граница
f_ThemeElementPlacements[ffeRightEdge] := Rect(l_FormRect.Right - f_BorderWidth,
f_BorderWidth, l_FormRect.Right, l_BottomEdgeTop);
// - правая граница
f_ThemeElementPlacements[ffeBottomEdge] := Rect(f_BorderWidth, l_BottomEdgeTop,
l_FormRect.Right - f_BorderWidth, l_FormRect.Bottom);
// - нижняя граница
f_ThemeElementPlacements[ffeLeftBottomCorner] := Rect(0, l_BottomEdgeTop,
f_BorderWidth, l_FormRect.Bottom);
// - Нижний левый угол границы
f_ThemeElementPlacements[ffeRightBottomCorner] := Rect(l_FormRect.Right - f_BorderWidth,
l_BottomEdgeTop, l_FormRect.Right, l_FormRect.Bottom);
// - Нижний правый угол границы
end;
function TChromeLikeFormFramePainter.pm_GetTheme: HTHEME;
const
cThemeWndClass: PWideChar = 'WINDOW';
begin
if (f_Theme = 0) then
f_Theme := OpenThemeData(f_Form.Handle, cThemeWndClass);
Result := f_Theme;
end;
procedure TChromeLikeformFramePainter.BeginUpdate;
begin
Inc(f_UpdateCount);
end;
procedure TChromeLikeformFramePainter.EndUpdate;
begin
Dec(f_UpdateCount);
if (f_UpdateCount = 0) then
PaintElementsInternal;
end;
constructor TChromeLikeformFramePainter.Create(aForm: TvcmGlassForm;
aCaptionHeight, aBorderWidth: Integer);
begin
inherited Create;
f_Form := aForm;
f_Theme := 0;
f_CaptionHeight := aCaptionHeight;
f_BorderWidth := aBorderWidth;
f_ThemeBitmap := TBitmap.Create;
f_Painted := False;
InvalidateSize;
l3FillChar(f_ThemeElementPlacements, SizeOf(f_ThemeElementPlacements), 0);
end;
destructor TChromeLikeformFramePainter.Destroy;
begin
if (f_Theme <> 0) then
CloseThemeData(f_Theme);
FreeAndNil(f_ThemeBitmap);
inherited;
end;
procedure TChromeLikeformFramePainter.InvalidateSize;
begin
f_Painted := False;
f_ThemeBitmap.Width := f_Form.Width;
f_ThemeBitmap.Height := f_Form.Height;
MakePlacements;
PaintElementsInternal;
end;
procedure TChromeLikeFormFramePainter.PaintElement(aCanvas: TCanvas;
aElement: TChromeLikeFormFrameElement; const aRect: TRect);
begin
CopyElementPartOnCanvas(aCanvas, aRect, f_ThemeElementPlacements[aElement]);
end;
procedure TChromeLikeformFramePainter.CopyElementPartOnCanvas(aCanvas: TCanvas;
const aDestRect: TRect; const aSrcRect: TRect);
begin
Assert(aCanvas <> nil);
if (not f_Painted) then
PaintElementsInternal;
aCanvas.CopyRect(aDestRect, f_ThemeBitmap.Canvas, aSrcRect);
end;
procedure TChromeLikeFormFramePainter.Repaint(aActive: Boolean);
begin
BeginUpdate;
InvalidateSize;
InvalidateState(aActive);
EndUpdate;
end;
procedure TChromeLikeFormFramePainter.InvalidateState(aActive: Boolean);
begin
f_FormActive := aActive;
PaintElementsInternal;
end;
procedure TChromeLikeformFramePainter.InvalidateTheme;
begin
if (f_Theme <> 0) then
CloseThemeData(f_Theme);
f_Painted := False;
end;
initialization
InitThemeLibrary;
finalization
FreeThemeLibrary;
end.
|
unit uRotinasBase;
interface
uses ZDataset, ZSqlProcessor, udmPrincipal;
function RotinaExiste(aNomeRotina: string): Boolean;
procedure FuncEstoqueAtual(var ScriptSQL: TZSQLProcessor);
procedure ProcVeLimite(var ScriptSQL: TZSQLProcessor);
procedure FuncFormatFone(var ScriptSQL: TZSQLProcessor);
procedure FuncSoNumeros(var ScriptSQL: TZSQLProcessor);
procedure FuncEstoqueFisico(var ScriptSQL: TZSQLProcessor);
procedure FuncIndiceConvProdutos(var ScriptSQL: TZSQLProcessor);
procedure FuncResumoEstoque(var ScriptSQL: TZSQLProcessor);
procedure FuncLucroProduto(var ScriptSQL: TZSQLProcessor);
procedure FuncCustoProduto(var ScriptSQL: TZSQLProcessor);
procedure FuncVeContasReceber(var ScriptSQL: TZSQLProcessor);
procedure FuncVeContasPagar(var ScriptSQL: TZSQLProcessor);
procedure FuncVeVendasPeriodo(var ScriptSQL: TZSQLProcessor);
implementation
uses ZConnection;
function RotinaExiste(aNomeRotina: string): Boolean;
begin
with TZReadOnlyQuery.Create(nil) do
begin
Connection := dmPrincipal.Database;
try
SQL.Text := 'select count(*) from information_schema.routines where routine_schema=:pDatabase and routine_name=:pNomeRotina';
ParamByName('pDatabase').AsString := dmPrincipal.Database.Database;
ParamByName('pNomeRotina').AsString := aNomeRotina;
Open;
Result := Fields[0].AsInteger > 0;
finally
Close;
Free;
end;
end;
end;
procedure FuncEstoqueAtual(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('estoque_atual') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION estoque_atual(pEmpresa INT,pData DATE,pProduto VARCHAR(60),pAgrupa CHAR(1)) RETURNS decimal(10,4)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE TotalRegistros INT DEFAULT 0;');
ScriptSQL.Script.Add(' select resumo_estoque(pEmpresa,pData,pData,pProduto,pAgrupa) into TotalRegistros;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' IF Totalregistros = 0 THEN');
ScriptSQL.Script.Add(' RETURN 0;');
ScriptSQL.Script.Add(' ELSE');
ScriptSQL.Script.Add(' select teorico into TotalRegistros from resumo_estoque where produto=pProduto;');
ScriptSQL.Script.Add(' RETURN TotalRegistros;');
ScriptSQL.Script.Add(' END IF;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure ProcVeLimite(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_limite') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE PROCEDURE ve_limite(pcodigo int, pfilial int, pempresa int, pvalor decimal(10,4), out limite decimal(10,4), out vencimento date)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add('select sum(cr.valor)-');
ScriptSQL.Script.Add(' sum(ifnull(bcr.valor,0))-if(sum(cr.desconto)-sum(ifnull(bcr.desconto,0))<0,0,sum(cr.desconto)-');
ScriptSQL.Script.Add(' sum(ifnull(bcr.desconto,0))) + pvalor,');
ScriptSQL.Script.Add(' min(cr.vencimento)');
ScriptSQL.Script.Add(' into limite, vencimento');
ScriptSQL.Script.Add('from contas_receber cr');
ScriptSQL.Script.Add(' left join baixas_creceber bcr on cr.id=bcr.id_receber and bcr.empresa_codigo=cr.empresa_codigo');
ScriptSQL.Script.Add('where');
ScriptSQL.Script.Add(' cr.status in(0,1) and cr.valor>0 and isnull(cr.data_exc)');
ScriptSQL.Script.Add(' and cr.empresa_codigo=pempresa');
ScriptSQL.Script.Add(' and cr.cliente_codigo=pcodigo and cr.cliente_filial=pfilial;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncFormatFone(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('format_fone') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION format_fone(aFone varchar(11)) RETURNS varchar(14)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' CASE length(aFone)');
ScriptSQL.Script.Add(' WHEN 10 THEN return concat(left(aFone,2)," ",mid(aFone,3,4),"-",mid(aFone,7,4));');
ScriptSQL.Script.Add(' WHEN 11 THEN');
ScriptSQL.Script.Add(' BEGIN');
ScriptSQL.Script.Add(' IF (left(aFone,4)="0300") or (left(aFone,4)="0500") or (left(aFone,4)="0800") then');
ScriptSQL.Script.Add(' return concat(left(aFone,4)," ",mid(aFone,5,3)," ",mid(aFone,8,4));');
ScriptSQL.Script.Add(' else');
ScriptSQL.Script.Add(' return concat(left(aFone,2)," ",mid(aFone,3,5),"-",mid(aFone,8,4));');
ScriptSQL.Script.Add(' END IF;');
ScriptSQL.Script.Add(' END;');
ScriptSQL.Script.Add(' ELSE');
ScriptSQL.Script.Add(' return aFone;');
ScriptSQL.Script.Add(' END CASE;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncSoNumeros(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('SO_NUMEROS') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION SO_NUMEROS(PALAVRA VARCHAR(255)) RETURNS varchar(255)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE RESULTADO VARCHAR(255) default "";');
ScriptSQL.Script.Add(' DECLARE LETRA CHAR(1);');
ScriptSQL.Script.Add(' DECLARE QTD_LETRA INTEGER;');
ScriptSQL.Script.Add(' DECLARE CONT INTEGER DEFAULT 0;');
ScriptSQL.Script.Add(' SET QTD_LETRA = LENGTH(PALAVRA);');
ScriptSQL.Script.Add(' WHILE CONT < QTD_LETRA DO');
ScriptSQL.Script.Add(' SET CONT = CONT + 1;');
ScriptSQL.Script.Add(' SET LETRA = MID(PALAVRA,CONT,1);');
ScriptSQL.Script.Add(' IF LETRA IN("0","1","2","3","4","5","6","7","8","9") THEN');
ScriptSQL.Script.Add(' SET RESULTADO = CONCAT(RESULTADO,LETRA);');
ScriptSQL.Script.Add(' END IF;');
ScriptSQL.Script.Add(' END WHILE;');
ScriptSQL.Script.Add(' RETURN RESULTADO;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncEstoqueFisico(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('estoque_fisico') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `estoque_fisico`(pEmpresa INT, pDataInicial DATE, pDataFinal DATE, pProduto VARCHAR(60)) RETURNS int(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE DataContagem DATE;');
ScriptSQL.Script.Add(' DECLARE TotalRegistros INT DEFAULT 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS estoque_fisico;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `estoque_fisico` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `tipo` enum("BA","IE","IS","EN","SD","CT") NOT NULL DEFAULT "BA",');
ScriptSQL.Script.Add(' `produto` varchar(60) NOT NULL,');
ScriptSQL.Script.Add(' `quantidade` decimal(10,4) DEFAULT "0.0000",');
ScriptSQL.Script.Add(' `unitario` decimal(16,10) DEFAULT "0.0000000000",');
ScriptSQL.Script.Add(' PRIMARY KEY (`empresa_codigo`,`produto`,`tipo`)');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select data INTO DataContagem');
ScriptSQL.Script.Add(' from contagem_estoque_data');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data<pDataInicial');
ScriptSQL.Script.Add(' order by 1 desc');
ScriptSQL.Script.Add(' limit 1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' if not isnull(DataContagem) then');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select empresa_codigo,"BA",produto,quantidade,valor_unitario');
ScriptSQL.Script.Add(' from contagem_estoque');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data=DataContagem and produto like pProduto;');
ScriptSQL.Script.Add(' else');
ScriptSQL.Script.Add(' SELECT FROM_DAYS(366) INTO DataContagem;');
ScriptSQL.Script.Add(' end if;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select empresa_codigo,"CT",produto,quantidade,valor_unitario');
ScriptSQL.Script.Add(' from contagem_estoque');
ScriptSQL.Script.Add(' Where empresa_codigo=pEmpresa and data=pDataFinal and produto like pProduto;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select a.empresa_codigo,"IE",produto_codigo,sum(quantidade),sum(valor_total)/sum(quantidade)');
ScriptSQL.Script.Add(' from compras a');
ScriptSQL.Script.Add(' join compras_itens b on a.empresa_codigo=b.empresa_codigo and a.id=b.id_compra');
ScriptSQL.Script.Add(' join operacoes o on a.operacao=o.codigo');
ScriptSQL.Script.Add(' where o.tipo="E" and o.estoque="S" and isnull(a.data_exc) and isnull(b.data_exc) and produto_codigo like pProduto');
ScriptSQL.Script.Add(' and a.empresa_codigo=pEmpresa and data between ADDDATE(DataContagem,INTERVAL 1 DAY) and ADDDATE(pDataFinal,INTERVAL -1 DAY)');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select a.empresa_codigo,"EN",produto_codigo,sum(quantidade),sum(valor_total)/sum(quantidade)');
ScriptSQL.Script.Add(' from compras a');
ScriptSQL.Script.Add(' join compras_itens b on a.empresa_codigo=b.empresa_codigo and a.id=b.id_compra');
ScriptSQL.Script.Add(' join operacoes o on a.operacao=o.codigo');
ScriptSQL.Script.Add(' where o.tipo="E" and o.estoque="S" and isnull(a.data_exc) and isnull(b.data_exc) and produto_codigo like pProduto');
ScriptSQL.Script.Add(' and a.empresa_codigo=pEmpresa and data between pDataInicial and pDataFinal');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select a.empresa_codigo,"IS",produto_codigo,sum(quantidade),sum(valor_total)/sum(quantidade)');
ScriptSQL.Script.Add(' from vendas a');
ScriptSQL.Script.Add(' join vendas_itens b on a.empresa_codigo=b.empresa_codigo and a.id=b.id_venda');
ScriptSQL.Script.Add(' join operacoes o on a.operacao=o.codigo');
ScriptSQL.Script.Add(' where o.tipo="S" and o.estoque="S" and isnull(a.data_exc) and isnull(b.data_exc) and produto_codigo like pProduto');
ScriptSQL.Script.Add(' and a.empresa_codigo=pEmpresa and data between ADDDATE(DataContagem,INTERVAL 1 DAY) and ADDDATE(pDataInicial,INTERVAL -1 DAY)');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into estoque_fisico');
ScriptSQL.Script.Add(' select a.empresa_codigo,"SD",produto_codigo,sum(quantidade),sum(valor_total)/sum(quantidade)');
ScriptSQL.Script.Add(' from vendas a');
ScriptSQL.Script.Add(' join vendas_itens b on a.empresa_codigo=b.empresa_codigo and a.id=b.id_venda');
ScriptSQL.Script.Add(' join operacoes o on a.operacao=o.codigo');
ScriptSQL.Script.Add(' where o.tipo="S" and o.estoque="S" and isnull(a.data_exc) and isnull(b.data_exc) and produto_codigo like pProduto');
ScriptSQL.Script.Add(' and a.empresa_codigo=pEmpresa and data between pDataInicial and pDataFinal');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select count(*) into TotalRegistros from estoque_fisico;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' RETURN TotalRegistros;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Script.Add('');
ScriptSQL.Execute;
end;
end;
procedure FuncIndiceConvProdutos(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('PROD_IND_CONV') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION PROD_IND_CONV(pAGRUPA CHAR(1),pPRODUTO VARCHAR(60)) RETURNS decimal(10,4)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DECLARE vTIPO char(1) default "";');
ScriptSQL.Script.Add(' DECLARE vQTDE_CONVERSAO,vQTDE_PRINCIPAL decimal(10,4) default 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' SELECT tipo,qtde_conversao,qtde_principal');
ScriptSQL.Script.Add(' INTO vTIPO,vQTDE_CONVERSAO,vQTDE_PRINCIPAL');
ScriptSQL.Script.Add(' FROM produtos WHERE CODIGO=pPRODUTO;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' IF UCASE(pAGRUPA) = "N" THEN');
ScriptSQL.Script.Add(' RETURN 1;');
ScriptSQL.Script.Add(' ELSEIF vTIPO = "P" THEN');
ScriptSQL.Script.Add(' RETURN 1;');
ScriptSQL.Script.Add(' ELSE');
ScriptSQL.Script.Add(' RETURN vQTDE_CONVERSAO / vQTDE_PRINCIPAL;');
ScriptSQL.Script.Add(' END IF;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncResumoEstoque(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('resumo_estoque') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `resumo_estoque`(pEmpresa INT,pDataI DATE,pDataF DATE,pProduto VARCHAR(60),pAgrupa CHAR(1)) RETURNS int(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE TotalRegistros INT DEFAULT 0;');
ScriptSQL.Script.Add(' SELECT estoque_fisico(pEmpresa,pDataI,pDataF,pProduto) INTO TotalRegistros;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' IF Totalregistros = 0 THEN');
ScriptSQL.Script.Add(' RETURN 0;');
ScriptSQL.Script.Add(' ELSE');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS resumo_estoque;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE resumo_estoque');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' if(pAgrupa="S",if(p.tipo="P",p.codigo,p.codigo_fechamento),produto) produto,');
ScriptSQL.Script.Add(' if(pAgrupa="S",if(p.tipo="P",p.nome,pc.nome),p.nome) nome,');
ScriptSQL.Script.Add(' if(pAgrupa="S",if(p.tipo="P",p.unidade,pc.unidade),p.unidade) unidade,');
ScriptSQL.Script.Add(' sum((if(e.tipo in("BA","IE"),quantidade,0)-if(e.tipo="IS",quantidade,0)+if(e.tipo="EN",quantidade,0)-');
ScriptSQL.Script.Add(' if(e.tipo="SD",quantidade,0))*PROD_IND_CONV("N",p.codigo)) as teorico');
ScriptSQL.Script.Add(' from estoque_fisico e');
ScriptSQL.Script.Add(' join produtos p on e.produto=p.codigo');
ScriptSQL.Script.Add(' left join produtos pc on p.codigo_fechamento=pc.codigo');
ScriptSQL.Script.Add(' group by if(pAgrupa="S",if(p.tipo="P",p.codigo,p.codigo_fechamento),produto)');
ScriptSQL.Script.Add(' order by nome;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select count(*) into TotalRegistros from resumo_estoque;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' RETURN TotalRegistros;');
ScriptSQL.Script.Add(' END IF;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncLucroProduto(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_lucro_produto') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `ve_lucro_produto` (pEmpresa INT, pDataInicial DATE, pDataFinal DATE) RETURNS INT(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE DataContagem DATE;');
ScriptSQL.Script.Add(' DECLARE TotalRegistros INT DEFAULT 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS prod_compra_venda;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `prod_compra_venda` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' data date,');
ScriptSQL.Script.Add(' `tipo` enum("ES","CP","VD") NOT NULL DEFAULT "ES",');
ScriptSQL.Script.Add(' pedido int(10),');
ScriptSQL.Script.Add(' item int(10),');
ScriptSQL.Script.Add(' `produto` varchar(60) NOT NULL,');
ScriptSQL.Script.Add(' `qtde_compra` decimal(10,4) DEFAULT "0.0000",');
ScriptSQL.Script.Add(' `total_compra` decimal(10,2) DEFAULT "0",');
ScriptSQL.Script.Add(' `qtde_venda` decimal(10,4) DEFAULT "0.0000",');
ScriptSQL.Script.Add(' `total_venda` decimal(10,2) DEFAULT "0"');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select data INTO DataContagem');
ScriptSQL.Script.Add(' from contagem_estoque_data');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data<pDataInicial');
ScriptSQL.Script.Add(' order by 1 desc');
ScriptSQL.Script.Add(' limit 1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' if not isnull(DataContagem) then');
ScriptSQL.Script.Add(' insert into prod_compra_venda(');
ScriptSQL.Script.Add(' empresa_codigo,data,tipo,pedido,item,produto,qtde_compra,total_compra)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' empresa_codigo,data,"ES",0,1,produto,quantidade,quantidade*valor_unitario');
ScriptSQL.Script.Add(' from contagem_estoque');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data=DataContagem;');
ScriptSQL.Script.Add(' else');
ScriptSQL.Script.Add(' SELECT FROM_DAYS(366) INTO DataContagem;');
ScriptSQL.Script.Add(' end if;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into prod_compra_venda(');
ScriptSQL.Script.Add(' empresa_codigo,data,tipo,pedido,item,produto,qtde_compra,total_compra)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' c.empresa_codigo,data,"ES",1,1,produto_codigo,sum(quantidade),sum(valor_total)');
ScriptSQL.Script.Add(' from compras c');
ScriptSQL.Script.Add(' join compras_itens ci on c.empresa_codigo=ci.empresa_codigo and c.id=ci.id_compra');
ScriptSQL.Script.Add(' join operacoes o on o.codigo=c.operacao');
ScriptSQL.Script.Add(' where financeiro="S" and c.empresa_codigo=pEmpresa');
ScriptSQL.Script.Add(' and data between ADDDATE(DataContagem,INTERVAL 1 DAY) and ADDDATE(pDataInicial,INTERVAL -1 DAY)');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into prod_compra_venda(');
ScriptSQL.Script.Add(' empresa_codigo,data,tipo,pedido,item,produto,qtde_compra,total_compra)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' c.empresa_codigo,data,"CP",1,1,produto_codigo,sum(quantidade),sum(valor_total)');
ScriptSQL.Script.Add(' from compras c');
ScriptSQL.Script.Add(' join compras_itens ci on c.empresa_codigo=ci.empresa_codigo and c.id=ci.id_compra');
ScriptSQL.Script.Add(' join operacoes o on o.codigo=c.operacao');
ScriptSQL.Script.Add(' where financeiro="S" and c.empresa_codigo=pEmpresa');
ScriptSQL.Script.Add(' and data between pDataInicial and pDataFinal');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into prod_compra_venda(');
ScriptSQL.Script.Add(' empresa_codigo,data,tipo,pedido,item,produto,qtde_venda,total_venda)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' v.empresa_codigo,data,"VD",id_venda,num_item,produto_codigo,quantidade,valor_total');
ScriptSQL.Script.Add(' from vendas v');
ScriptSQL.Script.Add(' join vendas_itens vi on v.empresa_codigo=vi.empresa_codigo and v.id=vi.id_venda');
ScriptSQL.Script.Add(' join operacoes o on o.codigo=v.operacao');
ScriptSQL.Script.Add(' where financeiro="S" and v.empresa_codigo=pEmpresa');
ScriptSQL.Script.Add(' and data between pDataInicial and pDataFinal;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select count(*) into TotalRegistros from prod_compra_venda;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' RETURN TotalRegistros;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncCustoProduto(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_custo_produto') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `ve_custo_produto`(pEmpresa INT, pProduto varchar(60), pDataInicial DATE, pDataFinal DATE) RETURNS decimal(16,10)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE DataContagem DATE;');
ScriptSQL.Script.Add(' DECLARE vCusto decimal(16,10);');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS preco_custo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `preco_custo` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `produto` varchar(60) NOT NULL,');
ScriptSQL.Script.Add(' `qtde_compra` decimal(10,4) DEFAULT "0.0000",');
ScriptSQL.Script.Add(' `total_compra` decimal(10,2) DEFAULT "0"');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select data INTO DataContagem');
ScriptSQL.Script.Add(' from contagem_estoque_data');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data<pDataInicial');
ScriptSQL.Script.Add(' order by 1 desc');
ScriptSQL.Script.Add(' limit 1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' if not isnull(DataContagem) then');
ScriptSQL.Script.Add(' insert into preco_custo(');
ScriptSQL.Script.Add(' empresa_codigo,produto,qtde_compra,total_compra)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' empresa_codigo,produto,sum(quantidade),sum(quantidade*valor_unitario)');
ScriptSQL.Script.Add(' from contagem_estoque');
ScriptSQL.Script.Add(' where empresa_codigo=pEmpresa and data=DataContagem and produto=pProduto');
ScriptSQL.Script.Add(' group by produto;');
ScriptSQL.Script.Add(' else');
ScriptSQL.Script.Add(' SELECT FROM_DAYS(366) INTO DataContagem;');
ScriptSQL.Script.Add(' end if;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into preco_custo(');
ScriptSQL.Script.Add(' empresa_codigo,produto,qtde_compra,total_compra)');
ScriptSQL.Script.Add(' select');
ScriptSQL.Script.Add(' c.empresa_codigo,produto_codigo,sum(quantidade),sum(valor_total)');
ScriptSQL.Script.Add(' from compras c');
ScriptSQL.Script.Add(' join compras_itens ci on c.empresa_codigo=ci.empresa_codigo and c.id=ci.id_compra');
ScriptSQL.Script.Add(' join operacoes o on o.codigo=c.operacao');
ScriptSQL.Script.Add(' where financeiro="S" and c.empresa_codigo=pEmpresa and produto_codigo=pProduto');
ScriptSQL.Script.Add(' and data between ADDDATE(DataContagem,INTERVAL 1 DAY) and pDataFinal');
ScriptSQL.Script.Add(' group by produto_codigo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select ifnull(sum(total_compra)/sum(qtde_compra),0) INTO vCusto from preco_custo;');
ScriptSQL.Script.Add(' RETURN vCusto;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncVeContasReceber(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_contas_receber') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `ve_contas_receber`(pEmpresa INT, pDataI DATE, pDataF DATE) RETURNS int(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE TOTAL_LINHAS INT DEFAULT 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS tmp_receber;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `tmp_receber` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `id_receber` int(10) unsigned NOT NULL,');
ScriptSQL.Script.Add(' `id_venda` bigint(11) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `numero` int(10) DEFAULT NULL,');
ScriptSQL.Script.Add(' `nota` int(11) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `fatura` int(11) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `data` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `vencimento` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `meio_pagamento` int(10) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `cond_pagamento` int(10) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `cliente_codigo` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `cliente_filial` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `valor_original` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `desconto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_documento` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_pago` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_aberto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `desconto_aberto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_receber` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' PRIMARY KEY (`empresa_codigo`,`id_receber`),');
ScriptSQL.Script.Add(' KEY `idx_venda` (`id_venda`)');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into tmp_receber');
ScriptSQL.Script.Add(' select cr.empresa_codigo,cr.id as id_receber,ifnull(id_venda,0) as id_venda,v.numero,');
ScriptSQL.Script.Add(' cast(ifnull(n.nota,0) as unsigned) as nota,cast(ifnull(n.fatura,0)as unsigned) as fatura,');
ScriptSQL.Script.Add(' cr.data,cr.vencimento,cr.id_meio_pagto,cr.id_condpag,cr.cliente_codigo,');
ScriptSQL.Script.Add(' cr.cliente_filial,cr.valor as valor_original,cr.desconto,');
ScriptSQL.Script.Add(' cast(cr.valor-cr.desconto as decimal(10,2)) as valor_documento,');
ScriptSQL.Script.Add(' cast(sum(ifnull(bcr.valor,0))-sum(ifnull(bcr.desconto,0))as decimal(10,2)) as valor_pago,');
ScriptSQL.Script.Add(' cast(cr.valor-sum(ifnull(bcr.valor,0)) as decimal(10,2))valor_aberto,');
ScriptSQL.Script.Add(' cast(if(cr.desconto-sum(ifnull(bcr.desconto,0))<0,0,cr.desconto-sum(ifnull(bcr.desconto,0))) as decimal(10,2)) as desconto_aberto,');
ScriptSQL.Script.Add(' cast(cr.valor-sum(ifnull(bcr.valor,0))-if(cr.desconto-sum(ifnull(bcr.desconto,0))<0,0,');
ScriptSQL.Script.Add(' cr.desconto-sum(ifnull(bcr.desconto,0)))as decimal(10,2)) as valor_receber');
ScriptSQL.Script.Add(' from contas_receber cr');
ScriptSQL.Script.Add(' left join baixas_creceber bcr on cr.id=bcr.id_receber and bcr.empresa_codigo=cr.empresa_codigo');
ScriptSQL.Script.Add(' left join vendas v on v.id=cr.id_venda and v.empresa_codigo=cr.empresa_codigo');
ScriptSQL.Script.Add(' left join notas_fiscais n on v.empresa_codigo=n.empresa_codigo and venda_codigo=v.id');
ScriptSQL.Script.Add(' where');
ScriptSQL.Script.Add(' cr.status in(0,1) and cr.valor>0 and isnull(cr.data_exc)');
ScriptSQL.Script.Add(' and cr.empresa_codigo=pEmpresa');
ScriptSQL.Script.Add(' and cr.data between pDataI and pDataF');
ScriptSQL.Script.Add(' group by cr.id;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' SELECT COUNT(*) INTO TOTAL_LINHAS FROM tmp_receber;');
ScriptSQL.Script.Add(' RETURN TOTAL_LINHAS;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncVeContasPagar(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_contas_pagar') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `ve_contas_pagar`(pEmpresa INT, pDataI DATE, pDataF DATE) RETURNS int(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE TOTAL_LINHAS INT DEFAULT 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DECLARE EXIT HANDLER FOR SQLEXCEPTION');
ScriptSQL.Script.Add(' BEGIN');
ScriptSQL.Script.Add(' RETURN 0;');
ScriptSQL.Script.Add(' END;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' DROP TEMPORARY TABLE IF EXISTS tmp_pagar;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `tmp_pagar` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `id_pagar` int(10) unsigned NOT NULL,');
ScriptSQL.Script.Add(' `id_compra` bigint(11) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `numero` int(10) DEFAULT NULL,');
ScriptSQL.Script.Add(' `nota` int(11) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `data` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `vencimento` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `meio_pagamento` int(10) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `cond_pagamento` int(10) NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `fornecedor_codigo` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `fornecedor_filial` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `valor_original` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `desconto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_documento` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_pago` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_aberto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `desconto_aberto` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' `valor_pagar` decimal(10,2) NOT NULL DEFAULT "0.00",');
ScriptSQL.Script.Add(' PRIMARY KEY (`empresa_codigo`,`id_pagar`),');
ScriptSQL.Script.Add(' KEY `idx_compra` (`id_compra`)');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into tmp_pagar');
ScriptSQL.Script.Add(' select cp.empresa_codigo,cp.id as id_pagar,ifnull(id_compra,0) as id_compra,c.numero,');
ScriptSQL.Script.Add(' cast(ifnull(c.nota,0) as unsigned) as nota,');
ScriptSQL.Script.Add(' cp.data,cp.vencimento,cp.id_meio_pagto,cp.id_condpag,cp.fornecedor_codigo,');
ScriptSQL.Script.Add(' cp.fornecedor_filial,cp.valor as valor_original,cp.desconto,');
ScriptSQL.Script.Add(' cast(cp.valor-cp.desconto as decimal(10,2)) as valor_documento,');
ScriptSQL.Script.Add(' cast(sum(ifnull(bcp.valor,0))-sum(ifnull(bcp.desconto,0))as decimal(10,2)) as valor_pago,');
ScriptSQL.Script.Add(' cast(cp.valor-sum(ifnull(bcp.valor,0)) as decimal(10,2))valor_aberto,');
ScriptSQL.Script.Add(' cast(if(cp.desconto-sum(ifnull(bcp.desconto,0))<0,0,cp.desconto-sum(ifnull(bcp.desconto,0))) as decimal(10,2)) as desconto_aberto,');
ScriptSQL.Script.Add(' cast(cp.valor-sum(ifnull(bcp.valor,0))-if(cp.desconto-sum(ifnull(bcp.desconto,0))<0,0,');
ScriptSQL.Script.Add(' cp.desconto-sum(ifnull(bcp.desconto,0)))as decimal(10,2)) as valor_receber');
ScriptSQL.Script.Add(' from contas_pagar cp');
ScriptSQL.Script.Add(' left join baixas_cpagar bcp on cp.id=bcp.id_pagar and bcp.empresa_codigo=cp.empresa_codigo');
ScriptSQL.Script.Add(' left join compras c on c.id=cp.id_compra and c.empresa_codigo=cp.empresa_codigo');
ScriptSQL.Script.Add(' where');
ScriptSQL.Script.Add(' cp.status in(0,1) and cp.valor>0 and isnull(cp.data_exc)');
ScriptSQL.Script.Add(' and cp.empresa_codigo=pEmpresa');
ScriptSQL.Script.Add(' and cp.data between pDataI and pDataF');
ScriptSQL.Script.Add(' group by cp.id;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' SELECT COUNT(*) INTO TOTAL_LINHAS FROM tmp_pagar;');
ScriptSQL.Script.Add(' RETURN TOTAL_LINHAS;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
procedure FuncVeVendasPeriodo(var ScriptSQL: TZSQLProcessor);
begin
if not RotinaExiste('ve_vendas_periodo') then
begin
ScriptSQL.Script.Clear;
ScriptSQL.Script.Add('CREATE FUNCTION `ve_vendas_periodo`(pEmpresa INT, pDataInicial DATE, pDataFinal DATE) RETURNS int(11)');
ScriptSQL.Script.Add('BEGIN');
ScriptSQL.Script.Add(' DECLARE TotalRegistros INT DEFAULT 0;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' drop temporary table if exists vendas_periodo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' CREATE TEMPORARY TABLE `vendas_periodo` (');
ScriptSQL.Script.Add(' `empresa_codigo` int(10) unsigned NOT NULL DEFAULT "0",');
ScriptSQL.Script.Add(' `id` int(10) NOT NULL,');
ScriptSQL.Script.Add(' `num_item` int(10) unsigned NOT NULL,');
ScriptSQL.Script.Add(' `data` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `vencimento` date DEFAULT NULL,');
ScriptSQL.Script.Add(' `vendedor` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `cliente_codigo` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `cliente_filial` int(10) unsigned DEFAULT NULL,');
ScriptSQL.Script.Add(' `quantidade` decimal(10,4) unsigned DEFAULT "0.0000",');
ScriptSQL.Script.Add(' `produto_codigo` varchar(60) DEFAULT NULL,');
ScriptSQL.Script.Add(' `valor_item` decimal(10,2) DEFAULT NULL,');
ScriptSQL.Script.Add(' `custo_item` decimal(10,2) DEFAULT NULL,');
ScriptSQL.Script.Add(' `lucro_item` decimal(10,2) DEFAULT NULL,');
ScriptSQL.Script.Add(' `comissao_vendedor` decimal(4,2) unsigned not null DEFAULT "0.00",');
ScriptSQL.Script.Add(' `tipo_comissao` enum("L","B") not null DEFAULT "L",');
ScriptSQL.Script.Add(' PRIMARY KEY (`empresa_codigo`,`id`,`num_item`),');
ScriptSQL.Script.Add(' KEY `idx_cliente` (`cliente_codigo`,`cliente_filial`),');
ScriptSQL.Script.Add(' KEY `idx_vendedor` (`vendedor`),');
ScriptSQL.Script.Add(' KEY `idx_produto` (`produto_codigo`)');
ScriptSQL.Script.Add(' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' insert into vendas_periodo');
ScriptSQL.Script.Add(' select v.empresa_codigo,v.id,num_item,v.data,v.vencimento,vendedor,v.cliente_codigo,');
ScriptSQL.Script.Add(' v.cliente_filial,quantidade,produto_codigo,');
ScriptSQL.Script.Add(' @valor_item:=cast(vi.valor_total-vi.desconto_item as decimal(10,2)) as valor_item,');
ScriptSQL.Script.Add(' @custo_item:=cast(quantidade*ve_custo_produto(v.empresa_codigo, produto_codigo, v.data, v.data)as decimal(10,2)) as custo_item,');
ScriptSQL.Script.Add(' cast(@valor_item-@custo_item as decimal(10,2)) as lucro_item,comissao_vendedor,tipo_comissao');
ScriptSQL.Script.Add(' from contas_receber r');
ScriptSQL.Script.Add(' join vendas v on r.id_venda=v.id and r.empresa_codigo=v.empresa_codigo');
ScriptSQL.Script.Add(' join vendas_itens vi on vi.id_venda=v.id and vi.empresa_codigo=v.empresa_codigo');
ScriptSQL.Script.Add(' where v.empresa_codigo=pEmpresa and v.data between pDataInicial and pDataFinal and parcela=1;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' select count(*) into TotalRegistros from vendas_periodo;');
ScriptSQL.Script.Add('');
ScriptSQL.Script.Add(' RETURN TotalRegistros;');
ScriptSQL.Script.Add('END $$');
ScriptSQL.Execute;
end;
end;
end.
|
unit fQIPPlugin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IniFiles, StdCtrls,
u_plugin_info, u_plugin_msg, u_common, ExtCtrls, Menus, ImgList;
type
{ TSpecCntUniq }
TSpecCntUniq = record
UniqID : DWord;
ItemType : DWord;
Index : DWord;
end;
pSpecCntUniq = ^TSpecCntUniq;
{ FadeMsg }
TFadeMsg = class
public
FadeType : Byte; //0 - message style, 1 - information style, 2 - warning style
FadeIcon : HICON; //icon in the top left corner of the window
FadeTitle : WideString;
FadeText : WideString;
TextCentered : Boolean; //if true then text will be centered inside window
NoAutoClose : Boolean; //if NoAutoClose is True then wnd will be always shown until user close it. Not recommended to set this param to True.
CloseTime : Integer;
pData : Integer;
end;
{ FadeMsgClosing }
TFadeMsgClosing = class
public
FadeID : DWord; //0 - message style, 1 - information style, 2 - warning style
Time : Integer; // 1 jednotka 500 ms.
end;
TfrmQIPPlugin = class(TForm)
tmrStep: TTimer;
tmrStart: TTimer;
pmContactMenu: TPopupMenu;
miContactMenu_OnOff: TMenuItem;
miContactMenu_Stations: TMenuItem;
miContactMenu_Formats: TMenuItem;
N1: TMenuItem;
miContactMenu_Informations: TMenuItem;
miContactMenu_Equalizer: TMenuItem;
miContactMenu_Recording: TMenuItem;
miContactMenu_EditStations: TMenuItem;
miContactMenu_Options: TMenuItem;
miContactMenu_Volume: TMenuItem;
ImageList1: TImageList;
miContactMenu_FastAddStation: TMenuItem;
tmrDraw: TTimer;
miContactMenu_CopySongName: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure tmrStepTimer(Sender: TObject);
procedure tmrStartTimer(Sender: TObject);
procedure miContactMenu_StationsClick(Sender: TObject);
procedure miContactMenu_FormatsClick(Sender: TObject);
procedure miContactMenu_InformationsClick(Sender: TObject);
procedure miContactMenu_EqualizerClick(Sender: TObject);
procedure miContactMenu_RecordingClick(Sender: TObject);
procedure miContactMenu_VolumeClick(Sender: TObject);
procedure miContactMenu_EditStationsClick(Sender: TObject);
procedure miContactMenu_OptionsClick(Sender: TObject);
procedure miContactMenu_OnOffClick(Sender: TObject);
procedure CMAdvDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect;
State: TOwnerDrawState);
procedure ddrrr(Sender: TObject; ACanvas: TCanvas; ARect: TRect;
Selected: Boolean);
procedure DrawMenu(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
procedure MeasureMenu(Sender: TObject; ACanvas: TCanvas;
var Width, Height: Integer);
procedure miContactMenu_FastAddStationClick(Sender: TObject);
procedure tmrDrawTimer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure miContactMenu_CopySongNameClick(Sender: TObject);
procedure pmContactMenuChange(Sender: TObject; Source: TMenuItem;
Rebuild: Boolean);
private
FPluginSvc : pIQIPPluginService;
FDllHandle : Cardinal;
FDllPath : WideString;
procedure WMHotKey(var msg:TWMHotKey);message WM_HOTKEY;
public
property PluginSvc : pIQIPPluginService read FPluginSvc write FPluginSvc;
property DllHandle : Cardinal read FDllHandle write FDllHandle;
property DllPath : WideString read FDllPath write FDllPath;
procedure CreateControls;
procedure FreeControls;
procedure LoadPluginOptions;
procedure SavePluginOptions;
procedure ShowPluginOptions;
// procedure SpellCheck(var PlugMsg: TPluginMessage);
// procedure SpellPopup(var PlugMsg: TPluginMessage);
procedure QipSoundChanged(PlugMsg: TPluginMessage);
procedure AntiBoss(HideForms: Boolean);
procedure CurrentLanguage(LangName: WideString);
procedure DrawSpecContact(PlugMsg: TPluginMessage);
procedure SpecContactDblClick(PlugMsg: TPluginMessage);
procedure SpecContactRightClick(PlugMsg: TPluginMessage);
procedure LeftClickOnFadeMsg(PlugMsg: TPluginMessage);
procedure GetSpecContactHintSize(var PlugMsg: TPluginMessage);
procedure DrawSpecContactHint(PlugMsg: TPluginMessage);
procedure XstatusChangedByUser(PlugMsg: TPluginMessage);
procedure InstantMsgRcvd(var PlugMsg: TPluginMessage);
procedure InstantMsgSend(var PlugMsg: TPluginMessage);
procedure NewMessageFlashing(PlugMsg: TPluginMessage);
procedure NewMessageStopFlashing(PlugMsg: TPluginMessage);
procedure AddNeededBtns(PlugMsg: TPluginMessage);
procedure MsgBtnClicked(PlugMsg: TPluginMessage);
procedure SpecMsgRcvd(PlugMsg: TPluginMessage);
procedure StatusChanged(PlugMsg: TPluginMessage);
procedure ImRcvdSuccess(PlugMsg: TPluginMessage);
procedure ContactStatusRcvd(PlugMsg: TPluginMessage);
procedure ChatTabAction(PlugMsg: TPluginMessage);
procedure AddNeededChatBtns(PlugMsg: TPluginMessage);
procedure ChatBtnClicked(PlugMsg: TPluginMessage);
procedure ChatMsgRcvd(PlugMsg: TPluginMessage);
procedure ChatMsgSending(var PlugMsg: TPluginMessage);
procedure EnumInfo(PlugMsg: TPluginMessage);
procedure DrawHint(Cnv: TCanvas; R : TRect; CalcRect: Boolean; var Width: Integer; var Height: Integer);
function FadeMsg(FType: Byte; FIcon: HICON; FTitle: WideString; FText: WideString; FTextCenter: Boolean; FNoAutoClose: Boolean; pData: Integer) : DWORD;
procedure AddFadeMsg(
FadeType : Byte; //0 - message style, 1 - information style, 2 - warning style
FadeIcon : HICON; //icon in the top left corner of the window
FadeTitle : WideString;
FadeText : WideString;
TextCentered : Boolean; //if true then text will be centered inside window
NoAutoClose : Boolean; //if NoAutoClose is True then wnd will be always shown until user close it. Not recommended to set this param to True.
CloseTime_Sec: Integer;
pData : Integer
);
procedure AddSpecContact(var UniqID: DWord; HeightCnt: Integer = 19);
procedure RedrawSpecContact(UniqID: DWord);
procedure RemoveSpecContact(var UniqID: DWord);
function GetLang(ID: Word) : WideString;
procedure InfiumClose(itype: Word);
procedure SetChangeVolume;
procedure ShowContactMenu(pX, pY : Integer );
procedure SaveSelectedRadio;
procedure StationNext;
procedure StationPrev;
protected
procedure CreateParams (var Params: TCreateParams); override;
end;
var
frmQIPPlugin: TfrmQIPPlugin;
FadeMsgs : TStringList;
FadeMsgsClosing : TStringList;
implementation
uses General, uImage, Convs, UpdaterUnit, uLNG, HotKeyManager,
DateUtils, BassPlayer, u_lang_ids, u_qip_plugin, uIcon, Drawing,
uSuperReplace, uStatistics, uColors, uTheme, uEqualizer, uFileFolder, uINI,
clipbrd;
{$R *.dfm}
procedure TfrmQIPPlugin.CreateParams (var Params: TCreateParams);
begin
inherited;
with Params do begin
ExStyle := (ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE);
end;
end;
procedure TfrmQIPPlugin.WMHotKey(var msg:TWMHotKey);
var
INI : TIniFile;
begin
if msg.HotKey = 8801 then
FBassPlayer.PlayStopRadio
else if msg.HotKey = 8802 then
begin
Player_Volume := Player_Volume + 5;
if Player_Volume > 100 then
Player_Volume := 100;
SetChangeVolume;
end
else if msg.HotKey = 8803 then
begin
Player_Volume := Player_Volume - 5;
if Player_Volume < 0 then
Player_Volume := 0;
SetChangeVolume;
end
else if msg.HotKey = 8804 then
begin
if Player_Mute = False then
Player_Mute := True
else
Player_Mute := False;
SetChangeVolume;
end
else if msg.HotKey = 8805 then
begin
StationNext();
end
else if msg.HotKey = 8806 then
begin
StationPrev();
end
else if msg.HotKey = 8807 then // Enable/Disable XStatus
begin
EnDisXStatus(-1);
end;
end;
procedure TfrmQIPPlugin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Unload_BASSDLL;
end;
procedure TfrmQIPPlugin.FormCreate(Sender: TObject);
begin
FadeMsgs := TStringList.Create;
FadeMsgs.Clear;
FadeMsgsClosing := TStringList.Create;
FadeMsgsClosing.Clear;
Stations := TStringList.Create;
Stations.Clear;
Playlist := TStringList.Create;
Playlist.Clear;
DataImportExport := TStringList.Create;
DataImportExport.Clear;
EqualizerPreset := TStringList.Create;
EqualizerPreset.Clear;
PluginSkin.MenuIcons := TStringList.Create;
PluginSkin.MenuIcons.Clear;
PluginSkin.OptionsIcons := TStringList.Create;
PluginSkin.OptionsIcons.Clear;
DTFormatDATETIME.DateSeparator := '-';
DTFormatDATETIME.TimeSeparator := ':';
DTFormatDATETIME.ShortDateFormat := 'YYYY-MM-DD';
DTFormatDATETIME.ShortTimeFormat := 'HH:MM:SS';
DTFormatDATETIME.LongDateFormat := 'YYYY-MM-DD'' ''HH:MM:SS';
FBassPlayer := TfrmBassPlayer.Create(nil);
// FBassPlayer.Show;
FBassPlayer.Height := 0;
FBassPlayer.Width := 0;
SetWindowPos(FBassPlayer.Handle,HWND_BOTTOM,0,0,0,0, SWP_NOACTIVATE {or SWP_SHOWWINDOW} or SWP_NOMOVE or SWP_NOSIZE);
end;
procedure TfrmQIPPlugin.CreateControls;
begin
//
end;
procedure TfrmQIPPlugin.FreeControls;
var RepMsg : TPluginMessage;
Repl_XStatus : TReplXStatus;
xRP : Boolean;
begin
xRP := False;
try
if Radio_Playing=True then
begin
xRP := True;
FBassPlayer.PlayStopRadio
end;
except
end;
try
if xRP = True then
begin
if (ActXstatusNum=11) or (XStatus_Type = 2) then
begin
if Radio_Playing=True then
begin
//FwStatus and FwDescription have to be class members or global variables to stay in memory because we return PWideChar
if Stations.Count - 1 >= Radio_StationID then
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID then
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
end;
FwStatus := ReplXStatus(XStatus_Title,Repl_XStatus);// 'Listenig radio:'; //max xstatus text length = 20 chars
if Stations.Count - 1 < Radio_StationID then
FwDescription := '' //max description text length = 512 chars
else
FwDescription := ReplXStatus(XStatus_Text,Repl_XStatus); //TSLStation(Stations.Objects[Radio_StationID]).Name; //max description text length = 512 chars
end
else
begin
FwStatus := LastXStatusText ; {''; } //max xstatus text length = 20 chars
FwDescription := LastXStatusDescription; {'';} //max description text length = 512 chars
end;
{Plugin msg to update xstatus}
RepMsg.Msg := PM_PLUGIN_XSTATUS_UPD;
{ WParam is number of xstatus picture in Core/Xstatuses/xstatuses.ini, if 0 then xstatus pic will be removed}
{When changing music track you can change xstatus picture number, it will cauz all clients to request your new
xstatus value, but better to make it optional, because it can be bothering for remote users}
if (Radio_Playing=False) And (XStatus_Type = 2) then
RepMsg.WParam := LastXStatusNumber { 0 }// Xstatus - not
else
RepMsg.WParam := 11; // Xstatus - Music
RepMsg.LParam := LongInt(PWideChar(FwStatus));
RepMsg.NParam := LongInt(PWideChar(FwDescription));
{when plugin sending msg to qip core it have to add self dllhandle, else your msg will be ignored}
RepMsg.DllHandle := DllHandle;
{send message to qip core. !!! Dont change xtatus too often, it can cauz disconnect}
FPluginSvc.OnPluginMessage(RepMsg);
{================================================================}
end;
end;
except
end;
try
if bBassLoadLibLoaded = True then
FBassPlayer.BASSPlayer_AllFree;
finally
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8801);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8802);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8803);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8804);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8805);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8806);
except
end;
try
UnregisterHotKey(QIPPlugin.Handle, 8807);
except
end;
try
if Assigned(FBassPlayer) then FreeAndNil(FBassPlayer);
except
end;
try
if Assigned(FAbout) then FreeAndNil(FAbout);
except
end;
try
if Assigned(FEqualizer) then FreeAndNil(FEqualizer);
except
end;
try
if Assigned(FFastAddStation) then FreeAndNil(FFastAddStation);
except
end;
try
if Assigned(FEditStations) then FreeAndNil(FEditStations);
except
end;
try
if Assigned(FInfo) then FreeAndNil(FInfo);
except
end;
try
if Assigned(FOptions) then FreeAndNil(FOptions);
except
end;
try
if Assigned(FRecording) then FreeAndNil(FRecording);
except
end;
try
if Assigned(FVolume) then FreeAndNil(FVolume);
except
end;
end;
procedure TfrmQIPPlugin.LoadPluginOptions;
var
PlugMsg1: TPluginMessage;
QipColors : pQipColors;
begin
PlugMsg1.Msg := PM_PLUGIN_GET_NAMES;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
if Boolean(PlugMsg1.Result) then
begin
Account_DisplayName := PWideChar(PlugMsg1.WParam);
Account_ProfileName := PWideChar(PlugMsg1.LParam);
end;
Account_FileName := Account_ProfileName;
// Profile path
PlugMsg1.Msg := PM_PLUGIN_GET_PROFILE_DIR;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
if Boolean(PlugMsg1.Result) then
begin
ProfilePath := PWideChar(PlugMsg1.WParam) + PLUGIN_NAME + '\';;
end;
PlugMsg1.Msg := PM_PLUGIN_GET_COLORS_FONT;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
//get results
{ wFontName := PWideChar(PlugMsg1.WParam);
iFontSize := PlugMsg1.LParam;}
QipColors := pQipColors(PlugMsg1.NParam);
QIP_Colors := QipColors^;
CheckFolder( ProfilePath, False );
tmrStart.Enabled := True;
end;
procedure TfrmQIPPlugin.miContactMenu_CopySongNameClick(Sender: TObject);
var
A: array[0..65000] of char;
Repl_XStatus : TReplXStatus;
sCopyText : WideString;
begin
if (Stations.Count - 1 < Radio_StationID) AND (Radio_StationID <> -1) then
else
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
if (TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID) AND (Radio_StreamID <> -1) then
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
sCopyText := ReplXStatus('%song%',Repl_XStatus);
StrPCopy(A, sCopyText );
Clipboard.SetTextBuf(A);
end;
end;
procedure TfrmQIPPlugin.miContactMenu_EditStationsClick(Sender: TObject);
begin
OpenEditStations;
end;
procedure TfrmQIPPlugin.miContactMenu_EqualizerClick(Sender: TObject);
begin
OpenEqualizer;
end;
procedure TfrmQIPPlugin.miContactMenu_FastAddStationClick(Sender: TObject);
begin
OpenFastAddStation;
end;
procedure TfrmQIPPlugin.miContactMenu_FormatsClick(Sender: TObject);
begin
if Sender <> miContactMenu_Formats then
begin
// Radio_StationID := (Sender as TMenuItem).Tag;
Radio_StreamID := (Sender as TMenuItem).Tag;
if SaveLastStream = True then
TStation(Stations.Objects[Radio_StationID]).DefaultStream := Radio_StreamID;
SaveSelectedRadio;
if Radio_Playing = True then
begin
FBassPlayer.PlayStopRadio;
Application.ProcessMessages;
FBassPlayer.PlayStopRadio;
end;
RedrawSpecContact(UniqContactId);
end;
end;
procedure TfrmQIPPlugin.miContactMenu_InformationsClick(Sender: TObject);
begin
OpenInfo;
end;
procedure TfrmQIPPlugin.miContactMenu_OnOffClick(Sender: TObject);
begin
FBassPlayer.PlayStopRadio;
end;
procedure TfrmQIPPlugin.MeasureMenu(Sender: TObject;
ACanvas: TCanvas; var Width, Height: Integer);
begin
Menu_MeasureMenu(Sender, ACanvas, Width, Height);
end;
procedure TfrmQIPPlugin.DrawMenu(Sender: TObject;
ACanvas: TCanvas; ARect: TRect; Selected: Boolean);
begin
Menu_DrawMenu(Sender, ACanvas, ARect, Selected);
end;
procedure TfrmQIPPlugin.miContactMenu_OptionsClick(Sender: TObject);
begin
OpenOptions;
end;
procedure TfrmQIPPlugin.miContactMenu_RecordingClick(Sender: TObject);
begin
OpenRecording;
end;
procedure TfrmQIPPlugin.miContactMenu_StationsClick(Sender: TObject);
begin
if Sender <> miContactMenu_Stations then
begin
Radio_StationID := (Sender as TMenuItem).Tag;
Radio_StreamID := TStation(Stations.Objects[Radio_StationID]).DefaultStream;
SaveSelectedRadio;
if Radio_Playing = True then
begin
FBassPlayer.PlayStopRadio;
Application.ProcessMessages;
FBassPlayer.PlayStopRadio;
end;
RedrawSpecContact(UniqContactId);
end;
end;
procedure TfrmQIPPlugin.miContactMenu_VolumeClick(Sender: TObject);
begin
OpenVolume;
end;
procedure TfrmQIPPlugin.SavePluginOptions;
var
INI : TIniFile;
begin
INIGetProfileConfig(INI);
if Assigned(Stations) then
begin
if Radio_StationID > Stations.Count - 1 then
//dodelat
else
begin
INIWriteStringUTF8(INI, 'Conf', 'StationID', TStation(Stations.Objects[ Radio_StationID ]).Name );
end;
INIWriteInteger(INI, 'Conf', 'StreamID', Radio_StreamID );
end;
INIFree(INI);
end;
procedure TfrmQIPPlugin.ShowPluginOptions;
begin
OpenOptions;
end;
procedure OldSetToNewPLugin(INI: TINIFile);
var
S: TextFile;
Rec: TSearchRec;
pom: String;
idx: Integer;
INI2: TINIFile;
begin
if (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) >= '0.6.1') and (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) <= '0.6.1.99 beta') then
begin
INIGetProfileConfig(INI2);
pom := INI2.ReadString('Equalizer', 'Values', '') + ', ';
for idx := 10 to FrequencyCount do
pom := pom + '0, ';
Delete(pom, Length(pom) - 1, 2); // smazání poslední mezery s čárkou
INI2.WriteString('Equalizer', 'Values', pom);
INIFree(INI2);
end;
if (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) >= '0.6.0') and (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) <= '0.6.0 beta 8') then
begin
CopyFileIfExists(PluginDllPath+Account_FileName+'.ini',PluginDllPath + 'Profiles\' + Account_FileName + '\config.ini');
CopyFileIfExists(PluginDllPath+'statistic_'+Account_FileName+'.ini',PluginDllPath + 'Profiles\' + Account_FileName + '\statistic.ini');
CopyFileIfExists(PluginDllPath+'stations.ftx',PluginDllPath + 'Profiles\' + Account_FileName + '\stations.ftx');
DeleteFileIfExists(PluginDllPath+Account_FileName+'.ini');
DeleteFileIfExists(PluginDllPath+'statistic_'+Account_FileName+'.ini');
DeleteFileIfExists(PluginDllPath+'stations.ftx');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\skin.ini');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\graph.dll');
RemoveFolderIfExists(PluginDllPath+'Skins\FMtune Big');
INIGetProfileConfig(INI2);
INI2.DeleteKey('Conf', 'ScrollText');
INIFree(INI2);
end;
if (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) < '0.6.0') then
begin
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\error.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\icon.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\pause.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\play.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\record.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune\stop.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\error.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\icon.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\pause.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\play.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\record.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\stop.ico');
DeleteFileIfExists(PluginDllPath+'Skins\FMtune Big\skin.ini');
RemoveFolderIfExists(PluginDllPath+'Skins\FMtune Big');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\error.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\icon.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\pause.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\play.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\record.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\record2.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\stop.ico');
DeleteFileIfExists(PluginDllPath+'Skins\iSimple\sound.ico');
DeleteFileIfExists(PluginDllPath+'icon.ico');
pom := '';
pom := pom + INIReadStringUTF8(INI, 'Equalizer', 'f70', '0');
INI.DeleteKey('Equalizer', 'f70');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f180', '0');
INI.DeleteKey('Equalizer', 'f180');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f320', '0');
INI.DeleteKey('Equalizer', 'f320');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f600', '0');
INI.DeleteKey('Equalizer', 'f600');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f1k', '0');
INI.DeleteKey('Equalizer', 'f1k');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f3k', '0');
INI.DeleteKey('Equalizer', 'f3k');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f6k', '0');
INI.DeleteKey('Equalizer', 'f6k');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f12k', '0');
INI.DeleteKey('Equalizer', 'f12k');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f14k', '0');
INI.DeleteKey('Equalizer', 'f14k');
pom := pom + ', ' + INIReadStringUTF8(INI, 'Equalizer', 'f16k', '0');
INI.DeleteKey('Equalizer', 'f16k');
INIWriteStringUTF8(INI, 'Equalizer', 'Values', pom);
INIWriteStringUTF8(INI, 'Conf', 'Skin', 'FMtune');
INI.DeleteKey('Conf', 'Language');
INI.EraseSection('Plugin');
if FindFirst(QIPInfiumPath + 'Profiles\*.*', faDirectory, Rec) = 0 then
begin
While FindNext(Rec) = 0 do
begin
if ExtractFileExt(Rec.Name) <> '' then
Rec.Name := '';
if Rec.Name = '' then
else if Rec.Name = '.' then
else if Rec.Name = '..' then
else
begin
{if not DirectoryExists(PluginDllPath + 'Profiles\'+Copy(Rec.Name, 1, Length(Rec.Name))) then
CreateDir(PluginDllPath + 'Profiles\'+Copy(Rec.Name, 1, Length(Rec.Name)));}
CheckFolder( PluginDllPath + 'Profiles\'+Copy(Rec.Name, 1, Length(Rec.Name)) , False );
CopyFileIfExists(PluginDllPath+'FMtune.ini',PluginDllPath + 'Profiles\' + Copy(Rec.Name, 1, Length(Rec.Name)) + '\config.ini');
CopyFileIfExists(PluginDllPath+'stations.ftx',PluginDllPath + 'Profiles\' + Copy(Rec.Name, 1, Length(Rec.Name)) + '\stations.ftx');
//showmessage ( PluginDllPath+ Copy(Rec.Name, 1, Length(Rec.Name)) + '.ini' ) ;
// AssignFile(S,{PChar(}PluginDllPath+ Copy(Rec.Name, 1, Length(Rec.Name)) + '.ini'{)});
// Reset(S);
// WriteLn(S,'; Code page: UTF-8');
// WriteLn(S);
// CloseFile(S);
end;
end;
end;
FindClose(Rec);
DeleteFileIfExists(PluginDllPath+'stations.ftx');
AssignFile(S,PluginDllPath + PLUGIN_NAME + '.ini');
Rewrite(S);
CloseFile(S);
end;
if (UTF82WideString(INIReadStringUTF8(INI, 'Plugin', 'Version', PluginVersion)) <= '0.6.3') then
begin
INI.EraseSection('Proxy');
INIGetProfileConfig(INI2);
if INIReadBool(INI2, 'Proxy', 'Enabled', false) = false then
INIWriteInteger(INI2, 'Proxy', 'Mode', 0)
else
INIWriteInteger(INI2, 'Proxy', 'Mode', 2);
INIDeleteKey(INI2, 'Proxy', 'Enabled');
INIFree(INI2);
end;
// --- převod aktuální profilu, převádí vždy pokud nebylo převedeno
if DirectoryExists( PluginDllPath + 'Profiles\' + Account_FileName ) = True then
begin
//presunout do noveho umisteni
MoveFileIfExists( PluginDllPath + 'Profiles\' + Account_FileName + '\config.ini', ProfilePath + 'config.ini' );
MoveFileIfExists( PluginDllPath + 'Profiles\' + Account_FileName + '\statistic.ini', ProfilePath + 'statistic.ini' );
MoveFileIfExists( PluginDllPath + 'Profiles\' + Account_FileName + '\stations.ftx', ProfilePath + 'stations.ftx' );
//odstrani starou slozku profilu
RemoveFolderIfExists( PluginDllPath + 'Profiles\' + Account_FileName );
//odstrani slozku starou Profiles (pouze pokud je prazdna)
RemoveFolderIfExists( PluginDllPath + 'Profiles' );
end;
end;
procedure TfrmQIPPlugin.tmrDrawTimer(Sender: TObject);
var bCntRedraw : Boolean;
Repl_XStatus : TReplXStatus;
begin
tmrDraw.Enabled := False;
bCntRedraw := False;
if SpecCntInfoTextScroll = True then
begin
Dec(SpecCntInfoTextX, 1);
if SpecCntInfoTextX = -SpecCntInfoTextWidth then
SpecCntInfoTextX := SpecCntInfoMaxWidth;
bCntRedraw := True;
end;
if SpecCntInfo2TextScroll = True then
begin
Dec(SpecCntInfo2TextX, 1);
if SpecCntInfo2TextX = -SpecCntInfo2TextWidth then
SpecCntInfo2TextX := SpecCntInfo2MaxWidth;
bCntRedraw := True;
end;
//showmessage( inttostr(Radio_StationID ) +#13 + inttostr(Radio_StreamID ) );
if (Stations.Count - 1 >= Radio_StationID) AND (Radio_StationID <> -1) then
begin
//if (Radio_StationID <> -1) AND (Radio_StreamID <> -1) then
if (TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID) AND (Radio_StreamID <> -1) then
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
end
end
else
begin
Repl_XStatus.Station := '';
Repl_XStatus.Genre := '';
Repl_XStatus.Format := '';
Repl_XStatus.Language := '';
Repl_XStatus.StationWeb := '';
end;
if ReplXStatus(SpecCntLine1Text,Repl_XStatus) <> SpecCntInfoText then
bCntRedraw := True;
if ReplXStatus(SpecCntLine2Text,Repl_XStatus) <> SpecCntInfo2Text then
bCntRedraw := True;
if bCntRedraw = True then
RedrawSpecContact(UniqContactId);
tmrDraw.Enabled := True;
end;
procedure TfrmQIPPlugin.tmrStartTimer(Sender: TObject);
var
hLibraryPics : THandle;
F : TextFile;
FName : WideString;
INI : TINIFile;
sXStatusTitle,sXStatusText, sPopupText, sL1Text, sL2Text: WideString;
PlugMsg1: TPluginMessage;
idx : Integer;
// iMod, iKey: Word;
// hIndex: Integer;
sColor: WideString;
NetParams : pNetParams;
begin
tmrStart.Enabled := False;
StatisticsRadioTime := 0; // nastavení přehrávání rádia na 0
(* //// Tato věc je prozatím k ničemu :D ale vypadá hezky :D
osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo) ;
if GetVersionEx(osVerInfo) then;
if osVerInfo.dwMajorVersion < 6 then
pmContactMenu.Images := ImageList1
else
pmContactMenu.Images := nil;
///////////////*)
(* // Tvorba složky profilů, pokud neexistují
if not DirectoryExists(PluginDllPath + 'Profiles') then
begin
CreateDir(PluginDllPath + 'Profiles');
end;
if not DirectoryExists(PluginDllPath + 'Profiles\'+Account_FileName) then
begin
CreateDir(PluginDllPath + 'Profiles\'+Account_FileName);
end;
// ---*)
INI := TiniFile.Create(PluginDllPath + PLUGIN_NAME + '.ini');
// Převod starého nastavení uživatelů pro novou verzi
OldSetToNewPlugin(INI);
INIWriteStringUTF8(INI, 'Plugin', 'Version', PluginVersion);
INIWriteStringUTF8(INI, 'SDK', 'Version', IntToStr(QIP_SDK_VER_MAJOR) + '.' + IntToStr(QIP_SDK_VER_MINOR));
//// Načtení barev
sColor := INIReadStringUTF8(INI, 'Colors', '1', 'F0F0F0'); //frmBgColor = $00F0F0F0;//$00FFEEDD;
frmBgColor := RGB( StrToInt('$' + Copy(sColor,1,2)),
StrToInt('$' + Copy(sColor,3,2)),
StrToInt('$' + Copy(sColor,5,2)));
INIWriteStringUTF8(INI, 'Colors', '1', sColor);
INIFree(INI);
INIGetProfileConfig(INI);
PluginLanguage := INIReadStringUTF8(INI, 'Conf', 'Language', '<default>');
CheckUpdates := INIReadBool(INI, 'Conf', 'CheckUpdates', True );
CheckUpdatesInterval := INIReadInteger(INI, 'Conf', 'CheckUpdatesInterval', 6);
CheckBetaUpdates := INIReadBool(INI, 'Conf', 'CheckBetaUpdates', False );
// pokud je plugin v testovací fázi, jsou zapnuty beta aktualizace
if Trim(PLUGIN_VER_BETA) <> '' then
begin
CheckBetaUpdates := True;
end;
PluginTheme.Name := INIReadStringUTF8(INI, 'Conf', 'Skin', 'FMtune');
OpenTheme;
sNStationID := INIReadStringUTF8(INI, 'Conf', 'StationID', '');
Radio_StreamID := INIReadInteger(INI, 'Conf', 'StreamID', 0);
UseQIPMute := INIReadBool(INI, 'Conf', 'UseQIPMute', false );
ShowComments := INIReadBool(INI, 'Conf', 'ShowComments', true);
LoadSongsExternal := INIReadBool(INI, 'Conf', 'LoadSongsExternal', true);
ShowCover := INIReadBool(INI, 'Conf', 'ShowCover', true);
SaveCover := INIReadBool(INI, 'Conf', 'SaveCover', false);
PlayOnStart := INIReadBool(INI, 'Conf', 'PlayOnStart', false);
Player_Volume := INIReadInteger(INI, 'Conf', 'Volume', 50);
SetChangeVolume;
SaveLastStream := INIReadBool(INI, 'Conf', 'SaveLastStream', false);
HotKeyEnabled := INIReadBool(INI, 'Conf', 'HotKey', false);
HotKeyFMtune := INIReadInteger(INI, 'Conf', 'HotKeyFMtune', 49222) ;
HotKeyVolumeUp := INIReadInteger(INI, 'Conf', 'HotKeyVolumeUp', 49342) ;
HotKeyVolumeDown := INIReadInteger(INI, 'Conf', 'HotKeyVolumeDown', 49340) ;
HotKeyMute := INIReadInteger(INI, 'Conf', 'HotKeyMute', 49240) ;
HotKeyStationNext := INIReadInteger(INI, 'Conf', 'HotKeyStationNext', 49228) ;
HotKeyStationPrev := INIReadInteger(INI, 'Conf', 'HotKeyStationPrev', 49227) ;
HotKeyEnableDisableXStatus := INIReadInteger(INI, 'Conf', 'HotKeyEnableDisableXStatus', 49235);
XStatus_Boolean := INIReadBool(INI, 'XStatus', 'Enabled', false) ;
XStatus_Type := INIReadInteger(INI, 'XStatus', 'Type', 2) ;
sXStatusTitle:= LNG('DEFAULT', 'XStatus.Title', 'I am listening to radio');
sXStatusText := LNG('DEFAULT', 'XStatus.Text', '%station%');
XStatus_Title := INIReadStringUTF8(INI, 'XStatus', 'Title', sXStatusTitle);
XStatus_Text := INIReadStringUTF8(INI, 'XStatus', 'Text', sXStatusText );
ShowPopups := INIReadBool(INI, 'Popup', 'Enabled', false);
PopupType := INIReadInteger(INI, 'Popup', 'Type', 2) ;
sPopupText := LNG('DEFAULT', 'PopUp.Text', '%station%');
PopupText := INIReadStringUTF8(INI, 'Popup', 'Text', sPopupText);
ShowPopUpIfChangeInfo := INIReadBool(INI, 'Popup', 'ShowPopUpIfChangeInfo', false);
EqualizerEnabled := INIReadBool(INI, 'Equalizer', 'Enabled', false);
LoadEqualizerSettings;
Proxy_Mode := INIReadInteger(INI, 'Proxy', 'Mode', 0);
case Proxy_Mode of
0: ;
1: begin
PlugMsg1.Msg := PM_PLUGIN_GET_NET_SET;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
if Boolean(PlugMsg1.Result) then
begin
NetParams := pNetParams(PWideChar(PlugMsg1.WParam)); // Získání parametrů o připojení
case NetParams.ConType of
0: ; // přímé spojení
1, // automatické nastavení
2: begin // ruční nastavení
Proxy_Server := '[' + NetParams.PrxUser + ':' +
NetParams.PrxPass + ']@' +
NetParams.PrxHost + ':' +
IntToStr( NetParams.PrxPort ) ;
end;
end;
end
else
ShowMessage('Proxy wasn''t configured');
end;
2: Proxy_Server := INIReadStringUTF8(INI, 'Proxy', 'Server', '');
end;
AutoUseWherePlaying := INIReadBool(INI, 'Conf', 'AutoOnOffUseWherePlaying', true );
AutoStatusFFC := INIReadInteger(INI, 'Conf', 'AutoOnOffFFC', 0 );
AutoStatusEvil := INIReadInteger(INI, 'Conf', 'AutoOnOffEvil', 0 );
AutoStatusDepres := INIReadInteger(INI, 'Conf', 'AutoOnOffDepres', 0 );
AutoStatusAtHome := INIReadInteger(INI, 'Conf', 'AutoOnOffAtHome', 0 );
AutoStatusAtWork := INIReadInteger(INI, 'Conf', 'AutoOnOffAtWork', 0 );
AutoStatusLunch := INIReadInteger(INI, 'Conf', 'AutoOnOffLunch', 0 );
AutoStatusAway := INIReadInteger(INI, 'Conf', 'AutoOnOffAway', 0 );
AutoStatusNA := INIReadInteger(INI, 'Conf', 'AutoOnOffNA', 0 );
AutoStatusOccupied := INIReadInteger(INI, 'Conf', 'AutoOnOffOccupied', 0 );
AutoStatusDND := INIReadInteger(INI, 'Conf', 'AutoOnOffDND', 0 );
AutoStatusOnline := INIReadInteger(INI, 'Conf', 'AutoOnOffOnline', 0 );
AutoStatusInvisible := INIReadInteger(INI, 'Conf', 'AutoOnOffInvisible', 0 );
AutoStatusOffline := INIReadInteger(INI, 'Conf', 'AutoOnOffOffline', 0 );
sL1Text := WideString2UTF8( LNG('DEFAULT', 'SpecCnt.Line1', '%station%') );
sL2Text := WideString2UTF8( LNG('DEFAULT', 'SpecCnt.Line2', '%song%') );
SpecCntShowLine2 := INIReadBool(INI, 'SpecCnt', 'ShowLine2', false );
SpecCntLine1Text := INIReadStringUTF8(INI, 'SpecCnt', 'L1Text', sL1Text);
SpecCntLine2Text := INIReadStringUTF8(INI, 'SpecCnt', 'L2Text', sL2Text );
SpecCntLine1ScrollText := INIReadBool(INI, 'SpecCnt', 'L1ScrollText', true );
SpecCntLine2ScrollText := INIReadBool(INI, 'SpecCnt', 'L2ScrollText', false );
INIFree(INI);
Pics := PluginDllPath + 'pics.dll';
hLibraryPics := LoadLibrary(PChar(Pics));
if hLibraryPics=0 then
begin
ShowMessage( TagsReplace( StringReplace(LNG('Texts', 'LibraryNotLoad', 'Can''t load library %file%.[br]Plugin can be unstable.'), '%file%', 'pics.dll', [rfReplaceAll, rfIgnoreCase]) ) );
Exit;
end;
PluginSkin.PluginIconBig := LoadImageFromResource(10, hLibraryPics);
PluginSkin.PluginIcon.Image := LoadImageFromResource(11, hLibraryPics);
PluginSkin.PluginIcon.Icon := LoadImageAsIconFromResource(11, hLibraryPics);
PluginSkin.Options.Image := LoadImageFromResource(12, hLibraryPics);
PluginSkin.Options.Icon := LoadImageAsIconFromResource(12, hLibraryPics);
PluginSkin.Volume.Image := LoadImageFromResource(13, hLibraryPics);
PluginSkin.Volume.Icon := LoadImageAsIconFromResource(13, hLibraryPics);
PluginSkin.Equalizer.Image := LoadImageFromResource(14, hLibraryPics);
PluginSkin.Equalizer.Icon := LoadImageAsIconFromResource(14, hLibraryPics);
PluginSkin.Info.Image := LoadImageFromResource(15, hLibraryPics);
PluginSkin.Info.Icon := LoadImageAsIconFromResource(15, hLibraryPics);
PluginSkin.Recording.Image := LoadImageFromResource(16, hLibraryPics);
PluginSkin.Recording.Icon := LoadImageAsIconFromResource(16, hLibraryPics);
PluginSkin.Stations.Image := LoadImageFromResource(17, hLibraryPics);
PluginSkin.Stations.Icon := LoadImageAsIconFromResource(17, hLibraryPics);
PluginSkin.Formats.Image := LoadImageFromResource(18, hLibraryPics);
PluginSkin.Formats.Icon := LoadImageAsIconFromResource(18, hLibraryPics);
PluginSkin.EditStations.Image := LoadImageFromResource(19, hLibraryPics);
PluginSkin.EditStations.Icon := LoadImageAsIconFromResource(19, hLibraryPics);
PluginSkin.FastAddStation.Image := LoadImageFromResource(20, hLibraryPics);
PluginSkin.FastAddStation.Icon := LoadImageAsIconFromResource(20, hLibraryPics);
PluginSkin.Copy.Image := LoadImageFromResource(21, hLibraryPics);
PluginSkin.Copy.Icon := LoadImageAsIconFromResource(21, hLibraryPics);
PluginSkin.ItemAdd.Image := LoadImageFromResource(22, hLibraryPics);
PluginSkin.ItemRemove.Image := LoadImageFromResource(23, hLibraryPics);
PluginSkin.ItemUp.Image := LoadImageFromResource(24, hLibraryPics);
PluginSkin.ItemDown.Image := LoadImageFromResource(25, hLibraryPics);
PluginSkin.ST_online.Image := LoadImageFromResource(26, hLibraryPics);
PluginSkin.ST_online.Icon := LoadImageAsIconFromResource(26, hLibraryPics);
PluginSkin.ST_ffc.Image := LoadImageFromResource(27, hLibraryPics);
PluginSkin.ST_ffc.Icon := LoadImageAsIconFromResource(27, hLibraryPics);
PluginSkin.ST_away.Image := LoadImageFromResource(28, hLibraryPics);
PluginSkin.ST_away.Icon := LoadImageAsIconFromResource(28, hLibraryPics);
PluginSkin.ST_na.Image := LoadImageFromResource(29, hLibraryPics);
PluginSkin.ST_na.Icon := LoadImageAsIconFromResource(29, hLibraryPics);
PluginSkin.ST_occ.Image := LoadImageFromResource(30, hLibraryPics);
PluginSkin.ST_occ.Icon := LoadImageAsIconFromResource(30, hLibraryPics);
PluginSkin.ST_dnd.Image := LoadImageFromResource(31, hLibraryPics);
PluginSkin.ST_dnd.Icon := LoadImageAsIconFromResource(31, hLibraryPics);
PluginSkin.ST_invisible.Image := LoadImageFromResource(32, hLibraryPics);
PluginSkin.ST_invisible.Icon := LoadImageAsIconFromResource(32, hLibraryPics);
PluginSkin.ST_lunch.Image := LoadImageFromResource(33, hLibraryPics);
PluginSkin.ST_lunch.Icon := LoadImageAsIconFromResource(33, hLibraryPics);
PluginSkin.ST_depression.Image := LoadImageFromResource(34, hLibraryPics);
PluginSkin.ST_depression.Icon := LoadImageAsIconFromResource(34, hLibraryPics);
PluginSkin.ST_evil.Image := LoadImageFromResource(35, hLibraryPics);
PluginSkin.ST_evil.Icon := LoadImageAsIconFromResource(35, hLibraryPics);
PluginSkin.ST_at_home.Image := LoadImageFromResource(36, hLibraryPics);
PluginSkin.ST_at_home.Icon := LoadImageAsIconFromResource(36, hLibraryPics);
PluginSkin.ST_at_work.Image := LoadImageFromResource(37, hLibraryPics);
PluginSkin.ST_at_work.Icon := LoadImageAsIconFromResource(37, hLibraryPics);
PluginSkin.ST_offline.Image := LoadImageFromResource(38, hLibraryPics);
PluginSkin.ST_offline.Icon := LoadImageAsIconFromResource(38, hLibraryPics);
PluginSkin.Mute.Icon := LoadImageAsIconFromResource(39, hLibraryPics);
PluginSkin.Unmute.Icon := LoadImageAsIconFromResource(40, hLibraryPics);
PluginSkin.Export.Icon := LoadImageAsIconFromResource(41, hLibraryPics);
PluginSkin.Import.Icon := LoadImageAsIconFromResource(42, hLibraryPics);
PluginSkin.CheckMenuItem := LoadImageAsIconFromResource(43, hLibraryPics);
PluginSkin.Update.Icon := LoadImageAsIconFromResource(44, hLibraryPics);
PluginSkin.Comment.Image := LoadImageFromResource(45, hLibraryPics);
PluginSkin.Comment.Icon := LoadImageAsIconFromResource(45, hLibraryPics);
PluginSkin.Folder.Image := LoadImageFromResource(46, hLibraryPics);
PluginSkin.Folder.Icon := LoadImageAsIconFromResource(46, hLibraryPics);
PluginSkin.Favourite.Image := LoadImageFromResource(47, hLibraryPics);
PluginSkin.Favourite.Icon := LoadImageAsIconFromResource(47, hLibraryPics);
FreeLibrary(hLibraryPics);
AddIconToStringList(PluginSkin.MenuIcons, PluginTheme.State.PictureStop.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Stations.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Formats.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Info.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Equalizer.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Recording.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Volume.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.EditStations.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.FastAddStation.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Options.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Folder.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Favourite.Icon);
AddIconToStringList(PluginSkin.MenuIcons, PluginSkin.Copy.Icon);
GetEqualizerPreset;
GetLangs;
LoadStations(Stations,'');
showmessage(inttostr(Stations.count));
GetStatistics;
idx:=0;
while ( idx <= Stations.Count - 1 ) do
begin
Application.ProcessMessages;
if TStation(Stations.Objects[idx]).Name = sNStationID then
begin
Radio_StationID := idx;
break;
end;
Inc(idx);
end;
if HotKeyEnabled = True then
begin
HotKeysActivate;
end;
QIPPlugin.AddSpecContact( UniqContactId, SpecCntHeight );
{=== Sound switch on/off test ===================================}
{getting sound option enabled/disbaled}
PlugMsg1.Msg := PM_PLUGIN_SOUND_GET;
{when plugin sending msg to qip core it have to add self dllhandle, else your msg will be ignored}
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
{if sound enabled then disabling it}
if Boolean(PlugMsg1.WParam) then
QIPSound := True
else
QIPSound := False;
if UseQIPMute = True then
begin
Player_Mute := not QIPSound;
SetChangeVolume;
end;
{================================================================}
UpdaterWebIndex := -1;
UpdaterWeb := TStringList.Create;
UpdaterWeb.Clear;
UpdaterWeb.Add('http://lmscze7.ic.cz/');
UpdaterWeb.Add('http://lmscze7.wz.cz/');
NextCheckVersion := Now + ( 5 * (1/(24*60*60) ) );
tmrStep.Enabled := True;
tmrDraw.Enabled := True;
if PlayOnStart = True then
begin
FBassPlayer.PlayStopRadio;
end;
end;
procedure TfrmQIPPlugin.tmrStepTimer(Sender: TObject);
var
fmFadeMsg : TFadeMsg;
fmcFadeMsgClosing: TFadeMsgClosing;
i : Integer;
fid: DWord;
PlugMsg1, RepMsg : TPluginMessage;
Repl_XStatus: TReplXStatus;
sText : WideString;
QipColors : pQipColors;
begin
PlugMsg1.Msg := PM_PLUGIN_GET_COLORS_FONT;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
//get results
{ wFontName := PWideChar(PlugMsg1.WParam);
iFontSize := PlugMsg1.LParam;}
QipColors := pQipColors(PlugMsg1.NParam);
QIP_Colors := QipColors^;
//--- Počítání doby hraní písničky/rádia
if Radio_Playing then
begin
iTime := iTime + tmrStep.Interval/1000;
if (iTime > 10) and (iRadio = LNG('PLAYER', 'Connecting', 'Connecting...')) then
begin
iRadio := LNG('PLAYER', 'NotInformation', 'Information not available');
end;
end;
if iTime > 359999 then // 99:59:59 - hh:mm:ss
iTime := 0;
//---
// Statistika - doba hraní
if Radio_Playing then
begin
StatisticsRadioTime := StatisticsRadioTime + tmrStep.Interval/1000;
if StatisticsRadioTime > 11 then // aktualizuj dobu přehrávání rádia (každých 11 sekund, klidně bych tam dal i každou sekundu, ale nevim jak je to se zátěží PC)
begin
if (Radio_StationID <> -1) and (Radio_StreamID <> -1) then
begin
Statistics_PlayTime_Add( TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL, StatisticsRadioTime );
end;
end;
end;
if FadeMsgsClosing.Count > 0 then
begin
i:=0;
while ( i<= FadeMsgsClosing.Count - 1 ) do
begin
Application.ProcessMessages;
Dec(TFadeMsgClosing(FadeMsgsClosing.Objects[i]).Time);
if TFadeMsgClosing(FadeMsgsClosing.Objects[i]).Time <= 0 then
begin
PlugMsg1.Msg := PM_PLUGIN_FADE_CLOSE;
PlugMsg1.WParam := TFadeMsgClosing(FadeMsgsClosing.Objects[i]).FadeID;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
FadeMsgsClosing.Delete(i);
Dec(i);
end;
Inc(i);
end;
end;
if FadeMsgs.Count > 0 then
begin
fmFadeMsg := TFadeMsg(FadeMsgs.Objects[0]);
FadeMsgs.Delete(0);
if fmFadeMsg.CloseTime <> 0 then
fmFadeMsg.NoAutoClose := True;
fid := FadeMsg(fmFadeMsg.FadeType,
fmFadeMsg.FadeIcon,
fmFadeMsg.FadeTitle,
fmFadeMsg.FadeText,
fmFadeMsg.TextCentered,
fmFadeMsg.NoAutoClose,
fmFadeMsg.pData
);
if fmFadeMsg.CloseTime <> 0 then
begin
fmcFadeMsgClosing := TFadeMsgClosing.Create;
fmcFadeMsgClosing.FadeID := fid;
fmcFadeMsgClosing.Time := fmFadeMsg.CloseTime * 2;
FadeMsgsClosing.Add('FADEMSG');
FadeMsgsClosing.Objects[FadeMsgsClosing.Count - 1] := fmcFadeMsgClosing.Create;
end;
if fmFadeMsg.pData=255 then
Updater_NewVersionFadeID := fid;
end;
if Stations.Count - 1 < Radio_StationID then
begin
Radio_StationID := 0;
if Radio_Playing=True then FBassPlayer.PlayStopRadio;
end
else
begin
if Radio_StationID <> -1 then
begin
if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 < Radio_StreamID then
begin
Radio_StreamID := 0;
if Radio_Playing=True then FBassPlayer.PlayStopRadio;
end;
end;
end;
if ExtraTextTime<>0 then
begin
ExtraTextTime := ExtraTextTime - 1;
if ExtraTextTime = 0 then
begin
// SpecCntInfoTextX := 0;
// SpecCntInfoTextScroll := False;
// SpecCntInfo2TextX := 0;
// SpecCntInfo2TextScroll := False;
RedrawSpecContact(UniqContactId);
end;
end;
// ---- Check new version ----
CheckNewVersion(False);
if ShowPopups = True then
begin
if Radio_Playing = True then
begin
if Stations.Count - 1 >= Radio_StationID then
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID then
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
end;
if PopupType = 1 then
sText := ReplXStatus(XStatus_Text,Repl_XStatus)
else if PopupType = 2 then
sText := ReplXStatus(PopupText,Repl_XStatus);
if (LastRadioFadeMsg <> sText) and (sText <> ' ') then
begin
QIPPlugin.AddFadeMsg(1, PluginSkin.PluginIcon.Icon.Handle, PLUGIN_NAME, sText, True, False, 0, 0);
end;
LastRadioFadeMsg := sText;
end;
end;
if RemoveXstatus = True then
begin
RemoveXstatus := False;
FwStatus := LastXStatusText ;
FwDescription := LastXStatusDescription;
RepMsg.Msg := PM_PLUGIN_XSTATUS_UPD;
RepMsg.WParam := LastXStatusNumber;
RepMsg.LParam := LongInt(PWideChar(FwStatus));
RepMsg.NParam := LongInt(PWideChar(FwDescription));
RepMsg.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(RepMsg);
end;
//XStatus - musí být nakonci tmrStep
if ChangeXstatusPos = 1 then
begin
//Zrusit XStatus
RepMsg.WParam := 0;
FwStatus := '';
FwDescription := '';
RepMsg.Msg := PM_PLUGIN_XSTATUS_UPD;
RepMsg.LParam := LongInt(PWideChar(FwStatus));
RepMsg.NParam := LongInt(PWideChar(FwDescription));
RepMsg.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(RepMsg);
Inc(ChangeXstatusPos);
Exit;
end;
if XStatus_Boolean = True then
begin
if ChangeXstatus=True then
begin
if (ActXstatusNum=11) or (XStatus_Type = 2) then
begin
Inc(ChangeXstatusPos);
if ChangeXstatusPos = 1 then //Odstraneni XStatusu
Exit;
if ChangeXstatusPos < 2 then // Cekani na nastaveni XStatusu
Exit;
if Radio_Playing=True then
begin
//FwStatus and FwDescription have to be class members or global variables to stay in memory because we return PWideChar
if Stations.Count - 1 >= Radio_StationID then
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID then
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
end;
FwStatus := ReplXStatus(XStatus_Title,Repl_XStatus);// 'Listenig radio:'; //max xstatus text length = 20 chars
if Stations.Count - 1 < Radio_StationID then
FwDescription := '' //max description text length = 512 chars
else
FwDescription := ReplXStatus(XStatus_Text,Repl_XStatus); //TSLStation(Stations.Objects[Radio_StationID]).Name; //max description text length = 512 chars
end
else
begin
FwStatus := LastXStatusText ; {''; } //max xstatus text length = 20 chars
FwDescription := LastXStatusDescription; {'';} //max description text length = 512 chars
end;
{Plugin msg to update xstatus}
RepMsg.Msg := PM_PLUGIN_XSTATUS_UPD;
{ WParam is number of xstatus picture in Core/Xstatuses/xstatuses.ini, if 0 then xstatus pic will be removed}
{When changing music track you can change xstatus picture number, it will cauz all clients to request your new
xstatus value, but better to make it optional, because it can be bothering for remote users}
if (Radio_Playing=False) And (XStatus_Type = 2) then
RepMsg.WParam := LastXStatusNumber { 0 }// Xstatus - not
else
RepMsg.WParam := 11; // Xstatus - Music
RepMsg.LParam := LongInt(PWideChar(FwStatus));
RepMsg.NParam := LongInt(PWideChar(FwDescription));
{when plugin sending msg to qip core it have to add self dllhandle, else your msg will be ignored}
RepMsg.DllHandle := DllHandle;
{send message to qip core. !!! Dont change xtatus too often, it can cauz disconnect}
FPluginSvc.OnPluginMessage(RepMsg);
{================================================================}
ChangeXstatusPos := 0;
end;
end;
ChangeXstatus:=False;
end;
end;
////////////////////////////////////////////////////////////////////////////////
{procedure TfrmQIPPlugin.SpellCheck(var PlugMsg: TPluginMessage);
begin
//
end;}
{******************************************************************************}
{procedure TfrmQIPPlugin.SpellPopup(var PlugMsg: TPluginMessage);
begin
//
end;}
{******************************************************************************}
procedure TfrmQIPPlugin.QipSoundChanged(PlugMsg: TPluginMessage);
begin
if Boolean(PlugMsg.WParam) then
QIPSound := True
else
QIPSound := False;
if UseQIPMute = True then
begin
Player_Mute := not QIPSound;
SetChangeVolume;
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.AntiBoss(HideForms: Boolean);
begin
if HideForms then
/// AntiBoss: activated
else
/// AntiBoss: deactivated
end;
{******************************************************************************}
procedure TfrmQIPPlugin.CurrentLanguage(LangName: WideString);
var
INI : TINIFile;
begin
// ShowMessage(LangName);
QIPInfiumLanguage := LangName;
INI := TiniFile.Create(PluginDllPath + PLUGIN_NAME + '.ini');
INIWriteStringUTF8(INI, 'Language', 'QIP', QIPInfiumLanguage );
INIFree(INI);
end;
procedure TfrmQIPPlugin.ddrrr(Sender: TObject; ACanvas: TCanvas; ARect: TRect;
Selected: Boolean);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.DrawSpecContact(PlugMsg: TPluginMessage);
var ContactId : DWord;
//Data : Pointer;
Cnv : TCanvas;
R : PRect;
wStr : WideString;
R1, R2, RCalc : TRect;
RRight, RBottom, RRight2, RBottom2, iAlign, iLeft : Integer;
RLeft, RTop : Integer;
Repl_XStatus : TReplXStatus;
Params: TDrawTextParams;
begin
//get unique contact id from msg
ContactId := PlugMsg.WParam;
//actually all incoming ContactIDs will be only of your plugin, but here i made condition just for example
// if (ContactId <> FfrmTest.UniqContactId) then Exit;
//get your Data pointer which you added when sent PM_PLUGIN_SPEC_ADD_CNT.
//IMPORTANT!!! Do NOT make here any heavy loading actions, like cycles FOR, WHILE etc.
//That's why you have to add Data pointer to PM_PLUGIN_SPEC_ADD_CNT, to get quick access to your data.
//Data not used here in this example because plugin added only one contact
//Data := Pointer(PlugMsg.LParam);
//create temporary canvas to draw the contact
Cnv := TCanvas.Create;
try
//get canvas handle from msg
Cnv.Handle := PlugMsg.NParam;
//get drawing rectangle pointer from msg
R := PRect(PlugMsg.Result);
//this needed to draw text over contact list backgroud
SetBkMode(Cnv.Handle, TRANSPARENT);
if ExtraTextTime <> 0 then
begin
if SpecCntShowLine2 then
SpecCntInfo2Text := ExtraText
else
SpecCntInfoText := ExtraText;
end
else
begin
if (Stations.Count - 1 < Radio_StationID) AND (Radio_StationID <> -1) then
SpecCntInfoText := ''
else
begin
Repl_XStatus.Station := TStation(Stations.Objects[Radio_StationID]).Name;
Repl_XStatus.Genre := TStation(Stations.Objects[Radio_StationID]).Genre;
if (TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID) AND (Radio_StreamID <> -1) then
Repl_XStatus.Format := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).Format;
Repl_XStatus.Language := TStation(Stations.Objects[Radio_StationID]).Language;
Repl_XStatus.StationWeb := TStation(Stations.Objects[Radio_StationID]).URL;
SpecCntInfoText := ReplXStatus(SpecCntLine1Text,Repl_XStatus);
SpecCntInfo2Text := ReplXStatus(SpecCntLine2Text,Repl_XStatus);
end;
end;
if SpecCntLine1TextLast <> SpecCntInfoText then
begin
SpecCntInfoTextX := 0;
SpecCntInfoTextScroll := False;
end;
if SpecCntLine2TextLast <> SpecCntInfo2Text then
begin
SpecCntInfo2TextX := 0;
SpecCntInfo2TextScroll := False;
end;
SpecCntLine1TextLast := SpecCntInfoText;
SpecCntLine2TextLast := SpecCntInfo2Text;
if PluginTheme.Info.Right > 0 then
RRight := R^.Right - PluginTheme.Info.Right
else
RRight := R^.Right + PluginTheme.Info.Right;
if StreamRecording then
RRight := RRight - 16;
if PluginTheme.Info.Bottom > 0 then
RBottom := R^.Bottom - PluginTheme.Info.Bottom
else
RBottom := R^.Bottom + PluginTheme.Info.Bottom;
if PluginTheme.Info2.Right > 0 then
RRight2 := R^.Right - PluginTheme.Info2.Right
else
RRight2 := R^.Right + PluginTheme.Info2.Right;
if PluginTheme.Info2.Bottom > 0 then
RBottom2 := R^.Bottom - PluginTheme.Info2.Bottom
else
RBottom2 := R^.Bottom + PluginTheme.Info2.Bottom;
// === Info 1 ===
Cnv.Font.Name := PluginTheme.Info.Font.Name;
Cnv.Font.Color := TextToColor( PluginTheme.Info.Font.Color, QIP_Colors );
Cnv.Font.Size := PluginTheme.Info.Font.Size;
Cnv.Font.Style := PluginTheme.Info.Font.Style;
if SpecCntLine1ScrollText = True then
begin
if PluginTheme.Title.Show then
iLeft := PluginTheme.Info.Left
else
iLeft := PluginTheme.Title.Left;
SpecCntInfoMaxWidth := RRight - (iLeft + R^.Left);
RCalc.Left := 0;
RCalc.Top := 0;
DrawTextW(Cnv.Handle, PWideChar(SpecCntInfoText), Length(SpecCntInfoText), RCalc, PluginTheme.Info.TextAlign + DT_CALCRECT + DT_NOPREFIX + DT_SINGLELINE);
SpecCntInfoTextWidth := RCalc.Right - RCalc.Left;
if SpecCntInfoTextWidth > SpecCntInfoMaxWidth then
begin
SpecCntInfoTextScroll := True;
iAlign := 0;
end
else
begin
SpecCntInfoTextX := 0;
SpecCntInfoTextScroll := False;
iAlign := PluginTheme.Info.TextAlign;
end;
Params.cbSize := SizeOf(Params);
Params.iLeftMargin := SpecCntInfoTextX;
Params.iRightMargin := 0;
Params.uiLengthDrawn := Length(SpecCntInfoText);
R1 := Rect(R^.Left + iLeft, R^.Top + PluginTheme.Info.Top, RRight, RBottom);
DrawTextExW(Cnv.Handle, PWideChar(SpecCntInfoText), Length(SpecCntInfoText), R1, iAlign + DT_NOPREFIX + DT_SINGLELINE, @Params);
end
else
begin
if PluginTheme.Title.Show then
iLeft := PluginTheme.Info.Left
else
iLeft := PluginTheme.Title.Left;
R1 := Rect(R^.Left + iLeft, R^.Top + PluginTheme.Info.Top, RRight, RBottom);
DrawTextW(Cnv.Handle, PWideChar(SpecCntInfoText), Length(SpecCntInfoText)+1, R1, PluginTheme.Info.TextAlign + DT_NOPREFIX + DT_SINGLELINE);
end;
// === Info 2 ===
Cnv.Font.Name := PluginTheme.Info2.Font.Name;
Cnv.Font.Color := TextToColor( PluginTheme.Info2.Font.Color, QIP_Colors );
Cnv.Font.Size := PluginTheme.Info2.Font.Size;
Cnv.Font.Style := PluginTheme.Info2.Font.Style;
if (SpecCntLine2ScrollText = True) and (SpecCntShowLine2 = True) then
begin
SpecCntInfo2MaxWidth := RRight2 - (PluginTheme.Info2.Left + R^.Left);
RCalc.Left := 0;
RCalc.Top := 0;
DrawTextW(Cnv.Handle, PWideChar(SpecCntInfo2Text), Length(SpecCntInfo2Text), RCalc, PluginTheme.Info2.TextAlign + DT_CALCRECT + DT_NOPREFIX + DT_SINGLELINE);
SpecCntInfo2TextWidth := RCalc.Right - RCalc.Left + 1;
if SpecCntInfo2TextWidth > SpecCntInfo2MaxWidth then
begin
SpecCntInfo2TextScroll := True;
iAlign := 0;
end
else
begin
SpecCntInfo2TextX := 0;
SpecCntInfo2TextScroll := False;
iAlign := PluginTheme.Info2.TextAlign;
end;
Params.cbSize := SizeOf(Params);
Params.iLeftMargin := SpecCntInfo2TextX;
Params.iRightMargin := 0;
Params.uiLengthDrawn := Length(SpecCntInfo2Text);
R1 := Rect(R^.Left + PluginTheme.Info2.Left, R^.Top + PluginTheme.Info2.Top, RRight2, RBottom2);
DrawTextExW(Cnv.Handle, PWideChar(SpecCntInfo2Text), Length(SpecCntInfo2Text), R1, iAlign + DT_NOPREFIX + DT_SINGLELINE, @Params);
end
else
begin
R1 := Rect(R^.Left + PluginTheme.Info2.Left, R^.Top + PluginTheme.Info2.Top, RRight2, RBottom2);
DrawTextW(Cnv.Handle, PWideChar(SpecCntInfo2Text), Length(SpecCntInfo2Text), R1, PluginTheme.Info2.TextAlign + DT_NOPREFIX + DT_SINGLELINE);
end;
///////////////
DrawIconEx(Cnv.Handle, PluginTheme.Icon.Left, PluginTheme.Icon.Top, PluginTheme.Icon.Picture.Handle,16, 16, 0, 0, DI_NORMAL);
if PluginTheme.State.First.Right > 0 then
RLeft := R^.Right - PluginTheme.State.First.Right
else
RLeft := -PluginTheme.State.First.Right;
if PluginTheme.State.First.Top <=0 then
RTop := R^.Bottom + PluginTheme.State.First.Top
else
RTop := PluginTheme.State.First.Top;
if Radio_Playing=True then
DrawIconEx(Cnv.Handle, RLeft, RTop, PluginTheme.State.PicturePlay.Icon.Handle, 16, 16, 0, 0, DI_NORMAL)
else
DrawIconEx(Cnv.Handle, RLeft, RTop, PluginTheme.State.PictureStop.Icon.Handle, 16, 16, 0, 0, DI_NORMAL);
if Radio_PlayingError = true then
DrawIconEx(Cnv.Handle, RLeft, RTop, PluginTheme.State.PictureError.Icon.Handle, 16, 16, 0, 0, DI_NORMAL);
if StreamRecording=True then
begin
if PluginTheme.State.Second.Right > 0 then
RLeft := R^.Right - PluginTheme.State.Second.Right
else
RLeft := -PluginTheme.State.Second.Right;
if PluginTheme.State.Second.Top <= 0 then
RTop := R^.Bottom + PluginTheme.State.Second.Top
else
RTop := PluginTheme.State.Second.Top;
DrawIconEx(Cnv.Handle, RLeft, RTop, PluginTheme.State.PictureRecord.Icon.Handle, 16, 16, 0, 0, DI_NORMAL);
end;
wStr := 'FMtune';
//== Font ==
Cnv.Font.Name := PluginTheme.Title.Font.Name;
Cnv.Font.Color := TextToColor( PluginTheme.Title.Font.Color, QIP_Colors);
Cnv.Font.Size := PluginTheme.Title.Font.Size;
Cnv.Font.Style := PluginTheme.Title.Font.Style;
if PluginTheme.Title.Right > 0 then
RRight := R^.Right - PluginTheme.Title.Right
else
RRight := R^.Right + PluginTheme.Title.Right;
if PluginTheme.Title.Bottom > 0 then
RBottom := R^.Bottom - PluginTheme.Title.Bottom
else
RBottom := R^.Bottom + PluginTheme.Title.Bottom;
if PluginTheme.Title.Show then
begin
R1 := Rect(R^.Left + PluginTheme.Title.Left, R^.Top + PluginTheme.Title.Top, RRight, RBottom);
DrawTextW(Cnv.Handle, PWideChar(wStr), Length(wStr), R1, PluginTheme.Title.TextAlign + DT_NOPREFIX + DT_SINGLELINE);
end;
finally
//free canvas
Cnv.Free;
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.SpecContactDblClick(PlugMsg: TPluginMessage);
var ContactId : DWord;
begin
ContactId := PlugMsg.WParam;
FBassPlayer.PlayStopRadio;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.SpecContactRightClick(PlugMsg: TPluginMessage);
var ContactId : DWord;
//Data : Pointer;
Pt : PPoint;
begin
//get right clicked contact id from msg
ContactId := PlugMsg.WParam;
//get data pointer if added
//Data := Pointer(PlugMsg.LParam);
//get popup screen coordinates
Pt := PPoint(PlugMsg.NParam);
QIPPlugin.ShowContactMenu(Pt.X, Pt.Y);
end;
{******************************************************************************}
procedure TfrmQIPPlugin.LeftClickOnFadeMsg(PlugMsg: TPluginMessage);
var PlugMsg1 : TPluginMessage;
FadeMsgID: integer;
//spec : Integer;
begin
FadeMsgID := PlugMsg.WParam;
if Updater_NewVersionFadeID = FadeMsgID then
begin
PlugMsg1.Msg := PM_PLUGIN_FADE_CLOSE;
PlugMsg1.WParam := FadeMsgID;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
OpenUpdater;
end;
end;
procedure TfrmQIPPlugin.DrawHint(Cnv: TCanvas; R : TRect; CalcRect: Boolean; var Width: Integer; var Height: Integer);
var
PlugMsg1 : TPluginMessage;
wFontName : WideString;
iFontSize : Integer;
QipColors : pQipColors;
R1, RTitle : TRect;
sBitrateKBPS: WideString;
sTextInfo, sTextInfoTitle : WideString;
iWidth : Integer;
begin
SetBkMode(Cnv.Handle, TRANSPARENT);
PlugMsg1.Msg := PM_PLUGIN_GET_COLORS_FONT;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
wFontName := PWideChar(PlugMsg1.WParam);
iFontSize := PlugMsg1.LParam;
QipColors := pQipColors(PlugMsg1.NParam);
QIP_Colors := QipColors^;
if iBitrate <> '' then
sBitrateKBPS := iBitrate + ' kbps';
sTextInfoTitle := QIPPlugin.GetLang(LI_INFORMATION);
sTextInfo := LNG('FORM Info', 'Song', 'Song') + ': ' + iSong + #13#10 +
LNG('FORM Info', 'Radio', 'Radio') + ': ' + iRadio + #13#10 +
LNG('FORM Info', 'Bitrate', 'Bitrate') + ': ' + sBitrateKBPS;
sTextInfo := #13#10+sTextInfo;
//Cnv.Font.Color := QipColors.AccBtnText;
Cnv.Font.Style := [fsBold];
DrawTextW(Cnv.Handle, PWideChar(sTextInfoTitle), Length(sTextInfoTitle), RTitle, DT_LEFT + DT_CALCRECT );
if CalcRect = True then
begin
Cnv.Font.Style := [];
DrawTextW(Cnv.Handle, PWideChar(sTextInfo), Length(sTextInfo), R1, DT_LEFT + DT_CALCRECT );
iWidth := 100;
if iWidth < RTitle.Right - RTitle.Left then
iWidth := RTitle.Right - RTitle.Left;
if iWidth < R1.Right - R1.Left then
iWidth := R1.Right - R1.Left;
Width := iWidth + 10;
Height := (R1.Bottom - R1.Top) - 10;
end
else
begin
R1 := Rect(R.Left + 5, R.Top + 5, R.Right, R.Bottom);
Cnv.Font.Style := [fsBold];
DrawTextW(Cnv.Handle, PWideChar(sTextInfoTitle), Length(sTextInfoTitle), R1, DT_LEFT );
// R2.Top := R1.Top + (RTitle.Bottom - RTitle.Top);
Cnv.Font.Style := [];
DrawTextW(Cnv.Handle, PWideChar(sTextInfo), Length(sTextInfo), R1, DT_LEFT );
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.GetSpecContactHintSize(var PlugMsg: TPluginMessage);
var ContactId : DWord;
//Data : Pointer;
Img : TImage;
Rx : TRect;
begin
ContactId := PlugMsg.WParam;
Img := TImage.Create(Self);
try
DrawHint( Img.Canvas, Rx, True, PlugMsg.LParam, PlugMsg.NParam);
finally
Img.Free;
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.DrawSpecContactHint(PlugMsg: TPluginMessage);
var ContactId : DWord;
//Data : Pointer;
Cnv : TCanvas;
R : PRect;
tmpI : Integer;
begin
ContactId := PlugMsg.WParam;
Cnv := TCanvas.Create;
try
Cnv.Handle := PlugMsg.LParam;
R := PRect(PlugMsg.NParam);
DrawHint( Cnv, R^, False, tmpI, tmpI);
finally
Cnv.Free;
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.XstatusChangedByUser(PlugMsg: TPluginMessage);
begin
LastXStatusText := PWideChar(PlugMsg.LParam);
LastXStatusDescription := PWideChar(PlugMsg.NParam);
LastXStatusNumber := PlugMsg.WParam;
if XStatus_Boolean = True then
begin
{=== XStatus picture/text changed msg example ===================}
ActXstatusNum := PlugMsg.WParam;
if ActXstatusNum=11 then
ChangeXstatus:=True;
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.InstantMsgRcvd(var PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.InstantMsgSend(var PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.NewMessageFlashing(PlugMsg: TPluginMessage);
//var wAccName, wNickName : WideString;
begin
// {getting aaccount name and nick name of contact whose msg was received but not read yet}
// wAccName := PWideChar(PlugMsg.WParam);
// wNickName := PWideChar(PlugMsg.LParam);
end;
{******************************************************************************}
procedure TfrmQIPPlugin.NewMessageStopFlashing(PlugMsg: TPluginMessage);
begin
end;
procedure TfrmQIPPlugin.pmContactMenuChange(Sender: TObject; Source: TMenuItem;
Rebuild: Boolean);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.AddNeededBtns(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.MsgBtnClicked(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.SpecMsgRcvd(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.StatusChanged(PlugMsg: TPluginMessage);
var iStatus, iPrivStatus : integer;
iAuto: Integer;
begin
//Core sends this msg everytime on global or privacy status change by user or by plugin
iStatus := PlugMsg.WParam;
iPrivStatus := PlugMsg.LParam;
if (iStatus <> -1) then
begin
{ if (Radio_Playing = True) or ((Radio_Playing = False) and (AutoUseWherePlaying = False)) then
begin }
iAuto := -1;
if (iStatus = QIP_STATUS_INVISIBLE) or (iStatus = QIP_STATUS_INVISFORALL) then
iAuto := AutoStatusInvisible;
if iStatus = QIP_STATUS_FFC then
iAuto := AutoStatusFFC;
if iStatus = QIP_STATUS_EVIL then
iAuto := AutoStatusEvil;
if iStatus = QIP_STATUS_DEPRES then
iAuto := AutoStatusDepres;
if iStatus = QIP_STATUS_ATHOME then
iAuto := AutoStatusAtHome;
if iStatus = QIP_STATUS_ATWORK then
iAuto := AutoStatusAtWork;
if iStatus = QIP_STATUS_OCCUPIED then
iAuto := AutoStatusOccupied;
if iStatus = QIP_STATUS_DND then
iAuto := AutoStatusDND;
if iStatus = QIP_STATUS_LUNCH then
iAuto := AutoStatusLunch;
if iStatus = QIP_STATUS_AWAY then
iAuto := AutoStatusAway;
if iStatus = QIP_STATUS_NA then
iAuto := AutoStatusNA;
if (iStatus = QIP_STATUS_OFFLINE) or (iStatus = QIP_STATUS_CONNECTING) then
iAuto := AutoStatusOffline;
if (iStatus = QIP_STATUS_ONLINE) or (iAuto = -1) then
iAuto := AutoStatusOnline;
if iAuto = 0 then // NIC
begin
// nic
end
else if iAuto = 1 then //SPUSTIT
begin
if Radio_Playing = False then
FBassPlayer.PlayStopRadio;
end
else if iAuto = 2 then //VYPNOUT
begin
if Radio_Playing = True then
FBassPlayer.PlayStopRadio;
end;
{
end;
}
end;
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ImRcvdSuccess(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ContactStatusRcvd(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ChatTabAction(PlugMsg: TPluginMessage);
begin
end;
procedure TfrmQIPPlugin.CMAdvDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; State: TOwnerDrawState);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.AddNeededChatBtns(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ChatBtnClicked(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ChatMsgRcvd(PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.ChatMsgSending(var PlugMsg: TPluginMessage);
begin
end;
{******************************************************************************}
procedure TfrmQIPPlugin.EnumInfo(PlugMsg: TPluginMessage);
begin
end;
////////////////////////////////////////////////////////////////////////////////
function TfrmQIPPlugin.FadeMsg(FType: Byte; FIcon: HICON; FTitle: WideString; FText: WideString; FTextCenter: Boolean; FNoAutoClose: Boolean; pData: Integer) : DWORD;
var PlugMsg1 : TPluginMessage;
aFadeWnd: TFadeWndInfo;
begin
//0 - message style, 1 - information style, 2 - warning style
aFadeWnd.FadeType := FType;//1;
//its better to use ImageList of icons if you gonna show more than one icon everytime,
//else you have to care about destroying your HICON after showing fade window, cauz core makes self copy of HICON
// aFadeWnd.FadeIcon := LoadImage(0, IDI_INFORMATION, IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR or LR_SHARED);
aFadeWnd.FadeIcon := FIcon;
aFadeWnd.FadeTitle := FTitle;
aFadeWnd.FadeText := FText;
//if your text is too long, then you have to set this param to False
aFadeWnd.TextCentered := FTextCenter;
//it's recommended to set this parameter = False if your fade window is not very important
aFadeWnd.NoAutoClose := FNoAutoClose;
//send msg to qip core
PlugMsg1.Msg := PM_PLUGIN_FADE_MSG;
PlugMsg1.WParam := LongInt(@aFadeWnd);
PlugMsg1.LParam := 0; //vlastni Pointer
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
//if your window was successfuly shown then core returns Result = True (Result is unique id of fade msg),
//else you should try later to show it again
if Boolean(PlugMsg1.Result) then
//LogAdd('Fading popup window successefuly shown: FadeMsg ID is '+ IntToStr(PlugMsg1.Result))
Result := PlugMsg1.Result
else
//LogAdd('Fading popup window was NOT shown');
Result := 0;
end;
procedure TfrmQIPPlugin.AddFadeMsg(
FadeType : Byte; //0 - message style, 1 - information style, 2 - warning style
FadeIcon : HICON; //icon in the top left corner of the window
FadeTitle : WideString;
FadeText : WideString;
TextCentered : Boolean; //if true then text will be centered inside window
NoAutoClose : Boolean; //if NoAutoClose is True then wnd will be always shown until user close it. Not recommended to set this param to True.
CloseTime_Sec: Integer;
pData : Integer
);
var fmFadeMsg : TFadeMsg;
begin
fmFadeMsg := TFadeMsg.Create;
fmFadeMsg.FadeType := FadeType ;
fmFadeMsg.FadeIcon := FadeIcon;
fmFadeMsg.FadeTitle := FadeTitle;
fmFadeMsg.FadeText := FadeText;
fmFadeMsg.TextCentered := TextCentered;
fmFadeMsg.NoAutoClose := NoAutoClose;
fmFadeMsg.CloseTime := CloseTime_Sec;
fmFadeMsg.pData := pData;
FadeMsgs.Add('FADEMSG');
FadeMsgs.Objects[FadeMsgs.Count - 1] := fmFadeMsg.Create;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfrmQIPPlugin.AddSpecContact(var UniqID: DWord; HeightCnt: Integer = 19);
var PlugMsg1 : TPluginMessage;
begin
PlugMsg1.Msg := PM_PLUGIN_SPEC_ADD_CNT;
//set height of your contact here, min 8, max 100.
PlugMsg1.WParam := HeightCnt;
//Pointer
PlugMsg1.LParam := LongInt(@UniqID);
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
UniqID := PlugMsg1.Result;
end;
procedure TfrmQIPPlugin.RedrawSpecContact(UniqID: DWord);
var
PlugMsg1 : TPluginMessage;
begin
if UniqID = 0 then Exit;
PlugMsg1.Msg := PM_PLUGIN_SPEC_REDRAW;
PlugMsg1.WParam := UniqID;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
end;
procedure TfrmQIPPlugin.RemoveSpecContact(var UniqID: DWord);
var
PlugMsg1 : TPluginMessage;
begin
if UniqID = 0 then Exit;
PlugMsg1.Msg := PM_PLUGIN_SPEC_DEL_CNT;
PlugMsg1.WParam := UniqID;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
if Boolean(PlugMsg1.Result) then
UniqID := 0;
end;
function TfrmQIPPlugin.GetLang(ID: Word) : WideString;
var
PlugMsg1 : TPluginMessage;
begin
PlugMsg1.Msg := PM_PLUGIN_GET_LANG_STR;
PlugMsg1.WParam := ID;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
Result := PWideChar(PlugMsg1.Result);
end;
procedure TfrmQIPPlugin.InfiumClose(itype: Word);
var PlugMsg1 : TPluginMessage;
begin
// 0 - close; 1 - restart
PlugMsg1.Msg := PM_PLUGIN_INFIUM_CLOSE;
PlugMsg1.WParam := itype;
PlugMsg1.DllHandle := DllHandle;
FPluginSvc.OnPluginMessage(PlugMsg1);
end;
procedure TfrmQIPPlugin.StationNext();
begin
LastRadioFadeMsg := '';
if Radio_StationID >= Stations.Count - 1 then
Radio_StationID := 0
else
Inc(Radio_StationID);
Radio_StreamID := TStation(Stations.Objects[Radio_StationID]).DefaultStream;
SaveSelectedRadio;
if Radio_Playing = True then
begin
FBassPlayer.PlayStopRadio;
Application.ProcessMessages;
FBassPlayer.PlayStopRadio;
end;
RedrawSpecContact(UniqContactId);
end;
procedure TfrmQIPPlugin.StationPrev();
begin
LastRadioFadeMsg := '';
if Radio_StationID <= 0 then
Radio_StationID := Stations.Count - 1
else
Dec(Radio_StationID);
Radio_StreamID := TStation(Stations.Objects[Radio_StationID]).DefaultStream;
SaveSelectedRadio;
if Radio_Playing = True then
begin
FBassPlayer.PlayStopRadio;
Application.ProcessMessages;
FBassPlayer.PlayStopRadio;
end;
RedrawSpecContact(UniqContactId);
end;
procedure TfrmQIPPlugin.ShowContactMenu(pX, pY : Integer );
var
NewItem, NewItemTop10Folder, NewItemTop10: TMenuItem;
i: Integer;
StationsPlayCount, MenuGroups : TStringlist;
idxGroup: Integer;
bTop10Items : Boolean;
begin
if not (Radio_Playing and StreamRecording) then
begin
MenuGroups := TStringList.Create;
MenuGroups.Clear;
StationsPlayCount := TStringList.Create;
StationsPlayCount.Clear;
for i:=1 to miContactMenu_Stations.Count do miContactMenu_Stations.Delete(0);
bTop10Items := False;
//Sekce - Nejpřehrávanějších rádíí
NewItemTop10Folder := TMenuItem.Create(Self);
NewItemTop10Folder.Caption := LNG('MENU ContactMenu', 'Favourites', 'Favourites');
NewItemTop10Folder.Tag := -1;
//NewItemTop10Folder.OnClick := miContactMenu_StationsClick;
NewItemTop10Folder.OnDrawItem := DrawMenu;
NewItemTop10Folder.OnMeasureItem := MeasureMenu;
NewItemTop10Folder.ImageIndex := 11;
miContactMenu_Stations.Add(NewItemTop10Folder);
NewItem := TMenuItem.Create(Self);
NewItem.Caption := '-';
NewItem.Tag := -1;
NewItem.OnDrawItem := DrawMenu;
miContactMenu_Stations.Add(NewItem);
StationsPlayCount.Assign(Stations);
//StationsPlayCount := SortStationsPlayCount(StationsPlayCount);
StationsPlayCount := SortStationsPlayTime(StationsPlayCount);
for i := 0 to StationsPlayCount.Count - 1 do
begin
if (TStation(StationsPlayCount.Objects[i]).PlayCount = 0) or (i > 9) then
break;
NewItemTop10 := TMenuItem.Create(Self);
NewItemTop10.Caption := TStation(StationsPlayCount.Objects[i]).Name;
NewItemTop10.Tag := Stations.IndexOfObject(StationsPlayCount.Objects[i]);
NewItemTop10.OnClick := miContactMenu_StationsClick;
NewItemTop10.OnDrawItem := DrawMenu;
NewItemTop10.OnMeasureItem := MeasureMenu;
if Radio_StationID = NewItemTop10.Tag then NewItemTop10.Checked := True;
NewItemTop10Folder.Add(NewItemTop10);
bTop10Items := True;
application.ProcessMessages;
end;
if bTop10Items = False then
begin
NewItemTop10 := TMenuItem.Create(Self);
NewItemTop10.Caption := QIPPlugin.GetLang(LI_NO_ACCOUNT);
NewItemTop10.Enabled := False;
NewItemTop10.Tag := 0;
NewItemTop10.OnClick := miContactMenu_StationsClick;
NewItemTop10.OnDrawItem := DrawMenu;
NewItemTop10.OnMeasureItem := MeasureMenu;
NewItemTop10Folder.Add(NewItemTop10);
end;
for i := 0 to Stations.Count - 1 do
begin
if TStation(Stations.Objects[i]).Group='' then
begin
NewItem := TMenuItem.Create(Self);
NewItem.Caption := TStation(Stations.Objects[i]).Name;
NewItem.Tag := i;
NewItem.OnClick := miContactMenu_StationsClick;
NewItem.OnDrawItem := DrawMenu;
NewItem.OnMeasureItem := MeasureMenu;
if Radio_StationID = i then NewItem.Checked := True;
miContactMenu_Stations.Add(NewItem);
end
else
begin
idxGroup := MenuGroups.IndexOf(TStation(Stations.Objects[i]).Group);
if idxGroup = -1 then
begin
MenuGroups.Add(TStation(Stations.Objects[i]).Group);
idxGroup := MenuGroups.Count - 1;
MenuGroups.Objects[idxGroup] := TMenuItem.Create(Self);
TMenuItem(MenuGroups.Objects[idxGroup]).Caption := TStation(Stations.Objects[i]).Group;
TMenuItem(MenuGroups.Objects[idxGroup]).Tag := -1;
//TMenuItem(MenuGroups.Objects[idxGroup]).OnClick := miContactMenu_StationsClick;
TMenuItem(MenuGroups.Objects[idxGroup]).OnDrawItem := DrawMenu;
TMenuItem(MenuGroups.Objects[idxGroup]).OnMeasureItem := MeasureMenu;
TMenuItem(MenuGroups.Objects[idxGroup]).ImageIndex := 10;
miContactMenu_Stations.Add(TMenuItem(MenuGroups.Objects[idxGroup]));
end;
NewItem := TMenuItem.Create(Self);
NewItem.Caption := TStation(Stations.Objects[i]).Name;
NewItem.Tag := i;
NewItem.OnClick := miContactMenu_StationsClick;
NewItem.OnDrawItem := DrawMenu;
NewItem.OnMeasureItem := MeasureMenu;
if Radio_StationID = i then NewItem.Checked := True;
TMenuItem(MenuGroups.Objects[idxGroup]).Add(NewItem);
// TMenuItem(MenuGroups.Objects[idxGroup]).
end;
application.ProcessMessages;
end;
for i:=1 to miContactMenu_Formats.Count do miContactMenu_Formats.Delete(0);
if Radio_StationID > Stations.Count - 1 then
//dodelat
else
begin
for i := 0 to TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 do
begin
NewItem := TMenuItem.Create(Self);
NewItem.Caption := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[i]).Format;
NewItem.Tag := i;
NewItem.OnClick := miContactMenu_FormatsClick;
NewItem.OnDrawItem := DrawMenu;
NewItem.OnMeasureItem := MeasureMenu;
if Radio_StreamID = i then NewItem.Checked := True;
miContactMenu_Formats.Add(NewItem);
end;
end;
miContactMenu_Stations.Caption := LNG('MENU ContactMenu', 'Stations', 'Stations');
miContactMenu_Formats.Caption := LNG('MENU ContactMenu', 'Format', 'Format');
miContactMenu_CopySongName.Caption := LNG('MENU ContactMenu', 'CopySongName', 'Copy song name');
miContactMenu_Informations.Caption := QIPPlugin.GetLang(LI_INFORMATION);
miContactMenu_Equalizer.Caption := LNG('MENU ContactMenu', 'Equalizer', 'Equalizer');
miContactMenu_Recording.Caption := LNG('MENU ContactMenu', 'Recording', 'Recording');
miContactMenu_Volume.Caption := LNG('MENU ContactMenu', 'Volume', 'Volume');
miContactMenu_EditStations.Caption := LNG('MENU ContactMenu', 'EditStations', 'Edit stations');
miContactMenu_FastAddStation.Caption := LNG('MENU ContactMenu', 'FastAddStation', 'Fast add station');
miContactMenu_Options.Caption := QIPPlugin.GetLang(LI_OPTIONS);
if Radio_Playing = False then
begin
miContactMenu_OnOff.Caption := LNG('MENU ContactMenu', 'RadioOn', 'Radio on');
TIcon(PluginSkin.MenuIcons.Objects[0]).Assign(PluginTheme.State.PicturePlay.Icon);
end
else
begin
miContactMenu_OnOff.Caption := LNG('MENU ContactMenu', 'RadioOff', 'Radio off');
TIcon(PluginSkin.MenuIcons.Objects[0]).Assign(PluginTheme.State.PictureStop.Icon);
end;
pmContactMenu.Popup(pX,pY);
end;
end;
procedure TfrmQIPPlugin.SetChangeVolume;
var INI : TIniFile;
begin
INIGetProfileConfig(INI);
INIWriteInteger(INI, 'Conf','Volume', Player_Volume );
INIFree(INI);
if Player_Mute=True then
begin
FBassPlayer.Player_ChangeVolume( 0 );
ExtraText := LNG('PLAYER', 'VolumeMute', 'Volume: Mute');
ExtraTextTime := 4;
end
else
begin
FBassPlayer.Player_ChangeVolume( Player_Volume );
ExtraText := LNG('PLAYER', 'Volume', 'Volume:') + ' ' + IntToStr(Player_Volume) + '%';
ExtraTextTime := 4;
end;
RedrawSpecContact(UniqContactId);
end;
procedure TfrmQIPPlugin.SaveSelectedRadio;
var INI : TIniFile;
begin
INIGetProfileConfig(INI);
if Radio_StationID > Stations.Count - 1 then
//dodelat
else
begin
INIWriteStringUTF8(INI, 'Conf','StationID', TStation(Stations.Objects[ Radio_StationID ]).Name );
end;
INIWriteInteger(INI, 'Conf','StreamID', Radio_StreamID );
INIFree(INI);
end;
end.
|
namespace Reachability;
interface
uses
Foundation, SystemConfiguration;
type
//struct sockaddr_in {
// __uint8_t sin_len;
// sa_family_t sin_family;
// in_port_t sin_port;
// struct in_addr sin_addr;
// char sin_zero[8];
//};
//typedef unsigned char __uint8_t;
//typedef __uint8_t sa_family_t;
//typedef __uint16_t in_port_t;
//typedef unsigned short __uint16_t;
//struct in_addr {
// in_addr_t s_addr;
//};
//typedef __uint32_t in_addr_t; /* base type for internet address */
//typedef unsigned int __uint32_t;
__uint8_t = UInt8;
sa_family_t = __uint8_t;
__uint16_t = UInt16;
in_port_t = __uint16_t;
__uint32_t = UInt32;
in_addr_t = __uint32_t;
in_addr = public record
public
s_addr:in_addr_t;
end;
sockaddr_in = public record
public
sin_len:__uint8_t;
sin_family:sa_family_t;
sin_port:in_port_t;
sin_addr:in_addr;
sin_zero:array of Char := new Char[8];
end;
NetworkStatus = public enum (NotReachable, ReachableViaWiFi, ReachableViaWWAN);
Reachability = public class
private
const kReachabilityChangedNotification:String = 'kNetworkReachabilityChangedNotification';
const kSCNetworkReachabilityFlagsTransientConnection:Int64 = 1 shl 0;
const kSCNetworkReachabilityFlagsReachable:Int64 = 1 shl 1;
const kSCNetworkReachabilityFlagsConnectionRequired:Int64 = 1 shl 2;
const kSCNetworkReachabilityFlagsConnectionOnTraffic:Int64 = 1 shl 3;
const kSCNetworkReachabilityFlagsInterventionRequired:Int64 = 1 shl 4;
const kSCNetworkReachabilityFlagsConnectionOnDemand:Int64 = 1 shl 5;
const kSCNetworkReachabilityFlagsIsLocalAddress:Int64 = 1 shl 16;
const kSCNetworkReachabilityFlagsIsDirect:Int64 = 1 shl 17;
{$IF TARGET_OS_IPHONE}
const kSCNetworkReachabilityFlagsIsWWAN:Int64 = 1 shl 18;
{$ENDIF}
const kSCNetworkReachabilityFlagsConnectionAutomatic:Int32 = kSCNetworkReachabilityFlagsConnectionOnTraffic;
private
localWiFiRef:Boolean;
reachabilityRef:SCNetworkReachabilityRef;
method localWiFiStatusForFlags(&flags:SCNetworkReachabilityFlags):NetworkStatus;
method networkStatusForFlags(&flags:SCNetworkReachabilityFlags):NetworkStatus;
public
method startNotifier:Boolean;
method stopNotifier;
method connectionRequired:Boolean;
method currentReachabilityStatus:NetworkStatus;
class method reachabilityWithHostName(hostName:NSString):Reachability;
class method reachabilityWithAddress(hostAddress:^sockaddr_in):Reachability;
class method reachabilityForInternetConnection:Reachability;
class method reachabilityForLocalWiFi:Reachability;
class method ReachabilityCallback (target:SCNetworkReachabilityRef; flags:SCNetworkReachabilityFlags; info: ^Object );
end;
implementation
method Reachability.localWiFiStatusForFlags(&flags:SCNetworkReachabilityFlags):NetworkStatus;
begin
var retVal := NetworkStatus.NotReachable;
if( ((&flags and kSCNetworkReachabilityFlagsReachable) = kSCNetworkReachabilityFlagsReachable) and ((&flags and kSCNetworkReachabilityFlagsIsDirect) = kSCNetworkReachabilityFlagsIsDirect))then
begin
retVal := NetworkStatus.ReachableViaWiFi;
end;
exit retVal;
end;
method Reachability.networkStatusForFlags(&flags:SCNetworkReachabilityFlags):NetworkStatus;
begin
if ((&flags and kSCNetworkReachabilityFlagsReachable) = 0)then
begin
// if target host is not reachable
exit NetworkStatus.NotReachable;
end;
var retVal := NetworkStatus.NotReachable;
if ((flags and kSCNetworkReachabilityFlagsConnectionRequired) = 0)then
begin
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
retVal := NetworkStatus.ReachableViaWiFi;
end;
if (
((&flags and kSCNetworkReachabilityFlagsConnectionOnDemand) <> 0) or
((&flags and kSCNetworkReachabilityFlagsConnectionOnTraffic) <> 0)
)then
begin
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags and kSCNetworkReachabilityFlagsInterventionRequired) = 0)then
begin
// ... and no [user] intervention is needed
retVal := NetworkStatus.ReachableViaWiFi;
end;
end;
if ((&flags and kSCNetworkReachabilityFlagsIsWWAN) = kSCNetworkReachabilityFlagsIsWWAN)then
begin
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
retVal := NetworkStatus.ReachableViaWWAN;
end;
exit retVal;
end;
class method Reachability.ReachabilityCallback (target:SCNetworkReachabilityRef; flags:SCNetworkReachabilityFlags; info: ^Object );
begin
using autoreleasepool do
begin
var noteObject := bridge<Reachability>(info);
// Post a notification to notify the client that the network reachability changed.
NSNotificationCenter.defaultCenter.postNotificationName(kReachabilityChangedNotification) object(noteObject);
end;
end;
method Reachability.connectionRequired: Boolean;
begin
var flags:SCNetworkReachabilityFlags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, @flags)) then
begin
exit (&flags and SCNetworkReachabilityFlags.kSCNetworkReachabilityFlagsConnectionRequired) = SCNetworkReachabilityFlags.kSCNetworkReachabilityFlagsConnectionRequired;
end;
exit false;
end;
method Reachability.currentReachabilityStatus: NetworkStatus;
begin
var retVal := NetworkStatus.NotReachable;
var &flags:SCNetworkReachabilityFlags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, @flags))then
begin
if(localWiFiRef)then
begin
retVal := self.localWiFiStatusForFlags(&flags);
end
else
begin
retVal := self.networkStatusForFlags(&flags);
end;
end;
exit retVal;
end;
class method Reachability.reachabilityForInternetConnection: Reachability;
begin
var zeroAddress:sockaddr_in;
bzero(@zeroAddress, sizeOf(zeroAddress));
zeroAddress.sin_len := sizeOf(zeroAddress);
zeroAddress.sin_family := AF_INET;
exit reachabilityWithAddress(@zeroAddress);
end;
class method Reachability.reachabilityForLocalWiFi: Reachability;
begin
var localWifiAddress:sockaddr_in;
bzero(@localWifiAddress, sizeOf(localWifiAddress));
localWifiAddress.sin_len := sizeOf(localWifiAddress);
localWifiAddress.sin_family := AF_INET;
localWifiAddress.sin_addr.s_addr := htonl(IN_LINKLOCALNETNUM);
var retVal : Reachability := reachabilityWithAddress(@localWifiAddress);
if(assigned(retVal))then
begin
retVal.localWiFiRef := true;
end;
exit retVal;
end;
class method Reachability.reachabilityWithAddress(hostAddress: ^sockaddr_in): Reachability;
begin
var reachability:SCNetworkReachabilityRef := SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, ^__struct_sockaddr(hostAddress));
var retVal : Reachability := nil;
if(assigned(reachability))then
begin
retVal := new Reachability;
if(assigned(retVal))then
begin
retVal.reachabilityRef := reachability;
retVal.localWiFiRef := false;
end;
end;
exit retVal;
end;
class method Reachability.reachabilityWithHostName(hostName: NSString): Reachability;
begin
var retVal:Reachability := nil;
var reachability:SCNetworkReachabilityRef := SCNetworkReachabilityCreateWithName(nil, hostName.UTF8String);
if ( assigned(reachability)) then
begin
retVal := new Reachability;
if(assigned(retVal))then
begin
retVal.reachabilityRef := reachability;
retVal.localWiFiRef := false;
end;
end;
exit retVal;
end;
method Reachability.startNotifier: Boolean;
begin
var callback:SCNetworkReachabilityCallBack;
//callback := @ReachabilityCallback
callback := method begin
end;
var retVal:Boolean := false;
var context:SCDynamicStoreContext;
context.version := 0;
context.info := bridge<^Void>(self);
context.retain:= nil;
context.release := nil;
context.copyDescription := nil;
if(SCNetworkReachabilitySetCallback(reachabilityRef, callback, @context)) then
begin
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetMain(), kCFRunLoopDefaultMode)) then // DFH CFRunLoopGetCurrent()
begin
retVal := true;
end;
end;
exit retVal;
end;
method Reachability.stopNotifier;
begin
if(assigned(reachabilityRef))then
begin
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetMain(), kCFRunLoopDefaultMode); // CFRunLoopGetCurrent()
end;
end;
end.
|
{ CFString.h
Copyright (c) 1998-2005, Apple, Inc. All rights reserved.
}
{ Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, November 2005 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit CFString;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,CFBase,CFArray,CFData,CFDictionary,CFCharacterSet,CFLocale;
{$ALIGN POWER}
{
Please note: CFStrings are conceptually an array of Unicode characters.
However, in general, how a CFString stores this array is an implementation
detail. For instance, CFString might choose to use an array of 8-bit characters;
to store its contents; or it might use multiple blocks of memory; or whatever.
Furthermore, the implementation might change depending on the default
system encoding, the user's language, the OS, or even a given release.
What this means is that you should use the following advanced functions with care:
CFStringGetPascalStringPtr()
CFStringGetCStringPtr()
CFStringGetCharactersPtr()
These functions are provided for optimization only. They will either return the desired
pointer quickly, in constant time, or they return NULL. They might choose to return NULL
for many reasons; for instance it's possible that for users running in different
languages these sometimes return NULL; or in a future OS release the first two might
switch to always returning NULL. Never observing NULL returns in your usages of these
functions does not mean they won't ever return NULL. (But note the CFStringGetCharactersPtr()
exception mentioned further below.)
In your usages of these functions, if you get a NULL return, use the non-Ptr version
of the functions as shown in this example:
Str255 buffer;
StringPtr ptr = CFStringGetPascalStringPtr(str, encoding);
if (ptr == NULL) (
if (CFStringGetPascalString(str, buffer, 256, encoding)) ptr = buffer;
)
Note that CFStringGetPascalString() or CFStringGetCString() calls might still fail --- but
that will happen in two circumstances only: The conversion from the UniChar contents of CFString
to the specified encoding fails, or the buffer is too small. If they fail, that means
the conversion was not possible.
If you need a copy of the buffer in the above example, you might consider simply
calling CFStringGetPascalString() in all cases --- CFStringGetPascalStringPtr()
is simply an optimization.
In addition, the following functions, which create immutable CFStrings from developer
supplied buffers without copying the buffers, might have to actually copy
under certain circumstances (If they do copy, the buffer will be dealt with by the
"contentsDeallocator" argument.):
CFStringCreateWithPascalStringNoCopy()
CFStringCreateWithCStringNoCopy()
CFStringCreateWithCharactersNoCopy()
You should of course never depend on the backing store of these CFStrings being
what you provided, and in other no circumstance should you change the contents
of that buffer (given that would break the invariant about the CFString being immutable).
Having said all this, there are actually ways to create a CFString where the backing store
is external, and can be manipulated by the developer or CFString itself:
CFStringCreateMutableWithExternalCharactersNoCopy()
CFStringSetExternalCharactersNoCopy()
A "contentsAllocator" is used to realloc or free the backing store by CFString.
kCFAllocatorNull can be provided to assure CFString will never realloc or free the buffer.
Developer can call CFStringSetExternalCharactersNoCopy() to update
CFString's idea of what's going on, if the buffer is changed externally. In these
strings, CFStringGetCharactersPtr() is guaranteed to return the external buffer.
These functions are here to allow wrapping a buffer of UniChar characters in a CFString,
allowing the buffer to passed into CFString functions and also manipulated via CFString
mutation functions. In general, developers should not use this technique for all strings,
as it prevents CFString from using certain optimizations.
}
{ Identifier for character encoding; the values are the same as Text Encoding Converter TextEncoding.
}
type
CFStringEncoding = UInt32;
CFStringEncodingPtr = ^CFStringEncoding;
{ Platform-independent built-in encodings; always available on all platforms.
Call CFStringGetSystemEncoding() to get the default system encoding.
}
type
CFStringBuiltInEncodings = SInt32;
const
kCFStringEncodingInvalidId = $FFFFFFFF;
kCFStringEncodingMacRoman = 0;
kCFStringEncodingWindowsLatin1 = $0500; { ANSI codepage 1252 }
kCFStringEncodingISOLatin1 = $0201; { ISO 8859-1 }
kCFStringEncodingNextStepLatin = $0B01; { NextStep encoding }
kCFStringEncodingASCII = $0600; { 0..127 (in creating CFString, values greater than 0x7F are treated as corresponding Unicode value) }
kCFStringEncodingUnicode = $0100; { kTextEncodingUnicodeDefault + kTextEncodingDefaultFormat (aka kUnicode16BitFormat) }
kCFStringEncodingUTF8 = $08000100; { kTextEncodingUnicodeDefault + kUnicodeUTF8Format }
kCFStringEncodingNonLossyASCII = $0BFF; { 7bit Unicode variants used by YellowBox & Java }
{#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4}
kCFStringEncodingUTF16 = $0100; { kTextEncodingUnicodeDefault + kUnicodeUTF16Format (alias of kCFStringEncodingUnicode) }
kCFStringEncodingUTF16BE = $10000100; { kTextEncodingUnicodeDefault + kUnicodeUTF16BEFormat }
kCFStringEncodingUTF16LE = $14000100; { kTextEncodingUnicodeDefault + kUnicodeUTF16LEFormat }
kCFStringEncodingUTF32 = $0C000100; { kTextEncodingUnicodeDefault + kUnicodeUTF32Format }
kCFStringEncodingUTF32BE = $18000100; { kTextEncodingUnicodeDefault + kUnicodeUTF32BEFormat }
kCFStringEncodingUTF32LE = $1C000100; { kTextEncodingUnicodeDefault + kUnicodeUTF32LEFormat }
{#endif} { MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 }
{ CFString type ID }
function CFStringGetTypeID: CFTypeID; external name '_CFStringGetTypeID';
{ Macro to allow creation of compile-time constant strings; the argument should be a constant string.
CFSTR(), not being a "Copy" or "Create" function, does not return a new
reference for you. So, you should not release the return value. This is
much like constant C or Pascal strings --- when you use "hello world"
in a program, you do not free it.
However, strings returned from CFSTR() can be retained and released in a
properly nested fashion, just like any other CF type. That is, if you pass
a CFSTR() return value to a function such as SetMenuItemWithCFString(), the
function can retain it, then later, when it's done with it, it can release it.
At this point non-7 bit characters (that is, characters > 127) in CFSTR() are not
supported and using them will lead to unpredictable results. This includes escaped
(\nnn) characters whose values are > 127. Even if it works for you in testing,
it might not work for a user with a different language preference.
}
{
*** Pascal Usage of CFSTR et al ***
For Pascal:
To define your own constant CFStrings, call call CFSTRP with a
constant Pascal single-quoted string only, for example
CFSTRP('a constant string').
For MetroWerks Pascal:
Include the CFStringGlue file in your project (it defines the private function,
CFSTRP0, which you should never call directly.
In your uses clause, use CFString and CFStringGlue and whichever PInterface files
defining the constant CFStrings (or define your own using CFSTRP('pascal string')).
For GNU Pascal:
Include the GPCMacros.inc file (for example $I GPCMacros.inc).
In your uses clause, use CFString (and, optionally, CFStringGlue and the
PInterface files defining the constant CFStrings).
You can optionally use CFSTR with a constant double-quoted C String (for example,
CFSTR("a constant C string")) although it will make no difference, but will
result in closer C source code similarity.
For maximum compatibility in both GPC and MetroWerks Pascal
Include the GPCMacros.inc file in GPC as part of your GPC prefix.
Include the CFStringGlue file in your MW project.
Only ever use CFSTRP with a constant Pascal string.
In your uses clause for a unit, use the CFString, CFStringGlue and any
PInterface files defining any constant CFStrings you need.
}
{
CFSTR Must only be called with a constant CString
}
function CFSTR( c: PChar ): CFStringRef; external name '___CFStringMakeConstantString';
{
CFSTRP Must only be called with a constant Pascal String
}
function CFSTRP( c: PChar ): CFStringRef; external name '___CFStringMakeConstantString';
{
CFSTRP0 Must only be called with a constant Pascal String terminated with a chr(0)
}
function CFSTRP0( c: PChar ): CFStringRef; external name '___CFStringMakeConstantString';
{** Immutable string creation functions **}
{ Functions to create basic immutable strings. The provided allocator is used for all memory activity in these functions.
}
{ These functions copy the provided buffer into CFString's internal storage. }
function CFStringCreateWithPascalString( alloc: CFAllocatorRef; const (*var*) pStr: Str255; encoding: CFStringEncoding ): CFStringRef; external name '_CFStringCreateWithPascalString';
function CFStringCreateWithCString( alloc: CFAllocatorRef; cStr: ConstCStringPtr; encoding: CFStringEncoding ): CFStringRef; external name '_CFStringCreateWithCString';
function CFStringCreateWithCharacters( alloc: CFAllocatorRef; chars: UniCharPtr; numChars: CFIndex ): CFStringRef; external name '_CFStringCreateWithCharacters';
{ These functions try not to copy the provided buffer. The buffer will be deallocated
with the provided contentsDeallocator when it's no longer needed; to not free
the buffer, specify kCFAllocatorNull here. As usual, NULL means default allocator.
NOTE: Do not count on these buffers as being used by the string;
in some cases the CFString might free the buffer and use something else
(for instance if it decides to always use Unicode encoding internally).
NOTE: If you are not transferring ownership of the buffer to the CFString
(for instance, you supplied contentsDeallocator = kCFAllocatorNull), it is your
responsibility to assure the buffer does not go away during the lifetime of the string.
If the string is retained or copied, its lifetime might extend in ways you cannot
predict. So, for strings created with buffers whose lifetimes you cannot
guarantee, you need to be extremely careful --- do not hand it out to any
APIs which might retain or copy the strings.
}
function CFStringCreateWithPascalStringNoCopy( alloc: CFAllocatorRef; const (*var*) pStr: Str255; encoding: CFStringEncoding; contentsDeallocator: CFAllocatorRef ): CFStringRef; external name '_CFStringCreateWithPascalStringNoCopy';
function CFStringCreateWithCStringNoCopy( alloc: CFAllocatorRef; cStr: ConstCStringPtr; encoding: CFStringEncoding; contentsDeallocator: CFAllocatorRef ): CFStringRef; external name '_CFStringCreateWithCStringNoCopy';
function CFStringCreateWithCharactersNoCopy( alloc: CFAllocatorRef; chars: UniCharPtr; numChars: CFIndex; contentsDeallocator: CFAllocatorRef ): CFStringRef; external name '_CFStringCreateWithCharactersNoCopy';
{ Create copies of part or all of the string.
}
function CFStringCreateWithSubstring( alloc: CFAllocatorRef; str: CFStringRef; range: CFRange ): CFStringRef; external name '_CFStringCreateWithSubstring';
function CFStringCreateCopy( alloc: CFAllocatorRef; theString: CFStringRef ): CFStringRef; external name '_CFStringCreateCopy';
{ These functions create a CFString from the provided printf-like format string and arguments.
}
function CFStringCreateWithFormat( alloc: CFAllocatorRef; formatOptions: CFDictionaryRef; format: CFStringRef; ... ): CFStringRef; external name '_CFStringCreateWithFormat';
function CFStringCreateWithFormatAndArguments( alloc: CFAllocatorRef; formatOptions: CFDictionaryRef; format: CFStringRef; arguments: UnivPtr ): CFStringRef; external name '_CFStringCreateWithFormatAndArguments';
{ Functions to create mutable strings. "maxLength", if not 0, is a hard bound on the length of the string. If 0, there is no limit on the length.
}
function CFStringCreateMutable( alloc: CFAllocatorRef; maxLength: CFIndex ): CFMutableStringRef; external name '_CFStringCreateMutable';
function CFStringCreateMutableCopy( alloc: CFAllocatorRef; maxLength: CFIndex; theString: CFStringRef ): CFMutableStringRef; external name '_CFStringCreateMutableCopy';
{ This function creates a mutable string that has a developer supplied and directly editable backing store.
The string will be manipulated within the provided buffer (if any) until it outgrows capacity; then the
externalCharactersAllocator will be consulted for more memory. When the CFString is deallocated, the
buffer will be freed with the externalCharactersAllocator. Provide kCFAllocatorNull here to prevent the buffer
from ever being reallocated or deallocated by CFString. See comments at top of this file for more info.
}
function CFStringCreateMutableWithExternalCharactersNoCopy( alloc: CFAllocatorRef; chars: UniCharPtr; numChars: CFIndex; capacity: CFIndex; externalCharactersAllocator: CFAllocatorRef ): CFMutableStringRef; external name '_CFStringCreateMutableWithExternalCharactersNoCopy';
{** Basic accessors for the contents **}
{ Number of 16-bit Unicode characters in the string.
}
function CFStringGetLength( theString: CFStringRef ): CFIndex; external name '_CFStringGetLength';
{ Extracting the contents of the string. For obtaining multiple characters, calling
CFStringGetCharacters() is more efficient than multiple calls to CFStringGetCharacterAtIndex().
If the length of the string is not known (so you can't use a fixed size buffer for CFStringGetCharacters()),
another method is to use is CFStringGetCharacterFromInlineBuffer() (see further below).
}
function CFStringGetCharacterAtIndex( theString: CFStringRef; idx: CFIndex ): UniChar; external name '_CFStringGetCharacterAtIndex';
procedure CFStringGetCharacters( theString: CFStringRef; range: CFRange; buffer: UniCharPtr ); external name '_CFStringGetCharacters';
{** Conversion to other encodings **}
{ These two convert into the provided buffer; they return false if conversion isn't possible
(due to conversion error, or not enough space in the provided buffer).
These functions do zero-terminate or put the length byte; the provided bufferSize should include
space for this (so pass 256 for Str255). More sophisticated usages can go through CFStringGetBytes().
These functions are equivalent to calling CFStringGetBytes() with
the range of the string; lossByte = 0; and isExternalRepresentation = false;
if successful, they then insert the leading length of terminating zero, as desired.
}
function CFStringGetPascalString( theString: CFStringRef; buffer: StringPtr; bufferSize: CFIndex; encoding: CFStringEncoding ): Boolean; external name '_CFStringGetPascalString';
function CFStringGetCString( theString: CFStringRef; buffer: CStringPtr; bufferSize: CFIndex; encoding: CFStringEncoding ): Boolean; external name '_CFStringGetCString';
{ These functions attempt to return in O(1) time the desired format for the string.
Note that although this means a pointer to the internal structure is being returned,
this can't always be counted on. Please see note at the top of the file for more
details.
}
function CFStringGetPascalStringPtr( theString: CFStringRef; encoding: CFStringEncoding ): ConstStringPtr; external name '_CFStringGetPascalStringPtr'; { May return NULL at any time; be prepared for NULL }
function CFStringGetCStringPtr( theString: CFStringRef; encoding: CFStringEncoding ): ConstCStringPtr; external name '_CFStringGetCStringPtr'; { May return NULL at any time; be prepared for NULL }
function CFStringGetCharactersPtr( theString: CFStringRef ): UniCharPtr; external name '_CFStringGetCharactersPtr'; { May return NULL at any time; be prepared for NULL }
{ The primitive conversion routine; allows you to convert a string piece at a time
into a fixed size buffer. Returns number of characters converted.
Characters that cannot be converted to the specified encoding are represented
with the byte specified by lossByte; if lossByte is 0, then lossy conversion
is not allowed and conversion stops, returning partial results.
Pass buffer==NULL if you don't care about the converted string (but just the convertability,
or number of bytes required).
maxBufLength indicates the maximum number of bytes to generate. It is ignored when buffer==NULL.
Does not zero-terminate. If you want to create Pascal or C string, allow one extra byte at start or end.
Setting isExternalRepresentation causes any extra bytes that would allow
the data to be made persistent to be included; for instance, the Unicode BOM.
}
function CFStringGetBytes( theString: CFStringRef; range: CFRange; encoding: CFStringEncoding; lossByte: ByteParameter; isExternalRepresentation: Boolean; buffer: UInt8Ptr; maxBufLen: CFIndex; var usedBufLen: CFIndex ): CFIndex; external name '_CFStringGetBytes';
{ This one goes the other way by creating a CFString from a bag of bytes.
This is much like CFStringCreateWithPascalString or CFStringCreateWithCString,
except the length is supplied explicitly. In addition, you can specify whether
the data is an external format --- that is, whether to pay attention to the
BOM character (if any) and do byte swapping if necessary
}
function CFStringCreateWithBytes( alloc: CFAllocatorRef; bytes: UnivPtr; numBytes: CFIndex; encoding: CFStringEncoding; isExternalRepresentation: Boolean ): CFStringRef; external name '_CFStringCreateWithBytes';
{ Convenience functions String <-> Data. These generate "external" formats, that is, formats that
can be written out to disk. For instance, if the encoding is Unicode, CFStringCreateFromExternalRepresentation()
pays attention to the BOM character (if any) and does byte swapping if necessary.
Similarly CFStringCreateExternalRepresentation() will always include a BOM character if the encoding is
Unicode. See above for description of lossByte.
}
function CFStringCreateFromExternalRepresentation( alloc: CFAllocatorRef; data: CFDataRef; encoding: CFStringEncoding ): CFStringRef; external name '_CFStringCreateFromExternalRepresentation'; { May return NULL on conversion error }
function CFStringCreateExternalRepresentation( alloc: CFAllocatorRef; theString: CFStringRef; encoding: CFStringEncoding; lossByte: ByteParameter ): CFDataRef; external name '_CFStringCreateExternalRepresentation'; { May return NULL on conversion error }
{ Hints about the contents of a string
}
function CFStringGetSmallestEncoding( theString: CFStringRef ): CFStringEncoding; external name '_CFStringGetSmallestEncoding'; { Result in O(n) time max }
function CFStringGetFastestEncoding( theString: CFStringRef ): CFStringEncoding; external name '_CFStringGetFastestEncoding'; { Result in O(1) time max }
{ General encoding info
}
function CFStringGetSystemEncoding: CFStringEncoding; external name '_CFStringGetSystemEncoding'; { The default encoding for the system; untagged 8-bit characters are usually in this encoding }
function CFStringGetMaximumSizeForEncoding( length: CFIndex; encoding: CFStringEncoding ): CFIndex; external name '_CFStringGetMaximumSizeForEncoding'; { Max bytes a string of specified length (in UniChars) will take up if encoded }
{** FileSystem path conversion functions **}
{ Extract the contents of the string as a NULL-terminated 8-bit string appropriate for passing to POSIX APIs. The string is zero-terminated. false will be returned if the conversion results don't fit into the buffer. Use CFStringGetMaximumSizeOfFileSystemRepresentation() if you want to make sure the buffer is of sufficient length.
}
function CFStringGetFileSystemRepresentation( strng: CFStringRef; buffer: CStringPtr; maxBufLen: CFIndex ): Boolean; external name '_CFStringGetFileSystemRepresentation';
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Get the upper bound on the number of bytes required to hold the file system representation for the string. This result is returned quickly as a very rough approximation, and could be much larger than the actual space required. The result includes space for the zero termination. If you are allocating a buffer for long-term keeping, it's recommended that you reallocate it smaller (to be the right size) after calling CFStringGetFileSystemRepresentation().
}
function CFStringGetMaximumSizeOfFileSystemRepresentation( strng: CFStringRef ): CFIndex; external name '_CFStringGetMaximumSizeOfFileSystemRepresentation';
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Create a CFString from the specified zero-terminated POSIX file system representation. If the conversion fails (possible due to bytes in the buffer not being a valid sequence of bytes for the appropriate character encoding), NULL is returned.
}
function CFStringCreateWithFileSystemRepresentation( alloc: CFAllocatorRef; buffer: ConstCStringPtr ): CFStringRef; external name '_CFStringCreateWithFileSystemRepresentation';
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{** Comparison functions. **}
{ Find and compare flags; these are OR'ed together as compareOptions or searchOptions in the various functions.
This typedef doesn't appear in the functions; instead the argument is CFOptionFlags.
}
type
CFStringCompareFlags = SInt32;
const
{ Flags used in all find and compare operations }
kCFCompareCaseInsensitive = 1;
kCFCompareBackwards = 4; { Starting from the end of the string }
kCFCompareAnchored = 8; { Only at the specified starting point }
kCFCompareNonliteral = 16; { If specified, loose equivalence is performed (o-umlaut == o, umlaut) }
kCFCompareLocalized = 32; { User's default locale is used for the comparisons }
kCFCompareNumerically = 64; { Numeric comparison is used; that is, Foo2.txt < Foo7.txt < Foo25.txt }
{ The main comparison routine; compares specified range of the first string to (the full range of) the second string.
locale == NULL indicates canonical locale.
kCFCompareNumerically, added in 10.2, does not work if kCFCompareLocalized is specified on systems before 10.3
kCFCompareBackwards and kCFCompareAnchored are not applicable.
}
function CFStringCompareWithOptions( theString1: CFStringRef; theString2: CFStringRef; rangeToCompare: CFRange; compareOptions: CFOptionFlags ): CFComparisonResult; external name '_CFStringCompareWithOptions';
{ Comparison convenience suitable for passing as sorting functions.
kCFCompareNumerically, added in 10.2, does not work if kCFCompareLocalized is specified on systems before 10.3
kCFCompareBackwards and kCFCompareAnchored are not applicable.
}
function CFStringCompare( theString1: CFStringRef; theString2: CFStringRef; compareOptions: CFOptionFlags ): CFComparisonResult; external name '_CFStringCompare';
{ CFStringFindWithOptions() returns the found range in the CFRange * argument; you can pass NULL for simple discovery check.
If stringToFind is the empty string (zero length), nothing is found.
Ignores the kCFCompareNumerically option.
}
function CFStringFindWithOptions( theString: CFStringRef; stringToFind: CFStringRef; rangeToSearch: CFRange; searchOptions: CFOptionFlags; var result: CFRange ): Boolean; external name '_CFStringFindWithOptions';
{ CFStringCreateArrayWithFindResults() returns an array of CFRange pointers, or NULL if there are no matches.
Overlapping instances are not found; so looking for "AA" in "AAA" finds just one range.
Post 10.1: If kCFCompareBackwards is provided, the scan is done from the end (which can give a different result), and
the results are stored in the array backwards (last found range in slot 0).
If stringToFind is the empty string (zero length), nothing is found.
kCFCompareAnchored causes just the consecutive instances at start (or end, if kCFCompareBackwards) to be reported. So, searching for "AB" in "ABABXAB..." you just get the first two occurrences.
Ignores the kCFCompareNumerically option.
}
function CFStringCreateArrayWithFindResults( alloc: CFAllocatorRef; theString: CFStringRef; stringToFind: CFStringRef; rangeToSearch: CFRange; compareOptions: CFOptionFlags ): CFArrayRef; external name '_CFStringCreateArrayWithFindResults';
{ Find conveniences; see comments above concerning empty string and options.
}
function CFStringFind( theString: CFStringRef; stringToFind: CFStringRef; compareOptions: CFOptionFlags ): CFRange; external name '_CFStringFind';
function CFStringHasPrefix( theString: CFStringRef; prefix: CFStringRef ): Boolean; external name '_CFStringHasPrefix';
function CFStringHasSuffix( theString: CFStringRef; suffix: CFStringRef ): Boolean; external name '_CFStringHasSuffix';
{#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED}
{!
@function CFStringGetRangeOfComposedCharactersAtIndex
Returns the range of the composed character sequence at the specified index.
@param theString The CFString which is to be searched. If this
parameter is not a valid CFString, the behavior is
undefined.
@param theIndex The index of the character contained in the
composed character sequence. If the index is
outside the index space of the string (0 to N-1 inclusive,
where N is the length of the string), the behavior is
undefined.
@result The range of the composed character sequence.
}
function CFStringGetRangeOfComposedCharactersAtIndex( theString: CFStringRef; theIndex: CFIndex ): CFRange; external name '_CFStringGetRangeOfComposedCharactersAtIndex';
{!
@function CFStringFindCharacterFromSet
Query the range of the first character contained in the specified character set.
@param theString The CFString which is to be searched. If this
parameter is not a valid CFString, the behavior is
undefined.
@param theSet The CFCharacterSet against which the membership
of characters is checked. If this parameter is not a valid
CFCharacterSet, the behavior is undefined.
@param range The range of characters within the string to search. If
the range location or end point (defined by the location
plus length minus 1) are outside the index space of the
string (0 to N-1 inclusive, where N is the length of the
string), the behavior is undefined. If the range length is
negative, the behavior is undefined. The range may be empty
(length 0), in which case no search is performed.
@param searchOptions The bitwise-or'ed option flags to control
the search behavior. The supported options are
kCFCompareBackwards andkCFCompareAnchored.
If other option flags are specified, the behavior
is undefined.
@param result The pointer to a CFRange supplied by the caller in
which the search result is stored. Note that the length
of this range could be more than If a pointer to an invalid
memory is specified, the behavior is undefined.
@result true, if at least a character which is a member of the character
set is found and result is filled, otherwise, false.
}
function CFStringFindCharacterFromSet( theString: CFStringRef; theSet: CFCharacterSetRef; rangeToSearch: CFRange; searchOptions: CFOptionFlags; var result: CFRange ): Boolean; external name '_CFStringFindCharacterFromSet';
{#endif}
{ Find range of bounds of the line(s) that span the indicated range (startIndex, numChars),
taking into account various possible line separator sequences (CR, CRLF, LF, and Unicode LS, PS).
All return values are "optional" (provide NULL if you don't want them)
lineStartIndex: index of first character in line
lineEndIndex: index of first character of the next line (including terminating line separator characters)
contentsEndIndex: index of the first line separator character
Thus, lineEndIndex - lineStartIndex is the number of chars in the line, including the line separators
contentsEndIndex - lineStartIndex is the number of chars in the line w/out the line separators
}
procedure CFStringGetLineBounds( theString: CFStringRef; range: CFRange; var lineBeginIndex: CFIndex; var lineEndIndex: CFIndex; var contentsEndIndex: CFIndex ); external name '_CFStringGetLineBounds';
{** Exploding and joining strings with a separator string **}
function CFStringCreateByCombiningStrings( alloc: CFAllocatorRef; theArray: CFArrayRef; separatorString: CFStringRef ): CFStringRef; external name '_CFStringCreateByCombiningStrings'; { Empty array returns empty string; one element array returns the element }
function CFStringCreateArrayBySeparatingStrings( alloc: CFAllocatorRef; theString: CFStringRef; separatorString: CFStringRef ): CFArrayRef; external name '_CFStringCreateArrayBySeparatingStrings'; { No separators in the string returns array with that string; string == sep returns two empty strings }
{** Parsing non-localized numbers from strings **}
function CFStringGetIntValue( str: CFStringRef ): SInt32; external name '_CFStringGetIntValue'; { Skips whitespace; returns 0 on error, MAX or -MAX on overflow }
function CFStringGetDoubleValue( str: CFStringRef ): Float64; external name '_CFStringGetDoubleValue'; { Skips whitespace; returns 0.0 on error }
{** MutableString functions **}
{ CFStringAppend("abcdef", "xxxxx") -> "abcdefxxxxx"
CFStringDelete("abcdef", CFRangeMake(2, 3)) -> "abf"
CFStringReplace("abcdef", CFRangeMake(2, 3), "xxxxx") -> "abxxxxxf"
CFStringReplaceAll("abcdef", "xxxxx") -> "xxxxx"
}
procedure CFStringAppend( theString: CFMutableStringRef; appendedString: CFStringRef ); external name '_CFStringAppend';
procedure CFStringAppendCharacters( theString: CFMutableStringRef; chars: UniCharPtr; numChars: CFIndex ); external name '_CFStringAppendCharacters';
procedure CFStringAppendPascalString( theString: CFMutableStringRef; const (*var*) pStr: Str255; encoding: CFStringEncoding ); external name '_CFStringAppendPascalString';
procedure CFStringAppendCString( theString: CFMutableStringRef; cStr: ConstCStringPtr; encoding: CFStringEncoding ); external name '_CFStringAppendCString';
procedure CFStringAppendFormat( theString: CFMutableStringRef; formatOptions: CFDictionaryRef; format: CFStringRef; ... ); external name '_CFStringAppendFormat';
procedure CFStringAppendFormatAndArguments( theString: CFMutableStringRef; formatOptions: CFDictionaryRef; format: CFStringRef; arguments: UnivPtr ); external name '_CFStringAppendFormatAndArguments';
procedure CFStringInsert( str: CFMutableStringRef; idx: CFIndex; insertedStr: CFStringRef ); external name '_CFStringInsert';
procedure CFStringDelete( theString: CFMutableStringRef; range: CFRange ); external name '_CFStringDelete';
procedure CFStringReplace( theString: CFMutableStringRef; range: CFRange; replacement: CFStringRef ); external name '_CFStringReplace';
procedure CFStringReplaceAll( theString: CFMutableStringRef; replacement: CFStringRef ); external name '_CFStringReplaceAll'; { Replaces whole string }
{#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED}
{ Replace all occurrences of target in rangeToSearch of theString with replacement.
Pays attention to kCFCompareCaseInsensitive, kCFCompareBackwards, kCFCompareNonliteral, and kCFCompareAnchored.
kCFCompareBackwards can be used to do the replacement starting from the end, which could give a different result.
ex. AAAAA, replace AA with B -> BBA or ABB; latter if kCFCompareBackwards
kCFCompareAnchored assures only anchored but multiple instances are found (the instances must be consecutive at start or end)
ex. AAXAA, replace A with B -> BBXBB or BBXAA; latter if kCFCompareAnchored
Returns number of replacements performed.
}
function CFStringFindAndReplace( theString: CFMutableStringRef; stringToFind: CFStringRef; replacementString: CFStringRef; rangeToSearch: CFRange; compareOptions: CFOptionFlags ): CFIndex; external name '_CFStringFindAndReplace';
{#endif}
{ This function will make the contents of a mutable CFString point directly at the specified UniChar array.
It works only with CFStrings created with CFStringCreateMutableWithExternalCharactersNoCopy().
This function does not free the previous buffer.
The string will be manipulated within the provided buffer (if any) until it outgrows capacity; then the
externalCharactersAllocator will be consulted for more memory.
See comments at the top of this file for more info.
}
procedure CFStringSetExternalCharactersNoCopy( theString: CFMutableStringRef; chars: UniCharPtr; length: CFIndex; capacity: CFIndex ); external name '_CFStringSetExternalCharactersNoCopy'; { Works only on specially created mutable strings! }
{ CFStringPad() will pad or cut down a string to the specified size.
The pad string is used as the fill string; indexIntoPad specifies which character to start with.
CFStringPad("abc", " ", 9, 0) -> "abc "
CFStringPad("abc", ". ", 9, 1) -> "abc . . ."
CFStringPad("abcdef", ?, 3, ?) -> "abc"
CFStringTrim() will trim the specified string from both ends of the string.
CFStringTrimWhitespace() will do the same with white space characters (tab, newline, etc)
CFStringTrim(" abc ", " ") -> "abc"
CFStringTrim("* * * *abc * ", "* ") -> "*abc "
}
procedure CFStringPad( theString: CFMutableStringRef; padString: CFStringRef; length: CFIndex; indexIntoPad: CFIndex ); external name '_CFStringPad';
procedure CFStringTrim( theString: CFMutableStringRef; trimString: CFStringRef ); external name '_CFStringTrim';
procedure CFStringTrimWhitespace( theString: CFMutableStringRef ); external name '_CFStringTrimWhitespace';
{#if MAC_OS_X_VERSION_10_3 <= MAC_OS_X_VERSION_MAX_ALLOWED}
procedure CFStringLowercase( theString: CFMutableStringRef; locale: CFLocaleRef ); external name '_CFStringLowercase';
procedure CFStringUppercase( theString: CFMutableStringRef; locale: CFLocaleRef ); external name '_CFStringUppercase';
procedure CFStringCapitalize( theString: CFMutableStringRef; locale: CFLocaleRef ); external name '_CFStringCapitalize';
{#else}
//procedure CFStringLowercase( theString: CFMutableStringRef; localeTBD: {const} UnivPtr ); // localeTBD must be NULL on pre-10.3
//procedure CFStringUppercase( theString: CFMutableStringRef; localeTBD: {const} UnivPtr ); // localeTBD must be NULL on pre-10.3
//procedure CFStringCapitalize( theString: CFMutableStringRef; localeTBD: {const} UnivPtr ); // localeTBD must be NULL on pre-10.3
{#endif}
{#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED}
{!
@typedef CFStringNormalizationForm
This is the type of Unicode normalization forms as described in
Unicode Technical Report #15.
}
type
CFStringNormalizationForm = SInt32;
const
kCFStringNormalizationFormD = 0; // Canonical Decomposition
kCFStringNormalizationFormKD = 1; // Compatibility Decomposition
kCFStringNormalizationFormC = 2; // Canonical Decomposition followed by Canonical Composition
kCFStringNormalizationFormKC = 3; // Compatibility Decomposition followed by Canonical Composition
{!
@function CFStringNormalize
Normalizes the string into the specified form as described in
Unicode Technical Report #15.
@param theString The string which is to be normalized. If this
parameter is not a valid mutable CFString, the behavior is
undefined.
@param theForm The form into which the string is to be normalized.
If this parameter is not a valid CFStringNormalizationForm value,
the behavior is undefined.
}
procedure CFStringNormalize( theString: CFMutableStringRef; theForm: CFStringNormalizationForm ); external name '_CFStringNormalize';
{#endif}
{ Perform string transliteration. The transformation represented by transform (see below for the full list of transforms supported) is applied to the given range of string, modifying it in place. Only the specified range will be modified, but the transform may look at portions of the string outside that range for context. NULL range pointer causes the whole string to be transformed. On return, range is modified to reflect the new range corresponding to the original range. reverse indicates that the inverse transform should be used instead, if it exists. If the transform is successful, true is returned; if unsuccessful, false. Reasons for the transform being unsuccessful include an invalid transform identifier, or attempting to reverse an irreversible transform.
}
function CFStringTransform( strng: CFMutableStringRef; var range: CFRange; transform: CFStringRef; reverse: Boolean ): Boolean; external name '_CFStringTransform';
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{ Transform identifiers for CFStringTransform()
}
var kCFStringTransformStripCombiningMarks: CFStringRef; external name '_kCFStringTransformStripCombiningMarks'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformToLatin: CFStringRef; external name '_kCFStringTransformToLatin'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformFullwidthHalfwidth: CFStringRef; external name '_kCFStringTransformFullwidthHalfwidth'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinKatakana: CFStringRef; external name '_kCFStringTransformLatinKatakana'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinHiragana: CFStringRef; external name '_kCFStringTransformLatinHiragana'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformHiraganaKatakana: CFStringRef; external name '_kCFStringTransformHiraganaKatakana'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformMandarinLatin: CFStringRef; external name '_kCFStringTransformMandarinLatin'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinHangul: CFStringRef; external name '_kCFStringTransformLatinHangul'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinArabic: CFStringRef; external name '_kCFStringTransformLatinArabic'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinHebrew: CFStringRef; external name '_kCFStringTransformLatinHebrew'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinThai: CFStringRef; external name '_kCFStringTransformLatinThai'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinCyrillic: CFStringRef; external name '_kCFStringTransformLatinCyrillic'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformLatinGreek: CFStringRef; external name '_kCFStringTransformLatinGreek'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformToXMLHex: CFStringRef; external name '_kCFStringTransformToXMLHex'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
var kCFStringTransformToUnicodeName: CFStringRef; external name '_kCFStringTransformToUnicodeName'; (* attribute const *)
(* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *)
{** General encoding related functionality **}
{ This returns availability of the encoding on the system
}
function CFStringIsEncodingAvailable( encoding: CFStringEncoding ): Boolean; external name '_CFStringIsEncodingAvailable';
{ This function returns list of available encodings. The returned list is terminated with kCFStringEncodingInvalidId and owned by the system.
}
function CFStringGetListOfAvailableEncodings: CFStringEncodingPtr; external name '_CFStringGetListOfAvailableEncodings';
{ Returns name of the encoding; non-localized.
}
function CFStringGetNameOfEncoding( encoding: CFStringEncoding ): CFStringRef; external name '_CFStringGetNameOfEncoding';
{ ID mapping functions from/to Cocoa NSStringEncoding. Returns kCFStringEncodingInvalidId if no mapping exists.
}
function CFStringConvertEncodingToNSStringEncoding( encoding: CFStringEncoding ): UInt32; external name '_CFStringConvertEncodingToNSStringEncoding';
function CFStringConvertNSStringEncodingToEncoding( encoding: UInt32 ): CFStringEncoding; external name '_CFStringConvertNSStringEncodingToEncoding';
{ ID mapping functions from/to Microsoft Windows codepage (covers both OEM & ANSI). Returns kCFStringEncodingInvalidId if no mapping exists.
}
function CFStringConvertEncodingToWindowsCodepage( encoding: CFStringEncoding ): UInt32; external name '_CFStringConvertEncodingToWindowsCodepage';
function CFStringConvertWindowsCodepageToEncoding( codepage: UInt32 ): CFStringEncoding; external name '_CFStringConvertWindowsCodepageToEncoding';
{ ID mapping functions from/to IANA registery charset names. Returns kCFStringEncodingInvalidId if no mapping exists.
}
function CFStringConvertIANACharSetNameToEncoding( theString: CFStringRef ): CFStringEncoding; external name '_CFStringConvertIANACharSetNameToEncoding';
function CFStringConvertEncodingToIANACharSetName( encoding: CFStringEncoding ): CFStringRef; external name '_CFStringConvertEncodingToIANACharSetName';
{ Returns the most compatible MacOS script value for the input encoding }
{ i.e. kCFStringEncodingMacRoman -> kCFStringEncodingMacRoman }
{ kCFStringEncodingWindowsLatin1 -> kCFStringEncodingMacRoman }
{ kCFStringEncodingISO_2022_JP -> kCFStringEncodingMacJapanese }
function CFStringGetMostCompatibleMacStringEncoding( encoding: CFStringEncoding ): CFStringEncoding; external name '_CFStringGetMostCompatibleMacStringEncoding';
{ The next two functions allow fast access to the contents of a string,
assuming you are doing sequential or localized accesses. To use, call
CFStringInitInlineBuffer() with a CFStringInlineBuffer (on the stack, say),
and a range in the string to look at. Then call CFStringGetCharacterFromInlineBuffer()
as many times as you want, with a index into that range (relative to the start
of that range). These are INLINE functions and will end up calling CFString only
once in a while, to fill a buffer. CFStringGetCharacterFromInlineBuffer() returns 0 if
a location outside the original range is specified.
}
const
__kCFStringInlineBufferLength = 64;
type
CFStringInlineBuffer = record
buffer: array[0..__kCFStringInlineBufferLength-1] of UniChar;
theString: CFStringRef;
directBuffer: UniCharPtr;
rangeToBuffer: CFRange; { Range in string to buffer }
bufferedRangeStart: CFIndex; { Start of range currently buffered (relative to rangeToBuffer.location) }
bufferedRangeEnd: CFIndex; { bufferedRangeStart + number of chars actually buffered }
end;
// Not currently converted to Pascal
// #if defined(CF_INLINE)
// CF_INLINE void CFStringInitInlineBuffer(CFStringRef str, CFStringInlineBuffer *buf, CFRange range) {
// buf->theString = str;
// buf->rangeToBuffer = range;
// buf->directBuffer = CFStringGetCharactersPtr(str);
// buf->bufferedRangeStart = buf->bufferedRangeEnd = 0;
// }
//
// CF_INLINE UniChar CFStringGetCharacterFromInlineBuffer(CFStringInlineBuffer *buf, CFIndex idx) {
// if (buf->directBuffer) {
// if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0;
// return buf->directBuffer[idx + buf->rangeToBuffer.location];
// }
// if (idx >= buf->bufferedRangeEnd || idx < buf->bufferedRangeStart) {
// if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0;
// if ((buf->bufferedRangeStart = idx - 4) < 0) buf->bufferedRangeStart = 0;
// buf->bufferedRangeEnd = buf->bufferedRangeStart + __kCFStringInlineBufferLength;
// if (buf->bufferedRangeEnd > buf->rangeToBuffer.length) buf->bufferedRangeEnd = buf->rangeToBuffer.length;
// CFStringGetCharacters(buf->theString, CFRangeMake(buf->rangeToBuffer.location + buf->bufferedRangeStart, buf->bufferedRangeEnd - buf->bufferedRangeStart), buf->buffer);
// }
// return buf->buffer[idx - buf->bufferedRangeStart];
// }
//
// #else
// { If INLINE functions are not available, we do somewhat less powerful macros that work similarly (except be aware that the buf argument is evaluated multiple times).
// }
// #define CFStringInitInlineBuffer(str, buf, range) \
// do {(buf)->theString = str; (buf)->rangeToBuffer = range; (buf)->directBuffer = CFStringGetCharactersPtr(str);} while (0)
//
// #define CFStringGetCharacterFromInlineBuffer(buf, idx) \
// (((idx) < 0 || (idx) >= (buf)->rangeToBuffer.length) ? 0 : ((buf)->directBuffer ? (buf)->directBuffer[(idx) + (buf)->rangeToBuffer.location] : CFStringGetCharacterAtIndex((buf)->theString, (idx) + (buf)->rangeToBuffer.location)))
//
// #endif { CF_INLINE }
{ Rest of the stuff in this file is private and should not be used directly
}
{ For debugging only
Use CFShow() to printf the description of any CFType;
Use CFShowStr() to printf detailed info about a CFString
}
procedure CFShow( obj: CFTypeRef ); external name '_CFShow';
procedure CFShowStr( str: CFStringRef ); external name '_CFShowStr';
{ This function is private and should not be used directly }
function __CFStringMakeConstantString( cStr: ConstCStringPtr ): CFStringRef; external name '___CFStringMakeConstantString'; { Private; do not use }
implementation
end.
|
unit glr_tween;
interface
uses
glr_utils,
glr_math;
type
TglrVarType = (vtInteger, vtSingle, vtVector);
PglrInteger = ^Integer;
PglrSingle = PSingle;
TglrTweenObject = TObject;
TglrEasingFunc = function(aStartValue, aDiffValue, aUnitValue: Single): Single of object;
TglrTweenStyle = (tsElasticEaseIn, tsElasticEaseOut, tsExpoEaseIn, tsBounce, tsSimple);
TglrSetSingle = procedure(aObject: TglrTweenObject; aValue: Single) of object;
TglrDoneCallback = procedure of object;
TglrBaseTweenItem = class
protected
FPaused: Boolean;
FTime: Single;
FPauseOnStart: Single;
FDone: Boolean;
FOnDone: TglrDoneCallback;
FDuration: Single;
protected
FEasingFunc: TglrEasingFunc;
function GetUnitValue(): Single; virtual;
function ShouldChange(): Boolean;
public
property Done: Boolean read FDone;
property OnDone: TglrDoneCallback read FOnDone write FOnDone;
procedure Play; virtual;
procedure Pause; virtual;
procedure SetPause(const aPause: Boolean); virtual;
procedure Update(const aDeltaTime: Single); virtual;
constructor Create(aDuration: Single; aPauseOnStart: Single);
end;
TglrBaseSingleTweenItem = class (TglrBaseTweenItem)
protected
FStartValue, FFinishValue: Single;
public
constructor Create(aStartValue, aFinishValue, aDuration: Single;
aPauseOnStart: Single);
end;
TglrPSingleTweenItem = class (TglrBaseSingleTweenItem)
protected
FValue: PglrSingle;
public
procedure Update(const aDeltaTime: Single); override;
constructor Create(aValue: PglrSingle; aStartValue, aFinishValue,
aDuration: Single; aPauseOnStart: Single);
end;
TglrSingleTweenItem = class (TglrBaseSingleTweenItem)
protected
FSetSingleEvent: TglrSetSingle;
FObject: TglrTweenObject;
public
property SetSingleEvent: TglrSetSingle read FSetSingleEvent write FSetSingleEvent;
procedure Update(const aDeltaTime: Single); override;
constructor Create(aObject: TglrTweenObject; aEvent: TglrSetSingle;
aStartValue, aFinishValue, aDuration: Single; aPauseOnStart: Single);
end;
TglrBaseVectorTweenItem = class (TglrBaseTweenItem)
protected
FStartValue, FFinishValue: TglrVec3f;
public
constructor Create(aStartValue, aFinishValue: TglrVec3f; aDuration: Single;
aPauseOnStart: Single);
end;
TglrPVectorTweenItem = class (TglrBaseVectorTweenItem)
protected
FValue: PglrVec3f;
public
procedure Update(const aDeltaTime: Single); override;
constructor Create(aValue: PglrVec3f; aStartValue, aFinishValue: TglrVec3f;
aDuration: Single; aPauseOnStart: Single);
end;
TglrBaseEasingFunctions = class
public
class function ExpoEaseIn(aStartValue, aDiffValue, aUnitValue: Single): Single;
class function QuintEaseOut(aStartValue, aDiffValue, aUnitValue: Single): Single;
class function ElasticEaseIn(aStartValue, aDiffValue, aUnitValue: Single): Single;
class function Simple(aStartValue, aDiffValue, aUnitValue: Single): Single;
end;
{ TglrTweener }
TglrTweener = class
protected
FTweenItems: TglrList<Pointer>;
FEasingFunctions: TglrBaseEasingFunctions;
function GetTweenCount: Integer;
public
property TweenCount: Integer read GetTweenCount;
// манипуляция с элементами списка
function GetItemByIndex(const aIndex: integer): TglrBaseTweenItem;
procedure FreeByIndex(const aIndex: integer);
procedure FreeAll;
function AddTweenItem(aTweenItem: TglrBaseTweenItem; aTweenStyle: TglrTweenStyle): Integer; virtual;
// добавление типовых элементов
function AddTweenPSingle(aVariable: PglrSingle; aTweenStyle: TglrTweenStyle;
const aStartValue, aFinishValue, aDuration: Single;
const aPauseOnStart: Single = 0;
aOnDone: TglrDoneCallback = nil): TglrPSingleTweenItem;
function AddTweenPVector(aVariable: PglrVec3f; aTweenStyle: TglrTweenStyle;
const aStartValue, aFinishValue: TglrVec3f; aDuration: Single;
const aPauseOnStart: Single = 0;
aOnDone: TglrDoneCallback = nil): TglrPVectorTweenItem;
function AddTweenSingle(aObject: TglrTweenObject; aSetValue: TglrSetSingle; aTweenStyle: TglrTweenStyle;
const aStartValue, aFinishValue, aDuration: Single;
const aPauseOnStart: Single = 0;
aOnDone: TglrDoneCallback = nil): TglrSingleTweenItem;
procedure Update(const aDeltaTime: Single);
constructor Create;
destructor Destroy; override;
end;
implementation
function TglrBaseTweenItem.GetUnitValue: Single;
begin
if FTime <= FPauseOnStart then
Result := 0
else if FTime = FDuration + FPauseOnStart then
Result := 1
else
Result := (FTime - FPauseOnStart) / FDuration;
end;
function TglrBaseTweenItem.ShouldChange: Boolean;
begin
Result := FTime >= FPauseOnStart;
end;
Procedure TglrBaseTweenItem.Play;
begin
SetPause(False);
end;
procedure TglrBaseTweenItem.Pause;
begin
SetPause(True);
end;
procedure TglrBaseTweenItem.SetPause(const aPause: Boolean);
begin
FPaused := aPause;
end;
procedure TglrBaseTweenItem.Update(const aDeltaTime: Single);
begin
if FPaused then
Exit;
FTime := FTime + aDeltaTime;
if FTime - FPauseOnStart >= FDuration then
begin
FTime := FDuration + FPauseOnStart;
FDone := True;
Pause;
if Assigned(FOnDone) then
FOnDone()
end;
end;
constructor TglrBaseTweenItem.Create(aDuration: Single; aPauseOnStart: Single);
begin
inherited Create;
FDuration := aDuration;
FPauseOnStart := aPauseOnStart;
FTime := 0;
FDone := False;
end;
constructor TglrBaseSingleTweenItem.Create(aStartValue, aFinishValue,
aDuration: Single; aPauseOnStart: Single);
begin
inherited Create(aDuration, aPauseOnStart);
FStartValue := aStartValue;
FFinishValue := aFinishValue;
end;
procedure TglrPSingleTweenItem.Update(const aDeltaTime: Single);
begin
inherited Update(aDeltaTime);
if Assigned(FEasingFunc) then
FValue^ := FEasingFunc(FStartValue, FFinishValue - FStartValue, GetUnitValue);
end;
constructor TglrPSingleTweenItem.Create(aValue: PglrSingle; aStartValue,
aFinishValue, aDuration: Single; aPauseOnStart: Single);
begin
inherited Create(aStartValue, aFinishValue, aDuration, aPauseOnStart);
FValue := aValue;
end;
procedure TglrSingleTweenItem.Update(const aDeltaTime: Single);
begin
inherited Update(aDeltaTime);
if Assigned(FSetSingleEvent) and Assigned(FEasingFunc) then
FSetSingleEvent(FObject, FEasingFunc(FStartValue, FFinishValue - FStartValue, GetUnitValue));
end;
constructor TglrSingleTweenItem.Create(aObject: TglrTweenObject; aEvent: TglrSetSingle;
aStartValue, aFinishValue, aDuration: Single; aPauseOnStart: Single);
begin
inherited Create(aStartValue, aFinishValue, aDuration, aPauseOnStart);
FObject := aObject;
FSetSingleEvent := aEvent;
end;
constructor TglrBaseVectorTweenItem.Create(aStartValue, aFinishValue: TglrVec3f;
aDuration: Single; aPauseOnStart: Single);
begin
inherited Create(aDuration, aPauseOnStart);
FStartValue := aStartValue;
FFinishValue := aFinishValue;
end;
procedure TglrPVectorTweenItem.Update(const aDeltaTime: Single);
begin
inherited Update(aDeltaTime);
if Assigned(FEasingFunc) and ShouldChange then
begin
FValue^.x := FEasingFunc(FStartValue.x, FFinishValue.x - FStartValue.x, GetUnitValue);
FValue^.y := FEasingFunc(FStartValue.y, FFinishValue.y - FStartValue.y, GetUnitValue);
FValue^.z := FEasingFunc(FStartValue.z, FFinishValue.z - FStartValue.z, GetUnitValue);
end;
end;
constructor TglrPVectorTweenItem.Create(aValue: PglrVec3f; aStartValue, aFinishValue: TglrVec3f;
aDuration: Single; aPauseOnStart: Single);
begin
inherited Create(aStartValue, aFinishValue, aDuration, aPauseOnStart);
FValue := aValue;
end;
class function TglrBaseEasingFunctions.ExpoEaseIn(aStartValue, aDiffValue, aUnitValue: Single): Single;
begin
if (aUnitValue = 1) then
Result := aStartValue + aDiffValue
else
Result := aDiffValue * (-Pow(2, -15*aUnitValue) + 1) + aStartValue;
end;
class function TglrBaseEasingFunctions.QuintEaseOut(aStartValue, aDiffValue, aUnitValue: Single): Single;
begin
Result := aStartValue;
end;
class function TglrBaseEasingFunctions.Simple(aStartValue, aDiffValue,
aUnitValue: Single): Single;
begin
if aUnitValue = 1 then
Result := aStartValue + aDiffValue
else
Result := aStartValue + aDiffValue * aUnitValue;
end;
class function TglrBaseEasingFunctions.ElasticEaseIn(aStartValue, aDiffValue, aUnitValue: Single): Single;
begin
if (aDiffValue = 0) or (aUnitValue = 0) or (aUnitValue = 1) then
begin
if (aUnitValue = 1) then
Result := aStartValue + aDiffValue
else
Result := aStartValue;
Exit;
end;
Result := (aDiffValue * Pow(2, -10 * aUnitValue) * Sin((aUnitValue - 0.25/4)*(2*3.14)/0.25)) + aDiffValue + aStartValue;
end;
function TglrTweener.GetTweenCount: Integer;
begin
Result := FTweenItems.Count;
end;
function TglrTweener.GetItemByIndex(const aIndex: integer): TglrBaseTweenItem;
begin
Result := TglrBaseTweenItem(FTweenItems[aIndex]);
end;
procedure TglrTweener.FreeByIndex(const aIndex: integer);
var
TweenItem: TglrBaseTweenItem;
begin
TweenItem := GetItemByIndex(aIndex);
TweenItem.Free();
FTweenItems.DeleteByIndex(aIndex);
end;
procedure TglrTweener.FreeAll;
begin
{TODO: rewrite}
while FTweenItems.Count > 0 do
FreeByIndex(0);
end;
function TglrTweener.AddTweenItem(aTweenItem: TglrBaseTweenItem; aTweenStyle: TglrTweenStyle): Integer;
begin
case aTweenStyle of
tsElasticEaseIn: aTweenItem.FEasingFunc := FEasingFunctions.ElasticEaseIn;
tsElasticEaseOut: aTweenItem.FEasingFunc := FEasingFunctions.ElasticEaseIn;
tsExpoEaseIn: aTweenItem.FEasingFunc := FEasingFunctions.ExpoEaseIn;
tsBounce: aTweenItem.FEasingFunc := FEasingFunctions.ElasticEaseIn;
tsSimple: aTweenItem.FEasingFunc := FEasingFunctions.Simple;
end;
Result := FTweenItems.Add(aTweenItem);
end;
function TglrTweener.AddTweenPSingle(aVariable: PglrSingle;
aTweenStyle: TglrTweenStyle; const aStartValue, aFinishValue,
aDuration: Single; const aPauseOnStart: Single; aOnDone: TglrDoneCallback
): TglrPSingleTweenItem;
begin
Result := TglrPSingleTweenItem.Create(aVariable, aStartValue, aFinishValue, aDuration, aPauseOnStart);
Result.OnDone := aOnDone;
AddTweenItem(Result, aTweenStyle);
end;
function TglrTweener.AddTweenPVector(aVariable: PglrVec3f;
aTweenStyle: TglrTweenStyle; const aStartValue, aFinishValue: TglrVec3f;
aDuration: Single; const aPauseOnStart: Single; aOnDone: TglrDoneCallback
): TglrPVectorTweenItem;
begin
Result := TglrPVectorTweenItem.Create(aVariable, aStartValue, aFinishValue, aDuration, aPauseOnStart);
Result.OnDone := aOnDone;
AddTweenItem(Result, aTweenStyle);
end;
function TglrTweener.AddTweenSingle(aObject: TglrTweenObject;
aSetValue: TglrSetSingle; aTweenStyle: TglrTweenStyle; const aStartValue,
aFinishValue, aDuration: Single; const aPauseOnStart: Single;
aOnDone: TglrDoneCallback): TglrSingleTweenItem;
begin
Result := TglrSingleTweenItem.Create(aObject, aSetValue, aStartValue, aFinishValue, aDuration, aPauseOnStart);
Result.OnDone := aOnDone;
AddTweenItem(Result, aTweenStyle);
end;
//------------------------------------------------------------------------------
procedure TglrTweener.Update(const aDeltaTime: Single);
var
i: integer;
item: TglrBaseTweenItem;
begin
{TODO: do not delete, sent to accum}
i := 0;
while (i < TweenCount)do
begin
item := GetItemByIndex(i);
if item.Done then
FreeByIndex(i)
else
begin
item.Update(aDeltaTime);
inc(i);
end;
end;
end;
constructor TglrTweener.Create;
begin
inherited Create;
FTweenItems := TglrList<Pointer>.Create;
FEasingFunctions := TglrBaseEasingFunctions.Create;
end;
destructor TglrTweener.Destroy;
begin
FreeAll;
FEasingFunctions.Free();
FTweenItems.Free();
inherited Destroy;
end;
end.
|
unit K365838449;
{* [RequestLink:365838449] }
// Модуль: "w:\common\components\rtl\Garant\Archi_Tests\K365838449.pas"
// Стереотип: "TestCase"
// Элемент модели: "K365838449" MUID: (4FBB6C4D032B)
// Имя типа: "TK365838449"
{$Include w:\common\components\rtl\Garant\Archi_Tests\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, ArchiStorageTestWithRename
;
type
TK365838449 = class(TArchiStorageTestWithRename)
{* [RequestLink:365838449] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK365838449
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *4FBB6C4D032Bimpl_uses*
//#UC END# *4FBB6C4D032Bimpl_uses*
;
function TK365838449.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Storage';
end;//TK365838449.GetFolder
function TK365838449.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4FBB6C4D032B';
end;//TK365838449.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK365838449.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clUserMgr;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils;
{$ELSE}
System.Classes, System.SysUtils;
{$ENDIF}
type
TclUserAccountItem = class(TCollectionItem)
private
FPassword: string;
FUserName: string;
FDisplayName: string;
public
function Authenticate(const APassword: string): Boolean;
procedure Assign(Source: TPersistent); override;
published
property UserName: string read FUserName write FUserName;
property Password: string read FPassword write FPassword;
property DisplayName: string read FDisplayName write FDisplayName;
end;
TclUserAccountList = class(TOwnedCollection)
private
FCaseInsensitive: Boolean;
protected
function GetItem(Index: Integer): TclUserAccountItem;
procedure SetItem(Index: Integer; const Value: TclUserAccountItem);
public
procedure Assign(Source: TPersistent); override;
function Add: TclUserAccountItem;
function AccountByUserName(const AUserName: string): TclUserAccountItem;
property Items[Index: Integer]: TclUserAccountItem read GetItem write SetItem; default;
property CaseInsensitive: Boolean read FCaseInsensitive write FCaseInsensitive;
end;
implementation
{ TclUserAccountList }
function TclUserAccountList.AccountByUserName(const AUserName: string): TclUserAccountItem;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if CaseInsensitive then
begin
if SameText(Result.UserName, AUserName) then Exit;
end else
begin
if (Result.UserName = AUserName) then Exit;
end;
end;
Result := nil;
end;
function TclUserAccountList.Add: TclUserAccountItem;
begin
Result := TclUserAccountItem(inherited Add());
end;
procedure TclUserAccountList.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if (Source is TclUserAccountList) then
begin
CaseInsensitive := (Source as TclUserAccountList).CaseInsensitive;
end;
end;
function TclUserAccountList.GetItem(Index: Integer): TclUserAccountItem;
begin
Result := TclUserAccountItem(inherited GetItem(Index));
end;
procedure TclUserAccountList.SetItem(Index: Integer; const Value: TclUserAccountItem);
begin
inherited SetItem(Index, Value);
end;
{ TclUserAccountItem }
procedure TclUserAccountItem.Assign(Source: TPersistent);
var
account: TclUserAccountItem;
begin
if (Source is TclUserAccountItem) then
begin
account := (Source as TclUserAccountItem);
FPassword := account.Password;
FUserName := account.UserName;
FDisplayName := account.DisplayName;
end else
begin
inherited Assign(Source);
end;
end;
function TclUserAccountItem.Authenticate(const APassword: string): Boolean;
begin
if (Collection as TclUserAccountList).CaseInsensitive then
begin
Result := SameText(Password, APassword);
end else
begin
Result := (Password = APassword);
end;
end;
end.
|
unit TjwStrUtil;
interface
function StrHasSuffix(S, Suffix: String): Boolean;
// Returns A + B, except Sep is interposed if both A and B are nonempty.
function ConcatWithSep(A, B: string; Sep: string = ' '): String;
// Returns true if S is Prefix plus an optional numeric suffix, separated by Sep.
function IsPrefixPlusIntegerSuffix(S, Prefix: String; Sep: String = ' '): Boolean;
// Returns the integer suffix from S, or DefValue if it has none.
function GetIntegerSuffix(S: String; DefValue: Integer = -1): Integer;
// If the given string has an integer suffix, increment it.
// Otherwise, give it a suffix of '1', with the given separator.
function IncrementIntegerSuffix(S: String; Sep: String = ' '): String;
{ Models the returned string after the given model string.
Model values:
1: Arabic numbers
i: Roman numbers, lowercase
I: Roman numbers, uppercase
a: Latin alphabet, lowercase; double (treble...) them for duplicates
A: Latin alphabet, uppercase
'': nothing is returned
In all cases, 1 becomes the element listed.
}
{$ifdef USE_VCL}
function IntToStrModeled(Value: Integer; Model: String): String;
{$endif USE_VCL}
{ Converts a standard one-word code identifier into a phrase for display.
Breaks words at changes in capitalization and at underscores, and
capitalizes the following word.
Omits a single initial capital T followed by another capital letter followed
by a lower case letter.
(for use with Delphi classes).
E.g.:
TMyClass -> My Class
ThisThing_One -> This Thing One
TLASet -> TLA Set
AnotherTLA -> Another TLA
XYZZY -> XYZZY
}
function DisplayFromID(ID: String): String;
// There's also JclHasPrefix/Suffix from JclStrings,
// but that requires an array. This has slightly better syntax and performance when you only have one prefix.
function HasPrefix(S: string; Prefix: string): Boolean;
function HasSuffix(S: string; Suffix: string): Boolean;
// Removes Prefix or Suffix from S if found.
// Returns S, as modified.
function RemovePrefix(const S, Prefix: String): String;
function RemoveSuffix(const S, Suffix: String): String;
// If S doesn't end with Suffix, add it. Return the result.
function EnsureSuffix(const S, Suffix: string): string;
// Trims the string so it contains no more than MaxLen characters.
// If AtSpace is true, tries to trim at whitespace if there is any.
// Always ends the string with an ellipsis if something was trimmed.
// (So, values of MaxLen < 3 may be violated.)
function TrimWithEllipsis(S: String; MaxLen: Integer; AtSpace: Boolean = true): String;
// Converts all substrings of whitespace characters into a single character.
function ConsolidateWhitespace(S: String): String;
// Simple shorthand functions for simple situations.
function FirstChar(S: String): Char;
function LastChar(S: String): Char;
function DeleteLastChar(S: String): String;
function DeleteFirstChar(S: String): String;
// Returns the length of the prefix or suffix that the two strings have in common.
// Uses case-sensitive matching.
function CommonPrefixLen(const A, B: string): Integer;
function CommonSuffixLen(const A, B: string): Integer;
// Returns S with any control characters deleted.
function RemoveControlChars(const S: string): string;
// Returns S in Title case.
// At present, just capitalizes the first character and lowercases the rest - no subsequent words.
function TitleCase(const S: string): string;
implementation
uses StrUtils, SysUtils, JclStrings, Math, CType
{$ifdef USE_VCL}
, JvJclUtils, JvStrings
{$endif}
;
function StrHasSuffix(S, Suffix: String): Boolean;
begin
Result := Copy(S, Length(S) - Length(Suffix) + 1, Length(Suffix)) = Suffix
end;
function ConcatWithSep(A, B: string; Sep: string = ' '): String;
begin
if (A <> '') and (B <> '') then
Result := A + Sep + B
else
Result := A + B
end;
function IsPrefixPlusIntegerSuffix(S, Prefix: String; Sep: String = ' '): Boolean;
begin
Result := (S = Prefix)
or (
StrHasPrefix(S, [Prefix + Sep])
and StrConsistsofNumberChars(Copy(S, Length(Prefix) + Length(Sep) + 1, Length(S)))
)
end;
function GetIntegerSuffix(S: String; DefValue: Integer = -1): Integer;
var
suffixIndex, place: Integer;
begin
// Look for an existing suffix.
Result := 0;
place := 1;
suffixIndex := Length(S) + 1;
while (suffixIndex > 1) and (CharIsNumberChar(S[suffixIndex - 1])) do begin
Inc(Result, (Ord(S[suffixIndex - 1]) - Ord('0')) * place);
Dec(suffixIndex);
place := place * 10;
end;
if suffixIndex > Length(S) then
// No suffix was found.
Result := DefValue
end;
function IncrementIntegerSuffix(S: String; Sep: String = ' '): String;
var
suffixIndex, suffixValue, place: Integer;
begin
// Look for an existing suffix.
suffixValue := 0;
place := 1;
suffixIndex := Length(S) + 1;
while (suffixIndex > 1) and (CharIsNumberChar(S[suffixIndex - 1])) do begin
Inc(suffixValue, (Ord(S[suffixIndex - 1]) - Ord('0')) * place);
Dec(suffixIndex);
place := place * 10;
end;
if suffixIndex > Length(S) then
// No suffix was found.
// Add one.
Result := ConcatWithSep(S, '1', Sep)
else
// There is an existing numeric suffix.
// Replace it.
Result := Copy(S, 1, suffixIndex - 1) + IntToStr(suffixValue + 1);
end;
{$ifdef USE_VCL}
function IntToStrModeled(Value: Integer; Model: String): String;
begin
if Model = '' then
Result := ''
else
case Model[1] of
'a', 'A': Result := DupeString(Chr(Ord(Model[1]) + (Value - 1) mod 26), (Value - 1) div 26 + 1);
'i': Result := LowerCase(IntToRoman(Value));
'I': Result := UpperCase(IntToRoman(Value));
else
Result := IntToStr(Value);
end;
end;
{$endif USE_VCL}
function DisplayFromID(ID: String): String;
var
i: Integer;
lastWasInsertedSpace, lastWasUpper: Boolean;
procedure AddChar(C: Char);
begin
Result := Result + C;
lastWasInsertedSpace := CharIsSpace(C);
lastWasUpper := CharIsUpper(C);
end;
procedure InsertSpaceIfNotAlready;
begin
if not lastWasInsertedSpace then
AddChar(' ');
end;
begin
Result := '';
lastWasUpper := true;
lastWasInsertedSpace := true;
for i := 1 to Length(ID) do
if (i = 1) and (ID[i] = 'T') and (Length(ID) > 2) and CharIsUpper(ID[2]) and CharIsLower(ID[3]) then
// skip initial 'T' followed by another capital
// |TMyClass -> My Class
else if CharIsUpper(ID[i]) then begin
// We're at:
// T|My|Class -> My Class
// |This|Thing_|One -> This Thing One
// |T|L|A|Set -> TLA Set
// |Another|T|L|A -> Another TLA
// |X|Y|Z|Z|Y -> XYZZY
if (not lastWasUpper)
or ((Length(ID) > i + 1) and CharIsLower(ID[i + 1]))
then
// We're at:
// TMy|Class -> My Class
// This|Thing_|One -> This Thing One
// TLA|Set -> TLA Set
// Another|TLA -> Another TLA
// XYZZY -> XYZZY
InsertSpaceIfNotAlready;
AddChar(ID[i]);
end else if not CharIsAlphaNum(ID[i]) then
// We're at:
// ThisThing|_One -> This Thing One
// ThisThing|_|_One -> This Thing One
InsertSpaceIfNotAlready
else
// Insert everything else.
AddChar(ID[i]);
end;
function HasPrefix(S, Prefix: string): Boolean;
begin
if Length(S) >= Length(Prefix) then
Result := SameText(StrLeft(S, Length(Prefix)), Prefix)
else
Result := False;
end;
function HasSuffix(S, Suffix: string): Boolean;
begin
if Length(S) >= Length(Suffix) then
Result := SameText(StrRight(S, Length(Suffix)), Suffix)
else
Result := False;
end;
function RemovePrefix(const S, Prefix: String): string;
begin
if HasPrefix(S, Prefix) then
Result := Copy(S, Length(Prefix) + 1)
else
Result := S;
end;
function RemoveSuffixLen(const S: string; SuffixLen: longint): string;
begin
Result := Copy(S, 1, length(S) - SuffixLen);
end;
function RemoveSuffix(const S, Suffix: string): string;
begin
if HasSuffix(S, Suffix) then
Result := RemoveSuffixLen(S, Length(Suffix))
else
Result := S;
end;
function EnsureSuffix(const S, Suffix: string): string;
begin
if not HasSuffix(S, Suffix) then
Result := S + Suffix
else
Result := S;
end;
function TrimWithEllipsis(S: String; MaxLen: Integer; AtSpace: Boolean = true): String;
const
ellipsis = '...';
var
i: Integer;
begin
if Length(S) > MaxLen then begin
for i := MaxLen - Length(ellipsis) downto 1 do
if (not AtSpace) or CharIsWhiteSpace(S[i]) then begin
Result := TrimLeft(Copy(S, 1, i-1)) + ellipsis;
Exit;
end;
// Couldn't find any whitespace.
// Just hack it off.
Result := Copy(S, 1, MaxLen - Length(ellipsis)) + ellipsis;
end else
Result := S;
end;
function ConsolidateWhitespace(S: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
if CharIsWhiteSpace(S[i]) then begin
if (Result = '') or (LastChar(Result) <> ' ') then
Result := Result + ' '
end else
Result := Result + S[i];
end;
function FirstChar(S: String): Char;
begin
Result := S[1]
end;
function LastChar(S: String): Char;
begin
Result := S[Length(S)]
end;
function DeleteLastChar(S: String): String;
begin
Result := Copy(S, 1, Length(S) - 1);
end;
function DeleteFirstChar(S: String): String;
begin
Result := Copy(S, 2, Length(S) - 1);
end;
function CommonPrefixLen(const A, B: string): Integer;
var
maxI: Integer;
begin
maxI := Min(Length(A), Length(B));
Result := 0;
while Result < maxI do
if A[Result + 1] <> B[Result + 1] then
Exit
else
Inc(Result);
end;
function CommonSuffixLen(const A, B: string): Integer;
var
maxI: Integer;
begin
maxI := Min(Length(A), Length(B));
Result := 0;
while Result < maxI do
if A[Length(A) - 1 - Result] <> B[Length(B) - 1 - Result] then
Exit
else
Inc(Result);
end;
function RemoveControlChars(const S: string): string;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
if S[i] >= ' ' then
Result := Result + S[i];
end;
function TitleCase(const S: string): string;
begin
if Length(S) = 0 then
Result := ''
else if Length(S) = 1 then
Result := StrUpper(S)
else
Result := StrUpper(S[1]) + StrLower(StrRestOf(S, 2));
end;
end.
|
unit PrintRowHeightsSpy;
{* Проверяльщик высот строк на разных страницах }
// Модуль: "w:\common\components\gui\Garant\Everest\new\PrintRowHeightsSpy.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "PrintRowHeightsSpy" MUID: (4DF1C6E90221)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
{$If Defined(nsTest)}
uses
l3IntfUses
, l3ProtoDataContainer
, l3Memory
, l3Types
, l3Interfaces
, l3Core
, l3Except
, Classes
, l3ProtoObject
, l3Filer
;
type
TRowHeight = record
rTableID: Integer;
rRowID: Integer;
rHeight: Integer;
rPage: Integer;
rTopAnchorID: Integer;
end;//TRowHeight
_ItemType_ = TRowHeight;
_l3RecordListPrim_Parent_ = Tl3ProtoDataContainer;
{$Define l3Items_IsProto}
{$Include w:\common\components\rtl\Garant\L3\l3RecordListPrim.imp.pas}
TRowHeightsList = class(_l3RecordListPrim_)
end;//TRowHeightsList
TPrintRowHeightsSpy = class(Tl3ProtoObject)
{* Следилка за высотами строк на разных страницах }
private
f_Filer: Tl3CustomFiler;
public
f_RowHeights: TRowHeightsList;
protected
procedure Release; override;
procedure BeforeAddToCache; override;
{* функция, вызываемая перед добавлением объекта в кэш повторного использования. }
public
procedure AddRowData(const aData: TRowHeight);
{* Добавить данные о высоте строки. }
procedure ClearData;
{* Очистить данные о строках. }
class function ExistsAndValid: Boolean;
procedure StartLogging(const aLogName: AnsiString);
procedure StopLogging;
class function Instance: TPrintRowHeightsSpy;
{* Метод получения экземпляра синглетона TPrintRowHeightsSpy }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
end;//TPrintRowHeightsSpy
{$IfEnd} // Defined(nsTest)
implementation
{$If Defined(nsTest)}
uses
l3ImplUses
, l3Base
, l3MinMax
, RTLConsts
, SysUtils
, evConst
//#UC START# *4DF1C6E90221impl_uses*
//#UC END# *4DF1C6E90221impl_uses*
;
var g_TPrintRowHeightsSpy: TPrintRowHeightsSpy = nil;
{* Экземпляр синглетона TPrintRowHeightsSpy }
procedure TPrintRowHeightsSpyFree;
{* Метод освобождения экземпляра синглетона TPrintRowHeightsSpy }
begin
l3Free(g_TPrintRowHeightsSpy);
end;//TPrintRowHeightsSpyFree
{$If Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)}
procedure AssignItem(const aTo: _ItemType_;
const aFrom: _ItemType_); forward;
{$IfEnd} // Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)
function CompareExistingItems(const CI: CompareItemsRec): Integer; forward;
{$If NOT Defined(l3Items_IsAtomic)}
function IsSameItems(const A: _ItemType_;
const B: _ItemType_): Boolean;
{* Сравнивает элементы списка }
//#UC START# *47B07CF403D0_4DF1C7F20336_var*
//#UC END# *47B07CF403D0_4DF1C7F20336_var*
begin
//#UC START# *47B07CF403D0_4DF1C7F20336_impl*
Result := (A.rTableID = B.rTableID) and
(A.rRowID = B.rRowID) and (A.rPage = B.rPage);
//#UC END# *47B07CF403D0_4DF1C7F20336_impl*
end;//IsSameItems
{$IfEnd} // NOT Defined(l3Items_IsAtomic)
{$If Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)}
procedure AssignItem(const aTo: _ItemType_;
const aFrom: _ItemType_);
//#UC START# *47B2C42A0163_4DF1C7F20336_var*
//#UC END# *47B2C42A0163_4DF1C7F20336_var*
begin
//#UC START# *47B2C42A0163_4DF1C7F20336_impl*
Assert(false);
//#UC END# *47B2C42A0163_4DF1C7F20336_impl*
end;//AssignItem
{$IfEnd} // Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)
function CompareExistingItems(const CI: CompareItemsRec): Integer;
{* Сравнивает два существующих элемента. }
//#UC START# *47B99D4503A2_4DF1C7F20336_var*
//#UC END# *47B99D4503A2_4DF1C7F20336_var*
begin
//#UC START# *47B99D4503A2_4DF1C7F20336_impl*
Result := CI.rA^.rTableID - CI.rB^.rTableID;
if Result = 0 then
Result := CI.rA^.rRowID - CI.rB^.rRowID;
if Result = 0 then
Result := CI.rA^.rPage - CI.rB^.rPage;
//#UC END# *47B99D4503A2_4DF1C7F20336_impl*
end;//CompareExistingItems
type _Instance_R_ = TRowHeightsList;
{$Include w:\common\components\rtl\Garant\L3\l3RecordListPrim.imp.pas}
procedure TPrintRowHeightsSpy.AddRowData(const aData: TRowHeight);
{* Добавить данные о высоте строки. }
//#UC START# *4DF1C9B1012D_4DF1C7300012_var*
function MangleCoord(aValue : Integer): Integer;
begin
Result := (aValue div 100) * 100;
end;
var
l_Index : Integer;
l_Height : Integer;
l_Delta : Integer;
//#UC END# *4DF1C9B1012D_4DF1C7300012_var*
begin
//#UC START# *4DF1C9B1012D_4DF1C7300012_impl*
if aData.rPage = -1 then Exit;
if f_RowHeights = nil then
f_RowHeights := TRowHeightsList.Create;
if f_RowHeights.FindData(aData, l_Index) then
begin
l_Height := f_RowHeights[l_Index].rHeight;
l_Delta := Abs(l_Height - aData.rHeight);
f_Filer.WriteLn(Format('%d %d %d %d', [aData.rRowID, aData.rPage, MangleCoord(l_Height), MangleCoord(aData.rHeight)]));
if (l_Delta >= 3 * evEpsilon) then
f_Filer.WriteLn(Format('Несовпадают высоты строки %d на странице %d: %d, %d', [aData.rRowID - aData.rTopAnchorID, aData.rPage, MangleCoord(l_Height), MangleCoord(aData.rHeight)]));
end // if f_RowHeights.FindData(aData, l_Index) then
else
f_RowHeights.Add(aData);
//#UC END# *4DF1C9B1012D_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.AddRowData
procedure TPrintRowHeightsSpy.ClearData;
{* Очистить данные о строках. }
//#UC START# *4DF1CA0803E2_4DF1C7300012_var*
//#UC END# *4DF1CA0803E2_4DF1C7300012_var*
begin
//#UC START# *4DF1CA0803E2_4DF1C7300012_impl*
if (f_RowHeights <> nil) and (f_RowHeights.Count > 0) then
begin
f_Filer.WriteLn('Окончание страницы');
f_RowHeights.Clear;
end; // if f_RowHeights <> nil then
//#UC END# *4DF1CA0803E2_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.ClearData
class function TPrintRowHeightsSpy.ExistsAndValid: Boolean;
//#UC START# *4DF1DB350207_4DF1C7300012_var*
//#UC END# *4DF1DB350207_4DF1C7300012_var*
begin
//#UC START# *4DF1DB350207_4DF1C7300012_impl*
Result := (g_TPrintRowHeightsSpy <> nil) and (g_TPrintRowHeightsSpy.f_Filer <> nil);
//#UC END# *4DF1DB350207_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.ExistsAndValid
procedure TPrintRowHeightsSpy.StartLogging(const aLogName: AnsiString);
//#UC START# *4DF8692C0010_4DF1C7300012_var*
//#UC END# *4DF8692C0010_4DF1C7300012_var*
begin
//#UC START# *4DF8692C0010_4DF1C7300012_impl*
Assert(f_Filer = nil);
f_Filer := Tl3CustomDOSFiler.Make(aLogName, l3_fmWrite);
f_Filer.Open;
//#UC END# *4DF8692C0010_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.StartLogging
procedure TPrintRowHeightsSpy.StopLogging;
//#UC START# *4DF869520107_4DF1C7300012_var*
//#UC END# *4DF869520107_4DF1C7300012_var*
begin
//#UC START# *4DF869520107_4DF1C7300012_impl*
try
f_Filer.Close;
finally
l3Free(f_Filer);
end;
//#UC END# *4DF869520107_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.StopLogging
class function TPrintRowHeightsSpy.Instance: TPrintRowHeightsSpy;
{* Метод получения экземпляра синглетона TPrintRowHeightsSpy }
begin
if (g_TPrintRowHeightsSpy = nil) then
begin
l3System.AddExitProc(TPrintRowHeightsSpyFree);
g_TPrintRowHeightsSpy := Create;
end;
Result := g_TPrintRowHeightsSpy;
end;//TPrintRowHeightsSpy.Instance
class function TPrintRowHeightsSpy.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TPrintRowHeightsSpy <> nil;
end;//TPrintRowHeightsSpy.Exists
procedure TPrintRowHeightsSpy.Release;
//#UC START# *479F2AFB0397_4DF1C7300012_var*
//#UC END# *479F2AFB0397_4DF1C7300012_var*
begin
//#UC START# *479F2AFB0397_4DF1C7300012_impl*
l3Free(f_RowHeights);
//#UC END# *479F2AFB0397_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.Release
procedure TPrintRowHeightsSpy.BeforeAddToCache;
{* функция, вызываемая перед добавлением объекта в кэш повторного использования. }
//#UC START# *479F2B3302C1_4DF1C7300012_var*
//#UC END# *479F2B3302C1_4DF1C7300012_var*
begin
//#UC START# *479F2B3302C1_4DF1C7300012_impl*
if f_RowHeights <> nil then
f_RowHeights.Clear;
//#UC END# *479F2B3302C1_4DF1C7300012_impl*
end;//TPrintRowHeightsSpy.BeforeAddToCache
{$IfEnd} // Defined(nsTest)
end.
|
unit uBehaviorInterfaces;
interface
uses
Classes, uUpdateListObserverInterface, uProjectData, IdGlobal;
type
TBaseProjectsDataDisplay = class(TComponent, IUpdateListObserver)
protected
FSubject: TProjectData;
procedure UpdateCheckListBox(const Values: TStrings); virtual; abstract;
public
procedure DisplayData; virtual; abstract;
procedure InitializeDisplayGrid; virtual; abstract;
end;
TProjectsDataDisplay = class(TBaseProjectsDataDisplay)
protected
procedure UpdateCheckListBox(const Values: TStrings); override;
public
constructor Create(aProjectData: TComponent); override;
destructor Destroy; override;
end;
implementation
uses
MainForm, uProjectConstants;
{ TProjectsDataDisplay }
constructor TProjectsDataDisplay.Create(aProjectData: TComponent);
begin
inherited Create(frmTeamCityMonitor);
FSubject := TProjectData(aProjectData);
FSubject.RegisterObserver(Self);
end;
destructor TProjectsDataDisplay.Destroy;
begin
if Assigned(FSubject) then
FreeAndNil(FSubject);
inherited;
end;
procedure TProjectsDataDisplay.UpdateCheckListBox(const Values: TStrings);
begin
inherited;
FSubject.FCheckLBItems.AddStrings(Values);
end;
end.
|
unit tmsUXlsPalette;
{$INCLUDE ..\FLXCOMPILER.INC}
interface
uses Classes, SysUtils, tmsUXlsBaseRecords, tmsUXlsBaseRecordLists, tmsXlsMessages, tmsUFlxMessages;
type
TPaletteRecord= class(TBaseRecord)
private
function GetColor(index: integer): LongWord;
procedure SetColor(index: integer; const Value: LongWord);
function GetCount: word;
public
property Count: word read GetCount;
property Color[index: integer]: LongWord read GetColor write SetColor;
constructor CreateStandard;
end;
function StandardPalette(const Index: integer): LongWord;
implementation
{ TPaletteRecord }
constructor TPaletteRecord.CreateStandard;
var
aData: PArrayOfByte;
aDataSize:integer;
i: integer;
begin
aDataSize:=SizeOf(Word)+High(TColorPaletteRange)*SizeOf(LongWord);
GetMem(aData, aDataSize);
try
SetWord(aData,0,High(TColorPaletteRange));
for i:=Low(TColorPaletteRange)-1 to High(TColorPaletteRange)-1 do SetLongWord(aData,2+i*SizeOf(LongWord), StandardPalette(i));
except
FreeAndNil(aData);
raise;
end; //Except
inherited Create(xlr_PALETTE, aData, aDataSize);
end;
function TPaletteRecord.GetColor(Index: integer): LongWord;
begin
if (Index>=Count) or (Index<0) then raise Exception.CreateFmt(ErrXlsIndexOutBounds,[Index,'Palette Color Index',0, Count-1]);
Result:=GetLongWord(Data, 2+Index*4);
end;
function TPaletteRecord.GetCount: word;
begin
Result:=GetWord(Data, 0);
end;
procedure TPaletteRecord.SetColor(index: integer; const Value: LongWord);
begin
if (Index>=Count) or (Index<0) then raise Exception.CreateFmt(ErrTooManyEntries,[Index, Count-1]);
SetLongWord(Data, 2+Index*4, Value);
end;
function StandardPalette(const Index: integer): LongWord;
const
StdArray: array[Low(TColorPaletteRange)-1..High(TColorPaletteRange)-1] of LongWord=
( 0,
16777215,
255,
65280,
16711680,
65535,
16711935,
16776960,
128,
32768,
8388608,
32896,
8388736,
8421376,
12632256,
8421504,
16751001,
6697881,
13434879,
16777164,
6684774,
8421631,
13395456,
16764108,
8388608,
16711935,
65535,
16776960,
8388736,
128,
8421376,
16711680,
16763904,
16777164,
13434828,
10092543,
16764057,
13408767,
16751052,
10079487,
16737843,
13421619,
52377,
52479,
39423,
26367,
10053222,
9868950,
6697728,
6723891,
13056,
13107,
13209,
6697881,
10040115,
3355443);
begin
if (Index<0) or (Index>High(TColorPaletteRange)-1) then Raise Exception.CreateFmt(ErrXlsIndexOutBounds,[Index,'Palette index' ,0,High(TColorPaletteRange)-1]);
Result:= StdArray[Index];
end;
end.
|
unit JustifyDemoForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm1 = class(TForm)
memoTyping: TMemo;
Panel1: TPanel;
paintJustification: TPaintBox;
chkJustifyTrailing: TCheckBox;
lblRectHeight: TLabel;
chkDrawRect: TCheckBox;
btnFont: TButton;
dlgFont: TFontDialog;
chkManual: TCheckBox;
lblTypeHeading: TLabel;
lblPreviewHeading: TLabel;
lblManualExplanation: TLabel;
lblManualUsed: TLabel;
chkJustifySingleWords: TCheckBox;
procedure memoTypingChange(Sender: TObject);
procedure paintJustificationPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure chkInvalidateClick(Sender: TObject);
procedure btnFontClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
JustifiedDrawText;
function SupportsJustification(const Canvas : TCanvas) : Boolean;
var
Metrics : TTextMetric;
SupportsJustification : Boolean;
begin
// This is actually decided inside the JustifiedDrawText unit, but to keep encapsulation for
// demo UI purposes it's rewritten here. Normally there is no need to know which method the
// unit internally decides to use.
GetTextMetrics(Canvas.Handle, Metrics);
// "tmBreakChar: The value of the character that will be used to define word breaks for text justification."
// - http://msdn.microsoft.com/en-us/library/windows/desktop/dd145132(v=vs.85).aspx
// But some fonts, such as Segoe UI (!), define this as #13 - a line break.
// Check if it is a character that takes up space onscreen, and if not return the space char
Result := Canvas.TextWidth(Metrics.tmBreakChar) > 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
// If set in the VCL designer, adds line breaks in the middle of paragraphs.
memoTyping.Lines.Text := 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod '
+ 'tempor incididunt ut labore et dolore magna aliqua.'
+ #13#10
+ 'Ut enim ad minim veniam, quis nostrud '
+ 'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
+ #13#10
+ 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla '
+ 'pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt '
+ 'mollit anim id est laborum.';
Panel1.DoubleBuffered := true; // Otherwise paintbox flickers sometimes
end;
procedure TForm1.memoTypingChange(Sender: TObject);
begin
paintJustification.Invalidate; // user has typed; repaint the preview
end;
procedure TForm1.btnFontClick(Sender: TObject);
begin
dlgFont.Font.Assign(memoTyping.Font);
if dlgFont.Execute then begin
memoTyping.Font.Assign(dlgFont.Font);
paintJustification.Invalidate; // Pepaint to update preview
end;
end;
procedure TForm1.chkInvalidateClick(Sender: TObject);
begin
paintJustification.Invalidate; // Repaint to show result of this setting
end;
procedure TForm1.paintJustificationPaint(Sender: TObject);
var
Rect : TRect;
Options : TDrawTextJustifiedOptions;
begin
paintJustification.Canvas.Font.Assign(memoTyping.Font);
paintJustification.Canvas.Brush.Color := clWindow;
paintJustification.Canvas.Brush.Style := bsSolid;
paintJustification.Canvas.FillRect(paintJustification.ClientRect);
Options := [];
if chkJustifyTrailing.Checked then
Options := Options + [tjJustifyTrailingLines];
if chkJustifySingleWords.Checked then
Options := Options + [tjJustifySingleWords];
if chkManual.Checked then
Options := Options + [tjForceManual];
// Paint
Rect := paintJustification.ClientRect;
DrawTextJustified(paintJustification.Canvas, memoTyping.Lines.Text, Rect, Options);
// And measure, to update the label and draw a faint rectangle to indicate
DrawTextJustified(paintJustification.Canvas, memoTyping.Lines.Text, Rect, Options + [tjMeasureOnly]);
lblRectHeight.Caption := 'Rect height: ' + IntToStr(Rect.Height) + 'px';
if chkDrawRect.Checked then begin // Draw an outline indicating the returned rect
paintJustification.Canvas.Pen.Color := clSkyBlue;
paintJustification.Canvas.Pen.Width := 1;
paintJustification.Canvas.Pen.Style := psSolid;
paintJustification.Canvas.Brush.Style := bsClear;
paintJustification.Canvas.Rectangle(Rect);
end;
lblManualUsed.Caption := 'Always used for this font: ' +
BoolToStr(not SupportsJustification(paintJustification.Canvas), true);
end;
end.
|
{ Subroutine SST_R_PAS_SMENT_CASE (STR_ALL_H)
*
* Process a CASE statement. The last syntax tag read was for the whole
* CASE statement from inside the RAW_STATEMENT syntax. STR_ALL_H is the
* string handle for that tag.
}
module sst_r_pas_SMENT_CASE;
define sst_r_pas_sment_case;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_sment_case ( {CASE statement, inside RAW_STATEMENT syntax}
in str_all_h: syo_string_t); {string handle for whole CASE statement}
const
max_msg_parms = 3; {max parameters we can pass to a message}
type
chain_k_t = ( {identifies which chain of choice values}
chain_all_k, {chain of all choice value in CASE statement}
chain_case_k); {chain of choice values for current case}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
dt_p: sst_dtype_p_t; {points to resolved base data type descriptor}
dt: sst_dtype_k_t; {resolved base data type ID}
case_opc_p: sst_case_opc_p_t; {pnt to current case exec block descriptor}
case_val_p: sst_case_val_p_t; {pnt to current case choice value descriptor}
fnam: string_treename_t; {file name passed to a message}
lnum: sys_int_machine_t; {line number passed to a message}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
label
loop_case, loop_choice;
{
***********************************************************************
*
* Local subroutine INSERT_CHAIN (CHAIN_ID)
*
* Insert the current choice value descriptor, pointed to by CASE_VAL_P,
* into the appropriate place in one of two chains. CHAIN_ID selects
* which chain to add the value descriptor to. Valid values of CHAIN_ID are:
*
* CHAIN_ALL_K - Add the choice value descriptor to the chain of all
* the choice value descriptors for this whole CASE statement.
*
* CHAIN_CASE_K - Add the choice value descriptor to the chain of
* choices for the current case. The descriptor for the current case
* is pointed to by CASE_OPC_P.
*
* In either case, the value descriptor is inserted to maintain the chain
* sorted in ascending order.
}
procedure insert_chain (
in chain_id: chain_k_t); {selects which chain to add to}
var
prev_pp: sst_case_val_pp_t; {points to chain pointer in previous entry}
ent_p: sst_case_val_p_t; {points to current chain entry}
ofs: sys_int_adr_t; {offset of chain pointer from entry start}
label
loop_ent;
begin
case chain_id of {which chain are we adding descriptor to ?}
chain_all_k: begin {add to chain of all choice values}
prev_pp := addr(sst_opc_p^.case_val_p);
ofs := {make adr offset for next entry pointer}
sys_int_adr_t(addr(case_val_p^.next_val_p)) -
sys_int_adr_t(case_val_p);
end;
chain_case_k: begin {add to chain of choice value for curr case}
prev_pp := addr(case_opc_p^.val_first_p);
ofs := {make adr offset for next entry pointer}
sys_int_adr_t(addr(case_val_p^.next_opc_p)) -
sys_int_adr_t(case_val_p);
end;
otherwise
sys_bomb;
end;
ent_p := prev_pp^; {init pointer to first entry in chain}
loop_ent: {back here to compare to next entry in chain}
if ent_p = nil then begin {hit end of chain ?}
prev_pp^ := case_val_p; {add new entry to end of chain}
return;
end;
if ent_p^.val > case_val_p^.val then begin {insert right before this entry ?}
prev_pp^ := case_val_p; {point previous entry to new entry}
prev_pp := univ_ptr( {make address of "next" chain entry pointer}
sys_int_adr_t(case_val_p) + ofs);
prev_pp^ := ent_p; {point new entry to next in chain}
return;
end;
if ent_p^.val = case_val_p^.val then begin {found duplicate choice value ?}
sst_strh_info (ent_p^.exp_p^.str_h, fnam, lnum);
sys_msg_parm_int (msg_parm[1], case_val_p^.val);
sys_msg_parm_int (msg_parm[2], lnum);
sys_msg_parm_vstr (msg_parm[3], fnam);
syo_error (
case_val_p^.exp_p^.str_h,
'sst_pas_read', 'case_duplicate_choice_vals', msg_parm, 3);
end;
prev_pp := univ_ptr( {advance one entry in chain}
sys_int_adr_t(ent_p) + ofs);
ent_p := prev_pp^;
goto loop_ent; {back and process this next chain entry}
end;
{
***********************************************************************
*
* Start of main routine.
}
begin
fnam.max := sizeof(fnam.str);
sst_opcode_new; {create new current opcode descriptor}
with sst_opc_p^: opc do begin {OPC is opcode descriptor for CASE statement}
opc.opcode := sst_opc_case_k; {opcode is for CASE switch}
opc.str_h := str_all_h; {save handle to source characters}
opc.case_val_p := nil; {init global choice values chain to empty}
opc.case_opc_p := nil; {init cases chain to empty}
opc.case_none_p := nil; {init to no OTHERWISE clause present}
{
* Process expression that selects which case.
}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_exec_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_r_pas_exp (str_h, false, opc.case_exp_p); {process choice selector expression}
sst_dtype_resolve ( {get base data types of this expression}
opc.case_exp_p^.dtype_p^, {input data type descriptor}
dt_p, dt); {returned base data types}
case dt of {what base data type ID does it have ?}
sst_dtype_int_k,
sst_dtype_enum_k,
sst_dtype_bool_k,
sst_dtype_char_k: ; {these are all the legal data types}
otherwise
syo_error (str_h, 'sst_pas_read', 'exp_bad_case', nil, 0);
end;
case_opc_p := nil; {init to no current exec block descriptor}
loop_case: {back here each new complete case}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_case_bad', nil, 0);
case tag of
{
*******************************************
*
* Tag indicates a whole new case with associated choice values and executable
* block.
}
1: begin
if case_opc_p = nil
then begin {this is first exec case in chain}
sst_mem_alloc_scope ( {allocate descriptor for this code block}
sizeof(case_opc_p^), case_opc_p);
opc.case_opc_p := case_opc_p; {init pointer to first exec block in chain}
end
else begin {add new block to end of existing chain}
sst_mem_alloc_scope ( {allocate descriptor for this code block}
sizeof(case_opc_p^.next_p^), case_opc_p^.next_p);
case_opc_p := case_opc_p^.next_p; {make new block the current block}
end
;
case_opc_p^.val_first_p := nil; {init to no choice values chain here yet}
case_opc_p^.code_p := nil; {init to no executable statements this case}
case_opc_p^.next_p := nil; {indicate this block is end of chain}
loop_choice: {back here for each new tag this case}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_case_bad', nil, 0);
case tag of
{
* Tag is for EXPRESSION syntax that identifies the value of another choice
* for the current case.
}
1: begin
sst_mem_alloc_scope ( {allocate descriptor for this choice value}
sizeof(case_val_p^), case_val_p);
case_val_p^.opc_p := case_opc_p; {point to descriptor for associated case}
case_val_p^.next_val_p := nil; {init chain pointers}
case_val_p^.next_opc_p := nil;
sst_r_pas_exp (str_h, true, case_val_p^.exp_p); {create expression descriptor}
sst_exp_useage_check ( {check expression attributes for this useage}
case_val_p^.exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
opc.case_exp_p^.dtype_p^); {data type value must be compatible with}
sst_ordval ( {get ordinal value of this choice expression}
case_val_p^.exp_p^.val, {constant value descriptor}
case_val_p^.val, {returned ordinal value}
stat); {error status return code}
syo_error_abort (stat, str_h, '', '', nil, 0);
insert_chain (chain_all_k); {add to choices chain for whole CASE sment}
insert_chain (chain_case_k); {add to choices chain for this case}
goto loop_choice; {back to get next choice val for this case}
end;
{
* Tag is for RAW_STATEMENT syntax for the executable code for the current case.
}
2: begin
sst_opcode_pos_push (case_opc_p^.code_p); {new opcodes get chained here}
sst_r_pas_raw_sment; {build opcodes chain for this case}
sst_opcode_pos_pop; {back to regular opcode chain}
end;
{
* Unexpected TAG value within current case.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of tag cases within current case}
goto loop_case; {back for next case in CASE statement}
end; {end of tag was another case in CASE sment}
{
*******************************************
*
* TAG is for STATEMENTS syntax for the statements in the OTHERWISE clause.
}
2: begin
sst_opcode_pos_push (opc.case_none_p); {new opcodes will get chained here}
sst_r_pas_statements; {build opcode chain for OTHERWISE case}
sst_opcode_pos_pop; {back to regular opcode chain}
end;
{
*******************************************
*
* TAG indicates that this CASE statement has no OTHERWISE clause.
}
3: ;
{
*******************************************
*
* Unexpected TAG value in CASE statement syntax.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of CASE statement top level syntax tags}
end; {done with OPC abbreviation}
end;
|
unit DocumentDomainInterfaces;
{* Работа с документом }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Model\DocumentDomainInterfaces.pas"
// Стереотип: "Interfaces"
// Элемент модели: "DocumentDomainInterfaces" MUID: (4991BD69025E)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, l3Interfaces
;
type
InsLinkedObjectDescription = interface
{* Содержит информацию о картинке }
['{29FA1780-029B-4E08-B914-F0668C44ADEB}']
function pm_GetID: Integer;
function pm_GetName: Il3CString;
function pm_GetShortName: Il3CString;
property ID: Integer
read pm_GetID;
property Name: Il3CString
read pm_GetName;
property ShortName: Il3CString
read pm_GetShortName;
end;//InsLinkedObjectDescription
InsLinkedObjectData = interface
{* Содержит информацию о картинке и ее данные }
['{650645AC-163D-4C26-82DA-2D307EB68A9F}']
function Get_IsPicture: Boolean;
function pm_GetObjectTitle: Il3CString;
function pm_GetWindowCaption: Il3CString;
function pm_GetFileName: Il3CString;
function pm_GetData: IStream;
function pm_GetDescription: InsLinkedObjectDescription;
property IsPicture: Boolean
read Get_IsPicture;
property ObjectTitle: Il3CString
read pm_GetObjectTitle;
property WindowCaption: Il3CString
read pm_GetWindowCaption;
property FileName: Il3CString
read pm_GetFileName;
property Data: IStream
read pm_GetData;
property Description: InsLinkedObjectDescription
read pm_GetDescription;
end;//InsLinkedObjectData
implementation
uses
l3ImplUses
;
end.
|
unit nsStartupTips;
{* Советик дня }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\DayTips\nsStartupTips.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnsStartupTips" MUID: (4992891800CF)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, l3SimpleObject
, DayTipsInterfaces
, l3TreeInterfaces
, l3Interfaces
, afwInterfaces
;
type
_afwApplicationDataUpdate_Parent_ = Tl3SimpleObject;
{$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas}
TnsStartupTips = class(_afwApplicationDataUpdate_, InsStartupTips)
{* Советик дня }
private
f_TipsTree: Il3SimpleTree;
f_CurrentNode: Il3SimpleNode;
f_DontShow: Boolean;
protected
function pm_GetTipCaption: Il3CString;
function pm_GetDontShow: Boolean;
procedure pm_SetDontShow(aValue: Boolean);
procedure Next;
procedure Prev;
procedure ShowDetails;
procedure GotoWeb;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure FinishDataUpdate; override;
public
constructor Create; reintroduce;
class function MakePrim: InsStartupTips; reintroduce;
class function Make: InsStartupTips;
end;//TnsStartupTips
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
{$If NOT Defined(NoVCM)}
, StdRes
{$IfEnd} // NOT Defined(NoVCM)
, DataAdapter
, afwFacade
, nsConst
, DynamicTreeUnit
, DocumentUnit
, BaseTypesUnit
, nsTreeStruct
, SysUtils
{$If NOT Defined(NoVCM)}
, vcmBase
{$IfEnd} // NOT Defined(NoVCM)
, deTips
, nsINodeWrap
, nsExternalObjectPrim
, nsTypes
//#UC START# *4992891800CFimpl_uses*
, Base_Operations_F1Services_Contracts
//#UC END# *4992891800CFimpl_uses*
;
{$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas}
constructor TnsStartupTips.Create;
//#UC START# *49928A97027C_4992891800CF_var*
var
l_Root: INodeBase;
l_Path: INodeIndexPath;
l_Temp: INodeBase;
//#UC END# *49928A97027C_4992891800CF_var*
begin
//#UC START# *49928A97027C_4992891800CF_impl*
inherited Create;
with defDataAdapter.NativeAdapter.MakeTipsManager do
begin
GetTipsTreeRoot(l_Root);
GetCurrentTip(l_Path);
Assert(Assigned(l_Path),'Undefined tips path');
end;
f_TipsTree := TnsTreeStruct.Make(l_Root, False);
l_Root.GetNodeByPath(l_Path, l_Temp);
if Assigned(l_Temp) then
f_CurrentNode := TnsINodeWrap.Make(l_Temp);
f_DontShow := afw.Settings.LoadBoolean(pi_DayTips_DontShowAtStart,
dv_DayTips_DontShowAtStart);
//#UC END# *49928A97027C_4992891800CF_impl*
end;//TnsStartupTips.Create
class function TnsStartupTips.MakePrim: InsStartupTips;
var
l_Inst : TnsStartupTips;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TnsStartupTips.MakePrim
class function TnsStartupTips.Make: InsStartupTips;
//#UC START# *4993F1F80032_4992891800CF_var*
//#UC END# *4993F1F80032_4992891800CF_var*
begin
//#UC START# *4993F1F80032_4992891800CF_impl*
if defDataAdapter.NativeAdapter.MakeTipsManager.IsExist then
Result := MakePrim
else
Result := nil;
//#UC END# *4993F1F80032_4992891800CF_impl*
end;//TnsStartupTips.Make
function TnsStartupTips.pm_GetTipCaption: Il3CString;
//#UC START# *4991C74701F8_4992891800CFget_var*
//#UC END# *4991C74701F8_4992891800CFget_var*
begin
//#UC START# *4991C74701F8_4992891800CFget_impl*
if Assigned(f_CurrentNode) then
Result := nsCStr(f_CurrentNode.Text)
else
Result := nil;
//#UC END# *4991C74701F8_4992891800CFget_impl*
end;//TnsStartupTips.pm_GetTipCaption
function TnsStartupTips.pm_GetDontShow: Boolean;
//#UC START# *4991C75C00D5_4992891800CFget_var*
//#UC END# *4991C75C00D5_4992891800CFget_var*
begin
//#UC START# *4991C75C00D5_4992891800CFget_impl*
Result := f_DontShow;
//#UC END# *4991C75C00D5_4992891800CFget_impl*
end;//TnsStartupTips.pm_GetDontShow
procedure TnsStartupTips.pm_SetDontShow(aValue: Boolean);
//#UC START# *4991C75C00D5_4992891800CFset_var*
//#UC END# *4991C75C00D5_4992891800CFset_var*
begin
//#UC START# *4991C75C00D5_4992891800CFset_impl*
f_DontShow := aValue;
//#UC END# *4991C75C00D5_4992891800CFset_impl*
end;//TnsStartupTips.pm_SetDontShow
procedure TnsStartupTips.Next;
//#UC START# *4991C7680235_4992891800CF_var*
//#UC END# *4991C7680235_4992891800CF_var*
begin
//#UC START# *4991C7680235_4992891800CF_impl*
if Assigned(f_CurrentNode) then
begin
if f_CurrentNode.IsLast then
f_CurrentNode := f_TipsTree.RootNode.Child
else
f_CurrentNode := f_CurrentNode.Next;
end;
//#UC END# *4991C7680235_4992891800CF_impl*
end;//TnsStartupTips.Next
procedure TnsStartupTips.Prev;
//#UC START# *4991C76E02ED_4992891800CF_var*
//#UC END# *4991C76E02ED_4992891800CF_var*
begin
//#UC START# *4991C76E02ED_4992891800CF_impl*
if Assigned(f_CurrentNode) then
begin
if f_CurrentNode.IsFirst then
while not f_CurrentNode.IsLast do
f_CurrentNode := f_CurrentNode.Next
else
f_CurrentNode := f_CurrentNode.Prev;
end;
//#UC END# *4991C76E02ED_4992891800CF_impl*
end;//TnsStartupTips.Prev
procedure TnsStartupTips.ShowDetails;
//#UC START# *4991C77601E9_4992891800CF_var*
var
l_Node : INodeBase;
l_Entity : IEntityBase;
l_Doc : IDocument;
//#UC END# *4991C77601E9_4992891800CF_var*
begin
//#UC START# *4991C77601E9_4992891800CF_impl*
if Supports(f_CurrentNode, INodeBase, l_Node) then
Begin
l_Node.GetEntity(l_Entity);
if Supports(l_Entity, IDocument, l_Doc) then
TDocumentService.Instance.OpenDocument(TdeTips.Make(l_Doc), nil);
end;
//#UC END# *4991C77601E9_4992891800CF_impl*
end;//TnsStartupTips.ShowDetails
procedure TnsStartupTips.GotoWeb;
//#UC START# *4991C78200E7_4992891800CF_var*
//#UC END# *4991C78200E7_4992891800CF_var*
begin
//#UC START# *4991C78200E7_4992891800CF_impl*
nsDoShellExecute(nsCStr(ciitAdviceOfDay));
//#UC END# *4991C78200E7_4992891800CF_impl*
end;//TnsStartupTips.GotoWeb
procedure TnsStartupTips.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4992891800CF_var*
//#UC END# *479731C50290_4992891800CF_var*
begin
//#UC START# *479731C50290_4992891800CF_impl*
f_TipsTree := nil;
f_CurrentNode := nil;
if f_DontShow <> afw.Settings.LoadBoolean(pi_DayTips_DontShowAtStart,
dv_DayTips_DontShowAtStart) then
afw.Settings.SaveBoolean(pi_DayTips_DontShowAtStart, f_DontShow, dv_DayTips_DontShowAtStart);
inherited;
//#UC END# *479731C50290_4992891800CF_impl*
end;//TnsStartupTips.Cleanup
procedure TnsStartupTips.FinishDataUpdate;
//#UC START# *47EA4E9002C6_4992891800CF_var*
//#UC END# *47EA4E9002C6_4992891800CF_var*
begin
//#UC START# *47EA4E9002C6_4992891800CF_impl*
f_CurrentNode := nil;
inherited;
//#UC END# *47EA4E9002C6_4992891800CF_impl*
end;//TnsStartupTips.FinishDataUpdate
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
Buttons, Types, LCLType;
type
{ TForm1 }
TForm1 = class(TForm)
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
ImageList1: TImageList;
Panel1: TPanel;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
SpeedButton1: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure Panel1Paint(Sender: TObject);
procedure SpeedButton1Paint(Sender: TObject);
private
procedure DoPnt(C: TCanvas);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.DoPnt(C: TCanvas);
begin
C.Pen.Color:= clRed;
C.Brush.Color:= clYellow;
C.Rectangle(5, 5, 105, 40);
ImageList1.Draw(C, 10, 10, 0);
ImageList1.Draw(C, 40, 10, 1);
ImageList1.Draw(C, 70, 10, 2);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
bmp: TBitmap;
fn: string;
begin
bmp:= TBItmap.Create;
fn:= ExtractFilePath(APplication.ExeName)+'bmp1.bmp';
if FileExists(fn) then
bmp.LoadFromFile(fn);
//bmp.Transparent:= false;
bmp.TransparentColor:= clYellow;
SpeedButton1.Glyph.Assign(bmp);
end;
procedure TForm1.Panel1Paint(Sender: TObject);
begin
DoPnt(Panel1.Canvas);
end;
procedure TForm1.SpeedButton1Paint(Sender: TObject);
begin
DoPnt(SpeedButton1.Canvas);
end;
end.
|
unit rand;
interface
type
rndinfotype=record
seed:array[1..4] of integer;
maxrnd:longint;
maxrndexp:integer
end;
Procedure initrnd(x:longint);
Procedure setmax(x:longint);
Function rnd:byte;
Function longrnd:longint;
Function realrnd:real;
Procedure getrndstat(var x:rndinfotype);
Procedure setrndstat(var x:rndinfotype);
implementation
const
prime1 = 263;
prime2 = 251;
prime3 = 241;
prime4 = 239;
type
seedtype=array[1..4] of byte;
var rndinfo:rndinfotype;
Procedure initrnd(x:longint);
var p:^seedtype;
begin
p := addr(x);
with rndinfo do
begin
seed[1] := p^[1];
seed[2] := p^[2] mod prime2;
seed[3] := p^[3] mod prime3;
seed[4] := p^[4] mod prime4
end
end;
Procedure setmax(x:longint);
var y:longint;
exp:integer;
begin
if x < 1 then x := 1;
y := x - 1;
exp := 0;
while (y > 0) do
begin
y := y div 2;
exp := exp + 1
end;
with rndinfo do
begin
maxrnd := x;
maxrndexp := exp
end
end;
Function rnd:byte;
begin
with rndinfo do
begin
repeat
seed[1] := (seed[1]*101 + 137) mod prime1
until seed[1] < 256;
repeat
seed[2] := (seed[2]*101 + 137) mod prime1
until seed[2] < prime2;
repeat
seed[3] := (seed[3]*101 + 137) mod prime1
until seed[3] < prime3;
repeat
seed[4] := (seed[4]*101 + 137) mod prime1
until seed[4] < prime4;
rnd := (seed[1] + seed[2] + seed[3] + seed[4]) mod 256
end
end;
Function longrnd:longint;
var rndnum:longint;
cnt:integer;
begin
repeat
cnt := 0;
rndnum := 0;
while (cnt < rndinfo.maxrndexp) do
begin
rndnum := 256*rndnum + rnd;
cnt := cnt + 8
end;
while (cnt > rndinfo.maxrndexp) do
begin
rndnum := rndnum div 2;
cnt := cnt - 1
end
until (rndnum < rndinfo.maxrnd);
longrnd := rndnum
end;
Function realrnd:real;
var x:real;
cnt:integer;
begin
x := 0.0;
for cnt := 1 to 4 do
x := (x + rnd) / 256.0;
realrnd := x
end;
Procedure getrndstat(var x:rndinfotype);
begin
x := rndinfo
end;
Procedure setrndstat(var x:rndinfotype);
begin
rndinfo := x
end;
end. |
unit ADC.Common;
interface
uses
System.SysUtils, Winapi.Windows, System.Classes, Vcl.Dialogs, System.Variants,
System.IniFiles, Vcl.Graphics, System.StrUtils, System.RegularExpressions,
Winapi.Messages, Winapi.TlHelp32, Winapi.PsAPI, Vcl.Forms, Winapi.ActiveX,
Vcl.ComCtrls, ActiveDs_TLB, JwaLmAccess, JwaLmApiBuf, JwaDSGetDc, JwaActiveDS,
ADC.NetInfo, Winapi.Winsock2, ADC.Types, System.DateUtils, System.Types, System.TypInfo,
Winapi.ShlObj, System.AnsiStrings, ADC.LDAP, JwaRpcDce, ADC.AD, ADC.Attributes;
function ReduceBrightness(AColor: TColor; Percent: Byte): TColor;
function IncreaseBrightness(AColor: TColor; Percent: Byte): TColor;
function GetUserEventColor(EventDate: TDate; DefaultColor: TColor = clBtnFace): TColor;
function TempDirPath: string;
function GetSpecialFolderPath(AFolderID: DWORD): string;
function IsCreateFileElevationRequired(APath: string): Boolean;
function DBProviderExists(Provider: string): Boolean;
procedure FreeThreadManually(AThread: TThread);
function TranslitCyrillicToLatin(const AInput: string): string;
function GetUserLogonPCName(AObj: TObject; AAttrList: TAttrCatalog; AAttrID: Integer): string;
function AppInstanceExists(AClassName: string): Boolean; overload;
function AppInstanceExists(AClassName: string; AIniFile: TFileName): Boolean; overload;
function SendMessageToWindow(AClassName, AMessage: string): DWORD;
function GetTreeNodePath(ANode: TTreeNode; var ARootPath: string;
ASeparator: string = '/'): string;
function GetTextWidthInPixels(const AText: string; ATextFont: TFont): Integer;
function GetTextHeightInPixels(const AText: string; ATextFont: TFont): Integer;
function GetFileInfo(const FileName: TFileName; Information: string): string;
function GetFileVersionNumber(const FileName: TFileName;
var MajorVersion, MinorVersion, BuildNumber, RevisionNumber: DWORD): Boolean;
function ADSIErrorToString: string;
function SortEvents(Item1, Item2: Pointer): Integer;
function SIDToString(objSID: PSID): string; overload;
function SIDToString(objSID: OleVariant): string; overload;
function ADEscapeReservedCharacters(AValue: string): string;
function DateTimeToADDate(ADate: TDateTime): ActiveDs_TLB._LARGE_INTEGER;
function ADDateToDateTime(ADDate: DATE_TIME): System.TDateTime; overload;
function ADDateToDateTime(ADDate: ActiveDs_TLB._LARGE_INTEGER): System.TDateTime; overload;
function ADDateToDateTime(ADDate: OleVariant): System.TDateTime; overload;
function CalcPasswordExpiration(const PwdLastSet: ActiveDs_TLB._LARGE_INTEGER;
MaxPwdAge: Integer): System.TDateTime;
function ADCheckPasswordComplexity(ADomainName, APassword: string): Boolean;
procedure ADEnumDomainControllers(const outDCList: TStrings);
procedure ADEnumContainers(ARootDSE: IADs; const outList: TStrings); overload;
procedure ADEnumContainers(ALDAP: PLDAP; const outList: TStrings); overload;
function DameWareMRC_Connect(const Executable, MachineName: string; key_a: Integer;
key_u, key_p, key_d: string; key_md, key_r, AutoConnect, ViewOnly: Boolean): Boolean;
function EncodeIP(AIP: string): Cardinal;
function DecodeIP(AIP: Cardinal): string;
procedure GetIPAddress(AClient: string; out AInfo: PIPAddr);
procedure GetDHCPInfo(AClient: string; out AInfo: PDHCPInfo);
procedure GetDHCPInfoEx(AClient: string; out AInfo: PDHCPInfo);
procedure GetDHCPInfoV4(AClient: string; out AInfo: PDHCPInfo);
procedure FreeDHCPClientInfoMemory(pClientInfo: PDHCP_CLIENT_INFO); overload;
procedure FreeDHCPClientInfoMemory(pClientInfo: LPDHCP_CLIENT_INFO_PB); overload;
procedure ServerBinding(ADcDnsName: string; out ALDAP: PLDAP;
AOnException: TExceptionProc); overload;
procedure ServerBinding(ADcName: string; ARootDSE: Pointer;
AOnException: TExceptionProc); overload;
function ADCreateOU(ALDAP: PLDAP; AContainer: string; ANewOU: string): string; overload;
function ADCreateOU(ARootDSE: IADS; AContainer: string; ANewOU: string): string; overload;
function ADCreateOUDS(ARootDSE: IADS; AContainer: string; ANewOU: string): string;
function ADCreateGroup(ALDAP: PLDAP; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string; overload;
function ADCreateGroup(ARootDSE: IADS; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string; overload;
function ADCreateGroupDS(ARootDSE: IADS; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string; overload;
function ADDeleteObject(ALDAP: PLDAP; ADN: string): Boolean; overload;
function ADDeleteObject(ARootDSE: IADS; ADN: string): Boolean; overload;
function ADDeleteObjectDS(ARootDSE: IADS; ADN: string): Boolean; overload;
implementation
function ReduceBrightness(AColor: TColor; Percent: Byte): TColor;
var
R, G, B: Byte;
Cl: Integer;
begin
Cl := ColorToRGB(AColor);
R := GetRValue(Cl);
G := GetGValue(Cl);
B := GetBValue(Cl);
R := R - MulDiv(R, Percent, 100);
G := G - MulDiv(G, Percent, 100);
B := B - MulDiv(B, Percent, 100);
Result := RGB(R, G, B);
end;
function IncreaseBrightness(AColor: TColor; Percent: Byte): TColor;
var
R, G, B: Byte;
Cl: Integer;
begin
Cl := ColorToRGB(AColor);
R := GetRValue(Cl);
G := GetGValue(Cl);
B := GetBValue(Cl);
R := R + MulDiv(255 - R, Percent, 100);
G := G + MulDiv(255 - G, Percent, 100);
B := B + MulDiv(255 - B, Percent, 100);
Result := RGB(R, G, B);
end;
function GetUserEventColor(EventDate: TDate; DefaultColor: TColor = clBtnFace): TColor;
begin
Result := DefaultColor;
if EventDate > 0 then
begin
if DateOf(EventDate) < DateOf(Now) then
begin
Result := clRed;
end else
if DateOf(EventDate) = DateOf(Now) then
begin
Result := clYellow;
end else
begin
// if DaysBetween(DateOf(Now), ctrlDate) <= 1 then Sender.Canvas.Brush.Color := $00E1E1FF else
// if DaysBetween(DateOf(Now), ctrlDate) <= 3 then Sender.Canvas.Brush.Color := $00CEFFFF;
end;
end;
end;
function TempDirPath: string;
var
Buf: string;
Len: Cardinal;
begin
SetLength(Buf, 1024);
Len := GetTempPath(1023, PChar(Buf));
SetLength(Buf, Len);
Result := IncludeTrailingBackslash(Buf);
end;
function GetSpecialFolderPath(AFolderID: DWORD): string;
var
DirPath: PChar;
begin
Result := '';
begin
DirPath := StrAlloc(MAX_PATH);
if SHGetSpecialFolderPath(0, DirPath, AFolderID, True) then
begin
Result := Format('%s%s', [IncludeTrailingBackslash(string(DirPath)), 'AD Commander']);
if not DirectoryExists(Result) then
if not ForceDirectories(Result) then Result := '';
end;
StrDispose(DirPath);
end;
end;
function IsCreateFileElevationRequired(APath: string): Boolean;
var
fName: string;
hFile: THandle;
begin
Result := False;
fName := IncludeTrailingBackslash(APath) + 'adcmd_test.tmp';
hFile := CreateFile(
PChar(fName),
GENERIC_WRITE,
0,
nil,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_DELETE_ON_CLOSE,
0
);
if hFile = INVALID_HANDLE_VALUE then
begin
if GetLastError = ERROR_ACCESS_DENIED
then Result := True;
end else CloseHandle(hFile);
end;
function DBProviderExists(Provider: string): Boolean;
var
CLSID: TGUID;
hRes: Integer;
begin
CLSID := TGUID.Empty;
hRes := CLSIDFromProgID(PChar(Provider), CLSID);
Result := hRes = 0;
end;
procedure FreeThreadManually(AThread: TThread);
begin
try
AThread.Terminate;
AThread.WaitFor;
AThread.Free;
FreeAndNil(AThread);
except
AThread := nil;
end;
end;
function TranslitCyrillicToLatin(const AInput: string): string;
const
CHAR_LOWER_CASE = 1;
CHAR_UPPER_CASE = 2;
AlphabetLC = 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя';
AlphabetUC = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ';
AlphabetLength = Length(AlphabetUC);
arr: array[CHAR_LOWER_CASE..CHAR_UPPER_CASE, 1..AlphabetLength] of string = (
(
'a', 'b', 'v', 'g', 'd', 'e', 'yo', 'zh', 'z', 'i', 'y',
'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f',
'kh', 'ts', 'ch', 'sh', 'shch', '''', 'y', '''', 'e', 'yu', 'ya'
),
(
'A', 'B', 'V', 'G', 'D', 'E', 'Yo', 'Zh', 'Z', 'I', 'Y',
'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F',
'Kh', 'Ts', 'Ch', 'Sh', 'Shch', '''', 'Y', '''', 'E', 'Yu', 'Ya'
)
);
var
i: Integer;
l: Integer;
p: Integer;
d: Byte;
begin
Result := '';
l := Length(AInput);
for i := 1 to l do
begin
d := CHAR_LOWER_CASE;
p := pos(AInput[i], AlphabetLC);
if p = 0 then
begin
p := pos(AInput[i], AlphabetUC);
d := CHAR_UPPER_CASE;
end;
if p <> 0 then
result := result + arr[d, p]
else
result := result + AInput[i]; //если не русская буква, то берем исходную
end;
end;
function GetUserLogonPCName(AObj: TObject; AAttrList: TAttrCatalog; AAttrID: Integer): string;
var
attr: TADAttribute;
val: string;
RegEx: TRegEx;
begin
if AAttrList.ItemByID(AAttrID) <> nil then
try
attr := AAttrList.ItemByID(AAttrID)^;
if IsPublishedProp(AObj, attr.ObjProperty)
then val := GetPropValue(AObj, attr.ObjProperty, True);
RegEx := TRegEx.Create('(%clientname%)|(,.*$)', [roIgnoreCase]);
Result := RegEx.Replace(val, '');
except
Result := ''
end;
end;
function AppInstanceExists(AClassName: string): Boolean;
begin
Result := AppInstanceExists(AClassName, '');
end;
function AppInstanceExists(AClassName: string; AIniFile: TFileName): Boolean;
const
PROCESS_NAME_NATIVE = $00000001;
PROCESS_QUERY_LIMITED_INFORMATION = $1000;
var
hW: THandle;
hP: THandle;
ProcessID: Integer;
Buf: PChar;
BufSize: DWORD;
ExeName: string;
QueryFullProcessImageName: TQueryFullProcessImageName;
SingleInstance: Boolean;
ExecParam: Byte;
CopyDataStruct : TCopyDataStruct;
Res: NativeInt;
MsgBoxParam: TMsgBoxParams;
fIni: TIniFile;
begin
hW := 0;
hP := 0;
ProcessID := 0;
BufSize := MAX_PATH;
GetMem(Buf, BufSize);
Result := False;
hW := FindWindow(PChar(AClassName), nil);
if hW > 0 then
begin
{ По классу основного окна приложения ищем ProcessID и, далее, }
{ по ProcessID получаем имя *.exe файла процесса (приложения) }
GetWindowThreadProcessID(hW, @ProcessID);
if ProcessID > 0 then
begin
if (Win32MajorVersion in [4, 5]) and (Win32Platform = VER_PLATFORM_WIN32_NT) then
begin
hP := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ProcessID);
if hP > 0
then if GetModuleFileNameEx(hP, 0, Buf, BufSize) > 0
then ExeName := StringReplace(Buf, '\??\', '', [rfReplaceAll, rfIgnoreCase]);
end else
begin
@QueryFullProcessImageName := GetProcAddress(
GetModuleHandle(PChar('kernel32.dll')),
PChar('QueryFullProcessImageNameW')
);
if Assigned(QueryFullProcessImageName) then
begin
hP := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, ProcessID);
if hP > 0
then if QueryFullProcessImageName(hP, 0, Buf, @BufSize) > 0
then ExeName := Buf;
end;
end;
CloseHandle(hP);
{ Если файл приложения существует, то читаем из *.ini файла }
{ параметры запуска нескольких копий приложения, иначе просто }
{ сообщаем что других экземпляров приложения не обнаружено }
if FileExists(AIniFile)
then fIni := TIniFile.Create(AIniFile)
else if FileExists(ExeName)
then fIni := TIniFile.Create(ChangeFileExt(ExeName, '.ini'));
try
SingleInstance := fIni.ReadBool(INI_SECTION_GENERAL, 'RunSingleInstance', False);
ExecParam := fIni.ReadInteger(INI_SECTION_GENERAL, 'ExecParam', EXEC_PROMPT_ACTION);
if SingleInstance then Res := IDNO else
case ExecParam of
EXEC_NEW_INSTANCE : Res := IDYES;
EXEC_PROMPT_ACTION: begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := 0;
hInstance := 0;
lpszCaption := PChar('Подтверждение');
lpszIcon := MAKEINTRESOURCE(32514);
dwStyle := MB_YESNO or MB_ICONQUESTION;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
end;
MsgBoxParam.lpszText := PChar(
'Программа "' + APP_TITLE +'" уже запущена.' + #13#10 +
'Запустить еще один экземпляр программы?'
);
MessageBeep(MB_ICONQUESTION);
Res := MessageBoxIndirect(MsgBoxParam);
end;
end;
case Res of
IDNO: begin
with CopyDataStruct do
begin
dwData := 0;
cbData := MAX_PATH;
lpData := PChar('SHOW_WINDOW');
end;
Res := SendMessage(hW, WM_COPYDATA, Integer(0), Integer(@CopyDataStruct)) ;
if Res = 0 then
begin
MessageBeep(MB_ICONASTERISK);
MessageDlg(
'Программа "' + APP_TITLE +'" уже запущена.',
mtInformation,
[mbOk],
0
);
end else
begin
SetForegroundWindow(hW);
//ShowWindow(MainWindow, SW_SHOW);
//SetWindowPos(MainWindow,HWND_TOP,0,0,0,0,SWP_NOMOVE or SWP_NOSIZE or SWP_SHOWWINDOW);
end;
Result := True;
end;
IDYES: begin
Result := False;
end;
end;
except
Result := False;
end;
fIni.Free;
end;
end;
FreeMem(Buf);
end;
function SendMessageToWindow(AClassName, AMessage: string): DWORD;
var
hW: THandle;
CopyDataStruct : TCopyDataStruct;
begin
hW := 0;
Result := 0;
hW := FindWindow(PChar(AClassName), nil);
if hW > 0 then
begin
with CopyDataStruct do
begin
dwData := 0;
cbData := MAX_PATH;
lpData := PChar(AMessage);
end;
Result := SendMessage(hW, WM_COPYDATA, Integer(0), Integer(@CopyDataStruct));
end;
end;
function GetTreeNodePath(ANode: TTreeNode; var ARootPath: string;
ASeparator: string): string;
begin
ARootPath := Format('%s%s%s', [ANode.Text, ASeparator, ARootPath]);
if ANode.Level = 0
then Result := ARootPath
else Result := GetTreeNodePath(ANode.Parent, ARootPath);
if (Length(Result) > 0) and (Result[Length(Result)] = ASeparator)
then Delete(Result, Length(Result), 1);
end;
function GetTextWidthInPixels(const AText: string; ATextFont: TFont): Integer;
var
c: TBitmap;
begin
Result := 0;
c := TBitmap.Create;
try
c.Canvas.Font.Assign(ATextFont);
Result := c.Canvas.TextWidth(AText);
finally
c.Free;
end;
end;
function GetTextHeightInPixels(const AText: string; ATextFont: TFont): Integer;
var
c: TBitmap;
begin
Result := 0;
c := TBitmap.Create;
try
c.Canvas.Font.Assign(ATextFont);
Result := c.Canvas.TextHeight(AText);
finally
c.Free;
end;
end;
function GetFileInfo(const FileName: TFileName; Information: string): string;
type
PDWORD = ^DWORD;
PLangAndCodePage = ^TLangAndCodePage;
TLangAndCodePage = packed record
wLanguage: WORD;
wCodePage: WORD;
end;
PLangAndCodePageArray = ^TLangAndCodePageArray;
TLangAndCodePageArray = array[0..0] of TLangAndCodePage;
var
loc_InfoBufSize: DWORD;
loc_InfoBuf: PChar;
loc_VerBufSize: DWORD;
loc_VerBuf: PChar;
cbTranslate: DWORD;
lpTranslate: PDWORD;
i: DWORD;
begin
Result := '';
if (Length(FileName) = 0) or (not FileExists(FileName)) then Exit;
loc_InfoBufSize := GetFileVersionInfoSize(PChar(FileName), loc_InfoBufSize);
if loc_InfoBufSize > 0 then
begin
loc_VerBuf := nil;
loc_InfoBuf := AllocMem(loc_InfoBufSize);
try
if not GetFileVersionInfo(PChar(FileName), 0, loc_InfoBufSize, loc_InfoBuf)
then
exit;
if not VerQueryValue(loc_InfoBuf, '\\VarFileInfo\\Translation',
LPVOID(lpTranslate), DWORD(cbTranslate)) then Exit;
for i := 0 to (cbTranslate div SizeOf(TLangAndCodePage)) - 1 do
begin
if VerQueryValue(
loc_InfoBuf,
PChar(Format(
'StringFileInfo\0%x0%x\%s', [
PLangAndCodePageArray(lpTranslate)[i].wLanguage,
PLangAndCodePageArray(lpTranslate)[i].wCodePage,
Information])),
Pointer(loc_VerBuf),
DWORD(loc_VerBufSize)
) then
begin
Result := loc_VerBuf;
Break;
end;
end;
finally
FreeMem(loc_InfoBuf, loc_InfoBufSize);
end;
end;
end;
function GetFileVersionNumber(const FileName: TFileName;
var MajorVersion, MinorVersion, BuildNumber, RevisionNumber: DWORD): Boolean;
var
InfoBufSize: DWORD;
InfoBuf: PChar;
BufLen: UINT;
lpFileInfo: ^VS_FIXEDFILEINFO;
begin
Result := False;
if (Length(FileName) = 0) or (not FileExists(FileName)) then Exit;
InfoBufSize := GetFileVersionInfoSize(PChar(FileName), InfoBufSize);
if InfoBufSize > 0 then
begin
InfoBuf := AllocMem(InfoBufSize);
try
if GetFileVersionInfo(PChar(FileName), 0, InfoBufSize, InfoBuf) then
if VerQueryValue(InfoBuf, '\\', LPVOID(lpFileInfo), BufLen) then
begin
MajorVersion := HIWORD(lpFileInfo.dwFileVersionMS);
MinorVersion := LOWORD(lpFileInfo.dwFileVersionMS);
BuildNumber := HIWORD(lpFileInfo.dwFileVersionLS);
RevisionNumber := LOWORD(lpFileInfo.dwFileVersionLS);
Result := True;
end;
finally
FreeMem(InfoBuf, InfoBufSize);
end;
end;
end;
function ADSIErrorToString: string;
var
hr: HRESULT;
adsiError: DWORD;
adsiErrorBuf: PChar;
adsiNameBuf: PChar;
begin
Result := '';
adsiErrorBuf := AllocMem(MAX_PATH);
adsiNameBuf := AllocMem(MAX_PATH);
hr := ADsGetLastError(
adsiError,
adsiErrorBuf,
MAX_PATH,
adsiNameBuf,
MAX_PATH
);
if Succeeded(hr)
{ Подробное описаниие ошибки }
// then Result := Format(
// 'Error Code: %d'#13#10'Error Text: %s'#13#10'Provider: %s',
// [adsiError, adsiErrorBuf, adsiNameBuf]
// );
{ Краткое описаниие ошибки }
then Result := SysErrorMessage(adsiError);
FreeMem(adsiErrorBuf);
FreeMem(adsiNameBuf);
end;
function SortEvents(Item1, Item2: Pointer): Integer;
var
e1, e2: TADEvent;
begin
e1 := PADEvent(Item1)^;
e2 := PADEvent(Item2)^;
Result := CompareDate(e1.Date, e2.Date);
end;
function SIDToString(objSID: PSID): string;
const
SID_REVISION = 1;
var
psia: PSIDIdentifierAuthority;
dwSubAuthorities: DWORD;
dwSidRev: DWORD;
dwCounter: DWORD;
res: PChar;
begin
Result := '';
dwSidRev := SID_REVISION;
if objSID = nil then Exit;
if not IsValidSid(objSID)
then Exit;
if ConvertSidToStringSid(objSID, res)
then Result := string(res);
// psia := GetSidIdentifierAuthority(objSID);
// dwSubAuthorities := GetSidSubAuthorityCount(objSID)^;
//
// result := Format('S-%u-', [dwSidRev]);
//
// if (psia^.Value[0] <> 0) or (psia^.Value[1] <> 0) then
// result := result + format('0x%02x%02x%02x%02x%02x%02x', [
// psia^.Value[0],
// psia^.Value[1],
// psia^.Value[2],
// psia^.Value[3],
// psia^.Value[4],
// psia^.Value[5]])
// else
// result := result + format('%u', [
// DWORD(psia^.Value[5]) +
// DWORD(psia^.Value[4] shl 8) +
// DWORD(psia^.Value[3] shl 16) +
// DWORD(psia^.Value[2] shl 24)
// ]);
//
// for dwCounter := 0 to dwSubAuthorities - 1 do
// result := result + Format('-%u', [GetSidSubAuthority(objSID, dwCounter)^])
end;
function SIDToString(objSID: OleVariant): string;
var
pSID: Pointer;
begin
pSID := VarArrayLock(objSID);
try
Result := SIDToString(pSID);
finally
VarArrayUnlock(objSID);
end;
end;
function ADEscapeReservedCharacters(AValue: string): string;
var
res: string;
begin
res := AValue;
if AValue.IsEmpty then Exit;
{ Важно сначала заменить символ "\" }
res := ReplaceStr(res, '\', '\5C');
res := ReplaceStr(res, ',', '\2C');
res := ReplaceStr(res, '+', '\2B');
res := ReplaceStr(res, '"', '\22');
res := ReplaceStr(res, '<', '\3C');
res := ReplaceStr(res, '>', '\3E');
res := ReplaceStr(res, ';', '\3B');
res := ReplaceStr(res, '=', '\3D');
res := ReplaceStr(res, '/', '\2F');
res := ReplaceStr(res, '#', '\#');
res := ReplaceStr(res, #10{LF}, '\0A');
res := ReplaceStr(res, #13{CR}, '\0D');
if res[Length(res)] = ' '
then Insert('\20', res, Length(res));
if res[1] = ' '
then Insert('\20', res, 1);
Result := res;
end;
function DateTimeToADDate(ADate: TDateTime): ActiveDs_TLB._LARGE_INTEGER;
var
LocalTime: Winapi.Windows.TFileTime;
SystemTime: TSystemTime;
FileTime : Winapi.Windows.TFileTime;
ULargeInt: ULARGE_INTEGER;
begin
DateTimeToSystemTime(ADate, SystemTime);
if SystemTimeToFileTime(SystemTime, LocalTime) then
if LocalFileTimeToFileTime(LocalTime, FileTime) then
begin
ULargeInt.HighPart := FileTime.dwHighDateTime;
ULargeInt.LowPart := FileTime.dwLowDateTime;
Result.QuadPart := ULargeInt.QuadPart;
end;
end;
function ADDateToDateTime(ADDate: DATE_TIME): System.TDateTime;
var
int64Value: Int64;
LocalTime: TFileTime;
SystemTime: TSystemTime;
FileTime : TFileTime;
begin
try
int64Value := ADDate.dwHighDateTime;
int64Value := int64Value shl 32;
int64Value := int64Value + ADDate.dwLowDateTime;
Result := EncodeDate(1601,1,1);
FileTime := TFileTime(int64Value);
if FileTimeToLocalFileTime(FileTime, LocalTime) then
if FileTimeToSystemTime(LocalTime, SystemTime) then
Result := SystemTimeToDateTime(SystemTime);
except
Result := 0;
end;
end;
function ADDateToDateTime(ADDate: ActiveDs_TLB._LARGE_INTEGER): System.TDateTime;
var
int64Value: Int64;
LocalTime: TFileTime;
SystemTime: TSystemTime;
FileTime : TFileTime;
begin
// Result := EncodeDate(1601,1,1);
Result := 0;
if ADDate.QuadPart = 0 then Result := 0 else
try
{int64Value := LastLogon.HighPart;
int64Value := int64Value shl 32;
int64Value := int64Value + LastLogon.LowPart;}
int64Value := ADDate.QuadPart;
FileTime := TFileTime(int64Value);
if FileTimeToLocalFileTime(FileTime, LocalTime) then
if FileTimeToSystemTime(LocalTime, SystemTime) then
Result := SystemTimeToDateTime(SystemTime);
except
end;
end;
function ADDateToDateTime(ADDate: OleVAriant): System.TDateTime;
var
d: LARGE_INTEGER;
val: ActiveDS_TLB._LARGE_INTEGER;
begin
d.HighPart := (IDispatch(ADDate) as IADsLargeInteger).HighPart;
d.LowPart := (IDispatch(ADDate) as IADsLargeInteger).LowPart;
if d.LowPart > 0 then
begin
d.QuadPart := d.HighPart;
d.QuadPart := d.QuadPart shl 32;
d.QuadPart := d.QuadPart + d.LowPart;
val.QuadPart := d.QuadPart;
Result := ADDateToDateTime(val)
end;
// val.QuadPart :=
// (UInt64(IADsLargeInteger(IDispatch(ADDate)).HighPart) shl 32)
// + UInt64(IADsLargeInteger(IDispatch(ADDate)).LowPart );
// Result := ADDateToDateTime(val);
end;
function CalcPasswordExpiration(const PwdLastSet: ActiveDs_TLB._LARGE_INTEGER;
MaxPwdAge: Integer): System.TDateTime;
var
d: System.TDateTime;
begin
d := ADDateToDateTime(PwdLastSet);
if d > 0
then Result := IncSecond(d, MaxPwdAge)
else Result := 0;
end;
function ADCheckPasswordComplexity(ADomainName, APassword: string): Boolean;
const
NERR_Success = 0;
var
InputArg: TNetValidatePasswordChangeInputArg;
pInputArg: PNetValidatePasswordChangeInputArg;
pOutputArg: PNetValidateOutputArg;
Res: DWORD;
begin
Result := False;
FillChar(InputArg, sizeof(InputArg), 0);
InputArg.ClearPassword := LPWSTR(APassword);
InputArg.PasswordMatch := True;
PInputArg := @InputArg;
Res := NetValidatePasswordPolicy(
LPWSTR('\\' + ADomainName),
nil,
NetValidatePasswordChange,
LPVOID(pInputArg),
LPVOID(pOutputArg)
);
if Res = NERR_Success then
begin
if (pOutputArg <> nil) and (pOutputArg^.ValidationStatus = 0)
then Result := True;
end else Result := True;
NetValidatePasswordPolicyFree(LPVOID(pOutputArg));
end;
procedure ADEnumDomainControllers(const outDCList: TStrings);
type
PDomainsArray = ^TDomainsArray;
TDomainsArray = array [1..100] of DS_DOMAIN_TRUSTS;
var
i: Integer;
dwRet: DWORD;
ulSocketCount: UINT;
Domains: PDomainsArray;
begin
for i := 0 to outDCList.Count - 1 do
if outDCList.Objects[i] <> nil then outDCList.Objects[i].Free;
outDCList.Clear;
dwRet := DsEnumerateDomainTrusts(
nil,
DS_DOMAIN_PRIMARY {or DS_DOMAIN_IN_FOREST or DS_DOMAIN_DIRECT_OUTBOUND},
PDS_DOMAIN_TRUSTS(Domains),
ulSocketCount
);
if dwRet = ERROR_SUCCESS then
for i := 1 to ulSocketCount do
begin
outDCList.Add(Domains[i].DnsDomainName);
end;
NetApiBufferFree(Domains);
end;
procedure ADEnumContainers(ARootDSE: IADs; const outList: TStrings);
var
v: OleVariant;
DomainHostName: string;
DomainDN: string;
dcPathName: string;
hr: HRESULT ;
SearchRes: IDirectorySearch;
SearchPrefs: array of ADS_SEARCHPREF_INFO;
hSearch: THandle;
Attributes: array of WideString;
col: ADS_SEARCH_COLUMN;
i, j: Integer;
outStr: string;
contData: PADContainer;
AdValue: PAdsValueArray;
begin
for i := 0 to outList.Count - 1 do
if outList.Objects[i] <> nil
then Dispose(PADContainer(outList.Objects[i]));
outList.Clear;
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
DomainHostName := VariantToStringWithDefault(v, '');
VariantClear(v);
v := ARootDSE.Get('defaultNamingContext');
DomainDN := VariantToStringWithDefault(v, '');
VariantClear(v);
New(contData);
with contData^ do
begin
Category := 0;
DistinguishedName := DomainDN;
CanonicalName := ReplaceText(
ReplaceText(
DomainDN,
',DC=',
'.'
),
'DC=',
''
);
end;
outList.AddObject(contData^.CanonicalName, TObject(contData));
hr := ADsOpenObject(
PChar('LDAP://' + DomainHostName + '/' + DomainDN),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IDirectorySearch,
@SearchRes
);
if SUCCEEDED(hr) then
begin
SetLength(SearchPrefs, 3);
with SearchPrefs[0] do
begin
dwSearchPref := ADS_SEARCHPREF_PAGESIZE;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 1000;
end;
with SearchPrefs[1] do
begin
dwSearchPref := ADS_SEARCHPREF_PAGED_TIME_LIMIT;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 60;
end;
with SearchPrefs[2] do
begin
dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADS_SCOPE_SUBTREE;
end;
hr := SearchRes.SetSearchPreference(SearchPrefs[0], Length(SearchPrefs));
SetLength(Attributes, 6);
Attributes := [
'name',
'distinguishedName',
'canonicalName',
'objectCategory',
'systemFlags',
'allowedChildClasses'
];
SearchRes.ExecuteSearch(
PChar(
'(|' +
'(&(ObjectCategory=organizationalUnit)(ou=*))' +
'(objectCategory=container)' +
'(objectCategory=builtinDomain)' +
'(objectClass=msExchSystemObjectsContainer)' +
')'
),
PWideChar(@Attributes[0]),
Length(Attributes),
LPVOID(hSearch)
);
hr := SearchRes.GetNextRow(LPVOID(hSearch));
while (hr <> S_ADS_NOMORE_ROWS) do
begin
New(contData);
for i := Low(Attributes) to High(Attributes) do
begin
j := 0;
hr := SearchRes.GetColumn(LPVOID(hSearch), PWideChar(Attributes[i]), col);
if Succeeded(hr)then
case i of
0: begin
contData^.name := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
end;
1: begin
contData^.DistinguishedName := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
end;
2: begin
outStr := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
contData^.CanonicalName := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
end;
3: begin
if ContainsText(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString, 'Organizational-Unit')
then contData^.Category := AD_CONTCAT_ORGUNIT
else contData^.Category := AD_CONTCAT_CONTAINER
end;
4: begin
contData^.systemFlags := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.Integer;
end;
5: begin
AdValue := PAdsValueArray(col.pADsValues);
for j := 0 to col.dwNumValues - 1 do
begin
if j > 0 then contData^.allowedChildClasses := contData^.allowedChildClasses + ',';
contData^.allowedChildClasses := contData^.allowedChildClasses
+ string(AdValue^[j].__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString);
end;
end;
end;
SearchRes.FreeColumn(col);
end;
outList.AddObject(outStr, TObject(contData));
hr := SearchRes.GetNextRow(LPVOID(hSearch));
end;
SearchRes.CloseSearchHandle(LPVOID(hSearch));
end;
except
on e:Exception do
begin
OutputDebugString(PChar(e.Message));
end;
end;
CoUninitialize;
end;
procedure ADEnumContainers(ALDAP: PLDAP; const outList: TStrings);
const
AttrArray: array of AnsiString = [
'name',
'distinguishedName',
'canonicalName',
'objectCategory',
'systemFlags',
'allowedChildClasses'
];
var
returnCode: ULONG;
errorCode: ULONG;
morePages: Boolean;
ldapBase: AnsiString;
ldapFilter: AnsiString;
ldapCookie: PLDAPBerVal;
ldapPage: PLDAPControl;
ldapControls: array[0..1] of PLDAPControl;
ldapServerControls: PPLDAPControl;
ldapCount: ULONG;
ldapSearchResult: PLDAPMessage;
ldapAttributes: array of PAnsiChar;
ldapEntry: PLDAPMessage;
ldapValues: PPAnsiChar;
ldapBinValues: PPLDAPBerVal;
i: Integer;
ldapClass: string;
attr: AnsiString;
outStr: string;
contData: PADContainer;
begin
for i := 0 to outList.Count - 1 do
if outList.Objects[i] <> nil
then Dispose(PADContainer(outList.Objects[i]));
outList.Clear;
if not Assigned(ALDAP) then Exit;
ldapCookie := nil;
ldapSearchResult := nil;
// Получаем имя домена
returnCode := ldap_search_ext_s(
ALDAP,
nil,
LDAP_SCOPE_BASE,
PAnsiChar('(objectclass=*)'),
nil,
0,
nil,
nil,
nil,
0,
ldapSearchResult
);
if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(ALDAP, ldapSearchResult) > 0 ) then
begin
ldapEntry := ldap_first_entry(ALDAP, ldapSearchResult);
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar('defaultNamingContext'));
if ldapValues <> nil then
begin
ldapBase := ldapValues^;
New(contData);
with contData^ do
begin
Category := 0;
DistinguishedName := ldapBase;
CanonicalName := ReplaceText(
ReplaceText(
ldapBase,
',DC=',
'.'
),
'DC=',
''
);
end;
outList.AddObject(contData^.CanonicalName, TObject(contData));
end;
ldap_value_free(ldapValues);
end;
if ldapSearchResult <> nil
then ldap_msgfree(ldapSearchResult);
{ Формируем набор атрибутов }
SetLength(ldapAttributes, Length(AttrArray) + 1);
for i := Low(AttrArray) to High(AttrArray) do
ldapAttributes[i] := PAnsiChar(AttrArray[i]);
try
{ Формируем фильтр объектов AD }
ldapFilter := '(|' +
'(&(ObjectCategory=organizationalUnit)(ou=*))' +
'(objectCategory=container)' +
'(objectCategory=builtinDomain)' +
'(objectClass=msExchSystemObjectsContainer)' +
')';
{ Постраничный поиск объектов AD }
repeat
returnCode := ldap_create_page_control(
ALDAP,
1000,
ldapCookie,
1,
ldapPage
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create('Failure during ldap_create_page_control.');
ldapControls[0] := ldapPage;
ldapControls[1] := nil;
returnCode := ldap_search_ext_s(
ALDAP,
PAnsiChar(ldapBase),
LDAP_SCOPE_SUBTREE,
PAnsiChar(ldapFilter),
PAnsiChar(@ldapAttributes[0]),
0,
@ldapControls,
nil,
nil,
0,
ldapSearchResult
);
if not (returnCode in [LDAP_SUCCESS, LDAP_PARTIAL_RESULTS])
then raise Exception.Create('Failure during ldap_search_ext_s.');
returnCode := ldap_parse_result(
ALDAP^,
ldapSearchResult,
@errorCode,
nil,
nil,
nil,
ldapServerControls,
False
);
if ldapCookie <> nil then
begin
ber_bvfree(ldapCookie);
ldapCookie := nil;
end;
returnCode := ldap_parse_page_control(
ALDAP,
ldapServerControls,
ldapCount,
ldapCookie
);
if (ldapCookie <> nil) and (ldapCookie.bv_val <> nil) and (System.SysUtils.StrLen(ldapCookie.bv_val) > 0)
then morePages := True
else morePages := False;
if ldapServerControls <> nil then
begin
ldap_controls_free(ldapServerControls);
ldapServerControls := nil;
end;
ldapControls[0]:= nil;
ldap_control_free(ldapPage);
ldapPage := nil;
{ Обработка результатов }
ldapEntry := ldap_first_entry(ALDAP, ldapSearchResult);
while ldapEntry <> nil do
begin
New(contData);
for attr in AttrArray do
begin
i := 0;
if Assigned(ldapValues) then
case IndexText(attr, ['name', 'distinguishedName', 'canonicalName', 'objectCategory', 'systemFlags', 'allowedChildClasses']) of
0: begin
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar(attr));
if ldapValues <> nil
then contData^.name := ldapValues^;
ldap_value_free(ldapValues);
end;
1: begin
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar(attr));
if ldapValues <> nil
then contData^.DistinguishedName := ldapValues^;
ldap_value_free(ldapValues);
end;
2: begin
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar(attr));
if ldapValues <> nil then
begin
outStr := ldapValues^;
contData^.CanonicalName := ldapValues^;
end;
ldap_value_free(ldapValues);
end;
3: begin
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar(attr));
if ldapValues <> nil then
if ContainsText(ldapValues^, 'Organizational-Unit')
then contData^.Category := AD_CONTCAT_ORGUNIT
else contData^.Category := AD_CONTCAT_CONTAINER;
ldap_value_free(ldapValues);
end;
4: begin
ldapBinValues := ldap_get_values_len(ALDAP, ldapEntry, PAnsiChar(attr));
if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0)
then contData^.systemFlags := StrToIntDef(ldapBinValues^.bv_val, 0);
ldap_value_free_len(ldapBinValues);
end;
5: begin
ldapValues := ldap_get_values(ALDAP, ldapEntry, PAnsiChar(attr));
if ldapValues <> nil then
while ldapValues^ <> nil do
begin
if i > 0 then contData^.allowedChildClasses := contData^.allowedChildClasses + ',';
contData^.allowedChildClasses := contData^.allowedChildClasses + ldapValues^;
Inc(ldapValues);
Inc(i);
end;
Dec(ldapValues, i);
ldap_value_free(ldapValues);
end;
end;
end;
outList.AddObject(outStr, TObject(contData));
ldapEntry := ldap_next_entry(ALDAP, ldapEntry);
end;
ldap_msgfree(ldapSearchResult);
ldapSearchResult := nil;
until (morePages = False);
ber_bvfree(ldapCookie);
ldapCookie := nil;
except
on e:Exception do
begin
OutputDebugString(PChar(e.Message));
end;
end;
if ldapSearchResult <> nil
then ldap_msgfree(ldapSearchResult);
end;
function DameWareMRC_Connect(const Executable, MachineName: string; key_a: Integer;
key_u, key_p, key_d: string; key_md, key_r, AutoConnect, ViewOnly: Boolean): Boolean;
var
CmdLine: string;
StartInfo: TStartupInfo;
ProcInfo: TProcessInformation;
begin
Result := False;
CmdLine := '"' + Executable + '"';
if AutoConnect then CmdLine := CmdLine + ' -c:';
CmdLine := CmdLine + ' -m:' + MachineName;
if key_r then
begin
CmdLine := CmdLine + ' -u:' + key_u;
CmdLine := CmdLine + ' -p:' + key_p;
CmdLine := CmdLine + ' -d:' + key_d;
CmdLine := CmdLine + ' -r:';
end else
begin
case key_a of
0: begin
CmdLine := CmdLine + ' -a:' + IntToStr(key_a);
CmdLine := CmdLine + ' -u:' + key_u;
CmdLine := CmdLine + ' -p:' + key_p;
end;
1..2: begin
CmdLine := CmdLine + ' -a:' + IntToStr(key_a);
CmdLine := CmdLine + ' -u:' + key_u;
CmdLine := CmdLine + ' -p:' + key_p;
CmdLine := CmdLine + ' -d:' + key_d;
end;
3: begin
CmdLine := CmdLine + ' -a:' + IntToStr(key_a);
CmdLine := CmdLine + ' -p:' + key_p;
end;
4: begin
CmdLine := CmdLine + ' -a:' + IntToStr(1);
end;
end;
end;
if key_md then CmdLine := CmdLine + ' -md:';
if ViewOnly then CmdLine := CmdLine + ' -v:';
CmdLine := CmdLine + ' -x:';
FillChar(StartInfo, SizeOf(StartInfo), #0);
FillChar(ProcInfo, SizeOf(StartInfo), #0);
with StartInfo do
begin
cb := SizeOf(StartInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := SW_SHOWDEFAULT;
end;
if CreateProcess(nil, PChar(CmdLine), nil, nil, False,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil,
PChar(ExtractFileDir(Executable)), StartInfo, ProcInfo) then
begin
//WaitForSingleObject(ProcInfo.hProcess, INFINITE);
{case WaitForSingleObject(ProcInfo.hProcess, 30000) of
WAIT_TIMEOUT : begin
TerminateProcess(ProcInfo.hProcess, 0);
end;
WAIT_FAILED : begin
TerminateProcess(ProcInfo.hProcess, 0);
end;
end;}
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
Result := True;
end;
end;
function EncodeIP(AIP: string): Cardinal;
type
TIP4Address = packed record
a: Byte;
b: Byte;
c: Byte;
d: Byte;
end;
var
_Result: TIP4Address absolute Result;
strArr: TStringDynArray;
begin
Result := 0;
strArr := SplitString(AIP, '.');
_Result.a := StrToInt(strArr[0]);
_Result.b := StrToInt(strArr[1]);
_Result.c := StrToInt(strArr[2]);
_Result.d := StrToInt(strArr[3]);
end;
{ Альтернативная реализация EncodeIP }
//function EncodeIP(AIP: string): Cardinal;
//var
// strArr: TStringDynArray;
//begin
// Result := 0;
// strArr := SplitString(AIP, '.');
// Result := (StrToInt(strArr[0]) shl 24) + (StrToInt(strArr[1]) shl 16) + (StrToInt(strArr[2]) shl 8) + StrToInt(strArr[3]);
//end;
function DecodeIP(AIP: Cardinal): string;
begin
Result := Format(
'%d.%d.%d.%d',
[
(AIP shr 24),
(AIP shr 16) and $FF,
(AIP shr 8) and $FF,
AIP and $FF
]
);
end;
procedure GetIPAddress(AClient: string; out AInfo: PIPAddr);
var
wsa: WSAData;
iRes: Integer;
aiRes: PAddrInfo;
aiPtr: PAddrInfo;
hints: PAddrInfo;
sockaddr_ipv4: PSOCKADDR_IN;
nodeName: AnsiString;
begin
nodeName := AClient;
ZeroMemory(AInfo, SizeOf(TIPAddr));
try
iRes := WSAStartup(MAKEWORD(2, 2), wsa);
if iRes <> 0
then raise Exception.Create(Format('WSAStartup failed. Error: %d', [iRes]));
hints := nil;
New(hints);
ZeroMemory(hints, SizeOf(addrinfo));
hints^.ai_flags := AI_FQDN;
hints^.ai_family := AF_INET;
hints^.ai_socktype := SOCK_STREAM;
hints^.ai_protocol := IPPROTO_TCP;
aiRes := nil;
iRes := getaddrinfo(
PAnsiChar(nodeName),
nil,
hints,
aiRes
);
if iRes <> 0
then raise Exception.Create(Format('getaddrinfo failed. Error: %d', [iRes]));
aiPtr := aiRes;
while aiPtr <> nil do
begin
case aiPtr.ai_family of
AF_UNSPEC: ;
AF_INET: begin
AInfo^.FQDN := aiPtr.ai_canonname;
sockaddr_ipv4 := PSOCKADDR_IN(aiPtr.ai_addr);
AInfo^.v4 := inet_ntoa(sockaddr_ipv4.sin_addr);
{ Получаем IP только из первого интерфейса }
Break;
end;
AF_NETBIOS: ;
AF_INET6: ;
AF_IRDA: ;
AF_BTH: ;
end;
aiPtr := aiPtr.ai_next;
end;
except
on e: Exception do
begin
end;
end;
WSACleanup;
sockaddr_ipv4 := nil;
aiPtr := nil;
if hints <> nil then
begin
Dispose(hints);
hints := nil;
end;
if aiRes <> nil then
begin
freeaddrinfo(aiRes);
aiRes := nil;
end;
end;
procedure GetDHCPInfo(AClient: string; out AInfo: PDHCPInfo);
var
DhcpGetClientInfo: TDhcpGetClientInfo;
i: integer;
returnCode: DWORD;
srvArr: PDHCPDS_SERVERS;
psInfo: LPDHCP_SEARCH_INFO;
pcInfo: PDHCP_CLIENT_INFO;
clientName: string;
begin
@DhcpGetClientInfo := GetProcAddress(
GetModuleHandle(PChar('dhcpsapi.dll')),
PChar('DhcpGetClientInfo')
);
if Assigned(DhcpGetClientInfo) then
begin
clientName := LowerCase(AClient);
srvArr := nil;
ZeroMemory(AInfo, SizeOf(TDHCPInfo));
returnCode := DhcpEnumServers(
0,
nil,
@srvArr,
nil,
nil
);
if (returnCode = ERROR_SUCCESS) then
begin
psInfo := HeapAlloc(GetProcessHeap, HEAP_ZERO_MEMORY, SizeOf(DHCP_SEARCH_INFO));
pcInfo := nil;
for i := 0 to srvArr.NumElements - 1 do
begin
psInfo^.SearchType := _DHCP_CLIENT_SEARCH_TYPE.DhcpClientName;
psInfo^.searchInfo.ClientName := PWideChar(clientName);
returnCode := DhcpGetClientInfo(
PChar(DecodeIP(srvArr^.Servers[i].ServerAddress)),
psInfo,
@pcInfo
);
if (returnCode = ERROR_SUCCESS) then
begin
AInfo^.ServerName := string(pcInfo^.OwnerHost.HostName);
AInfo^.ServerNetBIOSName := string(pcInfo^.OwnerHost.NetBiosName);
AInfo^.ServerAddress := DecodeIP(pcInfo^.OwnerHost.IpAddress{srvArr.Servers[i].ServerAddress});
AInfo^.HardwareAddress := Format(
'%.2x-%.2x-%.2x-%.2x-%.2x-%.2x',
[
pcInfo^.ClientHardwareAddress.Data[0],
pcInfo^.ClientHardwareAddress.Data[1],
pcInfo^.ClientHardwareAddress.Data[2],
pcInfo^.ClientHardwareAddress.Data[3],
pcInfo^.ClientHardwareAddress.Data[4],
pcInfo^.ClientHardwareAddress.Data[5]
]
);
AInfo^.IPAddress.FQDN := string(pcInfo^.ClientName);
AInfo^.IPAddress.v4 := DecodeIP(pcInfo^.ClientIpAddress);
AInfo^.SubnetMask := DecodeIP(pcInfo^.SubnetMask);
AInfo^.LeaseExpires := ADDateToDateTime(pcInfo^.ClientLeaseExpires);
Break;
end;
FreeDHCPClientInfoMemory(pcInfo);
end;
HeapFree(GetProcessHeap, HEAP_ZERO_MEMORY, psInfo);
psInfo := nil;
end;
end;
end;
procedure GetDHCPInfoEx(AClient: string; out AInfo: PDHCPInfo);
var
i: Integer;
bFound: Boolean;
returnCode: DWORD;
aServers: PDHCPDS_SERVERS;
retSubnets: DWORD;
hSubnetsResume: DHCP_RESUME_HANDLE;
aSubnets: LPDHCP_IP_ARRAY;
iSubnets: Integer;
Subnets: LPDHCP_IP_ADDRESS;
SubnetCount: Integer;
retClients: DWORD;
hClientsResume: DHCP_RESUME_HANDLE;
aClients: LPDHCP_CLIENT_INFO_ARRAY;
iClients: Integer;
Clients: LPDHCP_CLIENT_INFO;
ClientCount: Integer;
ElementsRead: DWORD;
ElementsTotal: DWORD;
begin
bFound := False;
aServers := nil;
ZeroMemory(AInfo, SizeOf(TDHCPInfo));
returnCode := DhcpEnumServers(
0,
nil,
@aServers,
nil,
nil
);
if (returnCode = ERROR_SUCCESS) then
for i := 0 to aServers.NumElements - 1 do
begin
hSubnetsResume := 0;
ElementsRead := 0;
ElementsTotal := 0;
repeat
aSubnets := nil;
retSubnets := DhcpEnumSubnets(
PChar(DecodeIP(aServers^.Servers[i].ServerAddress)),
hSubnetsResume,
500,
@aSubnets,
ElementsRead,
ElementsTotal
);
if retSubnets = ERROR_SUCCESS then
begin
SubnetCount := aSubnets^.NumElements;
Subnets := aSubnets^.Elements;
iSubnets := 0;
while iSubnets < SubnetCount do
begin
hClientsResume := 0;
ElementsRead := 0;
ElementsTotal := 0;
repeat
aClients := nil;
retClients := DhcpEnumSubnetClients(
PChar(DecodeIP(aServers^.Servers[i].ServerAddress)),
DHCP_IP_ADDRESS(Subnets^),
hClientsResume,
65536,
@aClients,
ElementsRead,
ElementsTotal
);
if retClients in [ERROR_SUCCESS, ERROR_MORE_DATA] then
begin
ClientCount := aClients^.NumElements;
Clients := aClients^.Clients;
iClients := 0;
while iClients < ClientCount do
begin
if CompareText(AClient, Clients^.ClientName) = 0 then
begin
AInfo^.ServerName := string(Clients^.OwnerHost.HostName);
AInfo^.ServerNetBIOSName := string(Clients^.OwnerHost.NetBiosName);
AInfo^.ServerAddress := DecodeIP(Clients^.OwnerHost.IpAddress{srvArr.Servers[i].ServerAddress});
AInfo^.HardwareAddress := Format(
'%.2x-%.2x-%.2x-%.2x-%.2x-%.2x',
[
Clients^.ClientHardwareAddress.Data[0],
Clients^.ClientHardwareAddress.Data[1],
Clients^.ClientHardwareAddress.Data[2],
Clients^.ClientHardwareAddress.Data[3],
Clients^.ClientHardwareAddress.Data[4],
Clients^.ClientHardwareAddress.Data[5]
]
);
AInfo^.IPAddress.FQDN := string(Clients^.ClientName);
AInfo^.IPAddress.v4 := DecodeIP(Clients^.ClientIpAddress);
AInfo^.SubnetMask := DecodeIP(Clients^.SubnetMask);
AInfo^.LeaseExpires := ADDateToDateTime(Clients^.ClientLeaseExpires);
// GetDHCPInfo(Clients^.ClientName, AInfo);
bFound := True;
Break;
end;
Inc(Clients);
Inc(iClients);
end;
end;
if bFound then Break;
Inc(Subnets);
Inc(iSubnets);
until retClients <> ERROR_MORE_DATA;
if bFound then Break;
end;
end;
DhcpRpcFreeMemory(aSubnets);
if bFound then Break;
until retSubnets <> 0;
if bFound then Break;
end;
end;
procedure GetDHCPInfoV4(AClient: string; out AInfo: PDHCPInfo);
var
DhcpV4GetClientInfo: TDhcpV4GetClientInfo;
i: integer;
returnCode: DWORD;
srvArr: PDHCPDS_SERVERS;
psInfo: LPDHCP_SEARCH_INFO;
pcInfo: LPDHCP_CLIENT_INFO_PB;
clientName: string;
begin
@DhcpV4GetClientInfo := GetProcAddress(
GetModuleHandle(PChar('dhcpsapi.dll')),
PChar('DhcpV4GetClientInfo')
);
if Assigned(DhcpV4GetClientInfo) then
begin
clientName := LowerCase(AClient);
srvArr := nil;
ZeroMemory(AInfo, SizeOf(TDHCPInfo));
returnCode := DhcpEnumServers(
0,
nil,
@srvArr,
nil,
nil
);
if (returnCode = ERROR_SUCCESS) then
begin
psInfo := HeapAlloc(GetProcessHeap, HEAP_ZERO_MEMORY, SizeOf(DHCP_SEARCH_INFO));
pcInfo := nil;
for i := 0 to srvArr.NumElements - 1 do
begin
psInfo^.SearchType := _DHCP_CLIENT_SEARCH_TYPE.DhcpClientName;
psInfo^.searchInfo.ClientName := PWideChar(clientName);
returnCode := DhcpV4GetClientInfo(
PChar(DecodeIP(srvArr^.Servers[i].ServerAddress)),
psInfo,
@pcInfo
);
if (returnCode = ERROR_SUCCESS) then
begin
AInfo^.ServerName := string(pcInfo^.OwnerHost.HostName);
AInfo^.ServerNetBIOSName := string(pcInfo^.OwnerHost.NetBiosName);
AInfo^.ServerAddress := DecodeIP(pcInfo^.OwnerHost.IpAddress{srvArr.Servers[i].ServerAddress});
AInfo^.HardwareAddress := Format(
'%.2x-%.2x-%.2x-%.2x-%.2x-%.2x',
[
pcInfo^.ClientHardwareAddress.Data[0],
pcInfo^.ClientHardwareAddress.Data[1],
pcInfo^.ClientHardwareAddress.Data[2],
pcInfo^.ClientHardwareAddress.Data[3],
pcInfo^.ClientHardwareAddress.Data[4],
pcInfo^.ClientHardwareAddress.Data[5]
]
);
AInfo^.IPAddress.FQDN := string(pcInfo^.ClientName);
AInfo^.IPAddress.v4 := DecodeIP(pcInfo^.ClientIpAddress);
AInfo^.SubnetMask := DecodeIP(pcInfo^.SubnetMask);
AInfo^.LeaseExpires := ADDateToDateTime(pcInfo^.ClientLeaseExpires);
Break;
end;
FreeDHCPClientInfoMemory(pcInfo);
pcInfo := nil;
end;
HeapFree(GetProcessHeap, HEAP_ZERO_MEMORY, psInfo);
psInfo := nil;
end;
end;
end;
procedure FreeDHCPClientInfoMemory(pClientInfo: PDHCP_CLIENT_INFO);
begin
if Assigned(pClientInfo) then
begin
{ Frees client name }
if Assigned(pClientInfo^.ClientName)
then DhcpRpcFreeMemory(pClientInfo^.ClientName);
{ Frees client comments }
if Assigned(pClientInfo^.ClientComment)
then DhcpRpcFreeMemory(pClientInfo^.ClientComment);
{ Frees the ClientHardwareAddress }
if Assigned(pClientInfo^.ClientHardwareAddress.Data) and (pClientInfo^.ClientHardwareAddress.DataLength > 0)
then DhcpRpcFreeMemory(pClientInfo^.ClientHardwareAddress.Data);
{ Frees the HostName }
if Assigned(pClientInfo^.OwnerHost.HostName)
then DhcpRpcFreeMemory(pClientInfo^.OwnerHost.HostName);
{ Frees the NetBiosName }
if Assigned(pClientInfo^.OwnerHost.NetBiosName)
then DhcpRpcFreeMemory(pClientInfo^.OwnerHost.NetBiosName);
{ Frees the clientInfo }
DhcpRpcFreeMemory(pClientInfo);
end;
end;
procedure FreeDHCPClientInfoMemory(pClientInfo: LPDHCP_CLIENT_INFO_PB);
begin
if Assigned(pClientInfo) then
begin
{ Frees client name }
if Assigned(pClientInfo^.ClientName)
then DhcpRpcFreeMemory(pClientInfo^.ClientName);
{ Frees policy name }
if Assigned(pClientInfo^.PolicyName)
then DhcpRpcFreeMemory(pClientInfo^.PolicyName);
{ Frees client comments }
if Assigned(pClientInfo^.ClientComment)
then DhcpRpcFreeMemory(pClientInfo^.ClientComment);
{ Frees the ClientHardwareAddress }
if Assigned(pClientInfo^.ClientHardwareAddress.Data) and (pClientInfo^.ClientHardwareAddress.DataLength > 0)
then DhcpRpcFreeMemory(pClientInfo^.ClientHardwareAddress.Data);
{ Frees the HostName }
if Assigned(pClientInfo^.OwnerHost.HostName)
then DhcpRpcFreeMemory(pClientInfo^.OwnerHost.HostName);
{ Frees the NetBiosName }
if Assigned(pClientInfo^.OwnerHost.NetBiosName)
then DhcpRpcFreeMemory(pClientInfo^.OwnerHost.NetBiosName);
{ Frees the clientInfo }
DhcpRpcFreeMemory(pClientInfo);
end;
end;
procedure ServerBinding(ADcDnsName: string; out ALDAP: PLDAP;
AOnException: TExceptionProc);
var
returnCode: ULONG;
optValue: ULONG;
secIdent: SEC_WINNT_AUTH_IDENTITY;
hostName: AnsiString;
pDN: AnsiString;
pUserName: AnsiString;
pPassword: AnsiString;
begin
ldap_unbind(ALDAP);
hostName := ADcDnsName;
ALDAP := nil;
// ALDAP := ldap_sslinit(PAnsiChar(hostName), LDAP_SSL_PORT, 1);
ALDAP := ldap_init(PAnsiChar(hostName), LDAP_PORT);
returnCode := GetLastError;
try
if ALDAP = nil
then raise Exception.Create(
Format(
'Init of server %s at port %d failed. %s',
[hostName, LDAP_PORT, ldap_err2string(returnCode)]
)
);
optValue := LDAP_VERSION3;
returnCode := ldap_set_option(
ALDAP,
LDAP_OPT_PROTOCOL_VERSION,
@optValue
);
optValue := LDAP_NO_LIMIT;
returnCode := ldap_set_option(
ALDAP,
LDAP_OPT_SIZELIMIT,
@optValue
);
returnCode := ldap_set_option(
ALDAP,
LDAP_OPT_AUTO_RECONNECT,
LDAP_OPT_ON
);
// returnCode := ldap_set_option(
// ALDAP,
// LDAP_OPT_ENCRYPT,
// LDAP_OPT_ON
// );
returnCode := ldap_set_option(
ALDAP,
LDAP_OPT_AREC_EXCLUSIVE,
LDAP_OPT_ON
);
{ Отключаем опцию LDAP_OPT_REFERRALS, т.к. с ней не работает постарничный поиск }
returnCode := ldap_set_option(
ALDAP,
LDAP_OPT_REFERRALS,
LDAP_OPT_OFF
);
// if (returnCode <> LDAP_SUCCESS)
// then raise Exception.Create(
// Format(
// 'Failure during ldap_set_option. %s',
// [ldap_err2string(returnCode)]
// )
// );
returnCode := ldap_connect(ALDAP, nil);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(
Format(
'Failure during ldap_connect. %s',
[ldap_err2string(returnCode)]
)
);
{ https://msdn.microsoft.com/en-us/library/aa366156(v=vs.85).aspx }
{ To log in as the current user, set the dn and cred parameters to NULL. }
{ To log in as another user, set the dn parameter to NULL and the cred }
{ parameter to a pointer to a SEC_WINNT_AUTH_IDENTITY or }
{ SEC_WINNT_AUTH_IDENTITY_EX structure with the appropriate user name, }
{ domain name, and password. }
pDN := System.AnsiStrings.ReplaceText('DC=' + hostName, '.', ',DC=');
secIdent.User := PChar(pUserName);
secIdent.UserLength := Length(pUserName);
secIdent.Password := PChar(pPassword);
secIdent.PasswordLength := Length(pPassword);
secIdent.Domain := PChar(hostName);
secIdent.DomainLength := Length(hostName);
secIdent.Flags := SEC_WINNT_AUTH_IDENTITY_ANSI;
returnCode := ldap_bind_s(
ALDAP,
nil, //PAnsiChar(pDN),
nil, //@secIdent,
LDAP_AUTH_NEGOTIATE
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(
Format(
'Unable to Bind to the LDAP server. %s',
[ldap_err2string(returnCode)]
)
);
except
on E: Exception do
begin
ALDAP := nil;
if Assigned(AOnException)
then AOnException(E.Message, returnCode);
end;
end;
end;
procedure ServerBinding(ADcName: string;
ARootDSE: Pointer; AOnException: TExceptionProc);
var
hr: HRESULT;
addr: string;
begin
IADs(ARootDSE^) := nil;
CoInitialize(nil);
addr := ADcName;
hr := ADsOpenObject(
PChar('LDAP://' + addr + '/RootDSE'),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADs,
ARootDSE
);
if not Succeeded(hr) then
begin
IADs(ARootDSE^) := nil;
if Assigned(AOnException)
then AOnException('Can not bind to server ' + addr, hr);
end;
CoUninitialize;
end;
function ADCreateOU(ALDAP: PLDAP; AContainer: string; ANewOU: string): string;
var
ldapDN: AnsiString;
attrArray: array of PLDAPMod;
valClass: array of PAnsiChar;
valOU: array of PAnsiChar;
valSAMAccountName: array of PAnsiChar;
returnCode: ULONG;
i: Integer;
begin
Result := '';
if AContainer.IsEmpty or ANewOU.IsEmpty
then Exit;
ldapDN := Format('OU=%s,%s', [ADEscapeReservedCharacters(ANewOU), AContainer]);
SetLength(valClass, 3);
valClass[0] := PAnsiChar('top');
valClass[1] := PAnsiChar('organizationalUnit');
SetLength(valOU, 2);
valOU[0] := PAnsiChar(AnsiString(ANewOU));
SetLength(attrArray, 3);
New(attrArray[0]);
with attrArray[0]^ do
begin
mod_op := 0;
mod_type := PAnsiChar('objectClass');
modv_strvals := @valClass[0];
end;
New(attrArray[1]);
with attrArray[1]^ do
begin
mod_op := 0;
mod_type := PAnsiChar('ou');
modv_strvals := @valOU[0];
end;
try
returnCode := ldap_add_ext_s(
ALDAP,
PAnsiChar(ldapDN),
@attrArray[0],
nil,
nil
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(ldap_err2string(returnCode));
Result := ldapDN;
finally
for i := Low(attrArray) to High(attrArray) do
if Assigned(attrArray[i])
then Dispose(attrArray[i]);
end;
end;
function ADCreateOU(ARootDSE: IADS; AContainer: string; ANewOU: string): string;
var
v: OleVariant;
hostName: string;
hr: HRESULT;
ICont: IADsContainer;
INewCont: IADs;
begin
Result := '';
ICont := nil;
INewCont := nil;
if AContainer.IsEmpty or ANewOU.IsEmpty
then Exit;
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
hr := ADsOpenObject(
PChar(Format('LDAP://%s/%s', [hostName, AContainer])),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADsContainer,
@ICont
);
if Succeeded(hr) then
begin
INewCont := ICont.Create(
'organizationalUnit',
'OU=' + ADEscapeReservedCharacters(ANewOU)
) as IADs;
if INewCont <> nil then
begin
INewCont.SetInfo;
v := INewCont.Get('distinguishedName');
Result := VariantToStringWithDefault(v, '');
VariantClear(v);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
finally
CoUninitialize;
end;
end;
function ADCreateOUDS(ARootDSE: IADS; AContainer: string; ANewOU: string): string;
var
v: OleVariant;
hostName: string;
hr: HRESULT;
attrArray: array of ADS_ATTR_INFO;
valClass: ADSVALUE;
IDir: IDirectoryObject;
IDisp: IDispatch;
INewCont: IADs;
begin
Result := '';
IDir := nil;
INewCont := nil;
if AContainer.IsEmpty or ANewOU.IsEmpty
then Exit;
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
SetLength(attrArray, 1);
with attrArray[0] do
begin
pszAttrName := 'objectClass';
dwControlCode := ADS_ATTR_UPDATE;
dwADsType := ADSTYPE_CASE_IGNORE_STRING;
pADsValues := @valClass;
dwNumValues := 1;
end;
valClass.dwType := ADSTYPE_CASE_IGNORE_STRING;
valClass.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString := PChar('organizationalUnit');
hr := ADsOpenObject(
PChar(Format('LDAP://%s/%s', [hostName, AContainer])),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IDirectoryObject,
@IDir
);
if Succeeded(hr) then
begin
hr := IDir.CreateDSObject(
PChar('OU=' + ADEscapeReservedCharacters(ANewOU)),
@attrArray[0],
Length(attrArray),
IDisp
);
if Succeeded(hr) then
begin
hr := IDisp.QueryInterface(IID_IADsContainer, INewCont);
if not Succeeded(hr)
then raise Exception.Create(ADSIErrorToString);
v := INewCont.Get('distinguishedName');
Result := VariantToStringWithDefault(v, '');
VariantClear(v);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
finally
CoUninitialize;
end;
end;
function ADCreateGroup(ALDAP: PLDAP; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string;
var
ldapDN: AnsiString;
attrArray: array of PLDAPMod;
valClass: array of PAnsiChar;
valCN: array of PAnsiChar;
valSamAccountName: array of PAnsiChar;
valGroupType: array of PAnsiChar;
returnCode: ULONG;
i: Integer;
begin
Result := '';
if AContainer.IsEmpty or AName.IsEmpty or ASamAccountName.IsEmpty
then Exit;
ldapDN := Format('CN=%s,%s', [ADEscapeReservedCharacters(AName), AContainer]);
SetLength(valClass, 3);
valClass[0] := PAnsiChar('top');
valClass[1] := PAnsiChar('group');
SetLength(valCN, 2);
valCN[0] := PAnsiChar(AnsiString(AName));
SetLength(attrArray, 3);
New(attrArray[0]);
with attrArray[0]^ do
begin
mod_op := 0;
mod_type := PAnsiChar('objectClass');
modv_strvals := @valClass[0];
end;
New(attrArray[1]);
with attrArray[1]^ do
begin
mod_op := 0;
mod_type := PAnsiChar('cn');
modv_strvals := @valCN[0];
end;
try
returnCode := ldap_add_ext_s(
ALDAP,
PAnsiChar(ldapDN),
@attrArray[0],
nil,
nil
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(ldap_err2string(returnCode));
for i := Low(attrArray) to High(attrArray) do
if Assigned(attrArray[i])
then Dispose(attrArray[i]);
SetLength(valSamAccountName, 2);
valSamAccountName[0] := PAnsiChar(AnsiString(ASamAccountName));
SetLength(valGroupType, 2);
valGroupType[0] := PAnsiChar(AnsiString(IntToStr(AGroupType)));
SetLength(attrArray, 3);
New(attrArray[0]);
with attrArray[0]^ do
begin
mod_op := LDAP_MOD_REPLACE;
mod_type := PAnsiChar('samAccountName');
modv_strvals := @valSamAccountName[0];
end;
New(attrArray[1]);
with attrArray[1]^ do
begin
mod_op := LDAP_MOD_REPLACE;
mod_type := PAnsiChar('groupType');
modv_strvals := @valGroupType[0];
end;
returnCode := ldap_modify_ext_s(
ALDAP,
PAnsiChar(ldapDN),
@attrArray[0],
nil,
nil
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(ldap_err2string(returnCode));
Result := ldapDN;
finally
for i := Low(attrArray) to High(attrArray) do
if Assigned(attrArray[i])
then Dispose(attrArray[i]);
end;
end;
function ADCreateGroup(ARootDSE: IADS; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string;
var
v: OleVariant;
hostName: string;
hr: HRESULT;
ICont: IADsContainer;
INewGroup: IADs;
begin
Result := '';
ICont := nil;
INewGroup := nil;
if AContainer.IsEmpty or AName.IsEmpty or ASamAccountName.IsEmpty
then Exit;
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
hr := ADsOpenObject(
PChar(Format('LDAP://%s/%s', [hostName, AContainer])),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADsContainer,
@ICont
);
if Succeeded(hr) then
begin
INewGroup := ICont.Create(
'group',
'CN=' + ADEscapeReservedCharacters(AName)
) as IADs;
if INewGroup <> nil then
begin
INewGroup.Put('samAccountName', ASamAccountName);
INewGroup.Put('groupType', AGroupType);
INewGroup.SetInfo;
v := INewGroup.Get('distinguishedName');
Result := VariantToStringWithDefault(v, '');
VariantClear(v);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
finally
CoUninitialize;
end;
end;
function ADCreateGroupDS(ARootDSE: IADS; AContainer: string; AName, ASamAccountName: string;
AGroupType: DWORD): string;
var
v: OleVariant;
hostName: string;
hr: HRESULT;
attrArray: array of ADS_ATTR_INFO;
valClass: ADSVALUE;
IDir: IDirectoryObject;
IDisp: IDispatch;
INewGroup: IADs;
begin
Result := '';
IDir := nil;
INewGroup := nil;
if AContainer.IsEmpty or AName.IsEmpty or ASamAccountName.IsEmpty
then Exit;
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
SetLength(attrArray, 1);
with attrArray[0] do
begin
pszAttrName := 'objectClass';
dwControlCode := ADS_ATTR_UPDATE;
dwADsType := ADSTYPE_CASE_IGNORE_STRING;
pADsValues := @valClass;
dwNumValues := 1;
end;
valClass.dwType := ADSTYPE_CASE_IGNORE_STRING;
valClass.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString := PChar('group');
hr := ADsOpenObject(
PChar(Format('LDAP://%s/%s', [hostName, AContainer])),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IDirectoryObject,
@IDir
);
if Succeeded(hr) then
begin
hr := IDir.CreateDSObject(
PChar('CN=' + ADEscapeReservedCharacters(AName)),
@attrArray[0],
Length(attrArray),
IDisp
);
if Succeeded(hr) then
begin
hr := IDisp.QueryInterface(IID_IADsGroup, INewGroup);
if not Succeeded(hr)
then raise Exception.Create(ADSIErrorToString);
INewGroup.Put('samAccountName', ASamAccountName);
INewGroup.Put('groupType', AGroupType);
INewGroup.SetInfo;
v := INewGroup.Get('distinguishedName');
Result := VariantToStringWithDefault(v, '');
VariantClear(v);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
finally
CoUninitialize;
end;
end;
function ADDeleteObject(ALDAP: PLDAP; ADN: string): Boolean;
var
ldapDN: AnsiString;
returnCode: ULONG;
begin
Result := False;
ldapDN := AnsiString(ADN);
try
returnCode := ldap_delete_ext_s(
ALDAP,
PAnsiChar(ldapDN),
nil,
nil
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create(ldap_err2string(returnCode));
Result := True;
finally
end;
end;
function ADDeleteObject(ARootDSE: IADS; ADN: string): Boolean;
var
Obj: IADs;
objClass: string;
objRelativeName: string;
objCont: IADsContainer;
hr: HRESULT;
dn: string;
ADSIPath_LDAP: string;
v: OleVariant;
hostName: string;
begin
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
except
end;
{ ADSI requires that the forward slash character "/" also be escaped }
{ in distinguished names in most scripts where distinguished names }
{ are used to bind to objects in Active Directory: }
{ https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx }
dn := ReplaceStr(ADN, '/', '\/');
if hostName.IsEmpty
then ADSIPath_LDAP := Format('LDAP://%s', [dn])
else ADSIPath_LDAP := Format('LDAP://%s/%s', [hostName, dn]);
Result := False;
try
hr := ADsOpenObject(
PChar(ADSIPath_LDAP),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADs,
@Obj
);
if Succeeded(hr) then
begin
objClass := Obj.Class_;
objRelativeName := Obj.Name;
hr := ADsOpenObject(
PChar(Obj.Parent),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADsContainer,
@objCont
);
if Succeeded(hr) then
begin
objCont.Delete(
objClass,
objRelativeName
);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
Result := True;
finally
CoUninitialize;
end;
end;
function ADDeleteObjectDS(ARootDSE: IADS; ADN: string): Boolean;
var
Obj: IADs;
objRelativeName: string;
objCont: IDirectoryObject;
hr: HRESULT;
dn: string;
ADSIPath_LDAP: string;
v: OleVariant;
hostName: string;
begin
CoInitialize(nil);
try
v := ARootDSE.Get('dnsHostName');
hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
except
end;
{ ADSI requires that the forward slash character "/" also be escaped }
{ in distinguished names in most scripts where distinguished names }
{ are used to bind to objects in Active Directory: }
{ https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx }
dn := ReplaceStr(ADN, '/', '\/');
if hostName.IsEmpty
then ADSIPath_LDAP := Format('LDAP://%s', [dn])
else ADSIPath_LDAP := Format('LDAP://%s/%s', [hostName, dn]);
Result := False;
try
hr := ADsOpenObject(
PChar(ADSIPath_LDAP),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADs,
@Obj
);
if Succeeded(hr) then
begin
objRelativeName := Obj.Name;
hr := ADsOpenObject(
PChar(Obj.Parent),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IDirectoryObject,
@objCont
);
if Succeeded(hr) then
begin
hr := objCont.DeleteDSObject(PChar(objRelativeName));
if not Succeeded(hr)
then raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
end else raise Exception.Create(ADSIErrorToString);
Result := True;
finally
CoUninitialize;
end;
end;
end.
|
unit AnalogSaat_2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
const
pib180 = pi/180;
pixelcount = 2048;
type
_pRGB = ^Trgb;
Trgb = array[0..pixelcount-1] of Trgbtriple;
pRGB = array[0..pixelcount-1] of _pRGB;
type
Tsekil = (ts_kare,ts_daire);
TAnalogSaat_2 = class(TGraphicControl)
private
_timer : TTimer;
r,x0,y0 : integer;
_saat : _SystemTime;
fsaat : tbitmap;
FTransparent: boolean;
FSaatKadranRenk: Tcolor;
FSaniyeKadranRenk: Tcolor;
FDakikaKadranRenk: Tcolor;
FSaatKadrankalinlik: integer;
FDakikaKadranKalinlik: integer;
FSaniyeKadranKalinlik: integer;
FBackground: tcolor;
FText: string;
FPicture: tpicture;
FActive: boolean;
FSekil: tsekil;
procedure saatgovde;
procedure tazele;
procedure ozellikkur;
procedure saatkadranciz(x0,y0,x1,y1:real);
procedure __Timer(Sender: TObject);
procedure SetTransparent(const Value: boolean);
procedure SetSaatKadranRenk(const Value: Tcolor);
procedure SetDakikaKadranRenk(const Value: Tcolor);
procedure SetSaniyeKadranRenk(const Value: Tcolor);
procedure SetSaatKadrankalinlik(const Value: integer);
procedure SetDakikaKadranKalinlik(const Value: integer);
procedure SetSaniyeKadranKalinlik(const Value: integer);
procedure SetBackground(const Value: tcolor);
procedure SetText(const Value: string);
procedure SetPicture(Value: tpicture);
procedure SetActive(const Value: boolean);
procedure SetSekil(const Value: tsekil);
{ Private declarations }
protected
{ Protected declarations }
public
constructor Create(aowner:tcomponent);override;
destructor Destroy;override;
procedure Paint;override;
{ Public declarations }
published
property Transparent:boolean read FTransparent write SetTransparent default False;
property SaatKadranRenk : Tcolor read FSaatKadranRenk write SetSaatKadranRenk default clRed;
property SaatKadranKalinlik : integer read FSaatKadrankalinlik write SetSaatKadrankalinlik default 3;
property DakikaKadranRenk : Tcolor read FDakikaKadranRenk write SetDakikaKadranRenk default clNavy;
property DakikaKadranKalinlik : integer read FDakikaKadranKalinlik write SetDakikaKadranKalinlik default 2;
property SaniyeKadranRenk : Tcolor read FSaniyeKadranRenk write SetSaniyeKadranRenk default clgreen;
property SaniyeKadranKalinlik : integer read FSaniyeKadranKalinlik write SetSaniyeKadranKalinlik default 1;
property Background : tcolor read FBackground write SetBackground default clsilver;
property Text:string read FText write SetText ;
property Font;
property Picture:tpicture read FPicture write SetPicture;
property Active:boolean read FActive write SetActive Default True;
property Popupmenu;
property Sekil:tsekil read FSekil write SetSekil default ts_kare;
{ Published declarations }
end;
procedure Register;
var
img_data : pRGB;
implementation
{$r analogsaat_2.dcr}
procedure Register;
begin
RegisterComponents('alikadir', [TAnalogSaat_2]);
end;
{ TAnalogSaat }
constructor TAnalogSaat_2.Create(aowner: tcomponent);
begin
inherited Create(aowner);
Fpicture := TPicture.Create ;
fsaat := tbitmap.create;
_timer := TTimer.Create(self);
_timer.Interval := 1000;
_timer.Enabled := true;
_timer.OnTimer := __Timer;
ozellikkur ;
repaint;
end;
destructor TAnalogSaat_2.Destroy;
begin
FPicture.Free ;
_timer.free;
fsaat.free;
inherited destroy;
end;
procedure loadimg(temp:tbitmap);
var
i:integer;
begin
for i:=0 to 10 do
img_data[i] := temp.scanline[i];
end;
procedure TAnalogSaat_2.ozellikkur;
begin
width := 100;
height := 100;
Transparent := False;
SaatKadranRenk := clRed;
SaatKadranKalinlik := 3;
DakikaKadranRenk := clNavy;
DakikaKadranKalinlik := 2;
SaniyeKadranRenk := clGreen ;
SaniyeKadranKalinlik := 1;
Background := clSilver;
Text := 'By alikadir';
Active := True;
sekil := ts_kare;
end;
procedure TAnalogSaat_2.Paint;
var
_x,__x,___x : integer;
r1,r2,r3 : integer;
i,j : integer;
begin
if fsaat.Width <> Width then
fsaat.Width := width;
if fsaat.Height <> Height then
fsaat.Height := Height ;
//*********** saat gövdesi çiziliyor**************//
fsaat.canvas.Font.Assign(Font);
saatgovde;
//************yerel saat öğreniliyor*****************//
GetLocalTime( _saat );
{
saat i gösterecek olan kadarnın açısı ayarlanıyor
ayrıca dakikanın ilerleyişi dikkate alınıyor
}
_x := round( _saat.wMinute * 0.5 ) + ( (_saat.wHour mod 12) * 30);
_x := 180 - _x;
// dakikayı gösterecek olan kadranın açısı hesaplanıyor
__x := _saat.wMinute*6; //her bir adım da 6 derece oynuyor
__x := 180 - __x;
//saniyeyi gösterecek olan kadranın açısı hesaplanıyor
___x := _saat.wSecond*6; //her bir adım da 6 derece oynuyor
___x := 180 - ___x;
//kadranın çapları hesaplanıyor
r1 := r div 2;
r2 := round ( r * 0.70 );
r3 := round ( r * 0.80 );
//kadranlar ekrana çiziliyor..
with fsaat do
begin
canvas.pen.width := SaatKadranKalinlik;
canvas.pen.color := SaatKadranRenk;
saatkadranciz(x0 , y0 , x0 + r1 * sin(pib180 * _x) , y0 + r1 * cos(pib180 * _x) );
//canvas.MoveTo( x0 , y0);
//canvas.lineto( ),
// );
canvas.pen.width := DakikaKadranKalinlik ;
canvas.pen.Color := DakikaKadranRenk ;
canvas.MoveTo( x0 , y0 );
canvas.lineto( x0 + round( r2 * sin(pib180 * __x) ),
y0 + round( r2 * cos(pib180 * __x) ));
canvas.pen.width := SaniyeKadranKalinlik ;
canvas.pen.color := SaniyeKadranRenk ;
canvas.MoveTo( x0 , y0);
canvas.lineto( x0 + round( r3 * sin(pib180 * ___x) ),
y0 + round( r3 * cos(pib180 * ___X) ));
end;
if sekil = ts_daire then
begin
// loadimg(fsaat);
{if (img_data[0] = nil) or (img_data[0]<>fsaat.ScanLine[0])then
loadimg;
{ for j:=0 to fsaat.height -1 do
for i:=0 to fsaat.width - 1 do
if sqrt( (x0-i)*(x0-i) + (y0-j)*(y0-j)) > r then
begin
img_data[j,i].rgbtBlue := 0;
img_data[j,i].rgbtGreen := 0;
img_data[j,i].rgbtRed := 0;
end; }
end;
canvas.draw(0,0,fsaat);
end;
procedure TAnalogSaat_2.saatgovde;
var
t_w,i,h,w : integer;
_x0,_y0,_r : real;
tr : trect;
_i,_j : integer;
begin
_x0 := (width / 2);
_y0 := (height / 2);
//***********saat dairesinin alanı hesaplanıyor
if width < height then
begin
tr.left := 0;
tr.Right := width ;
tr.top := (height - width) div 2;
tr.Bottom := tr.top + width;
end
else if height < width then
begin
tr.left := (width - height) div 2;
tr.Right := tr.left + height;
tr.top :=0;
tr.Bottom := height;
end
else tr:=ClientRect ;
//**********************************************
//çap hesaplanıyor
_r :=(tr.Right - tr.left - 20) / 2;
with fsaat do
begin
if self.Transparent then
begin
TransparentColor := Background;
Transparent := true;
end
else
begin
canvas.brush.color := background;
canvas.fillrect(clientrect);
end;
//****ekrana varsa grafik çiziliyor**********
if picture.Graphic <> nil then
begin
// grafik in çizime başlanacak kooordinatı hesaplanıyor
if picture.width<width then
w := (width - picture.width) div 2
else
w:=0;
if picture.height<Height then
h := (Height - picture.Height ) div 2
else
h:=0;
//********************************************
canvas.Draw(w,h,picture.graphic);
canvas.brush.Style := bsclear;
end;
//***********************************************
//*******ana çember****************
canvas.pen.color := clsilver;
canvas.pen.width := 3;
canvas.Ellipse(tr);
//**************************************
//**************iç çember******************
canvas.pen.color := clgray;
canvas.pen.width := 2;
tr.left := tr.left + 3;
tr.Right := tr.Right - 3;
tr.Top := tr.top +3;
tr.Bottom := tr.Bottom -3;
canvas.Ellipse(tr);
//*********************************************
//************rakamlar çiziliyor*******************
canvas.font.Style := canvas.font.Style + [fsbold];
canvas.brush.Style := bsclear;
for i:=1 to 12 do
canvas.TextOut( round(_x0 + (_r * sin( pib180 * (180 - (i * 30) ) ))) - (canvas.textwidth(inttostr(i)) div 2),
round(_y0 + (_r * cos( pib180 * (180 - (i * 30) ) ))) - (canvas.textheight(inttostr(i)) div 2),
inttostr(i));
//***************************************************
//***********saat ler arası noktalar konuluyor******
canvas.brush.style := bssolid;
canvas.pen.Style := psclear;
for i:=1 to 60 do
begin
if i mod 5 = 0 then continue; //eğer saat üzerine geldiyse atal
//koordinatlar hesaplanıyor
_i := round(_x0 + (_r * sin( pib180 * (180 - (i * 6) ) )));
_j := round(_y0 + (_r * cos( pib180 * (180 - (i * 6) ) )));
//iki adet elips çiz
canvas.Brush.color := clgray;
canvas.Ellipse(_i-2,_j-2,_i+2,_j+2);
canvas.Brush.color := clsilver;
canvas.Ellipse(_i-1,_j-1,_i+3,_j+3);
end;
//***************************************************
//********text i ekrana yaz***********
canvas.brush.Style := bsclear;
t_w := canvas.TextWidth ( text );
if (tr.Right - tr.left) >= t_w then
canvas.textout( ( width - t_w ) div 2 , round(tr.Bottom * 0.8),text);
//**************************************
canvas.brush.Style := bssolid;
x0 := round(_x0);
y0 := round(_y0);
r := trunc(_r);
//***********göbek çember çiziliyor
canvas.pen.Style := psClear ;
canvas.Brush.Color := SaatKadranRenk ;
canvas.Ellipse(x0-5,y0-5,x0+5,y0+5);
canvas.pen.Style := psSolid ;
//*************************************
end;
end;
procedure TAnalogSaat_2.saatkadranciz(x0, y0, x1, y1: real);
var
_x0 , _y0 , _x1 , _y1 ,
e , _e , mx, my ,cosx , sinx : real;
begin
mx := abs(x1-x0) ; my := abs(y1-y0);
e := sqrt(mx*mx+my*my);
_e := 8;
if (x0>=x1) and (y1>=y0) then
begin
cosx := mx/e; sinx := my/e;
cosx := -sinx ; sinx := - cosx;
_x0 := _e*(cosx*sin(pib180*-30) + sinx*cos(pib180*-30));
_y0 := _e*(sinx*sin(pib180*-30) - cosx*cos(pib180*-30));
_x1 := _e*(cosx*sin(pib180*-30) - sinx*cos(pib180*-30));
_y1 := _e*(sinx*sin(pib180*-30) + cosx*cos(pib180*-30));
with fsaat do
begin
canvas.MoveTo(trunc(x0),trunc(y0));
canvas.LineTo(trunc(x1),trunc(y1));
{ canvas.moveto(trunc(x1),trunc(y1));
Canvas.LineTo(trunc(x1+_x0),trunc(y1+_y0));
canvas.moveto(trunc(x1),trunc(y1));
Canvas.LineTo(trunc(x1+_x1),trunc(y1+_y1));}
end;
end
else
with fsaat do
begin
canvas.MoveTo(trunc(x0),trunc(y0));
canvas.LineTo(trunc(x1),trunc(y1));
end;
end;
procedure TAnalogSaat_2.SetActive(const Value: boolean);
begin
FActive := Value;
end;
procedure TAnalogSaat_2.SetBackground(const Value: tcolor);
begin
FBackground := Value;
tazele;
end;
procedure TAnalogSaat_2.SetDakikaKadranKalinlik(const Value: integer);
begin
FDakikaKadranKalinlik := Value;
tazele;
end;
procedure TAnalogSaat_2.SetDakikaKadranRenk(const Value: Tcolor);
begin
FDakikaKadranRenk := Value;
tazele;
end;
procedure TAnalogSaat_2.SetPicture(Value: tpicture);
begin
FPicture.Assign(Value);
tazele;
end;
procedure TAnalogSaat_2.SetSaatKadrankalinlik(const Value: integer);
begin
FSaatKadrankalinlik := Value;
tazele;
end;
procedure TAnalogSaat_2.SetSaatKadranRenk(const Value: Tcolor);
begin
FSaatKadranRenk := Value;
tazele;
end;
procedure TAnalogSaat_2.SetSaniyeKadranKalinlik(const Value: integer);
begin
FSaniyeKadranKalinlik := Value;
tazele;
end;
procedure TAnalogSaat_2.SetSaniyeKadranRenk(const Value: Tcolor);
begin
FSaniyeKadranRenk := Value;
tazele;
end;
procedure TAnalogSaat_2.SetSekil(const Value: tsekil);
begin
FSekil := Value;
end;
procedure TAnalogSaat_2.SetText(const Value: string);
begin
if ftext<>value then
begin
FText := Value;
tazele;
end;
end;
procedure TAnalogSaat_2.SetTransparent(const Value: boolean);
begin
if FTransparent <> Value then
begin
FTransparent := Value;
tazele;
end;
end;
procedure TAnalogSaat_2.tazele;
var
tr : trect;
h : integer;
begin
tr.Left := left;
tr.Top := top;
tr.Right := left + width;
tr.Bottom := top + height;
if parent = nil then exit;
h := (parent as tform).handle;
if h>-1 then
begin
InvalidateRect(h,@tr,false);
end;
end;
procedure TAnalogSaat_2.__Timer(Sender: TObject);
var
s:String;
begin
s:=(parent as tform).Name;
if (application.FindComponent(s)=nil)or(not active) then exit;
tazele;
end;
end.
|
unit guesstag;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TTagFromFilename }
TTagFromFilename = class
private
FAlbum: string;
FArtist: string;
FTitle: string;
FTrack: string;
FYear: string;
public
constructor create;
Function ReadTag(filename: string):boolean;
property Artist: string read FArtist;
property Title: string read FTitle;
property Album: string read FAlbum;
property Track: string read FTrack;
property year: string read FYear;
end;
implementation
{ TTagFromFilename }
constructor TTagFromFilename.create;
begin
end;
function TTagFromFilename.ReadTag(filename: string): boolean;
var FName: string;
z: integer;
FileExtLength: Integer;
begin
FName:=ExtractFileName(filename);
FileExtLength:= Length(ExtractFileExt(filename))+1;
FTitle:='';
FArtist:='';
FTrack:='';
FYear:='';
// get track number from NN - Artist - Title.mp3 like names
If (FName[1]<#60) And (FName[2]<#60) {And ((FName[4]=#45)) or (FName[3]=#45))} Then
Begin
FTrack:= (copy(FName,1,2));
z := pos(' - ', FName);
If z>4 Then
Begin
FTitle := TrimRight(copy(FName,z+3,length(FName)-z-FileExtLength));
FArtist := TrimRight(copy(FName,4,z-4));
End else
FTitle := TrimRight(copy(FName,z+3,length(FName)-z));
End
else begin
z := pos(' - ', FName);
If z>3 Then
Begin
FTitle := TrimRight(copy(FName,z+3,length(FName)-z-FileExtLength));
FArtist := TrimRight(copy(FName,1,z));
end;
End;
// Artist--Title.mp3 like names
z:=pos('--', FName);
if z>0 then begin
if FArtist='' then begin
FArtist := TrimRight(copy(FName,1,z-1));
end;
if FTitle='' then begin
FTitle := TrimRight(copy(FName,z+2,Length(FName)-z-FileExtLength));
end;
end;
end;
end.
|
unit ThreadManager;
interface
uses
System.Generics.Collections, System.Classes, LoggerInterface,
System.SyncObjs, SettingsInterface;
type
TThreadManager = class(TObject)
private
FCancellationEvent: TEvent;
FMyThreadList: TList<TThread>;
function CreateNewThread(ALoggerI: ILogger; AInterval: Cardinal): TThread;
public
constructor Create(const ALoggerI: ILogger; const ASettingsI:
IMessageThreadSettings);
destructor Destroy; override;
end;
implementation
uses
LoggerThread, System.SysUtils;
constructor TThreadManager.Create(const ALoggerI: ILogger; const ASettingsI:
IMessageThreadSettings);
var
AInterval: Cardinal;
begin
if not Assigned(ALoggerI) then
raise Exception.Create('Logger interface is not assigned');
FCancellationEvent := TEvent.Create();
FCancellationEvent.ResetEvent;
FMyThreadList := TList<TThread>.Create;
for AInterval in ASettingsI.Intervals do
FMyThreadList.Add( CreateNewThread(ALoggerI, AInterval) );
end;
destructor TThreadManager.Destroy;
var
AThread: TThread;
begin
// устанавливаем событие завершения, которого ждут все потоки
FCancellationEvent.SetEvent;
for AThread in FMyThreadList do
begin
AThread.WaitFor; // ждём, когда поток завершится
AThread.Free;
end;
inherited;
end;
function TThreadManager.CreateNewThread(ALoggerI: ILogger; AInterval:
Cardinal): TThread;
begin
Result := TLoggerThread.Create(ALoggerI, FCancellationEvent, AInterval)
end;
end.
|
unit MMO.ClientList;
interface
uses
Generics.Collections, MMO.ServerClient, MMO.Types;
type
TClientList<ClientType> = class(TList<TServerClient<ClientType>>)
private
var m_sessionId: TSessionId;
var m_lastInsertedIndex: Integer;
public
constructor Create;
destructor Destroy; override;
function Add(const Value: TServerClient<ClientType>): TSessionId;
end;
implementation
constructor TClientList<ClientType>.Create;
begin
inherited;
m_sessionId := 0;
end;
destructor TClientList<ClientType>.Destroy;
begin
inherited;
end;
function TClientList<ClientType>.Add(const Value: TServerClient<ClientType>): TSessionId;
var
realResult: integer;
begin
m_lastInsertedIndex := inherited Add(Value);
Result := m_sessionId;
Inc(m_sessionId);
end;
end.
|
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
//------------------------------------------------------------------------------||
//------------------------------------------------------------------------------||
// Miedian of three
//Median of three - Integer.
procedure Median3(var Arr:TIntArray; Left, Middle, Right:Integer); Inline; overload;
begin
if (Arr[Middle] < Arr[Left]) then Exch(Arr[Left], Arr[Middle]);
if (Arr[Right] < Arr[Left]) then Exch(Arr[Left], Arr[Right]);
if (Arr[Right] < Arr[Middle]) then Exch(Arr[Middle], Arr[Right]);
end;
//Median of three - Extended.
procedure Median3(var Arr:TExtArray; Left, Middle, Right:Integer); Inline; overload;
begin
if (Arr[Middle] < Arr[Left]) then Exch(Arr[Left], Arr[Middle]);
if (Arr[Right] < Arr[Left]) then Exch(Arr[Left], Arr[Right]);
if (Arr[Right] < Arr[Middle]) then Exch(Arr[Middle], Arr[Right]);
end;
//Median of three - Double.
procedure Median3(var Arr:TDoubleArray; Left, Middle, Right:Integer); Inline; overload;
begin
if (Arr[Middle] < Arr[Left]) then Exch(Arr[Left], Arr[Middle]);
if (Arr[Right] < Arr[Left]) then Exch(Arr[Left], Arr[Right]);
if (Arr[Right] < Arr[Middle]) then Exch(Arr[Middle], Arr[Right]);
end;
//Median of three - Single.
procedure Median3(var Arr:TFloatArray; Left, Middle, Right:Integer); Inline; overload;
begin
if (Arr[Middle] < Arr[Left]) then Exch(Arr[Left], Arr[Middle]);
if (Arr[Right] < Arr[Left]) then Exch(Arr[Left], Arr[Right]);
if (Arr[Right] < Arr[Middle]) then Exch(Arr[Middle], Arr[Right]);
end;
//Median of three - TPoint with weight.
procedure Median3(var Arr:TPointArray; var Weight:TIntArray; Left, Middle, Right:Integer); Inline; overload;
begin
if (Weight[Middle] < Weight[Left]) then begin
Exch(Arr[Left], Arr[Middle]);
Exch(Weight[Left], Weight[Middle]);
end;
if (Weight[Right] < Weight[Left]) then begin
Exch(Arr[Left], Arr[Right]);
Exch(Weight[Left], Weight[Right]);
end;
if (Weight[Right] < Weight[Middle]) then begin
Exch(Arr[Middle], Arr[Right]);
Exch(Weight[Middle], Weight[Right]);
end;
end;
//------------------------------------------------------------------------------||
//------------------------------------------------------------------------------||
// Miedian of Five
function MedianOfFive(a,b,c,d,e:uInt8): uInt8;
begin
ExchMin(a,b);
ExchMin(c,d);
if (c < a) then begin Exch(b,d); c := a; end;
a := e;
ExchMin(a,b);
if (a < c) then begin Exch(b,d); a := c; end;
Result := Min(d, a);
end;
function MedianOfFive(a,b,c,d,e:Int8): Int8;
begin
ExchMin(a,b);
ExchMin(c,d);
if (c < a) then begin Exch(b,d); c := a; end;
a := e;
ExchMin(a,b);
if (a < c) then begin Exch(b,d); a := c; end;
Result := Min(d, a);
end;
function MedianOfFive(a,b,c,d,e:Int32): Int32;
begin
ExchMin(a,b);
ExchMin(c,d);
if (c < a) then begin Exch(b,d); c := a; end;
a := e;
ExchMin(a,b);
if (a < c) then begin Exch(b,d); a := c; end;
Result := Min(d, a);
end;
function MedianOfFive(a,b,c,d,e:Single): Single;
begin
ExchMin(a,b);
ExchMin(c,d);
if (c < a) then begin Exch(b,d); c := a; end;
a := e;
ExchMin(a,b);
if (a < c) then begin Exch(b,d); a := c; end;
Result := Min(d, a);
end;
function MedianOfFive(a,b,c,d,e:Double): Double;
begin
ExchMin(a,b);
ExchMin(c,d);
if (c < a) then begin Exch(b,d); c := a; end;
a := e;
ExchMin(a,b);
if (a < c) then begin Exch(b,d); a := c; end;
Result := Min(d, a);
end;
//------------------------------------------------------------------------------||
//------------------------------------------------------------------------------||
//Insertion sort bellow
(*
Fast integer sorting from small arrays, or small parts of arrays.
*)
procedure InsSortTIA(var Arr:TIntArray; Left, Right:Integer); Inline;
var i, j, tmp:Integer;
begin
for i := Left+1 to Right do begin
j := i-1;
Tmp := arr[i];
while (j >= Left) and (Arr[j] > Tmp) do begin
Arr[j+1] := Arr[j];
j:=j-1;
end;
Arr[j+1] := Tmp;
end;
end;
(*
Fast extended sorting from small arrays, or small parts of arrays.
*)
procedure InsSortTEA(var Arr:TExtArray; Left, Right:Integer); Inline;
var i, j:Integer; tmp:Extended;
begin
for i := Left+1 to Right do begin
j := i-1;
Tmp := arr[i];
while (j >= Left) and (Arr[j] > Tmp) do begin
Arr[j+1] := Arr[j];
j:=j-1;
end;
Arr[j+1] := Tmp;
end;
end;
(*
Fast double sorting from small arrays, or small parts of arrays.
*)
procedure InsSortTDA(var Arr:TDoubleArray; Left, Right:Integer); Inline;
var i, j:Integer; tmp:Double;
begin
for i := Left+1 to Right do begin
j := i-1;
Tmp := arr[i];
while (j >= Left) and (Arr[j] > Tmp) do begin
Arr[j+1] := Arr[j];
j:=j-1;
end;
Arr[j+1] := Tmp;
end;
end;
(*
Fast single sorting from small arrays, or small parts of arrays.
*)
procedure InsSortTFA(var Arr:TFloatArray; Left, Right:Integer); Inline;
var i, j:Integer; tmp:Single;
begin
for i := Left+1 to Right do begin
j := i-1;
Tmp := arr[i];
while (j >= Left) and (Arr[j] > Tmp) do begin
Arr[j+1] := Arr[j];
j:=j-1;
end;
Arr[j+1] := Tmp;
end;
end;
(*
Fast TPoint sorting from small arrays, or small parts of arrays.
*)
procedure InsSortTPA(var Arr:TPointArray; Weight:TIntArray; Left, Right:Integer); Inline;
var i, j:Integer;
begin
for i := Left to Right do
for j := i downto Left + 1 do begin
if not (Weight[j] < Weight[j - 1]) then Break;
Exch(Arr[j-1], Arr[j]);
Exch(Weight[j-1], Weight[j]);
end;
end;
//------------------------------------------------------------------------------||
//------------------------------------------------------------------------------||
// ShellSort bellow (only used to ensure O(n^1.5)) in the "main" sorting algorithm.
// Using predifined gaps (Ciura's) only resulted in slowdown.
procedure ShellSortTIA(var Arr: TIntArray);
var
Gap, i, j, H: Integer;
begin
H := High(Arr);
Gap := 0;
while (Gap < (H+1) div 3) do Gap := Gap * 3 + 1;
while Gap >= 1 do begin
for i := Gap to H do begin
j := i;
while (j >= Gap) and (Arr[j] < Arr[j - Gap]) do
begin
Exch(Arr[j], Arr[j - Gap]);
j := j - Gap;
end;
end;
Gap := Gap div 3;
end;
end;
procedure ShellSortTEA(var Arr: TExtArray);
var
Gap, i, j, H: Integer;
begin
H := High(Arr);
Gap := 0;
while (Gap < (H+1) div 3) do Gap := Gap * 3 + 1;
while Gap >= 1 do begin
for i := Gap to H do begin
j := i;
while (j >= Gap) and (Arr[j] < Arr[j - Gap]) do
begin
Exch(Arr[j], Arr[j - Gap]);
j := j - Gap;
end;
end;
Gap := Gap div 3;
end;
end;
procedure ShellSortTDA(var Arr: TDoubleArray);
var
Gap, i, j, H: Integer;
begin
H := High(Arr);
Gap := 0;
while (Gap < (H+1) div 3) do Gap := Gap * 3 + 1;
while Gap >= 1 do begin
for i := Gap to H do begin
j := i;
while (j >= Gap) and (Arr[j] < Arr[j - Gap]) do
begin
Exch(Arr[j], Arr[j - Gap]);
j := j - Gap;
end;
end;
Gap := Gap div 3;
end;
end;
procedure ShellSortTFA(var Arr: TFloatArray);
var
Gap, i, j, H: Integer;
begin
H := High(Arr);
Gap := 0;
while (Gap < (H+1) div 3) do Gap := Gap * 3 + 1;
while Gap >= 1 do begin
for i := Gap to H do begin
j := i;
while (j >= Gap) and (Arr[j] < Arr[j - Gap]) do
begin
Exch(Arr[j], Arr[j - Gap]);
j := j - Gap;
end;
end;
Gap := Gap div 3;
end;
end;
procedure ShellSortTPA(var Arr: TPointArray; Weight:TIntArray);
var
Gap, i, j, H: Integer;
begin
H := High(Arr);
Gap := 0;
while (Gap < (H+1) div 3) do Gap := Gap * 3 + 1;
while Gap >= 1 do begin
for i := Gap to H do begin
j := i;
while (j >= Gap) and (Weight[j] < Weight[j - Gap]) do
begin
Exch(Arr[j], Arr[j - Gap]);
Exch(Weight[j], Weight[j - Gap]);
j := j - Gap;
end;
end;
Gap := Gap div 3;
end;
end;
|
unit GX_IdeDockDemo;
{$I GX_CondDefine.inc}
interface
uses
GX_Experts,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ExtCtrls, IniFiles, GX_IdeDock;
type
TDemoDockForm = class(TfmIdeDockForm)
Panel1: TPanel;
Splitter1: TSplitter;
Panel2: TPanel;
procedure FormShow(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveWindowState(MemIniFile: TMemIniFile; ABoolean: Boolean); override;
procedure LoadWindowState(MemIniFile: TMemIniFile); override;
end;
// The following DEFINE indicates whatever the expert can be
// loaded/unload at runtime (requires adjustments in GX_Expert).
{.$DEFINE LoadUnload}
type
TDemoExpert = class(TGX_Expert)
protected
{$IFDEF LoadUnload}
procedure SetActive(Value: Boolean); override;
{$ENDIF LoadUnload}
public
constructor Create; override;
destructor Destroy; override;
{$IFNDEF LoadUnload}
procedure LoadSettings; override;
{$ENDIF LoadUnload}
procedure Click(Sender: TObject); override;
function GetActionCaption: string; override;
class function GetName: string; override;
function GetDisplayName: string; override;
end;
var
// This variable is required for docking support
DemoDockForm: TDemoDockForm;
// Use this variable to get information from the expert
DemoExpert: TDemoExpert;
implementation
{$R *.dfm}
uses
GX_DbugIntf;
constructor TDemoDockForm.Create(AOwner: TComponent);
var
AClass: TClass;
begin
inherited Create(AOwner);
// Do something useful...
AClass := Self.ClassParent;
while AClass <> nil do
begin
SendDebug(AClass.ClassName + IntToStr(AClass.InstanceSize));
AClass := AClass.ClassParent;
end;
end;
destructor TDemoDockForm.Destroy;
begin
DemoDockForm := nil; // Required to learn if the form has been released.
inherited Destroy;
end;
procedure TDemoDockForm.FormShow(Sender: TObject);
begin
inherited; // Make sure that you call the inherited event!
SendDebug('Hello world!');
end;
procedure TDemoDockForm.LoadWindowState(MemIniFile: TMemIniFile);
begin
SendDebug('LoadWindowState');
inherited LoadWindowState(MemIniFile); // save position and size (and docking stuff)
Panel1.Width := MemIniFile.ReadInteger('DemoDockForm' {form name}, 'SplitPos', Panel1.Width);
end;
procedure TDemoDockForm.SaveWindowState(MemIniFile: TMemIniFile; ABoolean: Boolean);
begin
SendDebug('SaveWindowState');
inherited SaveWindowState(MemIniFile, ABoolean);
SendDebug('After SaveWindowState');
SendDebug(Panel1.Name);
MemIniFile.WriteInteger('DemoDockForm' {form name}, 'SplitPos', Panel1.Width);
end;
{ TDemoExpert }
constructor TDemoExpert.Create;
begin
inherited Create;
DemoExpert := Self;
end;
destructor TDemoExpert.Destroy;
begin
{$IFDEF LoadUnload}
// Unregister the form.
Active := False;
{$ELSE}
// It is not required to unregister the form,
// and since we don't know if the form is
// registered we don't unregister it.
FreeAndNil(DemoDockForm);
{$ENDIF LoadUnLoad}
DemoExpert := nil;
inherited Destroy;
end;
{$IFDEF LoadUnload}
procedure TDemoExpert.SetActive(Value: Boolean);
begin
if Active <> Value then
begin
inherited SetActive(Value);
if Value then
begin
// If active is set to True register the form.
IdeDockManager.RegisterDockableForm(TDemoDockForm, DemoDockForm, 'DemoDockForm')
// FormClass Form var form Name (must be unique).
end
else
begin
// If active is set to False, then free and unregister the form.
FreeAndNil(DemoDockForm);
IdeDockManager.UnRegisterDockableForm('DemoDockForm');
end;
end;
end;
{$ENDIF LoadUnload}
{$IFNDEF LoadUnload}
procedure TDemoExpert.LoadSettings;
begin
inherited LoadSettings;
// This procedure is only called once so it
// is safe to register the form here.
if Active then
begin
IdeDockManager.RegisterDockableForm(TDemoDockForm, DemoDockForm, 'DemoDockForm');
// FormClass Form var form Name (must be unique).
end;
end;
{$ENDIF LoadUnload}
procedure TDemoExpert.Click(Sender: TObject);
begin
// If the form doesn't exist, create it.
if DemoDockForm = nil then
DemoDockForm := TDemoDockForm.Create(nil);
// Show the form using IdeDockManager.ShowForm.
IdeDockManager.ShowForm(DemoDockForm);
end;
function TDemoExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Docking Demo Expert';
begin
Result := SMenuCaption;
end;
function TDemoExpert.GetName: string;
begin
Result := 'IdeDockDemo';
end;
initialization
RegisterGX_Expert(TDemoExpert);
end.
|
unit tstUtils;
{------------------------------------------------------------------------------}
{ Библиотека : Тестовый слой; }
{ Автор : Морозов М.А. }
{ Начат : 03.04.2006 16.48; }
{ Модуль : tstUtils }
{ Описание : Общие процедуры и функции используемые тестовым слоем; }
{------------------------------------------------------------------------------}
// $Id: tstUtils.pas,v 1.5 2006/04/10 09:29:21 mmorozov Exp $
// $Log: tstUtils.pas,v $
// Revision 1.5 2006/04/10 09:29:21 mmorozov
// - add comment;
//
// Revision 1.4 2006/04/10 09:28:42 mmorozov
// - bugfix: были проблемы с интерпретацией прочитанного из потока в строку;
//
// Revision 1.3 2006/04/04 07:59:15 mmorozov
// - new: использование фабрики потока + в случае успешного получения данных завершаем вызовом DataReceived;
//
// Revision 1.2 2006/04/03 14:06:15 mmorozov
// - new: вычитывание потока, копирование потока;
//
// Revision 1.1 2006/04/03 10:49:30 mmorozov
// - new: выделена функция tstFileToStream;
//
interface
uses
ActiveX
;
function tstFileToStream(const aFileName : String;
const aDest : IStream): Boolean;
{* - записать файл в поток. }
function tstReadStream(const aStream : IStream;
const aSuccess : PBoolean = nil): String;
{* - возвращает прочинное из потока в качестве результата. }
implementation
uses
SysUtils,
Classes
;
function tstReadStream(const aStream : IStream;
const aSuccess : PBoolean = nil): String;
{* - возвращает прочитанное из потока в качестве результата. }
const
c_BufferSize = 512;
var
l_Written : Longint;
l_Result : HRESULT;
l_Str : String;
begin
Result := '';
if Assigned(aSuccess) then
aSuccess^ := False;
if Assigned(aStream) then
begin
SetLength(l_Str, c_BufferSize);
while True do
begin
l_Result := aStream.Read(@l_Str[1], c_BufferSize, @l_Written);
if l_Result <> S_OK then
begin
if (l_Result = S_FALSE) and Assigned(aSuccess) then
aSuccess^ := True;
Break;
end;//if l_Result <> S_OK then
if l_Written < c_BufferSize then
Result := Result + Copy(l_Str, 1, l_Written)
else
Result := Result + l_Str;
end;//while True do
end;//if Assigned(aStream) then
end;//tstReadStream
function tstFileToStream(const aFileName : String;
const aDest : IStream): Boolean;
var
l_FileStream : TFileStream;
l_Stream : IStream;
l_Read : Int64;
l_Written : Int64;
begin
Result := False;
if Assigned(aDest) and FileExists(aFileName) then
begin
l_FileStream := TFileStream.Create(aFileName, fmOpenRead);
try
if Supports(TStreamAdapter.Create(l_FileStream), IStream, l_Stream) then
try
Result := l_Stream.CopyTo(aDest, l_FileStream.Size, l_Read,
l_Written) = S_OK;
finally
l_Stream := nil;
end;{try..finally}
finally
FreeAndNil(l_FileStream);
end;{try..finally}
end;//if Assigned(aStream)..
end;//tstFileToStream
end. |
unit nsChangesBetweenEditionsDocumentContainer;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ChangesBetweenEditions$Domain"
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/ChangesBetweenEditions/nsChangesBetweenEditionsDocumentContainer.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> F1 Пользовательские сервисы::ChangesBetweenEditions::ChangesBetweenEditions$Domain::ChangesBetweenEditionsImplementation::TnsChangesBetweenEditionsDocumentContainer
//
// Контейнер документа для ОИД
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
DocumentUnit,
eeDocumentContainer,
nevTools,
ChangesBetweenEditionsInterfaces,
DocumentInterfaces,
F1TagDataProviderInterface,
afwInterfaces,
l3Interfaces,
nevBase,
k2Base,
Classes,
nevPrintableDocumentContainer,
l3IID
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
_nsDocumentContainer_Parent_ = TeeDocumentContainer;
{$Include w:\garant6x\implementation\Garant\GbaNemesis\F1DocumentProcessing\nsDocumentContainer.imp.pas}
_nsEditionsDecorationRules_Parent_ = _nsDocumentContainer_;
{$Include w:\common\components\gui\Garant\Everest\nsEditionsDecorationRules.imp.pas}
TnsChangesBetweenEditionsDocumentContainer = class(_nsEditionsDecorationRules_)
{* Контейнер документа для ОИД }
private
// private fields
f_DiffProvider : IDiffDocDataProvider;
f_Data : InsChangesBetweenEditionsInfo;
f_GettingDocumentCount : Integer;
private
// private methods
function MakeDocument: InevTag;
{* Создаёт документ из данных, которые приехали с адаптера }
protected
// overridden protected methods
procedure FinishDataUpdate; override;
function ReplaceContainerInOwner(const aDocumentContainer: InevDocumentContainer): Boolean; override;
function CanBePlacedInDocumentsCache: Boolean; override;
function GetDocument: InevTag; override;
procedure AfterCreate(const aDocInfo: IdeDocInfo); override;
procedure ClearFields; override;
public
// public methods
constructor Create(const aData: InsChangesBetweenEditionsInfo); reintroduce;
class function Make(const aData: InsChangesBetweenEditionsInfo): InevDocumentContainer; reintroduce;
{* Сигнатура фабрики TnsChangesBetweenEditionsDocumentContainer.Make }
end;//TnsChangesBetweenEditionsDocumentContainer
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Base,
deDocInfo,
Document_Const,
TextPara_Const,
k2Facade,
k2Tags,
nsTagString,
Table_Const,
TableRow_Const,
TableCell_Const,
l3MinMax,
l3Defaults,
nsStyleParser,
evdStyles,
f1TextStyle_Const,
BitmapPara_Const,
l3Memory,
l3Stream,
SysUtils,
nsIDocumentDataObject,
nsDocumentPreview,
nsHAFPainter,
LoggingInterfaces,
nsDocumentPrintEvent,
DataAdapter,
evdTypes,
nsTypes,
LeafPara_Const,
evParaTools,
afwFacade,
evTextStyle_Const
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type _Instance_R_ = TnsChangesBetweenEditionsDocumentContainer;
{$Include w:\garant6x\implementation\Garant\GbaNemesis\F1DocumentProcessing\nsDocumentContainer.imp.pas}
{$Include w:\common\components\gui\Garant\Everest\nsEditionsDecorationRules.imp.pas}
// start class TnsChangesBetweenEditionsDocumentContainer
function TnsChangesBetweenEditionsDocumentContainer.MakeDocument: InevTag;
//#UC START# *4EA6BBFA01DF_4DDD0D92039C_var*
function MakeLeafPara(const aData : TDiffDocPara; aStyleID : Integer): InevTag;
var
l_T : InevTag;
l_S : TnsTagString;
l_Stream : TStream;
begin//MakeLeafPara
if (k2.TypeTable[Integer(aData.rType)] = nil) then
// - костыль, на случай приезжания мусора с сервера
l_T := k2_typTextPara.MakeTag
else
(* begin
Result := nil;
Exit;
end;//k2.TypeTable[Integer(aData.rType)] = nil*)
l_T := k2.TypeTable[Integer(aData.rType)].MakeTag;
try
if (aData.rStyle <> nil) then
TnsStyleParser.Parse(aData.rStyle, l_T);
if (aStyleID <> 0) then
l_T.IntA[k2_tiStyle] := aStyleID;
if (l_T.IntA[k2_tiStyle] = ev_saChangesInfo) then
l_T.BoolA[k2_tiCollapsed] := false;
if (aData.rText <> nil) AND (aData.rText.GetLength > 0) then
begin
l_S := TnsTagString.Create(aData.rText);
try
l_T.ObjW[k2_tiText, nil] := l_S;
finally
FreeAndNil(l_S);
end;//try..finally
end;//aData.rText <> nil
l_T.IntA[k2_tiHandle] := aData.rID;
// http://mdp.garant.ru/pages/viewpage.action?pageId=290267630
// http://mdp.garant.ru/pages/viewpage.action?pageId=290267630&focusedCommentId=290952637#comment-290952637
if l_T.InheritsFrom(k2_idBitmapPara) then
// http://mdp.garant.ru/pages/viewpage.action?pageId=303858634
begin
if (aData.rData <> nil) then
begin
l3IStream2Stream(aData.rData, l_Stream);
try
l_T.ObjW[k2_tiData, nil] := l_Stream;
finally
FreeAndNil(l_Stream);
end;//try..finally
end;//aData.rData <> nil
end;//l_T.InheritsFrom(k2_idBitmapPara)
Result := l_T;
finally
l_T := nil;
end;//try..finally
end;//MakeLeafPara
function MakeCell(const aRow : InevTag): InevTag;
var
l_TC : InevTag;
begin//MakeCell
l_TC := k2_typTableCell.MakeTag;
try
l_TC.IntA[k2_tiWidth] := def_inchPrintableWidth div 2;
aRow.AddChild(l_TC);
Result := l_TC;
finally
l_TC := nil;
end;//try..finally
end;//MakeCell
function AddLeafToCont(const aCont : InevTag;
const aData : TDiffDocPara;
aStyleID : Integer = 0): InevTag;
var
l_LP : InevTag;
begin//AddLeafToCont
l_LP := MakeLeafPara(aData, aStyleID);
Result := l_LP;
Assert(Result <> nil);
if (l_LP <> nil) then
try
aCont.AddChild(l_LP);
finally
l_LP := nil;
end;//try..finally
end;//AddLeafToCont
procedure AddListToCont(const aCont : InevTag;
const aList : IDiffDocParaList;
const aStyles : array of Integer);
var
l_P : TDiffDocPara;
l_Index : Integer;
l_St : Integer;
l_Added : Boolean;
l_EmptyTextPara : InevTag;
begin//AddListToCont
l_Added := false;
if (aList <> nil) then
begin
for l_Index := 0 to Pred(aList.Count) do
begin
aList.pm_GetItem(l_Index, l_P);
try
if (l_Index >= Low(aStyles)) AND (l_Index <= High(aStyles)) then
l_St := aStyles[l_Index]
else
l_St := 0;
AddLeafToCont(aCont, l_P, l_St);
l_Added := true;
finally
Finalize(l_P);
end;//try..finally
end;//for l_Index
end;//aList <> nil
if not l_Added AND aCont.InheritsFrom(k2_idTableCell) then
// - http://mdp.garant.ru/pages/viewpage.action?pageId=327826921
begin
//l_EmptyTextPara := k2_typTextPara.MakeTag;
l_EmptyTextPara := Tk2Type(aCont.TagType).ArrayProp[k2_tiChildren].DefaultChildType.MakeTag;
try
aCont.AddChild(l_EmptyTextPara);
finally
l_EmptyTextPara := nil;
end;//try..finally
end;//not l_Added..
end;//AddListToCont
procedure AddListToContWithFixedStyle(const aCont : InevTag;
const aList : IDiffDocParaList;
aStyle : Integer);
var
l_P : TDiffDocPara;
l_Index : Integer;
begin//AddListToContWithFixedStyle
if (aList <> nil) then
for l_Index := 0 to Pred(aList.Count) do
begin
aList.pm_GetItem(l_Index, l_P);
try
AddLeafToCont(aCont, l_P, aStyle);
finally
Finalize(l_P);
end;//try..finally
end;//for l_Index
end;//AddListToContWithFixedStyle
var
l_D : InevTag;
l_L : IDiffDocParaList;
l_P : TDiffDocPara;
l_Index : Integer;
l_Tb : InevTag;
l_TR : InevTag;
l_CB : TChangedBlock;
l_LeftDate : TDiffDocPara;
l_RightDate : TDiffDocPara;
l_LeftDateGot : Boolean;
l_RightDateGot : Boolean;
//#UC END# *4EA6BBFA01DF_4DDD0D92039C_var*
begin
//#UC START# *4EA6BBFA01DF_4DDD0D92039C_impl*
Assert(f_DocumentInfo <> nil);
Assert(f_DocumentInfo.Doc <> nil);
Assert(f_DiffProvider <> nil);
l_D := k2_typDocument.MakeTag;
try
Result := l_D;
l_D.IntA[k2_tiExternalHandle] := f_DocumentInfo.Doc.GetInternalId;
f_DiffProvider.GetHeaderParaList(l_L);
try
AddListToCont(l_D, l_L, [f1_saChanges1, ev_saTxtHeader1, f1_saChanges1, f1_saChanges2]);
finally
l_L := nil;
end;//try..finally
Finalize(l_LeftDate);
l3FillChar(l_LeftDate, SizeOf(l_LeftDate));
// - перестраховываемся
l_LeftDateGot := f_DiffProvider.GetDateParaLeft(l_LeftDate);
Finalize(l_RightDate);
l3FillChar(l_RightDate, SizeOf(l_RightDate));
// - перестраховываемся
l_RightDateGot := f_DiffProvider.GetDateParaRight(l_RightDate);
if l_LeftDateGot AND l_RightDateGot then
begin
l_Tb := k2_typTable.MakeTag;
try
l_TR := k2_typTableRow.MakeTag;
try
AddLeafToCont(MakeCell(l_TR), l_LeftDate, ev_saChangesInfo);
AddLeafToCont(MakeCell(l_TR), l_RightDate, ev_saChangesInfo);
l_Tb.AddChild(l_TR);
finally
l_TR := nil;
end;//try..finally
l_D.AddChild(l_Tb);
finally
l_Tb := nil;
end;//try..finally
end//l_LeftDateGot AND l_RightDateGot
else
begin
Assert(l_LeftDateGot = l_RightDateGot, 'http://mdp.garant.ru/pages/viewpage.action?pageId=281525453&focusedCommentId=336138971#comment-336138971');
end;//l_LeftDateGot AND l_RightDateGot
for l_Index := 0 to Pred(
Integer(f_DiffProvider.GetChangedBlockCount)
// http://mdp.garant.ru/pages/viewpage.action?pageId=294599509
) do
begin
f_DiffProvider.GetChangedBlock(l_Index, l_CB);
try
AddListToContWithFixedStyle(l_D, l_CB.rHeader, ev_saTxtHeader1);
l_Tb := k2_typTable.MakeTag;
try
l_TR := k2_typTableRow.MakeTag;
try
f_DiffProvider.GetRedactionNameLeft(l_P);
AddLeafToCont(MakeCell(l_TR), l_P);
f_DiffProvider.GetRedactionNameRight(l_P);
AddLeafToCont(MakeCell(l_TR), l_P);
l_Tb.AddChild(l_TR);
finally
l_TR := nil;
end;//try..finally
l_TR := k2_typTableRow.MakeTag;
try
AddListToCont(MakeCell(l_TR), l_CB.rLeftTextParaList, []);
AddListToCont(MakeCell(l_TR), l_CB.rRightTextParaList, []);
l_Tb.AddChild(l_TR);
finally
l_TR := nil;
end;//try..finally
l_D.AddChild(l_Tb);
finally
l_Tb := nil;
end;//try..finally
finally
Finalize(l_CB);
end;//try..finally
end;//for l_Index
l_D.IntA[k2_tiAllChildrenCount] := Max(l_D.ChildrenCount, f_DiffProvider.GetAllLeafParaCount);
Document := l_D;
finally
l_D := nil;
end;//try..finally
//#UC END# *4EA6BBFA01DF_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.MakeDocument
constructor TnsChangesBetweenEditionsDocumentContainer.Create(const aData: InsChangesBetweenEditionsInfo);
//#UC START# *4DDD0E080101_4DDD0D92039C_var*
//#UC END# *4DDD0E080101_4DDD0D92039C_var*
begin
//#UC START# *4DDD0E080101_4DDD0D92039C_impl*
f_Data := aData;
f_DiffProvider := aData.DiffProvider;
inherited Create(TdeDocInfo.Make(aData.RightEdition));
//#UC END# *4DDD0E080101_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.Create
class function TnsChangesBetweenEditionsDocumentContainer.Make(const aData: InsChangesBetweenEditionsInfo): InevDocumentContainer;
var
l_Inst : TnsChangesBetweenEditionsDocumentContainer;
begin
l_Inst := Create(aData);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
procedure TnsChangesBetweenEditionsDocumentContainer.FinishDataUpdate;
//#UC START# *47EA4E9002C6_4DDD0D92039C_var*
//#UC END# *47EA4E9002C6_4DDD0D92039C_var*
begin
//#UC START# *47EA4E9002C6_4DDD0D92039C_impl*
inherited;
f_DiffProvider := nil;
(* Assert(f_Data <> nil);
f_DiffProvider := f_Data.DiffProvider;
MakeDocument;*)
// - вообще говоря тут это нельзя делать, т.к. TnsChangesBetweenEditionsInfo.FinishDataUpdate
// может придти позже и его данные - не сбросятся
//#UC END# *47EA4E9002C6_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.FinishDataUpdate
function TnsChangesBetweenEditionsDocumentContainer.ReplaceContainerInOwner(const aDocumentContainer: InevDocumentContainer): Boolean;
//#UC START# *47F1024C0150_4DDD0D92039C_var*
//#UC END# *47F1024C0150_4DDD0D92039C_var*
begin
//#UC START# *47F1024C0150_4DDD0D92039C_impl*
Result := inherited ReplaceContainerInOwner(aDocumentContainer);
// - см. комментарии к TnsChangesBetweenEditionsDocumentContainer.CanBePlacedInDocumentsCache
//#UC END# *47F1024C0150_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.ReplaceContainerInOwner
function TnsChangesBetweenEditionsDocumentContainer.CanBePlacedInDocumentsCache: Boolean;
//#UC START# *47F10C6E0240_4DDD0D92039C_var*
//#UC END# *47F10C6E0240_4DDD0D92039C_var*
begin
//#UC START# *47F10C6E0240_4DDD0D92039C_impl*
//Result := inherited CanBePlacedInDocumentsCache;
Result := false;
// http://mdp.garant.ru/pages/viewpage.action?pageId=305962757
// - на самом деле конечно - костыль, т.к. надо в TnevDocumentContainer.IsSame
// проверять ещё и класс контейнера,
// а в TnsChangesBetweenEditionsDocumentContainer.GetIsSame ещё и вторую редакцию
// если уж так захочется класть контейнеры ОИД в кеш документов.
// !!! Хотя в кеш помещать может и придётся - для тех же нотификаций
//#UC END# *47F10C6E0240_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.CanBePlacedInDocumentsCache
function TnsChangesBetweenEditionsDocumentContainer.GetDocument: InevTag;
//#UC START# *47F27DA80172_4DDD0D92039C_var*
//#UC END# *47F27DA80172_4DDD0D92039C_var*
begin
//#UC START# *47F27DA80172_4DDD0D92039C_impl*
Result := inherited GetDocument;
if (Result = nil) then
begin
Assert(f_GettingDocumentCount = 0);
Inc(f_GettingDocumentCount);
try
Assert(f_Data <> nil);
if (f_DiffProvider = nil) then
f_DiffProvider := f_Data.DiffProvider;
Result := MakeDocument;
finally
Dec(f_GettingDocumentCount);
end;//try..finally
end;//Result = nil
//#UC END# *47F27DA80172_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.GetDocument
procedure TnsChangesBetweenEditionsDocumentContainer.AfterCreate(const aDocInfo: IdeDocInfo);
//#UC START# *4B1FBF87020C_4DDD0D92039C_var*
//#UC END# *4B1FBF87020C_4DDD0D92039C_var*
begin
//#UC START# *4B1FBF87020C_4DDD0D92039C_impl*
inherited;
MakeDocument;
//#UC END# *4B1FBF87020C_4DDD0D92039C_impl*
end;//TnsChangesBetweenEditionsDocumentContainer.AfterCreate
procedure TnsChangesBetweenEditionsDocumentContainer.ClearFields;
{-}
begin
f_DiffProvider := nil;
f_Data := nil;
inherited;
end;//TnsChangesBetweenEditionsDocumentContainer.ClearFields
{$IfEnd} //not Admin AND not Monitorings
end. |
Unit Numeric;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
{$macro on}
{$inline on}
interface
uses
CoreTypes, Math, SysUtils;
function SumFPtr(Ptr:PChar; Size:UInt8; Len:LongInt): Extended; cdecl;
function SumPtr(Ptr:PChar; Size:UInt8; Len:LongInt; Signed:Boolean): Int64; cdecl;
function SumTBA(const Arr: CoreTypes.TByteArray): Int64; Inline;
function SumTIA(const Arr: TIntArray): Int64; Inline;
function SumTEA(const Arr: TExtArray): Extended; Inline;
procedure MinMaxFPtr(Ptr:PChar; Size:UInt8; Len:LongInt; var Min,Max:Extended); cdecl;
procedure MinMaxPtr(Ptr:PChar; Size:UInt8; Len:LongInt; Signed:Boolean; var Min,Max:Int64); cdecl;
procedure MinMaxTBA(const Arr: CoreTypes.TByteArray; var Min:Byte; var Max: Byte); Inline;
procedure MinMaxTIA(const Arr: TIntArray; var Min:Integer; var Max: Integer); Inline;
procedure MinMaxTEA(const Arr: TExtArray; var Min:Extended; var Max: Extended); Inline;
function TIACombinations(const Arr: TIntArray; Seq:Integer): T2DIntArray;
function TEACombinations(const Arr: TExtArray; Seq:Integer): T2DExtArray;
function TIAMatches(const Arr1, Arr2:TIntArray; InPercent, Inversed:Boolean): Int32;
function LogscaleTIA(const Freq:TIntArray; Scale: Integer): TIntArray;
//--------------------------------------------------
implementation
{*
Returns the sum of a normal floating point type array.
*}
function SumFPtr(Ptr:PChar; Size:UInt8; Len:LongInt): Extended; cdecl;
var l:Int32;
begin
Result := 0;
l := UInt32(ptr)+(len*size);
while (UInt32(ptr) < l) do begin
case size of
4 : Result := Result + PFloat32(Ptr)^;
8 : Result := Result + PFloat64(Ptr)^;
10: Result := Result + PFloat80(Ptr)^;
end;
Inc(ptr,size);
end;
end;
{*
Returns the sum of a normal int type array.
*}
function SumPtr(Ptr:PChar; Size:UInt8; Len:LongInt; Signed:Boolean): Int64; cdecl;
var l:Int32;
begin
Result := 0;
l := UInt32(ptr)+(len*size);
case signed of
True:
while (UInt32(ptr) < l) do begin
case size of
1 : Result := Result + PUInt8(Ptr)^;
2 : Result := Result + PUInt16(Ptr)^;
4 : Result := Result + PUInt32(Ptr)^;
8 : Result := Result + PUInt64(Ptr)^;
end;
Inc(ptr,size);
end;
False:
while (UInt32(ptr) < l) do begin
case size of
1 : Result := Result + PInt8(Ptr)^;
2 : Result := Result + PInt16(Ptr)^;
4 : Result := Result + PInt32(Ptr)^;
8 : Result := Result + PInt64(Ptr)^;
end;
Inc(ptr,size);
end;
end;
end;
{*
Sum of a TBA.
*}
function SumTBA(const Arr: CoreTypes.TByteArray): Int64; Inline;
var i:Integer;
begin
Result := 0;
for i:=Low(Arr) to High(Arr) do
Result := Result + Arr[i];
end;
{*
Sum of a TIA.
*}
function SumTIA(const Arr: TIntArray): Int64; Inline;
var i:Integer;
begin
Result := 0;
for i:=Low(Arr) to High(Arr) do
Result := Result + Arr[i];
end;
{*
Sum of a TEA.
*}
function SumTEA(const Arr: TExtArray): Extended; Inline;
var i:Integer;
begin
Result := 0.0;
for i:=Low(Arr) to High(Arr) do
Result := Result + Arr[i];
end;
{*
Finds the minimum and maximum of a single-, double-, or extended array.
*}
procedure MinMaxFPtr(Ptr:PChar; Size:UInt8; Len:LongInt; var Min,Max:Extended); cdecl;
var l:Int32;
begin
l := UInt32(ptr)+(len*size);
case size of
4 :begin Min := PFloat32(Ptr)^; Max := Min; end;
8 :begin Min := PFloat64(Ptr)^; Max := Min; end;
10:begin Min := PFloat80(Ptr)^; Max := Min; end;
end;
while (UInt32(ptr) < l) do begin
case size of
4 : if PFloat32(Ptr)^ < Min then Min := PFloat32(Ptr)^
else if PFloat32(Ptr)^ > Max then Max := PFloat32(Ptr)^;
8 : if PFloat64(Ptr)^ < Min then Min := PFloat64(Ptr)^
else if PFloat64(Ptr)^ > Max then Max := PFloat64(Ptr)^;
10: if PFloat80(Ptr)^ < Min then Min := PFloat80(Ptr)^
else if PFloat80(Ptr)^ > Max then Max := PFloat80(Ptr)^;
end;
Inc(ptr,size);
end;
end;
{*
Finds the minimum and maximum of any normal integer typed array.
*}
procedure MinMaxPtr(Ptr:PChar; Size:UInt8; Len:LongInt; Signed:Boolean; var Min,Max:Int64); cdecl;
var l:Int32; tmp:Int64;
begin
l := UInt32(ptr)+(len*size);
if signed then
case size of
1 :begin Min := PInt8(Ptr)^; Max := Min; end;
2 :begin Min := PInt16(Ptr)^; Max := Min; end;
4 :begin Min := PInt32(Ptr)^; Max := Min; end;
8 :begin Min := PInt64(Ptr)^; Max := Min; end;
end
else
case size of
1 :begin Min := PUInt8(Ptr)^; Max := Min; end;
2 :begin Min := PUInt16(Ptr)^; Max := Min; end;
4 :begin Min := PUInt32(Ptr)^; Max := Min; end;
8 :begin Min := PUInt64(Ptr)^; Max := Min; end;
end;
case signed of
True:
while (UInt32(ptr) < l) do begin
case size of
1: tmp := PUInt8(Ptr)^;
2: tmp := PUInt16(Ptr)^;
4: tmp := PUInt32(Ptr)^;
8: tmp := PUInt64(Ptr)^;
end;
if (tmp < Min) then Min := tmp else if (tmp > Max) then Max := tmp;
Inc(ptr,size);
end;
False:
while (UInt32(ptr) < l) do begin
case size of
1: tmp := PUInt8(Ptr)^;
2: tmp := PUInt16(Ptr)^;
4: tmp := PUInt32(Ptr)^;
8: tmp := PUInt64(Ptr)^;
end;
if (tmp < Min) then Min := tmp else if (tmp > Max) then Max := tmp;
Inc(ptr,size);
end;
end;
end;
{*
Finds the minimum and maximum of a TBA.
*}
procedure MinMaxTBA(const Arr: CoreTypes.TByteArray; var Min:Byte; var Max: Byte); Inline;
var i:Int32;
begin
Min := Arr[0];
Max := Arr[0];
for i:=Low(Arr) to High(Arr) do
if (Arr[i] < Min) then Min := Arr[i] else if (Arr[i] > Max) then Max := Arr[i];
end;
{*
Finds the minimum and maximum of a TIA.
*}
procedure MinMaxTIA(const Arr: TIntArray; var Min:Integer; var Max: Integer); Inline;
var i:Int32;
begin
Min := Arr[0];
Max := Arr[0];
for i:=Low(Arr) to High(Arr) do
if (Arr[i] < Min) then Min := Arr[i] else if (Arr[i] > Max) then Max := Arr[i];
end;
{*
Finds the minimum and maximum of a TEA.
*}
procedure MinMaxTEA(const Arr: TExtArray; var Min:Extended; var Max: Extended); Inline;
var i:Integer;
begin
Min := Arr[0];
Max := Arr[0];
for i:=Low(Arr) to High(Arr) do
if (Arr[i] < Min) then Min := Arr[i] else if (Arr[i] > Max) then Max := Arr[i];
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~]
[--| OLDER STUFF |-----------------------------------------------------------------]
[~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{*
Combinations of size `seq` from given TIA `arr`.
*}
function TIACombinations(const Arr:TIntArray; Seq:Integer): T2DIntArray;
var
n,h,i,j: Integer;
indices: TIntArray;
breakout: Boolean;
begin
n := Length(arr);
if seq > n then Exit;
SetLength(indices, seq);
for i:=0 to (seq-1) do indices[i] := i;
SetLength(Result, 1, Seq);
for i:=0 to (seq-1) do Result[0][i] := arr[i];
while True do
begin
breakout := True;
for i:=(Seq-1) downto 0 do
if (indices[i] <> (i + n - Seq)) then begin
breakout := False;
Break;
end;
if breakout then Exit;
Indices[i] := Indices[i]+1;
for j:=i+1 to Seq-1 do
Indices[j] := (Indices[j-1] + 1);
h := Length(Result);
SetLength(Result, h+1);
SetLength(Result[h], Seq);
for i:=0 to Seq-1 do
Result[h][i] := Arr[Indices[i]];
end;
SetLength(Indices, 0);
end;
{*
Combinations of size `seq` from given TEA `arr`.
*}
function TEACombinations(const Arr: TExtArray; Seq:Integer): T2DExtArray;
var
n,h,i,j: Integer;
indices: TIntArray;
breakout: Boolean;
begin
n := Length(arr);
if seq > n then Exit;
SetLength(Indices, seq);
for i:=0 to (seq-1) do Indices[i] := i;
SetLength(Result, 1, Seq);
for i:=0 to (seq-1) do Result[0][i] := Arr[i];
while True do
begin
breakout := True;
for i:=(Seq-1) downto 0 do
if (Indices[i] <> (i + n - Seq)) then begin
Breakout := False;
Break;
end;
if Breakout then Exit;
Indices[i] := Indices[i]+1;
for j:=i+1 to Seq-1 do
Indices[j] := (Indices[j-1] + 1);
h := Length(Result);
SetLength(Result, h+1);
SetLength(Result[h], Seq);
for i:=0 to Seq-1 do
Result[h][i] := Arr[Indices[i]];
end;
SetLength(Indices, 0);
end;
{*
Finds the amount of different indices, by comparing each index in "Arr1" to each index in "Arr2".
*}
function TIAMatches(const Arr1, Arr2:TIntArray; InPercent, Inversed:Boolean): Int32;
var H,i:integer;
begin
H := Min(High(Arr1), High(Arr2));
Result := Abs(High(Arr1) - High(Arr2));
for I:=0 to H do
if (Arr1[I] <> Arr2[I]) then
Inc(Result);
if InPercent then begin
H := Max(High(Arr1), High(Arr2));
Result := Trunc((Result / H) * 100);
end;
if Inversed then begin
case InPercent of
True : Result := (100-Result);
False: Result := (Max(High(Arr1), High(Arr2)) - Result);
end;
end;
end;
{*
Given a TIA with a range of numbers it scales each element in a logarithmic pattern:
EG:
> Freq := [0,1,2,3,4]
> Scale := 2;
> Result := [0, 1,1, 2,2,2,2, 3,3,3,3,3,3,3,3, ...];
*}
function LogscaleTIA(const Freq:TIntArray; Scale: Integer): TIntArray;
var
Size,i,j,H: Integer;
step,L:Integer;
begin
H := High(Freq);
if H = -1 then Exit;
if (Scale <= 1) or (H = 0) then
begin
Result := Copy(Freq);
Exit;
end;
Step := 1;
SetLength(Result, Step);
Size := 1;
L := 0;
i := 0;
for i:=0 to H do
begin
for j:=0 to Size-1 do
begin
if L >= Step then begin
step := step+step;
SetLength(Result, step);
end;
Result[L] := Freq[i];
Inc(L);
end;
Size := Size * Scale;
end;
SetLength(Result, L);
end;
end.
|
unit ConvToIsometricTestWindow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls;
type
TForm1 = class(TForm)
Original: TImage;
Converted: TImage;
Convert: TBitBtn;
Load: TBitBtn;
OpenDialog: TOpenDialog;
SaveIt: TBitBtn;
SaveDialog: TSaveDialog;
procedure LoadClick(Sender: TObject);
procedure ConvertClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SaveItClick(Sender: TObject);
private
{ Private declarations }
fCurrentBitmap : TBitmap;
fTemplate : TBitmap;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses
ConvertToIsometric;
procedure TForm1.LoadClick(Sender: TObject);
begin
if OpenDialog.Execute
then
begin
fCurrentBitmap.Free;
fCurrentBitmap := TBitmap.Create;
fCurrentBitmap.LoadFromFile(OpenDialog.FileName);
Original.Picture.Bitmap := fCurrentBitmap;
end;
end;
procedure TForm1.ConvertClick(Sender: TObject);
begin
if fCurrentBitmap <> nil
then Converted.Picture.Bitmap := ConvertBmpToIsometric(fTemplate, fCurrentBitmap);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
fTemplate := TBitmap.Create;
fTemplate.LoadFromFile('template.bmp');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
fTemplate.Free;
end;
procedure TForm1.SaveItClick(Sender: TObject);
begin
SaveDialog.FileName := OpenDialog.FileName;
if SaveDialog.Execute
then Converted.Picture.Bitmap.SaveToFile(SaveDialog.FileName);
end;
end.
|
unit VoyagerInterfaces;
interface
uses
Controls, Graphics;
type
TURL = string;
TURLHandlerOption = (hopNonVisual, hopCacheable, hopCannotCloseIfBusy, hopEnabledWhenCached);
TURLHandlerOptions = set of TURLHandlerOption;
THandlingAbility = integer;
TURLHandlingResult = (urlNotHandled, urlHandled, urlError);
TEventHandlingResult = (evnNotHandled, evnHandled, evnError);
TEventId = integer;
TMetaHandlerRegistrationResult = (mhrRegistered, mhrDuplicated, mhrUknownError);
type
// Interfaces defined:
IMetaURLHandler = interface;
IURLHandler = interface;
IMasterURLHandler = interface;
IMetaURLHandler =
interface
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
end;
IURLHandler =
interface
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( const URLHandler : IMasterURLHandler );
end;
IMasterURLHandler =
interface( IURLHandler )
function RegisterMetaHandler( const aMetaURLHandler : IMetaURLHandler ) : TMetaHandlerRegistrationResult;
procedure RegisterDefaultHandler( Handler : string );
procedure RegisterExclusion( Excluder, ToExclude : string; mutual : boolean );
procedure ReportNavigation( const Handler : IURLHandler; URL : TURL; localBack, localForward : boolean );
function getURLIsLocal( URL : TURL ) : boolean;
end;
const
cmdAnswerChatHandler = 62332;
type
TChatRendererImageLocator = function ( ImgId : string ) : TGraphic of object;
IChatHandler =
interface
function getImageLocator : TChatRendererImageLocator;
function filterChatLine( line : string ) : string;
end;
implementation
end.
|
unit infoPOSTSOATable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TinfoPOSTSOARecord = record
PDatePaid: String[8];
PCheckNumber: String[10];
PtranType: String[1];
PAmount: Currency;
PPmtType: String[2];
End;
TinfoPOSTSOABuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TinfoPOSTSOARecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIinfoPOSTSOA = (infoPOSTSOAPrimaryKey);
TinfoPOSTSOATable = class( TDBISAMTableAU )
private
FDFDatePaid: TStringField;
FDFCheckNumber: TStringField;
FDFtranType: TStringField;
FDFAmount: TCurrencyField;
FDFPmtType: TStringField;
procedure SetPDatePaid(const Value: String);
function GetPDatePaid:String;
procedure SetPCheckNumber(const Value: String);
function GetPCheckNumber:String;
procedure SetPtranType(const Value: String);
function GetPtranType:String;
procedure SetPAmount(const Value: Currency);
function GetPAmount:Currency;
procedure SetPPmtType(const Value: String);
function GetPPmtType:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIinfoPOSTSOA);
function GetEnumIndex: TEIinfoPOSTSOA;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TinfoPOSTSOARecord;
procedure StoreDataBuffer(ABuffer:TinfoPOSTSOARecord);
property DFDatePaid: TStringField read FDFDatePaid;
property DFCheckNumber: TStringField read FDFCheckNumber;
property DFtranType: TStringField read FDFtranType;
property DFAmount: TCurrencyField read FDFAmount;
property DFPmtType: TStringField read FDFPmtType;
property PDatePaid: String read GetPDatePaid write SetPDatePaid;
property PCheckNumber: String read GetPCheckNumber write SetPCheckNumber;
property PtranType: String read GetPtranType write SetPtranType;
property PAmount: Currency read GetPAmount write SetPAmount;
property PPmtType: String read GetPPmtType write SetPPmtType;
published
property Active write SetActive;
property EnumIndex: TEIinfoPOSTSOA read GetEnumIndex write SetEnumIndex;
end; { TinfoPOSTSOATable }
procedure Register;
implementation
function TinfoPOSTSOATable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TinfoPOSTSOATable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TinfoPOSTSOATable.GenerateNewFieldName }
function TinfoPOSTSOATable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TinfoPOSTSOATable.CreateField }
procedure TinfoPOSTSOATable.CreateFields;
begin
FDFDatePaid := CreateField( 'DatePaid' ) as TStringField;
FDFCheckNumber := CreateField( 'CheckNumber' ) as TStringField;
FDFtranType := CreateField( 'tranType' ) as TStringField;
FDFAmount := CreateField( 'Amount' ) as TCurrencyField;
FDFPmtType := CreateField( 'PmtType' ) as TStringField;
end; { TinfoPOSTSOATable.CreateFields }
procedure TinfoPOSTSOATable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TinfoPOSTSOATable.SetActive }
procedure TinfoPOSTSOATable.SetPDatePaid(const Value: String);
begin
DFDatePaid.Value := Value;
end;
function TinfoPOSTSOATable.GetPDatePaid:String;
begin
result := DFDatePaid.Value;
end;
procedure TinfoPOSTSOATable.SetPCheckNumber(const Value: String);
begin
DFCheckNumber.Value := Value;
end;
function TinfoPOSTSOATable.GetPCheckNumber:String;
begin
result := DFCheckNumber.Value;
end;
procedure TinfoPOSTSOATable.SetPtranType(const Value: String);
begin
DFtranType.Value := Value;
end;
function TinfoPOSTSOATable.GetPtranType:String;
begin
result := DFtranType.Value;
end;
procedure TinfoPOSTSOATable.SetPAmount(const Value: Currency);
begin
DFAmount.Value := Value;
end;
function TinfoPOSTSOATable.GetPAmount:Currency;
begin
result := DFAmount.Value;
end;
procedure TinfoPOSTSOATable.SetPPmtType(const Value: String);
begin
DFPmtType.Value := Value;
end;
function TinfoPOSTSOATable.GetPPmtType:String;
begin
result := DFPmtType.Value;
end;
procedure TinfoPOSTSOATable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('DatePaid, String, 8, N');
Add('CheckNumber, String, 10, N');
Add('tranType, String, 1, N');
Add('Amount, Currency, 0, N');
Add('PmtType, String, 2, N');
end;
end;
procedure TinfoPOSTSOATable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, DatePaid;CheckNumber, Y, Y, N, N');
end;
end;
procedure TinfoPOSTSOATable.SetEnumIndex(Value: TEIinfoPOSTSOA);
begin
case Value of
infoPOSTSOAPrimaryKey : IndexName := '';
end;
end;
function TinfoPOSTSOATable.GetDataBuffer:TinfoPOSTSOARecord;
var buf: TinfoPOSTSOARecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PDatePaid := DFDatePaid.Value;
buf.PCheckNumber := DFCheckNumber.Value;
buf.PtranType := DFtranType.Value;
buf.PAmount := DFAmount.Value;
buf.PPmtType := DFPmtType.Value;
result := buf;
end;
procedure TinfoPOSTSOATable.StoreDataBuffer(ABuffer:TinfoPOSTSOARecord);
begin
DFDatePaid.Value := ABuffer.PDatePaid;
DFCheckNumber.Value := ABuffer.PCheckNumber;
DFtranType.Value := ABuffer.PtranType;
DFAmount.Value := ABuffer.PAmount;
DFPmtType.Value := ABuffer.PPmtType;
end;
function TinfoPOSTSOATable.GetEnumIndex: TEIinfoPOSTSOA;
var iname : string;
begin
result := infoPOSTSOAPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := infoPOSTSOAPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TinfoPOSTSOATable, TinfoPOSTSOABuffer ] );
end; { Register }
function TinfoPOSTSOABuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..5] of string = ('DATEPAID','CHECKNUMBER','TRANTYPE','AMOUNT','PMTTYPE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 5) and (flist[x] <> s) do inc(x);
if x <= 5 then result := x else result := 0;
end;
function TinfoPOSTSOABuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftCurrency;
5 : result := ftString;
end;
end;
function TinfoPOSTSOABuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PDatePaid;
2 : result := @Data.PCheckNumber;
3 : result := @Data.PtranType;
4 : result := @Data.PAmount;
5 : result := @Data.PPmtType;
end;
end;
end.
|
unit IMPORT_Math;
interface
uses
Math,
SysUtils,
Classes,
PaxCompiler,
PaxProgram,
PAXCOMP_CONSTANTS;
procedure RegisterForPaxCompiler(C: TPaxCompiler; L1, L2: TList);
procedure RegisterForPaxProgram(P: TPaxProgram; L1, L2: TList);
implementation
// TRIGONOMETRY ROUTINES ///////////////////////////////////////////////////////
procedure RegisterForPaxProgram(P: TPaxProgram; L1, L2: TList);
var
I: Integer;
begin
if L1.Count <> L2.Count then
raise Exception.Create('Error');
for I:=0 to L1.Count - 1 do
P.SetAddress(Integer(L1[I]), L2[I]);
end;
function _ArcCos(const X: Double): Double;
begin
result := ArcCos(X);
end;
procedure RegisterForPaxCompiler(C: TPaxCompiler; L1, L2: TList);
var
H_Namespace, H: Integer;
begin
// TRIGONOMETRY ROUTINES ///////////////////////////////////////////////////////
H_Namespace := C.RegisterNamespace(0, 'Math');
H := C.RegisterRoutine(H_Namespace, 'ArcCos', typeDOUBLE, ccREGISTER);
C.RegisterParameter(H, typeDOUBLE);
L1.Add(Pointer(H));
L2.Add(@_ArcCos);
end;
end.
|
{
model.pas
Model class for the texteditor class. Holds and manages resource files and user data.
This example project is released under public domain
AUTHORS: Felipe Monteiro de Carvalho
}
unit model;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
MacOSAll, objc, appkit, foundation;
type
{ TMyModel }
TMyModel = class
private
procedure LoadImages;
function GetResourcesDir: string;
public
{ Routines and variables for program resources }
imgOpen, imgSave, imgClose: NSImage;
ResourcesDir: string;
DocumentName: shortstring;
constructor Create;
end;
const
Str_Untitled = 'Untitled /1';
var
myModel: TMyModel;
implementation
procedure TMyModel.LoadImages;
var
ImagePath: CFStringRef;
begin
ImagePath := CFStringCreateWithPascalString(nil, ResourcesDir + 'imgOpen.png', kCFStringEncodingUTF8);
imgOpen := NSImage.initWithContentsOfFile(ImagePath);
ImagePath := CFStringCreateWithPascalString(nil, ResourcesDir + 'imgSave.png', kCFStringEncodingUTF8);
imgSave := NSImage.initWithContentsOfFile(ImagePath);
ImagePath := CFStringCreateWithPascalString(nil, ResourcesDir + 'imgClose.png', kCFStringEncodingUTF8);
imgClose := NSImage.initWithContentsOfFile(ImagePath);
end;
function TMyModel.GetResourcesDir: string;
const
BundleResourcesDirectory = '/Contents/Resources/';
var
pathRef: CFURLRef;
pathCFStr: CFStringRef;
pathStr: shortstring;
begin
// Under Mac OS X we need to get the location of the bundle
pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle());
pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle);
CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding());
CFRelease(pathRef);
CFRelease(pathCFStr);
Result := pathStr + BundleResourcesDirectory;
end;
constructor TMyModel.Create;
begin
ResourcesDir := GetResourcesDir;
LoadImages;
DocumentName := Str_Untitled;
end;
end.
|
unit pgFunction;
// Модуль: "w:\common\components\rtl\Garant\PG\pgFunction.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TpgFunction" MUID: (56616E840213)
{$Include w:\common\components\rtl\Garant\PG\pgDefine.inc}
interface
{$If Defined(UsePostgres)}
uses
l3IntfUses
, daQuery
, daInterfaces
, daParamList
, daSelectFieldList
, pgConnection
, pgParamDecsriptionList
;
type
TpgFunction = class(TdaQuery, IdaFunction)
private
f_SchemeName: AnsiString;
f_FunctionName: AnsiString;
f_CanReturnSet: Boolean;
f_InParamList: TdaParamList;
f_OutParamList: TdaParamList;
f_SelectFields: TdaSelectFieldList;
f_QueryName: AnsiString;
f_Connection: TpgConnection;
private
function BuildParamList: AnsiString;
protected
function MakeResultSet(Unidirectional: Boolean): IdaResultSet; override;
procedure PrepareQuery; override;
procedure UnprepareQuery; override;
procedure Execute;
function DoBuildSQLValue(const aHelper: IdaParamListHelper): AnsiString; override;
function Get_Name: AnsiString;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aConnection: TpgConnection;
const aDataConverter: IdaDataConverter;
const aSchemeName: AnsiString;
const aFunctionName: AnsiString;
aParamsDescription: TpgParamDecsriptionList;
CanReturnSet: Boolean); reintroduce;
class function Make(aConnection: TpgConnection;
const aDataConverter: IdaDataConverter;
const aSchemeName: AnsiString;
const aFunctionName: AnsiString;
aParamsDescription: TpgParamDecsriptionList;
CanReturnSet: Boolean): IdaFunction; reintroduce;
end;//TpgFunction
{$IfEnd} // Defined(UsePostgres)
implementation
{$If Defined(UsePostgres)}
uses
l3ImplUses
, daTypes
, SysUtils
, pgResultSet
, pgFunctionSelectField
, pgInterfaces
, LibPQ
, daScheme
, pgUtils
//#UC START# *56616E840213impl_uses*
//#UC END# *56616E840213impl_uses*
;
constructor TpgFunction.Create(aConnection: TpgConnection;
const aDataConverter: IdaDataConverter;
const aSchemeName: AnsiString;
const aFunctionName: AnsiString;
aParamsDescription: TpgParamDecsriptionList;
CanReturnSet: Boolean);
//#UC START# *5673D6990214_56616E840213_var*
var
l_IDX: Integer;
//#UC END# *5673D6990214_56616E840213_var*
begin
//#UC START# *5673D6990214_56616E840213_impl*
inherited Create(aDataConverter);
aConnection.SetRefTo(f_Connection);
f_SchemeName := aSchemeName;
f_FunctionName := aFunctionName;
f_CanReturnSet := CanReturnSet;
f_InParamList := TdaParamList.Make;
f_OutParamList := TdaParamList.Make;
f_SelectFields := TdaSelectFieldList.Make;
for l_IDX := 0 to aParamsDescription.Count - 1 do
begin
AddParam(aParamsDescription[l_IDX]);
if aParamsDescription[l_IDX].ParamType in [da_ptInput, da_ptInOut] then
f_InParamList.Add(Get_Param(aParamsDescription[l_IDX].Name));
if aParamsDescription[l_IDX].ParamType in [da_ptOutput, da_ptInOut] then
begin
f_OutParamList.Add(Get_Param(aParamsDescription[l_IDX].Name));
f_SelectFields.Add(TpgFunctionSelectField.Make(aParamsDescription[l_IDX]));
end;
end;
Prepare;
//#UC END# *5673D6990214_56616E840213_impl*
end;//TpgFunction.Create
function TpgFunction.BuildParamList: AnsiString;
//#UC START# *567BD1FA031C_56616E840213_var*
var
l_IDX: Integer;
//#UC END# *567BD1FA031C_56616E840213_var*
begin
//#UC START# *567BD1FA031C_56616E840213_impl*
Result := '';
for l_IDX := 0 to f_InParamList.Count - 1 do
begin
if l_IDX > 0 then
Result := Result + ', ';
Result := Format('%s$%d', [Result, l_IDX + 1]);
end;
if Result <> '' then
Result := Format('(%s)', [Result]);
//#UC END# *567BD1FA031C_56616E840213_impl*
end;//TpgFunction.BuildParamList
class function TpgFunction.Make(aConnection: TpgConnection;
const aDataConverter: IdaDataConverter;
const aSchemeName: AnsiString;
const aFunctionName: AnsiString;
aParamsDescription: TpgParamDecsriptionList;
CanReturnSet: Boolean): IdaFunction;
var
l_Inst : TpgFunction;
begin
l_Inst := Create(aConnection, aDataConverter, aSchemeName, aFunctionName, aParamsDescription, CanReturnSet);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TpgFunction.Make
function TpgFunction.MakeResultSet(Unidirectional: Boolean): IdaResultSet;
//#UC START# *56010A7801F2_56616E840213_var*
//#UC END# *56010A7801F2_56616E840213_var*
begin
//#UC START# *56010A7801F2_56616E840213_impl*
Result := TpgResultSet.Make(f_Connection, DataConverter as IpgDataConverter, f_QueryName, f_InParamList, f_SelectFields, Unidirectional);
//#UC END# *56010A7801F2_56616E840213_impl*
end;//TpgFunction.MakeResultSet
procedure TpgFunction.PrepareQuery;
//#UC START# *56010AB70258_56616E840213_var*
var
l_Result: PPGResult;
//#UC END# *56010AB70258_56616E840213_var*
begin
//#UC START# *56010AB70258_56616E840213_impl*
f_QueryName := Format('Prc%p', [Pointer(Self)]);
l_Result := PQprepare(f_Connection.Handle, PAnsiChar(f_QueryName), PAnsiChar(BuildSQLValue(f_InParamList)), Params.Count, nil);
try
pgCheckStatus(l_Result);
finally
PQclear(l_Result);
end;
//#UC END# *56010AB70258_56616E840213_impl*
end;//TpgFunction.PrepareQuery
procedure TpgFunction.UnprepareQuery;
//#UC START# *56010ACB00F0_56616E840213_var*
var
l_Result: PPGResult;
//#UC END# *56010ACB00F0_56616E840213_var*
begin
//#UC START# *56010ACB00F0_56616E840213_impl*
l_Result := PQExec(f_Connection.Handle, PAnsiChar(Format('DEALLOCATE "%s"', [f_QueryName])));
try
pgCheckStatus(l_Result);
f_QueryName := '';
finally
PQClear(l_Result);
end;
//#UC END# *56010ACB00F0_56616E840213_impl*
end;//TpgFunction.UnprepareQuery
procedure TpgFunction.Execute;
//#UC START# *5666D0EB0129_56616E840213_var*
var
l_ResultSet: IdaResultSet;
l_IDX: Integer;
//#UC END# *5666D0EB0129_56616E840213_var*
begin
//#UC START# *5666D0EB0129_56616E840213_impl*
l_ResultSet := OpenResultSet;
try
if l_ResultSet.IsEmpty then
Exit;
for l_IDX := 0 to f_OutParamList.Count - 1 do
f_OutParamList[l_IDX].AsString := l_ResultSet.Field[f_OutParamList[l_IDX].Name].AsString;
finally
l_ResultSet := nil;
end;
//#UC END# *5666D0EB0129_56616E840213_impl*
end;//TpgFunction.Execute
function TpgFunction.DoBuildSQLValue(const aHelper: IdaParamListHelper): AnsiString;
//#UC START# *566A850001E5_56616E840213_var*
//#UC END# *566A850001E5_56616E840213_var*
begin
//#UC START# *566A850001E5_56616E840213_impl*
Result := Format('select * from %s.%s%s', [TdaScheme.Instance.CheckScheme(f_SchemeName), f_FunctionName, BuildParamList]);
//#UC END# *566A850001E5_56616E840213_impl*
end;//TpgFunction.DoBuildSQLValue
function TpgFunction.Get_Name: AnsiString;
//#UC START# *57726BB403C3_56616E840213get_var*
//#UC END# *57726BB403C3_56616E840213get_var*
begin
//#UC START# *57726BB403C3_56616E840213get_impl*
Result := f_FunctionName;
//#UC END# *57726BB403C3_56616E840213get_impl*
end;//TpgFunction.Get_Name
procedure TpgFunction.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_56616E840213_var*
//#UC END# *479731C50290_56616E840213_var*
begin
//#UC START# *479731C50290_56616E840213_impl*
Unprepare;
FreeAndNil(f_SelectFields);
FreeAndNil(f_InParamList);
FreeAndNil(f_OutParamList);
FreeAndNil(f_Connection);
inherited;
//#UC END# *479731C50290_56616E840213_impl*
end;//TpgFunction.Cleanup
{$IfEnd} // Defined(UsePostgres)
end.
|
{
* Copyright © 2009 Red Hat, Inc.
* Copyright © 2011 Codethink Limited
* Copyright © 2011,2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Red Hat Author(s): Behdad Esfahbod
* Codethink Author(s): Ryan Lortie
* Google Author(s): Behdad Esfahbod
}
unit libharfbuzz;
{$MODE objfpc}{$H+}
{$PACKRECORDS C}
interface
uses ctypes, dynlibs;
const
cHarfBuzzLibName = 'libharfbuzz.so';
type
hb_bool_t = cint;
hb_codepoint_t = cuint32;
hb_position_t = cint32;
hb_mask_t = cuint32;
Phb_var_int_t = ^hb_var_int_t;
hb_var_int_t = record
case i: integer of
0: (u32: cuint32) ;
1: (i32: cint32);
2: (u16: array [0..1] of cuint16);
3: (i16: array [0..1] of cint16);
4: (u8: array [0..3] of cuint8);
5: (i8: array [0..3] of cint8);
end;
hb_direction_t = (
HB_DIRECTION_INVALID = 0,
HB_DIRECTION_LTR = 4,
HB_DIRECTION_RTL,
HB_DIRECTION_TTB,
HB_DIRECTION_BTT
);
hb_language_t = PChar; // opaque type
hb_tag_t = DWord;
hb_script_t = hb_tag_t; // see hb-common.h for values
//HB_SCRIPT_COMMON = HB_TAG ('Z','y','y','y'),
//#define HB_TAG(c1,c2,c3,c4) ((hb_tag_t)((((uint8_t)(c1))<<24)|(((uint8_t)(c2))<<16)|(((uint8_t)(c3))<<8)|((uint8_t)(c4))))
const
HB_SCRIPT_COMMON = (Ord('Z') shl 24) or (Ord('y') shl 16) or (Ord('y') shl 8) or Ord('y');
HB_TAG_NONE = $00000000;
HB_TAG_MAX = $FFFFFFFF;
HB_TAG_MAX_SIGNED = $7FFFFFFF;
type
Phb_user_data_key_t = ^hb_user_data_key_t;
hb_user_data_key_t = record
// <private>
unused: Pchar;
end;
hb_destroy_func_t = procedure (user_data: pointer); cdecl;
Phb_feature_t = ^hb_feature_t;
hb_feature_t = record
tag: hb_tag_t;
value: cuint32;
start: cuint;
end_: cuint;
end;
Phb_variation_t = ^hb_variation_t;
hb_variation_t = record
tag: hb_tag_t ;
value: cfloat;
end;
hb_memory_mode_t = (
HB_MEMORY_MODE_DUPLICATE = 0,
HB_MEMORY_MODE_READONLY = 1,
HB_MEMORY_MODE_WRITABLE = 2,
HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE = 3
);
Phb_blob_t = ^hb_blob_t;
hb_blob_t = record end; //opaque type
hb_unicode_general_category_t = (HB_UNICODE_GENERAL_CATEGORY_CONTROL,
HB_UNICODE_GENERAL_CATEGORY_FORMAT,HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED,
HB_UNICODE_GENERAL_CATEGORY_PRIVATE_USE,
HB_UNICODE_GENERAL_CATEGORY_SURROGATE,
HB_UNICODE_GENERAL_CATEGORY_LOWERCASE_LETTER,
HB_UNICODE_GENERAL_CATEGORY_MODIFIER_LETTER,
HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER,
HB_UNICODE_GENERAL_CATEGORY_TITLECASE_LETTER,
HB_UNICODE_GENERAL_CATEGORY_UPPERCASE_LETTER,
HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK,
HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK,
HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK,
HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER,
HB_UNICODE_GENERAL_CATEGORY_LETTER_NUMBER,
HB_UNICODE_GENERAL_CATEGORY_OTHER_NUMBER,
HB_UNICODE_GENERAL_CATEGORY_CONNECT_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_DASH_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_CLOSE_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_FINAL_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_INITIAL_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_OTHER_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_OPEN_PUNCTUATION,
HB_UNICODE_GENERAL_CATEGORY_CURRENCY_SYMBOL,
HB_UNICODE_GENERAL_CATEGORY_MODIFIER_SYMBOL,
HB_UNICODE_GENERAL_CATEGORY_MATH_SYMBOL,
HB_UNICODE_GENERAL_CATEGORY_OTHER_SYMBOL,
HB_UNICODE_GENERAL_CATEGORY_LINE_SEPARATOR,
HB_UNICODE_GENERAL_CATEGORY_PARAGRAPH_SEPARATOR,
HB_UNICODE_GENERAL_CATEGORY_SPACE_SEPARATOR
);
hb_unicode_combining_class_t = (HB_UNICODE_COMBINING_CLASS_NOT_REORDERED := 0,
HB_UNICODE_COMBINING_CLASS_OVERLAY := 1,
HB_UNICODE_COMBINING_CLASS_NUKTA := 7,
HB_UNICODE_COMBINING_CLASS_KANA_VOICING := 8,
HB_UNICODE_COMBINING_CLASS_VIRAMA := 9,
HB_UNICODE_COMBINING_CLASS_CCC10 := 10,
HB_UNICODE_COMBINING_CLASS_CCC11 := 11,
HB_UNICODE_COMBINING_CLASS_CCC12 := 12,
HB_UNICODE_COMBINING_CLASS_CCC13 := 13,
HB_UNICODE_COMBINING_CLASS_CCC14 := 14,
HB_UNICODE_COMBINING_CLASS_CCC15 := 15,
HB_UNICODE_COMBINING_CLASS_CCC16 := 16,
HB_UNICODE_COMBINING_CLASS_CCC17 := 17,
HB_UNICODE_COMBINING_CLASS_CCC18 := 18,
HB_UNICODE_COMBINING_CLASS_CCC19 := 19,
HB_UNICODE_COMBINING_CLASS_CCC20 := 20,
HB_UNICODE_COMBINING_CLASS_CCC21 := 21,
HB_UNICODE_COMBINING_CLASS_CCC22 := 22,
HB_UNICODE_COMBINING_CLASS_CCC23 := 23,
HB_UNICODE_COMBINING_CLASS_CCC24 := 24,
HB_UNICODE_COMBINING_CLASS_CCC25 := 25,
HB_UNICODE_COMBINING_CLASS_CCC26 := 26,
HB_UNICODE_COMBINING_CLASS_CCC27 := 27,
HB_UNICODE_COMBINING_CLASS_CCC28 := 28,
HB_UNICODE_COMBINING_CLASS_CCC29 := 29,
HB_UNICODE_COMBINING_CLASS_CCC30 := 30,
HB_UNICODE_COMBINING_CLASS_CCC31 := 31,
HB_UNICODE_COMBINING_CLASS_CCC32 := 32,
HB_UNICODE_COMBINING_CLASS_CCC33 := 33,
HB_UNICODE_COMBINING_CLASS_CCC34 := 34,
HB_UNICODE_COMBINING_CLASS_CCC35 := 35,
HB_UNICODE_COMBINING_CLASS_CCC36 := 36,
HB_UNICODE_COMBINING_CLASS_CCC84 := 84,
HB_UNICODE_COMBINING_CLASS_CCC91 := 91,
HB_UNICODE_COMBINING_CLASS_CCC103 := 103,
HB_UNICODE_COMBINING_CLASS_CCC107 := 107,
HB_UNICODE_COMBINING_CLASS_CCC118 := 118,
HB_UNICODE_COMBINING_CLASS_CCC122 := 122,
HB_UNICODE_COMBINING_CLASS_CCC129 := 129,
HB_UNICODE_COMBINING_CLASS_CCC130 := 130,
HB_UNICODE_COMBINING_CLASS_CCC133 := 132,
HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT := 200,
HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW := 202,
HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE := 214,
HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT := 216,
HB_UNICODE_COMBINING_CLASS_BELOW_LEFT := 218,
HB_UNICODE_COMBINING_CLASS_BELOW := 220,
HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT := 222,
HB_UNICODE_COMBINING_CLASS_LEFT := 224,
HB_UNICODE_COMBINING_CLASS_RIGHT := 226,
HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT := 228,
HB_UNICODE_COMBINING_CLASS_ABOVE := 230,
HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT := 232,
HB_UNICODE_COMBINING_CLASS_DOUBLE_BELOW := 233,
HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE := 234,
HB_UNICODE_COMBINING_CLASS_IOTA_SUBSCRIPT := 240,
HB_UNICODE_COMBINING_CLASS_INVALID := 255
);
Phb_unicode_funcs_t = ^hb_unicode_funcs_t;
hb_unicode_funcs_t = record end;
Phb_codepoint_t = ^hb_codepoint_t;
hb_unicode_combining_class_func_t = function (ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t; user_data:pointer):hb_unicode_combining_class_t;cdecl;
hb_unicode_eastasian_width_func_t = function (ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t; user_data:pointer):cuint;cdecl;
hb_unicode_general_category_func_t = function (ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t; user_data:pointer):hb_unicode_general_category_t;cdecl;
hb_unicode_mirroring_func_t = function (ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t; user_data:pointer):hb_codepoint_t;cdecl;
hb_unicode_script_func_t = function (ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t; user_data:pointer):hb_script_t;cdecl;
hb_unicode_compose_func_t = function (ufuncs:Phb_unicode_funcs_t; a:hb_codepoint_t; b:hb_codepoint_t; ab:Phb_codepoint_t; user_data:pointer):hb_bool_t;cdecl;
hb_unicode_decompose_func_t = function (ufuncs:Phb_unicode_funcs_t; ab:hb_codepoint_t; a:Phb_codepoint_t; b:Phb_codepoint_t; user_data:pointer):hb_bool_t;cdecl;
hb_unicode_decompose_compatibility_func_t = function (ufuncs:Phb_unicode_funcs_t; u:hb_codepoint_t; decomposed:Phb_codepoint_t; user_data:pointer):cuint;cdecl;
const
HB_UNICODE_MAX_DECOMPOSITION_LEN = 18+1;
type
Phb_buffer_t = ^hb_buffer_t;
hb_buffer_t = record end;
Phb_font_t = ^hb_font_t;
Phb_glyph_info_t = ^hb_glyph_info_t;
hb_glyph_info_t = record
codepoint : hb_codepoint_t;
mask : hb_mask_t;
cluster : cuint32;
var1 : hb_var_int_t;
var2 : hb_var_int_t;
end;
Phb_glyph_position_t = ^hb_glyph_position_t;
hb_glyph_position_t = record
x_advance : hb_position_t;
y_advance : hb_position_t;
x_offset : hb_position_t;
y_offset : hb_position_t;
var_ : hb_var_int_t;
end;
Phb_segment_properties_t = ^hb_segment_properties_t;
hb_segment_properties_t = record
direction : hb_direction_t;
script : hb_script_t;
language : hb_language_t;
reserved1 : pointer;
reserved2 : pointer;
end;
hb_font_t = pointer;
hb_buffer_content_type_t = (
HB_BUFFER_CONTENT_TYPE_INVALID := 0,
HB_BUFFER_CONTENT_TYPE_UNICODE,
HB_BUFFER_CONTENT_TYPE_GLYPHS
);
hb_buffer_flags_t = (
HB_BUFFER_FLAG_DEFAULT := $00000000,
HB_BUFFER_FLAG_BOT := $00000001,
HB_BUFFER_FLAG_EOT := $00000002,
HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES := $00000004
);
hb_buffer_cluster_level_t = (
HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES := 0,
HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS := 1,
HB_BUFFER_CLUSTER_LEVEL_CHARACTERS := 2
//HB_BUFFER_CLUSTER_LEVEL_DEFAULT = HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES;
);
const
HB_BUFFER_CLUSTER_LEVEL_DEFAULT = HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES;
HB_BUFFER_REPLACEMENT_CODEPOINT_DEFAULT = $FFFD;
type
hb_buffer_serialize_flags_t = (HB_BUFFER_SERIALIZE_FLAG_DEFAULT := $00000000,
HB_BUFFER_SERIALIZE_FLAG_NO_CLUSTERS := $00000001,
HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS := $00000002,
HB_BUFFER_SERIALIZE_FLAG_NO_GLYPH_NAMES := $00000004,
HB_BUFFER_SERIALIZE_FLAG_GLYPH_EXTENTS := $00000008
);
hb_buffer_serialize_format_t = (
HB_BUFFER_SERIALIZE_FORMAT_INVALID = HB_TAG_NONE,
HB_BUFFER_SERIALIZE_FORMAT_JSON = $4A534F4E, // (Ord('J') shl 24) or (Ord('S') shl 16) or (Ord('O') shl 8) or Ord('N'); // HB_TAG('J','S','O','N'),
HB_BUFFER_SERIALIZE_FORMAT_TEXT = $54455854 //(Ord('T') shl 24) or (Ord('E') shl 16) or (Ord('X') shl 8) or Ord('T')); // HB_TAG('T','E','X','T'),
);
hb_buffer_message_func_t = function (buffer:Phb_buffer_t; font:Phb_font_t; message:pchar; user_data:pointer):hb_bool_t;cdecl;
Phb_face_t = ^hb_face_t;
hb_face_t = record end;
hb_reference_table_func_t = function (face:Phb_face_t; tag:hb_tag_t; user_data:pointer):Phb_blob_t;cdecl;
Phb_position_t = ^hb_position_t;
Phb_font_funcs_t = ^hb_font_funcs_t;
hb_font_funcs_t = record end;
Phb_font_extents_t = ^hb_font_extents_t;
hb_font_extents_t = record
ascender : hb_position_t;
descender : hb_position_t;
line_gap : hb_position_t;
reserved9 : hb_position_t;
reserved8 : hb_position_t;
reserved7 : hb_position_t;
reserved6 : hb_position_t;
reserved5 : hb_position_t;
reserved4 : hb_position_t;
reserved3 : hb_position_t;
reserved2 : hb_position_t;
reserved1 : hb_position_t;
end;
Phb_glyph_extents_t = ^hb_glyph_extents_t;
hb_glyph_extents_t = record
x_bearing: hb_position_t; //* left side of glyph from origin. */
y_bearing: hb_position_t; //* top side of glyph from origin. */
width: hb_position_t ; //* distance from left to right side. */
height: hb_position_t; //* distance from top to bottom side. */
end;
hb_font_get_font_extents_func_t = function (font:Phb_font_t; font_data:pointer; metrics:Phb_font_extents_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_font_h_extents_func_t = hb_font_get_font_extents_func_t;
hb_font_get_font_v_extents_func_t = hb_font_get_font_extents_func_t;
hb_font_get_nominal_glyph_func_t = function (font:Phb_font_t; font_data:pointer; unicode:hb_codepoint_t; glyph:Phb_codepoint_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_variation_glyph_func_t = function (font:Phb_font_t; font_data:pointer; unicode:hb_codepoint_t; variation_selector:hb_codepoint_t; glyph:Phb_codepoint_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_glyph_advance_func_t = function (font:Phb_font_t; font_data:pointer; glyph:hb_codepoint_t; user_data:pointer):hb_position_t;cdecl;
hb_font_get_glyph_h_advance_func_t = hb_font_get_glyph_advance_func_t;
hb_font_get_glyph_v_advance_func_t = hb_font_get_glyph_advance_func_t;
hb_font_get_glyph_origin_func_t = function (font:Phb_font_t; font_data:pointer; glyph:hb_codepoint_t; x:Phb_position_t; y:Phb_position_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_glyph_h_origin_func_t = hb_font_get_glyph_origin_func_t;
hb_font_get_glyph_v_origin_func_t = hb_font_get_glyph_origin_func_t;
hb_font_get_glyph_kerning_func_t = function (font:Phb_font_t; font_data:pointer; first_glyph:hb_codepoint_t; second_glyph:hb_codepoint_t; user_data:pointer):hb_position_t;cdecl;
hb_font_get_glyph_h_kerning_func_t = hb_font_get_glyph_kerning_func_t;
hb_font_get_glyph_v_kerning_func_t = hb_font_get_glyph_kerning_func_t;
hb_font_get_glyph_extents_func_t = function (font:Phb_font_t; font_data:pointer; glyph:hb_codepoint_t; extents:Phb_glyph_extents_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_glyph_contour_point_func_t = function (font:Phb_font_t; font_data:pointer; glyph:hb_codepoint_t; point_index:cuint; x:Phb_position_t; y:Phb_position_t; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_glyph_name_func_t = function (font:Phb_font_t; font_data:pointer; glyph:hb_codepoint_t; name:pchar; size:cuint; user_data:pointer):hb_bool_t;cdecl;
hb_font_get_glyph_from_name_func_t = function (font:Phb_font_t; font_data:pointer; name:pchar; len:cint; glyph:Phb_codepoint_t; user_data:pointer):hb_bool_t;cdecl;
Phb_shape_plan_t = ^hb_shape_plan_t;
hb_shape_plan_t = record end;
const
HB_VERSION_MAJOR = 1;
HB_VERSION_MINOR = 4;
HB_VERSION_MICRO = 2;
HB_VERSION_STR = '1.4.2';
var
// hh-common
hb_tag_from_string : function (str: PChar; len: cint): hb_tag_t; cdecl;
hb_tag_to_string : procedure(tag: hb_tag_t; buf :pchar); cdecl;
hb_direction_from_string: function (str: pchar; len: cint): hb_direction_t; cdecl;
hb_direction_to_string: function(direction: hb_direction_t): pchar; cdecl;
hb_language_from_string: function (str: pchar; len: cint): hb_language_t; cdecl;
hb_language_to_string: function (language: hb_language_t): pchar; cdecl;
hb_language_get_default: function: hb_language_t;
hb_script_from_iso15924_tag: function (tag: hb_tag_t): hb_script_t; cdecl;
hb_script_from_string: function (str: pchar; len: cint): hb_script_t; cdecl;
hb_script_to_iso15924_tag: function (script: hb_script_t): hb_tag_t; cdecl;
hb_script_get_horizontal_direction: function(script: hb_script_t): hb_direction_t; cdecl;
hb_feature_from_string: function(str: pchar; len: cint; feature: Phb_feature_t): hb_bool_t; cdecl;
hb_feature_to_string: procedure(feature: Phb_feature_t; buf: pchar; size: cuint); cdecl;
hb_variation_from_string: function (tr: pchar; len: cint; variation: Phb_variation_t): hb_bool_t; cdecl;
hb_variation_to_string: procedure(variation: Phb_variation_t; buf: pchar; size: cuint); cdecl;
// hh-blob
hb_blob_create:function (data: pchar; length: cuint; mode: hb_memory_mode_t; user_data: pointer; destroy: hb_destroy_func_t): Phb_blob_t; cdecl;
hb_blob_create_sub_blob: function (parent: Phb_blob_t; offset: cuint; length: cuint): Phb_blob_t; cdecl;
hb_blob_get_empty: function: Phb_blob_t; cdecl;
hb_blob_reference: function(blob: Phb_blob_t): Phb_blob_t; cdecl;
hb_blob_destroy: procedure (blob: hb_blob_t) cdecl;
hb_blob_set_user_data: function (blob: Phb_blob_t; key: Phb_user_data_key_t; data: pointer; destroy: hb_destroy_func_t; replace: hb_bool_t): hb_bool_t; cdecl;
hb_blob_get_user_data: function(blob: Phb_blob_t; key: Phb_user_data_key_t): pointer; cdecl;
hb_blob_make_immutable: procedure (blob: Phb_blob_t); cdecl;
hb_blob_is_immutable: function(blob: Phb_blob_t): hb_bool_t; cdecl;
hb_blob_get_length: function(blob: Phb_blob_t): cuint; cdecl;
hb_blob_get_data: function(blob: Phb_blob_t; length: pcuint): pchar; cdecl;
hb_blob_get_data_writable: function (blob: Phb_blob_t; length: pcuint): pchar; cdecl;
// hh-unicode
hb_unicode_funcs_get_default : function:Phb_unicode_funcs_t;cdecl;
hb_unicode_funcs_create : function(parent:Phb_unicode_funcs_t):Phb_unicode_funcs_t;cdecl;
hb_unicode_funcs_get_empty : function:Phb_unicode_funcs_t;cdecl;
hb_unicode_funcs_reference : function(ufuncs:Phb_unicode_funcs_t):Phb_unicode_funcs_t;cdecl;
hb_unicode_funcs_destroy : procedure(ufuncs:Phb_unicode_funcs_t);cdecl;
hb_unicode_funcs_set_user_data : function(ufuncs:Phb_unicode_funcs_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_unicode_funcs_get_user_data : function(ufuncs:Phb_unicode_funcs_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_unicode_funcs_make_immutable : procedure(ufuncs:Phb_unicode_funcs_t);cdecl;
hb_unicode_funcs_is_immutable : function(ufuncs:Phb_unicode_funcs_t):hb_bool_t;cdecl;
hb_unicode_funcs_get_parent : function(ufuncs:Phb_unicode_funcs_t):Phb_unicode_funcs_t;cdecl;
hb_unicode_funcs_set_combining_class_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_combining_class_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_eastasian_width_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_eastasian_width_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_general_category_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_general_category_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_mirroring_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_mirroring_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_script_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_script_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_compose_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_compose_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_decompose_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_decompose_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_funcs_set_decompose_compatibility_func : procedure(ufuncs:Phb_unicode_funcs_t; func:hb_unicode_decompose_compatibility_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_unicode_combining_class : function(ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t):hb_unicode_combining_class_t;cdecl;
hb_unicode_eastasian_width : function(ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t):cuint;cdecl;
hb_unicode_general_category : function(ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t):hb_unicode_general_category_t;cdecl;
hb_unicode_mirroring : function(ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t):hb_codepoint_t;cdecl;
hb_unicode_script : function(ufuncs:Phb_unicode_funcs_t; unicode:hb_codepoint_t):hb_script_t;cdecl;
hb_unicode_compose : function(ufuncs:Phb_unicode_funcs_t; a:hb_codepoint_t; b:hb_codepoint_t; ab:Phb_codepoint_t):hb_bool_t;cdecl;
hb_unicode_decompose : function(ufuncs:Phb_unicode_funcs_t; ab:hb_codepoint_t; a:Phb_codepoint_t; b:Phb_codepoint_t):hb_bool_t;cdecl;
hb_unicode_decompose_compatibility : function(ufuncs:Phb_unicode_funcs_t; u:hb_codepoint_t; decomposed:Phb_codepoint_t):cuint;cdecl;
//buffer
hb_segment_properties_equal: function(a:Phb_segment_properties_t; b:Phb_segment_properties_t):hb_bool_t;cdecl;
hb_segment_properties_hash: function(p:Phb_segment_properties_t):cuint;cdecl;
hb_buffer_create : function:Phb_buffer_t;cdecl;
hb_buffer_get_empty : function:Phb_buffer_t;cdecl;
hb_buffer_reference : function(buffer:Phb_buffer_t):Phb_buffer_t;cdecl;
hb_buffer_destroy : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_set_user_data : function(buffer:Phb_buffer_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_buffer_get_user_data : function(buffer:Phb_buffer_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_buffer_set_content_type : procedure(buffer:Phb_buffer_t; content_type:hb_buffer_content_type_t);cdecl;
hb_buffer_get_content_type : function(buffer:Phb_buffer_t):hb_buffer_content_type_t;cdecl;
hb_buffer_set_unicode_funcs : procedure(buffer:Phb_buffer_t; unicode_funcs:Phb_unicode_funcs_t);cdecl;
hb_buffer_get_unicode_funcs : function(buffer:Phb_buffer_t):Phb_unicode_funcs_t;cdecl;
hb_buffer_set_direction : procedure(buffer:Phb_buffer_t; direction:hb_direction_t);cdecl;
hb_buffer_get_direction : function(buffer:Phb_buffer_t):hb_direction_t;cdecl;
hb_buffer_set_script : procedure(buffer:Phb_buffer_t; script:hb_script_t);cdecl;
hb_buffer_get_script : function(buffer:Phb_buffer_t):hb_script_t;cdecl;
hb_buffer_set_language : procedure(buffer:Phb_buffer_t; language:hb_language_t);cdecl;
hb_buffer_get_language : function(buffer:Phb_buffer_t):hb_language_t;cdecl;
hb_buffer_set_segment_properties : procedure(buffer:Phb_buffer_t; props:Phb_segment_properties_t);cdecl;
hb_buffer_get_segment_properties : procedure(buffer:Phb_buffer_t; props:Phb_segment_properties_t);cdecl;
hb_buffer_guess_segment_properties : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_set_flags : procedure(buffer:Phb_buffer_t; flags:hb_buffer_flags_t);cdecl;
hb_buffer_get_flags : function(buffer:Phb_buffer_t):hb_buffer_flags_t;cdecl;
hb_buffer_set_cluster_level : procedure(buffer:Phb_buffer_t; cluster_level:hb_buffer_cluster_level_t);cdecl;
hb_buffer_get_cluster_level : function(buffer:Phb_buffer_t):hb_buffer_cluster_level_t;cdecl;
hb_buffer_set_replacement_codepoint : procedure(buffer:Phb_buffer_t; replacement:hb_codepoint_t);cdecl;
hb_buffer_get_replacement_codepoint : function(buffer:Phb_buffer_t):hb_codepoint_t;cdecl;
hb_buffer_reset : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_clear_contents : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_pre_allocate : function(buffer:Phb_buffer_t; size:cuint):hb_bool_t;cdecl;
hb_buffer_allocation_successful : function(buffer:Phb_buffer_t):hb_bool_t;cdecl;
hb_buffer_reverse : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_reverse_range : procedure(buffer:Phb_buffer_t; start:cuint; end_:cuint);cdecl;
hb_buffer_reverse_clusters : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_add : procedure(buffer:Phb_buffer_t; codepoint:hb_codepoint_t; cluster:cuint);cdecl;
hb_buffer_add_utf8 : procedure(buffer:Phb_buffer_t; text:pchar; text_length:cint; item_offset:cuint; item_length:cint);cdecl;
hb_buffer_add_utf16 : procedure(buffer:Phb_buffer_t; text:pcuint16; text_length:cint; item_offset:cuint; item_length:cint);cdecl;
hb_buffer_add_utf32 : procedure(buffer:Phb_buffer_t; text:pcuint32; text_length:cint; item_offset:cuint; item_length:cint);cdecl;
hb_buffer_add_latin1 : procedure(buffer:Phb_buffer_t; text:PChar; text_length:cint; item_offset:cuint; item_length:cint);cdecl;
hb_buffer_add_codepoints : procedure(buffer:Phb_buffer_t; text:Phb_codepoint_t; text_length:cint; item_offset:cuint; item_length:cint);cdecl;
hb_buffer_set_length : function(buffer:Phb_buffer_t; length:cuint):hb_bool_t;cdecl;
hb_buffer_get_length : function(buffer:Phb_buffer_t):cuint;cdecl;
hb_buffer_get_glyph_infos : function(buffer:Phb_buffer_t; length:pcuint):Phb_glyph_info_t;cdecl;
hb_buffer_get_glyph_positions : function(buffer:Phb_buffer_t; length:pcuint):Phb_glyph_position_t;cdecl;
hb_buffer_normalize_glyphs : procedure(buffer:Phb_buffer_t);cdecl;
hb_buffer_serialize_format_from_string : function(str:pchar; len:cint):hb_buffer_serialize_format_t;cdecl;
hb_buffer_serialize_format_to_string : function(format:hb_buffer_serialize_format_t):pchar;cdecl;
hb_buffer_serialize_list_formats : function:ppchar;cdecl;
hb_buffer_serialize_glyphs : function(buffer:Phb_buffer_t; start:cuint; end_:cuint; buf:pchar; buf_size:cuint; buf_consumed:pcuint; font:Phb_font_t; format:hb_buffer_serialize_format_t; flags:hb_buffer_serialize_flags_t):cuint;cdecl;
hb_buffer_deserialize_glyphs : function(buffer:Phb_buffer_t; buf:pchar; buf_len:cint; end_ptr:Ppchar; font:Phb_font_t; format:hb_buffer_serialize_format_t):hb_bool_t;cdecl;
hb_buffer_set_message_func : procedure(buffer:Phb_buffer_t; func:hb_buffer_message_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
// hb-face
hb_face_create : function(blob:Phb_blob_t; index:cuint):Phb_face_t;cdecl;
hb_face_create_for_tables : function(reference_table_func:hb_reference_table_func_t; user_data:pointer; destroy:hb_destroy_func_t):Phb_face_t;cdecl;
hb_face_get_empty : function:Phb_face_t;cdecl;
hb_face_reference : function(face:Phb_face_t):hb_face_t;cdecl;
hb_face_destroy : procedure(face:Phb_face_t);cdecl;
hb_face_set_user_data : function(face:Phb_face_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_face_get_user_data : function(face:Phb_face_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_face_make_immutable : procedure(face:Phb_face_t);cdecl;
hb_face_is_immutable : function(face:Phb_face_t):hb_bool_t;cdecl;
hb_face_reference_table : function(face:Phb_face_t; tag:hb_tag_t):Phb_blob_t;cdecl;
hb_face_reference_blob : function(face:Phb_face_t):Phb_blob_t;cdecl;
hb_face_set_index : procedure(face:Phb_face_t; index:cuint);cdecl;
hb_face_get_index : function(face:Phb_face_t):cuint;cdecl;
hb_face_set_upem : procedure(face:Phb_face_t; upem:cuint);cdecl;
hb_face_get_upem : function(face:Phb_face_t):cuint;cdecl;
hb_face_set_glyph_count : procedure(face:Phb_face_t; glyph_count:cuint);cdecl;
hb_face_get_glyph_count : function(face:Phb_face_t):cuint;cdecl;
// hb-font
hb_font_funcs_create : function:Phb_font_funcs_t;cdecl;
hb_font_funcs_get_empty : function:Phb_font_funcs_t;cdecl;
hb_font_funcs_reference : function(ffuncs:Phb_font_funcs_t):Phb_font_funcs_t;cdecl;
hb_font_funcs_destroy : procedure(ffuncs:Phb_font_funcs_t);cdecl;
hb_font_funcs_set_user_data : function(ffuncs:Phb_font_funcs_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_font_funcs_get_user_data : function(ffuncs:Phb_font_funcs_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_font_funcs_make_immutable : procedure(ffuncs:Phb_font_funcs_t);cdecl;
hb_font_funcs_is_immutable : function(ffuncs:Phb_font_funcs_t):hb_bool_t;cdecl;
hb_font_funcs_set_font_h_extents_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_font_h_extents_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_font_v_extents_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_font_v_extents_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_nominal_glyph_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_nominal_glyph_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_variation_glyph_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_variation_glyph_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_h_advance_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_h_advance_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_v_advance_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_v_advance_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_h_origin_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_h_origin_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_v_origin_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_v_origin_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_h_kerning_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_h_kerning_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_v_kerning_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_v_kerning_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_extents_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_extents_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_contour_point_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_contour_point_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_name_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_name_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_funcs_set_glyph_from_name_func : procedure(ffuncs:Phb_font_funcs_t; func:hb_font_get_glyph_from_name_func_t; user_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_get_h_extents : function(font:Phb_font_t; extents:Phb_font_extents_t):hb_bool_t;cdecl;
hb_font_get_v_extents : function(font:Phb_font_t; extents:Phb_font_extents_t):hb_bool_t;cdecl;
hb_font_get_nominal_glyph : function(font:Phb_font_t; unicode:hb_codepoint_t; glyph:Phb_codepoint_t):hb_bool_t;cdecl;
hb_font_get_variation_glyph : function(font:Phb_font_t; unicode:hb_codepoint_t; variation_selector:hb_codepoint_t; glyph:Phb_codepoint_t):hb_bool_t;cdecl;
hb_font_get_glyph_h_advance : function(font:Phb_font_t; glyph:hb_codepoint_t):hb_position_t;cdecl;
hb_font_get_glyph_v_advance : function(font:Phb_font_t; glyph:hb_codepoint_t):hb_position_t;cdecl;
hb_font_get_glyph_h_origin : function(font:Phb_font_t; glyph:hb_codepoint_t; x:Phb_position_t; y:Phb_position_t):hb_bool_t;cdecl;
hb_font_get_glyph_v_origin : function(font:Phb_font_t; glyph:hb_codepoint_t; x:Phb_position_t; y:Phb_position_t):hb_bool_t;cdecl;
hb_font_get_glyph_h_kerning : function(font:Phb_font_t; left_glyph:hb_codepoint_t; right_glyph:hb_codepoint_t):hb_position_t;cdecl;
hb_font_get_glyph_v_kerning : function(font:Phb_font_t; top_glyph:hb_codepoint_t; bottom_glyph:hb_codepoint_t):hb_position_t;cdecl;
hb_font_get_glyph_extents : function(font:Phb_font_t; glyph:hb_codepoint_t; extents:Phb_glyph_extents_t):hb_bool_t;cdecl;
hb_font_get_glyph_contour_point : function(font:Phb_font_t; glyph:hb_codepoint_t; point_index:cuint; x:Phb_position_t; y:Phb_position_t):hb_bool_t;cdecl;
hb_font_get_glyph_name : function(font:Phb_font_t; glyph:hb_codepoint_t; name:pchar; size:cuint):hb_bool_t;cdecl;
{ -1 means nul-terminated }
hb_font_get_glyph_from_name : function(font:Phb_font_t; name:pchar; len:cint; glyph:Phb_codepoint_t):hb_bool_t;cdecl;
hb_font_get_glyph : function(font:Phb_font_t; unicode:hb_codepoint_t; variation_selector:hb_codepoint_t; glyph:Phb_codepoint_t):hb_bool_t;cdecl;
hb_font_get_extents_for_direction : procedure(font:Phb_font_t; direction:hb_direction_t; extents:Phb_font_extents_t);cdecl;
hb_font_get_glyph_advance_for_direction : procedure(font:Phb_font_t; glyph:hb_codepoint_t; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t);cdecl;
hb_font_get_glyph_origin_for_direction : procedure(font:Phb_font_t; glyph:hb_codepoint_t; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t);cdecl;
hb_font_add_glyph_origin_for_direction : procedure(font:Phb_font_t; glyph:hb_codepoint_t; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t);cdecl;
hb_font_subtract_glyph_origin_for_direction : procedure(font:Phb_font_t; glyph:hb_codepoint_t; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t);cdecl;
hb_font_get_glyph_kerning_for_direction : procedure(font:Phb_font_t; first_glyph:hb_codepoint_t; second_glyph:hb_codepoint_t; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t);cdecl;
hb_font_get_glyph_extents_for_origin : function(font:Phb_font_t; glyph:hb_codepoint_t; direction:hb_direction_t; extents:Phb_glyph_extents_t):hb_bool_t;cdecl;
hb_font_get_glyph_contour_point_for_origin : function(font:Phb_font_t; glyph:hb_codepoint_t; point_index:cuint; direction:hb_direction_t; x:Phb_position_t; y:Phb_position_t):hb_bool_t;cdecl;
{ Generates gidDDD if glyph has no name. }
hb_font_glyph_to_string : procedure(font:Phb_font_t; glyph:hb_codepoint_t; s:pchar; size:cuint);cdecl;
{ Parses gidDDD and uniUUUU strings automatically. }
{ -1 means nul-terminated }
hb_font_glyph_from_string : function(font:Phb_font_t; s:pchar; len:cint; glyph:Phb_codepoint_t):hb_bool_t;cdecl;
{ Fonts are very light-weight objects }
hb_font_create : function(face:Phb_face_t):Phb_font_t;cdecl;
hb_font_create_sub_font : function(parent:Phb_font_t):Phb_font_t;cdecl;
hb_font_get_empty : function:Phb_font_t;cdecl;
hb_font_reference : function(font:Phb_font_t):Phb_font_t;cdecl;
hb_font_destroy : procedure(font:Phb_font_t);cdecl;
hb_font_set_user_data : function(font:Phb_font_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_font_get_user_data : function(font:Phb_font_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_font_make_immutable : procedure(font:Phb_font_t);cdecl;
hb_font_is_immutable : function(font:Phb_font_t):hb_bool_t;cdecl;
hb_font_set_parent : procedure(font:Phb_font_t; parent:Phb_font_t);cdecl;
hb_font_get_parent : function(font:Phb_font_t):Phb_font_t;cdecl;
hb_font_get_face : function(font:Phb_font_t):Phb_face_t;cdecl;
hb_font_set_funcs : procedure(font:Phb_font_t; klass:Phb_font_funcs_t; font_data:pointer; destroy:hb_destroy_func_t);cdecl;
{ Be *very* careful with this function! }
hb_font_set_funcs_data : procedure(font:Phb_font_t; font_data:pointer; destroy:hb_destroy_func_t);cdecl;
hb_font_set_scale : procedure(font:Phb_font_t; x_scale:cint; y_scale:cint);cdecl;
hb_font_get_scale : procedure(font:Phb_font_t; x_scale:pcint; y_scale:pcint);cdecl;
{ * A zero value means "no hinting in that direction" }
hb_font_set_ppem : procedure(font:Phb_font_t; x_ppem:cuint; y_ppem:cuint);cdecl;
hb_font_get_ppem : procedure(font:Phb_font_t; x_ppem:pcuint; y_ppem:pcuint);cdecl;
hb_font_set_variations : procedure(font:Phb_font_t; variations:Phb_variation_t; variations_length:cuint);cdecl;
hb_font_set_var_coords_design : procedure(font:Phb_font_t; coords:Pcfloat; coords_length:cuint);cdecl;
{ 2.14 normalized }
hb_font_set_var_coords_normalized : procedure(font:Phb_font_t; coords:pcint; coords_length:cuint);cdecl;
hb_font_get_var_coords_normalized : function(font:Phb_font_t; length:pcuint):pcint;cdecl;
// hb-shape
hb_shape : procedure(font:Phb_font_t; buffer:Phb_buffer_t; features:Phb_feature_t; num_features:cuint);cdecl;
hb_shape_full : function(font:Phb_font_t; buffer:Phb_buffer_t; features:Phb_feature_t; num_features:cuint; shaper_list:Pchar):hb_bool_t;cdecl;
hb_shape_list_shapers : function:ppchar;cdecl;
// hb-shape-plan
hb_shape_plan_create : function(face:Phb_face_t; props:Phb_segment_properties_t; user_features:Phb_feature_t; num_user_features:cuint; shaper_list:Ppchar):Phb_shape_plan_t;cdecl;
hb_shape_plan_create_cached : function(face:Phb_face_t; props:Phb_segment_properties_t; user_features:Phb_feature_t; num_user_features:cuint; shaper_list:Ppchar):Phb_shape_plan_t;cdecl;
hb_shape_plan_create2 : function(face:Phb_face_t; props:Phb_segment_properties_t; user_features:Phb_feature_t; num_user_features:cuint; coords:pcint;
num_coords:cuint; shaper_list:Ppchar):Phb_shape_plan_t;cdecl;
hb_shape_plan_create_cached2 : function(face:Phb_face_t; props:Phb_segment_properties_t; user_features:Phb_feature_t; num_user_features:cuint; coords:pcint;
num_coords:cuint; shaper_list:Ppchar):Phb_shape_plan_t;cdecl;
hb_shape_plan_get_empty : function:Phb_shape_plan_t;cdecl;
hb_shape_plan_reference : function(shape_plan:Phb_shape_plan_t):Phb_shape_plan_t;cdecl;
hb_shape_plan_destroy : procedure(shape_plan:Phb_shape_plan_t);cdecl;
hb_shape_plan_set_user_data : function(shape_plan:Phb_shape_plan_t; key:Phb_user_data_key_t; data:pointer; destroy:hb_destroy_func_t; replace:hb_bool_t):hb_bool_t;cdecl;
hb_shape_plan_get_user_data : function(shape_plan:Phb_shape_plan_t; key:Phb_user_data_key_t):pointer;cdecl;
hb_shape_plan_execute : function(shape_plan:Phb_shape_plan_t; font:Phb_font_t; buffer:Phb_buffer_t; features:Phb_feature_t; num_features:cuint):hb_bool_t;cdecl;
hb_shape_plan_get_shaper : function(shape_plan:Phb_shape_plan_t):pchar;cdecl;
// hb-version
hb_version : procedure(major:pcuint; minor:pcuint; micro:pcuint);cdecl;
hb_version_string : function:pchar;cdecl;
hb_version_atleast : function(major:cuint; minor:cuint; micro:cuint):hb_bool_t;cdecl;
hb_version_check : function(major:cuint; minor:cuint; micro:cuint):hb_bool_t;
// hb-ft (freetype)
hb_ft_face_create : function(ft_face:pointer; destroy:hb_destroy_func_t):Phb_face_t;cdecl;
hb_ft_face_create_cached : function(ft_face:pointer):Phb_face_t;cdecl;
hb_ft_face_create_referenced : function(ft_face:pointer):Phb_face_t;cdecl;
hb_ft_font_create : function(ft_face:pointer; destroy:hb_destroy_func_t):Phb_font_t;cdecl;
hb_ft_font_create_referenced : function(ft_face:pointer):Phb_font_t;cdecl;
hb_ft_font_get_face : function(font:Phb_font_t):pointer;cdecl;
hb_ft_font_set_load_flags : procedure(font:Phb_font_t; load_flags:cint);cdecl;
hb_ft_font_get_load_flags : function(font:Phb_font_t):cint;cdecl;
hb_ft_font_set_funcs : procedure(font:Phb_font_t);cdecl;
function LoadHarfBuzzLibrary(ALibname: String = cHarfBuzzLibName): Boolean;
procedure UnloadHarfBuzzLibrary;
function LibHarfBuzzLoaded: Boolean;
implementation
var
libhandle: TLibHandle;
function LoadHarfBuzzLibrary(ALibname: String): Boolean;
begin
libhandle := LoadLibrary(ALibname);
Result := False;
if libhandle = 0 then
exit;
Result := True;
Pointer(hb_tag_from_string) := GetProcAddress(libhandle, 'hb_tag_from_string');
Pointer(hb_tag_to_string) := GetProcAddress(libhandle, 'hb_tag_to_string');
Pointer(hb_direction_from_string) := GetProcAddress(libhandle, 'hb_direction_from_string');
Pointer(hb_language_from_string) := GetProcAddress(libhandle, 'hb_language_from_string');
Pointer(hb_language_to_string) := GetProcAddress(libhandle, 'hb_language_to_string');
Pointer(hb_language_get_default) := GetProcAddress(libhandle, 'hb_language_get_default');
Pointer(hb_script_from_iso15924_tag) := GetProcAddress(libhandle, 'hb_script_from_iso15924_tag');
Pointer(hb_script_from_string) := GetProcAddress(libhandle, 'hb_script_from_string');
Pointer(hb_script_to_iso15924_tag) := GetProcAddress(libhandle, 'hb_script_to_iso15924_tag');
Pointer(hb_script_get_horizontal_direction) := GetProcAddress(libhandle, 'hb_script_get_horizontal_direction');
Pointer(hb_feature_from_string) := GetProcAddress(libhandle, 'hb_feature_from_string');
Pointer(hb_feature_to_string) := GetProcAddress(libhandle, 'hb_feature_to_string');
Pointer(hb_variation_from_string) := GetProcAddress(libhandle, 'hb_variation_from_string');
Pointer(hb_variation_to_string) := GetProcAddress(libhandle, 'hb_variation_to_string');
Pointer(hb_blob_create) := GetProcAddress(libhandle, 'hb_blob_create');
Pointer(hb_blob_create_sub_blob) := GetProcAddress(libhandle, 'hb_blob_create_sub_blob');
Pointer(hb_blob_get_empty) := GetProcAddress(libhandle, 'hb_blob_get_empty');
Pointer(hb_blob_reference) := GetProcAddress(libhandle, 'hb_blob_reference');
Pointer(hb_blob_destroy) := GetProcAddress(libhandle, 'hb_blob_destroy');
Pointer(hb_blob_set_user_data) := GetProcAddress(libhandle, 'hb_blob_set_user_data');
Pointer(hb_blob_get_user_data) := GetProcAddress(libhandle, 'hb_blob_get_user_data');
Pointer(hb_blob_make_immutable) := GetProcAddress(libhandle, 'hb_blob_make_immutable');
Pointer(hb_blob_is_immutable) := GetProcAddress(libhandle, 'hb_blob_is_immutable');
Pointer(hb_blob_get_length) := GetProcAddress(libhandle, 'hb_blob_get_length');
Pointer(hb_blob_get_data) := GetProcAddress(libhandle, 'hb_blob_get_data');
Pointer(hb_blob_get_data) := GetProcAddress(libhandle, 'hb_blob_get_data');
Pointer(hb_blob_get_data_writable) := GetProcAddress(libhandle, 'hb_blob_get_data_writable');
pointer(hb_unicode_funcs_get_default):=GetProcAddress(libhandle,'hb_unicode_funcs_get_default');
pointer(hb_unicode_funcs_create):=GetProcAddress(libhandle,'hb_unicode_funcs_create');
pointer(hb_unicode_funcs_get_empty):=GetProcAddress(libhandle,'hb_unicode_funcs_get_empty');
pointer(hb_unicode_funcs_reference):=GetProcAddress(libhandle,'hb_unicode_funcs_reference');
pointer(hb_unicode_funcs_destroy):=GetProcAddress(libhandle,'hb_unicode_funcs_destroy');
pointer(hb_unicode_funcs_set_user_data):=GetProcAddress(libhandle,'hb_unicode_funcs_set_user_data');
pointer(hb_unicode_funcs_get_user_data):=GetProcAddress(libhandle,'hb_unicode_funcs_get_user_data');
pointer(hb_unicode_funcs_make_immutable):=GetProcAddress(libhandle,'hb_unicode_funcs_make_immutable');
pointer(hb_unicode_funcs_is_immutable):=GetProcAddress(libhandle,'hb_unicode_funcs_is_immutable');
pointer(hb_unicode_funcs_get_parent):=GetProcAddress(libhandle,'hb_unicode_funcs_get_parent');
pointer(hb_unicode_funcs_set_combining_class_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_combining_class_func');
pointer(hb_unicode_funcs_set_eastasian_width_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_eastasian_width_func');
pointer(hb_unicode_funcs_set_general_category_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_general_category_func');
pointer(hb_unicode_funcs_set_mirroring_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_mirroring_func');
pointer(hb_unicode_funcs_set_script_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_script_func');
pointer(hb_unicode_funcs_set_compose_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_compose_func');
pointer(hb_unicode_funcs_set_decompose_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_decompose_func');
pointer(hb_unicode_funcs_set_decompose_compatibility_func):=GetProcAddress(libhandle,'hb_unicode_funcs_set_decompose_compatibility_func');
pointer(hb_unicode_combining_class):=GetProcAddress(libhandle,'hb_unicode_combining_class');
pointer(hb_unicode_eastasian_width):=GetProcAddress(libhandle,'hb_unicode_eastasian_width');
pointer(hb_unicode_general_category):=GetProcAddress(libhandle,'hb_unicode_general_category');
pointer(hb_unicode_mirroring):=GetProcAddress(libhandle,'hb_unicode_mirroring');
pointer(hb_unicode_script):=GetProcAddress(libhandle,'hb_unicode_script');
pointer(hb_unicode_compose):=GetProcAddress(libhandle,'hb_unicode_compose');
pointer(hb_unicode_decompose):=GetProcAddress(libhandle,'hb_unicode_decompose');
pointer(hb_unicode_decompose_compatibility):=GetProcAddress(libhandle,'hb_unicode_decompose_compatibility');
pointer(hb_segment_properties_equal):=GetProcAddress(libhandle,'hb_segment_properties_equal');
pointer(hb_segment_properties_hash):=GetProcAddress(libhandle,'hb_segment_properties_hash');
pointer(hb_buffer_create):=GetProcAddress(libhandle,'hb_buffer_create');
pointer(hb_buffer_get_empty):=GetProcAddress(libhandle,'hb_buffer_get_empty');
pointer(hb_buffer_reference):=GetProcAddress(libhandle,'hb_buffer_reference');
pointer(hb_buffer_destroy):=GetProcAddress(libhandle,'hb_buffer_destroy');
pointer(hb_buffer_set_user_data):=GetProcAddress(libhandle,'hb_buffer_set_user_data');
pointer(hb_buffer_get_user_data):=GetProcAddress(libhandle,'hb_buffer_get_user_data');
pointer(hb_buffer_set_content_type):=GetProcAddress(libhandle,'hb_buffer_set_content_type');
pointer(hb_buffer_get_content_type):=GetProcAddress(libhandle,'hb_buffer_get_content_type');
pointer(hb_buffer_set_unicode_funcs):=GetProcAddress(libhandle,'hb_buffer_set_unicode_funcs');
pointer(hb_buffer_get_unicode_funcs):=GetProcAddress(libhandle,'hb_buffer_get_unicode_funcs');
pointer(hb_buffer_set_direction):=GetProcAddress(libhandle,'hb_buffer_set_direction');
pointer(hb_buffer_get_direction):=GetProcAddress(libhandle,'hb_buffer_get_direction');
pointer(hb_buffer_set_script):=GetProcAddress(libhandle,'hb_buffer_set_script');
pointer(hb_buffer_get_script):=GetProcAddress(libhandle,'hb_buffer_get_script');
pointer(hb_buffer_set_language):=GetProcAddress(libhandle,'hb_buffer_set_language');
pointer(hb_buffer_get_language):=GetProcAddress(libhandle,'hb_buffer_get_language');
pointer(hb_buffer_set_segment_properties):=GetProcAddress(libhandle,'hb_buffer_set_segment_properties');
pointer(hb_buffer_get_segment_properties):=GetProcAddress(libhandle,'hb_buffer_get_segment_properties');
pointer(hb_buffer_guess_segment_properties):=GetProcAddress(libhandle,'hb_buffer_guess_segment_properties');
pointer(hb_buffer_set_flags):=GetProcAddress(libhandle,'hb_buffer_set_flags');
pointer(hb_buffer_get_flags):=GetProcAddress(libhandle,'hb_buffer_get_flags');
pointer(hb_buffer_set_cluster_level):=GetProcAddress(libhandle,'hb_buffer_set_cluster_level');
pointer(hb_buffer_get_cluster_level):=GetProcAddress(libhandle,'hb_buffer_get_cluster_level');
pointer(hb_buffer_set_replacement_codepoint):=GetProcAddress(libhandle,'hb_buffer_set_replacement_codepoint');
pointer(hb_buffer_get_replacement_codepoint):=GetProcAddress(libhandle,'hb_buffer_get_replacement_codepoint');
pointer(hb_buffer_reset):=GetProcAddress(libhandle,'hb_buffer_reset');
pointer(hb_buffer_clear_contents):=GetProcAddress(libhandle,'hb_buffer_clear_contents');
pointer(hb_buffer_pre_allocate):=GetProcAddress(libhandle,'hb_buffer_pre_allocate');
pointer(hb_buffer_allocation_successful):=GetProcAddress(libhandle,'hb_buffer_allocation_successful');
pointer(hb_buffer_reverse):=GetProcAddress(libhandle,'hb_buffer_reverse');
pointer(hb_buffer_reverse_range):=GetProcAddress(libhandle,'hb_buffer_reverse_range');
pointer(hb_buffer_reverse_clusters):=GetProcAddress(libhandle,'hb_buffer_reverse_clusters');
pointer(hb_buffer_add):=GetProcAddress(libhandle,'hb_buffer_add');
pointer(hb_buffer_add_utf8):=GetProcAddress(libhandle,'hb_buffer_add_utf8');
pointer(hb_buffer_add_utf16):=GetProcAddress(libhandle,'hb_buffer_add_utf16');
pointer(hb_buffer_add_utf32):=GetProcAddress(libhandle,'hb_buffer_add_utf32');
pointer(hb_buffer_add_latin1):=GetProcAddress(libhandle,'hb_buffer_add_latin1');
pointer(hb_buffer_add_codepoints):=GetProcAddress(libhandle,'hb_buffer_add_codepoints');
pointer(hb_buffer_set_length):=GetProcAddress(libhandle,'hb_buffer_set_length');
pointer(hb_buffer_get_length):=GetProcAddress(libhandle,'hb_buffer_get_length');
pointer(hb_buffer_get_glyph_infos):=GetProcAddress(libhandle,'hb_buffer_get_glyph_infos');
pointer(hb_buffer_get_glyph_positions):=GetProcAddress(libhandle,'hb_buffer_get_glyph_positions');
pointer(hb_buffer_normalize_glyphs):=GetProcAddress(libhandle,'hb_buffer_normalize_glyphs');
pointer(hb_buffer_serialize_format_from_string):=GetProcAddress(libhandle,'hb_buffer_serialize_format_from_string');
pointer(hb_buffer_serialize_format_to_string):=GetProcAddress(libhandle,'hb_buffer_serialize_format_to_string');
pointer(hb_buffer_serialize_list_formats):=GetProcAddress(libhandle,'hb_buffer_serialize_list_formats');
pointer(hb_buffer_serialize_glyphs):=GetProcAddress(libhandle,'hb_buffer_serialize_glyphs');
pointer(hb_buffer_deserialize_glyphs):=GetProcAddress(libhandle,'hb_buffer_deserialize_glyphs');
pointer(hb_buffer_set_message_func):=GetProcAddress(libhandle,'hb_buffer_set_message_func');
pointer(hb_font_funcs_create):=GetProcAddress(libhandle,'hb_font_funcs_create');
pointer(hb_font_funcs_get_empty):=GetProcAddress(libhandle,'hb_font_funcs_get_empty');
pointer(hb_font_funcs_reference):=GetProcAddress(libhandle,'hb_font_funcs_reference');
pointer(hb_font_funcs_destroy):=GetProcAddress(libhandle,'hb_font_funcs_destroy');
pointer(hb_font_funcs_set_user_data):=GetProcAddress(libhandle,'hb_font_funcs_set_user_data');
pointer(hb_font_funcs_get_user_data):=GetProcAddress(libhandle,'hb_font_funcs_get_user_data');
pointer(hb_font_funcs_make_immutable):=GetProcAddress(libhandle,'hb_font_funcs_make_immutable');
pointer(hb_font_funcs_is_immutable):=GetProcAddress(libhandle,'hb_font_funcs_is_immutable');
pointer(hb_font_funcs_set_font_h_extents_func):=GetProcAddress(libhandle,'hb_font_funcs_set_font_h_extents_func');
pointer(hb_font_funcs_set_font_v_extents_func):=GetProcAddress(libhandle,'hb_font_funcs_set_font_v_extents_func');
pointer(hb_font_funcs_set_nominal_glyph_func):=GetProcAddress(libhandle,'hb_font_funcs_set_nominal_glyph_func');
pointer(hb_font_funcs_set_variation_glyph_func):=GetProcAddress(libhandle,'hb_font_funcs_set_variation_glyph_func');
pointer(hb_font_funcs_set_glyph_h_advance_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_h_advance_func');
pointer(hb_font_funcs_set_glyph_v_advance_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_v_advance_func');
pointer(hb_font_funcs_set_glyph_h_origin_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_h_origin_func');
pointer(hb_font_funcs_set_glyph_v_origin_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_v_origin_func');
pointer(hb_font_funcs_set_glyph_h_kerning_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_h_kerning_func');
pointer(hb_font_funcs_set_glyph_v_kerning_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_v_kerning_func');
pointer(hb_font_funcs_set_glyph_extents_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_extents_func');
pointer(hb_font_funcs_set_glyph_contour_point_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_contour_point_func');
pointer(hb_font_funcs_set_glyph_name_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_name_func');
pointer(hb_font_funcs_set_glyph_from_name_func):=GetProcAddress(libhandle,'hb_font_funcs_set_glyph_from_name_func');
pointer(hb_font_get_h_extents):=GetProcAddress(libhandle,'hb_font_get_h_extents');
pointer(hb_font_get_v_extents):=GetProcAddress(libhandle,'hb_font_get_v_extents');
pointer(hb_font_get_nominal_glyph):=GetProcAddress(libhandle,'hb_font_get_nominal_glyph');
pointer(hb_font_get_variation_glyph):=GetProcAddress(libhandle,'hb_font_get_variation_glyph');
pointer(hb_font_get_glyph_h_advance):=GetProcAddress(libhandle,'hb_font_get_glyph_h_advance');
pointer(hb_font_get_glyph_v_advance):=GetProcAddress(libhandle,'hb_font_get_glyph_v_advance');
pointer(hb_font_get_glyph_h_origin):=GetProcAddress(libhandle,'hb_font_get_glyph_h_origin');
pointer(hb_font_get_glyph_v_origin):=GetProcAddress(libhandle,'hb_font_get_glyph_v_origin');
pointer(hb_font_get_glyph_h_kerning):=GetProcAddress(libhandle,'hb_font_get_glyph_h_kerning');
pointer(hb_font_get_glyph_v_kerning):=GetProcAddress(libhandle,'hb_font_get_glyph_v_kerning');
pointer(hb_font_get_glyph_extents):=GetProcAddress(libhandle,'hb_font_get_glyph_extents');
pointer(hb_font_get_glyph_contour_point):=GetProcAddress(libhandle,'hb_font_get_glyph_contour_point');
pointer(hb_font_get_glyph_name):=GetProcAddress(libhandle,'hb_font_get_glyph_name');
pointer(hb_font_get_glyph_from_name):=GetProcAddress(libhandle,'hb_font_get_glyph_from_name');
pointer(hb_font_get_glyph):=GetProcAddress(libhandle,'hb_font_get_glyph');
pointer(hb_font_get_extents_for_direction):=GetProcAddress(libhandle,'hb_font_get_extents_for_direction');
pointer(hb_font_get_glyph_advance_for_direction):=GetProcAddress(libhandle,'hb_font_get_glyph_advance_for_direction');
pointer(hb_font_get_glyph_origin_for_direction):=GetProcAddress(libhandle,'hb_font_get_glyph_origin_for_direction');
pointer(hb_font_add_glyph_origin_for_direction):=GetProcAddress(libhandle,'hb_font_add_glyph_origin_for_direction');
pointer(hb_font_subtract_glyph_origin_for_direction):=GetProcAddress(libhandle,'hb_font_subtract_glyph_origin_for_direction');
pointer(hb_font_get_glyph_kerning_for_direction):=GetProcAddress(libhandle,'hb_font_get_glyph_kerning_for_direction');
pointer(hb_font_get_glyph_extents_for_origin):=GetProcAddress(libhandle,'hb_font_get_glyph_extents_for_origin');
pointer(hb_font_get_glyph_contour_point_for_origin):=GetProcAddress(libhandle,'hb_font_get_glyph_contour_point_for_origin');
pointer(hb_font_glyph_to_string):=GetProcAddress(libhandle,'hb_font_glyph_to_string');
pointer(hb_font_glyph_from_string):=GetProcAddress(libhandle,'hb_font_glyph_from_string');
pointer(hb_font_create):=GetProcAddress(libhandle,'hb_font_create');
pointer(hb_font_create_sub_font):=GetProcAddress(libhandle,'hb_font_create_sub_font');
pointer(hb_font_get_empty):=GetProcAddress(libhandle,'hb_font_get_empty');
pointer(hb_font_reference):=GetProcAddress(libhandle,'hb_font_reference');
pointer(hb_font_destroy):=GetProcAddress(libhandle,'hb_font_destroy');
pointer(hb_font_set_user_data):=GetProcAddress(libhandle,'hb_font_set_user_data');
pointer(hb_font_get_user_data):=GetProcAddress(libhandle,'hb_font_get_user_data');
pointer(hb_font_make_immutable):=GetProcAddress(libhandle,'hb_font_make_immutable');
pointer(hb_font_is_immutable):=GetProcAddress(libhandle,'hb_font_is_immutable');
pointer(hb_font_set_parent):=GetProcAddress(libhandle,'hb_font_set_parent');
pointer(hb_font_get_parent):=GetProcAddress(libhandle,'hb_font_get_parent');
pointer(hb_font_get_face):=GetProcAddress(libhandle,'hb_font_get_face');
pointer(hb_font_set_funcs):=GetProcAddress(libhandle,'hb_font_set_funcs');
pointer(hb_font_set_funcs_data):=GetProcAddress(libhandle,'hb_font_set_funcs_data');
pointer(hb_font_set_scale):=GetProcAddress(libhandle,'hb_font_set_scale');
pointer(hb_font_get_scale):=GetProcAddress(libhandle,'hb_font_get_scale');
pointer(hb_font_set_ppem):=GetProcAddress(libhandle,'hb_font_set_ppem');
pointer(hb_font_get_ppem):=GetProcAddress(libhandle,'hb_font_get_ppem');
pointer(hb_font_set_variations):=GetProcAddress(libhandle,'hb_font_set_variations');
pointer(hb_font_set_var_coords_design):=GetProcAddress(libhandle,'hb_font_set_var_coords_design');
pointer(hb_font_set_var_coords_normalized):=GetProcAddress(libhandle,'hb_font_set_var_coords_normalized');
pointer(hb_font_get_var_coords_normalized):=GetProcAddress(libhandle,'hb_font_get_var_coords_normalized');
pointer(hb_shape):=GetProcAddress(libhandle,'hb_shape');
pointer(hb_shape_full):=GetProcAddress(libhandle,'hb_shape_full');
pointer(hb_shape_list_shapers):=GetProcAddress(libhandle,'hb_shape_list_shapers');
pointer(hb_shape_plan_create):=GetProcAddress(libhandle,'hb_shape_plan_create');
pointer(hb_shape_plan_create_cached):=GetProcAddress(libhandle,'hb_shape_plan_create_cached');
pointer(hb_shape_plan_create2):=GetProcAddress(libhandle,'hb_shape_plan_create2');
pointer(hb_shape_plan_create_cached2):=GetProcAddress(libhandle,'hb_shape_plan_create_cached2');
pointer(hb_shape_plan_get_empty):=GetProcAddress(libhandle,'hb_shape_plan_get_empty');
pointer(hb_shape_plan_reference):=GetProcAddress(libhandle,'hb_shape_plan_reference');
pointer(hb_shape_plan_destroy):=GetProcAddress(libhandle,'hb_shape_plan_destroy');
pointer(hb_shape_plan_set_user_data):=GetProcAddress(libhandle,'hb_shape_plan_set_user_data');
pointer(hb_shape_plan_get_user_data):=GetProcAddress(libhandle,'hb_shape_plan_get_user_data');
pointer(hb_shape_plan_execute):=GetProcAddress(libhandle,'hb_shape_plan_execute');
pointer(hb_shape_plan_get_shaper):=GetProcAddress(libhandle,'hb_shape_plan_get_shaper');
pointer(hb_version):=GetProcAddress(libhandle,'hb_version');
pointer(hb_version_string):=GetProcAddress(libhandle,'hb_version_string');
pointer(hb_version_atleast):=GetProcAddress(libhandle,'hb_version_atleast');
pointer(hb_version_check):=GetProcAddress(libhandle,'hb_version_check');
pointer(hb_ft_face_create):=GetProcAddress(libhandle,'hb_ft_face_create');
pointer(hb_ft_face_create_cached):=GetProcAddress(libhandle,'hb_ft_face_create_cached');
pointer(hb_ft_face_create_referenced):=GetProcAddress(libhandle,'hb_ft_face_create_referenced');
pointer(hb_ft_font_create):=GetProcAddress(libhandle,'hb_ft_font_create');
pointer(hb_ft_font_create_referenced):=GetProcAddress(libhandle,'hb_ft_font_create_referenced');
pointer(hb_ft_font_get_face):=GetProcAddress(libhandle,'hb_ft_font_get_face');
pointer(hb_ft_font_set_load_flags):=GetProcAddress(libhandle,'hb_ft_font_set_load_flags');
pointer(hb_ft_font_get_load_flags):=GetProcAddress(libhandle,'hb_ft_font_get_load_flags');
pointer(hb_ft_font_set_funcs):=GetProcAddress(libhandle,'hb_ft_font_set_funcs');
end;
procedure UnloadHarfBuzzLibrary;
begin
if libhandle = 0 then
Exit;
UnloadLibrary(libhandle);
libhandle:=0;
end;
function LibHarfBuzzLoaded: Boolean;
begin
Result := libhandle <> 0;
end;
initialization
LoadHarfBuzzLibrary(cHarfBuzzLibName);
finalization
if LibHarfBuzzLoaded then
UnloadHarfBuzzLibrary;
end.
|
{
*****************************************************************************
See the file COPYING.modifiedLGPL.txt, included in this distribution,
for details about the license.
*****************************************************************************
Copyright (C) <2005> <Andrew Haines> chmdataprovider.pas
}
unit ChmDataProvider;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IpHtml, iputils, IpMsg, Graphics, chmreader,
LCLType, Controls,
FPImage,
{$IF FPC_FULLVERSION>=20602} //fpreadgif exists since at least this version
FPReadgif,
{$ENDIF}
FPReadbmp,
FPReadxpm,
FPReadJPEG,
FPReadpng,
FPWritebmp,
FPWritePNG,
IntFGraphics,
lhelpstrconsts;
type
THelpPopupEvent = procedure(HelpFile: String; URL: String);
THtmlPageLoadStreamEvent = procedure (var AStream: TStream) of object;
{ TIpChmDataProvider }
TIpChmDataProvider = class(TIpAbstractHtmlDataProvider)
private
FChmFileList: TChmFileList;
FCurrentPage: String;
FCurrentPath: String;
FOnGetHtmlPage: THtmlPageLoadStreamEvent;
FOnHelpPopup: THelpPopupEvent;
function StripInPageLink(AURL: String): String;
protected
function DoGetHtmlStream(const URL: string;
{%H-}PostData: TIpFormDataEntity) : TStream; override;
function DoCheckURL(const URL: string;
var ContentType: string): Boolean; override;
procedure DoLeave({%H-}Html: TIpHtml); override;
procedure DoReference(const {%H-}URL: string); override;
procedure DoGetImage(Sender: TIpHtmlNode; const URL: string;
var Picture: TPicture); override;
function CanHandle(const AUrl: string): Boolean; override;
function BuildURL(const OldURL, NewURL: string): string; override;
function GetDirsParents(ADir: String): TStringList; deprecated;
function ReadDirsParents(const ADir: String; AStrings: TStrings): Boolean;
{ Result must be Free() by caller! }
function DoGetStream(const URL: string): TStream; override;
public
constructor Create(AOwner: TComponent; AChmFileList: TChmFileList); reintroduce;
destructor Destroy; override;
property ChmFileList: TChmFileList read FChmFileList write FChmFileList;
property OnHelpPopup: THelpPopupEvent read FOnHelpPopup write FOnHelpPopup;
property CurrentPage: String read FCurrentPage;
property CurrentPath: String read FCurrentPath write FCurrentPath;
property OnGetHtmlPage: THtmlPageLoadStreamEvent read FOnGetHtmlPage write FOnGetHtmlPage;
end;
implementation
{ TIpChmDataProvider }
function TIpChmDataProvider.StripInPageLink ( AURL: String ) : String;
var
i: LongInt;
begin
Result := AURL;
i := Pos('#', Result);
if i > 0 then
Result := Copy(Result, 1, i-1);
end;
function TIpChmDataProvider.DoGetHtmlStream(const URL: string;
PostData: TIpFormDataEntity): TStream;
var
Tmp: string;
begin
Result := TMemoryStream.Create();
// If for some reason we were not able to get the page return something so that
// we don't cause an AV
if not FChmFileList.GetObjectData(StripInPageLink(URL), Result) then
begin
Result.Size := 0;
Tmp := '<HTML>' + slhelp_PageCannotBeFound + '</HTML>';
Result.Write(Tmp, Length(tmp));
end;
if Assigned(FOnGetHtmlPage) then
FOnGetHtmlPage(Result);
end;
function TIpChmDataProvider.DoCheckURL(const URL: string;
var ContentType: string): Boolean;
var
Reader: TChmReader = nil;
begin
//DebugLn('RequestedUrl: ',URL);
Result := FChmFileList.ObjectExists(StripInPageLink(Url), Reader) > 0;
if Result then begin
ContentType := 'text/html';
FCurrentPath := ExtractFilePath(Url);
Result := True;
FCurrentPage := URL;
end;
end;
procedure TIpChmDataProvider.DoLeave(Html: TIpHtml);
begin
//
// //DebugLn('Left: ');
end;
procedure TIpChmDataProvider.DoReference(const URL: string);
begin
//
////DebugLn('Reference=',URL);
end;
procedure TIpChmDataProvider.DoGetImage(Sender: TIpHtmlNode; const URL: string;
var Picture: TPicture);
var
Stream: TMemoryStream;
FileExt: String;
begin
//DebugLn('Getting Image ',(Url));
Picture := nil;
FileExt := ExtractFileExt(URL);
Picture := TPicture.Create;
Stream := TMemoryStream.Create();
try
if FChmFileList.GetObjectData('/'+URL, Stream) then
begin
Stream.Position := 0;
try
Picture.LoadFromStreamWithFileExt(Stream, FileExt);
except
// only happens if it's an image type we can't handle
end;
end;
finally
Stream.Free();
end;
end;
function TIpChmDataProvider.CanHandle(const AUrl: string): Boolean;
var
HelpFile: String;
ChmReader: TChmReader = nil;
begin
Result := True;
if Pos('Java', AUrl) = 1 then
Result := False;
if (FChmFileList.ObjectExists(StripInPageLink(AUrl), ChmReader)= 0)
and (FChmFileList.ObjectExists(StripInPageLink(BuildUrl(FCurrentPath, AUrl)), ChmReader) = 0)
then
Result := False;
//DebugLn('CanHandle ',AUrl,' = ', Result);
//if not Result then if FChmFileList.ObjectExists(BuildURL('', AUrl)) > 0 Then result := true;
if (not Result) and (Pos('#', AUrl) = 1) then
Result := True;
end;
function TIpChmDataProvider.BuildURL(const OldURL, NewURL: string): string;
var
X: LongInt;
sNewURL: String;
ParentDirs: TStringList;
RemoveDirCount: Integer;
begin
Result := NewURL;
sNewURL := NewURL;
if OldURL = '' then
exit;
if Pos('ms-its:', NewURL) = 1 then
begin
if Pos('#', NewURL) = 0 then
exit;
X := Pos('::', NewURL);
if NewURL[X+2] = '/' then // NewURL is complete and absolute --> nothing to do
exit;
sNewURL := Copy(sNewURL, X+3, MaxInt);
end;
ParentDirs := TStringList.Create();
try
ReadDirsParents(OldURL, ParentDirs);
RemoveDirCount := 0;
repeat
X := Pos('../', sNewURL);
if X > 0 then
begin
Delete(sNewURL, X, 3);
Inc(RemoveDirCount);
end;
until X = 0;
repeat
X := Pos('./', sNewURL);
if X > 0 then
Delete(sNewURL, X, 2);
until X = 0;
Result := '';
for X := 0 to ParentDirs.Count-RemoveDirCount-1 do
Result := Result + ParentDirs[X] + '/';
Result := Result+sNewURL;
repeat
X := Pos('//', Result);
if X > 0 then
Delete(Result, X, 1);
until X = 0;
finally
ParentDirs.Free();
end;
//WriteLn('res = ', Result);
end;
function TIpChmDataProvider.GetDirsParents(ADir: String): TStringList;
begin
Result := TStringList.Create;
ReadDirsParents(ADir, Result);
end;
function TIpChmDataProvider.ReadDirsParents(const ADir: String; AStrings: TStrings): Boolean;
var
LastName: String;
begin
Result := True;
AStrings.Delimiter := '/';
AStrings.StrictDelimiter := True;
AStrings.DelimitedText := ADir;
LastName := ExtractFileName(ADir);
if LastName <> '' then
AStrings.Delete(AStrings.Count-1);
if AStrings[AStrings.Count-1] = '' then
AStrings.Delete(AStrings.Count-1);
end;
function TIpChmDataProvider.DoGetStream(const URL: string): TStream;
var
NewURL: String;
begin
Result := nil;
if Length(URL) = 0 then
Exit;
if not (URL[1] in ['/']) then
NewURL := BuildUrl(FCurrentPath,URL)
else
NewURL := URL;
Result := FChmFileList.GetObject(NewURL);
end;
constructor TIpChmDataProvider.Create(AOwner: TComponent; AChmFileList: TChmFileList);
begin
inherited Create(AOwner);
FChmFileList := AChmFileList;
end;
destructor TIpChmDataProvider.Destroy;
begin
inherited Destroy;
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2009-7-8
描述: 图像分析
*******************************************************************************}
unit UFormParse;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UDataModule, UBgFormBase, UTransPanel, cxGraphics, dxLayoutControl,
cxButtonEdit, cxImage, cxMCListBox, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxContainer, cxEdit, cxMemo, StdCtrls, cxControls;
type
TfFormParse = class(TfBgFormBase)
dxLayout1: TdxLayoutControl;
BtnOK: TButton;
BtnExit: TButton;
EditMemo: TcxMemo;
InfoItems: TcxComboBox;
EditInfo: TcxTextEdit;
BtnAdd: TButton;
BtnDel: TButton;
ListInfo1: TcxMCListBox;
ImagePic: TcxImage;
EditID: TcxButtonEdit;
EditPart: TcxComboBox;
EditName: TcxTextEdit;
dxLayoutGroup1: TdxLayoutGroup;
dxGroup1: TdxLayoutGroup;
dxLayout1Group4: TdxLayoutGroup;
dxLayout1Item4: TdxLayoutItem;
dxLayout1Item13: TdxLayoutItem;
dxLayout1Item12: TdxLayoutItem;
dxLayout1Item6: TdxLayoutItem;
dxLayout1Item3: TdxLayoutItem;
dxGroup2: TdxLayoutGroup;
dxLayout1Group2: TdxLayoutGroup;
dxLayout1Item7: TdxLayoutItem;
dxLayout1Item8: TdxLayoutItem;
dxLayout1Group7: TdxLayoutGroup;
dxLayout1Item9: TdxLayoutItem;
dxLayout1Item10: TdxLayoutItem;
dxLayout1Item11: TdxLayoutItem;
dxLayoutGroup2: TdxLayoutGroup;
dxLayoutItem1: TdxLayoutItem;
dxLayout1Item2: TdxLayoutItem;
EditHistory: TcxComboBox;
dxLayout1Item1: TdxLayoutItem;
dxLayout1Item5: TdxLayoutItem;
dxLayout1Group1: TdxLayoutGroup;
EditDate: TcxTextEdit;
dxLayout1Group5: TdxLayoutGroup;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure BtnAddClick(Sender: TObject);
procedure BtnDelClick(Sender: TObject);
procedure ListInfo1Click(Sender: TObject);
procedure ImagePicDblClick(Sender: TObject);
procedure EditIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditHistoryPropertiesChange(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure ImagePicEditing(Sender: TObject; var CanEdit: Boolean);
private
{ Private declarations }
FMemberID: string;
//会员编号
FDisplayRect: TRect;
//显示区域
FPrefixID: string;
//前缀编号
FIDLength: integer;
//前缀长度
FImageChanged,FInfoChanged: Boolean;
//数据变动
procedure InitFormData(const nID: string);
//初始化数据
function SaveData: Boolean;
//保存数据
public
{ Public declarations }
FActiveForm: TForm;
//活动窗口
end;
function ShowImageParseForm(const nMemberID: string; const nRect: TRect): TForm;
//入口函数
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, UFormCtrl, UAdjustForm, USysGrid, USysDB, USysConst,
USysFun, USysGobal, UFormEditPlan;
var
gForm: TForm = nil;
//------------------------------------------------------------------------------
//Date: 2009-7-3
//Parm: 显示区域
//Desc: 在nRect区域显示图像分析窗口
function ShowImageParseForm(const nMemberID: string; const nRect: TRect): TForm;
begin
Result := gForm;
if Assigned(gForm) then Exit;
gForm := TfFormParse.Create(gForm);
Result := gForm;
with TfFormParse(Result) do
begin
Position := poDesigned;
Left := nRect.Left + Round((nRect.Right - nRect.Left - Width) /2 );
Top := nRect.Top + Round((nRect.Bottom - nRect.Top - Height) /2 );
FMemberID := nMemberID;
FDisplayRect := nRect;
InitFormData('');
if not Showing then Show;
end;
end;
procedure TfFormParse.FormCreate(Sender: TObject);
var nIni: TIniFile;
begin
inherited;
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadMCListBoxConfig(Name, ListInfo1);
FPrefixID := nIni.ReadString(Name, 'IDPrefix', 'PF');
FIDLength := nIni.ReadInteger(Name, 'IDLength', 8);
finally
nIni.Free;
end;
AdjustCtrlData(Self);
ResetHintAllCtrl(Self, 'T', sTable_SkinType);
end;
procedure TfFormParse.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if Action = caFree then
begin
gForm := nil;
ReleaseCtrlData(Self);
if Assigned(gOnCloseActiveForm) then gOnCloseActiveForm(self);
SaveMCListBoxConfig(Name, ListInfo1);
ReleaseCtrlData(Self);
end;
end;
procedure TfFormParse.BtnExitClick(Sender: TObject);
begin
CloseForm;
end;
//------------------------------------------------------------------------------
procedure TfFormParse.InitFormData(const nID: string);
var nStr: string;
begin
EditDate.Text := DateTime2Str(Now);
if InfoItems.Properties.Items.Count < 1 then
begin
InfoItems.Clear;
nStr := MacroValue(sQuery_SysDict, [MI('$Table', sTable_SysDict),
MI('$Name', sFlag_SkinType)]);
//数据字典中皮肤状况信息项
with FDM.QueryTemp(nStr) do
begin
First;
while not Eof do
begin
InfoItems.Properties.Items.Add(FieldByName('D_Value').AsString);
Next;
end;
end;
end;
if EditPart.Properties.Items.Count < 1 then
begin
nStr := 'B_ID=Select B_ID,B_Text From %s Where B_Group=''%s''';
nStr := Format(nStr, [sTable_BaseInfo, sFlag_SkinPart]);
FDM.FillStringsData(EditPart.Properties.Items, nStr, -1, '、');
AdjustStringsItem(EditPart.Properties.Items, False);
end;
if EditHistory.Properties.Items.Count < 1 then
begin
nStr := 'T_ID=Select T_ID,T_Name From %s Where T_MID is Null Or T_MID=''%s''';
nStr := Format(nStr, [sTable_SkinType, FMemberID]);
FDM.FillStringsData(EditHistory.Properties.Items, nStr, -1, '、');
AdjustStringsItem(EditHistory.Properties.Items, False);
end;
if nID <> '' then
begin
FInfoChanged := False;
FImageChanged := False;
nStr := 'Select * From %s Where T_ID=''%s''';
nStr := Format(nStr, [sTable_SkinType, nID]);
LoadDataToCtrl(FDM.QueryTemp(nStr), Self, '');
FDM.LoadDBImage(FDM.SqlTemp, 'T_Image', ImagePic.Picture);
ListInfo1.Clear;
nStr := MacroValue(sQuery_ExtInfo, [MI('$Table', sTable_ExtInfo),
MI('$Group', sFlag_SkinType), MI('$ID', nID)]);
//扩展信息
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
First;
while not Eof do
begin
nStr := FieldByName('I_Item').AsString + ListInfo1.Delimiter +
FieldByName('I_Info').AsString;
ListInfo1.Items.Add(nStr);
Next;
end;
end;
end;
end;
//Desc: 添加信息项
procedure TfFormParse.BtnAddClick(Sender: TObject);
begin
InfoItems.Text := Trim(InfoItems.Text);
if InfoItems.Text = '' then
begin
ListInfo1.SetFocus;
FDM.ShowMsg('请填写 或 选择有效的名称', sHint); Exit;
end;
EditInfo.Text := Trim(EditInfo.Text);
if EditInfo.Text = '' then
begin
EditInfo.SetFocus;
FDM.ShowMsg('请填写有效的信息内容', sHint); Exit;
end;
ListInfo1.Items.Add(InfoItems.Text + ListInfo1.Delimiter + EditInfo.Text);
FInfoChanged := True;
end;
//Desc: 删除信息项
procedure TfFormParse.BtnDelClick(Sender: TObject);
var nIdx: integer;
begin
if ListInfo1.ItemIndex < 0 then
begin
FDM.ShowMsg('请选择要删除的内容', sHint); Exit;
end;
nIdx := ListInfo1.ItemIndex;
ListInfo1.Items.Delete(ListInfo1.ItemIndex);
FInfoChanged := True;
if nIdx >= ListInfo1.Count then Dec(nIdx);
ListInfo1.ItemIndex := nIdx;
FDM.ShowMsg('已成功删除', sHint);
end;
//Desc: 查看信息
procedure TfFormParse.ListInfo1Click(Sender: TObject);
var nStr: string;
nPos: integer;
begin
if ListInfo1.ItemIndex > -1 then
begin
nStr := ListInfo1.Items[ListInfo1.ItemIndex];
nPos := Pos(ListInfo1.Delimiter, nStr);
InfoItems.Text := Copy(nStr, 1, nPos - 1);
System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1);
EditInfo.Text := nStr;
end;
end;
//Desc: 选择照片
procedure TfFormParse.ImagePicDblClick(Sender: TObject);
var nStr: string;
begin
with TOpenDialog.Create(Application) do
begin
Title := '照片';
Filter := '图片文件|*.bmp;*.png;*.jpg';
if Execute then nStr := FileName else nStr := '';
Free;
end;
if FileExists(nStr) then
begin
ImagePic.Picture.LoadFromFile(nStr);
FImageChanged := True;
end;
end;
//Desc: 随机编号
procedure TfFormParse.EditIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
EditID.Text := RandomItemID(FPrefixID, FIDLength);
end;
//Desc: 选择方案
procedure TfFormParse.EditHistoryPropertiesChange(Sender: TObject);
begin
InitFormData(GetCtrlData(EditHistory));
end;
procedure TfFormParse.ImagePicEditing(Sender: TObject;
var CanEdit: Boolean);
begin
FImageChanged := True;
end;
//------------------------------------------------------------------------------
//Desc: 保存数据
function TfFormParse.SaveData: Boolean;
var nIsNew: Boolean;
nList: TStrings;
i,nCount: integer;
nStr,nSQL: string;
begin
Result := True;
nStr := 'Select * From %s Where T_ID=''%s''';
nStr := Format(nStr, [sTable_SkinType, EditID.Text]);
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
if FieldByName('T_MID').AsString <> FMemberID then Exit;
//共用方案
if EditID.Text <> GetCtrlData(EditHistory) then
begin
EditID.SetFocus;
FDM.ShowMsg('该编号已经被使用', sHint); Exit;
end else nIsNew := False;
end else
begin
nIsNew := True;
FInfoChanged := True;
FImageChanged := True;
end;
nList := nil;
FDM.ADOConn.BeginTrans;
try
nList := TStringList.Create;
nList.Add('T_BID=''' + gSysParam.FBeautyID + '''');
nList.Add('T_MID=''' + FMemberID + '''');
nStr := 'T_ID=''' + EditID.Text + '''';
nSQL := MakeSQLByForm(Self, sTable_SkinType, nStr, nIsNew, nil, nList);
FDM.ExecuteSQL(nSQL);
if FImageChanged then
begin
nStr := 'Select * From %s Where T_ID=''%s''';
nStr := Format(nStr, [sTable_SkinType, EditID.Text]);
FDM.QueryTemp(nStr);
FDM.SaveDBImage(FDM.SqlTemp, 'T_Image', ImagePic.Picture.Graphic);
end;
if gSysDBType = dtAccess then
begin
nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' +
'Values(''%s'', ''%s'', ''%s'')';
nSQL := Format(nSQL, [sTable_SyncItem, sTable_SkinType, 'T_ID', EditID.Text]);
FDM.ExecuteSQL(nSQL);
end; //记录变更
if FInfoChanged then
begin
if not nIsNew then
begin
nSQL := 'Delete From %s Where I_Group=''%s'' and I_ItemID=''%s''';
nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, EditID.Text]);
FDM.ExecuteSQL(nSQL);
end;
nCount := ListInfo1.Items.Count - 1;
for i:=0 to nCount do
begin
nStr := ListInfo1.Items[i];
if not SplitStr(nStr, nList, 2, ListInfo1.Delimiter) then Continue;
nSQL := 'Insert Into %s(I_Group, I_ItemID, I_Item, I_Info) ' +
'Values(''%s'', ''%s'', ''%s'', ''%s'')';
nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, EditID.Text, nList[0], nList[1]]);
FDM.ExecuteSQL(nSQL);
end;
if gSysDBType = dtAccess then
begin
nSQL := 'Insert Into %s(S_Table, S_Field, S_Value, S_ExtField, S_ExtValue) ' +
'Values(''%s'', ''%s'', ''%s'', ''%s'', ''%s'')';
nSQL := Format(nSQL, [sTable_SyncItem, sTable_ExtInfo, 'I_ItemID', EditID.Text,
'I_Group', sFlag_SkinType]);
FDM.ExecuteSQL(nSQL);
end; //记录变更
end;
FreeAndNil(nList);
FDM.ADOConn.CommitTrans;
except
Result := False;
FreeAndNil(nList);
FDM.ADOConn.RollbackTrans;
FDM.ShowMsg('保存分析结果失败', '未知原因');
end;
end;
//Desc: 开处方
procedure TfFormParse.BtnOKClick(Sender: TObject);
begin
EditID.Text := Trim(EditID.Text);
if EditID.Text = '' then
begin
EditID.SetFocus;
FDM.ShowMsg('请填写有效的编号', sHint); Exit;
end;
EditName.Text := Trim(EditName.Text);
if EditName.Text = '' then
begin
EditName.SetFocus;
FDM.ShowMsg('请填写有效的名称', sHint); Exit;
end;
if SaveData then
begin
FActiveForm := ShowPlanEditForm(FMemberID, EditID.Text, FDisplayRect);
CloseForm;
end;
end;
end.
|
unit ufmMain;
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
TfmMain = class(TForm)
edProtoFileName: TEdit;
btnOpenProtoFile: TButton;
odProtoFile: TFileOpenDialog;
btnGenerate: TButton;
edOutputFolder: TEdit;
btnChooseOutputFolder: TButton;
procedure btnOpenProtoFileClick(Sender: TObject);
procedure btnChooseOutputFolderClick(Sender: TObject);
procedure btnGenerateClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure Generate(SourceFiles: TStrings; const OutputDir: string);
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
uses
System.IOUtils,
System.IniFiles,
Vcl.FileCtrl,
uProtoBufGenerator;
{$R *.dfm}
procedure TfmMain.btnChooseOutputFolderClick(Sender: TObject);
var
Dir: string;
begin
Dir := edOutputFolder.Text;
if SelectDirectory('Select output directory', '', Dir, [sdNewFolder, sdShowShares, sdNewUI, sdValidateDir], nil) then
edOutputFolder.Text := Dir;
end;
procedure TfmMain.btnGenerateClick(Sender: TObject);
var
FileNames: TStrings;
begin
FileNames := TStringList.Create;
try
FileNames.Delimiter := odProtoFile.Files.Delimiter;
FileNames.DelimitedText := edProtoFileName.Text;
Generate(FileNames, edOutputFolder.Text);
ShowMessage('Complete! Take a look into output directory');
finally
FileNames.Free;
end;
end;
procedure TfmMain.btnOpenProtoFileClick(Sender: TObject);
begin
if odProtoFile.Execute then
edProtoFileName.Text := odProtoFile.Files.DelimitedText;
end;
procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction);
var
ini: TIniFile;
s: string;
begin
s := TPath.Combine(TPath.GetHomePath, 'DelphiProtoBufGenerator');
TDirectory.CreateDirectory(s);
s := TPath.Combine(s, 'settings.ini');
ini := TIniFile.Create(s);
try
ini.WriteString('Common', 'ProtoFiles', edProtoFileName.Text);
ini.WriteString('Common', 'PasOutputFolder', edOutputFolder.Text);
finally
ini.Free;
end;
end;
procedure TfmMain.FormCreate(Sender: TObject);
var
ini: TIniFile;
s: string;
begin
s := TPath.Combine(TPath.GetHomePath, 'DelphiProtoBufGenerator');
TDirectory.CreateDirectory(s);
s := TPath.Combine(s, 'settings.ini');
ini := TIniFile.Create(s);
try
edProtoFileName.Text := ini.ReadString('Common', 'ProtoFiles', '');
edOutputFolder.Text := ini.ReadString('Common', 'PasOutputFolder', '');
finally
ini.Free;
end;
end;
procedure TfmMain.Generate(SourceFiles: TStrings; const OutputDir: string);
var
Gen: TProtoBufGenerator;
i: Integer;
begin
System.SysUtils.ForceDirectories(OutputDir);
Gen := TProtoBufGenerator.Create;
try
for i := 0 to SourceFiles.Count - 1 do
Gen.Generate(SourceFiles[i], edOutputFolder.Text, TEncoding.UTF8);
finally
Gen.Free;
end;
end;
end.
|
unit uFormData;
interface
uses
Windows, Classes, SysUtils,
RttiClasses;
type
TBaseData = class(TRttiEnabled);
TFlashData = class;
TFlashPage = class;
TPageData = class;
TQuestionData = class;
TFlashPageArray = array of TFlashPage;
TPageDataArray = array of TPageData;
TQuestionDataArray = array of TQuestionData;
TFlashData = class(TBaseData)
private
FPages: TFlashPageArray;
FXMLFileName: TFilename;
function GetPageCount: Integer;
procedure SetPageCount(const Value: Integer);
public
procedure LoadFromFile(const aXMLFile: TFilename);
procedure SaveToFile(const aXMLFile: TFilename);
property XMLFileName: TFilename read FXMLFileName;
property PageCount: Integer read GetPageCount write SetPageCount;
published
property Pages: TFlashPageArray read FPages write FPages;
end;
TFlashPage = class(TBaseData)
private
FData: TPageDataArray;
FQuestions: TQuestionDataArray;
public
function DataCount: Integer;
function AddData : TPageData;
function QuestionCount: Integer;
function AddQuestion : TQuestionData;
published
property Data: TPageDataArray read FData write FData;
property Questions: TQuestionDataArray read FQuestions write FQuestions;
end;
TSize = class(TBaseData)
private
FWidth: Integer;
FTop: Integer;
FHeight: Integer;
FLeft: Integer;
public
// procedure AfterConstruction;override;
// destructor Destroy;override;
published
property Top : Integer read FTop write FTop;
property Left : Integer read FLeft write FLeft;
property Width : Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
end;
TPageData = class(TBaseData)
private
FAnswerText: string;
// FButtonText: string;
// FButtonPos: TSize;
FAnswerPos: TSize;
FFontSize: Integer;
published
//property ButtonText: string read FButtonText write FButtonText;
// property ButtonPos : TSize read FButtonPos write FButtonPos;
property AnswerText: string read FAnswerText write FAnswerText;
property AnswerPos : TSize read FAnswerPos write FAnswerPos;
property FontSize : Integer read FFontSize write FFontSize;
end;
TQuestionData = class(TBaseData)
private
FQuestionPos: TSize;
FImageFile: TFileName;
published
property QuestionPos: TSize read FQuestionPos write FQuestionPos;
property ImageFile: TFileName read FImageFile write FImageFile;
end;
implementation
uses
XMLFile;
{ TFlashData }
procedure TFlashData.LoadFromFile(const aXMLFile: TFilename);
var
temp: TFlashData;
begin
//create empty file
if not FileExists(aXMLFile) then
begin
temp := TFlashData.Create;
try
temp.SaveToFile(aXMLFile);
finally
temp.Free
end;
end;
FXMLFileName := aXMLFile;
Self.PageCount := 0; //clear
XMLFile.LoadFromFile(aXMLFile, Self);
end;
function TFlashData.GetPageCount: Integer;
begin
Result := Length(FPages);
end;
procedure TFlashData.SaveToFile(const aXMLFile: TFilename);
begin
XMLFile.SaveToFile(aXMLFile, Self);
end;
procedure TFlashData.SetPageCount(const Value: Integer);
var
i: Integer;
begin
for i := Value to High(FPages) do
begin
if FPages[i] <> nil then
begin
FPages[i].Free;
FPages[i] := nil;
end;
end;
SetLength(FPages, Value);
for i := 0 to High(FPages) do
begin
if FPages[i] = nil then
FPages[i] := TFlashPage.Create;
end;
end;
{ TFlashPage }
function TFlashPage.AddData: TPageData;
begin
Result := TPageData.Create;
// Result.ButtonPos.Height := 25;
// Result.ButtonPos.Width := 50;
Result.AnswerPos.Height := 100;
Result.AnswerPos.Width := 200;
SetLength(FData, Length(FData)+1);
FData[High(FData)] := Result;
end;
function TFlashPage.AddQuestion: TQuestionData;
begin
Result := TQuestionData.Create;
Result.QuestionPos.Height := 30;
Result.QuestionPos.Width := 30;
SetLength(FQuestions, Length(FQuestions)+1);
FQuestions[High(FQuestions)] := Result;
end;
function TFlashPage.DataCount: Integer;
begin
Result := Length(FData);
end;
function TFlashPage.QuestionCount: Integer;
begin
Result := Length(FQuestions);
end;
end.
|
unit FindUnit.FormSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ToolsAPI, Menus, SyncObjs,
FindUnit.EnvironmentController, StrUtils, AppEvnts, Buttons, ShellAPI, FindUnit.Header, FindUnit.FileEditor;
type
TFuncBoolean = function: Boolean of object;
TFuncString = function: string of object;
TfrmFindUnit = class(TForm)
grpOptions: TGroupBox;
chkSearchLibraryPath: TCheckBox;
chkSearchProjectFiles: TCheckBox;
grpResult: TGroupBox;
lstResult: TListBox;
grpSearch: TGroupBox;
edtSearch: TEdit;
lblWhere: TLabel;
rbInterface: TRadioButton;
rbImplementation: TRadioButton;
aevKeys: TApplicationEvents;
tmrLoadedItens: TTimer;
lblProjectUnitsStatus: TLabel;
lblLibraryUnitsStatus: TLabel;
btnRefreshProject: TSpeedButton;
btnRefreshLibraryPath: TSpeedButton;
btnAdd: TButton;
btnProcessDCUs: TSpeedButton;
pnlMsg: TPanel;
lblMessage: TLabel;
chkMemorize: TCheckBox;
procedure FormShow(Sender: TObject);
procedure edtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnAddClick(Sender: TObject);
procedure edtSearchChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lstResultDblClick(Sender: TObject);
procedure edtSearchClick(Sender: TObject);
procedure aevKeysMessage(var Msg: tagMSG; var Handled: Boolean);
procedure tmrLoadedItensTimer(Sender: TObject);
procedure chkSearchProjectFilesClick(Sender: TObject);
procedure chkSearchLibraryPathClick(Sender: TObject);
procedure btnRefreshProjectClick(Sender: TObject);
procedure btnRefreshLibraryPathClick(Sender: TObject);
procedure btnProcessDCUsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FEnvControl: TEnvironmentController;
FFileEditor: TSourceFileEditor;
procedure AddUnit;
procedure ProcessKeyCommand(var Msg: tagMSG; var Handled: Boolean);
procedure CheckLoadingStatus(Func: TFuncBoolean; FuncStatus: TFuncString; LabelDesc: TLabel; RefreshButton: TSpeedButton);
procedure CheckLibraryStatus;
procedure FilterItemFromSearchString;
procedure SaveConfigs;
procedure LoadConfigs;
procedure SelectTheMostSelectableItem;
procedure ProcessDCUFiles;
function CanProcessDCUFiles: Boolean;
procedure ShowMessageToMuchResults(Show: Boolean);
procedure LoadCurrentFile;
procedure GetSelectedItem(out UnitName, ClassName: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetEnvControl(EnvControl: TEnvironmentController);
procedure SetSearch(Filter: TStringPosition);
procedure FilterItem(const SearchString: string);
procedure ShowTextOnScreen(Text: string);
end;
var
frmFindUnit: TfrmFindUnit;
implementation
uses
FindUnit.OTAUtils, FindUnit.Utils, FindUnit.FormMessage, FindUnit.DcuDecompiler;
{$R *.dfm}
const
IDCONT = '1';
SEARCH_MESSAGE = 'Type your search...';
var
CONFIG_SearchOnProjectUnits: Boolean;
CONFIG_SearchOnLibraryPath: Boolean;
procedure TfrmFindUnit.ShowTextOnScreen(Text: string);
var
MsgForm: TfrmMessage;
begin
MsgForm := TfrmMessage.Create(nil);
if rbInterface.Checked then
Text := 'Unit ' + Text + ' added to interface''s uses.'
else
Text := 'Unit ' + Text + ' added to implementation''s uses.';
MsgForm.ShowMessage(Text);
SetFocus;
end;
procedure TfrmFindUnit.AddUnit;
var
SelectedUnit: string;
SelectedClass: string;
begin
GetSelectedItem(SelectedUnit, SelectedClass);
if SelectedUnit = '' then
Exit;
ShowTextOnScreen(SelectedUnit);
if rbInterface.Checked then
FFileEditor.AddUsesToInterface(SelectedUnit)
else
FFileEditor.AddUsesToImplementation(SelectedUnit);
if chkMemorize.Checked then
FEnvControl.AutoImport.SetMemorizedUnit(SelectedClass, SelectedUnit);
Close;
end;
procedure TfrmFindUnit.aevKeysMessage(var Msg: tagMSG; var Handled: Boolean);
begin
if Msg.message = WM_KEYDOWN then
ProcessKeyCommand(Msg, Handled);
end;
procedure TfrmFindUnit.btnAddClick(Sender: TObject);
begin
AddUnit;
end;
procedure TfrmFindUnit.btnProcessDCUsClick(Sender: TObject);
begin
if CanProcessDCUFiles then
ProcessDCUFiles;
end;
function TfrmFindUnit.CanProcessDCUFiles: Boolean;
const
MESGEM = 'The dcu32int.exe was not found. It should be at %s . If you download the projectīs source you will '
+ 'find it at {PATH}\RFindUnit\Thirdy\Dcu32Int\dcu32int.exe . Copy the executable and past it on the %s, and '
+ 'try execute this command again. If you donīt know where to find this executable I can send you '
+ 'to the project page, do you want I open it to you ?';
var
ForMessage: string;
MesDlg: TForm;
begin
Result := True;
if Dcu32IntExecutableExists then
Exit;
Result := False;
ForMessage := GetDcu32ExecutablePath;
ForMessage := Format(MESGEM, [ForMessage, ForMessage]);
MesDlg := CreateMessageDialog(ForMessage, mtError, [mbCancel, mbYes]);
try
MesDlg.Width := 900;
MesDlg.Position := poScreenCenter;
MesDlg.ShowModal;
if MesDlg.ModalResult <> mrYes then
Exit;
finally
MesDlg.Free;
end;
ShellExecute(0, 'open', PChar('https://github.com/rfrezino/RFindUnit/'), nil, nil, SW_SHOWNORMAL);
end;
procedure TfrmFindUnit.ProcessDCUFiles;
const
MESGEM = 'This command will list all the DCUs files that you donīt have access to .PAS '
+ ' and process it to make it available for search.'
+ ' This process will slowdown your computer and can take some minutes (~2), '
+ ' are you sure that you want to run it now ?';
begin
if MessageDlg(MESGEM, mtWarning, [mbCancel, mbYes], 0) <> mrYes then
Exit;
btnProcessDCUs.Enabled := False;
FEnvControl.ProcessDCUFiles;
end;
procedure TfrmFindUnit.btnRefreshLibraryPathClick(Sender: TObject);
begin
try
FEnvControl.LoadLibraryPath;
CheckLibraryStatus;
except
on E: exception do
MessageDlg('btnRefreshLibraryPathClick Error: ' + e.Message, mtError, [mbOK], 0);
end;
end;
procedure TfrmFindUnit.btnRefreshProjectClick(Sender: TObject);
begin
try
FEnvControl.LoadProjectPath;
CheckLibraryStatus;
except
on E: exception do
MessageDlg('btnRefreshProjectClick Error: ' + e.Message, mtError, [mbOK], 0);
end;
end;
procedure TfrmFindUnit.CheckLoadingStatus(Func: TFuncBoolean; FuncStatus: TFuncString; LabelDesc: TLabel; RefreshButton: TSpeedButton);
var
NewCaption: string;
begin
NewCaption := '';
if Func then
begin
RefreshButton.Visible := True;
LabelDesc.Visible := False;
end
else
begin
LabelDesc.Visible := True;
RefreshButton.Visible := False;
NewCaption := FuncStatus;
LabelDesc.Font.Color := $000069D2;
LabelDesc.Font.Style := [fsItalic];
end;
if NewCaption <> LabelDesc.Caption then
begin
FilterItemFromSearchString;
LabelDesc.Caption := NewCaption;
end;
end;
procedure TfrmFindUnit.chkSearchLibraryPathClick(Sender: TObject);
begin
FilterItemFromSearchString;
end;
procedure TfrmFindUnit.chkSearchProjectFilesClick(Sender: TObject);
begin
FilterItemFromSearchString;
end;
constructor TfrmFindUnit.Create(AOwner: TComponent);
begin
inherited;
LoadCurrentFile;
end;
destructor TfrmFindUnit.Destroy;
begin
FFileEditor.Free;
inherited;
end;
procedure TfrmFindUnit.edtSearchChange(Sender: TObject);
begin
FilterItemFromSearchString;
end;
procedure TfrmFindUnit.edtSearchClick(Sender: TObject);
begin
if edtSearch.Text = SEARCH_MESSAGE then
edtSearch.SelectAll;
end;
procedure TfrmFindUnit.edtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_RETURN) then
AddUnit
else if (Key = VK_ESCAPE) then
Close;
end;
procedure TfrmFindUnit.ShowMessageToMuchResults(Show: Boolean);
begin
pnlMsg.Visible := Show;
lblMessage.Caption := ' There are to many results on your search, I''m not showing everything. Type a bigger search.' + #13#10 +
'Remember that you can create incremental searchs like: "string replace", I''m going to look for the arguments separataly.'
end;
procedure TfrmFindUnit.FilterItem(const SearchString: string);
var
Return: TStringList;
ResultSearch: TStringList;
ToMuchResults: Boolean;
procedure IsThereToMuchResults;
begin
if Return.Count >= MAX_RETURN_ITEMS then
ToMuchResults := True;
end;
begin
ToMuchResults := False;
lstResult.Items.BeginUpdate;
ResultSearch := TStringList.Create;
try
lstResult.Clear;
if (SearchString = '') or (FEnvControl = nil) then
Exit;
if chkSearchProjectFiles.Checked then
begin
Return := FEnvControl.GetProjectUnits(SearchString);
ResultSearch.Text := ResultSearch.Text + Return.Text;
IsThereToMuchResults;
Return.Free;
end;
if chkSearchLibraryPath.Checked then
begin
Return := FEnvControl.GetLibraryPathUnits(SearchString);
ResultSearch.Text := ResultSearch.Text + Return.Text;
IsThereToMuchResults;
Return.Free;
end;
ResultSearch.Sorted := True;
lstResult.Items.Text := ResultSearch.Text;
SelectTheMostSelectableItem;
ShowMessageToMuchResults(ToMuchResults);
lstResult.Count
finally
ResultSearch.Free;
lstResult.Items.EndUpdate;
end;
end;
procedure TfrmFindUnit.FilterItemFromSearchString;
begin
try
FilterItem(edtSearch.Text);
except
ShowMessage('FilterItemFromSearchString');
end;
end;
procedure TfrmFindUnit.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SaveConfigs;
Action := caFree;
frmFindUnit := nil;
end;
procedure TfrmFindUnit.FormCreate(Sender: TObject);
begin
Caption := 'Find Uses - Version ' + VERSION_STR;
end;
procedure TfrmFindUnit.FormShow(Sender: TObject);
begin
edtSearch.SelectAll;
edtSearch.SetFocus;
LoadConfigs;
end;
procedure TfrmFindUnit.GetSelectedItem(out UnitName, ClassName: string);
var
I: Integer;
function CorrectUses(Item: string): string;
begin
Result := Item;
Result := Trim(Fetch(Result, '-'));
Result := ReverseString(Result);
ClassName := Fetch(Result,'.');
ClassName := ReverseString(ClassName);
Result := ReverseString(Result);
end;
begin
UnitName := '';
if lstResult.Count = 0 then
Exit;
for I := 0 to lstResult.Items.Count -1 do
begin
if lstResult.Selected[i] then
begin
UnitName := CorrectUses(lstResult.Items[i]);
Exit;
end;
end;
UnitName := CorrectUses(lstResult.Items[0])
end;
procedure TfrmFindUnit.LoadConfigs;
begin
chkSearchLibraryPath.Checked := CONFIG_SearchOnLibraryPath;
chkSearchProjectFiles.Checked := CONFIG_SearchOnProjectUnits;
end;
procedure TfrmFindUnit.LoadCurrentFile;
var
CurEditor: IOTASourceEditor;
begin
CurEditor := OtaGetCurrentSourceEditor;
FFileEditor := TSourceFileEditor.Create(CurEditor);
FFileEditor.Prepare;
end;
procedure TfrmFindUnit.lstResultDblClick(Sender: TObject);
begin
AddUnit;
Close;
end;
procedure TfrmFindUnit.ProcessKeyCommand(var Msg: tagMSG; var Handled: Boolean);
const
MOVE_COMMANDS = [VK_UP, VK_DOWN];
function IsCtrlA: Boolean;
begin
Result := (GetKeyState(VK_CONTROL) < 0) and (Char(Msg.wParam) = 'A');
end;
begin
if (Msg.wParam in MOVE_COMMANDS) then
begin
Msg.hwnd := lstResult.Handle;
lstResult.SetFocus;
end
else
begin
Msg.hwnd := edtSearch.Handle;
edtSearch.SetFocus;
if IsCtrlA then
edtSearch.SelectAll;
end;
end;
procedure TfrmFindUnit.SaveConfigs;
begin
CONFIG_SearchOnProjectUnits := chkSearchProjectFiles.Checked;
CONFIG_SearchOnLibraryPath := chkSearchLibraryPath.Checked;
end;
procedure TfrmFindUnit.SelectTheMostSelectableItem;
var
SmallItemId: Integer;
SmallItemLength: Integer;
I: Integer;
List: TStrings;
PosSize: Integer;
begin
SmallItemLength := 999999;
SmallItemId := -1;
List := lstResult.Items;
if List.Count = 0 then
Exit;
for I := 0 to List.Count -1 do
begin
PosSize := Pos('-', List[i]);
if PosSize < SmallItemLength then
begin
SmallItemLength := PosSize;
SmallItemId := I;
end;
end;
lstResult.Selected[SmallItemId] := True;
end;
procedure TfrmFindUnit.SetEnvControl(EnvControl: TEnvironmentController);
begin
FEnvControl := EnvControl;
CheckLibraryStatus;
end;
procedure TfrmFindUnit.SetSearch(Filter: TStringPosition);
begin
rbInterface.Checked := not FFileEditor.IsLineOnImplementationSection(Filter.Line);
rbImplementation.Checked := FFileEditor.IsLineOnImplementationSection(Filter.Line);
if (Filter.Value = '') or (Pos(#13#10, Filter.Value) > 0) then
Exit;
edtSearch.Text := Filter.Value;
end;
procedure TfrmFindUnit.CheckLibraryStatus;
begin
btnProcessDCUs.Enabled := not FEnvControl.ProcessingDCU;
CheckLoadingStatus(FEnvControl.IsProjectsUnitReady, FEnvControl.GetProjectPathStatus, lblProjectUnitsStatus, btnRefreshProject);
CheckLoadingStatus(FEnvControl.IsLibraryPathsUnitReady, FEnvControl.GetLibraryPathStatus, lblLibraryUnitsStatus, btnRefreshLibraryPath);
end;
procedure TfrmFindUnit.tmrLoadedItensTimer(Sender: TObject);
begin
CheckLibraryStatus;
end;
procedure LoadInitialConfigs;
begin
CONFIG_SearchOnProjectUnits := True;
CONFIG_SearchOnLibraryPath := True;
end;
initialization
LoadInitialConfigs;
end.
|
{********************************************************************}
{ TInspectorImage component }
{ for Delphi & C++Builder }
{ }
{ written }
{ TMS Software }
{ copyright © 2000 - 2012 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{ }
{ The source code is given as is. The author is not responsible }
{ for any possible damage done due to the use of this code. }
{ The component can be freely used in any application. The source }
{ code remains property of the writer and may not be distributed }
{ freely as such. }
{********************************************************************}
unit InspImg;
{$I TMSDEFS.INC}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ComObj,
ActiveX;
type
TInspImage = class(TGraphic)
private
{ Private declarations }
FDatastream: TMemoryStream;
FIsEmpty: Boolean;
gpPicture: IPicture;
FLogPixX,FLogPixY: Integer;
procedure LoadPicture;
protected
{ Protected declarations }
function GetEmpty: Boolean; override;
function GetHeight: integer; override;
function GetWidth: integer; override;
procedure SetHeight(Value: integer); override;
procedure SetWidth(Value: integer); override;
procedure ReadData(Stream: TStream); override;
procedure WriteData(Stream: TStream); override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
public
{ Public declarations }
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromFile(const FileName: string); override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE); override;
procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE); override;
procedure LoadFromResourceName(Instance: THandle; const ResName: String);
procedure LoadFromResourceID(Instance: THandle; ResID: Integer);
published
{ Published declarations }
end;
implementation
const
HIMETRIC_INCH = 2540;
{ TInspImage }
procedure TInspImage.Assign(Source: TPersistent);
begin
FIsEmpty := True;
gpPicture := nil;
if Source = nil then
begin
FDataStream.Clear;
if assigned(OnChange) then OnChange(self);
end
else
begin
if (Source is TInspImage) then
begin
FDataStream.LoadFromStream(TInspImage(Source).fDataStream);
FIsEmpty := False;
LoadPicture;
if Assigned(OnChange) then OnChange(self);
end;
end;
end;
constructor TInspImage.Create;
begin
inherited;
FDataStream := TMemoryStream.Create;
FIsEmpty := True;
gpPicture := nil;
FLogPixX := 96;
FLogPixY := 96;
end;
destructor TInspImage.Destroy;
begin
FDataStream.Free;
inherited;
end;
procedure TInspImage.LoadPicture;
const
IID_IPicture: TGUID = (
D1:$7BF80980;D2:$BF32;D3:$101A;D4:($8B,$BB,$00,$AA,$00,$30,$0C,$AB));
var
hGlobal: THandle;
pvData: Pointer;
pstm: IStream;
hr: HResult;
begin
hGlobal := GlobalAlloc(GMEM_MOVEABLE, fDataStream.Size);
if (hGlobal = 0) then
raise Exception.Create('Could not allocate memory for image');
pvData := GlobalLock(hGlobal);
FDataStream.Position := 0;
FDataStream.ReadBuffer(pvData^,fDataStream.Size);
GlobalUnlock(hGlobal);
pstm := nil;
// create IStream* from global memory
hr := CreateStreamOnHGlobal(hGlobal, TRUE, pstm);
if (not hr = S_OK) then
raise Exception.Create('Could not create image stream')
else
if (pstm = nil) then
raise Exception.Create('Empty image stream created');
// Create IPicture from image file
hr := OleLoadPicture(pstm,
fDataStream.Size,
FALSE,
IID_IPicture,
gpPicture);
if (not (hr = S_OK)) then raise Exception.Create('Could not load image. Invalid format')
else if (gpPicture = nil) then
raise Exception.Create('Could not load image');
end;
procedure TInspImage.Draw(ACanvas: TCanvas; const Rect: TRect);
var
hmWidth: Integer;
hmHeight: Integer;
begin
if Empty then Exit;
if (gpPicture = nil) then Exit;
hmWidth := 0;
hmHeight := 0;
gpPicture.get_Width(hmWidth);
gpPicture.get_Height(hmHeight);
gpPicture.Render(ACanvas.Handle,rect.Left,rect.Top,rect.Right - rect.Left,(rect.Bottom - rect.Top),0,hmHeight,
hmWidth,-hmHeight,rect);
end;
function TInspImage.GetEmpty: Boolean;
begin
Result := FIsEmpty;
end;
function TInspImage.GetHeight: integer;
var
hmHeight: Integer;
hScreenDC: HDC;
begin
if gpPicture = nil then
Result := 0
else
begin
hScreenDC := GetDC(0);
gpPicture.get_Height(hmHeight);
Result := MulDiv(hmHeight, GetDeviceCaps(hScreenDC, LOGPIXELSY), HIMETRIC_INCH);
ReleaseDC(0, hScreenDC);
end;
end;
function TInspImage.GetWidth: Integer;
var
hmWidth: Integer;
hScreenDC: HDC;
begin
if gpPicture = nil then
Result := 0
else
begin
hScreenDC := GetDC(0);
gpPicture.get_Width(hmWidth);
Result := MulDiv(hmWidth, GetDeviceCaps(hScreenDC, LOGPIXELSX), HIMETRIC_INCH);
ReleaseDC(0, hScreenDC);
end;
end;
procedure TInspImage.LoadFromFile(const FileName: string);
begin
try
FDataStream.LoadFromFile(Filename);
FIsEmpty := False;
LoadPicture;
if Assigned(OnChange) then OnChange(self);
except
FIsEmpty := True;
end;
end;
procedure TInspImage.LoadFromStream(Stream: TStream);
begin
if Assigned(Stream) then
begin
FDataStream.LoadFromStream(Stream);
FIsEmpty := False;
LoadPicture;
if Assigned(OnChange) then OnChange(self);
end;
end;
procedure TInspImage.LoadFromResourceName(Instance: THandle; const ResName: string);
var
Stream: TCustomMemoryStream;
begin
Stream := TResourceStream.Create(Instance, ResName, RT_RCDATA);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TInspImage.LoadFromResourceID(Instance: THandle; ResID: Integer);
var
Stream: TCustomMemoryStream;
begin
Stream := TResourceStream.CreateFromID(Instance, ResID, RT_RCDATA);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TInspImage.ReadData(Stream: TStream);
begin
if Assigned(Stream) then
begin
FDataStream.LoadFromStream(Stream);
FIsEmpty := False;
LoadPicture;
end;
end;
procedure TInspImage.SaveToStream(Stream: TStream);
begin
if Assigned(Stream) then FDataStream.SaveToStream(Stream);
end;
procedure TInspImage.SetHeight(Value: integer);
begin
end;
procedure TInspImage.SetWidth(Value: integer);
begin
end;
procedure TInspImage.WriteData(Stream: TStream);
begin
if assigned(Stream) then
begin
FDataStream.SaveToStream(stream);
end;
end;
procedure TInspImage.LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE);
begin
end;
procedure TInspImage.SaveToClipboardFormat(var AFormat: Word;
var AData: THandle; var APalette: HPALETTE);
begin
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: Common definitions for TSysLogClient and TSysLogServer classes.
See RFC3164 for reference.
Creation: September 2009
Version: 1.01
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2009 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software 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.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
Feb 08, 2010 V1.01 F. Piette renamed NILVALUE to SYSLOG_NILVALUE it here from
the client component so that it can be used from server
component.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsSysLogDefs;
interface
type
// Facility (See RFC 3164)
TSysLogFacility = (
SYSLOG_FACILITY_KERNEL = 0, // kernel messages
SYSLOG_FACILITY_USER = 1, // user-level messages
SYSLOG_FACILITY_MAIL = 2, // mail system
SYSLOG_FACILITY_SYS_DAEMON = 3, // system daemons
SYSLOG_FACILITY_SECURITY1 = 4, // security/authorization messages (note 1)
SYSLOG_FACILITY_INTERNAL = 5, // messages generated internally by syslogd
SYSLOG_FACILITY_LPR = 6, // line printer subsystem
SYSLOG_FACILITY_NNTP = 7, // network news subsystem
SYSLOG_FACILITY_UUCP = 8, // UUCP subsystem
SYSLOG_FACILITY_CLOCK1 = 9, // clock daemon (note 1)
SYSLOG_FACILITY_SECURITY2 = 10, // security/authorization messages (note 2)
SYSLOG_FACILITY_FTP = 11, // FTP daemon
SYSLOG_FACILITY_NTP = 12, // NTP subsystem
SYSLOG_FACILITY_AUDIT = 13, // log audit (note 1)
SYSLOG_FACILITY_ALERT = 14, // log alert (note 1)
SYSLOG_FACILITY_CLOCK2 = 15, // clock daemon (note 2)
SYSLOG_FACILITY_LOCAL0 = 16, // local use 0 (local0)
SYSLOG_FACILITY_LOCAL1 = 17, // local use 1 (local1)
SYSLOG_FACILITY_LOCAL2 = 18, // local use 2 (local2)
SYSLOG_FACILITY_LOCAL3 = 19, // local use 3 (local3)
SYSLOG_FACILITY_LOCAL4 = 20, // local use 4 (local4)
SYSLOG_FACILITY_LOCAL5 = 21, // local use 5 (local5)
SYSLOG_FACILITY_LOCAL6 = 22, // local use 6 (local6)
SYSLOG_FACILITY_LOCAL7 = 23 // local use 7 (local7)
);
const
SysLogFacilityString : array [TSysLogFacility] of String = (
'KERNEL', 'USER', 'MAIL', 'SYS_DAEMON',
'SECURITY1', 'INTERNAL', 'LPR', 'NNTP',
'UUCP', 'CLOCK1', 'SECURITY2', 'FTP',
'NTP', 'AUDIT', 'ALERT', 'CLOCK2',
'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3',
'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7');
type
// Note 1 - Various operating systems have been found to utilize
// Facilities 4, 10, 13 and 14 for security/authorization,
// audit, and alert messages which seem to be similar.
// Note 2 - Various operating systems have been found to utilize
// both Facilities 9 and 15 for clock (cron/at) messages.
// Severity (See RFC 3164)
TSysLogSeverity = (
SYSLOG_SEVERITY_EMERGENCY = 0, // Emergency: system is unusable
SYSLOG_SEVERITY_ALERT = 1, // Alert: action must be taken immediately
SYSLOG_SEVERITY_CRITICAL = 2, // Critical: critical conditions
SYSLOG_SEVERITY_ERROR = 3, // Error: error conditions
SYSLOG_SEVERITY_WARNING = 4, // Warning: warning conditions
SYSLOG_SEVERITY_NOTICE = 5, // Notice: normal but significant condition
SYSLOG_SEVERITY_INFORMATIONAL = 6, // Informational: informational messages
SYSLOG_SEVERITY_DEBUG = 7 // Debug: debug-level messages
);
const
SysLogSeverityString : array [TSysLogSeverity] of String = (
'EMERGENCY', 'ALERT', 'CRITICAL', 'ERROR',
'WARNING', 'NOTICE', 'INFORMATIONAL', 'DEBUG');
const
SysLogMonthNames : array [1..12] of string = (
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
const
// The next constant is specific to RFC 5424
SYSLOG_NILVALUE = '-'; // Empty value
implementation
end.
|
unit ddMessageDlg;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls;
type
TALCUMessageDlg = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
cbLockBase: TCheckBox;
cbToAll: TCheckBox;
comboDefined: TComboBox;
dtpLockDate: TDateTimePicker;
dtpLockTime: TDateTimePicker;
dtpStartLockDate: TDateTimePicker;
dtpStartLockTime: TDateTimePicker;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure cbLockBaseClick(Sender: TObject);
procedure cbToAllClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function GetLockDateTime: TDateTime;
function GetStartLockDateTime: TDateTime;
public
DoLockBase: Boolean;
Text: string;
ToAllUsers: Boolean;
UserName: string;
function Execute: Boolean;
property LockDateTime: TDateTime read GetLockDateTime;
property StartLockDateTime: TDateTime read GetStartLockDateTime;
end;
var
ALCUMessageDlg: TALCUMessageDlg;
function GetALCUMessage(aUserName: String; var aMsg: String;
var aToAll, aLockBase: Boolean;
var aLockDateTime, aStartLock: TDateTime): Boolean;
implementation
{$R *.DFM}
Uses
l3IniFile,
DateUtils;
{
******************************* TALCUMessageDlg ********************************
}
procedure TALCUMessageDlg.cbLockBaseClick(Sender: TObject);
begin
(*
dtpLockTime.Enabled:= cbLockBase.Checked;
dtpLockDate.Enabled:= cbLockBase.Checked;
*)
GroupBox1.Enabled:= cbLockBase.Checked;
end;
procedure TALCUMessageDlg.cbToAllClick(Sender: TObject);
begin
if cbToAll.Checked then
Caption:= 'Сообщение для всех пользователей'
else
Caption:= Format('Сообщение для %s', [UserName]);
cbLockBase.Enabled:= cbToAll.Checked;
ToAllUsers:= cbToAll.Checked;
end;
function TALCUMessageDlg.Execute: Boolean;
var
l_Texts: TStringList;
S: string;
begin
Caption:= Format('Сообщение для %s', [UserName]);
comboDefined.ItemIndex:= -1;
// прочитать новые элементы из ини-файла
with StationConfig do
try
l_Texts:= TStringList.Create;
try
Section := 'MessageList';
ReadSectionValues(l_Texts);
comboDefined.Items.AddStrings(l_Texts);
S:= IntToStr(l_Texts.Count);
finally
l_Texts.Free;
end;
except
end;
dtpStartLockTime.Time:= Time;
dtpStartLockDate.Date:= Date;
dtpLockTime.Time:= IncMinute(Time, 30);
dtpLockDate.Date:= Date;
Result:= ShowModal = mrOk;
if Result then
begin
Text:= comboDefined.Text;
DoLockBase:= cbLockBase.Checked;
if comboDefined.Items.IndexOf(Text) = -1 then // добавить новый текст в ини-файл
StationConfig.WriteParamStr(S, Text);
end; // Result
end;
procedure TALCUMessageDlg.FormCreate(Sender: TObject);
begin
UserName:= 'всех пользователей';
end;
function TALCUMessageDlg.GetLockDateTime: TDateTime;
begin
Result:= dtpLockDate.Date;
ReplaceTime(Result, dtpLockTime.Time)
end;
function TALCUMessageDlg.GetStartLockDateTime: TDateTime;
begin
Result:= dtpStartLockDate.Date;
ReplaceTime(Result, dtpStartLockTime.Time)
end;
function GetALCUMessage(aUserName: String; var aMsg: String;
var aToAll, aLockBase: Boolean;
var aLockDateTime, aStartLock: TDateTime): Boolean;
begin
with TALCUMessageDlg.Create(Application) do
try
UserName:= aUserName;
if Execute then
begin
Result:= True;
aMsg:= Text;
aToAll:= ToAllUsers;
aLockBase:= DoLockBase;
aLockDateTime:= LockDateTime;
aStartLock:= StartLockDateTime;
end
else
Result:= False;
finally
Free;
end;
end;
end.
|
{ Subroutine SST_R_PAS_EXP_SYM (SYM_P)
*
* Process EXPRESSION syntax and return the pointer to the symbol that formed
* the expression. It is an error if the expression was more complex than just
* a symbol. The symbol will automatically be flagged as used.
}
module sst_r_pas_EXP_SYM;
define sst_r_pas_exp_sym;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_exp_sym ( {point to symbol that is EXPRESSION}
out sym_p: sst_symbol_p_t); {error if EXPRESSION is not just one symbol}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
stat: sys_err_t; {completion status code}
label
not_symbol;
begin
syo_level_down; {down into EXPRESSION syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0);
syo_level_down; {down into EXPRESSION2 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0);
syo_level_down; {down into EXPRESSION3 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0);
syo_level_down; {down into EXPRESSION4 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0);
syo_level_down; {down into ITEM syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {unadic op tag}
if tag <> 1 then goto not_symbol;
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {operand type tag}
if tag <> 6 then goto not_symbol;
syo_level_down; {down into VARIABLE syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {variable name tag}
sst_symbol_lookup (str_h, sym_p, stat);
syo_error_abort (stat, str_h, '', '', nil, 0);
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to ITEM syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag in ITEM}
if tag <> 1 then goto not_symbol;
syo_level_up; {back up to EXPRESSION4 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to EXPRESSION3 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to EXPRESSION2 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to EXPRESSION1 syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to EXPRESSION syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get next tag if there}
if tag <> syo_tag_end_k then goto not_symbol;
syo_level_up; {back up to caller's syntax}
sym_p^.flags := sym_p^.flags + [sst_symflag_used_k];
return;
not_symbol: {jump here if expression not just a symbol}
syo_error (str_h, 'sst_pas_read', 'exp_not_symbol', nil, 0);
end;
|
unit osClientDataset;
interface
uses
sysutils, classes, dbtables, typinfo, contnrs, dbclient, dialogs,
db, provider, variants;
type
TosClientDataset = class(TClientDataset)
private
FDataProvider : TCustomProvider;
FIDHighValue: integer;
FIDLowValue: integer;
FIDField: TField;
FRootClientDS: TosClientDataset;
//FOnUserReconcileError: TReconcileErrorEvent;
FClosedLookup: boolean;
FDataLink: TDataLink;
FHasKey: boolean;
FBizDatamoduleName: string;
FIDName: string;
FDeleteDetails: boolean;
procedure InitAppServer;
procedure SetDataProvider(Value : TCustomProvider);
procedure SetClosedLookup(const Value: boolean);
procedure RefreshParams;
function GetMasterDataSource: TDataSource;
procedure SetMasterDataSource(const Value: TDataSource);
function GetHasKey: boolean;
function GetIDField: TField;
function GetQuotedString(const PStr: string): string;
procedure ClearDataSet(DataSet: TDataSet);
procedure ClearDetails(DataSet: TDataSet);
protected
FClearing : boolean;
procedure Notification(AComponent : TComponent; Operation : TOperation); override;
procedure DoBeforePost; override;
procedure DoOnNewRecord; override;
procedure DoBeforeOpen; override;
procedure DoBeforeDelete; override;
procedure OpenCursor(InfoQuery: Boolean = False); override;
{procedure HandleReconcileError(DataSet: TClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction); }
procedure Loaded; override;
property RootClientDS: TosClientDataset read FRootClientDS;
property DataLink: TDataLink read FDataLink;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetNewID: integer;
procedure RefreshCalcFields;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant; override;
procedure GetRecordByID(const PID: integer);
procedure CloseCursor; override;
procedure Post; override;
//procedure LoadFromDataset(PDataset: TDataset);
property IDField: TField read GetIDField;
published
property DataProvider : TCustomProvider read FDataProvider write SetDataProvider;
property ClosedLookup: boolean read FClosedLookup write SetClosedLookup default False;
property MasterDataSource: TDataSource read GetMasterDataSource write SetMasterDataSource;
property HasKey: boolean read GetHasKey;
property BizDatamoduleName: string read FBizDatamoduleName write FBizDatamoduleName;
property IDName: string read FIDName write FIDName;
property DeleteDetails: boolean read FDeleteDetails write FDeleteDetails default True;
property Active stored False;
end;
// Utilizada para estabelecer relacionamentos mestre-detalhe
TccClientDataLink = class(TDetailDataLink)
private
FClientDataset: TosClientDataset;
protected
procedure ActiveChanged; override;
procedure RecordChanged(Field: TField); override;
function GetDetailDataSet: TDataSet; override;
procedure CheckBrowseMode; override;
public
constructor Create(AClientDataset: TosClientDataset);
end;
TStringListExt = class(TStringList)
private
FElementFormat: string;
FSeparator: string;
function GetAsFmtText: string;
procedure SetElementFormat(const Value: string);
procedure SetSeparator(const Value: string);
public
constructor Create; virtual;
procedure PrepareForID;
published
property Separator: string read FSeparator write SetSeparator;
property ElementFormat: string read FElementFormat write SetElementFormat;
property AsFmtText: string read GetAsFmtText;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('OS Controls', [TosClientDataset]);
end;
{ TosClientDataset }
procedure TosClientDataset.CloseCursor;
begin
inherited CloseCursor;
if Assigned(DataProvider) then // Only reset AppServer if we're using a local connection
InitAppServer;
end;
constructor TosClientDataset.Create(AOwner: TComponent);
begin
inherited;
FIDHighValue := -1;
FIDLowValue := 0;
FClosedLookup := False;
FetchOnDemand := False;
FDataLink := TccClientDataLink.Create(Self);
FIDField := nil;
FHasKey := False;
FClearing := False;
FDeleteDetails := True;
end;
destructor TosClientDataset.Destroy;
begin
FDataLink.Free;
inherited;
end;
procedure TosClientDataset.DoBeforeOpen;
begin
inherited;
if Assigned(DatasetField) then
if Assigned(TosClientDataset(DatasetField.Dataset).RootClientDS) then
FRootClientDS := TosClientDataset(DatasetField.Dataset).RootClientDS
else
FRootClientDS := TosClientDataset(DatasetField.Dataset);
end;
procedure TosClientDataset.DoOnNewRecord;
begin
if Assigned(FIDField) then
FIDField.Value := GetNewID;
//FIDField.AsString := IntToHex(GetNewID, 12);
inherited;
end;
function TosClientDataset.GetHasKey: boolean;
begin
Result := Assigned(IDField);
end;
function TosClientDataset.GetMasterDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
function TosClientDataset.GetNewID: integer;
var
v: variant;
vCmd: OleVariant;
sName: string;
begin
// Se estourou a faixa, lê um novo HighValue
if Assigned(FRootClientDS) then // Se é detalhe pede o valor para o "raiz"
Result := FRootClientDS.GetNewID
else // é o raiz, fornece o valor
begin
if (FIDLowValue = 10) or (FIDHighValue = -1) then
begin
sName := IDName;
if sName = '' then
sName := 'Geral';
vCmd := VarArrayOf(['_CMD','GET_IDHIGH',sName]);
v := DataRequest(vCmd);
if v = NULL then
raise Exception.Create('Não conseguiu obter o ID do server para inclusão');
FIDHighValue := v; // por convenção
FIDLowValue := 0;
end;
Result := FIDHighValue * 10 + FIDLowValue;
Inc(FIDLowValue);
end;
end;
function TosClientDataset.GetIDField: TField;
var
i: integer;
begin
if not Assigned(FIDField) then
begin
for i:=0 to Fields.Count-1 do
if pfInKey in Fields[i].ProviderFlags then
begin
FIDField := Fields[i];
break;
end;
if not Assigned(FIDField) then
FIDField := FindField('ID');
end;
Result := FIDField;
end;
procedure TosClientDataset.GetRecordByID(const PID: integer);
begin
if Assigned(FIDField) then
begin
Close;
Params.ParamByName('ID').AsInteger := PID;
Open;
end;
end;
{
procedure TosClientDataset.HandleReconcileError(DataSet: TClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
begin
if Assigned(FOnUserReconcileError) then
FOnUserReconcileError(DataSet, E, UpdateKind, Action);
ShowMessage(E.Message);
end;
}
procedure TosClientDataset.InitAppServer;
begin
try
if FDataProvider is TCustomProvider then
AppServer := TLocalAppServer.Create(TCustomProvider(FDataProvider))
else
AppServer := TLocalAppServer.Create(TDataset(FDataProvider));
except
on EDatabaseError do
Abort;
end;
end;
procedure TosClientDataset.Loaded;
//var
// TempParam: TParam;
// TempComp: TComponent;
begin
inherited;
{
if (not Assigned(DataProvider)) and (Trim(BizDatamoduleName)<>'') then
begin
TempComp := GetComponentByName(GetDatamoduleByName(BizDatamoduleName),'prvMaster', TCustomProvider);
if Assigned(Tempcomp) then
DataProvider := TCustomProvider(TempComp);
end;
}
{
if Assigned(OnReconcileError) then
FOnUserReconcileError := OnReconcileError;
OnReconcileError := HandleReconcileError;
}
{ Ex de parâmetros automáticos
if cfEmpresa in FCustomFilterOptions then
begin
TempParam := Params.FindParam('Empresa');
if not Assigned(TempParam) then
TempParam := Params.CreateParam(ftString, 'Empresa', ptInput);
TempParam.AsString := GlobalEmpresa;
end;
}
end;
{
procedure TosClientDataset.LoadFromDataset(PDataset: TDataset);
var
prvTemp: TDataSetProvider;
bActive: boolean;
begin
bActive := PDataset.Active;
prvTemp := TDataSetProvider.Create(Self);
try
prvTemp.DataSet := PDataset;
if not bActive then
PDataset.Open;
Self.Data := prvTemp.Data;
if not bActive then
PDataset.Close;
finally
prvTemp.Free;
end;
end;
}
function TosClientDataset.Lookup(const KeyFields: string;
const KeyValues: Variant; const ResultFields: string): Variant;
var
Param: TParam;
begin
Result := Null;
if KeyValues <> Null then
begin
if FClosedLookup then
begin
//if not ((HasKey) and (KeyFields = IDField.FieldName)) then
// raise Exception.Create('Não é possivel fazer ClosedLookup de fields diferentes de ID.');
if IDField.AsString <> VarToStr(KeyValues) then // Se já estiver na memória
begin
Param := Params.FindParam(KeyFields);
if not Assigned(Param) then
raise Exception.CreateFmt('O parâmetro chave é necessário para se fazer ClosedLookup - Componente: %s', [Self.Name]);
Close;
Param.Value := KeyValues;
Open;
end;
if LocateRecord(KeyFields, KeyValues, [], False) then
begin
SetTempState(dsCalcFields);
try
CalculateFields(TempBuffer);
Result := FieldValues[ResultFields];
finally
RestoreState(dsBrowse);
end;
end;
end
else // Executa o lookup padrão (do ancestral), ou seja com os dados armazenados internamente
begin
Result := inherited Lookup(KeyFields, KeyValues, ResultFields);
end;
end;
end;
procedure TosClientDataset.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FDataProvider) then
AppServer := nil;
end;
procedure TosClientDataset.OpenCursor(InfoQuery: Boolean);
begin
inherited OpenCursor(InfoQuery);
if not InfoQuery then
GetIDField;
end;
procedure TosClientDataset.RefreshCalcFields;
begin
GetCalcFields(ActiveBuffer);
end;
procedure TosClientDataset.RefreshParams;
var
DataSet: TDataSet;
i: integer;
sFieldName: string;
begin
DisableControls;
try
if FDataLink.DataSource <> nil then
begin
DataSet := FDataLink.DataSource.DataSet;
if DataSet <> nil then
if DataSet.Active and (DataSet.State <> dsSetKey) then
begin
Close;
for i := 0 to Params.Count - 1 do
begin
sFieldName := Params[i].Name;
sFieldName := Trim(StringReplace(sFieldName, '*', '', []));
if not Dataset.FieldByName(sFieldName).IsNull then
Params[i].Value := Dataset.FieldByName(sFieldName).Value;
end;
Open;
end;
end;
finally
EnableControls;
end;
end;
procedure TosClientDataset.SetClosedLookup(const Value: boolean);
begin
FClosedLookup := Value;
end;
procedure TosClientDataset.SetDataProvider(Value: TCustomProvider);
begin
if Value <> FDataProvider then
begin
FDataProvider := Value;
{Calling FreeNotification ensures that this component will receive an}
{opRemove when Value is either removed from its owner or when it is destroyed.}
if FDataProvider <> nil then
begin
FDataProvider.FreeNotification(Self);
{Assign the provider from the host provider component to the ClientDataset (ourself)}
InitAppServer;
end
else
AppServer := nil;
end;
end;
procedure TosClientDataset.SetMasterDataSource(const Value: TDataSource);
begin
if IsLinkedTo(Value) then
DatabaseError('Referência circular', Self);
FDataLink.DataSource := Value;
end;
procedure TosClientDataset.DoBeforePost;
begin
inherited;
end;
procedure TosClientDataset.Post;
begin
try
inherited;
except
On E: EDatabaseError do
begin
if Pos('must have', E.Message) <> 0 then
raise Exception.Create('Obrigatório: ' + GetQuotedString(E.Message))
else
raise;
end;
end;
end;
function TosClientDataset.GetQuotedString(const PStr: string): string;
var
i, iLen: integer;
bCapture: boolean;
begin
Result := '';
bCapture := False;
iLen := Length(PStr);
for i:=1 to iLen do
if bCapture then
if PStr[i] <> '''' then
Result := Result + PStr[i]
else
break
else
if PStr[i] = '''' then
bCapture := True;
end;
procedure TosClientDataset.DoBeforeDelete;
begin
inherited;
if FDeleteDetails and not FClearing then
ClearDetails(Self);
if DataSetField <> nil then
DataSetField.DataSet.Edit;
end;
procedure TosClientDataset.ClearDataSet(DataSet: TDataSet);
begin
if DataSet is TosClientDataSet then
TosClientDataSet(DataSet).FClearing := True;
try
DataSet.First;
while not DataSet.Eof do
begin
ClearDetails(DataSet);
DataSet.Delete;
end;
finally
if DataSet is TosClientDataSet then
TosClientDataSet(DataSet).FClearing := False;
end;
end;
procedure TosClientDataset.ClearDetails(DataSet: TDataSet);
var
i: integer;
begin
for i := 0 to DataSet.FieldCount - 1 do
if ftDataSet = DataSet.Fields[i].DataType then
ClearDataSet(TDataSetField(DataSet.Fields[i]).NestedDataSet);
end;
{ TccClientDataLink }
procedure TccClientDataLink.ActiveChanged;
begin
if FClientDataset.Active then FClientDataset.RefreshParams;
end;
procedure TccClientDataLink.CheckBrowseMode;
begin
if FClientDataset.Active then FClientDataset.CheckBrowseMode;
end;
constructor TccClientDataLink.Create(AClientDataset: TosClientDataset);
begin
inherited Create;
FClientDataset := AClientDataset;
end;
function TccClientDataLink.GetDetailDataSet: TDataSet;
begin
Result := FClientDataset;
end;
procedure TccClientDataLink.RecordChanged(Field: TField);
begin
if (Field = nil) and FClientDataset.Active then FClientDataset.RefreshParams;
end;
{ TStringListExt }
constructor TStringListExt.Create;
begin
inherited;
FSeparator := '';
FElementFormat := '';
end;
function TStringListExt.GetAsFmtText: string;
var
i: integer;
sSep: string;
begin
Result := '';
sSep := '';
for i:=0 to Count - 1 do
begin
Result := Result + sSep + Format(FElementFormat, [Strings[i]]);
sSep := FSeparator;
end;
end;
procedure TStringListExt.PrepareForID;
begin
FSeparator := ',';
FElementFormat := '''%s''';
end;
procedure TStringListExt.SetElementFormat(const Value: string);
begin
FElementFormat := Value;
end;
procedure TStringListExt.SetSeparator(const Value: string);
begin
FSeparator := Value;
end;
end.
|
unit BooleanArray;
interface
type
PIntegerArray = ^TIntegerArray;
TIntegerArray = array[word] of integer;
type
TBooleanMatrix =
class
public
constructor Create(aRows, aCols : integer);
destructor Destroy; override;
private
fRows : integer;
fCols : integer;
fInfo : PIntegerArray;
function GetItem(i, j : integer) : boolean;
procedure SetItem(i, j : integer; which : boolean);
public
property Rows : integer read fRows;
property Cols : integer read fCols;
property Item[i, j : integer] : boolean read GetItem write SetItem; default;
procedure Clear;
procedure Fill;
function GetAddressOf(i, j : integer; out mask : integer) : PIntegerArray;
private
fSize : integer;
end;
implementation
// TBooleanMatrix.
const
cIntegerBits = 32;
constructor TBooleanMatrix.Create(aRows, aCols : integer);
begin
fSize := (aRows*aCols div cIntegerBits)*sizeof(integer);
fRows := aRows;
fCols := aCols;
getmem(fInfo, fSize);
Clear;
end;
destructor TBooleanMatrix.Destroy;
begin
freemem(fInfo);
inherited;
end;
function TBooleanMatrix.GetItem(i, j : integer) : boolean;
var
aux : integer;
begin
assert((i >= 0) and (i < fRows) and (j >= 0) and (j < fCols));
aux := i*fCols + j;
Result := fInfo[aux div 32] and (1 shl (aux mod 32)) <> 0;
end;
procedure TBooleanMatrix.SetItem(i, j : integer; which : boolean);
var
aux : integer;
begin
assert((i >= 0) and (i < fRows) and (j >= 0) and (j < fCols));
aux := i*fCols + j;
if which
then fInfo[aux div 32] := fInfo[aux div 32] or (1 shl (aux mod 32))
else fInfo[aux div 32] := fInfo[aux div 32] and not (1 shl (aux mod 32));
end;
procedure TBooleanMatrix.Clear;
begin
fillchar(fInfo^, fSize, 0);
end;
procedure TBooleanMatrix.Fill;
begin
fillchar(fInfo^, fSize, $FF);
end;
function TBooleanMatrix.GetAddressOf(i, j : integer; out mask : integer) : PIntegerArray;
var
aux : integer;
begin
assert((i >= 0) and (i < fRows) and (j >= 0) and (j < fCols));
aux := i*fCols + j;
mask := 1 shl (aux mod 32);
Result := @fInfo[aux div 32];
end;
end.
|
unit evMultiSelectionBlock;
// Модуль: "w:\common\components\gui\Garant\Everest\evMultiSelectionBlock.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevMultiSelectionBlock" MUID: (48E3B83B0187)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evMultiSelectionText
, evdInterfaces
, nevTools
, nevBase
, l3Interfaces
;
type
TevMultiSelectionBlock = class(TevMultiSelectionText, IevdDataObject, InevDataObjectPrim2)
protected
procedure DoStore(const aView: InevView;
const G: InevTagGenerator;
aFlags: TevdStoreFlags); virtual;
{* сохраняет выделение в G }
procedure Store(const aView: InevView;
const G: InevTagGenerator;
aFlags: TevdStoreFlags = evDefaultStoreFlags); overload;
{* сохраняет выделение в G. }
function Store(aFormat: TevdClipboardFormat;
const aPool: IStream;
const aFilters: TevdTagGenerator;
aFlags: TevdStoreFlags = [evd_sfStoreParaEnd]): Boolean; overload;
{* сохраняет выделение в формате aFormat в Pool, который должен реализовывать IStream. }
function GetData: IevdDataObject; override;
function GetAsStorable: InevDataObjectPrim2; override;
end;//TevMultiSelectionBlock
implementation
uses
l3ImplUses
, l3InterfacedString
, k2BaseTypes
, l3Base
, nevFacade
, ContentsElement_Const
, Block_Const
, Document_Const
, k2Tags
//#UC START# *48E3B83B0187impl_uses*
//#UC END# *48E3B83B0187impl_uses*
;
procedure TevMultiSelectionBlock.DoStore(const aView: InevView;
const G: InevTagGenerator;
aFlags: TevdStoreFlags);
{* сохраняет выделение в G }
//#UC START# *48ECE4420180_48E3B83B0187_var*
function StoreSel(const aSel: InevRange; anIndex: Integer): Boolean;
begin//StoreSel
Result := true;
aSel.AsStorable.Store(aView, G, aFlags - [evd_sfChildrenOnly]);
end;//StoreSel
var
l_Tag : Tl3Variant;
//#UC END# *48ECE4420180_48E3B83B0187_var*
begin
//#UC START# *48ECE4420180_48E3B83B0187_impl*
l_Tag := GetRedirect;
if (evd_sfChildrenOnly in aFlags) then
begin
{$IfDef Nemesis}
with l_Tag do
if IsKindOf(k2_typDocument) then
begin
if HasSubAtom(k2_tiInContents) then
G.AddBoolAtom(k2_tiInContents, BoolA[k2_tiInContents]);
if HasSubAtom(k2_tiName) then
G.AddStringAtom(k2_tiName, PCharLenA[k2_tiName]);
if HasSubAtom(k2_tiShortName) then
G.AddStringAtom(k2_tiShortName, PCharLenA[k2_tiShortName]);
if HasSubAtom(k2_tiExternalHandle) then
G.AddIntegerAtom(k2_tiExternalHandle, IntA[k2_tiExternalHandle]);
end;//IsKindOf(k2_typDocument)
{$EndIf Nemesis}
IterateF(evL2TSA(@StoreSel));
end//evd_sfChildrenOnly in aFlags
else
begin
with l_Tag.AsObject do
begin
if TagType.IsKindOf(k2_typBlock) AND
not TagType.IsKindOf(k2_typDocument) then
G.StartChild(k2_typContentsElement)
// - т.к. мы не Solid (см. TevMultiSelectionBlock.Store), то надо сигнализировать
// об этом фильтрам иначе не все правильно будут работать, например - http://mdp.garant.ru/pages/viewpage.action?pageId=151588139
else
G.StartChild(TagType);
try
WriteTag(G, l3_spfAll - [l3_spfChildren]);
IterateF(evL2TSA(@StoreSel));
finally
G.Finish;
end;//try..finally
end;//with l_Tag
end;//ChildrenOnly
//#UC END# *48ECE4420180_48E3B83B0187_impl*
end;//TevMultiSelectionBlock.DoStore
procedure TevMultiSelectionBlock.Store(const aView: InevView;
const G: InevTagGenerator;
aFlags: TevdStoreFlags = evDefaultStoreFlags);
{* сохраняет выделение в G. }
//#UC START# *47C68BFD011C_48E3B83B0187_var*
var
l_Tag : Tl3Variant;
//#UC END# *47C68BFD011C_48E3B83B0187_var*
begin
//#UC START# *47C68BFD011C_48E3B83B0187_impl*
if (Blocks <> nil) AND (Blocks.Count = 1) then
Blocks.First.AsStorable.Store(aView, G, aFlags)
else
begin
aFlags := aFlags - [evd_sfStoreParaEnd];
l_Tag := GetRedirect;
if Solid(aView) then
begin
if not (evd_sfChildrenOnly in aFlags) then
begin
with l_Tag.AsObject do
begin
G.StartChild(TagType);
try
WriteTag(G, l3_spfAll);
finally
G.Finish;
end;{try..finally}
end;//with l_Tag
Exit;
end;//not ChildrenOnly
end;//Solid
DoStore(aView, G, aFlags);
end;//(f_Blocks <> nil) AND (f_Blocks.Count = 1)
//#UC END# *47C68BFD011C_48E3B83B0187_impl*
end;//TevMultiSelectionBlock.Store
function TevMultiSelectionBlock.Store(aFormat: TevdClipboardFormat;
const aPool: IStream;
const aFilters: TevdTagGenerator;
aFlags: TevdStoreFlags = [evd_sfStoreParaEnd]): Boolean;
{* сохраняет выделение в формате aFormat в Pool, который должен реализовывать IStream. }
//#UC START# *47C68C6701AF_48E3B83B0187_var*
var
l_TSR : InevTagReader;
//#UC END# *47C68C6701AF_48E3B83B0187_var*
begin
//#UC START# *47C68C6701AF_48E3B83B0187_impl*
l_TSR := ParaX.DocumentContainer.TagReader;
if (l_TSR <> nil) then
try
Result := (l_TSR.ReadTag(aFormat, aPool, aFilters, Self, aFlags) > 0);
finally
l_TSR := nil;
end//try..finally
else
Result := false;
//#UC END# *47C68C6701AF_48E3B83B0187_impl*
end;//TevMultiSelectionBlock.Store
function TevMultiSelectionBlock.GetData: IevdDataObject;
//#UC START# *48ECD89F02EA_48E3B83B0187_var*
//#UC END# *48ECD89F02EA_48E3B83B0187_var*
begin
//#UC START# *48ECD89F02EA_48E3B83B0187_impl*
Result := Self;
//#UC END# *48ECD89F02EA_48E3B83B0187_impl*
end;//TevMultiSelectionBlock.GetData
function TevMultiSelectionBlock.GetAsStorable: InevDataObjectPrim2;
//#UC START# *48ECD8FE0184_48E3B83B0187_var*
//#UC END# *48ECD8FE0184_48E3B83B0187_var*
begin
//#UC START# *48ECD8FE0184_48E3B83B0187_impl*
Result := Self;
//#UC END# *48ECD8FE0184_48E3B83B0187_impl*
end;//TevMultiSelectionBlock.GetAsStorable
end.
|
unit uBaseScriptEngine;
interface
uses
CodeTemplateAPI
, ToolsAPI
, Classes
;
type
TBaseScriptEngine = class abstract(TNotifierObject, IOTACodeTemplateScriptEngine)
private
FScriptInfo: TStrings;
procedure FetchScriptInfo(const AScript: IOTACodeTemplateScript);
function GetScriptInfo: TStrings;
protected
function GetIDString: WideString; virtual; abstract;
function GetLanguage: WideString; virtual; abstract;
procedure ProcessScriptEntry(const aPoint: IOTACodeTemplatePoint; const aName: string; const aValue: string); virtual; abstract;
public
constructor Create;
destructor Destroy; override;
procedure Execute(const ATemplate: IOTACodeTemplate; const APoint: IOTACodeTemplatePoint; const ASyncPoints: IOTASyncEditPoints; const AScript: IOTACodeTemplateScript; var Cancel: Boolean); virtual;
property Language: WideString read GetLanguage;
property ScriptInfo: TStrings read GetScriptInfo;
end;
implementation
uses
SysUtils
;
{ TBaseScriptEngine }
constructor TBaseScriptEngine.Create;
begin
inherited Create;
end;
destructor TBaseScriptEngine.Destroy;
begin
FScriptInfo.Free;
inherited;
end;
procedure TBaseScriptEngine.Execute(const ATemplate: IOTACodeTemplate;
const APoint: IOTACodeTemplatePoint; const ASyncPoints: IOTASyncEditPoints;
const AScript: IOTACodeTemplateScript; var Cancel: Boolean);
var
i: Integer;
TempName: string;
TempPoint: IOTACodeTemplatePoint;
begin
FetchScriptInfo(aScript);
for i := 0 to ScriptInfo.Count - 1 do
begin
TempName := Scriptinfo.Names[i];
TempPoint := aTemplate.FindPoint(TempName);
ProcessScriptEntry(TempPoint, TempName, ScriptInfo.Values[TempName]);
end;
end;
procedure TBaseScriptEngine.FetchScriptInfo(const AScript: IOTACodeTemplateScript);
var
Counter: Integer;
begin
ScriptInfo.Text := AScript.Script;
// Trim each item in the stringlist
for Counter := 0 to ScriptInfo.Count - 1 do
begin
ScriptInfo[Counter] := Trim(ScriptInfo[Counter]);
end;
end;
function TBaseScriptEngine.GetScriptInfo: TStrings;
begin
if FScriptInfo = nil then
begin
FScriptInfo := TStringList.Create
end;
Result := FScriptInfo;
end;
end.
|
unit System.IniFiles.Helper;
interface
Uses System.Classes, System.IniFiles, System.JSON;
type
TCustomIniFileHelper = class Helper for TIniFile
public
function ToJson: string;
function JSON: TJsonObject;
procedure FromJson(AJson: string);
end;
implementation
uses Variants;
procedure TCustomIniFileHelper.FromJson(AJson: string);
var
LJson: TJsonObject;
LSecao: TJsonArray;
Chave: string;
it: TJSONPair;
itValue: TJsonValue;
LPair: TJSONPair;
LItem: TJsonObject;
begin
LJson := TJsonObject.ParseJSONValue(AJson) as TJsonObject;
for it in LJson do
begin
Chave := it.JsonString.Value;
LJson.TryGetValue<TJsonArray>(Chave, LSecao);
for itValue in LSecao do
begin
LItem := itValue as TJsonObject;
for LPair in LItem do
writeString(Chave, LPair.JsonString.Value, LPair.JsonValue.Value);
end;
end;
end;
function TCustomIniFileHelper.JSON: TJsonObject;
var
LArray: TJsonArray;
sec: TStringList;
it: TStringList;
i, n: integer;
LPair: TJSONPair;
v: variant;
begin
result := TJsonObject.create;
sec := TStringList.create;
it := TStringList.create;
try
ReadSections(sec);
for i := 0 to sec.count - 1 do
begin
ReadSection(sec[i], it);
if it.count > 0 then
begin
LArray := TJsonArray.create;
try
for n := 0 to it.count - 1 do
begin
v := ReadString(sec[i], it[n], '');
if VarIsOrdinal(v) or VarIsFloat(v) or VarIsNumeric(v) then
LPair := TJSONPair.create(it[n], TJSONNumber.create(v))
else
LPair := TJSONPair.create(it[n], v);
LArray.Add(LPair.ToJson);
end;
result.AddPair(sec[i], LArray);
finally
end;
end;
end;
finally
end;
end;
function TCustomIniFileHelper.ToJson: string;
begin
result := JSON.ToJson;
end;
end.
|
unit RemoteLogSender;
interface
uses Windows, Messages, SysUtils, Classes, InterfacedForm, Forms, AbZipper,
AbUtils, commonMIS;
// Отправка массива значений на сервер.
// Data - это список пар key-value.
/// При записи значения используется стандартный разделитель
function send(AURL: string; Data: TStrings): string;
// Отправка данных пингового запроса к DBMIS
// Функция дополняет отправляемые данные сведениями о пользователе
// и отправляет данные в отдельном потоке.
procedure sendPingLog(Data: TStrings);
// Отправка текстового представления json объекта.
// Функци предназначена для отправки логов из Log4D
// при помощи TLogHttpAppender
// Функция создает отдельный процесс для отправки данных.
procedure sendJsonText(json: string);
// Установить разрешение на отправку логов на севрер
procedure EnableJsonSend(Enabled: boolean);
// Отправка спика значений на сервере с дополнительным заголовком
function sendH(AURL: string; Data: TStrings; Headers: TStrings): string;
implementation
uses
httpsend, ssl_openssl, blcksock, synautil, synaip, synacode, synsock,
OSUserInfo, pingsend, Math, IniFiles, variants, superobject;
type
TSendLogThread = class(TThread)
private
FData: TStringList;
Fjson: string;
FURL: string;
public
constructor Create(URL: string; Data: TStrings; jsonText: string); overload;
destructor Destroy; override;
procedure Execute; override;
end;
var
FMainForm: IInterfacedForm;
FDbServer: string;
FDbName: string;
FJsonSendEnabled: boolean;
function GetLogUrl: string;
begin
Result := 'https://ws.ctmed.ru/remotelog/index.php'
end;
function HTTPEncodeStrings(SL: TStrings): UTF8String;
var
I: Integer;
begin
Result := '';
for I:=0 to SL.Count-1 do
begin
if I>0 then
Result := Result + '&';
Result := Result + UTF8Encode(SL.Names[I])+'='+UTF8Encode(SL.ValueFromIndex[I]);
end;
end;
function send(AURL: string; Data: TStrings): string;
begin
Result := sendH(AURL, Data, nil);
end;
procedure SetMainForm;
begin
if FMainForm=nil then
if Application.MainForm.InheritsFrom(TInterfacedForm) then
TInterfacedForm(Application.MainForm).QueryInterface(IInterfacedForm,
FMainForm)
end;
procedure addUserInfo(Data: TStringList);
var
user: TCTMUserInfo;
begin
SetMainForm;
if not Assigned(FMainForm)then Exit;
user := FMainForm.GetLastUser;
Data.Add('lan.ip.address='+GetLocalIP);
Data.Add('client.id='+IntToStr(user.id));
Data.Add('client.name='+user.user);
Data.Add('client.post='+user.dol);
Data.Add('client.group.id='+IntToStr(user.type_id));
Data.Add('client.group.name='+user.group_name);
Data.Add('clinic.id='+IntToStr(user.lpu_id));
end;
procedure addDbName(Data: TStrings);
var
ini: TIniFile;
begin
if (FDbName = '') or (FDbServer = '') then
begin
ini:= TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
try
FDbServer := ini.ReadString('FIBDataBase', 'ServerName', 'fb.ctmed.ru');
FDbName := ini.ReadString('FIBDataBase', 'DatabaseName', 'dbmis');
finally
ini.Free;
end;
end;
Data.Values['db.server'] := FDbServer;
Data.Values['db.name'] := FDbName;
end;
procedure parseJson(Data: TStrings; jsonText: string);
procedure parse(p: string; o: ISuperObject);
var
iter: TSuperObjectIter;
begin
if not Assigned(o) then Exit;
if o.IsType(stObject) then
begin
if ObjectFindFirst(o, iter) then
repeat
parse(iter.key, iter.val);
until not ObjectFindNext(iter);
end
else
Data.Add(p + '=' + VarToStr(o.AsString));
end;
var
json: ISuperObject;
begin
json := SO(jsonText);
parse('message', json);
end;
procedure EnableJsonSend(Enabled: boolean);
begin
FJsonSendEnabled := Enabled;
end;
procedure sendJsonText(json: string);
var
tmp: TStringList;
begin
if not FJsonSendEnabled then Exit;
tmp := TStringList.Create;
try
addUserInfo(tmp);
addDbName(tmp);
TSendLogThread.Create(GetLogUrl, tmp, json);
finally
tmp.Free;
end;
end;
function sendH(AURL: string; Data: TStrings; Headers: TStrings): string;
var
Resp: TStringStream;
HTTP: THTTPSend;
I: Integer;
tmp: TStringList;
begin
HTTP := THTTPSend.Create;
Resp := TStringStream.Create('');
tmp := TStringList.Create;
try
addUserInfo(tmp);
tmp.AddStrings(Data);
WriteStrToStream(HTTP.Document, HTTPEncodeStrings(tmp));
HTTP.MimeType := 'application/x-www-form-urlencoded';
HTTP.Headers.Add('MISAUTH: CDAF5A2C-4250-4D0E-B427-8237736E3ED8');
if Assigned(Headers) then
for I:=0 to Headers.Count-1 do
HTTP.Headers.Add(Headers.Names[I] + ': ' + Headers.ValueFromIndex[I]);
if HTTP.HTTPMethod('POST', AURL) then
Resp.CopyFrom(HTTP.Document, 0);
Result := Resp.DataString;
finally
tmp.Free;
Resp.Free;
HTTP.Free;
end;
end;
procedure sendPingLog(Data: TStrings);
var
tmp: TStringList;
begin
tmp := TStringList.Create;
try
addUserInfo(tmp);
tmp.AddStrings(Data);
TSendLogThread.Create(GetLogUrl, tmp, '');
finally
tmp.Free;
end;
end;
{ TSendLogThread }
constructor TSendLogThread.Create(URL: string; Data: TStrings; jsonText: string);
begin
FData := TStringList.Create;
FData.AddStrings(Data);
FreeOnTerminate := True;
Fjson := jsonText;
FURL := URL;
inherited Create(False);
end;
destructor TSendLogThread.Destroy;
begin
FData.Free;
inherited;
end;
procedure parseSQLmessage(Data: TStrings);
const
sExecute = ': [Execute]';
sPrepare = ': [Prepare]';
sTickCount = 'Execute tick count';
sAffected = 'Rows Affected:';
function isParam(S: string): boolean;
var
I, J: Integer;
begin
Result := False;
if (Length(S)>3) and (S[1]=' ') and (S[2]=' ') and (S[3]<>' ') then
begin
I := 3;
J := Length(S);
while (I<=J) and (S[I]<>' ') do
begin
if not (S[I] in ['A'..'Z', '0'..'9', '_']) then
begin
Exit;
end;
Inc(I);
end;
if I+1 < J then
begin
Result := (S[I+1]='=') and (S[I+2]=' ');
end;
end;
end;
procedure parseExecute(msg: string);
var
SL: TStringList;
I, J: Integer;
S: string;
begin
Data.Add('log.sql.type=execute');
SL := TStringList.Create;
try
SL.Text := msg;
I := SL.Count - 1;
J := pos(sTickCount, SL[I]);
if (J>0) then
begin
J := J+Length(sTickCount);
Data.Add('exec.time.server='+copy(SL[I], J, Length(SL[I])-J+1));
Dec(I);
end;
J := pos(sAffected, SL[I]);
if (J>0) then
begin
J := J+Length(sAffected);
Data.Add('rows.affected='+copy(SL[I], J, Length(SL[I])-J+1));
Dec(I);
end;
S := '';
while isParam(SL[I]) do
begin
S := SL[I] + sLineBreak + S;
Dec(I);
end;
if S<>'' then
Data.Add('params='+S);
J := I;
S := '';
for I:=0 to J do
begin
S := S + SL[I] + sLineBreak;
end;
if S<>'' then
Data.Values['message'] := S;
finally
SL.Free;
end;
end;
var
msg: string;
I: Integer;
begin
msg := Data.Values['message'];
I := pos(sExecute, msg);
if I > 0 then
begin
I := I+Length(sExecute);
parseExecute(trim(copy(msg, I, Length(msg)-I+1)));
Exit;
end
end;
procedure WriteGzipToStream(Stream: TStream; Data: UTF8String);
var
Zip: TAbZipper;
MS: TMemoryStream;
begin
Zip := TAbZipper.Create(nil);
MS := TMemoryStream.Create;
try
Zip.ArchiveType := atGzip;
Zip.ForceType := True;
Zip.Stream := Stream;
WriteStrToStream(MS, Data);
MS.Position := 0;
Zip.AddFromStream('', MS);
finally
MS.Free;
Zip.Free;
end;
end;
procedure TSendLogThread.Execute;
var
Resp: TStringStream;
HTTP: THTTPSend;
tmp: TStringList;
S: string;
FContent: UTF8String;
URL: string;
begin
HTTP := THTTPSend.Create;
Resp := TStringStream.Create('');
tmp := TStringList.Create;
try
tmp.Delimiter := '&';
tmp.AddStrings(FData);
if Fjson<>'' then
begin
parseJson(tmp, Fjson);
parseSQLmessage(tmp);
end;
URL := AppParamValue('/logurl');
// Если удалось получить имя сервера
if URL='' then
URL := FURL;
if URL<>'' then
begin
FContent := HTTPEncodeStrings(tmp);
if Length(FContent)<256 then
WriteStrToStream(HTTP.Document, FContent)
else
begin
WriteGzipToStream(HTTP.Document, FContent);
HTTP.Headers.Add('Content-Encoding: gzip');
end;
HTTP.MimeType := 'application/x-www-form-urlencoded';
HTTP.Headers.Add('MISAUTH: CDAF5A2C-4250-4D0E-B427-8237736E3ED8');
HTTP.Headers.Add('PINGLOG: 1');
if HTTP.HTTPMethod('POST', URL) then
Resp.CopyFrom(HTTP.Document, 0);
S := Resp.DataString;
S := '';
end;
finally
tmp.Free;
Resp.Free;
HTTP.Free;
end;
end;
end.
|
unit Errores;
interface
resourcestring
rsInformeNoEncontrado = 'Error! Informe no Encontrado';
rsErrorFechaVencida = 'FECHA de comprobante (%s) ' + #13 +
'corresponde a periodo CERRADO (%s)' + #13 +
'Debe Modificar la fecha. Imposible Continuar';
rsClienteSinPedido = 'Cliente NO tiene pedidos pendientes';
rsCompleteDatos = 'Falta completar datos de Registro';
rsNoEliminar = 'No se puede eliminar (%s) ya que Hay (%s) que la referencian';
rsDatosIncompletos = 'Datos Incompletos. (%s)';
implementation
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ 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 FB4D.SimpleRTDBMainFmx;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.JSON,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit,
FB4D.Interfaces, FB4D.Configuration;
type
TFmxSimpleReadWrite = class(TForm)
edtDBMessage: TEdit;
btnWrite: TButton;
lblStatus: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnWriteClick(Sender: TObject);
procedure edtDBMessageChangeTracking(Sender: TObject);
private
fConfig: IFirebaseConfiguration;
fEvent: IFirebaseEvent;
procedure DBEvent(const Event: string; Params: TRequestResourceParam;
JSONObj: TJSONObject);
procedure DBError(const RequestID, ErrMsg: string);
procedure DBWritten(ResourceParams: TRequestResourceParam; Val: TJSONValue);
procedure OnDBStop(Sender: TObject);
end;
var
FmxSimpleReadWrite: TFmxSimpleReadWrite;
implementation
uses
FB4D.Helpers, FB4D.RealTimeDB;
{$R *.fmx}
resourcestring
rsHintRTDBRules =
'Hint to permission error: ' +
'Before you can write into the real time database add the following ' +
'text in the Firebase console as rule for the Realtime Database:'#13 +
' {"rules": {"Message": {".read": true,".write": true}}}'#13;
const
GoogleServiceJSON = '..\..\..\google-services.json';
// Alternative way by entering
// ApiKey = '<Your Firebase ApiKey listed in the Firebase Console>';
// ProjectID = '<Your Porject ID listed in the Firebase Console>';
// FirebaseURL = '<The URL of your RealTime DB from the Firebase Console>';
DBPath: TRequestResourceParam = ['Message'];
procedure TFmxSimpleReadWrite.FormCreate(Sender: TObject);
begin
fConfig := TFirebaseConfiguration.Create(GoogleServiceJSON);
// fConfig := TFirebaseConfiguration.Create(ApiKey, ProjectID, '', FirebaseURL);
fEvent := fConfig.RealTimeDB.ListenForValueEvents(DBPath, DBEvent, OnDBStop,
DBError, nil);
lblStatus.Text := 'Firebase RT DB connected';
btnWrite.Enabled := false;
end;
procedure TFmxSimpleReadWrite.OnDBStop(Sender: TObject);
begin
Caption := 'DB Listener was stopped - restart App';
end;
procedure TFmxSimpleReadWrite.DBEvent(const Event: string;
Params: TRequestResourceParam; JSONObj: TJSONObject);
var
data: string;
begin
if Event = cEventPut then
begin
if not JSONObj.TryGetValue<string>(cData, data) then
data := '';
edtDBMessage.Text := data;
btnWrite.Enabled := false;
lblStatus.Text := 'Last read: ' + DateTimeToStr(now);
end;
end;
procedure TFmxSimpleReadWrite.DBWritten(ResourceParams: TRequestResourceParam;
Val: TJSONValue);
begin
lblStatus.Text := 'Last write: ' + DateTimeToStr(now);
end;
procedure TFmxSimpleReadWrite.DBError(const RequestID, ErrMsg: string);
begin
if SameText(ErrMsg, 'Permission denied') or
SameText(ErrMsg, 'Unauthorized') then
lblStatus.Text := rsHintRTDBRules
else
lblStatus.Text := 'Error: ' + ErrMsg;
end;
procedure TFmxSimpleReadWrite.btnWriteClick(Sender: TObject);
var
Data: TJSONValue;
begin
Data := TJSONString.Create(edtDBMessage.Text);
try
fConfig.RealTimeDB.Put(DBPath, Data, DBWritten, DBError);
finally
Data.Free;
end;
btnWrite.Enabled := false;
end;
procedure TFmxSimpleReadWrite.edtDBMessageChangeTracking(Sender: TObject);
begin
btnWrite.Enabled := true;
end;
end.
|
unit Records;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Grids,
Vcl.DBGrids;
type
TFRecord = class(TForm)
ESearch: TEdit;
BSearch: TButton;
RAuthor: TRadioButton;
RBook: TRadioButton;
Label1: TLabel;
BAdd: TButton;
BDelete: TButton;
BChange: TButton;
StringGrid1: TStringGrid;
ComboBox1: TComboBox;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure RButtonClick(Sender: TObject);
procedure BAddClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ESearchClick(Sender: TObject);
procedure BDeleteClick(Sender: TObject);
procedure DeleteARow(Grid: TStringGrid; ARow: Integer);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure BChangeClick(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure BSearchClick(Sender: TObject);
procedure ESearchKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FRecord: TFRecord;
implementation
{$R *.dfm}
uses Add, Lib;
type
TMyGrid = class(TCustomGrid);
procedure TFRecord.DeleteARow(Grid: TStringGrid; ARow: Integer);
begin
TMyGrid(Grid).DeleteRow(ARow);
end;
procedure TFRecord.BAddClick(Sender: TObject);
begin
FAdd.Show;
FAdd.BCompleteAdd.Visible := True;
FAdd.BCompleteChange.Visible := False;
FAdd.EAuthor.Text := '';
FAdd.EName.Text := '';
FAdd.EYear.Text := '';
end;
procedure TFRecord.BChangeClick(Sender: TObject);
var
i: Integer;
el: TBook;
begin
if (first^.next <> nil) and (FRecord.StringGrid1.RowCount > 1) then
begin
FAdd.Show;
FAdd.BCompleteAdd.Visible := False;
FAdd.BCompleteChange.Visible := True;
q := first;
el.Author := FRecord.StringGrid1.cells[0,StringGrid1.row];
el.NameOfBook := FRecord.StringGrid1.cells[1,StringGrid1.row];
el.Year := StrToInt(FRecord.StringGrid1.cells[2,StringGrid1.row]);
while (el.Author <> q^.Element.Author) and (el.NameOfBook <> q^.Element.NameOfBook) and (el.Year <> q^.Element.Year) do
q := q^.next;
FAdd.EAuthor.Text := q^.Element.Author;
FAdd.EName.Text := q^.Element.NameOfBook;
FAdd.EYear.Text := IntToStr(q^.Element.Year);
end;
end;
procedure TFRecord.BDeleteClick(Sender: TObject);
begin
if (first^.next <> nil) and (FRecord.StringGrid1.RowCount > 1) then
begin
DeleteBook(first, StringGrid1.row);
DeleteARow(StringGrid1, StringGrid1.Row);
end;
end;
procedure TFRecord.BSearchClick(Sender: TObject);
begin
if RAuthor.Checked then
SearchBook(first, ESearch.Text, 0);
if RBook.Checked then
SearchBook(first, ESearch.Text, 1);
end;
procedure TFRecord.ComboBox1Change(Sender: TObject);
begin
if ComboBox1.Items[ComboBox1.ItemIndex] = 'Времени добавления' then
showdata(first, StringGrid1)
else
begin
if ComboBox1.Items[ComboBox1.ItemIndex] = 'Автору' then
sortlist(first, 0);
if ComboBox1.Items[ComboBox1.ItemIndex] = 'Названию' then
sortlist(first, 1);
end;
end;
procedure TFRecord.ESearchClick(Sender: TObject);
begin
if (ESearch.Text = 'Автор') or (ESearch.Text = 'Название книги') then
ESearch.Text := '';
end;
procedure TFRecord.ESearchKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
BSearchClick(BSearch);
end;
end;
procedure TFRecord.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Rewrite(f);
q := first;
while q^.next <> nil do
begin
q := q^.next;
write(f, q^.Element);
end;
CloseFile(f);
deletelist(first);
end;
procedure TFRecord.FormCreate(Sender: TObject);
begin
RBook.Checked := True;
with ComboBox1 do
begin
items.add('Времени добавления');
items.add('Автору');
items.add('Названию');
end;
ComboBox1.ItemIndex := 0;
with StringGrid1 do
begin
Cells[0,0] := 'Автор';
Cells[1,0] := 'Название книги';
Cells[2,0] := 'Год издания';
end;
New(first);
q := first;
q^.next := nil;
AssignFile(f,'Books.txt');
//Reset(F);
if not FileExists('Books.txt') then
ReWrite(F)
else
Reset(F);
while not Eof(F) do
begin
New(q^.next);
q := q^.next;
read(f, q^.Element);
q^.next := nil;
end;
showdata(first, StringGrid1);
if first^.next = nil then
StringGrid1.RowCount := 2;
StringGrid1.Row := 1;
CloseFile(f);
end;
procedure TFRecord.RButtonClick(Sender: TObject);
begin
ESearch.Text := (Sender as TRadioButton).Caption;
end;
procedure TFRecord.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
if ARow = 0 then
CanSelect := False;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIWNafL2RMultiplier;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpBigInteger,
ClpIAbstractECMultiplier;
type
IWNafL2RMultiplier = interface(IAbstractECMultiplier)
['{E2A5E4EF-C092-4F83-ACCF-0FC8731FB274}']
/// <summary>
/// Determine window width to use for a scalar multiplication of the
/// given size.
/// </summary>
/// <param name="bits">
/// the bit-length of the scalar to multiply by
/// </param>
/// <returns>
/// the window size to use
/// </returns>
function GetWindowSize(bits: Int32): Int32;
end;
implementation
end.
|
unit WebModuleUnit1;
interface
uses
System.SysUtils,
System.Classes,
Web.HTTPApp,
MVCFramework;
type
TWebModule1 = class(TWebModule)
procedure WebModuleCreate(Sender: TObject);
procedure WebModuleDestroy(Sender: TObject);
private
FMVCEngine: TMVCEngine;
public
{ Public declarations }
end;
var
WebModuleClass: TComponentClass = TWebModule1;
implementation
{$R *.dfm}
uses
App1MainControllerU,
MVCFramework.Middleware.StaticFiles, MVCFramework.Commons;
procedure TWebModule1.WebModuleCreate(Sender: TObject);
begin
FMVCEngine := TMVCEngine.Create(Self,
procedure(Config: TMVCConfig)
begin
Config['view_path'] := '..\Debug\HTML5Application';
end);
FMVCEngine.AddController(
TApp1MainController);
FMVCEngine.AddMiddleware(TMVCStaticFilesMiddleware.Create(
'/', { StaticFilesPath }
'HTML5Application\public_html', { DocumentRoot }
'index.html' { IndexDocument - Before it was named fallbackresource }
));
end;
procedure TWebModule1.WebModuleDestroy(Sender: TObject);
begin
FMVCEngine.free;
end;
end.
|
unit TTSOFCRTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSOFCRRecord = record
PLenderNum: String[4];
PInitials: String[6];
PModCount: Integer;
PName: String[30];
PTitle: String[25];
PPhone: String[40];
End;
TTTSOFCRBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSOFCRRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSOFCR = (TTSOFCRPrimaryKey);
TTTSOFCRTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFInitials: TStringField;
FDFModCount: TIntegerField;
FDFName: TStringField;
FDFTitle: TStringField;
FDFPhone:TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPInitials(const Value: String);
function GetPInitials:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPTitle(const Value: String);
function GetPTitle:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetEnumIndex(Value: TEITTSOFCR);
function GetEnumIndex: TEITTSOFCR;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSOFCRRecord;
procedure StoreDataBuffer(ABuffer:TTTSOFCRRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFInitials: TStringField read FDFInitials;
property DFModCount: TIntegerField read FDFModCount;
property DFName: TStringField read FDFName;
property DFTitle: TStringField read FDFTitle;
property DFPhone: TStringField read FDFPhone;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PInitials: String read GetPInitials write SetPInitials;
property PModCount: Integer read GetPModCount write SetPModCount;
property PName: String read GetPName write SetPName;
property PTitle: String read GetPTitle write SetPTitle;
property PPhone: string read GetPPhone write SetPPhone;
published
property Active write SetActive;
property EnumIndex: TEITTSOFCR read GetEnumIndex write SetEnumIndex;
end; { TTTSOFCRTable }
procedure Register;
implementation
procedure TTTSOFCRTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFInitials := CreateField( 'Initials' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFTitle := CreateField( 'Title' ) as TStringField;
FDFTitle := CreateField( 'Phone' ) as TStringField;
end; { TTTSOFCRTable.CreateFields }
procedure TTTSOFCRTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSOFCRTable.SetActive }
procedure TTTSOFCRTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSOFCRTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSOFCRTable.SetPInitials(const Value: String);
begin
DFInitials.Value := Value;
end;
function TTTSOFCRTable.GetPInitials:String;
begin
result := DFInitials.Value;
end;
procedure TTTSOFCRTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSOFCRTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSOFCRTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TTTSOFCRTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TTTSOFCRTable.SetPTitle(const Value: String);
begin
DFTitle.Value := Value;
end;
function TTTSOFCRTable.GetPTitle:String;
begin
result := DFTitle.Value;
end;
procedure TTTSOFCRTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('Initials, String, 6, N');
Add('ModCount, Integer, 0, N');
Add('Name, String, 30, N');
Add('Title, String, 25, N');
Add('Phone, String, 25, N');
end;
end;
procedure TTTSOFCRTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;Initials, Y, Y, N, N');
end;
end;
procedure TTTSOFCRTable.SetEnumIndex(Value: TEITTSOFCR);
begin
case Value of
TTSOFCRPrimaryKey : IndexName := '';
end;
end;
function TTTSOFCRTable.GetDataBuffer:TTTSOFCRRecord;
var buf: TTTSOFCRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PInitials := DFInitials.Value;
buf.PModCount := DFModCount.Value;
buf.PName := DFName.Value;
buf.PTitle := DFTitle.Value;
buf.PPhone := DFPhone.Value;
result := buf;
end;
procedure TTTSOFCRTable.StoreDataBuffer(ABuffer:TTTSOFCRRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFInitials.Value := ABuffer.PInitials;
DFModCount.Value := ABuffer.PModCount;
DFName.Value := ABuffer.PName;
DFTitle.Value := ABuffer.PTitle;
DFPhone.Value := ABuffer.PPhone;
end;
function TTTSOFCRTable.GetEnumIndex: TEITTSOFCR;
var iname : string;
begin
result := TTSOFCRPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSOFCRPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSOFCRTable, TTTSOFCRBuffer ] );
end; { Register }
function TTTSOFCRBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..6] of string = ('LENDERNUM','INITIALS','MODCOUNT','NAME','TITLE','PHONE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 6) and (flist[x] <> s) do inc(x);
if x <= 6 then result := x else result := 0;
end;
function TTTSOFCRBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftString;
5 : result := ftString;
6 : Result := ftString;
end;
end;
function TTTSOFCRBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PInitials;
3 : result := @Data.PModCount;
4 : result := @Data.PName;
5 : result := @Data.PTitle;
6 : Result := @Data.PPhone;
end;
end;
function TTTSOFCRTable.GetPPhone: String;
begin
result := DFPhone.Value;
end;
procedure TTTSOFCRTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
end.
|
unit Androidapi.JNI.baidu.mapapi.favorite;
// ====================================================
// Android Baidu Map SDK interface
// Package:com.baidu.mapapi.favorite
// author:Xubzhlin
// email:371889755@qq.com
//
// date:2017.5.10
// version:4.3.0
// ====================================================
interface
uses
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.baidu.mapapi.model;
type
// ===== Forward declarations =====
JFavoriteManager = interface; // com.baidu.mapapi.favorite.FavoriteManager
JFavoritePoiInfo = interface; // com.baidu.mapapi.favorite.FavoritePoiInfo
// ===== Interface declarations =====
JFavoriteManagerClass = interface(JObjectClass)
['{F4E7101B-0F28-416D-B7DC-259CE44487BD}']
{ static Property Methods }
{ static Methods }
{ class } function getInstance: JFavoriteManager; cdecl;
// ()Lcom/baidu/mapapi/favorite/FavoriteManager;
{ static Property }
end;
[JavaSignature('com/baidu/mapapi/favorite/FavoriteManager')]
JFavoriteManager = interface(JObject)
['{FF031617-2698-4B1A-8199-3CAE6A6A6BFF}']
{ Property Methods }
{ methods }
procedure init; cdecl; // ()V
function add(P1: JFavoritePoiInfo): Integer; cdecl;
// (Lcom/baidu/mapapi/favorite/FavoritePoiInfo;)I
function getFavPoi(P1: JString): JFavoritePoiInfo; cdecl;
// (Ljava/lang/String;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function getAllFavPois: JList; cdecl; // ()Ljava/util/List;
function deleteFavPoi(P1: JString): Boolean; cdecl; // (Ljava/lang/String;)Z
function clearAllFavPois: Boolean; cdecl; // ()Z
function updateFavPoi(P1: JString; P2: JFavoritePoiInfo): Boolean; cdecl;
// (Ljava/lang/String;Lcom/baidu/mapapi/favorite/FavoritePoiInfo;)Z
procedure destroy; cdecl; // ()V
{ Property }
end;
TJFavoriteManager = class(TJavaGenericImport<JFavoriteManagerClass,
JFavoriteManager>)
end;
JFavoritePoiInfoClass = interface(JObjectClass)
['{07DB3A81-B473-46FB-BE9D-199D5BA45F96}']
{ static Property Methods }
{ static Methods }
{ class } function init: JFavoritePoiInfo; cdecl; // ()V
{ static Property }
end;
[JavaSignature('com/baidu/mapapi/favorite/FavoritePoiInfo')]
JFavoritePoiInfo = interface(JObject)
['{08D2C683-9F70-4552-84FE-F3B641D3230C}']
{ Property Methods }
{ methods }
function poiName(P1: JString): JFavoritePoiInfo; cdecl;
// (Ljava/lang/String;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function pt(P1: JLatLng): JFavoritePoiInfo; cdecl;
// (Lcom/baidu/mapapi/model/LatLng;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function addr(P1: JString): JFavoritePoiInfo; cdecl;
// (Ljava/lang/String;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function cityName(P1: JString): JFavoritePoiInfo; cdecl;
// (Ljava/lang/String;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function uid(P1: JString): JFavoritePoiInfo; cdecl;
// (Ljava/lang/String;)Lcom/baidu/mapapi/favorite/FavoritePoiInfo;
function getID: JString; cdecl; // ()Ljava/lang/String;
function getPoiName: JString; cdecl; // ()Ljava/lang/String;
function getPt: JLatLng; cdecl; // ()Lcom/baidu/mapapi/model/LatLng;
function getAddr: JString; cdecl; // ()Ljava/lang/String;
function getUid: JString; cdecl; // ()Ljava/lang/String;
function getCityName: JString; cdecl; // ()Ljava/lang/String;
function getTimeStamp: Int64; cdecl; // ()J
{ Property }
end;
TJFavoritePoiInfo = class(TJavaGenericImport<JFavoritePoiInfoClass,
JFavoritePoiInfo>)
end;
implementation
procedure RegisterTypes;
begin
TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.favorite.FavoriteManager',
TypeInfo(Androidapi.JNI.baidu.mapapi.favorite.JFavoriteManager));
TRegTypes.RegisterType('Androidapi.JNI.baidu.mapapi.favorite.FavoritePoiInfo',
TypeInfo(Androidapi.JNI.baidu.mapapi.favorite.JFavoritePoiInfo));
end;
initialization
RegisterTypes;
end.
|
unit uUtilPadrao;
interface
uses
Classes, FireDAC.Comp.Client, DmdConnection, Vcl.Printers, Datasnap.DBClient;
function SQLLocate(Tabela, CampoProcura, CampoRetorno, ValorFind: string): string ;
function GetDefaultPrinterName: string;
function Monta_Numero(Campo: String; Tamanho: Integer): String;
function RemoverZeros(S: string): string;
procedure CopiarDataSet(Origem, Destino : TClientDataSet);
function ProximaSequencia(NomeTabela: string; Filial: Integer; SerieCupom: String): Integer;
var
vCaminhoBanco: String;
implementation
uses
System.SysUtils, Winapi.CommDlg;
function SQLLocate(Tabela, CampoProcura, CampoRetorno, ValorFind: string): string ;
var
MyQuery: TFDQuery;
FConn : TDMConection;
begin
if ValorFind <> '' then
begin
FConn := TDMConection.Create(nil);
MyQuery := TFDQuery.Create(DMConection);
MyQuery.Connection := FConn.FDConnection;
MyQuery.Close;
MyQuery.SQL.Clear ;
MyQuery.SQL.Add('select ' + CampoRetorno + ' from ' + Tabela) ;
MyQuery.SQL.Add('where ' + CampoProcura + ' = ' + QuotedStr(ValorFind));
MyQuery.Open ;
if not MyQuery.EOF then
SQLLocate := MyQuery.FieldByName(CampoRetorno).AsString
else
SQLLocate := '' ;
MyQuery.Free;
FConn.Free;
end
else
ValorFind := '' ;
end;
function GetDefaultPrinterName: string;
begin
if (Printer.PrinterIndex >= 0) then
begin
Result := Printer.Printers[Printer.PrinterIndex];
end
else
begin
Result := 'Nenhuma impressora padrão foi detectada.';
end;
end;
procedure CopiarDataSet(Origem, Destino : TClientDataSet);
begin
Destino.Data := Origem.Data;
end;
function Monta_Numero(Campo: String; Tamanho: Integer): String;
var
texto2: String;
i: Integer;
begin
texto2 := '';
for i := 1 to Length(Campo) do
if Campo[i] in ['0','1','2','3','4','5','6','7','8','9'] then
Texto2 := Texto2 + Copy(Campo,i,1);
for i := 1 to Tamanho - Length(texto2) do
texto2 := '0' + texto2;
Result := texto2;
end;
function RemoverZeros(S: string): string;
var
I, J : Integer;
begin
I := Length(S);
while (I > 0) and (S[I] <= ' ') do
begin
Dec(I);
end;
J := 1;
while (J < I) and ((S[J] <= ' ') or (S[J] = '0')) do
begin
Inc(J);
end;
Result := Copy(S, J, (I-J)+1);
end;
function ProximaSequencia(NomeTabela: string; Filial: Integer;
SerieCupom: String): Integer;
var
xSql : String;
Fconn : TDMConection;
begin
Result := 0;
Fconn := TDMConection.Create(nil);
try
xSql := 'EXECUTE PROCEDURE PRC_BUSCAR_SEQUENCIAL(' + QuotedStr(NomeTabela) + ', ' + IntToStr(Filial) + ', ' + QuotedStr(SerieCupom) + ')';
Result := Fconn.FDConnection.ExecSQLScalar(xSql);
finally
Fconn.Free;
end;
end;
end.
|
unit AceRtfC;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995-2004 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses sctctrl, sctvar,acertfp, classes, aceout, windows
,controls, sctrtf, dialogs, sysutils;
type
{ TSctRichTextLabel }
{$IFDEF VCL230PLUS}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSctRichTextLabel = class(TSctLabel)
private
FVariable: TSctvar;
FRtfDraw: TAceRtfDraw;
FBottomMargin: Integer;
FSetDefaultFont: Boolean;
protected
function GetDisplayText: string; override;
procedure Paint; override;
procedure DefineProperties(Filer: TFiler); override;
function PrintMemo( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer): Integer;
public
constructor Create(AOwner: Tcomponent); override;
destructor Destroy; override;
procedure SetVariable(variable: TSctvar);
function GetDataNow: String; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Print(oPage: TComponent; Space: Integer); override;
procedure StartPrint; override;
function PrintHeight( oPage: TComponent; Space, Taking: Integer): Integer; override;
function SpendHeight(oPage: TComponent; Space: Integer): Integer; override;
procedure PrintRtf(oPage: TWinControl; rtf: TSctRtfFile; PrintRow: Integer); override;
procedure PrintTab(oPage: TWinControl; rtf: TSctRtfFile; PrintRow: Integer); override;
procedure PrintLabel( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer); override;
published
property Variable: TSctvar read FVariable write setvariable;
property Align;
property Color;
property Font;
property ParentColor;
property ParentFont;
property Transparent;
property ClipType;
property AlignVertical;
property AlignHorizontal;
property Stretch;
property BorderType;
property Shade;
property BorderMargin;
property BottomMargin: Integer read FBottomMargin write FBottomMargin;
property SetDefaultFont: Boolean read FSetDefaultFont write FSetDefaultFont default False;
end;
implementation
uses sctrep, acememou, printers, forms;
constructor TSctRichTextLabel.Create(AOwner: Tcomponent);
begin
inherited Create(AOwner);
FRtfDraw := TAceRtfDraw.Create;
FBottomMargin := 20;
FSetDefaultFont := False;
end;
destructor TSctRichTextLabel.Destroy;
begin
if FRtfDraw <> nil then FRtfDraw.Free;
inherited Destroy;
end;
procedure TSctRichTextLabel.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineProperty('AutoSize', ReadAutoSize, WriteAutoSize, False);
end;
function TSctRichTextLabel.GetDataNow: String;
begin
Result := DisplayText
end;
procedure TSctRichTextLabel.Print(oPage: TComponent; space: Integer);
var
pg: TSctPage;
R: TRect;
Begin
EndPrint := False;
if PrintOk then
begin
BeforePrint;
pg := TSctPage(oPage);
R := Bounds(pg.xPos + left, pg.yPos + top, width, height);
FirstTime := True;
Space := Space - Top;
if FRtfDraw <> nil then FRtfDraw.Free;
FRtfDraw := TAceRtfDraw.Create;
FRtfDraw.Reset;
FRtfDraw.Font := Font;
FRtfDraw.SetDefaultFont := FSetDefaultFont;
if Variable <> nil then
begin
if Variable.Active then
begin
FRtfDraw.LoadFromStream(Variable.AsStream);
end;
end;
PrintLabel(pg.PrintTo.AceCanvas, R, Space);
AfterPrint;
end;
EndPrint := True;
End;
procedure TSctRichTextLabel.PrintTab(oPage: TWinControl; rtf: TSctRtfFile; PrintRow: Integer);
begin
end;
procedure TSctRichTextLabel.PrintRtf(oPage: TWinControl; rtf: TSctRtfFile; PrintRow: Integer);
Begin
EndPrint := True;
end;
procedure TSctRichTextLabel.Paint;
var
AceCanvas: TAceCanvas;
R: TRect;
begin
Painting := True;
AceCanvas := TAceCanvas.Create;
try
FirstTime := True;
AceCanvas.Handle := Canvas.Handle;
R := Bounds(0, 0, width - 1, height - 1);
if FRtfDraw <> nil then FRtfDraw.Free;
FRtfDraw := TAceRtfDraw.Create;
FRtfDraw.Reset;
FRtfDraw.Font := Font;
FRtfDraw.SetDefaultFont := FSetDefaultFont;
if Variable <> nil then
begin
if Not Variable.Initialized then Variable.Initialize;
if Variable.Active then
begin
FRtfDraw.LoadFromStream(Variable.AsStream);
end;
end;
PrintLabel(AceCanvas, R, Height);
finally
AceCanvas.free;
Painting := False;
end;
end;
function TSctRichTextLabel.PrintMemo( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer): Integer;
var
Count: LongInt;
DRect: TRect;
begin
FRtfDraw.PrintCount := 0;
FRtfDraw.PixelsPerInchX := PixelsPerInch;
FRtfDraw.PixelsPerInchY := PixelsPerInch;
DRect := Bounds(Rect.Left + BorderMargin
, Rect.Top + BorderMargin
, Rect.Right-Rect.Left-(BorderMargin*2)
, Rect.Bottom-Rect.Top-(BorderMargin * 2) - FBottomMargin) ;
FRtfDraw.Font := Font;
FRtfDraw.SetDefaultFont := FSetDefaultFont;
if Stretch then
begin
DRect.Bottom := DRect.Top + Space - (BorderMargin * 2) - FBottomMargin;
FRtfDraw.OutRect := DRect;
Count := FRtfDraw.PrintCount;
Result := FRtfDraw.Height + (BorderMargin * 2) + FBottomMargin;
if (FRtfDraw.Position + Count) >= FRtfDraw.TextLength then
EndPrint := True;
if FirstTime And (Result < Height) then Result := Height;
end else
begin
DRect.Bottom := DRect.Top + Height - (BorderMargin * 2) - FBottomMargin;
FRtfDraw.OutRect := DRect;
EndPrint := True;
Result := Height;
Count := FRtfDraw.PrintCount;
end;
InitPrint(AceCanvas, Bounds(Rect.left, Rect.Top, width, Result - 1));
if Variable <> nil then
begin
if Variable.Active then
begin
AceCanvas.Font := Font;
AceCanvas.RtfDraw(DRect, Variable.AsStream, FRtfDraw.Position, FRtfDraw.Position + Count, FSetDefaultFont);
FRtfDraw.Position := FRtfDraw.Position + Count;
end;
end;
if Not Painting then PrintBorder(AceCanvas, Bounds(Rect.Left, Rect.Top, width, Result))
else PrintBorder(AceCanvas,Rect );
end;
procedure TSctRichTextLabel.PrintLabel( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer);
begin
PrintMemo(AceCanvas, Rect, Space);
end;
procedure TSctRichTextLabel.StartPrint;
begin
EndPrint := False;
if PrintOk then
begin
if Not RtfPrint And (TSctPage(Page).Outputtype = otRichText) then
EndPrint := True;
if Not EndPrint then
begin
FirstTime := True;
if Variable <> nil then
begin
if FRtfDraw <> nil then FRtfDraw.Free;
FRtfDraw := TAceRtfDraw.Create;
FRtfDraw.Reset;
FRtfDraw.Font := Font;
FRtfDraw.SetDefaultFont := FSetDefaultFont;
FRtfDraw.PixelsPerInchX := PixelsPerInch;
FRtfDraw.PixelsPerInchY := PixelsPerInch;
FRtfDraw.OutRect := Bounds(100,100, width - (BorderMargin*2), 2000);
FRtfDraw.LoadFromStream(Variable.AsStream);
end;
end;
end else
EndPrint := True;
end;
function TSctRichTextLabel.PrintHeight( oPage: Tcomponent; Space, taking: Integer): Integer;
var
pg: TSctPage;
R: TRect;
begin
if PrintOk then
begin
if Variable <> nil Then
begin
if FirstTime then BeforePrint;
pg := TSctPage(oPage);
if FirstTime then
begin
Space := Space - top;
R := Bounds(pg.xPos + left, pg.yPos + top, width, Space)
end else R := Bounds(pg.xPos + left, pg.yPos + 1, width, Space);
Result := PrintMemo( pg.PrintTo.AceCanvas, R, Space);
{ Adjust space taken to add in starting point of label }
if FirstTime then Result := Result + top;
if EndPrint then AfterPrint;
FirstTime := False;
end else
begin
EndPrint := True;
Result := 0;
end;
end else
begin
EndPrint := True;
Result := 0;
end;
end;
function TSctRichTextLabel.spendheight(oPage: TComponent; Space: Integer): Integer;
begin
if PrintOk And (Variable <> nil) Then
begin
FRtfDraw.PrintCount := 0;
FRtfDraw.Font := Font;
FRtfDraw.SetDefaultFont := FSetDefaultFont;
if Stretch then
begin
if FirstTime then
begin
if (Space - Top) < Height Then
begin
Result := Top + Height;
end else
begin
FRtfDraw.OutRect := Bounds(TSctPage(Parent).xPos + Left + BorderMargin
, TSctPage(Parent).yPos + Top + BorderMargin
, Width - (BorderMargin * 2)
, Space - Top - (BorderMargin * 2) - FBottomMargin);
FRtfDraw.PrintCount;
Result := Top + FRtfDraw.Height + (BorderMargin * 2) + FBottomMargin;
if ((Top + Height) > Result) And ((Top + Height) <= Space) Then Result := Top + Height;
end;
end else
begin
FRtfDraw.OutRect := Bounds(TSctPage(Parent).xPos + Left + BorderMargin
, TSctPage(Parent).yPos + BorderMargin
, Width - (BorderMargin * 2)
, Space - (BorderMargin * 2) - FBottomMargin);
FRtfDraw.PrintCount;
Result := 1 + FRtfDraw.Height + (BorderMargin * 2) + FBottomMargin;
end;
end else
begin
Result := Top + Height;
end;
end else Result := 0;
end;
procedure TSctRichTextLabel.SetVariable(Variable: TSctvar);
begin
FVariable := Variable;
Caption := DisplayText;
end;
function TSctRichTextLabel.GetDisplayText: string;
begin
if Variable <> nil then Result := Variable.Name
else Result := 'Fill in variable.';
end;
procedure TSctRichTextLabel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
Inherited Notification(AComponent, Operation);
if (AComponent is TSctvar) Then
begin
if (Operation = opRemove) And (TSctvar(AComponent) = Variable) Then
Variable := nil;
end;
end;
end.
|
PROGRAM WordCounterO;
USES
Crt, Timer, WordReader;
CONST
HashTableSize = 120000;
TYPE
Element = RECORD
value: STRING;
counter: INTEGER;
END;
Hash = 1..HashTableSize;
HashTable = ARRAY[Hash] OF ^Element;
FUNCTION ComputeHash(value: STRING): Hash;
BEGIN
IF (Length(value) = 0) THEN
ComputeHash := 1
ELSE
ComputeHash := (ORD(value[1]) MOD HashTableSize) + 1;
END;
PROCEDURE InitHashTable(VAR ht: HashTable);
VAR
i: Hash;
BEGIN
FOR i := LOW(ht) TO HIGH(ht) DO BEGIN
ht[i] := NIL;
END;
END;
PROCEDURE DisposeHashTable(VAR ht: HashTable);
VAR
i: Hash;
BEGIN
FOR i := LOW(ht) TO HIGH(ht) DO BEGIN
WHILE (ht[i] <> NIL) DO BEGIN
Dispose(ht[i]);
ht[i] := NIL;
END;
END;
END;
PROCEDURE AddToHashTable(VAR ht: HashTable; value: STRING);
VAR
i: Hash;
count: LONGINT;
BEGIN
i := ComputeHash(value);
count := 0;
WHILE (ht[i] <> NIL) AND (ht[i]^.value <> value) AND (count < HashTableSize) DO BEGIN
i := (((i - LOW(ht)) + 1 MOD HashTableSize) + LOW(ht));
INC(count);
END;
IF (ht[i] = NIL) THEN BEGIN
New(ht[i]);
ht[i]^.value := value;
ht[i]^.counter := 1;
END ELSE IF ht[i]^.value = value THEN
Inc(ht[i]^.counter)
END;
PROCEDURE DisposeWordsOnce(VAR ht: HashTable);
VAR
i: Hash;
n: ^Element;
BEGIN
FOR i := LOW(Hash) TO HIGH(Hash) DO BEGIN
IF (ht[i] <> NIL) AND (ht[i]^.counter = 1) THEN BEGIN
n := ht[i];
ht[i] := NIL;
Dispose(n);
END;
END;
END;
PROCEDURE WordsMoreThanOnce(ht: HashTable);
VAR
i: Hash;
count: LONGINT;
BEGIN
count := 0;
FOR i := LOW(Hash) TO HIGH(Hash) DO BEGIN
IF ht[i] <> NIL THEN
INC(count)
END;
WriteLn('Number of words more than once: ', count);
END;
PROCEDURE MostCommonWord(ht : HashTable);
VAR
i: Hash;
mostWordCount: LONGINT;
mostWord: STRING;
n: ^Element;
BEGIN
mostWordCount := 0;
mostWord := '';
FOR i := LOW(Hash) TO HIGH(Hash) DO BEGIN
n := ht[i];
IF (n <> NIL) AND (n^.counter > mostWordCount) THEN BEGIN
mostWord := n^.value;
mostWordCount := n^.counter;
END;
END;
WriteLn('Most common word: ', mostWord,' ', mostWordCount);
END;
VAR
w: Word;
n: LONGINT;
ht: HashTable;
BEGIN
InitHashTable(ht);
WriteLn;
WriteLn('WordCounter:');
OpenFile('Kafka.txt', toLower);
StartTimer;
n := 0;
ReadWord(w);
WHILE w <> '' DO BEGIN
n := n + 1;
AddToHashTable(ht, w);
(*insert word in data structure and count its occurence*)
ReadWord(w);
END;
StopTimer;
CloseFile;
WriteLn('number of words: ', n);
WriteLn('elapsed time: ', ElapsedTime);
MostCommonWord(ht);
DisposeWordsOnce(ht);
WordsMoreThanOnce(ht);
DisposeHashTable(ht);
END. |
unit uObjects;
interface
uses
glr_render2d,
glr_utils,
glr_math;
(*
type
{ TPopupText }
TPopupText = class (TglrText)
private
procedure SetEnabled(const aEnabled: Boolean);
public
T: Single;
property Enabled: Boolean read fVisible write SetEnabled;
end;
{ TPopupManager }
TPopupManager = class (TglrPool<TPopupText>)
private
fBatch: TglrFontBatch;
public
constructor Create(aBatch: TglrFontBatch); virtual;
procedure Update(const dt: Double);
procedure RenderSelf();
end;
TBonusType = (bHealth);
{ TBonus }
TBonus = class (TglrSprite)
private
fT, fLifeTime: Single;
fBonusType: TBonusType;
fVelocity: TglrVec3f;
procedure SetEnabled(const aEnabled: Boolean);
procedure SetBonusType(aBonusType: TBonusType);
public
property BonusType: TBonusType read fBonusType write SetBonusType;
procedure Use();
property Enabled: Boolean read fVisible write SetEnabled;
end;
{ TBonusManager }
TBonusManager = class (TglrPool<TBonus>)
private
fBatch: TglrFontBatch;
public
constructor Create(aBatch: TglrFontBatch); virtual;
procedure Update(const dt: Double);
procedure RenderSelf();
end;
TBulletType = (bSimple, bFragile, bRocket);
TBulletOwner = (bPlayer, bEnemy);
{ TBullet }
TBullet = class (TglrSprite)
private
procedure SetEnabled(const aEnabled: Boolean);
public
T, LifeTime: Single;
Velocity: TglrVec2f;
BType: TBulletType;
Owner: TBulletOwner;
Damage: Integer;
property Enabled: Boolean read fVisible write SetEnabled;
end;
{ TBulletManager }
TBulletManager = class (TglrPool<TBullet>)
private
fBatch: TglrSpriteBatch;
public
constructor Create(aBatch: TglrSpriteBatch); virtual;
procedure Update(const dt: Double);
procedure RenderSelf();
end;
*)
implementation
end.
|
{
This file is part of the AF UDF library for Firebird 1.0 or high.
Copyright (c) 2007-2009 by Arteev Alexei, OAO Pharmacy Tyumen.
See the file COPYING.TXT, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
email: alarteev@yandex.ru, arteev@pharm-tmn.ru, support@pharm-tmn.ru
**********************************************************************}
unit ufbblob;
{$MODE objfpc}
{$H+}
interface
uses Classes;
Type
// FireBird/Interbase BLOB structure
PFBBlob=^TFBBlob;
TFBBlob = record
GetSegment : function(Handle : Pointer; Buffer : PChar;
MaxLength : Longint; var ReadLength : Longint) : WordBool; cdecl;
Handle : Pointer; // BLOb handle
SegCount, // Number of BLOb segments
MaxSegLength, // Max length of BLOb segment
TotalLength : Longint; // Total BLOb length
PutSegment : procedure(Handle : Pointer; Buffer : PChar;
Length : Longint); cdecl;
// Seek : function : Long; cdecl; // I don'n know input parameters
end;
Type
{ TFBBlobStream }
TFBBlobStream=class(TStream)
private
FBlob:PFBBlob;
FPos:Int64;
protected
function GetPosition: Int64; override;
procedure SetPosition(const {%H-}Pos: Int64); override;
function GetSize: Int64; override;
procedure SetSize64(const {%H-}NewSize: Int64);override;
procedure SetSize({%H-}NewSize: Longint); override;overload;
procedure SetSize(const {%H-}NewSize: Int64); override;overload;
procedure NotSupportedSize;
procedure NotSupportedSeek;
public
constructor Create(Blob:PFBBlob);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek({%H-}Offset: Longint; {%H-}Origin: Word): Longint; override; overload;
function Seek(const {%H-}Offset: Int64; {%H-}Origin: TSeekOrigin): Int64; override; overload;
end;
{ Copy from Blob into Buffer }
function FillBuffer(var BLOb : TFBBlob; Buf : PChar; FreeBufLen : Integer;
var ReadLen : Integer) : Boolean;
{ Fill Blob from Pchar }
procedure PCharToBlob(S:PChar;var BLob:TFBBlob);
const
MaxBLObPutLength = 80;
MaxVarCharLength = 32766;
implementation
uses SysUtils;
procedure PCharToBlob(S:PChar;var BLob:TFBBlob);
var len, PutLength: LongInt;
begin
len := StrLen(S);
if len = 0 then Exit; // Is it possible to set BLOb = null when
// StrLen(CString) = 0 ?
with BLOb do
if not Assigned(Handle) then Exit;
while len > 0 do begin
if len > MaxBLObPutLength then PutLength := MaxBLObPutLength
else PutLength := len;
with BLOb do
PutSegment(Handle, S,PutLength);
Dec(len, PutLength);
Inc(S, PutLength);
end;
end;
function FillBuffer(var BLOb : TFBBlob; Buf : PChar; FreeBufLen : Integer;
var ReadLen : Integer) : Boolean;
var
EndOfBLOb : Boolean;
FreeBufLenX, GotLength : LongInt;
begin
try
ReadLen := 0;
repeat
GotLength := 0; { !?! }
if FreeBufLen > MaxBLObPutLength then FreeBufLenX := MaxBLObPutLength
else FreeBufLenX := FreeBufLen;
with BLOb do
EndOfBLOb := not GetSegment(Handle, Buf + ReadLen, FreeBufLenX, GotLength);
Inc(ReadLen, GotLength);
Dec(FreeBufLen, GotLength);
until EndOfBLOb or (FreeBufLen = 0);
except
end;
Buf[ReadLen] := #0;
Result := EndOfBLOb;
end;
{ TFBBlobStream }
function TFBBlobStream.GetPosition: Int64;
begin
Exit(FPos);
end;
procedure TFBBlobStream.SetPosition(const Pos: Int64);
begin
NotSupportedSeek;
end;
function TFBBlobStream.GetSize: Int64;
begin
if (FBlob<>nil) and Assigned(FBlob^.Handle) then
result := FBlob^.TotalLength
else
result := 0;
end;
procedure TFBBlobStream.SetSize64(const NewSize: Int64);
begin
NotSupportedSize;
end;
procedure TFBBlobStream.SetSize(NewSize: Longint);
begin
NotSupportedSize;
end;
procedure TFBBlobStream.SetSize(const NewSize: Int64);
begin
NotSupportedSize;
end;
procedure TFBBlobStream.NotSupportedSize;
begin
raise EStreamError.CreateFmt('Change size %s is not supported', [ClassName]) at get_caller_addr(get_frame);
end;
procedure TFBBlobStream.NotSupportedSeek;
begin
raise EStreamError.CreateFmt('Change position %s is not supported', [ClassName]) at get_caller_addr(get_frame);
end;
constructor TFBBlobStream.Create(Blob: PFBBlob);
begin
FPos:=0;
FBlob:=Blob;
end;
function TFBBlobStream.Read(var Buffer; Count: Longint): Longint;
var
EndOfBLOb : Boolean;
FreeBufLenX, GotLength : LongInt;
ReadLen: LongInt;
begin
try
ReadLen := 0;
repeat
GotLength := 0;
if Count > MaxBLObPutLength then
FreeBufLenX := MaxBLObPutLength
else
FreeBufLenX := Count;
with FBLOb^ do
EndOfBLOb := not GetSegment(Handle, @Buffer + ReadLen, FreeBufLenX, GotLength);
Inc(ReadLen, GotLength);
Dec(Count, GotLength);
until EndOfBLOb or (Count = 0);
except
end;
Result := ReadLen;
end;
function TFBBlobStream.Write(const Buffer; Count: Longint): Longint;
var
PutAll,
PutLength: LongInt;
begin
with FBLOb^ do
if not Assigned(Handle) then Exit(0);
PutAll := 0 ;
while Count > 0 do begin
if Count > MaxBLObPutLength then
PutLength := MaxBLObPutLength
else
PutLength := Count;
with FBlob^ do
PutSegment(Handle, @Buffer+PutAll ,PutLength);
Dec(Count, PutLength);
Inc(PutAll, PutLength);
end;
end;
function TFBBlobStream.{%H-}Seek(Offset: Longint; Origin: Word): Longint;
begin
NotSupportedSeek;
end;
function TFBBlobStream.{%H-}Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
NotSupportedSeek;
end;
end.
|
unit SystemInfo;
interface
uses
Windows;
var
keyWinCurrentVersion : string;
OSVersion : TOSVersionInfo;
SysInfo : TSystemInfo;
const
wpWinNT = VER_PLATFORM_WIN32_WINDOWS;
wpWin95 = VER_PLATFORM_WIN32_NT;
function WinPlatform : integer;
function WinPlatformStr : string;
function WinVersionStr : string;
function GlobalMemStatus : TMemoryStatus;
implementation
uses
SysUtils;
function GlobalMemStatus : TMemoryStatus;
begin
GlobalMemoryStatus( Result );
end;
function WinPlatformStr : string;
begin
case WinPlatform of
wpWin95 :
Result := 'Windows 95';
wpWinNT :
Result := 'Windows NT';
else
Result := 'Unknown';
end;
end;
function WinVersionStr : string;
begin
Result := Format( '%s, v%d.%.2d', [WinPlatformStr, OSVersion.dwMajorVersion, OSVersion.dwMinorVersion] );
end;
function WinPlatform : integer;
begin
Result := OSVersion.dwPlatformID;
end;
initialization
OSVersion.dwOSVersionInfoSize := sizeof( OSVersion );
GetVersionEx( OSVersion );
GetSystemInfo( SysInfo );
case OSVersion.dwPlatformID of
VER_PLATFORM_WIN32_WINDOWS :
keyWinCurrentVersion := 'Software\Microsoft\Windows\CurrentVersion';
VER_PLATFORM_WIN32_NT :
keyWinCurrentVersion := 'Software\Microsoft\Windows NT\CurrentVersion';
else
keyWinCurrentVersion := '';
end;
end.
|
unit vcmAeroForm;
{ Класс формы с поддержкой оформления Aero }
{ Библиотека "vcm" }
{ Автор: Морозов В.Л. }
{ Модуль: vcmAeroForm - }
{ Начат: 07.03.2014 09:05 }
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Forms,
Controls,
UxTheme;
type
TElementMargins = UxTheme.TMargins;
TvcmAeroForm = class;
TvcmGlassFrame = class(TPersistent)
private
f_Client: TvcmAeroForm;
f_Enabled: Boolean;
f_Left: Integer;
f_Top: Integer;
f_Right: Integer;
f_Bottom: Integer;
f_OnChange: TNotifyEvent;
f_SheetOfGlass: Boolean;
procedure pm_SetEnabled(aValue: Boolean);
procedure pm_SetSheetOfGlass(aValue: Boolean);
procedure pm_SetLeft(aValue: Integer);
procedure pm_SetTop(aValue: Integer);
procedure pm_SetRight(aValue: Integer);
procedure pm_SetBottom(aValue: Integer);
function pm_GetExtraRect: TRect;
function pm_GetBoundsRect: TRect;
procedure pm_SetBoundsRect(const aValue: TRect);
protected
procedure Change; virtual;
public
constructor Create(aClient: TvcmAeroForm);
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function FrameExtended: Boolean;
function IntersectsControl(aControl: TControl): Boolean;
property OnChange: TNotifyEvent read f_OnChange write f_OnChange;
published
property Enabled: Boolean read f_Enabled write pm_SetEnabled default False;
property Left: Integer read f_Left write pm_SetLeft default 0;
property Top: Integer read f_Top write pm_SetTop default 0;
property Right: Integer read f_Right write pm_SetRight default 0;
property Bottom: Integer read f_Bottom write pm_SetBottom default 0;
property ExtraRect: TRect read pm_GetExtraRect;
property SheetOfGlass: Boolean read f_SheetOfGlass write pm_SetSheetOfGlass default False;
property BoundsRect: TRect read pm_GetBoundsRect write pm_SetBoundsRect;
end;
TvcmAeroForm = class(TForm)
private
f_GlassFrame: TvcmGlassFrame;
f_GlassFramePainting: Boolean;
protected
procedure pm_SetGlassFrame(const aValue: TvcmGlassFrame);
procedure UpdateGlassFrame(aSender: TObject);
procedure UpdateGlassFrameControls(const aRect: TRect);
procedure AlignControls(Control: TControl; var Rect: TRect); override;
property GlassFramePainting: Boolean
read f_GlassFramePainting
write f_GlassFramePainting;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
property GlassFrame: TvcmGlassFrame
read f_GlassFrame
write pm_SetGlassFrame;
end;
implementation
uses
Types,
l3DwmApi;
{ TvcmGlassFrame }
constructor TvcmGlassFrame.Create(aClient: TvcmAeroForm);
begin
inherited Create;
f_Client := aClient;
f_Left := 0;
f_Top := 0;
f_Right := 0;
f_Bottom := 0;
f_SheetOfGlass := False;
end;//Create
procedure TvcmGlassFrame.Assign(Source: TPersistent);
var
l_Source: TvcmGlassFrame;
begin
if Source is TvcmGlassFrame then
begin
l_Source := TvcmGlassFrame(Source);
f_Enabled := l_Source.Enabled;
f_Left := l_Source.Left;
f_Top := l_Source.Top;
f_Right := l_Source.Right;
f_Bottom := l_Source.Bottom;
f_SheetOfGlass := l_Source.SheetOfGlass;
Change;
end
else
inherited Assign(Source);
end;//Assign
procedure TvcmGlassFrame.Change;
var
l_RectToUpdate: TRect;
begin
if not (csLoading in f_Client.ComponentState) then
begin
if Assigned(f_OnChange) then
f_OnChange(Self);
l_RectToUpdate := Rect(Left, Top, f_Client.ClientWidth - Right,
f_Client.ClientHeight - Bottom);
f_Client.UpdateGlassFrameControls(l_RectToUpdate);
end;//if not csLoading...
end;//Change
function TvcmGlassFrame.FrameExtended: Boolean;
begin
Result := (f_Enabled and DwmCompositionEnabled and
(f_SheetOfGlass or (Left <> 0) or (Top <> 0) or (Right <> 0) or (Bottom <> 0)));
end;//FrameExtended
function TvcmGlassFrame.IntersectsControl(aControl: TControl): Boolean;
var
l_ControlRect: TRect;
l_NonGlassRect: TRect;
begin
Result := False;
if (f_Enabled and DwmCompositionEnabled) then
begin
Result := f_SheetOfGlass;
if (not Result) then
begin
l_ControlRect := aControl.ClientRect;
l_ControlRect.TopLeft := aControl.ClientToParent(l_ControlRect.TopLeft,
f_Client);
l_ControlRect.BottomRight := aControl.ClientToParent(l_ControlRect.BottomRight,
f_Client);
l_NonGlassRect := f_Client.ClientRect;
l_NonGlassRect := Rect(f_Left, f_Top, l_NonGlassRect.Right - f_Right,
l_NonGlassRect.Bottom - f_Bottom);
Result := not (PtInRect(l_NonGlassRect, l_ControlRect.TopLeft)) and
(PtInRect(l_NonGlassRect, l_ControlRect.BottomRight));
end;//if not Result
end;//if (f_Enabled and DwmCompositionEnabled)
end;//IntersectsControl
procedure TvcmGlassFrame.pm_SetEnabled(aValue: Boolean);
begin
if (aValue <> f_Enabled) then
begin
f_Enabled := aValue;
if (f_Enabled and f_Client.TransparentColor) then
f_Client.TransparentColor := False;
Change;
end;//if (aValue <> f_Enabled)
end;//SetEnabled
procedure TvcmGlassFrame.pm_SetSheetOfGlass(aValue: Boolean);
begin
if (aValue <> f_SheetOfGlass) and not
(f_SheetOfGlass and ((f_Left = -1) or (f_Top = -1) or (f_Right = -1) or (f_Bottom = -1))) then
begin
f_SheetOfGlass := aValue;
Change;
end;
end;//SetSheetOfGlass
procedure TvcmGlassFrame.pm_SetBottom(aValue: Integer);
begin
if (aValue <> f_Bottom) then
begin
f_Bottom := aValue;
if (aValue = -1) then
f_SheetOfGlass := True;
Change;
end;//if (aValue <> f_Bottom)
end;//pm_SetBottom
procedure TvcmGlassFrame.pm_SetLeft(aValue: Integer);
begin
if (aValue <> f_Left) then
begin
f_Left := aValue;
if (aValue = -1) then
f_SheetOfGlass := True;
Change;
end;//if (aValue <> f_Left)
end;//pm_SetLeft
procedure TvcmGlassFrame.pm_SetRight(aValue: Integer);
begin
if (aValue <> f_Right) then
begin
f_Right := aValue;
if (aValue = -1) then
f_SheetOfGlass := True;
Change;
end;//if (aValue <> f_Right)
end;//pm_SetRight
procedure TvcmGlassFrame.pm_SetTop(aValue: Integer);
begin
if (aValue <> f_Top) then
begin
f_Top := aValue;
if (aValue = -1) then
f_SheetOfGlass := True;
Change;
end;//if (aValue <> f_Top)
end;//pm_SetTop
function TvcmGlassFrame.pm_GetExtraRect: TRect;
begin
Result := f_Client.ClientRect;
Result.Bottom := Result.Top + Top;
end;
function TvcmGlassFrame.pm_GetBoundsRect: TRect;
begin
Result.Top := Top;
Result.Left := Left;
Result.Right := Right;
Result.Bottom := Bottom;
end;
procedure TvcmGlassFrame.pm_SetBoundsRect(const aValue: TRect);
begin
Left := aValue.Left;
Top := aValue.Top;
Right := aValue.Top;
Bottom := aValue.Bottom;
end;
destructor TvcmGlassFrame.Destroy;
begin
inherited;
end;
{ TvcmAeroForm }
procedure TvcmAeroForm.AlignControls(Control: TControl;
var Rect: TRect);
var
l_RectToUpdate: TRect;
begin
inherited;
if (GlassFramePainting and not (csLoading in ComponentState)) then
begin
l_RectToUpdate := Types.Rect(f_GlassFrame.Left, f_GlassFrame.Top,
ClientWidth - f_GlassFrame.Right, ClientHeight - f_GlassFrame.Bottom);
UpdateGlassFrameControls(l_RectToUpdate);
end;//if (GlassFramePainting...
end;//AlignControls
constructor TvcmAeroForm.Create(aOwner: TComponent);
begin
inherited;
f_GlassFrame := TvcmGlassFrame.Create(Self);
f_GlassFrame.OnChange := UpdateGlassFrame;
f_GlassFrame.OnNeedUpdateGlassFrameControls := UpdateGlassFrameControls;
end;//Create
destructor TvcmAeroForm.Destroy;
begin
FreeAndNil(f_GlassFrame);
inherited;
end;//Destroy
procedure TvcmAeroForm.pm_SetGlassFrame(const aValue: TvcmGlassFrame);
begin
f_GlassFrame.Assign(aValue);
end;//pm_SetGlassFrame
procedure TvcmAeroForm.UpdateGlassFrame(aSender: TObject);
const
cSheetOfGlassMarginsSize = -1;
cSheetOfGlassMargins: TElementMargins = (cxLeftWidth: -1; cxRightWidth: -1; cyTopHeight: -1; cyBottomHeight: -1);
procedure lp_AdjustMargins(var aMargins: TElementMargins);
begin
if (not f_GlassFrame.SheetOfGlass) then
begin
aMargins.cxLeftWidth := f_GlassFrame.Left;
aMargins.cxRightWidth := f_GlassFrame.Right;
aMargins.cyTopHeight := f_GlassFrame.Top;
aMargins.cyBottomHeight := f_GlassFrame.Bottom;
end
else
aMargins := cSheetOfGlassMargins;
end;//lp_AdjustMargins;
var
l_Margins: TElementMargins;
begin
if DwmCompositionEnabled and HandleAllocated then
begin
lp_AdjustMargins(l_Margins);
if not (csDesigning in ComponentState) then
GlassFramePainting := True
else
begin
GlassFramePainting := False;
FillChar(l_Margins, SizeOf(l_Margins), 0);
end;//if Enabled
if (csDesigning in ComponentState) then
InvalidateRect(Handle, nil, True)
else
begin
DwmExtendFrameIntoClientArea(Handle, l_Margins);
Invalidate;
end;
end
else
begin
GlassFramePainting := False;
if (csDesigning in ComponentState) then
InvalidateRect(Handle, nil, True)
end;//if DwmCompositionEnabled and HandleAllocated
end;//UpdateGlassFrame
function ContainsRect(const anOuterRect: TRect; const anInnerRect: TRect): Boolean;
begin
with anInnerRect do
Result := (Left >= anOuterRect.Left) and (Right <= anOuterRect.Right) and
(Top >= anOuterRect.Top) and (Bottom <= anOuterRect.Bottom);
end;//ContainsRect
procedure TvcmAeroForm.UpdateGlassFrameControls(const aRect: TRect);
procedure lp_DoUpdateControls(aControl: TWinControl);
var
l_Index: Integer;
l_Rect: TRect;
l_Control: TControl;
begin
for l_Index := 0 to aControl.ControlCount - 1 do
begin
l_Control := aControl.Controls[l_Index];
if (not f_GlassFrame.SheetOfGlass) then
begin
l_Rect := l_Control.ClientRect;
l_Rect.TopLeft := l_Control.ClientToParent(l_Rect.TopLeft, Self);
l_Rect.BottomRight := l_Control.ClientToParent(l_Rect.BottomRight, Self);
end;//if (not f_GlassFrame.SheetOfGlass)
if (f_GlassFrame.SheetOfGlass) or (not ContainsRect(aRect, l_Rect)) then
begin
if (not GlassFramePainting) then
GlassFramePainting := True;
end
else
if GlassFramePainting then
GlassFramePainting := False;
if l_Control is TWinControl then
lp_DoUpdateControls(TWinControl(l_Control));
end;//for l_Index := 0
end;//lp_DoUpdateControls
begin
if ((not (csDesigning in ComponentState)) and DwmCompositionEnabled) then
lp_DoUpdateControls(Self);
end;//UpdateGlassFrameControls
end.
|
unit Logo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buffer, SpeedBmp;
type
TLogo =
class( TCustomControl )
private
fMaskBitmap : string;
fMask : TSpeedBitmap;
procedure SetMaskBitmap( const Value : string );
protected
procedure Loaded; override;
procedure DefineProperties( Filer : TFiler ); override;
procedure ReadData( Stream : TStream ); virtual;
procedure WriteData( Stream : TStream ); virtual;
function Equals( Value : TLogo ) : boolean; virtual;
published
property MaskBitmap : string read fMaskBitmap write SetMaskBitmap stored false;
end;
procedure Register;
implementation
uses
MemUtils;
function TLogo.Equals( Value : TLogo ) : boolean;
begin
Result := ( Assigned( fMask ) = Assigned( Value.fMask ) ) and
fMask.Equals( Value.fMask );
end;
procedure TLogo.DefineProperties( Filer : TFiler );
function DoWrite : boolean;
begin
if Filer.Ancestor <> nil
then Result := not (Filer.Ancestor is TLogo) or not Equals( TLogo( Filer.Ancestor ) )
else Result := Assigned( fMask ) and not fMask.Empty;
end;
begin
Filer.DefineBinaryProperty( 'Data', ReadData, WriteData, DoWrite );
end;
procedure TLogo.ReadData( Stream : TStream );
var
LoadMask : boolean;
begin
FreeObject( fMask );
Stream.ReadBuffer( LoadMask, sizeof( LoadMask ) );
if LoadMask
then
begin
fMask := TSpeedBitmap.Create;
fMask.LoadFromStream( Stream );
end;
end;
procedure TLogo.WriteData( Stream : TStream );
var
SaveMask : boolean;
begin
SaveMask := Assigned( fMask );
Stream.WriteBuffer( SaveMask, sizeof( SaveMask ) );
if SaveMask
then fMask.SaveToStream( Stream );
end;
procedure TLogo.Loaded;
begin
inherited;
if Assigned( fMask ) and not (csDesigning in ComponentState)
then
begin
SetWindowRgn( Handle, fMask.CreateMask( true ), Visible );
FreeObject( fMask );
end;
end;
procedure TLogo.SetMaskBitmap( const Value : string );
begin
fMaskBitmap := Value;
fMask := LoadBitmapFile( Value );
end;
procedure Register;
begin
RegisterComponents( 'Merchise', [TLogo] );
end;
end.
|
unit UniversalMapHandler;
interface
uses
VoyagerInterfaces, Classes, Controls, MPlayer, UniversalMapViewer, VoyagerServerInterfaces;
type
TUniversalMapHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler )
public
constructor Create;
destructor Destroy; override;
private
fControl : TUniversalMapView;
fUserName : string;
fPassword : string;
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
fClientView : IClientView;
end;
const
tidMetaHandler_UniversalMapHandler = 'UniversalMapHandler';
const
htmlAction_SetUserInfo = 'SETUSERINFO';
htmlParmName_Username = 'Username';
htmlParmName_Password = 'Password';
htmlParmName_Logon = 'Logon';
implementation
uses
URLParser, SysUtils, Events, ServerCnxEvents, Forms, URLUtils;
// TUniversalMapHandler
constructor TUniversalMapHandler.Create;
begin
inherited Create;
fControl := TUniversalMapView.Create( nil );
end;
destructor TUniversalMapHandler.Destroy;
begin
fControl.Free;
inherited;
end;
function TUniversalMapHandler.getName : string;
begin
result := tidMetaHandler_UniversalMapHandler;
end;
function TUniversalMapHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable];
end;
function TUniversalMapHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TUniversalMapHandler.Instantiate : IURLHandler;
begin
result := self;
end;
function TUniversalMapHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
var
AnchorData : TAnchorData;
begin
AnchorData := GetAnchorData( URL );
fControl.Logon := URLParser.StrToBoolean(URLParser.GetParmValue( URL, htmlParmName_Logon ));
if AnchorData.Action = htmlAction_SetUserInfo
then
begin
if (fClientView = nil) or (fClientView.getUserMasterName = '')
then fUserName := GetParmValue( URL, htmlParmName_Username )
else fUserName := fClientView.getUserMasterName;
fPassword := GetParmValue( URL, htmlParmName_Password );
fControl.Username := fUserName;
fControl.Password := fPassword;
fControl.Start;
end;
result := urlHandled;
end;
function TUniversalMapHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
begin
result := evnHandled;
case EventId of
evnHandlerExposed :
begin
fMasterURLHandler.HandleEvent( evnAnswerClientView, fClientView );
if fClientView <> nil
then
begin
fUserName := fClientView.getUserMasterName;
fPassword := fClientView.getUserPassword;
fControl.Username := fUserName;
fControl.Password := fPassword;
fControl.Start;
end;
end;
evnLogonCompleted :
fControl.Jump.Enabled := true;
end;
end;
function TUniversalMapHandler.getControl : TControl;
begin
result := fControl;
end;
procedure TUniversalMapHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
var
cache : string;
begin
fMasterURLHandler := URLHandler;
fControl.MasterURLHandler := URLHandler;
URLHandler.HandleEvent( evnAnswerPrivateCache, cache );
fControl.Cache := cache;
end;
end.
|
unit CompanyType;
interface
type
TCompanyType = class
private
[JSONName('type')]
Ftype: string;
public
property &type : string read Ftype write Ftype;
end;
implementation
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StNetCon.pas 4.04 *}
{*********************************************************}
{* SysTools: Net Connection Class *}
{*********************************************************}
{$I STDEFINE.INC}
{$H+} {Huge strings}
unit StNetCon;
interface
uses
Windows, Classes, StBase
{$IFDEF FPC}
, Delphi.Windows
{$ENDIF}
;
type
TStNetConnectOptions = (coUseConnectDialog, coPersistentConnection,
coReadOnlyPath, coUseMRU, coHideRestoreBox,
coPromptForAccount, coAlwaysPromptForAccount,
coRedirectIfNeeded);
TStNetDisconnectOptions = (doUseDisconnectDialog, doUpdateProfile,
doForceFilesClosed, doPromptToForceFilesClosed);
TStNetConnectOptionsSet = set of TStNetConnectOptions;
TStNetDisconnectOptionsSet = set of TStNetDisconnectOptions;
TOnConnectFailEvent = procedure(Sender: TObject; ErrorCode: DWord) of object;
TOnConnectCancelEvent = procedure(Sender: TObject; ErrorCode: DWord) of object;
TOnDisconnectFailEvent = procedure(Sender: TObject; ErrorCode: DWord) of object;
TOnDisconnectCancelEvent = procedure(Sender: TObject; ErrorCode: DWord) of object;
TStNetConnection = class(TStComponent)
protected { Protected declarations }
FLocalDevice : String;
FPassword : String;
FServerName : String;
FShareName : String;
FUserName : String;
FConnectOptions : TStNetConnectOptionsSet;
FDisconnectOptions : TStNetDisconnectOptionsSet;
FOnConnect : TNotifyEvent;
FOnConnectFail : TOnConnectFailEvent;
FOnConnectCancel : TOnConnectCancelEvent;
FOnDisconnect : TNotifyEvent;
FOnDisconnectFail : TOnDisconnectFailEvent;
FOnDisconnectCancel: TOnDisconnectCancelEvent;
private { Private declarations }
function GetServerName: string;
procedure SetServerName(Value: string);
public { Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Connect: DWord;
function Disconnect: DWord;
property Password: String read FPassword write FPassword;
property UserName: String read FUserName write FUserName;
published { Published declarations }
property ConnectOptions : TStNetConnectOptionsSet
read FConnectOptions write FConnectOptions;
property DisconnectOptions : TStNetDisconnectOptionsSet
read FDisconnectOptions write FDisconnectOptions;
property LocalDevice: String
read FLocalDevice write FLocalDevice;
property ServerName : String
read GetServerName write SetServerName;
property ShareName : String
read FShareName write FShareName;
property OnConnect: TNotifyEvent
read FOnConnect write FOnConnect;
property OnConnectFail: TOnConnectFailEvent
read FOnConnectFail write FOnConnectFail;
property OnConnectCancel: TOnConnectCancelEvent
read FOnConnectCancel write FOnConnectCancel;
property OnDisconnect: TNotifyEvent
read FOnDisconnect write FOnDisconnect;
property OnDisconnectFail: TOnDisconnectFailEvent
read FOnDisconnectFail write FOnDisconnectFail;
property OnDisconnectCancel: TOnDisconnectCancelEvent
read FOnDisconnectCancel write FOnDisconnectCancel;
end;
implementation
uses StStrL,
SysUtils;
constructor TStNetConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FConnectOptions := [coUseConnectDialog, coUseMRU, coPromptForAccount];
FDisconnectOptions := [doUseDisconnectDialog, doPromptToForceFilesClosed];
end;
destructor TStNetConnection.Destroy;
begin
inherited Destroy;
end;
function TStNetConnection.GetServerName: string;
begin
{ don't return any UNC notation }
Result := FilterL(FServerName, '\');
end;
procedure TStNetConnection.SetServerName(Value : string);
begin
{ get rid of any UNC notation or trailing marks }
Value := FilterL(Value, '\');
{ do we have a valid server name? }
if (Length(Value) > 0) then
FServerName := '\\' + Value
else
FServerName := Value;
end;
function TStNetConnection.Connect: DWord;
var
CDS : TConnectDlgStruct;
NR : TNetResource;
ServerAndShare : String;
DevRedirect : Pointer;
DevRedirectSize: DWord;
COFlags : DWord;
LDResult : DWord;
UN, PW : PChar;
X : string;
begin
{ Fill in the structures with 'nil' values as the default }
FillChar(CDS, SizeOf(CDS), 0);
FillChar(NR, SizeOf(NR), 0);
{ we can only connect to DISK resources }
NR.dwType := RESOURCETYPE_DISK;
{ fill in the default server and share names }
if (Length(FServerName) > 0) then begin
ServerAndShare := FServerName;
if (Length(FShareName) > 0) then
ServerAndShare := ServerAndShare + '\' + FShareName;
NR.lpRemoteName := PChar(ServerAndShare);
end;
{ Get the needed memory for any device redirections that occur .. 20 seems like a good buffer }
DevRedirectSize := Length(NR.lpRemoteName) + 20;
GetMem(DevRedirect, DevRedirectSize * SizeOf(Char));
LDResult := 0;
{ do we have a LocalDevice name to use? }
if Length(FLocalDevice) > 0 then
NR.lpLocalName := PChar(FLocalDevice);
if (coUseConnectDialog in FConnectOptions) then begin
{ always set the size of the record structure }
CDS.cbStructure := SizeOf(CDS);
{ what options, if any, do we need to display? }
if (coReadOnlyPath in FConnectOptions) and (Length(NR.lpRemoteName) > 1) and
(not (coUseMRU in FConnectOptions)) then
CDS.dwFlags := CDS.dwFlags + CONNDLG_RO_PATH;
if (coUseMRU in FConnectOptions) then
CDS.dwFlags := CDS.dwFlags + CONNDLG_USE_MRU;
if (coHideRestoreBox in FConnectOptions) then
CDS.dwFlags := CDS.dwFlags + CONNDLG_HIDE_BOX;
if (coPersistentConnection in FConnectOptions) then
CDS.dwFlags := CDS.dwFlags + CONNDLG_PERSIST
else
CDS.dwFlags := CDS.dwFlags + CONNDLG_NOT_PERSIST;
{ set the netresource information of the connect structure }
CDS.lpConnRes := @NR;
{ call the API and display the dialog }
Result := WNetConnectionDialog1(CDS);
if (Result = NO_ERROR) and (CDS.dwDevNum > 0) then begin
LDResult := CONNECT_LOCALDRIVE;
X := Char(Ord('A') + CDS.dwDevNum - 1) + ':';
StrCopy(DevRedirect, PChar(X));
end;
end else begin
{ fill in the necessary NetResource information }
COFlags := 0;
if (coAlwaysPromptForAccount in FConnectOptions) then
COFlags := COFlags + CONNECT_INTERACTIVE + CONNECT_PROMPT
else if (coPromptForAccount in FConnectOptions) then
COFlags := COFlags + CONNECT_INTERACTIVE;
if (coRedirectIfNeeded in FConnectOptions) then
COFlags := COFlags + CONNECT_REDIRECT;
if (coPersistentConnection in FConnectOptions) then
COFLags := COFlags + CONNECT_UPDATE_PROFILE;
{ Set up the Username and password }
UN := nil;
PW := nil;
if Length(FUserName) > 0 then
UN := PChar(FUserName);
if Length(FPassword) > 0 then
PW := PChar(FPassword);
{ Call the API .. the Parameter order is different for NT and 9x }
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
Result := WNetUseConnection(0, NR, UN, PW, COFlags, DevRedirect,
DevRedirectSize, LDResult)
else
Result := WNetUseConnection(0, NR, PW, UN, COFlags, DevRedirect,
DevRedirectSize, LDResult);
{
Result := WNetUseConnection(0, NR, UN, PW, COFlags, DevRedirect,
DevRedirectSize, LDResult);
if Result = ERROR_INVALID_PASSWORD then
Result := WNetUseConnection(0, NR, PW, UN, COFlags, DevRedirect,
DevRedirectSize, LDResult);
}
end;
case Result of
NO_ERROR :
if Assigned(FOnConnect) then
FOnConnect(Self);
1223, $FFFFFFFF :
if Assigned(FOnConnectCancel) then
FOnConnectCancel(Self, Result);
else
if Assigned(FOnConnectFail) then
FOnConnectFail(Self, Result)
end;
{ Free up the device redirection memory }
FreeMem(DevRedirect);
end;
function TStNetConnection.Disconnect: DWord;
var
DDS : TDiscDlgStruct;
ServerAndShare : String;
UpdateProfile : DWord;
begin
if (doUseDisconnectDialog in FDisconnectOptions) then begin
Result := WNetDisconnectDialog(0, RESOURCETYPE_DISK);
end else begin
{ fill in the default server and share names }
if (Length(FServerName) > 0) then begin
ServerAndShare := FServerName;
if (Length(FShareName) > 0) then
ServerAndShare := ServerAndShare + '\' + FShareName;
end;
if (doForceFilesClosed in FDisconnectOptions) and
(not (doPromptToForceFilesClosed in FDisconnectOptions)) then begin
{ what options, if any, do we need? }
if (doUpdateProfile in FDisconnectOptions) then
UpdateProfile := CONNECT_UPDATE_PROFILE
else
UpdateProfile := 0;
{ call the API }
if Length(FLocalDevice) > 0 then
Result := WNetCancelConnection2(PChar(FLocalDevice),
UpdateProfile, True)
else
Result := WNetCancelConnection2(PChar(ServerAndShare),
UpdateProfile, True)
end else begin
{ Fill in the structure with 'nil' values as the default }
FillChar(DDS, SizeOf(DDS), 0);
{ always set the size of the record structure }
DDS.cbStructure := SizeOf(DDS);
if Length(FLocalDevice) > 0 then
DDS.lpLocalName := PChar(FLocalDevice);
DDS.lpRemoteName := PChar(ServerAndShare);
{ what options, if any, do we need to display? }
if (doUpdateProfile in FDisconnectOptions) then
DDS.dwFlags := DDS.dwFlags + DISC_UPDATE_PROFILE;
if not (doForceFilesClosed in FDisconnectOptions) then
DDS.dwFlags := DDS.dwFlags + DISC_NO_FORCE;
{ call the API }
Result := WNetDisconnectDialog1(DDS);
end;
end;
case Result of
NO_ERROR :
if Assigned(FOnDisconnect) then
FOnDisconnect(Self);
$FFFFFFFF :
if Assigned(FOnDisconnectCancel)
then FOnDisconnectCancel(Self, Result);
else
if Assigned(FOnDisconnectFail) then
FOnDisconnectFail(Self, Result)
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.