text stringlengths 14 6.51M |
|---|
unit LLVM.Imports.Core;
interface
//based on Core.h
uses
LLVM.Imports,
LLVM.Imports.Types;
{$MinEnumSize 4}
const
// versione
LTO_API_VERSION = 24;
type
TLLVMAttrKind = (
// IR-Level Attributes
LLVMNone, ///< No attributes have been set
LLVMAlignment, //'align',
LLVMAllocSize, //'allocsize',
LLVMAlwaysInline, //'alwaysinline',
LLVMArgMemOnly, //'argmemonly',
LLVMBuiltin, //'builtin',
LLVMByVal, //'byval',
LLVMCold, //'cold',
LLVMConvergent, //'convergent',
LLVMDereferenceable, //'dereferenceable',
LLVMDereferenceableOrNull, //'dereferenceable_or_null',
LLVMImmArg, //'immarg',
LLVMInAlloca, //'inalloca',
LLVMInReg, //'inreg',
LLVMInaccessibleMemOnly, //'inaccessiblememonly',
LLVMInaccessibleMemOrArgMemOnly, //'inaccessiblemem_or_argmemonly',
LLVMInlineHint, //'inlinehint',
LLVMJumpTable, //'jumptable',
LLVMMinSize, //'minsize',
LLVMNaked, //'naked',
LLVMNest, //'nest',
LLVMNoAlias, //'noalias',
LLVMNoBuiltin, //'nobuiltin',
LLVMNoCapture, //'nocapture',
LLVMNoCfCheck, //'nocf_check',
LLVMNoDuplicate, //'noduplicate',
LLVMNoFree, //'nofree',
LLVMNoImplicitFloat, //'noimplicitfloat',
LLVMNoInline, //'noinline',
LLVMNoRecurse, //'norecurse',
LLVMNoRedZone, //'noredzone',
LLVMNoReturn, //'noreturn',
LLVMNoSync, //'nosync',
LLVMNoUnwind, //'nounwind',
LLVMNonLazyBind, //'nonlazybind',
LLVMNonNull, //'nonnull',
LLVMOptForFuzzing, //'optforfuzzing',
LLVMOptimizeForSize, //'optsize',
LLVMOptimizeNone, //'optnone',
LLVMReadNone, //'readnone',
LLVMReadOnly, //'readonly',
LLVMReturned, //'returned',
LLVMReturnsTwice, //'returns_twice',
LLVMSignedExt, //'signext',
LLVMSafeStack, //'safestack',
LLVMSanitizeAddress, //'sanitize_address',
LLVMSanitizeHWAddress, //'sanitize_hwaddress',
LLVMSanitizeMemTag, //'sanitize_memtag',
LLVMSanitizeMemory, //'sanitize_memory',
LLVMSanitizeThread, //'sanitize_thread',
LLVMShadowCallStack, //'shadowcallstack',
LLVMSpeculatable, //'speculatable',
LLVMSpeculativeLoadHardening, //'speculative_load_hardening',
LLVMStackAlignment, //'alignstack',
LLVMStackProtect, //'ssp',
LLVMStackProtectReq, //'sspreq',
LLVMStackProtectStrong, //'sspstrong',
LLVMStrictFP, //'strictfp',
LLVMStructRet, //'sret',
LLVMSwiftError, //'swifterror',
LLVMSwiftSelf, //'swiftself',
LLVMUWTable, //'uwtable',
LLVMWillReturn, //'willreturn',
LLVMWriteOnly, //'writeonly',
LLVMZeroExt, //'zeroext',
LLVMEndAttrKinds); ///< Sentinal value useful for loops
TLLVMOpcode = (
//* Terminator Instructions */
LLVMRet = 1,
LLVMBr = 2,
LLVMSwitch = 3,
LLVMIndirectBr = 4,
LLVMInvoke = 5,
//* removed 6 due to API changes */
LLVMUnreachable = 7,
//* Standard Binary Operators */
LLVMAdd = 8,
LLVMFAdd = 9,
LLVMSub = 10,
LLVMFSub = 11,
LLVMMul = 12,
LLVMFMul = 13,
LLVMUDiv = 14,
LLVMSDiv = 15,
LLVMFDiv = 16,
LLVMURem = 17,
LLVMSRem = 18,
LLVMFRem = 19,
//* Logical Operators */
LLVMShl = 20,
LLVMLShr = 21,
LLVMAShr = 22,
LLVMAnd = 23,
LLVMOr = 24,
LLVMXor = 25,
//* Memory Operators */
LLVMAlloca = 26,
LLVMLoad = 27,
LLVMStore = 28,
LLVMGetElementPtr = 29,
//* Cast Operators */
LLVMTrunc = 30,
LLVMZExt = 31,
LLVMSExt = 32,
LLVMFPToUI = 33,
LLVMFPToSI = 34,
LLVMUIToFP = 35,
LLVMSIToFP = 36,
LLVMFPTrunc = 37,
LLVMFPExt = 38,
LLVMPtrToInt = 39,
LLVMIntToPtr = 40,
LLVMBitCast = 41,
LLVMAddrSpaceCast = 60,
//* Other Operators */
LLVMICmp = 42,
LLVMFCmp = 43,
LLVMPHI = 44,
LLVMCall = 45,
LLVMSelect = 46,
LLVMUserOp1 = 47,
LLVMUserOp2 = 48,
LLVMVAArg = 49,
LLVMExtractElement = 50,
LLVMInsertElement = 51,
LLVMShuffleVector = 52,
LLVMExtractValue = 53,
LLVMInsertValue = 54,
//* Atomic operators */
LLVMFence = 55,
LLVMAtomicCmpXchg = 56,
LLVMAtomicRMW = 57,
//* Exception Handling Operators */
LLVMResume = 58,
LLVMLandingPad = 59,
LLVMCleanupRet = 61,
LLVMCatchRet = 62,
LLVMCatchPad = 63,
LLVMCleanupPad = 64,
LLVMCatchSwitch = 65,
{/* Standard Unary Operators */}
LLVMFNeg = 66,
LLVMCallBr = 67
);
TLLVMTypeKind = (
LLVMVoidTypeKind, //**< type with no size */
LLVMHalfTypeKind, //**< 16 bit floating point type */
LLVMFloatTypeKind, //**< 32 bit floating point type */
LLVMDoubleTypeKind, //**< 64 bit floating point type */
LLVMX86_FP80TypeKind, //**< 80 bit floating point type (X87) */
LLVMFP128TypeKind, //**< 128 bit floating point type (112-bit mantissa)*/
LLVMPPC_FP128TypeKind, //**< 128 bit floating point type (two 64-bits) */
LLVMLabelTypeKind, //**< Labels */
LLVMIntegerTypeKind, //**< Arbitrary bit width integers */
LLVMFunctionTypeKind, //**< Functions */
LLVMStructTypeKind, //**< Structures */
LLVMArrayTypeKind, //**< Arrays */
LLVMPointerTypeKind, //**< Pointers */
LLVMVectorTypeKind, //**< SIMD 'packed' format, or other vector type */
LLVMMetadataTypeKind, //**< Metadata */
LLVMX86_MMXTypeKind, //**< X86 MMX */
LLVMTokenTypeKind //**< Tokens */
);
TLLVMLinkage = (
LLVMExternalLinkage, //**< Externally visible function */
LLVMAvailableExternallyLinkage,
LLVMLinkOnceAnyLinkage, //**< Keep one copy of function when linking (inline)*/
LLVMLinkOnceODRLinkage, //**< Same, but only replaced by something equivalent. */
LLVMLinkOnceODRAutoHideLinkage, //**< Obsolete */
LLVMWeakAnyLinkage, //**< Keep one copy of function when linking (weak) */
LLVMWeakODRLinkage, //**< Same, but only replaced by something equivalent. */
LLVMAppendingLinkage, //**< Special purpose, only applies to global arrays */
LLVMInternalLinkage, //**< Rename collisions when linking (static functions) */
LLVMPrivateLinkage, //**< Like Internal, but omit from symbol table */
LLVMDLLImportLinkage, //**< Obsolete */
LLVMDLLExportLinkage, //**< Obsolete */
LLVMExternalWeakLinkage,//**< ExternalWeak linkage description */
LLVMGhostLinkage, //**< Obsolete */
LLVMCommonLinkage, //**< Tentative definitions */
LLVMLinkerPrivateLinkage, //**< Like Private, but linker removes. */
LLVMLinkerPrivateWeakLinkage //**< Like LinkerPrivate, but is weak. */
);
TLLVMVisibility = (
LLVMDefaultVisibility, //**< The GV is visible */
LLVMHiddenVisibility, //**< The GV is hidden */
LLVMProtectedVisibility //**< The GV is protected */
);
TLLVMUnnamedAddr = (
LLVMNoUnnamedAddr, {/**< Address of the GV is significant. */}
LLVMLocalUnnamedAddr, {/**< Address of the GV is locally insignificant. */}
LLVMGlobalUnnamedAddr {/**< Address of the GV is globally insignificant. */}
);
TLLVMDLLStorageClass = (
LLVMDefaultStorageClass = 0,
LLVMDLLImportStorageClass = 1, //**< Function to be imported from DLL. */
LLVMDLLExportStorageClass = 2 //**< Function to be accessible from DLL. */
);
TLLVMCallConv = (
LLVMCCallConv = 0,
LLVMFastCallConv = 8,
LLVMColdCallConv = 9,
LLVMGHCCallConv = 10,
LLVMHiPECallConv = 11,
LLVMWebKitJSCallConv = 12,
LLVMAnyRegCallConv = 13,
LLVMPreserveMostCallConv = 14,
LLVMPreserveAllCallConv = 15,
LLVMSwiftCallConv = 16,
LLVMCXXFASTTLSCallConv = 17,
LLVMX86StdcallCallConv = 64,
LLVMX86FastcallCallConv = 65,
LLVMARMAPCSCallConv = 66,
LLVMARMAAPCSCallConv = 67,
LLVMARMAAPCSVFPCallConv = 68,
LLVMMSP430INTRCallConv = 69,
LLVMX86ThisCallCallConv = 70,
LLVMPTXKernelCallConv = 71,
LLVMPTXDeviceCallConv = 72,
LLVMSPIRFUNCCallConv = 75,
LLVMSPIRKERNELCallConv = 76,
LLVMIntelOCLBICallConv = 77,
LLVMX8664SysVCallConv = 78,
LLVMWin64CallConv = 79,
LLVMX86VectorCallCallConv = 80,
LLVMHHVMCallConv = 81,
LLVMHHVMCCallConv = 82,
LLVMX86INTRCallConv = 83,
LLVMAVRINTRCallConv = 84,
LLVMAVRSIGNALCallConv = 85,
LLVMAVRBUILTINCallConv = 86,
LLVMAMDGPUVSCallConv = 87,
LLVMAMDGPUGSCallConv = 88,
LLVMAMDGPUPSCallConv = 89,
LLVMAMDGPUCSCallConv = 90,
LLVMAMDGPUKERNELCallConv = 91,
LLVMX86RegCallCallConv = 92,
LLVMAMDGPUHSCallConv = 93,
LLVMMSP430BUILTINCallConv = 94,
LLVMAMDGPULSCallConv = 95,
LLVMAMDGPUESCallConv = 96
);
TLLVMValueKind = (
LLVMArgumentValueKind,
LLVMBasicBlockValueKind,
LLVMMemoryUseValueKind,
LLVMMemoryDefValueKind,
LLVMMemoryPhiValueKind,
LLVMFunctionValueKind,
LLVMGlobalAliasValueKind,
LLVMGlobalIFuncValueKind,
LLVMGlobalVariableValueKind,
LLVMBlockAddressValueKind,
LLVMConstantExprValueKind,
LLVMConstantArrayValueKind,
LLVMConstantStructValueKind,
LLVMConstantVectorValueKind,
LLVMUndefValueValueKind,
LLVMConstantAggregateZeroValueKind,
LLVMConstantDataArrayValueKind,
LLVMConstantDataVectorValueKind,
LLVMConstantIntValueKind,
LLVMConstantFPValueKind,
LLVMConstantPointerNullValueKind,
LLVMConstantTokenNoneValueKind,
LLVMMetadataAsValueValueKind,
LLVMInlineAsmValueKind,
LLVMInstructionValueKind
);
TLLVMIntPredicate = (
LLVMIntEQ = 32, //**< equal */
LLVMIntNE, //**< not equal */
LLVMIntUGT, //**< unsigned greater than */
LLVMIntUGE, //**< unsigned greater or equal */
LLVMIntULT, //**< unsigned less than */
LLVMIntULE, //**< unsigned less or equal */
LLVMIntSGT, //**< signed greater than */
LLVMIntSGE, //**< signed greater or equal */
LLVMIntSLT, //**< signed less than */
LLVMIntSLE //**< signed less or equal */
);
TLLVMRealPredicate = (
LLVMRealPredicateFalse, //**< Always false (always folded) */
LLVMRealOEQ, //**< True if ordered and equal */
LLVMRealOGT, //**< True if ordered and greater than */
LLVMRealOGE, //**< True if ordered and greater than or equal */
LLVMRealOLT, //**< True if ordered and less than */
LLVMRealOLE, //**< True if ordered and less than or equal */
LLVMRealONE, //**< True if ordered and operands are unequal */
LLVMRealORD, //**< True if ordered (no nans) */
LLVMRealUNO, //**< True if unordered: isnan(X) | isnan(Y) */
LLVMRealUEQ, //**< True if unordered or equal */
LLVMRealUGT, //**< True if unordered or greater than */
LLVMRealUGE, //**< True if unordered, greater than, or equal */
LLVMRealULT, //**< True if unordered or less than */
LLVMRealULE, //**< True if unordered, less than, or equal */
LLVMRealUNE, //**< True if unordered or not equal */
LLVMRealPredicateTrue //**< Always true (always folded) */
);
TLLVMLandingPadClauseTy = (
LLVMLandingPadCatch, //**< A catch clause */
LLVMLandingPadFilter //**< A filter clause */
);
TLLVMThreadLocalMode = (
LLVMNotThreadLocal = 0,
LLVMGeneralDynamicTLSModel,
LLVMLocalDynamicTLSModel,
LLVMInitialExecTLSModel,
LLVMLocalExecTLSModel
);
TLLVMAtomicOrdering = (
LLVMAtomicOrderingNotAtomic = 0, //**< A load or store which is not atomic */
LLVMAtomicOrderingUnordered = 1, //**< Lowest level of atomicity, guarantees somewhat sane results, lock free. */
LLVMAtomicOrderingMonotonic = 2, //**< guarantees that if you take all the operations affecting a specific address, a consistent ordering exists */
LLVMAtomicOrderingAcquire = 4, //**< Acquire provides a barrier of the sort necessary to acquire a lock to access other memory with normal loads and stores. */
LLVMAtomicOrderingRelease = 5, //**< Release is similar to Acquire, but with a barrier of the sort necessary to release a lock. */
LLVMAtomicOrderingAcquireRelease = 6, //**< provides both an Acquire and a Release barrier (for fences and operations which both read and write memory). */
LLVMAtomicOrderingSequentiallyConsistent = 7 //**< provides Acquire semantics for loads and Release semantics for stores. Additionally, it guarantees that a total ordering exists between all SequentiallyConsistent operations. */
);
TLLVMAtomicRMWBinOp = (
LLVMAtomicRMWBinOpXchg, //**< Set the new value and return the one old */
LLVMAtomicRMWBinOpAdd, //**< Add a value and return the old one */
LLVMAtomicRMWBinOpSub, //**< Subtract a value and return the old one */
LLVMAtomicRMWBinOpAnd, //**< And a value and return the old one */
LLVMAtomicRMWBinOpNand, //**< Not-And a value and return the old one */
LLVMAtomicRMWBinOpOr, //**< OR a value and return the old one */
LLVMAtomicRMWBinOpXor, //**< Xor a value and return the old one */
LLVMAtomicRMWBinOpMax, //**< Sets the value if it's greater than the original using a signed comparison and return the old one */
LLVMAtomicRMWBinOpMin, //**< Sets the value if it's Smaller than the original using a signed comparison and return the old one */
LLVMAtomicRMWBinOpUMax, //**< Sets the value if it's greater than the original using an unsigned comparison and return the old one */
LLVMAtomicRMWBinOpUMin //**< Sets the value if it's greater than the original using an unsigned comparison and return the old one */
);
TLLVMDiagnosticSeverity = (
LLVMDSError,
LLVMDSWarning,
LLVMDSRemark,
LLVMDSNote
);
TLLVMInlineAsmDialect = (
LLVMInlineAsmDialectATT,
LLVMInlineAsmDialectIntel
);
TLLVMModuleFlagBehavior = (
(**
* Emits an error if two values disagree, otherwise the resulting value is
* that of the operands.
*
* @see Module::ModFlagBehavior::Error
*)
LLVMModuleFlagBehaviorError,
(**
* Emits a warning if two values disagree. The result value will be the
* operand for the flag from the first module being linked.
*
* @see Module::ModFlagBehavior::Warning
*)
LLVMModuleFlagBehaviorWarning,
(**
* Adds a requirement that another module flag be present and have a
* specified value after linking is performed. The value must be a metadata
* pair, where the first element of the pair is the ID of the module flag
* to be restricted, and the second element of the pair is the value the
* module flag should be restricted to. This behavior can be used to
* restrict the allowable results (via triggering of an error) of linking
* IDs with the **Override** behavior.
*
* @see Module::ModFlagBehavior::Require
*)
LLVMModuleFlagBehaviorRequire,
(**
* Uses the specified value, regardless of the behavior or value of the
* other module. If both modules specify **Override**, but the values
* differ, an error will be emitted.
*
* @see Module::ModFlagBehavior::Override
*)
LLVMModuleFlagBehaviorOverride,
(**
* Appends the two values, which are required to be metadata nodes.
*
* @see Module::ModFlagBehavior::Append
*)
LLVMModuleFlagBehaviorAppend,
(**
* Appends the two values, which are required to be metadata
* nodes. However, duplicate entries in the second list are dropped
* during the append operation.
*
* @see Module::ModFlagBehavior::AppendUnique
*)
LLVMModuleFlagBehaviorAppendUnique
);
{//**
* Attribute index are either LLVMAttributeReturnIndex,
* LLVMAttributeFunctionIndex or a parameter number from 1 to N.
*/}
TLLVMAttributeIndex = (
LLVMAttributeReturnIndex = 0,
// ISO C restricts enumerator values to range of 'int'
// (4294967295 is too large)
// LLVMAttributeFunctionIndex = ~0U,
LLVMAttributeFunctionIndex = -1
);
procedure LLVMInitializeCore(R: TLLVMPassRegistryRef); cdecl; external CLLVMLibrary;
procedure LLVMShutdown; cdecl; external CLLVMLibrary;
function LLVMCreateMessage(const Message: PLLVMChar): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMDisposeMessage(Message: PLLVMChar); cdecl; external CLLVMLibrary;
type
TLLVMDiagnosticHandler = procedure(DiagnosticInfo: TLLVMDiagnosticInfoRef; UserContext: Pointer); cdecl;
TLLVMYieldCallback = procedure(Context: TLLVMContextRef; UserContext: Pointer); cdecl;
function LLVMContextCreate: TLLVMContextRef cdecl; external CLLVMLibrary;
function LLVMGetGlobalContext: TLLVMContextRef; cdecl; external CLLVMLibrary;
procedure LLVMContextSetDiagnosticHandler(C: TLLVMContextRef; Handler: TLLVMDiagnosticHandler; DiagnosticContext: Pointer); cdecl; external CLLVMLibrary;
function LLVMContextGetDiagnosticHandler(C: TLLVMContextRef): TLLVMDiagnosticHandler; cdecl; external CLLVMLibrary;
function LLVMContextGetDiagnosticContext(C: TLLVMContextRef): Pointer; cdecl; external CLLVMLibrary;
procedure LLVMContextSetYieldCallback(C: TLLVMContextRef; Callback: TLLVMYieldCallback; OpaqueHandle: Pointer); cdecl; external CLLVMLibrary;
(**
* Retrieve whether the given context is set to discard all value names.
*
* @see LLVMContext::shouldDiscardValueNames()
*)
function LLVMContextShouldDiscardValueNames(C: TLLVMContextRef): TLLVMBool; cdecl; external CLLVMLibrary;
(**
* Set whether the given context discards all value names.
*
* If true, only the names of GlobalValue objects will be available in the IR.
* This can be used to save memory and runtime, especially in release mode.
*
* @see LLVMContext::setDiscardValueNames()
*)
procedure LLVMContextSetDiscardValueNames(C: TLLVMContextRef; Discard: TLLVMBool); cdecl; external CLLVMLibrary;
procedure LLVMContextDispose(C: TLLVMContextRef); cdecl; external CLLVMLibrary;
function LLVMGetDiagInfoDescription(DI: TLLVMDiagnosticInfoRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetDiagInfoSeverity(DI: TLLVMDiagnosticInfoRef): TLLVMDiagnosticSeverity; cdecl; external CLLVMLibrary;
function LLVMGetMDKindIDInContext(C: TLLVMContextRef; const Name: PLLVMChar; SLen: Cardinal): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetMDKindID(const Name: PLLVMChar; SLen: Cardinal): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetEnumAttributeKindForName(const Name: PLLVMChar; SLen: TLLVMSizeT): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetLastEnumAttributeKind: Cardinal; cdecl; external CLLVMLibrary;
function LLVMCreateEnumAttribute(C: TLLVMContextRef; KindID: Cardinal; Val: UInt64): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
function LLVMGetEnumAttributeKind(A: TLLVMAttributeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetEnumAttributeValue(A: TLLVMAttributeRef): UInt64; cdecl; external CLLVMLibrary;
function LLVMCreateStringAttribute(C: TLLVMContextRef; const K: PLLVMChar; KLength: Cardinal; const V: PLLVMChar; VLength: Cardinal): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
function LLVMGetStringAttributeKind(A: TLLVMAttributeRef; out Length: Cardinal): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetStringAttributeValue(A: TLLVMAttributeRef; out Length: Cardinal): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMIsEnumAttribute(A: TLLVMAttributeRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMIsStringAttribute(A: TLLVMAttributeRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMModuleCreateWithName(const ModuleID: PLLVMChar): TLLVMModuleRef; cdecl; external CLLVMLibrary;
function LLVMModuleCreateWithNameInContext(const ModuleID: PLLVMChar; C: TLLVMContextRef): TLLVMModuleRef; cdecl; external CLLVMLibrary;
function LLVMCloneModule(M: TLLVMModuleRef): TLLVMModuleRef; cdecl; external CLLVMLibrary;
procedure LLVMDisposeModule(M: TLLVMModuleRef); cdecl; external CLLVMLibrary;
function LLVMGetModuleIdentifier(M: TLLVMModuleRef; out Len: TLLVMSizeT): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMSetModuleIdentifier(M: TLLVMModuleRef; const Ident: PLLVMChar; Len: TLLVMSizeT); cdecl; external CLLVMLibrary;
(**
* Obtain the module's original source file name.
*
* @param M Module to obtain the name of
* @param Len Out parameter which holds the length of the returned string
* @return The original source file name of M
* @see Module::getSourceFileName()
*)
function LLVMGetSourceFileName(M: TLLVMModuleRef; var Len: TLLVMSizeT):PLLVMChar;cdecl; external CLLVMLibrary;
(**
* Set the original source file name of a module to a string Name with length
* Len.
*
* @param M The module to set the source file name of
* @param Name The string to set M's source file name to
* @param Len Length of Name
* @see Module::setSourceFileName()
*)
procedure LLVMSetSourceFileName(M: TLLVMModuleRef; Name: PLLVMChar; Len: TLLVMSizeT); cdecl; external CLLVMLibrary;
function LLVMGetDataLayoutStr(M: TLLVMModuleRef): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMSetDataLayout(M: TLLVMModuleRef; const DataLayoutStr: PLLVMChar); cdecl; external CLLVMLibrary;
function LLVMGetTarget(M: TLLVMModuleRef): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMSetTarget(M: TLLVMModuleRef; const Triple: PLLVMChar); cdecl; external CLLVMLibrary;
(**
* Returns the module flags as an array of flag-key-value triples. The caller
* is responsible for freeing this array by calling
* \c LLVMDisposeModuleFlagsMetadata.
*
* @see Module::getModuleFlagsMetadata()
*)
function LLVMCopyModuleFlagsMetadata(M: TLLVMModuleRef; var Len: TLLVMSizeT): PLLVMModuleFlagEntry;cdecl; external CLLVMLibrary;
(**
* Destroys module flags metadata entries.
*)
procedure LLVMDisposeModuleFlagsMetadata(Entries: PLLVMModuleFlagEntry); cdecl; external CLLVMLibrary;
(**
* Returns the flag behavior for a module flag entry at a specific index.
*
* @see Module::ModuleFlagEntry::Behavior
*)
function LLVMModuleFlagEntriesGetFlagBehavior(Entries : PLLVMModuleFlagEntry;Index: Cardinal): TLLVMModuleFlagBehavior; cdecl; external CLLVMLibrary;
(**
* Returns the key for a module flag entry at a specific index.
*
* @see Module::ModuleFlagEntry::Key
*)
function LLVMModuleFlagEntriesGetKey(Entries: PLLVMModuleFlagEntry;Index: Cardinal; var Len:TLLVMSizeT):PLLVMChar;cdecl; external CLLVMLibrary;
(**
* Returns the metadata for a module flag entry at a specific index.
*
* @see Module::ModuleFlagEntry::Val
*)
function LLVMModuleFlagEntriesGetMetadata(Entries: PLLVMModuleFlagEntry; Index: Cardinal):TLLVMMetadataRef;cdecl; external CLLVMLibrary;
(**
* Add a module-level flag to the module-level flags metadata if it doesn't
* already exist.
*
* @see Module::getModuleFlag()
*)
function LLVMGetModuleFlag(M: TLLVMModuleRef; Key: PLLVMChar; KeyLen: TLLVMSizeT): TLLVMMetadataRef; cdecl; external CLLVMLibrary;
(**
* Add a module-level flag to the module-level flags metadata if it doesn't
* already exist.
*
* @see Module::addModuleFlag()
*)
procedure LLVMAddModuleFlag(M: TLLVMModuleRef; Behavior : TLLVMModuleFlagBehavior; Key: PLLVMChar;KeyLen:TLLVMSizeT; Val : TLLVMMetadataRef ); cdecl; external CLLVMLibrary;
procedure LLVMDumpModule(M: TLLVMModuleRef); cdecl; external CLLVMLibrary;
function LLVMPrintModuleToFile(M: TLLVMModuleRef; const Filename: PLLVMChar; out ErrorMessage: PLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary;
function LLVMPrintModuleToString(M: TLLVMModuleRef): PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Get inline assembly for a module.
*
* @see Module::getModuleInlineAsm()
*)
function LLVMGetModuleInlineAsm(M: TLLVMModuleRef; var Len: TLLVMSizeT): PLLVMChar;cdecl; external CLLVMLibrary;
(**
* Set inline assembly for a module.
*
* @see Module::setModuleInlineAsm()
*)
procedure LLVMSetModuleInlineAsm2(M: TLLVMModuleRef; const InlineAsm: PLLVMChar; Len: TLLVMSizeT); cdecl; external CLLVMLibrary;
(**
* Append inline assembly to a module.
*
* @see Module::appendModuleInlineAsm()
*)
procedure LLVMAppendModuleInlineAsm(M: TLLVMModuleRef; const InlineAsm: PLLVMChar; Len: TLLVMSizeT); cdecl; external CLLVMLibrary;
(**
* Create the specified uniqued inline asm string.
*
* @see InlineAsm::get()
*)
function LLVMGetInlineAsm(Ty : TLLVMTypeRef;
AsmString : PLLVMChar;
AsmStringSize : TLLVMSizeT;
Constraints : PLLVMChar;
ConstraintsSize : TLLVMSizeT;
HasSideEffects : TLLVMBool;
IsAlignStack : TLLVMBool;
Dialect : TLLVMInlineAsmDialect): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetModuleContext(M: TLLVMModuleRef): TLLVMContextRef; cdecl; external CLLVMLibrary;
function LLVMGetTypeByName(M: TLLVMModuleRef; const Name: PLLVMChar): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(*
* Obtain an iterator to the first NamedMDNode in a Module.
*
* @see llvm::Module::named_metadata_begin()
*)
function LLVMGetFirstNamedMetadata(M: TLLVMModuleRef):TLLVMNamedMDNodeRef; cdecl; external CLLVMLibrary;
(**
* Obtain an iterator to the last NamedMDNode in a Module.
*
* @see llvm::Module::named_metadata_end()
*)
function LLVMGetLastNamedMetadata(M: TLLVMModuleRef):TLLVMNamedMDNodeRef ; cdecl; external CLLVMLibrary;
(**
* Advance a NamedMDNode iterator to the next NamedMDNode.
*
* Returns NULL if the iterator was already at the end and there are no more
* named metadata nodes.
*)
function LLVMGetNextNamedMetadata(NamedMDNode: TLLVMNamedMDNodeRef): TLLVMNamedMDNodeRef;cdecl; external CLLVMLibrary;
(**
* Decrement a NamedMDNode iterator to the previous NamedMDNode.
*
* Returns NULL if the iterator was already at the beginning and there are
* no previous named metadata nodes.
*)
function LLVMGetPreviousNamedMetadata(NamedMDNode: TLLVMNamedMDNodeRef): TLLVMNamedMDNodeRef;cdecl; external CLLVMLibrary;
(**
* Retrieve a NamedMDNode with the given name, returning NULL if no such
* node exists.
*
* @see llvm::Module::getNamedMetadata()
*)
function LLVMGetNamedMetadata(M: TLLVMModuleRef; const Name: PLLVMChar; NameLen: TLLVMSizeT ): TLLVMNamedMDNodeRef; cdecl; external CLLVMLibrary;
(**
* Retrieve a NamedMDNode with the given name, creating a new node if no such
* node exists.
*
* @see llvm::Module::getOrInsertNamedMetadata()
*)
function LLVMGetOrInsertNamedMetadata(M: TLLVMModuleRef;const Name: PLLVMChar; NameLen: TLLVMSizeT):TLLVMNamedMDNodeRef; cdecl; external CLLVMLibrary;
(**
* Retrieve the name of a NamedMDNode.
*
* @see llvm::NamedMDNode::getName()
*)
function LLVMGetNamedMetadataName(NamedMD: TLLVMNamedMDNodeRef; var NameLen:TLLVMSizeT): TLLVMNamedMDNodeRef; cdecl; external CLLVMLibrary;
function LLVMGetNamedMetadataNumOperands(M: TLLVMModuleRef; const Name: PLLVMChar): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetNamedMetadataOperands(M: TLLVMModuleRef; const Name: PLLVMChar; out Dest: PLLVMValueRef); cdecl; external CLLVMLibrary;
(*
* Add an operand to named metadata.
*
* @see llvm::Module::getNamedMetadata()
* @see llvm::MDNode::addOperand()
*)
procedure LLVMAddNamedMetadataOperand(M: TLLVMModuleRef; const Name: PLLVMChar; Val: TLLVMValueRef);cdecl; external CLLVMLibrary;
(**
* Return the directory of the debug location for this value, which must be
* an llvm::Instruction, llvm::GlobalVariable, or llvm::Function.
*
* @see llvm::Instruction::getDebugLoc()
* @see llvm::GlobalVariable::getDebugInfo()
* @see llvm::Function::getSubprogram()
*)
function LLVMGetDebugLocDirectory(Val: TLLVMValueRef; var Len: Cardinal):PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Return the filename of the debug location for this value, which must be
* an llvm::Instruction, llvm::GlobalVariable, or llvm::Function.
*
* @see llvm::Instruction::getDebugLoc()
* @see llvm::GlobalVariable::getDebugInfo()
* @see llvm::Function::getSubprogram()
*)
function LLVMGetDebugLocFilename(Val: TLLVMValueRef; var Len: Cardinal):PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Return the line number of the debug location for this value, which must be
* an llvm::Instruction, llvm::GlobalVariable, or llvm::Function.
*
* @see llvm::Instruction::getDebugLoc()
* @see llvm::GlobalVariable::getDebugInfo()
* @see llvm::Function::getSubprogram()
*)
function LLVMGetDebugLocLine(Val: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Return the column number of the debug location for this value, which must be
* an llvm::Instruction.
*
* @see llvm::Instruction::getDebugLoc()
*)
function LLVMGetDebugLocColumn(Val: TLLVMValueRef):Cardinal; cdecl; external CLLVMLibrary;
function LLVMAddFunction(M: TLLVMModuleRef; const Name: PLLVMChar; FunctionTy: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain a Function value from a Module by its name.
*
* The returned value corresponds to a llvm::Function value.
*
* @see llvm::Module::getFunction()
*)
function LLVMGetNamedFunction(M: TLLVMModuleRef; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetFirstFunction(M: TLLVMModuleRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetLastFunction(M: TLLVMModuleRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetNextFunction(Fn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetPreviousFunction(Fn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
{* Deprecated: Use LLVMSetModuleInlineAsm2 instead. *}
procedure LLVMSetModuleInlineAsm(M: TLLVMModuleRef; const InlineAsm: PLLVMChar); cdecl; external CLLVMLibrary;
function LLVMGetTypeKind(Ty: TLLVMTypeRef): TLLVMTypeKind; cdecl; external CLLVMLibrary;
function LLVMTypeIsSized(Ty: TLLVMTypeRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMGetTypeContext(Ty: TLLVMTypeRef): TLLVMContextRef; cdecl; external CLLVMLibrary;
procedure LLVMDumpType(Val: TLLVMTypeRef); cdecl; external CLLVMLibrary;
function LLVMPrintTypeToString(Val: TLLVMTypeRef): PLLVMChar; cdecl; external CLLVMLibrary;
(**
* @defgroup LLVMCCoreTypeInt Integer Types
*
* Functions in this section operate on integer types.
*
* @{
*)
(**
* Obtain an integer type from a context with specified bit width.
*)
function LLVMInt1TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt8TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt16TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt32TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt64TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt128TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIntTypeInContext(C: TLLVMContextRef; NumBits: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* Obtain an integer type from the global context with a specified bit
* width.
*)
function LLVMInt1Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt8Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt16Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt32Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt64Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMInt128Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIntType(NumBits: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMGetIntTypeWidth(IntegerTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMHalfTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMFloatTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMDoubleTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMX86FP80TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMFP128TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMPPCFP128TypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMHalfType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMFloatType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMDoubleType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMX86FP80Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMFP128Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMPPCFP128Type: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMFunctionType(ReturnType: TLLVMTypeRef; ParamTypes: PLLVMTypeRef; ParamCount: Cardinal; IsVarArg: LongBool): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIsFunctionVarArg(FunctionTy: TLLVMTypeRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMGetReturnType(FunctionTy: TLLVMTypeRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMCountParamTypes(FunctionTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetParamTypes(FunctionTy: TLLVMTypeRef; out Dest: PLLVMTypeRef); cdecl; external CLLVMLibrary;
function LLVMStructTypeInContext(C: TLLVMContextRef; ElementTypes: PLLVMTypeRef; ElementCount: Cardinal; IsPacked: LongBool): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMStructType(ElementTypes: PLLVMTypeRef; ElementCount: Cardinal; IsPacked: LongBool): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMStructCreateNamed(C: TLLVMContextRef; const Name: PLLVMChar): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMGetStructName(Ty: TLLVMTypeRef): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMStructSetBody(StructTy: TLLVMTypeRef; ElementTypes: PLLVMTypeRef; ElementCount: Cardinal; IsPacked: LongBool); cdecl; external CLLVMLibrary;
function LLVMCountStructElementTypes(StructTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetStructElementTypes(StructTy: TLLVMTypeRef; Dest: PLLVMTypeRef); cdecl; external CLLVMLibrary;
function LLVMStructGetTypeAtIndex(StructTy: TLLVMTypeRef; i: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIsPackedStruct(StructTy: TLLVMTypeRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMIsOpaqueStruct(StructTy: TLLVMTypeRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Determine whether a structure is literal.
*
* @see llvm::StructType::isLiteral()
*)
function LLVMIsLiteralStruct(StructTy: TLLVMTypeRef): TLLVMBool; cdecl; external CLLVMLibrary;
function LLVMGetElementType(Ty: TLLVMTypeRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
procedure LLVMGetSubtypes(Tp: TLLVMTypeRef; out Arr: PLLVMTypeRef); cdecl; external CLLVMLibrary;
function LLVMGetNumContainedTypes(Tp: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMArrayType(ElementType: TLLVMTypeRef; ElementCount: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMGetArrayLength(ArrayTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMPointerType(ElementType: TLLVMTypeRef; AddressSpace: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMGetPointerAddressSpace(PointerTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMVectorType(ElementType: TLLVMTypeRef; ElementCount: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMGetVectorSize(VectorTy: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMVoidTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMLabelTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMX86MMXTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* Create a token type in a context.
*)
function LLVMTokenTypeInContext(C: TLLVMContextRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* Create a metadata type in a context.
*)
function LLVMMetadataTypeInContext(C: TLLVMContextRef): TLLVMTypeRef;cdecl; external CLLVMLibrary;
function LLVMVoidType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMLabelType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMX86MMXType: TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* @}
*/
/**
* @}
*/
/**
* @defgroup LLVMCCoreValues Values
*
* The bulk of LLVM's object model consists of values, which comprise a very
* rich type hierarchy.
*
* LLVMValueRef essentially represents llvm::Value. There is a rich
* hierarchy of classes within this type. Depending on the instance
* obtained, not all APIs are available.
*
* Callers can determine the type of an LLVMValueRef by calling the
* LLVMIsA* family of functions (e.g. LLVMIsAArgument()). These
* functions are defined by a macro, so it isn't obvious which are
* available by looking at the Doxygen source code. Instead, look at the
* source definition of LLVM_FOR_EACH_VALUE_SUBCLASS and note the list
* of value names given. These value names also correspond to classes in
* the llvm::Value hierarchy.
*
* @{
*)
{/*--.. Conversion functions ................................................--*/}
function LLVMIsAArgument (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsABasicBlock (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAInlineAsm (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAUser (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstant (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsABlockAddress (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantAggregateZero (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantArray (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantDataSequential(Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantDataArray (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantDataVector (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantExpr (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantFP (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantInt (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantPointerNull (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantStruct (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantTokenNone (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAConstantVector (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGlobalValue (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGlobalAlias (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGlobalIFunc (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGlobalObject (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAfunction (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGlobalVariable (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAUndefValue (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAInstruction (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsABinaryOperator (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACallInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAIntrinsicInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsADbgInfoIntrinsic (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsADbgVariableIntrinsic (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsADbgDeclareInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsADbgLabelInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAMemIntrinsic (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAMemCpyInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAMemMoveInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAMemSetInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACmpInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFCmpInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAICmpInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAExtractElementInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAGetElementPtrInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAInsertElementInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAInsertValueInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsALandingPadInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAPHINode (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsASelectInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAShuffleVectorInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAStoreInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsABranchInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAIndirectBrInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAInvokeInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAReturnInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsASwitchInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAUnreachableInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAResumeInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACleanupReturnInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACatchReturnInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFuncletPadInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACatchPadInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACleanupPadInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAUnaryInstruction (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAAllocaInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsACastInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAAddrSpaceCastInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsABitCastInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFPExtInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFPToSIInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFPToUIInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAFPTruncInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAIntToPtrInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAPtrToIntInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsASExtInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsASIToFPInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsATruncInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAUIToFPInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAZExtInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAExtractValueInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsALoadInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
function LLVMIsAVAArgInst (Val: TLLVMValueRef ): TLLVMValueRef ; cdecl; external CLLVMLibrary;
(**
* @defgroup LLVMCCoreValueGeneral General APIs
*
* Functions in this section work on all LLVMValueRef instances,
* regardless of their sub-type. They correspond to functions available
* on llvm::Value.
*
* @{
*)
(**
* Obtain the type of a value.
*
* @see llvm::Value::getType()
*)
function LLVMTypeOf(Val: TLLVMValueRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* Obtain the enumerated type of a Value instance.
*
* @see llvm::Value::getValueID()
*)
function LLVMGetValueKind(Val: TLLVMValueRef): TLLVMValueKind; cdecl; external CLLVMLibrary;
(**
* Obtain the string name of a value.
*
* @see llvm::Value::getName()
*)
function LLVMGetValueName(Val: TLLVMValueRef): PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Obtain the string name of a value.
*
* @see llvm::Value::getName()
*)
function LLVMGetValueName2(Val: TLLVMValueRef; var Len: TLLVMSizeT):PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Set the string name of a value.
*
* @see llvm::Value::setName()
*)
procedure LLVMSetValueName(Val: TLLVMValueRef; const Name: PLLVMChar); cdecl; external CLLVMLibrary;
(**
* Set the string name of a value.
*
* @see llvm::Value::setName()
*)
procedure LLVMSetValueName2(Valore: TLLVMValueRef; const Name: PLLVMChar; NameLen: TLLVMSizeT); cdecl; external CLLVMLibrary;
(*
* Dump a representation of a value to stderr.
*
* @see llvm::Value::dump()
*)
procedure LLVMDumpValue(Val: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Return a string representation of the value. Use
* LLVMDisposeMessage to free the string.
*
* @see llvm::Value::print()
*)
function LLVMPrintValueToString(Val: TLLVMValueRef): PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Replace all uses of a value with another one.
*
* @see llvm::Value::replaceAllUsesWith()
*)
procedure LLVMReplaceAllUsesWith(OldVal: TLLVMValueRef; NewVal: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMIsConstant(Val: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMIsUndef(Val: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMIsAMDNode(Val: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMIsAMDString(Val: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* @defgroup LLVMCCoreValueUses Usage
*
* This module defines functions that allow you to inspect the uses of a
* LLVMValueRef.
*
* It is possible to obtain an LLVMUseRef for any LLVMValueRef instance.
* Each LLVMUseRef (which corresponds to a llvm::Use instance) holds a
* llvm::User and llvm::Value.
*
* @{
*)
(**
* Obtain the first use of a value.
*
* Uses are obtained in an iterator fashion. First, call this function
* to obtain a reference to the first use. Then, call LLVMGetNextUse()
* on that instance and all subsequently obtained instances until
* LLVMGetNextUse() returns NULL.
*
* @see llvm::Value::use_begin()
*)
function LLVMGetFirstUse(Val: TLLVMValueRef): TLLVMUseRef; cdecl; external CLLVMLibrary;
(**
* Obtain the next use of a value.
*
* This effectively advances the iterator. It returns NULL if you are on
* the final use and no more are available.
*)
function LLVMGetNextUse(U: TLLVMUseRef): TLLVMUseRef; cdecl; external CLLVMLibrary;
(**
* Obtain the user value for a user.
*
* The returned value corresponds to a llvm::User type.
*
* @see llvm::Use::getUser()
*)
function LLVMGetUser(U: TLLVMUseRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the value this use corresponds to.
*
* @see llvm::Use::get().
*)
function LLVMGetUsedValue(U: TLLVMUseRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueUser User value
*
* function in this group pertain to LLVMValueRef instances that descent
* from llvm::User. This includes constants, instructions, and
* operators.
*
* @{
*)
(**
* Obtain an operand at a specific index in a llvm::User value.
*
* @see llvm::User::getOperand()
*)
function LLVMGetOperand(Val: TLLVMValueRef; Index: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the use of an operand at a specific index in a llvm::User value.
*
* @see llvm::User::getOperandUse()
*)
function LLVMGetOperandUse(Val: TLLVMValueRef; Index: Cardinal): TLLVMUseRef; cdecl; external CLLVMLibrary;
(**
* Set an operand at a specific index in a llvm::User value.
*
* @see llvm::User::setOperand()
*)
procedure LLVMSetOperand(User: TLLVMValueRef; Index: Cardinal; Val: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Obtain the number of operands in a llvm::User value.
*
* @see llvm::User::getNumOperands()
*)
function LLVMGetNumOperands(Val: TLLVMValueRef): Integer; cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueConstant Constants
*
* This section contains APIs for interacting with LLVMValueRef that
* correspond to llvm::Constant instances.
*
* These functions will work for any LLVMValueRef in the llvm::Constant
* class hierarchy.
*
* @{
*)
(**
* Obtain a constant value referring to the null instance of a type.
*
* @see llvm::Constant::getNullValue()
*)
function LLVMConstNull(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain a constant value referring to the instance of a type
* consisting of all ones.
*
* This is only valid for integer types.
*
* @see llvm::Constant::getAllOnesValue()
*)
function LLVMConstAllOnes(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain a constant value referring to an undefined value of a type.
*
* @see llvm::UndefValue::get()
*)
function LLVMGetUndef(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Determine whether a value instance is null.
*
* @see llvm::Constant::isNullValue()
*)
function LLVMIsNull(Val: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Obtain a constant that is a constant pointer pointing to NULL for a
* specified type.
*)
function LLVMConstPointerNull(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* @defgroup LLVMCCoreValueConstantScalar Scalar constants
*
* Functions in this group model LLVMValueRef instances that correspond
* to constants referring to scalar types.
*
* For integer types, the LLVMTypeRef parameter should correspond to a
* llvm::IntegerType instance and the returned LLVMValueRef will
* correspond to a llvm::ConstantInt.
*
* For floating point types, the LLVMTypeRef returned corresponds to a
* llvm::ConstantFP.
*
* @{
*)
(**
* Obtain a constant value for an integer type.
*
* The returned value corresponds to a llvm::ConstantInt.
*
* @see llvm::ConstantInt::get()
*
* @param IntTy Integer type to obtain value of.
* @param N The value the returned instance should refer to.
* @param SignExtend Whether to sign extend the produced value.
*)
function LLVMConstInt(IntTy: TLLVMTypeRef; N: UInt64; SignExtend: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntOfArbitraryPrecision(IntTy: TLLVMTypeRef; NumWords: Cardinal; Words: PUInt64): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntOfString(IntTy: TLLVMTypeRef; const Text: PLLVMChar; Radix: Byte): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntOfStringAndSize(IntTy: TLLVMTypeRef; const Text: PLLVMChar; SLen: Cardinal; Radix: Byte): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstReal(RealTy: TLLVMTypeRef; N: Double): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstRealOfString(RealTy: TLLVMTypeRef; const Text: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstRealOfStringAndSize(RealTy: TLLVMTypeRef; const Text: PLLVMChar; SLen: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntGetZExtValue(ConstantVal: TLLVMValueRef): UInt64; cdecl; external CLLVMLibrary;
function LLVMConstIntGetSExtValue(ConstantVal: TLLVMValueRef): Int64; cdecl; external CLLVMLibrary;
function LLVMConstRealGetDouble(ConstantVal: TLLVMValueRef; out losesInfo: LongBool): Double; cdecl; external CLLVMLibrary;
function LLVMConstStringInContext(C: TLLVMContextRef; const Str: PLLVMChar; Length: Cardinal; DontNullTerminate: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstString(const Str: PLLVMChar; Length: Cardinal; DontNullTerminate: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMIsConstantString(c: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMGetAsString(c: TLLVMValueRef; out Length: TLLVMSizeT): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMConstStructInContext(C: TLLVMContextRef; ConstantVals: PLLVMValueRef; Count: Cardinal; IsPacked: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstStruct(ConstantVals: PLLVMValueRef; Count: Cardinal; IsPacked: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstArray(ElementTy: TLLVMTypeRef; ConstantVals: PLLVMValueRef; Length: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNamedStruct(StructTy: TLLVMTypeRef; ConstantVals: PLLVMValueRef; Count: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetElementAsConstant(C: TLLVMValueRef; idx: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstVector(ScalarConstantVals: PLLVMValueRef; Size: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetConstOpcode(ConstantVal: TLLVMValueRef): TLLVMOpcode; cdecl; external CLLVMLibrary;
function LLVMAlignOf(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMSizeOf(Ty: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNeg(ConstantVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNSWNeg(ConstantVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNUWNeg(ConstantVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFNeg(ConstantVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNot(ConstantVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstAdd(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNSWAdd(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNUWAdd(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFAdd(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSub(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNSWSub(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNUWSub(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFSub(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstMul(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNSWMul(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstNUWMul(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFMul(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstUDiv(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstExactUDiv(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSDiv(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstExactSDiv(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFDiv(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstURem(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSRem(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFRem(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstAnd(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstOr(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstXor(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstICmp(Predicate: TLLVMIntPredicate; LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFCmp(Predicate: TLLVMRealPredicate; LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstShl(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstLShr(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstAShr(LHSConstant: TLLVMValueRef; RHSConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstGEP(ConstantVal: TLLVMValueRef; ConstantIndices: PLLVMValueRef; NumIndices: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstInBoundsGEP(ConstantVal: TLLVMValueRef; ConstantIndices: PLLVMValueRef; NumIndices: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstTrunc(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSExt(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstZExt(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFPTrunc(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFPExt(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstUIToFP(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSIToFP(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFPToUI(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFPToSI(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstPtrToInt(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntToPtr(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstBitCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstAddrSpaceCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstZExtOrBitCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSExtOrBitCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstTruncOrBitCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstPointerCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstIntCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef; isSigned: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstFPCast(ConstantVal: TLLVMValueRef; ToType: TLLVMTypeRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstSelect(ConstantCondition: TLLVMValueRef; ConstantIfTrue: TLLVMValueRef; ConstantIfFalse: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstExtractElement(VectorConstant: TLLVMValueRef; IndexConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstInsertElement(VectorConstant: TLLVMValueRef; ElementValueConstant: TLLVMValueRef; IndexConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstShuffleVector(VectorAConstant: TLLVMValueRef; VectorBConstant: TLLVMValueRef; MaskConstant: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstExtractValue(AggConstant: TLLVMValueRef; IdxList: PCardinal; NumIdx: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstInsertValue(AggConstant: TLLVMValueRef; ElementValueConstant: TLLVMValueRef; IdxList: PCardinal; NumIdx: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMConstInlineAsm(Ty: TLLVMTypeRef; const AsmString: PLLVMChar; const Constraints: PLLVMChar; HasSideEffects: LongBool; IsAlignStack: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBlockAddress(F: TLLVMValueRef; BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetGlobalParent(Global: TLLVMValueRef): TLLVMModuleRef; cdecl; external CLLVMLibrary;
function LLVMIsDeclaration(Global: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMGetLinkage(Global: TLLVMValueRef): TLLVMLinkage; cdecl; external CLLVMLibrary;
procedure LLVMSetLinkage(Global: TLLVMValueRef; Linkage: TLLVMLinkage); cdecl; external CLLVMLibrary;
function LLVMGetSection(Global: TLLVMValueRef): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMSetSection(Global: TLLVMValueRef; const Section: PLLVMChar); cdecl; external CLLVMLibrary;
function LLVMGetVisibility(Global: TLLVMValueRef): TLLVMVisibility; cdecl; external CLLVMLibrary;
procedure LLVMSetVisibility(Global: TLLVMValueRef; Viz: TLLVMVisibility); cdecl; external CLLVMLibrary;
function LLVMGetDLLStorageClass(Global: TLLVMValueRef): TLLVMDLLStorageClass; cdecl; external CLLVMLibrary;
procedure LLVMSetDLLStorageClass(Global: TLLVMValueRef; StorageClass: TLLVMDLLStorageClass); cdecl; external CLLVMLibrary;
function LLVMHasUnnamedAddr(Global: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetUnnamedAddr(Global: TLLVMValueRef; HasUnnamedAddr: LongBool); cdecl; external CLLVMLibrary;
function LLVMGetAlignment(V: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMSetAlignment(V: TLLVMValueRef; Bytes: Cardinal); cdecl; external CLLVMLibrary;
function LLVMAddGlobal(M: TLLVMModuleRef; Ty: TLLVMTypeRef; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMAddGlobalInAddressSpace(M: TLLVMModuleRef; Ty: TLLVMTypeRef; const Name: PLLVMChar; AddressSpace: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetNamedGlobal(M: TLLVMModuleRef; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetFirstGlobal(M: TLLVMModuleRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetLastGlobal(M: TLLVMModuleRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetNextGlobal(GlobalVar: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetPreviousGlobal(GlobalVar: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMDeleteGlobal(GlobalVar: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMGetInitializer(GlobalVar: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMSetInitializer(GlobalVar: TLLVMValueRef; ConstantVal: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMIsThreadLocal(GlobalVar: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetThreadLocal(GlobalVar: TLLVMValueRef; IsThreadLocal: LongBool); cdecl; external CLLVMLibrary;
function LLVMIsGlobalConstant(GlobalVar: TLLVMValueRef): LongBool; cdecl external CLLVMLibrary;
procedure LLVMSetGlobalConstant(GlobalVar: TLLVMValueRef; IsConstant: LongBool); cdecl; external CLLVMLibrary;
function LLVMGetThreadLocalMode(GlobalVar: TLLVMValueRef): TLLVMThreadLocalMode; cdecl; external CLLVMLibrary;
procedure LLVMSetThreadLocalMode(GlobalVar: TLLVMValueRef; Mode: TLLVMThreadLocalMode); cdecl; external CLLVMLibrary;
function LLVMIsExternallyInitialized(GlobalVar: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetExternallyInitialized(GlobalVar: TLLVMValueRef; IsExtInit: LongBool); cdecl; external CLLVMLibrary;
(**
* @}
*/
/**
* @defgroup LLVMCoreValueConstantGlobalAlias Global Aliases
*
* This group contains function that operate on global alias values.
*
* @see llvm::GlobalAlias
*
* @{
*)
function LLVMAddAlias(M: TLLVMModuleRef; Ty: TLLVMTypeRef; Aliasee: TLLVMValueRef; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain a GlobalAlias value from a Module by its name.
*
* The returned value corresponds to a llvm::GlobalAlias value.
*
* @see llvm::Module::getNamedAlias()
*)
function LLVMGetNamedGlobalAlias(M: TLLVMModuleRef;const Name: PLLVMChar; NameLen: TLLVMSizeT): TLLVMValueRef;cdecl; external CLLVMLibrary;
(**
* Obtain an iterator to the first GlobalAlias in a Module.
*
* @see llvm::Module::alias_begin()
*)
function LLVMGetFirstGlobalAlias(M: TLLVMModuleRef): TLLVMValueRef;cdecl; external CLLVMLibrary;
(**
* Obtain an iterator to the last GlobalAlias in a Module.
*
* @see llvm::Module::alias_end()
*)
function LLVMGetLastGlobalAlias(M: TLLVMModuleRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Advance a GlobalAlias iterator to the next GlobalAlias.
*
* Returns NULL if the iterator was already at the end and there are no more
* global aliases.
*)
function LLVMGetNextGlobalAlias(GA: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Decrement a GlobalAlias iterator to the previous GlobalAlias.
*
* Returns NULL if the iterator was already at the beginning and there are
* no previous global aliases.
*)
function LLVMGetPreviousGlobalAlias(GA: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Retrieve the target value of an alias.
*)
function LLVMAliasGetAliasee(Alias: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Set the target value of an alias.
*)
procedure LLVMAliasSetAliasee(Alias: TLLVMValueRef; Aliasee: TLLVMValueRef);cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValuefunction function values
*
* Functions in this group operate on LLVMValueRef instances that
* correspond to llvm::function instances.
*
* @see llvm::Function
*
* @{
*)
(**
* Remove a function from its containing module and deletes it.
*
* @see llvm::Function::eraseFromParent()
*)
procedure LLVMDeleteFunction(Fn: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Check whether the given function has a personality function.
*
* @see llvm::Function::hasPersonalityFn()
*)
function LLVMHasPersonalityFn(Fn: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Obtain the personality function attached to the function.
*
* @see llvm::Function::getPersonalityFn()
*)
function LLVMGetPersonalityFn(Fn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Set the personality function attached to the function.
*
* @see llvm::Function::setPersonalityFn()
*)
procedure LLVMSetPersonalityFn(Fn: TLLVMValueRef; PersonalityFn: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Obtain the intrinsic ID number which matches the given function name.
*
* @see llvm::Function::lookupIntrinsicID()
*)
function LLVMLookupIntrinsicID(const Name: PLLVMChar; NameLen: TLLVMSizeT): Cardinal;cdecl; external CLLVMLibrary;
(**
* Obtain the ID number from a function instance.
*
* @see llvm::Function::getIntrinsicID()
*)
function LLVMGetIntrinsicID(Fn: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Create or insert the declaration of an intrinsic. For overloaded intrinsics,
* parameter types must be provided to uniquely identify an overload.
*
* @see llvm::Intrinsic::getDeclaration()
*)
function LLVMGetIntrinsicDeclaration(_Mod : TLLVMModuleRef; ID: Cardinal; ParamTypes: PLLVMTypeRef; ParamCount: TLLVMSizeT): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Retrieves the type of an intrinsic. For overloaded intrinsics, parameter
* types must be provided to uniquely identify an overload.
*
* @see llvm::Intrinsic::getType()
*)
function LLVMIntrinsicGetType(Ctx: TLLVMContextRef; ID: Cardinal; ParamTypes: PLLVMTypeRef; ParamCount: TLLVMSizeT): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* Retrieves the name of an intrinsic.
*
* @see llvm::Intrinsic::getName()
*)
function LLVMIntrinsicGetName(ID: Cardinal; var NameLength: TLLVMSizeT):PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Copies the name of an overloaded intrinsic identified by a given list of
* parameter types.
*
* Unlike LLVMIntrinsicGetName, the caller is responsible for freeing the
* returned string.
*
* @see llvm::Intrinsic::getName()
*)
function LLVMIntrinsicCopyOverloadedName(ID : Cardinal; ParamTypes: PLLVMTypeRef; ParamCount: TLLVMSizeT;var NameLength: TLLVMSizeT):PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Obtain if the intrinsic identified by the given ID is overloaded.
*
* @see llvm::Intrinsic::isOverloaded()
*)
function LLVMIntrinsicIsOverloaded(ID: Cardinal): TLLVMBool; cdecl; external CLLVMLibrary;
(**
* Obtain the calling function of a function.
*
* The returned value corresponds to the LLVMCallConv enumeration.
*
* @see llvm::Function::getCallingConv()
*)
function LLVMGetFunctionCallConv(Fn: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMSetFunctionCallConv(Fn: TLLVMValueRef; CC: Cardinal); cdecl; external CLLVMLibrary;
function LLVMGetGC(Fn: TLLVMValueRef): PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMSetGC(Fn: TLLVMValueRef; const Name: PLLVMChar); cdecl; external CLLVMLibrary;
procedure LLVMAddAttributeAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; A: TLLVMAttributeRef); cdecl; external CLLVMLibrary;
function LLVMGetAttributeCountAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetAttributesAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; out Attrs: PLLVMAttributeRef); cdecl; external CLLVMLibrary;
function LLVMGetEnumAttributeAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; KindID: Cardinal): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
function LLVMGetStringAttributeAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; const K: PLLVMChar; KLen: Cardinal): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
procedure LLVMRemoveEnumAttributeAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; KindID: Cardinal); cdecl; external CLLVMLibrary;
procedure LLVMRemoveStringAttributeAtIndex(F: TLLVMValueRef; Idx: TLLVMAttributeIndex; const K: PLLVMChar; KLen: Cardinal); cdecl; external CLLVMLibrary;
procedure LLVMAddTargetDependentFunctionAttr(Fn: TLLVMValueRef; const A: PLLVMChar; const V: PLLVMChar); cdecl; external CLLVMLibrary;
function LLVMCountParams(Fn: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetParams(Fn: TLLVMValueRef; Params: PLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMGetParam(Fn: TLLVMValueRef; Index: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetParamParent(Inst: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetFirstParam(Fn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetLastParam(Fn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetNextParam(Arg: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetPreviousParam(Arg: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMSetParamAlignment(Arg: TLLVMValueRef; Align: Cardinal); cdecl; external CLLVMLibrary;
function LLVMMDStringInContext(C: TLLVMContextRef; const Str: PLLVMChar; SLen: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMMDString(const Str: PLLVMChar; SLen: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMMDNodeInContext(C: TLLVMContextRef; Vals: PLLVMValueRef; Count: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMMDNode(Vals: PLLVMValueRef; Count: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMMetadataAsValue(C: TLLVMContextRef; MD: TLLVMMetadataRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMValueAsMetadata(Val: TLLVMValueRef): TLLVMMetadataRef; cdecl; external CLLVMLibrary;
function LLVMGetMDString(V: TLLVMValueRef; out Length: Cardinal): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetMDNodeNumOperands(V: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetMDNodeOperands(V: TLLVMValueRef; Dest: PLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* @}
*/
/**
* @defgroup LLVMCCoreValueBasicBlock Basic Block
*
* A basic block represents a single entry single exit section of code.
* Basic blocks contain a list of instructions which form the body of
* the block.
*
* Basic blocks belong to functions. They have the type of label.
*
* Basic blocks are themselves values. However, the C API models them as
* LLVMBasicBlockRef.
*
* @see llvm::BasicBlock
*
* @{
*)
(**
* Convert a basic block instance to a value type.
*)
function LLVMBasicBlockAsValue(BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Determine whether an LLVMValueRef is itself a basic block.
*)
function LLVMValueIsBasicBlock(Val: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Convert an LLVMValueRef to an LLVMBasicBlockRef instance.
*)
function LLVMValueAsBasicBlock(Val: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Obtain the string name of a basic block.
*)
function LLVMGetBasicBlockName(BB: TLLVMBasicBlockRef): PLLVMChar; cdecl; external CLLVMLibrary;
(**
* Obtain the function to which a basic block belongs.
*
* @see llvm::BasicBlock::getParent()
*)
function LLVMGetBasicBlockParent(BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the terminator instruction for a basic block.
*
* If the basic block does not have a terminator (it is not well-formed
* if it doesn't), then NULL is returned.
*
* The returned LLVMValueRef corresponds to an llvm::Instruction.
*
* @see llvm::BasicBlock::getTerminator()
*)
function LLVMGetBasicBlockTerminator(BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the number of basic blocks in a function.
*
* @param Fn function value to operate on.
*)
function LLVMCountBasicBlocks(Fn: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Obtain all of the basic blocks in a function.
*
* This operates on a function value. The BasicBlocks parameter is a
* pointer to a pre-allocated array of LLVMBasicBlockRef of at least
* LLVMCountBasicBlocks() in length. This array is populated with
* LLVMBasicBlockRef instances.
*)
procedure LLVMGetBasicBlocks(Fn: TLLVMValueRef; BasicBlocks: PLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* Obtain the first basic block in a function.
*
* The returned basic block can be used as an iterator. You will likely
* eventually call into LLVMGetNextBasicBlock() with it.
*
* @see llvm::Function::begin()
*)
function LLVMGetFirstBasicBlock(Fn: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Obtain the last basic block in a function.
*
* @see llvm::Function::end()
*)
function LLVMGetLastBasicBlock(Fn: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Advance a basic block iterator.
*)
function LLVMGetNextBasicBlock(BB: TLLVMBasicBlockRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Go backwards in a basic block iterator.
*)
function LLVMGetPreviousBasicBlock(BB: TLLVMBasicBlockRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Obtain the basic block that corresponds to the entry point of a
* function.
*
* @see llvm::Function::getEntryBlock()
*)
function LLVMGetEntryBasicBlock(Fn: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Insert the given basic block after the insertion point of the given builder.
*
* The insertion point must be valid.
*
* @see llvm::Function::BasicBlockListType::insertAfter()
*)
procedure LLVMInsertExistingBasicBlockAfterInsertBlock(Builder: TLLVMBuilderRef; BB: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* Append the given basic block to the basic block list of the given function.
*
* @see llvm::Function::BasicBlockListType::push_back()
*)
procedure LLVMAppendExistingBasicBlock(Fn: TLLVMValueRef; BB: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* Create a new basic block without inserting it into a function.
*
* @see llvm::BasicBlock::Create()
*)
function LLVMCreateBasicBlockInContext(C: TLLVMContextRef; const Name: PLLVMChar): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Append a basic block to the end of a function.
*
* @see llvm::BasicBlock::Create()
*)
function LLVMAppendBasicBlockInContext(C: TLLVMContextRef; Fn: TLLVMValueRef; const Name: PLLVMChar): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Append a basic block to the end of a function using the global
* context.
*
* @see llvm::BasicBlock::Create()
*)
function LLVMAppendBasicBlock(Fn: TLLVMValueRef; const Name: PLLVMChar): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
function LLVMInsertBasicBlockInContext(C: TLLVMContextRef; BB: TLLVMBasicBlockRef; const Name: PLLVMChar): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
function LLVMInsertBasicBlock(InsertBeforeBB: TLLVMBasicBlockRef; const Name: PLLVMChar): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
procedure LLVMDeleteBasicBlock(BB: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
procedure LLVMRemoveBasicBlockFromParent(BB: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
procedure LLVMMoveBasicBlockBefore(BB: TLLVMBasicBlockRef; MovePos: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
procedure LLVMMoveBasicBlockAfter(BB: TLLVMBasicBlockRef; MovePos: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* Obtain the first instruction in a basic block.
*
* The returned LLVMValueRef corresponds to a llvm::Instruction
* instance.
*)
function LLVMGetFirstInstruction(BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the last instruction in a basic block.
*
* The returned LLVMValueRef corresponds to an LLVM:Instruction.
*)
function LLVMGetLastInstruction(BB: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMHasMetadata(Val: TLLVMValueRef): Integer; cdecl; external CLLVMLibrary;
function LLVMGetMetadata(Val: TLLVMValueRef; KindID: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMSetMetadata(Val: TLLVMValueRef; KindID: Cardinal; Node: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Returns the metadata associated with an instruction value, but filters out
* all the debug locations.
*
* @see llvm::Instruction::getAllMetadataOtherThanDebugLoc()
*
*)
function LLVMInstructionGetAllMetadataOtherThanDebugLoc(Instr: TLLVMValueRef; var NumEntries: TLLVMSizeT):PLLVMValueMetadataEntry;cdecl; external CLLVMLibrary;
(**
* Obtain the basic block to which an instruction belongs.
*
* @see llvm::Instruction::getParent()
*)
function LLVMGetInstructionParent(Inst: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Obtain the instruction that occurs after the one specified.
*
* The next instruction will be from the same basic block.
*
* If this is the last instruction in a basic block, NULL will be
* returned.
*)
function LLVMGetNextInstruction(Inst: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain the instruction that occurred before this one.
*
* If the instruction is the first instruction in a basic block, NULL
* will be returned.
*)
function LLVMGetPreviousInstruction(Inst: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Remove and delete an instruction.
*
* The instruction specified is removed from its containing building
* block but is kept alive.
*
* @see llvm::Instruction::removeFromParent()
*)
procedure LLVMInstructionRemoveFromParent(Inst: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Remove and delete an instruction.
*
* The instruction specified is removed from its containing building
* block and then deleted.
*
* @see llvm::Instruction::eraseFromParent()
*)
procedure LLVMInstructionEraseFromParent(Inst: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Obtain the code opcode for an individual instruction.
*
* @see llvm::Instruction::getOpCode()
*)
function LLVMGetInstructionOpcode(Inst: TLLVMValueRef): TLLVMOpcode; cdecl; external CLLVMLibrary;
(**
* Obtain the predicate of an instruction.
*
* This is only valid for instructions that correspond to llvm::ICmpInst
* or llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp.
*
* @see llvm::ICmpInst::getPredicate()
*)
function LLVMGetICmpPredicate(Inst: TLLVMValueRef): TLLVMIntPredicate; cdecl; external CLLVMLibrary;
(**
* Obtain the float predicate of an instruction.
*
* This is only valid for instructions that correspond to llvm::FCmpInst
* or llvm::ConstantExpr whose opcode is llvm::Instruction::FCmp.
*
* @see llvm::FCmpInst::getPredicate()
*)
function LLVMGetFCmpPredicate(Inst: TLLVMValueRef): TLLVMRealPredicate; cdecl; external CLLVMLibrary;
(**
* Create a copy of 'this' instruction that is identical in all ways
* except the following:
* * The instruction has no parent
* * The instruction has no name
*
* @see llvm::Instruction::clone()
*)
function LLVMInstructionClone(Inst: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Determine whether an instruction is a terminator. This routine is named to
* be compatible with historical functions that did this by querying the
* underlying C++ type.
*
* @see llvm::Instruction::isTerminator()
*)
function LLVMIsATerminatorInst(Inst: TLLVMValueRef):TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* @defgroup LLVMCCoreValueInstructionCall Call Sites and Invocations
*
* Functions in this group apply to instructions that refer to call
* sites and invocations. These correspond to C++ types in the
* llvm::CallInst class tree.
*
* @{
*)
(**
* Obtain the argument count for a call instruction.
*
* This expects an LLVMValueRef that corresponds to a llvm::CallInst,
* llvm::InvokeInst, or llvm:FuncletPadInst.
*
* @see llvm::CallInst::getNumArgOperands()
* @see llvm::InvokeInst::getNumArgOperands()
* @see llvm::FuncletPadInst::getNumArgOperands()
*)
function LLVMGetNumArgOperands(Instr: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Set the calling convention for a call instruction.
*
* This expects an LLVMValueRef that corresponds to a llvm::CallInst or
* llvm::InvokeInst.
*
* @see llvm::CallInst::setCallingConv()
* @see llvm::InvokeInst::setCallingConv()
*)
procedure LLVMSetInstructionCallConv(Instr: TLLVMValueRef; CC: Cardinal); cdecl; external CLLVMLibrary;
(**
* Obtain the calling convention for a call instruction.
*
* This is the opposite of LLVMSetInstructionCallConv(). Reads its
* usage.
*
* @see LLVMSetInstructionCallConv()
*)
function LLVMGetInstructionCallConv(Instr: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMSetInstrParamAlignment(Instr: TLLVMValueRef; index: Cardinal; Align: Cardinal); cdecl; external CLLVMLibrary;
procedure LLVMAddCallSiteAttribute(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; A: TLLVMAttributeRef); cdecl; external CLLVMLibrary;
function LLVMGetCallSiteAttributeCount(C: TLLVMValueRef; Idx: TLLVMAttributeIndex): Cardinal; cdecl; external CLLVMLibrary;
procedure LLVMGetCallSiteAttributes(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; Attrs: PLLVMAttributeRef); cdecl; external CLLVMLibrary;
function LLVMGetCallSiteEnumAttribute(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; KindID: Cardinal): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
function LLVMGetCallSiteStringAttribute(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; const K: PLLVMChar; KLen: Cardinal): TLLVMAttributeRef; cdecl; external CLLVMLibrary;
procedure LLVMRemoveCallSiteEnumAttribute(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; KindID: Cardinal); cdecl; external CLLVMLibrary;
procedure LLVMRemoveCallSiteStringAttribute(C: TLLVMValueRef; Idx: TLLVMAttributeIndex; const K: PLLVMChar; KLen: Cardinal); cdecl; external CLLVMLibrary;
(**
* Obtain the function type called by this instruction.
*
* @see llvm::CallBase::getFunctionType()
*)
function LLVMGetCalledFunctionType(C: TLLVMValueRef): TLLVMTypeRef;cdecl; external CLLVMLibrary;
(**
* Obtain the pointer to the function invoked by this instruction.
*
* This expects an LLVMValueRef that corresponds to a llvm::CallInst or
* llvm::InvokeInst.
*
* @see llvm::CallInst::getCalledValue()
* @see llvm::InvokeInst::getCalledValue()
*)
function LLVMGetCalledValue(Instr: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMIsTailCall(CallInst: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetTailCall(CallInst: TLLVMValueRef; IsTailCall: LongBool); cdecl; external CLLVMLibrary;
function LLVMGetNormalDest(InvokeInst: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
function LLVMGetUnwindDest(InvokeInst: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
procedure LLVMSetNormalDest(InvokeInst: TLLVMValueRef; B: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
procedure LLVMSetUnwindDest(InvokeInst: TLLVMValueRef; B: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueInstructionTerminator Terminators
*
* Functions in this group only apply to instructions for which
* LLVMIsATerminatorInst returns true.
*
*
*)
(*
* Return the number of successors that this terminator has.
*
* @see llvm::Instruction::getNumSuccessors
*)
function LLVMGetNumSuccessors(Term: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Return the specified successor.
*
* @see llvm::Instruction::getSuccessor
*)
function LLVMGetSuccessor(Term: TLLVMValueRef; i: Cardinal): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* Update the specified successor to point at the provided block.
*
* @see llvm::Instruction::setSuccessor
*)
procedure LLVMSetSuccessor(Term: TLLVMValueRef; i: Cardinal; block: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
(**
* Return if a branch is conditional.
*
* This only works on llvm::BranchInst instructions.
*
* @see llvm::BranchInst::isConditional
*)
function LLVMIsConditional(Branch: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Return the condition of a branch instruction.
*
* This only works on llvm::BranchInst instructions.
*
* @see llvm::BranchInst::getCondition
*)
function LLVMGetCondition(Branch: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Set the condition of a branch instruction.
*
* This only works on llvm::BranchInst instructions.
*
* @see llvm::BranchInst::setCondition
*)
procedure LLVMSetCondition(Branch: TLLVMValueRef; Cond: TLLVMValueRef); cdecl; external CLLVMLibrary;
(**
* Obtain the default destination basic block of a switch instruction.
*
* This only works on llvm::SwitchInst instructions.
*
* @see llvm::SwitchInst::getDefaultDest()
*)
function LLVMGetSwitchDefaultDest(SwitchInstr: TLLVMValueRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueInstructionAlloca Allocas
*
* Functions in this group only apply to instructions that map to
* llvm::AllocaInst instances.
*
* @{
*)
(**
* Obtain the type that is being allocated by the alloca instruction.
*)
function LLVMGetAllocatedType(Alloca: TLLVMValueRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueInstructionGetElementPointer GEPs
*
* Functions in this group only apply to instructions that map to
* llvm::GetElementPtrInst instances.
*
* @{
*)
(**
* Check whether the given GEP instruction is inbounds.
*)
function LLVMIsInBounds(GEP: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
(**
* Set the given GEP instruction to be inbounds or not.
*)
procedure LLVMSetIsInBounds(GEP: TLLVMValueRef; InBounds: LongBool); cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCoreValueInstructionPHINode PHI Nodes
*
* Functions in this group only apply to instructions that map to
* llvm::PHINode instances.
*
* @{
*)
(**
* Add an incoming value to the end of a PHI list.
*)
procedure LLVMAddIncoming(PhiNode: TLLVMValueRef; IncomingValues: PLLVMValueRef; IncomingBlocks: PLLVMBasicBlockRef; Count: Cardinal); cdecl; external CLLVMLibrary;
(**
* Obtain the number of incoming basic blocks to a PHI node.
*)
function LLVMCountIncoming(PhiNode: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Obtain an incoming value to a PHI node as an LLVMValueRef.
*)
function LLVMGetIncomingValue(PhiNode: TLLVMValueRef; Index: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Obtain an incoming value to a PHI node as an LLVMBasicBlockRef.
*)
function LLVMGetIncomingBlock(PhiNode: TLLVMValueRef; Index: Cardinal): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
function LLVMGetNumIndices(Inst: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetIndices(Inst: TLLVMValueRef): PCardinal; cdecl; external CLLVMLibrary;
function LLVMCreateBuilderInContext(C: TLLVMContextRef): TLLVMBuilderRef; cdecl; external CLLVMLibrary;
function LLVMCreateBuilder: TLLVMBuilderRef; cdecl; external CLLVMLibrary;
procedure LLVMPositionBuilder(Builder: TLLVMBuilderRef; Block: TLLVMBasicBlockRef; Instr: TLLVMValueRef); cdecl; external CLLVMLibrary;
procedure LLVMPositionBuilderBefore(Builder: TLLVMBuilderRef; Instr: TLLVMValueRef); cdecl; external CLLVMLibrary;
procedure LLVMPositionBuilderAtEnd(Builder: TLLVMBuilderRef; Block: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
function LLVMGetInsertBlock(Builder: TLLVMBuilderRef): TLLVMBasicBlockRef; cdecl; external CLLVMLibrary;
procedure LLVMClearInsertionPosition(Builder: TLLVMBuilderRef); cdecl; external CLLVMLibrary;
procedure LLVMInsertIntoBuilder(Builder: TLLVMBuilderRef; Instr: TLLVMValueRef); cdecl; external CLLVMLibrary;
procedure LLVMInsertIntoBuilderWithName(Builder: TLLVMBuilderRef; Instr: TLLVMValueRef; Name: PLLVMChar); cdecl; external CLLVMLibrary;
procedure LLVMDisposeBuilder(Builder: TLLVMBuilderRef); cdecl; external CLLVMLibrary;
{/* Metadata */}
(**
* Get location information used by debugging information.
*
* @see llvm::IRBuilder::getCurrentDebugLocation()
*)
function LLVMGetCurrentDebugLocation2(Builder: TLLVMBuilderRef ):TLLVMMetadataRef;cdecl; external CLLVMLibrary;
(**
* Set location information used by debugging information.
*
* To clear the location metadata of the given instruction, pass NULL to \p Loc.
*
* @see llvm::IRBuilder::SetCurrentDebugLocation()
*)
procedure LLVMSetCurrentDebugLocation2(Builder: TLLVMBuilderRef; Loc: TLLVMMetadataRef); cdecl; external CLLVMLibrary;
procedure LLVMSetCurrentDebugLocation(Builder: TLLVMBuilderRef; L: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMGetCurrentDebugLocation(Builder: TLLVMBuilderRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMSetInstDebugLocation(Builder: TLLVMBuilderRef; Inst: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMBuildRetVoid(Arg0: TLLVMBuilderRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildRet(Arg0: TLLVMBuilderRef; V: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAggregateRet(Arg0: TLLVMBuilderRef; RetVals: PLLVMValueRef; N: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildBr(Arg0: TLLVMBuilderRef; Dest: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildCondBr(Arg0: TLLVMBuilderRef; IfValue: TLLVMValueRef; ThenValue: TLLVMBasicBlockRef; ElseValue: TLLVMBasicBlockRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSwitch(Arg0: TLLVMBuilderRef; V: TLLVMValueRef; ElseValue: TLLVMBasicBlockRef; NumCases: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildIndirectBr(B: TLLVMBuilderRef; Addr: TLLVMValueRef; NumDests: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildInvoke(Arg0: TLLVMBuilderRef; Fn: TLLVMValueRef; Args: PLLVMValueRef; NumArgs: Cardinal; ThenValue: TLLVMBasicBlockRef; Catch: TLLVMBasicBlockRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildLandingPad(B: TLLVMBuilderRef; Ty: TLLVMTypeRef; PersFn: TLLVMValueRef; NumClauses: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildResume(B: TLLVMBuilderRef; Exn: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildUnreachable(Arg0: TLLVMBuilderRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMAddCase(Switch: TLLVMValueRef; OnVal: TLLVMValueRef; Dest: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
procedure LLVMAddDestination(IndirectBr: TLLVMValueRef; Dest: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
function LLVMGetNumClauses(LandingPad: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMGetClause(LandingPad: TLLVMValueRef; Idx: Cardinal): TLLVMValueRef; cdecl; external CLLVMLibrary;
procedure LLVMAddClause(LandingPad: TLLVMValueRef; ClauseVal: TLLVMValueRef); cdecl; external CLLVMLibrary;
function LLVMIsCleanup(LandingPad: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetCleanup(LandingPad: TLLVMValueRef; Val: LongBool); cdecl; external CLLVMLibrary;
{/* Add a destination to the catchswitch instruction */}
procedure LLVMAddHandler(CatchSwitch: TLLVMValueRef; Dest: TLLVMBasicBlockRef); cdecl; external CLLVMLibrary;
{/* Get the number of handlers on the catchswitch instruction */}
function LLVMGetNumHandlers(CatchSwitch: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
(**
* Obtain the basic blocks acting as handlers for a catchswitch instruction.
*
* The Handlers parameter should point to a pre-allocated array of
* LLVMBasicBlockRefs at least LLVMGetNumHandlers() large. On return, the
* first LLVMGetNumHandlers() entries in the array will be populated
* with LLVMBasicBlockRef instances.
*
* @param CatchSwitch The catchswitch instruction to operate on.
* @param Handlers Memory address of an array to be filled with basic blocks.
*)
procedure LLVMGetHandlers(CatchSwitch: TLLVMValueRef; Handlers: PLLVMBasicBlockRef);cdecl; external CLLVMLibrary;
{/* Funclets */}
{/* Get the number of funcletpad arguments. */}
function LLVMGetArgOperand(Funclet: TLLVMValueRef; i: Cardinal): TLLVMValueRef;cdecl; external CLLVMLibrary;
{/* Set a funcletpad argument at the given index. */}
procedure LLVMSetArgOperand(Funclet: TLLVMValueRef; i: Cardinal; value: TLLVMValueRef);cdecl; external CLLVMLibrary;
(**
* Get the parent catchswitch instruction of a catchpad instruction.
*
* This only works on llvm::CatchPadInst instructions.
*
* @see llvm::CatchPadInst::getCatchSwitch()
*)
function LLVMGetParentCatchSwitch(CatchPad: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Set the parent catchswitch instruction of a catchpad instruction.
*
* This only works on llvm::CatchPadInst instructions.
*
* @see llvm::CatchPadInst::setCatchSwitch()
*)
procedure LLVMSetParentCatchSwitch(CatchPad: TLLVMValueRef; CatchSwitch: TLLVMValueRef);cdecl; external CLLVMLibrary;
{/* Arithmetic */}
function LLVMBuildAdd(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNSWAdd(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNUWAdd(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFAdd(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSub(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNSWSub(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNUWSub(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFSub(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildMul(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNSWMul(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNUWMul(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFMul(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildUDiv(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildExactUDiv(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSDiv(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildExactSDiv(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFDiv(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildURem(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSRem(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFRem(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildShl(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildLShr(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAShr(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAnd(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildOr(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildXor(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildBinOp(B: TLLVMBuilderRef; Op: TLLVMOpcode; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNeg(Arg0: TLLVMBuilderRef; V: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNSWNeg(B: TLLVMBuilderRef; V: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNUWNeg(B: TLLVMBuilderRef; V: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFNeg(Arg0: TLLVMBuilderRef; V: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildNot(Arg0: TLLVMBuilderRef; V: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
{/* Memory */}
function LLVMBuildMalloc(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildArrayMalloc(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; Val: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Creates and inserts a memset to the specified pointer and the
* specified value.
*
* @see llvm::IRRBuilder::CreateMemSet()
*)
function LLVMBuildMemSet(B: TLLVMBuilderRef; Ptr: TLLVMValueRef; Val: TLLVMValueRef; Len: TLLVMValueRef; Align: Cardinal): TLLVMValueRef;cdecl; external CLLVMLibrary;
(**
* Creates and inserts a memcpy between the specified pointers.
*
* @see llvm::IRRBuilder::CreateMemCpy()
*)
function LLVMBuildMemCpy(B : TLLVMBuilderRef;
Dst: TLLVMValueRef; DstAlign: Cardinal;
Src: TLLVMValueRef; SrcAlign: Cardinal;
Size: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
(**
* Creates and inserts a memmove between the specified pointers.
*
* @see llvm::IRRBuilder::CreateMemMove()
*)
function LLVMBuildMemMove(B: TLLVMBuilderRef; Dst: TLLVMValueRef; DstAlign: Cardinal; Src: TLLVMValueRef; SrcAlign: Cardinal; Size: TLLVMValueRef):TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAlloca(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildArrayAlloca(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; Val: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFree(Arg0: TLLVMBuilderRef; PointerVal: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
// LLVMBuildLoad is deprecated in favor of LLVMBuildLoad2, in preparation for opaque pointer types.
function LLVMBuildLoad(Arg0: TLLVMBuilderRef; PointerVal: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildLoad2(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; PointerVal: TLLVMValueRef; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildStore(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; Ptr: TLLVMValueRef): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildGEP (B: TLLVMBuilderRef; Pointer: TLLVMValueRef; Indices: PLLVMValueRef; NumIndices: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildInBoundsGEP (B: TLLVMBuilderRef; Pointer: TLLVMValueRef; Indices: PLLVMValueRef; NumIndices: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildStructGEP (B: TLLVMBuilderRef; Pointer: TLLVMValueRef; Idx: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildGEP2 (B: TLLVMBuilderRef; Ty: TLLVMTypeRef; Pointer: TLLVMValueRef; Indices: PLLVMValueRef; NumIndices: Cardinal; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildInBoundsGEP2(B: TLLVMBuilderRef; Ty: TLLVMTypeRef; Pointer: TLLVMValueRef; Indices: PLLVMValueRef; NumIndices: Cardinal; const Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildStructGEP2 (B: TLLVMBuilderRef; Ty: TLLVMTypeRef; Pointer: TLLVMValueRef; Idx: Cardinal; const Name: PLLVMChar): TLLVMValueRef;cdecl; external CLLVMLibrary;
function LLVMBuildGlobalString(B: TLLVMBuilderRef; Str: PLLVMChar; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildGlobalStringPtr(B: TLLVMBuilderRef; Str: PLLVMChar; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMGetVolatile(MemoryAccessInst: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetVolatile(MemoryAccessInst: TLLVMValueRef; IsVolatile: LongBool); cdecl; external CLLVMLibrary;
function LLVMGetOrdering(MemoryAccessInst: TLLVMValueRef): TLLVMAtomicOrdering; cdecl; external CLLVMLibrary;
procedure LLVMSetOrdering(MemoryAccessInst: TLLVMValueRef; Ordering: TLLVMAtomicOrdering); cdecl; external CLLVMLibrary;
{/* Casts */}
function LLVMBuildTrunc(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildZExt(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSExt(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFPToUI(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFPToSI(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildUIToFP(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSIToFP(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFPTrunc(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFPExt(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildPtrToInt(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildIntToPtr(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildBitCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAddrSpaceCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildZExtOrBitCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSExtOrBitCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildTruncOrBitCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildCast(B: TLLVMBuilderRef; Op: TLLVMOpcode; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildPointerCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildIntCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFPCast(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; DestTy: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
{/* Comparisons */}
function LLVMBuildICmp(Arg0: TLLVMBuilderRef; Op: TLLVMIntPredicate; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFCmp(Arg0: TLLVMBuilderRef; Op: TLLVMRealPredicate; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildPhi(Arg0: TLLVMBuilderRef; Ty: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildCall(Arg0: TLLVMBuilderRef; Fn: TLLVMValueRef; Args: PLLVMValueRef; NumArgs: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildSelect(Arg0: TLLVMBuilderRef; IfValue: TLLVMValueRef; ThenValue: TLLVMValueRef; ElseValue: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildVAArg(Arg0: TLLVMBuilderRef; List: TLLVMValueRef; Ty: TLLVMTypeRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildExtractElement(Arg0: TLLVMBuilderRef; VecVal: TLLVMValueRef; Index: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildInsertElement(Arg0: TLLVMBuilderRef; VecVal: TLLVMValueRef; EltVal: TLLVMValueRef; Index: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildShuffleVector(Arg0: TLLVMBuilderRef; V1: TLLVMValueRef; V2: TLLVMValueRef; Mask: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildExtractValue(Arg0: TLLVMBuilderRef; AggVal: TLLVMValueRef; Index: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildInsertValue(Arg0: TLLVMBuilderRef; AggVal: TLLVMValueRef; EltVal: TLLVMValueRef; Index: Cardinal; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildIsNull(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildIsNotNull(Arg0: TLLVMBuilderRef; Val: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildPtrDiff(Arg0: TLLVMBuilderRef; LHS: TLLVMValueRef; RHS: TLLVMValueRef; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildFence(B: TLLVMBuilderRef; ordering: TLLVMAtomicOrdering; singleThread: LongBool; Name: PLLVMChar): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAtomicRMW(B: TLLVMBuilderRef; op: TLLVMAtomicRMWBinOp; PTR: TLLVMValueRef; Val: TLLVMValueRef; ordering: TLLVMAtomicOrdering; singleThread: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMBuildAtomicCmpXchg(B: TLLVMBuilderRef; Ptr: TLLVMValueRef; Cmp: TLLVMValueRef; New: TLLVMValueRef; SuccessOrdering: TLLVMAtomicOrdering; FailureOrdering: TLLVMAtomicOrdering; SingleThread: LongBool): TLLVMValueRef; cdecl; external CLLVMLibrary;
function LLVMIsAtomicSingleThread(AtomicInst: TLLVMValueRef): LongBool; cdecl; external CLLVMLibrary;
procedure LLVMSetAtomicSingleThread(AtomicInst: TLLVMValueRef; SingleThread: LongBool); cdecl; external CLLVMLibrary;
function LLVMGetCmpXchgSuccessOrdering(CmpXchgInst: TLLVMValueRef): TLLVMAtomicOrdering; cdecl; external CLLVMLibrary;
procedure LLVMSetCmpXchgSuccessOrdering(CmpXchgInst: TLLVMValueRef; Ordering: TLLVMAtomicOrdering); cdecl; external CLLVMLibrary;
function LLVMGetCmpXchgFailureOrdering(CmpXchgInst: TLLVMValueRef): TLLVMAtomicOrdering; cdecl; external CLLVMLibrary;
procedure LLVMSetCmpXchgFailureOrdering(CmpXchgInst: TLLVMValueRef; Ordering: TLLVMAtomicOrdering); cdecl; external CLLVMLibrary;
function LLVMCreateModuleProviderForExistingModule(M: TLLVMModuleRef): TLLVMModuleProviderRef; cdecl; external CLLVMLibrary;
procedure LLVMDisposeModuleProvider(M: TLLVMModuleProviderRef); cdecl; external CLLVMLibrary;
function LLVMCreateMemoryBufferWithContentsOfFile(Path: PLLVMChar; out OutMemBuf: TLLVMMemoryBufferRef; out OutMessage: PLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary;
function LLVMCreateMemoryBufferWithSTDIN(out OutMemBuf: TLLVMMemoryBufferRef; out OutMessage: PLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary;
function LLVMCreateMemoryBufferWithMemoryRange(InputData: PLLVMChar; InputDataLength: TLLVMSizeT; BufferName: PLLVMChar; RequiresNullTerminator: LongBool): TLLVMMemoryBufferRef; cdecl; external CLLVMLibrary;
function LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: PLLVMChar; InputDataLength: TLLVMSizeT; BufferName: PLLVMChar): TLLVMMemoryBufferRef; cdecl; external CLLVMLibrary;
function LLVMGetBufferStart(MemBuf: TLLVMMemoryBufferRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetBufferSize(MemBuf: TLLVMMemoryBufferRef): TLLVMSizeT; cdecl; external CLLVMLibrary;
procedure LLVMDisposeMemoryBuffer(MemBuf: TLLVMMemoryBufferRef); cdecl; external CLLVMLibrary;
function LLVMGetGlobalPassRegistry: TLLVMPassRegistryRef; cdecl; external CLLVMLibrary;
(**
* @}
*)
(**
* @defgroup LLVMCCorePassManagers Pass Managers
*
* @{
*)
(** Constructs a new whole-module pass pipeline. This type of pipeline is
suitable for link-time optimization and whole-module transformations.
@see llvm::PassManager::PassManager *)
function LLVMCreatePassManager: TLLVMPassManagerRef; cdecl; external CLLVMLibrary;
(** Constructs a new function-by-function pass pipeline over the module
provider. It does not take ownership of the module provider. This type of
pipeline is suitable for code generation and JIT compilation tasks.
@see llvm::FunctionPassManager::FunctionPassManager *)
function LLVMCreateFunctionPassManagerForModule(M: TLLVMModuleRef): TLLVMPassManagerRef; cdecl; external CLLVMLibrary;
{/** Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. */}
function LLVMCreateFunctionPassManager(MP: TLLVMModuleProviderRef): TLLVMPassManagerRef; cdecl; external CLLVMLibrary;
(** Initializes, executes on the provided module, and finalizes all of the
passes scheduled in the pass manager. Returns 1 if any of the passes
modified the module, 0 otherwise.
@see llvm::PassManager::run(Module&) *)
function LLVMRunPassManager(PM: TLLVMPassManagerRef; M: TLLVMModuleRef): TLLVMBool; cdecl; external CLLVMLibrary;
(** Initializes all of the function passes scheduled in the function pass
manager. Returns 1 if any of the passes modified the module, 0 otherwise.
@see llvm::FunctionPassManager::doInitialization *)
function LLVMInitializeFunctionPassManager(FPM: TLLVMPassManagerRef): TLLVMBool; cdecl; external CLLVMLibrary;
(** Executes all of the function passes scheduled in the function pass manager
on the provided function. Returns 1 if any of the passes modified the
function, false otherwise.
@see llvm::FunctionPassManager::run(Function&) *)
function LLVMRunFunctionPassManager(FPM: TLLVMPassManagerRef; F: TLLVMValueRef): TLLVMBool; cdecl; external CLLVMLibrary;
(** Finalizes all of the function passes scheduled in the function pass
manager. Returns 1 if any of the passes modified the module, 0 otherwise.
@see llvm::FunctionPassManager::doFinalization *)
function LLVMFinalizeFunctionPassManager(FPM: TLLVMPassManagerRef): TLLVMBool; cdecl; external CLLVMLibrary;
(** Frees the memory of a pass pipeline. For function pipelines, does not free
the module provider.
@see llvm::PassManagerBase::~PassManagerBase. *)
procedure LLVMDisposePassManager(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
(** Deprecated: Multi-threading can only be enabled/disabled with the compile
time define LLVM_ENABLE_THREADS. This function always returns
LLVMIsMultithreaded(). *)
function LLVMStartMultithreaded: TLLVMBool;cdecl; external CLLVMLibrary;
(** Deprecated: Multi-threading can only be enabled/disabled with the compile
time define LLVM_ENABLE_THREADS. *)
procedure LLVMStopMultithreaded; cdecl; external CLLVMLibrary;
(** Check whether LLVM is executing in thread-safe mode or not.
@see llvm::llvm_is_multithreaded *)
function LLVMIsMultithreaded: LongBool; cdecl; external CLLVMLibrary;
// Added by Max 13/09/2019 17:22:45
(** Return the function this instruction belongs to.
*
* Note: it is undefined behavior to call this on an instruction not
* currently inserted into a function. see : const function *llvm::getFunction()
*)
function LLVMGetInstructionFunc(Inst: TLLVMValueRef):TLLVMValueRef;
function LLVMGetCallFromFunc(F: TLLVMValueRef ; nameCall : AnsiString): TLLVMValueRef;
function LLVMGetUsesVal(val : TLLVMValueRef): TArray<TLLVMValueRef> ;
function LLVMGetNextNonDebugInstruction(I: TLLVMValueRef): TLLVMValueRef;
function LLVMGetPrevNonDebugInstruction(I: TLLVMValueRef): TLLVMValueRef;
function LLVMDumpValueToStr(v:TLLVMValueRef) : AnsiString;
function LLVMGetgetFirstInsertionPt(block: TLLVMBasicBlockRef): TLLVMValueRef;
function LLVMGetFunctionInstructions(F: TLLVMValueRef): TArray<TLLVMValueRef>;
procedure LLVMPositionBuilderAfter(Builder: TLLVMBuilderRef; Instr: TLLVMValueRef);
procedure LLVMAddAttr(F: TLLVMValueRef; sAttr: AnsiString);
procedure LLVMRemoveAttr(F: TLLVMValueRef; sAttr: AnsiString);
implementation
uses System.SysUtils;
function LLVMGetInstructionFunc(Inst: TLLVMValueRef):TLLVMValueRef;
begin
Result.Value := nil;
var bb : TLLVMBasicBlockRef := LLVMGetInstructionParent(Inst);
Result := LLVMGetBasicBlockParent(bb) ;
end;
function LLVMGetUsesVal(val : TLLVMValueRef): TArray<TLLVMValueRef> ;
begin
Result := [];
var U : TLLVMUseRef := LLVMGetFirstUse(val);
while U.IsValid do
begin
Result := Result + [ LLVMGetUser(U) ] ;
U := LLVMGetNextUse(U);
end;
end;
function LLVMGetNextNonDebugInstruction(I: TLLVMValueRef): TLLVMValueRef;
var
rI : TLLVMValueRef;
begin
Result := default(TLLVMValueRef);
rI := LLVMGetNextInstruction(I);
while rI.IsValid do
begin
if LLVMIsADbgInfoIntrinsic(rI).IsValid = False then
Exit(rI);
rI := LLVMGetNextInstruction(I);
end;
end;
function LLVMGetPrevNonDebugInstruction(I: TLLVMValueRef): TLLVMValueRef;
var
rI : TLLVMValueRef;
begin
Result := default(TLLVMValueRef);
rI := LLVMGetPreviousInstruction(I);
while rI.IsValid do
begin
if LLVMIsADbgInfoIntrinsic(rI).IsValid = False then
Exit(rI);
rI := LLVMGetPreviousInstruction(I);
end;
end;
function LLVMDumpValueToStr(v:TLLVMValueRef) : AnsiString;
var
pDump : PAnsiChar;
begin
pDump := LLVMPrintValueToString(v);
try
Result := AnsiString(pDump) ;
finally
LLVMDisposeMessage(pDump);
end;
end;
function LLVMGetgetFirstInsertionPt(block: TLLVMBasicBlockRef): TLLVMValueRef;
var
I,IPhi : TLLVMValueRef;
// Return true if the instruction is a variety of EH-block.
function isEHPad(Inst: TLLVMValueRef): Boolean;
begin
case LLVMGetInstructionOpcode(Inst) of
LLVMCatchSwitch,
LLVMCatchPad,
LLVMCleanupPad,
LLVMLandingPad : Result := True;
else
Result := False;
end;
end;
begin
Result := default(TLLVMValueRef);
I := LLVMGetFirstInstruction(block) ;
while I.IsValid do
begin
IPhi := LLVMIsAPHINode(I);
if (not IPhi.IsValid) and (not isEHPad(I)) then
Exit(I);
I := LLVMGetNextInstruction(I)
end;
end;
function LLVMGetFunctionInstructions(F: TLLVMValueRef): TArray<TLLVMValueRef>;
begin
Result := [];
var BB : TLLVMBasicBlockRef := LLVMGetEntryBasicBlock(F);
while BB.IsValid do
begin
var I : TLLVMValueRef := LLVMGetFirstInstruction(BB);
while I.IsValid do
begin
Result := Result + [ I ];
I := LLVMGetNextInstruction(I) ;
end;
BB := LLVMGetNextBasicBlock(BB)
end;
end;
function LLVMGetCallFromFunc(F: TLLVMValueRef ; nameCall : AnsiString): TLLVMValueRef;
var
CallI: TLLVMValueRef;
lstI : TArray<TLLVMValueRef> ;
i : Integer;
begin
Result.Value := nil;
lstI := LLVMGetFunctionInstructions(F);
for i :=0 to High(lstI) do
begin
CallI := LLVMIsACallInst(lstI[i]);
if (CallI.IsValid) then
begin
var s : AnsiString := LLVMGetValueName(LLVMGetCalledValue(CallI));
if s = nameCall then
begin
Result := LLVMIsACallInst(lstI[i]);
Break;
end;
end;
end;
end;
procedure LLVMPositionBuilderAfter(Builder: TLLVMBuilderRef; Instr: TLLVMValueRef);
var
bb : TLLVMBasicBlockRef ;
ISucc : TLLVMValueRef;
begin
if not LLVMIsAInstruction(Instr).IsValid then
raise Exception.Create('it is not a valid instruction');
if LLVMIsATerminatorInst(Instr).IsValid then
begin
bb := LLVMGetInstructionParent(Instr) ;
LLVMPositionBuilderAtEnd(Builder,bb);
end;
ISucc := LLVMGetNextInstruction(Instr);
LLVMPositionBuilderBefore(Builder,ISucc);
end;
procedure LLVMAddAttr(F: TLLVMValueRef; sAttr: AnsiString);
var
KindID : cardinal;
vattr : TLLVMAttributeRef;
begin
sAttr := LowerCase( string(sAttr));
KindID := LLVMGetEnumAttributeKindForName( PAnsiChar(sAttr),Length(sAttr));
vattr := LLVMCreateEnumAttribute( LLVMGetGlobalContext, KindID, 0);
LLVMAddAttributeAtIndex(F, LLVMAttributeFunctionIndex, vattr) ;
end;
procedure LLVMRemoveAttr(F: TLLVMValueRef; sAttr: AnsiString);
var
KindID : cardinal;
vattr : TLLVMAttributeRef;
begin
sAttr := LowerCase( string(sAttr));
KindID := LLVMGetEnumAttributeKindForName( PAnsiChar(sAttr),Length(sAttr));
LLVMRemoveEnumAttributeAtIndex(F,LLVMAttributeFunctionIndex,KindID);
end;
end.
|
unit ncTarifador;
{
ResourceString: Dario 13/03/13
}
{
Ajustar re-ordenação de passaportes a cada hora
Evitar expiração de passaportes indevidamente
}
interface
uses
SysUtils,
DB,
MD5,
Classes,
Windows,
ClasseCS,
ncClassesBase,
ncPassaportes;
type
TncPausa = class
pInicio : TDateTime;
pFim : TDateTime;
constructor Create;
function DuracaoT: Cardinal;
function DuracaoM: Double;
end;
TncPausas = class
private
FItens : TList;
function GetItem(Index: Integer): TncPausa;
function GetString: String;
procedure SetString(Value: String);
public
constructor Create;
destructor Destroy; override;
procedure Limpa;
function Count : Integer;
function NewPausa: TncPausa;
function TicksTotal: Cardinal;
function DTTotal: TDateTime;
function TicksPausaEtapa(aInicioE, aFimE: TDateTime): Cardinal;
property Itens[Index: Integer]: TncPausa
read GetItem; default;
property AsString: String
read GetString write SetString;
end;
TncTarifador = class
FInicio : TDateTime;
FAgora : TDateTime;
FNumTicks : Cardinal;
FTicksR : Cardinal;
FCredito : TncTempo;
FTipoAcessoObj: TncTipoAcesso;
FPassaportes : TncPassaportes;
FPausas : TncPausas;
FTempoCobrado : Cardinal;
FCreditoR : Cardinal;
FCredValor : Double;
FValor : Double;
FDia, FHora : Byte;
FNumTicksI,
FTicksPreco : Cardinal;
FEtapa : Integer;
FRestoT : Extended;
FResto : Extended;
FTarifa,
FTarifaA : TncTarifa;
FResetar : Boolean;
FSomandoResto : Boolean;
FPosPago : Boolean;
FCreditoTotal : Cardinal;
FCredTotalG : Cardinal;
FTicksTEtapa : Cardinal;
FPrimeiraEtapa: Boolean;
FTicksResPass : Cardinal;
FTempoRes,
FTol : Cardinal;
FPrecoRes : Double;
FTipoCalc : Byte;
FIsento : Boolean;
FCredProporcional : Boolean;
FCredValorT : Cardinal;
FSemTolerancia : Boolean;
private
procedure AtualizaDiaH;
procedure AvancaProxHora;
function CalculaEtapaTarifacao(aTempo, aTol: Cardinal; aPreco: Double): Boolean;
function CalculaEtapaTempoValor(aTempo, aTol: Cardinal; aPreco: Double): Boolean;
function CalculaEtapaTempoCred(aTempo, aTol: Cardinal; aPreco: Double): Boolean;
function Calcular(aTempoCalc, aTempoCorrido: Cardinal): Boolean;
protected
function GetIsento: Boolean;
function GetHoraTarifa(D, H: Integer): TncTarifa;
function GetInicio: TDateTime;
function GetIDTipoAcesso: Integer;
function GetCredValor: Double;
function GetTipoCalc: Byte;
function GetValor: Double;
function GetCreditoTotal: TncTempo;
function GetTempoCobrado: TncTempo;
procedure SetCredito(const Value: TncTempo);
procedure SetInicio(const Value: TDateTime);
procedure SetTipoCalc(const Value: Byte);
procedure SetCredValor(const Value: Double);
procedure SetNumTicks(const Value: Cardinal);
procedure SetIsento(const Value: Boolean);
procedure SetIDTipoAcesso(const Value: Integer);
public
constructor Create;
destructor Destroy; override;
procedure Reset;
function Cronometro: TncTempo;
function CronometroStr: String;
function CredTempoUsado: TncTempo;
function CredValorUsado: Currency;
function PCredito: PncTempo;
procedure ZeraVars;
procedure CalculaCreditoTotal(aZeraVars: Boolean = True);
function CredValorETempo: TncTempo;
function TempoCredValor(aCredProporcional: Boolean): Cardinal; // Obtem o tempo correspondente ao crédito em valor (FCredValor)
property TicksResPass: Cardinal read FTicksResPass;
property CredTotalG: Cardinal read FCredTotalG;
property NumTicks: Cardinal
read FNumTicks write SetNumTicks;
property IDTipoAcesso: Integer
read GetIDTipoAcesso Write SetIDTipoAcesso;
property Inicio : TDateTime
read GetInicio write SetInicio;
property Credito : TncTempo
read FCredito;
property Passaportes : TncPassaportes
read FPassaportes;
property Pausas : TncPausas
read FPausas;
property CredValor: Double
read GetCredValor write SetCredValor;
property CreditoTotal: TncTempo
read GetCreditoTotal;
property TipoCalc: Byte
read GetTipoCalc write SetTipoCalc;
property Valor: Double
read GetValor;
property Isento: Boolean
read GetIsento write SetIsento;
property TempoCobrado: TncTempo
read GetTempoCobrado;
property SemTolerancia: Boolean
read FSemTolerancia write FSemTolerancia;
end;
const
// Tipos de calculos realizados pela classe Tarifador
tcTarifacao = 0;
tcTempoCred = 1;
tcTempoValor = 2;
var
HoraTarBranco : TncHoraTarifa;
implementation
{ TncPausas }
constructor TncPausa.Create;
begin
pInicio := 0;
pFim := 0;
end;
function TncPausa.DuracaoM: Double;
begin
Result := (pFim - pInicio) * 24 * 60;
end;
function TncPausa.DuracaoT: Cardinal;
begin
Result := DateTimeToTicks(pFim - pInicio);
end;
procedure TncPausas.Limpa;
begin
while FItens.Count>0 do begin
Itens[0].Free;
FItens.Delete(0);
end;
end;
constructor TncPausas.Create;
begin
FItens := TList.Create;
end;
destructor TncPausas.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TncPausas.NewPausa: TncPausa;
begin
Result := TncPausa.Create;
FItens.Add(Result);
end;
function TncPausas.DTTotal: TDateTime;
begin
Result := TicksToDateTime(TicksTotal);
end;
function TncPausas.GetItem(Index: Integer): TncPausa;
begin
Result := TncPausa(FItens[Index]);
end;
function TncPausas.Count: Integer;
begin
Result := FItens.Count;
end;
function TncPausas.GetString: String;
var
I : Integer;
begin
Result := '';
for I := 0 to Count-1 do
with Itens[I] do
Result := Result + GetDTStr(pInicio) + '@' + GetDtStr(pFim) + sListaDelim(classid_TncPausas);
end;
procedure TncPausas.SetString(Value: String);
var
SL : TStrings;
S : String;
I ,P : Integer;
aInicio, aFim : TDateTime;
begin
Limpa;
while GetNextListItem(Value, S, classid_TncPausas) do begin
P := Pos('@', S);
if P > 0 then begin
aInicio := DTFromStr(Copy(S, 1, P-1));
if aInicio>0 then begin
aFim := DTFromStr(Copy(S, P+1, 50));
if aFim>aInicio then with NewPausa do begin
pInicio := aInicio;
pFim := aFim;
end;
end;
end;
end;
end;
function TncPausas.TicksTotal: Cardinal;
var I : Integer;
begin
Result := 0;
for I := 0 to pred(Count) do
Result := Result + Itens[I].DuracaoT;
end;
function TncPausas.TicksPausaEtapa(aInicioE, aFimE: TDateTime): Cardinal;
var I : Integer;
begin
Result := 0;
for I := 0 to pred(Count) - 1 do
with Itens[I] do
if ((aInicioE >= pInicio) and (aInicioE <= pFim)) or
((aFimE >=pInicio) and (aFimE <= pFim)) or
((aInicioE < pInicio) and (aFimE > pFim)) then
Result := DuracaoT;
end;
procedure CalcRestoTempo(Preco, Valor: Double; Tempo: Cardinal; var Resto: Extended; var T: Cardinal);
begin
if Preco > 0.00001 then begin
Resto := (Valor / Preco) * Tempo;
T := Trunc(Resto);
Resto := Frac(Resto);
end else begin
Resto := 0;
T := Tempo;
end;
end;
procedure TncTarifador.AtualizaDiaH;
var Hour, Min, Sec, MSec : Word;
begin
FDia := DayOfWeek(FAgora);
DecodeTime(FAgora, Hour, Min, Sec, MSec);
FHora := Hour;
end;
procedure TncTarifador.AvancaProxHora;
var Hour, Min, Sec, MSec : Word;
begin
DecodeTime(FAgora, Hour, Min, Sec, MSec);
if Hour=23 then begin
FAgora := FAgora + 1;
FHora := 0;
end else
FHora := Hour+1;
FAgora := Trunc(Int(FAgora)) + EncodeTime(FHora, 0, 0, 0);
FDia := DayOfWeek(FAgora);
end;
function TncTarifador.CalculaEtapaTarifacao(aTempo, aTol: Cardinal; aPreco: Double): Boolean;
var
RestoI: Integer;
TempoR,
TempoP : Cardinal;
InicioE, FimE : TDateTime;
begin
Result := False;
FTempoRes := aTempo;
FPrecoRes := aPreco;
if (aTempo=0) then Exit;
InicioE := FAgora;
if not FSomandoResto then begin
FRestoT := FRestoT + FResto;
RestoI := Trunc(FRestoT);
if RestoI > 0 then begin
aTempo := aTempo + RestoI;
FRestoT := FRestoT - RestoI;
end;
FTempoCobrado := FTempoCobrado + aTempo;
FTicksTEtapa := MenorCardinal(aTempo, FTicksR);
aTol := glTolerancia;
if aTol>(aTempo div 2) then
aTol := (aTempo div 2);
FTol := aTol;
end else
FTicksTEtapa := FTicksTEtapa + MenorCardinal(aTempo, FTicksR);
if FSemTolerancia then FTol := 0;
if FPassaportes.Count>0 then begin
TempoP := FPassaportes.AbateCreditos(FTipoAcessoObj.ID, FAgora, MenorCardinal(aTempo, FTicksR));
TempoR := MenorCardinal(aTempo, FTicksR) - TempoP;
end else begin
TempoP := 0;
TempoR := MenorCardinal(aTempo, FTicksR);
end;
if TempoR > 0 then begin
if FCreditoR >= TempoR then begin
FCreditoR := FCreditoR - TempoR;
{ if (FTicksR<aTempo) then
FCreditoR := FCreditoR - MenorCardinal(aTempo-TempoP, FCreditoR) else
FCreditoR := FCreditoR - TempoR; }
end else begin
FCreditoR := 0;
if FPrimeiraEtapa or (FTicksTEtapa > FTol) then begin
if (FTicksR<aTempo) and FCredProporcional then
FValor := FValor + ((FTicksR/aTempo) * aPreco) else
FValor := FValor + aPreco;
FPrecoRes := 0;
FPrimeiraEtapa := False;
end;
end;
end;
if aTempo>FTicksR then
FTempoRes := aTempo-FTicksR else
FTempoRes := 0;
if (FTicksR<=aTempo) {or (FTicksR<(aTempo+FTol))} then begin
FAgora := FAgora + TicksToDateTime(FTicksR);
FTicksR := 0;
end else begin
FTicksR := FTicksR - aTempo;
FAgora := FAgora + TicksToDateTime(aTempo);
end;
if FTempoRes=0 then begin
FimE := FAgora;
FAgora := FAgora + TicksToDateTime(FPausas.TicksPausaEtapa(InicioE, FimE));
end;
AtualizaDiaH;
FSomandoResto := False;
Result := True;
end;
procedure TncTarifador.SetNumTicks(const Value: Cardinal);
begin
if FNumTicks=Value then Exit;
if Value<FNumTicks then Reset;
if FResetar then
Reset;
FTipoCalc := tcTarifacao;
FTicksR := Value - FNumTicks;
if (FNumTicks>0) and (FTempoRes>0) then begin
{ Estamos na continuação de um cálculo, temos então que terminar o cálculo da ultima
etapa que estávamos }
FSomandoResto := True;
try
CalculaEtapaTarifacao(FTempoRes, FTol, FPrecoRes);
finally
FSomandoResto := False;
end;
end;
while (FTicksR > 50) do
if not Calcular(FTicksR, Value-FTicksR) then begin
// Houve uma falha no cáculo. Zerar valor e desistir da tarifação
FValor := 0;
Exit;
end;
FNumTicks := Value;
end;
function TncTarifador.Calcular(aTempoCalc, aTempoCorrido: Cardinal): Boolean;
var
T: Cardinal;
Avancou, aDia, aHora : Byte;
begin
Result := False;
{ 1a coisa é obter a Tarifa para a hora que estamos calculando. FHoraTarifa é uma matriz
que contém a cor da tarifa a ser usada para cada hora e dia da semana.
O código de cor é guardado em FTarifaAI e é a chave para obter o objeto TncTarifa que
contém os detalhes necessários para a tarifação. FTarifa e FTarifaA guardam a referencia
para o TncTarifa. FTarifaA é um cache }
if (FTarifaA<>nil) and (FTarifaA=GetHoraTarifa(FDia, FHora)) then
FTarifa := FTarifaA
{ Tarifa atual igual anterior então usamos o cache }
else begin
{ Mudou a tarifa, temos que atualizar nosso objeto }
FTarifa := GetHoraTarifa(FDia, FHora);
{ Se FTarifa=nil significa que não existe nenhuma Tarifa associada ao horário que estamos,
portanto vamos avançando no tempo até encontrar uma hora seguinte q tenha
uma tarifa associada. Mas pode ser que a tabela toda não tenha nenhuma tarifa associada,
nesse caso temos que abortar a Tarifação para não entrar em Loop Infinito }
Avancou := 0;
aDia := FDia;
aHora := FHora;
while (FTarifa=nil) and (Avancou<24) do begin
if aHora<23 then
Inc(aHora) else
begin
aHora := 0;
if aDia<7 then
Inc(aDia) else
aDia := 1;
end;
FTarifa := GetHoraTarifa(aDia, aHora);
Inc(Avancou);
end;
if (FTarifa=nil) {and (Avancou>=24)} then
Exit;
// Rodamos 24H e não encontramos nenhuma tarifa então desistimos da tarifação
end;
{ Uma cor pode ter várias etapas de tarifação, em qual estamos ? }
if (FTarifa<>FTarifaA) then begin
{ Mudou de cor. Cada cor tem suas etapas e regras de tarifação.
O Tempo Corrido na Cor Anterior ajuda a determinar em qual etapa da
próxima cor o sistema deve continuar a tarifacao }
{ Obtem o indice da etapa de preço atual }
FEtapa := FTarifa.ObtemIndProxPreco(aTempoCorrido);
FTicksPreco := aTempoCorrido;
end else
if ((aTempoCorrido-FTicksPreco) >= FTarifa.PPrecos^[FEtapa].etTempo) then begin
{ Não mudou a cor. Mas o tempo já é maior que o definido para essa etapa }
if (FEtapa < High(FTarifa.PPrecos^)) then begin
{ Ainda existe existe mais etapas nessa tarifa. Devemos avançar para próxima então }
Inc(FEtapa);
FTicksPreco := aTempoCorrido;
end else begin
{ Não existe mais etapas nessa tarifa. Obter a próxima tarifa a ser repetida }
FEtapa := FTarifa.IndiceRepetir;
FTicksPreco := aTempoCorrido;
end;
end;
if (FEtapa>=0) then
with FTarifa.PPrecos^[FEtapa] do begin
{ Retorna em T qual é o tempo correspondente à fração mínima e tb o resto
dessa regra de 3 em FResto }
CalcRestoTempo(etValor, etValorMin, etTempo, FResto, T);
{ Tarifar (no máximo) uma fatia de tempo de Fração Mínima }
case FTipoCalc of
tcTarifacao : if not CalculaEtapaTarifacao(T, etTolerancia, etValorMin) then Exit;
tcTempoCred : if not CalculaEtapaTempoCred(T, etTolerancia, etValorMin) then Exit;
tcTempoValor : if not CalculaEtapaTempoValor(T, etTolerancia, etValorMin) then Exit;
end;
end else
// Etapa inválida entao desistimos da Tarifação
Exit;
FTarifaA := FTarifa;
Result := True;
end;
constructor TncTarifador.Create;
begin
FTipoAcessoObj := nil;
FCreditoTotal := 0;
FCredTotalG := 0;
FPassaportes := TncPassaportes.Create;
FPausas := TncPausas.Create;
FNumTicks := 0;
FCredValor := 0;
FIsento := False;
FCredito.Minutos := 0;
FTipoCalc := tcTarifacao;
FSemTolerancia := False;
FCredValorT := 0;
FTicksResPass := 0;
Reset;
end;
procedure TncTarifador.SetCredito(const Value: TncTempo);
begin
if FCredito.Minutos=Value.Minutos then Exit;
FCredito.Minutos := Value.Minutos;
FResetar := True;
end;
procedure TncTarifador.SetInicio(const Value: TDateTime);
begin
if FInicio=Value then Exit;
FInicio := Value;
FResetar := True;
end;
procedure TncTarifador.SetIDTipoAcesso(const Value: Integer);
begin
FTipoAcessoObj := gTiposAcesso.PorCodigo[Value];
FResetar := True;
end;
procedure TncTarifador.SetTipoCalc(const Value: Byte);
begin
if FTipoCalc=Value then Exit;
FTipoCalc := Value;
Reset;
end;
procedure TncTarifador.SetCredValor(const Value: Double);
begin
if FCredValor=Value then Exit;
FCredValor := Value;
FResetar := True;
end;
function TncTarifador.TempoCredValor(aCredProporcional: Boolean): Cardinal;
begin
Result := 0;
ZeraVars;
if FCredValor < 0.00000001 then Exit;
FCredProporcional := aCredProporcional;
try
FTipoCalc := tcTempoValor;
FValor := 0;
FNumTicks := 0;
while (FValor <= FCredValor) and Calcular(0, FNumTicks) do {};
Result := FNumTicks;
finally
FCredProporcional := False;
end;
end;
function TncTarifador.CredValorETempo: TncTempo;
begin
Result.Ticks := PCredito^.Ticks + FCredValorT;
end;
function TncTarifador.CalculaEtapaTempoValor(aTempo, aTol: Cardinal; aPreco: Double): Boolean;
var
RestoI: Integer;
begin
Result := False;
if (aTempo=0) then Exit;
FRestoT := FRestoT + FResto;
RestoI := Trunc(FRestoT);
if RestoI > 0 then begin
aTempo := aTempo + RestoI;
FRestoT := FRestoT - RestoI;
end;
if ((FValor + aPreco) - FCredValor) >= 0.00001 then begin
if FCredProporcional then
FNumTicks := FNumTicks + Trunc(((FCredValor - FValor) / aPreco) * aTempo);
FValor := FCredValor + 1;
end else begin
FNumTicks := FNumTicks + aTempo;
FValor := FValor + aPreco;
end;
FAgora := FAgora + TicksToDateTime(aTempo);
AtualizaDiaH;
Result := True;
end;
function TncTarifador.CalculaEtapaTempoCred(aTempo, aTol: Cardinal;aPreco: Double): Boolean;
var
RestoI: Integer;
TempoP : Cardinal;
begin
Result := False;
if (aTempo=0) then Exit;
FRestoT := FRestoT + FResto;
RestoI := Trunc(FRestoT);
if RestoI > 0 then begin
aTempo := aTempo + RestoI;
FRestoT := FRestoT - RestoI;
end;
if FPassaportes.Count>0 then
TempoP := FPassaportes.AbateCreditos(FTipoAcessoObj.ID, FAgora, aTempo)
else
TempoP := 0;
if (FCreditoR+TempoP) < aTempo then begin
FNumTicks := FNumTicks + FCreditoR + TempoP;
FValor := 1;
FCreditoR := 0;
end else begin
FNumTicks := FNumTicks + aTempo;
FCreditoR := FCreditoR - (aTempo - TempoP);
end;
FAgora := FAgora + TicksToDateTime(aTempo);
AtualizaDiaH;
Result := True;
end;
function TncTarifador.GetCreditoTotal: TncTempo;
begin
Result.Ticks := FCreditoTotal;
end;
function TncTarifador.GetTempoCobrado: TncTempo;
begin
Result.Ticks := FTempoCobrado;
end;
function TncTarifador.GetCredValor: Double;
begin
Result := FCredValor;
end;
function TncTarifador.GetHoraTarifa(D, H: Integer): TncTarifa;
begin
if FTipoAcessoObj<>nil then
Result := FTipoAcessoObj.TarifaHoraObj(D, H) else
Result := nil;;
end;
function TncTarifador.GetInicio: TDateTime;
begin
Result := FInicio;
end;
function TncTarifador.GetIDTipoAcesso: Integer;
begin
if FTipoAcessoObj=nil then
Result := -1 else
Result := FTipoAcessoObj.ID;
end;
function TncTarifador.GetTipoCalc: Byte;
begin
Result := FTipoCalc;
end;
function TncTarifador.GetValor: Double;
begin
if FIsento then
Result := 0 else
Result := FValor;
end;
function TncTarifador.PCredito: PncTempo;
begin
Result := @FCredito;
end;
function TncTarifador.CredTempoUsado: TncTempo;
begin
if (FCreditoR >= FCredito.Ticks) then
Result.Ticks := 0 else
Result.Ticks := FCredito.Ticks - FCreditoR;
end;
function TncTarifador.CredValorUsado: Currency;
var Tar: TncTarifador;
begin
if (FCreditoR <= FCredito.Ticks) then
Result := FCredValor
else begin
Tar := TncTarifador.Create;
try
Tar.IDTipoAcesso := IDTipoAcesso;
Tar.Inicio := Inicio;
Tar.FCredProporcional := True;
Tar.NumTicks := FCreditoR - FCredito.Ticks;
Tar.SemTolerancia := True;
Result := FCredValor - Tar.Valor;
finally
Tar.Free;
end;
end;
end;
function TncTarifador.GetIsento: Boolean;
begin
Result := FIsento;
end;
procedure TncTarifador.SetIsento(const Value: Boolean);
begin
FIsento := Value;
end;
procedure TncTarifador.CalculaCreditoTotal(aZeraVars: Boolean= True);
var FSalvaCred: Extended;
begin
FTipoCalc := tcTempoCred;
ZeraVars;
FValor := 0;
FCreditoTotal := 0;
FCredTotalG := 0;
FTicksResPass := 0;
FNumTicks := 0;
if FTipoAcessoObj<>nil then
FCredTotalG := FPassaportes.TempoTotalDisp(FTipoAcessoObj.ID, FAgora) + FCredito.Ticks + FCredValorT;
try
while (FValor <= 0.01) and Calcular(0, FNumTicks) do {};
if FTipoAcessoObj<>nil then
FTicksResPass := FPassaportes.TempoRestanteTotal(FAgora);
FCreditoTotal := FNumTicks;
finally
if aZeraVars then ZeraVars;
end;
end;
function TncTarifador.Cronometro: TncTempo;
begin
if FCreditoTotal>FNumTicks then
Result.Ticks := FCreditoTotal - FNumTicks else
Result.Ticks := FNumTicks - FCreditoTotal;
end;
function TncTarifador.CronometroStr: String;
begin
Result := FormatDateTime('hh:mm:ss', Cronometro.DateTime); // do not localize
end;
destructor TncTarifador.Destroy;
begin
FPassaportes.Free;
FPausas.Free;
inherited;
end;
procedure TncTarifador.Reset;
begin
try
FCredValorT := TempoCredValor(True);
if FPassaportes.Count>0 then
CalculaCreditoTotal
else begin
FCreditoTotal := FCredito.Ticks + FCredValorT;
FCredTotalG := FCreditoTotal;
end;
finally
ZeraVars;
end;
end;
procedure TncTarifador.ZeraVars;
begin
FTempoRes := 0;
FTol := 0;
FPrecoRes := 0;
FPrimeiraEtapa := True;
FResetar := False;
FValor := 0;
FAgora := FInicio;
if FPassaportes.Count>0 then
FPassaportes.ZeraInicioUso;
FTempoCobrado := 0;
FCreditoR := FCredito.Ticks + FCredValorT;
AtualizaDiaH;
FNumTicksI := 0;
FRestoT := 0;
FResto := 0;
FTarifaA := nil;
FTicksPreco := 0;
FTicksR := 0;
FNumTicks := 0;
end;
initialization
Fillchar(HoraTarBranco, SizeOf(HoraTarBranco), 0);
end.
|
unit uMainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Menus, frxpngimage, sSkinManager,
Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, frxClass, CPort;
type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Konfigurasi1: TMenuItem;
Exit: TMenuItem;
N1: TMenuItem;
PengaturanBerkas1: TMenuItem;
ManajemenBerkas1: TMenuItem;
MutasiBerkas1: TMenuItem;
Laporan1: TMenuItem;
TentangIrma1: TMenuItem;
StatusBar1: TStatusBar;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
btnRefresh: TButton;
tmrRefresh: TTimer;
BerkasKeluarMasuk1: TMenuItem;
N2: TMenuItem;
sSkinManager1: TsSkinManager;
lstResult: TAdvStringGrid;
btnBerkasKeluarMasuk: TButton;
frxReport1: TfrxReport;
ComPort1: TComPort;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tmrRefreshTimer(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure btnBerkasKeluarMasukClick(Sender: TObject);
procedure lstResultDblClick(Sender: TObject);
procedure Konfigurasi1Click(Sender: TObject);
procedure ExitClick(Sender: TObject);
procedure BerkasKeluarMasuk1Click(Sender: TObject);
procedure ManajemenBerkas1Click(Sender: TObject);
procedure MutasiBerkas1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure LoadData();
end;
var
MainForm: TMainForm;
implementation
uses _uStringGrid, _IniFiles, uDM, uBerkas, uBerkasMutasi, uBerkasScan, ADODB, DB,
DateUtils, uKonfigurasi;
{$R *.dfm}
var
vIni: TMyIni;
tmrCnt: Integer;
procedure WriteCOM(TextToSend:string);
begin
with MainForm.ComPort1 do
begin
Port:= vIni.Read('COMPort','port','COM1');
try
Open;
except
ShowSetupDialog;
try
Open;
finally
vIni.Write('COMPort','Port',Port);
end;
end;
if not Connected then Exit;
WriteStr(TextToSend);
Sleep(200);
end;
end;
procedure TMainForm.LoadData();
var
i, iCnt: Integer;
sNoRM, sNama, sLokasi: string;
begin
tmrRefresh.Enabled:=False;
btnRefresh.Enabled:=False;
btnRefresh.Caption:= 'Loading...';
//note: kosongkan status berkas rm
DM.runQuery(DM.cnn2, DM.qry2, 'update rm set ada=false', eExecute);
//note: load data pasien aktif saat ini di sirus
if DM.runQuery(DM.cnn1, DM.qry1, 'select norm,nama,lokasi from msttblreg', eOpen, DBSQLServer) then
begin
DM.qry1.First;
for i:= 1 to DM.qry1.RecordCount do
begin
sNoRM:= DM.qry1.FieldByName('norm').AsString;
sNama:= DM.qry1.FieldByName('nama').AsString;
sLokasi:= DM.qry1.FieldByName('lokasi').AsString;
//note: cek apakah no rm tersebut tidak ada di tabel rm
if not DM.runQuery(DM.cnn2, DM.qry2, 'select idrm from rm where norm='+QuotedStr(DM.qry1.FieldByName('norm').AsString)) then
begin
DM.runQuery(DM.cnn2, DM.qry2, 'insert into rm(norm,nama,lokasi,norak) values('+
QuotedStr(sNoRM)+','+QuotedStr(sNama)+','+QuotedStr(sLokasi)+',0)', eExecute);
end;
//note: cek apakah no rm tersebut ada di tabel detil
if DM.runQuery(DM.cnn2, DM.qry2, 'select top 1 rm.idrm,detil.ada from detil inner join rm on detil.idrm=rm.idrm where rm.norm='+QuotedStr(DM.qry1.FieldByName('norm').AsString)+' order by detil.iddetil desc') then
begin
//note: perbaharui data rm
DM.runQuery(DM.cnn3, DM.qry3, 'update rm set nama='+QuotedStr(sNama)+',lokasi='+QuotedStr(sLokasi)+',ada='+DM.qry2.FieldByName('ada').AsString+
' where idrm='+DM.qry2.FieldByName('idrm').AsString, eExecute);
end else
begin
//note: bikin data detil yang baru dengan status ada=true
if DM.qry2.RecordCount = 0 then
begin
if DM.runQuery(DM.cnn2, DM.qry2, 'select idrm from rm where norm='+QuotedStr(sNoRM)) then
begin
DM.runQuery(DM.cnn3, DM.qry3, 'insert into detil(idrm,tanggal,lokasi,ada) values('+
DM.qry2.FieldByName('idrm').AsString+',now(),'+QuotedStr(sLokasi)+',true)', eExecute);
DM.runQuery(DM.cnn3, DM.qry3, 'update rm set ada=true where idrm='+DM.qry2.FieldByName('idrm').AsString, eExecute);
end;
end;
end;
DM.qry1.Next;
end;
end;
//note: load data untuk ditampilkan
WriteCOM('Z');
DM.runQuery(DM.cnn1, DM.qry1, 'select idrm,norm,nama,lokasi,norak from rm where ada=true order by norm');
with lstResult do
begin
ClearStringGrid(lstResult);
iCnt:= DM.qry1.RecordCount;
if iCnt > 0 then
begin
RowCount:= iCnt + 1;
DM.qry1.First;
for i:= 1 to iCnt do
begin
Cells[0,i]:= DM.qry1.Fields[0].AsString;
Cells[1,i]:= DM.qry1.Fields[1].AsString;
Cells[2,i]:= DM.qry1.Fields[2].AsString;
Cells[3,i]:= DM.qry1.Fields[3].AsString;
Cells[4,i]:= DM.qry1.Fields[4].AsString;
WriteCOM(Cells[4,i]+'AX');
DM.qry1.Next;
end;
end;
end;
btnRefresh.Caption:= 'Finish!';
btnRefresh.Enabled:=True;
tmrRefresh.Enabled:=True;
tmrCnt:= StrToInt(vIni.Read('Timer','Refresh','20'));
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
vIni:= TMyIni.Create;
//note: sembunyikan kolom idrm
lstResult.HideColumn(0);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
WriteCOM('Z');
vIni.Free;
end;
procedure TMainForm.tmrRefreshTimer(Sender: TObject);
begin
btnRefresh.Caption:= 'Ambil Data Pendaftaran (' + IntToStr(tmrCnt) + ' detik)';
if tmrCnt > 0 then Dec(tmrCnt) else LoadData;
end;
procedure TMainForm.btnRefreshClick(Sender: TObject);
begin
LoadData;
end;
procedure TMainForm.lstResultDblClick(Sender: TObject);
begin
//note: tampilkan data yang terseleksi pada form manajemen berkas
frmBerkas.CariBerkas(lstResult.Cells[0, lstResult.Row]);
end;
procedure TMainForm.btnBerkasKeluarMasukClick(Sender: TObject);
begin
frmBerkasScan.ShowModal;
end;
procedure TMainForm.Konfigurasi1Click(Sender: TObject);
begin
frmKonfigurasi.ShowModal;
end;
procedure TMainForm.ExitClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.BerkasKeluarMasuk1Click(Sender: TObject);
begin
btnBerkasKeluarMasuk.Click;
end;
procedure TMainForm.ManajemenBerkas1Click(Sender: TObject);
begin
frmBerkas.ShowModal;
end;
procedure TMainForm.MutasiBerkas1Click(Sender: TObject);
begin
frmBerkasMutasi.ShowModal;
end;
end.
|
unit delphi_intf_2;
interface
implementation
type
IUnknown = interface
function QueryInterface(const IID: TGUID; out Intf: IUnknown): Int32; stdcall;
function _AddRef: Int32; stdcall;
function _Release: Int32; stdcall;
end external 'SYS';
function GetIUnknown: IUnknown; external 'SYS';
var I, J: IUnknown;
R: Int32;
procedure Test;
begin
I := GetIUnknown();
R := I.QueryInterface('{00000000-0000-0000-C000-000000000046}', J);
end;
initialization
Test();
finalization
Assert(I = J);
end. |
unit ksSlideMenuUI;
interface
{$I ksComponents.inc}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
ksTypes, ksVirtualListView, FMX.Effects, ksAppEvents;
type
TfrmSlideMenuUI = class(TForm)
lvMenu: TksVirtualListView;
PaintBox1: TPaintBox;
procedure _Image1Click(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure PaintBox1Click(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
procedure lvMenuMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
private
FCanSelect: Boolean;
FOnSelectItem: TksVListItemClickEvent;
FBitmap: TBitmap;
FAppEvents: TksAppEvents;
FCallingForm: TCommonCustomForm;
FLeftAlign: Boolean;
procedure Delay;
procedure WillBecomeActive(Sender: TObject);
{ Private declarations }
protected
procedure DoShow; override;
procedure SelectItem(Sender: TObject; AItem: TksVListItem);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure OpenMenu(ACallingForm: TCommonCustomForm; ALeftAlign: Boolean);
procedure CloseMenu;
property OnSelectItem: TksVListItemClickEvent read FOnSelectItem write FOnSelectItem;
property Bitmap: TBitmap read FBitmap;
{ Public declarations }
end;
implementation
uses FMX.Ani, ksCommon, ksSlideMenu, DateUtils, System.UIConsts;
{$R *.fmx}
{ TfrmSlideMenuUI }
constructor TfrmSlideMenuUI.Create(AOwner: TComponent);
begin
inherited;
FAppEvents := TksAppEvents.Create(nil);
FBitmap := TBitmap.Create;
FAppEvents.WillBecomeForeground := WillBecomeActive;
end;
procedure TfrmSlideMenuUI.Delay;
var
ANow: TDatetime;
begin
ANow := Now;
while MilliSecondsBetween(ANow, Now) < 100 do
Application.ProcessMessages;
end;
destructor TfrmSlideMenuUI.Destroy;
begin
FreeAndNil(FBitmap);
FAppEvents.DisposeOf;
inherited;
end;
procedure TfrmSlideMenuUI.WillBecomeActive(Sender: TObject);
{$IFDEF ANDROID}
var
ABmp: TBitmap;
{$ENDIF}
begin
{$IFDEF ANDROID}
ABmp := TBitmap.Create;
try
GenerateFormImageExt(FCallingForm, ABmp);
Bitmap.Assign(ABmp);
finally
FreeAndNil(ABmp);
end;
{$ENDIF}
end;
procedure TfrmSlideMenuUI.CloseMenu;
begin
Delay;
TAnimator.AnimateFloatWait(PaintBox1, 'Position.X', 0, 0.2, TAnimationType.InOut, TInterpolationType.Sinusoidal);
Visible := False;
end;
procedure TfrmSlideMenuUI.DoShow;
begin
inherited;
Delay;
case FLeftAlign of
True: TAnimator.AnimateFloatWait(PaintBox1, 'Position.X', C_DEFAULT_MENU_WIDTH, 0.2, TAnimationType.InOut, TInterpolationType.Sinusoidal);
False: TAnimator.AnimateFloatWait(PaintBox1, 'Position.X', 0 - C_DEFAULT_MENU_WIDTH, 0.2, TAnimationType.InOut, TInterpolationType.Sinusoidal);
end;
FCanSelect := True;
end;
procedure TfrmSlideMenuUI.FormKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkHardwareBack then
PaintBox1Click(Self); //Image1Click(Self);
Key := 0;
end;
procedure TfrmSlideMenuUI.lvMenuMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
if lvMenu.Items.ItemAtPos(x, y) = nil then
begin
CloseMenu;
FCallingForm.Visible := True;
end;
end;
procedure TfrmSlideMenuUI._Image1Click(Sender: TObject);
begin
SelectItem(Self, lvMenu.Items[lvMenu.ItemIndex]);
end;
procedure TfrmSlideMenuUI.OpenMenu(ACallingForm: TCommonCustomForm; ALeftAlign: Boolean);
var
ABmp: TBitmap;
begin
FLeftAlign := ALeftAlign;
case ALeftAlign of
True: lvMenu.Align := TAlignLayout.Left;
False: lvMenu.Align := TAlignLayout.Right;
end;
FCallingForm := ACallingForm;
FCanSelect := False;
if lvMenu.ItemIndex = -1 then
lvMenu.ItemIndex := 0;
lvMenu.OnItemClick := SelectItem;
lvMenu.Width := C_DEFAULT_MENU_WIDTH;
ABmp := TBitmap.Create;
try
GenerateFormImageExt(ACallingForm, ABmp);
Bitmap.Assign(ABmp);
finally
FreeAndNil(ABmp);
end;
PaintBox1.SetBounds(0, 0, ACallingForm.ClientWidth, ACallingForm.ClientHeight);
{$IFDEF XE10_OR_NEWER}
SetBounds(ACallingForm.Bounds);
{$ELSE}
SetBounds(ACallingForm.Left, ACallingForm.Top, ACallingForm.Width, ACallingForm.Height);
{$ENDIF}
Visible := True;
end;
procedure TfrmSlideMenuUI.PaintBox1Click(Sender: TObject);
begin
CloseMenu;
FCallingForm.Visible := True;
end;
procedure TfrmSlideMenuUI.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
begin
Canvas.DrawBitmap(FBitmap, RectF(0, 0, FBitmap.Width, FBitmap.Height), PaintBox1.ClipRect, 1, False);
{Canvas.Stroke.Color := claBlack;
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.DrawRect(PaintBox1.ClipRect, 10, 10, AllCorners, 1);}
end;
procedure TfrmSlideMenuUI.SelectItem(Sender: TObject; AItem: TksVListItem);
begin
if FCanSelect = False then
Exit;
FCanSelect := False;
if Assigned(FOnSelectItem) then
FOnSelectItem(Self, AItem);
end;
end.
|
unit uEngineAnimation;
{$ZEROBASEDSTRINGS OFF}
{
引擎中基础的动画类....
以T2DAnimation为基础,对具体的动画进行扩展....
这里的动画,实际上主要的功能就是根据时间计算出当前的值....
}
interface
uses
System.Classes,System.UITypes, FMX.Types,FMX.Objects, System.JSon,
System.SysUtils, System.Types, uEngineUtils, Math,RTTI;
Type
TAnimationFinish = Procedure(AnimationName : String) Of Object;
Type
T2DAnimation = Class
Private
FOwner : TObject; //Pointer; // 这个动画的Parent...
FTimeDur : Integer; // 整个引擎的Timer的时间间隔...
FCounter : Integer; // 当前的计数器的值...
FAnimationName : String; // Animation的名称,方便后面直接通过名称来激活这个Animation...
FEnabled : Boolean; // 是否处于激活状态....
FLoop : Boolean; // 是否循环播放...
FFreeOnFinish : Boolean; // 执行完成后自动销毁...
//FOnFinish : TAnimationFinish; // 动画执行完成后的函数...
FOnFinish : TProc<String>; // 动画执行完成后的函数...
protected
FOwnerClass : TClass;
procedure SetOwner(value : TObject);
Public
Constructor Create;
Destructor Destroy; override;
Procedure Start; virtual;abstract; // 开始动画...
Procedure Pause; virtual;abstract; // 暂停动画...
Procedure Stop; virtual;abstract; // 结束动画...Stop的时候会将一些变量初始化一下,而Pause的时候不需要...
Procedure DoAnimation(inT : Integer); virtual; abstract; // 执行一次动画,然后改变下Owner的某一些值...
property Owner : TObject read FOwner write SetOwner;
property TimeDur : Integer Read FTimeDur Write FTimeDur;
property Counter : Integer Read FCounter Write FCounter;
Property Name : String Read FAnimationName Write FAnimationName;
Property Enabled : Boolean Read FEnabled Write FEnabled;
Property Loop : Boolean Read FLoop Write FLoop;
Property FreeOnFinish : Boolean Read FFreeOnFinish Write FFreeOnFinish;
// Property OnFinish : TAnimationFinish Read FOnFinish Write FOnFinish;
property OnFinish : TProc<String> read FOnFinish write FOnFinish;
End;
// 旋转动画...
Type
T2DRotationAnimation = Class(T2DAnimation)
Private
FSpeed : Single; // 旋转的速度...每秒多少度....
FStartValue : Single; // 旋转的起始角度....
FStopValue : Single; // 旋转的结束角度....
FCurrentValue : Single; // 当前的值...
FInitRotationPoint : TPointF;
Public
Constructor Create;
Destructor Destroy; override;
Procedure Start; override;
Procedure Pause; Override;
Procedure Stop; Override;
Procedure DoAnimation(inT : Integer); Override;
Procedure ReadFromJSON(inJObj : TJSONObject);
Property Speed : Single Read FSpeed Write FSpeed;
Property StartValue : Single Read FStartValue Write FStartValue;
Property StopValue : Single Read FStopValue Write FStopValue;
property InitRotationPoint : TPointF read FInitRotationPoint write FInitRotationPoint;
End;
// 位移动画...
Type
T2DPathAnimation = Class(T2DAnimation)
Private
FStart : TPointF; // 动画的起始点...
FStop : TPointF; // 动画的结束点...
FCurrentPoint : TPointF; // 动画当前的位置...
FSpeed : Single; // 位移的速度...每秒位移的像素...
FMovePoints : Array Of TPointF; // 所有的移动的点的数组...
FTotalLength : Single; // 整个位移的总长度....
FCurrentLength : Single; // 当前的位移长度...用于计算下当前的点...
Procedure ReadAllPoints(inStr : String);
public
Constructor Create;
Destructor Destroy; override;
Procedure Start; override;
Procedure Pause; Override;
Procedure Stop; Override;
Procedure DoAnimation(inT : Integer); Override;
Procedure ReadFromJSON(inJObj : TJSONObject);
Procedure AddAPoint(X, Y : Single);
Property Speed : Single Read FSpeed Write FSpeed;
Property StartValue : TPointF Read FStart Write FStart;
Property StopValue : TPointF Read FStop Write FStop;
End;
implementation
uses
uEngine2DSprite,uEngine2DExtend,uEngine2DObject,uGeometryClasses;
{T2DAnimation}
Constructor T2DAnimation.Create;
begin
FTimeDur := 10;
FCounter := 0;
FEnabled := False;
FLoop := False;
end;
Destructor T2DAnimation.Destroy;
begin
Inherited;
end;
procedure T2DAnimation.SetOwner(value: TObject);
var
LContext : TRttiContext;
LClass : TRttiInstanceType;
begin
FOwner := value;
FOwnerClass := value.ClassType;
end;
{T2DRotationAnimation}
Constructor T2DRotationAnimation.Create;
begin
Inherited;
FInitRotationPoint := PointF(0,0);
end;
DEstructor T2DRotationAnimation.Destroy;
begin
Inherited;
end;
Procedure T2DRotationAnimation.Start;
begin
if not Enabled then
begin
Enabled := true;
end;
end;
Procedure T2DRotationAnimation.Pause;
begin
if Enabled then
begin
Enabled := False;
end;
end;
Procedure T2DRotationAnimation.Stop;
begin
if Enabled then
begin
Enabled := False;
Counter := 0;
FCurrentValue := FStartValue;
end;
end;
Procedure T2DRotationAnimation.ReadFromJSON(inJObj: TJSONObject);
var
tmpValue : TJSONValue;
II : Integer;
begin
tmpValue := inJObj.Values['Name'];
if tmpValue <> nil then
begin
self.Name := tmpValue.Value;
end;
tmpValue := inJObj.Values['StartValue'];
if tmpValue <> nil then
begin
try
II := StrToInt(tmpValue.Value);
except
II := 0;
end;
Self.FStartValue := II;
end;
tmpValue := inJObj.Values['StopValue'];
if tmpValue <> nil then
begin
try
II := StrToInt(tmpValue.Value);
except
II := 0;
end;
Self.FStopValue := II;
end;
tmpValue := inJObj.Values['Speed'];
if tmpValue <> nil then
begin
try
II := StrToInt(tmpValue.Value);
except
II := 0;
end;
Self.FSpeed := II;
end;
tmpValue := inJObj.Values['Enabled'];
if tmpValue <> nil then
begin
Self.Enabled := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['Loop'];
if tmpValue <> nil then
begin
Self.Loop := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['RotationX'];
if tmpValue <> nil then
begin
try
FInitRotationPoint.X := StrToFloat(tmpValue.Value);
except
FInitRotationPoint.X := 0;
end;
end;
tmpValue := inJObj.Values['RotationY'];
if tmpValue <> nil then
begin
try
FInitRotationPoint.Y := StrToFloat(tmpValue.Value);
except
FInitRotationPoint.Y := 0;
end;
end;
end;
Procedure T2DRotationAnimation.DoAnimation(inT : Integer ) ;
var
PSprite : TEngine2DSprite;
begin
Counter := Counter + 1;
if Owner = nil then
exit;
PSprite := TEngine2DSprite(Owner);
PSprite.RotationAngle := PSprite.RotationAngle +(FSpeed*inT)/1000*(pi/180);
if Loop then
begin
if PSprite.RotationAngle >= FStopValue*pi/180 then
begin
PSprite.RotationAngle := PSprite.RotationAngle - FStopValue*pi/180;
end;
end else
begin
if PSprite.RotationAngle >= FStopValue*pi/180 then
begin
PSprite.RotationAngle := FStopValue*pi/180;
Enabled := False;
// 动画结束了,调用OnFinish事件....
if Assigned(FOnFinish) then
begin
FOnFinish(Self.Name);
end;
end;
end;
// 计算下旋转的点...
PSprite.RotationPoint := PointF((PSprite.Position.Width/PSprite.Position.InitWidth)*Self.FInitRotationPoint.X,
(PSprite.Position.Height/PSprite.Position.InitHeight)*Self.FInitRotationPoint.Y);
end;
{T2DPathAnimation}
Constructor T2DPathAnimation.Create;
begin
Inherited;
SetLength(FMovePoints, 0);
end;
Destructor T2DPathAnimation.Destroy;
begin
SetLength(FMovePoints, 0);
Inherited;
end;
Procedure T2DPathAnimation.Start;
begin
if not Enabled then
begin
Enabled := true;
end;
end;
Procedure T2DPathAnimation.Pause;
begin
if Enabled then
begin
Enabled := false;
end;
end;
Procedure T2DPathAnimation.Stop;
begin
if Enabled then
begin
Enabled := False;
FCurrentPoint := FStart;
Counter := 0;
end;
end;
Procedure T2DPathAnimation.ReadFromJSON(inJObj: TJSONObject);
var
tmpValue : TJSONValue;
II : Integer;
begin
tmpValue := inJObj.Values['Name'];
if tmpValue <> nil then
begin
self.Name := tmpValue.Value;
end;
tmpValue := inJObj.Values['Loop'];
if tmpValue <> nil then
begin
self.Loop := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['Enabled'];
if tmpValue <> nil then
begin
self.Enabled := UpperCase(tmpValue.Value) = 'TRUE';
end;
tmpValue := inJObj.Values['Speed'];
if tmpValue <> nil then
begin
try
II := StrToInt(tmpValue.Value);
except
end;
Self.Speed := II;
end;
tmpValue := inJObj.Values['MovePoints'];
if tmpValue <> nil then
begin
ReadAllPoints(tmpValue.Value);
end;
end;
Procedure T2DPathAnimation.AddAPoint(X: Single; Y: Single);
Var
_Len : Integer;
I : Integer;
begin
_Len := Length(FMovePoints);
SetLength(FMovePoints, _Len + 1);
FMovePoints[_Len] := PointF(X,Y);
if length(FMovePoints) <= 1 then
begin
Self.FTotalLength := 0;
end;
FTotalLength := 0;
for i := 1 to High(FMovePoints) do
begin
FTotalLength := FTotalLength + sqrt(power(FMovePoints[I].X - FMovePoints[I-1].X, 2) + Power(FMovePoints[I].Y - FMovePoints[I-1].Y, 2));
end;
end;
Procedure T2DPathAnimation.ReadAllPoints(inStr: string);
var
S, S1 : String;
P1, P2 : Single;
_Len : Integer;
I : Integer;
begin
SetLength(Self.FMovePoints,0);
while inStr <> '' do
begin
GetHeadString(inStr,'(');
S := GetHeadString(inStr,')');
try
S1 := GetHeadString(S,',');
P1 := StrToFloat(S1);
P2 := StrToFloat(S);
except
Continue;
end;
_Len := Length(FMovePoints);
_Len := _Len + 1;
SetLength(FMovePoints, _Len);
FMovePoints[_Len-1] := PointF(P1, P2);
end;
// 计算下总长度...
if length(FMovePoints) <= 1 then
begin
Self.FTotalLength := 0;
end;
FTotalLength := 0;
for i := 1 to High(FMovePoints) do
begin
FTotalLength := FTotalLength + sqrt(power(FMovePoints[I].X - FMovePoints[I-1].X, 2) + Power(FMovePoints[I].Y - FMovePoints[I-1].Y, 2));
end;
end;
Procedure T2DPathAnimation.DoAnimation(inT : Integer);
var
I : Integer;
DL, TL : Single;
CX, CY : Single;
PSprite : TEngine2DSprite;
PImage : TEngine2DImage;
T : TRttiType;
P : TRttiProperty;
R : TValue;
LPosition : T2DPosition;
LX,LY : Single;
LRPosition : TValue;
begin
if Owner = nil then
exit;
if not Enabled then
exit;
// 开始计算下当前的位移量....
Counter := Counter + 1;
FCurrentLength := FCurrentLength + Speed*inT/1000;
if FCurrentLength >= FTotalLength then
begin
if Loop then
begin
while FCurrentLength > FTotalLength do
begin
FCurrentLength := FCurrentLength - FTotalLength;
end;
end else
begin
FCurrentLength := FTotalLength;
Enabled := False;
if Assigned(FOnFinish) then
begin
FOnFinish(Self.Name);
end;
end;
end;
// 根据当前的位移来计算相应的位置...
TL := 0;
CX := 0;
CY := 0;
for i := 1 to High(FMovePoints) do
begin
DL := sqrt(Power(FMovePoints[i].X - FMovePoints[i-1].X, 2) + Power(FMovePoints[i].Y - FMovePoints[i-1].Y, 2));
if DL = 0 then
begin
if not Enabled then
begin
Enabled := False;
if Assigned(FOnFinish) then
begin
FOnFinish(Self.Name);
end;
end;
exit;
end;
if TL + DL >= FCurrentLength then
begin
// 找到了当前的点....
CX := FMovePoints[I-1].X + ((FCurrentLength - TL)/DL)*(FMovePoints[i].X - FMovePoints[i-1].X);
CY := FMovePoints[I-1].Y + ((FCurrentLength - TL)/DL)*(FMovePoints[i].Y - FMovePoints[i-1].Y);
Break;
end;
TL := TL + DL;
end;
// 通过CX, CY 来计算下当前的实际的坐标点...
T := TRttiContext.Create.GetType(FOwnerClass);
P := T.GetProperty('Position');
R := P.GetValue(FOwner);
if R.TryAsType(LPosition) then
begin
LX := (LPosition.Width / LPosition.InitWidth) * CX;
LY := (LPosition.Height / LPosition.InitHeight) * CY;
LPosition.X := LX;
LPosition.Y := LY;
TValue.Make(@LPosition,TypeInfo(T2DPosition),LRPosition);
P.SetValue(FOwner,LRPosition);
end;
// if Owner.ClassName.Equals('TEngine2DSprite') then
// begin
// PSprite := TEngine2DSprite(Owner);
// PSprite.X := (PSprite.Position.Width/ PSprite.Position.InitWidth)*CX;
// PSprite.Y := (PSprite.Position.Height/PSprite.Position.InitHeight)*CY;
// end else
// if Owner.ClassName.Equals('TEngine2DImage') then
// begin
// PImage := TEngine2DImage(Owner);
// PImage.X := (PImage.Position.Width/ PImage.Position.InitWidth)*CX;
// PImage.Y := (PImage.Position.Height/PImage.Position.InitHeight)*CY;
// end;
end;
end.
|
{***************************************************************
*
* Project : TCPStreamClient
* Unit Name: ClientMain
* Purpose : Indy TCP Stream Client Demo - streaming a StringList
* Version : 1.0
* Date : October 6, 2000
* Author : Don Siders <sidersd@att.net>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit ClientMain;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QGrids,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids,
{$ENDIF}
windows, messages, SysUtils, Classes, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, Outline;
{
** NOTES **
Load button connects to the server and sends the OUTLINE command.
Reads data from the server using ReadStream, and stores the data
in the outline component.
A timer is provided to simulate load conditions from a single PC.
}
type
TForm2 = class(TForm)
TCPClient: TIdTCPClient;
Panel1: TPanel;
Button1: TButton;
Outline1: TOutline;
Button2: TButton;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormResize(Sender: TObject);
private
public
end;
var
Form2: TForm2;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TForm2.Button1Click(Sender: TObject);
var
SResponse: string;
AStream: TStringStream;
begin
with TCPClient do
begin
Connect;
while Connected do
begin
AStream := TStringStream.Create('');
try
// banner means the server thread is running
SResponse := UpperCase(ReadLn);
if Pos('HELLO', SResponse) = 0 then
Break;
// request OUTLINE data
WriteLn('OUTLINE');
{ read all bytes until disconnected
no length marker in stream }
ReadStream(AStream, -1, True);
AStream.Seek(0, soFromBeginning);
with Outline1 do
begin
Clear;
Lines.LoadFromStream(AStream);
// Lines.Text := AStream.DataString;
FullExpand;
end;
finally
Disconnect;
AStream.Free;
end;
end;
end;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
Outline1.Clear;
Timer1.Enabled := not Timer1.Enabled;
Button1.Enabled := not TImer1.Enabled;
if Timer1.Enabled then
Button2.Caption := 'Stop Timer'
else
Button2.Caption := 'Start Timer';
end;
procedure TForm2.Timer1Timer(Sender: TObject);
begin
try
Button1.Click;
except // reset the timer and raise the exception
begin
Button2.Click;
raise;
end;
end;
end;
procedure TForm2.FormResize(Sender: TObject);
begin
Button1.Width := (Width - 26) div 2;
Button2.Width := Button1.Width;
Button2.Left := Button1.Left + Button1.Width + 4;
end;
end.
|
program tema6_2017;
uses crt;
const
N = 7;
type Tmat = array[1..7,1..N] of Integer;
Tvec = array[1..7] of Integer;
procedure cargarProduccion(var A: Tmat);
var
i,j: Integer;
begin
for i := 1 to 7 do
begin
for j := 1 to N do
begin
A[i,j]:=1+random(N+10+1-1);
end;
end;
end;
procedure mostrarProduccion(A: Tmat);
var
i,j: Integer;
begin
for i := 1 to 7 do
begin
writeln;
for j := 1 to N do
begin
write(A[i,j]:5);
end;
end;
end;
function posicionMayor(A: Tmat; fila: Integer): Integer;
var
j,mayor,pos: Integer;
begin
mayor:=0;
for j := 1 to N do
begin
if mayor<A[fila,j] then
begin
mayor:=A[fila,j];
pos:=j;
end;
end;
posicionMayor:=pos;
end;
procedure cargaMayores(var Vect: Tvec; M: Tmat);
var
i: Integer;
begin
for i := 1 to 7 do
begin
Vect[i]:=posicionMayor(M,i);
end;
end;
var
A: Tmat;
Vect: Tvec;
i: Integer;
BEGIN{MAIN}
randomize;
cargarProduccion(A);
mostrarProduccion(A);
writeln;writeln;
cargaMayores(Vect,A);
for i := 1 to 7 do
begin
write(Vect[i]:5);
end;
END.
|
unit SMCnst;
interface
{English strings}
const
strMessage = 'Yazdır...';
strSaveChanges = 'Database Server''a bilgileri yazmak istediğinize emin misiniz?';
strErrSaveChanges = 'Veriler kaydedilemedi. Veri taban bağlantısını ve/veya datalar kontrol ediniz.';
strDeleteWarning = '%s tablosunu gerçekten silmek istiyor musunuz?';
strEmptyWarning = '%s tablosunu gerçekten boaltmak istiyor musunuz?';
const
PopUpCaption: array [0..24] of string[33] =
('Kayıt ekle',
'Araya ekle',
'Kaydı düzelt',
'Kaydı sil',
'-',
'Yazdır ...',
'İhraç ...',
'Filtreleme',
'Ara-Bul...',
'-',
'Değişiklikleri kaydet',
'Değişiklikleri iptal et',
'Görüntüyü Yenile',
'-',
'Kaydı seç/seçimi kaldır',
'Kaydı seç',
'Tüm kayıtları seç',
'-',
'Seçimden çıkar',
'Tüm Kayıt seçimini kaldır',
'-',
'Sütun yapısını kaydet',
'Sütun yapısını yükle',
'-',
'Ayarlar...');
const //for TSMSetDBGridDialog
SgbTitle = ' Başlık ';
SgbData = ' Veri ';
STitleCaption ='Manet';
STitleAlignment = 'Yn:';
STitleColor = 'Arkaplan';
STitleFont = 'Yazı karakteri';
SWidth = 'Genişlik';
SWidthFix = 'karakter';
SAlignLeft = 'sol';
SAlignRight = 'sağ';
SAlignCenter = 'merkez';
const //for TSMDBFilterDialog
strEqual = 'eşit';
strNonEqual = 'eşit deil';
strNonMore = 'daha fazla değil';
strNonLess = 'daha az değil';
strLessThan = 'daha küçük';
strLargeThan = 'daha büyük';
strExist = 'boş';
strNonExist = 'boş deil';
strIn = 'liste içinde';
strBetween = 'arasında';
strLike = 'benzer';
strOR = 'VEYA';
strAND = 'VE';
strField = 'Alan';
strCondition = 'Kriter';
strValue = 'Değer';
strAddCondition = ' Ek kriteri tanımlayın:';
strSelection = ' Diğer kritere dayanarak kayıtları seçin: ';
strAddToList = 'Listeye ekle';
strEditInList = 'Liste içinde düzenle';
strDeleteFromList = 'Listeden sil';
strTemplate = 'Şablon diyaloğu süz';
strFLoadFrom = 'Dosyadan Yükle';
strFSaveAs = 'Farklı kaydet...';
strFDescription = 'Tanım';
strFFileName = 'Dosya adı';
strFCreate = '%s Oluşturuldu';
strFModify = '%s Değiştirildi';
strFProtect = 'Yazmaya karşı korumalı';
strFProtectErr = 'Dosya korunuyor!';
const //for SMDBNavigator
SFirstRecord = 'İlk kayıt';
SPriorRecord = 'Önceki kayıt';
SNextRecord = 'Sonraki kayıt';
SLastRecord = 'Son kayıt';
SInsertRecord = 'Kayıt ekle';
SCopyRecord = 'Kaydı kopyala';
SDeleteRecord = 'Kaydı sil';
SEditRecord = 'Kaydı düzenle';
SFilterRecord = 'Kriterlere göre süz';
SFindRecord = 'Kaydı ara';
SPrintRecord = 'Kaydı bas';
SExportRecord = 'Kayıtları İhraç Et';
SPostEdit = 'Değişiklikleri kaydet';
SCancelEdit = 'Değişiklikleri sil';
SRefreshRecord = 'Veri güncelle';
SChoice ='Bir kayıt seç';
SClear = 'Seçili kaydı temizle';
SDeleteRecordQuestion = 'Kayıt silinsin mi?';
SDeleteMultipleRecordsQuestion ='Seçili kaydı silmek istediğinizden emin misiniz?';
SRecordNotFound = 'Kayıt bulunamadı';
SFirstName = 'İlk';
SPriorName = 'Önceki';
SNextName = 'Sonraki';
SLastName = 'Son';
SInsertName = 'Ekle';
SCopyName = 'Kopyala';
SDeleteName = 'Sil';
SEditName = 'Düzenle';
SFilterName = 'Söz';
SFindName = 'Bul';
SPrintName = 'Yazdır';
SExportName = 'Tanım';
SPostName = 'Kaydet';
SCancelName = 'İptal';
SRefreshName = 'Yenile';
SChoiceName ='Seç';
SClearName = 'Temizle';
SImportName= 'Veri Al';
SImportRecord='Kayıt Al';
SBtnOk = '&TAMAM';
SBtnCancel = 'İ&ptal';
SBtnLoad = 'Yükle';
SBtnSave = 'Kaydet';
SBtnCopy = 'Kopyala';
SBtnPaste = 'Yapıştır';
SBtnClear = 'Temizle';
SNoDataToDisplay ='Kayıt yok';
SRecNo = 'Kayıt No.';
SRecOf = ' / ';
SApplyAll = 'Tümüne Uygula';
const //for EditTyped
etValidNumber = 'geçerli sayı';
etValidInteger = 'geçerli tamsayı';
etValidDateTime = 'geçerli tarih/saat';
etValidDate = 'geçerli tarih';
etValidTime = 'geçerli saat';
etValid = 'geçerli';
etIsNot = 'değildir';
etOutOfRange = '%s değeri (%s..%s arasından)';
SPrevYear = 'geçen yıl';
SPrevMonth = 'geçen yıl';
SNextMonth = 'gelecek ay';
SNextYear = 'gelecek yıl';
implementation
end.
|
unit FIToolkit.Reports.Builder.Consts;
interface
uses
System.SysUtils,
FIToolkit.Reports.Parser.Types,
FIToolkit.Localization;
const
{ Common consts }
ARR_MSGTYPE_TO_MSGKEYWORD_MAPPING : array [TFixInsightMessageType] of String =
(String.Empty, 'Warning', 'Optimization', 'CodingConvention', 'Fatal', 'Trial'); // Do not localize!
{ XML consts for an HTML report template format. Do not localize! }
// <HTMLReportTemplate>\<%REPORT_ELEMENT%>\<%REPORT_ELEMENT'S_CHILD_ELEMENT%>\...\<Element>
STR_RPTXML_ROOT_NODE = 'HTMLReportTemplate';
STR_RPTXML_CSS_NODE = 'CSS';
STR_RPTXML_JAVASCRIPT_NODE = 'JavaScript';
STR_RPTXML_HEADER_NODE = 'Header';
STR_RPTXML_TOTAL_SUMMARY_NODE = 'TotalSummary';
STR_RPTXML_TOTAL_SUMMARY_ITEM_NODE = 'TotalSummaryItem';
STR_RPTXML_PROJECT_SECTION_NODE = 'ProjectSection';
STR_RPTXML_PROJECT_SUMMARY_NODE = 'ProjectSummary';
STR_RPTXML_PROJECT_SUMMARY_ITEM_NODE = 'ProjectSummaryItem';
STR_RPTXML_PROJECT_MESSAGES_NODE = 'ProjectMessages';
STR_RPTXML_MESSAGE_NODE = 'Message';
STR_RPTXML_FOOTER_NODE = 'Footer';
STR_RPTXML_ELEMENT_NODE = 'Element';
{ HTML report builder consts. Do not localize! }
// IDs & classes:
STR_HTML_REPORT_ROOT_ID = 'root';
// Macros:
STR_HTML_COLUMN = '%COLUMN%';
STR_HTML_FILE_NAME = '%FILE_NAME%';
STR_HTML_FINISH_TIME = '%FINISH_TIME%';
STR_HTML_LINE = '%LINE%';
STR_HTML_MESSAGE_TEXT = '%MESSAGE_TEXT%';
STR_HTML_MESSAGE_TYPE_KEYWORD = '%MESSAGE_TYPE_KEYWORD%';
STR_HTML_MESSAGE_TYPE_NAME = '%MESSAGE_TYPE_NAME%';
STR_HTML_PROJECT_SUMMARY = '{PROJECT_SUMMARY}';
STR_HTML_PROJECT_SUMMARY_ITEMS = '{PROJECT_SUMMARY_ITEMS}';
STR_HTML_PROJECT_TITLE = '%PROJECT_TITLE%';
STR_HTML_REPORT_TITLE = '%REPORT_TITLE%';
STR_HTML_SNIPPET = '%SNIPPET%';
STR_HTML_START_TIME = '%START_TIME%';
STR_HTML_SUMMARY_MESSAGE_COUNT = '%SUMMARY_MESSAGE_COUNT%';
STR_HTML_SUMMARY_MESSAGE_TYPE_KEYWORD = '%SUMMARY_MESSAGE_TYPE_KEYWORD%';
STR_HTML_SUMMARY_MESSAGE_TYPE_NAME = '%SUMMARY_MESSAGE_TYPE_NAME%';
STR_HTML_TOTAL_SUMMARY_ITEMS = '{TOTAL_SUMMARY_ITEMS}';
// Code snippet output:
FMT_CSO_LINE_NUMBER = '{%s}'; // Do not localize!
STR_CSO_TARGET_LINE_NUMBER_PREFIX = '→ ';
{ Resources. Do not localize! }
STR_RES_HTML_REPORT_DEFAULT_TEMPLATE = 'HTMLReportDefaultTemplate';
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
const
ARR_MSGTYPE_TO_MSGNAME_MAPPING : array [TFixInsightMessageType] of String =
(String.Empty, RSWarning, RSOptimization, RSCodingConvention, RSFatal, RSTrial);
implementation
end.
|
unit vr_JsonRpcClasses;
{$mode delphi}{$H+}
{$I vrode.inc}
interface
{.$DEFINE FORMS_ASYNC_CALL}
uses
Classes, SysUtils, vr_utils, vr_classes, vr_JsonRpc, vr_JsonUtils, vr_promise,
vr_transport, vr_SysUtils, vr_variant
{$IFDEF FORMS_ASYNC_CALL}, Forms{$ENDIF};
type
IPromise = vr_promise.IPromise;
IJsonRpcNotification = vr_JsonRpc.IJsonRpcNotification;
IJsonRpcRequest = vr_JsonRpc.IJsonRpcRequest;
IJsonRpcSuccess = vr_JsonRpc.IJsonRpcSuccess;
IJsonRpcError = vr_JsonRpc.IJsonRpcError;
TServerMethodsList = TStringListHashed;
TOnJsonRpcRequest = function(const ARequest: IJsonRpcRequest; const AThread: TThread;
out AResult: string; var AErrorCode: Integer): Boolean of object;
TOnJsonRpcRequestASync = function(const ARequest: IJsonRpcRequest; out AResult: string;
var AErrorCode: Integer): Boolean of object;
TOnJsonRpcNotification = function(const ANotify: IJsonRpcNotification; const AThread: TThread): Boolean of object;
TOnJsonRpcNotificationASync = procedure(const ANotify: IJsonRpcNotification) of object;
TRequestMethod = procedure(const AParams: IJsonData; out AResult: string;
var AErrorCode: Integer) of object;
TNotificationMethod = procedure(const AParams: IJsonData; const AClient: Pointer) of object;
//use prefix for published methods to autodetect if UsePublishedMethods=True
TPublishedMethodKind = (pmkNone,
{rt_*}pmkRequestThread, //TRequestMethod: current thread
{rq_*}pmkRequestQueue, //TRequestMethod: QueueAsyncCall(InMainThread=False)
{rm_*}pmkRequestMainThread, //TRequestMethod: MainThread TThread.Synchronize()
{ra_*}pmkRequestASync, //TRequestMethod: MainThread QueueAsyncCall(InMainThread=True)
{nt_*}pmkNotificationThread, //TNotificationMethod: current thread
{nq_*}pmkNotificationQueue, //TNotificationMethod QueueAsyncCall(InMainThread=False)
{nm_*}pmkNotificationMainThread,//TNotificationMethod: MainThread TThread.Synchronize()
{na_*}pmkNotificationAsync //TNotificationMethod: MainThread QueueAsyncCall(InMainThread=True)
);
TJsonRpcMethodData = record
Request: IJsonRpcRequest;
Notification: IJsonRpcNotification;
Client: Pointer;
ProcKind: TPublishedMethodKind;
proc: TMethod;
end;
PJsonRpcMethodData = ^TJsonRpcMethodData;
{ TCustomJsonRpc }
{$M+}
TCustomJsonRpc = class(TObject)
private
FOwnTransport: Boolean;
FTransport: TCustomTransport;
FPromiseList: IInterfaceList;
FUsePublishedMethods: Boolean;
FMethods: TServerMethodsList;
FOnRequest: TOnJsonRpcRequest;
FOnRequestASync: TOnJsonRpcRequestASync;
FOnNotification: TOnJsonRpcNotification;
FOnNotificationASync: TOnJsonRpcNotificationASync;
FSyncData: TJsonRpcMethodData;
procedure SetUsePublishedMethods(const AValue: Boolean);
function FindRequestMethod(AName: string; out AMethod: TRequestMethod;
out AKind: TPublishedMethodKind): Boolean;
function FindNotificationMethod(AName: string; out AMethod: TNotificationMethod;
out AKind: TPublishedMethodKind): Boolean;
procedure AppQueueProc(AData: PtrInt);
procedure SyncPublishedMethod;
private
procedure DoReceiveMessage(const AMsg: string;
const AClient: Pointer; const AThread: TThread);
//if not Server then AClient ignore
procedure DoSend(const AMsg: string; const AClient: Pointer); virtual; abstract;
procedure DoSendResponse(const AId: string; AMsg: string; const AErrorCode: Integer;
const AClient: Pointer = nil);
function DoSendRequest(const AMethod, AParams, AId: string;
const AClient: Pointer): IPromise;
//on error: AResult.JsonType=jtNull
function DoSendRequestWait(out AResult: IJsonData;
const AMethod, AParams: string;
const AWaitMsec: Integer; const AClient: Pointer; const AId: string): Boolean;
private
procedure DoPublishedRequest(const AProc: TRequestMethod; const ARequest: IJsonRpcRequest;
const AClient: Pointer);
procedure DoPublishedNotification(const AProc: TNotificationMethod;
const ANotification: IJsonRpcNotification; const AClient: Pointer);
protected
procedure ReleaseTransport;
function DoRequest(const ARequest: IJsonRpcRequest; const AThread: TThread;
const AClient: Pointer): Boolean; virtual;
function DoRequestASync(const ARequest: IJsonRpcRequest; const AClient: Pointer): Boolean; virtual;
function DoNotification(const ANotification: IJsonRpcNotification; const AThread: TThread): Boolean; virtual;
function DoNotificationASync(const ANotification: IJsonRpcNotification): Boolean; virtual;
property Methods: TServerMethodsList read FMethods;
public
constructor Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean; const AUsePublishedMethods: Boolean); virtual;
destructor Destroy; override;
//events called from FTransport thread in DoReceiveMessage()
property OnRequest: TOnJsonRpcRequest read FOnRequest write FOnRequest;
property OnNotification: TOnJsonRpcNotification read FOnNotification write FOnNotification;
//ASync events called im Main Thread by {Application.}QueueAsyncCall
property OnRequestASync: TOnJsonRpcRequestASync read FOnRequestASync write FOnRequestASync;
property OnNotificationASync: TOnJsonRpcNotificationASync read FOnNotificationASync write FOnNotificationASync;
procedure AddPublishedMethods(const AObject: TObject);
property UsePublishedMethods: Boolean read FUsePublishedMethods write SetUsePublishedMethods;
end;
{$M-}
{ TJsonRpcClient }
TJsonRpcClient = class(TCustomJsonRpc)
private
function GetTransport: TCustomTransportClient; inline;
protected
procedure DoSend(const AMsg: string; const {%H-}AClient: Pointer); override;
public
constructor Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean = False;
const AUsePublishedMethods: Boolean = False); override;
procedure SendResponse(const AId: string; AMsg: string; const AErrorCode: Integer);
procedure SendNotification(const AMethod: string; const AParams: string = '');
//on resolve: IPromise.Value=IJsonData; on reject: IPromise.Value.Kind=ivkError
function SendRequest(const AMethod: string; AParams: string = ''): IPromise;
//on error: Result.JsonType=jtNull
function SendRequestWait(const AMethod: string; AParams: string = '';
const AWaitMSec: Integer = 3000): IJsonData; overload;
function SendRequestWait(out AResult: IJsonData;
const AMethod: string; AParams: string = '';
const AWaitMSec: Integer = 3000): Boolean; overload;
property Transport: TCustomTransportClient read GetTransport;
end;
{ TJsonRpcServer }
TJsonRpcServer = class(TCustomJsonRpc)
private
function GetTransport: TCustomTransportServer; inline;
protected
procedure DoSend(const AMsg: string; const AClient: Pointer); override;
public
constructor Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean = False; const AUsePublishedMethods: Boolean = False); override;
procedure SendResponse(const AId: string; AMsg: string; const AErrorCode: Integer;
const AClient: Pointer = nil);
procedure SendNotification(const AMethod: string; const AParams: string = '';
const AClient: Pointer = nil);
//on resolve: IPromise.Value=IJsonData; on reject: IPromise.Value.Kind=ivkError
function SendRequest(const AClient: Pointer; const AMethod: string;
const AParams: string = ''): IPromise;
//on error: Result.JsonType=jtNull
function SendRequestWait(const AClient: Pointer; const AMethod: string;
const AParams: string = ''; const AWaitMsec: Integer = 3000): IJsonData; overload;
function SendRequestWait(out AResult: IJsonData;
const AClient: Pointer; const AMethod: string;
const AParams: string = ''; const AWaitMsec: Integer = 3000): Boolean; overload;
public
property Transport: TCustomTransportServer read GetTransport;
end;
implementation
function _ExtractPromise(const APromiseList: IInterfaceList;
const AId: string; out APromise: IPromise): Boolean;
var
i: Integer;
begin
APromiseList.Lock;
try
for i := 0 to APromiseList.Count - 1 do
begin
APromise := IPromise(APromiseList[i]);
if APromise.Data.Str = AId then
begin
APromiseList.Delete(i);
Exit(True);
end;
end;
Result := False;
finally
APromiseList.Unlock;
end;
end;
{ TCustomJsonRpc }
type
tmethodnamerec = packed record
name : pshortstring;
addr : pointer;
end;
pmethodnamerec = ^tmethodnamerec;
tmethodnametable = packed record
count : dword;
entries : packed array[0..0] of tmethodnamerec;
end;
pmethodnametable = ^tmethodnametable;
TPublishedMethodInfo = record
Self: Pointer;
Addr: Pointer;
Kind: TPublishedMethodKind;
end;
PPublishedMethodInfo = ^TPublishedMethodInfo;
procedure TCustomJsonRpc.AddPublishedMethods(const AObject: TObject);
var
methodtable: pmethodnametable;
i : dword;
ovmt : PVmt;
r: pmethodnamerec;
sName, sPrefix: String;
k: TPublishedMethodKind;
Info: PPublishedMethodInfo;
begin
{$R-}
ovmt := PVmt(AObject.ClassType);
while assigned(ovmt) do
begin
methodtable:=pmethodnametable(ovmt^.vMethodTable);
if assigned(methodtable) then
begin
for i:=0 to methodtable^.count-1 do
begin
r := @methodtable^.entries[i];
sPrefix := Copy(r.name^, 1, 3);
sName := Copy(r.name^, 4, MaxInt);
if (sName = '') or (sPrefix[3] <> '_') then Continue;
k := pmkNone;
case sPrefix[1] of
'r':
case sPrefix[2] of
't': k := pmkRequestThread;
'q': k := pmkRequestQueue;
'm': k := pmkRequestMainThread;
'a': k := pmkRequestASync;
end;
'n':
case sPrefix[2] of
't': k := pmkNotificationThread;
'q': k := pmkNotificationQueue;
'm': k := pmkNotificationMainThread;
'a': k := pmkNotificationASync;
end;
end;//case sPrefix[1]
if k <> pmkNone then
begin
New(Info);
Info.Self := AObject;
Info.Addr := r.addr;
Info.Kind := k;
FMethods.AddObject(sName, TObject(Info));
end;
end;
end;
ovmt := ovmt^.vParent;
end;
{$IFDEF DEBUG_MODE}{$R+}{$ENDIF}
end;
procedure TCustomJsonRpc.SetUsePublishedMethods(const AValue: Boolean);
procedure _ClearMethods;
var
i: Integer;
begin
for i := 0 to FMethods.Count - 1 do
Dispose(PPublishedMethodInfo(FMethods.Objects[i]));
FMethods.Clear;
end;
begin
if FUsePublishedMethods = AValue then Exit;
FUsePublishedMethods := AValue;
_ClearMethods;
if AValue then
AddPublishedMethods(Self);
end;
function TCustomJsonRpc.FindRequestMethod(AName: string; out
AMethod: TRequestMethod; out AKind: TPublishedMethodKind): Boolean;
var
i: Integer;
Info: PPublishedMethodInfo;
begin
Result := False;
AMethod := nil;
if not UsePublishedMethods then Exit;
i := FMethods.IndexOf(AName);
Result := i <> -1;
if Result then
begin
Info := PPublishedMethodInfo(FMethods.Objects[i]);
AKind := Info.Kind;
Result := AKind in [pmkRequestThread, pmkRequestQueue, pmkRequestMainThread, pmkRequestASync];
if Result then
AMethod := TRequestMethod(Method(Info.Addr, Info.Self));
end;
end;
function TCustomJsonRpc.FindNotificationMethod(AName: string; out
AMethod: TNotificationMethod; out AKind: TPublishedMethodKind): Boolean;
var
i: Integer;
Info: PPublishedMethodInfo;
begin
Result := False;
AMethod := nil;
if not UsePublishedMethods then Exit;
i := FMethods.IndexOf(AName);
Result := i <> -1;
if Result then
begin
Info := PPublishedMethodInfo(FMethods.Objects[i]);
AKind := Info.Kind;
Result := AKind in [pmkNotificationThread, pmkNotificationQueue,
pmkNotificationMainThread, pmkNotificationASync];
if Result then
AMethod := TNotificationMethod(Method(Info.Addr, Info.Self));
end;
end;
procedure TCustomJsonRpc.AppQueueProc(AData: PtrInt);
var
AsyncData: PJsonRpcMethodData absolute AData;
Data: TJsonRpcMethodData;
begin
Data := AsyncData^;
Dispose(AsyncData);
case Data.ProcKind of
pmkRequestASync, pmkRequestQueue:
DoPublishedRequest(TRequestMethod(Data.proc), Data.Request, Data.Client);
pmkNotificationAsync, pmkNotificationQueue:
DoPublishedNotification(TNotificationMethod(Data.proc), Data.Notification, Data.Client);
pmkNone:
if Assigned(Data.Request) then
DoRequestASync(Data.Request, Data.Client)
else if Assigned(Data.Notification) then
DoNotificationASync(Data.Notification);
end
end;
procedure TCustomJsonRpc.SyncPublishedMethod;
begin
case FSyncData.ProcKind of
pmkRequestMainThread:
DoPublishedRequest(TRequestMethod(FSyncData.proc), FSyncData.Request, FSyncData.Client);
pmkNotificationMainThread:
DoPublishedNotification(TNotificationMethod(FSyncData.proc),
FSyncData.Notification, FSyncData.Client);
end;
end;
procedure TCustomJsonRpc.DoReceiveMessage(const AMsg: string;
const AClient: Pointer; const AThread: TThread);
var
FRequest: IJsonRpcRequest;
FNotification: IJsonRpcNotification;
FSuccess: IJsonRpcSuccess;
FError: IJsonRpcError;
procedure _DoAsync(const AProc: TMethod; const AProcKind: TPublishedMethodKind;
AInMainThread: Boolean);
var
Data: PJsonRpcMethodData;
begin
New(Data);
Data.Request := FRequest;
Data.Notification := FNotification;
Data.Client := AClient;
Data.ProcKind := AProcKind;
Data.proc := AProc;
{$IFDEF FORMS_ASYNC_CALL}
if AInMainThread then
Application.QueueAsyncCall(AppQueueProc, {%H-}PtrInt(Data));{$ELSE}
QueueAsyncCall(AppQueueProc, {%H-}PtrInt(Data), AInMainThread);{$ENDIF}
end;
procedure _DoInMainThread(const AProc: TMethod; const AProcKind: TPublishedMethodKind);
begin
FSyncData.Request := FRequest;
FSyncData.Notification := FNotification;
FSyncData.Client := AClient;
FSyncData.ProcKind := AProcKind;
FSyncData.proc := TMethod(AProc);
TThread.Synchronize(AThread, SyncPublishedMethod)
end;
procedure _DoRequest;
var
proc: TRequestMethod;
ProcKind: TPublishedMethodKind;
begin
if not FindRequestMethod(FRequest.Method, proc, ProcKind) then
begin
if not DoRequest(FRequest, AThread, AClient) then
if Assigned(OnRequestASync) then
_DoAsync(Method(nil, nil), pmkNone, True)
else
DoSendResponse(FRequest.ID, '"' + PRC_ERR_METHOD_NOT_FOUND + '"', CODE_METHOD_NOT_FOUND, AClient);
end
else
case ProcKind of
pmkRequestThread:
DoPublishedRequest(proc, FRequest, AClient);
pmkRequestQueue:
_DoAsync(TMethod(proc), ProcKind, False);
pmkRequestMainThread:
_DoInMainThread(TMethod(proc), ProcKind);
pmkRequestASync:
_DoAsync(TMethod(proc), ProcKind, True);
end;
end;
procedure _DoNotification;
var
proc: TNotificationMethod;
ProcKind: TPublishedMethodKind;
begin
if not FindNotificationMethod(FNotification.Method, proc, ProcKind) then
begin
if not DoNotification(FNotification, AThread) then
if Assigned(OnNotificationASync) then
_DoAsync(Method(nil, nil), pmkNone, True);
end
else
case ProcKind of
pmkNotificationThread:
proc(FNotification.Params, AClient);
pmkNotificationQueue:
_DoAsync(TMethod(proc), ProcKind, False);
pmkNotificationMainThread:
_DoInMainThread(TMethod(proc), ProcKind);
pmkNotificationASync:
_DoAsync(TMethod(proc), ProcKind, True);
end;
end;
procedure _DoSuccesOrError(const AState: TPromiseState; const AId: string);
var
p, p1: IPromise;
v: IVariant;
begin
if _ExtractPromise(FPromiseList, AId, p) then
begin
if AState = psFulfilled then
v := FSuccess.Result
else
v := ivar_Err(FError.Message, FError.Code);
p1 := TPromise.DoChain(p, AState, v);
if not p1.Settled then
begin
p1.Data := p.Data;
FPromiseList.Add(p1); //ToDo ? not add
end;
end;
end;
var
msg: IJsonRpcMessage;
begin
case rpc_Parse(AMsg, msg) of
jrmtRequest:
if msg.QueryInterface(IJsonRpcRequest, FRequest) = S_OK then
begin
_DoRequest;
{$IFDEF DEBUG_MODE}
WriteToDebugConsole(Format(' <<< {"id": "%s", "%s": %s}',
[FRequest.ID, FRequest.Method, FRequest.Params.AsJsonString]));{$ENDIF}
end;
jrmtNotification:
if msg.QueryInterface(IJsonRpcNotification, FNotification) = S_OK then
begin
_DoNotification;
{$IFDEF DEBUG_MODE}
WriteToDebugConsole(Format(' <<< {"%s": %s}',
[FNotification.Method, FNotification.Params.AsJsonString]));{$ENDIF}
end;
jrmtSuccess:
if msg.QueryInterface(IJsonRpcSuccess, FSuccess) = S_OK then
begin
_DoSuccesOrError(psFulfilled, FSuccess.ID);
{$IFDEF DEBUG_MODE}
WriteToDebugConsole(Format(' <<< {"id": "%s", "result": %s}',
[FSuccess.ID, FSuccess.Result.AsJsonString]));{$ENDIF}
end;
jrmtError, jrmtInvalid:
if msg.QueryInterface(IJsonRpcError, FError) = S_OK then
begin
_DoSuccesOrError(psRejected, FError.ID);
{$IFDEF DEBUG_MODE}
WriteToDebugConsole(Format(' <<< {"id": "%s", "code": %d, "message": "%s", "data": %s}',
[FError.ID, FError.Code, FError.Message, FError.Data.AsJsonString]));{$ENDIF}
end;
end;
end;
function TCustomJsonRpc.DoSendRequest(const AMethod, AParams, AId: string;
const AClient: Pointer): IPromise;
begin
Result := TPromise.New(AId);
FPromiseList.Add(Result);
DoSend(rpc_Request(AId, AMethod, AParams), AClient);
end;
function TCustomJsonRpc.DoSendRequestWait(out AResult: IJsonData;
const AMethod, AParams: string; const AWaitMsec: Integer;
const AClient: Pointer; const AId: string): Boolean;
var
pr: IPromise;
begin
pr := TPromise.New(AId);
FPromiseList.Add(pr);
DoSend(rpc_Request(AId, AMethod, AParams), AClient);
pr.Wait(AWaitMsec);
case pr.State of
psFulfilled:
begin
Result := True;
AResult := IJsonData(pr.Value.Intf);
end
//psRejected:
// Result := json_CreateString(pr.Value.Str)
else
begin
Result := False;
AResult := json_CreateNull;
end;
end;
end;
procedure TCustomJsonRpc.DoPublishedRequest(const AProc: TRequestMethod;
const ARequest: IJsonRpcRequest; const AClient: Pointer);
var
sResult: string;
ErrCode: Integer = 0;
begin
try
AProc(ARequest.Params, sResult, ErrCode);
except
on E: Exception do
begin
ErrCode := CODE_INTERNAL_ERROR;
sResult := E.Message;
end;
end;
DoSendResponse(ARequest.ID, sResult, ErrCode, AClient);
end;
procedure TCustomJsonRpc.DoPublishedNotification(const AProc: TNotificationMethod;
const ANotification: IJsonRpcNotification; const AClient: Pointer);
begin
try
AProc(ANotification.Params, AClient);
except end;
end;
procedure TCustomJsonRpc.ReleaseTransport;
begin
if FOwnTransport then
FTransport.Free;
FTransport := nil;
end;
function TCustomJsonRpc.DoRequest(const ARequest: IJsonRpcRequest;
const AThread: TThread; const AClient: Pointer): Boolean;
var
sResult: string;
ErrCode: Integer = 0;
begin
Result := Assigned(FOnRequest) and FOnRequest(ARequest, AThread, sResult, ErrCode);
if Result then
DoSendResponse(ARequest.ID, sResult, ErrCode, AClient);
end;
function TCustomJsonRpc.DoRequestASync(const ARequest: IJsonRpcRequest;
const AClient: Pointer): Boolean;
var
sResult: string;
ErrCode: Integer = 0;
begin
Result := Assigned(FOnRequestASync) and FOnRequestASync(ARequest, sResult, ErrCode);
if Result then
DoSendResponse(ARequest.ID, sResult, ErrCode, AClient)
else
DoSendResponse(ARequest.ID, sResult,
IfThen(ErrCode = 0, CODE_INTERNAL_ERROR, ErrCode), AClient);
end;
function TCustomJsonRpc.DoNotification(
const ANotification: IJsonRpcNotification; const AThread: TThread): Boolean;
begin
Result := Assigned(OnNotification) and OnNotification(ANotification, AThread);
end;
function TCustomJsonRpc.DoNotificationASync(
const ANotification: IJsonRpcNotification): Boolean;
begin
Result := Assigned(OnNotificationASync);
if Result then
OnNotificationASync(ANotification);
end;
constructor TCustomJsonRpc.Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean; const AUsePublishedMethods: Boolean);
begin
{$IFDEF DEBUG_MODE}
if ATransport = nil then
raise Exception.Create('TCustomJsonRpc.Create(): ATransport = nil');{$ENDIF}
FOwnTransport := AOwnTransport;
FTransport := ATransport;
FTransport.OnReceive := DoReceiveMessage;
FPromiseList := TInterfaceList.Create;
FMethods := TServerMethodsList.Create;
UsePublishedMethods := AUsePublishedMethods;
end;
destructor TCustomJsonRpc.Destroy;
begin
FTransport.OnReceive := nil;
{$IFDEF FORMS_ASYNC_CALL}
Application.RemoveAsyncCalls(Self);{$ELSE}
RemoveAsyncCalls(Self);{$ENDIF}
ReleaseTransport;
UsePublishedMethods := False;//to clear FMethods.Objects;
FreeAndNil(FMethods);
inherited Destroy;
end;
procedure TCustomJsonRpc.DoSendResponse(const AId: string; AMsg: string;
const AErrorCode: Integer; const AClient: Pointer);
var
S: String;
begin
if AErrorCode = 0 then
S := rpc_Success(AId, AMsg)
else
begin
if AMsg = '' then
begin
case AErrorCode of
CODE_INVALID_REQUEST: AMsg := PRC_ERR_INVALID_REQUEST;
CODE_METHOD_NOT_FOUND: AMsg := PRC_ERR_METHOD_NOT_FOUND;
CODE_INVALID_PARAMS: AMsg := RPC_ERR_INVALID_PARAMS;
CODE_INTERNAL_ERROR: AMsg := RPC_ERR_INTERNAL_ERROR;
CODE_PARSE_ERROR: AMsg := RPC_ERR_PARSE_ERROR;
end;
AMsg := '"' + AMsg + '"';
end;
S := rpc_Error(AId, AErrorCode, AMsg);
end;
DoSend(S, AClient);
end;
{ TJsonRpcServer }
function TJsonRpcServer.GetTransport: TCustomTransportServer;
begin
Result := TCustomTransportServer(FTransport);
end;
procedure TJsonRpcServer.DoSend(const AMsg: string; const AClient: Pointer);
begin
FTransport.Send(AMsg, AClient);
end;
procedure TJsonRpcServer.SendNotification(const AMethod: string;
const AParams: string; const AClient: Pointer);
begin
FTransport.Send(rpc_Notification(AMethod, AParams), AClient);
end;
function TJsonRpcServer.SendRequest(const AClient: Pointer;
const AMethod: string; const AParams: string): IPromise;
begin
if AClient = nil then
Exit(TPromise.Resolve(0));
Result := DoSendRequest(AMethod, AParams, FTransport.NextId, AClient);
end;
function TJsonRpcServer.SendRequestWait(const AClient: Pointer;
const AMethod: string; const AParams: string; const AWaitMsec: Integer): IJsonData;
begin
if AClient = nil then
Exit(json_CreateNull);
DoSendRequestWait(Result, AMethod, AParams, AWaitMsec, AClient, FTransport.NextId);
end;
function TJsonRpcServer.SendRequestWait(out AResult: IJsonData;
const AClient: Pointer; const AMethod: string; const AParams: string;
const AWaitMsec: Integer): Boolean;
begin
if AClient = nil then
Exit(False);
Result := DoSendRequestWait(AResult, AMethod, AParams, AWaitMsec, AClient, FTransport.NextId);
end;
constructor TJsonRpcServer.Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean; const AUsePublishedMethods: Boolean);
begin
{$IFDEF DEBUG_MODE}
if not (ATransport is TCustomTransportServer) then
raise Exception.Create('TJsonRpcServer.Create(): ATransport is not TCustomTransportServer');
{$ENDIF}
inherited Create(ATransport, AOwnTransport, AUsePublishedMethods);
end;
procedure TJsonRpcServer.SendResponse(const AId: string; AMsg: string;
const AErrorCode: Integer; const AClient: Pointer);
begin
DoSendResponse(AId, AMsg, AErrorCode, AClient);
end;
{ TJsonRpcClient }
function TJsonRpcClient.GetTransport: TCustomTransportClient;
begin
Result := TCustomTransportClient(FTransport);
end;
procedure TJsonRpcClient.DoSend(const AMsg: string; const AClient: Pointer);
begin
FTransport.Send(AMsg);
end;
constructor TJsonRpcClient.Create(const ATransport: TCustomTransport;
const AOwnTransport: Boolean; const AUsePublishedMethods: Boolean);
begin
{$IFDEF DEBUG_MODE}
if not (ATransport is TCustomTransportClient) then
raise Exception.Create('TJsonRpcClient.Create(): ATransport is not TCustomTransportClient');
{$ENDIF}
inherited Create(ATransport, AOwnTransport, AUsePublishedMethods);
end;
procedure TJsonRpcClient.SendResponse(const AId: string; AMsg: string;
const AErrorCode: Integer);
begin
DoSendResponse(AId, AMsg, AErrorCode, nil);
end;
procedure TJsonRpcClient.SendNotification(const AMethod: string;
const AParams: string);
begin
FTransport.Send(rpc_Notification(AMethod, AParams));
end;
function TJsonRpcClient.SendRequest(const AMethod: string; AParams: string): IPromise;
begin
Result := DoSendRequest(AMethod, AParams, FTransport.NextId, nil);
end;
function TJsonRpcClient.SendRequestWait(const AMethod: string; AParams: string;
const AWaitMSec: Integer): IJsonData;
begin
DoSendRequestWait(Result, AMethod, AParams, AWaitMSec, nil, FTransport.NextId);
end;
function TJsonRpcClient.SendRequestWait(out AResult: IJsonData;
const AMethod: string; AParams: string; const AWaitMSec: Integer): Boolean;
begin
Result := DoSendRequestWait(AResult, AMethod, AParams, AWaitMSec, nil, FTransport.NextId);
end;
end.
|
unit Error;
interface
uses
ScktComp;
type
TError = class
type ErrorCode = (
UnknownError,
UnknownCommand,
InvalidCommandFormat,
IncorrectNickName,
NickNameIsInUse,
IncorrectRoomName,
AlreadyInChannel
);
// Эмиттировать ошибку у клиента
class procedure EmitError(Error: ErrorCode; Socket: TCustomWinSocket;
AdditionalInfo: string = '');
end;
implementation
{ TError }
class procedure TError.EmitError(Error: TError.ErrorCode; Socket: TCustomWinSocket;
AdditionalInfo: string = '');
var
ErrorString: string;
ForFree: boolean;
begin
ForFree := False;
case Error of
UnknownError: ErrorString := 'Неизвестная ошибка';
UnknownCommand: ErrorString := 'Неизвестная команда: ' + AdditionalInfo;
InvalidCommandFormat: ErrorString := 'Неправильный формат команды: ' + AdditionalInfo;
IncorrectNickName:
begin
ErrorString := 'Неправильный ник: ' + AdditionalInfo;
ForFree := True;
end;
NickNameIsInUse:
begin
ErrorString := 'Такой ник уже используется: ' + AdditionalInfo;
ForFree := True;
end;
IncorrectRoomName: ErrorString := 'Неправильное имя комнаты: ' + AdditionalInfo;
AlreadyInChannel: ErrorString := 'Уже в комнате: ' + AdditionalInfo;
end;
Socket.SendText('$e ' + ErrorString);
if ForFree then
Socket.Free;
end;
end.
|
unit RValueComparison;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, wwdblook,
TabNotBk, Types, RPFiler, RPDefine, RPBase, RPCanvas, RPrinter, Progress,
RPTXFilr, ComCtrls, Math;
type
TValueComparisonTypes = (vcAssessedValue, vcCountyTaxableValue,
vcMunicipalTaxableValue, vcSchoolTaxableValue);
TValueComparisonType = set of TValueComparisonTypes;
Tfm_ValueComparisonReport = class(TForm)
Panel1: TPanel;
TitleLabel: TLabel;
PrintDialog: TPrintDialog;
ReportPrinter: TReportPrinter;
ReportFiler: TReportFiler;
Label11: TLabel;
Label12: TLabel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
PageControl1: TPageControl;
OptionsTabSheet: TTabSheet;
Swis_School_RS_TabSheet: TTabSheet;
Label15: TLabel;
Label9: TLabel;
Label18: TLabel;
lbx_RollSection: TListBox;
lbx_SwisCode: TListBox;
lbx_SchoolCode: TListBox;
GroupBox1: TGroupBox;
cb_CreateParcelList: TCheckBox;
cb_ExtractToExcel: TCheckBox;
tb_ParcelYear1: TTable;
tb_ParcelYear2: TTable;
ReportFiler1: TReportFiler;
tb_SwisCode: TTable;
tb_SchoolCode: TTable;
cb_LoadFromParcelList: TCheckBox;
Panel3: TPanel;
btn_Print: TBitBtn;
btn_Close: TBitBtn;
gbx_ValuesToCompare: TGroupBox;
cb_AssessedValue: TCheckBox;
cb_CountyTaxableValue: TCheckBox;
cb_MunicipalTaxableValue: TCheckBox;
cb_SchoolTaxableValue: TCheckBox;
cb_VillageTaxableValue: TCheckBox;
GroupBox2: TGroupBox;
Label1: TLabel;
cbx_DatabaseYear1: TComboBox;
Label2: TLabel;
cbx_AssessmentYear1: TComboBox;
GroupBox3: TGroupBox;
Label3: TLabel;
Label4: TLabel;
cbx_DatabaseYear2: TComboBox;
cbx_AssessmentYear2: TComboBox;
tb_Sort: TTable;
tb_AssessmentYear1: TTable;
tb_AssessmentYear2: TTable;
tb_ExemptionYear1: TTable;
tb_ExemptionYear2: TTable;
tb_ExemptionCodeYear1: TTable;
tb_ExemptionCodeYear2: TTable;
cb_PrintDetails: TCheckBox;
ed_AssessmentYearLabel1: TEdit;
Label5: TLabel;
Label6: TLabel;
ed_AssessmentYearLabel2: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btn_PrintClick(Sender: TObject);
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure cbx_DatabaseYearChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
ReportCancelled, CreateParcelList,
LoadFromParcelList, ExtractToExcel : Boolean;
OrigSortFileName,
AssessmentYear1, AssessmentYear2,
AssessmentYearLabel1, AssessmentYearLabel2,
DatabaseNameYear1, DatabaseNameYear2 : String;
SelectedSchoolCodes, SelectedSwisCodes, SelectedRollSections : TStringList;
ExtractFile : TextFile;
ValueComparisonSections : TValueComparisonType;
Procedure InitializeForm; {Open the tables and setup.}
Procedure FillListBoxes;
Procedure SortFiles;
Function RecordMeetsCriteria(tb_Parcel : TTable;
AssessmentYear : String) : Boolean;
Procedure InsertOneSortRecord(tb_Sort : TTable;
SwisSBLKey : String;
tb_Parcel : TTable;
tb_Assessment : TTable;
tb_Exemption : TTable;
tb_ExemptionCode : TTable;
AssessmentYear : String;
FirstYear : Boolean);
Procedure LoadSortFileOneYear(tb_Sort : TTable;
tb_Parcel : TTable;
tb_Assessment : TTable;
tb_Exemption : TTable;
tb_ExemptionCode : TTable;
DatabaseName : String;
AssessmentYear : String;
FirstYear : Boolean);
Procedure PrintOneDifference( Sender : TObject;
tb_Sort : TTable;
AssessmentYearLabel1 : String;
AssessmentYearLabel2 : String;
var AssessedValueDifference : LongInt;
var CountyTaxableDifference : LongInt;
var MunicipalTaxableDifference : LongInt;
var SchoolTaxableDifference : LongInt);
end;
implementation
uses GlblVars, WinUtils, Utilitys, UTILEXSD, GlblCnst, PASUtils,
PRCLLIST, {Parcel list}
Prog, RptDialg,
Preview, PASTypes, DataAccessUnit;
{$R *.DFM}
{========================================================}
Procedure Tfm_ValueComparisonReport.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure Tfm_ValueComparisonReport.FillListBoxes;
var
AssessmentYear : String;
Quit : Boolean;
DatabaseNamesList : TStringList;
I : Integer;
begin
DatabaseNamesList := TStringList.Create;
AssessmentYear := GetTaxRlYr;
OpenTableForProcessingType(tb_SchoolCode, SchoolCodeTableName,
GlblProcessingType, Quit);
OpenTableForProcessingType(tb_SwisCode, SwisCodeTableName,
GlblProcessingType, Quit);
FillOneListBox(lbx_SwisCode, tb_SwisCode, 'SwisCode',
'MunicipalityName', 25, True, True, GlblProcessingType, AssessmentYear);
FillOneListBox(lbx_SchoolCode, tb_SchoolCode, 'SchoolCode',
'SchoolName', 25, True, True, GlblProcessingType, AssessmentYear);
SelectItemsInListBox(lbx_RollSection);
Session.GetDatabaseNames(DatabaseNamesList);
For I := (DatabaseNamesList.Count - 1) downto 0 do
If not (_Compare(DatabaseNamesList[I], 'PROPERTY', coStartsWith) or
_Compare(DatabaseNamesList[I], 'PAS', coStartsWith))
then DatabaseNamesList.Delete(I);
cbx_DatabaseYear1.Items.Assign(DatabaseNamesList);
cbx_DatabaseYear2.Items.Assign(DatabaseNamesList);
DatabaseNamesList.Free;
end; {FillListBoxes}
{========================================================}
Procedure Tfm_ValueComparisonReport.InitializeForm;
begin
UnitName := 'RValueComparison';
SelectedRollSections := TStringList.Create;
SelectedSwisCodes := TStringList.Create;
SelectedSchoolCodes := TStringList.Create;
FillListBoxes;
end; {InitializeForm}
{===================================================================}
Procedure Tfm_ValueComparisonReport.cbx_DatabaseYearChange(Sender: TObject);
var
DatabaseName : String;
AssessmentYears : TStringList;
begin
AssessmentYears := TStringList.Create;
with Sender as TComboBox do
begin
DatabaseName := Text;
GetAllAssessmentYears(AssessmentYears, DatabaseName);
If _Compare(Name, '1', coContains)
then cbx_AssessmentYear1.Items.Assign(AssessmentYears)
else cbx_AssessmentYear2.Items.Assign(AssessmentYears);
end; {with Sender as TComboBox do}
AssessmentYears.Free;
end; {cbx_DatabaseYearChange}
{===================================================================}
Procedure Tfm_ValueComparisonReport.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{==============================================================}
Function Tfm_ValueComparisonReport.RecordMeetsCriteria(tb_Parcel : TTable;
AssessmentYear : String) : Boolean;
begin
Result := ((SelectedRollSections.IndexOf(tb_Parcel.FieldByName('RollSection').Text) > -1) and
(SelectedSchoolCodes.IndexOf(tb_Parcel.FieldByName('SchoolCode').Text) > -1) and
(SelectedSwisCodes.IndexOf(tb_Parcel.FieldByName('SwisCode').Text) > -1) and
(tb_Parcel.FieldByName('TaxRollYr').Text = AssessmentYear));
end; {RecordMeetsCriteria}
{==============================================================}
Procedure Tfm_ValueComparisonReport.InsertOneSortRecord(tb_Sort : TTable;
SwisSBLKey : String;
tb_Parcel : TTable;
tb_Assessment : TTable;
tb_Exemption : TTable;
tb_ExemptionCode : TTable;
AssessmentYear : String;
FirstYear : Boolean);
var
RollSection, ActiveStatus,
SchoolCode, HomesteadCode, YearNumber : String;
LandAssessedValue, TotalAssessedValue,
CountyTaxableValue, MunicipalTaxableValue,
SchoolTaxableValue, VillageTaxableValue,
BasicSTARAmount, EnhancedSTARAmount : LongInt;
begin
_Locate(tb_Assessment, [AssessmentYear, SwisSBLKey], '', []);
with tb_Sort do
try
If FirstYear
then
begin
YearNumber := 'Year1';
Insert;
FieldByName('ParcelExistsYear1').AsBoolean := True;
end
else
begin
YearNumber := 'Year2';
If _Locate(tb_Sort, [SwisSBLKey], '', [])
then Edit
else Insert;
FieldByName('ParcelExistsYear2').AsBoolean := True;
end; {else of If FirstYear}
FieldByName('SwisSBLKey').AsString := SwisSBLKey;
RollSection := tb_Parcel.FieldByName('RollSection').AsString;
ActiveStatus := tb_Parcel.FieldByName('ActiveFlag').AsString;
SchoolCode := tb_Parcel.FieldByName('SchoolCode').AsString;
HomesteadCode := tb_Parcel.FieldByName('HomesteadCode').AsString;
DetermineAssessedAndTaxableValues(AssessmentYear, SwisSBLKey,
HomesteadCode, tb_Exemption,
tb_ExemptionCode, tb_Assessment,
LandAssessedValue, TotalAssessedValue,
CountyTaxableValue, MunicipalTaxableValue,
SchoolTaxableValue, VillageTaxableValue,
BasicSTARAmount, EnhancedSTARAmount);
If _Compare(ActiveStatus, InactiveParcelFlag, coEqual)
then
begin
LandAssessedValue:= 0;
TotalAssessedValue:= 0;
CountyTaxableValue:= 0;
MunicipalTaxableValue:= 0;
SchoolTaxableValue:= 0;
VillageTaxableValue:= 0;
BasicSTARAmount:= 0;
EnhancedSTARAmount := 0;
end; {If _Compare(ActiveStatus, InactiveParcelFlag)}
FieldByName('Status' + YearNumber).AsString := ActiveStatus;
FieldByName('RollSection' + YearNumber).AsString := RollSection;
FieldByName('SchoolCode' + YearNumber).AsString := SchoolCode;
FieldByName('HomesteadCode' + YearNumber).AsString := HomesteadCode;
FieldByName('AssessedValue' + YearNumber).AsInteger := TotalAssessedValue;
FieldByName('CountyTaxable' + YearNumber).AsInteger := CountyTaxableValue;
FieldByName('MunicipalTaxable' + YearNumber).AsInteger := MunicipalTaxableValue;
FieldByName('SchoolTaxable' + YearNumber).AsInteger := SchoolTaxableValue;
FieldByName('VillageTaxable' + YearNumber).AsInteger := VillageTaxableValue;
Post;
except
end;
end; {InsertOneSortRecord}
{==============================================================}
Procedure Tfm_ValueComparisonReport.LoadSortFileOneYear(tb_Sort : TTable;
tb_Parcel : TTable;
tb_Assessment : TTable;
tb_Exemption : TTable;
tb_ExemptionCode : TTable;
DatabaseName : String;
AssessmentYear : String;
FirstYear : Boolean);
var
Index : Integer;
SwisSBLKey : String;
Done : Boolean;
begin
Index := 0;
Done := False;
ProgressDialog.UserLabelCaption := 'Scanning ' + AssessmentYear + ' in ' + DatabaseName + '.';
If LoadFromParcelList
then
begin
Index := 1;
ParcelListDialog.GetParcelWithAssessmentYear(tb_Parcel, Index, AssessmentYear);
SwisSBLKey := ParcelListDialog.GetParcelSwisSBLKey(Index);
end
else
begin
tb_Parcel.First;
SwisSBLKey := ExtractSSKey(tb_Parcel);
end;
with tb_Parcel do
while (not (Done or ReportCancelled)) do
begin
ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey));
Application.ProcessMessages;
If RecordMeetsCriteria(tb_Parcel, AssessmentYear)
then InsertOneSortRecord(tb_Sort, SwisSBLKey,
tb_Parcel, tb_Assessment,
tb_Exemption, tb_ExemptionCode,
AssessmentYear, FirstYear);
If LoadFromParcelList
then
begin
Inc(Index);
SwisSBLKey := ParcelListDialog.GetParcelSwisSBLKey(Index);
ParcelListDialog.GetParcelWithAssessmentYear(tb_Parcel, Index, AssessmentYear);
end
else
begin
Next;
SwisSBLKey := ExtractSSKey(tb_Parcel);
end;
ReportCancelled := ProgressDialog.Cancelled;
Done := EOF or
(LoadFromParcelList and
_Compare(Index, ParcelListDialog.NumItems, coGreaterThan));
end; {while (not (EOF or ReportCancelled)) do}
end; {LoadSortFileOneYear}
{==============================================================}
Procedure Tfm_ValueComparisonReport.SortFiles;
begin
ProgressDialog.Start((tb_ParcelYear1.RecordCount + tb_ParcelYear2.RecordCount), True, True);
LoadSortFileOneYear(tb_Sort, tb_ParcelYear1, tb_AssessmentYear1,
tb_ExemptionYear1, tb_ExemptionCodeYear1,
DatabaseNameYear1, AssessmentYear1, True);
LoadSortFileOneYear(tb_Sort, tb_ParcelYear2, tb_AssessmentYear2,
tb_ExemptionYear2, tb_ExemptionCodeYear2,
DatabaseNameYear2, AssessmentYear2, False);
ProgressDialog.Finish;
end; {SortFiles}
{==============================================================}
Procedure OpenTablesForYear(tb_Parcel : TTable;
tb_Assessment : TTable;
tb_Exemption : TTable;
tb_ExemptionCode : TTable;
DatabaseName : String;
ProcessingType : Integer);
begin
_OpenTable(tb_Parcel, ParcelTableName, DatabaseName,
'', ProcessingType, []);
_OpenTable(tb_Assessment, AssessmentTableName, DatabaseName,
'', ProcessingType, []);
_OpenTable(tb_Exemption, ExemptionsTableName, DatabaseName,
'', ProcessingType, []);
_OpenTable(tb_ExemptionCode, ExemptionCodesTableName, DatabaseName,
'', ProcessingType, []);
end; {OpenTablesForYear}
{==============================================================}
Procedure Tfm_ValueComparisonReport.btn_PrintClick(Sender: TObject);
var
ProcessingTypeYear1, ProcessingTypeYear2 : Integer;
SortFileName, NewFileName, SpreadsheetFileName : String;
Quit : Boolean;
begin
OrigSortFileName := tb_Sort.TableName;
SetPrintToScreenDefault(PrintDialog);
ReportCancelled := False;
ExtractToExcel := cb_ExtractToExcel.Checked;
LoadFromParcelList := cb_LoadFromParcelList.Checked;
AssessmentYear1 := cbx_AssessmentYear1.Text;
AssessmentYear2 := cbx_AssessmentYear2.Text;
AssessmentYearLabel1 := ed_AssessmentYearLabel1.Text;
AssessmentYearLabel2 := ed_AssessmentYearLabel2.Text;
DatabaseNameYear1 := cbx_DatabaseYear1.Text;
DatabaseNameYear2 := cbx_DatabaseYear2.Text;
If _Compare(AssessmentYearLabel1, coBlank)
then AssessmentYearLabel1 := AssessmentYear1;
If _Compare(AssessmentYearLabel2, coBlank)
then AssessmentYearLabel2 := AssessmentYear2;
ValueComparisonSections := [];
If cb_AssessedValue.Checked
then ValueComparisonSections := ValueComparisonSections + [vcAssessedValue];
If cb_CountyTaxableValue.Checked
then ValueComparisonSections := ValueComparisonSections + [vcCountyTaxableValue];
If cb_MunicipalTaxableValue.Checked
then ValueComparisonSections := ValueComparisonSections + [vcMunicipalTaxableValue];
If cb_SchoolTaxableValue.Checked
then ValueComparisonSections := ValueComparisonSections + [vcSchoolTaxableValue];
case cbx_AssessmentYear1.Items.IndexOf(AssessmentYear1) of
0 : ProcessingTypeYear1 := NextYear;
1 : ProcessingTypeYear1 := ThisYear;
else ProcessingTypeYear1 := History;
end;
case cbx_AssessmentYear2.Items.IndexOf(AssessmentYear2) of
0 : ProcessingTypeYear2 := NextYear;
1 : ProcessingTypeYear2 := ThisYear;
else ProcessingTypeYear2 := History;
end;
FillSelectedItemList(lbx_SchoolCode, SelectedSchoolCodes, 6);
FillSelectedItemList(lbx_SwisCode, SelectedSwisCodes, 6);
FillSelectedItemList(lbx_RollSection, SelectedRollSections, 1);
If PrintDialog.Execute
then
begin
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptBoth], True, Quit);
ReportPrinter.SetPaperSize(dmPaper_Letter, 0, 0);
ReportFiler.SetPaperSize(dmPaper_Letter, 0, 0);
ReportPrinter.Orientation := poLandscape;
ReportFiler.Orientation := poLandscape;
ReportPrinter.ScaleX := 90;
ReportPrinter.ScaleY := 90;
ReportFiler.ScaleX := 90;
ReportFiler.ScaleY := 90;
ReportCancelled := False;
CreateParcelList := cb_CreateParcelList.Checked;
If CreateParcelList
then ParcelListDialog.ClearParcelGrid(True);
GlblPreviewPrint := False;
CopyAndOpenSortFile(tb_Sort, 'ValueCompare',
OrigSortFileName, SortFileName,
True, True, Quit);
OpenTablesForYear(tb_ParcelYear1, tb_AssessmentYear1,
tb_ExemptionYear1, tb_ExemptionCodeYear1,
DatabaseNameYear1, ProcessingTypeYear1);
OpenTablesForYear(tb_ParcelYear2, tb_AssessmentYear2,
tb_ExemptionYear2, tb_ExemptionCodeYear2,
DatabaseNameYear2, ProcessingTypeYear2);
SortFiles;
If ExtractToExcel
then
begin
SpreadsheetFileName := GetPrintFileName(Self.Caption, True);
AssignFile(ExtractFile, SpreadsheetFileName);
Rewrite(ExtractFile);
end; {If PrintToExcel}
If PrintDialog.PrintToFile
then
begin
GlblPreviewPrint := True;
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
PreviewForm.FilePreview.ZoomFactor := 130;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end;
{Delete the report printer file.}
try
Chdir(GlblReportDir);
OldDeleteFile(NewFileName);
except
end;
end
else ReportPrinter.Execute;
{Make sure to close and delete the sort file.}
tb_Sort.Close;
{Now delete the file.}
try
ChDir(GlblDataDir);
OldDeleteFile(SortFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
If CreateParcelList
then ParcelListDialog.Show;
ResetPrinter(ReportPrinter);
ProgressDialog.Finish;
If ExtractToExcel
then
begin
CloseFile(ExtractFile);
SendTextFileToExcelSpreadsheet(SpreadsheetFileName, True,
False, '');
end; {If PrintToExcel}
end; {If PrintDialog.Execute}
tb_Sort.TableName := OrigSortFileName;
end; {StartButtonClick}
{==============================================================}
Procedure Tfm_ValueComparisonReport.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage) + ' ', pjRight);
PrintHeader(' Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft);
SetFont('Times New Roman',12);
Bold := True;
Home;
Println('');
PrintCenter('Value Comparison Report', (PageWidth / 2));
Println('');
Println('');
SetFont('Times New Roman',10);
Bold := True;
ClearTabs;
SetTab(0.3, pjCenter, 1.2, 0, BoxLineBottom, 0); {Parcel ID}
SetTab(1.6, pjCenter, 1.4, 0, BoxLineBottom, 0); {Year}
SetTab(3.1, pjCenter, 0.5, 0, BoxLineBottom, 0); {Status}
SetTab(3.7, pjCenter, 0.2, 0, BoxLineBottom, 0); {RS}
SetTab(4.0, pjCenter, 0.2, 0, BoxLineBottom, 0); {HC}
SetTab(4.3, pjCenter, 0.6, 0, BoxLineBottom, 0); {School Code}
SetTab(5.0, pjCenter, 1.0, 0, BoxLineBottom, 0); {Assessed Value}
SetTab(6.1, pjCenter, 1.0, 0, BoxLineBottom, 0); {County Taxable}
SetTab(7.2, pjCenter, 1.0, 0, BoxLineBottom, 0); {Municipal Taxable}
SetTab(8.3, pjCenter, 1.0, 0, BoxLineBottom, 0); {School Taxable}
Print(#9 + 'Parcel ID' +
#9 + 'Year' +
#9 + 'Status' +
#9 + 'RS' +
#9 + 'HC' +
#9 + 'School');
If (vcAssessedValue in ValueComparisonSections)
then Print(#9 + 'Total Value')
else Print(#9);
If (vcCountyTaxableValue in ValueComparisonSections)
then Print(#9 + 'County Taxable')
else Print(#9);
If (vcMunicipalTaxableValue in ValueComparisonSections)
then Print(#9 + GetMunicipalityTypeName(GlblMunicipalityType) + ' Taxable')
else Print(#9);
If (vcSchoolTaxableValue in ValueComparisonSections)
then Println(#9 + 'School Taxable')
else Println(#9);
Bold := False;
ClearTabs;
SetTab(0.3, pjLeft, 1.2, 0, BoxLineNone, 0); {Parcel ID}
SetTab(1.6, pjLeft, 1.4, 0, BoxLineNone, 0); {Year}
SetTab(3.1, pjLeft, 0.5, 0, BoxLineNone, 0); {Status}
SetTab(3.7, pjLeft, 0.2, 0, BoxLineNone, 0); {RS}
SetTab(4.0, pjLeft, 0.2, 0, BoxLineNone, 0); {HC}
SetTab(4.3, pjLeft, 0.6, 0, BoxLineNone, 0); {School Code}
SetTab(5.0, pjRight, 1.0, 0, BoxLineNone, 0); {Assessed Value}
SetTab(6.1, pjRight, 1.0, 0, BoxLineNone, 0); {County Taxable}
SetTab(7.2, pjRight, 1.0, 0, BoxLineNone, 0); {Municipal Taxable}
SetTab(8.3, pjRight, 1.0, 0, BoxLineNone, 0); {School Taxable}
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{==============================================================}
Function DifferencesExist(tb_Sort : TTable;
ValueComparisonSections : TValueComparisonType) : Boolean;
begin
Result := False;
with tb_Sort do
begin
If not (FieldByName('ParcelExistsYear1').AsBoolean and
FieldByName('ParcelExistsYear2').AsBoolean)
then Result := True;
If (_Compare(FieldByName('StatusYear1').AsString, FieldByName('StatusYear2').AsString, coNotEqual) or
_Compare(FieldByName('RollSectionYear1').AsString, FieldByName('RollSectionYear2').AsString, coNotEqual) or
_Compare(FieldByName('SchoolCodeYear1').AsString, FieldByName('SchoolCodeYear2').AsString, coNotEqual) or
_Compare(FieldByName('HomesteadCodeYear1').AsString, FieldByName('HomesteadCodeYear2').AsString, coNotEqual))
then Result := True;
If ((vcAssessedValue in ValueComparisonSections) and
_Compare(FieldByName('AssessedValueYear1').AsInteger, FieldByName('AssessedValueYear2').AsInteger, coNotEqual))
then Result := True;
If ((vcCountyTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('CountyTaxableYear1').AsInteger, FieldByName('CountyTaxableYear2').AsInteger, coNotEqual))
then Result := True;
If ((vcMunicipalTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('MunicipalTaxableYear1').AsInteger, FieldByName('MunicipalTaxableYear2').AsInteger, coNotEqual))
then Result := True;
If ((vcSchoolTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('SchoolTaxableYear1').AsInteger, FieldByName('SchoolTaxableYear2').AsInteger, coNotEqual))
then Result := True;
{If the parcel does not exist in 1 year and is inactive in the other, don't print it.}
If ((not FieldByName('ParcelExistsYear1').AsBoolean) and
_Compare(FieldByName('StatusYear2').AsString, InactiveParcelFlag, coEqual))
then Result := False;
If ((not FieldByName('ParcelExistsYear2').AsBoolean) and
_Compare(FieldByName('StatusYear1').AsString, InactiveParcelFlag, coEqual))
then Result := False;
end; {with tb_Sort do}
end; {DifferencesExist}
{==============================================================}
Procedure Tfm_ValueComparisonReport.PrintOneDifference( Sender : TObject;
tb_Sort : TTable;
AssessmentYearLabel1 : String;
AssessmentYearLabel2 : String;
var AssessedValueDifference : LongInt;
var CountyTaxableDifference : LongInt;
var MunicipalTaxableDifference : LongInt;
var SchoolTaxableDifference : LongInt);
var
Difference : LongInt;
begin
with Sender as TBaseReport, tb_Sort do
begin
Bold := True;
Print(#9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').AsString) +
#9 + AssessmentYearLabel1);
Bold := False;
If FieldByName('ParcelExistsYear1').AsBoolean
then
begin
Print(#9 + FieldByName('StatusYear1').AsString +
#9 + FieldByName('RollSectionYear1').AsString +
#9 + FieldByName('HomesteadCodeYear1').AsString +
#9 + FieldByName('SchoolCodeYear1').AsString);
If (vcAssessedValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('AssessedValueYear1').AsInteger))
else Print(#9);
If (vcCountyTaxableValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('CountyTaxableYear1').AsInteger))
else Print(#9);
If (vcMunicipalTaxableValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('MunicipalTaxableYear1').AsInteger))
else Print(#9);
If (vcSchoolTaxableValue in ValueComparisonSections)
then Println(#9 + FormatFloat(IntegerDisplay, FieldByName('SchoolTaxableYear1').AsInteger))
else Println('');
end
else Println(#9 + 'Does not exist.');
Bold := True;
Print(#9 +
#9 + AssessmentYearLabel2);
Bold := False;
If FieldByName('ParcelExistsYear2').AsBoolean
then
begin
Print(#9 + FieldByName('StatusYear2').AsString +
#9 + FieldByName('RollSectionYear2').AsString +
#9 + FieldByName('HomesteadCodeYear2').AsString +
#9 + FieldByName('SchoolCodeYear2').AsString);
If (vcAssessedValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('AssessedValueYear2').AsInteger))
else Print(#9);
If (vcCountyTaxableValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('CountyTaxableYear2').AsInteger))
else Print(#9);
If (vcMunicipalTaxableValue in ValueComparisonSections)
then Print(#9 + FormatFloat(IntegerDisplay, FieldByName('MunicipalTaxableYear2').AsInteger))
else Print(#9);
If (vcSchoolTaxableValue in ValueComparisonSections)
then Println(#9 + FormatFloat(IntegerDisplay, FieldByName('SchoolTaxableYear2').AsInteger))
else Println('');
end
else Println(#9 + 'Does not exist.');
Bold := True;
Print(#9 +
#9 + 'Difference');
Underline := True;
If _Compare(FieldByName('StatusYear1').AsString, FieldByName('StatusYear2').AsString, coNotEqual)
then Print(#9 + '*')
else Print(#9);
If _Compare(FieldByName('RollSectionYear1').AsString, FieldByName('RollSectionYear2').AsString, coNotEqual)
then Print(#9 + '*')
else Print(#9);
If _Compare(FieldByName('HomesteadCodeYear1').AsString, FieldByName('HomesteadCodeYear2').AsString, coNotEqual)
then Print(#9 + '*')
else Print(#9);
If _Compare(FieldByName('SchoolCodeYear1').AsString, FieldByName('SchoolCodeYear2').AsString, coNotEqual)
then Print(#9 + '*')
else Print(#9);
If ((vcAssessedValue in ValueComparisonSections) and
_Compare(FieldByName('AssessedValueYear1').AsInteger, FieldByName('AssessedValueYear2').AsInteger, coNotEqual))
then
begin
Difference := FieldByName('AssessedValueYear1').AsInteger - FieldByName('AssessedValueYear2').AsInteger;
AssessedValueDifference := AssessedValueDifference + Difference;
Print(#9 + FormatFloat(IntegerDisplay, Difference));
end
else Print(#9);
If ((vcCountyTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('CountyTaxableYear1').AsInteger, FieldByName('CountyTaxableYear2').AsInteger, coNotEqual))
then
begin
Difference := FieldByName('CountyTaxableYear1').AsInteger - FieldByName('CountyTaxableYear2').AsInteger;
CountyTaxableDifference := CountyTaxableDifference + Difference;
Print(#9 + FormatFloat(IntegerDisplay, Difference));
end
else Print(#9);
If ((vcMunicipalTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('MunicipalTaxableYear1').AsInteger, FieldByName('MunicipalTaxableYear2').AsInteger, coNotEqual))
then
begin
Difference := FieldByName('MunicipalTaxableYear1').AsInteger - FieldByName('MunicipalTaxableYear2').AsInteger;
MunicipalTaxableDifference := MunicipalTaxableDifference + Difference;
Print(#9 + FormatFloat(IntegerDisplay, Difference));
end
else Print(#9);
If ((vcSchoolTaxableValue in ValueComparisonSections) and
_Compare(FieldByName('SchoolTaxableYear1').AsInteger, FieldByName('SchoolTaxableYear2').AsInteger, coNotEqual))
then
begin
Difference := FieldByName('SchoolTaxableYear1').AsInteger - FieldByName('SchoolTaxableYear2').AsInteger;
SchoolTaxableDifference := SchoolTaxableDifference + Difference;
Println(#9 + FormatFloat(IntegerDisplay, Difference));
end
else Println(#9);
Bold := False;
Underline := False;
Println('');
end; {with Sender as TBaseReport do}
end; {PrintOneDifference}
{==============================================================}
Procedure Tfm_ValueComparisonReport.ReportPrint(Sender: TObject);
var
AssessedValueDifference, CountyTaxableDifference,
MunicipalTaxableDifference, SchoolTaxableDifference : LongInt;
begin
ReportCancelled := False;
AssessedValueDifference := 0;
CountyTaxableDifference := 0;
MunicipalTaxableDifference := 0;
SchoolTaxableDifference := 0;
tb_Sort.First;
ProgressDialog.UserLabelCaption := 'Printing Sort Results';
ProgressDialog.Start(tb_Sort.RecordCount, True, True);
with tb_Sort do
while not (EOF or ReportCancelled) do
begin
ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').AsString));
Application.ProcessMessages;
If DifferencesExist(tb_Sort, ValueComparisonSections)
then
begin
PrintOneDifference(Sender, tb_Sort,
AssessmentYearLabel1, AssessmentYearLabel2,
AssessedValueDifference, CountyTaxableDifference,
MunicipalTaxableDifference, SchoolTaxableDifference);
with Sender as TBaseReport do
If (LinesLeft < 5)
then NewPage;
end; {If DifferencesExist(tb_Sort)}
Next;
ReportCancelled := ProgressDialog.Cancelled;
end; {while not (EOF or ReportCancelled) do}
with Sender as TBaseReport do
begin
Bold := True;
Underline := True;
Println(#9 + 'Total Difference:' +
#9 + #9 + #9 + #9 + #9 +
#9 + FormatFloat(IntegerDisplay, AssessedValueDifference) +
#9 + FormatFloat(IntegerDisplay, CountyTaxableDifference) +
#9 + FormatFloat(IntegerDisplay, MunicipalTaxableDifference) +
#9 + FormatFloat(IntegerDisplay, SchoolTaxableDifference));
Underline := False;
end; {with Sender as TBaseReport do}
end; {ReportPrint}
{===================================================================}
Procedure Tfm_ValueComparisonReport.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
SelectedSchoolCodes.Free;
SelectedSwisCodes.Free;
SelectedRollSections.Free;
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
unit MediaStream.Framer.Bmp;
interface
uses Windows,SysUtils,Classes,MediaProcessing.Definitions,MediaStream.Framer,MediaStream.Framer.Picture,BitPlane;
type
TStreamFramerBmp = class (TStreamFramerPicture)
private
FBmpFileHeader: BITMAPFILEHEADER;
FBmpInfoHeader: BITMAPINFOHEADER;
FBmpDib: TBytes;
FFrameNo: int64;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; override;
function VideoStreamType: TStreamType; override;
function AudioStreamType: TStreamType; override;
function StreamInfo: TBytes; override;
end;
implementation
{ TStreamFramerBmp }
constructor TStreamFramerBmp.Create;
begin
inherited;
end;
destructor TStreamFramerBmp.Destroy;
begin
inherited;
end;
function TStreamFramerBmp.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean;
begin
result:=true;
aOutData:=@FBmpDib[0];
aOutDataSize:=Length(FBmpDib);
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.Clear;
aOutFormat.biMediaType:=mtVideo;
aOutFormat.Assign(FBmpInfoHeader);
aOutFormat.TimeStamp:=FFrameNo*FrameInterval;
inc(FFrameNo);
Assert(aOutFormat.biStreamType=VideoStreamType);
end;
procedure TStreamFramerBmp.OpenStream(aStream: TStream);
var
aPos: int64;
begin
aPos:=aStream.Position;
aStream.ReadBuffer(FBmpFileHeader,sizeof(FBmpFileHeader));
aStream.ReadBuffer(FBmpInfoHeader,sizeof(FBmpInfoHeader));
if FBmpFileHeader.bfType<>$4d42 then //"BM"
raise Exception.Create('Неверный формат');
aPos:=aStream.Position-aPos;
if FBmpFileHeader.bfOffBits<aPos then
raise Exception.Create('Неверный формат');
aStream.Seek(FBmpFileHeader.bfOffBits-aPos,soFromCurrent);
aPos:=GetRGBLineSize(FBmpInfoHeader.biWidth,FBmpInfoHeader.biBitCount)*FBmpInfoHeader.biHeight;
if (aPos<>FBmpInfoHeader.biSizeImage) then
raise Exception.Create('Размер изображения некорректный');
SetLength(FBmpDib,FBmpInfoHeader.biSizeImage);
aStream.ReadBuffer(FBmpDib[0],FBmpInfoHeader.biSizeImage);
FFrameNo:=0;
end;
function TStreamFramerBmp.StreamInfo: TBytes;
begin
result:=nil;
end;
function TStreamFramerBmp.VideoStreamType: TStreamType;
begin
result:=stRGB;
end;
function TStreamFramerBmp.AudioStreamType: TStreamType;
begin
result:=0;
end;
end.
|
// auteur : Djebien Tarik
// date : Mai 2010
// objet : Unite pour la structure de donnée linéaire de PILE (LIFO).
UNIT U_Pile;
INTERFACE
uses SysUtils;
TYPE
(*===============================================================================================*)
(*============================= DEFINITION DU TYPE POINTEUR DE CELLULE===========================*)
// Pointeur de Cellule (pointeur de noeud de l'arbre)
P_CELLULE = ^CELLULE;
// Une cellule est un enregistrement qui possede deux champs
CELLULE = record
// le premier indique la fin de mot *
isMot : BOOLEAN;
// le second represente les 26 lettres de l'alphabet
Contenu : ARRAY['a'..'z'] of P_CELLULE; (* par default, en pascal, un pointeur est initialisé à nil.*)
end{CELLULE};
(*=============================== DEFINITION DU TYPE PILE =========================================*)
(* _ __________________
PILE = |_|--->|______|___________|
valeur en|dessous
|
__________v_______
|______|___________|
|
__________v_______
|______|___________|
|
__________v_______
|______|___________|
*)
// Un element de la pile est un pointeur de noeud de l'arbre du dictionnaire
ELEMENT_PILE = P_CELLULE;
// Une PILE (LIFO) est
PILE = ^NIVEAU;
// composé de plusieurs
NIVEAU = record
// contenant chacun
valeur : ELEMENT_PILE; // qui est un pointeur de noeud de l'arbre.
endessous : PILE; // pour acceder au niveau situé sous le niveau au sommet de la PILE.
end {record};
PileVide = class(SysUtils.Exception);
const
PILE_VIDE : PILE = NIL;
// estPileVide(P) ssi P est vide
function estPileVide(P : PILE) : BOOLEAN;
// sommet(P) = element situe au sommet de P
// declenche une exception si la pile est vide
function sommet(P : PILE) : ELEMENT_PILE;
// empile x au sommet de la pile P
procedure empiler(const x : ELEMENT_PILE; var P : PILE);
// depile x la pile P
// declenche une exception si la pile est vide
procedure depiler(var P : PILE);
IMPLEMENTATION
// estPileVide(P) ssi P est vide
function estPileVide(P : PILE) : BOOLEAN;
begin
estPileVide := (p = PILE_VIDE);
end { estPileVide };
// sommet(P) = element situe au sommet de P
// CU : declenche une exception si la pile est vide
function sommet(P : PILE) : ELEMENT_PILE;
begin
if estPileVide(p) then
raise PileVide.create('Pile Vide')
else
sommet := p.valeur;
end {sommet};
// empile l'element x au sommet de la pile P
procedure empiler(const x : ELEMENT_PILE; var P : PILE);
var
q : PILE;
begin
new(q);
q.valeur := x;
q.endessous := p;
p := q;
end {empiler};
// depile l'élement x au sommet de la pile P
// CU : declenche une exception si la pile est vide
procedure depiler(var P : PILE);
var
q : PILE;
begin
if estPileVide(p) then
raise PileVide.create('Impossible de depiler : Pile Vide')
else begin
q := p;
p := p.endessous;
dispose(q);
end {if};
end {depiler};
INITIALIZATION
(* UNITE MANIPULATION DE STRUCTURE DE DONNEE LINEAIRE DE PILE (LIFO) *)
(* ANNEXE : Prototypes *)
(* SELECTEURS
function sommet(P : PILE) : ELEMENT_PILE;
(* PREDICATS
function estPileVide(P : PILE) : BOOLEAN;
(* MODIFICATEURS
procedure empiler(const x : ELEMENT_PILE; var P : PILE);
procedure depiler(var P : PILE);
*)
FINALIZATION
(* Auteur, Djebien Tarik *)
END {U_Pile}.
|
unit Rx.Observable.Delay;
interface
uses Rx, Rx.Implementations, Generics.Collections, Rx.Subjects;
type
TDelay<T> = class(TPublishSubject<T>)
type
TValue = TSmartVariable<T>;
strict private
FCache: TList<TValue>;
FCompleted: Boolean;
FError: IThrowable;
FInterval: TObservable<LongWord>;
FSubscription: ISubscription;
procedure OnTimeout(const Iter: LongWord);
public
constructor Create(Source: IObservable<T>;
aInterval: LongWord; aTimeUnit: TimeUnit = TimeUnit.SECONDS);
destructor Destroy; override;
procedure OnNext(const Data: T); override;
procedure OnError(E: IThrowable); override;
procedure OnCompleted; override;
end;
implementation
{ TDelay<T> }
constructor TDelay<T>.Create(Source: IObservable<T>;
aInterval: LongWord; aTimeUnit: TimeUnit = TimeUnit.SECONDS);
begin
inherited Create;
FCache := TList<TValue>.Create;
Merge(Source);
FInterval := Observable.Interval(aInterval, aTimeUnit);
FSubscription := FInterval.Subscribe(OnTimeout);
end;
destructor TDelay<T>.Destroy;
begin
FSubscription.Unsubscribe;
FCache.Free;
FInterval := nil;
inherited;
end;
procedure TDelay<T>.OnCompleted;
var
DoRaise: Boolean;
begin
Lock;
try
FCompleted := True;
DoRaise := FCache.Count = 0;
finally
Unlock;
end;
if DoRaise then
inherited OnCompleted;
end;
procedure TDelay<T>.OnError(E: IThrowable);
var
DoRaise: Boolean;
begin
Lock;
try
FError := E;
DoRaise := FCache.Count = 0;
finally
Unlock;
end;
if DoRaise then
inherited OnError(E);
end;
procedure TDelay<T>.OnNext(const Data: T);
begin
// hide parent logic
Lock;
try
FCache.Add(Data)
finally
Unlock;
end;
end;
procedure TDelay<T>.OnTimeout(const Iter: LongWord);
var
Value: TValue;
ValueExists: Boolean;
IsCompleted: Boolean;
begin
Lock;
try
ValueExists := FCache.Count > 0;
if ValueExists then begin
Value := FCache[0];
FCache.Delete(0);
end;
IsCompleted := FCompleted or Assigned(FError);
finally
Unlock;
end;
if ValueExists then
inherited OnNext(Value)
else begin
if IsCompleted then
if Assigned(FError) then
inherited OnError(FError)
else
inherited OnCompleted;
end;
end;
end.
|
{
LaKraven Studios Standard Library [LKSL]
Copyright (c) 2014, LaKraven Studios Ltd, All Rights Reserved
Original Source Location: https://github.com/LaKraven/LKSL
License:
- You may use this library as you see fit, including use within commercial applications.
- You may modify this library to suit your needs, without the requirement of distributing
modified versions.
- You may redistribute this library (in part or whole) individually, or as part of any
other works.
- You must NOT charge a fee for the distribution of this library (compiled or in its
source form). It MUST be distributed freely.
- This license and the surrounding comment block MUST remain in place on all copies and
modified versions of this source code.
- Modified versions of this source MUST be clearly marked, including the name of the
person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog"
detailing all additions/deletions/modifications made.
Disclaimer:
- Your use of this source constitutes your understanding and acceptance of this
disclaimer.
- LaKraven Studios Ltd and its employees (including but not limited to directors,
programmers and clerical staff) cannot be held liable for your use of this source
code. This includes any losses and/or damages resulting from your use of this source
code, be they physical, financial, or psychological.
- There is no warranty or guarantee (implicit or otherwise) provided with this source
code. It is provided on an "AS-IS" basis.
Donations:
- While not mandatory, contributions are always appreciated. They help keep the coffee
flowing during the long hours invested in this and all other Open Source projects we
produce.
- Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com
^ Garbled to prevent spam! ^
}
unit LKSL_Settings_Groups;
{
About this unit: (FPC/Lazarus)
- This unit provides the objects that contain groups of key/value pairs.
Changelog (newest on top):
3rd October 2014:
- Initial Scaffolding
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LKSL_Settings_Fields;
type
{
TLKSettingsGroup
- Implements a container for a simple group of key/value pairs.
}
TLKSettingsGroups = class; // Forward class
TLKSettingsGroup = class(TComponent)
private
FGroupName: String;
FDisplayName: String;
FSettingsFields: TLKSettingsFields;
FSettingsGroups: TLKSettingsGroups;
function GetSettingsField(Index: Integer): TLKSettingsField;
function GetSettingsGroup(Index: Integer): TLKSettingsGroup;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Fields[Index: Integer]: TLKSettingsField read GetSettingsField; default;
property Groups[Index: Integer]: TLKSettingsGroup read GetSettingsGroup;
published
property GroupName: String read FGroupName write FGroupName;
property DisplayName: String read FDisplayName write FDisplayName;
end;
TLKSettingsGroupClass = class of TLKSettingsGroup;
{
TLKSettingsGroups
- Implements a container for a list of TLKSettingsGroup with many levels.
}
TLKSettingsGroups = class(TComponent)
private
FSettingsGroupItems: TFPList;
function GetCount: Integer;
function GetSettingsGroup(Index: Integer): TLKSettingsGroup;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Add(AGroup: TLKSettingsGroup): Integer;
procedure Delete(AGroup: TLKSettingsGroup);
procedure Delete(AIndex: Integer); overload;
procedure Clear;
property Items[Index: Integer]: TLKSettingsGroup read GetSettingsGroup; default;
property Count: Integer read GetCount;
published
end;
TLKSettingsGroupsClass = class of TLKSettingsGroups;
{
Register
- Procedure to register component on the component bar
}
procedure Register;
implementation
procedure Register;
begin
// Will need to register the property editors for Groups
end;
{ TLKSettingsGroup }
function TLKSettingsGroup.GetSettingsField(Index: Integer): TLKSettingsField;
begin
Result:= TLKSettingsField(FSettingsFields[Index]);
end;
function TLKSettingsGroup.GetSettingsGroup(Index: Integer): TLKSettingsGroup;
begin
Result:= TLKSettingsGroup(FSettingsGroups[Index]);
end;
constructor TLKSettingsGroup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSettingsFields:= TLKSettingsFields.Create(Self);
FSettingsGroups:= TLKSettingsGroups.Create(Self);
end;
destructor TLKSettingsGroup.Destroy;
begin
if Assigned(FSettingsFields) then
begin
FSettingsFields.Free;
end;
if Assigned(FSettingsGroups) then
begin
FSettingsGroups.Free;
end;
inherited Destroy;
end;
{ TLKSettingsGroups }
function TLKSettingsGroups.GetSettingsGroup(Index: Integer): TLKSettingsGroup;
begin
Result:= TLKSettingsGroup(FSettingsGroupItems[Index]);
end;
function TLKSettingsGroups.GetCount: Integer;
begin
Result:= FSettingsGroupItems.Count;
end;
constructor TLKSettingsGroups.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSettingsGroupItems:= TFPList.Create;
end;
destructor TLKSettingsGroups.Destroy;
var
Index: Integer;
begin
if Assigned(FSettingsGroupItems) then
begin
for Index:= FSettingsGroupItems.Count - 1 downto 0 do
begin
if Assigned(FSettingsGroupItems[Index]) then
begin
TLKSettingsGroup(FSettingsGroupItems[Index]).Free;
end;
FSettingsGroupItems.Delete(Index);
end;
end;
FSettingsGroupItems.Free;
inherited Destroy;
end;
function TLKSettingsGroups.Add(AGroup: TLKSettingsGroup): Integer;
begin
Result:= FSettingsGroupItems.Add(AGroup);
end;
procedure TLKSettingsGroups.Delete(AGroup: TLKSettingsGroup);
var
Index: Integer;
begin
for Index:= 0 to FSettingsGroupItems.Count - 1 do
begin
if AGroup = TLKSettingsGroup(FSettingsGroupItems[Index]) then
begin
TLKSettingsGroup(FSettingsGroupItems[Index]).Free;
FSettingsGroupItems.Delete(Index);
break;
end;
end;
end;
procedure TLKSettingsGroups.Delete(AIndex: Integer);
begin
FSettingsGroupItems.Delete(AIndex);
end;
procedure TLKSettingsGroups.Clear;
var
Index: Integer;
begin
for Index:= FSettingsGroupItems.Count - 1 downto 0 do
begin
if Assigned(FSettingsGroupItems[Index]) then
begin
TLKSettingsGroup(FSettingsGroupItems[Index]).Free;
end;
FSettingsGroupItems.Delete(Index);
end;
end;
end.
|
////////////////////////////////////////////
// Обертка над Query и Connection к SQL
// Требуется для относительно бескровного перехода от MS SQL к Postgres
////////////////////////////////////////////
unit GMSqlQuery;
interface
uses Windows, Classes, ZDataset, ZConnection, GMGlobals, DB, ConnParamsStorage, SysUtils;
{$ifndef SQL_APP}
message Для использования модуля define SQL_APP
{$endif}
type
TGMSqlQuery = class
private
q: TZReadOnlyQuery;
FConnectionParams: TZConnectionParams;
FOwnsConnection: bool;
function GetSQL: TStrings;
function GetFields: TFields;
function GetEof: bool;
function GetState: TDataSetState;
procedure Connect();
procedure Connect_Own;
procedure Connect_Thread;
procedure UpdateConnectionParams(conn: TZConnection; params: TZConnectionParams);
function GetThreadDescription: string;
function CommentQueryText(const sql: string): string;
procedure SetAppNameForConnection;
public
constructor Create(); overload;
constructor Create(Params: TZConnectionParams); overload;
destructor Destroy; override;
property SQL: TStrings read GetSQL;
property Fields: TFields read GetFields;
property State: TDataSetState read GetState;
function FieldByName(const FieldName: string): TField;
procedure Open();
procedure ExecSQL();
procedure Execute(const s: string);
procedure Next();
procedure Close();
property Eof: bool read GetEof;
end;
TReadGMQueryProc = procedure(q: TGMSqlQuery; obj: pointer) of object;
TReadGMQueryProcRef = reference to procedure(q: TGMSqlQuery);
procedure ReadFromQuery(const sql: string; proc: TReadGMQueryProc; obj: pointer = nil); overload;
procedure ReadFromQuery(const sql: string; proc: TReadGMQueryProcRef); overload;
procedure ReadFromQueryFmt(const sql: string; args: array of const; proc: TReadGMQueryProcRef);
procedure ExecSQL(const sql: string);
procedure ExecSQLFmt(const sql: string; args: array of const);
procedure ExecPLSQL(const sql: string);
procedure ExecPLSQLFmt(const sql: string; args: array of const);
function QueryResult(const sql: string): string;
function QueryResultFmt(const sql: string; args: array of const): string;
function QueryResultArray_FirstRow(const sql: string): ArrayOfString;
function QueryResultArray_FirstRowFmt(const sql: string; args: array of const): ArrayOfString;
function QueryResultArray_FirstColumn(const sql: string): ArrayOfString;
procedure DropThreadConnection(thrId: int);
implementation
uses
System.Generics.Collections, Threads.Base;
var
ThreadConnections: TDictionary<Cardinal, TZConnection>;
procedure ReadFromQuery(const sql: string; proc: TReadGMQueryProc; obj: pointer = nil);
var
q: TGMSqlQuery;
begin
q := TGMSqlQuery.Create();
try
q.SQL.Text := sql;
q.Open();
while not q.Eof do
begin
proc(q, obj);
q.Next();
end;
finally
q.Free();
end;
end;
procedure ReadFromQuery(const sql: string; proc: TReadGMQueryProcRef);
var
q: TGMSqlQuery;
begin
q := TGMSqlQuery.Create();
try
q.SQL.Text := sql;
q.Open();
while not q.Eof do
begin
proc(q);
q.Next();
end;
finally
q.Free();
end;
end;
procedure ReadFromQueryFmt(const sql: string; args: array of const; proc: TReadGMQueryProcRef);
begin
ReadFromQuery(Format(sql, args), proc);
end;
procedure ExecSQL(const sql: string);
var
q: TGMSqlQuery;
begin
if sql.Trim() = '' then Exit;
q := TGMSqlQuery.Create();
try
q.Execute(sql);
finally
q.Free();
end;
end;
procedure ExecSQLFmt(const sql: string; args: array of const);
var
s: string;
begin
s := Format(sql, args);
ExecSQL(s);
end;
procedure ExecPLSQL(const sql: string);
var s: string;
begin
s := sql.Trim();
if s = '' then Exit;
if not s.EndsWith(';') then
s := s + ';';
s := 'do $$ begin ' + s + ' end $$';
ExecSQL(s);
end;
procedure ExecPLSQLFmt(const sql: string; args: array of const);
var
s: string;
begin
s := Format(sql, args);
ExecPLSQL(s);
end;
function QueryResultArray_FirstRow(const sql: string): ArrayOfString;
var q: TGMSqlQuery;
i: int;
begin
q := TGMSqlQuery.Create();
SetLength(Result, 0);
try
q.SQL.Text := sql;
q.Open();
if not q.Eof then
begin
SetLength(Result, q.Fields.Count + 1);
for i := 0 to q.Fields.Count - 1 do
Result[i] := q.Fields[i].AsString;
// в последнюю колонку запишем 1, если запрос вернул больше одной строки
q.Next();
if q.Eof then
Result[q.Fields.Count] := '0'
else
Result[q.Fields.Count] := '1';
end;
finally
q.Free();
end;
end;
function QueryResultArray_FirstRowFmt(const sql: string; args: array of const): ArrayOfString;
begin
Result := QueryResultArray_FirstRow(Format(sql, args));
end;
function QueryResultArray_FirstColumn(const sql: string): ArrayOfString;
var q: TGMSqlQuery;
n: int;
begin
q := TGMSqlQuery.Create();
SetLength(Result, 0);
try
q.SQL.Text := sql;
q.Open();
if q.Eof or (q.Fields.Count = 0) then Exit;
n := 0;
while not q.Eof do
begin
SetLength(Result, Length(Result) + 1);
Result[n] := q.Fields[0].AsString;
q.Next();
inc(n);
end;
finally
q.Free();
end;
end;
function QueryResult(const sql: string): string;
var
arr: ArrayOfString;
begin
Result := '';
arr := QueryResultArray_FirstRow(sql);
if Length(arr) > 0 then
Result := arr[0];
end;
function QueryResultFmt(const sql: string; args: array of const): string;
begin
Result := QueryResult(Format(sql, args));
end;
{ TGMSqlQuery }
procedure TGMSqlQuery.Close;
begin
q.Close();
end;
procedure TGMSqlQuery.UpdateConnectionParams(conn: TZConnection; params: TZConnectionParams);
begin
conn.HostName := params.Host;
conn.Port := params.Port;
conn.User := params.Login;
conn.Password := params.Password;
conn.Database := params.Database;
conn.Protocol := 'postgresql-9';
conn.ClientCodepage := 'WIN1251';
// должно работать, но почему-то это недопустимый параметр соединения
// придется делать костылем через SetAppNameForConnection
// conn.Properties.Values['application_name'] := Paramstr(0);
if params.LibraryLocation <> '' then
conn.LibraryLocation := params.LibraryLocation;
end;
procedure TGMSqlQuery.SetAppNameForConnection;
begin
if (q.Connection <> nil) and q.Connection.Connected then
q.Connection.ExecuteDirect(CommentQueryText('set application_name to ' + AnsiQuotedStr(Paramstr(0), '"')));
end;
procedure TGMSqlQuery.Connect_Own();
begin
if q.Connection = nil then
q.Connection := TZConnection.Create(nil);
if not q.Connection.Connected then
begin
UpdateConnectionParams(TZConnection(q.Connection), FConnectionParams);
q.Connection.Connect();
SetAppNameForConnection();
end;
end;
procedure TGMSqlQuery.Connect_Thread();
var
conn: TZConnection;
thrId: cardinal;
begin
thrId := GetCurrentThreadId();
if not ThreadConnections.TryGetValue(thrId, conn) then
conn := TZConnection.Create(nil);
if not conn.Connected then
begin
UpdateConnectionParams(conn, GlobalSQLConnectionParams());
conn.Connect();
end;
ThreadConnections.AddOrSetValue(thrId, conn);
q.Connection := conn;
SetAppNameForConnection();
end;
procedure TGMSqlQuery.Connect;
begin
if (q.Connection <> nil) and q.Connection.Connected then
Exit;
if FOwnsConnection then
Connect_Own()
else
Connect_Thread();
end;
constructor TGMSqlQuery.Create;
begin
inherited;
FConnectionParams := GlobalSQLConnectionParams();
q := TZReadOnlyQuery.Create(nil);
q.ParamCheck := false;
FOwnsConnection := false;
end;
constructor TGMSqlQuery.Create(Params: TZConnectionParams);
begin
Create();
FConnectionParams := Params;
FOwnsConnection := true;
end;
destructor TGMSqlQuery.Destroy;
begin
if FOwnsConnection then
q.Connection.Free();
q.Free();
inherited;
end;
procedure TGMSqlQuery.ExecSQL;
begin
Connect();
q.SQL.Text := CommentQueryText(q.SQL.Text);
try
q.ExecSQL();
except
q.Connection.Disconnect();
Connect();
q.ExecSQL();
end;
end;
function TGMSqlQuery.GetThreadDescription(): string;
var
thr: TThread;
begin
Result := '';
thr := TThread.CurrentThread;
if thr = nil then
Exit;
if thr is TGMThread then
Result := TGMThread(thr).Description;
if Trim(Result) = '' then
Result := thr.ClassName();
Result := '/* ' + Result + ' */ ';
end;
function TGMSqlQuery.CommentQueryText(const sql: string): string;
var
desc: string;
begin
desc := GetThreadDescription();
if (desc = '') or (Pos(AnsiUpperCase(desc), AnsiUpperCase(sql)) > 0) then
Exit(sql);
Result := desc + sql;
end;
procedure TGMSqlQuery.Execute(const s: string);
begin
Connect();
try
q.Connection.ExecuteDirect(CommentQueryText(s));
except
q.Connection.Disconnect();
Connect();
q.Connection.ExecuteDirect(CommentQueryText(s));
end;
end;
function TGMSqlQuery.FieldByName(const FieldName: string): TField;
begin
Result := q.FieldByName(FieldName);
end;
function TGMSqlQuery.GetEof: bool;
begin
Result := q.Eof;
end;
function TGMSqlQuery.GetFields: TFields;
begin
Result := q.Fields;
end;
function TGMSqlQuery.GetSQL: TStrings;
begin
Result := q.SQL;
end;
function TGMSqlQuery.GetState: TDataSetState;
begin
Result := q.State;
end;
procedure TGMSqlQuery.Next;
begin
q.Next();
end;
procedure TGMSqlQuery.Open;
begin
Connect();
if not q.ControlsDisabled then
q.DisableControls();
q.SQL.Text := CommentQueryText(q.SQL.Text);
try
q.Open();
except
q.Connection.Disconnect();
Connect();
q.Open();
end;
end;
procedure FreeThreadConnections();
var
conn: TZConnection;
begin
for conn in ThreadConnections.Values do
conn.Free();
FreeAndNil(ThreadConnections);
end;
procedure DropThreadConnection(thrId: int);
var
conn: TZConnection;
begin
if (ThreadConnections = nil) or not ThreadConnections.TryGetValue(thrId, conn) then
Exit;
conn.Free();
ThreadConnections.Remove(thrId);
end;
initialization
ThreadConnections := TDictionary<Cardinal, TZConnection>.Create();
finalization
FreeThreadConnections();
end.
|
unit frmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.Grids, System.StrUtils, Vcl.ExtCtrls,
Vcl.ComCtrls, Vcl.Menus,
Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc,
Ths.Erp.Helper.BaseTypes,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.ComboBox,
Ths.Erp.Helper.Memo;
const
PROJECT_UNITNAME = 'Ths.Erp.Database.Table.';
COL_ROW_NO = 0;
COL_PROPERTY_NAME = 1;
COL_FIELD_NAME = 2;
COL_FIELD_TYPE = 3;
COL_GRID_COL_CAPTION = 4;
COL_INPUT_LABEL_CAPTION = 5;
COL_GUI_CONTROL = 6;
COL_CONTROL_TYPE = 7;
type
TfrmMainClassGenerator = class(TForm)
pnlTop: TPanel;
strngrdList: TStringGrid;
pgcMemos: TPageControl;
tsClass: TTabSheet;
mmoClass: TMemo;
tsOutput: TTabSheet;
tsInput: TTabSheet;
pnlClass: TPanel;
btnAddClassToMemo: TButton;
pnlOutputDFM: TPanel;
mmoOutputDFM: TMemo;
pnlOutputBottomDFM: TPanel;
btnAddOutputDFMToMemo: TButton;
Splitter1: TSplitter;
pnlOutputPAS: TPanel;
mmoOutputPAS: TMemo;
pnlOutputBottomPAS: TPanel;
btnAddOutputPASToMemo: TButton;
pnlInputDFM: TPanel;
mmoInputDFM: TMemo;
pnlInputBottomDFM: TPanel;
btnAddInputDFMToMemo: TButton;
Splitter2: TSplitter;
pnlInputPAS: TPanel;
mmoInputPAS: TMemo;
pnlInputBottomPAS: TPanel;
btnAddInputPASToMemo: TButton;
Splitter3: TSplitter;
pmBase: TPopupMenu;
mniDeleteRow: TMenuItem;
mniSaveToFile: TMenuItem;
mniLoadFromFile: TMenuItem;
pnlLeft: TPanel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lblCaption: TLabel;
lblFieldName: TLabel;
lblFieldType: TLabel;
lblpropertyname: TLabel;
Label5: TLabel;
lblOutputFormCaption: TLabel;
lblOutputFormName: TLabel;
lblInputFormName: TLabel;
lblIsGUIControl: TLabel;
lblControlType: TLabel;
lblInputFormCaption: TLabel;
lblInputLabelCaption: TLabel;
edtMainProjectDirectory: TEdit;
edtClassType: TEdit;
edtTableName: TEdit;
edtSourceCode: TEdit;
edtOutputFormName: TEdit;
edtOutputFormCaption: TEdit;
edtInputFormName: TEdit;
edtInputFormCaption: TEdit;
edtpropertyname: TEdit;
edtFieldName: TEdit;
cbbFieldType: TComboBox;
edtCaption: TEdit;
chkIsGUIControl: TCheckBox;
cbbControlType: TComboBox;
btnAddField: TButton;
btnClearLists: TButton;
btnSaveToFiles: TButton;
edtInputLabelCaption: TEdit;
btnEditField: TButton;
procedure btnClearListsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnAddFieldClick(Sender: TObject);
procedure btnAddClassToMemoClick(Sender: TObject);
procedure btnSaveToFilesClick(Sender: TObject);
procedure edtMainProjectDirectoryDblClick(Sender: TObject);
procedure btnAddOutputDFMToMemoClick(Sender: TObject);
procedure mmoClassKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnAddOutputPASToMemoClick(Sender: TObject);
procedure btnAddInputDFMToMemoClick(Sender: TObject);
procedure btnAddInputPASToMemoClick(Sender: TObject);
procedure mniDeleteRowClick(Sender: TObject);
procedure strngrdListRowMoved(Sender: TObject; FromIndex, ToIndex: Integer);
procedure chkIsGUIControlClick(Sender: TObject);
procedure strngrdListMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mniSaveToFileClick(Sender: TObject);
procedure mniLoadFromFileClick(Sender: TObject);
procedure strngrdListDblClick(Sender: TObject);
procedure btnEditFieldClick(Sender: TObject);
private
FRowNo: Integer;
procedure ReFillAndSort();
procedure ClearGridList;
public
{ Public declarations }
end;
var
frmMainClassGenerator: TfrmMainClassGenerator;
implementation
{$R *.dfm}
procedure TfrmMainClassGenerator.btnAddFieldClick(Sender: TObject);
begin
strngrdList.Cells[COL_ROW_NO,strngrdList.RowCount-1] := (strngrdList.RowCount-1).ToString;
strngrdList.Cells[COL_PROPERTY_NAME,strngrdList.RowCount-1] := edtpropertyname.Text;
strngrdList.Cells[COL_FIELD_NAME,strngrdList.RowCount-1] := edtFieldName.Text;
strngrdList.Cells[COL_FIELD_TYPE,strngrdList.RowCount-1] := cbbFieldType.Text;
strngrdList.Cells[COL_GRID_COL_CAPTION,strngrdList.RowCount-1] := edtCaption.Text;
strngrdList.Cells[COL_INPUT_LABEL_CAPTION,strngrdList.RowCount-1] := edtInputLabelCaption.Text;
if chkIsGUIControl.Checked then
strngrdList.Cells[COL_GUI_CONTROL,strngrdList.RowCount-1] := 'Yes'
else
strngrdList.Cells[COL_GUI_CONTROL,strngrdList.RowCount-1] := 'No';
strngrdList.Cells[COL_CONTROL_TYPE,strngrdList.RowCount-1] := cbbControlType.Text;
strngrdList.RowCount := strngrdList.RowCount + 1;
edtpropertyname.Clear;
edtFieldName.Clear;
cbbFieldType.ItemIndex := -1;
edtCaption.Clear;
edtInputLabelCaption.Clear;
chkIsGUIControl.Checked := False;
chkIsGUIControlClick(chkIsGUIControl);
cbbControlType.ItemIndex := -1;
edtpropertyname.SetFocus;
strngrdList.Top := strngrdList.RowCount-1;
btnEditField.Enabled := False;
FRowNo := -1;
end;
procedure TfrmMainClassGenerator.btnAddInputDFMToMemoClick(Sender: TObject);
var
n1, vMaxCaptionLenght, vGuiCount, vOrder: Integer;
function GetMaxCaptionLength(): Integer;
var
n2: Integer;
vDump: Integer;
begin
Result := 0;
for n2 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n2] = 'Yes' then
begin
vDump := Canvas.TextWidth(LowerCase(strngrdList.Cells[COL_GRID_COL_CAPTION, n2]));
if Result < vDump then
Result := vDump;
end;
end;
end;
function GetGuiControlCount(): Integer;
var
n2: Integer;
begin
Result := 0;
for n2 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n2] = 'Yes' then
begin
Inc(Result);
end;
end;
end;
begin
vOrder := 0;
vMaxCaptionLenght := GetMaxCaptionLength;
vGuiCount := GetGuiControlCount;
mmoInputDFM.Lines.Clear;
mmoInputDFM.Lines.BeginUpdate;
mmoInputDFM.Lines.Add('inherited frm' + edtInputFormName.Text + ': Tfrm' + edtInputFormName.Text);
mmoInputDFM.Lines.Add(' Left = 501');
mmoInputDFM.Lines.Add(' Top = 443');
mmoInputDFM.Lines.Add(' ActiveControl = btnClose');
mmoInputDFM.Lines.Add(' BorderIcons = [biSystemMenu, biMinimize]');
mmoInputDFM.Lines.Add(' BorderStyle = bsSingle');
mmoInputDFM.Lines.Add(' Caption = ' + QuotedStr(edtInputFormCaption.Text));
mmoInputDFM.Lines.Add(' ClientHeight = ' + IntToStr(70 + vGuiCount * 25) );
mmoInputDFM.Lines.Add(' ClientWidth = ' + IntToStr( 32 + vMaxCaptionLenght + 16 + 4 + 200 + 16 ));
mmoInputDFM.Lines.Add(' Font.Name = ''MS Sans Serif''');
mmoInputDFM.Lines.Add(' Position = poOwnerFormCenter');
mmoInputDFM.Lines.Add(' ExplicitWidth = 383');
mmoInputDFM.Lines.Add(' ExplicitHeight = 162');
mmoInputDFM.Lines.Add(' PixelsPerInch = 96');
mmoInputDFM.Lines.Add(' TextHeight = 13');
mmoInputDFM.Lines.Add(' inherited pnlMain: TPanel');
mmoInputDFM.Lines.Add(' Width = 357');
mmoInputDFM.Lines.Add(' Height = 67');
mmoInputDFM.Lines.Add(' Color = clWindow');
mmoInputDFM.Lines.Add(' ParentBackground = True');
mmoInputDFM.Lines.Add(' ExplicitWidth = 373');
mmoInputDFM.Lines.Add(' ExplicitHeight = 67');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
mmoInputDFM.Lines.Add(' object lbl' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TLabel');
mmoInputDFM.Lines.Add(' Left = ' + IntToStr(32 + vMaxCaptionLenght-Canvas.TextWidth( strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1] )) );
mmoInputDFM.Lines.Add(' Top = ' + (6+(vOrder*22)).ToString);
mmoInputDFM.Lines.Add(' Width = ' + IntToStr(Canvas.TextWidth(strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1]) + 16) );
mmoInputDFM.Lines.Add(' Height = 13');
mmoInputDFM.Lines.Add(' Alignment = taRightJustify');
mmoInputDFM.Lines.Add(' BiDiMode = bdLeftToRight');
mmoInputDFM.Lines.Add(' Caption = ' + QuotedStr(strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1]) );
mmoInputDFM.Lines.Add(' Font.Charset = DEFAULT_CHARSET');
mmoInputDFM.Lines.Add(' Font.Color = clWindowText');
mmoInputDFM.Lines.Add(' Font.Height = -11');
mmoInputDFM.Lines.Add(' Font.Name = ''MS Sans Serif''');
mmoInputDFM.Lines.Add(' Font.Style = [fsBold]');
mmoInputDFM.Lines.Add(' ParentBiDiMode = False');
mmoInputDFM.Lines.Add(' ParentFont = False');
mmoInputDFM.Lines.Add(' end');
Inc(vOrder);
end;
end;
vOrder := 0;
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Edit') then
begin
mmoInputDFM.Lines.Add(' object edt' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TEdit');
mmoInputDFM.Lines.Add(' Height = 21');
end
else
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Memo') then
begin
mmoInputDFM.Lines.Add(' object mmo' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TMemo');
mmoInputDFM.Lines.Add(' Height = 21');
end
else
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'ComboBox') then
begin
mmoInputDFM.Lines.Add(' object cbb' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TComboBox');
mmoInputDFM.Lines.Add(' Height = 21');
end
else
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'CheckBox') then
begin
mmoInputDFM.Lines.Add(' object chk' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TCheckBox');
mmoInputDFM.Lines.Add(' Height = 17');
end;
mmoInputDFM.Lines.Add(' Left = ' + IntToStr(32 + vMaxCaptionLenght + 16 + 4));
mmoInputDFM.Lines.Add(' Width = 200');
mmoInputDFM.Lines.Add(' TabOrder = ' + vOrder.ToString);
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'CheckBox') then
begin
mmoInputDFM.Lines.Add(' Top = ' + (3+(vOrder*23)).ToString);
mmoInputDFM.Lines.Add(' end');
end
else
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] <> 'CheckBox') then
begin
mmoInputDFM.Lines.Add(' Top = ' + (3+(vOrder*22)).ToString);
// mmoInputDFM.Lines.Add(' thsAlignment = taLeftJustify');
// mmoInputDFM.Lines.Add(' thsColorActive = clSkyBlue');
// mmoInputDFM.Lines.Add(' thsColorRequiredData = 7367916');
// mmoInputDFM.Lines.Add(' thsTabEnterKeyJump = True');
// if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[0])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[1])
// then
// mmoInputDFM.Lines.Add(' thsInputDataType = itString')
// else
// if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[2])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[3])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[4])
// then
// mmoInputDFM.Lines.Add(' thsInputDataType = itInteger')
// else
// if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[5])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[6])
// then
// mmoInputDFM.Lines.Add(' thsInputDataType = itFloat')
// else
// if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[7])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[8])
// or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[9])
// then
// mmoInputDFM.Lines.Add(' thsInputDataType = itFloat');
// mmoInputDFM.Lines.Add(' thsCaseUpLowSupportTr = True');
// mmoInputDFM.Lines.Add(' thsDecimalDigit = 4');
// mmoInputDFM.Lines.Add(' thsRequiredData = True');
// mmoInputDFM.Lines.Add(' thsDoTrim = True');
// mmoInputDFM.Lines.Add(' thsActiveYear = 2018');
mmoInputDFM.Lines.Add(' end');
end;
Inc(vOrder);
end;
end;
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add(' inherited pnlBottom: TPanel');
mmoInputDFM.Lines.Add(' Top = 71');
mmoInputDFM.Lines.Add(' Width = 373');
mmoInputDFM.Lines.Add(' ExplicitTop = 71');
mmoInputDFM.Lines.Add(' ExplicitWidth = 373');
mmoInputDFM.Lines.Add(' inherited btnAccept: TButton');
mmoInputDFM.Lines.Add(' Left = 164');
mmoInputDFM.Lines.Add(' ExplicitLeft = 164');
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add(' inherited btnDelete: TButton');
mmoInputDFM.Lines.Add(' Left = 60');
mmoInputDFM.Lines.Add(' ExplicitLeft = 60');
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add(' inherited btnClose: TButton');
mmoInputDFM.Lines.Add(' Left = 268');
mmoInputDFM.Lines.Add(' ExplicitLeft = 268');
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add(' inherited stbBase: TStatusBar');
mmoInputDFM.Lines.Add(' Top = 115');
mmoInputDFM.Lines.Add(' Width = 377');
mmoInputDFM.Lines.Add(' ExplicitTop = 115');
mmoInputDFM.Lines.Add(' ExplicitWidth = 377');
mmoInputDFM.Lines.Add(' end');
mmoInputDFM.Lines.Add('end');
mmoInputDFM.Lines.EndUpdate;
end;
procedure TfrmMainClassGenerator.btnAddInputPASToMemoClick(Sender: TObject);
var
n1: Integer;
begin
mmoInputPAS.Lines.Clear;
mmoInputPAS.Lines.BeginUpdate;
mmoInputPAS.Lines.Add('unit ufrm' + edtClassType.Text + ';');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('interface');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('uses');
mmoInputPAS.Lines.Add(' Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,');
mmoInputPAS.Lines.Add(' Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.Menus,');
mmoInputPAS.Lines.Add(' Vcl.AppEvnts, System.ImageList, Vcl.ImgList, Vcl.Samples.Spin,');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add(' Ths.Erp.Helper.BaseTypes,');
mmoInputPAS.Lines.Add(' Ths.Erp.Helper.Edit,');
mmoInputPAS.Lines.Add(' Ths.Erp.Helper.ComboBox,');
mmoInputPAS.Lines.Add(' Ths.Erp.Helper.Memo,');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add(' ufrmBase, ufrmBaseInputDB;');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('type');
mmoInputPAS.Lines.Add(' Tfrm' + edtInputFormName.Text + ' = class(TfrmBaseInputDB)');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
mmoInputPAS.Lines.Add(' lbl' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TLabel;');
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Edit') then
mmoInputPAS.Lines.Add(' edt' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TEdit;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Memo') then
mmoInputPAS.Lines.Add(' mmo' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TMemo;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'ComboBox') then
mmoInputPAS.Lines.Add(' cbb' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TComboBox;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'CheckBox') then
mmoInputPAS.Lines.Add(' chk' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ': TCheckBox;');
end;
end;
mmoInputPAS.Lines.Add(' procedure FormCreate(Sender: TObject);override;');
mmoInputPAS.Lines.Add(' procedure RefreshData();override;');
mmoInputPAS.Lines.Add(' procedure btnAcceptClick(Sender: TObject);override;');
mmoInputPAS.Lines.Add(' private');
mmoInputPAS.Lines.Add(' public');
mmoInputPAS.Lines.Add(' protected');
mmoInputPAS.Lines.Add(' published');
mmoInputPAS.Lines.Add(' end;');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('implementation');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('uses');
mmoInputPAS.Lines.Add(' Ths.Erp.Database.Singleton,');
mmoInputPAS.Lines.Add(' ' + PROJECT_UNITNAME + edtClassType.Text + ';');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('{$R *.dfm}');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('procedure Tfrm' + edtInputFormName.Text + '.FormCreate(Sender: TObject);');
mmoInputPAS.Lines.Add('begin');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Edit') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.SetControlProperty(Table.TableName, edt' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ');')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Memo') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.SetControlProperty(Table.TableName, mmo' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ');')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'ComboBox') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.SetControlProperty(Table.TableName, cbb' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + ');');
end;
end;
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add(' inherited;');
mmoInputPAS.Lines.Add('end;');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('procedure Tfrm' + edtInputFormName.Text + '.RefreshData();');
mmoInputPAS.Lines.Add('begin');
mmoInputPAS.Lines.Add(' //control içeriğini table class ile doldur');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Edit') then
mmoInputPAS.Lines.Add(' edt' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text := ' +
'FormatedVariantVal(T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.FieldType, T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value);')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Memo') then
mmoInputPAS.Lines.Add(' mmo' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text := ' +
'FormatedVariantVal(T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.FieldType, T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value);')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'ComboBox') then
mmoInputPAS.Lines.Add(' cbb' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text := ' +
'FormatedVariantVal(T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.FieldType, T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value);')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'CheckBox') then
mmoInputPAS.Lines.Add(' chk' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Checked := ' +
'FormatedVariantVal(T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.FieldType, T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value);')
end;
end;
mmoInputPAS.Lines.Add('end;');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('procedure Tfrm' + edtInputFormName.Text + '.btnAcceptClick(Sender: TObject);');
mmoInputPAS.Lines.Add('begin');
mmoInputPAS.Lines.Add(' if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then');
mmoInputPAS.Lines.Add(' begin');
mmoInputPAS.Lines.Add(' if (ValidateInput) then');
mmoInputPAS.Lines.Add(' begin');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_GUI_CONTROL, n1] = 'Yes' then
begin
if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Edit') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value := edt' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'Memo') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value := mmo' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'ComboBox') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value := cbb' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Text;')
else if (strngrdList.Cells[COL_CONTROL_TYPE, n1] = 'CheckBox') then
mmoInputPAS.Lines.Add(' T' + edtClassType.Text + '(Table).' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Value := chk' + strngrdList.Cells[COL_PROPERTY_NAME, n1] + '.Checked;')
end;
end;
mmoInputPAS.Lines.Add(' inherited;');
mmoInputPAS.Lines.Add(' end;');
mmoInputPAS.Lines.Add(' end');
mmoInputPAS.Lines.Add(' else');
mmoInputPAS.Lines.Add(' inherited;');
mmoInputPAS.Lines.Add('end;');
mmoInputPAS.Lines.Add('');
mmoInputPAS.Lines.Add('end.');
mmoInputPAS.Lines.EndUpdate;
end;
procedure TfrmMainClassGenerator.btnAddOutputDFMToMemoClick(Sender: TObject);
begin
mmoOutputDFM.Clear;
mmoOutputDFM.Lines.BeginUpdate;
mmoOutputDFM.Lines.Add('inherited frm' + edtOutputFormName.Text + ': Tfrm' + edtOutputFormName.Text);
mmoOutputDFM.Lines.Add(' Caption = ' + QuotedStr(edtOutputFormCaption.Text));
mmoOutputDFM.Lines.Add(' ClientHeight = 311');
mmoOutputDFM.Lines.Add(' ClientWidth = 548');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 564');
mmoOutputDFM.Lines.Add(' ExplicitHeight = 350');
mmoOutputDFM.Lines.Add(' PixelsPerInch = 96');
mmoOutputDFM.Lines.Add(' TextHeight = 13');
mmoOutputDFM.Lines.Add(' inherited pnlMain: TPanel');
mmoOutputDFM.Lines.Add(' Width = 544');
mmoOutputDFM.Lines.Add(' Height = 245');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 544');
mmoOutputDFM.Lines.Add(' ExplicitHeight = 245');
mmoOutputDFM.Lines.Add(' inherited splLeft: TSplitter');
mmoOutputDFM.Lines.Add(' Height = 128');
mmoOutputDFM.Lines.Add(' ExplicitHeight = 219');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited splHeader: TSplitter');
mmoOutputDFM.Lines.Add(' Width = 542');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 554');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited pnlLeft: TPanel');
mmoOutputDFM.Lines.Add(' Height = 125');
mmoOutputDFM.Lines.Add(' ExplicitHeight = 125');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited pnlHeader: TPanel');
mmoOutputDFM.Lines.Add(' Width = 538');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 538');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited pnlContent: TPanel');
mmoOutputDFM.Lines.Add(' Width = 433');
mmoOutputDFM.Lines.Add(' Height = 125');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 433');
mmoOutputDFM.Lines.Add(' ExplicitHeight = 125');
mmoOutputDFM.Lines.Add(' inherited dbgrdBase: TDBGrid');
mmoOutputDFM.Lines.Add(' Width = 431');
mmoOutputDFM.Lines.Add(' Height = 123');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited pnlButtons: TPanel');
mmoOutputDFM.Lines.Add(' Top = 165');
mmoOutputDFM.Lines.Add(' Width = 542');
mmoOutputDFM.Lines.Add(' ExplicitTop = 165');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 542');
mmoOutputDFM.Lines.Add(' inherited flwpnlLeft: TFlowPanel');
mmoOutputDFM.Lines.Add(' Width = 233');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 233');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited flwpnlRight: TFlowPanel');
mmoOutputDFM.Lines.Add(' Left = 438');
mmoOutputDFM.Lines.Add(' Width = 104');
mmoOutputDFM.Lines.Add(' ExplicitLeft = 438');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 104');
mmoOutputDFM.Lines.Add(' inherited imgFilterRemove: TImage');
mmoOutputDFM.Lines.Add(' Left = 72');
mmoOutputDFM.Lines.Add(' ExplicitLeft = 72');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited pnlBottom: TPanel');
mmoOutputDFM.Lines.Add(' Top = 249');
mmoOutputDFM.Lines.Add(' Width = 544');
mmoOutputDFM.Lines.Add(' ExplicitTop = 249');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 544');
mmoOutputDFM.Lines.Add(' inherited btnAccept: TButton');
mmoOutputDFM.Lines.Add(' Left = 335');
mmoOutputDFM.Lines.Add(' ExplicitLeft = 335');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited btnDelete: TButton');
mmoOutputDFM.Lines.Add(' Left = 231');
mmoOutputDFM.Lines.Add(' ExplicitLeft = 231');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited btnClose: TButton');
mmoOutputDFM.Lines.Add(' Left = 439');
mmoOutputDFM.Lines.Add(' ExplicitLeft = 439');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add(' inherited stbBase: TStatusBar');
mmoOutputDFM.Lines.Add(' Top = 293');
mmoOutputDFM.Lines.Add(' Width = 548');
mmoOutputDFM.Lines.Add(' ExplicitTop = 293');
mmoOutputDFM.Lines.Add(' ExplicitWidth = 548');
mmoOutputDFM.Lines.Add(' end');
mmoOutputDFM.Lines.Add('end');
mmoOutputDFM.Lines.EndUpdate;
end;
procedure TfrmMainClassGenerator.btnAddOutputPASToMemoClick(Sender: TObject);
begin
mmoOutputPAS.Lines.Clear;
mmoOutputPAS.Lines.BeginUpdate;
mmoOutputPAS.Lines.Add('unit ufrm' + edtOutputFormName.Text + ';');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('interface');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('uses');
mmoOutputPAS.Lines.Add(' System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Data.DB,');
mmoOutputPAS.Lines.Add(' Vcl.DBGrids, Vcl.Menus, Vcl.AppEvnts, Vcl.ComCtrls, Vcl.StdCtrls,');
mmoOutputPAS.Lines.Add(' Vcl.ExtCtrls, Vcl.Grids, System.ImageList, Vcl.ImgList, Vcl.Samples.Spin,');
mmoOutputPAS.Lines.Add(' ufrmBase, ufrmBaseDBGrid;');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('type');
mmoOutputPAS.Lines.Add(' Tfrm' + edtOutputFormName.Text + ' = class(TfrmBaseDBGrid)');
mmoOutputPAS.Lines.Add(' private');
mmoOutputPAS.Lines.Add(' protected');
mmoOutputPAS.Lines.Add(' function CreateInputForm(pFormMode: TInputFormMod):TForm; override;');
mmoOutputPAS.Lines.Add(' public');
mmoOutputPAS.Lines.Add(' published');
mmoOutputPAS.Lines.Add(' end;');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('implementation');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('uses');
mmoOutputPAS.Lines.Add(' Ths.Erp.Database.Singleton,');
mmoOutputPAS.Lines.Add(' ufrm' + edtInputFormName.Text + ',');
mmoOutputPAS.Lines.Add(' ' + PROJECT_UNITNAME + edtClassType.Text + ';');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('{$R *.dfm}');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('{ Tfrm' + edtOutputFormName.Text + ' }');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('function Tfrm' + edtOutputFormName.Text + '.CreateInputForm(pFormMode: TInputFormMod): TForm;');
mmoOutputPAS.Lines.Add('begin');
mmoOutputPAS.Lines.Add(' Result:=nil;');
mmoOutputPAS.Lines.Add(' if (pFormMode = ifmRewiev) then');
mmoOutputPAS.Lines.Add(' Result := Tfrm' + edtInputFormName.Text + '.Create(Application, Self, Table.Clone(), True, pFormMode)');
mmoOutputPAS.Lines.Add(' else if (pFormMode = ifmNewRecord) then');
mmoOutputPAS.Lines.Add(' Result := Tfrm' + edtInputFormName.Text + '.Create(Application, Self, T' + edtClassType.Text + '.Create(Table.Database), True, pFormMode)');
mmoOutputPAS.Lines.Add(' else if (pFormMode = ifmCopyNewRecord) then');
mmoOutputPAS.Lines.Add(' Result := Tfrm' + edtInputFormName.Text + '.Create(Application, Self, Table.Clone(), True, pFormMode);');
mmoOutputPAS.Lines.Add('end;');
mmoOutputPAS.Lines.Add('');
mmoOutputPAS.Lines.Add('end.');
mmoOutputPAS.Lines.EndUpdate;
end;
procedure TfrmMainClassGenerator.btnAddClassToMemoClick(Sender: TObject);
var
n1: Integer;
begin
mmoClass.Lines.BeginUpdate;
if strngrdList.Cells[COL_ROW_NO, strngrdList.RowCount-1] = '' then
strngrdList.RowCount := strngrdList.RowCount-1;
mmoClass.Clear;
mmoClass.Lines.Add('unit ' + PROJECT_UNITNAME + edtClassType.Text + ';');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('interface');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('uses');
mmoClass.Lines.Add(' SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,');
mmoClass.Lines.Add(' FireDAC.Stan.Param, System.Variants, Data.DB,');
mmoClass.Lines.Add(' Ths.Erp.Database,');
mmoClass.Lines.Add(' Ths.Erp.Database.Table,');
mmoClass.Lines.Add(' Ths.Erp.Database.Table.Field;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('type');
mmoClass.Lines.Add(' T' + edtClassType.Text + ' = class(TTable)');
mmoClass.Lines.Add(' private');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ': TFieldDB;');
mmoClass.Lines.Add(' protected');
mmoClass.Lines.Add(' published');
mmoClass.Lines.Add(' constructor Create(OwnerDatabase:TDatabase);override;');
mmoClass.Lines.Add(' public');
mmoClass.Lines.Add(' procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;');
mmoClass.Lines.Add(' procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;');
mmoClass.Lines.Add(' procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;');
mmoClass.Lines.Add(' procedure Update(pPermissionControl: Boolean=True); override;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' function Clone():TTable;override;');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' Property ' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ': TFieldDB read F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ' write F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ';');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('implementation');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('uses');
mmoClass.Lines.Add(' Ths.Erp.Constants,');
mmoClass.Lines.Add(' Ths.Erp.Database.Singleton;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('constructor T' + edtClassType.Text + '.Create(OwnerDatabase:TDatabase);');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' inherited Create(OwnerDatabase);');
mmoClass.Lines.Add(' TableName := ' + QuotedStr(edtTableName.Text) + ';');
mmoClass.Lines.Add(' SourceCode := ' + QuotedStr(edtSourceCode.Text) + ';');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
begin
if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[0])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[1])
then
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ' := TFieldDB.Create(' + QuotedStr(strngrdList.Cells[COL_FIELD_NAME,n1]) + ', ' + strngrdList.Cells[COL_FIELD_TYPE,n1] + ', '''');')
else
if (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[2])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[3])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[4])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[5])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[6])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[7])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[8])
or (strngrdList.Cells[COL_FIELD_TYPE, n1] = cbbFieldType.Items.Strings[9])
then
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ' := TFieldDB.Create(' + QuotedStr(strngrdList.Cells[COL_FIELD_NAME,n1]) + ', ' + strngrdList.Cells[COL_FIELD_TYPE,n1] + ', 0);')
else
if (strngrdList.Cells[3, n1] = cbbFieldType.Items.Strings[10]) then
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ' := TFieldDB.Create(' + QuotedStr(strngrdList.Cells[COL_FIELD_NAME,n1]) + ', ' + strngrdList.Cells[COL_FIELD_TYPE,n1] + ', False);')
end;
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('procedure T' + edtClassType.Text + '.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' if IsAuthorized(ptRead, pPermissionControl) then');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' with QueryOfDS do');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' SQL.Clear;');
mmoClass.Lines.Add(' SQL.Text := Database.GetSQLSelectCmd(TableName, [');
mmoClass.Lines.Add(' TableName + ''.'' + Self.Id.FieldName,');
for n1 := 1 to strngrdList.RowCount-1 do
begin
mmoClass.Lines.Add(' TableName + ''.'' + F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName,');
if n1 = strngrdList.RowCount-1 then
mmoClass.Lines.Strings[mmoClass.Lines.Count-1] := LeftStr(mmoClass.Lines.Strings[mmoClass.Lines.Count-1], Length(mmoClass.Lines.Strings[mmoClass.Lines.Count-1])-1);
end;
mmoClass.Lines.Add(' ]) +');
mmoClass.Lines.Add(' ''WHERE 1=1 '' + pFilter;');
mmoClass.Lines.Add(' Open;');
mmoClass.Lines.Add(' Active := True;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := ''ID'';');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' Self.DataSource.DataSet.FindField(F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName).DisplayLabel := ''' + strngrdList.Cells[COL_GRID_COL_CAPTION,n1] + ''';');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('procedure T' + edtClassType.Text + '.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' if IsAuthorized(ptRead, pPermissionControl) then');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' if (pLock) then');
mmoClass.Lines.Add(' pFilter := pFilter + '' FOR UPDATE NOWAIT; '';');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' with QueryOfList do');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' SQL.Text := Database.GetSQLSelectCmd(TableName, [');
mmoClass.Lines.Add(' TableName + ''.'' + Self.Id.FieldName,');
for n1 := 1 to strngrdList.RowCount-1 do
begin
mmoClass.Lines.Add(' TableName + ''.'' + F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName,');
if n1 = strngrdList.RowCount-1 then
mmoClass.Lines.Strings[mmoClass.Lines.Count-1] := LeftStr(mmoClass.Lines.Strings[mmoClass.Lines.Count-1], Length(mmoClass.Lines.Strings[mmoClass.Lines.Count-1])-1);
end;
mmoClass.Lines.Add(' ]) +');
mmoClass.Lines.Add(' ''WHERE 1=1 '' + pFilter;');
mmoClass.Lines.Add(' Open;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' FreeListContent();');
mmoClass.Lines.Add(' List.Clear;');
mmoClass.Lines.Add(' while NOT EOF do');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.Value := FormatedVariantVal(FieldByName(F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName).DataType, FieldByName(F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName).Value);');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' List.Add(Self.Clone());');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' Next;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('procedure T' + edtClassType.Text + '.Insert(out pID: Integer; pPermissionControl: Boolean=True);');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' if IsAuthorized(ptAddRecord, pPermissionControl) then');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' with QueryOfInsert do');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' SQL.Clear;');
mmoClass.Lines.Add(' SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [');
for n1 := 1 to strngrdList.RowCount-1 do
begin
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName,');
if n1 = strngrdList.RowCount-1 then
mmoClass.Lines.Strings[mmoClass.Lines.Count-1] := LeftStr(mmoClass.Lines.Strings[mmoClass.Lines.Count-1], Length(mmoClass.Lines.Strings[mmoClass.Lines.Count-1])-1);
end;
mmoClass.Lines.Add(' ]);');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' NewParamForQuery(QueryOfInsert, F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ');');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' Open;');
mmoClass.Lines.Add(' if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then');
mmoClass.Lines.Add(' pID := Fields.FieldByName(Self.Id.FieldName).AsInteger');
mmoClass.Lines.Add(' else');
mmoClass.Lines.Add(' pID := 0;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' EmptyDataSet;');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add(' Self.notify;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('procedure T' + edtClassType.Text + '.Update(pPermissionControl: Boolean=True);');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' if IsAuthorized(ptUpdate, pPermissionControl) then');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' with QueryOfUpdate do');
mmoClass.Lines.Add(' begin');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' SQL.Clear;');
mmoClass.Lines.Add(' SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [');
for n1 := 1 to strngrdList.RowCount-1 do
begin
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.FieldName,');
if n1 = strngrdList.RowCount-1 then
mmoClass.Lines.Strings[mmoClass.Lines.Count-1] := LeftStr(mmoClass.Lines.Strings[mmoClass.Lines.Count-1], Length(mmoClass.Lines.Strings[mmoClass.Lines.Count-1])-1);
end;
mmoClass.Lines.Add(' ]);');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' NewParamForQuery(QueryOfUpdate, F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ');');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' NewParamForQuery(QueryOfUpdate, Id);');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' ExecSQL;');
mmoClass.Lines.Add(' Close;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add(' Self.notify;');
mmoClass.Lines.Add(' end;');
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('function T' + edtClassType.Text + '.Clone():TTable;');
mmoClass.Lines.Add('begin');
mmoClass.Lines.Add(' Result := T' + edtClassType.Text + '.Create(Database);');
mmoClass.Lines.Add('');
mmoClass.Lines.Add(' Self.Id.Clone(T' + edtClassType.Text + '(Result).Id);');
mmoClass.Lines.Add('');
for n1 := 1 to strngrdList.RowCount-1 do
mmoClass.Lines.Add(' F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + '.Clone(T' + edtClassType.Text + '(Result).F' + strngrdList.Cells[COL_PROPERTY_NAME,n1] + ');');
mmoClass.Lines.Add('end;');
mmoClass.Lines.Add('');
mmoClass.Lines.Add('end.');
mmoClass.Lines.EndUpdate;
end;
procedure TfrmMainClassGenerator.btnClearListsClick(Sender: TObject);
begin
if MessageBox(Handle, PWideChar('Are you sure you want to clear Grid?'), PWideChar('Confirmation'), MB_YESNO) <> mrYes then
Exit;
ClearGridList();
end;
procedure TfrmMainClassGenerator.btnEditFieldClick(Sender: TObject);
begin
strngrdList.Cells[COL_ROW_NO, FRowNo] := FRowNo.ToString;
strngrdList.Cells[COL_PROPERTY_NAME, FRowNo] := edtpropertyname.Text;
strngrdList.Cells[COL_FIELD_NAME, FRowNo] := edtFieldName.Text;
strngrdList.Cells[COL_FIELD_TYPE, FRowNo] := cbbFieldType.Text;
strngrdList.Cells[COL_GRID_COL_CAPTION, FRowNo] := edtCaption.Text;
strngrdList.Cells[COL_INPUT_LABEL_CAPTION, FRowNo] := edtInputLabelCaption.Text;
if chkIsGUIControl.Checked then
begin
strngrdList.Cells[COL_GUI_CONTROL, FRowNo] := 'Yes';
strngrdList.Cells[COL_CONTROL_TYPE, FRowNo] := cbbControlType.Text;
end
else
begin
strngrdList.Cells[COL_GUI_CONTROL, FRowNo] := 'No';
strngrdList.Cells[COL_CONTROL_TYPE, FRowNo] := '';
end;
edtpropertyname.Clear;
edtFieldName.Clear;
cbbFieldType.ItemIndex := -1;
edtCaption.Clear;
edtInputLabelCaption.Clear;
chkIsGUIControl.Checked := False;
chkIsGUIControlClick(chkIsGUIControl);
cbbControlType.ItemIndex := -1;
edtpropertyname.SetFocus;
strngrdList.Top := strngrdList.RowCount-1;
btnEditField.Enabled := False;
FRowNo := -1;
end;
procedure TfrmMainClassGenerator.btnSaveToFilesClick(Sender: TObject);
var
vPath, vFileNameClass, vFileNameOutput, vFileNameInput: string;
vFileDPR: TStringList;
n1: Integer;
begin
if MessageBox(Handle, PWideChar('Are you sure you want to Save Content to File?'), PWideChar('Confirmation'), MB_YESNO) <> mrYes then
Exit;
if edtMainProjectDirectory.Text <> '' then
begin
btnAddClassToMemo.Click;
btnAddOutputDFMToMemo.Click;
btnAddOutputPASToMemo.Click;
btnAddInputDFMToMemo.Click;
btnAddInputPASToMemo.Click;
vPath := ExtractFilePath(edtMainProjectDirectory.Text);
vFileNameClass := vPath + 'BackEnd\' + PROJECT_UNITNAME + edtClassType.Text + '.pas';
vFileNameOutput := vPath + 'Forms\OutputForms\DbGrid\ufrm' + edtOutputFormName.Text + '.pas';
vFileNameInput := vPath + 'Forms\InputForms\ufrm' + edtInputFormName.Text + '.pas';
mmoClass.Lines.SaveToFile(vFileNameClass);
mmoOutputDFM.Lines.SaveToFile(vPath + 'Forms\OutputForms\DbGrid\ufrm' + edtOutputFormName.Text + '.dfm');
mmoOutputPAS.Lines.SaveToFile(vFileNameOutput);
mmoInputDFM.Lines.SaveToFile(vPath + 'Forms\InputForms\ufrm' + edtInputFormName.Text + '.dfm');
mmoInputPAS.Lines.SaveToFile(vFileNameInput);
vFileDPR := TStringList.Create;
try
vFileDPR.LoadFromFile(edtMainProjectDirectory.Text);
//projede kullanılan dosyalardan sonraki son satır numarasını bul
n1 := vFileDPR.IndexOf('{$R *.res}');
//son elemanın noktalı virgül bilgisini virgüle çevir.
vFileDPR.Strings[n1-2] := LeftStr(vFileDPR.Strings[n1-2], Length(vFileDPR.Strings[n1-2])-1) + ',';
//eklenen sınıf, output ve input formlarını projeye dahil et
vFileDPR.Insert(n1-1, ' ufrm' + edtInputFormName.Text + ' in ''Forms\InputForms\' + 'ufrm' + edtInputFormName.Text + '.pas'' {frm' + edtInputFormName.Text + '};');
vFileDPR.Insert(n1-1, ' ufrm' + edtOutputFormName.Text + ' in ''Forms\OutputForms\DbGrid\' + 'ufrm' + edtOutputFormName.Text + '.pas'' {frm' + edtOutputFormName.Text + '},');
vFileDPR.Insert(n1-1, ' ' + PROJECT_UNITNAME + edtClassType.Text + ' in ''BackEnd\' + PROJECT_UNITNAME + edtClassType.Text + '.pas'',');
vFileDPR.SaveToFile(edtMainProjectDirectory.Text);
finally
vFileDPR.Free;
end;
end
else
raise Exception.Create('Main Project File *.dpr is missing');
end;
procedure TfrmMainClassGenerator.chkIsGUIControlClick(Sender: TObject);
begin
if chkIsGUIControl.Checked then
begin
lblControlType.Visible := True;
cbbControlType.Visible := True;
end
else
begin
lblControlType.Visible := False;
cbbControlType.Visible := False;
end;
end;
procedure TfrmMainClassGenerator.ClearGridList;
var
nr: Integer;
nc: Integer;
begin
cbbFieldType.Items.Add('ftString');
cbbFieldType.Items.Add('ftWideString');
cbbFieldType.Items.Add('ftInteger');
cbbFieldType.Items.Add('ftLongInt');
cbbFieldType.Items.Add('ftWord');
cbbFieldType.Items.Add('ftFloat');
cbbFieldType.Items.Add('ftCurrency');
cbbFieldType.Items.Add('ftDate');
cbbFieldType.Items.Add('ftTime');
cbbFieldType.Items.Add('ftDateTime');
cbbFieldType.Items.Add('ftBoolean');
cbbControlType.Clear;
cbbControlType.Items.Add('Edit');
cbbControlType.Items.Add('Memo');
cbbControlType.Items.Add('ComboBox');
cbbControlType.Items.Add('CheckBox');
edtpropertyname.Clear;
edtFieldName.Clear;
cbbFieldType.ItemIndex := -1;
edtCaption.Clear;
chkIsGUIControl.Checked := False;
chkIsGUIControlClick(chkIsGUIControl);
cbbControlType.ItemIndex := -1;
for nr := 0 to strngrdList.RowCount-1 do
for nc := 0 to strngrdList.ColCount-1 do
strngrdList.Cells[nc, nr] := '';
strngrdList.RowCount := 2;
strngrdList.ColCount := 8;
strngrdList.FixedColor := clGray;
strngrdList.FixedRows := 1;
strngrdList.FixedColor := 1;
strngrdList.ColWidths[COL_ROW_NO] := 25;
strngrdList.ColWidths[COL_PROPERTY_NAME] := 140;
strngrdList.ColWidths[COL_FIELD_NAME] := 140;
strngrdList.ColWidths[COL_FIELD_TYPE] := 140;
strngrdList.ColWidths[COL_GRID_COL_CAPTION] := 150;
strngrdList.ColWidths[COL_INPUT_LABEL_CAPTION] := 150;
strngrdList.ColWidths[COL_GUI_CONTROL] := 50;
strngrdList.ColWidths[COL_CONTROL_TYPE] := 150;
strngrdList.Cells[COL_ROW_NO,0] := 'No';
strngrdList.Cells[COL_PROPERTY_NAME,0] := 'Property Name';
strngrdList.Cells[COL_FIELD_NAME,0] := 'Field Name';
strngrdList.Cells[COL_FIELD_TYPE,0] := 'Field Type';
strngrdList.Cells[COL_GRID_COL_CAPTION,0] := 'Column Caption';
strngrdList.Cells[COL_INPUT_LABEL_CAPTION,0] := 'Input Caption';
strngrdList.Cells[COL_GUI_CONTROL,0] := 'GUI Control?';
strngrdList.Cells[COL_CONTROL_TYPE,0] := 'Control Type';
strngrdList.Cells[COL_ROW_NO,1] := '';
strngrdList.Cells[COL_PROPERTY_NAME,1] := '';
strngrdList.Cells[COL_FIELD_NAME,1] := '';
strngrdList.Cells[COL_FIELD_TYPE,1] := '';
strngrdList.Cells[COL_GRID_COL_CAPTION,1] := '';
strngrdList.Cells[COL_INPUT_LABEL_CAPTION,1] := '';
strngrdList.Cells[COL_GUI_CONTROL,1] := '';
strngrdList.Cells[COL_CONTROL_TYPE,1] := '';
end;
procedure TfrmMainClassGenerator.edtMainProjectDirectoryDblClick(
Sender: TObject);
var
vOD: TOpenDialog;
begin
vOD := TOpenDialog.Create(Self);
try
vOD.InitialDir := ExtractFilePath(Application.ExeName);
vOD.Filter := 'Delphi Project File|*.dpr';
if vOD.Execute(Self.Handle) then
begin
edtMainProjectDirectory.Text := vOD.FileName;
end;
finally
vOD.Free;
end;
end;
procedure TfrmMainClassGenerator.FormCreate(Sender: TObject);
procedure AddRow(pPropName, pFieldName, pDataType, pGridCaption, pInputLabelCaption: string; pIsGUI: Boolean; pControlType: string);
begin
strngrdList.Cells[COL_ROW_NO,strngrdList.RowCount-1] := (strngrdList.RowCount-1).ToString;;
strngrdList.Cells[COL_PROPERTY_NAME,strngrdList.RowCount-1] := pPropName;
strngrdList.Cells[COL_FIELD_NAME,strngrdList.RowCount-1] := pFieldName;
strngrdList.Cells[COL_FIELD_TYPE,strngrdList.RowCount-1] := pDataType;
strngrdList.Cells[COL_GRID_COL_CAPTION,strngrdList.RowCount-1] := pGridCaption;
strngrdList.Cells[COL_INPUT_LABEL_CAPTION,strngrdList.RowCount-1] := pInputLabelCaption;
if pIsGUI then
strngrdList.Cells[COL_GUI_CONTROL,strngrdList.RowCount-1] := 'Yes'
else
strngrdList.Cells[COL_GUI_CONTROL,strngrdList.RowCount-1] := 'No';
strngrdList.Cells[COL_CONTROL_TYPE,strngrdList.RowCount-1] := pControlType;
strngrdList.RowCount := strngrdList.RowCount + 1;
end;
begin
ClearGridList;
edtMainProjectDirectory.ReadOnly := True;
btnEditField.Enabled := False;
mmoClass.Clear;
mmoOutputDFM.Clear;
mmoOutputPAS.Clear;
mmoInputDFM.Clear;
mmoInputPAS.Clear;
end;
procedure TfrmMainClassGenerator.mmoClassKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Sender is TMemo then
begin
if (Key = Word('A')) and (ssCtrl in Shift) then
TMemo(Sender).SelectAll
else if (Key = Word('C')) and (ssCtrl in Shift) then
TMemo(Sender).CopyToClipboard;
end;
end;
procedure TfrmMainClassGenerator.mniDeleteRowClick(Sender: TObject);
var
n1: Integer;
begin
for n1 := 0 to strngrdList.ColCount-1 do
strngrdList.Cells[n1, strngrdList.Row] := '';
for n1 := 1 to strngrdList.RowCount-1 do
begin
strngrdList.Cells[COL_ROW_NO, n1] := '';
if (strngrdList.Cells[COL_PROPERTY_NAME, n1] <> '') then
strngrdList.Cells[COL_ROW_NO, n1] := n1.ToString;
end;
ReFillAndSort;
end;
procedure TfrmMainClassGenerator.mniLoadFromFileClick(Sender: TObject);
var
nR: Integer;
vXML: IXMLDocument;
NodeRoot, NodeRow, NodeData: IXMLNode;
function getNodeValue(vNodeName: string): string;
begin
NodeData := NodeRow.ChildNodes.FindNode(vNodeName);
Result := NodeData.Text;
end;
begin
vXML := TXMLDocument.Create(nil);
if FileExists(ExtractFilePath(Application.ExeName) + '\setting.xml', False) then
begin
vXML.LoadFromFile(ExtractFilePath(Application.ExeName) + '\setting.xml');
vXML.Active := True;
try
ClearGridList;
NodeRoot := vXML.ChildNodes.FindNode('GridSetting');
NodeRow := NodeRoot.ChildNodes.FindNode('Header');
edtMainProjectDirectory.Text := getNodeValue('ProjectFile');
edtClassType.Text := getNodeValue('ClassType');
edtTableName.Text := getNodeValue('TableName');
edtSourceCode.Text := getNodeValue('SourceCode');
edtOutputFormName.Text := getNodeValue('OutputFormName');
edtOutputFormCaption.Text := getNodeValue('OutputFormCaption');
edtInputFormName.Text := getNodeValue('InputFormName');
edtInputFormCaption.Text := getNodeValue('InputFormCaption');
for nR := 0 to NodeRoot.ChildNodes.Count-1 do
begin
if NodeRoot.ChildNodes.Get(nR).NodeName = 'Row' then
begin
NodeRow := NodeRoot.ChildNodes.Get(nR);
strngrdList.Cells[COL_ROW_NO, strngrdList.Row] := getNodeValue('RowNo');
strngrdList.Cells[COL_PROPERTY_NAME, strngrdList.Row] := getNodeValue('PropertyName');
strngrdList.Cells[COL_FIELD_NAME, strngrdList.Row] := getNodeValue('FieldName');
strngrdList.Cells[COL_FIELD_TYPE, strngrdList.Row] := getNodeValue('FieldType');
strngrdList.Cells[COL_GRID_COL_CAPTION, strngrdList.Row] := getNodeValue('ColumnCaption');
strngrdList.Cells[COL_INPUT_LABEL_CAPTION, strngrdList.Row] := getNodeValue('InputCaption');
strngrdList.Cells[COL_GUI_CONTROL, strngrdList.Row] := getNodeValue('GuiControl');
strngrdList.Cells[COL_CONTROL_TYPE, strngrdList.Row] := getNodeValue('ControlType');
strngrdList.RowCount := strngrdList.RowCount+1;
strngrdList.Row := strngrdList.Row+1;
end;
end;
strngrdList.Top := strngrdList.RowCount-1;
finally
vXML.Active := False;
// TXMLDocument(vXML).Destroy;
end;
ShowMessage('File saved succesfully');
end;
end;
procedure TfrmMainClassGenerator.mniSaveToFileClick(Sender: TObject);
var
nR: Integer;
nC: Integer;
vXML: TXMLDocument;
NodeRoot, NodeData: IXMLNode;
procedure AddNode(vNodeName, vValue: string);
begin
NodeData := vXML.CreateNode(vNodeName);
NodeData.Text := vValue;
NodeRoot.ChildNodes.Add(NodeData);
end;
begin
vXML := TXMLDocument.Create(nil);
vXML.Options := [doNodeAutoIndent];
vXML.Active := True;
try
vXML.DocumentElement := vXML.CreateNode('GridSetting', ntElement, '');
NodeRoot := vXML.DocumentElement.AddChild('Header');
AddNode('ProjectFile', edtMainProjectDirectory.Text);
AddNode('ClassType', edtClassType.Text);
AddNode('TableName', edtTableName.Text);
AddNode('SourceCode', edtSourceCode.Text);
AddNode('OutputFormName', edtOutputFormName.Text);
AddNode('OutputFormCaption', edtOutputFormCaption.Text);
AddNode('InputFormName', edtInputFormName.Text);
AddNode('InputFormCaption', edtInputFormCaption.Text);
for nR := 1 to strngrdList.RowCount-1 do
begin
if strngrdList.Cells[COL_ROW_NO, nR] <> '' then
NodeRoot := vXML.DocumentElement.AddChild('Row');
for nC := 0 to strngrdList.ColCount-1 do
begin
if strngrdList.Cells[COL_ROW_NO, nR] <> '' then
begin
if nC = COL_ROW_NO then AddNode('RowNo', strngrdList.Cells[nC, nR]);
if nC = COL_PROPERTY_NAME then AddNode('PropertyName', strngrdList.Cells[nC, nR]);
if nC = COL_FIELD_NAME then AddNode('FieldName', strngrdList.Cells[nC, nR]);
if nC = COL_FIELD_TYPE then AddNode('FieldType', strngrdList.Cells[nC, nR]);
if nC = COL_GRID_COL_CAPTION then AddNode('ColumnCaption', strngrdList.Cells[nC, nR]);
if nC = COL_INPUT_LABEL_CAPTION then AddNode('InputCaption', strngrdList.Cells[nC, nR]);
if nC = COL_GUI_CONTROL then AddNode('GuiControl', strngrdList.Cells[nC, nR]);
if nC = COL_CONTROL_TYPE then AddNode('ControlType', strngrdList.Cells[nC, nR]);
end;
end;
end;
vXML.SaveToFile(ExtractFilePath(Application.ExeName) + '\setting.xml');
ShowMessage('File saved succesfully');
finally
vXML.Active := False;
vXML.Free;
end;
end;
procedure TfrmMainClassGenerator.strngrdListDblClick(Sender: TObject);
begin
if strngrdList.Row > 0 then
begin
if strngrdList.Cells[strngrdList.Col, strngrdList.Row] <> '' then
begin
edtpropertyname.Text := strngrdList.Cells[COL_PROPERTY_NAME, strngrdList.Row];
edtFieldName.Text := strngrdList.Cells[COL_FIELD_NAME, strngrdList.Row];
cbbFieldType.ItemIndex := cbbFieldType.Items.IndexOf(strngrdList.Cells[COL_FIELD_TYPE, strngrdList.Row]);
edtCaption.Text := strngrdList.Cells[COL_GRID_COL_CAPTION, strngrdList.Row];
edtInputLabelCaption.Text := strngrdList.Cells[COL_INPUT_LABEL_CAPTION, strngrdList.Row];
chkIsGUIControl.Checked := strngrdList.Cells[COL_INPUT_LABEL_CAPTION, strngrdList.Row] = 'Yes';
chkIsGUIControlClick(chkIsGUIControl);
cbbControlType.ItemIndex := cbbControlType.Items.IndexOf(strngrdList.Cells[COL_CONTROL_TYPE, strngrdList.Row]);
btnEditField.Enabled := True;
FRowNo := strngrdList.Cells[COL_ROW_NO, strngrdList.Row].ToInteger;
end;
end;
end;
procedure TfrmMainClassGenerator.strngrdListMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Cell: TGridCoord;
begin
strngrdList.MouseToCell(X, Y, Cell.X, Cell.Y);
if (Cell.Y > 0) and (Cell.X > 0) then
begin
strngrdList.Row := Cell.Y;
strngrdList.Col := Cell.X;
end;
end;
procedure TfrmMainClassGenerator.strngrdListRowMoved(Sender: TObject; FromIndex,
ToIndex: Integer);
var
n1: Integer;
begin
for n1 := 1 to strngrdList.RowCount-1 do
begin
strngrdList.Cells[COL_ROW_NO, n1] := '';
if (strngrdList.Cells[COL_PROPERTY_NAME, n1] <> '') then
strngrdList.Cells[COL_ROW_NO, n1] := n1.ToString;
end;
ReFillAndSort;
end;
procedure TfrmMainClassGenerator.ReFillAndSort();
var
n1, vRow: Integer;
begin
vRow := 0;
for n1 := 1 to strngrdList.RowCount-1 do
begin
if (strngrdList.Cells[COL_ROW_NO, n1] = '') then
begin
if n1 < strngrdList.RowCount-1 then
begin
strngrdList.Cells[COL_ROW_NO, n1] := n1.ToString;
strngrdList.Cells[COL_PROPERTY_NAME, n1] := strngrdList.Cells[COL_PROPERTY_NAME, n1+1];
strngrdList.Cells[COL_FIELD_NAME, n1] := strngrdList.Cells[COL_FIELD_NAME, n1+1];
strngrdList.Cells[COL_FIELD_TYPE, n1] := strngrdList.Cells[COL_FIELD_TYPE, n1+1];
strngrdList.Cells[COL_GRID_COL_CAPTION, n1] := strngrdList.Cells[COL_GRID_COL_CAPTION, n1+1];
strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1] := strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1+1];
strngrdList.Cells[COL_GUI_CONTROL, n1] := strngrdList.Cells[COL_GUI_CONTROL, n1+1];
strngrdList.Cells[COL_CONTROL_TYPE, n1] := strngrdList.Cells[COL_CONTROL_TYPE, n1+1];
strngrdList.Cells[COL_ROW_NO, n1+1] := '';
strngrdList.Cells[COL_PROPERTY_NAME, n1+1] := '';
strngrdList.Cells[COL_FIELD_NAME, n1+1] := '';
strngrdList.Cells[COL_FIELD_TYPE, n1+1] := '';
strngrdList.Cells[COL_GRID_COL_CAPTION, n1+1] := '';
strngrdList.Cells[COL_INPUT_LABEL_CAPTION, n1+1] := '';
strngrdList.Cells[COL_GUI_CONTROL, n1+1] := '';
strngrdList.Cells[COL_CONTROL_TYPE, n1+1] := '';
end;
end;
if (strngrdList.Cells[COL_PROPERTY_NAME, n1] <> '') then
Inc(vRow);
end;
strngrdList.RowCount := vRow+2;
strngrdList.Cells[COL_ROW_NO, strngrdList.RowCount-1] := '';
end;
end.
|
unit SJ_CTR;
(*************************************************************************
DESCRIPTION : SkipJack CTR mode functions
Because of buffering en/decrypting is associative
User can supply custom increment functions
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.9
REMARKS : - If a predefined or user-supplied INCProc is used, it must
be set before using SJ_CTR_Seek.
- SJ_CTR_Seek may be time-consuming for user-defined
INCProcs, because this function is called many times.
See SJ_CTR_Seek how to provide user-supplied short-cuts.
WARNING : - CTR mode demands that the same key / initial CTR pair is
never reused for encryption. This requirement is especially
important for the CTR_Seek function. If different data is
written to the same position there will be leakage of
information about the plaintexts. Therefore CTR_Seek should
normally be used for random reads only.
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 03.06.09 W.Ehrhardt Initial version a la XT_CTR
0.11 06.08.10 we Longint ILen, XT_CTR_Seek/64 via xt_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, SJ_Base;
{$ifdef CONST}
function SJ_CTR_Init(const Key; KeyBytes: word; const CTR: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if inv. key size, encrypt CTR}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_CTR_Reset(const CTR: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
{$ifdef DLL} stdcall; {$endif}
{$else}
function SJ_CTR_Init(var Key; KeyBytes: word; var CTR: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if inv. key size, encrypt CTR}
procedure SJ_CTR_Reset(var CTR: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
{$endif}
{$ifndef DLL}
function SJ_CTR_Seek({$ifdef CONST}const{$else}var{$endif} iCTR: TSJBlock;
SOL, SOH: longint; var ctx: TSJContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in SJ_CTR_Init.}
{$ifdef HAS_INT64}
function SJ_CTR_Seek64(const iCTR: TSJBlock; SO: int64; var ctx: TSJContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SO >= 0;}
{ iCTR is the initial CTR value for offset 0, i.e. the same as in SJ_CTR_Init.}
{$endif}
{$endif}
function SJ_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
{$ifdef DLL} stdcall; {$endif}
function SJ_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
{$ifdef DLL} stdcall; {$endif}
function SJ_SetIncProc(IncP: TSJIncProc; var ctx: TSJContext): integer;
{-Set user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_IncMSBFull(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[0]}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_IncLSBFull(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[7]}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_IncMSBPart(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[4]}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_IncLSBPart(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[3]}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
procedure SJ_IncMSBPart(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[4]}
var
j: integer;
begin
for j:=7 downto 4 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure SJ_IncLSBPart(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[3]}
var
j: integer;
begin
for j:=0 to 3 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure SJ_IncMSBFull(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[0]}
var
j: integer;
begin
for j:=7 downto 0 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure SJ_IncLSBFull(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[7]}
var
j: integer;
begin
for j:=0 to 7 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
function SJ_SetIncProc(IncP: TSJIncProc; var ctx: TSJContext): integer;
{-Set user supplied IncCTR proc}
begin
SJ_SetIncProc := SJ_Err_MultipleIncProcs;
with ctx do begin
{$ifdef FPC}
if IncProc=nil then begin
IncProc := IncP;
SJ_SetIncProc := 0;
end;
{$else}
if @IncProc=nil then begin
IncProc := IncP;
SJ_SetIncProc := 0;
end;
{$endif}
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function SJ_CTR_Init(const Key; KeyBytes: word; const CTR: TSJBlock; var ctx: TSJContext): integer;
{$else}
function SJ_CTR_Init(var Key; KeyBytes: word; var CTR: TSJBlock; var ctx: TSJContext): integer;
{$endif}
{-SkipJack key expansion, error if inv. key size, encrypt CTR}
var
err: integer;
begin
err := SJ_Init(Key, KeyBytes, ctx);
if err=0 then begin
ctx.IV := CTR;
{encrypt CTR}
SJ_Encrypt(ctx, CTR, ctx.buf);
end;
SJ_CTR_Init := err;
end;
{---------------------------------------------------------------------------}
procedure SJ_CTR_Reset({$ifdef CONST}const {$else} var {$endif} CTR: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
begin
SJ_Reset(ctx);
ctx.IV := CTR;
SJ_Encrypt(ctx, CTR, ctx.buf);
end;
{---------------------------------------------------------------------------}
function SJ_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
begin
SJ_CTR_Encrypt := 0;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
SJ_CTR_Encrypt := SJ_Err_NIL_Pointer; {nil pointer to block with nonzero length}
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
SJ_CTR_Encrypt := SJ_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
if ctx.blen=0 then begin
{Handle full blocks first}
while ILen>=SJBLKSIZE do with ctx do begin
{Cipher text = plain text xor encr(CTR)}
SJ_XorBlock(PSJBlock(ptp)^, buf, PSJBlock(ctp)^);
inc(Ptr2Inc(ptp), SJBLKSIZE);
inc(Ptr2Inc(ctp), SJBLKSIZE);
dec(ILen, SJBLKSIZE);
{use SJ_IncMSBFull if IncProc=nil}
{$ifdef FPC}
if IncProc=nil then SJ_IncMSBFull(IV) else IncProc(IV);
{$else}
if @IncProc=nil then SJ_IncMSBFull(IV) else IncProc(IV);
{$endif}
SJ_Encrypt(ctx, IV, buf);
end;
end;
{Handle remaining bytes}
while ILen>0 do with ctx do begin
{Refill buffer with encrypted CTR}
if bLen>=SJBLKSIZE then begin
{use SJ_IncMSBFull if IncProc=nil}
{$ifdef FPC}
if IncProc=nil then SJ_IncMSBFull(IV) else IncProc(IV);
{$else}
if @IncProc=nil then SJ_IncMSBFull(IV) else IncProc(IV);
{$endif}
SJ_Encrypt(ctx, IV, buf);
bLen := 0;
end;
{Cipher text = plain text xor encr(CTR)}
pByte(ctp)^ := buf[bLen] xor pByte(ptp)^;
inc(bLen);
inc(Ptr2Inc(ptp));
inc(Ptr2Inc(ctp));
dec(ILen);
end;
end;
{---------------------------------------------------------------------------}
function SJ_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
begin
{Decrypt = encrypt for CTR mode}
SJ_CTR_Decrypt := SJ_CTR_Encrypt(ctp, ptp, ILen, ctx);
end;
{$ifndef DLL}
{$i sj_seek.inc}
{$endif}
end.
|
unit Dirs_Entrega;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, RxToolEdit, StrMan, StringLib,
RzEdit, RzBtnEdt, RzLabel, ExtCtrls, RzPanel, RzRadChk, RzButton, RzCmboBx,
ClsDirEntrega;
type
TfraDirs_Entrega = class(TFrame)
RzPanel1: TRzPanel;
RzLabel27: TRzLabel;
RzPanel2: TRzPanel;
mmoDirEnt: TRzMemo;
btnLimpiar: TRzBitBtn;
chkEsPrincipal: TRzCheckBox;
btnEliminar: TRzBitBtn;
btnGrabar: TRzBitBtn;
cboNombreDir: TRzComboBox;
procedure Initiate;
procedure Terminate;
procedure btnGrabarClick(Sender: TObject);
procedure Leer_DirPrincipal;
procedure Grabar;
procedure Limpiar;
procedure LimpiarTodo;
procedure DisplayDatos;
procedure Eliminar;
procedure btnLimpiarClick(Sender: TObject);
procedure btnEliminarClick(Sender: TObject);
procedure Llena_Dirs;
procedure cboNombreDirSelect(Sender: TObject);
private
{ Private declarations }
FoDirEnt:TDirEntrega;
FIDDIRENTREGA:Integer;
FNOMBRE_DIR: String;
FDIR_ENTREGA: String;
FPRIORIDAD:SmallInt;
FDATOS_EMBARQUE: String;
FError:Integer;
FCODCTEPROV: String;
FEventSelect: TNotifyEvent;
mrRes:Integer;
procedure SetIdDirEntrega(AIdDirEntrega:Integer);
procedure SetCodCteProv(ACodCteProv:String);
procedure Set_Nombre_Dir(ANombre_Dir:String);
function Get_Nombre_Dir:String;
procedure Set_Dir_Entrega(ADir_Entrega:String);
function Get_Dir_Entrega:String;
procedure Set_Datos_Embarque(ADatos_Embarque:String);
function Get_Datos_Embarque:String;
procedure Set_Prioridad(APrioridad:SmallInt);
function Get_Prioridad:SmallInt;
procedure DoEventSelect;
public
{ Public declarations }
property IDDirEntrega:Integer read FIDDirEntrega write SetIdDirEntrega;
property Nombre_Dir:String read Get_Nombre_Dir write Set_Nombre_Dir;
property Dir_Entrega:String read Get_Dir_Entrega write Set_Dir_Entrega;
property Prioridad:SmallInt read Get_Prioridad write Set_Prioridad;
property Datos_Embarque:String read Get_Datos_Embarque write Set_Datos_Embarque;
property CodCteProv:String read FCodCteProv write SetCodCteProv;
property EventSelect: TNotifyEvent read FEventSelect write FEventSelect;
end;
implementation
uses DM_MBA, SelTabla;
{$R *.DFM}
procedure TfraDirs_Entrega.Initiate;
begin
FError := 0;
FoDirEnt := TDirEntrega.Create;
end;
procedure TfraDirs_Entrega.Terminate;
begin
FreeAndNil(FoDirEnt);
end;
procedure TfraDirs_Entrega.btnEliminarClick(Sender: TObject);
begin
Eliminar;
end;
procedure TfraDirs_Entrega.btnGrabarClick(Sender: TObject);
begin
Grabar;
end;
procedure TfraDirs_Entrega.Leer_DirPrincipal;
var iPrioridad:smallint;
begin
if not Assigned(FoDirEnt) then begin
FError := 1;
exit;
end;
FoDirEnt.Set_Dir_EntregaPrincipal;
cboNombreDir.Text := FoDirEnt.NOMBRE_DIR;
mmoDirEnt.Text := FoDirEnt.DIR_ENTREGA;
chkEsprincipal.Checked := (FoDirEnt.PRIORIDAD = 0);
FIDDIRENTREGA := FoDirEnt.IDDIRENTREGA;
//
end;
procedure TfraDirs_Entrega.Llena_Dirs;
var iPrioridad:smallint;
begin
if not Assigned(FoDirEnt) then begin
FError := 1;
exit;
end;
if chkEsPrincipal.Checked then iPrioridad := 0 else iPrioridad := 1;
FoDirEnt.Fill_Nombre_Dirs(cboNombreDir.Items);
cboNombreDir.ItemIndex := 0;
mmoDirEnt.Text := FoDirEnt.Get_Dir_Entrega(cboNombreDir.Text);
FDATOS_EMBARQUE := FoDirEnt.DATOS_EMBARQUE;
chkEsPrincipal.Checked := (FoDirEnt.PRIORIDAD = 0);
FIDDIRENTREGA := FoDirEnt.IDDIRENTREGA;
DoEventSelect;
end;
procedure TfraDirs_Entrega.btnLimpiarClick(Sender: TObject);
begin
Limpiar;
end;
procedure TfraDirs_Entrega.DisplayDatos;
begin
cboNombreDir.Text := FoDirEnt.NOMBRE_DIR;
chkEsPrincipal.Checked := (FoDirEnt.PRIORIDAD = 0);
mmoDirEnt.Text := FoDirEnt.DIR_ENTREGA;
FDatos_Embarque := FoDirEnt.DATOS_EMBARQUE;
FIDDIRENTREGA := FoDirEnt.IDDIRENTREGA;
DoEventSelect;
end;
procedure TfraDirs_Entrega.cboNombreDirSelect(Sender: TObject);
begin
FDIR_ENTREGA := FoDirEnt.Get_Dir_Entrega(cboNombreDir.Text);
chkEsPrincipal.Checked := (FoDirEnt.PRIORIDAD = 0);
mmoDirEnt.Text := FoDirEnt.DIR_ENTREGA;
FDatos_Embarque := FoDirEnt.DATOS_EMBARQUE;
FIDDIRENTREGA := FoDirEnt.IDDIRENTREGA;
DoEventSelect;
end;
procedure TfraDirs_Entrega.Grabar;
var
iPrioridad:smallint;
tDir:String;
begin
if not Assigned(FoDirEnt) then begin
FError := 1;
exit;
end;
if length(cboNombreDir.Text) <= 0 then begin
ShowMessage('El nombre de la direccion NO puede estar vacío!'+#10+#13+'Captura un nombre');
FError := 1;
exit;
end;
if chkEsPrincipal.Checked then iPrioridad := 0 else iPrioridad := 1;
FoDirEnt.CODCTEPROV := FCODCTEPROV;
FoDirEnt.NOMBRE_DIR := Trim(cboNombreDir.Text);
FoDirEnt.DIR_ENTREGA := mmoDirEnt.Text;
FoDirEnt.DATOS_EMBARQUE := FDATOS_EMBARQUE;
FoDirEnt.PRIORIDAD := iPrioridad;
tDir := FoDirEnt.NOMBRE_DIR;
FoDirEnt.Save_DirEntrega;
FError := FoDirEnt.Error;
LimpiarTodo;
Llena_Dirs;
cboNombreDir.ItemIndex:= ComboSeekText(cboNombreDir.Items,tDir);
if cboNombreDir.ItemIndex = -1 then
Leer_DirPrincipal
else
cboNombreDirSelect(nil);
end;
procedure TfraDirs_Entrega.Limpiar;
begin
cboNombreDir.Text := '';
chkEsPrincipal.Checked := False;
mmoDirEnt.Text := '';;
FIDDIRENTREGA := -1;
FNOMBRE_DIR:='';
FDIR_ENTREGA:='';
FPRIORIDAD:=0;
FDATOS_EMBARQUE:='';
end;
procedure TfraDirs_Entrega.LimpiarTodo;
begin
cboNombreDir.Items.Clear;
cboNombreDir.Text := '';
chkEsPrincipal.Checked := False;
mmoDirEnt.Lines.Clear;
mmoDirEnt.Text := '';
FIDDIRENTREGA := -1;
FNOMBRE_DIR:='';
FDIR_ENTREGA:='';
FPRIORIDAD:=0;
FDATOS_EMBARQUE:='';
end;
procedure TfraDirs_Entrega.Eliminar;
begin
cboNombreDir.Text := '';
chkEsPrincipal.Checked := False;
mmoDirEnt.Text := '';;
end;
{$REGION 'SET GET'}
procedure TfraDirs_Entrega.SetIdDirEntrega(AIdDirEntrega:Integer);
begin
if AIdDirEntrega <= 0 then exit;
FIdDirEntrega := AIdDirEntrega;
FoDirEnt.SelectById(FIdDirEntrega);
if FoDirEnt.Error = 0 then
DisplayDatos;
end;
procedure TfraDirs_Entrega.SetCodCteProv(ACodCteProv:String);
begin
FCODCTEPROV := ACodCteProv;
FoDirEnt.CODCTEPROV := FCODCTEPROV;
end;
procedure TfraDirs_Entrega.Set_Nombre_Dir(ANombre_Dir:String);
begin
FNOMBRE_DIR := ANombre_Dir;
cboNombreDir.Text := FNOMBRE_DIR;
if sm.IsEmpty(FNOMBRE_DIR) then
Leer_DirPrincipal
else begin
FDIR_ENTREGA := FoDirEnt.Get_Dir_Entrega(FNOMBRE_DIR);
mmoDirEnt.Text := FDIR_ENTREGA;
end;
end;
function TfraDirs_Entrega.Get_Nombre_Dir:String;
begin
Result := FNOMBRE_DIR;
end;
procedure TfraDirs_Entrega.Set_Prioridad(APrioridad:SmallInt);
begin
FPRIORIDAD := APrioridad;
chkEsPrincipal.Checked := (APrioridad <= 0);
end;
function TfraDirs_Entrega.Get_Prioridad:SmallInt;
begin
Result := FPrioridad;
end;
procedure TfraDirs_Entrega.Set_Dir_Entrega(ADir_Entrega:String);
begin
FDIR_ENTREGA := ADir_Entrega;
mmoDirEnt.Text := FDIR_ENTREGA;
end;
function TfraDirs_Entrega.Get_Dir_Entrega:String;
begin
Result := FDIR_ENTREGA;
end;
procedure TfraDirs_Entrega.Set_Datos_Embarque(ADatos_Embarque:String);
begin
FDATOS_EMBARQUE := ADatos_Embarque;
end;
function TfraDirs_Entrega.Get_Datos_Embarque:String;
begin
Result := FDATOS_EMBARQUE;
end;
procedure TfraDirs_Entrega.DoEventSelect;
begin
if assigned(FEventSelect) then
FEventSelect(nil);
end;
{$ENDREGION}
end.
|
unit uTurtleManager;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, fgl, uTurtle;
type TTurtleListe = TFPGList<TTurtle>;
type PTurtle = ^TTurtle;
type TTurtleManager = class
private
FTurtleListe: TTurtleListe;
{ Rueckgabe: True, wenn gueltig. False andernfalls. }
function ueberpruefeGueltigkeitVomIndex(idx: Cardinal) : Boolean;
public
constructor Create;
destructor Destroy; override;
// property
property turtleListe: TTurtleListe read FTurtleListe;
{ Aufgabe: Fuegt eine Turtle hinzu. }
procedure addTurtle(turtle: TTurtle);
{ Aufgabe: Entfernt eine Turtle, die den gleichen Wert, wie die uebergebene Instanz hat.
Rueckgabe: Gibt an, ob die Turtle endfernt wurde bzw. ob der Index.}
function entferneTurtle(turtle: TTurtle) : Boolean;
{ Aufgabe: Entfernt die Schildkroete am Index, der als Parameter uebergeben wurde.
Rueckgabe: Gibt an, ob die Turtle endfernt wurde bzw. ob der Index. }
function entferneTurtleAn(idx: Cardinal) : Boolean;
{ Aufgabe: Zeichnet alle L-Systeme dessen Turtles schon in den Manager eingefuegt worden
wurden und dessen status auf sichtbar gestellt wurde. }
procedure zeichnen;
function copy : TTurtleManager;
// setter-Funktion (public)
{ Rueckgabe: Gibt an, ob die Sichtbarkeit gesetzt wurde bzw. ob der Index
gueltig war. }
function setzeSichtbarkeit(idx: Cardinal; visibility: Boolean) : Boolean;
// getter-Funktionen (public)
function gibTurtle(idx: Cardinal; var turt: TTurtle) : Boolean;
end;
implementation
uses uMatrizen,dglOpenGL;
constructor TTurtleManager.Create;
begin
FTurtleListe := TTurtleListe.Create;
end;
destructor TTurtleManager.Destroy;
VAR i:CARDINAL;
begin
for i:=0 to FTurtleListe.count-1 do
begin
FTurtleListe[i].destroy()
end;
FreeandNil(FTurtleListe);
end;
function TTurtleManager.ueberpruefeGueltigkeitVomIndex(idx: Cardinal) :Boolean;
begin
if (idx >= 0) and (idx < FTurtleListe.Count) then result := true
else result := false;
end;
procedure TTurtleManager.addTurtle(turtle: TTurtle);
begin
FTurtleListe.add(turtle);
end;
function TTurtleManager.entferneTurtle(turtle: TTurtle) : Boolean;
var retSpeicher: Integer;
begin
retSpeicher := FTurtleListe.remove(turtle);
if retSpeicher = -1 then result := false
else result := true;
end;
function TTurtleManager.entferneTurtleAn(idx: Cardinal) : Boolean;
begin
result := ueberpruefeGueltigkeitVomIndex(idx);
if result then result := entferneTurtle(FTurtleListe[idx]);
end;
procedure TTurtleManager.zeichnen;
var i: Cardinal;
begin
glMatrixMode(GL_ModelView);
glClearColor(0,0,0,0);
if not (FTurtleListe.Count=0) then
begin
for i := 0 to FTurtleListe.Count-1 do
begin
if not FTurtleListe[i].visible then continue;
FTurtleListe[i].zeichnen;
end;
end;
end;
function TTurtleManager.copy : TTurtleManager;
var i: Cardinal;
turtle: TTurtle;
begin
result := TTurtleManager.Create;
if not (FTurtleListe.Count=0) then
begin
for i := 0 to FTurtleListe.Count-1 do
begin
gibTurtle(i,turtle);
result.addTurtle(turtle.copy);
end;
end;
end;
function TTurtleManager.setzeSichtbarkeit(idx: Cardinal; visibility: Boolean) : Boolean;
begin
result := ueberpruefeGueltigkeitVomIndex(idx);
if result then FTurtleListe[idx].visible := visibility;
end;
function TTurtleManager.gibTurtle(idx: Cardinal; var turt: TTurtle) : Boolean;
begin
result := ueberpruefeGueltigkeitVomIndex(idx);
if result then turt := FTurtleListe[idx];
end;
end.
|
program TestEnums;
procedure internal();
type
Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat);
var day : Days;
begin
WriteLn('Mon: ', Mon);
day := Tue;
WriteLn('day: ', day);
end;
begin
internal();
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Android.Permissions;
interface
implementation
uses
System.Generics.Collections,
System.Messaging,
System.Permissions,
System.SysUtils,
System.Types,
System.UITypes,
Androidapi.Helpers,
Androidapi.JniBridge,
Androidapi.Jni,
Androidapi.JNI.App,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
Androidapi.JNI.Support,
Androidapi.JNI.Widget;
type
TRequestPermissionsCallbackPair = record
Proc: TRequestPermissionsResultProc;
Event: TRequestPermissionsResultEvent;
constructor Create(const AProc: TRequestPermissionsResultProc; const AEvent: TRequestPermissionsResultEvent);
end;
TDisplayRationaleCallbackPair = record
Proc: TDisplayRationaleProc;
Event: TDisplayRationaleEvent;
constructor Create(const AProc: TDisplayRationaleProc; const AEvent: TDisplayRationaleEvent);
end;
TAndroidPermissionsService = class(TPermissionsService)
private
FPermissionsRequestsAndCallbacks: TDictionary<Integer, TRequestPermissionsCallbackPair>;
procedure DoRequestPermissions(const APermissions: TArray<string>; const ARequestCode: Integer);
procedure DoRequestPermissionsCallback(const ARequestPermissionsCallbackPair: TRequestPermissionsCallbackPair; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure InternalRequestPermissions(const APermissions: TArray<string>;
const ARequestPermissionsCallbackPair: TRequestPermissionsCallbackPair;
const ADisplayRationaleCallbackPair: TDisplayRationaleCallbackPair);
/// <summary>RTL messaging system listener</summary>
procedure HandlePermissionsRequest(const Sender: TObject; const AMessage: TMessage);
/// <summary>Delphi representation of the Android onRequestPermissionsResult callback</summary>
procedure OnPermissionsRequest(const ARequestCode: Integer; const APermissions: TJavaObjectArray<JString>;
const AGrantResults: TJavaArray<Integer>);
/// <summary>Helper routine to get a unique request code</summary>
function NextAvailableRequestCode: Integer;
public
constructor Create; override;
destructor Destroy; override;
function IsPermissionGranted(const APermission: string): Boolean; override;
function IsEveryPermissionGranted(const APermissions: TArray<string>): Boolean; override;
procedure RequestPermissions(const APermissions: TArray<string>;
const AOnRequestPermissionsResult: TRequestPermissionsResultEvent; AOnDisplayRationale: TDisplayRationaleEvent = nil);
overload; override;
procedure RequestPermissions(const APermissions: TArray<string>;
const AOnRequestPermissionsResult: TRequestPermissionsResultProc; AOnDisplayRationale: TDisplayRationaleProc = nil);
overload; override;
end;
{ TRequestPermissionsCallbackPair }
constructor TRequestPermissionsCallbackPair.Create(const AProc: TRequestPermissionsResultProc;
const AEvent: TRequestPermissionsResultEvent);
begin
Proc := AProc;
Event := AEvent;
end;
{ TDisplayRationaleCallbackPair }
constructor TDisplayRationaleCallbackPair.Create(const AProc: TDisplayRationaleProc; const AEvent: TDisplayRationaleEvent);
begin
Proc := AProc;
Event := AEvent;
end;
{ TAndroidPermissionsService }
constructor TAndroidPermissionsService.Create;
begin
inherited Create;
FPermissionsRequestsAndCallbacks := TDictionary<Integer, TRequestPermissionsCallbackPair>.Create;
TMessageManager.DefaultManager.SubscribeToMessage(TPermissionsRequestResultMessage,
HandlePermissionsRequest);
end;
destructor TAndroidPermissionsService.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TPermissionsRequestResultMessage, HandlePermissionsRequest);
FPermissionsRequestsAndCallbacks.Free;
inherited Destroy;
end;
procedure TAndroidPermissionsService.DoRequestPermissions(const APermissions: TArray<string>;
const ARequestCode: Integer);
var
Permissions: TJavaObjectArray<JString>;
I: Integer;
begin
Permissions := TJavaObjectArray<JString>.Create(Length(APermissions));
for I := Low(APermissions) to High(APermissions) do
Permissions[I] := StringToJString(APermissions[I]);
// Using helper class from Android Support Library, so no OS version-checking required
TJActivityCompat.JavaClass.RequestPermissions(TAndroidHelper.Activity, Permissions, ARequestCode);
end;
function TAndroidPermissionsService.IsPermissionGranted(const APermission: string): Boolean;
begin
// Using helper class from Android Support Library, so no OS version checking required
Result := TJContextCompat.JavaClass.checkSelfPermission(TAndroidHelper.Context,
StringToJString(APermission)) = TJPackageManager.JavaClass.PERMISSION_GRANTED
end;
function TAndroidPermissionsService.IsEveryPermissionGranted(const APermissions: TArray<string>): Boolean;
var
Permission: string;
begin
Result := True;
for Permission in APermissions do
if not IsPermissionGranted(Permission) then
Exit(False)
end;
procedure TAndroidPermissionsService.DoRequestPermissionsCallback(
const ARequestPermissionsCallbackPair: TRequestPermissionsCallbackPair;
const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
begin
// Call whichever callback (method or anonymous procedure) was passed in
if Assigned(ARequestPermissionsCallbackPair.Proc) then
ARequestPermissionsCallbackPair.Proc(APermissions, AGrantResults)
else if Assigned(ARequestPermissionsCallbackPair.Event) then
ARequestPermissionsCallbackPair.Event(Self, APermissions, AGrantResults)
end;
procedure TAndroidPermissionsService.InternalRequestPermissions(const APermissions: TArray<string>;
const ARequestPermissionsCallbackPair: TRequestPermissionsCallbackPair;
const ADisplayRationaleCallbackPair: TDisplayRationaleCallbackPair);
var
RequestCode, I, NextRationaleRequirementIndex: Integer;
RequestedPermissionsNotAllGranted, ShowRationale: Boolean;
GrantResults: TArray<TPermissionStatus>;
Permissions: TArray<string>;
PostRationale: TProc;
begin
// First, check which permissions are not currently granted
SetLength(GrantResults, Length(APermissions));
RequestedPermissionsNotAllGranted := False;
for I := Low(GrantResults) to High(GrantResults) do
begin
if IsPermissionGranted(APermissions[I]) then
GrantResults[I] := TPermissionStatus.Granted
else
GrantResults[I] := TPermissionStatus.Denied;
if GrantResults[I] <> TPermissionStatus.Granted then
RequestedPermissionsNotAllGranted := True;
end;
// If we have any then act accordingly
if RequestedPermissionsNotAllGranted then
begin
RequestCode := NextAvailableRequestCode;
FPermissionsRequestsAndCallbacks.Add(RequestCode, ARequestPermissionsCallbackPair);
ShowRationale := False;
// Permissions are not granted. Is there an explanation/rationale to show
if Assigned(ADisplayRationaleCallbackPair.Proc) or Assigned(ADisplayRationaleCallbackPair.Event) then
begin
SetLength(Permissions, Length(APermissions));
NextRationaleRequirementIndex := 0;
// Iterate all the permissions and get any rationale strings that need displaying
for I := Low(APermissions) to High(APermissions) do
begin
// References to the Activity won't work in a service where it's nil and will
// throw an exception if read there, so we check the DelphiActivity symbol first
if DelphiActivity <> nil then
begin
if TJActivityCompat.JavaClass.shouldShowRequestPermissionRationale(
TAndroidHelper.Activity, StringToJString(APermissions[I])) then
begin
Permissions[NextRationaleRequirementIndex] := APermissions[I];
ShowRationale := True;
Inc(NextRationaleRequirementIndex);
end;
end;
end;
SetLength(Permissions, NextRationaleRequirementIndex);
end;
if ShowRationale then
begin
PostRationale := procedure
begin
DoRequestPermissions(APermissions, RequestCode)
end;
// Call whichever rationale display callback has been passed in.
// This should show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, try again to request the permission.
if Assigned(ADisplayRationaleCallbackPair.Proc) then
ADisplayRationaleCallbackPair.Proc(Permissions, PostRationale)
else if Assigned(ADisplayRationaleCallbackPair.Event) then
ADisplayRationaleCallbackPair.Event(Self, Permissions, PostRationale)
end
else
DoRequestPermissions(APermissions, RequestCode)
end
else // Permissions already granted
DoRequestPermissionsCallback(ARequestPermissionsCallbackPair, APermissions, GrantResults);
end;
procedure TAndroidPermissionsService.RequestPermissions(const APermissions: TArray<string>;
const AOnRequestPermissionsResult: TRequestPermissionsResultEvent; AOnDisplayRationale: TDisplayRationaleEvent);
begin
InternalRequestPermissions(APermissions, TRequestPermissionsCallbackPair.Create(nil, AOnRequestPermissionsResult), TDisplayRationaleCallbackPair.Create(nil, AOnDisplayRationale));
end;
procedure TAndroidPermissionsService.RequestPermissions(const APermissions: TArray<string>;
const AOnRequestPermissionsResult: TRequestPermissionsResultProc; AOnDisplayRationale: TDisplayRationaleProc);
begin
InternalRequestPermissions(APermissions, TRequestPermissionsCallbackPair.Create(AOnRequestPermissionsResult, nil), TDisplayRationaleCallbackPair.Create(AOnDisplayRationale, nil));
end;
procedure TAndroidPermissionsService.HandlePermissionsRequest(const Sender: TObject; const AMessage: TMessage);
var
MessageData: TPermissionsRequestResultData;
RequestCode: Integer;
Permissions: TJavaObjectArray<JString>;
GrantResults: TJavaArray<Integer>;
begin
if AMessage is TPermissionsRequestResultMessage then
begin
MessageData := TPermissionsRequestResultMessage(AMessage).Value;
RequestCode := MessageData.RequestCode;
Permissions := MessageData.Permissions;
GrantResults := MessageData.GrantResults;
OnPermissionsRequest(RequestCode, Permissions, GrantResults);
end;
end;
function TAndroidPermissionsService.NextAvailableRequestCode: Integer;
const
StartingRequestCode = 10000;
var
CallbackPair: TRequestPermissionsCallbackPair;
begin
Result := StartingRequestCode;
// Loop until we encounter an unused request code
while FPermissionsRequestsAndCallbacks.TryGetValue(Result, CallbackPair) do
Inc(Result)
end;
procedure TAndroidPermissionsService.OnPermissionsRequest(const ARequestCode: Integer;
const APermissions: TJavaObjectArray<JString>; const AGrantResults: TJavaArray<Integer>);
var
CallbackPair: TRequestPermissionsCallbackPair;
Permissions: TArray<string>;
GrantResults: TArray<TPermissionStatus>;
NumPermissions: Integer;
I: Integer;
begin
// Look up the request code in FPermissionsRequestsAndCallbacks CallbackPair to get the user callback to call
if FPermissionsRequestsAndCallbacks.TryGetValue(ARequestCode, CallbackPair) then
begin
NumPermissions := APermissions.Length;
// This callback appears to be called twice, once with empty arrays and then with populated arrays
if (NumPermissions > 0) and (NumPermissions = AGrantResults.Length) then
begin
SetLength(Permissions, NumPermissions);
SetLength(GrantResults, NumPermissions);
for I := 0 to Pred(NumPermissions) do
begin
Permissions[I] := JStringToString(APermissions[I]);
if AGrantResults[I] = TJPackageManager.JavaClass.PERMISSION_GRANTED then
GrantResults[I] := TPermissionStatus.Granted
else if TJActivityCompat.JavaClass.shouldShowRequestPermissionRationale(
TAndroidHelper.Activity, APermissions[I]) then
GrantResults[I] := TPermissionStatus.Denied
else
GrantResults[I] := TPermissionStatus.PermanentlyDenied;
end;
try
DoRequestPermissionsCallback(CallbackPair, Permissions, GrantResults);
finally
// Tidy up the resources logged against this request code
FPermissionsRequestsAndCallbacks.Remove(ARequestCode);
end;
end;
end;
end;
initialization
PermissionsServiceClass := TAndroidPermissionsService
end.
|
unit NtUtils.Registry;
interface
uses
Winapi.WinNt, Ntapi.ntregapi, NtUtils.Exceptions, NtUtils.Objects;
type
TRegValueType = Ntapi.ntregapi.TRegValueType;
TKeyBasicInfo = record
LastWriteTime: TLargeInteger;
TitleIndex: Cardinal;
Name: String;
end;
TRegValueEntry = record
ValueType: TRegValueType;
ValueName: String;
end;
{ Keys }
// Open a key
function NtxOpenKey(out hxKey: IHandle; Name: String;
DesiredAccess: TAccessMask; Root: THandle = 0; OpenOptions: Cardinal = 0;
Attributes: Cardinal = 0): TNtxStatus;
// Create a key
function NtxCreateKey(out hxKey: IHandle; Name: String;
DesiredAccess: TAccessMask; Root: THandle = 0; CreateOptions: Cardinal = 0;
Attributes: Cardinal = 0; Disposition: PCardinal = nil): TNtxStatus;
// Delete a key
function NtxDeleteKey(hKey: THandle): TNtxStatus;
// Rename a key
function NtxRenameKey(hKey: THandle; NewName: String): TNtxStatus;
// Enumerate sub-keys
function NtxEnumerateSubKeys(hKey: THandle; out SubKeys: TArray<String>)
: TNtxStatus;
// Query variable-length key information
function NtxQueryInformationKey(hKey: THandle; InfoClass: TKeyInformationClass;
out xMemory: IMemory): TNtxStatus;
// Query key basic information
function NtxQueryBasicKey(hKey: THandle; out Info: TKeyBasicInfo): TNtxStatus;
type
NtxKey = class
// Query fixed-size key information
class function Query<T>(hKey: THandle; InfoClass: TKeyInformationClass;
out Buffer: T): TNtxStatus; static;
// Set fixed-size key information
class function SetInfo<T>(hKey: THandle; InfoClass: TKeySetInformationClass;
const Buffer: T): TNtxStatus; static;
end;
{ Values }
// Enumerate values of a key
function NtxEnumerateValuesKey(hKey: THandle;
out ValueNames: TArray<TRegValueEntry>): TNtxStatus;
// Query variable-length value information
function NtxQueryValueKey(hKey: THandle; ValueName: String;
InfoClass: TKeyValueInformationClass; out Status: TNtxStatus): Pointer;
// Query value of a DWORD type
function NtxQueryDwordValueKey(hKey: THandle; ValueName: String;
out Value: Cardinal): TNtxStatus;
// Query value of a string type
function NtxQueryStringValueKey(hKey: THandle; ValueName: String;
out Value: String): TNtxStatus;
// Query value of a multi-string type
function NtxQueryMultiStringValueKey(hKey: THandle; ValueName: String;
out Value: TArray<String>): TNtxStatus;
// Set value
function NtxSetValueKey(hKey: THandle; ValueName: String;
ValueType: TRegValueType; Data: Pointer; DataSize: Cardinal): TNtxStatus;
// Set a DWORD value
function NtxSetDwordValueKey(hKey: THandle; ValueName: String; Value: Cardinal)
: TNtxStatus;
// Set a string value
function NtxSetStringValueKey(hKey: THandle; ValueName: String; Value: String;
ValueType: TRegValueType = REG_SZ): TNtxStatus;
// Set a multi-string value
function NtxSetMultiStringValueKey(hKey: THandle; ValueName: String;
Value: TArray<String>): TNtxStatus;
// Delete a value
function NtxDeleteValueKey(hKey: THandle; ValueName: String): TNtxStatus;
{ Other }
// Mount a hive file to the registry
function NtxLoadKey(KeyName: String; FileName: String): TNtxStatus;
// Unmount a hive file from the registry
function NtxUnloadKey(KeyName: String): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntseapi, DelphiUtils.Arrays;
{ Keys }
function NtxOpenKey(out hxKey: IHandle; Name: String;
DesiredAccess: TAccessMask; Root: THandle; OpenOptions: Cardinal;
Attributes: Cardinal): TNtxStatus;
var
hKey: THandle;
NameStr: UNICODE_STRING;
ObjAttr: TObjectAttributes;
begin
NameStr.FromString(Name);
InitializeObjectAttributes(ObjAttr, @NameStr, Attributes or
OBJ_CASE_INSENSITIVE, Root);
Result.Location := 'NtOpenKeyEx';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @KeyAccessType;
Result.Status := NtOpenKeyEx(hKey, DesiredAccess, ObjAttr, OpenOptions);
if Result.IsSuccess then
hxKey := TAutoHandle.Capture(hKey);
end;
function NtxCreateKey(out hxKey: IHandle; Name: String;
DesiredAccess: TAccessMask; Root: THandle; CreateOptions: Cardinal;
Attributes: Cardinal; Disposition: PCardinal): TNtxStatus;
var
hKey: THandle;
NameStr: UNICODE_STRING;
ObjAttr: TObjectAttributes;
begin
NameStr.FromString(Name);
InitializeObjectAttributes(ObjAttr, @NameStr, Attributes or
OBJ_CASE_INSENSITIVE, Root);
Result.Location := 'NtCreateKey';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @KeyAccessType;
Result.Status := NtCreateKey(hKey, DesiredAccess, ObjAttr, 0, nil,
CreateOptions, Disposition);
if Result.IsSuccess then
hxKey := TAutoHandle.Capture(hKey);
end;
function NtxDeleteKey(hKey: THandle): TNtxStatus;
begin
Result.Location := 'NtDeleteKey';
Result.LastCall.Expects(_DELETE, @KeyAccessType);
Result.Status := NtDeleteKey(hKey);
end;
function NtxRenameKey(hKey: THandle; NewName: String): TNtxStatus;
var
NewNameStr: UNICODE_STRING;
begin
NewNameStr.FromString(NewName);
Result.Location := 'NtRenameKey';
Result.LastCall.Expects(READ_CONTROL or KEY_SET_VALUE or KEY_CREATE_SUB_KEY,
@KeyAccessType);
// Or READ_CONTROL | KEY_NOTIFY | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE
// in case of enabled virtualization
Result.Status := NtRenameKey(hKey, NewNameStr)
end;
function NtxEnumerateSubKeys(hKey: THandle; out SubKeys: TArray<String>)
: TNtxStatus;
var
Index: Integer;
Buffer: PKeyBasicInformation;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtEnumerateKey';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(KeyBasicInformation);
Result.LastCall.InfoClassType := TypeInfo(TKeyInformationClass);
Result.LastCall.Expects(KEY_ENUMERATE_SUB_KEYS, @KeyAccessType);
SetLength(SubKeys, 0);
Index := 0;
repeat
// Query sub-key name
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtEnumerateKey(hKey, Index, KeyBasicInformation, Buffer,
BufferSize, Required);
if not Result.IsSuccess then
FreeMem(Buffer);
until not NtxExpandBuffer(Result, BufferSize, Required);
if Result.IsSuccess then
begin
SetLength(SubKeys, Length(SubKeys) + 1);
SetString(SubKeys[High(SubKeys)], PWideChar(@Buffer.Name),
Buffer.NameLength div SizeOf(WideChar));
FreeMem(Buffer);
end;
Inc(Index);
until not Result.IsSuccess;
if Result.Status = STATUS_NO_MORE_ENTRIES then
Result.Status := STATUS_SUCCESS;
end;
function NtxQueryInformationKey(hKey: THandle; InfoClass: TKeyInformationClass;
out xMemory: IMemory): TNtxStatus;
var
Buffer: Pointer;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtQueryKey';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TKeyInformationClass);
if not (InfoClass in [KeyNameInformation, KeyHandleTagsInformation]) then
Result.LastCall.Expects(KEY_QUERY_VALUE, @KeyAccessType);
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtQueryKey(hKey, InfoClass, Buffer, BufferSize, Required);
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if Result.IsSuccess then
xMemory := TAutoMemory.Capture(Buffer, BufferSize);
end;
function NtxQueryBasicKey(hKey: THandle; out Info: TKeyBasicInfo): TNtxStatus;
var
xMemory: IMemory;
Buffer: PKeyBasicInformation;
begin
Result := NtxQueryInformationKey(hKey, KeyBasicInformation, xMemory);
if Result.IsSuccess then
begin
Buffer := xMemory.Address;
Info.LastWriteTime := Buffer.LastWriteTime;
Info.TitleIndex := Buffer.TitleIndex;
SetString(Info.Name, PWideChar(@Buffer.Name), Buffer.NameLength);
end;
end;
class function NtxKey.Query<T>(hKey: THandle; InfoClass: TKeyInformationClass;
out Buffer: T): TNtxStatus;
var
Returned: Cardinal;
begin
Result.Location := 'NtQueryKey';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TKeyInformationClass);
if not (InfoClass in [KeyNameInformation, KeyHandleTagsInformation]) then
Result.LastCall.Expects(KEY_QUERY_VALUE, @KeyAccessType);
Result.Status := NtQueryKey(hKey, InfoClass, @Buffer, SizeOf(Buffer),
Returned);
end;
class function NtxKey.SetInfo<T>(hKey: THandle;
InfoClass: TKeySetInformationClass; const Buffer: T): TNtxStatus;
begin
Result.Location := 'NtSetInformationKey';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TKeySetInformationClass);
if InfoClass <> KeySetHandleTagsInformation then
Result.LastCall.Expects(KEY_SET_VALUE, @KeyAccessType);
// Or READ_CONTROL | KEY_NOTIFY | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE
// in case of enabled virtualization
Result.Status := NtSetInformationKey(hKey, InfoClass, @Buffer,
SizeOf(Buffer));
end;
{ Values }
function NtxEnumerateValuesKey(hKey: THandle;
out ValueNames: TArray<TRegValueEntry>): TNtxStatus;
var
Index: Integer;
Buffer: PKeyValueBasicInformation;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtEnumerateValueKey';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(KeyValueBasicInformation);
Result.LastCall.InfoClassType := TypeInfo(TKeyValueInformationClass);
Result.LastCall.Expects(KEY_QUERY_VALUE, @KeyAccessType);
SetLength(ValueNames, 0);
Index := 0;
repeat
// Query value name
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtEnumerateValueKey(hKey, Index,
KeyValueBasicInformation, Buffer, BufferSize, Required);
if not Result.IsSuccess then
FreeMem(Buffer);
until not NtxExpandBuffer(Result, BufferSize, Required);
if Result.IsSuccess then
begin
SetLength(ValueNames, Length(ValueNames) + 1);
ValueNames[High(ValueNames)].ValueType := Buffer.ValueType;
SetString(ValueNames[High(ValueNames)].ValueName, PWideChar(@Buffer.Name),
Buffer.NameLength div SizeOf(WideChar));
FreeMem(Buffer);
end;
Inc(Index);
until not Result.IsSuccess;
if Result.Status = STATUS_NO_MORE_ENTRIES then
Result.Status := STATUS_SUCCESS;
end;
function NtxQueryValueKey(hKey: THandle; ValueName: String;
InfoClass: TKeyValueInformationClass; out Status: TNtxStatus): Pointer;
var
NameStr: UNICODE_STRING;
BufferSize, Required: Cardinal;
begin
NameStr.FromString(ValueName);
Status.Location := 'NtQueryValueKey';
Status.LastCall.CallType := lcQuerySetCall;
Status.LastCall.InfoClass := Cardinal(InfoClass);
Status.LastCall.InfoClassType := TypeInfo(TKeyValueInformationClass);
Status.LastCall.Expects(KEY_QUERY_VALUE, @KeyAccessType);
BufferSize := 0;
repeat
// Make sure we have a gap for zero-terminate strings
Result := AllocMem(BufferSize + SizeOf(WideChar));
Required := 0;
Status.Status := NtQueryValueKey(hKey, NameStr, InfoClass, Result,
BufferSize, Required);
if not Status.IsSuccess then
begin
FreeMem(Result);
Result := nil;
end;
until not NtxExpandBuffer(Status, BufferSize, Required);
end;
function NtxQueryDwordValueKey(hKey: THandle; ValueName: String;
out Value: Cardinal): TNtxStatus;
var
Buffer: PKeyValuePartialInfromation;
begin
Buffer := NtxQueryValueKey(hKey, ValueName,
KeyValuePartialInformation, Result);
if not Result.IsSuccess then
Exit;
if Buffer.DataLength < SizeOf(Cardinal) then
begin
Result.Status := STATUS_INFO_LENGTH_MISMATCH;
Exit;
end;
case Buffer.ValueType of
REG_DWORD:
Value := PCardinal(@Buffer.Data)^;
else
Result.Status := STATUS_OBJECT_TYPE_MISMATCH;
end;
FreeMem(Buffer);
end;
function NtxQueryStringValueKey(hKey: THandle; ValueName: String;
out Value: String): TNtxStatus;
var
Buffer: PKeyValuePartialInfromation;
begin
Buffer := NtxQueryValueKey(hKey, ValueName,
KeyValuePartialInformation, Result);
if not Result.IsSuccess then
Exit;
case Buffer.ValueType of
REG_SZ, REG_EXPAND_SZ, REG_LINK:
Value := String(PWideChar(@Buffer.Data));
else
Result.Status := STATUS_OBJECT_TYPE_MISMATCH;
end;
FreeMem(Buffer);
end;
function NtxQueryMultiStringValueKey(hKey: THandle; ValueName: String;
out Value: TArray<String>): TNtxStatus;
var
Buffer: PKeyValuePartialInfromation;
begin
Buffer := NtxQueryValueKey(hKey, ValueName,
KeyValuePartialInformation, Result);
if not Result.IsSuccess then
Exit;
case Buffer.ValueType of
REG_SZ, REG_EXPAND_SZ, REG_LINK:
begin
SetLength(Value, 1);
Value[0] := String(PWideChar(@Buffer.Data));
end;
REG_MULTI_SZ:
Value := ParseMultiSz(PWideChar(@Buffer.Data), Buffer.DataLength);
else
Result.Status := STATUS_OBJECT_TYPE_MISMATCH;
end;
FreeMem(Buffer);
end;
function NtxSetValueKey(hKey: THandle; ValueName: String;
ValueType: TRegValueType; Data: Pointer; DataSize: Cardinal): TNtxStatus;
var
ValueNameStr: UNICODE_STRING;
begin
ValueNameStr.FromString(ValueName);
Result.Location := 'NtSetValueKey';
Result.LastCall.Expects(KEY_SET_VALUE, @KeyAccessType);
Result.Status := NtSetValueKey(hKey, ValueNameStr, 0, ValueType, Data,
DataSize);
end;
function NtxSetDwordValueKey(hKey: THandle; ValueName: String; Value: Cardinal)
: TNtxStatus;
begin
Result := NtxSetValueKey(hKey, ValueName, REG_DWORD, @Value, SizeOf(Value));
end;
function NtxSetStringValueKey(hKey: THandle; ValueName: String; Value: String;
ValueType: TRegValueType): TNtxStatus;
begin
Result := NtxSetValueKey(hKey, ValueName, ValueType, PWideChar(Value),
Length(Value) * SizeOf(WideChar));
end;
function NtxSetMultiStringValueKey(hKey: THandle; ValueName: String;
Value: TArray<String>): TNtxStatus;
var
Buffer, pCurrentPosition: PWideChar;
BufferSize: Cardinal;
i: Integer;
begin
// Calculate required memory
BufferSize := SizeOf(WideChar); // Include ending #0
for i := 0 to High(Value) do
Inc(BufferSize, (Length(Value[i]) + 1) * SizeOf(WideChar));
Buffer := AllocMem(BufferSize);
pCurrentPosition := Buffer;
for i := 0 to High(Value) do
begin
Move(PWideChar(Value[i])^, pCurrentPosition^,
Length(Value[i]) * SizeOf(WideChar));
Inc(pCurrentPosition, Length(Value[i]) + 1);
end;
Result := NtxSetValueKey(hKey, ValueName, REG_MULTI_SZ, Buffer, BufferSize);
FreeMem(Buffer);
end;
function NtxDeleteValueKey(hKey: THandle; ValueName: String): TNtxStatus;
var
ValueNameStr: UNICODE_STRING;
begin
ValueNameStr.FromString(ValueName);
Result.Location := 'NtDeleteValueKey';
Result.LastCall.Expects(KEY_SET_VALUE, @KeyAccessType);
// Or READ_CONTROL | KEY_NOTIFY | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE
// in case of enabled virtualization
Result.Status := NtDeleteValueKey(hKey, ValueNameStr);
end;
function NtxLoadKey(KeyName: String; FileName: String): TNtxStatus;
var
KeyStr, FileStr: UNICODE_STRING;
TargetKey, SourceFile: TObjectAttributes;
begin
KeyStr.FromString(KeyName);
FileStr.FromString(FileName);
InitializeObjectAttributes(TargetKey, @KeyStr);
InitializeObjectAttributes(SourceFile, @FileStr);
Result.Location := 'NtLoadKey';
Result.LastCall.ExpectedPrivilege := SE_RESTORE_PRIVILEGE;
Result.Status := NtLoadKey(TargetKey, SourceFile);
end;
function NtxUnloadKey(KeyName: String): TNtxStatus;
var
KeyStr: UNICODE_STRING;
ObjAttr: TObjectAttributes;
begin
KeyStr.FromString(KeyName);
InitializeObjectAttributes(ObjAttr, @KeyStr);
Result.Location := 'NtUnloadKey';
Result.LastCall.ExpectedPrivilege := SE_RESTORE_PRIVILEGE;
Result.Status := NtUnloadKey(ObjAttr);
end;
end.
|
program rhombus;
function EnterRhombusHight(): integer;
var
d : integer;
begin
repeat
write('Enter a hight (an odd positive number):');
readln(d);
until (d > 0) and (d mod 2 = 1);
EnterRhombusHight := d;
end;
var
rhombus_hight, line_num, line_pos, rhombus_mid, star_shift : integer;
begin
rhombus_hight := EnterRhombusHight;
rhombus_mid := rhombus_hight div 2;
line_num := 0;
line_pos := 0;
while line_num <= rhombus_hight -1 do begin
star_shift := rhombus_mid - abs(line_num - rhombus_mid);
line_pos := 0;
while line_pos <= rhombus_mid + star_shift do begin
if line_pos = rhombus_mid + star_shift then
writeln('*')
else if line_pos = rhombus_mid - star_shift then
write('*')
else
write(' ');
line_pos := line_pos + 1;
end;
line_num := line_num + 1;
end;
end.
|
unit ActiveClient;
interface
uses
AppConstants, System.Rtti, SysUtils, DateUtils, Ledger, Math, LoanClassification;
type
TLoan = class
strict private
FId: string;
FLoanTypeName: string;
FAccountTypeName: string;
FBalance: currency;
FPrincipalDeficit: currency;
FInterestMethod: string;
FPrincipalAmortisation: currency;
FInterestAmortisation: currency;
FDiminishingType: TDiminishingType;
FLastTransactionDate: TDateTime;
FInterestInDecimal: currency;
FInterestDeficit: currency;
FInterestAdditional: currency;
FInterestComputed: currency;
FLedger: array of TLedger;
FPayments: integer;
FReleaseAmount: currency;
FApprovedTerm: integer;
FFullpaymentInterest: currency;
FPaymentsAdvance: integer;
FAmortization: currency;
FReleaseDate: TDateTime;
FRebate: currency;
FLastInterestPostDate: TDateTime;
function GetIsDiminishing: boolean;
function GetIsFixed: boolean;
function GetLedger(const i: integer): TLedger;
function GetIsFirstPayment: boolean;
function GetNextPayment: TDateTime;
procedure GetInterestDue(const paymentDate: TDateTime); overload;
procedure GetPrincipalDue(const paymentDate: TDateTime);
function GetLedgerCount: integer;
function GetHasInterestBalance: boolean;
function GetHasInterestComputed: boolean;
function GetHasInterstAdditional: boolean;
function GetInterestTotalDue: currency;
function GetLatestInterestDate(const paymentDate: TDateTime): TDateTime;
function GetInterestMethodName: string;
function GetHasAdvancePayment: boolean;
function GetInterestDueOnPaymentDate: currency;
function GetHasRebate: boolean;
public
property Id: string read FId write FId;
property Balance: currency read FBalance write FBalance;
property PrincipalDeficit: currency read FPrincipalDeficit write FPrincipalDeficit;
property LoanTypeName: string read FLoanTypeName write FLoanTypeName;
property AccountTypeName: string read FAccountTypeName write FAccountTypeName;
property InterestMethod: string write FInterestMethod;
property IsDiminishing: boolean read GetIsDiminishing;
property IsFixed: boolean read GetIsFixed;
property DiminishingType: TDiminishingType read FDiminishingType write FDiminishingType;
property LastTransactionDate: TDateTime read FLastTransactionDate write FLastTransactionDate;
property InterestInDecimal: currency read FInterestInDecimal write FInterestInDecimal;
property NextPayment: TDateTime read GetNextPayment;
property InterestDeficit: currency read FInterestDeficit write FInterestDeficit;
property Ledger[const i: integer]: TLedger read GetLedger;
property IsFirstPayment: boolean read GetIsFirstPayment;
property LedgerCount: integer read GetLedgerCount;
property InterestAdditional: currency read FInterestAdditional;
property InterestComputed: currency read FInterestComputed;
property HasInterestBalance: boolean read GetHasInterestBalance;
property HasInterestComputed: boolean read GetHasInterestComputed;
property HasInterestAdditional: boolean read GetHasInterstAdditional;
property InterestTotalDue: currency read GetInterestTotalDue;
property ReleaseAmount: currency read FReleaseAmount write FReleaseAmount;
property ApprovedTerm: integer read FApprovedTerm write FApprovedTerm;
property FullPaymentInterest: currency read FFullPaymentInterest;
property Payments: integer write FPayments;
property InterestMethodName: string read GetInterestMethodName;
property HasAdvancePayment: boolean read GetHasAdvancePayment;
property PaymentsAdvance: integer write FPaymentsAdvance;
property Amortization: currency read FAmortization write FAmortization;
property InterestAmortisation: currency read FInterestAmortisation;
property PrincipalAmortisation: currency read FPrincipalAmortisation;
property InterestDueOnPaymentDate: currency read GetInterestDueOnPaymentDate;
property ReleaseDate: TDateTime read FReleaseDate write FReleaseDate;
property Rebate: currency read FRebate;
property LastInterestPostDate: TDateTime read FLastInterestPostDate write FLastInterestPostDate;
property HasRebate: boolean read GetHasRebate;
procedure GetPaymentDue(const paymentDate: TDateTime);
procedure RetrieveLedger;
procedure ClearLedger;
procedure AddLedger(const ALedger: TLedger);
end;
TActiveClient = class
private
FId: string;
FName: string;
FLoans: array of TLoan;
function GetLoan(const i: integer): TLoan;
function GetLoanCount: integer;
function GetLastInterestPostDate(const ALoanId: string): TDateTime;
public
property Id: string read FId write FId;
property Name: string read FName write FName;
property ActiveLoans[const i: integer]: TLoan read GetLoan;
property ActiveLoansCount: integer read GetLoanCount;
procedure AddLoan(const ln: TLoan);
procedure RetrieveActiveLoans;
function IndexOf(const loan: TLoan): integer;
constructor Create;
end;
var
activeCln: TActiveClient;
implementation
uses
PaymentData, IFinanceGlobal, IFinanceDialogs, Payment;
constructor TActiveClient.Create;
begin
if activeCln = nil then inherited Create
else activeCln := self;
end;
procedure TActiveClient.AddLoan(const ln: TLoan);
begin
SetLength(FLoans,Length(FLoans)+1);
FLoans[Length(FLoans)-1] := ln;
end;
procedure TActiveClient.RetrieveActiveLoans;
var
loan: TLoan;
begin
// check if loans have been retrieved
// retrieve only once
if Length(FLoans) > 0 then Exit;
try
with dmPayment.dstActiveLoans do
begin
Open;
while not Eof do
begin
loan := TLoan.Create;
loan.Id := FieldByName('loan_id').AsString;
loan.Balance := FieldByName('balance').AsCurrency;
loan.PrincipalDeficit := FieldByName('prc_deficit').AsCurrency;
loan.InterestDeficit := FieldByName('int_deficit').AsCurrency;
loan.LoanTypeName := FieldByName('loan_type_name').AsString;
loan.AccountTypeName := FieldByName('acct_type_name').AsString;
loan.InterestMethod := FieldByName('int_comp_method').AsString;
loan.DiminishingType := TDiminishingType(FieldByName('dim_type').AsInteger);
loan.LastTransactionDate := FieldByName('last_transaction_date').AsDateTime;
loan.InterestInDecimal := FieldByName('int_rate').AsCurrency / 100;
loan.ApprovedTerm := FieldByName('terms').AsInteger;
loan.ReleaseAmount := FieldByName('rel_amt').AsCurrency;
loan.Payments := FieldByName('payments').AsInteger;
loan.PaymentsAdvance := FieldByName('payments_advance').AsInteger;
loan.Amortization := FieldByName('amort').AsCurrency;
loan.ReleaseDate := FieldByName('date_rel').AsDateTime;
// loan.LastInterestPostDate := GetLastInterestPostDate(loan.Id);
AddLoan(loan);
Next;
end;
end;
finally
dmPayment.dstActiveLoans.Close;
end;
end;
function TActiveClient.GetLastInterestPostDate(
const ALoanId: string): TDateTime;
begin
Result := 0;
with dmPayment.dstLastInterestPostDate do
begin
try
Parameters.ParamByName('@loan_id').Value := ALoanId;
Open;
if RecordCount > 0 then
Result := FieldByName('interest_date').AsDateTime
finally
Close;
end;
end;
end;
function TActiveClient.GetLoan(const i: integer): TLoan;
begin
Result := FLoans[i];
end;
function TActiveClient.GetLoanCount: integer;
begin
Result := Length(FLoans);
end;
function TActiveClient.IndexOf(const loan: TLoan): integer;
var
i: integer;
l: TLoan;
begin
for i := Low(FLoans) to High(FLoans) do
begin
l := FLoans[i];
if l.Id = loan.Id then
begin
Result := i;
Exit;
end;
end;
end;
{ TLoan }
procedure TLoan.AddLedger(const ALedger: TLedger);
begin
SetLength(FLedger,Length(FLedger)+1);
FLedger[Length(FLedger)-1] := ALedger;
end;
procedure TLoan.ClearLedger;
var
LLedger: TLedger;
i: integer;
begin
for i := Low(FLedger) to High(FLedger) do
begin
LLedger := FLedger[i];
FreeAndNil(LLedger);
end;
SetLength(FLedger,0);
end;
function TLoan.GetHasAdvancePayment: boolean;
begin
Result := FPaymentsAdvance > 0;
end;
function TLoan.GetHasInterestBalance: boolean;
begin
Result := FInterestDeficit > 0;
end;
function TLoan.GetHasInterestComputed: boolean;
begin
Result := FInterestComputed > 0;
end;
function TLoan.GetHasInterstAdditional: boolean;
begin
Result := FInterestAdditional > 0;
end;
function TLoan.GetHasRebate: boolean;
begin
Result := FRebate > 0;
end;
procedure TLoan.GetInterestDue(const paymentDate: TDateTime);
var
amort, additional, computed, full, tmp, rbt: currency;
LLedger, debitLedger: TLedger;
days: integer;
py, pm, pd, vy, vm, vd, ny, nm, nd: word;
scheduleDate: TDateTime;
begin
additional := 0; // payment after schedule date
computed := 0; // payment before schedule date
full := 0; // full payment
amort := 0; // amortisation for the month of payment date
tmp := 0; // stores the first amount in the Ledger.. used when no amortisation is found as of payment date
rbt := 0; // rebate
// will be used only for fixed accounts
// or diminishing scheduled accounts
DecodeDate(paymentDate,py,pm,pd);
// get any open accounts in the ledger
// can either be scheduled interest, balance of previous or both
for LLedger in FLedger do
begin
if (LLedger.EventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR))
and (LLedger.CaseType = TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS)) then
begin
if tmp = 0 then tmp := LLedger.Amortisation;
DecodeDate(LLedger.ValueDate,vy,vm,vd);
// amortisation and schedule date
if (vm = pm) and (vy = py) then
begin
amort := LLedger.Amortisation;
scheduleDate := LLedger.ValueDate;
end;
scheduleDate := LLedger.ValueDate;
end;
end; // end for loop
if amort = 0 then
begin
if ((IsDiminishing) and (DiminishingType = dtFixed)) then amort := (FBalance * FInterestInDecimal)
else amort := FReleaseAmount * FInterestInDecimal;
amort := RoundTo(amort,-2)
end;
// payment is made before or after schedule date
if ((IsDiminishing) and (DiminishingType = dtFixed)) then
begin
DecodeDate(NextPayment,ny,nm,nd);
if ((paymentDate <> NextPayment) and (paymentDate <> FLastTransactionDate)) then
begin
debitLedger := TLedger.Create;
debitLedger.EventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR);
debitLedger.CaseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
debitLedger.ValueDate := paymentDate;
debitLedger.CurrentStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
debitLedger.Credit := 0;
if paymentDate < NextPayment then // before schedule
begin
days := DaysBetween(paymentDate,FLastTransactionDate);
// check if this is the first payment
// check the rules for first payment
// only applicable when no advance payment is made
{if (IsFirstPayment) and (not HasAdvancePayment) then
begin
if ((days >= ifn.Rules.FirstPayment.MinDaysHalfInterest) and
(days <= ifn.Rules.FirstPayment.MaxDaysHalfInterest)) then
computed := (FBalance * FInterestInDecimal * ifn.HalfMonth) / ifn.DaysInAMonth
else computed := FBalance * FInterestInDecimal;
end
else}
computed := (FBalance * FInterestInDecimal) / ifn.DaysInAMonth;
// round off to 2 decimal places
computed := RoundTo(computed,-2) * days;
debitLedger.Debit := computed;
end
else // after schedule
begin
// additional interest
days := DaysBetween(scheduleDate,paymentDate);
// if payment date is more than a month from scheduled payment date
// divide the days with the days in a month and use the remainder
additional := (FBalance * FInterestInDecimal) / ifn.DaysInAMonth;
// round off to 2 decimal places before multiplying to number of days
additional := RoundTo(additional,-2) * days;
debitLedger.Debit := additional;
end;
if debitLedger.Debit > 0 then AddLedger(debitLedger);
end;
end
else // for full payment
begin
// note: set the FullpPayment property to true
debitLedger := TLedger.Create;
debitLedger.ValueDate := paymentDate;
debitLedger.CurrentStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
debitLedger.Credit := 0;
debitLedger.FullPayment := true;
if IsDiminishing then
begin
debitLedger.EventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR);
debitLedger.CaseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
days := DaysBetween(paymentDate,GetLatestInterestDate(paymentDate));
full := (FBalance * FInterestInDecimal * days) / ifn.DaysInAMonth;
// round off to 2 decimal places
full := RoundTo(full,-2);
debitLedger.Debit := full;
end
else
begin
// for fixed accounts
// calculate rebate if any
debitLedger.EventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.REB);
debitLedger.CaseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.RBT);
days := DaysBetween(paymentDate,GetLatestInterestDate(paymentDate));
// add 1 day.. to offset the first interest posting which is the following day of release
days := days + 1;
rbt := FInterestAmortisation - ((FReleaseAmount * FInterestInDecimal * days) / ifn.DaysInAMonth);
// round off to 2 decimal places
rbt := RoundTo(rbt,-2);
debitLedger.Debit := rbt;
end;
AddLedger(debitLedger);
end;;
// set the different amounts
FInterestAdditional := additional;
FInterestComputed := computed;
FFullPaymentInterest := full;
FInterestAmortisation := amort;
FRebate := rbt;
end;
function TLoan.GetInterestDueOnPaymentDate: currency;
begin
Result := 0;
if ((IsDiminishing) and (FDiminishingType = dtFixed)) then
begin
if (pmt.Date <> NextPayment) and (pmt.Date <> FLastTransactionDate) then
begin
if HasInterestComputed then Result := FInterestComputed
else if HasInterestAdditional then Result := FInterestAdditional
else Result := FInterestAmortisation;
end
else if pmt.Date = NextPayment then Result := FInterestAmortisation
else Result := 0;
end;
end;
function TLoan.GetInterestMethodName: string;
begin
if (FInterestMethod = 'D') and (DiminishingType = dtScheduled) then Result := 'Diminishing Scheduled'
else if FInterestMethod = 'D' then Result := 'Diminishing Fixed'
else Result := 'Fixed';
end;
function TLoan.GetInterestTotalDue: currency;
begin
if HasInterestAdditional then Result := FInterestDeficit + FInterestAdditional
else Result := FInterestDeficit + InterestDueOnPaymentDate;
end;
function TLoan.GetIsDiminishing: boolean;
begin
Result := FInterestMethod = 'D';
end;
function TLoan.GetIsFirstPayment: boolean;
begin
Result := FPayments = 0;
end;
function TLoan.GetIsFixed: boolean;
begin
Result := FInterestMethod = 'F';
end;
function TLoan.GetLatestInterestDate(const paymentDate: TDateTime): TDateTime;
var
LLedger: TLedger;
interestDate: TDateTime;
begin
interestDate := FLastTransactionDate;
for LLedger in FLedger do
begin
if (LLedger.EventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR))
and (LLedger.CaseType = TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS))then
if LLedger.ValueDate <= paymentDate then
if LLedger.ValueDate > interestDate then interestDate := LLedger.ValueDate;
end;
Result := interestDate;
end;
function TLoan.GetLedger(const i: integer): TLedger;
begin
Result := FLedger[i];
end;
function TLoan.GetLedgerCount: integer;
begin
Result := Length(FLedger);
end;
function TLoan.GetNextPayment: TDateTime;
var
LNextPayment: TDateTime;
mm, dd, yy, fm, fd, fy: word;
begin
if (IsFirstPayment) and (HasAdvancePayment) then
LNextPayment := IncMonth(FLastTransactionDate,FPaymentsAdvance)
else
begin
LNextPayment := IncMonth(FLastTransactionDate);
DecodeDate(FLastTransactionDate,fy,fm,fd);
DecodeDate(LNextPayment,yy,mm,dd);
if fd <> dd then
begin
if (DaysBetween(LNextPayment,FLastTransactionDate) < ifn.DaysInAMonth)
or (fd = 31) then
LNextPayment := IncDay(LNextPayment);
end;
end;
Result := LNextPayment;
end;
procedure TLoan.GetPaymentDue(const paymentDate: TDateTime);
var
caseType: TCaseTypes;
begin
// loop thru each case type
for caseType := TCaseTypes.ITS to TCaseTypes.PRC do
begin
case caseType of
ITS: GetInterestDue(paymentDate);
PRC: GetPrincipalDue(paymentDate);
end;
end;
end;
procedure TLoan.GetPrincipalDue(const paymentDate: TDateTime);
var
amort, tmp: currency;
LLedger: TLedger;
py, pm, pd, vy, vm, vd: word;
begin
amort := 0;
tmp := 0; // check the GetInterestDue function for usage of this variable
DecodeDate(paymentDate,py,pm,pd);
for LLedger in FLedger do
begin
if (LLedger.EventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.LON))
and (LLedger.CaseType = TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PRC))then
begin
if tmp = 0 then tmp := LLedger.Amortisation;
DecodeDate(LLedger.ValueDate,vy,vm,vd);
// only get the due for the month.. exclude balance
if (vm = pm) and (vy = py) then amort := LLedger.Amortisation;
end;
end;
if amort = 0 then amort := tmp;
FPrincipalAmortisation := amort;
end;
procedure TLoan.RetrieveLedger;
var
LLedger: TLedger;
begin
try
ClearLedger;
// loop thru the dataset
with dmPayment.dstSchedule do
begin
try
Parameters.ParamByName('@loan_id').Value := FId;
Open;
while not Eof do
begin
LLedger := TLedger.Create;
LLedger.PostingId := FieldByName('posting_id').AsString;
LLedger.EventObject := FieldByName('event_object').AsString;
LLedger.PrimaryKey := FieldByName('pk_event_object').AsString;
LLedger.ValueDate := FieldByName('value_date').AsDateTime;
LLedger.Amortisation := FieldByName('amortisation').AsCurrency;
LLedger.Debit := FieldByName('payment_due').AsCurrency;
LLedger.CaseType := FieldByName('case_type').AsString;
LLedger.CurrentStatus := FieldByName('status_code').AsString;
LLedger.HasPartial := FieldByName('has_partial').AsInteger = 1;
AddLedger(LLedger);
Next;
end;
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
finally
dmPayment.dstSchedule.Close;
end;
end;
end.
|
unit UEngineConfig;
interface
uses
windows,IniFiles,SysUtils;
const
C_ROOT = 'NgPlugin';
type
TEngineConfig = class
private
mActive:BOOL;
mDir:String; //模块所在目录
mCfgPath:String; //配置文件完整路径
mFileName:String;
mIni:TIniFile;
function GetIp: String;
function GetPort: Integer;
public
constructor Create(Handle:Cardinal;FileName:String);
destructor Destroy;override;
//是否加载成功
property Active:Bool read mActive;
//模块目录
property ModuleDir:String read mDir;
//控制台IP,端口
property ConsoleIp:String read GetIp;
property ConsolePort:Integer read GetPort;
end;
var
g_EngineConfig:TEngineConfig;
implementation
uses
GD_Utils;
{ TConfig }
constructor TEngineConfig.Create(Handle:Cardinal;FileName:String);
var
ModuleName:Array [0..MAX_PATH] of Char;
begin
mActive:=False;
try
if GetModuleFileName(Handle,ModuleName,MAX_PATH) > 0 then
begin
mFileName:=FileName;
mDir:=ExtractFileDir(ModuleName);
mCfgPath:=Format('%s\%s',[mDir,FileName]);
mActive:=FileExists(mCfgPath);
if mActive then
mIni:=TIniFile.Create(mCfgPath);
end;
except
LogPrintf('Config Load Error',[]);
end;
end;
destructor TEngineConfig.Destroy;
begin
mIni.Free;
end;
function TEngineConfig.GetIp: String;
begin
Result:=mIni.ReadString(C_ROOT,'Ip','');
end;
function TEngineConfig.GetPort: Integer;
begin
Result:=mIni.ReadInteger(C_ROOT,'Port',0);
end;
end.
|
program Sample;
var
H, G : String;
begin
H := 'Hello World';
G := H;
H[1] := 'M';
WriteLn('G: ', G);
WriteLn('H: ', H);
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Abstract TBIGridPlugin class }
{ Copyright (c) 2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.Grid.Plugin;
interface
uses
System.Classes,
BI.DataItem, BI.UI, Data.DB;
type
TBIGridPluginClass=class of TBIGridPlugin;
// Pending: Try to merge VCL and FMX TBIGridPlugin classes into a single one.
// Abstract class to define Grid control classes as "plugins" of TBIGrid.
// See VCLBI.Grid.DBGrid unit for an example, using the VCL TDBGrid.
TBIGridPlugin=class abstract
protected
IAlternate : TAlternateColor;
procedure AutoWidth; virtual; abstract;
procedure ChangedAlternate(Sender:TObject); virtual; abstract;
function GetCanSort: Boolean; virtual; abstract;
function GetDataSource: TDataSource; virtual; abstract;
function GetEditorClass:String; virtual; abstract;
function GetReadOnly:Boolean; virtual; abstract;
function GetSortEnabled: Boolean; virtual; abstract;
function GetTotals:Boolean; virtual; abstract;
procedure SetDataSource(const Value: TDataSource); virtual; abstract;
procedure SetFilters(const Value:Boolean); virtual; abstract;
procedure SetOnRowChanged(const AEvent:TNotifyEvent); virtual; abstract;
procedure SetReadOnly(const Value:Boolean); virtual; abstract;
procedure SetRowNumber(const Value:Boolean); virtual; abstract;
procedure SetPopup(const Value:TObject); virtual; abstract;
procedure SetSearch(const Value:Boolean); virtual; abstract;
procedure SetSortEnabled(const Value: Boolean); virtual; abstract;
procedure SetTotals(const Value:Boolean); virtual; abstract;
public
Constructor Create(const AOwner:TComponent); virtual; abstract;
procedure BindTo(const ADataSet:TDataSet); virtual; abstract;
procedure Colorize(const AItems:TDataColorizers); virtual; abstract;
procedure Duplicates(const AData:TDataItem; const Hide:Boolean); virtual; abstract;
function GetControl:TObject; virtual; abstract; // Returns TObject, for compat VCL <-> FMX
function GetObject:TObject; virtual; abstract;
property CanSort:Boolean read GetCanSort;
property DataSource:TDataSource read GetDataSource write SetDataSource;
property EditorClass:String read GetEditorClass;
property ReadOnly:Boolean read GetReadOnly write SetReadOnly;
property SortEnabled:Boolean read GetSortEnabled write SetSortEnabled;
property Totals:Boolean read GetTotals write SetTotals;
end;
implementation
|
unit Stats.PedsTraceData;
interface
uses
Stats.IO.Base,
Stats.Constant;
type
TPedTestTraceData = class (TTraceDataObj)
strict private
FSimTime: TDateTime;
FID: integer;
FName: String;
public
property SimTime: TDateTime read FSimTime write FSimTime;
property ID: integer read FID write FID;
property Name: String read FName write FName;
end;
TPedTraceData = class(TTraceDataObj)
strict private
aPedID: Integer; /// ID chodca
aPedPathID: Integer; /// ID typu
aPedCount : Integer;
public
property PedID: Integer read aPedID write aPedID;
property PedPathID: Integer read aPedPathID write aPedPathID;
property PedCount: Integer read aPedCount write aPedCount;
end;
TPedProjectTraceData = class(TTraceDataObj)
strict private
aModelID: Integer;
aConfigID: Integer;
aTraceID: Integer;
aReplicationID: Integer;
aReplicationInterupted: Boolean;
public
property ModelID: Integer read aModelID write aModelID;
property ConfigID: Integer read aConfigID write aConfigID;
property TraceID: Integer read aTraceID write aTraceID;
property ReplicationID: Integer read aReplicationID write aReplicationID;
property ReplicationInterupted: Boolean read aReplicationInterupted write aReplicationInterupted;
end;
TPedPositionTraceData = class(TTraceDataObj)
strict private
aSimTime: Extended;
aEntityID: Integer;
aX,aY,aZ: Single;
aRotation: Single;
aZoneID: Integer;
public
property SimTime: Extended read aSimTime write aSimTime;
property EntityID: Integer read aEntityID write aEntityID;
property X: Single read aX write aX;
property Y: Single read aY write aY;
property Z: Single read aZ write aZ;
property Rotation: Single read aRotation write aRotation;
property ZoneID: Integer read aZoneID write aZoneID;
end;
TPedEventsTraceData = class(TTraceDataObj)
strict private
aSimTime: TDateTime; /// Cas výskytu udalosti
aPedID: Integer; /// ID chodca, ktorého sa udalost tyka
aEntityID: Integer; /// ID entity, ktorej sa udalost týka
aEventType: TEventType; /// Typ udalosti
public
property SimTime: TDateTime read aSimTime write aSimTime;
property PedID: Integer read aPedID write aPedID;
property EntityID: Integer read aEntityID write aEntityID;
property EventType: TEventType read aEventType write aEventType;
end;
TPedElevatorTraceData = class(TTraceDataObj)
strict private
aElevatorID: Integer;
aEventType: TStatElevatorEvent;
aLevelID: Integer;
aSimTime: Double;
public
property ElevatorID: Integer read aElevatorID write aElevatorID;
property EventType: TStatElevatorEvent read aEventType write aEventType ;
property LevelID: Integer read aLevelID write aLevelID;
property SimTime: Double read aSimTime write aSimTime;
end;
TPedStartEndTraceData = class(TTraceDataObj)
strict private
aPedID: Integer;
aStartID: Integer;
aStartTime: TDateTime;
aEndID: Integer;
aEndTime: TDateTime;
aTime: string;
public
property PedID: Integer read aPedID write aPedID;
property StartID: Integer read aStartID write aStartID;
property StartTime: TDateTime read aStartTime write aStartTime;
property EndID: Integer read aEndID write aEndID;
property EndTime: TDateTime read aEndTime write aEndTime;
property Time: string read aTime write aTime;
end;
TPedMacroGraphTraceData = class(TTraceDataObj)
strict private
aEdgeID: Integer;
aSimTime: TDateTime;
aDensity: Double;
public
property EdgeID: Integer read aEdgeID write aEdgeID;
property SimTime: TDateTime read aSimTime write aSimTime;
property Density: Double read aDensity write aDensity;
end;
TPedModelTraceData = class(TTraceDataObj)
strict private
aModelID: Integer;
aModelName: string;
public
property ModelID: Integer read aModelID write aModelID;
property ModelName: string read aModelName write aModelName;
end;
TPedTraceTraceData = class(TTraceDataObj)
strict private
aTraceID: Integer;
aTraceName: string;
public
property TraceID: Integer read aTraceID write aTraceID;
property TraceName: string read aTraceName write aTraceName;
end;
implementation
end.
|
unit uReminders;
interface
uses
Windows, Messages, Classes, Controls, StdCtrls, SysUtils, ComCtrls, Menus,
Graphics, Forms, ORClasses, ORCtrls, ORDtTm, ORFn, ORNet, Dialogs, uPCE,
uVitals,
ExtCtrls, fDrawers, fDeviceSelect, TypInfo, StrUtils,fRptBox;
type
TReminderDialog = class(TObject)
private
FDlgData: string;
FElements: TStringList; // list of TRemDlgElement objects
FOnNeedRedraw: TNotifyEvent;
FNeedRedrawCount: integer;
FOnTextChanged: TNotifyEvent;
FTextChangedCount: integer;
FPCEDataObj: TPCEData;
FNoResolve: boolean;
FWHReviewIEN: string;
// AGP CHANGE 23.13 Allow for multiple processing of WH Review of Result Reminders
FRemWipe: integer;
FMHTestArray: TORStringList;
FPromptsDefaults: TStringList;
protected
linkSeqList: TStrings;
linkSeqListChecked: TStrings;
function GetIEN: string; virtual;
function GetPrintName: string; virtual;
procedure BeginNeedRedraw;
procedure EndNeedRedraw(Sender: TObject);
procedure BeginTextChanged;
procedure EndTextChanged(Sender: TObject);
function GetDlgSL: TORStringList;
procedure ComboBoxResized(Sender: TObject);
procedure ComboBoxCheckedText(Sender: TObject; NumChecked: integer;
var Text: string);
function AddData(Lst: TStrings; Finishing: boolean = FALSE;
Historical: boolean = FALSE): integer;
function Visible: boolean;
procedure findLinkItem(elementList, promptList: TStringList; startSeq: String);
public
constructor BaseCreate;
constructor Create(ADlgData: string);
destructor Destroy; override;
procedure FinishProblems(List: TStrings;
var MissingTemplateFields: boolean);
function BuildControls(ParentWidth: integer; AParent, AOwner: TWinControl)
: TWinControl;
function Processing: boolean;
procedure AddText(Lst: TStrings);
procedure closeReportView;
property PrintName: string read GetPrintName;
property IEN: string read GetIEN;
property Elements: TStringList read FElements;
property OnNeedRedraw: TNotifyEvent read FOnNeedRedraw write FOnNeedRedraw;
property OnTextChanged: TNotifyEvent read FOnTextChanged
write FOnTextChanged;
property PCEDataObj: TPCEData read FPCEDataObj write FPCEDataObj;
property DlgData: string read FDlgData; // AGP Change 24.8
property WHReviewIEN: string read FWHReviewIEN write FWHReviewIEN;
// AGP CHANGE 23.13
property RemWipe: integer read FRemWipe write FRemWipe;
property MHTestArray: TORStringList read FMHTestArray write FMHTestArray;
end;
TReminder = class(TReminderDialog)
private
FRemData: string;
FCurNodeID: string;
protected
function GetDueDateStr: string;
function GetLastDateStr: string;
function GetIEN: string; override;
function GetPrintName: string; override;
function GetPriority: integer;
function GetStatus: string;
public
constructor Create(ARemData: string);
property DueDateStr: string read GetDueDateStr;
property LastDateStr: string read GetLastDateStr;
property Priority: integer read GetPriority;
property Status: string read GetStatus;
property RemData: string read FRemData;
property CurrentNodeID: string read FCurNodeID write FCurNodeID;
end;
TRDChildReq = (crNone, crOne, crAtLeastOne, crNoneOrOne, crAll);
TRDElemType = (etCheckBox, etTaxonomy, etDisplayOnly, etChecked, etDisable);
TRemPrompt = class;
TRemDlgElement = class(TObject)
private
FReminder: TReminderDialog;
FParent: TRemDlgElement;
FChildren: TList; // Points to other TRemDlgElement objects
FData: TList; // List of TRemData objects
FPrompts: TList; // list of TRemPrompts objects
FText: string;
FPNText: string;
FRec1: string;
FID: string;
FDlgID: string;
FHaveData: boolean;
FTaxID: string;
FChecked: boolean;
FChildrenShareChecked: boolean;
FHasSharedPrompts: boolean;
FHasComment: boolean;
FHasSubComments: boolean;
FCommentPrompt: TRemPrompt;
FFieldValues: TORStringList;
FMSTPrompt: TRemPrompt;
FWHPrintDevice, FWHResultChk, FWHResultNot: String;
FVitalDateTime: TFMDateTime; // AGP Changes 26.1
FInitialChecked: boolean;
protected
originalType: String;
function buildLinkSeq(linkIEN, dialogIEN, seq: string): boolean;
procedure Check4ChildrenSharedPrompts;
function ShowChildren: boolean;
function EnableChildren: boolean;
function Enabled: boolean;
procedure SetChecked(const Value: boolean);
procedure UpdateData;
function oneValidCode(Choices: TORStringList; ChoicesActiveDates: TList;
encDt: TFMDateTime): String;
procedure setActiveDates(Choices: TORStringList; ChoicesActiveDates: TList;
ActiveDates: TStringList);
procedure GetData;
function TrueIndent: integer;
procedure cbClicked(Sender: TObject);
procedure cbEntered(Sender: TObject);
procedure linkItemRedraw(element: TRemDlgElement);
procedure FieldPanelEntered(Sender: TObject);
procedure FieldPanelExited(Sender: TObject);
procedure FieldPanelKeyPress(Sender: TObject; var Key: Char);
procedure FieldPanelOnClick(Sender: TObject);
procedure FieldPanelLabelOnClick(Sender: TObject);
function BuildControls(var Y: integer; ParentWidth: integer;
BaseParent, AOwner: TWinControl): TWinControl;
function AddData(Lst: TStrings; Finishing: boolean;
AHistorical: boolean = FALSE): integer;
procedure FinishProblems(List: TStrings);
function IsChecked: boolean;
procedure SubCommentChange(Sender: TObject);
function EntryID: string;
procedure FieldPanelChange(Sender: TObject);
procedure GetFieldValues(FldData: TStrings);
procedure ParentCBEnter(Sender: TObject);
procedure ParentCBExit(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
function ElemType: TRDElemType;
function Add2PN: boolean;
function Indent: integer;
function FindingType: string;
function Historical: boolean;
function ResultDlgID: string;
function IncludeMHTestInPN: boolean;
function HideChildren: boolean;
function ChildrenIndent: integer;
function ChildrenSharePrompts: boolean;
function ChildrenRequired: TRDChildReq;
function Box: boolean;
function BoxCaption: string;
function IndentChildrenInPN: boolean;
function IndentPNLevel: integer;
function GetTemplateFieldValues(const Text: string;
FldValues: TORStringList = nil): string;
procedure AddText(Lst: TStrings);
property Text: string read FText;
property ID: string read FID;
property DlgID: string read FDlgID;
property Checked: boolean read FChecked write SetChecked;
property Reminder: TReminderDialog read FReminder;
property HasComment: boolean read FHasComment;
property WHPrintDevice: String read FWHPrintDevice write FWHPrintDevice;
property WHResultChk: String read FWHResultChk write FWHResultChk;
property WHResultNot: String read FWHResultNot write FWHResultNot;
property VitalDateTime: TFMDateTime read FVitalDateTime
write FVitalDateTime;
end;
TRemDataType = (dtDiagnosis, dtProcedure, dtPatientEducation, dtExam,
dtHealthFactor, dtImmunization, dtSkinTest, dtVitals, dtOrder,
dtMentalHealthTest, dtWHPapResult, dtWhNotPurp, dtGenFindings);
TRemPCERoot = class;
TRemData = class(TObject)
private
FPCERoot: TRemPCERoot;
FParent: TRemDlgElement;
FRec3: string;
FActiveDates: TStringList; // Active dates for finding items. (rectype 3)
// FRoot: string;
FChoices: TORStringList;
FChoicesActiveDates: TList;
// Active date ranges for taxonomies. (rectype 5)
// List of TStringList objects that contain active date
// ranges for each FChoices object of the same index
FChoicePrompt: TRemPrompt; // rectype 4
FChoicesMin: integer;
FChoicesMax: integer;
FChoicesFont: THandle;
FSyncCount: integer;
protected
function AddData(List: TStrings; Finishing: boolean): integer;
public
destructor Destroy; override;
function Add2PN: boolean;
function DisplayWHResults: boolean;
function InternalValue: string;
function ExternalValue: string;
function Narrative: string;
function Category: string;
function DataType: TRemDataType;
property Parent: TRemDlgElement read FParent;
end;
TRemPromptType = (ptComment, ptVisitLocation, ptVisitDate, ptQuantity,
ptPrimaryDiag, ptAdd2PL, ptExamResults, ptSkinResults, ptSkinReading,
ptLevelSeverity, ptSeries, ptReaction, ptContraindicated,
ptLevelUnderstanding, ptWHPapResult, ptWHNotPurp, ptDate, ptDateTime, ptView, ptPrint);
TRemPrompt = class(TObject)
private
FFromControl: boolean;
FParent: TRemDlgElement;
FRec4: string;
FCaptionAssigned: boolean;
FData: TRemData;
FValue: string;
FOverrideType: TRemPromptType;
FIsShared: boolean;
FSharedChildren: TList;
FCurrentControl: TControl;
FFromParent: boolean;
FInitializing: boolean;
FMiscText: string;
FMonthReq: boolean;
FPrintNow: String;
FMHTestComplete: integer;
FValidate: String;
ViewRecord: boolean;
reportView: TfrmReportBox;
FOldReportViewOnDestroy: TNotifyEvent;
procedure reportViewClosed(Sender: TObject);
protected
function RemDataActive(RData: TRemData; encDt: TFMDateTime): boolean;
function CompareActiveDate(ActiveDates: TStringList;
encDt: TFMDateTime): boolean;
function RemDataChoiceActive(RData: TRemData; j: integer;
encDt: TFMDateTime): boolean;
function GetValue: string;
procedure SetValueFromParent(Value: string);
procedure SetValue(Value: string);
procedure PromptChange(Sender: TObject);
procedure VitalVerify(Sender: TObject);
procedure ComboBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
function CanShare(Prompt: TRemPrompt): boolean;
procedure InitValue;
procedure DoMHTest(Sender: TObject);
procedure DoView(Sender: TObject);
procedure DoWHReport(Sender: TObject);
procedure ViewWHText(Sender: TObject);
procedure GAFHelp(Sender: TObject);
function EntryID: string;
procedure EditKeyPress(Sender: TObject; var Key: Char);
function EventType: string;
public
constructor Create;
destructor Destroy; override;
function PromptOK: boolean;
function PromptType: TRemPromptType;
function Add2PN: boolean;
function InternalValue: string;
function Forced: boolean;
function Caption: string;
function ForcedCaption: string;
function SameLine: boolean;
function Required: boolean;
function NoteText: string;
function VitalType: TVitalType;
function VitalValue: string;
function VitalUnitValue: string;
property Value: string read GetValue write SetValue;
property validate: string read FValidate write FValidate;
end;
TRemPCERoot = class(TObject)
private
FData: TList;
FID: string;
FForcedPrompts: TStringList;
FValue: string;
FValueSet: string;
protected
class function GetRoot(Data: TRemData; Rec3: string; Historical: boolean)
: TRemPCERoot;
procedure Done(Data: TRemData);
procedure Sync(Prompt: TRemPrompt);
procedure UnSync(Prompt: TRemPrompt);
function GetValue(PromptType: TRemPromptType; var NewValue: string)
: boolean;
public
destructor Destroy; override;
end;
TReminderStatus = (rsDue, rsApplicable, rsNotApplicable, rsNone, rsUnknown);
TRemCanFinishProc = function: boolean of object;
TRemDisplayPCEProc = procedure of object;
TTreeChangeNotifyEvent = procedure(Proc: TNotifyEvent) of object;
TRemForm = record
Form: TForm;
PCEObj: TPCEData;
RightPanel: TPanel;
CanFinishProc: TRemCanFinishProc;
DisplayPCEProc: TRemDisplayPCEProc;
DrawerReminderTV: TORTreeView;
DrawerReminderTreeChange: TTreeChangeNotifyEvent;
DrawerRemoveReminderTreeChange: TTreeChangeNotifyEvent;
NewNoteRE: TRichEdit;
NoteList: TORListBox;
end;
var
RemForm: TRemForm;
NotPurposeValue: string;
WHRemPrint: string;
InitialRemindersLoaded: boolean = FALSE;
const
HAVE_REMINDERS = 0;
NO_REMINDERS = 1;
RemPriorityText: array [1 .. 3] of string = ('High', '', 'Low');
ClinMaintText = 'Clinical Maintenance';
dtUnknown = TRemDataType(-1);
dtAll = TRemDataType(-2);
dtHistorical = TRemDataType(-3);
ptUnknown = TRemPromptType(-1);
ptSubComment = TRemPromptType(-2);
ptDataList = TRemPromptType(-3);
ptVitalEntry = TRemPromptType(-4);
ptMHTest = TRemPromptType(-5);
ptGAF = TRemPromptType(-6);
ptMST = TRemPromptType(-7);
MSTCode = 'MST';
MSTDataTypes = [pdcHF, pdcExam];
pnumMST = ord(pnumComment) + 4;
procedure NotifyWhenRemindersChange(Proc: TNotifyEvent);
procedure RemoveNotifyRemindersChange(Proc: TNotifyEvent);
procedure StartupReminders;
function GetReminderStatus: TReminderStatus;
function RemindersEvaluatingInBackground: boolean;
procedure ResetReminderLoad;
procedure LoadReminderData(ProcessingInBackground: boolean = FALSE);
function ReminderEvaluated(Data: string; ForceUpdate: boolean = FALSE): boolean;
procedure RemindersEvaluated(List: TStringList);
procedure EvalReminder(IEN: integer);
procedure EvalProcessed;
procedure EvaluateCategoryClicked(AData: pointer; Sender: TObject);
procedure SetReminderPopupRoutine(Menu: TPopupMenu);
procedure SetReminderPopupCoverRoutine(Menu: TPopupMenu);
procedure SetReminderMenuSelectRoutine(Menu: TMenuItem);
procedure BuildReminderTree(Tree: TORTreeView);
function ReminderNode(Node: TTreeNode): TORTreeNode;
procedure ClearReminderData;
function GetReminder(ARemData: string): TReminder;
procedure WordWrap(AText: string; Output: TStrings; LineLength: integer;
AutoIndent: integer = 4; MHTest: boolean = FALSE);
function InteractiveRemindersActive: boolean;
function GetReminderData(Rem: TReminderDialog; Lst: TStrings;
Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; overload;
function GetReminderData(Lst: TStrings; Finishing: boolean = FALSE;
Historical: boolean = FALSE): integer; overload;
procedure SetReminderFormBounds(Frm: TForm; DefX, DefY, DefW, DefH, ALeft, ATop,
AWidth, AHeight: integer);
procedure UpdateReminderDialogStatus;
// Added to interface to allow Coversheet to use exact same menu structure
procedure ReminderMenuBuilder(MI: TMenuItem; RemStr: string; IncludeActions, IncludeEval, ViewFolders: boolean);
function PXRMWorking: boolean;
procedure PXRMDoneWorking;
// const
// InteractiveRemindersActive = FALSE;
var
{ ActiveReminder string format:
IEN^PRINT NAME^DUE DATE/TIME^LAST OCCURENCE DATE/TIME^PRIORITY^DUE^DIALOG
where PRIORITY 1=High, 2=Normal, 3=Low
DUE 0=Applicable, 1=Due, 2=Not Applicable }
ActiveReminders: TORStringList = nil;
{ OtherReminder string format:
IDENTIFIER^TYPE^NAME^PARENT IDENTIFIER^REMINDER IEN^DIALOG
where TYPE C=Category, R=Reminder }
OtherReminders: TORStringList = nil;
RemindersInProcess: TORStringList = nil;
CoverSheetRemindersInBackground: boolean = FALSE;
KillReminderDialogProc: procedure(Frm: TForm) = nil;
RemindersStarted: boolean = FALSE;
ProcessedReminders: TORStringList = nil;
ReminderDialogInfo: TStringList = nil;
uPXRMWorkingCount: integer = 0;
const
CatCode = 'C';
RemCode = 'R';
EduCode = 'E';
pnumVisitLoc = pnumComment + 1;
pnumVisitDate = pnumComment + 2;
RemTreeDateIdx = 8;
IncludeParentID = ';';
OtherCatID = CatCode + '-6';
RemDataCodes: array [TRemDataType] of string =
{ dtDiagnosis } ('POV',
{ dtProcedure } 'CPT',
{ dtPatientEducation } 'PED',
{ dtExam } 'XAM',
{ dtHealthFactor } 'HF',
{ dtImmunization } 'IMM',
{ dtSkinTest } 'SK',
{ dtVitals } 'VIT',
{ dtOrder } 'Q',
{ dtMentalHealthTest } 'MH',
{ dtWHPapResult } 'WHR',
{ dtWHNotPurp } 'WH',
{ dtGenFindings } 'GFIND');
implementation
uses
rCore, uCore, rReminders, uConst, fReminderDialog, fNotes, rMisc,
fMHTest, rPCE, rTemplates, dShared, uTemplateFields, fIconLegend,
fReminderTree, uInit,
VAUtils, VA508AccessibilityRouter, VA508AccessibilityManager, uDlgComponents,
fBase508Form, System.Types, System.UITypes;
type
TRemFolder = (rfUnknown, rfDue, rfApplicable, rfNotApplicable,
rfEvaluated, rfOther);
TRemFolders = set of TRemFolder;
TValidRemFolders = succ(low(TRemFolder)) .. high(TRemFolder);
TExposedComponent = class(TControl);
TWHCheckBox = class(TCPRSDialogCheckBox)
private
FPrintNow: TCPRSDialogCheckBox;
FViewLetter: TCPRSDialogCheckBox;
FCheck1: TWHCheckBox;
FCheck2: TWHCheckBox;
FCheck3: TWHCheckBox;
FEdit: TEdit;
FButton: TButton;
FOnDestroy: TNotifyEvent;
Flbl, Flbl2: TControl;
FPrintVis: String;
// FPrintDevice: String;
FPntNow: String;
FPntBatch: String;
FButtonText: String;
FCheckNum: String;
protected
public
property lbl: TControl read Flbl write Flbl;
property lbl2: TControl read Flbl2 write Flbl2;
property PntNow: String read FPntNow write FPntNow;
property PntBatch: String read FPntBatch write FPntBatch;
property CheckNum: String read FCheckNum write FCheckNum;
property ButtonText: String read FButtonText write FButtonText;
property PrintNow: TCPRSDialogCheckBox read FPrintNow write FPrintNow;
property Check1: TWHCheckBox read FCheck1 write FCheck1;
property Check2: TWHCheckBox read FCheck2 write FCheck2;
property Check3: TWHCheckBox read FCheck3 write FCheck3;
property ViewLetter: TCPRSDialogCheckBox read FViewLetter write FViewLetter;
property Button: TButton read FButton write FButton;
property Edit: TEdit read FEdit write FEdit;
property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy;
property PrintVis: String read FPrintVis write FPrintVis;
end;
var
LastReminderLocation: integer = -2;
EvaluatedReminders: TORStringList = nil;
ReminderTreeMenu: TORPopupMenu = nil;
ReminderTreeMenuDlg: TORPopupMenu = nil;
ReminderCatMenu: TPopupMenu = nil;
EducationTopics: TORStringList = nil;
WebPages: TORStringList = nil;
ReminderCallList: TORStringList = nil;
LastProcessingList: string = '';
InteractiveRemindersActiveChecked: boolean = FALSE;
InteractiveRemindersActiveStatus: boolean = FALSE;
PCERootList: TStringList;
PrimaryDiagRoot: TRemPCERoot = nil;
ElementChecked: TRemDlgElement = nil;
HistRootCount: longint = 0;
uRemFolders: TRemFolders = [rfUnknown];
const
DueText = 'Due';
ApplicableText = 'Applicable';
NotApplicableText = 'Not Applicable';
EvaluatedText = 'All Evaluated';
OtherText = 'Other Categories';
DueCatID = CatCode + '-2';
DueCatString = DueCatID + U + DueText;
ApplCatID = CatCode + '-3';
ApplCatString = ApplCatID + U + ApplicableText;
NotApplCatID = CatCode + '-4';
NotApplCatString = NotApplCatID + U + NotApplicableText;
EvaluatedCatID = CatCode + '-5';
EvaluatedCatString = EvaluatedCatID + U + EvaluatedText;
// OtherCatID = CatCode + '-6';
OtherCatString = OtherCatID + U + OtherText;
LostCatID = CatCode + '-7';
LostCatString = LostCatID + U + 'In Process';
ReminderDateFormat = 'mm/dd/yyyy';
RemData2PCECat: array [TRemDataType] of TPCEDataCat =
{ dtDiagnosis } (pdcDiag,
{ dtProcedure } pdcProc,
{ dtPatientEducation } pdcPED,
{ dtExam } pdcExam,
{ dtHealthFactor } pdcHF,
{ dtImmunization } pdcImm,
{ dtSkinTest } pdcSkin,
{ dtVitals } pdcVital,
{ dtOrder } pdcOrder,
{ dtMentalHealthTest } pdcMH,
{ dtWHPapResult } pdcWHR,
{ dtWHNotPurp } pdcWH,
{ dtGenFindings } pdcGenFinding);
RemPromptCodes: array [TRemPromptType] of string =
{ ptComment } ('COM',
{ ptVisitLocation } 'VST_LOC',
{ ptVisitDate } 'VST_DATE',
{ ptQuantity } 'CPT_QTY',
{ ptPrimaryDiag } 'POV_PRIM',
{ ptAdd2PL } 'POV_ADD',
{ ptExamResults } 'XAM_RES',
{ ptSkinResults } 'SK_RES',
{ ptSkinReading } 'SK_READ',
{ ptLevelSeverity } 'HF_LVL',
{ ptSeries } 'IMM_SER',
{ ptReaction } 'IMM_RCTN',
{ ptContraindicated } 'IMM_CNTR',
{ ptLevelUnderstanding } 'PED_LVL',
{ ptWHPapResult } 'WH_PAP_RESULT',
{ ptWHNotPurp } 'WH_NOT_PURP',
{ ptDate } 'DATE',
{ ptDateTime } 'DATE_TIME',
{ptView} 'GF_VIEW',
{ptPrint} 'GF_PRINT');
RemPromptTypes: array [TRemPromptType] of TRemDataType =
{ ptComment } (dtAll,
{ ptVisitLocation } dtHistorical,
{ ptVisitDate } dtHistorical,
{ ptQuantity } dtProcedure,
{ ptPrimaryDiag } dtDiagnosis,
{ ptAdd2PL } dtDiagnosis,
{ ptExamResults } dtExam,
{ ptSkinResults } dtSkinTest,
{ ptSkinReading } dtSkinTest,
{ ptLevelSeverity } dtHealthFactor,
{ ptSeries } dtImmunization,
{ ptReaction } dtImmunization,
{ ptContraindicated } dtImmunization,
{ ptLevelUnderstanding } dtPatientEducation,
{ ptWHPapResult } dtWHPapResult,
{ ptWHNotPurp } dtWhNotPurp,
{ ptDate } dtAll,
{ ptDateTime } dtGenFindings,
{ ptView} dtGenFindings,
{ ptPrint} dtGenFindings);
FinishPromptPieceNum: array [TRemPromptType] of integer =
{ ptComment } (pnumComment,
{ ptVisitLocation } pnumVisitLoc,
{ ptVisitDate } pnumVisitDate,
{ ptQuantity } pnumProcQty,
{ ptPrimaryDiag } pnumDiagPrimary,
{ ptAdd2PL } pnumDiagAdd2PL,
{ ptExamResults } pnumExamResults,
{ ptSkinResults } pnumSkinResults,
{ ptSkinReading } pnumSkinReading,
{ ptLevelSeverity } pnumHFLevel,
{ ptSeries } pnumImmSeries,
{ ptReaction } pnumImmReaction,
{ ptContraindicated } pnumImmContra,
{ ptLevelUnderstanding } pnumPEDLevel,
{ ptWHPapResult } pnumWHPapResult,
{ ptWHNotPurp } pnumWHNotPurp,
{ ptDate } pnumDate,
{ ptDateTime } pnumDate,
{ ptView} pnumGFPrint,
{ ptPrint} pnumGFPrint);
ComboPromptTags: array [TRemPromptType] of integer =
{ ptComment } (0,
{ ptVisitLocation } TAG_HISTLOC,
{ ptVisitDate } 0,
{ ptQuantity } 0,
{ ptPrimaryDiag } 0,
{ ptAdd2PL } 0,
{ ptExamResults } TAG_XAMRESULTS,
{ ptSkinResults } TAG_SKRESULTS,
{ ptSkinReading } 0,
{ ptLevelSeverity } TAG_HFLEVEL,
{ ptSeries } TAG_IMMSERIES,
{ ptReaction } TAG_IMMREACTION,
{ ptContraindicated } 0,
{ ptLevelUnderstanding } TAG_PEDLEVEL,
{ ptWHPapResult } 0,
{ ptWHNotPurp } 0,
{ ptDate } 0,
{ ptDateTime } 0,
{ ptView } 0,
{ ptPrint} 0);
PromptDescriptions: array [TRemPromptType] of string =
{ ptComment } ('Comment',
{ ptVisitLocation } 'Visit Location',
{ ptVisitDate } 'Visit Date',
{ ptQuantity } 'Quantity',
{ ptPrimaryDiag } 'Primary Diagnosis',
{ ptAdd2PL } 'Add to Problem List',
{ ptExamResults } 'Exam Results',
{ ptSkinResults } 'Skin Test Results',
{ ptSkinReading } 'Skin Test Reading',
{ ptLevelSeverity } 'Level of Severity',
{ ptSeries } 'Series',
{ ptReaction } 'Reaction',
{ ptContraindicated } 'Repeat Contraindicated',
{ ptLevelUnderstanding } 'Level of Understanding',
{ ptWHPapResult } 'Women''s Health Procedure',
{ ptWHNotPurp } 'Women Health Notification Purpose',
{ ptDate } 'Date',
{ ptDateTime } 'Date\Time',
{ ptView} 'General Finding View',
{ ptPrint} 'General Finding Print');
RemFolderCodes: array [TValidRemFolders] of Char =
{ rfDue } ('D',
{ rfApplicable } 'A',
{ rfNotApplicable } 'N',
{ rfEvaluated } 'E',
{ rfOther } 'O');
MSTDescTxt: array [0 .. 4, 0 .. 1] of string = (('Yes', 'Y'), ('No', 'N'),
('Declined', 'D'), ('Normal', 'N'), ('Abnormal', 'A'));
SyncPrompts = [ptComment, ptQuantity, ptAdd2PL, ptExamResults, ptSkinResults,
ptSkinReading, ptLevelSeverity, ptSeries, ptReaction, ptContraindicated,
ptLevelUnderstanding];
Gap = 3;
LblGap = 4;
IndentGap = 18;
PromptGap = 10;
NewLinePromptGap = 18;
IndentMult = 9;
PromptIndent = 30;
gbLeftIndent = 2;
gbTopIndent = 9;
gbTopIndent2 = 16;
DisabledFontColor = clBtnShadow;
r3Type = 4;
r3Code2 = 6;
r3Code = 7;
r3Cat = 9;
r3Nar = 8;
r3GAF = 12;
r3GenFindID = 14;
r3GenFindNewData = 16;
r3GenFindDataGroup = 17;
r3GenFindPrinter = 18;
RemTreeCode = 999;
CRCode = '<br>';
CRCodeLen = length(CRCode);
REMEntryCode = 'REM';
MonthReqCode = 'M';
HistCode = 'H';
EncDateCode = 'E';
FutureCode = 'F';
AnyDateCode = 'A';
function PXRMWorking: boolean;
begin
Result := (uPXRMWorkingCount > 0);
if not Result then
inc(uPXRMWorkingCount);
end;
procedure PXRMDoneWorking;
begin
if uPXRMWorkingCount > 0 then
dec(uPXRMWorkingCount);
end;
function InitText(const InStr: string): string;
var
i: integer;
begin
Result := InStr;
if (copy(Result, 1, CRCodeLen) = CRCode) then
begin
i := pos(CRCode, copy(Result, CRCodeLen + 1, MaxInt));
if (i > 0) and ((i = (CRCodeLen + 1)) or
(Trim(copy(Result, CRCodeLen + 1, i - 1)) = '')) then
delete(Result, 1, CRCodeLen + i - 1);
end;
end;
function CRLFText(const InStr: string): string;
begin
Result := StringReplace(InStr, '<br>', CRLF, [rfReplaceAll]);
end;
function Code2VitalType(Code: string): TVitalType;
var
v: TVitalType;
begin
Result := vtUnknown;
for v := low(TValidVitalTypes) to high(TValidVitalTypes) do
begin
if (Code = VitalPCECodes[v]) then
begin
Result := v;
break;
end;
end;
end;
type
TMultiClassObj = record
case integer of
0:
(edt: TCPRSDialogFieldEdit);
1:
(cb: TCPRSDialogCheckBox);
2:
(cbo: TCPRSDialogComboBox);
3:
(dt: TCPRSDialogDateCombo);
4:
(ctrl: TORExposedControl);
5:
(vedt: TVitalEdit);
6:
(vcbo: TVitalComboBox);
7:
(btn: TCPRSDialogButton);
8:
(pNow: TORCheckBox);
9:
(pBat: TORCheckBox);
10:
(lbl: TLabel);
11:
(WHChk: TWHCheckBox);
12:
(date: TCPRSDialogDateBox);
end;
EForcedPromptConflict = class(EAbort);
function IsSyncPrompt(pt: TRemPromptType): boolean;
begin
if (pt in SyncPrompts) then
Result := TRUE
else
Result := (pt = ptVitalEntry);
end;
procedure NotifyWhenRemindersChange(Proc: TNotifyEvent);
begin
ActiveReminders.Notifier.NotifyWhenChanged(Proc);
OtherReminders.Notifier.NotifyWhenChanged(Proc);
RemindersInProcess.Notifier.NotifyWhenChanged(Proc);
Proc(nil);
end;
procedure RemoveNotifyRemindersChange(Proc: TNotifyEvent);
begin
ActiveReminders.Notifier.RemoveNotify(Proc);
OtherReminders.Notifier.RemoveNotify(Proc);
RemindersInProcess.Notifier.RemoveNotify(Proc);
end;
function ProcessingChangeString: string;
var
i: integer;
TmpSL: TStringList;
begin
Result := U;
if (RemindersInProcess.Count > 0) then
begin
TmpSL := TStringList.Create;
try
FastAssign(RemindersInProcess, TmpSL);
TmpSL.Sort;
for i := 0 to TmpSL.Count - 1 do
begin
if (TReminder(TmpSL.Objects[i]).Processing) then
Result := Result + TmpSL[i] + U;
end;
finally
TmpSL.Free;
end;
end;
end;
procedure StartupReminders;
begin
if (not InitialRemindersLoaded) then
begin
RemindersStarted := TRUE;
InitialRemindersLoaded := TRUE;
LoadReminderData;
end;
end;
function GetReminderStatus: TReminderStatus;
begin
if (EvaluatedReminders.IndexOfPiece('1', U, 6) >= 0) then
Result := rsDue
else if (EvaluatedReminders.IndexOfPiece('0', U, 6) >= 0) then
Result := rsApplicable
else if (EvaluatedReminders.IndexOfPiece('2', U, 6) >= 0) then
Result := rsNotApplicable
else
Result := rsUnknown;
// else if(EvaluatedReminders.Count > 0) or (OtherReminders.Count > 0) or
// (not InitialRemindersLoaded) or
// (ProcessingChangeString <> U) then Result := rsUnknown
// else Result := rsNone;
end;
function RemindersEvaluatingInBackground: boolean;
begin
Result := CoverSheetRemindersInBackground;
if (not Result) then
Result := (ReminderCallList.Count > 0)
end;
var
TmpActive: TStringList = nil;
TmpOther: TStringList = nil;
procedure BeginReminderUpdate;
begin
ActiveReminders.Notifier.BeginUpdate;
OtherReminders.Notifier.BeginUpdate;
TmpActive := TStringList.Create;
FastAssign(ActiveReminders, TmpActive);
TmpOther := TStringList.Create;
FastAssign(OtherReminders, TmpOther);
end;
procedure EndReminderUpdate(Force: boolean = FALSE);
var
DoNotify: boolean;
begin
DoNotify := Force;
if (not DoNotify) then
DoNotify := (not ActiveReminders.Equals(TmpActive));
KillObj(@TmpActive);
if (not DoNotify) then
DoNotify := (not OtherReminders.Equals(TmpOther));
KillObj(@TmpOther);
OtherReminders.Notifier.EndUpdate;
ActiveReminders.Notifier.EndUpdate(DoNotify);
end;
function GetRemFolders: TRemFolders;
var
i: TRemFolder;
tmp: string;
begin
if rfUnknown in uRemFolders then
begin
tmp := GetReminderFolders;
uRemFolders := [];
for i := low(TValidRemFolders) to high(TValidRemFolders) do
if (pos(RemFolderCodes[i], tmp) > 0) then
include(uRemFolders, i);
end;
Result := uRemFolders;
end;
procedure SetRemFolders(const Value: TRemFolders);
var
i: TRemFolder;
tmp: string;
begin
if (Value <> uRemFolders) then
begin
BeginReminderUpdate;
try
uRemFolders := Value;
tmp := '';
for i := low(TValidRemFolders) to high(TValidRemFolders) do
if (i in Value) then
tmp := tmp + RemFolderCodes[i];
SetReminderFolders(tmp);
finally
EndReminderUpdate(TRUE);
end;
end;
end;
function ReminderEvaluated(Data: string; ForceUpdate: boolean = FALSE): boolean;
var
idx: integer;
Code, Sts, Before: string;
begin
Result := ForceUpdate;
if (Data <> '') then
begin
Code := Piece(Data, U, 1);
if StrToIntDef(Code, 0) > 0 then
begin
ActiveReminders.Notifier.BeginUpdate;
try
idx := EvaluatedReminders.IndexOfPiece(Code);
if (idx < 0) then
begin
EvaluatedReminders.Add(Data);
Result := TRUE;
end
else
begin
Before := Piece(EvaluatedReminders[idx], U, 6);
EvaluatedReminders[idx] := Data;
if (not Result) then
Result := (Before <> Piece(Data, U, 6));
end;
idx := ActiveReminders.IndexOfPiece(Code);
if (idx < 0) then
begin
Sts := Piece(Data, U, 6);
// if(Sts = '0') or (Sts = '1') then
if (Sts = '0') or (Sts = '1') or (Sts = '3') or (Sts = '4') then
// AGP Error change 26.8
begin
Result := TRUE;
ActiveReminders.Add(Data);
end;
end
else
begin
if (not Result) then
Result := (ActiveReminders[idx] <> Data);
ActiveReminders[idx] := Data;
end;
idx := ProcessedReminders.IndexOfPiece(Code);
if (idx >= 0) then
ProcessedReminders.delete(idx);
finally
ActiveReminders.Notifier.EndUpdate(Result);
end;
end
else
Result := TRUE;
// If Code = 0 then it's 0^No Reminders Due, indicating a status change.
end;
end;
procedure RemindersEvaluated(List: TStringList);
var
i: integer;
DoUpdate, RemChanged: boolean;
begin
DoUpdate := FALSE;
ActiveReminders.Notifier.BeginUpdate;
try
for i := 0 to List.Count - 1 do
begin
RemChanged := ReminderEvaluated(List[i]);
if (RemChanged) then
DoUpdate := TRUE;
end;
finally
ActiveReminders.Notifier.EndUpdate(DoUpdate);
end;
end;
(*
procedure CheckReminders; forward;
procedure IdleCallEvaluateReminder(Msg: string);
var
i:integer;
Code: string;
begin
Code := Piece(Msg,U,1);
repeat
i := ReminderCallList.IndexOfPiece(Code);
if(i >= 0) then
ReminderCallList.Delete(i);
until(i < 0);
ReminderEvaluated(EvaluateReminder(Msg), (ReminderCallList.Count = 0));
CheckReminders;
end;
procedure CheckReminders;
var
i:integer;
begin
for i := ReminderCallList.Count-1 downto 0 do
if(EvaluatedReminders.IndexOfPiece(Piece(ReminderCallList[i], U, 1)) >= 0) then
ReminderCallList.Delete(i);
if(ReminderCallList.Count > 0) then
CallRPCWhenIdle(IdleCallEvaluateReminder,ReminderCallList[0])
end;
*)
procedure CheckReminders;
var
RemList: TStringList;
i: integer;
Code: string;
aList: TStrings;
begin
for i := ReminderCallList.Count - 1 downto 0 do
if (EvaluatedReminders.IndexOfPiece(Piece(ReminderCallList[i], U, 1)) >= 0)
then
ReminderCallList.delete(i);
if (ReminderCallList.Count > 0) then
begin
RemList := TStringList.Create;
try
while (ReminderCallList.Count > 0) do
begin
Code := Piece(ReminderCallList[0], U, 1);
ReminderCallList.delete(0);
repeat
i := ReminderCallList.IndexOfPiece(Code);
if (i >= 0) then
ReminderCallList.delete(i);
until (i < 0);
RemList.Add(Code);
end;
if (RemList.Count > 0) then
begin
aList := TStringList.Create;
try
EvaluateReminders(RemList, aList);
FastAssign(aList, RemList);
for i := 0 to RemList.Count - 1 do
ReminderEvaluated(RemList[i], (i = (RemList.Count - 1)));
finally
FreeAndNil(aList);
end;
end;
finally
RemList.Free;
end;
end;
end;
procedure ResetReminderLoad;
begin
LastReminderLocation := -2;
LoadReminderData;
end;
procedure LoadReminderData(ProcessingInBackground: boolean = FALSE);
var
i, idx: integer;
RemID: string;
TempList: TORStringList;
aList: TStrings;
begin
if (RemindersStarted and (LastReminderLocation <> Encounter.Location)) then
begin
LastReminderLocation := Encounter.Location;
BeginReminderUpdate;
aList := TStringList.Create;
try
GetCurrentReminders(aList);
TempList := TORStringList.Create;
try
if (aList.Count > 0) then
begin
for i := 0 to AList.Count - 1 do
begin
RemID := AList[i];
idx := EvaluatedReminders.IndexOfPiece(RemID);
if (idx < 0) then
begin
TempList.Add(RemID);
if (not ProcessingInBackground) then
ReminderCallList.Add(RemID);
end
else
TempList.Add(EvaluatedReminders[idx]);
end;
end;
// FastAssign(TempList,ActiveReminders);
for i := 0 to TempList.Count - 1 do
begin
RemID := Piece(TempList[i], U, 1);
if (ActiveReminders.IndexOfPiece(RemID) < 0) then
ActiveReminders.Add(TempList[i]);
end;
finally
TempList.Free;
end;
CheckReminders;
GetOtherReminders(OtherReminders);
finally
FreeAndNil(aList);
EndReminderUpdate;
end;
end;
end;
{ Supporting events for Reminder TreeViews }
procedure GetImageIndex(AData: pointer; Sender: TObject; Node: TTreeNode);
var
iidx, oidx: integer;
Data, tmp: string;
begin
if (Assigned(Node)) then
begin
oidx := -1;
Data := (Node as TORTreeNode).StringData;
if (copy(Piece(Data, U, 1), 1, 1) = CatCode) then
begin
if (Node.Expanded) then
iidx := 1
else
iidx := 0;
end
else
begin
tmp := Piece(Data, U, 6);
// if(Tmp = '1') then iidx := 2
if (tmp = '3') or (tmp = '4') or (tmp = '1') then
iidx := 2 // AGP ERROR CHANGE 26.8
else if (tmp = '0') then
iidx := 3
else
begin
if (EvaluatedReminders.IndexOfPiece(copy(Piece(Data, U, 1), 2, MaxInt),
U, 1) < 0) then
iidx := 5
else
iidx := 4;
end;
if (Piece(Data, U, 7) = '1') then
begin
tmp := copy(Piece(Data, U, 1), 2, 99);
if (ProcessedReminders.IndexOfPiece(tmp, U, 1) >= 0) then
oidx := 1
else
oidx := 0;
end;
end;
Node.ImageIndex := iidx;
Node.SelectedIndex := iidx;
if (Node.OverlayIndex <> oidx) then
begin
Node.OverlayIndex := oidx;
Node.TreeView.Invalidate;
end;
end;
end;
type
TRemMenuCmd = (rmClinMaint, rmEdu, rmInq, rmWeb, rmDash, rmEval, rmDue,
rmApplicable, rmNotApplicable, rmEvaluated, rmOther, rmLegend);
TRemViewCmds = rmDue .. rmOther;
const
RemMenuFolder: array [TRemViewCmds] of TRemFolder =
{ rmDue } (rfDue,
{ rmApplicable } rfApplicable,
{ rmNotApplicable } rfNotApplicable,
{ rmEvaluated } rfEvaluated,
{ rmOther } rfOther);
RemMenuNames: array [TRemMenuCmd] of string = (
{ rmClinMaint } ClinMaintText,
{ rmEdu } 'Education Topic Definition',
{ rmInq } 'Reminder Inquiry',
{ rmWeb } 'Reference Information',
{ rmDash } '-',
{ rmEval } 'Evaluate Reminder',
{ rmDue } DueText,
{ rmApplicable } ApplicableText,
{ rmNotApplicable } NotApplicableText,
{ rmEvaluated } EvaluatedText,
{ rmOther } OtherText,
{ rmLegend } 'Reminder Icon Legend');
EvalCatName = 'Evaluate Category Reminders';
function GetEducationTopics(EIEN: string): string;
var
i, idx: integer;
tmp, Data: string;
aList: TSTrings;
begin
aList := TStringList.Create;
try
if (not Assigned(EducationTopics)) then
EducationTopics := TORStringList.Create;
idx := EducationTopics.IndexOfPiece(EIEN);
if (idx < 0) then
begin
tmp := copy(EIEN, 1, 1);
idx := StrToIntDef(copy(EIEN, 2, MaxInt), 0);
if (tmp = RemCode) then
GetEducationTopicsForReminder(idx, alist)
else if (tmp = EduCode) then
GetEducationSubtopics(idx, alist);
tmp := EIEN;
if (aList.Count > 0) then
begin
for i := 0 to aList.Count - 1 do
begin
Data := aList[i];
tmp := tmp + U + Piece(Data, U, 1) + ';';
if (Piece(Data, U, 3) = '') then
tmp := tmp + Piece(Data, U, 2)
else
tmp := tmp + Piece(Data, U, 3);
end;
end;
idx := EducationTopics.Add(tmp);
end;
Result := EducationTopics[idx];
idx := pos(U, Result);
if (idx > 0) then
Result := copy(Result, idx + 1, MaxInt)
else
Result := '';
finally
FreeAndNil(Alist);
end;
end;
function GetWebPageName(idx: integer): string;
begin
Result := Piece(WebPages[idx], U, 2);
end;
function GetWebPageAddress(idx: integer): string;
begin
Result := Piece(WebPages[idx], U, 3);
end;
function GetWebPages(EIEN: string): string; overload;
var
i, idx: integer;
tmp, Data, Title: string;
RIEN: string;
aList: TStrings;
begin
aList := TStringList.Create;
try
if not user.WebAccess then exit;
RIEN := RemCode + EIEN;
if (not Assigned(WebPages)) then
WebPages := TORStringList.Create;
idx := WebPages.IndexOfPiece(RIEN);
if (idx < 0) then
begin
GetReminderWebPages(EIEN, aList);
tmp := RIEN;
if (aList.Count > 0) then
begin
for i := 0 to Alist.Count - 1 do
begin
Data := aList[i];
if (Piece(Data, U, 1) = '1') and (Piece(Data, U, 3) <> '') then
begin
Data := U + Piece(Data, U, 4) + U + Piece(Data, U, 3);
if (Piece(Data, U, 2) = '') then
begin
Title := Piece(Data, U, 3);
if (length(Title) > 60) then
Title := copy(Title, 1, 57) + '...';
SetPiece(Data, U, 2, Title);
end;
// if(copy(UpperCase(Piece(Data, U, 3)),1,7) <> 'HTTP://') then
// SetPiece(Data, U, 3,'http://'+Piece(Data,U,3));
idx := WebPages.IndexOf(Data);
if (idx < 0) then
idx := WebPages.Add(Data);
tmp := tmp + U + IntToStr(idx);
end;
end;
end;
idx := WebPages.Add(tmp);
end;
Result := WebPages[idx];
idx := pos(U, Result);
if (idx > 0) then
Result := copy(Result, idx + 1, MaxInt)
else
Result := '';
finally
FreeAndNil(aList);
end;
end;
function ReminderName(IEN: integer): string;
var
idx: integer;
SIEN: string;
begin
SIEN := IntToStr(IEN);
Result := '';
idx := EvaluatedReminders.IndexOfPiece(SIEN);
if (idx >= 0) then
Result := Piece(EvaluatedReminders[idx], U, 2);
if (Result = '') then
begin
idx := ActiveReminders.IndexOfPiece(SIEN);
if (idx >= 0) then
Result := Piece(ActiveReminders[idx], U, 2);
end;
if (Result = '') then
begin
idx := OtherReminders.IndexOfPiece(SIEN, U, 5);
if (idx >= 0) then
Result := Piece(OtherReminders[idx], U, 3);
end;
if (Result = '') then
begin
idx := RemindersInProcess.IndexOfPiece(SIEN);
if (idx >= 0) then
Result := TReminder(RemindersInProcess.Objects[idx]).PrintName;
end;
end;
procedure ReminderClinMaintClicked(AData: pointer; Sender: TObject);
var
IEN: integer;
aList: TStrings;
returnValue: integer;
begin
aList := TStringList.Create;
try
IEN := (Sender as TMenuItem).Tag;
if (IEN > 0) then
begin
returnValue := DetailReminder(IEN, aList);
if returnValue > 0 then
ReportBox(aList, RemMenuNames[rmClinMaint] + ': ' + ReminderName(IEN), TRUE)
else infoBox('Error loading Clinical maintenance', 'Error', MB_OK);
end;
finally
FreeAndNil(aList);
end;
end;
procedure ReminderEduClicked(AData: pointer; Sender: TObject);
var
IEN: integer;
aList: TStrings;
begin
IEN := (Sender as TMenuItem).Tag;
if (IEN > 0) then
aList := TStringList.Create;
try
if ReminderInquiry(IEN, aList) > 0 then
ReportBox(Alist, 'Reminder Inquiry: ' + 'Education Topic: ' + (Sender as TMenuItem).Caption, TRUE)
else infoBox('Error loading Education Topic Inquiry.', 'Error', MB_OK);
finally
FreeAndNil(aList);
end;
end;
procedure ReminderInqClicked(AData: pointer; Sender: TObject);
var
IEN: integer;
aList: TStrings;
begin
IEN := (Sender as TMenuItem).Tag;
if (IEN > 0) then
aList := TStringList.Create;
try
if ReminderInquiry(IEN, aList) > 0 then
ReportBox(Alist, 'Reminder Inquiry: ' + ReminderName(IEN), TRUE)
else infoBox('Error loading Reminder Inquiry.', 'Error', MB_OK);
finally
FreeAndNil(aList);
end;
end;
procedure ReminderWebClicked(AData: pointer; Sender: TObject);
var
idx: integer;
begin
idx := (Sender as TMenuItem).Tag - 1;
if (idx >= 0) then
GotoWebPage(GetWebPageAddress(idx));
end;
procedure EvalReminder(IEN: integer);
var
Msg, RName: string;
NewStatus: string;
begin
if (IEN > 0) then
begin
NewStatus := EvaluateReminder(IntToStr(IEN));
ReminderEvaluated(NewStatus);
NewStatus := Piece(NewStatus, U, 6);
RName := ReminderName(IEN);
if (RName = '') then
RName := 'Reminder';
if (NewStatus = '1') then
Msg := 'Due'
else if (NewStatus = '0') then
Msg := 'Applicable'
else if (NewStatus = '3') then
Msg := 'Error' // AGP Error code change 26.8
else if (NewStatus = '4') then
Msg := 'CNBD' // AGP Error code change 26.8
else
Msg := 'Not Applicable';
Msg := RName + ' is ' + Msg + '.';
InfoBox(Msg, RName + ' Evaluation', MB_OK);
end;
end;
procedure EvalProcessed;
var
i: integer;
begin
if (ProcessedReminders.Count > 0) then
begin
BeginReminderUpdate;
try
while (ProcessedReminders.Count > 0) do
begin
if (ReminderCallList.IndexOf(ProcessedReminders[0]) < 0) then
ReminderCallList.Add(ProcessedReminders[0]);
repeat
i := EvaluatedReminders.IndexOfPiece
(Piece(ProcessedReminders[0], U, 1));
if (i >= 0) then
EvaluatedReminders.delete(i);
until (i < 0);
ProcessedReminders.delete(0);
end;
CheckReminders;
finally
EndReminderUpdate(TRUE);
end;
end;
end;
procedure ReminderEvalClicked(AData: pointer; Sender: TObject);
begin
EvalReminder((Sender as TMenuItem).Tag);
end;
procedure ReminderViewFolderClicked(AData: pointer; Sender: TObject);
var
rfldrs: TRemFolders;
rfldr: TRemFolder;
begin
rfldrs := GetRemFolders;
rfldr := TRemFolder((Sender as TMenuItem).Tag);
if rfldr in rfldrs then
exclude(rfldrs, rfldr)
else
include(rfldrs, rfldr);
SetRemFolders(rfldrs);
end;
procedure EvaluateCategoryClicked(AData: pointer; Sender: TObject);
var
Node: TORTreeNode;
Code: string;
i: integer;
begin
if (Sender is TMenuItem) then
begin
BeginReminderUpdate;
try
Node := TORTreeNode(TORTreeNode(TMenuItem(Sender).Tag).GetFirstChild);
while Assigned(Node) do
begin
Code := Piece(Node.StringData, U, 1);
if (copy(Code, 1, 1) = RemCode) then
begin
Code := copy(Code, 2, MaxInt);
if (ReminderCallList.IndexOf(Code) < 0) then
ReminderCallList.Add(copy(Node.StringData, 2, MaxInt));
repeat
i := EvaluatedReminders.IndexOfPiece(Code);
if (i >= 0) then
EvaluatedReminders.delete(i);
until (i < 0);
end;
Node := TORTreeNode(Node.GetNextSibling);
end;
CheckReminders;
finally
EndReminderUpdate(TRUE);
end;
end;
end;
procedure ReminderIconLegendClicked(AData: pointer; Sender: TObject);
begin
ShowIconLegend(ilReminders);
end;
procedure ReminderMenuBuilder(MI: TMenuItem; RemStr: string;
IncludeActions, IncludeEval, ViewFolders: boolean);
var
M: TMethod;
tmp: string;
Cnt: integer;
RemID: integer;
cmd: TRemMenuCmd;
function Add(Text: string; Parent: TMenuItem; Tag: integer; Typ: TRemMenuCmd)
: TORMenuItem;
var
InsertMenu: boolean;
idx: integer;
begin
Result := nil;
InsertMenu := TRUE;
if (Parent = MI) then
begin
if (MI.Count > Cnt) then
begin
Result := TORMenuItem(MI.Items[Cnt]);
Result.Enabled := TRUE;
Result.Visible := TRUE;
Result.ImageIndex := -1;
while Result.Count > 0 do
Result.delete(Result.Count - 1);
InsertMenu := FALSE;
end;
inc(Cnt);
end;
if (not Assigned(Result)) then
Result := TORMenuItem.Create(MI);
if (Text = '') then
Result.Caption := RemMenuNames[Typ]
else
Result.Caption := Text;
Result.Tag := Tag;
Result.Data := RemStr;
if (Tag <> 0) then
begin
case Typ of
rmClinMaint:
M.Code := @ReminderClinMaintClicked;
rmEdu:
M.Code := @ReminderEduClicked;
rmInq:
M.Code := @ReminderInqClicked;
rmWeb:
M.Code := @ReminderWebClicked;
rmEval:
M.Code := @ReminderEvalClicked;
rmDue .. rmOther:
begin
M.Code := @ReminderViewFolderClicked;
case Typ of
rmDue:
idx := 0;
rmApplicable:
idx := 2;
rmNotApplicable:
idx := 4;
rmEvaluated:
idx := 6;
rmOther:
idx := 8;
else
idx := -1;
end;
if (idx >= 0) and (RemMenuFolder[Typ] in GetRemFolders) then
inc(idx);
Result.ImageIndex := idx;
end;
rmLegend:
M.Code := @ReminderIconLegendClicked;
else
M.Code := nil;
end;
if (Assigned(M.Code)) then
Result.OnClick := TNotifyEvent(M)
else
Result.OnClick := nil;
end;
if (InsertMenu) then
Parent.Add(Result);
end;
procedure AddEducationTopics(Item: TMenuItem; EduStr: string);
var
i, j: integer;
Code: String;
NewEduStr: string;
itm: TMenuItem;
begin
if (EduStr <> '') then
begin
repeat
i := pos(';', EduStr);
j := pos(U, EduStr);
if (j = 0) then
j := length(EduStr) + 1;
Code := copy(EduStr, 1, i - 1);
// AddEducationTopics(Add(copy(EduStr,i+1,j-i-1), Item, StrToIntDef(Code, 0), rmEdu),
// GetEducationTopics(EduCode + Code));
NewEduStr := GetEducationTopics(EduCode + Code);
if (NewEduStr = '') then
Add(copy(EduStr, i + 1, j - i - 1), Item, StrToIntDef(Code, 0), rmEdu)
else
begin
itm := Add(copy(EduStr, i + 1, j - i - 1), Item, 0, rmEdu);
Add(copy(EduStr, i + 1, j - i - 1), itm, StrToIntDef(Code, 0), rmEdu);
Add('', itm, 0, rmDash);
AddEducationTopics(itm, NewEduStr);
end;
delete(EduStr, 1, j);
until (EduStr = '');
end;
end;
procedure AddWebPages(Item: TMenuItem; WebStr: string);
var
i, idx: integer;
begin
if (WebStr <> '') then
begin
repeat
i := pos(U, WebStr);
if (i = 0) then
i := length(WebStr) + 1;
idx := StrToIntDef(copy(WebStr, 1, i - 1), -1);
if (idx >= 0) then
Add(GetWebPageName(idx), Item, idx + 1, rmWeb);
delete(WebStr, 1, i);
until (WebStr = '');
end;
end;
begin
RemID := StrToIntDef(copy(Piece(RemStr, U, 1), 2, MaxInt), 0);
Cnt := 0;
M.Data := nil;
if (RemID > 0) then
begin
Add('', MI, RemID, rmClinMaint);
tmp := GetEducationTopics(RemCode + IntToStr(RemID));
if (tmp <> '') then
AddEducationTopics(Add('', MI, 0, rmEdu), tmp)
else
Add('', MI, 0, rmEdu).Enabled := FALSE;
Add('', MI, RemID, rmInq);
tmp := GetWebPages(IntToStr(RemID));
if (tmp <> '') then
AddWebPages(Add('', MI, 0, rmWeb), tmp)
else
Add('', MI, 0, rmWeb).Enabled := FALSE;
if (IncludeActions or IncludeEval) then
begin
Add('', MI, 0, rmDash);
Add('', MI, RemID, rmEval);
end;
end;
if (ViewFolders) then
begin
Add('', MI, 0, rmDash);
for cmd := low(TRemViewCmds) to high(TRemViewCmds) do
Add('', MI, ord(RemMenuFolder[cmd]), cmd);
end;
Add('', MI, 0, rmDash);
Add('', MI, 1, rmLegend);
while MI.Count > Cnt do
MI.delete(MI.Count - 1);
end;
procedure ReminderTreePopup(AData: pointer; Sender: TObject);
begin
ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu)
.Data, TRUE, FALSE, FALSE);
end;
procedure ReminderTreePopupCover(AData: pointer; Sender: TObject);
begin
ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu)
.Data, FALSE, FALSE, FALSE);
end;
procedure ReminderTreePopupDlg(AData: pointer; Sender: TObject);
begin
ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu)
.Data, FALSE, TRUE, FALSE);
end;
procedure ReminderMenuItemSelect(AData: pointer; Sender: TObject);
begin
ReminderMenuBuilder((Sender as TMenuItem), (Sender as TORMenuItem).Data,
FALSE, FALSE, TRUE);
end;
procedure SetReminderPopupRoutine(Menu: TPopupMenu);
var
M: TMethod;
begin
M.Code := @ReminderTreePopup;
M.Data := nil;
Menu.OnPopup := TNotifyEvent(M);
end;
procedure SetReminderPopupCoverRoutine(Menu: TPopupMenu);
var
M: TMethod;
begin
M.Code := @ReminderTreePopupCover;
M.Data := nil;
Menu.OnPopup := TNotifyEvent(M);
end;
procedure SetReminderPopupDlgRoutine(Menu: TPopupMenu);
var
M: TMethod;
begin
M.Code := @ReminderTreePopupDlg;
M.Data := nil;
Menu.OnPopup := TNotifyEvent(M);
end;
procedure SetReminderMenuSelectRoutine(Menu: TMenuItem);
var
M: TMethod;
begin
M.Code := @ReminderMenuItemSelect;
M.Data := nil;
Menu.OnClick := TNotifyEvent(M);
end;
function ReminderMenu(Sender: TComponent): TORPopupMenu;
begin
if (Sender.Tag = RemTreeCode) then
begin
if (not Assigned(ReminderTreeMenuDlg)) then
begin
ReminderTreeMenuDlg := TORPopupMenu.Create(nil);
SetReminderPopupDlgRoutine(ReminderTreeMenuDlg)
end;
Result := ReminderTreeMenuDlg;
end
else
begin
if (not Assigned(ReminderTreeMenu)) then
begin
ReminderTreeMenu := TORPopupMenu.Create(nil);
SetReminderPopupRoutine(ReminderTreeMenu);
end;
Result := ReminderTreeMenu;
end;
end;
procedure RemContextPopup(AData: pointer; Sender: TObject; MousePos: TPoint;
var Handled: boolean);
var
Menu: TORPopupMenu;
MItem: TMenuItem;
M: TMethod;
p1: string;
UpdateMenu: boolean;
begin
UpdateMenu := TRUE;
Menu := nil;
with (Sender as TORTreeView) do
begin
if ((htOnItem in GetHitTestInfoAt(MousePos.X, MousePos.Y)) and
(Assigned(Selected))) then
begin
p1 := Piece((Selected as TORTreeNode).StringData, U, 1);
if (copy(p1, 1, 1) = RemCode) then
begin
Menu := ReminderMenu(TComponent(Sender));
Menu.Data := TORTreeNode(Selected).StringData;
end
else if (copy(p1, 1, 1) = CatCode) and (p1 <> OtherCatID) and
(Selected.HasChildren) then
begin
if (not Assigned(ReminderCatMenu)) then
begin
ReminderCatMenu := TPopupMenu.Create(nil);
MItem := TMenuItem.Create(ReminderCatMenu);
MItem.Caption := EvalCatName;
M.Data := nil;
M.Code := @EvaluateCategoryClicked;
MItem.OnClick := TNotifyEvent(M);
ReminderCatMenu.Items.Add(MItem);
end
else
MItem := ReminderCatMenu.Items[0];
PopupMenu := ReminderCatMenu;
MItem.Tag := integer(TORTreeNode(Selected));
UpdateMenu := FALSE;
end;
end;
if UpdateMenu then
PopupMenu := Menu;
Selected := Selected;
// This strange line Keeps item selected after a right click
if (not Assigned(PopupMenu)) then
Handled := TRUE;
end;
end;
{ StringData of the TORTreeNodes will be in the format:
1 2 3 4 5 6 7
TYPE + IEN^PRINT NAME^DUE DATE/TIME^LAST OCCURENCE DATE/TIME^PRIORITY^DUE^DIALOG
8 9 10
Formated Due Date^Formated Last Occurence Date^InitialAbsoluteIdx
where TYPE C=Category, R=Reminder
PRIORITY 1=High, 2=Normal, 3=Low
DUE 0=Applicable, 1=Due, 2=Not Applicable
DIALOG 1=Active Dialog Exists
}
procedure BuildReminderTree(Tree: TORTreeView);
var
ExpandedStr: string;
TopID1, TopID2: string;
SelID1, SelID2: string;
i, j: integer;
NeedLost: boolean;
tmp, Data, LostCat, Code: string;
Node: TORTreeNode;
M: TMethod;
Rem: TReminder;
OpenDue, Found: boolean;
function Add2Tree(Folder: TRemFolder; CatID: string; Node: TORTreeNode = nil)
: TORTreeNode;
begin
if (Folder = rfUnknown) or (Folder in GetRemFolders) then
begin
if (CatID = LostCatID) then
begin
if (NeedLost) then
begin
(Tree.Items.AddFirst(nil, '') as TORTreeNode).StringData :=
LostCatString;
NeedLost := FALSE;
end;
end;
if (not Assigned(Node)) then
Node := Tree.FindPieceNode(CatID, 1);
if (Assigned(Node)) then
begin
Result := (Tree.Items.AddChild(Node, '') as TORTreeNode);
Result.StringData := Data;
end
else
Result := nil;
end
else
Result := nil;
end;
begin
if (not Assigned(Tree)) then
exit;
Tree.Items.BeginUpdate;
try
Tree.NodeDelim := U;
Tree.NodePiece := 2;
M.Code := @GetImageIndex;
M.Data := nil;
Tree.OnGetImageIndex := TTVExpandedEvent(M);
Tree.OnGetSelectedIndex := TTVExpandedEvent(M);
M.Code := @RemContextPopup;
Tree.OnContextPopup := TContextPopupEvent(M);
if (Assigned(Tree.TopItem)) then
begin
TopID1 := Tree.GetNodeID(TORTreeNode(Tree.TopItem), 1, IncludeParentID);
TopID2 := Tree.GetNodeID(TORTreeNode(Tree.TopItem), 1);
end
else
TopID1 := U;
if (Assigned(Tree.Selected)) then
begin
SelID1 := Tree.GetNodeID(TORTreeNode(Tree.Selected), 1, IncludeParentID);
SelID2 := Tree.GetNodeID(TORTreeNode(Tree.Selected), 1);
end
else
SelID1 := U;
ExpandedStr := Tree.GetExpandedIDStr(1, IncludeParentID);
OpenDue := (ExpandedStr = '');
Tree.Items.Clear;
NeedLost := TRUE;
if (rfDue in GetRemFolders) then
(Tree.Items.Add(nil, '') as TORTreeNode).StringData := DueCatString;
if (rfApplicable in GetRemFolders) then
(Tree.Items.Add(nil, '') as TORTreeNode).StringData := ApplCatString;
if (rfNotApplicable in GetRemFolders) then
(Tree.Items.Add(nil, '') as TORTreeNode).StringData := NotApplCatString;
if (rfEvaluated in GetRemFolders) then
(Tree.Items.Add(nil, '') as TORTreeNode).StringData := EvaluatedCatString;
if (rfOther in GetRemFolders) then
(Tree.Items.Add(nil, '') as TORTreeNode).StringData := OtherCatString;
for i := 0 to EvaluatedReminders.Count - 1 do
begin
Data := RemCode + EvaluatedReminders[i];
tmp := Piece(Data, U, 6);
// if(Tmp = '1') then Add2Tree(rfDue, DueCatID)
if (tmp = '1') or (tmp = '3') or (tmp = '4') then
Add2Tree(rfDue, DueCatID) // AGP Error code change 26.8
else if (tmp = '0') then
Add2Tree(rfApplicable, ApplCatID)
else
Add2Tree(rfNotApplicable, NotApplCatID);
Add2Tree(rfEvaluated, EvaluatedCatID);
end;
if (rfOther in GetRemFolders) and (OtherReminders.Count > 0) then
begin
for i := 0 to OtherReminders.Count - 1 do
begin
tmp := OtherReminders[i];
if (Piece(tmp, U, 2) = CatCode) then
Data := CatCode + Piece(tmp, U, 1)
else
begin
Code := Piece(tmp, U, 5);
Data := RemCode + Code;
Node := Tree.FindPieceNode(Data, 1);
if (Assigned(Node)) then
Data := Node.StringData
else
begin
j := EvaluatedReminders.IndexOfPiece(Code);
if (j >= 0) then
SetPiece(Data, U, 6, Piece(EvaluatedReminders[j], U, 6));
end;
end;
SetPiece(Data, U, 2, Piece(tmp, U, 3));
SetPiece(Data, U, 7, Piece(tmp, U, 6));
tmp := CatCode + Piece(tmp, U, 4);
Add2Tree(rfOther, OtherCatID, Tree.FindPieceNode(tmp, 1));
end;
end;
{ The Lost category is for reminders being processed that are no longer in the
reminder tree view. This can happen with reminders that were Due or Applicable,
but due to user action are no longer applicable, or due to location changes.
The Lost category will not be used if a lost reminder is in the other list. }
if (RemindersInProcess.Count > 0) then
begin
for i := 0 to RemindersInProcess.Count - 1 do
begin
Rem := TReminder(RemindersInProcess.Objects[i]);
tmp := RemCode + Rem.IEN;
Found := FALSE;
Node := nil;
repeat
Node := Tree.FindPieceNode(tmp, 1, #0, Node);
// look in the tree first
if ((not Found) and (not Assigned(Node))) then
begin
Data := tmp + U + Rem.PrintName + U + Rem.DueDateStr + U +
Rem.LastDateStr + U + IntToStr(Rem.Priority) + U + Rem.Status;
if (Rem.Status = '1') then
LostCat := DueCatID
else if (Rem.Status = '0') then
LostCat := ApplCatID
else
LostCat := LostCatID;
Node := Add2Tree(rfUnknown, LostCat);
end;
if (Assigned(Node)) then
begin
Node.Bold := Rem.Processing;
Found := TRUE;
end;
until (Found and (not Assigned(Node)));
end;
end;
for i := 0 to Tree.Items.Count - 1 do
begin
Node := TORTreeNode(Tree.Items[i]);
for j := 3 to 4 do
begin
tmp := Piece(Node.StringData, U, j);
if (tmp = '') then
Data := ''
else
Data := FormatFMDateTimeStr(ReminderDateFormat, tmp);
Node.SetPiece(j + (RemTreeDateIdx - 3), Data);
end;
Node.SetPiece(RemTreeDateIdx + 2, IntToStr(Node.AbsoluteIndex));
tmp := Piece(Node.StringData, U, 5);
if (tmp <> '1') and (tmp <> '3') then
Node.SetPiece(5, '2');
end;
finally
Tree.Items.EndUpdate;
end;
if (SelID1 = U) then
Node := nil
else
begin
Node := Tree.FindPieceNode(SelID1, 1, IncludeParentID);
if (not Assigned(Node)) then
Node := Tree.FindPieceNode(SelID2, 1);
if (Assigned(Node)) then
Node.EnsureVisible;
end;
Tree.Selected := Node;
Tree.SetExpandedIDStr(1, IncludeParentID, ExpandedStr);
if (OpenDue) then
begin
Node := Tree.FindPieceNode(DueCatID, 1);
if (Assigned(Node)) then
Node.Expand(FALSE);
end;
if (TopID1 = U) then
Tree.TopItem := Tree.Items.GetFirstNode
else
begin
Tree.TopItem := Tree.FindPieceNode(TopID1, 1, IncludeParentID);
if (not Assigned(Tree.TopItem)) then
Tree.TopItem := Tree.FindPieceNode(TopID2, 1);
end;
end;
function ReminderNode(Node: TTreeNode): TORTreeNode;
var
p1: string;
begin
Result := nil;
if (Assigned(Node)) then
begin
p1 := Piece((Node as TORTreeNode).StringData, U, 1);
if (copy(p1, 1, 1) = RemCode) then
Result := (Node as TORTreeNode)
end;
end;
procedure LocationChanged(Sender: TObject);
begin
LoadReminderData;
end;
procedure ClearReminderData;
var
Changed: boolean;
begin
if (Assigned(frmReminderTree)) then
frmReminderTree.Free;
Changed := ((ActiveReminders.Count > 0) or (OtherReminders.Count > 0) or
(ProcessingChangeString <> U));
ActiveReminders.Notifier.BeginUpdate;
OtherReminders.Notifier.BeginUpdate;
RemindersInProcess.Notifier.BeginUpdate;
try
ProcessedReminders.Clear;
if (Assigned(KillReminderDialogProc)) then
KillReminderDialogProc(nil);
ActiveReminders.Clear;
OtherReminders.Clear;
EvaluatedReminders.Clear;
ReminderCallList.Clear;
RemindersInProcess.KillObjects;
RemindersInProcess.Clear;
LastProcessingList := '';
InitialRemindersLoaded := FALSE;
CoverSheetRemindersInBackground := FALSE;
finally
RemindersInProcess.Notifier.EndUpdate;
OtherReminders.Notifier.EndUpdate;
ActiveReminders.Notifier.EndUpdate(Changed);
RemindersStarted := FALSE;
LastReminderLocation := -2;
RemForm.Form := nil;
end;
end;
procedure RemindersInProcessChanged(Data: pointer; Sender: TObject;
var CanNotify: boolean);
var
CurProcessing: string;
begin
CurProcessing := ProcessingChangeString;
CanNotify := (LastProcessingList <> CurProcessing);
if (CanNotify) then
LastProcessingList := CurProcessing;
end;
procedure InitReminderObjects;
var
M: TMethod;
procedure InitReminderList(var List: TORStringList);
begin
if (not Assigned(List)) then
List := TORStringList.Create;
end;
begin
InitReminderList(ActiveReminders);
InitReminderList(OtherReminders);
InitReminderList(EvaluatedReminders);
InitReminderList(ReminderCallList);
InitReminderList(RemindersInProcess);
InitReminderList(ProcessedReminders);
M.Code := @RemindersInProcessChanged;
M.Data := nil;
RemindersInProcess.Notifier.OnNotify := TCanNotifyEvent(M);
AddToNotifyWhenCreated(LocationChanged, TEncounter);
RemForm.Form := nil;
end;
procedure FreeReminderObjects;
begin
KillObj(@ActiveReminders);
KillObj(@OtherReminders);
KillObj(@EvaluatedReminders);
KillObj(@ReminderTreeMenuDlg);
KillObj(@ReminderTreeMenu);
KillObj(@ReminderCatMenu);
KillObj(@EducationTopics);
KillObj(@WebPages);
KillObj(@ReminderCallList);
KillObj(@TmpActive);
KillObj(@TmpOther);
KillObj(@RemindersInProcess, TRUE);
KillObj(@ReminderDialogInfo, TRUE);
KillObj(@PCERootList, TRUE);
KillObj(@ProcessedReminders);
end;
function GetReminder(ARemData: string): TReminder;
var
idx: integer;
SIEN: string;
begin
Result := nil;
SIEN := Piece(ARemData, U, 1);
if (copy(SIEN, 1, 1) = RemCode) then
begin
SIEN := copy(SIEN, 2, MaxInt);
idx := RemindersInProcess.IndexOf(SIEN);
if (idx < 0) then
begin
RemindersInProcess.Notifier.BeginUpdate;
try
idx := RemindersInProcess.AddObject(SIEN, TReminder.Create(ARemData));
finally
RemindersInProcess.Notifier.EndUpdate;
end;
end;
Result := TReminder(RemindersInProcess.Objects[idx]);
end;
end;
var
ScootOver: integer = 0;
procedure WordWrap(AText: string; Output: TStrings; LineLength: integer;
AutoIndent: integer = 4; MHTest: boolean = FALSE);
var
i, j, FCount, MHLoop: integer;
First, MHRes: boolean;
OrgText, Text, Prefix, tmpText: string;
begin
StripScreenReaderCodes(AText);
inc(LineLength, ScootOver);
dec(AutoIndent, ScootOver);
FCount := Output.Count;
First := TRUE;
MHLoop := 1;
MHRes := FALSE;
tmpText := '';
if (MHTest = TRUE) and (pos('~', AText) > 0) then
MHLoop := 2;
for j := 1 to MHLoop do
begin
if (j = 1) and (MHLoop = 2) then
begin
tmpText := Piece(AText, '~', 1);
MHRes := TRUE;
end
else if (j = 2) then
begin
tmpText := Piece(AText, '~', 2);
First := FALSE;
MHRes := FALSE;
end
else if (j = 1) and (MHLoop = 1) then
begin
tmpText := AText;
First := FALSE;
MHRes := FALSE;
end;
if tmpText <> '' then
OrgText := tmpText
else
OrgText := InitText(AText);
Prefix := StringOfChar(' ', MAX_ENTRY_WIDTH - LineLength);
repeat
OrgText := CRLFText(OrgText);
// i := pos(CRCode, OrgText);
// if (i = 0) then i := pos(CRLF, orgText);
i := pos(CRLF, OrgText);
if (i = 0) then
begin
Text := OrgText;
OrgText := '';
end
else
begin
Text := copy(OrgText, 1, i - 1);
delete(OrgText, 1, i + Length(CRLF) - 1);
end;
if (Text = '') and (OrgText <> '') then
begin
Output.Add('');
inc(FCount);
end;
If Text <> '' then begin
if(First) then
begin
dec(LineLength, AutoIndent);
Prefix := Prefix + StringOfChar(' ', AutoIndent);
First := FALSE;
end;
// Wrap the text and account for the new charaters
Text := SafeWrapText(text, CRLF + Prefix, [#3, ' '], LineLength, LineLength);
// remove the #3 (if present)
If Pos(#3, Text) > 0 then
Text := StringReplace(Text, #3, '', [rfReplaceAll,rfIgnoreCase]);
Output.Add(Prefix + Text);
end;
if ((First) and (FCount <> Output.Count)) and (MHRes = FALSE) then
begin
dec(LineLength, AutoIndent);
Prefix := Prefix + StringOfChar(' ', AutoIndent);
First := FALSE;
end;
until (OrgText = '');
end;
end;
function InteractiveRemindersActive: boolean;
begin
if (not InteractiveRemindersActiveChecked) then
begin
InteractiveRemindersActiveStatus := GetRemindersActive;
InteractiveRemindersActiveChecked := TRUE;
end;
Result := InteractiveRemindersActiveStatus;
end;
function GetReminderData(Rem: TReminderDialog; Lst: TStrings;
Finishing: boolean = FALSE; Historical: boolean = FALSE): integer;
begin
Result := Rem.AddData(Lst, Finishing, Historical);
end;
function GetReminderData(Lst: TStrings; Finishing: boolean = FALSE;
Historical: boolean = FALSE): integer;
var
i: integer;
begin
Result := 0;
for i := 0 to RemindersInProcess.Count - 1 do
inc(Result, TReminder(RemindersInProcess.Objects[i]).AddData(Lst, Finishing,
Historical));
end;
procedure SetReminderFormBounds(Frm: TForm; DefX, DefY, DefW, DefH, ALeft, ATop,
AWidth, AHeight: integer);
var
Rect: TRect;
ScreenW, ScreenH: integer;
begin
SystemParametersInfo(SPI_GETWORKAREA, 0, @Rect, 0);
ScreenW := Rect.Right - Rect.Left + 1;
ScreenH := Rect.Bottom - Rect.Top + 1;
if (AWidth = 0) then
AWidth := DefW
else
DefW := AWidth;
if (AHeight = 0) then
AHeight := DefH
else
DefH := AHeight;
if (DefX = 0) and (DefY = 0) then
begin
DefX := (ScreenW - DefW) div 2;
DefY := (ScreenH - DefH) div 2;
end
else
dec(DefY, DefH);
if ((ALeft <= 0) or (ATop <= 0) or ((ALeft + AWidth) > ScreenW) or
((ATop + AHeight) > ScreenH)) then
begin
if (DefX < 0) then
DefX := 0
else if ((DefX + DefW) > ScreenW) then
DefX := ScreenW - DefW;
if (DefY < 0) then
DefY := 0
else if ((DefY + DefH) > ScreenH) then
DefY := ScreenH - DefH;
Frm.SetBounds(Rect.Left + DefX, Rect.Top + DefY, DefW, DefH);
end
else
Frm.SetBounds(Rect.Left + ALeft, Rect.Top + ATop, AWidth, AHeight);
end;
procedure UpdateReminderDialogStatus;
var
TmpSL: TStringList;
Changed: boolean;
procedure Build(AList: TORStringList; PNum: integer);
var
i: integer;
Code: string;
begin
for i := 0 to AList.Count - 1 do
begin
Code := Piece(AList[i], U, PNum);
if ((Code <> '') and (TmpSL.IndexOf(Code) < 0)) then
TmpSL.Add(Code);
end;
end;
procedure Reset(AList: TORStringList; PNum, DlgPNum: integer);
var
i, j: integer;
tmp, Code, Dlg: string;
begin
for i := 0 to TmpSL.Count - 1 do
begin
Code := Piece(TmpSL[i], U, 1);
j := -1;
repeat
j := AList.IndexOfPiece(Code, U, PNum, j);
if (j >= 0) then
begin
Dlg := Piece(TmpSL[i], U, 2);
if (Dlg <> Piece(AList[j], U, DlgPNum)) then
begin
tmp := AList[j];
SetPiece(tmp, U, DlgPNum, Dlg);
AList[j] := tmp;
Changed := TRUE;
end;
end;
until (j < 0);
end;
end;
begin
Changed := FALSE;
BeginReminderUpdate;
try
TmpSL := TStringList.Create;
try
Build(ActiveReminders, 1);
Build(OtherReminders, 5);
Build(EvaluatedReminders, 1);
GetDialogStatus(TmpSL);
Reset(ActiveReminders, 1, 7);
Reset(OtherReminders, 5, 6);
Reset(EvaluatedReminders, 1, 7);
finally
TmpSL.Free;
end;
finally
EndReminderUpdate(Changed);
end;
end;
procedure PrepText4NextLine(var txt: string);
var
tlen: integer;
begin
if (txt <> '') then
begin
tlen := length(txt);
if (copy(txt, tlen - CRCodeLen + 1, CRCodeLen) = CRCode) then
exit;
if (copy(txt, tlen, 1) = '.') then
txt := txt + ' ';
txt := txt + ' ';
end;
end;
procedure ExpandTIUObjects(var txt: string; Msg: string = '');
var
ObjList: TStringList;
Err: TStringList;
i, j, k, oLen: integer;
obj, ObjTxt: string;
begin
ObjList := TStringList.Create;
try
Err := nil;
if (not dmodShared.BoilerplateOK(txt, CRCode, ObjList, Err)) and
(Assigned(Err)) then
begin
try
Err.Add(CRLF + 'Contact IRM and inform them about this error.' + CRLF +
'Make sure you give them the name of the reminder that you are processing,'
+ CRLF + 'and which dialog elements were selected to produce this error.');
InfoBox(Err.Text, 'Reminder Boilerplate Object Error',
MB_OK + MB_ICONERROR);
finally
Err.Free;
end;
end;
if (ObjList.Count > 0) then
begin
GetTemplateText(ObjList);
i := 0;
while (i < ObjList.Count) do
begin
if (pos(ObjMarker, ObjList[i]) = 1) then
begin
obj := copy(ObjList[i], ObjMarkerLen + 1, MaxInt);
if (obj = '') then
break;
j := i + 1;
while (j < ObjList.Count) and (pos(ObjMarker, ObjList[j]) = 0) do
inc(j);
if ((j - i) > 2) then
begin
ObjTxt := '';
for k := i + 1 to j - 1 do
ObjTxt := ObjTxt + CRCode + ObjList[k];
end
else
ObjTxt := ObjList[i + 1];
i := j;
obj := '|' + obj + '|';
oLen := length(obj);
repeat
j := pos(obj, txt);
if (j > 0) then
begin
delete(txt, j, oLen);
insert(ObjTxt, txt, j);
end;
until (j = 0);
end
else
inc(i);
end
end;
finally
ObjList.Free;
end;
end;
{ TReminderDialog }
const
RPCCalled = '99';
DlgCalled = RPCCalled + U + 'DLG';
constructor TReminderDialog.BaseCreate;
var
idx, eidx, i: integer;
TempSL: TORStringList;
ParentID: string;
// Line: string;
Element: TRemDlgElement;
begin
TempSL := GetDlgSL;
if Piece(TempSL[0], U, 2) = '1' then
begin
Self.RemWipe := 1;
end;
idx := -1;
repeat
idx := TempSL.IndexOfPiece('1', U, 1, idx);
if (idx >= 0) then
begin
if (not Assigned(FElements)) then
FElements := TStringList.Create;
eidx := FElements.AddObject('', TRemDlgElement.Create);
Element := TRemDlgElement(FElements.Objects[eidx]);
with Element do
begin
FReminder := Self;
FRec1 := TempSL[idx];
FID := Piece(FRec1, U, 2);
FDlgID := Piece(FRec1, U, 3);
FElements[eidx] := FDlgID;
if (ElemType = etTaxonomy) then
FTaxID := BOOLCHAR[Historical] + FindingType
else
FTaxID := '';
FText := '';
i := -1;
// if Piece(FRec1,U,5) <> '1' then
repeat
i := TempSL.IndexOfPieces(['2', FID, FDlgID], i);
if (i >= 0) then
begin
PrepText4NextLine(FText);
FText := FText + Trim(Piece(TempSL[i], U, 4));
end;
until (i < 0);
ExpandTIUObjects(FText);
AssignFieldIDs(FText);
if (pos('.', FDlgID) > 0) then
begin
ParentID := FDlgID;
i := length(ParentID);
while ((i > 0) and (ParentID[i] <> '.')) do
dec(i);
if (i > 0) then
begin
ParentID := copy(ParentID, 1, i - 1);
i := FElements.IndexOf(ParentID);
if (i >= 0) then
begin
FParent := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(FParent.FChildren)) then
FParent.FChildren := TList.Create;
FParent.FChildren.Add(Element);
end;
end;
end;
if (ElemType = etDisplayOnly) then
SetChecked(TRUE);
UpdateData;
end;
end;
until (idx < 0);
end;
constructor TReminderDialog.Create(ADlgData: string);
begin
FDlgData := ADlgData;
linkSeqList := TStringlist.Create;
linkSeqListChecked := TStringlist.Create;
BaseCreate;
end;
destructor TReminderDialog.Destroy;
begin
KillObj(@FElements, TRUE);
FreeAndNil(linkSeqList);
FreeAndNil(linkSeqListChecked);
inherited;
end;
function TReminderDialog.Processing: boolean;
var
i, j: integer;
Elem: TRemDlgElement;
RData: TRemData;
function ChildrenChecked(Prnt: TRemDlgElement): boolean; forward;
function CheckItem(Item: TRemDlgElement): boolean;
begin
if (Item.ElemType = etDisplayOnly) then
begin
Result := ChildrenChecked(Item);
if (not Result) then
Result := Item.Add2PN;
end
else
Result := Item.FChecked;
end;
function ChildrenChecked(Prnt: TRemDlgElement): boolean;
var
i: integer;
begin
Result := FALSE;
if (Assigned(Prnt.FChildren)) then
begin
for i := 0 to Prnt.FChildren.Count - 1 do
begin
Result := CheckItem(TRemDlgElement(Prnt.FChildren[i]));
if (Result) then
break;
end;
end;
end;
begin
Result := FALSE;
if (Assigned(FElements)) then
begin
for i := 0 to FElements.Count - 1 do
begin
Elem := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(Elem.FParent)) then
begin
Result := CheckItem(Elem);
if (Result = FALSE) then
// (AGP CHANGE 24.9 add check to have the finish problem check for MH test)
begin
if (Assigned(Elem.FData)) then
begin
for j := 0 to Elem.FData.Count - 1 do
begin
RData := TRemData(Elem.FData[j]);
if Piece(RData.FRec3, U, 4) = 'MH' then
Result := TRUE;
if (Result) then
break;
end;
end;
end;
if (Result) then
break;
end;
end;
end;
end;
function TReminderDialog.GetDlgSL: TORStringList;
var
idx: integer;
aList: TStrings;
isReminder: boolean;
begin
aList := TStringList.Create;
try
if (not Assigned(ReminderDialogInfo)) then
ReminderDialogInfo := TStringList.Create;
idx := ReminderDialogInfo.IndexOf(GetIEN);
if (idx < 0) then
idx := ReminderDialogInfo.AddObject(GetIEN, TORStringList.Create);
Result := TORStringList(ReminderDialogInfo.Objects[idx]);
if (Result.Count = 0) then
begin
if (Self is TReminder) then isReminder := true
else isReminder := false;
if GetDialogInfo(GetIEN, isReminder, aList) = 0 then exit;
FastAssign(alist, Result);
Result.Add(DlgCalled);
// Used to prevent repeated calling of RPC if dialog is empty
end;
finally
FreeAndNil(aList);
end;
end;
function TReminderDialog.BuildControls(ParentWidth: integer;
AParent, AOwner: TWinControl): TWinControl;
var
Y, i: integer;
Elem: TRemDlgElement;
ERes: TWinControl;
begin
Result := nil;
if (Assigned(FElements)) then
begin
Y := 0;
for i := 0 to FElements.Count - 1 do
begin
Elem := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(Elem.FParent)) then
begin
ERes := Elem.BuildControls(Y, ParentWidth, AParent, AOwner);
if (not Assigned(Result)) then
Result := ERes;
end;
if (Elem.ElemType = etChecked) then
begin
elem.SetChecked(true);
SetPiece(Elem.FRec1, U, 4, 'S');
end;
end;
end;
if (AParent.ControlCount = 0) then
begin
with TVA508StaticText.Create(AOwner) do
begin
Parent := AParent;
Caption := 'No Dialog found for ' + Trim(GetPrintName) + ' Reminder.';
Left := Gap;
Top := Gap;
end;
end;
ElementChecked := nil;
end;
procedure TReminderDialog.closeReportView;
var
e, p: integer;
Element: TRemDlgElement;
prompt: TRemPrompt;
begin
try
if self.FElements = nil then exit;
for e := 0 to self.FElements.Count - 1 do
begin
Element := TRemDlgElement(self.FElements.Objects[e]);
if not Assigned(element.FPrompts) then continue;
for p := 0 to Element.FPrompts.Count -1 do
begin
Prompt := TRemPrompt(Element.FPrompts[p]);
if assigned(prompt.reportView) then
begin
if prompt.reportView.Showing then
begin
prompt.reportView.Close;
FreeAndNil(prompt.reportView);
end;
end;
end;
end;
finally
end;
end;
procedure TReminderDialog.AddText(Lst: TStrings);
var
i, idx: integer;
Elem: TRemDlgElement;
temp: string;
begin
if (Assigned(FElements)) then
begin
idx := Lst.Count;
for i := 0 to FElements.Count - 1 do
begin
Elem := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(Elem.FParent)) then
Elem.AddText(Lst);
end;
if (Self is TReminder) and (PrintName <> '') and (idx <> Lst.Count) then
begin
temp := PrintName;
StripScreenReaderCodes(temp);
Lst.insert(idx, ' ' + temp + ':')
end;
end;
end;
function TReminderDialog.AddData(Lst: TStrings; Finishing: boolean = FALSE;
Historical: boolean = FALSE): integer;
var
i: integer;
Elem: TRemDlgElement;
begin
Result := 0;
if (Assigned(FElements)) then
begin
for i := 0 to FElements.Count - 1 do
begin
Elem := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(Elem.FParent)) then
inc(Result, Elem.AddData(Lst, Finishing, Historical));
end;
end;
end;
procedure TReminderDialog.ComboBoxCheckedText(Sender: TObject;
NumChecked: integer; var Text: string);
var
i, Done: integer;
DotLen, ComLen, TxtW, TotalW, NewLen: integer;
tmp: string;
Fnt: THandle;
lb: TORListBox;
begin
if (NumChecked = 0) then
Text := '(None Selected)'
else if (NumChecked > 1) then
begin
Text := '';
lb := (Sender as TORListBox);
Fnt := lb.Font.Handle;
DotLen := TextWidthByFont(Fnt, '...');
TotalW := (lb.Owner as TControl).ClientWidth - 15;
ComLen := TextWidthByFont(Fnt, ', ');
dec(TotalW, (NumChecked - 1) * ComLen);
Done := 0;
for i := 0 to lb.Items.Count - 1 do
begin
if (lb.Checked[i]) then
begin
inc(Done);
if (Text <> '') then
begin
Text := Text + ', ';
dec(TotalW, ComLen);
end;
tmp := lb.DisplayText[i];
if (Done = NumChecked) then
TxtW := TotalW
else
TxtW := TotalW div (NumChecked - Done + 1);
NewLen := NumCharsFitInWidth(Fnt, tmp, TxtW);
if (NewLen < length(tmp)) then
tmp := copy(tmp, 1, NumCharsFitInWidth(Fnt, tmp, (TxtW - DotLen)
)) + '...';
dec(TotalW, TextWidthByFont(Fnt, tmp));
Text := Text + tmp;
end;
end;
end;
end;
procedure TReminderDialog.BeginTextChanged;
begin
inc(FTextChangedCount);
end;
procedure TReminderDialog.EndTextChanged(Sender: TObject);
begin
if (FTextChangedCount > 0) then
begin
dec(FTextChangedCount);
if (FTextChangedCount = 0) and Assigned(FOnTextChanged) then
FOnTextChanged(Sender);
end;
end;
function TReminderDialog.GetIEN: string;
begin
Result := Piece(FDlgData, U, 1);
end;
function TReminderDialog.GetPrintName: string;
begin
Result := Piece(FDlgData, U, 2);
end;
procedure TReminderDialog.BeginNeedRedraw;
begin
inc(FNeedRedrawCount);
end;
procedure TReminderDialog.EndNeedRedraw(Sender: TObject);
begin
if (FNeedRedrawCount > 0) then
begin
dec(FNeedRedrawCount);
if (FNeedRedrawCount = 0) and (Assigned(FOnNeedRedraw)) then
FOnNeedRedraw(Sender);
end;
end;
procedure TReminderDialog.FinishProblems(List: TStrings;
var MissingTemplateFields: boolean);
var
i: integer;
Elem: TRemDlgElement;
TmpSL: TStringList;
FldData: TORStringList;
begin
if (Processing and Assigned(FElements)) then
begin
TmpSL := TStringList.Create;
try
FldData := TORStringList.Create;
try
for i := 0 to FElements.Count - 1 do
begin
Elem := TRemDlgElement(FElements.Objects[i]);
if (not Assigned(Elem.FParent)) then
begin
Elem.FinishProblems(List);
Elem.GetFieldValues(FldData);
end;
end;
FNoResolve := TRUE;
try
AddText(TmpSL);
finally
FNoResolve := FALSE;
end;
MissingTemplateFields := AreTemplateFieldsRequired(TmpSL.Text, FldData);
finally
FldData.Free;
end;
finally
TmpSL.Free;
end;
end;
end;
procedure TReminderDialog.ComboBoxResized(Sender: TObject);
begin
// This causes the ONCheckedText event to re-fire and re-update the text,
// based on the new size of the combo box.
if (Sender is TORComboBox) then
with (Sender as TORComboBox) do
OnCheckedText := OnCheckedText;
end;
function TReminderDialog.Visible: boolean;
begin
Result := (CurrentReminderInDialog = Self);
end;
procedure TReminderDialog.findLinkItem(elementList, promptList: TStringList; startSeq: String);
var
a, r, p: integer;
action: string;
elementChange: boolean;
Element: TRemDlgElement;
Prompt: TRemPrompt;
promptActedOn: TStringList;
procedure setToDisable(Element: TRemDlgElement);
var
c: integer;
tempElem: TRemDlgElement;
begin
if not assigned(element.FChildren) then exit;
for c := 0 to element.FChildren.Count - 1 do
begin
tempElem := TRemDlgElement(element.FChildren[c]);
tempElem.originalType := Piece(tempElem.FRec1, U, 4) + U;
SetPiece(tempElem.FRec1, U, 4, 'H');
setToDisable(tempElem);
end;
end;
procedure setToEnable(Element: TRemDlgElement);
var
c: integer;
tempElem: TRemDlgElement;
begin
if not assigned(element.FChildren) then exit;
for c := 0 to element.FChildren.Count - 1 do
begin
tempElem := TRemDlgElement(element.FChildren[c]);
SetPiece(tempElem.FRec1, U, 4, Piece(tempElem.originalType, U, 1));
setToEnable(tempElem);
end;
end;
function sequenceMatch(id, seq, frec1, startSeq: string): boolean;
var
l: integer;
temp: string;
begin
if linkSeqListChecked.IndexOf(seq) = -1 then result := false
else
begin
result := false;
for l := 0 to linkSeqList.Count - 1 do
begin
temp := linkSeqList.Strings[l];
if Piece(temp, u, 1) <> seq then continue;
if (Piece(temp, u, 2) <> '') and (Piece(temp, u, 2) <> startSeq) then continue;
if Piece(FRec1, U, 3) = Piece(temp, U, 3) then
begin
result := true;
exit;
end;
end;
end;
end;
begin
try
promptActedOn := TStringList.Create;
for r := 0 to Self.FElements.Count - 1 do
begin
elementChange := FALSE;
Element := TRemDlgElement(Self.FElements.Objects[r]);
if (elementList.Count > 0) then
begin
for a := 0 to elementList.Count - 1 do
begin
action := elementList.Strings[a];
if StrToInt(Piece(Element.FRec1, U, 2)) <> StrToInt(Piece(action, U, 1))
then
continue;
if (Piece(action, u, 4) <> '0') and (not sequenceMatch(Piece(action, U, 1), Piece(action, u, 4), element.FRec1, startSeq)) then continue;
// if (Piece(Element.FRec1, U, 3) <> Piece(action, U, 4)) and (Piece(action, U, 4) <> '') then
// continue;
if (Piece(action, U, 2) = 'CHECKED') and (not Element.isChecked) then
begin
Application.ProcessMessages;
Element.SetChecked(TRUE);
elementChange := TRUE;
end
else if Piece(action, U, 2) = 'SUPPRESS' then
begin
if Piece(Element.FRec1, U, 4) <> 'D' then
begin
Application.ProcessMessages;
SetPiece(Element.FRec1, U, 4, 'D');
Element.SetChecked(TRUE);
elementChange := TRUE;
end;
end
else if (Piece(action, U, 2) = 'UNCHECKED') and (Element.isChecked) then
begin
Application.ProcessMessages;
Element.SetChecked(FALSE);
elementChange := TRUE;
end
else if (Piece(action, U, 2) = 'UNSUPPRESS') and (Piece(Element.FRec1, U, 4) = 'D') then
begin
Application.ProcessMessages;
SetPiece(Element.FRec1, U, 4, 'S');
Element.SetChecked(FALSE);
elementChange := TRUE;
end
else if Piece(action, U, 2) = 'DISABLE' then
begin
Application.ProcessMessages;
if Piece(Element.FRec1, U, 4) <> 'H' then
begin
// element.originalType := Piece(Element.FRec1, U, 4);
if element.Checked then element.originalType := Piece(Element.FRec1, U, 4) + U + '1'
else element.originalType := Piece(Element.FRec1, U, 4) + U + '0';
SetPiece(Element.FRec1, U, 4, 'H');
Element.SetChecked(false);
setToDisable(element);
elementChange := True;
end;
end
else if Piece(action, U, 2) = 'UNDISABLE' then
begin
Application.ProcessMessages;
SetPiece(Element.FRec1, U, 4, Piece(element.originalType, U, 1));
if (Piece(element.originalType, U, 2)= '1') or (Piece(element.originalType, U, 1) = 'D') then element.SetChecked(true)
else element.SetChecked(false);
setToEnable(element);
elementChange := True;
end
end;
end;
if (Element.FPrompts = nil) then
begin
if elementChange then Element.linkItemRedraw(element);
continue;
end;
if not Element.FChecked then
begin
if elementChange then Element.linkItemRedraw(element);
continue;
end;
if promptList.Count > 0 then
begin
for p := 0 to Element.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(Element.FPrompts[p]);
for a := 0 to promptList.Count - 1 do
begin
action := promptList.Strings[a];
if StrToInt(Piece(Prompt.FRec4, U, 2)) <> StrToInt(Piece(action, U, 1))
then
continue;
if (Piece(Prompt.FRec4, U, 4) <> Piece(action, U, 2)) then
continue;
if (Piece(action, u, 5) <> '0') and (not sequenceMatch(Piece(action, U, 1), Piece(action, u, 5), element.FRec1, startSeq)) then continue;
promptActedOn.Add(action);
if (Piece(action, U, 3) = 'REQUIRED') then
begin
SetPiece(Prompt.FRec4, U, 10, '1');
elementChange := TRUE;
end
else if (Piece(action, U, 3) = 'UNREQUIRED') then
begin
SetPiece(Prompt.FRec4, U, 10, '0');
elementChange := TRUE;
end
else
begin
Prompt.SetValueFromParent(Piece(action, U, 4));
// Prompt.SetValue(Piece(action, U, 4));
end;
end;
end;
end;
if elementChange and (element <> nil) and (element.FParent <> nil) then Element.linkItemRedraw(element);
end;
for p := 0 to promptList.Count - 1 do
begin
action := promptList.Strings[p];
if (promptActedOn <> nil) and (promptActedOn.IndexOf(action) = -1) then
begin
if FPromptsDefaults = nil then FPromptsDefaults := TStringList.Create;
FPromptsDefaults.Add(action);
end;
end;
finally
end;
end;
{ TReminder }
constructor TReminder.Create(ARemData: string);
begin
linkSeqList := TStringlist.Create;
linkSeqListChecked := TStringlist.Create;
FRemData := ARemData;
BaseCreate;
end;
function TReminder.GetDueDateStr: string;
begin
Result := Piece(FRemData, U, 3);
end;
function TReminder.GetIEN: string;
begin
Result := copy(Piece(FRemData, U, 1), 2, MaxInt);
end;
function TReminder.GetLastDateStr: string;
begin
Result := Piece(FRemData, U, 4);
end;
function TReminder.GetPrintName: string;
begin
Result := Piece(FRemData, U, 2);
end;
function TReminder.GetPriority: integer;
begin
Result := StrToIntDef(Piece(FRemData, U, 5), 2);
end;
function TReminder.GetStatus: string;
begin
Result := Piece(FRemData, U, 6);
end;
{ TRemDlgElement }
function Code2DataType(Code: string): TRemDataType;
var
idx: TRemDataType;
begin
Result := dtUnknown;
for idx := low(TRemDataType) to high(TRemDataType) do
begin
if (Code = RemDataCodes[idx]) then
begin
Result := idx;
break;
end;
end;
end;
function Code2PromptType(Code: string): TRemPromptType;
var
idx: TRemPromptType;
begin
if (Code = '') then
Result := ptSubComment
else if (Code = MSTCode) then
Result := ptMST
else
begin
Result := ptUnknown;
for idx := low(TRemPromptType) to high(TRemPromptType) do
begin
if (Code = RemPromptCodes[idx]) then
begin
Result := idx;
break;
end;
end;
end;
end;
function TRemDlgElement.Add2PN: boolean;
var
Lst: TStringList;
begin
if (FChecked) then
begin
Result := (Piece(FRec1, U, 5) <> '1');
// Suppress := (Piece(FRec1,U,1)='1');
if (Result and (ElemType = etDisplayOnly)) then
begin
// Result := FALSE;
if (Assigned(FPrompts) and (FPrompts.Count > 0)) or
(Assigned(FData) and (FData.Count > 0)) or Result then
begin
Lst := TStringList.Create;
try
AddData(Lst, FALSE);
Result := (Lst.Count > 0);
if not Assigned(FData) then
Result := TRUE;
finally
Lst.Free;
end;
end;
end;
end
else
Result := FALSE;
end;
function TRemDlgElement.Box: boolean;
begin
Result := (Piece(FRec1, U, 19) = '1');
end;
function TRemDlgElement.BoxCaption: string;
begin
if (Box) then
Result := Piece(FRec1, U, 20)
else
Result := '';
end;
function TRemDlgElement.ChildrenIndent: integer;
begin
Result := StrToIntDef(Piece(FRec1, U, 16), 0);
end;
function TRemDlgElement.ChildrenRequired: TRDChildReq;
var
tmp: string;
begin
tmp := Piece(FRec1, U, 18);
if tmp = '1' then
Result := crOne
else if tmp = '2' then
Result := crAtLeastOne
else if tmp = '3' then
Result := crNoneOrOne
else if tmp = '4' then
Result := crAll
else
Result := crNone;
end;
function TRemDlgElement.ChildrenSharePrompts: boolean;
begin
Result := (Piece(FRec1, U, 17) = '1');
end;
destructor TRemDlgElement.Destroy;
begin
KillObj(@FFieldValues);
KillObj(@FData, TRUE);
KillObj(@FPrompts, TRUE);
KillObj(@FChildren);
inherited;
end;
function TRemDlgElement.ElemType: TRDElemType;
var
tmp: string;
begin
tmp := Piece(FRec1, U, 4);
if (tmp = 'D') then
Result := etDisplayOnly
else if (tmp = 'T') then
Result := etTaxonomy
else if (tmp = 'C') then
Result := etChecked
else if (tmp = 'H') then
Result := etDisable
else
Result := etCheckBox;
end;
function TRemDlgElement.FindingType: string;
begin
if (ElemType = etTaxonomy) then
Result := Piece(FRec1, U, 7)
else
Result := '';
end;
function TRemDlgElement.HideChildren: boolean;
begin
Result := (Piece(FRec1, U, 15) <> '0');
end;
function TRemDlgElement.Historical: boolean;
begin
Result := (Piece(FRec1, U, 8) = '1');
end;
function TRemDlgElement.Indent: integer;
begin
Result := StrToIntDef(Piece(FRec1, U, 6), 0);
end;
procedure TRemDlgElement.GetData;
var
TempSL: TStrings;
i: integer;
tmp, remIEN, newDataOnly, tempRPC: string;
begin
if FHaveData then exit;
if Piece(FRec1, U, 25) = '0' then exit;
TempSL := TStringList.Create;
try
newDataOnly := Piece(self.FRec1, U, 27);
if (FReminder.GetDlgSL.IndexOfPieces([RPCCalled, FID, FTaxID, newDataOnly]) < 0) then
begin
if self.FReminder.DlgData <> '' then remIen := Piece(self.FReminder.FDlgData, U, 1)
else remIen := Piece(TReminder(self.FReminder).FRemData, U, 1);
if GetDialogPrompts(FID, Historical, FindingType, remIEN, tempSL, newDataOnly) = 0 then exit;
tempRPC := RPCCalled + U + U + U + newDataOnly;
TempSL.Add(tempRPC);
for i := 0 to TempSL.Count - 1 do
begin
tmp := TempSL[i];
SetPiece(tmp, U, 2, FID);
SetPiece(tmp, U, 3, FTaxID);
TempSL[i] := tmp;
end;
FastAddStrings(TempSL, FReminder.GetDlgSL);
end;
UpdateData;
finally
FreeAndNil(TempSL);
end;
end;
procedure TRemDlgElement.UpdateData;
var
Ary: array of integer;
idx, i, Cnt: integer;
TempSL: TORStringList;
RData: TRemData;
RPrompt: TRemPrompt;
tmp, Tmp2, choiceTmp: string;
NewLine: boolean;
dt: TRemDataType;
pt: TRemPromptType;
DateRange: string;
ChoicesActiveDates: TStringList;
ChoiceIdx: integer;
Piece7, newDataOnly: string;
encDt: TFMDateTime;
begin
if FHaveData then
exit;
TempSL := FReminder.GetDlgSL;
newDataOnly := Piece(self.FRec1, U, 27);
if (TempSL.IndexOfPieces([RPCCalled, FID, FTaxID, newDataOnly]) >= 0) then
begin
FHaveData := TRUE;
RData := nil;
idx := -1;
repeat
idx := TempSL.IndexOfPieces(['3', FID, FTaxID], idx);
if (idx >= 0) and (Pieces(TempSL[idx - 1], U, 1, 6) = Pieces(TempSL[idx],
U, 1, 6)) then
if pos(':', Piece(TempSL[idx], U, 7)) > 0 then // if has date ranges
begin
if RData <> nil then
begin
if (not Assigned(RData.FActiveDates)) then
RData.FActiveDates := TStringList.Create;
DateRange := Pieces(Piece(TempSL[idx], U, 7), ':', 2, 3);
RData.FActiveDates.Add(DateRange);
with RData do
begin
FParent := Self;
Piece7 := Piece(Piece(TempSL[idx], U, 7), ':', 1);
FRec3 := TempSL[idx];
SetPiece(FRec3, U, 7, Piece7);
end;
end;
end;
if (idx >= 0) and (Pieces(TempSL[idx - 1], U, 1, 6) <> Pieces(TempSL[idx],
U, 1, 6)) then
begin
dt := Code2DataType(Piece(TempSL[idx], U, r3Type));
if (dt <> dtUnknown) and
((dt <> dtOrder) or CharInSet(CharAt(Piece(TempSL[idx], U, 11), 1),
['D', 'Q', 'M', 'O', 'A'])) and // AGP change 26.10 for allergy orders
((dt <> dtMentalHealthTest) or MHTestsOK) then
begin
if (not Assigned(FData)) then
FData := TList.Create;
RData := TRemData(FData[FData.Add(TRemData.Create)]);
if pos(':', Piece(TempSL[idx], U, 7)) > 0 then
begin
RData.FActiveDates := TStringList.Create;
RData.FActiveDates.Add(Pieces(Piece(TempSL[idx], U, 7), ':', 2, 3));
end;
with RData do
begin
FParent := Self;
Piece7 := Piece(Piece(TempSL[idx], U, 7), ':', 1);
FRec3 := TempSL[idx];
SetPiece(FRec3, U, 7, Piece7);
// FRoot := FRec3;
i := idx + 1;
ChoiceIdx := 0;
while (i < TempSL.Count) and
(TempSL.PiecesEqual(i, ['5', FID, FTaxID])) do
begin
if (Pieces(TempSL[i - 1], U, 1, 6) = Pieces(TempSL[i], U, 1, 6))
then
begin
if pos(':', Piece(TempSL[i], U, 7)) > 0 then
begin
if (not Assigned(FChoicesActiveDates)) then
begin
FChoicesActiveDates := TList.Create;
ChoicesActiveDates := TStringList.Create;
FChoicesActiveDates.insert(ChoiceIdx, ChoicesActiveDates);
end;
TStringList(FChoicesActiveDates[ChoiceIdx])
.Add(Pieces(Piece(TempSL[i], U, 7), ':', 2, 3));
end;
inc(i);
end
else
begin
if (not Assigned(FChoices)) then
begin
FChoices := TORStringList.Create;
if (not Assigned(FPrompts)) then
FPrompts := TList.Create;
FChoicePrompt :=
TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]);
with FChoicePrompt do
begin
FParent := Self;
tmp := Piece(FRec3, U, 10);
NewLine := (tmp <> '');
FRec4 := '4' + U + FID + U + FTaxID + U + U +
BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + tmp + U +
BOOLCHAR[NewLine] + U + '1';
FData := RData;
FOverrideType := ptDataList;
InitValue;
end;
end;
tmp := TempSL[i];
Piece7 := Piece(Piece(TempSL[i], U, 7), ':', 1);
SetPiece(tmp, U, 7, Piece7);
Tmp2 := Piece(Piece(tmp, U, r3Code), ':', 1);
if (Tmp2 <> '') then
Tmp2 := ' (' + Tmp2 + ')';
Tmp2 := MixedCase(Piece(tmp, U, r3Nar)) + Tmp2;
SetPiece(tmp, U, 12, Tmp2);
ChoiceIdx := FChoices.Add(tmp);
if pos(':', Piece(TempSL[i], U, 7)) > 0 then
begin
if (not Assigned(FChoicesActiveDates)) then
FChoicesActiveDates := TList.Create;
ChoicesActiveDates := TStringList.Create;
ChoicesActiveDates.Add(Pieces(Piece(TempSL[i], U, 7),
':', 2, 3));
FChoicesActiveDates.insert(ChoiceIdx, ChoicesActiveDates);
end
else if Assigned(FChoicesActiveDates) then
FChoicesActiveDates.insert(ChoiceIdx, TStringList.Create);
inc(i);
end;
end;
choiceTmp := '';
// agp ICD-10 modify this code to handle one valid code against encounter date if combobox contains more than one code.
if (Assigned(FChoices)) and
((FChoices.Count = 1) or (FChoicesActiveDates.Count = 1)) then
// If only one choice just pick it
begin
choiceTmp := FChoices[0];
end;
if (Assigned(FChoices)) and (Assigned(FChoicesActiveDates)) and
(choiceTmp = '') then
begin
if (Assigned(FParent.FReminder.FPCEDataObj)) then
encDt := FParent.FReminder.FPCEDataObj.DateTime
else
encDt := RemForm.PCEObj.VisitDateTime;
choiceTmp := oneValidCode(FChoices, FChoicesActiveDates, encDt);
end;
// if(assigned(FChoices)) and (((FChoices.Count = 1) or (FChoicesActiveDates.Count = 1)) or
// (oneValidCode(FChoices, FChoicesActiveDates, FParent.FReminder.FPCEDataObj.DateTime) = true)) then // If only one choice just pick it
if (choiceTmp <> '') then
begin
if (not Assigned(RData.FActiveDates)) then
begin
RData.FActiveDates := TStringList.Create;
setActiveDates(FChoices, FChoicesActiveDates,
RData.FActiveDates);
end;
FPrompts.Remove(FChoicePrompt);
KillObj(@FChoicePrompt);
tmp := choiceTmp;
KillObj(@FChoices);
Cnt := 5;
if (Piece(FRec3, U, 9) = '') then
inc(Cnt);
SetLength(Ary, Cnt);
for i := 0 to Cnt - 1 do
Ary[i] := i + 4;
SetPieces(FRec3, U, Ary, tmp);
if (not Assigned(RData.FActiveDates)) then
begin
RData.FActiveDates := TStringList.Create;
end;
end;
if (Assigned(FChoices)) then
begin
for i := 0 to FChoices.Count - 1 do
FChoices.Objects[i] := TRemPCERoot.GetRoot(RData, FChoices[i],
Historical);
end
else
FPCERoot := TRemPCERoot.GetRoot(RData, RData.FRec3, Historical);
if (dt = dtVitals) then
begin
if (Code2VitalType(Piece(FRec3, U, 6)) <> vtUnknown) then
begin
if (not Assigned(FPrompts)) then
FPrompts := TList.Create;
FChoicePrompt :=
TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]);
with FChoicePrompt do
begin
FParent := Self;
tmp := Piece(FRec3, U, 10);
NewLine := FALSE;
// FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U +
// RData.InternalValue + U + 'P' + U + Tmp + U + BOOLCHAR[SameL] + U + '1';
FRec4 := '4' + U + FID + U + FTaxID + U + U +
BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + tmp + U +
BOOLCHAR[NewLine] + U + '0';
FData := RData;
FOverrideType := ptVitalEntry;
InitValue;
end;
end;
end;
if (dt = dtMentalHealthTest) then
begin
if (not Assigned(FPrompts)) then
FPrompts := TList.Create;
FChoicePrompt :=
TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]);
with FChoicePrompt do
begin
FParent := Self;
tmp := Piece(FRec3, U, 10);
NewLine := FALSE;
// FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U +
// RData.InternalValue + U + 'P' + U + Tmp + U + BOOLCHAR[SameL] + U + '1';
FRec4 := '4' + U + FID + U + FTaxID + U + U +
BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + tmp + U +
BOOLCHAR[NewLine] + U + '0';
FData := RData;
if ((Piece(FRec3, U, r3GAF) = '1')) and (MHDLLFound = FALSE)
then
begin
FOverrideType := ptGAF;
SetPiece(FRec4, U, 8, ForcedCaption + ':');
end
else
FOverrideType := ptMHTest;
end;
end;
end;
end;
end;
until (idx < 0);
idx := -1;
repeat
idx := TempSL.IndexOfPieces(['4', FID, FTaxID], idx);
if (idx >= 0) then
begin
if Piece(TempSL[idx], U, 20) <> newDataOnly then
continue;
pt := Code2PromptType(Piece(TempSL[idx], U, 4));
if (pt <> ptUnknown) and ((pt <> ptComment) or (not FHasComment)) then
begin
if (not Assigned(FPrompts)) then
FPrompts := TList.Create;
RPrompt := TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]);
with RPrompt do
begin
FParent := Self;
FRec4 := TempSL[idx];
InitValue;
end;
if (pt = ptComment) then
begin
FHasComment := TRUE;
FCommentPrompt := RPrompt;
end;
if (pt = ptSubComment) then
FHasSubComments := TRUE;
if (pt = ptMST) then
FMSTPrompt := RPrompt;
end;
end;
until (idx < 0);
idx := -1;
repeat
idx := TempSL.IndexOfPieces(['6', FID, FTaxID], idx);
if (idx >= 0) then
begin
if Piece(TempSL[idx], U, 5) <> newDataOnly then
continue;
PrepText4NextLine(FPNText);
FPNText := FPNText + Trim(Piece(TempSL[idx], U, 4));
end;
until (idx < 0);
ExpandTIUObjects(FPNText);
end;
end;
procedure TRemDlgElement.SetChecked(const Value: boolean);
var
i, j, k: integer;
Kid: TRemDlgElement;
Prompt: TRemPrompt;
RData: TRemData;
linkItem, linkAction, linkType, linkSeq: String;
elementList, promptList: TStringList;
procedure UpdateForcedValues(Elem: TRemDlgElement);
var
i: integer;
begin
if (Elem.IsChecked) then
begin
if (Assigned(Elem.FPrompts)) then
begin
for i := 0 to Elem.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(Elem.FPrompts[i]);
if Prompt.Forced then
begin
try
Prompt.SetValueFromParent(Prompt.FValue);
except
on E: EForcedPromptConflict do
begin
Elem.FChecked := FALSE;
InfoBox(E.Message, 'Error', MB_OK or MB_ICONERROR);
break;
end
else
raise;
end;
end;
end;
end;
if (Elem.FChecked) and (Assigned(Elem.FChildren)) then
for i := 0 to Elem.FChildren.Count - 1 do
UpdateForcedValues(TRemDlgElement(Elem.FChildren[i]));
end;
end;
begin
if (FChecked <> Value) then
begin
FChecked := Value;
if (Value) then
begin
GetData;
if (FChecked and Assigned(FParent)) then
begin
FParent.Check4ChildrenSharedPrompts;
if (FParent.ChildrenRequired in [crOne, crNoneOrOne]) then
begin
for i := 0 to FParent.FChildren.Count - 1 do
begin
Kid := TRemDlgElement(FParent.FChildren[i]);
if (Kid <> Self) and (Kid.FChecked) then
Kid.SetChecked(FALSE);
end;
end;
end;
UpdateForcedValues(Self);
end
else if (Assigned(FPrompts) and Assigned(FData)) then
begin
for i := 0 to FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FPrompts[i]);
if Prompt.Forced and (IsSyncPrompt(Prompt.PromptType)) then
begin
for j := 0 to FData.Count - 1 do
begin
RData := TRemData(FData[j]);
if (Assigned(RData.FPCERoot)) then
RData.FPCERoot.UnSync(Prompt);
if (Assigned(RData.FChoices)) then
begin
for k := 0 to RData.FChoices.Count - 1 do
begin
if (Assigned(RData.FChoices.Objects[k])) then
TRemPCERoot(RData.FChoices.Objects[k]).UnSync(Prompt);
end;
end;
end;
end;
end;
end;
try
begin
elementList := TStringList.Create;
promptList := TStringList.Create;
linkItem := Piece(Self.FRec1, U, 22);
linkType := Piece(Self.FRec1, U, 23);
linkAction := Piece(Self.FRec1, U, 24);
linkSeq := Piece(self.FRec1, u, 28);
if (linkItem <> '') and (linkAction <> '') and (linkType <> '') then
begin
if linkType = 'ELEMENT' then
begin
if value then elementList.Add(linkItem + U + LINKACTION + U + U + linkSeq)
else elementList.Add(linkItem + U + 'UN'+linkAction + U + U + linkSeq);
end
else if linkAction= 'REQUIRED' then promptList.Add(linkItem + U + linkType + U + 'REQUIRED')
else promptList.Add(linkItem + U + linkType + U + 'VALUE' + U + linkAction);
if buildLinkSeq(linkSeq, self.FID, Piece(self.FRec1, u, 3)) then
self.FReminder.findLinkItem(elementList, promptList, Piece(self.FRec1, u, 3));
end;
end;
finally
if elementList <> nil then FreeAndNil(elementList);
if promptList <> nil then FreeAndNil(promptList);
end;
end;
end;
function TRemDlgElement.TrueIndent: integer;
var
Prnt: TRemDlgElement;
Nudge: integer;
begin
Result := Indent;
Nudge := Gap;
Prnt := FParent;
while Assigned(Prnt) do
begin
if (Prnt.Box) then
begin
Prnt := nil;
inc(Nudge, Gap);
end
else
begin
Result := Result + Prnt.ChildrenIndent;
Prnt := Prnt.FParent;
end;
end;
Result := (Result * IndentMult) + Nudge;
end;
procedure TRemDlgElement.cbClicked(Sender: TObject);
begin
FReminder.BeginTextChanged;
try
FReminder.BeginNeedRedraw;
try
if (Assigned(Sender)) then
begin
SetChecked((Sender as TORCheckBox).Checked);
ElementChecked := Self;
end;
finally
FReminder.EndNeedRedraw(Sender);
end;
finally
FReminder.EndTextChanged(Sender);
end;
RemindersInProcess.Notifier.Notify;
if Assigned(TORCheckBox(Sender).Associate) and (not ScreenReaderSystemActive)
then
if self.FInitialChecked then self.FInitialChecked := false
else TDlgFieldPanel(TORCheckBox(Sender).Associate).SetFocus;
end;
function TRemDlgElement.EnableChildren: boolean;
var
Chk: boolean;
begin
if (Assigned(FParent)) then
Chk := FParent.EnableChildren
else
Chk := TRUE;
if (Chk) then
begin
if (ElemType = etDisplayOnly) then
Result := TRUE
else if (ElemType = etChecked) then
Result := True
else if (ElemType = etDisable) then
Result := false
else
Result := FChecked;
end
else
Result := FALSE;
end;
function TRemDlgElement.Enabled: boolean;
begin
if (Assigned(FParent)) then
Result := FParent.EnableChildren
else
Result := TRUE;
end;
function TRemDlgElement.ShowChildren: boolean;
begin
if (Assigned(FChildren) and (FChildren.Count > 0)) then
begin
if ((ElemType = etDisplayOnly) or FChecked) then
Result := TRUE
else
Result := (not HideChildren);
end
else
Result := FALSE;
end;
type
TAccessCheckBox = class(TORCheckBox);
procedure TRemDlgElement.cbEntered(Sender: TObject);
begin
// changing focus because of a mouse click sets ClicksDisabled to false during the
// call to SetFocus - this is how we allow the cbClicked code to execute on a mouse
// click, which will set the focus after the mouse click. All other cases and the
// ClicksDisabled will be FALSE and the focus is reset here. If we don't make this
// check, you can't click on the check box..
if (Last508KeyCode = VK_UP) or (Last508KeyCode = VK_LEFT) then
begin
UnfocusableControlEnter(nil, Sender);
exit;
end;
if not TAccessCheckBox(Sender).ClicksDisabled then
begin
if ScreenReaderSystemActive then
(Sender as TCPRSDialogParentCheckBox).FocusOnBox := TRUE
else
TDlgFieldPanel(TORCheckBox(Sender).Associate).SetFocus;
end;
end;
procedure TRemDlgElement.ParentCBEnter(Sender: TObject);
begin
(Sender as TORCheckBox).FocusOnBox := TRUE;
end;
procedure TRemDlgElement.ParentCBExit(Sender: TObject);
begin
(Sender as TORCheckBox).FocusOnBox := FALSE;
end;
type
TORExposedWinControl = class(TWinControl);
function TRemDlgElement.BuildControls(var Y: integer; ParentWidth: integer;
BaseParent, AOwner: TWinControl): TWinControl;
var
lbl: TLabel;
lblText: string;
sLbl: TCPRSDialogStaticLabel;
lblCtrl: TControl;
pnl: TDlgFieldPanel;
AutoFocusControl: TWinControl;
cb: TCPRSDialogParentCheckBox;
gb: TGroupBox;
ERes, Prnt: TWinControl;
PrntWidth: integer;
i, X, Y1: integer;
LastX, MinX, MaxX: integer;
Prompt: TRemPrompt;
ctrl: TMultiClassObj;
OK, DoLbl, HasVCombo, cbSingleLine: boolean;
ud: TUpDown;
HelpBtn: TButton;
vCombo: TComboBox;
pt: TRemPromptType;
SameLineCtrl: TList;
Kid: TRemDlgElement;
vt: TVitalType;
DefaultDate: TFMDateTime;
Req: boolean;
isDisable: boolean;
function GetPanel(const EID, AText: string; const PnlWidth: integer;
OwningCheckBox: TCPRSDialogParentCheckBox): TDlgFieldPanel;
var
idx, p: integer;
Entry: TTemplateDialogEntry;
begin
// This call creates a new TTemplateDialogEntry if necessary and creates the
// necessary template field controls with their default values stored in the
// TTemplateField object.
Entry := GetDialogEntry(BaseParent,
EID + IntToStr(integer(BaseParent)), AText);
Entry.InternalID := EID;
// This call looks for the Entry's values in TRemDlgElement.FFieldValues
idx := FFieldValues.IndexOfPiece(EID);
// If the Entry's values were found in the previous step then they will be
// restored to the TTemplateDialogEntry.FieldValues in the next step.
if (idx >= 0) then
begin
p := pos(U, FFieldValues[idx]);
// Can't use Piece because 2nd piece may contain ^ characters
if (p > 0) then
Entry.FieldValues := copy(FFieldValues[idx], p + 1, MaxInt);
end
else
begin
if ((OwningCheckBox = nil) or (OwningCheckBox.Checked = true)) and (Entry.FieldValues <> '') then
FFieldValues.Add(Entry.InternalID + U + Entry.FieldValues);
// if (OwningCheckBox.Checked = true) and (Entry.FieldValues <> '') then
// FFieldValues.Add(Entry.InternalID + U + Entry.FieldValues);
end;
Entry.AutoDestroyOnPanelFree := TRUE;
// The FieldPanelChange event handler is where the Entry.FieldValues are saved to the
// Element.FFieldValues.
Entry.OnChange := FieldPanelChange;
// Calls TTemplateDialogEntry.SetFieldValues which calls
// TTemplateDialogEntry.SetControlText to reset the template field default
// values to the values that were restored to the Entry from the Element if
// they exist, otherwise the default values will remain.
Result := Entry.GetPanel(PnlWidth, BaseParent, OwningCheckBox);
end;
procedure NextLine(var Y: integer);
var
i: integer;
MaxY: integer;
C: TControl;
begin
MaxY := 0;
for i := 0 to SameLineCtrl.Count - 1 do
begin
C := TControl(SameLineCtrl[i]);
if (MaxY < C.Height) then
MaxY := C.Height;
end;
for i := 0 to SameLineCtrl.Count - 1 do
begin
C := TControl(SameLineCtrl[i]);
if (MaxY > C.Height) then
C.Top := Y + ((MaxY - C.Height) div 2);
end;
inc(Y, MaxY);
if Assigned(cb) and Assigned(pnl) then
cb.Top := pnl.Top;
SameLineCtrl.Clear;
end;
procedure ProcessLabel(Required, AEnabled: boolean; AParent: TWinControl;
Control: TControl);
begin
if (Trim(Prompt.Caption) = '') and (not Required) then
lblCtrl := nil
else
begin
lbl := TLabel.Create(AOwner);
lbl.Parent := AParent;
if ScreenReaderSystemActive then
begin
sLbl := TCPRSDialogStaticLabel.Create(AOwner);
sLbl.Parent := AParent;
sLbl.Height := lbl.Height;
lbl.Free;
lblCtrl := sLbl;
end
else
lblCtrl := lbl;
lblText := Prompt.Caption;
if Required then
begin
if Assigned(Control) and Supports(Control, ICPRSDialogComponent) then
begin
(Control as ICPRSDialogComponent).RequiredField := TRUE;
if ScreenReaderSystemActive and (AOwner = frmRemDlg) then
frmRemDlg.amgrMain.AccessText[sLbl] := lblText;
end;
lblText := lblText + ' *';
end;
SetStrProp(lblCtrl, CaptionProperty, lblText);
if ScreenReaderSystemActive then
begin
ScreenReaderSystem_CurrentLabel(sLbl);
ScreenReaderSystem_AddText(lblText);
end;
lblCtrl.Enabled := AEnabled;
UpdateColorsFor508Compliance(lblCtrl);
end;
end;
procedure ScreenReaderSupport(Control: TWinControl);
begin
if ScreenReaderSystemActive then
begin
if Supports(Control, ICPRSDialogComponent) then
ScreenReaderSystem_CurrentComponent(Control as ICPRSDialogComponent)
else
ScreenReaderSystem_Stop;
end;
end;
procedure updatePrompt(var prompt: TRemPrompt);
var
action,frec4: string;
p: integer;
found: boolean;
begin
if prompt.FParent.FReminder.FPromptsDefaults = nil then exit;
frec4 := prompt.FRec4;
found := false;
for p := 0 to prompt.FParent.FReminder.FPromptsDefaults.Count -1 do
begin
action := prompt.FParent.FReminder.FPromptsDefaults.Strings[p];
if ((Piece(FRec4, U, 4) <> Piece(action, U, 2))) or
(Piece(FRec4, U, 2) <> Piece(action, U, 1)) then continue;
if (Piece(action, U, 3) = 'REQUIRED') then
begin
SetPiece(Prompt.FRec4, U, 10, '1');
end
else if (Piece(action, U, 3) = 'UNREQUIRED') then
begin
SetPiece(Prompt.FRec4, U, 10, '0');
end
else
begin
Prompt.SetValueFromParent(Piece(action, U, 4));
// SetPiece(Prompt.FRec4, U, 6 ,(Piece(action, U, 4)));
end;
found := true;
// prompt.FParent.FReminder.FPromptsDefaults.Delete(p);
end;
// if prompt.FParent.FReminder.FPromptsDefaults.Count = 0 then
if found then
FreeAndNil(prompt.FParent.FReminder.FPromptsDefaults);
end;
procedure AddPrompts(Shared: boolean; AParent: TWinControl; PWidth: integer;
var Y: integer);
var
i, j, k, idx: integer;
textArr, DefLoc: TStrings;
LocText, text: string;
LocFound: boolean;
M, n,t: integer;
ActDt, InActDt: Double;
encDt: TFMDateTime;
ActChoicesSL: TORStringList;
Piece12, WHReportStr, TMP: String;
WrapLeft, LineWidth: integer;
begin
SameLineCtrl := TList.Create;
try
if (Assigned(cb)) then
begin
if (not Shared) then
begin
SameLineCtrl.Add(cb);
SameLineCtrl.Add(pnl);
end;
if (cbSingleLine and (not Shared)) then
LastX := cb.Left + pnl.Width + PromptGap + IndentGap
else
LastX := PWidth;
end
else
begin
if (not Shared) then
SameLineCtrl.Add(pnl);
LastX := PWidth;
end;
for i := 0 to FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FPrompts[i]);
updatePrompt(prompt);
OK := ((Prompt.FIsShared = Shared) and Prompt.PromptOK and
(not Prompt.Forced));
if (OK and Shared) then
begin
OK := FALSE;
for j := 0 to Prompt.FSharedChildren.Count - 1 do
begin
Kid := TRemDlgElement(Prompt.FSharedChildren[j]);
if (Kid.FChecked) then
begin
OK := TRUE;
break;
end;
end;
end;
ctrl.ctrl := nil;
ud := nil;
HelpBtn := nil;
vCombo := nil;
HasVCombo := FALSE;
if (OK) then
begin
pt := Prompt.PromptType;
MinX := 0;
MaxX := 0;
lbl := nil;
sLbl := nil;
lblCtrl := nil;
DoLbl := Prompt.Required;
case pt of
ptComment, ptQuantity:
begin
ctrl.edt := TCPRSDialogFieldEdit.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.edt.Text := Prompt.Value;
if (pt = ptComment) then
begin
ctrl.edt.MaxLength := 245;
MinX := TextWidthByFont(ctrl.edt.Font.Handle,
'AbCdEfGhIjKlMnOpQrStUvWxYz 1234');
MaxX := PWidth;
end
else
begin
ud := TUpDown.Create(AOwner);
ud.Parent := AParent;
ud.Associate := ctrl.edt;
if (pt = ptQuantity) then
begin
ud.Min := 1;
ud.max := 100;
end
else
begin
ud.Min := 0;
ud.max := 40;
end;
MinX := TextWidthByFont(ctrl.edt.Font.Handle,
IntToStr(ud.max)) + 24;
ud.Position := StrToIntDef(Prompt.Value, ud.Min);
UpdateColorsFor508Compliance(ud);
end;
ctrl.edt.OnKeyPress := Prompt.EditKeyPress;
if pt = ptComment then
begin
if prompt.EventType = 'E' then ctrl.edt.OnExit := Prompt.PromptChange
else ctrl.edt.OnChange := Prompt.PromptChange;
end
else ctrl.edt.OnChange := Prompt.PromptChange;
UpdateColorsFor508Compliance(ctrl.edt);
DoLbl := TRUE;
end;
ptVisitLocation, ptLevelUnderstanding, ptSeries, ptReaction,
ptExamResults, ptLevelSeverity, ptSkinResults, ptSkinReading:
begin
ctrl.cbo := TCPRSDialogComboBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.cbo.OnKeyDown := Prompt.ComboBoxKeyDown;
ctrl.cbo.Style := orcsDropDown;
ctrl.cbo.Pieces := '2';
if pt = ptSkinReading then
begin
ctrl.cbo.Pieces := '1';
ctrl.cbo.Items.Add('');
for j := 0 to 50 do
ctrl.cbo.Items.Add(IntToStr(j));
GetComboBoxMinMax(ctrl.cbo, MinX, MaxX);
end;
if pt <> ptSkinReading then
begin
ctrl.cbo.Tag := ComboPromptTags[pt];
PCELoadORCombo(ctrl.cbo, MinX, MaxX);
end;
if pt = ptVisitLocation then
begin
DefLoc := TStringList.Create;
try
if GetDefLocations(DefLoc) > 0 then
begin
idx := 1;
for j := 0 to DefLoc.Count - 1 do
begin
LocText := Piece(DefLoc[j], U, 2);
if LocText <> '' then
begin
if (LocText <> '0') and
(IntToStr(StrToIntDef(LocText, 0)) = LocText) then
begin
LocFound := FALSE;
for k := 0 to ctrl.cbo.Items.Count - 1 do
begin
if (Piece(ctrl.cbo.Items[k], U, 1) = LocText) then
begin
LocText := ctrl.cbo.Items[k];
LocFound := TRUE;
break;
end;
end;
if not LocFound then
LocText := '';
end
else
LocText := '0^' + LocText;
if LocText <> '' then
begin
ctrl.cbo.Items.insert(idx, LocText);
inc(idx);
end;
end;
end;
if idx > 1 then
begin
ctrl.cbo.Items.insert(idx, '-1' + LLS_LINE);
ctrl.cbo.Items.insert(idx + 1, '-1' + LLS_SPACE);
end;
end;
finally
FreeAndNil(defLoc);
end
end;
MinX := MaxX;
ctrl.cbo.SelectByID(Prompt.Value);
if (ctrl.cbo.ItemIndex < 0) then
begin
ctrl.cbo.Text := Prompt.Value;
if (pt = ptVisitLocation) then
ctrl.cbo.Items[0] := '0' + U + Prompt.Value;
end;
if (ctrl.cbo.ItemIndex < 0) then
ctrl.cbo.ItemIndex := 0;
ctrl.cbo.OnChange := Prompt.PromptChange;
DoLbl := TRUE;
ctrl.cbo.ListItemsOnly := (pt <> ptVisitLocation);
UpdateColorsFor508Compliance(ctrl.cbo);
end;
ptWHPapResult:
begin
if FData <> nil then
begin
if (TRemData(FData[i]).DisplayWHResults) = TRUE then
begin
NextLine(Y);
ctrl.btn := TCPRSDialogButton.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.btn.Left := NewLinePromptGap + 15;
ctrl.btn.Top := Y + 7;
ctrl.btn.OnClick := Prompt.DoWHReport;
ctrl.btn.Caption := 'Review complete report';
ctrl.btn.Width := TextWidthByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 13;
ctrl.btn.Height := TextHeightByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 13;
ctrl.btn.Height := TextHeightByFont(ctrl.btn.Handle,
ctrl.btn.Caption) + 8;
ScreenReaderSupport(ctrl.btn);
UpdateColorsFor508Compliance(ctrl.btn);
Y := ctrl.btn.Top + ctrl.btn.Height;
NextLine(Y);
ctrl.WHChk := TWHCheckBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ProcessLabel(Prompt.Required, TRUE, ctrl.WHChk.Parent,
ctrl.WHChk);
if lblCtrl is TWinControl then
TWinControl(lblCtrl).TabOrder := ctrl.WHChk.TabOrder;
ctrl.WHChk.Flbl := lblCtrl;
ctrl.WHChk.Flbl.Top := Y + 5;
ctrl.WHChk.Flbl.Left := NewLinePromptGap + 15;
WrapLeft := ctrl.WHChk.Flbl.Left;
Y := ctrl.WHChk.Flbl.Top + ctrl.WHChk.Flbl.Height;
NextLine(Y);
ctrl.WHChk.RadioStyle := TRUE;
ctrl.WHChk.GroupIndex := 1;
ctrl.WHChk.Check2 := TWHCheckBox.Create(AOwner);
ctrl.WHChk.Check2.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.Check2.RadioStyle := TRUE;
ctrl.WHChk.Check2.GroupIndex := 1;
ctrl.WHChk.Check3 := TWHCheckBox.Create(AOwner);
ctrl.WHChk.Check3.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.Check3.RadioStyle := TRUE;
ctrl.WHChk.Check3.GroupIndex := 1;
ctrl.WHChk.Caption := 'NEM (No Evidence of Malignancy)';
ctrl.WHChk.ShowHint := TRUE;
ctrl.WHChk.Hint := 'No Evidence of Malignancy';
ctrl.WHChk.Width := TextWidthByFont(ctrl.WHChk.Font.Handle,
ctrl.WHChk.Caption) + 20;
ctrl.WHChk.Height :=
TextHeightByFont(ctrl.WHChk.Font.Handle,
ctrl.WHChk.Caption) + 4;
ctrl.WHChk.Top := Y + 5;
ctrl.WHChk.Left := WrapLeft;
ctrl.WHChk.OnClick := Prompt.PromptChange;
ctrl.WHChk.Checked := (WHResultChk = 'N');
LineWidth := WrapLeft + ctrl.WHChk.Width + 5;
ctrl.WHChk.Check2.Caption := 'Abnormal';
ctrl.WHChk.Check2.Width :=
TextWidthByFont(ctrl.WHChk.Check2.Font.Handle,
ctrl.WHChk.Check2.Caption) + 20;
ctrl.WHChk.Check2.Height :=
TextHeightByFont(ctrl.WHChk.Check2.Font.Handle,
ctrl.WHChk.Check2.Caption) + 4;
if (LineWidth + ctrl.WHChk.Check2.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.Top + ctrl.WHChk.Height;
NextLine(Y);
end;
ctrl.WHChk.Check2.Top := Y + 5;
ctrl.WHChk.Check2.Left := LineWidth;
ctrl.WHChk.Check2.OnClick := Prompt.PromptChange;
ctrl.WHChk.Check2.Checked := (WHResultChk = 'A');
LineWidth := LineWidth + ctrl.WHChk.Check2.Width + 5;
ctrl.WHChk.Check3.Caption := 'Unsatisfactory for Diagnosis';
ctrl.WHChk.Check3.Width :=
TextWidthByFont(ctrl.WHChk.Check3.Font.Handle,
ctrl.WHChk.Check3.Caption) + 20;
ctrl.WHChk.Check3.Height :=
TextHeightByFont(ctrl.WHChk.Check3.Font.Handle,
ctrl.WHChk.Check3.Caption) + 4;
if (LineWidth + ctrl.WHChk.Check3.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.Check2.Top + ctrl.WHChk.Check2.Height;
NextLine(Y);
end;
ctrl.WHChk.Check3.Top := Y + 5;
ctrl.WHChk.Check3.OnClick := Prompt.PromptChange;
ctrl.WHChk.Check3.Checked := (WHResultChk = 'U');
ctrl.WHChk.Check3.Left := LineWidth;
UpdateColorsFor508Compliance(ctrl.WHChk);
UpdateColorsFor508Compliance(ctrl.WHChk.Flbl);
UpdateColorsFor508Compliance(ctrl.WHChk.Check2);
UpdateColorsFor508Compliance(ctrl.WHChk.Check3);
ScreenReaderSupport(ctrl.WHChk);
ScreenReaderSupport(ctrl.WHChk.Check2);
ScreenReaderSupport(ctrl.WHChk.Check3);
Y := ctrl.WHChk.Check3.Top + ctrl.WHChk.Check3.Height;
NextLine(Y);
end
else
DoLbl := FALSE;
end
else
DoLbl := FALSE;
end;
ptWHNotPurp:
begin
NextLine(Y);
ctrl.WHChk := TWHCheckBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ProcessLabel(Prompt.Required, TRUE, ctrl.WHChk.Parent,
ctrl.WHChk);
ctrl.WHChk.Flbl := lblCtrl;
if lblCtrl is TWinControl then
TWinControl(lblCtrl).TabOrder := ctrl.WHChk.TabOrder;
ctrl.WHChk.Flbl.Top := Y + 7;
ctrl.WHChk.Flbl.Left := NewLinePromptGap + 30;
WrapLeft := ctrl.WHChk.Flbl.Left;
LineWidth := WrapLeft + ctrl.WHChk.Flbl.Width + 10;
ctrl.WHChk.Check2 := TWHCheckBox.Create(AOwner);
ctrl.WHChk.Check2.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.Check3 := TWHCheckBox.Create(AOwner);
ctrl.WHChk.Check3.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.ShowHint := TRUE;
ctrl.WHChk.Hint := 'Letter will print with next WH batch run';
ctrl.WHChk.Caption := 'Letter';
ctrl.WHChk.Width := TextWidthByFont(ctrl.WHChk.Font.Handle,
ctrl.WHChk.Caption) + 25;
ctrl.WHChk.Height := TextHeightByFont(ctrl.WHChk.Font.Handle,
ctrl.WHChk.Caption) + 4;
if (LineWidth + ctrl.WHChk.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.Flbl.Top + ctrl.WHChk.Flbl.Height;
NextLine(Y);
end;
ctrl.WHChk.Top := Y + 7;
ctrl.WHChk.Left := LineWidth;
ctrl.WHChk.OnClick := Prompt.PromptChange;
ctrl.WHChk.Checked := (pos('L', WHResultNot) > 0);
LineWidth := LineWidth + ctrl.WHChk.Width + 10;
ctrl.WHChk.Check2.Caption := 'In-Person';
ctrl.WHChk.Check2.Width :=
TextWidthByFont(ctrl.WHChk.Check2.Font.Handle,
ctrl.WHChk.Check2.Caption) + 25;
ctrl.WHChk.Check2.Height :=
TextHeightByFont(ctrl.WHChk.Check2.Font.Handle,
ctrl.WHChk.Check2.Caption) + 4;
if (LineWidth + ctrl.WHChk.Check2.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.Top + ctrl.WHChk.Height;
NextLine(Y);
end;
ctrl.WHChk.Check2.Top := Y + 7;
ctrl.WHChk.Check2.Left := LineWidth;
ctrl.WHChk.Check2.OnClick := Prompt.PromptChange;
ctrl.WHChk.Check2.Checked := (pos('I', WHResultNot) > 0);
LineWidth := LineWidth + ctrl.WHChk.Check2.Width + 10;
ctrl.WHChk.Check3.Caption := 'Phone Call';
ctrl.WHChk.Check3.Width :=
TextWidthByFont(ctrl.WHChk.Check3.Font.Handle,
ctrl.WHChk.Check3.Caption) + 20;
ctrl.WHChk.Check3.Height :=
TextHeightByFont(ctrl.WHChk.Check3.Font.Handle,
ctrl.WHChk.Check3.Caption) + 4;
if (LineWidth + ctrl.WHChk.Check3.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.Check2.Top + ctrl.WHChk.Check2.Height;
NextLine(Y);
end;
ctrl.WHChk.Check3.Top := Y + 7;
ctrl.WHChk.Check3.OnClick := Prompt.PromptChange;
ctrl.WHChk.Check3.Checked := (pos('P', WHResultNot) > 0);
ctrl.WHChk.Check3.Left := LineWidth;
Y := ctrl.WHChk.Check3.Top + ctrl.WHChk.Check3.Height;
NextLine(Y);
ctrl.WHChk.FButton := TCPRSDialogButton.Create(AOwner);
ctrl.WHChk.FButton.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.FButton.Enabled := (pos('L', WHResultNot) > 0);
ctrl.WHChk.FButton.Left := ctrl.WHChk.Flbl.Left;
ctrl.WHChk.FButton.Top := Y + 7;
ctrl.WHChk.FButton.OnClick := Prompt.ViewWHText;
ctrl.WHChk.FButton.Caption := 'View WH Notification Letter';
ctrl.WHChk.FButton.Width :=
TextWidthByFont(ctrl.WHChk.FButton.Font.Handle,
ctrl.WHChk.FButton.Caption) + 13;
ctrl.WHChk.FButton.Height :=
TextHeightByFont(ctrl.WHChk.FButton.Font.Handle,
ctrl.WHChk.FButton.Caption) + 13;
UpdateColorsFor508Compliance(ctrl.WHChk);
UpdateColorsFor508Compliance(ctrl.WHChk.Flbl);
UpdateColorsFor508Compliance(ctrl.WHChk.Check2);
UpdateColorsFor508Compliance(ctrl.WHChk.Check3);
UpdateColorsFor508Compliance(ctrl.WHChk.FButton);
ScreenReaderSupport(ctrl.WHChk);
ScreenReaderSupport(ctrl.WHChk.Check2);
ScreenReaderSupport(ctrl.WHChk.Check3);
ScreenReaderSupport(ctrl.WHChk.FButton);
LineWidth := ctrl.WHChk.FButton.Left + ctrl.WHChk.FButton.Width;
if Piece(Prompt.FRec4, U, 12) = '1' then
begin
ctrl.WHChk.FPrintNow := TCPRSDialogCheckBox.Create(AOwner);
ctrl.WHChk.FPrintNow.Parent := ctrl.WHChk.Parent;
ctrl.WHChk.FPrintNow.ShowHint := TRUE;
ctrl.WHChk.FPrintNow.Hint :=
'Letter will print after "Finish" button is clicked';
ctrl.WHChk.FPrintNow.Caption := 'Print Now';
ctrl.WHChk.FPrintNow.Width :=
TextWidthByFont(ctrl.WHChk.FPrintNow.Font.Handle,
ctrl.WHChk.FPrintNow.Caption) + 20;
ctrl.WHChk.FPrintNow.Height :=
TextHeightByFont(ctrl.WHChk.FPrintNow.Font.Handle,
ctrl.WHChk.FPrintNow.Caption) + 4;
if (LineWidth + ctrl.WHChk.FPrintNow.Width) > PWidth - 10 then
begin
LineWidth := WrapLeft;
Y := ctrl.WHChk.FButton.Top + ctrl.WHChk.FButton.Height;
NextLine(Y);
end;
ctrl.WHChk.FPrintNow.Left := LineWidth + 15;
ctrl.WHChk.FPrintNow.Top := Y + 7;
ctrl.WHChk.FPrintNow.Enabled := (pos('L', WHResultNot) > 0);
ctrl.WHChk.FPrintNow.Checked := (WHPrintDevice <> '');
ctrl.WHChk.FPrintNow.OnClick := Prompt.PromptChange;
UpdateColorsFor508Compliance(ctrl.WHChk.FPrintNow);
MinX := PWidth;
if (ctrl.WHChk.FButton.Top + ctrl.WHChk.FButton.Height) >
(ctrl.WHChk.FPrintNow.Top + ctrl.WHChk.FPrintNow.Height)
then
Y := ctrl.WHChk.FButton.Top + ctrl.WHChk.FButton.Height + 7
else
Y := ctrl.WHChk.FPrintNow.Top +
ctrl.WHChk.FPrintNow.Height + 7;
ScreenReaderSupport(ctrl.WHChk.FPrintNow);
end
else
Y := ctrl.WHChk.FButton.Top + ctrl.WHChk.FButton.Height + 7;
NextLine(Y);
end;
ptVisitDate:
begin
ctrl.dt := TCPRSDialogDateCombo.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.dt.LongMonths := TRUE;
try
DefaultDate := ctrl.dt.FMDate;
ctrl.dt.FMDate := StrToFloat(Prompt.Value);
except
on EConvertError do
ctrl.dt.FMDate := DefaultDate;
else
raise;
end;
ctrl.dt.OnChange := Prompt.PromptChange;
UpdateColorsFor508Compliance(ctrl.dt);
DoLbl := TRUE;
MinX := ctrl.dt.Width;
end;
ptDate, ptDateTime:
begin
ctrl.date := TCPRSDialogDateBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
if pt = ptDate then ctrl.date.DateOnly := true
else ctrl.date.DateOnly := false;
// ctrl.dt.LongMonths := TRUE;
try
DefaultDate := ctrl.dt.FMDate;
tmp := Prompt.Value;
// ctrl.date.FMDateTime := StrToFloat(Prompt.Value);
if tmp = 'E' then
begin
ctrl.date.FMDateTime := prompt.FParent.FReminder.PCEDataObj.DateTime;
prompt.Value := FloatToStr(ctrl.date.FMDateTime);
end
else
ctrl.date.FMDateTime := StrToFloatDef(tmp, 0);
// ctrl.date.FMDateTime := prompt.FParent.FReminder.FPCEDataObj.DateTime;
except
on EConvertError do
ctrl.date.FMDateTime := DefaultDate;
else
raise;
end;
if Prompt.EventType = 'E' then
ctrl.Date.onExit := Prompt.promptChange
else ctrl.date.OnChange := Prompt.PromptChange;
UpdateColorsFor508Compliance(ctrl.dt);
DoLbl := TRUE;
MinX := ctrl.dt.Width;
end;
ptView, ptPrint:
begin
ctrl.btn := TCPRSDialogButton.Create(AOwner);
ctrl.ctrl.Parent := AParent;
// if Piece(prompt.FRec4, U, 12) <> 'V' then
ctrl.btn.OnClick := Prompt.DoView;
// else ctrl.btn.OnClick := prompt.PromptChange;
ctrl.btn.Caption := Prompt.ForcedCaption;
if prompt.Required then
begin
ctrl.btn.Caption := ctrl.btn.Caption + ' *';
(ctrl.btn as ICPRSDialogComponent).RequiredField := TRUE;
end;
MinX := TextWidthByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 13;
ctrl.btn.Height := TextHeightByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 8;
DoLbl := FALSE;
end;
ptPrimaryDiag, ptAdd2PL, ptContraindicated:
begin
ctrl.cb := TCPRSDialogCheckBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.cb.Checked := (Prompt.Value = '1');
ctrl.cb.Caption := Prompt.Caption;
if Prompt.Required = FALSE then
DoLbl := TRUE;
ctrl.cb.AutoSize := FALSE;
ctrl.cb.OnEnter := ParentCBEnter;
ctrl.cb.OnExit := ParentCBExit;
ctrl.cb.Height := TORCheckBox(ctrl.cb).Height + 5;
ctrl.cb.Width := 17;
ctrl.cb.OnClick := Prompt.PromptChange;
UpdateColorsFor508Compliance(ctrl.cb);
MinX := ctrl.cb.Width;
end;
else
begin
if (pt = ptSubComment) then
begin
ctrl.cb := TCPRSDialogCheckBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.cb.Checked := (Prompt.Value = '1');
ctrl.cb.Caption := Prompt.Caption;
if (ctrl.cb.Checked = false) then
begin
// if textArr = nil then textArr := TStringList.Create;
text := prompt.FParent.FCommentPrompt.value;
if pos(ctrl.cb.Caption, text)>0 then
begin
ctrl.cb.Checked := true;
Prompt.Value := '1';
end;
end;
// PiecestoList(text, ',', textArr);
// for t := 0 to textArr.Count -1 do
// begin
//
// if Pos(trim(textArr.Strings[t]), Prompt.Caption)>0 then ctrl.cb.Checked := true;
//
// end;
// end;
ctrl.cb.AutoSize := TRUE;
ctrl.cb.OnClick := SubCommentChange;
// if (ctrl.cb.Checked = false) then
// begin
//// if textArr = nil then textArr := TStringList.Create;
// text := prompt.FParent.FCommentPrompt.value;
// if pos(Prompt.Caption, text)>0 then ctrl.cb.Checked := true;
// end;
ctrl.cb.Tag := integer(Prompt);
UpdateColorsFor508Compliance(ctrl.cb);
MinX := ctrl.cb.Width;
end
else if pt = ptVitalEntry then
begin
vt := Prompt.VitalType;
if (vt = vtPain) then
begin
ctrl.cbo := TCPRSDialogComboBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.cbo.Style := orcsDropDown;
ctrl.cbo.Pieces := '1,2';
ctrl.cbo.OnKeyDown := Prompt.ComboBoxKeyDown;
InitPainCombo(ctrl.cbo);
ctrl.cbo.ListItemsOnly := TRUE;
ctrl.cbo.SelectByID(Prompt.VitalValue);
ctrl.cbo.OnChange := Prompt.PromptChange;
ctrl.cbo.SelLength := 0;
MinX := TextWidthByFont(ctrl.cbo.Font.Handle,
ctrl.cbo.DisplayText[0]) + 24;
MaxX := TextWidthByFont(ctrl.cbo.Font.Handle,
ctrl.cbo.DisplayText[1]) + 24;
if (ElementChecked = Self) then
begin
AutoFocusControl := ctrl.cbo;
ElementChecked := nil;
end;
UpdateColorsFor508Compliance(ctrl.cbo);
end
else
begin
ctrl.vedt := TVitalEdit.Create(AOwner);
ctrl.ctrl.Parent := AParent;
MinX := TextWidthByFont(ctrl.vedt.Font.Handle, '12345.67');
ctrl.vedt.OnKeyPress := Prompt.EditKeyPress;
ctrl.vedt.OnChange := Prompt.PromptChange;
ctrl.vedt.OnExit := Prompt.VitalVerify;
UpdateColorsFor508Compliance(ctrl.vedt);
if (vt in [vtTemp, vtHeight, vtWeight]) then
begin
HasVCombo := TRUE;
ctrl.vedt.LinkedCombo := TVitalComboBox.Create(AOwner);
ctrl.vedt.LinkedCombo.Parent := AParent;
ctrl.vedt.LinkedCombo.OnChange := Prompt.PromptChange;
ctrl.vedt.LinkedCombo.Tag := VitalControlTag(vt, TRUE);
ctrl.vedt.LinkedCombo.OnExit := Prompt.VitalVerify;
ctrl.vedt.LinkedCombo.LinkedEdit := ctrl.vedt;
case vt of
vtTemp:
begin
ctrl.vedt.LinkedCombo.Items.Add('F');
ctrl.vedt.LinkedCombo.Items.Add('C');
end;
vtHeight:
begin
ctrl.vedt.LinkedCombo.Items.Add('IN');
ctrl.vedt.LinkedCombo.Items.Add('CM');
end;
vtWeight:
begin
ctrl.vedt.LinkedCombo.Items.Add('LB');
ctrl.vedt.LinkedCombo.Items.Add('KG');
end;
end;
ctrl.vedt.LinkedCombo.SelectByID(Prompt.VitalUnitValue);
if (ctrl.vedt.LinkedCombo.ItemIndex < 0) then
ctrl.vedt.LinkedCombo.ItemIndex := 0;
ctrl.vedt.LinkedCombo.Width :=
TextWidthByFont(ctrl.vedt.Font.Handle,
ctrl.vedt.LinkedCombo.Items[1]) + 30;
ctrl.vedt.LinkedCombo.SelLength := 0;
UpdateColorsFor508Compliance(ctrl.vedt.LinkedCombo);
inc(MinX, ctrl.vedt.LinkedCombo.Width);
end;
if (ElementChecked = Self) then
begin
AutoFocusControl := ctrl.vedt;
ElementChecked := nil;
end;
end;
ctrl.ctrl.Text := Prompt.VitalValue;
ctrl.ctrl.Tag := VitalControlTag(vt);
DoLbl := TRUE;
end
else if pt = ptDataList then
begin
ctrl.cbo := TCPRSDialogComboBox.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.cbo.Style := orcsDropDown;
ctrl.cbo.Pieces := '12';
if ActChoicesSL = nil then
ActChoicesSL := TORStringList.Create;
if Self.Historical then
encDt := DateTimeToFMDateTime(Date)
else
encDt := RemForm.PCEObj.VisitDateTime;
if Assigned(Prompt.FData.FChoicesActiveDates)
then { csv active/inactive dates }
for M := 0 to (Prompt.FData.FChoices.Count - 1) do
begin
for n := 0 to
(TStringList(Prompt.FData.FChoicesActiveDates[M])
.Count - 1) do
begin
ActDt := StrToIntDef
((Piece(TStringList(Prompt.FData.FChoicesActiveDates[M])
.Strings[n], ':', 1)), 0);
InActDt :=
StrToIntDef
((Piece(TStringList(Prompt.FData.FChoicesActiveDates[M])
.Strings[n], ':', 2)), 9999999);
// Piece12 := Piece(Piece(Prompt.FData.FChoices.Strings[m],U,12),':',1);
Piece12 := Piece(Prompt.FData.FChoices.Strings[M], U, 12);
Prompt.FData.FChoices.SetStrPiece(M, 12, Piece12);
if (encDt >= ActDt) and (encDt <= InActDt) then
ActChoicesSL.AddObject(Prompt.FData.FChoices[M],
Prompt.FData.FChoices.Objects[M]);
end; { loop through the TStringList object in FChoicesActiveDates[m] object property }
end { loop through FChoices/FChoicesActiveDates }
else
FastAssign(Prompt.FData.FChoices, ActChoicesSL);
FastAssign(ActChoicesSL, ctrl.cbo.Items);
ctrl.cbo.CheckBoxes := TRUE;
ctrl.cbo.SelectByID(Prompt.Value);
ctrl.cbo.OnCheckedText := FReminder.ComboBoxCheckedText;
ctrl.cbo.OnResize := FReminder.ComboBoxResized;
ctrl.cbo.CheckedString := Prompt.Value;
ctrl.cbo.OnChange := Prompt.PromptChange;
ctrl.cbo.ListItemsOnly := TRUE;
UpdateColorsFor508Compliance(ctrl.cbo);
if (ElementChecked = Self) then
begin
AutoFocusControl := ctrl.cbo;
ElementChecked := nil;
end;
DoLbl := TRUE;
if (Prompt.FData.FChoicesFont = ctrl.cbo.Font.Handle) then
begin
MinX := Prompt.FData.FChoicesMin;
MaxX := Prompt.FData.FChoicesMax;
end
// agp ICD-10 suppress combobox and label if no values.
else if (ctrl.cbo.Items.Count > 0) then
begin
GetComboBoxMinMax(ctrl.cbo, MinX, MaxX);
inc(MaxX, 18); // Adjust for checkboxes
MinX := MaxX;
Prompt.FData.FChoicesFont := ctrl.cbo.Font.Handle;
Prompt.FData.FChoicesMin := MinX;
Prompt.FData.FChoicesMax := MaxX;
end
else
DoLbl := FALSE
end
else if (pt = ptMHTest) or ((pt = ptGAF) and (MHDLLFound = TRUE))
then
begin
ctrl.btn := TCPRSDialogButton.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.btn.OnClick := Prompt.DoMHTest;
ctrl.btn.Caption := Prompt.ForcedCaption;
if Piece(Prompt.FData.FRec3, U, 13) = '1' then
begin
ctrl.btn.Caption := ctrl.btn.Caption + ' *';
(ctrl.btn as ICPRSDialogComponent).RequiredField := TRUE;
end;
MinX := TextWidthByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 13;
ctrl.btn.Height := TextHeightByFont(ctrl.btn.Font.Handle,
ctrl.btn.Caption) + 8;
DoLbl := TRUE;
end
else if ((pt = ptGAF)) and (MHDLLFound = FALSE) then
begin
ctrl.edt := TCPRSDialogFieldEdit.Create(AOwner);
ctrl.ctrl.Parent := AParent;
ctrl.edt.Text := Prompt.Value;
ud := TUpDown.Create(AOwner);
ud.Parent := AParent;
ud.Associate := ctrl.edt;
ud.Min := 0;
ud.max := 100;
MinX := TextWidthByFont(ctrl.edt.Font.Handle, IntToStr(ud.max))
+ 24 + Gap;
ud.Position := StrToIntDef(Prompt.Value, ud.Min);
ctrl.edt.OnKeyPress := Prompt.EditKeyPress;
ctrl.edt.OnChange := Prompt.PromptChange;
if (User.WebAccess and (GAFURL <> '')) then
begin
HelpBtn := TCPRSDialogButton.Create(AOwner);
HelpBtn.Parent := AParent;
HelpBtn.Caption := 'Reference Info';
HelpBtn.OnClick := Prompt.GAFHelp;
HelpBtn.Width := TextWidthByFont(HelpBtn.Font.Handle,
HelpBtn.Caption) + 13;
HelpBtn.Height := ctrl.edt.Height;
inc(MinX, HelpBtn.Width);
end;
DoLbl := TRUE;
end
else
ctrl.ctrl := nil;
end;
end;
if (DoLbl) and ((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then
begin
Req := Prompt.Required;
if (not Req) and (pt = ptGAF) and (MHDLLFound = FALSE) then
Req := (Piece(Prompt.FData.FRec3, U, 13) = '1');
ProcessLabel(Req, Prompt.FParent.Enabled, AParent, ctrl.ctrl);
if Assigned(lblCtrl) then
begin
inc(MinX, lblCtrl.Width + LblGap);
inc(MaxX, lblCtrl.Width + LblGap);
end
else
DoLbl := FALSE;
end;
if (MaxX < MinX) then
MaxX := MinX;
if ((Prompt.SameLine) and ((LastX + MinX + Gap) < PWidth)) and
((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then
begin
X := LastX;
end
else
begin
if (Shared) and (Assigned(FChildren)) and (FChildren.Count > 0) then
X := TRemDlgElement(FChildren[0]).TrueIndent
else
begin
if (Assigned(cb)) then
X := cb.Left + NewLinePromptGap
else
X := pnl.Left + NewLinePromptGap;
end;
NextLine(Y);
end;
if (MaxX > (PWidth - X - Gap)) then
MaxX := PWidth - X - Gap;
if ((DoLbl) or (Assigned(ctrl.ctrl))) and
((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then
begin
if DoLbl then
begin
lblCtrl.Left := X;
lblCtrl.Top := Y;
inc(X, lblCtrl.Width + LblGap);
dec(MinX, lblCtrl.Width + LblGap);
dec(MaxX, lblCtrl.Width + LblGap);
SameLineCtrl.Add(lblCtrl);
end;
if (Assigned(ctrl.ctrl)) then
begin
if ScreenReaderSystemActive then
begin
if Supports(ctrl.ctrl, ICPRSDialogComponent) then
ScreenReaderSystem_CurrentComponent
(ctrl.ctrl as ICPRSDialogComponent)
else
ScreenReaderSystem_Stop;
end;
ctrl.ctrl.Enabled := Prompt.FParent.Enabled;
if not ctrl.ctrl.Enabled then
ctrl.ctrl.Font.Color := DisabledFontColor;
ctrl.ctrl.Left := X;
ctrl.ctrl.Top := Y;
SameLineCtrl.Add(ctrl.ctrl);
if (Assigned(ud)) then
begin
SameLineCtrl.Add(ud);
if (Assigned(HelpBtn)) then
begin
SameLineCtrl.Add(HelpBtn);
ctrl.ctrl.Width := MinX - HelpBtn.Width - ud.Width;
HelpBtn.Left := X + ctrl.ctrl.Width + ud.Width + Gap;
HelpBtn.Top := Y;
HelpBtn.Enabled := Prompt.FParent.Enabled;
end
else
ctrl.ctrl.Width := MinX - ud.Width;
ud.Left := X + ctrl.ctrl.Width;
ud.Top := Y;
LastX := X + MinX + PromptGap;
ud.Enabled := Prompt.FParent.Enabled;
end
else if (HasVCombo) then
begin
SameLineCtrl.Add(ctrl.vedt.LinkedCombo);
ctrl.ctrl.Width := MinX - ctrl.vedt.LinkedCombo.Width;
ctrl.vedt.LinkedCombo.Left := X + ctrl.ctrl.Width;
ctrl.vedt.LinkedCombo.Top := Y;
LastX := X + MinX + PromptGap;
ctrl.vedt.LinkedCombo.Enabled := Prompt.FParent.Enabled;
end
else
begin
ctrl.ctrl.Width := MaxX;
LastX := X + MaxX + PromptGap;
end;
end;
end;
end;
if (Assigned(ud)) then
Prompt.FCurrentControl := ud
else
Prompt.FCurrentControl := ctrl.ctrl;
end;
NextLine(Y);
finally
SameLineCtrl.Free;
end;
end;
procedure UpdatePrompts(EnablePanel: boolean; ClearCB: boolean);
begin
if EnablePanel then
begin
if not ScreenReaderSystemActive then
begin
pnl.TabStop := TRUE;
{ tab through the panels instead of the checkboxes }
pnl.OnEnter := FieldPanelEntered;
pnl.OnExit := FieldPanelExited;
end;
if ClearCB then
cb := nil;
end;
if (FChecked and Assigned(FPrompts) and (FPrompts.Count > 0)) then
begin
AddPrompts(FALSE, BaseParent, ParentWidth, Y);
end
else
inc(Y, pnl.Height);
end;
begin
Result := nil;
cb := nil;
pnl := nil;
if elemType = etDisable then isDisable := true
// else if assigned(fparent) and (fParent.ElemType = etDisable) then isDisable := true
else isDisable := false;
AutoFocusControl := nil;
X := TrueIndent;
if (Assigned(FPrompts)) then
begin
for i := 0 to FPrompts.Count - 1 do
TRemPrompt(FPrompts[i]).FCurrentControl := nil;
end;
if (ElemType = etDisplayOnly) or ((isDisable) and (Piece(originalType, U, 1) = 'D')) then
begin
if (FText <> '') then
begin
inc(Y, Gap);
pnl := GetPanel(EntryID, CRLFText(FText),
ParentWidth - X - (Gap * 2), nil);
pnl.Left := X;
pnl.Top := Y;
UpdatePrompts(ScreenReaderSystemActive, TRUE);
if isDisable then
pnl.Font.Color := DisabledFontColor;
end;
end
else
begin
inc(Y, Gap);
cb := TCPRSDialogParentCheckBox.Create(AOwner);
cb.Parent := BaseParent;
cb.Left := X;
cb.Top := Y;
cb.Tag := integer(Self);
cb.WordWrap := TRUE;
cb.AutoSize := TRUE;
if isDisable then
begin
cb.checked := false;
cb.Enabled := false;
end
else
cb.Checked := FChecked;
cb.Width := ParentWidth - X - Gap;
if not ScreenReaderSystemActive then
cb.Caption := CRLFText(FText);
cb.AutoAdjustSize;
cbSingleLine := cb.SingleLine;
cb.WordWrap := FALSE;
cb.Caption := ' ';
if not ScreenReaderSystemActive then
cb.TabStop := FALSE; { take checkboxes out of the tab order }
pnl := GetPanel(EntryID, CRLFText(FText), ParentWidth - X - (Gap * 2) -
IndentGap, cb);
pnl.Left := X + IndentGap;
pnl.Top := Y;
if (isDisable) then pnl.Font.Color := DisabledFontColor;
cb.Associate := pnl;
pnl.Tag := integer(cb); { So the panel can check the checkbox }
cb.OnClick := cbClicked;
cb.OnEnter := cbEntered;
if ScreenReaderSystemActive then
cb.OnExit := ParentCBExit;
UpdateColorsFor508Compliance(cb);
pnl.OnKeyPress := FieldPanelKeyPress;
pnl.OnClick := FieldPanelOnClick;
for i := 0 to pnl.ControlCount - 1 do
if ((pnl.Controls[i] is TLabel) or (pnl.Controls[i] is TVA508StaticText))
and not(fsUnderline in TLabel(pnl.Controls[i]).Font.Style) then
// If this isn't a hyperlink change then event handler
TLabel(pnl.Controls[i]).OnClick := FieldPanelLabelOnClick;
if (Assigned(FParent) and (FParent.ChildrenRequired in [crOne, crNoneOrOne]))
then
cb.RadioStyle := TRUE;
// if (ElemType = etChecked) then
// begin
// cb.Checked := true;
// self.FInitialChecked := true;
// UpdatePrompts(True, False);
// end
// else
UpdatePrompts(TRUE, FALSE);
end;
if (ShowChildren) then
begin
gb := nil;
if (Box) then
begin
gb := TGroupBox.Create(AOwner);
gb.Parent := BaseParent;
gb.Left := TrueIndent + (ChildrenIndent * IndentMult);
gb.Top := Y;
gb.Width := ParentWidth - gb.Left - Gap;
PrntWidth := gb.Width - (Gap * 2);
gb.Caption := BoxCaption;
gb.Enabled := EnableChildren;
if (not EnableChildren) then
gb.Font.Color := DisabledFontColor;
UpdateColorsFor508Compliance(gb);
Prnt := gb;
if (gb.Caption = '') then
Y1 := gbTopIndent
else
Y1 := gbTopIndent2;
end
else
begin
Prnt := BaseParent;
Y1 := Y;
PrntWidth := ParentWidth;
// if elemType = etDisable then Prnt.Enabled := false;
end;
for i := 0 to FChildren.Count - 1 do
begin
ERes := TRemDlgElement(FChildren[i]).BuildControls(Y1, PrntWidth,
Prnt, AOwner);
if (not Assigned(Result)) then
Result := ERes;
end;
if (FHasSharedPrompts) then
AddPrompts(TRUE, Prnt, PrntWidth, Y1);
if (Box) then
begin
gb.Height := Y1 + (Gap * 3);
inc(Y, Y1 + (Gap * 4));
end
else
Y := Y1;
end;
SubCommentChange(nil);
if (Assigned(AutoFocusControl)) then
begin
if (AutoFocusControl is TORComboBox) and
(TORComboBox(AutoFocusControl).CheckBoxes) and
(pos('1', TORComboBox(AutoFocusControl).CheckedString) = 0) then
Result := AutoFocusControl
else if (TORExposedControl(AutoFocusControl).Text = '') then
Result := AutoFocusControl
end;
if ScreenReaderSystemActive then
ScreenReaderSystem_Stop;
end;
function TRemDlgElement.buildLinkSeq(linkIEN, dialogIEN, seq: string): boolean;
var
seqList: TStrings;
idx: integer;
hasStart, found: boolean;
temp: string;
begin
if linkIEN = '0' then
begin
result := true;
exit;
end;
seqList := TStringList.Create;
try
if self.FReminder.linkSeqListChecked.IndexOf(linkIEN) = -1 then
begin
getLinkSeqList(seqlist, linkIEN);
FastAssign(seqList, FReminder.linkSeqList);
// for idx := 0 to seqList.Count - 1 do
// self.FReminder.linkSeqList.Add(linkIEN + U + seqList.Strings[idx]);
self.FReminder.linkSeqListChecked.Add(linkIEN);
end;
hasStart := false;
found := false;
for idx := 0 to FReminder.linkSeqList.Count - 1 do
begin
temp := FReminder.linkSeqList.Strings[idx];
if Piece(temp, U, 2) <> '' then
begin
hasStart := true;
if Piece(temp, U, 2) = seq then
begin
found := true;
break;
end;
end;
end;
if hasStart then
begin
if not found then result := false
else result := true
end
else result := true;
finally
FreeAndNil(seqList);
end;
end;
// This is used to get the template field values if this reminder is not the
// current reminder in dialog, in which case no uEntries will exist so we have
// to get the template field values that were saved in the element.
function TRemDlgElement.GetTemplateFieldValues(const Text: string;
FldValues: TORStringList = nil): string;
var
flen, CtrlID, i, j: integer;
Fld: TTemplateField;
temp, FldName, NewTxt: string;
const
TemplateFieldBeginSignature = '{FLD:';
TemplateFieldEndSignature = '}';
TemplateFieldSignatureLen = length(TemplateFieldBeginSignature);
TemplateFieldSignatureEndLen = length(TemplateFieldEndSignature);
FieldIDDelim = '`';
FieldIDLen = 6;
procedure AddNewTxt;
begin
if (NewTxt <> '') then
begin
insert(StringOfChar('x', length(NewTxt)), temp, i);
insert(NewTxt, Result, i);
inc(i, length(NewTxt));
end;
end;
begin
Result := Text;
temp := Text;
repeat
i := pos(TemplateFieldBeginSignature, temp);
if (i > 0) then
begin
CtrlID := 0;
if (copy(temp, i + TemplateFieldSignatureLen, 1) = FieldIDDelim) then
begin
CtrlID := StrToIntDef(copy(temp, i + TemplateFieldSignatureLen + 1,
FieldIDLen - 1), 0);
delete(temp, i + TemplateFieldSignatureLen, FieldIDLen);
delete(Result, i + TemplateFieldSignatureLen, FieldIDLen);
end;
j := pos(TemplateFieldEndSignature,
copy(temp, i + TemplateFieldSignatureLen, MaxInt));
if (j > 0) then
begin
inc(j, i + TemplateFieldSignatureLen - 1);
flen := j - i - TemplateFieldSignatureLen;
FldName := copy(temp, i + TemplateFieldSignatureLen, flen);
Fld := GetTemplateField(FldName, FALSE);
delete(temp, i, flen + TemplateFieldSignatureLen + 1);
delete(Result, i, flen + TemplateFieldSignatureLen + 1);
end
else
begin
delete(temp, i, TemplateFieldSignatureLen);
delete(Result, i, TemplateFieldSignatureLen);
Fld := nil;
end;
// Get the value that was entered if there is one
if Assigned(FldValues) and (CtrlID > 0) then
begin
j := FldValues.IndexOfPiece(IntToStr(CtrlID));
if not(j < 0) then
if Fld.DateType in DateComboTypes then
NewTxt := Piece(Piece(FldValues[j], U, 2), ':', 1)
else
NewTxt := Piece(FldValues[j], U, 2);
end;
// If nothing has been entered, use the default
if (NewTxt = '') and Assigned(Fld) and
// If this template field is a dftHyperlink or dftText that is
// excluded (FSepLines = True) then don't get the default text
not((Fld.FldType in [dftHyperlink, dftText]) and Fld.SepLines) then
NewTxt := Fld.TemplateFieldDefault;
AddNewTxt;
end;
until not(i > 0);
end;
procedure TRemDlgElement.AddText(Lst: TStrings);
var
i, ilvl: integer;
Prompt: TRemPrompt;
txt: string;
FldData: TORStringList;
begin
if (not(FReminder is TReminder)) then
ScootOver := 4;
try
if Add2PN then
begin
ilvl := IndentPNLevel;
if (FPNText <> '') then
txt := FPNText
else
begin
txt := FText;
if not FReminder.FNoResolve then
// If this is the CurrentReminderInDialog then we get the template field
// values from the visual control in the dialog window.
if FReminder = CurrentReminderInDialog then
txt := ResolveTemplateFields(CRLFText(txt), false, false, false, (ilvl + ScootOver))
else
// If this is not the CurrentReminderInDialog (i.e.: Next or Back button
// has been pressed), then we have to get the template field values
// that were saved in the element.
begin
FldData := TORStringList.Create;
GetFieldValues(FldData);
txt := GetTemplateFieldValues(txt, FldData);
end;
end;
if FReminder.FNoResolve then
begin
StripScreenReaderCodes(txt);
Lst.Add(txt);
end
else
WordWrap(txt, Lst, ilvl);
dec(ilvl, 2);
if (Assigned(FPrompts)) then
begin
for i := 0 to FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FPrompts[i]);
if (not Prompt.FIsShared) then
begin
if Prompt.PromptType = ptMHTest then
WordWrap(Prompt.NoteText, Lst, ilvl, 4, TRUE)
else
WordWrap(Prompt.NoteText, Lst, ilvl);
end;
end;
end;
if (Assigned(FParent) and FParent.FHasSharedPrompts) then
begin
for i := 0 to FParent.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FParent.FPrompts[i]);
if (Prompt.FIsShared) and (Prompt.FSharedChildren.IndexOf(Self) >= 0)
then
begin
// AGP Change MH dll
if (Prompt.PromptType = ptMHTest) then
WordWrap(Prompt.NoteText, Lst, ilvl, 4, TRUE)
else
WordWrap(Prompt.NoteText, Lst, ilvl);
end;
end;
end;
end;
if (Assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then
begin
for i := 0 to FChildren.Count - 1 do
begin
TRemDlgElement(FChildren[i]).AddText(Lst);
end;
end;
finally
if (not(FReminder is TReminder)) then
ScootOver := 0;
end;
end;
function TRemDlgElement.AddData(Lst: TStrings; Finishing: boolean;
AHistorical: boolean = FALSE): integer;
var
i, j: integer;
OK: boolean;
ActDt, InActDt, encDt: Double;
RData: TRemData;
foundDone: boolean;
newDataOnly: String;
function findDataGroup(elem: TRemDlgElement; var foundDone: boolean): string;
begin
while foundDone = false do
begin
if Piece(elem.FParent.FRec1, U, 26) <> '' then
begin
result := Piece(elem.FParent.FRec1, U, 26);
foundDone := true;
end
else if elem.FParent.FParent <> nil then
begin
result := findDataGroup(elem.FParent, foundDone);
foundDone := true;
end
else begin
result := '';
foundDone := true;
end;
end;
end;
begin
Result := 0;
// OK := ((ElemType <> etDisplayOnly) and FChecked);
OK := FChecked;
newDataOnly := Piece(self.FRec1, U, 27);
if (OK and Finishing) then
OK := (Historical = AHistorical);
if OK then
begin
if (Assigned(FData)) then
begin
if Self.Historical then
encDt := DateTimeToFMDateTime(Date)
else
encDt := RemForm.PCEObj.VisitDateTime;
for i := 0 to FData.Count - 1 do
begin
RData := TRemData(FData[i]);
if newDataOnly <> Piece(RData.FRec3, U, 16) then
continue;
if finishing and (Piece(RData.FRec3, U, 17) = '') and (self.FParent <> nil) then
begin
foundDone := false;
setPiece(RData.FRec3, U, pnumRemGenFindGroup, findDataGroup(self, foundDone));
end
else if finishing and (Piece(RData.FRec3, U, 17) <> '') then
setPiece(RData.FRec3, U, pnumRemGenFindGroup, Piece(RData.FRec3, U, 17));
if Assigned(RData.FActiveDates) then
for j := 0 to (TRemData(FData[i]).FActiveDates.Count - 1) do
begin
ActDt := StrToIntDef(Piece(TRemData(FData[i]).FActiveDates[j],
':', 1), 0);
InActDt := StrToIntDef(Piece(TRemData(FData[i]).FActiveDates[j],
':', 2), 9999999);
if (encDt >= ActDt) and (encDt <= InActDt) then
begin
inc(Result, TRemData(FData[i]).AddData(Lst, Finishing));
break;
end;
end
else
inc(Result, TRemData(FData[i]).AddData(Lst, Finishing));
end;
end;
end;
if (Assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then
begin
for i := 0 to FChildren.Count - 1 do
inc(Result, TRemDlgElement(FChildren[i]).AddData(Lst, Finishing,
AHistorical));
end;
end;
procedure TRemDlgElement.Check4ChildrenSharedPrompts;
var
i, j: integer;
Kid: TRemDlgElement;
PList, EList: TList;
FirstMatch: boolean;
Prompt: TRemPrompt;
begin
if (not FChildrenShareChecked) then
begin
FChildrenShareChecked := TRUE;
if (ChildrenSharePrompts and Assigned(FChildren)) then
begin
for i := 0 to FChildren.Count - 1 do
TRemDlgElement(FChildren[i]).GetData;
PList := TList.Create;
try
EList := TList.Create;
try
for i := 0 to FChildren.Count - 1 do
begin
Kid := TRemDlgElement(FChildren[i]);
// if(Kid.ElemType <> etDisplayOnly) and (assigned(Kid.FPrompts)) then
if (Assigned(Kid.FPrompts)) then
begin
for j := 0 to Kid.FPrompts.Count - 1 do
begin
PList.Add(Kid.FPrompts[j]);
EList.Add(Kid);
end;
end;
end;
if (PList.Count > 1) then
begin
for i := 0 to PList.Count - 2 do
begin
if (Assigned(EList[i])) then
begin
FirstMatch := TRUE;
Prompt := TRemPrompt(PList[i]);
for j := i + 1 to PList.Count - 1 do
begin
if (Assigned(EList[j]) and
(Prompt.CanShare(TRemPrompt(PList[j])))) then
begin
if (FirstMatch) then
begin
FirstMatch := FALSE;
if (not Assigned(FPrompts)) then
FPrompts := TList.Create;
FHasSharedPrompts := TRUE;
Prompt.FIsShared := TRUE;
if (not Assigned(Prompt.FSharedChildren)) then
Prompt.FSharedChildren := TList.Create;
Prompt.FSharedChildren.Add(EList[i]);
FPrompts.Add(PList[i]);
TRemDlgElement(EList[i]).FPrompts.Remove(PList[i]);
EList[i] := nil;
end;
Prompt.FSharedChildren.Add(EList[j]);
Kid := TRemDlgElement(EList[j]);
Kid.FPrompts.Remove(PList[j]);
if (Kid.FHasComment) and (Kid.FCommentPrompt = PList[j])
then
begin
Kid.FHasComment := FALSE;
Kid.FCommentPrompt := nil;
end;
TRemPrompt(PList[j]).Free;
EList[j] := nil;
end;
end;
end;
end;
end;
finally
EList.Free;
end;
finally
PList.Free;
end;
for i := 0 to FChildren.Count - 1 do
begin
Kid := TRemDlgElement(FChildren[i]);
if (Assigned(Kid.FPrompts) and (Kid.FPrompts.Count = 0)) then
begin
Kid.FPrompts.Free;
Kid.FPrompts := nil;
end;
end;
end;
end;
end;
procedure TRemDlgElement.FinishProblems(List: TStrings);
var
i, Cnt: integer;
cReq: TRDChildReq;
Kid: TRemDlgElement;
Prompt: TRemPrompt;
txt, Msg, Value: string;
pt: TRemPromptType;
required: boolean;
begin
// if(ElemType <> etDisplayOnly) and (FChecked) and (assigned(FPrompts)) then
if (FChecked and (Assigned(FPrompts))) then
begin
for i := 0 to FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FPrompts[i]);
if assigned(Prompt.reportView) then
begin
if Prompt.reportView.Showing then
begin
Prompt.reportView.cmdClose.Click;
FreeAndNil(Prompt.reportView);
end;
// Prompt.reportView.Close;
end;
Value := Prompt.GetValue;
pt := Prompt.PromptType;
required := false;
if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and
(((pt <> ptWHNotPurp) and (pt <> ptWHPapResult) and ((pt <> ptView) and (pt <> ptPrint))) and
((Value = '') or (Value = '@') or ((pt = ptPrimaryDiag) and
(Value = '0'))) or ((pt in [ptVisitDate, ptDate, ptDateTime]) and
Prompt.FMonthReq and (StrToIntDef(copy(Value, 4, 2), 0) = 0)) or
((pt in [ptVisitDate, ptVisitLocation]) and (Value = '0'))))
then required := true
else if Prompt.Required and ((pt = ptDate) or (pt = ptDateTime))
then required := true;
if (required = true) and ((pt = ptDate) or (pt = ptDateTime)) then
begin
if (StrToIntDef(copy(Value, 4, 2), 0) <> 0) and (StrToIntDef(copy(Value, 6, 2), 0) <> 0) then
required := false;
end;
// if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and
// (((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) and
// ((Value = '') or (Value = '@') or ((pt = ptPrimaryDiag) and
// (Value = '0'))) or ((pt in [ptVisitDate]) and
// Prompt.FMonthReq and (StrToIntDef(copy(Value, 4, 2), 0) = 0)) or
// ((pt in [ptVisitDate, ptVisitLocation]) and (Value = '0')))
// or((pt = ptDate) and ((StrToIntDef(copy(Value, 4, 2), 0) = 0) or
// (StrToIntDef(copy(Value, 6, 2), 0) = 0))))
if required = true then
begin
WordWrap('Element: ' + FText, List, 68, 6);
txt := Prompt.ForcedCaption;
if (pt in [ptVisitDate]) and Prompt.FMonthReq then
txt := txt + ' (Month Required)';
WordWrap('Item: ' + txt, List, 65, 6);
if (pt = ptDate) then txt := txt + ' (Month and Day Required)';
WordWrap('Item: ' + txt, List, 65, 6);
end;
if (pt = ptDate) then
begin
if ( prompt.validate = HistCode) and (StrToFloatDef(value, 0) > FMNow) then
begin
txt := Prompt.ForcedCaption + ' cannot have a date in the future.';
WordWrap('Prompt: ' + txt, List, 65, 6);
end;
if ( prompt.validate = FutureCode) and (StrToFloatDef(value, 0) < FMNow) then
begin
txt := Prompt.ForcedCaption + ' cannot have a date in the past.';
WordWrap('Prompt: ' + txt, List, 65, 6);
end;
end;
if (pt = ptDateTime) and (StrToFloatDef(value, 0) < FMNOW) then
begin
txt := Prompt.ForcedCaption + ' cannot have a date/time in the past.';
WordWrap('Prompt: ' + txt, List, 65, 6);
end;
if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and
((WHResultChk = '') and (Value = '')) and ((pt = ptWHPapResult) and
(FData <> nil))) then
begin
WordWrap('Prompt: ' + Prompt.ForcedCaption, List, 65, 6);
end;
if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and
(pt = ptWHNotPurp)) and ((WHResultNot = '') and (Value = '')) then
begin
WordWrap('Element: ' + FText, List, 68, 6);
WordWrap('Prompt: ' + Prompt.ForcedCaption, List, 65, 6);
end;
if ((pt = ptView) or (pt = ptPrint)) and (Prompt.Required) then
begin
if prompt.ViewRecord then break
else
begin
WordWrap('Element: ' + FText, List, 68, 6);
WordWrap('Prompt: ' + Prompt.ForcedCaption + ' must be viewed', List, 65, 6);
end;
end;
// (AGP Change 24.9 add check to see if MH tests are required)
if ((pt = ptMHTest) or (pt = ptGAF)) and
(StrToInt(Piece(Prompt.FData.FRec3, U, 13)) > 0) and (not Prompt.Forced)
then
begin
if (Piece(Prompt.FData.FRec3, U, 13) = '2') and
(Prompt.FMHTestComplete = 0) then
break;
if (pt = ptMHTest) and (Prompt.FMHTestComplete = 2) then
begin
if ((Prompt.FValue = '') or (pos('X', Prompt.FValue) > 0)) then
begin
if Prompt.FValue = '' then
WordWrap('MH test ' + Piece(Prompt.FData.FRec3, U, 8) +
' not done', List, 65, 6);
if pos('X', Prompt.FValue) > 0 then
WordWrap('You are missing one or more responses in the MH test ' +
Piece(Prompt.FData.FRec3, U, 8), List, 65, 6);
WordWrap(' ', List, 65, 6);
end;
end;
if (pt = ptMHTest) and (Prompt.FMHTestComplete = 0) or
((Prompt.FValue = '') and (pos('New MH dll', Prompt.FValue) = 0)) then
begin
if Prompt.FValue = '' then
WordWrap('MH test ' + Piece(Prompt.FData.FRec3, U, 8) + ' not done',
List, 65, 6);
if pos('X', Prompt.FValue) > 0 then
WordWrap('You are missing one or more responses in the MH test ' +
Piece(Prompt.FData.FRec3, U, 8), List, 65, 6);
WordWrap(' ', List, 65, 6);
end;
if (pt = ptMHTest) and (Prompt.FMHTestComplete = 0) and
(pos('New MH dll', Prompt.FValue) > 0) then
begin
WordWrap('MH test ' + Piece(Prompt.FData.FRec3, U, 8) +
' is not complete', List, 65, 6);
WordWrap(' ', List, 65, 6);
end;
if (pt = ptGAF) and ((Prompt.FValue = '0') or (Prompt.FValue = '')) then
begin
WordWrap('GAF test must have a score greater then zero', List, 65, 6);
WordWrap(' ', List, 65, 6);
end;
end;
end;
end;
if (Assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then
begin
cReq := ChildrenRequired;
if (cReq in [crOne, crAtLeastOne, crAll]) then
begin
Cnt := 0;
for i := 0 to FChildren.Count - 1 do
begin
Kid := TRemDlgElement(FChildren[i]);
// if(Kid.FChecked and (Kid.ElemType <> etDisplayOnly)) then
if (Kid.FChecked) then
inc(Cnt);
end;
if (cReq = crOne) and (Cnt <> 1) then
Msg := 'One selection required'
else if (cReq = crAtLeastOne) and (Cnt < 1) then
Msg := 'One or more selections required'
else if (cReq = crAll) and (Cnt < FChildren.Count) then
Msg := 'All selections are required'
else
Msg := '';
if (Msg <> '') then
begin
txt := BoxCaption;
if (txt = '') then
txt := FText;
WordWrap('Group: ' + txt, List, 68, 6);
WordWrap(Msg, List, 65, 0);
WordWrap(' ', List, 68, 6);
// (AGP change 24.9 added blank line for display spacing)
end;
end;
for i := 0 to FChildren.Count - 1 do
TRemDlgElement(FChildren[i]).FinishProblems(List);
end;
end;
function TRemDlgElement.IsChecked: boolean;
var
Prnt: TRemDlgElement;
begin
Result := TRUE;
Prnt := Self;
while Result and Assigned(Prnt) do
begin
Result := ((Prnt.ElemType = etDisplayOnly) or Prnt.FChecked);
Prnt := Prnt.FParent;
end;
end;
procedure TRemDlgElement.linkItemRedraw(element: TRemDlgElement);
begin
FReminder.BeginTextChanged;
try
begin
FReminder.BeginNeedRedraw;
FReminder.EndNeedRedraw(element);
end;
finally
FReminder.EndTextChanged(element);
end;
RemindersInProcess.Notifier.Notify;
end;
// agp ICD-10 add this function to scan for valid codes against encounter date.
function TRemDlgElement.oneValidCode(Choices: TORStringList;
ChoicesActiveDates: TList; encDt: TFMDateTime): string;
var
C, Cnt, lastItem: integer;
Prompt: TRemPrompt;
begin
Cnt := 0;
Result := '';
Prompt := TRemPrompt.Create();
lastItem := 0;
for C := 0 to Choices.Count - 1 do
begin
if (Prompt.CompareActiveDate(TStringList(ChoicesActiveDates[C]), encDt)
= TRUE) then
begin
Cnt := Cnt + 1;
lastItem := C;
if (Cnt > 1) then
break;
end;
end;
if (Cnt = 1) then
Result := Choices[lastItem];
end;
function TRemDlgElement.IndentChildrenInPN: boolean;
begin
// if(Box) then
Result := (Piece(FRec1, U, 21) = '1');
// else
// Result := FALSE;
end;
function TRemDlgElement.IndentPNLevel: integer;
begin
if (Assigned(FParent)) then
begin
Result := FParent.IndentPNLevel;
if (FParent.IndentChildrenInPN) then
dec(Result, 2);
end
else
Result := 76;
end;
function TRemDlgElement.IncludeMHTestInPN: boolean;
begin
Result := (Piece(FRec1, U, 9) = '0');
end;
function TRemDlgElement.ResultDlgID: string;
begin
Result := Piece(FRec1, U, 10);
end;
procedure TRemDlgElement.setActiveDates(Choices: TORStringList;
ChoicesActiveDates: TList; ActiveDates: TStringList);
var
C: integer;
begin
for C := 0 to Choices.Count - 1 do
begin
ActiveDates.Add(TStringList(ChoicesActiveDates[C]).CommaText)
end;
end;
procedure TRemDlgElement.SubCommentChange(Sender: TObject);
var
i: integer;
txt: string;
OK: boolean;
begin
if (FHasSubComments and FHasComment and Assigned(FCommentPrompt)) then
begin
OK := FALSE;
if (Assigned(Sender)) then
begin
with (Sender as TORCheckBox) do
TRemPrompt(Tag).FValue := BOOLCHAR[Checked];
OK := TRUE;
end;
if (not OK) then
OK := (FCommentPrompt.GetValue = '');
if (OK) then
begin
for i := 0 to FPrompts.Count - 1 do
begin
with TRemPrompt(FPrompts[i]) do
begin
if (PromptType = ptSubComment) and (FValue = BOOLCHAR[TRUE]) then
begin
if (txt <> '') then
txt := txt + ', ';
txt := txt + Caption;
end;
end;
end;
if (txt <> '') then
txt[1] := UpCase(txt[1]);
FCommentPrompt.SetValue(txt);
end;
end;
end;
constructor TRemDlgElement.Create;
begin
FFieldValues := TORStringList.Create;
end;
function TRemDlgElement.EntryID: string;
begin
Result := REMEntryCode + FReminder.GetIEN + '/' + IntToStr(integer(Self));
end;
procedure TRemDlgElement.FieldPanelChange(Sender: TObject);
var
idx: integer;
Entry: TTemplateDialogEntry;
fval: string;
begin
FReminder.BeginTextChanged;
try
Entry := TTemplateDialogEntry(Sender);
idx := FFieldValues.IndexOfPiece(Entry.InternalID);
fval := Entry.InternalID + U + Entry.FieldValues;
if (idx < 0) then
FFieldValues.Add(fval)
else
FFieldValues[idx] := fval;
finally
FReminder.EndTextChanged(Sender);
end;
end;
procedure TRemDlgElement.GetFieldValues(FldData: TStrings);
var
i, p: integer;
TmpSL: TStringList;
begin
TmpSL := TStringList.Create;
try
for i := 0 to FFieldValues.Count - 1 do
begin
p := pos(U, FFieldValues[i]);
// Can't use Piece because 2nd piece may contain ^ characters
if (p > 0) then
begin
TmpSL.CommaText := copy(FFieldValues[i], p + 1, MaxInt);
FastAddStrings(TmpSL, FldData);
TmpSL.Clear;
end;
end;
finally
TmpSL.Free;
end;
if (Assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then
for i := 0 to FChildren.Count - 1 do
TRemDlgElement(FChildren[i]).GetFieldValues(FldData);
end;
{ cause the paint event to be called and draw a focus rectangle on the TFieldPanel }
procedure TRemDlgElement.FieldPanelEntered(Sender: TObject);
begin
with TDlgFieldPanel(Sender) do
begin
Focus := TRUE;
Invalidate;
if Parent is TDlgFieldPanel then
begin
TDlgFieldPanel(Parent).Focus := FALSE;
TDlgFieldPanel(Parent).Invalidate;
end;
end;
end;
{ cause the paint event to be called and draw the TFieldPanel without the focus rect. }
procedure TRemDlgElement.FieldPanelExited(Sender: TObject);
begin
with TDlgFieldPanel(Sender) do
begin
Focus := FALSE;
Invalidate;
if Parent is TDlgFieldPanel then
begin
TDlgFieldPanel(Parent).Focus := TRUE;
TDlgFieldPanel(Parent).Invalidate;
end;
end;
end;
{ Check the associated checkbox when spacebar is pressed }
procedure TRemDlgElement.FieldPanelKeyPress(Sender: TObject; var Key: Char);
begin
if Key = ' ' then
begin
FieldPanelOnClick(Sender);
Key := #0;
end;
end;
{ So the FieldPanel will check the associated checkbox }
procedure TRemDlgElement.FieldPanelOnClick(Sender: TObject);
begin
// if TFieldPanel(Sender).Focus then
TORCheckBox(TDlgFieldPanel(Sender).Tag).Checked := not FChecked;
end;
{ call the FieldPanelOnClick so labels on the panels will also click the checkbox }
procedure TRemDlgElement.FieldPanelLabelOnClick(Sender: TObject);
begin
FieldPanelOnClick(TLabel(Sender).Parent);
{ use the parent/fieldpanel as the Sender }
end;
{ TRemData }
function TRemData.Add2PN: boolean;
begin
Result := (Piece(FRec3, U, 5) <> '1');
end;
function TRemData.AddData(List: TStrings; Finishing: boolean): integer;
var
i, j, k: integer;
PCECat: TPCEDataCat;
Primary: boolean;
ActDt, InActDt: Double;
encDt: TFMDateTime;
procedure AddPrompt(Prompt: TRemPrompt; dt: TRemDataType; var X: string);
var
pt: TRemPromptType;
PNum: integer;
Pdt: TRemDataType;
v: TVitalType;
rte, unt, txt, tmp: string;
UIEN: Int64;
begin
PNum := -1;
pt := Prompt.PromptType;
if (pt = ptSubComment) or (pt = ptUnknown) or (((pt = ptView) or (pt = ptPrint)) and (Piece(prompt.FRec4, U, 12) <> 'V')) then
exit;
if (pt = ptMST) then
begin
if (PCECat in MSTDataTypes) then
begin
UIEN := FParent.FReminder.PCEDataObj.Providers.PCEProvider;
if UIEN <= 0 then
UIEN := User.DUZ;
SetPiece(X, U, pnumMST, Prompt.GetValue + ';' + // MST Code
FloatToStr(RemForm.PCEObj.VisitDateTime) + ';' + IntToStr(UIEN)
+ ';' + //
Prompt.FMiscText); // IEN of Exam, if any
end;
end
else if (PCECat = pdcVital) then
begin
if (pt = ptVitalEntry) then
begin
rte := Prompt.VitalValue;
if (rte <> '') then
begin
v := Prompt.VitalType;
unt := Prompt.VitalUnitValue;
ConvertVital(v, rte, unt);
// txt := U + VitalCodes[v] + U + rte + U + FloatToStr(RemForm.PCEObj.VisitDateTime); AGP Change 26.1 commented out
txt := U + VitalCodes[v] + U + rte + U + '0';
// AGP Change 26.1 Use for Vital date/time
if (not Finishing) then
txt := Char(ord('A') + ord(v)) + FormatVitalForNote(txt);
// Add vital sort char
List.AddObject(Char(ord('A') + ord(PCECat)) + txt, Self);
end;
end
else
exit;
end
else if (PCECat = pdcMH) then
begin
if (pt = ptMHTest) or (pt = ptGAF) then
X := X + U + Prompt.GetValue
else
exit;
end
else if (pt <> ptDataList) and (ord(pt) >= ord(low(TRemPromptType))) then
begin
Pdt := RemPromptTypes[pt];
if (Pdt = dt) or (Pdt = dtAll) or (Pdt = dtGenFindings) or
((Pdt = dtHistorical) and Assigned(Prompt.FParent) and
Prompt.FParent.Historical) then
PNum := FinishPromptPieceNum[pt];
if (PNum > 0) then
begin
if (pt = ptPrimaryDiag) then
begin
SetPiece(X, U, PNum, BOOLCHAR[Primary]);
// SetPiece(x, U, 13, BoolChar[Primary]);
end
else if (pt = ptDate) or (pt = ptDateTime) then
begin
tmp := Prompt.GetValue;
if (tmp = '0') then
tmp := '';
SetPiece(X, U, PNum, tmp);
end
else
begin
SetPiece(X, U, PNum, Prompt.GetValue);
// SetPiece(x, U, 13, Prompt.GetValue);
end;
end;
end;
end;
procedure Add(Str: string; Root: TRemPCERoot);
var
i, Qty: integer;
Value, IsGAF, txt, X, Code, Nar, Cat,
GenFindID, GenFindNewData, GenFindDataGroup, GenFindPrinter: string;
Skip: boolean;
Prompt: TRemPrompt;
dt: TRemDataType;
TestDate: TFMDateTime;
i1, i2: integer;
begin
X := '';
dt := Code2DataType(Piece(Str, U, r3Type));
PCECat := RemData2PCECat[dt];
Code := Piece(Str, U, r3Code);
if (Code = '') then
Code := Piece(Str, U, r3Code2);
Nar := Piece(Str, U, r3Nar);
Cat := Piece(Str, U, r3Cat);
GenFindID := Piece(Str, U, r3GenFindID);
GenFindNewData := Piece(Str, U, r3GenFindNewData);
GenFindDataGroup := Piece(Str, U, r3GenFindDataGroup);
GenFindPrinter := Piece(Str, U, r3GenFindPrinter);
Primary := FALSE;
if (Assigned(FParent) and Assigned(FParent.FPrompts) and (PCECat = pdcDiag))
then
begin
if (FParent.Historical) then
begin
for i := 0 to FParent.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FParent.FPrompts[i]);
if (Prompt.PromptType = ptPrimaryDiag) then
begin
Primary := (Prompt.GetValue = BOOLCHAR[TRUE]);
break;
end;
end;
end
else
Primary := (Root = PrimaryDiagRoot);
end;
Skip := FALSE;
if (PCECat = pdcMH) then
begin
IsGAF := Piece(FRec3, U, r3GAF);
Value := FChoicePrompt.GetValue;
if (Value = '') or ((IsGAF = '1') and (Value = '0')) then
Skip := TRUE;
end;
if Finishing or (PCECat = pdcVital) then
begin
if (dt = dtOrder) then
X := U + Piece(Str, U, 6) + U + Piece(Str, U, 11) + U + Nar
else
begin
if (PCECat = pdcMH) then
begin
if (Skip) then
X := ''
else
begin
TestDate := Trunc(FParent.FReminder.PCEDataObj.VisitDateTime);
if (IsGAF = '1') then
ValidateGAFDate(TestDate);
X := U + Nar + U + IsGAF + U + FloatToStr(TestDate) + U +
IntToStr(FParent.FReminder.PCEDataObj.Providers.PCEProvider);
end;
end
else if (PCECat <> pdcVital) then
begin
X := Piece(Str, U, 6);
SetPiece(X, U, pnumCode, Code);
SetPiece(X, U, pnumCategory, Cat);
SetPiece(X, U, pnumNarrative, Nar);
SetPiece(X, U, pnumRemGenFindID, GenFindID);
SetPiece(X, U, pnumRemGenFindNewData, GenFindNewData);
SetPiece(X, U, pnumRemGenFindGroup, GenFindDataGroup);
setPiece(X, U, pnumGFPrint, GenFindPrinter);
end;
if (Assigned(FParent)) then
begin
if (Assigned(FParent.FPrompts)) then
begin
for i := 0 to FParent.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FParent.FPrompts[i]);
if (not Prompt.FIsShared) then
AddPrompt(Prompt, dt, X);
end;
end;
if (Assigned(FParent.FParent) and FParent.FParent.FHasSharedPrompts)
then
begin
for i := 0 to FParent.FParent.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FParent.FParent.FPrompts[i]);
if (Prompt.FIsShared) and
(Prompt.FSharedChildren.IndexOf(FParent) >= 0) then
AddPrompt(Prompt, dt, X);
end;
end;
end;
end;
if (X <> '') then
List.AddObject(Char(ord('A') + ord(PCECat)) + X, Self);
end
else
begin
Qty := 1;
if (Assigned(FParent) and Assigned(FParent.FPrompts)) then
begin
if (PCECat = pdcProc) then
begin
for i := 0 to FParent.FPrompts.Count - 1 do
begin
Prompt := TRemPrompt(FParent.FPrompts[i]);
if (Prompt.PromptType = ptQuantity) then
begin
Qty := StrToIntDef(Prompt.GetValue, 1);
if (Qty < 1) then
Qty := 1;
break;
end;
end;
end;
end;
if (not Skip) then
begin
txt := Char(ord('A') + ord(PCECat)) + GetPCEDataText(PCECat, Code, Cat,
Nar, Primary, Qty);
if (Assigned(FParent) and FParent.Historical) then
txt := txt + ' (Historical)';
List.AddObject(txt, Self);
inc(Result);
end;
if Assigned(FParent) and Assigned(FParent.FMSTPrompt) then
begin
txt := FParent.FMSTPrompt.Value;
if txt <> '' then
begin
if FParent.FMSTPrompt.FMiscText = '' then
begin
i1 := 0;
i2 := 2;
end
else
begin
i1 := 3;
i2 := 4;
end;
for i := i1 to i2 do
if txt = MSTDescTxt[i, 1] then
begin
List.AddObject(Char(ord('A') + ord(pdcMST)) + MSTDescTxt[i,
0], Self);
break;
end;
end;
end;
end;
end;
begin
Result := 0;
if (Assigned(FChoicePrompt)) and (Assigned(FChoices)) then
begin
If not Assigned(FChoicesActiveDates) then
begin
for i := 0 to FChoices.Count - 1 do
begin
if (copy(FChoicePrompt.GetValue, i + 1, 1) = '1') then
Add(FChoices[i], TRemPCERoot(FChoices.Objects[i]))
end
end
else { if there are active dates for each choice then check them }
begin
If Self.FParent.Historical then
encDt := DateTimeToFMDateTime(Date)
else
encDt := RemForm.PCEObj.VisitDateTime;
k := 0;
for i := 0 to FChoices.Count - 1 do
begin
for j := 0 to (TStringList(Self.FChoicesActiveDates[i]).Count - 1) do
begin
ActDt := StrToIntDef
((Piece(TStringList(Self.FChoicesActiveDates[i]).Strings[j],
':', 1)), 0);
InActDt := StrToIntDef
((Piece(TStringList(Self.FChoicesActiveDates[i]).Strings[j], ':', 2)
), 9999999);
if (encDt >= ActDt) and (encDt <= InActDt) then
begin
if (copy(FChoicePrompt.GetValue, k + 1, 1) = '1') then
Add(FChoices[i], TRemPCERoot(FChoices.Objects[i]));
inc(k);
end; { Active date check }
end; { FChoicesActiveDates.Items[i] loop }
end; { FChoices loop }
end { FChoicesActiveDates check }
end { FChoicePrompt and FChoices check }
else
Add(FRec3, FPCERoot);
{ Active dates for this are checked in TRemDlgElement.AddData }
end;
function TRemData.Category: string;
begin
Result := Piece(FRec3, U, r3Cat);
end;
function TRemData.DataType: TRemDataType;
begin
Result := Code2DataType(Piece(FRec3, U, r3Type));
end;
destructor TRemData.Destroy;
var
i: integer;
begin
if (Assigned(FPCERoot)) then
FPCERoot.Done(Self);
if (Assigned(FChoices)) then
begin
for i := 0 to FChoices.Count - 1 do
begin
if (Assigned(FChoices.Objects[i])) then
TRemPCERoot(FChoices.Objects[i]).Done(Self);
end;
end;
KillObj(@FChoices);
inherited;
end;
function TRemData.DisplayWHResults: boolean;
begin
Result := FALSE;
if FRec3 <> '' then
Result := (Piece(FRec3, U, 6) <> '0');
end;
function TRemData.ExternalValue: string;
begin
Result := Piece(FRec3, U, r3Code);
end;
function TRemData.InternalValue: string;
begin
Result := Piece(FRec3, U, 6);
end;
function TRemData.Narrative: string;
begin
Result := Piece(FRec3, U, r3Nar);
end;
{ TRemPrompt }
function TRemPrompt.Add2PN: boolean;
begin
Result := FALSE;
if (not Forced) and (PromptOK) then
// if PromptOK then
Result := (Piece(FRec4, U, 5) <> '1');
if (Result = FALSE) and (Piece(FRec4, U, 4) = 'WH_NOT_PURP') then
Result := TRUE;
end;
function TRemPrompt.Caption: string;
begin
Result := Piece(FRec4, U, 8);
if (not FCaptionAssigned) then
begin
AssignFieldIDs(Result);
SetPiece(FRec4, U, 8, Result);
FCaptionAssigned := TRUE;
end;
end;
constructor TRemPrompt.Create;
begin
FOverrideType := ptUnknown;
end;
function TRemPrompt.Forced: boolean;
begin
Result := (Piece(FRec4, U, 7) = 'F');
end;
function TRemPrompt.InternalValue: string;
var
M, d, Y: Word;
Code, valid: string;
begin
Result := Piece(FRec4, U, 6);
Code := Piece(FRec4, U, 4);
valid := Piece(FRec4, U, 15);
if (Code = RemPromptCodes[ptVisitDate])
then
begin
if (copy(Result, 1, 1) = MonthReqCode) then
begin
FMonthReq := TRUE;
delete(Result, 1, 1);
end;
if (Result = '') then
begin
DecodeDate(Now, Y, M, d);
Result := IntToStr(Y - 1700) + '0000';
SetPiece(FRec4, U, 6, Result);
end;
end;
if (Code = RemPromptCodes[ptDate]) or (Code = RemPromptCodes[ptDateTime]) then
begin
if (copy(Result, 1, 1) = EncDateCode) then
begin
Result := EncDateCode;
SetPiece(FRec4, U, 6, Result);
end;
if valid = HistCode then validate := HistCode
else if valid = FutureCode then validate := FutureCode
else validate := AnyDateCode;
end;
end;
procedure TRemPrompt.PromptChange(Sender: TObject);
var
cbo: TORComboBox;
pt: TRemPromptType;
device, TmpValue, OrgValue: string;
idx, I: integer;
NeedRedraw, elementNeedRedraw: boolean;
dte: TFMDateTime;
whCKB: TWHCheckBox;
// printoption: TORCheckBox;
WHValue, WHValue1, itemId, linkItem, linkSeq, linkType, promptValue: String;
elementList, promptList: TStringList;
begin
if pxrmworking then
exit;
try
FParent.FReminder.BeginTextChanged;
try
FFromControl := TRUE;
try
TmpValue := GetValue;
OrgValue := TmpValue;
pt := PromptType;
NeedRedraw := FALSE;
elementNeedRedraw := FALSE;
case pt of
ptComment, ptQuantity:
TmpValue := (Sender as TEdit).Text;
ptVisitDate, ptDate, ptDateTime:
begin
if pt = ptVisitDate then dte := (Sender as TORDateCombo).FMDate
else dte := (Sender as TORDateBox).FMDateTime;
if (pt = ptVisitDate) then
begin
while (dte > 2000000) and (dte > FMToday) do
begin
dte := dte - 10000;
NeedRedraw := TRUE;
end;
end;
TmpValue := FloatToStr(dte);
if (TmpValue = '1000000') then
begin
if (pt = ptVisitDate) then
TmpValue := '0'
else
TmpValue := '';
end;
end;
ptPrimaryDiag, ptAdd2PL, ptContraindicated:
begin
TmpValue := BOOLCHAR[(Sender as TORCheckBox).Checked];
NeedRedraw := (pt = ptPrimaryDiag);
end;
ptVisitLocation:
begin
cbo := (Sender as TORComboBox);
if (cbo.ItemIEN < 0) then
NeedRedraw := (not cbo.DroppedDown)
else
begin
if (cbo.ItemIndex <= 0) then
cbo.Items[0] := '0' + U + cbo.Text;
TmpValue := cbo.itemId;
if (StrToIntDef(TmpValue, 0) = 0) then
TmpValue := cbo.Text;
end;
end;
ptWHPapResult:
begin
if (Sender is TWHCheckBox) then
begin
whCKB := (Sender as TWHCheckBox);
if whCKB.Checked = TRUE then
begin
if whCKB.Caption = 'NEM (No Evidence of Malignancy)' then
FParent.WHResultChk := 'N';
if whCKB.Caption = 'Abnormal' then
FParent.WHResultChk := 'A';
if whCKB.Caption = 'Unsatisfactory for Diagnosis' then
FParent.WHResultChk := 'U';
// AGP Change 23.13 WH multiple processing
for i := 0 to FParent.FData.Count - 1 do
begin
if Piece(TRemData(FParent.FData[i]).FRec3, U, 4) = 'WHR' then
begin
FParent.FReminder.WHReviewIEN :=
Piece(TRemData(FParent.FData[i]).FRec3, U, 6)
end;
end;
end
else
begin
FParent.WHResultChk := '';
FParent.FReminder.WHReviewIEN := ''; // AGP CHANGE 23.13
end;
end;
end;
ptWHNotPurp:
begin
if (Sender is TWHCheckBox) then
begin
whCKB := (Sender as TWHCheckBox);
if whCKB.Checked = TRUE then
begin
if whCKB.Caption = 'Letter' then
begin
if FParent.WHResultNot = '' then
FParent.WHResultNot := 'L'
else if pos('L', FParent.WHResultNot) = 0 then
FParent.WHResultNot := FParent.WHResultNot + ':L';
if whCKB.FButton <> nil then
whCKB.FButton.Enabled := TRUE;
if whCKB.FPrintNow <> nil then
begin
whCKB.FPrintVis := '1';
whCKB.FPrintNow.Enabled := TRUE;
end;
end;
if whCKB.Caption = 'In-Person' then
begin
if FParent.WHResultNot = '' then
FParent.WHResultNot := 'I'
else if pos('I', FParent.WHResultNot) = 0 then
FParent.WHResultNot := FParent.WHResultNot + ':I';
end;
if whCKB.Caption = 'Phone Call' then
begin
if FParent.WHResultNot = '' then
FParent.WHResultNot := 'P'
else if pos('P', FParent.WHResultNot) = 0 then
FParent.WHResultNot := FParent.WHResultNot + ':P';
end;
end
else
begin
// this section is to handle unchecking of boxes and disabling print now and view button
WHValue := FParent.WHResultNot;
if whCKB.Caption = 'Letter' then
begin
for i := 1 to length(WHValue) do
begin
if WHValue1 = '' then
begin
if (WHValue[i] <> 'L') and (WHValue[i] <> ':') then
WHValue1 := WHValue[i];
end
else if (WHValue[i] <> 'L') and (WHValue[i] <> ':') then
WHValue1 := WHValue1 + ':' + WHValue[i];
end;
if (whCKB.FButton <> nil) and (whCKB.FButton.Enabled = TRUE)
then
whCKB.FButton.Enabled := FALSE;
if (whCKB.FPrintNow <> nil) and
(whCKB.FPrintNow.Enabled = TRUE) then
begin
whCKB.FPrintVis := '0';
if whCKB.FPrintNow.Checked = TRUE then
whCKB.FPrintNow.Checked := FALSE;
whCKB.FPrintNow.Enabled := FALSE;
FParent.WHPrintDevice := '';
end;
end;
if whCKB.Caption = 'In-Person' then
begin
for i := 1 to length(WHValue) do
begin
if WHValue1 = '' then
begin
if (WHValue[i] <> 'I') and (WHValue[i] <> ':') then
WHValue1 := WHValue[i];
end
else if (WHValue[i] <> 'I') and (WHValue[i] <> ':') then
WHValue1 := WHValue1 + ':' + WHValue[i];
end;
end;
if whCKB.Caption = 'Phone Call' then
begin
for i := 1 to length(WHValue) do
begin
if WHValue1 = '' then
begin
if (WHValue[i] <> 'P') and (WHValue[i] <> ':') then
WHValue1 := WHValue[i];
end
else if (WHValue[i] <> 'P') and (WHValue[i] <> ':') then
WHValue1 := WHValue1 + ':' + WHValue[i];
end;
end;
FParent.WHResultNot := WHValue1;
end;
end
else if ((Sender as TORCheckBox) <> nil) and
(Piece(FRec4, U, 12) = '1') then
begin
if (((Sender as TORCheckBox).Caption = 'Print Now') and
((Sender as TORCheckBox).Enabled = TRUE)) and
((Sender as TORCheckBox).Checked = TRUE) and
(FParent.WHPrintDevice = '') then
begin
FParent.WHPrintDevice := SelectDevice(Self, Encounter.Location,
FALSE, 'Women Health Print Device Selection');
FPrintNow := '1';
if FParent.WHPrintDevice = '' then
begin
FPrintNow := '0';
(Sender as TORCheckBox).Checked := FALSE;
end;
end;
if (((Sender as TORCheckBox).Caption = 'Print Now') and
((Sender as TORCheckBox).Enabled = TRUE)) and
((Sender as TORCheckBox).Checked = FALSE) then
begin
FParent.WHPrintDevice := '';
FPrintNow := '0';
end;
end;
end;
ptPrint:
begin
if Piece(FRec4, U, 12) = 'V' then
begin
device := SelectDevice(Self, Encounter.Location, FALSE, 'Print Device Selection');
tmpValue := Piece(device, U, 1);
// if device <> '' then FValue := device
// else FValue := '';
end;
end;
ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction,
ptLevelUnderstanding, ptSkinReading: // (AGP Change 26.1)
TmpValue := (Sender as TORComboBox).itemId;
else
if pt = ptVitalEntry then
begin
case (Sender as TControl).Tag of
TAG_VITTEMPUNIT, TAG_VITHTUNIT, TAG_VITWTUNIT:
idx := 2;
TAG_VITPAIN:
begin
idx := -1;
TmpValue := (Sender as TORComboBox).itemId;
if FParent.VitalDateTime = 0 then
FParent.VitalDateTime := FMNow;
end;
else
idx := 1;
end;
if (idx > 0) then
begin
// AGP Change 26.1 change Vital time/date to Now instead of encounter date/time
SetPiece(TmpValue, ';', idx, TORExposedControl(Sender).Text);
if (FParent.VitalDateTime > 0) and
(TORExposedControl(Sender).Text = '') then
FParent.VitalDateTime := 0;
if (FParent.VitalDateTime = 0) and
(TORExposedControl(Sender).Text <> '') then
FParent.VitalDateTime := FMNow;
end;
end
else if pt = ptDataList then
begin
TmpValue := (Sender as TORComboBox).CheckedString;
NeedRedraw := TRUE;
end
else if (pt = ptGAF) and (MHDLLFound = FALSE) then
TmpValue := (Sender as TEdit).Text;
end;
if (TmpValue <> OrgValue) then
begin
if NeedRedraw then
FParent.FReminder.BeginNeedRedraw;
try
elementNeedRedraw := FALSE;
itemId := Piece(Self.FRec4, U, 2);
linkItem := Piece(Self.FRec4, U, 13);
linkType := Piece(Self.FRec4, U, 14);
linkSeq := Piece(self.FRec4, U, 28);
elementList := TStringList.Create;
promptList := TStringList.Create;
SetValue(TmpValue);
//check to not call VistA if user is in the middle of changing a date.
if ((pt = ptDate) or (pt = ptDateTime)) and (TmpValue = '-1') then exit;
if (linkItem = '') or (linkType = '') then exit;
promptValue := getLinkPromptValue(TmpValue, itemId, OrgValue, patient.dfn);
if linkType = 'ELEMENT' then
begin
if promptValue <> '' then
begin
elementNeedRedraw := TRUE;
elementList.Add(linkItem + U + promptValue + U + U + linkseq);
end;
end
else
begin
if promptValue = 'REQUIRED' then
begin
promptList.Add(linkItem + U + linkType + U + 'REQUIRED' + U + U + linkseq);
elementNeedRedraw := TRUE;
end
else if promptValue <> '' then
begin
promptList.Add(linkItem + U + linkType + U + 'VALUE' + U +
promptValue + U + linkseq);
elementNeedRedraw := TRUE;
end;
end;
finally
if NeedRedraw then
FParent.FReminder.EndNeedRedraw(Self);
end;
end
else if NeedRedraw then
begin
FParent.FReminder.BeginNeedRedraw;
FParent.FReminder.EndNeedRedraw(Self);
end;
finally
FFromControl := FALSE;
end;
finally
FParent.FReminder.EndTextChanged(Sender);
end;
if (FParent.ElemType = etDisplayOnly) and (not Assigned(FParent.FParent)) then
RemindersInProcess.Notifier.Notify;
if elementNeedRedraw then
try
if FParent.buildLinkSeq(linkSeq, self.FParent.FID, Piece(self.FParent.FRec1, u, 3)) then
FParent.FReminder.findLinkItem(elementList, promptList, Piece(self.FParent.FRec1, u, 3));
finally
if elementList <> nil then FreeAndNil(elementList);
if promptList <> nil then FreeAndNil(promptList);
end;
finally
pxrmDoneWorking;
end;
end;
procedure TRemPrompt.ComboBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and (Sender is TORComboBox) and
((Sender as TORComboBox).DroppedDown) then
(Sender as TORComboBox).DroppedDown := FALSE;
end;
function TRemPrompt.PromptOK: boolean;
var
pt: TRemPromptType;
dt: TRemDataType;
C, i: integer;
encDate: TFMDateTime;
begin
pt := PromptType;
if (pt = ptUnknown) or (pt = ptMST) then
Result := FALSE
else if (pt = ptDataList) or (pt = ptVitalEntry) or (pt = ptMHTest) or
(pt = ptGAF) or (pt = ptWHPapResult) then
Result := TRUE
else if (pt = ptSubComment) then
Result := FParent.FHasComment
else
begin
dt := RemPromptTypes[PromptType];
if (dt = dtAll) then
Result := TRUE
else if (dt = dtUnknown) then
Result := FALSE
else if (dt = dtHistorical) then
Result := FParent.Historical
// hanlde combo box prompts that are not assocaite with codes
else if (dt <> dtProcedure) and (dt <> dtDiagnosis) then
begin
Result := FALSE;
if (Assigned(FParent.FData)) then
begin
for i := 0 to FParent.FData.Count - 1 do
begin
if (TRemData(FParent.FData[i]).DataType = dt) then
begin
Result := TRUE;
break;
end;
end;
end;
end
else
// agp ICD10 change to screen out prompts if taxonomy does not contain active codes for the encounter date.
// historical values override the date check.
begin
Result := FALSE;
if (Assigned(FParent.FData)) then
begin
for i := 0 to FParent.FData.Count - 1 do
begin
if (TRemData(FParent.FData[i]).DataType = dt) then
begin
if (FParent.Historical) then
begin
Result := TRUE;
break;
end
else if (TRemData(FParent.FData[i]).FActiveDates <> nil) then
begin
encDate := TRemData(FParent.FData[i])
.FParent.FReminder.FPCEDataObj.DateTime;
if (RemDataActive(TRemData(FParent.FData[i]), encDate) = TRUE)
then
Result := TRUE;
break;
end
// else if (Assigned(TRemData(FParent.FData[i]).FChoices) and (TRemData(FParent.FData[i]).FChoices <> nil)) then
else if Assigned(TRemData(FParent.FData[i]).FChoices) then
begin
encDate := TRemData(FParent.FData[i])
.FParent.FReminder.FPCEDataObj.DateTime;
for C := 0 to TRemData(FParent.FData[i]).FChoices.Count - 1 do
begin
if (CompareActiveDate(TStringList(TRemData(FParent.FData[i])
.FChoicesActiveDates[C]), encDate) = TRUE) then
begin
Result := TRUE;
break;
end;
end;
end;
// Result := TRUE;
// break;
end;
end;
end;
end;
end;
end;
function TRemPrompt.PromptType: TRemPromptType;
begin
if (Assigned(FData)) then
Result := FOverrideType
else
Result := Code2PromptType(Piece(FRec4, U, 4));
end;
function TRemPrompt.Required: boolean;
var
pt: TRemPromptType;
begin
pt := PromptType;
if (pt = ptVisitDate) then
Result := TRUE
else if (pt = ptSubComment) then
Result := FALSE
else
Result := (Piece(FRec4, U, 10) = '1');
end;
function TRemPrompt.SameLine: boolean;
begin
Result := (Piece(FRec4, U, 9) <> '1');
end;
function TRemPrompt.NoteText: string;
var
pt: TRemPromptType;
dateStr, fmt, tmp, WHValue: string;
Cnt, i, j, k: integer;
ActDt, InActDt: Double;
encDt: TFMDateTime;
begin
Result := '';
if Add2PN then
begin
pt := PromptType;
tmp := GetValue;
case pt of
ptComment:
Result := tmp;
ptQuantity:
if (StrToIntDef(tmp, 1) <> 1) then
Result := tmp;
(* ptSkinReading: if(StrToIntDef(tmp,0) <> 0) then
Result := tmp; *)
ptSkinReading: // (AGP Change 26.1)
begin
Result := tmp;
end;
ptVisitDate, ptDate:
begin
try
if (tmp <> '') and (tmp <> '0') and (length(tmp) = 7) then
begin
dateStr := '';
if FMonthReq and (copy(tmp, 4, 2) = '00') then
Result := ''
else
begin
if (copy(tmp, 4, 4) = '0000') then
begin
fmt := 'YYYY';
dateStr := ' – Exact date is unknown';
end
else if (copy(tmp, 6, 2) = '00') then
begin
fmt := 'MMMM, YYYY';
dateStr := ' – Exact date is unknown';
end
else
fmt := 'MMMM D, YYYY';
if dateStr = '' then
Result := FormatFMDateTimeStr(fmt, tmp)
else
Result := FormatFMDateTimeStr(fmt, tmp) + ' ' + dateStr;
end;
end;
except
on EConvertError do
Result := tmp
else
raise;
end;
end;
ptDateTime:
begin
try
fmt := 'MMMM D, YYYY@HH:NN';
if dateStr = '' then
Result := FormatFMDateTimeStr(fmt, tmp)
else
Result := FormatFMDateTimeStr(fmt, tmp) + ' ' + dateStr;
except
on EConvertError do
Result := tmp
else
raise;
end;
end;
ptPrimaryDiag, ptAdd2PL, ptContraindicated:
if (tmp = '1') then
Result := ' ';
ptVisitLocation:
if (StrToIntDef(tmp, 0) = 0) then
begin
if (tmp <> '0') then
Result := tmp;
end
else
begin
Result := GetPCEDisplayText(tmp, ComboPromptTags[pt]);
end;
ptWHPapResult:
begin
if FParent.WHResultChk = 'N' then
Result := 'NEM (No Evidence of Malignancy)';
if FParent.WHResultChk = 'A' then
Result := 'Abnormal';
if FParent.WHResultChk = 'U' then
Result := 'Unsatisfactory for Diagnosis';
if FParent.WHResultChk = '' then
Result := '';
end;
ptWHNotPurp:
begin
if FParent.WHResultNot <> '' then
begin
WHValue := FParent.WHResultNot;
// IF Forced = false then
// begin
if WHValue <> 'CPRS' then
begin
for Cnt := 1 to length(WHValue) do
begin
if Result = '' then
begin
if WHValue[Cnt] = 'L' then
Result := 'Letter';
if WHValue[Cnt] = 'I' then
Result := 'In-Person';
if WHValue[Cnt] = 'P' then
Result := 'Phone Call';
end
else
begin
if (WHValue[Cnt] = 'L') and (pos('Letter', Result) = 0) then
Result := Result + '; Letter';
if (WHValue[Cnt] = 'I') and (pos('In-Person', Result) = 0)
then
Result := Result + '; In-Person';
if (WHValue[Cnt] = 'P') and (pos('Phone Call', Result) = 0)
then
Result := Result + '; Phone Call';
end;
end;
end;
end
else if Forced = TRUE then
begin
if pos(':', Piece(FRec4, U, 6)) = 0 then
begin
if Piece(FRec4, U, 6) = 'L' then
begin
Result := 'Letter';
FParent.WHResultNot := 'L';
end;
if Piece(FRec4, U, 6) = 'I' then
begin
Result := 'In-Person';
FParent.WHResultNot := 'I';
end;
if Piece(FRec4, U, 6) = 'P' then
begin
Result := 'Phone Call';
FParent.WHResultNot := 'P';
end;
if Piece(FRec4, U, 6) = 'CPRS' then
begin
Result := '';
FParent.WHResultNot := 'CPRS';
end;
end
else
begin
WHValue := Piece(FRec4, U, 6);
for Cnt := 0 to length(WHValue) do
begin
if Result = '' then
begin
if WHValue[Cnt] = 'L' then
begin
Result := 'Letter';
FParent.WHResultNot := WHValue[Cnt];
end;
if WHValue[Cnt] = 'I' then
begin
Result := 'In-Person';
FParent.WHResultNot := WHValue[Cnt];
end;
if WHValue[Cnt] = 'P' then
begin
Result := 'Phone Call';
FParent.WHResultNot := WHValue[Cnt];
end;
end
else
begin
if (WHValue[Cnt] = 'L') and (pos('Letter', Result) = 0) then
begin
Result := Result + '; Letter';
FParent.WHResultNot := FParent.WHResultNot + ':' +
WHValue[Cnt];
end;
if (WHValue[Cnt] = 'I') and (pos('In-Person', Result) = 0)
then
begin
Result := Result + '; In-Person';
FParent.WHResultNot := FParent.WHResultNot + ':' +
WHValue[Cnt];
end;
if (WHValue[Cnt] = 'P') and (pos('Phone Call', Result) = 0)
then
begin
Result := Result + '; Phone Call';
FParent.WHResultNot := FParent.WHResultNot + ':' +
WHValue[Cnt];
end;
end;
end;
end;
end
else
Result := '';
end;
ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction,
ptLevelUnderstanding:
begin
Result := tmp;
if (Piece(Result, U, 1) = '@') then
Result := ''
else
Result := GetPCEDisplayText(tmp, ComboPromptTags[pt]);
end;
else
begin
if pt = ptDataList then
begin
if (Assigned(FData) and Assigned(FData.FChoices)) then
begin
if not(Assigned(FData.FChoicesActiveDates)) then
for i := 0 to FData.FChoices.Count - 1 do
begin
if (copy(tmp, i + 1, 1) = '1') then
begin
if (Result <> '') then
Result := Result + ', ';
Result := Result + Piece(FData.FChoices[i], U, 12);
end;
end
else { if there are active dates for each choice then check them }
begin
if Self.FParent.Historical then
encDt := DateTimeToFMDateTime(Date)
else
encDt := RemForm.PCEObj.VisitDateTime;
k := 0;
for i := 0 to FData.FChoices.Count - 1 do
begin
for j := 0 to (TStringList(FData.FChoicesActiveDates[i])
.Count - 1) do
begin
ActDt := StrToIntDef
((Piece(TStringList(FData.FChoicesActiveDates[i])
.Strings[j], ':', 1)), 0);
InActDt :=
StrToIntDef
((Piece(TStringList(FData.FChoicesActiveDates[i])
.Strings[j], ':', 2)), 9999999);
if (encDt >= ActDt) and (encDt <= InActDt) then
begin
if (copy(tmp, k + 1, 1) = '1') then
begin
if (Result <> '') then
Result := Result + ', ';
Result := Result + Piece(FData.FChoices[i], U, 12);
end;
inc(k);
end; { ActiveDate check }
end; { FChoicesActiveDates.Items[i] loop }
end; { FChoices loop }
end;
end;
end
else if pt = ptVitalEntry then
begin
Result := VitalValue;
if (Result <> '') then
Result := ConvertVitalData(Result, VitalType, VitalUnitValue);
end
else if pt = ptMHTest then
Result := FMiscText
else if (pt = ptGAF) and (MHDLLFound = FALSE) then
begin
if (StrToIntDef(Piece(tmp, U, 1), 0) <> 0) then
begin
Result := tmp;
end
end
else if pt = ptMHTest then
Result := FMiscText;
(*
GafDate := Trunc(FParent.FReminder.PCEDataObj.VisitDateTime);
ValidateGAFDate(GafDate);
Result := tmp + CRCode + 'Date Determined: ' + FormatFMDateTime('mm/dd/yyyy', GafDate) +
CRCode + 'Determined By: ' + FParent.FReminder.PCEDataObj.Providers.PCEProviderName;
*)
// end;
end;
end;
end;
if (Result <> '') and (Caption <> '') then
Result := Trim(Caption + ' ' + Trim(Result));
// end;
end;
function TRemPrompt.CanShare(Prompt: TRemPrompt): boolean;
var
pt: TRemPromptType;
begin
if (Forced or Prompt.Forced or Prompt.FIsShared or Required or Prompt.Required)
then
Result := FALSE
else
begin
pt := PromptType;
Result := (pt = Prompt.PromptType);
if (Result) then
begin
if (pt in [ptAdd2PL, ptLevelUnderstanding]) or
((pt = ptComment) and (not FParent.FHasSubComments)) then
Result := ((Add2PN = Prompt.Add2PN) and (Caption = Prompt.Caption))
else
Result := FALSE;
end;
end;
end;
destructor TRemPrompt.Destroy;
begin
KillObj(@FSharedChildren);
inherited;
end;
function TRemPrompt.RemDataActive(RData: TRemData; encDt: TFMDateTime): boolean;
// var
// ActDt, InActDt: Double;
// j: integer;
begin
// Result := FALSE;
if Assigned(RData.FActiveDates) then
Result := CompareActiveDate(RData.FActiveDates, encDt)
// agp ICD-10 move code to it own function to reuse the comparison in other parts of dialogs
// for j := 0 to (RData.FActiveDates.Count - 1) do
// begin
// ActDt := StrToIntDef(Piece(RData.FActiveDates[j],':',1), 0);
// InActDt := StrToIntDef(Piece(RData.FActiveDates[j], ':', 2), 9999999);
// if (EncDt >= ActDt) and (EncDt <= InActDt) then
// begin
// Result := TRUE;
// Break;
// end;
// end
else
Result := TRUE;
end;
// agp ICD-10 code was imported from RemDataActive
function TRemPrompt.CompareActiveDate(ActiveDates: TStringList;
encDt: TFMDateTime): boolean;
var
ActDt, InActDt: Double;
j: integer;
begin
Result := FALSE;
for j := 0 to (ActiveDates.Count - 1) do
begin
ActDt := StrToIntDef(Piece(ActiveDates[j], ':', 1), 0);
InActDt := StrToIntDef(Piece(ActiveDates[j], ':', 2), 9999999);
if (encDt >= ActDt) and (encDt <= InActDt) then
begin
Result := TRUE;
break;
end;
end
end;
function TRemPrompt.RemDataChoiceActive(RData: TRemData; j: integer;
encDt: TFMDateTime): boolean;
var
ActDt, InActDt: Double;
i: integer;
begin
Result := FALSE;
If not Assigned(RData.FChoicesActiveDates) then
// if no active dates were sent
Result := TRUE // from the server then don't check dates
else { if there are active dates for each choice then check them }
begin
for i := 0 to (TStringList(RData.FChoicesActiveDates[j]).Count - 1) do
begin
ActDt := StrToIntDef((Piece(TStringList(RData.FChoicesActiveDates[j])
.Strings[i], ':', 1)), 0);
InActDt := StrToIntDef
((Piece(TStringList(RData.FChoicesActiveDates[j]).Strings[i], ':', 2)
), 9999999);
if (encDt >= ActDt) and (encDt <= InActDt) then
begin
Result := TRUE;
end; { Active date check }
end; { FChoicesActiveDates.Items[i] loop }
end { FChoicesActiveDates check }
end;
procedure TRemPrompt.reportViewClosed(Sender: TObject);
begin
if assigned(self.reportView) then
begin
if assigned(FOldReportViewOnDestroy) then
FOldReportViewOnDestroy(self.reportView);
self.reportView := nil;
end;
end;
function TRemPrompt.GetValue: string;
// Returns TRemPrompt.FValue if this TRemPrompt is not a ptPrimaryDiag
// Returns 0-False or 1-True if this TRemPrompt is a ptPrimaryDiag
var
i, j, k: integer;
RData: TRemData;
OK: boolean;
encDt: TFMDateTime;
begin
OK := (Piece(FRec4, U, 4) = RemPromptCodes[ptPrimaryDiag]);
if (OK) and (Assigned(FParent)) then
OK := (not FParent.Historical);
if OK then
begin
OK := FALSE;
if (Assigned(FParent) and Assigned(FParent.FData))
then { If there's FData, see if }
begin { there's a primary diagnosis }
for i := 0 to FParent.FData.Count - 1 do { if there is return True }
begin
encDt := RemForm.PCEObj.VisitDateTime;
RData := TRemData(FParent.FData[i]);
if (RData.DataType = dtDiagnosis) then
begin
if (Assigned(RData.FPCERoot)) and (RemDataActive(RData, encDt)) then
OK := (RData.FPCERoot = PrimaryDiagRoot)
else if (Assigned(RData.FChoices)) and (Assigned(RData.FChoicePrompt))
then
begin
k := 0;
for j := 0 to RData.FChoices.Count - 1 do
begin
if RemDataChoiceActive(RData, j, encDt) then
begin
if (Assigned(RData.FChoices.Objects[j])) and
(copy(RData.FChoicePrompt.FValue, k + 1, 1) = '1') then
begin
if (TRemPCERoot(RData.FChoices.Objects[j]) = PrimaryDiagRoot)
then
begin
OK := TRUE;
break;
end;
end; // if FChoices.Objects (which is the RemPCERoot object) is assigned
inc(k);
end; // if FChoices[j] is active
end; // loop through FChoices
end; // If there are FChoices and an FChoicePrompt (i.e.: is this a ptDataList}
end;
if OK then
break;
end;
end;
Result := BOOLCHAR[OK];
end
else
Result := FValue;
end;
procedure TRemPrompt.SetValue(Value: string);
var
pt: TRemPromptType;
i, j, k: integer;
RData: TRemData;
Primary, Done: boolean;
tmp: string;
OK, NeedRefresh: boolean;
encDt: TFMDateTime;
genFindOnly: boolean;
function genFindingOnly(list: TList): boolean;
var
rData: TRemData;
i: integer;
begin
result := true;
for i := 0 to list.Count-1 do
begin
// if (list[i] is not typeof(TRemDlgElement)) then
// begin
// result := false;
// continue;
// end;
rData := TRemData(List[i]);
if (rData.DataType <> dtGenFindings) and (rData.DataType <> dtOrder) then
result := false;
exit;
end;
end;
begin
NeedRefresh := (not FFromControl);
if (Forced and (not FFromParent)) then
exit;
pt := PromptType;
if (pt in [ptVisitDate, ptDate, ptDateTime]) then
begin
if (pt = ptVisitDate) and (Value = '') then
Value := '0'
else
begin
try
if (pt = ptVisitDate) and (StrToFloat(Value) > FMToday) then
begin
Value := '0';
InfoBox('Can not enter a future date for a historical event.',
'Invalid Future Date', MB_OK + MB_ICONERROR);
end;
except
on EConvertError do
Value := '0'
else
raise;
end;
if (Value = '0') or (Value = '') then
NeedRefresh := TRUE;
end;
end;
if (GetValue <> Value) or (FFromParent) then
begin
FValue := Value;
encDt := RemForm.PCEObj.VisitDateTime;
if ((pt = ptExamResults) and Assigned(FParent) and Assigned(FParent.FData)
and (FParent.FData.Count > 0) and Assigned(FParent.FMSTPrompt)) then
begin
FParent.FMSTPrompt.SetValueFromParent(Value);
if (FParent.FMSTPrompt.FMiscText = '') then
// Assumes first finding item is MST finding
FParent.FMSTPrompt.FMiscText := TRemData(FParent.FData[0])
.InternalValue;
end;
if assigned(FParent.FData) then genFindOnly := genFindingOnly(FParent.FData)
else genFindOnly := false;
OK := (Assigned(FParent) and Assigned(FParent.FData) and
(Piece(FRec4, U, 4) = RemPromptCodes[ptPrimaryDiag]));
if (OK = FALSE) and (Value = 'New MH dll') then
OK := TRUE;
if OK then
OK := (not FParent.Historical);
if OK then
begin
Done := FALSE;
Primary := (Value = BOOLCHAR[TRUE]);
for i := 0 to FParent.FData.Count - 1 do
begin
RData := TRemData(FParent.FData[i]);
if (RData.DataType = dtDiagnosis) then
begin
if (Assigned(RData.FPCERoot)) and (RemDataActive(RData, encDt)) then
begin
if (Primary) then
begin
PrimaryDiagRoot := RData.FPCERoot;
Done := TRUE;
end
else
begin
if (PrimaryDiagRoot = RData.FPCERoot) then
begin
PrimaryDiagRoot := nil;
Done := TRUE;
end;
end;
end
else if (Assigned(RData.FChoices)) and (Assigned(RData.FChoicePrompt))
then
begin
k := 0;
for j := 0 to RData.FChoices.Count - 1 do
begin
if RemDataChoiceActive(RData, j, encDt) then
begin
if (Primary) then
begin
if (Assigned(RData.FChoices.Objects[j])) and
(copy(RData.FChoicePrompt.FValue, k + 1, 1) = '1') then
begin
PrimaryDiagRoot := TRemPCERoot(RData.FChoices.Objects[j]);
Done := TRUE;
break;
end;
end
else
begin
if (Assigned(RData.FChoices.Objects[j])) and
(PrimaryDiagRoot = TRemPCERoot(RData.FChoices.Objects[j]))
then
begin
PrimaryDiagRoot := nil;
Done := TRUE;
break;
end;
end;
inc(k);
end;
end;
end;
end;
if Done then
break;
end;
end;
if (Assigned(FParent) and Assigned(FParent.FData) and IsSyncPrompt(pt)) and (not genFindOnly) then
begin
for i := 0 to FParent.FData.Count - 1 do
begin
RData := TRemData(FParent.FData[i]);
if (Assigned(RData.FPCERoot)) and (RemDataActive(RData, encDt)) then
RData.FPCERoot.Sync(Self);
if (Assigned(RData.FChoices)) then
begin
for j := 0 to RData.FChoices.Count - 1 do
begin
if (Assigned(RData.FChoices.Objects[j])) and
RemDataChoiceActive(RData, j, encDt) then
TRemPCERoot(RData.FChoices.Objects[j]).Sync(Self);
end;
end;
end;
end;
end;
if (not NeedRefresh) then
NeedRefresh := (GetValue <> Value);
if (NeedRefresh and Assigned(FCurrentControl) and FParent.FReminder.Visible)
then
begin
case pt of
ptComment:
begin
try
// infoBox('before set', 'Warning',MB_OK);
tmp := GetValue;
(FCurrentControl as TEdit).Text := tmp;
// infoBox('after set set', 'Warning',MB_OK);
except
end;
end;
ptQuantity:
(FCurrentControl as TUpDown).Position := StrToIntDef(GetValue, 1);
(* ptSkinReading:
(FCurrentControl as TUpDown).Position := StrToIntDef(GetValue,0); *)
ptVisitDate:
begin
try
(FCurrentControl as TORDateCombo).FMDate := StrToFloat(GetValue);
except
on EConvertError do
(FCurrentControl as TORDateCombo).FMDate := 0;
else
raise;
end;
end;
ptDate, ptDateTime:
begin
try
(FCurrentControl as TORDateBox).FMDateTime := StrToFloatDef(GetValue, 0);
except
on EConvertError do
(FCurrentControl as TORDateBox).FMDateTime := 0;
else
raise;
end;
end;
ptPrimaryDiag, ptAdd2PL, ptContraindicated:
(FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]);
ptVisitLocation:
begin
tmp := GetValue;
with (FCurrentControl as TORComboBox) do
begin
if (Piece(tmp, U, 1) = '0') then
begin
Items[0] := tmp;
SelectByID('0');
end
else
SelectByID(tmp);
end;
end;
ptWHPapResult:
(FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]);
ptWHNotPurp:
(FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]);
ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction,
ptLevelUnderstanding, ptSkinReading: // (AGP Change 26.1)
(FCurrentControl as TORComboBox).SelectByID(GetValue);
else
if (pt = ptVitalEntry) then
begin
if (FCurrentControl is TORComboBox) then
(FCurrentControl as TORComboBox).SelectByID(VitalValue)
else if (FCurrentControl is TVitalEdit) then
begin
with (FCurrentControl as TVitalEdit) do
begin
Text := VitalValue;
if (Assigned(LinkedCombo)) then
begin
tmp := VitalUnitValue;
if (tmp <> '') then
LinkedCombo.Text := VitalUnitValue
else
LinkedCombo.ItemIndex := 0;
end;
end;
end;
end;
end;
end;
end;
procedure TRemPrompt.SetValueFromParent(Value: string);
begin
FFromParent := TRUE;
try
SetValue(Value);
finally
FFromParent := FALSE;
end;
end;
procedure TRemPrompt.InitValue;
var
Value: string;
pt: TRemPromptType;
idx, i, j: integer;
TempSL: TORStringList;
Found: boolean;
RData: TRemData;
begin
Value := InternalValue;
pt := PromptType;
if (ord(pt) >= ord(low(TRemPromptType))) and (ComboPromptTags[pt] <> 0) then
begin
TempSL := TORStringList.Create;
try
GetPCECodes(TempSL, ComboPromptTags[pt]);
idx := TempSL.CaseInsensitiveIndexOfPiece(Value, U, 1);
if (idx < 0) then
idx := TempSL.CaseInsensitiveIndexOfPiece(Value, U, 2);
if (idx >= 0) then
Value := Piece(TempSL[idx], U, 1);
finally
TempSL.Free;
end;
end;
if ((not Forced) and Assigned(FParent) and Assigned(FParent.FData) and
IsSyncPrompt(pt)) then
begin
Found := FALSE;
for i := 0 to FParent.FData.Count - 1 do
begin
RData := TRemData(FParent.FData[i]);
if (Assigned(RData.FPCERoot)) then
Found := RData.FPCERoot.GetValue(pt, Value);
if (not Found) and (Assigned(RData.FChoices)) then
begin
for j := 0 to RData.FChoices.Count - 1 do
begin
if (Assigned(RData.FChoices.Objects[j])) then
begin
Found := TRemPCERoot(RData.FChoices.Objects[j]).GetValue(pt, Value);
if (Found) then
break;
end;
end;
end;
if (Found) then
break;
end;
end;
FInitializing := TRUE;
try
SetValueFromParent(Value);
finally
FInitializing := FALSE;
end;
end;
function TRemPrompt.ForcedCaption: string;
var
pt: TRemPromptType;
begin
Result := Caption;
if (Result = '') then
begin
pt := PromptType;
if (pt = ptDataList) then
begin
if (Assigned(FData)) then
begin
if (FData.DataType = dtDiagnosis) then
Result := 'Diagnosis'
else if (FData.DataType = dtProcedure) then
Result := 'Procedure';
end;
end
else if (pt = ptVitalEntry) then
Result := VitalDesc[VitalType] + ':'
else if (pt = ptMHTest) then
Result := 'Perform ' + FData.Narrative
else if (pt = ptGAF) then
Result := 'GAF Score'
else
Result := PromptDescriptions[pt];
if (Result = '') then
Result := 'Prompt';
end;
if (copy(Result, length(Result), 1) = ':') then
delete(Result, length(Result), 1);
end;
function TRemPrompt.VitalType: TVitalType;
begin
Result := vtUnknown;
if (Assigned(FData)) then
Result := Code2VitalType(FData.InternalValue);
end;
procedure TRemPrompt.VitalVerify(Sender: TObject);
var
vedt: TVitalEdit;
vcbo: TVitalComboBox;
AObj: TWinControl;
begin
if (Sender is TVitalEdit) then
begin
vedt := TVitalEdit(Sender);
vcbo := vedt.LinkedCombo;
end
else if (Sender is TVitalComboBox) then
begin
vcbo := TVitalComboBox(Sender);
vedt := vcbo.LinkedEdit;
end
else
begin
vcbo := nil;
vedt := nil;
end;
AObj := Screen.ActiveControl;
if ((not Assigned(AObj)) or ((AObj <> vedt) and (AObj <> vcbo))) then
begin
if (vedt.Tag = TAG_VITHEIGHT) then
vedt.Text := ConvertHeight2Inches(vedt.Text);
if VitalInvalid(vedt, vcbo) then
vedt.SetFocus;
end;
end;
function TRemPrompt.VitalUnitValue: string;
var
vt: TVitalType;
begin
vt := VitalType;
if (vt in [vtTemp, vtHeight, vtWeight]) then
begin
Result := Piece(GetValue, ';', 2);
if (Result = '') then
begin
case vt of
vtTemp:
Result := 'F';
vtHeight:
Result := 'IN';
vtWeight:
Result := 'LB';
end;
SetPiece(FValue, ';', 2, Result);
end;
end
else
Result := '';
end;
function TRemPrompt.VitalValue: string;
begin
Result := Piece(GetValue, ';', 1);
end;
procedure TRemPrompt.DoView(Sender: TObject);
var
ien,value: string;
aList: TStrings;
canPrint,vistaPrint: boolean;
header, vistaDevice: string;
begin
if pxrmworking then
exit;
aList := TStringList.Create;
try
begin
// IEN := Piece(TRemData(FParent.FData[0]).FRec3, U, 6);
canPrint := false;
vistaPrint := Piece(Frec4, U, 12) = 'V';
IEN := Piece(FParent.FRec1, U, 2);
value := Piece(TRemData(FParent.FData[0]).FRec3, U, 14);
getGeneralFindingText(aList, canprint, header, patient.DFN, ien, value);
if Piece(FRec4, U, 12) = 'N' then canPrint := false;
if vistaPrint then
begin
vistaDevice := VistAPrintReportBox(aList, header);
if VistaPrint then setValue(Piece(VistADevice, U, 1));
end
else
begin
self.reportView := ModelessReportBox(aList, header, canPrint, false);
FOldReportViewOnDestroy := self.reportView.OnDestroy;
self.reportView.OnDestroy := self.reportViewClosed;
end;
ViewRecord := true;
end;
finally
FreeAndNil(aList);
pxrmDoneWorking;
end;
end;
procedure TRemPrompt.DoWHReport(Sender: TObject);
Var
comp, IEN: string;
i: integer;
begin
if pxrmWorking then
exit;
try
for i := 0 to FParent.FData.Count - 1 do
begin
comp := Piece(TRemData(FParent.FData[i]).FRec3, U, 4);
IEN := Piece(TRemData(FParent.FData[i]).FRec3, U, 6);
end;
CallV('ORQQPXRM GET WH REPORT TEXT', [IEN]);
ReportBox(RPCBrokerV.Results, 'Procedure Report Results', TRUE);
finally
pxrmDoneWorking;
end;
end;
procedure TRemPrompt.ViewWHText(Sender: TObject);
var
WHRecNum, WHTitle: string;
i: integer;
begin
if pxrmWorking then
exit;
try
for i := 0 to FParent.FData.Count - 1 do
begin
if Piece(TRemData(FParent.FData[i]).FRec3, U, 4) = 'WH' then
begin
WHRecNum := (Piece(TRemData(FParent.FData[i]).FRec3, U, 6));
WHTitle := (Piece(TRemData(FParent.FData[i]).FRec3, U, 8));
end;
end;
CallV('ORQQPXRM GET WH LETTER TEXT', [WHRecNum]);
ReportBox(RPCBrokerV.Results, 'Women Health Notification Purpose: ' +
WHTitle, FALSE);
finally
pxrmDoneWorking;
end;
end;
procedure TRemPrompt.DoMHTest(Sender: TObject);
var
TmpSL, tmpScores, tmpResults, linkList, elementList, promptList: TStringList;
i, l: integer;
Before, After, Score, dien, linkType, linkItem, linkSeq, value: string;
MHRequired, doLink: boolean;
begin
if pxrmworking then
exit;
linkList := TStringList.Create;
if (Sender is TCPRSDialogButton) then
(Sender as TCPRSDialogButton).Enabled := FALSE;
// dolink := false;
try
dien := Piece(self.FRec4, U, 2);
if FParent.FReminder.MHTestArray = nil then
FParent.FReminder.MHTestArray := TORStringList.Create;
if (MHTestAuthorized(FData.Narrative)) then
begin
FParent.FReminder.BeginTextChanged;
try
if (FParent.IncludeMHTestInPN) then
TmpSL := TStringList.Create
else
TmpSL := nil;
if Piece(Self.FData.FRec3, U, 13) = '1' then
MHRequired := TRUE
else
MHRequired := FALSE;
Before := GetValue;
After := PerformMHTest(Before, FData.Narrative, TmpSL, MHRequired);
if uInit.TimedOut then
After := '';
if Piece(After, U, 1) = 'New MH dll' then
begin
if Piece(After, U, 2) = 'COMPLETE' then
begin
FParent.FReminder.MHTestArray.Add(FData.Narrative + U +
FParent.FReminder.IEN);
Self.FMHTestComplete := 1;
Score := Piece(After, U, 3);
if FParent.ResultDlgID <> '' then
begin
tmpScores := TStringList.Create;
tmpResults := TStringList.Create;
PiecestoList(copy(Score, 2, length(Score)), '*', tmpScores);
PiecestoList(FParent.ResultDlgID, '~', tmpResults);
GetMHResultText(FMiscText, tmpResults, tmpScores, dien, linkList);
if tmpScores <> nil then
tmpScores.Free;
if tmpResults <> nil then
tmpResults.Free;
end;
if (FMiscText <> '') then
FMiscText := FMiscText + '~<br>';
if TmpSL <> nil then
begin
for i := 0 to TmpSL.Count - 1 do
begin
if (i > 0) then
FMiscText := FMiscText + CRCode;
FMiscText := FMiscText + TmpSL[i];
end;
end;
// end;
// ExpandTIUObjects(FMiscText);
end
else if Piece(After, U, 2) = 'INCOMPLETE' then
begin
FParent.FReminder.MHTestArray.Add(FData.Narrative + U +
FParent.FReminder.IEN);
Self.FMHTestComplete := 2;
FMiscText := '';
After := 'X';
end
else if Piece(After, U, 2) = 'CANCELLED' then
begin
Self.FMHTestComplete := 0;
FMiscText := '';
After := '';
end;
SetValue(After);
end;
finally
if not uInit.TimedOut then
FParent.FReminder.EndTextChanged(Sender);
end;
if not uInit.TimedOut then
if (FParent.ElemType = etDisplayOnly) and (not Assigned(FParent.FParent))
then
RemindersInProcess.Notifier.Notify;
end
else
InfoBox('Not Authorized to score the ' + FData.Narrative + ' test.',
'Insufficient Authorization', MB_OK + MB_ICONERROR);
// finally
// if (Sender is TCPRSDialogButton) then
// begin
// (Sender as TCPRSDialogButton).Enabled := TRUE;
// (Sender as TCPRSDialogButton).SetFocus;
// end;
if linkList.Count > 0 then
begin
try
begin
promptList := TStringList.Create;
elementList := TStringList.Create;
doLink := false;
for l := 0 to linkList.Count - 1 do
begin
linkItem := Piece(linkList.Strings[l], U, 1);
if linkItem = '' then continue;
linkType := Piece(linkList.Strings[l], U, 2);
if linkType = '' then continue;
value := Piece(linkList.Strings[l], U, 3);
if value = '' then continue;
linkSeq := Piece(linkList.Strings[l],u, 4);
if linkType = 'ELEMENT' then elementList.Add(linkItem + U + value + U + '' + U + linkSeq)
else
begin
if value = 'REQUIRED' then promptList.Add(linkItem + U + linkType + U + 'REQUIRED' + U + U + linkSeq)
else promptList.Add(linkItem + U + linkType + U + 'VALUE' + U + value + U + linkSeq);
end;
if FParent.buildLinkSeq(linkSeq, self.FParent.FID, Piece(self.FParent.FRec1, u, 3)) then
doLink := true;
end;
if doLink then self.FParent.FReminder.findLinkItem(elementList, promptList, Piece(self.FParent.FRec1, u, 3));
end;
finally
// freeAndNil(linkList);
// if elementList <> nil then freeAndNil(elementList);
// if promptList <> nil then freeAndNil(promptList);
end;
end;
finally
if (Sender is TCPRSDialogButton) then
begin
(Sender as TCPRSDialogButton).Enabled := TRUE;
(Sender as TCPRSDialogButton).SetFocus;
end;
pxrmdoneWorking;
end;
end;
procedure TRemPrompt.GAFHelp(Sender: TObject);
begin
inherited;
GotoWebPage(GAFURL);
end;
function TRemPrompt.EntryID: string;
begin
Result := FParent.EntryID + '/' + IntToStr(integer(Self));
end;
function TRemPrompt.EventType: string;
begin
Result := Piece(FRec4, U, 29);
end;
procedure TRemPrompt.EditKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = '?') and (Sender is TCustomEdit) and
((TCustomEdit(Sender).Text = '') or (TCustomEdit(Sender).SelStart = 0)) then
Key := #0;
end;
{ TRemPCERoot }
destructor TRemPCERoot.Destroy;
begin
KillObj(@FData);
KillObj(@FForcedPrompts);
inherited;
end;
procedure TRemPCERoot.Done(Data: TRemData);
var
i, idx: integer;
begin
if (Assigned(FForcedPrompts) and Assigned(Data.FParent) and
Assigned(Data.FParent.FPrompts)) then
begin
for i := 0 to Data.FParent.FPrompts.Count - 1 do
UnSync(TRemPrompt(Data.FParent.FPrompts[i]));
end;
FData.Remove(Data);
if (FData.Count <= 0) then
begin
idx := PCERootList.IndexOfObject(Self);
// if(idx < 0) then
// idx := PCERootList.IndexOf(FID);
if (idx >= 0) then
PCERootList.delete(idx);
if PrimaryDiagRoot = Self then
PrimaryDiagRoot := nil;
Free;
end;
end;
class function TRemPCERoot.GetRoot(Data: TRemData; Rec3: string;
Historical: boolean): TRemPCERoot;
var
DID: string;
idx: integer;
obj: TRemPCERoot;
begin
if (Data.DataType = dtVitals) then
DID := 'V' + Piece(Rec3, U, 6)
else
begin
if (Historical) then
begin
inc(HistRootCount);
DID := IntToStr(HistRootCount);
end
else
DID := '0';
DID := DID + U + Piece(Rec3, U, r3Type) + U + Piece(Rec3, U, r3Code) + U +
Piece(Rec3, U, r3Cat) + U + Piece(Rec3, U, r3Nar);
end;
idx := -1;
if (not Assigned(PCERootList)) then
PCERootList := TStringList.Create
else if (PCERootList.Count > 0) then
idx := PCERootList.IndexOf(DID);
if (idx < 0) then
begin
obj := TRemPCERoot.Create;
try
obj.FData := TList.Create;
obj.FID := DID;
idx := PCERootList.AddObject(DID, obj);
except
obj.Free;
raise;
end;
end;
Result := TRemPCERoot(PCERootList.Objects[idx]);
Result.FData.Add(Data);
end;
function TRemPCERoot.GetValue(PromptType: TRemPromptType;
var NewValue: string): boolean;
var
ptS: string;
i: integer;
begin
ptS := Char(ord('D') + ord(PromptType));
i := pos(ptS, FValueSet);
if (i = 0) then
Result := FALSE
else
begin
NewValue := Piece(FValue, U, i);
Result := TRUE;
end;
end;
procedure TRemPCERoot.Sync(Prompt: TRemPrompt);
var
i, j: integer;
RData: TRemData;
Prm: TRemPrompt;
pt: TRemPromptType;
ptS, Value: string;
begin
// if(assigned(Prompt.FParent) and ((not Prompt.FParent.FChecked) or
// (Prompt.FParent.ElemType = etDisplayOnly))) then exit;
if (Assigned(Prompt.FParent) and (not Prompt.FParent.FChecked)) then
exit;
pt := Prompt.PromptType;
Value := Prompt.GetValue;
if (Prompt.Forced) then
begin
if (not Prompt.FInitializing) then
begin
if (not Assigned(FForcedPrompts)) then
FForcedPrompts := TStringList.Create;
if (FForcedPrompts.IndexOfObject(Prompt) < 0) then
begin
for i := 0 to FForcedPrompts.Count - 1 do
begin
Prm := TRemPrompt(FForcedPrompts.Objects[i]);
if (pt = Prm.PromptType) and (FForcedPrompts[i] <> Value) and
(Prm.FParent.IsChecked) then
raise EForcedPromptConflict.Create('Forced Value Error:' + CRLF +
CRLF + Prompt.ForcedCaption +
' is already being forced to another value.');
end;
FForcedPrompts.AddObject(Value, Prompt);
end;
end;
end
else
begin
if (Assigned(FForcedPrompts)) then
begin
for i := 0 to FForcedPrompts.Count - 1 do
begin
Prm := TRemPrompt(FForcedPrompts.Objects[i]);
if (pt = Prm.PromptType) and (FForcedPrompts[i] <> Value) and
(Prm.FParent.IsChecked) then
begin
Prompt.SetValue(FForcedPrompts[i]);
if (Assigned(Prompt.FParent)) then
Prompt.FParent.cbClicked(nil); // Forces redraw
exit;
end;
end;
end;
end;
if (Prompt.FInitializing) then
exit;
for i := 0 to FData.Count - 1 do
inc(TRemData(FData[i]).FSyncCount);
ptS := Char(ord('D') + ord(pt));
i := pos(ptS, FValueSet);
if (i = 0) then
begin
FValueSet := FValueSet + ptS;
i := length(FValueSet);
end;
SetPiece(FValue, U, i, Value);
for i := 0 to FData.Count - 1 do
begin
RData := TRemData(FData[i]);
if (RData.FSyncCount = 1) and (Assigned(RData.FParent)) and
(Assigned(RData.FParent.FPrompts)) then
begin
for j := 0 to RData.FParent.FPrompts.Count - 1 do
begin
Prm := TRemPrompt(RData.FParent.FPrompts[j]);
if (Prm <> Prompt) and (pt = Prm.PromptType) and (not Prm.Forced) then
Prm.SetValue(Prompt.GetValue);
end;
end;
end;
for i := 0 to FData.Count - 1 do
begin
RData := TRemData(FData[i]);
if (RData.FSyncCount > 0) then
dec(RData.FSyncCount);
end;
end;
procedure TRemPCERoot.UnSync(Prompt: TRemPrompt);
var
idx: integer;
begin
if (Assigned(FForcedPrompts) and Prompt.Forced) then
begin
idx := FForcedPrompts.IndexOfObject(Prompt);
if (idx >= 0) then
FForcedPrompts.delete(idx);
end;
end;
initialization
InitReminderObjects;
finalization
FreeReminderObjects;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Generic file view containing default panels (header, footer, etc.)
Copyright (C) 2012-2018 Alexander Koblov (alexx2000@mail.ru)
Copyright (C) 2012 Przemyslaw Nagay (cobines@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit uFileViewWithPanels;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, ExtCtrls, StdCtrls,
uFileView,
uFileViewHeader,
uFileSource;
type
{ TFileViewWithPanels }
TFileViewWithPanels = class(TFileView)
protected
FSelectedCount: Integer;
lblInfo: TLabel;
pnlFooter: TPanel;
pnlHeader: TFileViewHeader;
procedure AfterChangePath; override;
procedure CreateDefault(AOwner: TWinControl); override;
procedure DisplayFileListChanged; override;
procedure DoActiveChanged; override;
procedure DoSelectionChanged; override;
procedure ShowPathEdit;
procedure DoUpdateView; override;
procedure UpdateFlatFileName; virtual;
procedure UpdateInfoPanel; virtual;
public
property Header:TFileViewHeader read pnlHeader;
procedure AddFileSource(aFileSource: IFileSource; aPath: String); override;
procedure RemoveCurrentFileSource; override;
published
procedure cm_EditPath(const {%H-}Params: array of string);
end;
implementation
uses
DCStrUtils, uFile, uGlobs, uLng, uFileProperty, uFileViewWorker, uDCUtils;
{ TFileViewWithPanels }
procedure TFileViewWithPanels.AddFileSource(aFileSource: IFileSource; aPath: String);
begin
inherited AddFileSource(aFileSource, aPath);
pnlHeader.UpdateAddressLabel;
end;
procedure TFileViewWithPanels.AfterChangePath;
begin
inherited AfterChangePath;
if FileSourcesCount > 0 then
pnlHeader.UpdatePathLabel;
end;
procedure TFileViewWithPanels.cm_EditPath(const Params: array of string);
begin
ShowPathEdit;
end;
procedure TFileViewWithPanels.CreateDefault(AOwner: TWinControl);
begin
inherited CreateDefault(AOwner);
pnlHeader := TFileViewHeader.Create(Self, Self);
pnlFooter := TPanel.Create(Self);
pnlFooter.Parent := Self;
pnlFooter.Align := alBottom;
pnlFooter.BevelInner := bvNone;
pnlFooter.BevelOuter := bvNone;
pnlFooter.AutoSize := True;
pnlFooter.DoubleBuffered := True;
lblInfo := TLabel.Create(pnlFooter);
lblInfo.Parent := pnlFooter;
lblInfo.AutoSize := False;
lblInfo.Align := alClient;
{$IF DEFINED(LCLGTK2)}
// Workaround: "Layout and line"
// http://doublecmd.sourceforge.net/mantisbt/view.php?id=573
pnlFooter.Visible := False;
{$ELSE}
lblInfo.Height := lblInfo.Canvas.TextHeight('Wg');
{$ENDIF}
{$IFDEF LCLCARBON}
// Under Carbon AutoSize don't work without it
pnlHeader.ClientHeight:= 0;
pnlFooter.ClientHeight:= 0;
{$ENDIF}
end;
procedure TFileViewWithPanels.DisplayFileListChanged;
begin
inherited DisplayFileListChanged;
UpdateInfoPanel;
end;
procedure TFileViewWithPanels.DoActiveChanged;
begin
inherited DoActiveChanged;
pnlHeader.SetActive(Active);
end;
procedure TFileViewWithPanels.DoSelectionChanged;
begin
inherited DoSelectionChanged;
UpdateInfoPanel;
end;
procedure TFileViewWithPanels.DoUpdateView;
begin
inherited DoUpdateView;
pnlHeader.Visible := gCurDir; // Current directory
pnlFooter.Visible := gStatusBar; // Status bar
pnlHeader.UpdateFont;
pnlHeader.UpdateAddressLabel;
pnlHeader.UpdatePathLabel;
end;
procedure TFileViewWithPanels.RemoveCurrentFileSource;
begin
inherited RemoveCurrentFileSource;
if FileSourcesCount > 0 then
pnlHeader.UpdateAddressLabel;
end;
procedure TFileViewWithPanels.ShowPathEdit;
begin
pnlHeader.ShowPathEdit;
end;
procedure TFileViewWithPanels.UpdateFlatFileName;
var
AFile: TFile;
begin
AFile:= CloneActiveFile;
if Assigned(AFile) then
try
lblInfo.Caption := MinimizeFilePath(ExtractDirLevel(CurrentPath, AFile.FullPath),
lblInfo.Canvas, lblInfo.Width);
finally
AFile.Free;
end;
end;
procedure TFileViewWithPanels.UpdateInfoPanel;
var
i: Integer;
FilesInDir, FilesSelected, FolderInDir, FolderSelected: Integer;
SizeInDir, SizeSelected: Int64;
SizeProperty: TFileSizeProperty;
begin
FSelectedCount := 0;
if GetCurrentWorkType = fvwtCreate then
begin
lblInfo.Caption := rsMsgLoadingFileList;
end
else if not Assigned(FAllDisplayFiles) or (FAllDisplayFiles.Count = 0) then
begin
lblInfo.Caption := rsMsgNoFiles;
end
else if Assigned(FileSource) then
begin
FilesInDir := 0;
FilesSelected := 0;
SizeInDir := 0;
SizeSelected := 0;
FolderInDir := 0;
FolderSelected := 0;
for i := 0 to FFiles.Count - 1 do
begin
with FFiles[i] do
begin
if FSFile.Name = '..' then Continue;
if FSFile.IsDirectory then
inc(FolderInDir)
else
inc(FilesInDir);
if Selected then
begin
if FSFile.IsDirectory then
inc(FolderSelected)
else
inc(FilesSelected);
end;
// Count size if Size property exists.
if fpSize in FSFile.AssignedProperties then
begin
SizeProperty := FSFile.SizeProperty;
if Selected then
SizeSelected := SizeSelected + SizeProperty.Value;
SizeInDir := SizeInDir + SizeProperty.Value;
end;
end;
end;
FSelectedCount := FilesSelected + FolderSelected;
if FlatView and (FSelectedCount = 0) then
UpdateFlatFileName
else
lblInfo.Caption := Format(rsMsgSelectedInfo,
[cnvFormatFileSize(SizeSelected, uoscHeaderFooter),
cnvFormatFileSize(SizeInDir, uoscHeaderFooter),
FilesSelected,
FilesInDir,
FolderSelected,
FolderInDir]);
end
else if not (csDestroying in ComponentState) then
lblInfo.Caption := '';
end;
end.
|
unit PosInterface;
interface
type
TMsgDescriptionProc = procedure(AMsgDescription : string) of object;
IPos = interface
procedure SetMsgDescriptionProc(Value: TMsgDescriptionProc);
function GetMsgDescriptionProc: TMsgDescriptionProc;
function GetLastPosError : string;
function Payment(ASumma : Currency) : Boolean;
procedure Cancel;
property OnMsgDescriptionProc: TMsgDescriptionProc read GetMsgDescriptionProc write SetMsgDescriptionProc;
property LastPosError : String read GetLastPosError;
end;
implementation
end.
|
unit fpeMakerNoteSanyo;
{$IFDEF FPC}
{$MODE DELPHI}
//{$mode objfpc}{$H+}
{$ENDIF}
interface
uses
Classes, SysUtils,
fpeTags, fpeExifReadWrite;
type
TSanyoMakerNoteReader = class(TMakerNoteReader)
protected
procedure GetTagDefs({%H-}AStream: TStream); override;
end;
implementation
uses
fpeStrConsts;
resourcestring
rsSanyoMacroLkup = '0:Normal,1:Macro,2:View,3:Manual';
rsSanyoQualityLkup = '0:Normal/Very Low,1:Normal/Low,2:Normal/Medium Low,'+
'3:Normal/Medium,4:Normal/Medium High,5:Normal/High,6:Normal/Very High'+
'7:Normal/Super High,256:Fine/Very Low,257:Fine/Low,258:Fine/Medium Low'+
'259:Fine/Medium,260:Fine/Medium High,261:Fine/High,262:Fine/Very High'+
'263:Fine/Super High,512:Super Fine/Very Low,513:Super Fine/Low,'+
'514:Super Fine/Medium Low,515:Super Fine/Medium,516:Super Fine/Medium High,'+
'517:Super Fine/High,518:Super Fine/Very High,519:Super Fine/Super High';
rsSanyoSpecialMode = 'Special mode';
// from dExif
procedure BuildSanyoTagDefs(AList: TTagDefList);
const
M = LongWord(TAGPARENT_MAKERNOTE);
begin
Assert(AList <> nil);
with AList do begin
AddULongTag (M+$0200, 'SpecialMode', 3, rsSanyoSpecialMode);
AddUShortTag (M+$0201, 'Quality', 1, rsQuality, rsSanyoQualityLkup);
AddUShortTag (M+$0202, 'Macro', 1, rsMacro, rsSanyoMacroLkup);
AddURationalTag(M+$0204, 'DigitalZoom', 1, rsDigitalZoom);
end;
end;
//==============================================================================
// TSanyoMakerNoteReader
//==============================================================================
procedure TSanyoMakerNoteReader.GetTagDefs(AStream: TStream);
begin
BuildSanyoTagDefs(FTagDefs);
end;
//==============================================================================
// initialization
//==============================================================================
initialization
RegisterMakerNoteReader(TSanyoMakerNoteReader, 'Sanyo', '');
end.
|
unit FC.Trade.Statistics;
{$I Compiler.inc}
interface
uses Classes, SysUtils, FC.Definitions;
type
TStockTradingStatistics = class
private
FBalance: TStockRealNumber;
FLargestProfit: TStockRealNumber;
FLargestLoss : TStockRealNumber;
FLargestProfitPts: integer;
FLargestLossPts : integer;
FOrderCount : integer;
FProfitOrderCount: integer;
FLossOrderCount : integer;
FTotalProfit : TStockRealNumber;
FTotalLoss : TStockRealNumber;
FTotalProfitPts : integer;
FTotalLossPts : integer;
FTotalPossibleProfit : TStockRealNumber;
FTotalPossibleProfitPts : integer;
public
StartDate : TDateTime;
StopDate : TDateTime;
property Balance: TStockRealNumber read FBalance write FBalance;
property LargestProfit: TStockRealNumber read FLargestProfit;
property LargestLoss : TStockRealNumber read FLargestLoss;
property LargestProfitPts: integer read FLargestProfitPts;
property LargestLossPts : integer read FLargestLossPts;
property OrderCount : integer read FOrderCount;
property ProfitOrderCount: integer read FProfitOrderCount;
property LossOrderCount : integer read FLossOrderCount;
property TotalProfit : TStockRealNumber read FTotalProfit;
property TotalLoss : TStockRealNumber read FTotalLoss;
property TotalProfitPts : integer read FTotalProfitPts;
property TotalLossPts : integer read FTotalLossPts;
property TotalPossibleProfit : TStockRealNumber read FTotalPossibleProfit;
property TotalPossibleProfitPts : integer read FTotalPossibleProfitPts;
procedure AddValue(aValue,aBestPossible,aWorstPossible: TStockRealNumber;
aValuePts,aBestPossiblePts,aWorstPossiblePts: integer);
procedure ToStrings(aList: TStrings);
end;
implementation
uses Math,DateUtils;
{ TStockTradingStatistics }
procedure TStockTradingStatistics.AddValue(aValue,aBestPossible,aWorstPossible: TStockRealNumber;
aValuePts,aBestPossiblePts,aWorstPossiblePts: integer);
begin
FBalance:=FBalance+aValue;
FLargestProfit:=max(aValue,FLargestProfit);
FLargestProfitPts:=max(aValuePts,FLargestProfitPts);
FLargestLoss:=min(aValue,FLargestLoss);
FLargestLossPts:=min(aValuePts,FLargestLossPts);
inc(FOrderCount);
if aValue>0 then
begin
inc(FProfitOrderCount);
FTotalProfit:=FTotalProfit+aValue;
FTotalProfitPts:=FTotalProfitPts+aValuePts;
FTotalPossibleProfit:=FTotalPossibleProfit+aBestPossible;
FTotalPossibleProfitPts:=FTotalPossibleProfitPts+aBestPossiblePts;
end
else if aValue<0 then
begin
inc(FLossOrderCount);
FTotalLoss:=FTotalLoss+aValue;
FTotalLossPts:=FTotalLossPts+aValuePts;
end;
end;
procedure TStockTradingStatistics.ToStrings(aList: TStrings);
var
aDays: TStockRealNumber;
s: string;
begin
aDays:=DaySpan(StopDate,StartDate);
aList.Clear;
aList.Values['Start Scanning at']:=DateTimeToStr(StartDate);
aList.Values['Stop Scanning at']:=DateTimeToStr(StopDate);
aList.Values['Days of trading']:=FloatToStr(RoundTo(aDays,-2));
aList.Values['Orders per day']:= FloatToStr(RoundTo(OrderCount/max(aDays,1),-2));
aList.Add('');
aList.Values['Balance']:=FormatCurr('0,.00',Balance);
aList.Values['Total Profit($)']:=FormatCurr('0,.00',TotalProfit);
aList.Values['Total Profit(pt)']:=FormatCurr('0,.00',TotalProfitPts);
aList.Values['Possible Profit($)']:=FormatCurr('0,.00',TotalPossibleProfit);
aList.Values['Possible Profit(pt)']:=FormatCurr('0,.00',TotalPossibleProfitPts);
//-----
if TotalPossibleProfit=0 then
s:='-'
else
s:=FormatCurr('0,.00',TotalProfit/TotalPossibleProfit*100);
aList.Values['% from Possible Profit($)']:=s;
//-----
if TotalPossibleProfitPts=0 then
s:='-'
else
s:=FormatCurr('0,.00',TotalProfitPts/TotalPossibleProfitPts*100);
aList.Values['% from Possible Profit(pt)']:=s;
//-----
aList.Values['Total Loss($)']:=FormatCurr('0,.00',TotalLoss);
aList.Values['Total Loss(pt)']:=FormatCurr('0,.00',TotalLossPts);
//-----
if FTotalLossPts=0 then
s:='-'
else
s:=FormatCurr('0,.00',abs(FTotalProfitPts/FTotalLossPts))+':1';
aList.Values['Profit(pt):Loss(pt)']:=s;
//-----
aList.Values['Count of wins']:=IntToStr(ProfitOrderCount);
aList.Values['Count of losses']:=IntToStr(LossOrderCount);
//-----
if ProfitOrderCount>0 then
begin
aList.Values['Average Profit($)']:=FormatCurr('0,.00', TotalProfit/ProfitOrderCount);
aList.Values['Average Profit(pt)']:=FormatCurr('0,.00', TotalProfitPts/ProfitOrderCount)
end
else begin
aList.Values['Average Profit($)']:='-';
aList.Values['Average Profit(pt)']:='-';
end;
//-----
if LossOrderCount>0 then
begin
aList.Values['Average Loss($)']:=FormatCurr('0,.00', TotalLoss/LossOrderCount);
aList.Values['Average Loss(pt)']:=FormatCurr('0,.00', TotalLossPts/LossOrderCount);
end
else begin
aList.Values['Average Loss($)']:='-';
aList.Values['Average Loss(pt)']:='-';
end;
//-----
aList.Values['Largest Profit($)']:=FormatCurr('0,.00', LargestProfit);
aList.Values['Largest Profit(pt)']:=FormatCurr('0,.00', LargestProfitPts);
aList.Values['Largest Loss($)']:=FormatCurr('0,.00',LargestLoss);
aList.Values['Largest Loss(pt)']:=FormatCurr('0,.00',LargestLossPts);
aList.Values['Profit per day($)']:=FormatCurr('0,.00',Balance/max(aDays,1));
end;
end.
|
unit DragDropInternet;
// -----------------------------------------------------------------------------
// Project: Drag and Drop Component Suite.
// Module: DragDropInternet
// Description: Implements Dragging and Dropping of internet related data.
// Version: 4.0
// Date: 18-MAY-2001
// Target: Win32, Delphi 5-6
// Authors: Anders Melander, anders@melander.dk, http://www.melander.dk
// Copyright © 1997-2001 Angus Johnson & Anders Melander
// -----------------------------------------------------------------------------
interface
uses
DragDrop,
DropTarget,
DropSource,
DragDropFormats,
Windows,
Classes,
ActiveX;
type
////////////////////////////////////////////////////////////////////////////////
//
// TURLClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// Implements support for the 'UniformResourceLocator' format.
////////////////////////////////////////////////////////////////////////////////
TURLClipboardFormat = class(TCustomTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
property URL: string read GetString write SetString;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TNetscapeBookmarkClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// Implements support for the 'Netscape Bookmark' format.
////////////////////////////////////////////////////////////////////////////////
TNetscapeBookmarkClipboardFormat = class(TCustomSimpleClipboardFormat)
private
FURL : string;
FTitle : string;
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
function GetClipboardFormat: TClipFormat; override;
procedure Clear; override;
property URL: string read FURL write FURL;
property Title: string read FTitle write FTitle;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TNetscapeImageClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// Implements support for the 'Netscape Image Format' format.
////////////////////////////////////////////////////////////////////////////////
TNetscapeImageClipboardFormat = class(TCustomSimpleClipboardFormat)
private
FURL : string;
FTitle : string;
FImage : string;
FLowRes : string;
FExtra : string;
FHeight : integer;
FWidth : integer;
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
function GetClipboardFormat: TClipFormat; override;
procedure Clear; override;
property URL: string read FURL write FURL;
property Title: string read FTitle write FTitle;
property Image: string read FImage write FImage;
property LowRes: string read FLowRes write FLowRes;
property Extra: string read FExtra write FExtra;
property Height: integer read FHeight write FHeight;
property Width: integer read FWidth write FWidth;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TVCardClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// Implements support for the '+//ISBN 1-887687-00-9::versit::PDI//vCard'
// (vCard) format.
////////////////////////////////////////////////////////////////////////////////
TVCardClipboardFormat = class(TCustomStringListClipboardFormat)
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
function GetClipboardFormat: TClipFormat; override;
property Items: TStrings read GetLines;
end;
////////////////////////////////////////////////////////////////////////////////
//
// THTMLClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// Implements support for the 'HTML Format' format.
////////////////////////////////////////////////////////////////////////////////
THTMLClipboardFormat = class(TCustomStringListClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function HasData: boolean; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property HTML: TStrings read GetLines;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TRFC822ClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TRFC822ClipboardFormat = class(TCustomStringListClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Text: TStrings read GetLines;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TURLDataFormat
//
////////////////////////////////////////////////////////////////////////////////
// Renderer for URL formats.
////////////////////////////////////////////////////////////////////////////////
TURLDataFormat = class(TCustomDataFormat)
private
FURL : string;
FTitle : string;
procedure SetTitle(const Value: string);
procedure SetURL(const Value: string);
protected
public
function Assign(Source: TClipboardFormat): boolean; override;
function AssignTo(Dest: TClipboardFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
function NeedsData: boolean; override;
property URL: string read FURL write SetURL;
property Title: string read FTitle write SetTitle;
end;
////////////////////////////////////////////////////////////////////////////////
//
// THTMLDataFormat
//
////////////////////////////////////////////////////////////////////////////////
// Renderer for HTML text data.
////////////////////////////////////////////////////////////////////////////////
THTMLDataFormat = class(TCustomDataFormat)
private
FHTML: TStrings;
procedure SetHTML(const Value: TStrings);
protected
public
constructor Create(AOwner: TDragDropComponent); override;
destructor Destroy; override;
function Assign(Source: TClipboardFormat): boolean; override;
function AssignTo(Dest: TClipboardFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
function NeedsData: boolean; override;
property HTML: TStrings read FHTML write SetHTML;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TOutlookMailDataFormat
//
////////////////////////////////////////////////////////////////////////////////
// Renderer for Microsoft Outlook email formats.
////////////////////////////////////////////////////////////////////////////////
(*
TOutlookMessage = class;
TOutlookAttachments = class(TObject)
public
property Attachments[Index: integer]: TOutlookMessage; default;
property Count: integer;
end;
TOutlookMessage = class(TObject)
public
property Text: string;
property Stream: IStream;
property Attachments: TOutlookAttachments;
end;
*)
TOutlookMailDataFormat = class(TCustomDataFormat)
private
FStorages : TStorageInterfaceList;
protected
public
constructor Create(AOwner: TDragDropComponent); override;
destructor Destroy; override;
function Assign(Source: TClipboardFormat): boolean; override;
function AssignTo(Dest: TClipboardFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
function NeedsData: boolean; override;
property Storages: TStorageInterfaceList read FStorages;
// property Streams: TStreamInterfaceList;
// property Messages: TOutlookAttachments;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropURLTarget
//
////////////////////////////////////////////////////////////////////////////////
// URL drop target component.
////////////////////////////////////////////////////////////////////////////////
TDropURLTarget = class(TCustomDropMultiTarget)
private
FURLFormat : TURLDataFormat;
protected
function GetTitle: string;
function GetURL: string;
function GetPreferredDropEffect: LongInt; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property URL: string read GetURL;
property Title: string read GetTitle;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropURLSource
//
////////////////////////////////////////////////////////////////////////////////
// URL drop source component.
////////////////////////////////////////////////////////////////////////////////
TDropURLSource = class(TCustomDropMultiSource)
private
FURLFormat : TURLDataFormat;
procedure SetTitle(const Value: string);
procedure SetURL(const Value: string);
protected
function GetTitle: string;
function GetURL: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property URL: string read GetURL write SetURL;
property Title: string read GetTitle write SetTitle;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
////////////////////////////////////////////////////////////////////////////////
//
// Misc.
//
////////////////////////////////////////////////////////////////////////////////
function GetURLFromFile(const Filename: string; var URL: string): boolean;
function GetURLFromStream(Stream: TStream; var URL: string): boolean;
function ConvertURLToFilename(const url: string): string;
function IsHTML(const s: string): boolean;
function MakeHTML(const s: string): string;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
implementation
uses
SysUtils,
ShlObj,
DragDropFile,
DragDropPIDL;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
begin
RegisterComponents(DragDropComponentPalettePage, [TDropURLTarget,
TDropURLSource]);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utilities
//
////////////////////////////////////////////////////////////////////////////////
function GetURLFromFile(const Filename: string; var URL: string): boolean;
var
Stream : TStream;
begin
Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
try
Result := GetURLFromStream(Stream, URL);
finally
Stream.Free;
end;
end;
function GetURLFromString(const s: string; var URL: string): boolean;
var
Stream : TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.Size := Length(s);
Move(PChar(s)^, Stream.Memory^, Length(s));
Result := GetURLFromStream(Stream, URL);
finally
Stream.Free;
end;
end;
const
// *** DO NOT LOCALIZE ***
InternetShortcut = '[InternetShortcut]';
InternetShortcutExt = '.url';
function GetURLFromStream(Stream: TStream; var URL: string): boolean;
var
URLfile : TStringList;
i : integer;
s : string;
p : PChar;
begin
Result := False;
URLfile := TStringList.Create;
try
URLFile.LoadFromStream(Stream);
i := 0;
while (i < URLFile.Count-1) do
begin
if (CompareText(URLFile[i], InternetShortcut) = 0) then
begin
inc(i);
while (i < URLFile.Count) do
begin
s := URLFile[i];
p := PChar(s);
if (StrLIComp(p, 'URL=', length('URL=')) = 0) then
begin
inc(p, length('URL='));
URL := p;
Result := True;
exit;
end else
if (p^ = '[') then
exit;
inc(i);
end;
end;
inc(i);
end;
finally
URLFile.Free;
end;
end;
function ConvertURLToFilename(const url: string): string;
const
Invalids : set of char
= ['\', '/', ':', '?', '*', '<', '>', ',', '|', '''', '"'];
var
i: integer;
LastInvalid: boolean;
begin
Result := url;
if (AnsiStrLIComp(PChar(lowercase(Result)), 'http://', 7) = 0) then
delete(Result, 1, 7)
else if (AnsiStrLIComp(PChar(lowercase(Result)), 'ftp://', 6) = 0) then
delete(Result, 1, 6)
else if (AnsiStrLIComp(PChar(lowercase(Result)), 'mailto:', 7) = 0) then
delete(Result, 1, 7)
else if (AnsiStrLIComp(PChar(lowercase(Result)), 'file:', 5) = 0) then
delete(Result, 1, 5);
if (length(Result) > 120) then
SetLength(Result, 120);
// Truncate at first slash
i := pos('/', Result);
if (i > 0) then
SetLength(Result, i-1);
// Replace invalids with spaces.
// If string starts with invalids, they are trimmed.
LastInvalid := True;
for i := length(Result) downto 1 do
if (Result[i] in Invalids) then
begin
if (not LastInvalid) then
begin
Result[i] := ' ';
LastInvalid := True;
end else
// Repeating invalids are trimmed.
Delete(Result, i, 1);
end else
LastInvalid := False;
if Result = '' then
Result := 'untitled';
Result := Result+InternetShortcutExt;
end;
function IsHTML(const s: string): boolean;
begin
Result := (pos('<HTML>', Uppercase(s)) > 0);
end;
function MakeHTML(const s: string): string;
begin
{ TODO -oanme -cImprovement : Needs to escape special chars in text to HTML conversion. }
{ TODO -oanme -cImprovement : Needs better text to HTML conversion. }
if (not IsHTML(s)) then
Result := '<HTML>'#13#10'<BODY>'#13#10 + s + #13#10'</BODY>'#13#10'</HTML>'
else
Result := s;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TURLClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_URL: TClipFormat = 0;
function TURLClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_URL = 0) then
CF_URL := RegisterClipboardFormat(CFSTR_SHELLURL);
Result := CF_URL;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TNetscapeBookmarkClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_NETSCAPEBOOKMARK: TClipFormat = 0;
function TNetscapeBookmarkClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_NETSCAPEBOOKMARK = 0) then
CF_NETSCAPEBOOKMARK := RegisterClipboardFormat('Netscape Bookmark'); // *** DO NOT LOCALIZE ***
Result := CF_NETSCAPEBOOKMARK;
end;
function TNetscapeBookmarkClipboardFormat.GetSize: integer;
begin
Result := 0;
if (FURL <> '') then
begin
inc(Result, 1024);
if (FTitle <> '') then
inc(Result, 1024);
end;
end;
function TNetscapeBookmarkClipboardFormat.ReadData(Value: pointer;
Size: integer): boolean;
begin
// Note: No check for missing string terminator!
FURL := PChar(Value);
if (Size > 1024) then
begin
inc(PChar(Value), 1024);
FTitle := PChar(Value);
end;
Result := True;
end;
function TNetscapeBookmarkClipboardFormat.WriteData(Value: pointer;
Size: integer): boolean;
begin
StrLCopy(Value, PChar(FURL), Size);
dec(Size, 1024);
if (Size > 0) and (FTitle <> '') then
begin
inc(PChar(Value), 1024);
StrLCopy(Value, PChar(FTitle), Size);
end;
Result := True;
end;
procedure TNetscapeBookmarkClipboardFormat.Clear;
begin
FURL := '';
FTitle := '';
end;
////////////////////////////////////////////////////////////////////////////////
//
// TNetscapeImageClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_NETSCAPEIMAGE: TClipFormat = 0;
function TNetscapeImageClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_NETSCAPEIMAGE = 0) then
CF_NETSCAPEIMAGE := RegisterClipboardFormat('Netscape Image Format');
Result := CF_NETSCAPEIMAGE;
end;
type
TNetscapeImageRec = record
Size ,
_Unknown1 ,
Width ,
Height ,
HorMargin ,
VerMargin ,
Border ,
OfsLowRes ,
OfsTitle ,
OfsURL ,
OfsExtra : DWORD
end;
PNetscapeImageRec = ^TNetscapeImageRec;
function TNetscapeImageClipboardFormat.GetSize: integer;
begin
Result := SizeOf(TNetscapeImageRec);
inc(Result, Length(FImage)+1);
if (FLowRes <> '') then
inc(Result, Length(FLowRes)+1);
if (FTitle <> '') then
inc(Result, Length(FTitle)+1);
if (FUrl <> '') then
inc(Result, Length(FUrl)+1);
if (FExtra <> '') then
inc(Result, Length(FExtra)+1);
end;
function TNetscapeImageClipboardFormat.ReadData(Value: pointer;
Size: integer): boolean;
begin
Result := (Size > SizeOf(TNetscapeImageRec));
if (Result) then
begin
FWidth := PNetscapeImageRec(Value)^.Width;
FHeight := PNetscapeImageRec(Value)^.Height;
FImage := PChar(Value) + SizeOf(TNetscapeImageRec);
if (PNetscapeImageRec(Value)^.OfsLowRes <> 0) then
FLowRes := PChar(Value) + PNetscapeImageRec(Value)^.OfsLowRes;
if (PNetscapeImageRec(Value)^.OfsTitle <> 0) then
FTitle := PChar(Value) + PNetscapeImageRec(Value)^.OfsTitle;
if (PNetscapeImageRec(Value)^.OfsURL <> 0) then
FUrl := PChar(Value) + PNetscapeImageRec(Value)^.OfsUrl;
if (PNetscapeImageRec(Value)^.OfsExtra <> 0) then
FExtra := PChar(Value) + PNetscapeImageRec(Value)^.OfsExtra;
end;
end;
function TNetscapeImageClipboardFormat.WriteData(Value: pointer;
Size: integer): boolean;
var
NetscapeImageRec : PNetscapeImageRec;
begin
Result := (Size > SizeOf(TNetscapeImageRec));
if (Result) then
begin
NetscapeImageRec := PNetscapeImageRec(Value);
NetscapeImageRec^.Width := FWidth;
NetscapeImageRec^.Height := FHeight;
inc(PChar(Value), SizeOf(TNetscapeImageRec));
dec(Size, SizeOf(TNetscapeImageRec));
StrLCopy(Value, PChar(FImage), Size);
dec(Size, Length(FImage)+1);
if (Size <= 0) then
exit;
if (FLowRes <> '') then
begin
StrLCopy(Value, PChar(FLowRes), Size);
NetscapeImageRec^.OfsLowRes := integer(Value) - integer(NetscapeImageRec);
dec(Size, Length(FLowRes)+1);
inc(PChar(Value), Length(FLowRes)+1);
if (Size <= 0) then
exit;
end;
if (FTitle <> '') then
begin
StrLCopy(Value, PChar(FTitle), Size);
NetscapeImageRec^.OfsTitle := integer(Value) - integer(NetscapeImageRec);
dec(Size, Length(FTitle)+1);
inc(PChar(Value), Length(FTitle)+1);
if (Size <= 0) then
exit;
end;
if (FUrl <> '') then
begin
StrLCopy(Value, PChar(FUrl), Size);
NetscapeImageRec^.OfsUrl := integer(Value) - integer(NetscapeImageRec);
dec(Size, Length(FUrl)+1);
inc(PChar(Value), Length(FUrl)+1);
if (Size <= 0) then
exit;
end;
if (FExtra <> '') then
begin
StrLCopy(Value, PChar(FExtra), Size);
NetscapeImageRec^.OfsExtra := integer(Value) - integer(NetscapeImageRec);
dec(Size, Length(FExtra)+1);
inc(PChar(Value), Length(FExtra)+1);
if (Size <= 0) then
exit;
end;
end;
end;
procedure TNetscapeImageClipboardFormat.Clear;
begin
FURL := '';
FTitle := '';
FImage := '';
FLowRes := '';
FExtra := '';
FHeight := 0;
FWidth := 0;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TVCardClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_VCARD: TClipFormat = 0;
function TVCardClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_VCARD = 0) then
CF_VCARD := RegisterClipboardFormat('+//ISBN 1-887687-00-9::versit::PDI//vCard'); // *** DO NOT LOCALIZE ***
Result := CF_VCARD;
end;
function TVCardClipboardFormat.GetSize: integer;
var
i : integer;
begin
if (Items.Count > 0) then
begin
Result := 22; // Length('begin:vcard'+#13+'end:vcard'+#0);
for i := 0 to Items.Count-1 do
inc(Result, Length(Items[i])+1);
end else
Result := 0;
end;
function TVCardClipboardFormat.ReadData(Value: pointer; Size: integer): boolean;
var
i : integer;
s : string;
begin
Result := inherited ReadData(Value, Size);
if (Result) then
begin
// Zap vCard header and trailer
if (Items.Count > 0) and (CompareText(Items[0], 'begin:vcard') = 0) then
Items.Delete(0);
if (Items.Count > 0) and (CompareText(Items[Items.Count-1], 'end:vcard') = 0) then
Items.Delete(Items.Count-1);
// Convert to item/value list
for i := 0 to Items.Count-1 do
if (pos(':', Items[i]) > 0) then
begin
s := Items[i];
s[pos(':', Items[i])] := '=';
Items[i] := s;
end;
end;
end;
function DOSStringToUnixString(dos: string): string;
var
s, d : PChar;
l : integer;
begin
SetLength(Result, Length(dos)+1);
s := PChar(dos);
d := PChar(Result);
l := 1;
while (s^ <> #0) do
begin
// Ignore LF
if (s^ <> #10) then
begin
d^ := s^;
inc(l);
inc(d);
end;
inc(s);
end;
SetLength(Result, l);
end;
function TVCardClipboardFormat.WriteData(Value: pointer; Size: integer): boolean;
var
s : string;
begin
Result := (Items.Count > 0);
if (Result) then
begin
s := DOSStringToUnixString('begin:vcard'+#13+Items.Text+#13+'end:vcard');
StrLCopy(Value, PChar(s), Size);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// THTMLClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_HTML: TClipFormat = 0;
function THTMLClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_HTML = 0) then
CF_HTML := RegisterClipboardFormat('HTML Format');
Result := CF_HTML;
end;
function THTMLClipboardFormat.HasData: boolean;
begin
Result := inherited HasData and IsHTML(HTML.Text);
end;
function THTMLClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
Result := True;
if (Source is TTextDataFormat) then
HTML.Text := MakeHTML(TTextDataFormat(Source).Text)
else
Result := inherited Assign(Source);
end;
function THTMLClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
Result := True;
if (Dest is TTextDataFormat) then
TTextDataFormat(Dest).Text := HTML.Text
else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TRFC822ClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_RFC822: TClipFormat = 0;
function TRFC822ClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_RFC822 = 0) then
CF_RFC822 := RegisterClipboardFormat('Internet Message (rfc822/rfc1522)'); // *** DO NOT LOCALIZE ***
Result := CF_RFC822;
end;
function TRFC822ClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
Result := True;
if (Source is TTextDataFormat) then
Text.Text := TTextDataFormat(Source).Text
else
Result := inherited Assign(Source);
end;
function TRFC822ClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
Result := True;
if (Dest is TTextDataFormat) then
TTextDataFormat(Dest).Text := Text.Text
else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TURLDataFormat
//
////////////////////////////////////////////////////////////////////////////////
function TURLDataFormat.Assign(Source: TClipboardFormat): boolean;
var
s : string;
begin
Result := False;
(*
** TURLClipboardFormat
*)
if (Source is TURLClipboardFormat) then
begin
if (FURL = '') then
FURL := TURLClipboardFormat(Source).URL;
Result := True;
end else
(*
** TTextClipboardFormat
*)
if (Source is TTextClipboardFormat) then
begin
if (FURL = '') then
begin
s := TTextClipboardFormat(Source).Text;
// Convert from text if the string looks like an URL
if (pos('://', s) > 1) then
begin
FURL := s;
Result := True;
end;
end;
end else
(*
** TFileClipboardFormat
*)
if (Source is TFileClipboardFormat) then
begin
if (FURL = '') then
begin
s := TFileClipboardFormat(Source).Files[0];
// Convert from Internet Shortcut file format.
if (CompareText(ExtractFileExt(s), InternetShortcutExt) = 0) and
(GetURLFromFile(s, FURL)) then
begin
if (FTitle = '') then
FTitle := ChangeFileExt(ExtractFileName(s), '');
Result := True;
end;
end;
end else
(*
** TFileContentsClipboardFormat
*)
if (Source is TFileContentsClipboardFormat) then
begin
if (FURL = '') then
begin
s := TFileContentsClipboardFormat(Source).Data;
Result := GetURLFromString(s, FURL);
end;
end else
(*
** TFileGroupDescritorClipboardFormat
*)
if (Source is TFileGroupDescritorClipboardFormat) then
begin
if (FTitle = '') then
begin
if (TFileGroupDescritorClipboardFormat(Source).FileGroupDescriptor^.cItems > 0) then
begin
// Extract the title of an Internet Shortcut
s := TFileGroupDescritorClipboardFormat(Source).FileGroupDescriptor^.fgd[0].cFileName;
if (CompareText(ExtractFileExt(s), InternetShortcutExt) = 0) then
begin
FTitle := ChangeFileExt(s, '');
Result := True;
end;
end;
end;
end else
(*
** TNetscapeBookmarkClipboardFormat
*)
if (Source is TNetscapeBookmarkClipboardFormat) then
begin
if (FURL = '') then
FURL := TNetscapeBookmarkClipboardFormat(Source).URL;
if (FTitle = '') then
FTitle := TNetscapeBookmarkClipboardFormat(Source).Title;
Result := True;
end else
(*
** TNetscapeImageClipboardFormat
*)
if (Source is TNetscapeImageClipboardFormat) then
begin
if (FURL = '') then
FURL := TNetscapeImageClipboardFormat(Source).URL;
if (FTitle = '') then
FTitle := TNetscapeImageClipboardFormat(Source).Title;
Result := True;
end else
Result := inherited Assign(Source);
end;
function TURLDataFormat.AssignTo(Dest: TClipboardFormat): boolean;
var
FGD : TFileGroupDescriptor;
s : string;
begin
Result := True;
(*
** TURLClipboardFormat
*)
if (Dest is TURLClipboardFormat) then
begin
TURLClipboardFormat(Dest).URL := FURL;
end else
(*
** TTextClipboardFormat
*)
if (Dest is TTextClipboardFormat) then
begin
TTextClipboardFormat(Dest).Text := FURL;
end else
(*
** TFileContentsClipboardFormat
*)
if (Dest is TFileContentsClipboardFormat) then
begin
TFileContentsClipboardFormat(Dest).Data := InternetShortcut + #13#10 +
'URL='+FURL + #13#10;
end else
(*
** TFileGroupDescritorClipboardFormat
*)
if (Dest is TFileGroupDescritorClipboardFormat) then
begin
FillChar(FGD, SizeOf(FGD), 0);
FGD.cItems := 1;
if (FTitle = '') then
s := FURL
else
s := FTitle;
StrLCopy(@FGD.fgd[0].cFileName[0], PChar(ConvertURLToFilename(s)),
SizeOf(FGD.fgd[0].cFileName));
FGD.fgd[0].dwFlags := FD_LINKUI;
TFileGroupDescritorClipboardFormat(Dest).CopyFrom(@FGD);
end else
(*
** TNetscapeBookmarkClipboardFormat
*)
if (Dest is TNetscapeBookmarkClipboardFormat) then
begin
TNetscapeBookmarkClipboardFormat(Dest).URL := FURL;
TNetscapeBookmarkClipboardFormat(Dest).Title := FTitle;
end else
(*
** TNetscapeImageClipboardFormat
*)
if (Dest is TNetscapeImageClipboardFormat) then
begin
TNetscapeImageClipboardFormat(Dest).URL := FURL;
TNetscapeImageClipboardFormat(Dest).Title := FTitle;
end else
Result := inherited AssignTo(Dest);
end;
procedure TURLDataFormat.Clear;
begin
Changing;
FURL := '';
FTitle := '';
end;
procedure TURLDataFormat.SetTitle(const Value: string);
begin
Changing;
FTitle := Value;
end;
procedure TURLDataFormat.SetURL(const Value: string);
begin
Changing;
FURL := Value;
end;
function TURLDataFormat.HasData: boolean;
begin
Result := (FURL <> '') or (FTitle <> '');
end;
function TURLDataFormat.NeedsData: boolean;
begin
Result := (FURL = '') or (FTitle = '');
end;
////////////////////////////////////////////////////////////////////////////////
//
// THTMLDataFormat
//
////////////////////////////////////////////////////////////////////////////////
function THTMLDataFormat.Assign(Source: TClipboardFormat): boolean;
begin
Result := True;
if (Source is THTMLClipboardFormat) then
FHTML.Assign(THTMLClipboardFormat(Source).HTML)
else
Result := inherited Assign(Source);
end;
function THTMLDataFormat.AssignTo(Dest: TClipboardFormat): boolean;
begin
Result := True;
if (Dest is THTMLClipboardFormat) then
THTMLClipboardFormat(Dest).HTML.Assign(FHTML)
else
Result := inherited AssignTo(Dest);
end;
procedure THTMLDataFormat.Clear;
begin
Changing;
FHTML.Clear;
end;
constructor THTMLDataFormat.Create(AOwner: TDragDropComponent);
begin
inherited Create(AOwner);
FHTML := TStringList.Create;
end;
destructor THTMLDataFormat.Destroy;
begin
FHTML.Free;
inherited Destroy;
end;
function THTMLDataFormat.HasData: boolean;
begin
Result := (FHTML.Count > 0);
end;
function THTMLDataFormat.NeedsData: boolean;
begin
Result := (FHTML.Count = 0);
end;
procedure THTMLDataFormat.SetHTML(const Value: TStrings);
begin
FHTML.Assign(Value);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TOutlookMailDataFormat
//
////////////////////////////////////////////////////////////////////////////////
constructor TOutlookMailDataFormat.Create(AOwner: TDragDropComponent);
begin
inherited Create(AOwner);
FStorages := TStorageInterfaceList.Create;
FStorages.OnChanging := DoOnChanging;
end;
destructor TOutlookMailDataFormat.Destroy;
begin
Clear;
FStorages.Free;
inherited Destroy;
end;
procedure TOutlookMailDataFormat.Clear;
begin
Changing;
FStorages.Clear;
end;
function TOutlookMailDataFormat.Assign(Source: TClipboardFormat): boolean;
begin
Result := True;
if (Source is TFileContentsStorageClipboardFormat) then
FStorages.Assign(TFileContentsStorageClipboardFormat(Source).Storages)
else
Result := inherited Assign(Source);
end;
function TOutlookMailDataFormat.AssignTo(Dest: TClipboardFormat): boolean;
begin
Result := True;
if (Dest is TFileContentsStorageClipboardFormat) then
TFileContentsStorageClipboardFormat(Dest).Storages.Assign(FStorages)
else
Result := inherited AssignTo(Dest);
end;
function TOutlookMailDataFormat.HasData: boolean;
begin
Result := (FStorages.Count > 0);
end;
function TOutlookMailDataFormat.NeedsData: boolean;
begin
Result := (FStorages.Count = 0);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropURLTarget
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropURLTarget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DragTypes := [dtCopy, dtLink];
GetDataOnEnter := True;
FURLFormat := TURLDataFormat.Create(Self);
end;
destructor TDropURLTarget.Destroy;
begin
FURLFormat.Free;
inherited Destroy;
end;
function TDropURLTarget.GetTitle: string;
begin
Result := FURLFormat.Title;
end;
function TDropURLTarget.GetURL: string;
begin
Result := FURLFormat.URL;
end;
function TDropURLTarget.GetPreferredDropEffect: LongInt;
begin
Result := GetPreferredDropEffect;
if (Result = DROPEFFECT_NONE) then
Result := DROPEFFECT_LINK;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropURLSource
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropURLSource.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DragTypes := [dtCopy, dtLink];
PreferredDropEffect := DROPEFFECT_LINK;
FURLFormat := TURLDataFormat.Create(Self);
end;
destructor TDropURLSource.Destroy;
begin
FURLFormat.Free;
inherited Destroy;
end;
function TDropURLSource.GetTitle: string;
begin
Result := FURLFormat.Title;
end;
procedure TDropURLSource.SetTitle(const Value: string);
begin
FURLFormat.Title := Value;
end;
function TDropURLSource.GetURL: string;
begin
Result := FURLFormat.URL;
end;
procedure TDropURLSource.SetURL(const Value: string);
begin
FURLFormat.URL := Value;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Initialization/Finalization
//
////////////////////////////////////////////////////////////////////////////////
initialization
// Data format registration
TURLDataFormat.RegisterDataFormat;
THTMLDataFormat.RegisterDataFormat;
// Clipboard format registration
TURLDataFormat.RegisterCompatibleFormat(TNetscapeBookmarkClipboardFormat, 0, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TNetscapeImageClipboardFormat, 1, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TFileContentsClipboardFormat, 2, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TFileGroupDescritorClipboardFormat, 2, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TURLClipboardFormat, 2, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TTextClipboardFormat, 3, csSourceTarget, [ddRead]);
TURLDataFormat.RegisterCompatibleFormat(TFileClipboardFormat, 4, [csTarget], [ddRead]);
THTMLDataFormat.RegisterCompatibleFormat(THTMLClipboardFormat, 0, csSourceTarget, [ddRead]);
TTextDataFormat.RegisterCompatibleFormat(TRFC822ClipboardFormat, 1, csSourceTarget, [ddRead]);
TTextDataFormat.RegisterCompatibleFormat(THTMLClipboardFormat, 2, csSourceTarget, [ddRead]);
finalization
// Clipboard format unregistration
TNetscapeBookmarkClipboardFormat.UnregisterClipboardFormat;
TNetscapeImageClipboardFormat.UnregisterClipboardFormat;
TURLClipboardFormat.UnregisterClipboardFormat;
TVCardClipboardFormat.UnregisterClipboardFormat;
THTMLClipboardFormat.UnregisterClipboardFormat;
TRFC822ClipboardFormat.UnregisterClipboardFormat;
// Target format unregistration
TURLDataFormat.UnregisterDataFormat;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://localhost:8082/wsdl/IClientsTalking
// >Import : http://localhost:8082/wsdl/IClientsTalking>0
// Version : 1.0
// (07.07.2016 15:04:40 - - $Rev: 86412 $)
// ************************************************************************ //
unit IClientsTalking1;
interface
uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:boolean - "http://www.w3.org/2001/XMLSchema"[]
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
TClientServ = class; { "urn:uClientsTalkingIntf"[GblCplx] }
ClientsArray = array of TClientServ; { "urn:uClientsTalkingIntf"[GblCplx] }
// ************************************************************************ //
// XML : TClientServ, global, <complexType>
// Namespace : urn:uClientsTalkingIntf
// ************************************************************************ //
TClientServ = class(TRemotable)
private
FId: string;
FFIO: string;
FAdress: string;
FPhone: string;
FPhoto: string;
FDataTime: string;
published
property Id: string read FId write FId;
property FIO: string read FFIO write FFIO;
property Adress: string read FAdress write FAdress;
property Phone: string read FPhone write FPhone;
property Photo: string read FPhoto write FPhoto;
property DataTime: string read FDataTime write FDataTime;
end;
// ************************************************************************ //
// Namespace : urn:uClientsTalkingIntf-IClientsTalking
// soapAction: urn:uClientsTalkingIntf-IClientsTalking#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// use : encoded
// binding : IClientsTalkingbinding
// service : IClientsTalkingservice
// port : IClientsTalkingPort
// URL : http://localhost:8082/soap/IClientsTalking
// ************************************************************************ //
IClientsTalking = interface(IInvokable)
['{25D915D6-8010-70E9-6A5C-34F302D4FA18}']
procedure Update(const Item: TClientServ); stdcall;
procedure Delete(const Id: string); stdcall;
procedure AddClientInBd(const Item: TClientServ); stdcall;
function LoadClients: ClientsArray; stdcall;
procedure DeleteDataFromTable; stdcall;
procedure UpdateOrInsert(const Item: TClientServ); stdcall;
function LogIn(const name_: string; const password: string)
: Boolean; stdcall;
procedure Autorisation(const name_: string;
const password: string); stdcall;
function CheckUser(const name_: string): Boolean; stdcall;
function SelectUser(const Id: string): Boolean; stdcall;
function SelectClient(const Id: string): TClientServ; stdcall;
end;
function GetIClientsTalking(UseWSDL: Boolean = System.False; Addr: string = '';
HTTPRIO: THTTPRIO = nil): IClientsTalking;
implementation
uses System.SysUtils;
function GetIClientsTalking(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO)
: IClientsTalking;
const
defWSDL = 'http://192.168.38.129:8082/wsdl/IClientsTalking';
defURL = 'http://192.168.38.129:8082/soap/IClientsTalking';
defSvc = 'IClientsTalkingservice';
defPrt = 'IClientsTalkingPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as IClientsTalking);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end
else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
{ IClientsTalking }
InvRegistry.RegisterInterface(TypeInfo(IClientsTalking),
'urn:uClientsTalkingIntf-IClientsTalking', '');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IClientsTalking),
'urn:uClientsTalkingIntf-IClientsTalking#%operationName%');
{ IClientsTalking.LogIn }
InvRegistry.RegisterParamInfo(TypeInfo(IClientsTalking), 'LogIn', 'name_',
'name', '');
{ IClientsTalking.Autorisation }
InvRegistry.RegisterParamInfo(TypeInfo(IClientsTalking), 'Autorisation',
'name_', 'name', '');
{ IClientsTalking.CheckUser }
InvRegistry.RegisterParamInfo(TypeInfo(IClientsTalking), 'CheckUser', 'name_',
'name', '');
RemClassRegistry.RegisterXSInfo(TypeInfo(ClientsArray),
'urn:uClientsTalkingIntf', 'ClientsArray');
RemClassRegistry.RegisterXSClass(TClientServ, 'urn:uClientsTalkingIntf',
'TClientServ');
end.
|
unit ANovaCondicaoPagamento;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, DBKeyViolation, constantes,
ComCtrls, Grids, CGrades, Mask, numericos, UnDadosCR, UnCondicaoPagamento,
Localizacao;
type
TFNovaCondicaoPagamento = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
BFechar: TBitBtn;
ValidaGravacao1: TValidaGravacao;
Paginas: TPageControl;
PGeral: TTabSheet;
PParcela1: TTabSheet;
PanelColor3: TPanelColor;
ENome: TEditColor;
Label1: TLabel;
EQtdParcelas: Tnumerico;
Label2: TLabel;
GPercentual: TRBStringGridColor;
Label3: TLabel;
PParcela: TPanelColor;
Label4: TLabel;
RadioButton1: TRadioButton;
COpcao2: TRadioButton;
Label5: TLabel;
COpcao3: TRadioButton;
COpcao4: TRadioButton;
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
Label7: TLabel;
Label8: TLabel;
EQtdDias: Tnumerico;
LTexto3: TLabel;
LTexto31: TLabel;
EDiaFixo: Tnumerico;
LTexto4: TLabel;
LTexto41: TLabel;
LTexto42: TLabel;
LTexto43: TLabel;
EDatFixa: TMaskEditColor;
Label14: TLabel;
numerico2: Tnumerico;
Panel1: TPanelColor;
RadioButton5: TRadioButton;
RadioButton6: TRadioButton;
Label6: TLabel;
Label9: TLabel;
EFormaPagamento: TRBEditLocaliza;
SpeedButton4: TSpeedButton;
Label10: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure EQtdParcelasExit(Sender: TObject);
procedure EQtdParcelasKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GPercentualCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GPercentualDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GPercentualMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure COpcao2Click(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure ENomeChange(Sender: TObject);
private
{ Private declarations }
VprAcao : Boolean;
VprOperacao : TRBDOperacaoCadastro;
VprDCondicaoPagamento : TRBDCondicaoPagamento;
VprDPercentual : TRBDParcelaCondicaoPagamento;
FunCondicaoPagamento : TRBFuncoesCondicaoPagamento;
procedure HabilitaCampos(VpaDono : TWinControl);
procedure EstadoBotoes(VpaEstado : boolean);
procedure InicializaTela;
procedure CarTitulosGrade;
procedure CriaParcelas;
procedure CriaPaginasParcelas(VpaQtdParcelas : Integer);
procedure CarDClasse;
procedure CarDParcelas;
procedure CarDTela;
procedure CarDParcelaTela;
public
{ Public declarations }
function NovaCondicaoPagamento: boolean;
function AlteraCondicaoPagamento(VpaCodCondicaoPagamento : Integer):Boolean;
end;
var
FNovaCondicaoPagamento: TFNovaCondicaoPagamento;
implementation
uses APrincipal, FunObjeto, ConstMsg, FunString;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovaCondicaoPagamento.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
FunCondicaoPagamento := TRBFuncoesCondicaoPagamento.cria(FPrincipal.BaseDados);
VprAcao := false;
CarTitulosGrade;
VprDCondicaoPagamento := TRBDCondicaoPagamento.cria;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.GPercentualCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDPercentual := TRBDParcelaCondicaoPagamento(VprDCondicaoPagamento.Parcelas.Items[VpaLinha-1]);
GPercentual.Cells[1,VpaLinha]:= InttoStr(VprDPercentual.NumParcela);
GPercentual.Cells[2,VpaLinha]:= FormatFloat('0.00',VprDPercentual.PerParcela);
end;
procedure TFNovaCondicaoPagamento.GPercentualDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
var
VpfLinhaAtual : Integer;
begin
VpfLinhaAtual := GPercentual.Row;
VpaValidos := true;
if (GPercentual.Cells[2,GPercentual.ALinha] = '') then
begin
VpaValidos := false;
aviso('PERCENTUAL NÃO PREENCHIDO!!!'#13'É necessário preencher o percentual da parcela');
GPercentual.Col := 2;
end;
if VpaValidos then
begin
VprDPercentual.PerParcela := StrToFloat(DeletaChars(GPercentual.Cells[2,GPercentual.ALinha],'.'));
if VprDPercentual.PerParcela = 0 then
begin
VpaValidos := false;
aviso('PERCENTUAL NÃO PREENCHIDO!!!'#13'É necessário preencher o percentual da parcela');
GPercentual.Col := 2;
end;
if VpaValidos then
begin
FunCondicaoPagamento.VerificaPercentuais(VprDCondicaoPagamento);
GPercentual.CarregaGrade;
GPercentual.Row := VpfLinhaAtual;
end;
end;
end;
procedure TFNovaCondicaoPagamento.GPercentualMudouLinha(Sender: TObject;
VpaLinhaAtual, VpaLinhaAnterior: Integer);
begin
if VprDCondicaoPagamento.Parcelas.Count >0 then
VprDPercentual := TRBDParcelaCondicaoPagamento(VprDCondicaoPagamento.Parcelas.Items[VpaLinhaAtual-1]);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovaCondicaoPagamento.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
VprDCondicaoPagamento.Free;
FunCondicaoPagamento.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
function TFNovaCondicaoPagamento.AlteraCondicaoPagamento(VpaCodCondicaoPagamento: Integer): Boolean;
begin
VprDCondicaoPagamento.Free;
VprDCondicaoPagamento :=TRBDCondicaoPagamento.cria;
FunCondicaoPagamento.CarDCondicaoPagamento(VprDCondicaoPagamento,VpaCodCondicaoPagamento);
GPercentual.ADados := VprDCondicaoPagamento.Parcelas;
GPercentual.CarregaGrade;
CarDTela;
showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.BCancelarClick(Sender: TObject);
begin
VprAcao := false;
Close;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.BFecharClick(Sender: TObject);
begin
close;
end;
procedure TFNovaCondicaoPagamento.BGravarClick(Sender: TObject);
var
VpfResultado : string;
begin
CarDClasse;
VpfResultado := FunCondicaoPagamento.GravaDCondicaoPagamento(VprDCondicaoPagamento);
if VpfResultado <> '' then
begin
aviso(VpfResultado);
if VprOperacao = ocInsercao then
VprDCondicaoPagamento.CodCondicaoPagamento := 0;
end
else
begin
VprAcao := true;
close;
end;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.ENomeChange(Sender: TObject);
begin
if VprOperacao in [ocinsercao,ocedicao] then
ValidaGravacao1.execute;
end;
procedure TFNovaCondicaoPagamento.EQtdParcelasExit(Sender: TObject);
begin
CriaParcelas;
end;
procedure TFNovaCondicaoPagamento.EQtdParcelasKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = 13 then
CriaParcelas;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.HabilitaCampos(VpaDono : TWinControl);
var
VpfNumerico : TNumerico;
VpfCheckBox : TCheckBox;
VpfMaskEdit : TMaskEditColor;
begin
//opcao 1
VpfCheckBox := TCheckBox(LocalizaComponente(VpaDono,2));
VpfCheckBox.Enabled := TRadioButton(LocalizaComponente(VpaDono,1)).Checked;
VpfCheckBox.Checked := VpfCheckBox.Enabled;
TLabel(LocalizaComponente(VpaDono,3)).Enabled := VpfCheckBox.Enabled;
TLabel(LocalizaComponente(VpaDono,4)).Enabled := VpfCheckBox.Enabled;
//opcao 2
VpfNumerico := TNumerico(LocalizaComponente(VpaDono,11));
VpfNumerico.Enabled := TRadioButton(LocalizaComponente(VpaDono,10)).Checked;
if not VpfNumerico.Enabled then
VpfNumerico.clear;
TLabel(LocalizaComponente(VpaDono,12)).Enabled := VpfNumerico.Enabled;
TLabel(LocalizaComponente(VpaDono,13)).Enabled := VpfNumerico.Enabled;
//opcao 3
VpfNumerico := TNumerico(LocalizaComponente(VpaDono,21));
VpfNumerico.Enabled := TRadioButton(LocalizaComponente(VpaDono,20)).Checked;
if not VpfNumerico.Enabled then
VpfNumerico.clear;
TLabel(LocalizaComponente(VpaDono,22)).Enabled := VpfNumerico.Enabled;
TLabel(LocalizaComponente(VpaDono,23)).Enabled := VpfNumerico.Enabled;
//opcao 4
VpfMaskEdit := TMaskEditColor(LocalizaComponente(VpaDono,31));
VpfMaskEdit.Enabled := TRadioButton(LocalizaComponente(VpaDono,30)).Checked;
if not VpfMaskEdit.Enabled then
VpfMaskEdit.clear;
TLabel(LocalizaComponente(VpaDono,32)).Enabled := VpfMaskEdit.Enabled;
TLabel(LocalizaComponente(VpaDono,33)).Enabled := VpfMaskEdit.Enabled;
TLabel(LocalizaComponente(VpaDono,34)).Enabled := VpfMaskEdit.Enabled;
TLabel(LocalizaComponente(VpaDono,35)).Enabled := VpfMaskEdit.Enabled;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.EstadoBotoes(VpaEstado : boolean);
begin
BGravar.Enabled := VpaEstado;
BCancelar.Enabled := VpaEstado;
BFechar.Enabled := not VpaEstado;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.InicializaTela;
begin
EstadoBotoes(true);
VprDCondicaoPagamento.free;
VprDCondicaoPagamento := TRBDCondicaoPagamento.cria;
GPercentual.ADados := VprDCondicaoPagamento.Parcelas;
GPercentual.CarregaGrade;
LimpaComponentes(PanelColor1,0);
EQtdParcelas.AsInteger := 1;
CriaParcelas;
Paginas.ActivePage := PGeral;
ActiveControl := ENome;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CarDClasse;
begin
with VprDCondicaoPagamento do
begin
NomCondicaoPagamento := ENome.Text;
QtdParcelas := EQtdParcelas.AsInteger;
end;
CarDParcelas;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CarDParcelas;
Var
Vpflaco : Integer;
VpfPagina : TTabSheet;
VpfDParcela : TRBDParcelaCondicaoPagamento;
VpfNumerico : TNumerico;
VpfMaskEdit : TMaskEditColor;
begin
for VpfLaco := 1 to Paginas.PageCount - 1 do
begin
VpfDParcela := TRBDParcelaCondicaoPagamento(VprDCondicaoPagamento.Parcelas.Items[VpfLaco - 1]);
VpfPagina := Paginas.Pages[VpfLaco];
if TCheckBox(LocalizaComponente(VpfPagina,1)).Checked then
begin
VpfDParcela.TipoParcela := tpProximoMes;
VpfDParcela.DiaFixo := 100;
end
else
if TCheckBox(LocalizaComponente(VpfPagina,10)).Checked then
begin
VpfDParcela.TipoParcela := tpQtdDias;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,11));
VpfDParcela.QtdDias := VpfNumerico.AsInteger;
end
else
if TCheckBox(LocalizaComponente(VpfPagina,20)).Checked then
begin
VpfDParcela.TipoParcela := tpDiaFixo;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,21));
VpfDParcela.DiaFixo := VpfNumerico.AsInteger;
end
else
if TCheckBox(LocalizaComponente(VpfPagina,30)).Checked then
begin
VpfDParcela.TipoParcela := tpDataFixa;
VpfDParcela.DatFixa := StrToDate(TMaskEditColor(LocalizaComponente(VpfPagina,31)).Text);
end;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,50));
VpfDParcela.PerAcrescimoDesconto := VpfNumerico.AValor;
VpfDParcela.CodFormaPagamento := TRBEditLocaliza(LocalizaComponente(VpfPagina,60)).AInteiro;
if TCheckBox(LocalizaComponente(VpfPagina,51)).Checked then
VpfDParcela.TipAcrescimoDesconto := 'C'
else
VpfDParcela.TipAcrescimoDesconto := 'D';
end;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CarDParcelaTela;
Var
Vpflaco : Integer;
VpfPagina : TTabSheet;
VpfDParcela : TRBDParcelaCondicaoPagamento;
VpfNumerico : TNumerico;
VpfMaskEdit : TMaskEditColor;
VpfEditLocaliza : TRBEditLocaliza;
begin
if VprDCondicaoPagamento.Parcelas.Count = 0 then
begin
VprDCondicaoPagamento.QtdParcelas := 0;
EQtdParcelas.AsInteger := 1;
CriaParcelas;
end;
CriaPaginasParcelas(VprDCondicaoPagamento.QtdParcelas);
for VpfLaco := 1 to VprDCondicaoPagamento.Parcelas.Count do
begin
VpfDParcela := TRBDParcelaCondicaoPagamento(VprDCondicaoPagamento.Parcelas.Items[VpfLaco - 1]);
VpfPagina := Paginas.Pages[VpfLaco];
TCheckBox(LocalizaComponente(VpfPagina,1)).Checked := false;
TCheckBox(LocalizaComponente(VpfPagina,10)).Checked := false;
TCheckBox(LocalizaComponente(VpfPagina,20)).Checked := false;
TCheckBox(LocalizaComponente(VpfPagina,30)).Checked := false;
case VpfDParcela.TipoParcela of
tpProximoMes:
begin
TCheckBox(LocalizaComponente(VpfPagina,1)).Checked := true ;
end;
tpQtdDias:
begin
TCheckBox(LocalizaComponente(VpfPagina,10)).Checked := true;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,11));
VpfNumerico.AsInteger := VpfDParcela.QtdDias;
end;
tpDiaFixo:
begin
TCheckBox(LocalizaComponente(VpfPagina,20)).Checked := true;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,21));
VpfNumerico.AsInteger := VpfDParcela.DiaFixo;
end;
tpDataFixa:
begin
TCheckBox(LocalizaComponente(VpfPagina,30)).Checked := true;
TMaskEditColor(LocalizaComponente(VpfPagina,31)).Text := FormatDateTime('DD/MM/YYYY',VpfDParcela.DatFixa);
end;
end;
VpfNumerico := TNumerico(LocalizaComponente(VpfPagina,50));
VpfNumerico.AValor := VpfDParcela.PerAcrescimoDesconto;
if VpfDParcela.TipAcrescimoDesconto = 'C' then
TCheckBox(LocalizaComponente(VpfPagina,51)).Checked := true;
VpfEditLocaliza := TRBEditLocaliza(LocalizaComponente(VpfPagina,60));
VpfEditLocaliza.AInteiro := VpfDParcela.CodFormaPagamento;
VpfEditLocaliza.Atualiza;
end;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CarDTela;
begin
with VprDCondicaoPagamento do
begin
ENome.Text := NomCondicaoPagamento;
EQtdParcelas.AsInteger := QtdParcelas;
end;
CarDParcelaTela;
Paginas.ActivePage := PGeral;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CarTitulosGrade;
begin
GPercentual.Cells[1,0] := 'Parcela';
GPercentual.Cells[2,0] := 'Percentual';
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.COpcao2Click(Sender: TObject);
begin
// HabilitaCampos(TCheckBox(sender).parent);
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CriaPaginasParcelas(VpaQtdParcelas: Integer);
var
VpfLaco : Integer;
VpfPagina : TTabSheet;
begin
for VpfLaco := Paginas.PageCount-1 downto 2 do
Paginas.Pages[VpfLaco].Destroy;
AlterarVisibleDet([COpcao3,COpcao4,EDiaFixo,LTexto3,LTexto31,LTexto4,LTexto41,LTexto42,LTexto43,EDatFixa],EQtdParcelas.AsInteger = 1);
for Vpflaco := 2 to VpaQtdParcelas do
begin
VpfPagina := TTabSheet.Create(Paginas);
Paginas.InsertControl(VpfPagina);
VpfPagina.PageControl := Paginas;
VpfPagina.Caption := 'Parcela '+ IntToStr(VpfLaco);
CopiaComponente(PParcela1,VpfPagina);
end;
end;
{******************************************************************************}
procedure TFNovaCondicaoPagamento.CriaParcelas;
begin
if VprOperacao in [ocInsercao,ocEdicao] then
begin
if EQtdParcelas.AsInteger = 0 then
begin
aviso('QUANTIDADE DE PARCELAS INVÁLIDO!!!'#13+'É necessãrio digitar no mínimo 1 parcela');
EQtdParcelas.AsInteger := VprDCondicaoPagamento.QtdParcelas;
end
else
begin
if varia.QtdParcelasCondicaoPagamento <> 0 then
begin
if EQtdParcelas.AsInteger > Varia.QtdParcelasCondicaoPagamento then
begin
aviso('QUANTIDADE DE PARCELAS INVÁLIDA!!!!'#13'É permitido no máximo "'+IntToStr(Varia.QtdParcelasCondicaoPagamento) +'" parcelas');
EQtdParcelas.AsInteger := 1;
end;
end;
if VprDCondicaoPagamento.QtdParcelas <> EQtdParcelas.AsInteger then
begin
VprDCondicaoPagamento.QtdParcelas := EQtdParcelas.AsInteger;
FunCondicaoPagamento.CriaParcelas(VprDCondicaoPagamento);
GPercentual.CarregaGrade;
CriaPaginasParcelas(VprDCondicaoPagamento.QtdParcelas);
end;
end;
end;
end;
{******************************************************************************}
function TFNovaCondicaoPagamento.NovaCondicaoPagamento: boolean;
begin
InicializaTela;
VprOperacao := ocInsercao;
showmodal;
result := VprAcao;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovaCondicaoPagamento]);
end.
|
unit classe.aluno;
interface
Uses TEntity, AttributeEntity, SysUtils;
type
[TableName('ALUNO')]
TAluno = class(TGenericEntity)
private
FIdAluno:integer;
FNome:string;
procedure setIdAluno(const Value: integer);
procedure setNome(value:string);
public
[KeyField('IDALUNO')]
[FieldName('IDALUNO')]
property Codigo: integer read FIdAluno write setIdAluno;
[FieldName('NOME')]
property Nome:string read FNome write setNome;
function ToString:string; override;
end;
implementation
procedure TAluno.setIdAluno(const Value: integer);
begin
FIdAluno := Value;
end;
procedure TAluno.setNome(value: string);
begin
FNome := Value;
end;
function TAluno.toString;
begin
result := ' Matricula: '+ IntToStr(Codigo) + ' Nome: '+ Nome;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Bindings.ExpressionDefaults;
interface
uses
System.SysUtils, System.Classes, System.Rtti, System.Generics.Collections, System.Math, System.Bindings.Consts,
System.Bindings.EvalProtocol, System.Bindings.EvalSys, System.Bindings.Evaluator, System.Bindings.ObjEval,
System.Bindings.NotifierContracts, System.Bindings.Expression, System.Bindings.Manager;
type
/// <summary>Class that implements the default behaviour for binding expressions.</summary>
TBindingExpressionDefault = class(TBindingExpression,
IScope, IScopeEx, IScopeEnumerator, IScopeSymbols,
ICompiledBinding, ICompiledBindingWrappers)
private
FBinding: ICompiledBinding;
FRootScope: IScope;
FCompiled: Boolean;
[weak] FManager: TBindingManager;
FScopeSymbols: IScopeSymbols;
FCompiledBinding: ICompiledBinding;
FPreparedWrappers: IPreparedWrappers;
function GetRootScopeEx: IScopeEx; inline;
function GetRootScopeEnumerator: IScopeEnumerator; inline;
function GetBindingWrappers: ICompiledBindingWrappers; inline;
procedure SetBinding(const ABinding: ICompiledBinding);
protected
function GetCompiled: Boolean; override;
/// <summary>Creates a scope based on the passed associations between Delphi
/// objects and expression objects.</summary>
/// <param name="Assocs">Indicates the associations between Delphi objects
/// and expression objects that are going to be added in the resultin scope.</param>
/// <returns>A scope containing the associations passed as input.</returns>
function CreateScope(const Assocs: TBindingExpression.TAssociations): IScope;
procedure Compile; overload; override;
function GetIsManaged: Boolean; override;
{ IInterface }
/// <summary>Denotes the scope of the expression that contains all the
/// wrappers for the rest of the symbols in the expression.</summary>
property RootScope: IScope read FRootScope implements IScope;
/// <summary>Delegates the implementation for supplementary scope functionality.</summary>
property RootScopeEx: IScopeEx read GetRootScopeEx implements IScopeEx;
/// <summary>Delegates the enumerator of the expression scope and makes the
/// expression enumerable in terms of wrappers.</summary>
property RootScopeEnumerator: IScopeEnumerator read GetRootScopeEnumerator implements IScopeEnumerator;
/// <summary>Delegates the implementation of IScopeSymbols to an internal object.</summary>
property ScopeSymbols: IScopeSymbols read FScopeSymbols implements IScopeSymbols;
/// <summary>The compiled binding through which evaluation of the expression can occur.</summary>
property Binding: ICompiledBinding read FCompiledBinding implements ICompiledBinding;
/// <summary>The wrappers used by the compiled binding in order to evaluate the expression.</summary>
property BindingWrappers: ICompiledBindingWrappers read GetBindingWrappers implements ICompiledBindingWrappers;
public
/// <summary>Assigning a manager doesn't mean that the expression is added
/// in the manager's list. Instances of this class should not be created
/// using directly this constructor, but using a binding manager instead.</summary>
constructor Create(Manager: TBindingManager = nil);
destructor Destroy; override;
/// <summary>The binding manager owning the expression.</summary>
property Manager: TBindingManager read FManager;
function Evaluate: IValue; override;
procedure EvaluateOutputs; override;
procedure Clear; override;
end;
implementation
uses
System.TypInfo, System.Bindings.Factories, System.Bindings.Graph;
{ TBindingExpressionDefault }
procedure TBindingExpressionDefault.Compile;
var
LScope: IScope;
LParentScope: IScope;
begin
try
// Create nested scopes as needed
LParentScope := TNestedScope.Create(BasicOperators, BasicConstants);
for LScope in FScopes do
LParentScope := TNestedScope.Create(LParentScope,
LScope);
if Associations.Count > 0 then
LParentScope := TNestedScope.Create(LParentScope,
CreateScope(Associations));
SetBinding(nil); // Clear weak references in FRootScope
FRootScope := LParentScope;
FPreparedWrappers := nil;
// compile the binding and store it
SetBinding(System.Bindings.Evaluator.Compile(Source, FRootScope));
FCompiled := True;
except on E: Exception do
begin
if Assigned(OnEvalErrorEvent) then
OnEvalErrorEvent(E);
raise;
end;
end;
end;
constructor TBindingExpressionDefault.Create(Manager: TBindingManager);
begin
// if not Assigned(Manager) then
// raise EBindingExpressionError.Create(sManagerNotFound);
// the manager must be assigned before the creation because the inherited
// constructor determines whether the outputs must notify or not based
// on the IsManaged property of the expression
FManager := Manager;
inherited Create;
FScopeSymbols := TScopeSymbols.Create;
end;
function TBindingExpressionDefault.CreateScope(const Assocs: TBindingExpression.TAssociations): IScope;
var
LScope: TDictionaryScope;
LAssocPair: TPair<TObject, String>;
begin
// add the mappings to a local and specific scope for the expression
LScope := TDictionaryScope.Create;
Result := LScope;
for LAssocPair in Assocs do
begin
// and possibly remove them on TObjectWrapper.Destroy? (with ref count)
LScope.Map.Add(LAssocPair.Value, WrapObject(LAssocPair.Key));
end;
end;
destructor TBindingExpressionDefault.Destroy;
begin
// remove the expression from its owner manager; if it fails in the constructor,
// it won't signal an error
if Assigned(FManager) then
// in destroy so use extract instead of remove
FManager.Extract(Self);
inherited;
end;
function TBindingExpressionDefault.Evaluate: IValue;
var
ResultVal: IValue;
begin
if not FCompiled then
raise EBindingExpressionError.Create(sUncompiledExpression);
try
Result := FBinding.Evaluate(FRootScope, nil, nil, FPreparedWrappers);
ResultVal := Result;
OutputValue := Result.GetValue;
SetOutputs(
function: IValue
begin
Result := ResultVal
end
);
except on E: Exception do
begin
if not (E is EAbort) and Assigned(OnEvalErrorEvent) then
OnEvalErrorEvent(E);
raise;
end;
end;
end;
procedure TBindingExpressionDefault.EvaluateOutputs;
begin
if not FCompiled then
raise EBindingExpressionError.Create(sUncompiledExpression);
SetOutputs(
function: IValue
begin
Result := FBinding.Evaluate(FRootScope, nil, nil);
end
);
end;
function TBindingExpressionDefault.GetBindingWrappers: ICompiledBindingWrappers;
begin
Supports(FBinding, ICompiledBindingWrappers, Result);
end;
function TBindingExpressionDefault.GetCompiled: Boolean;
begin
Result := FCompiled;
end;
function TBindingExpressionDefault.GetIsManaged: Boolean;
begin
Result := FManager <> nil;
end;
function TBindingExpressionDefault.GetRootScopeEnumerator: IScopeEnumerator;
begin
Supports(FRootScope, IScopeEnumerator, Result);
end;
function TBindingExpressionDefault.GetRootScopeEx: IScopeEx;
begin
Supports(FRootScope, IScopeEx, Result);
end;
procedure TBindingExpressionDefault.SetBinding(
const ABinding: ICompiledBinding);
// Clear weak references to ICompiledBinding
procedure ClearBinding(const StartScopeEnumerable: IScopeEnumerable;
const ABinding: ICompiledBinding);
var
ScopeEnumerable: IScopeEnumerable;
WrapperBinding: IWrapperBinding;
Wrapper: IInterface;
begin
if Assigned(StartScopeEnumerable) then
for Wrapper in StartScopeEnumerable do
begin
// set the owner binding of the wrapper nil if match
if Supports(Wrapper, IWrapperBinding, WrapperBinding) then
if WrapperBinding.Binding = ABinding then
WrapperBinding.SetBinding(nil);
// the wrapper contains sub-wrappers, so go in-depth
if Supports(Wrapper, IScopeEnumerable, ScopeEnumerable) then
ClearBinding(ScopeEnumerable, ABinding);
end;
end;
var
LScopeEnumerable: IScopeEnumerable;
begin
if FBinding <> nil then
if Supports(FRootScope, IScopeEnumerable, LScopeEnumerable) then
ClearBinding(LScopeEnumerable, FBinding);
FBinding := ABinding;
end;
procedure TBindingExpressionDefault.Clear;
begin
inherited;
SetBinding(nil); // Call before clear FRootScope
FRootScope := nil;
FCompiled := False;
FPreparedWrappers := nil;
end;
end.
|
// ****************************************************************************
// * mxWebUpdate Component for Delphi 5,6,7
// ****************************************************************************
// * This component can be freely used and distributed in commercial and
// * private environments, provied this notice is not modified in any way.
// ****************************************************************************
// * Feel free to contact me if you have any questions, comments or suggestions
// * at support@maxcomponents.net
// ****************************************************************************
// * Web page: www.maxcomponents.net
// ****************************************************************************
// * Description:
// *
// * TmxWebUpdate helps you to add automatic update support to your application.
// * It retrieves information from the web, if a newer version available, it
// * can download a file via HTTP and run the update.
// *
// ****************************************************************************
Unit mxWebUpdateReg;
Interface
{$I MAX.INC}
// *************************************************************************************
// ** Component registration
// *************************************************************************************
Procedure Register;
Implementation
// *************************************************************************************
// ** List of used units
// *************************************************************************************
Uses SysUtils,
Classes,
{$IFDEF Delphi6_Up}
DesignIntf,
DesignEditors,
{$ELSE}
Dsgnintf,
{$ENDIF}
Dialogs,
Forms,
mxWebUpdate,
mxWebUpdateAbout;
Type
TDesigner = IDesigner;
{$IFDEF Delphi6_Up}
TFormDesigner = IDesigner;
{$ELSE}
TFormDesigner = IFormDesigner;
{$ENDIF}
// *************************************************************************************
// ** Component Editor
// *************************************************************************************
TmxWebUpdateEditor = Class( TComponentEditor )
Function GetVerbCount: integer; Override;
Function GetVerb( Index: integer ): String; Override;
Procedure ExecuteVerb( Index: integer ); Override;
End;
// *************************************************************************************
// ** GetVerbCount
// *************************************************************************************
Function TmxWebUpdateEditor.GetVerbCount: integer;
Begin
Result := 1;
End;
// *************************************************************************************
// ** GetVerb
// *************************************************************************************
Function TmxWebUpdateEditor.GetVerb( Index: integer ): String;
Begin
Case Index Of
0: Result := 'WebUpdate (C) 2002-2008 Bitvadász Kft.';
End;
End;
// *************************************************************************************
// ** ExecuteVerb
// *************************************************************************************
Procedure TmxWebUpdateEditor.ExecuteVerb( Index: integer );
Begin
Case Index Of
0: ShowAboutBox( 'Max''s WebUpdate Component' );
End;
End;
// *************************************************************************************
// ** Register, 4/5/01 11:46:42 AM
// *************************************************************************************
Procedure Register;
Begin
RegisterComponents( 'Max', [ TmxWebUpdate ] );
RegisterComponentEditor( TmxWebUpdate, TmxWebUpdateEditor );
End;
End.
|
unit ncaPanItensVendaBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, ncMovEst, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls, cxButtons,
cxLabel, cxTextEdit, cxMemo;
type
TBotaoItemVenda = (bivRemoverItem, bivCancelarItem);
TClicouBotao = procedure (Sender: TObject; aBotao: TBotaoItemVenda) of object;
TpanItensVendaBase = class(TForm)
panPri: TLMDSimplePanel;
panTot: TLMDSimplePanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FClicouBotao : TClicouBotao;
FOnClickPagamento : TNotifyEvent;
FResgateFidelidade : Boolean;
procedure SetResgateFidelidade(const Value: Boolean);
protected
FUpdating: Integer;
function GetField(aIndex: Integer; aName: String): Variant; virtual; abstract;
procedure SetField(aIndex: Integer; aName: String; const Value: Variant); virtual; abstract;
function GetCount: Integer; virtual; abstract;
procedure SetCount(const Value: Integer); virtual; abstract;
procedure _SetResgateFidelidade; virtual;
public
TipoTran: Byte;
procedure UpdateItem(aIndex, aIDProduto: Integer; aQuant: Extended; aUnit, aTotal: Double; aCancelado: Boolean);
procedure UpdateItemMovEst(aIndex: Integer; aItem: TncItemMovEst);
property Count: Integer
read GetCount write SetCount;
function IsUpdating: Boolean;
function QuantProduto(aProduto: Integer): Double; virtual; abstract;
procedure BeginUpdate; virtual;
procedure EndUpdate; virtual;
procedure SetGap(aPixels: Integer); virtual;
procedure LoadFromItensMovEst(aItens: TncItensMovEst);
function FocusedItemIndex: Integer; virtual; abstract;
procedure DelItem(aIndex: Integer); virtual; abstract;
property ResgateFidelidade: Boolean
read FResgateFidelidade write SetResgateFidelidade;
procedure Atualiza; virtual; abstract;
procedure SetFontSize(aSize: Integer); virtual; abstract;
procedure MostrarBotao(aBotao: TBotaoItemVenda; aMostrar: Boolean); virtual;
property OnClickPagamento: TNotifyEvent
read FOnClickPagamento write FOnClickPagamento;
property OnClicouBotao: TClicouBotao
read FClicouBotao write FClicouBotao;
property Values[aIndex: Integer; aName: String]: Variant
read GetField write SetField;
{ Public declarations }
end;
var
panItensVendaBase: TpanItensVendaBase;
implementation
uses ncaDM;
{$R *.dfm}
{ TFrmPanItensVendaBase }
function VarToString(V: Variant): String;
begin
if VarIsNull(V) then
Result := '' else
Result := V;
end;
function Descr(aCodigo, aDescr: String): String;
begin
if aCodigo>'' then
Result := aCodigo+' - '+aDescr else
Result := aDescr;
end;
procedure TpanItensVendaBase.UpdateItem(aIndex, aIDProduto: Integer;
aQuant: Extended; aUnit, aTotal: Double; aCancelado: Boolean);
var aCodigo, aDescr: Variant;
begin
if aIndex=-1 then begin
aIndex := Count;
Count := Count+1;
end;
with Dados do
if (Values[aIndex, 'IDProduto']=null) or
(Values[aIndex, 'IDProduto']<>aIDProduto) then begin
aCodigo := tbPro.Lookup('ID', aIDProduto, 'Codigo');
aDescr := tbPro.Lookup('ID', aIDProduto, 'Descricao');
Values[aIndex, 'IDProduto'] := aIDProduto;
Values[aIndex, 'Codigo'] := VarToString(aCodigo)+' ';
Values[aIndex, 'Descr'] := aDescr; //Descr(VarToString(aCodigo), VarToString(aDescr));
end;
if ResgateFidelidade then begin
Values[aIndex, 'FidPontos'] := aUnit;
Values[aIndex, 'FidPontosTotal'] := aUnit*aQuant;
Values[aIndex, 'Unitario'] := 0;
Values[aIndex, 'Total'] := 0;
end else begin
Values[aIndex, 'Unitario'] := aUnit;
Values[aIndex, 'Total'] := aTotal;
Values[aIndex, 'FidPontos'] := 0;
Values[aIndex, 'FidPontosTotal'] := 0;
end;
Values[aIndex, 'Quant'] := aQuant;
Values[aIndex, 'Cancelado'] := aCancelado;
end;
procedure TpanItensVendaBase.UpdateItemMovEst(aIndex: Integer; aItem: TncItemMovEst);
begin
with aItem do
if ResgateFidelidade then
UpdateItem(aIndex, imProduto, imQuant, Trunc(imFidPontos / imQuant), aItem.imTotal, aItem.imCancelado) else
UpdateItem(aIndex, imProduto, imQuant, imUnitario, aItem.imTotal, aItem.imCancelado);
end;
procedure TpanItensVendaBase.BeginUpdate;
begin
Inc(FUpdating);
end;
procedure TpanItensVendaBase.EndUpdate;
begin
Dec(FUpdating);
end;
procedure TpanItensVendaBase.FormCreate(Sender: TObject);
begin
FOnClickPagamento := nil;
FResgateFidelidade := False;
FUpdating := 0;
FClicouBotao := nil;
end;
function TpanItensVendaBase.IsUpdating: Boolean;
begin
Result := (FUpdating>0);
end;
procedure TpanItensVendaBase.LoadFromItensMovEst(aItens: TncItensMovEst);
var I: Integer;
begin
BeginUpdate;
try
Count := aItens.Count;
for I := 0 to aItens.Count - 1 do
UpdateItemMovEst(I, aItens[i]);
finally
EndUpdate;
end;
end;
procedure TpanItensVendaBase.MostrarBotao(aBotao: TBotaoItemVenda;
aMostrar: Boolean);
begin
end;
procedure TpanItensVendaBase.SetGap(aPixels: Integer);
begin
end;
procedure TpanItensVendaBase.SetResgateFidelidade(const Value: Boolean);
begin
FResgateFidelidade := Value;
_SetResgateFidelidade;
end;
procedure TpanItensVendaBase._SetResgateFidelidade;
begin
end;
end.
|
// (c) Alex Konshin mailto:alexk@msmt.spb.su 05.01.99
unit DateComboBox;
// замена для TDateTimePicker
interface
uses
SysUtils, Windows, Classes, Messages, Graphics, Controls, ComCtrls, CommCtrl, Types;
type
{ Calendar common control support }
TCustomCalendar = class;
ECommonCalendarError = class(Exception);
TCalendarColors = class(TPersistent)
private
Owner: TCustomCalendar;
FBackColor: TColor;
FTextColor: TColor;
FTitleBackColor: TColor;
FTitleTextColor: TColor;
FMonthBackColor: TColor;
FTrailingTextColor: TColor;
procedure SetColor(Index: Integer; Value: TColor);
procedure SetAllColors;
public
constructor Create(AOwner: TCustomCalendar);
procedure Assign(Source: TPersistent); override;
published
property BackColor: TColor index 0 read FBackColor write SetColor default clWindow;
property TextColor: TColor index 1 read FTextColor write SetColor default clWindowText;
property TitleBackColor: TColor index 2 read FTitleBackColor write SetColor default clActiveCaption;
property TitleTextColor: TColor index 3 read FTitleTextColor write SetColor default clWhite;
property MonthBackColor: TColor index 4 read FMonthBackColor write SetColor default clWhite;
property TrailingTextColor: TColor index 5 read FTrailingTextColor
write SetColor default clInactiveCaptionText;
end;
TCalDayOfWeek = (dowMonday, dowTuesday, dowWednesday, dowThursday,
dowFriday, dowSaturday, dowSunday, dowLocaleDefault);
TOnGetMonthInfoEvent = procedure(Sender: TObject; Month: LongWord;
var MonthBoldInfo: LongWord) of object;
TCustomCalendar = class(TWinControl)
protected
FMaxSelectRange: Integer;
FMonthDelta, FInitMonthDelta: Integer;
FCalExceptionClass: ExceptClass;
FEndDate: TDate;
FMaxDate: TDate;
FMinDate: TDate;
FDateTime: TDateTime;
FOldDateTime: TDateTime;
FCalColors: TCalendarColors;
FOnGetMonthInfo: TOnGetMonthInfoEvent;
FFirstDayOfWeek: TCalDayOfWeek;
FOnChange: TNotifyEvent;
FMultiSelect: Boolean;
FShowToday: Boolean;
FShowTodayCircle: Boolean;
FWeekNumbers: Boolean;
function DoStoreEndDate: Boolean;
function DoStoreMaxDate: Boolean;
function DoStoreMinDate: Boolean;
function GetDate: TDate;
function GetIsChanged : Boolean; virtual;
procedure SetInitMonthDelta( Value : Integer ); virtual;
procedure SetCalColors(Value: TCalendarColors);
procedure SetDate(Value: TDate); virtual;
procedure SetDateTime(Value: TDateTime); virtual;
procedure SetEndDate(Value: TDate);
procedure SetFirstDayOfWeek(Value: TCalDayOfWeek);
procedure SetMaxDate(Value: TDate);
procedure SetMaxSelectRange(Value: Integer);
procedure SetMinDate(Value: TDate);
procedure SetMonthDelta(Value: Integer);
procedure SetMultiSelect(Value: Boolean);
procedure SetRange(MinVal, MaxVal: TDate);
procedure SetSelectedRange(Date, EndDate: TDate);
procedure SetShowToday(Value: Boolean);
procedure SetShowTodayCircle(Value: Boolean);
procedure SetWeekNumbers(Value: Boolean);
procedure CheckEmptyDate; virtual;
procedure CheckValidDate(Value: TDate); virtual;
procedure Change; virtual;
procedure ChangeDate(Value: TDate);
procedure ChangeDateTime(Value: TDateTime);
procedure CreateWnd; override;
function GetCalendarHandle: HWND; virtual; abstract;
function GetCalStyles: DWORD; virtual;
function MsgSetCalColors(ColorIndex: Integer; ColorValue: TColor): Boolean; virtual; abstract;
function MsgSetDateTime(Value: TSystemTime): Boolean; virtual; abstract;
function MsgSetRange(Flags: Integer; SysTime: PSystemTime): Boolean; virtual; abstract;
property CalColors: TCalendarColors read FCalColors write SetCalColors;
property CalendarHandle: HWND read GetCalendarHandle;
property CalExceptionClass: ExceptClass read FCalExceptionClass write FCalExceptionClass;
property Date: TDate read GetDate write SetDate;
property DateTime: TDateTime read FDateTime write SetDateTime;
property EndDate: TDate read FEndDate write SetEndDate stored DoStoreEndDate;
property FirstDayOfWeek: TCalDayOfWeek read FFirstDayOfWeek write SetFirstDayOfWeek default dowLocaleDefault;
property MaxDate: TDate read FMaxDate write SetMaxDate stored DoStoreMaxDate;
property MaxSelectRange: Integer read FMaxSelectRange write SetMaxSelectRange default 31;
property MinDate: TDate read FMinDate write SetMinDate stored DoStoreMinDate;
property MonthDelta: Integer read FMonthDelta write SetMonthDelta default 1;
property InitMonthDelta : Integer read FInitMonthDelta write SetInitMonthDelta default 0;
property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False;
property ShowToday: Boolean read FShowToday write SetShowToday default True;
property ShowTodayCircle: Boolean read FShowTodayCircle write SetShowTodayCircle default True;
property WeekNumbers: Boolean read FWeekNumbers write SetWeekNumbers default False;
property OnGetMonthInfo: TOnGetMonthInfoEvent read FOnGetMonthInfo write FOnGetMonthInfo;
property IsChanged : Boolean read GetIsChanged;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BoldDays(Days: array of LongWord; var MonthBoldInfo: LongWord);
end;
{ TDateComboBox }
EDateTimeError = class(ECommonCalendarError);
{ TDTDateMode = (dmComboBox, dmUpDown);
TDTCalAlignment = (dtaLeft, dtaRight);}
{ TDTParseInputEvent = procedure(Sender: TObject; const UserString: string; var DateAndTime: TDateTime; var AllowChange: Boolean) of object;}
TDTPKind = (dtkShortDate,dtkLongDate,dtkTime,dtkShortDateTime,dtkLongDateTime,dtkCustom);
TDateTimeColors = TCalendarColors; // for backward compatibility
TDateComboBox = class(TCustomCalendar)
protected
FCustomFormat : String;
FButtonWidth : LongInt;
FOnUserInput: TDTParseInputEvent;
FOnCloseUp: TNotifyEvent;
FOnDropDown: TNotifyEvent;
FCalAlignment: TDTCalAlignment;
FDateMode: TDTDateMode;
FKind: TDTPKind;
FLastChange: TSystemTime;
FDroppedDown,FButtonPressed: Boolean;
FParseInput: Boolean;
FShowCheckbox: Boolean;
FChanging: Boolean;
FChecked: Boolean;
FOldChecked: Boolean;
FOnClick: TNotifyEvent;
procedure AdjustHeight;
function GetTime: TTime;
procedure SetCalAlignment(Value: TDTCalAlignment);
procedure SetChecked(Value: Boolean);
procedure SetDateMode(Value: TDTDateMode);
procedure SetCustomFormat( Value : String );
procedure SetInitMonthDelta( Value : Integer ); override;
procedure SetKind(Value: TDTPKind);
procedure SetParseInput(Value: Boolean);
procedure SetShowCheckbox(Value: Boolean);
procedure ChangeTime(Value: TTime);
procedure SetTime(Value: TTime); virtual;
procedure SetDate(Value: TDate); override;
procedure SetDateTime(Value: TDateTime); override;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
procedure CheckEmptyDate; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
function GetCalendarHandle: HWND; override;
function MsgSetCalColors(ColorIndex: Integer; ColorValue: TColor): Boolean; override;
function MsgSetDateTime( ASystemTime: TSystemTime ): Boolean; override;
function MsgSetDateTimeAndChecked( ASystemTime: TSystemTime; const AChecked : Boolean ): Boolean;
function MsgSetRange(Flags: Integer; SysTime: PSystemTime): Boolean; override;
procedure DoExit; override;
function GetIsChanged : Boolean; override;
function StoreCustomFormat : Boolean;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
public
constructor Create(AOwner: TComponent); override;
procedure SetDateTimeAndChecked( ADateTime: TDateTime; const AChecked : Boolean );
property DateTime;
property DroppedDown: Boolean read FDroppedDown;
property Date stored False;
property Time: TTime read GetTime write SetTime stored False;
published
property Anchors;
property BiDiMode;
property CalAlignment: TDTCalAlignment read FCalAlignment write SetCalAlignment;
property CalColors;
property Constraints;
// The Date, Time, ShowCheckbox, and Checked properties must be in this order:
property ShowCheckbox: Boolean read FShowCheckbox write SetShowCheckbox default False;
property Checked: Boolean read FChecked write SetChecked default True;
property Color stored True default clWindow;
property CustomFormat : String read FCustomFormat write SetCustomFormat stored StoreCustomFormat;
property DateMode: TDTDateMode read FDateMode write SetDateMode;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property Kind: TDTPKind read FKind write SetKind;
property MaxDate;
property MinDate;
property ParseInput: Boolean read FParseInput write SetParseInput;
property ParentBiDiMode;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
property OnChange;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnCloseUp: TNotifyEvent read FOnCloseUp write FOnCloseUp;
property OnDropDown: TNotifyEvent read FOnDropDown write FOnDropDown;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDock;
property OnStartDrag;
property OnUserInput: TDTParseInputEvent read FOnUserInput write FOnUserInput;
property InitMonthDelta;
end;
procedure Register;
//=============================================================
implementation
//=============================================================
uses
RtlConsts,
ComStrs{, StringConv};
const
ColorIndex: array[0..5] of Integer = (MCSC_BACKGROUND, MCSC_TEXT, MCSC_TITLEBK, MCSC_TITLETEXT, MCSC_MONTHBK, MCSC_TRAILINGTEXT);
eCustomFormats = [dtkShortDateTime,dtkLongDateTime,dtkCustom];
sShortDateTimeFormat = 'dd''.''MM''.''yyy HH'':''mm';
sLongDateTimeFormat = 'dd MMMM yyy HH'':''mm'':''ss';
//=============================================================
procedure Register;
begin
RegisterComponents('Additional', [TDateComboBox]);
end;
//=============================================================
procedure SetComCtlStyle(Ctl: TWinControl; Value: Integer; UseStyle: Boolean);
var Style: Integer;
begin
if Ctl.HandleAllocated then
begin
Style := GetWindowLong(Ctl.Handle, GWL_STYLE);
if not UseStyle then Style := Style and not Value else Style := Style or Value;
SetWindowLong(Ctl.Handle, GWL_STYLE, Style);
end;
end;
//==TCalendarColors===========================================================
constructor TCalendarColors.Create(AOwner: TCustomCalendar);
begin
Owner := AOwner;
FBackColor := clWindow;
FTextColor := clWindowText;
FTitleBackColor := clActiveCaption;
FTitleTextColor := clWhite;
FMonthBackColor := clWhite;
FTrailingTextColor := clInactiveCaptionText;
end;
//-------------------------------------------------------------
procedure TCalendarColors.Assign(Source: TPersistent);
var SourceName: string;
begin
if Source = nil then SourceName := 'nil'
else SourceName := Source.ClassName;
if (Source = nil) or not (Source is TCalendarColors) then
raise EConvertError.CreateFmt(SAssignError, [SourceName, ClassName]);
FBackColor := TCalendarColors(Source).BackColor;
FTextColor := TCalendarColors(Source).TextColor;
FTitleBackColor := TCalendarColors(Source).TitleBackColor;
FTitleTextColor := TCalendarColors(Source).TitleTextColor;
FMonthBackColor := TCalendarColors(Source).MonthBackColor;
FTrailingTextColor := TCalendarColors(Source).TrailingTextColor;
end;
//-------------------------------------------------------------
procedure TCalendarColors.SetColor(Index: Integer; Value: TColor);
begin
case Index of
0: FBackColor := Value;
1: FTextColor := Value;
2: FTitleBackColor := Value;
3: FTitleTextColor := Value;
4: FMonthBackColor := Value;
5: FTrailingTextColor := Value;
end;
if Owner.HandleAllocated then
Owner.MsgSetCalColors(ColorIndex[Index], ColorToRGB(Value));
end;
//-------------------------------------------------------------
procedure TCalendarColors.SetAllColors;
begin
SetColor(0, FBackColor);
SetColor(1, FTextColor);
SetColor(2, FTitleBackColor);
SetColor(3, FTitleTextColor);
SetColor(4, FMonthBackColor);
SetColor(5, FTrailingTextColor);
end;
//==TCustomCalendar===========================================================
constructor TCustomCalendar.Create(AOwner: TComponent);
begin
CheckCommonControl(ICC_DATE_CLASSES);
inherited Create(AOwner);
FShowToday := True;
FShowTodayCircle := True;
ControlStyle := [csOpaque, csClickEvents, csDoubleClicks, csReflector];
FCalColors := TDateTimeColors.Create(Self);
FDateTime := Now;
FOldDateTime := FDateTime;
FFirstDayOfWeek := dowLocaleDefault;
FMaxSelectRange := 31;
FMonthDelta := 1;
// FInitMonthDelta := 0;
end;
//-------------------------------------------------------------
destructor TCustomCalendar.Destroy;
begin
inherited Destroy;
FCalColors.Free;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.BoldDays(Days: array of LongWord; var MonthBoldInfo: LongWord);
var I: LongWord;
begin
MonthBoldInfo := 0;
for I := Low(Days) to High(Days) do
if (Days[I] > 0) and (Days[I] < 32) then
MonthBoldInfo := MonthBoldInfo or ($00000001 shl (Days[I] - 1));
end;
//-------------------------------------------------------------
procedure TCustomCalendar.CheckEmptyDate;
begin
// do nothing
end;
//-------------------------------------------------------------
procedure TCustomCalendar.CheckValidDate(Value: TDate);
begin
if (FMaxDate <> 0.0) and (Value > FMaxDate) then
raise CalExceptionClass.CreateFmt(SDateTimeMax, [DateToStr(FMaxDate)]);
if (FMinDate <> 0.0) and (Value < FMinDate) then
raise CalExceptionClass.CreateFmt(SDateTimeMin, [DateToStr(FMinDate)]);
end;
//-------------------------------------------------------------
procedure TCustomCalendar.CreateWnd;
begin
inherited CreateWnd;
FCalColors.SetAllColors;
SetRange(FMinDate, FMaxDate);
SetMaxSelectRange(FMaxSelectRange);
SetFirstDayOfWeek(FFirstDayOfWeek);
if not (Self is TDateComboBox) then
begin
if FMultiSelect then SetSelectedRange(FDateTime, FEndDate) else SetDateTime(FDateTime);
SetMonthDelta(FMonthDelta);
end
else if FMultiSelect then SetSelectedRange(FDateTime, FEndDate);
end;
//-------------------------------------------------------------
procedure TCustomCalendar.Change;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
//-------------------------------------------------------------
procedure TCustomCalendar.ChangeDate(Value: TDate);
var TruncValue: TDate;
begin
TruncValue := Trunc(Value);
if Trunc(FDateTime)=TruncValue then Exit;
Value := TruncValue + Frac(FDateTime);
if Value = 0.0 then CheckEmptyDate;
try
CheckValidDate(TruncValue);
SetDateTime(Value);
except
SetDateTime(FDateTime);
raise;
end;
Changed;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.ChangeDateTime(Value: TDateTime);
var ST: TSystemTime;
begin
if FMultiSelect then
begin
SetSelectedRange(Value,FEndDate);
FOldDateTime := 0.0;
end
else if FDateTime<>Value then
begin
CheckValidDate(Value);
if HandleAllocated then
begin
DateTimeToSystemTime(Value,ST);
if not MsgSetDateTime(ST) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
end;
FDateTime := Value;
end;
Changed;
end;
//-------------------------------------------------------------
function TCustomCalendar.DoStoreEndDate: Boolean;
begin
Result := FMultiSelect;
end;
//-------------------------------------------------------------
function TCustomCalendar.DoStoreMaxDate: Boolean;
begin
Result := FMaxDate <> 0.0;
end;
//-------------------------------------------------------------
function TCustomCalendar.DoStoreMinDate: Boolean;
begin
Result := FMinDate <> 0.0;
end;
//-------------------------------------------------------------
function TCustomCalendar.GetCalStyles: DWORD;
const
ShowTodayFlags: array[Boolean] of DWORD = (MCS_NOTODAY, 0);
ShowTodayCircleFlags: array[Boolean] of DWORD = (MCS_NOTODAYCIRCLE, 0);
WeekNumFlags: array[Boolean] of DWORD = (0, MCS_WEEKNUMBERS);
MultiSelFlags: array[Boolean] of DWORD = (0, MCS_MULTISELECT);
begin
Result := MCS_DAYSTATE or ShowTodayFlags[FShowToday] or
ShowTodayCircleFlags[FShowTodayCircle] or WeekNumFlags[FWeekNumbers] or
MultiSelFlags[FMultiSelect];
end;
//-------------------------------------------------------------
function TCustomCalendar.GetIsChanged : Boolean;
begin
Result := FOldDateTime<>FDateTime;
end;
//-------------------------------------------------------------
function TCustomCalendar.GetDate: TDate;
begin
Result := TDate(FDateTime);
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetDate(Value: TDate);
var TruncValue: TDate;
begin
TruncValue := Trunc(Value);
if Trunc(FDateTime)=TruncValue then Exit;
Value := TruncValue + Frac(FDateTime);
if Value = 0.0 then CheckEmptyDate;
try
CheckValidDate(TruncValue);
SetDateTime(Value);
except
SetDateTime(FDateTime);
raise;
end;
FOldDateTime := Value;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetDateTime(Value: TDateTime);
var ST: TSystemTime;
begin
if FMultiSelect then SetSelectedRange(Value, FEndDate)
else if FDateTime<>Value then
begin
if HandleAllocated then
begin
DateTimeToSystemTime(Value,ST);
if not MsgSetDateTime(ST) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
end;
FDateTime := Value;
FOldDateTime := Value;
end;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetInitMonthDelta( Value : Integer );
begin
// if FInitMonthDelta=Value then Exit;
FInitMonthDelta := Value;
if Value<>0 then SetDateTime(IncMonth(Now,Value));
end; {TCustomCalendar.SetInitMonthDelta}
//-------------------------------------------------------------
procedure TCustomCalendar.SetCalColors(Value: TDateTimeColors);
begin
if FCalColors <> Value then FCalColors.Assign(Value);
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetEndDate(Value: TDate);
var
TruncValue: TDate;
begin
TruncValue := Trunc(Value);
if Trunc(FEndDate) <> TruncValue then
begin
Value := TruncValue + 0.0;
if Value = 0.0 then CheckEmptyDate;
CheckValidDate(TruncValue);
SetSelectedRange(Date, TruncValue);
end;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetFirstDayOfWeek(Value: TCalDayOfWeek);
var
DOWFlag: Integer;
A: array[0..1] of char;
begin
if HandleAllocated then
begin
if Value = dowLocaleDefault then
begin
GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, A, SizeOf(A));
DOWFlag := Ord(A[0]) - Ord('0');
end
else
DOWFlag := Ord(Value);
if CalendarHandle <> 0 then
MonthCal_SetFirstDayOfWeek(CalendarHandle, DOWFlag);
end;
FFirstDayOfWeek := Value;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetMaxDate(Value: TDate);
begin
if (FMinDate <> 0.0) and (Value < FMinDate) then
raise CalExceptionClass.CreateFmt(SDateTimeMin, [DateToStr(FMinDate)]);
if FMaxDate <> Value then
begin
SetRange(FMinDate, Value);
FMaxDate := Value;
end;
end;
procedure TCustomCalendar.SetMaxSelectRange(Value: Integer);
begin
if FMultiSelect and HandleAllocated then
if not MonthCal_SetMaxSelCount(CalendarHandle, Value) then
raise ECommonCalendarError.Create(sFailSetCalMaxSelRange);
FMaxSelectRange := Value;
end;
procedure TCustomCalendar.SetMinDate(Value: TDate);
begin
if (FMaxDate <> 0.0) and (Value > FMaxDate) then
raise CalExceptionClass.CreateFmt(SDateTimeMax, [DateToStr(FMaxDate)]);
if FMinDate <> Value then
begin
SetRange(Value, FMaxDate);
FMinDate := Value;
end;
end;
//-------------------------------------------------------------
procedure TCustomCalendar.SetMonthDelta( Value: Integer );
begin
if FMonthDelta<>Value then
begin
if HandleAllocated and (CalendarHandle<>0) then MonthCal_SetMonthDelta(CalendarHandle,Value);
FMonthDelta := Value;
end;
end;
procedure TCustomCalendar.SetMultiSelect(Value: Boolean);
begin
if FMultiSelect <> Value then
begin
FMultiSelect := Value;
if Value then FEndDate := FDateTime else FEndDate := 0.0;
RecreateWnd;
end;
end;
procedure TCustomCalendar.SetRange(MinVal, MaxVal: TDate);
var
STA: packed array[1..2] of TSystemTime;
Flags: DWORD;
TruncDate, TruncEnd, TruncMin, TruncMax: Int64;
begin
Flags := 0;
TruncMin := Trunc(MinVal);
TruncMax := Trunc(MaxVal);
TruncDate := Trunc(FDateTime);
TruncEnd := Trunc(FEndDate);
if TruncMin <> 0 then
begin
if TruncDate < TruncMin then ChangeDate(MinVal);
if TruncEnd < TruncMin then SetEndDate(MinVal);
Flags := Flags or GDTR_MIN;
DateTimeToSystemTime(MinVal, STA[1]);
end;
if TruncMax <> 0 then
begin
if TruncDate > TruncMax then ChangeDate(MaxVal);
if TruncEnd > TruncMax then SetEndDate(MaxVal);
Flags := Flags or GDTR_MAX;
DateTimeToSystemTime(MaxVal, STA[2]);
end;
if HandleAllocated then
if not MsgSetRange(Flags, @STA[1]) then
raise ECommonCalendarError.Create(sFailSetCalMinMaxRange);
end;
procedure TCustomCalendar.SetSelectedRange(Date, EndDate: TDate);
var
DateArray: array[1..2] of TSystemTime;
begin
if not FMultiSelect then SetDateTime(Date)
else
begin
DateTimeToSystemTime(Date, DateArray[1]);
DateTimeToSystemTime(EndDate, DateArray[2]);
if HandleAllocated then
if not MonthCal_SetSelRange(Handle, @DateArray[1]) then
raise ECommonCalendarError.Create(sFailsetCalSelRange);
FDateTime := Date;
FEndDate := EndDate;
end;
end;
procedure TCustomCalendar.SetShowToday(Value: Boolean);
begin
if FShowToday <> Value then
begin
FShowToday := Value;
SetComCtlStyle(Self, MCS_NOTODAY, not Value);
end;
end;
procedure TCustomCalendar.SetShowTodayCircle(Value: Boolean);
begin
if FShowTodayCircle <> Value then
begin
FShowTodayCircle := Value;
SetComCtlStyle(Self, MCS_NOTODAYCIRCLE, not Value);
end;
end;
procedure TCustomCalendar.SetWeekNumbers(Value: Boolean);
begin
if FWeekNumbers <> Value then
begin
FWeekNumbers := Value;
SetComCtlStyle(Self, MCS_WEEKNUMBERS, Value);
end;
end;
function IsBlankSysTime(const ST: TSystemTime): Boolean;
begin
with ST do
Result := (wYear = 0) and (wMonth = 0) and (wDayOfWeek = 0) and
(wDay = 0) and (wHour = 0) and (wMinute = 0) and (wSecond = 0) and
(wMilliseconds = 0);
end;
//==TDateComboBox===========================================================
constructor TDateComboBox.Create(AOwner: TComponent);
begin
FCalExceptionClass := EDateTimeError;
FChanging := False;
inherited Create(AOwner);
DateTimeToSystemTime(FDateTime,FLastChange);
FShowCheckbox := False;
FChecked := True;
ControlStyle := ControlStyle + [csFixedHeight, csReflector];
Color := clWindow;
ParentColor := False;
TabStop := True;
Width := 186;
AdjustHeight;
end;
//-------------------------------------------------------------
procedure TDateComboBox.AdjustHeight;
var
DC: HDC;
SaveFont: HFont;
SysMetrics, Metrics: TTextMetric;
begin
DC := GetDC(0);
try
GetTextMetrics(DC, SysMetrics);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
Height := Metrics.tmHeight + (GetSystemMetrics(SM_CYBORDER) * 8);
end;
//-------------------------------------------------------------
procedure TDateComboBox.CheckEmptyDate;
begin
if not FShowCheckbox then raise EDateTimeError.Create(SNeedAllowNone);
FChecked := False;
Invalidate;
end;
//-------------------------------------------------------------
procedure TDateComboBox.CreateParams(var Params: TCreateParams);
const
aStyles: array[TDTPKind] of DWORD = (DTS_SHORTDATEFORMAT,DTS_LONGDATEFORMAT,DTS_TIMEFORMAT,DTS_SHORTDATEFORMAT,DTS_LONGDATEFORMAT,0);
var ACalAlignment: TDTCalAlignment;
begin
inherited CreateParams(Params);
CreateSubClass(Params, DATETIMEPICK_CLASS);
with Params do
begin
if FDateMode = dmUpDown then Style := Style or DTS_UPDOWN;
if (FKind=dtkCustom)and(FCustomFormat='') then FKind := dtkShortDate;
if FKind=dtkShortDateTime then FCustomFormat := sShortDateTimeFormat
else if FKind=dtkLongDateTime then FCustomFormat := sLongDateTimeFormat
else Style := Style or aStyles[FKind];
ACalAlignment := FCalAlignment;
if UseRightToLeftAlignment then
if ACalAlignment = dtaLeft then ACalAlignment := dtaRight else ACalAlignment := dtaLeft;
if ACalAlignment = dtaRight then Style := Style or DTS_RIGHTALIGN;
if FParseInput then Style := Style or DTS_APPCANPARSE;
if FShowCheckbox then Style := Style or DTS_SHOWNONE;
WindowClass.Style := WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.CreateWnd;
begin
inherited CreateWnd;
if (FKind in eCustomFormats)and(FCustomFormat<>'') then DateTime_SetFormat(Handle,PChar(FCustomFormat));
if FInitMonthDelta<>0 then
begin
FDateTime := IncMonth(Now,FInitMonthDelta);
FOldDateTime := FDateTime;
end;
DateTimeToSystemTime(FDateTime,FLastChange);
if not MsgSetDateTimeAndChecked( FLastChange, FChecked or not FShowCheckbox ) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
FButtonWidth := GetSystemMetrics(SM_CXVSCROLL);
FButtonPressed := False;
// Invalidate;
end;
//-------------------------------------------------------------
procedure TDateComboBox.CMColorChanged(var Message: TMessage);
begin
inherited;
InvalidateRect(Handle, nil, True);
end;
//-------------------------------------------------------------
procedure TDateComboBox.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustHeight;
InvalidateRect(Handle, nil, True);
end;
//-------------------------------------------------------------
procedure TDateComboBox.CNNotify(var Message: TWMNotify);
var dtNew : TDateTime;
bAllowChange: Boolean;
begin
with Message, NMHdr^ do
begin
Result := 0;
case code of
DTN_CLOSEUP:
begin
FDroppedDown := False;
FButtonPressed := False;
// SetDate(SystemTimeToDateTime(FLastChange));
if Assigned(FOnCloseUp) then FOnCloseUp(Self);
if Assigned(FOnClick) and ((FDateTime<>FOldDateTime)or(FShowCheckbox and not FChecked)) then
begin
FChecked := True;
FOnClick(Self);
FOldChecked := True;
FOldDateTime := FDateTime;
end
else FChecked := True;
end;
DTN_DATETIMECHANGE:
begin
with PNMDateTimeChange(NMHdr)^ do
begin
if FDroppedDown and (dwFlags = GDT_VALID) then
begin
FLastChange := st;
FDateTime := SystemTimeToDateTime(FLastChange);
Change;
end
else
if (dwFlags = GDT_NONE) or IsBlankSysTime(st) then
if FShowCheckbox and FChecked and Assigned(FOnClick) then
begin
FChecked := False;
FOnClick(Self);
FOldChecked := False;
FOldDateTime := FDateTime;
end
else FChecked := False
else if dwFlags = GDT_VALID then
begin
FLastChange := st;
dtNew := SystemTimeToDateTime(st);
if not FButtonPressed and FShowCheckbox and not FChecked and Assigned(FOnClick) then
begin
if dtNew<>FDateTime then
if (FKind=dtkShortDate)or(FKind=dtkLongDate) then FDateTime := Trunc(dtNew)+Frac(FDateTime)
else if FKind=dtkTime then FDateTime := Trunc(FDateTime)+Frac(dtNew)
else FDateTime := dtNew;
FChecked := True;
FOnClick(Self);
FOldChecked := True;
FOldDateTime := dtNew;
end
else if dtNew<>FDateTime then
begin
if (FKind=dtkShortDate)or(FKind=dtkLongDate) then FDateTime := Trunc(dtNew)+Frac(FDateTime)
else if FKind=dtkTime then FDateTime := Trunc(FDateTime)+Frac(dtNew)
else FDateTime := dtNew;
FChecked := True;
Change;
end
else FChecked := not FButtonPressed;
end;
end;
end;
DTN_DROPDOWN:
begin
DateTimeToSystemTime(Date,FLastChange);
FDroppedDown := True;
FButtonPressed := False;
if Assigned(FOnDropDown) then FOnDropDown(Self);
end;
DTN_USERSTRING:
begin
bAllowChange := Assigned(FOnUserInput);
with PNMDateTimeString(NMHdr)^ do
begin
if bAllowChange then
begin
dtNew := 0.0;
FOnUserInput(Self, pszUserString, dtNew, bAllowChange);
DateTimeToSystemTime(dtNew, st);
end;
dwFlags := Ord(not bAllowChange);
end;
end;
else
inherited;
end;
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.WMLButtonDown(var Message: TWMLButtonDown);
begin
FButtonPressed := PtInRect( Rect(ClientWidth-FButtonWidth,0,ClientWidth,ClientHeight), Point(Message.XPos,Message.YPos) );
inherited;
end;
//-------------------------------------------------------------
function TDateComboBox.GetCalendarHandle: HWND;
begin
Result := DateTime_GetMonthCal(Handle);
end;
//-------------------------------------------------------------
function TDateComboBox.GetTime: TTime;
begin
Result := TTime(FDateTime);
end;
//-------------------------------------------------------------
function TDateComboBox.MsgSetCalColors(ColorIndex: Integer; ColorValue: TColor): Boolean;
begin
Result := True;
if HandleAllocated then
Result := DateTime_SetMonthCalColor(Handle, ColorIndex, ColorValue) <> DWORD($FFFFFFFF);
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetDateTimeAndChecked( ADateTime: TDateTime; const AChecked : Boolean );
begin
if not FShowCheckbox then raise EDateTimeError.Create(SNeedAllowNone);
if (AChecked<>FChecked)or(AChecked and (FDateTime=ADateTime)) then
begin
FDateTime := ADateTime;
if HandleAllocated then
begin
DateTimeToSystemTime(FDateTime,FLastChange);
if not MsgSetDateTimeAndChecked(FLastChange,AChecked) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
Invalidate;
end;
FOldDateTime := FDateTime;
FChecked := AChecked;
FOldChecked := AChecked;
end;
end; {TDateComboBox.SetDateTimeAndChecked}
//-------------------------------------------------------------
function TDateComboBox.MsgSetDateTime( ASystemTime: TSystemTime{; const AChecked : Boolean} ): Boolean;
begin
Result := MsgSetDateTimeAndChecked( ASystemTime, True );
end;
//-------------------------------------------------------------
function TDateComboBox.MsgSetDateTimeAndChecked( ASystemTime: TSystemTime; const AChecked : Boolean ): Boolean;
const aGDT_Flag : array [Boolean] of DWORD = (GDT_NONE,GDT_VALID);
begin
Result := True;
if HandleAllocated then
if not FChanging then
begin
FChanging := True;
try
Result := DateTime_SetSystemTime(Handle,aGDT_Flag[AChecked],ASystemTime);
finally
FChanging := False;
end;
end;
end;
//-------------------------------------------------------------
function TDateComboBox.MsgSetRange(Flags: Integer; SysTime: PSystemTime): Boolean;
begin
Result := True;
if HandleAllocated then
if Flags <> 0 then Result := DateTime_SetRange(Handle, Flags, SysTime);
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetCalAlignment(Value: TDTCalAlignment);
begin
if FCalAlignment <> Value then
begin
FCalAlignment := Value;
if not (csDesigning in ComponentState) then
SetComCtlStyle(Self, DTS_RIGHTALIGN, Value = dtaRight);
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetChecked(Value: Boolean);
begin
if FChecked=Value then Exit;
if FShowCheckbox and HandleAllocated then
begin
DateTimeToSystemTime(FDateTime,FLastChange);
if not MsgSetDateTimeAndChecked(FLastChange,Value) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
Invalidate;
end;
FChecked := Value;
FOldChecked := Value;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetCustomFormat( Value : String );
begin
if FCustomFormat<>Value then
begin
FCustomFormat := Value;
if Value<>'' then FKind := dtkCustom;
RecreateWnd;
end;
end; {TDateComboBox.SetCustomFormat}
//-------------------------------------------------------------
function TDateComboBox.StoreCustomFormat : Boolean;
begin
Result := FKind=dtkCustom;
end; {TDateComboBox.StoreCustomFormat}
//-------------------------------------------------------------
procedure TDateComboBox.SetDateMode(Value: TDTDateMode);
begin
if FDateMode <> Value then
begin
FDateMode := Value;
RecreateWnd;
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetKind(Value: TDTPKind);
// TDTPKind = (dtkShortDate,dtkLongDate,dtkTime,dtkShortDateTime,dtkLongDateTime,dtkCustom);
const
aStyles: array[TDTPKind] of DWORD = (DTS_SHORTDATEFORMAT,DTS_LONGDATEFORMAT,DTS_TIMEFORMAT,DTS_SHORTDATEFORMAT,DTS_LONGDATEFORMAT,0);
DropFormats = not(DTS_SHORTDATEFORMAT or DTS_LONGDATEFORMAT or DTS_TIMEFORMAT);
var Style: DWORD;
begin
if (Value=dtkCustom)and(FCustomFormat='') then Value := dtkShortDate;
if FKind <> Value then
begin
if Value=dtkShortDateTime then FCustomFormat := sShortDateTimeFormat
else if Value=dtkLongDateTime then FCustomFormat := sLongDateTimeFormat;
if HandleAllocated then
begin
if Value in eCustomFormats then DateTime_SetFormat(Handle,PChar(FCustomFormat))
else if not (FKind in eCustomFormats) then
begin
Style := GetWindowLong(Handle,GWL_STYLE) and DropFormats;
SetWindowLong(Handle,GWL_STYLE,Style or aStyles[Value]);
end
else
begin
FKind := Value;
RecreateWnd;
Exit;
end;
end;
FKind := Value;
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetParseInput(Value: Boolean);
begin
if FParseInput <> Value then
begin
FParseInput := Value;
if not (csDesigning in ComponentState) then SetComCtlStyle(Self, DTS_APPCANPARSE, Value);
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetShowCheckbox(Value: Boolean);
begin
if FShowCheckbox <> Value then
begin
FShowCheckbox := Value;
RecreateWnd;
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetInitMonthDelta( Value : Integer );
var dt : TDateTime;
begin
// if FInitMonthDelta=Value then Exit;
FInitMonthDelta := Value;
if Value=0 then dt := Now else dt := IncMonth(Now,Value);
if ShowCheckbox then SetDateTimeAndChecked(dt,FChecked) else SetDateTime(dt);
end; {TDateComboBox.SetInitMonthDelta}
//-------------------------------------------------------------
procedure TDateComboBox.SetDate(Value: TDate);
var TruncValue: TDate;
begin
TruncValue := Trunc(Value);
if (Trunc(FDateTime)=TruncValue)and FChecked then Exit;
Value := TruncValue + Frac(FDateTime);
if Value = 0.0 then CheckEmptyDate;
try
CheckValidDate(TruncValue);
SetDateTime(Value);
except
SetDateTime(FDateTime);
raise;
end;
FOldDateTime := Value;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetDateTime(Value: TDateTime);
begin
if FMultiSelect then SetSelectedRange(Value, FEndDate)
else if (FDateTime<>Value)or not FChecked then
begin
FChecked := True;
FOldChecked := True;
if HandleAllocated then
begin
DateTimeToSystemTime(Value,FLastChange);
if not MsgSetDateTimeAndChecked(FLastChange,True) then raise ECommonCalendarError.Create(sFailSetCalDateTime);
FChecked := True;
FOldChecked := True;
Invalidate;
end;
FDateTime := Value;
FOldDateTime := Value;
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.SetTime(Value: TTime);
begin
if (Frac(FDateTime)<>Frac(Value))or not Checked then
begin
Value := Trunc(FDateTime) + Frac(Value);
if Value = 0.0 then
begin
if not FShowCheckbox then raise EDateTimeError.Create(SNeedAllowNone);
Checked := False;
end
else SetDateTime(Value);
end;
end;
//-------------------------------------------------------------
function TDateComboBox.GetIsChanged : Boolean;
begin
Result := (FOldChecked<>FChecked)or(FOldDateTime<>FDateTime);
end;
//-------------------------------------------------------------
procedure TDateComboBox.ChangeTime(Value: TTime);
begin
if (Frac(FDateTime)<>Frac(Value))or not Checked then
begin
Value := Trunc(FDateTime) + Frac(Value);
if Value = 0.0 then
begin
if not FShowCheckbox then raise EDateTimeError.Create(SNeedAllowNone);
Checked := False;
end
else ChangeDateTime(Value);
end;
end;
//-------------------------------------------------------------
procedure TDateComboBox.DoExit;
begin
if Assigned(FOnClick) and not FMultiSelect and IsChanged then FOnClick(Self);
inherited;
FOldDateTime := FDateTime;
FOldChecked := FChecked;
end;
end. |
unit GeoUnitTests;
interface
uses
TestFramework;
type
// Test methods for unit Geo.pas
TGeoUnitTest = class(TTestCase)
private
public
published
procedure Test00;
procedure Test01;
procedure Test02;
procedure Test03;
procedure Test04;
procedure Test05;
procedure Test06;
procedure Test07;
procedure Test08;
procedure Test09;
procedure Test10;
end;
implementation
uses Math, Geo;
procedure TGeoUnitTest.Test00;
var
test : string;
begin
test := ToDMS(NaN, TDMSFormat.D, TDecimalPlaces.Zero);
CheckEquals('', test, 'Not a number');
end;
procedure TGeoUnitTest.Test01;
var
test : string;
begin
test := ToDMS(Infinity, TDMSFormat.D, TDecimalPlaces.Zero);
CheckEquals('', test, 'Infinity');
end;
procedure TGeoUnitTest.Test02;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.D, TDecimalPlaces.Zero);
CheckEquals('000º', test, 'Zero Degrees, Zero DP');
end;
procedure TGeoUnitTest.Test03;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.D, TDecimalPlaces.Two);
CheckEquals('000.00º', test, 'Zero Degrees, Two DP');
end;
procedure TGeoUnitTest.Test04;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.D, TDecimalPlaces.Four);
CheckEquals('000.0000º', test, 'Zero Degrees, Four DP');
end;
procedure TGeoUnitTest.Test05;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DM, TDecimalPlaces.Zero);
CheckEquals('000º00''', test, 'Zero Degrees Minutes, Zero DP');
end;
procedure TGeoUnitTest.Test06;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DM, TDecimalPlaces.Two);
CheckEquals('000º00.00''', test, 'Zero Degrees Minutes, Two DP');
end;
procedure TGeoUnitTest.Test07;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DM, TDecimalPlaces.Four);
CheckEquals('000º00.0000''', test, 'Zero Degrees Minutes, Four DP');
end;
procedure TGeoUnitTest.Test08;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DMS, TDecimalPlaces.Zero);
CheckEquals('000º00''00"', test, 'Zero Degrees Minutes Seconds, Zero DP');
end;
procedure TGeoUnitTest.Test09;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DMS, TDecimalPlaces.Two);
CheckEquals('000º00''00.00"', test, 'Zero Degrees Minutes Seconds, Two DP');
end;
procedure TGeoUnitTest.Test10;
var
test : string;
begin
test := ToDMS(0.0, TDMSFormat.DMS, TDecimalPlaces.Four);
CheckEquals('000º00''00.0000"', test, 'Zero Degrees Minutes Seconds, Four DP');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TGeoUnitTest.Suite);
end.
|
unit OS.EnvironmentVariable;
interface
uses
Forms, Windows, SysUtils, Classes, ShlObj, Character,
Registry.Helper, Registry.Helper.Internal, AsciiCheck;
type
TEnvironmentVariable = class
private
function AppendRandomNSTFooter(const BasePath: String): String;
function RootTempFolder: String;
procedure SetPathForNormalInstance(const Application: TApplication);
procedure SetPathForServiceInstance;
var
FAppPath: String;
FWinDir: String;
FWinDrive: String;
FAllDesktopPath: String;
FDesktopPathInChar: array[0..MAX_PATH] of char;
public
procedure SetPath(const Application: TApplication);
function AppPath: String;
function WinDir: String;
function WinDrive: String;
function TempFolder(const AnsiOnly: Boolean): String;
function AllDesktopPath: String;
class function Create: TEnvironmentVariable;
end;
var
EnvironmentVariable: TEnvironmentVariable;
implementation
procedure TEnvironmentVariable.SetPathForNormalInstance(
const Application: TApplication);
begin
FAppPath := ExtractFilePath(Application.ExeName);
FWinDir := GetEnvironmentVariable('windir');
FWinDrive := ExtractFileDrive(WinDir);
SHGetFolderPath(0, CSIDL_COMMON_DESKTOPDIRECTORY, 0, 0,
@FDesktopPathInChar[0]);
end;
procedure TEnvironmentVariable.SetPathForServiceInstance;
const
ServiceInstancePath: TRegistryPath =
(Root: LocalMachine;
PathUnderHKEY: 'SYSTEM\CurrentControlSet\services\NaraeonSSDToolsDiag';
ValueName: 'ImagePath');
begin
FAppPath := ExtractFilePath(NSTRegistry.GetRegStr(ServiceInstancePath));
FAllDesktopPath := FDesktopPathInChar;
end;
procedure TEnvironmentVariable.SetPath(const Application: TApplication);
begin
Randomize;
if Application <> nil then
SetPathForNormalInstance(Application)
else
SetPathForServiceInstance;
end;
function TEnvironmentVariable.AllDesktopPath: String;
begin
exit(FAllDesktopPath);
end;
function TEnvironmentVariable.AppPath: String;
begin
exit(FAppPath);
end;
function TEnvironmentVariable.WinDir: String;
begin
exit(FWinDir);
end;
function TEnvironmentVariable.WinDrive: String;
begin
exit(FWinDrive);
end;
function TEnvironmentVariable.AppendRandomNSTFooter(
const BasePath: String): String;
var
OptionalBackslash: String;
begin
OptionalBackslash := '';
if BasePath[Length(BasePath)] <> '\' then
OptionalBackslash := '\';
result := BasePath + OptionalBackslash +
'NST' + IntToStr(Random(2147483647)) + '\';
while DirectoryExists(result) do
result :=
BasePath + OptionalBackslash +
'NST' + IntToStr(Random(2147483647)) + '\';
end;
function TEnvironmentVariable.RootTempFolder: String;
begin
result := AppendRandomNSTFooter(FWinDrive);
end;
function TEnvironmentVariable.TempFolder(const AnsiOnly: Boolean): String;
var
TempPath: String;
begin
SetLength(TempPath, MAX_PATH + 1);
SetLength(TempPath, GetTempPath(MAX_PATH, PChar(TempPath)));
if (not AnsiOnly) or (StringHelper.IsAscii(TempPath)) then
result := AppendRandomNSTFooter(TempPath)
else
result := RootTempFolder;
end;
class function TEnvironmentVariable.Create: TEnvironmentVariable;
begin
if EnvironmentVariable = nil then
result := inherited Create as self
else
result := EnvironmentVariable;
end;
initialization
EnvironmentVariable := TEnvironmentVariable.Create;
finalization
EnvironmentVariable.Free;
end.
|
{$mode objfpc}{$H+}{$J-}
{$modeswitch advancedrecords}
type
TMyRecord = record
public
I, Square: Integer;
procedure WriteLnDescription;
end;
procedure TMyRecord.WriteLnDescription;
begin
WriteLn('Квадрат числа ', I, ' равен ', Square);
end;
var
A: array [0..9] of TMyRecord;
R: TMyRecord;
I: Integer;
begin
for I := 0 to 9 do
begin
A[I].I := I;
A[I].Square := I * I;
end;
for R in A do
R.WriteLnDescription;
end. |
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, jpeg, ExtCtrls, StdCtrls, Mask, DBCtrls;
type
TForm2 = class(TForm)
Image2: TImage;
Panel2: TPanel;
Panel1: TPanel;
Image1: TImage;
Label1: TLabel;
txtRamal: TDBEdit;
txtSetor: TDBEdit;
Label2: TLabel;
txtContato: TDBEdit;
Label3: TLabel;
txtDescricao: TDBEdit;
Label4: TLabel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure txtRamalKeyPress(Sender: TObject; var Key: Char);
procedure txtSetorKeyPress(Sender: TObject; var Key: Char);
procedure txtContatoKeyPress(Sender: TObject; var Key: Char);
procedure txtDescricaoKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses Unit1, Unit3;
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
if (txtRamal.Text = '') or (txtSetor.Text = '' ) or (txtContato.Text = '') then
begin
messagedlg('Verifique se os campos Ramal, Setor e Contato foram preenchidos corretamente!', mtInformation, [mbOk], 0);
end
else
begin
form1.adoquery1.post;
form2.Hide;
end;
form3.DBGrid1.Enabled := true;
form3.SpeedButton1.Enabled := true;
form3.btnCadastrar.Enabled :=true;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
form1.ADOQuery1.Cancel;
form2.Hide;
form3.DBGrid1.Enabled := true;
form3.SpeedButton1.Enabled := true;
form3.btnCadastrar.Enabled := true;
end;
procedure TForm2.txtRamalKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', chr(8)]) then
Key:=#0;
end;
procedure TForm2.txtSetorKeyPress(Sender: TObject; var Key: Char);
begin
if (Key in [ chr(39)]) then
Key:=#0;
end;
procedure TForm2.txtContatoKeyPress(Sender: TObject; var Key: Char);
begin
if (Key in [ chr(39)]) then
Key:=#0;
end;
procedure TForm2.txtDescricaoKeyPress(Sender: TObject; var Key: Char);
begin
if (Key in [ chr(39)]) then
Key:=#0;
end;
procedure TForm2.FormShow(Sender: TObject);
begin
txtRamal.SetFocus;
end;
end.
|
unit CustLayout;
interface
uses Classes, HTTPApp, Db, DbClient, Midas,
XMLBrokr, WebComp, PagItems, MidItems;
type
TTitleLayoutGroup = class(TLayoutGroup)
private
FCaption: string;
FCaptionPosition: TCaptionPosition;
FCaptionAttributes: TCaptionAttributes;
protected
function ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string; override;
procedure SetCaptionAttributes(const Value: TCaptionAttributes);
function FormatCaption: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property CaptionPosition: TCaptionPosition
read FCaptionPosition write FCaptionPosition;
property Caption: string read FCaption write FCaption;
property CaptionAttributes: TCaptionAttributes
read FCaptionAttributes write SetCaptionAttributes;
end;
TTitleDataForm = class(TDataForm)
private
FCaption: string;
FCaptionPosition: TCaptionPosition;
FCaptionAttributes: TCaptionAttributes;
protected
function ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string; override;
procedure SetCaptionAttributes(const Value: TCaptionAttributes);
function FormatCaption: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property CaptionPosition: TCaptionPosition
read FCaptionPosition write FCaptionPosition;
property Caption: string read FCaption write FCaption;
property CaptionAttributes: TCaptionAttributes
read FCaptionAttributes write SetCaptionAttributes;
end;
implementation
uses sysutils;
{ TTitleLayoutGroup }
constructor TTitleLayoutGroup.Create(AOwner: TComponent);
begin
inherited;
FCaptionAttributes := TCaptionAttributes.Create(Self);
FCaptionAttributes.Style := 'text-align: center';
FCaptionPosition := capAbove;
end;
destructor TTitleLayoutGroup.Destroy;
begin
inherited;
FCaptionAttributes.Free;
end;
function TTitleLayoutGroup.ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string;
var
FormLayout: TFormLayout;
function FormatField(Field: TComponent): string;
var
Intf: IWebContent;
begin
if Field.GetInterface(IWebContent, Intf) then
Result := Format('%0:s'#13#10, [Intf.Content(Options, FormLayout)])
end;
function Min(X, Y: Integer): Integer;
begin
Result := X;
if X > Y then Result := Y;
end;
var
I: Integer;
Intf: ILayoutWebContent;
Attribs: string;
begin
Result := '';
if WebFieldControls.Count = 0 then
Exit;
FormLayout := TFormLayout.Create(ParentLayout);
try
AddStringAttrib(Attribs, 'NAME', Name);
AddQuotedAttrib(Attribs, 'STYLE', Style);
AddQuotedAttrib(Attribs, 'CLASS', StyleRule);
AddCustomAttrib(Attribs, Custom);
if DisplayColumns >= 1 then
begin
FormLayout.ColumnCount := Min(DisplayColumns, WebFieldControls.Count);
FormLayout.BreakButtons := True;
end;
FormLayout.TableHeader :=
Format('<TABLE %s>', [Attribs]);
for I := 0 to WebFieldControls.Count - 1 do
begin
Result := Result +
FormatField(WebFieldControls[I]);
end;
Result := Result + FormLayout.EndLayout;
if Assigned(ParentLayout) and ParentLayout.GetInterface(ILayoutWebContent, Intf) then
if Caption = '' then
Result := Intf.LayoutTable(Result, GetLayoutAttributes)
else
Result := Intf.LayoutLabelAndField(FormatCaption, Result, GetLayoutAttributes);
finally
FormLayout.Free;
end;
end;
function TTitleLayoutGroup.FormatCaption: string;
var
Attribs: string;
begin
AddQuotedAttrib(Attribs, 'STYLE', CaptionAttributes.Style);
AddCustomAttrib(Attribs, CaptionAttributes.Custom);
AddQuotedAttrib(Attribs, 'CLASS', CaptionAttributes.StyleRule);
GetLayoutAttributes.LabelAttributes := Attribs;
case CaptionPosition of
capLeft: GetLayoutAttributes.LabelPosition := lposLeft;
capRight: GetLayoutAttributes.LabelPosition := lposRight;
capAbove: GetLayoutAttributes.LabelPosition := lposAbove;
capBelow: GetLayoutAttributes.LabelPosition := lposBelow;
else
Assert(False, 'Unknown position');
end;
if Attribs <> '' then
Result := Format('<SPAN %0:s>%1:s</SPAN>', [Attribs, Caption])
else
Result := Caption;
end;
procedure TTitleLayoutGroup.SetCaptionAttributes(
const Value: TCaptionAttributes);
begin
FCaptionAttributes.Assign(Value);
end;
{ TTitleDataForm }
constructor TTitleDataForm.Create(AOwner: TComponent);
begin
inherited;
FCaptionAttributes := TCaptionAttributes.Create(Self);
FCaptionAttributes.Style := 'text-align: center';
FCaptionPosition := capAbove;
end;
destructor TTitleDataForm.Destroy;
begin
inherited;
FCaptionAttributes.Free;
end;
function TTitleDataForm.FormatCaption: string;
var
Attribs: string;
begin
AddQuotedAttrib(Attribs, 'STYLE', CaptionAttributes.Style);
AddCustomAttrib(Attribs, CaptionAttributes.Custom);
AddQuotedAttrib(Attribs, 'CLASS', CaptionAttributes.StyleRule);
GetLayoutAttributes.LabelAttributes := Attribs;
case CaptionPosition of
capLeft: GetLayoutAttributes.LabelPosition := lposLeft;
capRight: GetLayoutAttributes.LabelPosition := lposRight;
capAbove: GetLayoutAttributes.LabelPosition := lposAbove;
capBelow: GetLayoutAttributes.LabelPosition := lposBelow;
else
Assert(False, 'Unknown position');
end;
if Attribs <> '' then
Result := Format('<SPAN %0:s>%1:s</SPAN>', [Attribs, Caption])
else
Result := Caption;
end;
function TTitleDataForm.ImplContent(Options: TWebContentOptions;
ParentLayout: TLayout): string;
var
Intf: ILayoutWebContent;
begin
Result := inherited ImplContent(Options, ParentLayout);
if Caption <> '' then
begin
with TFormLayout.Create(ParentLayout) do
try
if GetInterface(ILayoutWebContent, Intf) then
Result := Intf.LayoutLabelAndField(FormatCaption, Result, GetLayoutAttributes);
finally
Result := Result + EndLayout;
Free;
end;
end;
end;
procedure TTitleDataForm.SetCaptionAttributes(
const Value: TCaptionAttributes);
begin
FCaptionAttributes.Assign(Value);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ CGI/WinCGI Web server application components }
{ }
{ Copyright (c) 1997,98 Inprise Corporation }
{ }
{*******************************************************}
unit CGIApp;
interface
uses Windows, Classes, HTTPApp, IniFiles;
type
TCGIRequest = class(TWebRequest)
private
FContent: string;
protected
function GetStringVariable(Index: Integer): string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
public
constructor Create;
function GetFieldByName(const Name: string): string; override;
function ReadClient(var Buffer; Count: Integer): Integer; override;
function ReadString(Count: Integer): string; override;
function TranslateURI(const URI: string): string; override;
function WriteClient(var Buffer; Count: Integer): Integer; override;
function WriteString(const AString: string): Boolean; override;
end;
TCGIResponse = class(TWebResponse)
private
FStatusCode: Integer;
FStringVariables: array[0..MAX_STRINGS - 1] of string;
FIntegerVariables: array[0..MAX_INTEGERS - 1] of Integer;
FDateVariables: array[0..MAX_DATETIMES - 1] of TDateTime;
FContent: string;
FSent: Boolean;
protected
function GetContent: string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetLogMessage: string; override;
function GetStatusCode: Integer; override;
function GetStringVariable(Index: Integer): string; override;
procedure SetContent(const Value: string); override;
procedure SetDateVariable(Index: Integer; const Value: TDateTime); override;
procedure SetIntegerVariable(Index: Integer; Value: Integer); override;
procedure SetLogMessage(const Value: string); override;
procedure SetStatusCode(Value: Integer); override;
procedure SetStringVariable(Index: Integer; const Value: string); override;
public
constructor Create(HTTPRequest: TWebRequest);
procedure SendResponse; override;
procedure SendRedirect(const URI: string); override;
procedure SendStream(AStream: TStream); override;
function Sent: Boolean; override;
end;
TWinCGIRequest = class(TCGIRequest)
private
FIniFile: TIniFile;
FClientData, FServerData: TFileStream;
protected
function GetStringVariable(Index: Integer): string; override;
public
constructor Create(IniFileName, ContentFile, OutputFile: string);
destructor Destroy; override;
function GetFieldByName(const Name: string): string; override;
function ReadClient(var Buffer; Count: Integer): Integer; override;
function ReadString(Count: Integer): string; override;
function TranslateURI(const URI: string): string; override;
function WriteClient(var Buffer; Count: Integer): Integer; override;
function WriteString(const AString: string): Boolean; override;
end;
TWinCGIResponse = class(TCGIResponse);
TCGIApplication = class(TWebApplication)
private
FOutputFileName: string;
function NewRequest: TCGIRequest;
function NewResponse(CGIRequest: TCGIRequest): TCGIResponse;
public
procedure Run; override;
end;
implementation
uses SysUtils, WebConst;
const
CGIServerVariables: array[0..28] of string = (
'REQUEST_METHOD',
'SERVER_PROTOCOL',
'URL',
'QUERY_STRING',
'PATH_INFO',
'PATH_TRANSLATED',
'HTTP_CACHE_CONTROL',
'HTTP_DATE',
'HTTP_ACCEPT',
'HTTP_FROM',
'HTTP_HOST',
'HTTP_IF_MODIFIED_SINCE',
'HTTP_REFERER',
'HTTP_USER_AGENT',
'HTTP_CONTENT_ENCODING',
'HTTP_CONTENT_TYPE',
'HTTP_CONTENT_LENGTH',
'HTTP_CONTENT_VERSION',
'HTTP_DERIVED_FROM',
'HTTP_EXPIRES',
'HTTP_TITLE',
'REMOTE_ADDR',
'REMOTE_HOST',
'SCRIPT_NAME',
'SERVER_PORT',
'',
'HTTP_CONNECTION',
'HTTP_COOKIE',
'HTTP_AUTHORIZATION');
{ TCGIRequest }
constructor TCGIRequest.Create;
begin
inherited Create;
FContent := ReadString(ContentLength);
end;
function TCGIRequest.GetFieldByName(const Name: string): string;
var
Buffer: array[0..4095] of Char;
function StripHTTP(const Name: string): string;
begin
if Pos('HTTP_', Name) = 1 then
Result := Copy(Name, 6, MaxInt)
else Result := Name;
end;
begin
SetString(Result, Buffer, GetEnvironmentVariable(PChar(Name), Buffer, SizeOf(Buffer)));
if Result = '' then
SetString(Result, Buffer, GetEnvironmentVariable(PChar(StripHTTP(Name)), Buffer, SizeOf(Buffer)));
end;
function TCGIRequest.GetStringVariable(Index: Integer): string;
begin
if Index = 25 then
Result := FContent
else Result := GetFieldByName(CGIServerVariables[Index]);
end;
function TCGIRequest.GetDateVariable(Index: Integer): TDateTime;
var
Value: string;
begin
Value := GetStringVariable(Index);
if Value <> '' then
Result := ParseDate(Value)
else Result := -1;
end;
function TCGIRequest.GetIntegerVariable(Index: Integer): Integer;
var
Value: string;
begin
Value := GetStringVariable(Index);
Result := StrToIntDef(Value, -1)
end;
function TCGIRequest.ReadClient(var Buffer; Count: Integer): Integer;
begin
Result := FileRead(TTextRec(Input).Handle, Buffer, Count);
end;
function TCGIRequest.ReadString(Count: Integer): string;
begin
SetLength(Result, Count);
if Count > 0 then
SetLength(Result, FileRead(TTextRec(Input).Handle, Pointer(Result)^, Count));
end;
function TCGIRequest.TranslateURI(const URI: string): string;
begin
end;
function TCGIRequest.WriteClient(var Buffer; Count: Integer): Integer;
begin
Result := FileWrite(TTextRec(Output).Handle, Buffer, Count);
end;
function TCGIRequest.WriteString(const AString: string): Boolean;
begin
if AString <> '' then
Result := FileWrite(TTextRec(Output).Handle, Pointer(AString)^, Length(AString)) = Length(AString)
else Result := False;
end;
{ TCGIResponse }
constructor TCGIResponse.Create(HTTPRequest: TWebRequest);
begin
inherited Create(HTTPRequest);
if FHTTPRequest.ProtocolVersion = '' then
Version := '1.0';
StatusCode := 200;
LastModified := -1;
Expires := -1;
Date := -1;
ContentType := 'text/html';
end;
function TCGIResponse.GetContent: string;
begin
Result := FContent;
end;
function TCGIResponse.GetDateVariable(Index: Integer): TDateTime;
begin
if (Index >= 0) and (Index < 3) then
Result := FDateVariables[Index]
else Result := -1;
end;
function TCGIResponse.GetIntegerVariable(Index: Integer): Integer;
begin
if (Index >= 0) and (Index < 2) then
Result := FIntegerVariables[Index]
else Result := -1;
end;
function TCGIResponse.GetLogMessage: string;
begin
// Result := TCGIRequest(HTTPRequest).ECB.lpszLogData;
end;
function TCGIResponse.GetStatusCode: Integer;
begin
Result := FStatusCode;
end;
function TCGIResponse.GetStringVariable(Index: Integer): string;
begin
if (Index >= 0) and (Index < 12) then
Result := FStringVariables[Index];
end;
function TCGIResponse.Sent: Boolean;
begin
Result := FSent;
end;
procedure TCGIResponse.SetContent(const Value: string);
begin
FContent := Value;
ContentLength := Length(FContent);
end;
procedure TCGIResponse.SetDateVariable(Index: Integer; const Value: TDateTime);
begin
if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then
if Value <> FDateVariables[Index] then
FDateVariables[Index] := Value;
end;
procedure TCGIResponse.SetIntegerVariable(Index: Integer; Value: Integer);
begin
if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then
if Value <> FDateVariables[Index] then
FIntegerVariables[Index] := Value;
end;
procedure TCGIResponse.SetLogMessage(const Value: string);
begin
// StrPLCopy(TCGIRequest(HTTPRequest).ECB.lpszLogData, Value, HSE_LOG_BUFFER_LEN);
end;
procedure TCGIResponse.SetStatusCode(Value: Integer);
begin
if FStatusCode <> Value then
begin
FStatusCode := Value;
ReasonString := StatusString(Value);
end;
end;
procedure TCGIResponse.SetStringVariable(Index: Integer; const Value: string);
begin
if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then
FStringVariables[Index] := Value;
end;
procedure TCGIResponse.SendResponse;
var
StatusString: string;
Headers: string;
I: Integer;
procedure AddHeaderItem(const Item, FormatStr: string);
begin
if Item <> '' then
Headers := Headers + Format(FormatStr, [Item]);
end;
begin
if HTTPRequest.ProtocolVersion <> '' then
begin
if (ReasonString <> '') and (StatusCode > 0) then
StatusString := Format('%d %s', [StatusCode, ReasonString])
else StatusString := '200 OK';
AddHeaderItem(StatusString, 'Status: %s'#13#10);
AddHeaderItem(Location, 'Location: %s'#13#10);
AddHeaderItem(Allow, 'Allow: %s'#13#10);
for I := 0 to Cookies.Count - 1 do
AddHeaderItem(Cookies[I].HeaderValue, 'Set-Cookie: %s'#13#10);
AddHeaderItem(DerivedFrom, 'Derived-From: %s'#13#10);
if Expires > 0 then
Format(FormatDateTime('"Expires: "' + sDateFormat + ' "GMT"'#13#10, Expires),
[DayOfWeekStr(Expires), MonthStr(Expires)]);
if LastModified > 0 then
Format(FormatDateTime('"Last-Modified: "' + sDateFormat + ' "GMT"'#13#10,
LastModified), [DayOfWeekStr(LastModified), MonthStr(LastModified)]);
AddHeaderItem(Title, 'Title: %s'#13#10);
AddHeaderItem(WWWAuthenticate, 'WWW-Authenticate: %s'#13#10);
AddCustomHeaders(Headers);
AddHeaderItem(ContentVersion, 'Content-Version: %s'#13#10);
AddHeaderItem(ContentEncoding, 'Content-Encoding: %s'#13#10);
AddHeaderItem(ContentType, 'Content-Type: %s'#13#10);
if (Content <> '') or (ContentStream <> nil) then
AddHeaderItem(IntToStr(ContentLength), 'Content-Length: %s'#13#10);
Headers := Headers + 'Content:'#13#10#13#10;
HTTPRequest.WriteString(Headers);
end;
if ContentStream = nil then
HTTPRequest.WriteString(Content)
else if ContentStream <> nil then
begin
SendStream(ContentStream);
ContentStream := nil; // Drop the stream
end;
FSent := True;
end;
procedure TCGIResponse.SendRedirect(const URI: string);
begin
Location := URI;
StatusCode := 302;
ContentType := 'text/html';
Content := Format(sDocumentMoved, [URI]);
SendResponse;
end;
procedure TCGIResponse.SendStream(AStream: TStream);
var
Buffer: array[0..8191] of Byte;
BytesToSend: Integer;
begin
while AStream.Position < AStream.Size do
begin
BytesToSend := AStream.Read(Buffer, SizeOf(Buffer));
FHTTPRequest.WriteClient(Buffer, BytesToSend);
end;
end;
const
WinCGIServerVariables: array[0..28] of string = (
'Request Method',
'Request Protocol',
'Url',
'Query String',
'Logical Path',
'Physical Path',
'Cache Control',
'Date',
'Accept',
'From',
'Host',
'If-Modified-Since',
'Referer',
'User-Agent',
'Content-Encoding',
'Content Type',
'Content Length',
'Content Version',
'Derived-From',
'Expires',
'Title',
'Remote Address',
'Remote Host',
'Executable Path',
'Server Port',
'',
'Connection',
'Cookie',
'Authorization');
{ TWinCGIRequest }
constructor TWinCGIRequest.Create(IniFileName, ContentFile, OutputFile: string);
begin
FIniFile := TIniFile.Create(IniFileName);
if ContentFile = '' then
ContentFile := FIniFile.ReadString('System', 'Content File', '');
if OutputFile = '' then
OutputFile := FIniFile.ReadString('System', 'Output File', '');
if FileExists(ContentFile) then
FClientData := TFileStream.Create(ContentFile, fmOpenRead or fmShareDenyNone);
if FileExists(OutputFile) then
FServerData := TFileStream.Create(OutputFile, fmOpenWrite or fmShareDenyNone)
else FServerData := TFileStream.Create(OutputFile, fmCreate);
inherited Create;
end;
destructor TWinCGIRequest.Destroy;
begin
FIniFile.Free;
if FClientData <> nil then
FClientData.Free;
FServerData.Free;
inherited Destroy;
end;
function TWinCGIRequest.GetFieldByName(const Name: string): string;
begin
Result := FIniFile.ReadString('Extra Headers', Name, '');
end;
function TWinCGIRequest.GetStringVariable(Index: Integer): string;
function AcceptSection: string;
var
Section: TStringList;
I: Integer;
begin
Section := TStringList.Create;
try
FIniFile.ReadSection('Accept', Section);
Result := '';
for I := 0 to Section.Count - 1 do
Result := Result + Section[I] + ',';
if Result <> '' then SetLength(Result, Length(Result) - 1);
finally
Section.Free;
end;
end;
begin
case Index of
0..1,3..5,15..16,
21..24, 26, 28:
Result := FIniFile.ReadString('CGI', WinCGIServerVariables[Index], '');
25: Result := FContent;
27: Result := FIniFile.ReadString('Extra Headers', WinCGIServerVariables[Index], '');
8: Result := AcceptSection;
else
if (Index >= Low(WinCGIServerVariables)) and (Index <= High(WinCGIServerVariables)) then
Result := GetFieldByName(WinCGIServerVariables[Index])
else Result := '';
end;
end;
function TWinCGIRequest.ReadClient(var Buffer; Count: Integer): Integer;
begin
if FClientData <> nil then
Result := FClientData.Read(Buffer, Count)
else Result := 0;
end;
function TWinCGIRequest.ReadString(Count: Integer): string;
begin
if (Count > 0) and (FClientData <> nil) then
begin
SetLength(Result, Count);
SetLength(Result, FClientData.Read(Pointer(Result)^, Count));
end else Result := '';
end;
function TWinCGIRequest.TranslateURI(const URI: string): string;
begin
end;
function TWinCGIRequest.WriteClient(var Buffer; Count: Integer): Integer;
begin
Result := FServerData.Write(Buffer, Count);
end;
function TWinCGIRequest.WriteString(const AString: string): Boolean;
begin
if AString <> '' then
Result := FServerData.Write(Pointer(AString)^, Length(AString)) = Length(AString)
else Result := False;
end;
{ TCGIApplication }
procedure HandleServerException(E: Exception; const OutputFile: string);
var
ResultText, ResultHeaders: string;
OutFile: TStream;
begin
ResultText := Format(sInternalServerError, [E.ClassName, E.Message]);
ResultHeaders := Format(
'Status: 500 %s'#13#10+ //Not resourced
'Content-Type: text/html'#13#10 + //Not resourced
'Content-Length: %d'#13#10 + //Not resourced
'Content:'#13#10#13#10, [E.Message, Length(ResultText)]); //Not resourced
if IsConsole then
begin
FileWrite(TTextRec(Output).Handle, Pointer(ResultHeaders)^, Length(ResultHeaders));
FileWrite(TTextRec(Output).Handle, Pointer(ResultText)^, Length(ResultText));
end else
begin
if FileExists(OutputFile) then
OutFile := TFileStream.Create(OutputFile, fmOpenWrite or fmShareDenyNone)
else OutFile := TFileStream.Create(OutputFile, fmCreate);
try
OutFile.Write(Pointer(ResultHeaders)^, Length(ResultHeaders));
OutFile.Write(Pointer(ResultText)^, Length(ResultText));
finally
OutFile.Free;
end;
end;
end;
function TCGIApplication.NewRequest: TCGIRequest;
var
Buffer: array[0..MAX_PATH] of Char;
begin
if IsConsole then
Result := TCGIRequest.Create
else
begin
Result := TWinCGIRequest.Create(ParamStr(1), ParamStr(2), ParamStr(3));
FOutputFileName := ParamStr(3);
if FOutputFileName = '' then
SetString(FOutputFileName, Buffer, GetPrivateProfileString('System',
'Output File', '', Buffer, SizeOf(Buffer), PChar(ParamStr(1))));
end;
end;
function TCGIApplication.NewResponse(CGIRequest: TCGIRequest): TCGIResponse;
begin
if IsConsole then
Result := TCGIResponse.Create(CGIRequest)
else Result := TWinCGIResponse.Create(CGIRequest);
end;
procedure TCGIApplication.Run;
var
HTTPRequest: TCGIRequest;
HTTPResponse: TCGIResponse;
begin
inherited Run;
if IsConsole then
begin
Rewrite(Output);
Reset(Input);
end;
try
HTTPRequest := NewRequest;
try
HTTPResponse := NewResponse(HTTPRequest);
try
HandleRequest(HTTPRequest, HTTPResponse);
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
except
HandleServerException(Exception(ExceptObject), FOutputFileName);
end;
end;
procedure InitApplication;
begin
Application := TCGIApplication.Create(nil);
end;
procedure DoneApplication;
begin
Application.Free;
Application := nil;
end;
initialization
InitApplication;
finalization
DoneApplication;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit Swap;
interface
const
UseEmsIfAvailable : Boolean = True; {True to use EMS if available}
BytesSwapped : LongInt = 0; {Bytes to swap to EMS/disk}
EmsAllocated : Boolean = False; {True when EMS allocated for swap}
FileAllocated : Boolean = False; {True when file allocated for swap}
function ExecWithSwap(Path, CmdLine : String) : Word;
{-DOS EXEC supporting swap to EMS or disk}
function InitExecSwap(LastToSave : Pointer; SwapFileName : String) : Boolean;
{-Initialize for swapping, returning TRUE if successful}
procedure ShutdownExecSwap;
{-Deallocate swap area}
implementation
var
EmsHandle : Word; {Handle of EMS allocation block}
FrameSeg : Word; {Segment of EMS page frame}
FileHandle : Word; {DOS handle of swap file}
SwapName : String[80]; {ASCIIZ name of swap file}
SaveExit : Pointer; {Exit chain pointer}
{$L SWAP.OBJ}
function ExecWithSwap(Path, CmdLine : String) : Word; external;
procedure FirstToSave; external;
function AllocateSwapFile : Boolean; external;
procedure DeallocateSwapFile; external;
{$F+} {These routines could be interfaced for general use}
function EmsInstalled : Boolean; external;
function EmsPageFrame : Word; external;
function AllocateEmsPages(NumPages : Word) : Word; external;
procedure DeallocateEmsHandle(Handle : Word); external;
function DefaultDrive : Char; external;
function DiskFree(Drive : Byte) : LongInt; external;
procedure ExecSwapExit;
begin
ExitProc := SaveExit;
ShutdownExecSwap;
end;
{$F-}
procedure ShutdownExecSwap;
begin
if EmsAllocated then begin
DeallocateEmsHandle(EmsHandle);
EmsAllocated := False;
end else if FileAllocated then begin
DeallocateSwapFile;
FileAllocated := False;
end;
end;
function PtrDiff(H, L : Pointer) : LongInt;
type
OS = record O, S : Word; end; {Convenient typecast}
begin
PtrDiff := (LongInt(OS(H).S) shl 4+OS(H).O)-
(LongInt(OS(L).S) shl 4+OS(L).O);
end;
function InitExecSwap(LastToSave : Pointer;
SwapFileName : String) : Boolean;
const
EmsPageSize = 16384; {Bytes in a standard EMS page}
var
PagesInEms : Word; {Pages needed in EMS}
BytesFree : LongInt; {Bytes free on swap file drive}
DriveChar : Char; {Drive letter for swap file}
begin
InitExecSwap := False;
if EmsAllocated or FileAllocated then
Exit;
BytesSwapped := PtrDiff(LastToSave, @FirstToSave);
if BytesSwapped <= 0 then
Exit;
if UseEmsIfAvailable and EmsInstalled then begin
PagesInEms := (BytesSwapped+EmsPageSize-1) div EmsPageSize;
EmsHandle := AllocateEmsPages(PagesInEms);
if EmsHandle <> $FFFF then begin
EmsAllocated := True;
FrameSeg := EmsPageFrame;
if FrameSeg <> 0 then begin
InitExecSwap := True;
Exit;
end;
end;
end;
if Length(SwapFileName) <> 0 then begin
SwapName := SwapFileName+#0;
if Pos(':', SwapFileName) = 2 then
DriveChar := Upcase(SwapFileName[1])
else
DriveChar := DefaultDrive;
BytesFree := DiskFree(Byte(DriveChar)-$40);
FileAllocated := (BytesFree > BytesSwapped) and AllocateSwapFile;
if FileAllocated then
InitExecSwap := True;
end;
end;
begin
SaveExit := ExitProc;
ExitProc := @ExecSwapExit;
end.
|
unit FrostUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls;
type
TFrostForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
EditH: TEdit;
TrackBarH: TTrackBar;
TrackBarV: TTrackBar;
UpDownH: TUpDown;
UpDownV: TUpDown;
EditV: TEdit;
OKButton: TButton;
CancelButton: TButton;
procedure TrackBarHChange(Sender: TObject);
procedure TrackBarVChange(Sender: TObject);
procedure EditHChange(Sender: TObject);
procedure EditVChange(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrostForm: TFrostForm;
UndoImage:TBitmap;
implementation
{$R *.dfm}
Uses MainUnit;
procedure Disorder(Bitmap:TBitmap; H,V:integer; BColor:TColor);
function RandomInRadius(Num,Radius:integer):integer;
begin
if Random(2)=0 then
Result:=Num+Random(Radius)
else
Result:=Num-random(Radius);
end;
type TRGB=record
R,G,B:byte;
end;
pRGB=^TRGB;
var x,y,ww,hh,xr,yr:integer;
Dest1,Dest2,Src1,Src2:PRGB;
bmp:TBitmap;
begin
Randomize;
Bitmap.PixelFormat:=pf24bit;
bmp:=TBitmap.Create;
try
bmp.Assign(Bitmap);
ww:=Bitmap.Width-1;
hh:=Bitmap.Height-1;
Bitmap.Canvas.Brush.Color:=BColor;
Bitmap.Canvas.FillRect(Rect(0,0,ww+1,hh+1));
for y:=0 to hh do begin
for x:=0 to ww do begin
xr:=RandomInRadius(x,H);
yr:=RandominRadius(y,V);
if (xr>=0) and (xr<ww) and (yr>=0) and (yr<hh) then begin
Src1:=bmp.ScanLine[y];
Src2:=bmp.ScanLine[yr];
Dest1:=Bitmap.ScanLine[y];
Dest2:=Bitmap.ScanLine[yr];
Inc(Src1,x);
Inc(Src2,xr);
Inc(Dest1,x);
Inc(Dest2,xr);
Dest1^:=Src2^;
Dest2^:=Src1^;
end;
end;
end;
finally
bmp.Free;
end;
end;
procedure TFrostForm.CancelButtonClick(Sender: TObject);
begin
buffer.Assign(img);
MainForm.PaintBox.Canvas.CopyRect(bounds(0,0,img.Width,img.Height),buffer.Canvas,
bounds(0,0,img.Width,img.Height));
MainForm.PaintBox.Visible:=false;
MainForm.PaintBox.Visible:=true;
FrostForm.Close;
end;
procedure TFrostForm.EditHChange(Sender: TObject);
begin
TrackBarH.Position:=StrToInt(EditH.Text);
TrackBarH.Position:=StrToInt(EditH.Text);
Disorder(buffer,TrackBarH.Position,TrackBarV.Position,clWhite);
MainForm.PaintBox.Visible:=false;
MainForm.PaintBox.Visible:=true;
end;
procedure TFrostForm.EditVChange(Sender: TObject);
begin
TrackBarH.Position:=StrToInt(EditH.Text);
Disorder(buffer,TrackBarH.Position,TrackBarV.Position,clWhite);
MainForm.PaintBox.Visible:=false;
MainForm.PaintBox.Visible:=true;
end;
procedure TFrostForm.OKButtonClick(Sender: TObject);
begin
img.Assign(buffer);
MainForm.Log('Использован эффект: иней');
FrostForm.Close;
end;
procedure TFrostForm.TrackBarHChange(Sender: TObject);
begin
EditH.Text:=IntToStr(TrackBarH.Position);
end;
procedure TFrostForm.TrackBarVChange(Sender: TObject);
begin
EditV.Text:=IntToStr(TrackBarV.Position);
end;
end.
|
unit Support.Sandisk.USB;
interface
uses
SysUtils, Math,
Support, Device.SMART.List;
type
TSandiskUSBNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetFullSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsProductOfSandisk: Boolean;
function IsU100: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TSandiskNSTSupport }
function TSandiskUSBNSTSupport.IsU100: Boolean;
begin
result := (Pos('SANDISK', Identify.Model) > 0) and
((Pos('U100', Identify.Model) > 0) or (Pos('PSSD', Identify.Model) > 0));
end;
function TSandiskUSBNSTSupport.IsProductOfSandisk: Boolean;
begin
result := IsU100;
end;
function TSandiskUSBNSTSupport.GetFullSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := true;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TSandiskUSBNSTSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfSandisk then
result := GetFullSupport;
end;
function TSandiskUSBNSTSupport.GetTotalWrite: TTotalWrite;
const
LBAtoMiB: Double = 1/2 * 1/1024;
IDOfHostWrite = 241;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := Floor(RAWValue * LBAtoMiB);
end;
function TSandiskUSBNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 172;
IDOfReplacedSector = 5;
IDofUsedHour = 9;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := false;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
unit ElevationUtils;
{
#===============================================================================
# Name: ElevationUtils.pas
# Author: Aleksander Oven
# Created: 2007-03-01
# Last Change: 2007-03-01
# Version: 1.0
# Description:
Windows Vista COM Elevation Moniker implementation.
http://msdn2.microsoft.com/en-us/library/ms679687.aspx
# Warnings and/or special considerations:
Source code in this file is subject to the license specified below.
#===============================================================================
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 'ElevationUtils.pas'.
The Initial Developer of the Original Code is 'Aleksander Oven'.
Contributor(s): None.
#===============================================================================
}
interface
uses
Registry,
Windows;
function IsElevated: Boolean;
function IsUACEnabled: Boolean;
implementation
type
// Vista SDK - extended BIND_OPTS2 struct
// Vista SDK - extended TOKEN_INFORMATION_CLASS enum
TOKEN_INFORMATION_CLASS = (
TokenICPad, // dummy padding element
TokenUser,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
);
TOKEN_ELEVATION = packed record
TokenIsElevated: DWORD;
end;
PTOKEN_ELEVATION = ^TOKEN_ELEVATION;
function RegBool: Boolean;
var R : TRegistry;
begin
try
R := TRegistry.Create;
try
R.Access := KEY_READ;
R.RootKey := HKEY_LOCAL_MACHINE;
if R.OpenKeyReadOnly('\Software\Microsoft\Windows\CurrentVersion\Policies\System') then
Result := R.ReadBool('EnableLUA') else
Result := False;
finally
R.Free;
end;
except
Result := False;
end;
end;
function IsWinVista: Boolean;
var
VerInfo: TOSVersioninfo;
begin
VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
GetVersionEx(VerInfo);
Result := (VerInfo.dwMajorVersion >= 6);
end;
function IsUACEnabled: Boolean;
begin
Result := IsWinVista and RegBool;
end;
function GetTokenInformation(TokenHandle: THandle;
TokenInformationClass: TOKEN_INFORMATION_CLASS; TokenInformation: Pointer;
TokenInformationLength: DWORD; var ReturnLength: DWORD
): BOOL; stdcall; external advapi32 name 'GetTokenInformation';
function IsElevated: Boolean;
var
Token: THandle;
Elevation: TOKEN_ELEVATION;
Dummy: Cardinal;
begin
Result := False;
if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token) then begin
Dummy := 0;
if GetTokenInformation(Token, TokenElevation, @Elevation,
SizeOf(TOKEN_ELEVATION), Dummy)
then
Result := (Elevation.TokenIsElevated <> 0);
CloseHandle(Token);
end;
end;
end.
|
{
Huge Integer Numbers
By Mehran
}
unit numunit;
interface
const
CBase = 10;
MaxN = 100;
type
TInt = longint;
TDigit = integer;
TWorkDigit = longint;
TNumber = record
n:integer;
a:array [0..MaxN] of TDigit;
end;
function compareNumber(const a, b:TNumber):integer; (* approved *)
procedure assignInt(var a:TNumber; n:TInt); (* approved *)
function zeroNumber(const a:TNumber):boolean; (* approved *)
function toIntNumber(const a:TNumber):TInt; (* approved *)
function addNumber(const a,b:TNumber; var res:TNumber):boolean; (* approved *)
function mulNumber(const a,b:TNumber; var res:TNumber):boolean; (* approved *)
function subNumber(const a,b:TNumber; var res:TNumber):boolean; (* approved *)
function divNumber(const a,b:TNumber; var d, m:TNumber):boolean;
function addIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean; (* approved *)
function mulIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean; (* approved *)
function subIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean; (* approved *)
function shlNumber(const a:TNumber; b:integer; var res:TNumber):boolean; (* approved *)
procedure shrNumber(const a:TNumber; b:integer; var res:TNumber); (* approved *)
function powNumber(const a:TNumber; pow:integer; var res:TNumber):boolean; (* approved *)
procedure sqrtNumber(const a:TNumber; var res:TNumber);
implementation
function maxInteger(a,b:integer):integer;
begin
if a > b then maxInteger := a else maxInteger := b;
end;
function minInteger(a,b:integer):integer;
begin
if a < b then minInteger := a else minInteger := b;
end;
function compareNumber(const a, b:TNumber):integer;
var
i:integer;
begin
if a.n <> b.n then
compareNumber := a.n - b.n
else begin
i := a.n - 1;
while i >= 0 do begin
if a.a[i] <> b.a[i] then
break;
dec(i);
end;
compareNumber := a.a[i] - b.a[i];
end;
end;
procedure assignInt(var a:TNumber; n:TInt);
begin
a.n := 0;
while n > 0 do begin
a.a[a.n] := n mod CBase;
n := n div CBase;
inc(a.n);
end;
a.a[a.n] := 0;
end;
function zeroNumber(const a:TNumber):boolean;
begin
zeroNumber := a.n = 0;
end;
function toIntNumber(const a:TNumber):TInt;
var
return:TInt;
i:integer;
begin
return := 0;
i := a.n;
while i > 0 do begin
dec(i);
return := return * CBase + a.a[i];
end;
toIntNumber := return;
end;
function addNumber(const a,b:TNumber; var res:TNumber):boolean;
var
i:integer;
c:TDigit;
begin
res.n := maxInteger(a.n,b.n);
c := 0;
i := 0;
while i < res.n do begin
inc(c,a.a[minInteger(i,a.n)] + b.a[minInteger(i,b.n)]);
res.a[i] := c mod CBase;
c := c div CBase;
inc(i);
end;
if c <> 0 then begin
res.a[res.n] := 1;
inc(res.n);
end;
if res.n = maxN then
addNumber := false
else begin
res.a[res.n] := 0;
addNumber := true;
end;
end;
function mulNumber(const a,b:TNumber; var res:TNumber):boolean;
var
c:TWorkDigit; (* can be integer *)
i,j,max:integer;
begin
res.n := a.n + b.n - 1;
if res.n >= maxN then begin
mulNumber := false;
exit;
end;
c := 0;
for i := 0 to res.n-1 do begin
for j := 0 to i do
inc(c,TWorkDigit(a.a[minInteger(j,a.n)]) * b.a[minInteger(i-j,b.n)]);
res.a[i] := c mod CBase;
c := c div CBase;
end;
if c > 0 then begin
res.a[res.n] := c;
inc(res.n);
end;
if res.n = maxN then
mulNumber := false
else begin
res.a[res.n] := 0;
mulNumber := true;
end;
end;
function subNumber(const a,b:TNumber; var res:TNumber):boolean;
var
i:integer;
c:TDigit;
begin
res.n := maxInteger(a.n,b.n);
c := 0;
i := 0;
while i < res.n do begin
inc(c,a.a[minInteger(i,a.n)] - b.a[minInteger(i,b.n)]);
if c < 0 then begin
res.a[i] := c + CBase;
c := -1;
end else begin
res.a[i] := c;
c := 0;
end;
inc(i);
end;
if c = -1 then begin
c := 1;
i := 0;
while i < res.n do begin
res.a[i] := (CBase - 1) - res.a[i] + c;
if res.a[i] = CBase then begin
res.a[i] := 0;
c := 1;
end else
c := 0;
inc(i);
end;
subNumber := false
end else begin
subNumber := true;
end;
res.a[res.n] := 0;
while (res.n > 0) and (res.a[res.n-1] = 0) do
dec(res.n);
end;
function divNumber(const a,b:TNumber; var d, m:TNumber):boolean;
var
i,j:integer;
c:TWorkDigit;
diff2,diff:TDigit;
begin
if zeroNumber(b) then begin
divNumber := false;
exit;
end;
if a.n < b.n then begin
assignInt(d,0);
m := a;
end;
m := a;
i := a.n - b.n + 1;
d.n := i;
d.a[i] := 0;
while i > 0 do begin
dec(i);
d.a[i] := 0;
for j := i+b.n downto i do begin
diff := m.a[j] - b.a[j-i];
if diff <> 0 then
break;
end;
while diff >= 0 do begin
diff := 0;
c := 0;
inc(d.a[i]);
for j := i to i+b.n do begin
inc(c,b.a[j-i]-m.a[j]);
if c < 0 then begin
m.a[j] := -c;
c := 0;
end else if c mod CBase = 0 then begin
m.a[j] := 0;
c := c div CBase;
end else begin
m.a[j] := CBase - c mod CBase;
c := c div CBase + 1;
end;
diff2 := m.a[j] - b.a[j-i];
if diff2 <> 0 then
diff := diff2;
end;
end;
while (m.n > 0) and (m.a[m.n-1] = 0) do
dec(m.n);
end;
while (d.n > 0) and (d.a[d.n-1] = 0) do
dec(d.n);
divNumber := true;
end;
function addIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean;
var
i:integer;
begin
res.n := a.n;
i := 0;
while i < res.n do begin
inc(b,a.a[i]);
res.a[i] := b mod CBase;
b := b div CBase;
inc(i);
end;
while b > 0 do begin
res.a[res.n] := b mod CBase;
b := b div CBase;
inc(res.n);
if res.n = maxN then begin
addIntNumber := false;
exit;
end;
end;
res.a[res.n] := 0;
addIntNumber := true;
end;
function mulIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean;
var
i:integer;
c:TInt;
begin
res.n := a.n;
c := 0;
i := 0;
while i < res.n do begin
inc(c,b*a.a[i]);
res.a[i] := c mod CBase;
c := c div CBase;
inc(i);
end;
while c > 0 do begin
res.a[res.n] := c mod CBase;
c := c div CBase;
inc(res.n);
if res.n = maxN then begin
mulIntNumber := false;
exit;
end;
end;
res.a[res.n] := 0;
mulIntNumber := true;
end;
function subIntNumber(const a:TNumber; b:TInt; var res:TNumber):boolean;
var
i:integer;
begin
res.n := a.n;
i := 0;
while i < res.n do begin
dec(b,a.a[i]);
if b < 0 then begin
res.a[i] := -b;
b := 0;
end else if b mod CBase = 0 then begin
res.a[i] := 0;
b := b div CBase;
end else begin
res.a[i] := CBase - b mod CBase;
b := b div CBase + 1;
end;
inc(i);
end;
if b > 0 then begin
subIntNumber := false;
exit;
end;
res.a[res.n] := 0;
subIntNumber := true;
while (res.n > 0) and (res.a[res.n-1] = 0) do
dec(res.n);
end;
function shlNumber(const a:TNumber; b:integer; var res:TNumber):boolean;
var
i:integer;
begin
res.n := a.n + b;
if res.n >= Maxn then
shlNumber := false
else begin
for i := 0 to a.n do
res.a[i+b] := a.a[i];
for i := 0 to b-1 do
res.a[i] := 0;
shlNumber := true;
end;
end;
procedure shrNumber(const a:TNumber; b:integer; var res:TNumber);
var
i:integer;
begin
if b > a.n then
b := a.n;
res.n := a.n - b;
for i := a.n downto b do
res.a[i-b] := a.a[i];
end;
function powNumber(const a:TNumber; pow:integer; var res:TNumber):boolean;
var
temp:TNumber;
i:integer;
begin
powNumber := true;
i := $4000;
assignInt(res,1);
while i > 0 do begin
if not mulNumber(res,res,temp) then begin
powNumber := false;
exit;
end;
res := temp;
if i and pow > 0 then begin
if not mulNumber(res,a,temp) then begin
powNumber := false;
exit;
end;
res := temp;
end;
i := i shr 1;
end;
end;
procedure sqrtNumber(const a:TNumber; var res:TNumber);
var
temp1,temp2,temp3:TNumber;
i:integer;
begin
if zeroNumber(a) then begin
res := a;
exit;
end;
res.n := a.n div 2 + 1;
for i := 0 to res.n-1 do
res.a[i] := CBase - 1;
res.a[res.n] := 0;
while true do begin
mulNumber(res,res,temp1);
if compareNumber(temp1,a) <= 0 then
break;
addNumber(temp1,a,temp2);
mulIntNumber(res,2,temp1);
divNumber(temp2,temp1,res,temp3);
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls ,ComCtrls,uSoundTypes,uToneGenerator, sTrackBar,
ExtCtrls ;
type
TVolumeLevel = 0..127;
type
TForm1 = class(TForm)
Button1: TButton;
btnSave: TButton;
edtFrequency: TEdit;
edtDuration: TEdit;
strckbr1: TsTrackBar;
cbbSampleRate: TComboBox;
rgChannel: TRadioGroup;
rb1: TRadioButton;
rb2: TRadioButton;
dlgSave1: TSaveDialog;
lbl1: TLabel;
lbl2: TLabel;
btn1: TButton;
procedure Button1Click(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btn1Click(Sender: TObject);
private
tone:TToneGenerator;
{ Private declarations }
public
// constructor Create(AOwner:TComponent);override;
// destructor destroy;override;
{ Public declarations }
procedure MakeSound(Frequency{Hz}, Duration{mSec}: Integer; Volume: TVolumeLevel);
end;
var
Form1: TForm1;
implementation
uses winapi.MMSystem;
{$R *.dfm}
procedure TForm1.MakeSound(Frequency{Hz}, Duration{mSec}: Integer; Volume: TVolumeLevel);
{writes tone to memory and plays it}
var
WaveFormatEx: TWaveFormatEx;
MS: TMemoryStream;
i, TempInt, DataCount, RiffCount: integer;
SoundValue: byte;
w: double; // omega ( 2 * pi * frequency)
const
Mono: Word = $0001;
SampleRate: Integer = 11025; // 8000, 11025, 22050, or 44100
RiffId: AnsiString = 'RIFF';
WaveId: AnsiString = 'WAVE';
FmtId: AnsiString = 'fmt ';
DataId: AnsiString = 'data';
begin
if Frequency > (0.6 * SampleRate) then
begin
ShowMessage(Format('Sample rate of %d is too Low to play a tone of %dHz',
[SampleRate, Frequency]));
Exit;
end;
with WaveFormatEx do
begin
wFormatTag := WAVE_FORMAT_PCM;
nChannels := Mono;
nSamplesPerSec := SampleRate;
wBitsPerSample := $0008;
nBlockAlign := (nChannels * wBitsPerSample) div 8;
nAvgBytesPerSec := nSamplesPerSec * nBlockAlign;
cbSize := 0;
end;
MS := TMemoryStream.Create;
with MS do
begin
{Calculate length of sound data and of file data}
DataCount := (Duration * SampleRate) div 1000; // sound data
RiffCount := Length(WaveId) + Length(FmtId) + SizeOf(DWORD) +
SizeOf(TWaveFormatEx) + Length(DataId) + SizeOf(DWORD) + DataCount; // file data
{write out the wave header}
Write(RiffId[1], 4); // 'RIFF'
Write(RiffCount, SizeOf(DWORD)); // file data size
Write(WaveId[1], Length(WaveId)); // 'WAVE'
Write(FmtId[1], Length(FmtId)); // 'fmt '
TempInt := SizeOf(TWaveFormatEx);
Write(TempInt, SizeOf(DWORD)); // TWaveFormat data size
Write(WaveFormatEx, SizeOf(TWaveFormatEx)); // WaveFormatEx record
Write(DataId[1], Length(DataId)); // 'data'
Write(DataCount, SizeOf(DWORD)); // sound data size
{calculate and write out the tone signal} // now the data values
w := 2 * Pi * Frequency; // omega
for i := 0 to DataCount - 1 do
begin
SoundValue := 127 + trunc(Volume * sin(i * w / SampleRate)); // wt = w * i / SampleRate
Write(SoundValue, SizeOf(Byte));
end;
{now play the sound}
Sleep(100);
sndPlaySound(MS.Memory, SND_MEMORY or SND_SYNC);
MS.Free;
end;
end;
procedure TForm1.btn1Click(Sender: TObject);
begin
MakeSound(1200, 1000, 100);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
tone.Frequency:=strToInt(edtFrequency.Text);
tone.Duration:=strToInt(edtDuration.Text);
tone.Volume:=TVolumeLevel(strckbr1.Position);
tone.SampleRate:=TSampleRate(cbbSampleRate.ItemIndex);
if rgChannel.ItemIndex=0 then
tone.Channel:=chMono
else
tone.Channel:=chStereo;
tone.Generate;
tone.Play;
btnSave.Enabled:=true;
end;
procedure TForm1.btnSaveClick(Sender: TObject);
begin
if dlgSave1.Execute then
tone.SaveToFile(dlgSave1.Filename);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
tone.Free;
inherited;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
inherited;
tone:=TToneGenerator.Create;
btnSave.Enabled:=false;
end;
end.
|
unit Thread.Update.Helper;
interface
uses
Classes, SysUtils, Windows, ShellApi,
Version, Web.HTTP, Global.Constant, Thread.Download, Getter.WebPath,
Getter.CodesignVerifier, Global.LanguageString, OS.EnvironmentVariable, Form.Alert,
Thread.Download.Helper, OS.DeleteDirectory;
type
TCheckUpdateResult = record
IsUpdateNeeded: Boolean;
LatestVersion: TVersion;
UpdateNotice: String;
end;
TUpdater = class
private
HTTPWeb: THTTPWeb;
DownloadThread: TDownloadThread;
DestinationPath: String;
DestinationDirectory: String;
function IsNewerVersionExistsGetLatestVersion: TCheckUpdateResult;
function GetUpdateCheckResultByGottenPage(
GottenPage: TStringList): TCheckUpdateResult;
function GetUpdateNotice: String;
function GetUpdateNoticeByGottenPage(GottenPage: TStringStream): String;
procedure PostDownloadMethod;
procedure VerifyCodesignAndExecute;
procedure WrongCodesignAlertAndDelete;
procedure MoveSetupAndExecute;
function GetLatestVersion: TStringList;
public
function CheckUpdate: TCheckUpdateResult;
procedure StartUpdate;
end;
implementation
uses Form.Main;
{ TUpdater }
function TUpdater.GetUpdateCheckResultByGottenPage(GottenPage: TStringList):
TCheckUpdateResult;
var
CurrentVersionInTVersion: TVersion;
begin
CurrentVersionInTVersion := VersionStringToTVersion(CurrentVersion);
result.LatestVersion := VersionStringToTVersion(GottenPage[0]);
result.IsUpdateNeeded := (CurrentVersionInTVersion < result.LatestVersion);
end;
function TUpdater.GetLatestVersion: TStringList;
begin
try
result := HTTPWeb.GetToStringList(AddrUpdChk[CurrLang]);
except
result := TStringList.Create;
end;
end;
function TUpdater.IsNewerVersionExistsGetLatestVersion: TCheckUpdateResult;
var
LatestSSDToolGetResult: TStringList;
begin
LatestSSDToolGetResult := GetLatestVersion;
try
if LatestSSDToolGetResult.Count = 0 then
result.IsUpdateNeeded := false
else
result := GetUpdateCheckResultByGottenPage(LatestSSDToolGetResult);
finally
FreeAndNil(LatestSSDToolGetResult);
end;
end;
function TUpdater.GetUpdateNoticeByGottenPage(GottenPage: TStringStream):
String;
const
FromFirst = 1;
MaximumCharacters = 300;
LowerLimit = 200;
VersionStart = #$D#$A#$D#$A'- ';
VersionEnd = ' -';
var
VersionInLog: String;
GottenPageDataString: String;
CurrentVersionPosInLog: Integer;
begin
VersionInLog :=
VersionStart + CurrentVersion + VersionEnd;
GottenPageDataString := GottenPage.DataString;
CurrentVersionPosInLog := Pos(VersionInLog, GottenPageDataString);
if CurrentVersionPosInLog = 0 then
CurrentVersionPosInLog := Length(GottenPageDataString);
if CurrentVersionPosInLog > MaximumCharacters then
CurrentVersionPosInLog :=
Pos(VersionStart, GottenPageDataString, LowerLimit);
result :=
Copy(GottenPageDataString, FromFirst, CurrentVersionPosInLog);
end;
function TUpdater.GetUpdateNotice: String;
const
VersionLogHeader = 'http://nstupdate.naraeon.net/ChangeLog';
VersionLogExtension = '.htm';
var
UpdateNoticeStream: TStringStream;
begin
result := '';
UpdateNoticeStream :=
HTTPWeb.GetToStringStream(VersionLogHeader + VersionLogExtension);
if UpdateNoticeStream.Size > 0 then
result := GetUpdateNoticeByGottenPage(UpdateNoticeStream);
FreeAndNil(UpdateNoticeStream);
end;
function TUpdater.CheckUpdate: TCheckUpdateResult;
begin
HTTPWeb := THTTPWeb.Create;
result := IsNewerVersionExistsGetLatestVersion;
if result.IsUpdateNeeded then
result.UpdateNotice := GetUpdateNotice;
FreeAndNil(HTTPWeb);
end;
procedure TUpdater.StartUpdate;
const
CancelButton = 1;
var
Request: TDownloadRequest;
TempFolder: String;
begin
if MessageBox(
fMain.Handle,
PChar(fMain.GetUpdateNotice),
PChar(AlrtNewVer[CurrLang]),
MB_OKCANCEL + MB_IconInformation) <> CancelButton then
begin
fMain.TerminateUpdateThread;
exit;
end;
Request.Source.FBaseAddress := 'http://nstupdate.naraeon.net';
Request.Source.FFileAddress := '/Setup.exe';
Request.Source.FType := dftPlain;
TempFolder := EnvironmentVariable.TempFolder(false);
CreateDir(TempFolder);
Request.Destination.FBaseAddress := TempFolder;
Request.Destination.FFileAddress := 'Setup.exe';
Request.Destination.FType := dftPlain;
DestinationPath := TempFolder + 'Setup.exe';
DestinationDirectory := TempFolder;
Request.DownloadModelStrings.Download := CapUpdDwld[CurrLang];
Request.DownloadModelStrings.Cancel := fMain.bCancel.Caption;
DownloadThread := TDownloadThread.Create;
DownloadThread.SetRequest(Request);
DownloadThread.SetPostDownloadMethod(PostDownloadMethod);
DownloadThread.Start;
end;
procedure TUpdater.WrongCodesignAlertAndDelete;
begin
AlertCreate(fMain, AlrtWrongCodesign[CurrLang]);
DeleteFile(PChar(DestinationPath));
DeleteDirectory(DestinationDirectory);
end;
procedure TUpdater.MoveSetupAndExecute;
begin
AlertCreate(fMain, AlrtUpdateExit[CurrLang]);
MoveFile(PChar(DestinationPath),
PChar(EnvironmentVariable.AppPath + 'Setup.exe'));
DeleteDirectory(DestinationDirectory);
ShellExecute(0, nil,
PChar(EnvironmentVariable.AppPath + 'Setup.exe'), nil, nil, SW_NORMAL);
fMain.Close;
end;
procedure TUpdater.VerifyCodesignAndExecute;
var
CodesignVerifier: TCodesignVerifier;
begin
CodesignVerifier := TCodesignVerifier.Create;
if not CodesignVerifier.VerifySignByPublisher(
DestinationPath, NaraeonPublisher) then
WrongCodesignAlertAndDelete
else
MoveSetupAndExecute;
FreeAndNil(CodesignVerifier);
end;
procedure TUpdater.PostDownloadMethod;
begin
fMain.CloseButtonGroup;
if not FileExists(DestinationPath) then
begin
AlertCreate(fMain, AlrtVerCanc[CurrLang]);
fMain.TerminateUpdateThread;
exit;
end;
VerifyCodesignAndExecute;
fMain.TerminateUpdateThread;
end;
end.
|
unit Plus;
interface
uses windows, classes, xbase;
procedure PrepareVariables;
function Win2Dos(const WinStr: string): string;
function Dos2Win(const DosStr: string): string;
function FileNameDos2Win(const FileName: string; convert: boolean): string;
function FileNameWin2Dos(const FileName: string; convert: boolean): string;
function ShortFileName(const LongName: string):string;
procedure UnPrepareVariables;
function FreeSpace(const s: string): int64;
function GetFileSize(const FileName: string): Int64;
function GetFileTime(const FileName: string): Int64;
function GetDirSize(const FileName: string): Int64;
function GetDirTime(const FileName: string): Integer;
function GetFileList(const Dir, nam: string): TStringColl;
implementation
uses sysutils;
const
MBsize = 1024 * 1024;
var
plusSrcStr, plusDestStr, plusLongFileName, plusShortFileName: PChar;
function GetFileSize;
var
Handle: THandle;
FindData: TWin32FindData;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
Int64Rec(Result).Lo := FindData.nFileSizeLow;
Int64Rec(Result).Hi := FindData.nFileSizeHigh;
Exit;
end;
end;
Result := -1;
end;
function GetFileTime;
var
SR: TSearchRec;
begin
SR.Time := 0;
if FindFirst(FileName, faAnyFile, SR) = 0 then begin
FindClose(SR);
end;
Result := SR.Time;
end;
function GetDirSize;
var
Handle: THandle;
FindData: TWin32FindData;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then
begin
Int64Rec(Result).Lo := FindData.nFileSizeLow;
Int64Rec(Result).Hi := FindData.nFileSizeHigh;
Exit;
end;
end;
Result := -1;
end;
function GetDirTime;
var
Handle: THandle;
FindData: TWin32FindData;
LT: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LT);
if FileTimeToDosDateTime(LT, LongRec(Result).Hi, LongRec(Result).Lo) then Exit;
Exit;
end;
end;
Result := -1;
end;
function FreeSpace;
var
lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes: int64;
begin
GetDiskFreeSpaceEx(PChar(s), lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes, plargeinteger(@lpTotalNumberOfFreeBytes));
Result := lpFreeBytesAvailableToCaller;
end;
procedure PrepareVariables;
begin
plusSrcStr := StrAlloc(MAX_PATH);
plusDestStr := StrAlloc(MAX_PATH);
plusLongFileName := StrAlloc(MAX_PATH);
plusShortFileName := StrAlloc(MAX_PATH);
end;
procedure UnPrepareVariables;
begin
StrDispose(plusSrcStr);
StrDispose(plusDestStr);
StrDispose(plusLongFileName);
StrDispose(plusShortFileName);
end;
function Win2Dos;
begin
StrPCopy(plusSrcStr,WinStr);
CharToOEM(plusSrcStr, plusDestStr);
Win2Dos := plusDestStr;
end;
function Dos2Win;
begin
StrPCopy(plusSrcStr,DosStr);
OEMToChar(plusSrcStr, plusDestStr);
Dos2Win := plusDestStr;
end;
function FileNameDos2Win;
begin
if not (convert) then
result := FileName
else
result := Dos2Win(FileName);
end;
function FileNameWin2Dos;
begin
if not (convert) then
result := FileName
else
result := Win2Dos(FileName);
end;
{based on function LongToShortFileName from RxLibrary}
function ShortFileName;
var
Temp: TWin32FindData;
SearchHandle: THandle;
Name, Ext: string;
ExtPos: integer;
i: integer;
begin
Result := LongName;
SearchHandle := FindFirstFile(PChar(LongName), Temp);
if SearchHandle <> INVALID_HANDLE_VALUE then begin
Result := string(Temp.cAlternateFileName);
if Result = '' then Result := string(Temp.cFileName);
end;
Windows.FindClose(SearchHandle);
if length(Result) > 12 then begin
Name := ExtractFileName(Result);
Ext := ExtractFileExt(Result);
ExtPos := pos(Ext, Name);
if ExtPos > 9 then ExtPos := 9;
Name := copy(Name, 1, ExtPos - 1);
Ext := copy(Ext, 2, 3);
result := Name + '.' + Ext;
end;
for i := 1 to length(result) do
if (result[i] <= ' ') then result[i] := '_';
end;
function GetPriority(PriorityName: string): integer;
begin
PriorityName := UpperCase(PriorityName);
result := NORMAL_PRIORITY_CLASS;
if PriorityName = 'IDLE' then result := IDLE_PRIORITY_CLASS else
if PriorityName = 'NORMAL' then result := NORMAL_PRIORITY_CLASS else
if PriorityName = 'HIGH' then result := HIGH_PRIORITY_CLASS else
if PriorityName = 'REAL' then result := REALTIME_PRIORITY_CLASS;
end;
function GetThreadPriority(PriorityName: string): TThreadPriority;
begin
PriorityName := UpperCase(PriorityName);
result := tpNormal;
if PriorityName = 'IDLE' then result := tpIdle else
if PriorityName = 'NORMAL' then result := tpNormal else
if PriorityName = 'HIGH' then result := tpHighest else
if PriorityName = 'REAL' then result := tpTimeCritical;
end;
function GetFileList(const dir, nam: string): TStringColl;
var
Srch: TWin32FindData;
flag: Integer;
succ: boolean;
path: string;
begin
Result := TStringColl.Create(nam);
path := dir;
if (path[Length(path)] <> '\') and
(path[Length(path)] <> '*') then path := path + '\*.*';
flag := FindFirstFile(PChar(path), Srch);
succ := flag <> 0;
while succ do begin
if Srch.cFileName[0] <> '.' then begin
Result.Add(Srch.cFileName);
end;
succ := FindNextFile(Flag, Srch);
end;
Windows.FindClose(Flag);
end;
begin
end. |
{
ID: a2peter1
PROG: milk
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'milk';
MaxN = 5000;
var
N,M,i,j,sol : longint;
A,B : array[0..MaxN] of longint;
var p,tmp : longint;
procedure qsort(d,h: longint);
var i,j : longint;
begin
i := d; j := h; p := A[(d + h) shr 1];
repeat
while A[i] < p do inc(i);
while A[j] > p do dec(j);
if i <= j then
begin
tmp := A[i]; A[i] := A[j]; A[j] := tmp;
tmp := B[i]; B[i] := B[j]; B[j] := tmp;
inc(i); dec(j);
end;{then}
until i > j;
if i < h then qsort(i,h);
if j > d then qsort(d,j);
end;{qsort}
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(M,N);
for i := 1 to N
do readln(A[i],B[i]);
qsort(1,N);
i := 1;
while M - B[i] >= 0 do
begin
dec(M,B[i]);
inc(sol,A[i] * B[i]);
inc(i);
end;{while}
inc(sol,A[i] * M);
writeln(sol);
close(output);
end.{main}
|
{*******************************************************}
{ }
{ Kylix Runtime Library }
{ Linux Kernel API Interface Unit }
{ }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ This translation is based on include files }
{ taken from the Linux 4.4 kernel. }
{ Translator: Embarcadero Technologies, Inc. }
{*******************************************************}
unit Linuxapi.KernelIoctl;
{$WEAKPACKAGEUNIT}
{$ALIGN 4}
{$MINENUMSIZE 4}
{$ASSERTIONS OFF}
interface
// Translated from linux/include/asm-i386/ioctl.h
{ ioctl command encoding: 32 bits total, command in lower 16 bits,
* size of the parameter structure in the lower 14 bits of the
* upper 16 bits.
* Encoding the size of the parameter structure in the ioctl request
* is useful for catching programs compiled with old versions
* and to avoid overwriting user space outside the user buffer area.
* The highest 2 bits are reserved for indicating the ``access mode''.
* NOTE: This limits the max parameter size to 16kB -1 !
}
{
* The following is for compatibility across the various Linux
* platforms. The i386 ioctl numbering scheme doesn't really enforce
* a type field. De facto, however, the top 8 bits of the lower 16
* bits are indeed used as a type field, so we might just as well make
* this explicit here. Please be sure to use the decoding macros
* below from now on.
}
const
_IOC_NRBITS = 8;
{$EXTERNALSYM _IOC_NRBITS}
_IOC_TYPEBITS = 8;
{$EXTERNALSYM _IOC_TYPEBITS}
_IOC_SIZEBITS = 14;
{$EXTERNALSYM _IOC_SIZEBITS}
_IOC_DIRBITS = 2;
{$EXTERNALSYM _IOC_DIRBITS}
_IOC_NRMASK = ((1 shl _IOC_NRBITS)-1);
{$EXTERNALSYM _IOC_NRMASK}
_IOC_TYPEMASK = ((1 shl _IOC_TYPEBITS)-1);
{$EXTERNALSYM _IOC_TYPEMASK}
_IOC_SIZEMASK = ((1 shl _IOC_SIZEBITS)-1);
{$EXTERNALSYM _IOC_SIZEMASK}
_IOC_DIRMASK = ((1 shl _IOC_DIRBITS)-1);
{$EXTERNALSYM _IOC_DIRMASK}
_IOC_NRSHIFT = 0;
{$EXTERNALSYM _IOC_NRSHIFT}
_IOC_TYPESHIFT = (_IOC_NRSHIFT+_IOC_NRBITS);
{$EXTERNALSYM _IOC_TYPESHIFT}
_IOC_SIZESHIFT = (_IOC_TYPESHIFT+_IOC_TYPEBITS);
{$EXTERNALSYM _IOC_SIZESHIFT}
_IOC_DIRSHIFT = (_IOC_SIZESHIFT+_IOC_SIZEBITS);
{$EXTERNALSYM _IOC_DIRSHIFT}
{ Direction bits. }
_IOC_NONE = 0;
{$EXTERNALSYM _IOC_NONE}
_IOC_WRITE = 1;
{$EXTERNALSYM _IOC_WRITE}
_IOC_READ = 2;
{$EXTERNALSYM _IOC_READ}
function _IOC(dir, __type, nr, size: Cardinal): Cardinal;
{$EXTERNALSYM _IOC}
{ used to create numbers }
function _IO(__type, nr: Cardinal): Cardinal;
{$EXTERNALSYM _IO}
// Warning: BufferSize is sizeof(size) !
function __IOR(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
{.$EXTERNALSYM __IOR} // Renamed because of implementation change
function __IOW(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
{.$EXTERNALSYM __IOW} // Renamed because of implementation change
function __IOWR(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
{.$EXTERNALSYM __IOWR} // Renamed because of implementation change
function _IOR_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
{$EXTERNALSYM _IOR_BAD}
function _IOW_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
{$EXTERNALSYM _IOW_BAD}
function _IOWR_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
{$EXTERNALSYM _IOWR_BAD}
{ used to decode ioctl numbers.. }
function _IOC_DIR(nr: Cardinal): Cardinal;
{$EXTERNALSYM _IOC_DIR}
function _IOC_TYPE(nr: Cardinal): Cardinal;
{$EXTERNALSYM _IOC_TYPE}
function _IOC_NR(nr: Cardinal): Cardinal;
{$EXTERNALSYM _IOC_NR}
function _IOC_SIZE(nr: Cardinal): Cardinal;
{$EXTERNALSYM _IOC_SIZE}
{ ...and for the drivers/sound files... }
const
IOC_IN = (_IOC_WRITE shl _IOC_DIRSHIFT);
{$EXTERNALSYM IOC_IN}
IOC_OUT = (_IOC_READ shl _IOC_DIRSHIFT);
{$EXTERNALSYM IOC_OUT}
IOC_INOUT = ((_IOC_WRITE or _IOC_READ) shl _IOC_DIRSHIFT);
{$EXTERNALSYM IOC_INOUT}
IOCSIZE_MASK = (_IOC_SIZEMASK shl _IOC_SIZESHIFT);
{$EXTERNALSYM IOCSIZE_MASK}
IOCSIZE_SHIFT = (_IOC_SIZESHIFT);
{$EXTERNALSYM IOCSIZE_SHIFT}
// Translated from linux/include/asm-i386/ioctls.h
{ 0x54 is just a magic number to make these relatively unique ('T') }
const
TCGETS = $5401;
{$EXTERNALSYM TCGETS}
TCSETS = $5402;
{$EXTERNALSYM TCSETS}
TCSETSW = $5403;
{$EXTERNALSYM TCSETSW}
TCSETSF = $5404;
{$EXTERNALSYM TCSETSF}
TCGETA = $5405;
{$EXTERNALSYM TCGETA}
TCSETA = $5406;
{$EXTERNALSYM TCSETA}
TCSETAW = $5407;
{$EXTERNALSYM TCSETAW}
TCSETAF = $5408;
{$EXTERNALSYM TCSETAF}
TCSBRK = $5409;
{$EXTERNALSYM TCSBRK}
TCXONC = $540A;
{$EXTERNALSYM TCXONC}
TCFLSH = $540B;
{$EXTERNALSYM TCFLSH}
TIOCEXCL = $540C;
{$EXTERNALSYM TIOCEXCL}
TIOCNXCL = $540D;
{$EXTERNALSYM TIOCNXCL}
TIOCSCTTY = $540E;
{$EXTERNALSYM TIOCSCTTY}
TIOCGPGRP = $540F;
{$EXTERNALSYM TIOCGPGRP}
TIOCSPGRP = $5410;
{$EXTERNALSYM TIOCSPGRP}
TIOCOUTQ = $5411;
{$EXTERNALSYM TIOCOUTQ}
TIOCSTI = $5412;
{$EXTERNALSYM TIOCSTI}
TIOCGWINSZ = $5413;
{$EXTERNALSYM TIOCGWINSZ}
TIOCSWINSZ = $5414;
{$EXTERNALSYM TIOCSWINSZ}
TIOCMGET = $5415;
{$EXTERNALSYM TIOCMGET}
TIOCMBIS = $5416;
{$EXTERNALSYM TIOCMBIS}
TIOCMBIC = $5417;
{$EXTERNALSYM TIOCMBIC}
TIOCMSET = $5418;
{$EXTERNALSYM TIOCMSET}
TIOCGSOFTCAR = $5419;
{$EXTERNALSYM TIOCGSOFTCAR}
TIOCSSOFTCAR = $541A;
{$EXTERNALSYM TIOCSSOFTCAR}
FIONREAD = $541B;
{$EXTERNALSYM FIONREAD}
TIOCINQ = FIONREAD;
{$EXTERNALSYM TIOCINQ}
TIOCLINUX = $541C;
{$EXTERNALSYM TIOCLINUX}
TIOCCONS = $541D;
{$EXTERNALSYM TIOCCONS}
TIOCGSERIAL = $541E;
{$EXTERNALSYM TIOCGSERIAL}
TIOCSSERIAL = $541F;
{$EXTERNALSYM TIOCSSERIAL}
TIOCPKT = $5420;
{$EXTERNALSYM TIOCPKT}
FIONBIO = $5421;
{$EXTERNALSYM FIONBIO}
TIOCNOTTY = $5422;
{$EXTERNALSYM TIOCNOTTY}
TIOCSETD = $5423;
{$EXTERNALSYM TIOCSETD}
TIOCGETD = $5424;
{$EXTERNALSYM TIOCGETD}
TCSBRKP = $5425; { Needed for POSIX tcsendbreak() }
{$EXTERNALSYM TCSBRKP}
TIOCSBRK = $5427; { BSD compatibility }
{$EXTERNALSYM TIOCSBRK}
TIOCCBRK = $5428; { BSD compatibility }
{$EXTERNALSYM TIOCCBRK}
TIOCGSID = $5429; { Return the session ID of FD }
{$EXTERNALSYM TIOCGSID}
function TCGETS2: Cardinal;
{$EXTERNALSYM TCGETS2}
function TCSETS2: Cardinal;
{$EXTERNALSYM TCSETS2}
function TCSETSW2: Cardinal;
{$EXTERNALSYM TCSETSW2}
function TCSETSF2: Cardinal;
{$EXTERNALSYM TCSETSF2}
const
TIOCGRS485 = $542E;
{$EXTERNALSYM TIOCGRS485}
TIOCSRS485 = $542F;
{$EXTERNALSYM TIOCSRS485}
function TIOCGPTN: Cardinal; { Get Pty Number (of pty-mux device) }
{$EXTERNALSYM TIOCGPTN}
function TIOCSPTLCK: Cardinal;{ Lock/unlock Pty }
{$EXTERNALSYM TIOCSPTLCK}
function TIOCGDEV: Cardinal; { Get primary device node of /dev/console }
{$EXTERNALSYM TIOCGDEV}
const
TCGETX = $5432; { SYS5 TCGETX compatibility }
{$EXTERNALSYM TCGETX}
TCSETX = $5433;
{$EXTERNALSYM TCSETX}
TCSETXF = $5434;
{$EXTERNALSYM TCSETXF}
TCSETXW = $5435;
{$EXTERNALSYM TCSETXW}
function TIOCSIG : Cardinal;{ pty: generate signal }
{$EXTERNALSYM TIOCGPKT}
const
TIOCVHANGUP = $5437;
{$EXTERNALSYM TIOCVHANGUP}
function TIOCGPKT: Cardinal; { Get packet mode state }
{$EXTERNALSYM TIOCGPKT}
function TIOCGPTLCK: Cardinal;{ Get Pty lock state }
{$EXTERNALSYM TIOCGPTLCK}
function TIOCGEXCL: Cardinal; { Get exclusive mode state }
{$EXTERNALSYM TIOCGEXCL}
const
FIONCLEX = $5450; { these numbers need to be adjusted. }
{$EXTERNALSYM FIONCLEX}
FIOCLEX = $5451;
{$EXTERNALSYM FIOCLEX}
FIOASYNC = $5452;
{$EXTERNALSYM FIOASYNC}
TIOCSERCONFIG = $5453;
{$EXTERNALSYM TIOCSERCONFIG}
TIOCSERGWILD = $5454;
{$EXTERNALSYM TIOCSERGWILD}
TIOCSERSWILD = $5455;
{$EXTERNALSYM TIOCSERSWILD}
TIOCGLCKTRMIOS = $5456;
{$EXTERNALSYM TIOCGLCKTRMIOS}
TIOCSLCKTRMIOS = $5457;
{$EXTERNALSYM TIOCSLCKTRMIOS}
TIOCSERGSTRUCT = $5458; { For debugging only }
{$EXTERNALSYM TIOCSERGSTRUCT}
TIOCSERGETLSR = $5459; { Get line status register }
{$EXTERNALSYM TIOCSERGETLSR}
TIOCSERGETMULTI = $545A; { Get multiport config }
{$EXTERNALSYM TIOCSERGETMULTI}
TIOCSERSETMULTI = $545B; { Set multiport config }
{$EXTERNALSYM TIOCSERSETMULTI}
TIOCMIWAIT = $545C; { wait for a change on serial input line(s) }
{$EXTERNALSYM TIOCMIWAIT}
TIOCGICOUNT = $545D; { read serial port inline interrupt counts }
{$EXTERNALSYM TIOCGICOUNT}
{ Used for packet mode }
TIOCPKT_DATA = 0;
{$EXTERNALSYM TIOCPKT_DATA}
TIOCPKT_FLUSHREAD = 1;
{$EXTERNALSYM TIOCPKT_FLUSHREAD}
TIOCPKT_FLUSHWRITE = 2;
{$EXTERNALSYM TIOCPKT_FLUSHWRITE}
TIOCPKT_STOP = 4;
{$EXTERNALSYM TIOCPKT_STOP}
TIOCPKT_START = 8;
{$EXTERNALSYM TIOCPKT_START}
TIOCPKT_NOSTOP = 16;
{$EXTERNALSYM TIOCPKT_NOSTOP}
TIOCPKT_DOSTOP = 32;
{$EXTERNALSYM TIOCPKT_DOSTOP}
TIOCPKT_IOCTL = 64;
{$EXTERNALSYM TIOCPKT_IOCTL}
TIOCSER_TEMT = $01; { Transmitter physically empty }
{$EXTERNALSYM TIOCSER_TEMT}
implementation
uses
Linuxapi.KernelDefs;
// Macros for ioctl.h
function _IOC(dir, __type, nr, size: Cardinal): Cardinal;
begin
Result := (dir shl _IOC_DIRSHIFT) or
(__type shl _IOC_TYPESHIFT) or
(nr shl _IOC_NRSHIFT) or
(size shl _IOC_SIZESHIFT);
end;
function _IO(__type, nr: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_NONE, __type, nr, 0);
end;
function __IOR(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_READ, __type, nr, BufferSize);
end;
function __IOW(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_WRITE, __type, nr, BufferSize);
end;
function __IOWR(__type, nr: Cardinal; BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_READ or _IOC_WRITE, __type, nr, BufferSize);
end;
function _IOR_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_READ, __type, nr, BufferSize);
end;
function _IOW_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_WRITE, __type, nr, BufferSize);
end;
function _IOWR_BAD(__type, nr, BufferSize: Cardinal): Cardinal;
begin
Result := _IOC(_IOC_READ or _IOC_WRITE, __type, nr, BufferSize);
end;
function _IOC_DIR(nr: Cardinal): Cardinal;
begin
Result := (nr shr _IOC_DIRSHIFT) and _IOC_DIRMASK;
end;
function _IOC_TYPE(nr: Cardinal): Cardinal;
begin
Result := (nr shr _IOC_TYPESHIFT) and _IOC_TYPEMASK;
end;
function _IOC_NR(nr: Cardinal): Cardinal;
begin
Result := (nr shr _IOC_NRSHIFT) and _IOC_NRMASK;
end;
function _IOC_SIZE(nr: Cardinal): Cardinal;
begin
Result := (nr shr _IOC_SIZESHIFT) and _IOC_SIZEMASK;
end;
// Macros for ioctls.h
function TCGETS2: Cardinal;
begin
Result := __IOR(Ord('T'), $2A, SizeOf(termios2));
end;
function TCSETS2: Cardinal;
begin
Result := __IOW(Ord('T'), $2B, SizeOf(termios2));
end;
function TCSETSW2: Cardinal;
begin
Result := __IOW(Ord('T'), $2C, SizeOf(termios2));
end;
function TCSETSF2: Cardinal;
begin
Result := __IOW(Ord('T'), $2D, SizeOf(termios2));
end;
function TIOCGPTN: Cardinal;
begin
Result := __IOR(Ord('T'), $30, SizeOf(Cardinal)); { Get Pty Number (of pty-mux device) }
end;
function TIOCSPTLCK: Cardinal;
begin
Result := __IOW(Ord('T'), $31, SizeOf(Integer)); { Lock/unlock Pty }
end;
function TIOCGDEV: Cardinal;
begin
Result := __IOR(Ord('T'), $32, SizeOf(Integer)); { Get primary device node of /dev/console }
end;
function TIOCSIG : Cardinal;
begin
Result := __IOW(Ord('T'), $36, SizeOf(Integer));{ pty: generate signal }
end;
function TIOCGPKT: Cardinal;
begin
Result := __IOR(Ord('T'), $38, SizeOf(Integer)); { Get packet mode state }
end;
function TIOCGPTLCK: Cardinal;
begin
Result := __IOR(Ord('T'), $39, SizeOf(Integer)); { Get Pty lock state }
end;
function TIOCGEXCL: Cardinal;
begin
Result := __IOR(Ord('T'), $40, SizeOf(Integer)); { Get exclusive mode state }
end;
end.
|
unit MediaStream.Framer.Wave;
interface
uses Windows,SysUtils,Classes,MediaProcessing.Definitions,MediaStream.Framer,MMSystem;
type
TStreamFramerWave = class (TStreamFramer)
private
FStream : TStream;
FBuffer: TBytes;
FFormat: TPCMWaveFormat;
FDataSize: DWORD;
FTimeStamp: int64;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; override;
function VideoStreamType: TStreamType; override;
function AudioStreamType: TStreamType; override;
function StreamInfo: TBytes; override;
property Format: TPCMWaveFormat read FFormat;
end;
implementation
type
TWaveHeader = packed record
//Contains the letters "RIFF" in ASCII form (0x52494646 big-endian form).
IdRiff: array[0..3] of AnsiChar;
//This is the size of the rest of the chunk
//following this number. This is the size of the
//entire file in bytes minus 8 bytes for the
//two fields not included in this count:
//IdRiff and RiffLenth.
RiffLenth: longint;
//Contains the letters "WAVE"
//0x57415645 big-endian form).
IdWave: array[0..3] of AnsiChar;
end;
TChunkHeader = packed record
Id: array[0..3] of AnsiChar;
Size: DWORD;
end;
//Chunks ==========
//id = "fmt "
//size 16;
TFormatChunk = TPCMWaveFormat;
TDataChunk = packed record
//Data
end;
{ TStreamFramerWave }
constructor TStreamFramerWave.Create;
begin
inherited;
end;
destructor TStreamFramerWave.Destroy;
begin
FStream:=nil;
inherited;
end;
function TStreamFramerWave.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean;
var
aPacketSize: cardinal;
const
aFrameLengthMsec = 40;
begin
result:=false;
if FDataSize=0 then
exit;
aPacketSize:=FFormat.wf.nSamplesPerSec*(FFormat.wBitsPerSample div 8)*FFormat.wf.nChannels;
//Читаем по 1-й секунде
//if aFrameLengthMsec>1000 then
// aPacketSize:=aPacketSize * (aFrameLengthMsec div 1000)
//else
aPacketSize:=aPacketSize * aFrameLengthMsec div 1000;
if aPacketSize>FDataSize then
aPacketSize:=FDataSize;
dec(FDataSize,aPacketSize);
if cardinal(Length(FBuffer))<aPacketSize then
SetLength(FBuffer,aPacketSize);
result:=cardinal(FStream.Read(FBuffer[0],aPacketSize))=aPacketSize;
if result then
begin
aOutData:=FBuffer;
aOutDataSize:=aPacketSize;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.Assign(FFormat);
aOutFormat.TimeStamp:=FTimeStamp;
inc(FTimeStamp,aFrameLengthMsec);
end;
end;
procedure TStreamFramerWave.OpenStream(aStream: TStream);
const
MsgBadFileFormat ='Неверный формат файла';
var
aWaveHeader: TWaveHeader;
aChunkHeader : TChunkHeader;
begin
FStream:=aStream;
FTimeStamp:=0;
FStream.ReadBuffer(aWaveHeader,sizeof(aWaveHeader));
if aWaveHeader.IdRiff<>'RIFF' then
raise Exception.Create(MsgBadFileFormat);
if aWaveHeader.IdWave<>'WAVE' then
raise Exception.Create(MsgBadFileFormat);
//format chunk
FStream.ReadBuffer(aChunkHeader,sizeof(aChunkHeader));
if aChunkHeader.Id<>'fmt ' then
raise Exception.Create(MsgBadFileFormat);
if aChunkHeader.Size<sizeof(FFormat) then
raise Exception.Create(MsgBadFileFormat);
FStream.ReadBuffer(FFormat,sizeof(FFormat));
//Какие-то доп. данные, которых мы не знаем
if aChunkHeader.Size>sizeof(FFormat) then
FStream.Seek(aChunkHeader.Size-sizeof(FFormat),soFromCurrent);
//0 (0x0000) Unknown
//1 (0x0001) PCM/uncompressed
//2 (0x0002) Microsoft ADPCM
//6 (0x0006) ITU G.711 a-law
//7 (0x0007) ITU G.711 Aч-law
//17 (0x0011) IMA ADPCM
//20 (0x0016) ITU G.723 ADPCM (Yamaha)
//49 (0x0031) GSM 6.10
//64 (0x0040) ITU G.721 ADPCM
//80 (0x0050) MPEG
//65,536 (0xFFFF) Experimental
if not FFormat.wf.wFormatTag in [WAVE_FORMAT_PCM,7] then
raise Exception.Create('Неподдерживаемый тип компрессии аудио');
//lookup for fact
FStream.ReadBuffer(aChunkHeader,sizeof(aChunkHeader));
if aChunkHeader.Id='chunk' then
begin
FStream.Seek(aChunkHeader.Size,soFromCurrent);
end
else if aChunkHeader.Id='data' then
FDataSize:=aChunkHeader.Size
else
raise Exception.Create(MsgBadFileFormat);
if FFormat.wBitsPerSample mod 8<>0 then
raise Exception.Create(MsgBadFileFormat);
end;
function TStreamFramerWave.StreamInfo: TBytes;
begin
result:=nil;
end;
function TStreamFramerWave.VideoStreamType: TStreamType;
begin
result:=0;
end;
function TStreamFramerWave.AudioStreamType: TStreamType;
var
aFormat: TMediaStreamDataHeader;
begin
Assert(FStream<>nil);
aFormat.Assign(FFormat);
result:=aFormat.biStreamType;
end;
end.
|
unit Financas.Model.Connections.Interfaces;
interface
uses
System.Classes;
type
iModelConnectionParams = interface;
iModelConnection = interface
['{E8538D27-DFF2-4485-A303-616176681A93}']
function Conectar : iModelConnection;
function EndConnection: TComponent;
function Params: iModelConnectionParams;
end;
iModelConnectionParams = interface
['{69BA62BF-43C2-495B-8E0B-C5B6D509FFCB}']
function Database(Value: String): iModelConnectionParams;
function UserName(Value: String): iModelConnectionParams;
function Password(Value: String): iModelConnectionParams;
function DriverID(Value: String): iModelConnectionParams;
function Server(Value: String): iModelConnectionParams;
function Porta(Value: Integer): iModelConnectionParams;
function EndParams: iModelConnection;
end;
iModelDataSet = interface
['{5CFF1908-225F-4A05-A633-914A35BF2858}']
function Open(aTable: String): iModelDataSet;
function EndDataSet: TComponent;
end;
iModelFactoryConnection = interface
['{30C0A523-319F-46E8-97F5-F4C7B32BDF95}']
function ConnectionFiredac : iModelConnection;
end;
iModelFactoryDataSet = interface
['{EA1766BB-437B-4133-95D5-73AF1EA851D7}']
function DataSetFiredac(Connection : iModelConnection) : iModelDataSet;
end;
implementation
end.
|
{
Copyright (c) 2003-2006, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
{
В этом модуле хранятся все общие переменные и константы
}
unit GlobalsUnit;
interface
uses
Windows, Messages, SysUtils;
const
SShortCopyRight = 'Разработка пользовательского интерфейса, 2003 - 2006';
SShortProgramName = 'Демо-приложение';
SStartMutexName = '{CC5A50F3-F964-440A-80E1-F1860C89CD98}';
var
Path: string; // Директория с запущенной программой
IniFileName: string; // Имя файла настроек
// Определяет, следует ли сохранять положение панелей в ини-файле
SaveControlsPosToIni: Boolean = True;
implementation
initialization
Path := ExtractFilePath(ParamStr(0));
IniFileName := ChangeFileExt(ParamStr(0), '.ini');
end.
|
unit DragDropFile;
// -----------------------------------------------------------------------------
// Project: Drag and Drop Component Suite.
// Module: DragDropFile
// Description: Implements Dragging and Dropping of files and folders.
// Version: 4.0
// Date: 18-MAY-2001
// Target: Win32, Delphi 5-6
// Authors: Anders Melander, anders@melander.dk, http://www.melander.dk
// Copyright © 1997-2001 Angus Johnson & Anders Melander
// -----------------------------------------------------------------------------
interface
uses
DragDrop,
DropTarget,
DropSource,
DragDropFormats,
ActiveX,
Windows,
Classes;
type
////////////////////////////////////////////////////////////////////////////////
//
// TFileClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TFileClipboardFormat = class(TCustomSimpleClipboardFormat)
private
FFiles: TStrings;
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
constructor Create; override;
destructor Destroy; override;
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
property Files: TStrings read FFiles;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TFilenameClipboardFormat = class(TCustomTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Filename: string read GetString write SetString;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameWClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TFilenameWClipboardFormat = class(TCustomWideTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Filename: WideString read GetText write SetText;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameMapClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
// DONE -oanme -cStopShip : Rename TFilenameMapClipboardFormat to TFilenameMapClipboardFormat. Also wide version.
TFilenameMapClipboardFormat = class(TCustomSimpleClipboardFormat)
private
FFileMaps : TStrings;
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
constructor Create; override;
destructor Destroy; override;
function GetClipboardFormat: TClipFormat; override;
procedure Clear; override;
function HasData: boolean; override;
property FileMaps: TStrings read FFileMaps;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameMapWClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TFilenameMapWClipboardFormat = class(TCustomSimpleClipboardFormat)
private
FFileMaps : TStrings;
protected
function ReadData(Value: pointer; Size: integer): boolean; override;
function WriteData(Value: pointer; Size: integer): boolean; override;
function GetSize: integer; override;
public
constructor Create; override;
destructor Destroy; override;
function GetClipboardFormat: TClipFormat; override;
procedure Clear; override;
function HasData: boolean; override;
property FileMaps: TStrings read FFileMaps;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFileMapDataFormat
//
////////////////////////////////////////////////////////////////////////////////
TFileMapDataFormat = class(TCustomDataFormat)
private
FFileMaps : TStrings;
public
constructor Create(AOwner: TDragDropComponent); override;
destructor Destroy; override;
function Assign(Source: TClipboardFormat): boolean; override;
function AssignTo(Dest: TClipboardFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
function NeedsData: boolean; override;
property FileMaps: TStrings read FFileMaps;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFileDataFormat
//
////////////////////////////////////////////////////////////////////////////////
TFileDataFormat = class(TCustomDataFormat)
private
FFiles : TStrings;
protected
public
constructor Create(AOwner: TDragDropComponent); override;
destructor Destroy; override;
function Assign(Source: TClipboardFormat): boolean; override;
function AssignTo(Dest: TClipboardFormat): boolean; override;
procedure Clear; override;
function HasData: boolean; override;
function NeedsData: boolean; override;
property Files: TStrings read FFiles;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropFileTarget
//
////////////////////////////////////////////////////////////////////////////////
TDropFileTarget = class(TCustomDropMultiTarget)
private
FFileFormat : TFileDataFormat;
FFileMapFormat : TFileMapDataFormat;
protected
function GetFiles: TStrings;
function GetMappedNames: TStrings;
function GetPreferredDropEffect: LongInt; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Files: TStrings read GetFiles;
property MappedNames: TStrings read GetMappedNames;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropFileSource
//
////////////////////////////////////////////////////////////////////////////////
TDropFileSource = class(TCustomDropMultiSource)
private
FFileFormat : TFileDataFormat;
FFileMapFormat : TFileMapDataFormat;
function GetFiles: TStrings;
function GetMappedNames: TStrings;
protected
procedure SetFiles(AFiles: TStrings);
procedure SetMappedNames(ANames: TStrings);
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
published
property Files: TStrings read GetFiles write SetFiles;
// MappedNames is only needed if files need to be renamed during a drag op.
// E.g. dragging from 'Recycle Bin'.
property MappedNames: TStrings read GetMappedNames write SetMappedNames;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
////////////////////////////////////////////////////////////////////////////////
//
// Misc.
//
////////////////////////////////////////////////////////////////////////////////
function ReadFilesFromHGlobal(const HGlob: HGlobal; Files: TStrings): boolean; // V4: renamed
function ReadFilesFromData(Data: pointer; Size: integer; Files: TStrings): boolean;
function ReadFilesFromZeroList(Data: pointer; Size: integer;
Wide: boolean; Files: TStrings): boolean;
function WriteFilesToZeroList(Data: pointer; Size: integer;
Wide: boolean; Files: TStrings): boolean;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
implementation
uses
DragDropPIDL,
SysUtils,
ShlObj;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
begin
RegisterComponents(DragDropComponentPalettePage, [TDropFileTarget,
TDropFileSource]);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utilities
//
////////////////////////////////////////////////////////////////////////////////
function ReadFilesFromHGlobal(const HGlob: HGlobal; Files: TStrings): boolean;
var
DropFiles : PDropFiles;
begin
DropFiles := PDropFiles(GlobalLock(HGlob));
try
Result := ReadFilesFromData(DropFiles, GlobalSize(HGlob), Files)
finally
GlobalUnlock(HGlob);
end;
end;
function ReadFilesFromData(Data: pointer; Size: integer; Files: TStrings): boolean;
var
Wide : boolean;
begin
Files.Clear;
if (Data <> nil) then
begin
Wide := PDropFiles(Data)^.fWide;
dec(Size, PDropFiles(Data)^.pFiles);
inc(PChar(Data), PDropFiles(Data)^.pFiles);
ReadFilesFromZeroList(Data, Size, Wide, Files);
end;
Result := (Files.Count > 0);
end;
function ReadFilesFromZeroList(Data: pointer; Size: integer;
Wide: boolean; Files: TStrings): boolean;
var
StringSize : integer;
begin
Result := False;
if (Data <> nil) then
while (Size > 0) and (PChar(Data)^ <> #0) do
begin
if (Wide) then
begin
Files.Add(PWideChar(Data));
StringSize := (Length(PWideChar(Data)) + 1) * 2;
end else
begin
Files.Add(PChar(Data));
StringSize := Length(PChar(Data)) + 1;
end;
inc(PChar(Data), StringSize);
dec(Size, StringSize);
Result := True;
end;
end;
function WriteFilesToZeroList(Data: pointer; Size: integer;
Wide: boolean; Files: TStrings): boolean;
var
i : integer;
begin
Result := False;
if (Data <> nil) then
begin
i := 0;
dec(Size);
while (Size > 0) and (i < Files.Count) do
begin
if (Wide) then
begin
StringToWideChar(Files[i], Data, Size);
dec(Size, (Length(Files[i])+1)*2);
end else
begin
StrPLCopy(Data, Files[i], Size);
dec(Size, Length(Files[i])+1);
end;
inc(PChar(Data), Length(Files[i])+1);
inc(i);
Result := True;
end;
// Final teminating zero.
if (Size >= 0) then
PChar(Data)^ := #0;
end;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFileClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
constructor TFileClipboardFormat.Create;
begin
inherited Create;
FFiles := TStringList.Create;
// Note: Setting dwAspect to DVASPECT_SHORT will request that the data source
// returns the file names in short (8.3) format.
// FFormatEtc.dwAspect := DVASPECT_SHORT;
end;
destructor TFileClipboardFormat.Destroy;
begin
FFiles.Free;
inherited Destroy;
end;
function TFileClipboardFormat.GetClipboardFormat: TClipFormat;
begin
Result := CF_HDROP;
end;
procedure TFileClipboardFormat.Clear;
begin
FFiles.Clear;
end;
function TFileClipboardFormat.HasData: boolean;
begin
Result := (FFiles.Count > 0);
end;
function TFileClipboardFormat.GetSize: integer;
var
i : integer;
begin
Result := SizeOf(TDropFiles) + FFiles.Count + 1;
for i := 0 to FFiles.Count-1 do
inc(Result, Length(FFiles[i]));
end;
function TFileClipboardFormat.ReadData(Value: pointer;
Size: integer): boolean;
begin
Result := (Size > SizeOf(TDropFiles));
if (not Result) then
exit;
Result := ReadFilesFromData(Value, Size, FFiles);
end;
function TFileClipboardFormat.WriteData(Value: pointer;
Size: integer): boolean;
begin
Result := (Size > SizeOf(TDropFiles));
if (not Result) then
exit;
PDropFiles(Value)^.pfiles := SizeOf(TDropFiles);
PDropFiles(Value)^.fwide := False;
inc(PChar(Value), SizeOf(TDropFiles));
dec(Size, SizeOf(TDropFiles));
WriteFilesToZeroList(Value, Size, False, FFiles);
end;
function TFileClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TFileDataFormat) then
begin
FFiles.Assign(TFileDataFormat(Source).Files);
Result := True;
end else
Result := inherited Assign(Source);
end;
function TFileClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TFileDataFormat) then
begin
TFileDataFormat(Dest).Files.Assign(FFiles);
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_FILENAMEA: TClipFormat = 0;
function TFilenameClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_FILENAMEA = 0) then
CF_FILENAMEA := RegisterClipboardFormat(CFSTR_FILENAMEA);
Result := CF_FILENAMEA;
end;
function TFilenameClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TFileDataFormat) then
begin
Result := (TFileDataFormat(Source).Files.Count > 0);
if (Result) then
Filename := TFileDataFormat(Source).Files[0];
end else
Result := inherited Assign(Source);
end;
function TFilenameClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TFileDataFormat) then
begin
TFileDataFormat(Dest).Files.Add(Filename);
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameWClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_FILENAMEW: TClipFormat = 0;
function TFilenameWClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_FILENAMEW = 0) then
CF_FILENAMEW := RegisterClipboardFormat(CFSTR_FILENAMEW);
Result := CF_FILENAMEW;
end;
function TFilenameWClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TFileDataFormat) then
begin
Result := (TFileDataFormat(Source).Files.Count > 0);
if (Result) then
Filename := TFileDataFormat(Source).Files[0];
end else
Result := inherited Assign(Source);
end;
function TFilenameWClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TFileDataFormat) then
begin
TFileDataFormat(Dest).Files.Add(Filename);
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameMapClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_FILENAMEMAP: TClipFormat = 0;
constructor TFilenameMapClipboardFormat.Create;
begin
inherited Create;
FFileMaps := TStringList.Create;
end;
destructor TFilenameMapClipboardFormat.Destroy;
begin
FFileMaps.Free;
inherited Destroy;
end;
function TFilenameMapClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_FILENAMEMAP = 0) then
CF_FILENAMEMAP := RegisterClipboardFormat(CFSTR_FILENAMEMAPA);
Result := CF_FILENAMEMAP;
end;
procedure TFilenameMapClipboardFormat.Clear;
begin
FFileMaps.Clear;
end;
function TFilenameMapClipboardFormat.HasData: boolean;
begin
Result := (FFileMaps.Count > 0);
end;
function TFilenameMapClipboardFormat.GetSize: integer;
var
i : integer;
begin
Result := FFileMaps.Count + 1;
for i := 0 to FFileMaps.Count-1 do
inc(Result, Length(FFileMaps[i]));
end;
function TFilenameMapClipboardFormat.ReadData(Value: pointer;
Size: integer): boolean;
begin
Result := ReadFilesFromZeroList(Value, Size, False, FFileMaps);
end;
function TFilenameMapClipboardFormat.WriteData(Value: pointer;
Size: integer): boolean;
begin
Result := WriteFilesToZeroList(Value, Size, False, FFileMaps);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFilenameMapWClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_FILENAMEMAPW: TClipFormat = 0;
constructor TFilenameMapWClipboardFormat.Create;
begin
inherited Create;
FFileMaps := TStringList.Create;
end;
destructor TFilenameMapWClipboardFormat.Destroy;
begin
FFileMaps.Free;
inherited Destroy;
end;
function TFilenameMapWClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_FILENAMEMAPW = 0) then
CF_FILENAMEMAPW := RegisterClipboardFormat(CFSTR_FILENAMEMAPW);
Result := CF_FILENAMEMAPW;
end;
procedure TFilenameMapWClipboardFormat.Clear;
begin
FFileMaps.Clear;
end;
function TFilenameMapWClipboardFormat.HasData: boolean;
begin
Result := (FFileMaps.Count > 0);
end;
function TFilenameMapWClipboardFormat.GetSize: integer;
var
i : integer;
begin
Result := FFileMaps.Count + 1;
for i := 0 to FFileMaps.Count-1 do
inc(Result, Length(FFileMaps[i]));
inc(Result, Result);
end;
function TFilenameMapWClipboardFormat.ReadData(Value: pointer;
Size: integer): boolean;
begin
Result := ReadFilesFromZeroList(Value, Size, True, FFileMaps);
end;
function TFilenameMapWClipboardFormat.WriteData(Value: pointer;
Size: integer): boolean;
begin
Result := WriteFilesToZeroList(Value, Size, True, FFileMaps);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFileMapDataFormat
//
////////////////////////////////////////////////////////////////////////////////
constructor TFileMapDataFormat.Create(AOwner: TDragDropComponent);
begin
inherited Create(AOwner);
FFileMaps := TStringList.Create;
TStringList(FFileMaps).OnChanging := DoOnChanging;
end;
destructor TFileMapDataFormat.Destroy;
begin
FFileMaps.Free;
inherited Destroy;
end;
function TFileMapDataFormat.Assign(Source: TClipboardFormat): boolean;
begin
Result := True;
if (Source is TFilenameMapClipboardFormat) then
FFileMaps.Assign(TFilenameMapClipboardFormat(Source).FileMaps)
else if (Source is TFilenameMapWClipboardFormat) then
FFileMaps.Assign(TFilenameMapWClipboardFormat(Source).FileMaps)
else
Result := inherited Assign(Source);
end;
function TFileMapDataFormat.AssignTo(Dest: TClipboardFormat): boolean;
begin
Result := True;
if (Dest is TFilenameMapClipboardFormat) then
TFilenameMapClipboardFormat(Dest).FileMaps.Assign(FFileMaps)
else if (Dest is TFilenameMapWClipboardFormat) then
TFilenameMapWClipboardFormat(Dest).FileMaps.Assign(FFileMaps)
else
Result := inherited AssignTo(Dest);
end;
procedure TFileMapDataFormat.Clear;
begin
FFileMaps.Clear;
end;
function TFileMapDataFormat.HasData: boolean;
begin
Result := (FFileMaps.Count > 0);
end;
function TFileMapDataFormat.NeedsData: boolean;
begin
Result := (FFileMaps.Count = 0);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TFileDataFormat
//
////////////////////////////////////////////////////////////////////////////////
constructor TFileDataFormat.Create(AOwner: TDragDropComponent);
begin
inherited Create(AOwner);
FFiles := TStringList.Create;
TStringList(FFiles).OnChanging := DoOnChanging;
end;
destructor TFileDataFormat.Destroy;
begin
FFiles.Free;
inherited Destroy;
end;
function TFileDataFormat.Assign(Source: TClipboardFormat): boolean;
begin
Result := True;
if (Source is TFileClipboardFormat) then
FFiles.Assign(TFileClipboardFormat(Source).Files)
else if (Source is TPIDLClipboardFormat) then
FFiles.Assign(TPIDLClipboardFormat(Source).Filenames)
else
Result := inherited Assign(Source);
end;
function TFileDataFormat.AssignTo(Dest: TClipboardFormat): boolean;
begin
Result := True;
if (Dest is TFileClipboardFormat) then
TFileClipboardFormat(Dest).Files.Assign(FFiles)
else if (Dest is TPIDLClipboardFormat) then
TPIDLClipboardFormat(Dest).Filenames.Assign(FFiles)
else
Result := inherited AssignTo(Dest);
end;
procedure TFileDataFormat.Clear;
begin
FFiles.Clear;
end;
function TFileDataFormat.HasData: boolean;
begin
Result := (FFiles.Count > 0);
end;
function TFileDataFormat.NeedsData: boolean;
begin
Result := (FFiles.Count = 0);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropFileTarget
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropFileTarget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
OptimizedMove := True;
FFileFormat := TFileDataFormat.Create(Self);
FFileMapFormat := TFileMapDataFormat.Create(Self);
end;
destructor TDropFileTarget.Destroy;
begin
FFileFormat.Free;
FFileMapFormat.Free;
inherited Destroy;
end;
function TDropFileTarget.GetFiles: TStrings;
begin
Result := FFileFormat.Files;
end;
function TDropFileTarget.GetMappedNames: TStrings;
begin
Result := FFileMapFormat.FileMaps;
end;
function TDropFileTarget.GetPreferredDropEffect: LongInt;
begin
Result := inherited GetPreferredDropEffect;
if (Result = DROPEFFECT_NONE) then
Result := DROPEFFECT_COPY;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropFileSource
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropFileSource.Create(aOwner: TComponent);
begin
inherited Create(AOwner);
FFileFormat := TFileDataFormat.Create(Self);
FFileMapFormat := TFileMapDataFormat.Create(Self);
end;
destructor TDropFileSource.Destroy;
begin
FFileFormat.Free;
FFileMapFormat.Free;
inherited Destroy;
end;
function TDropFileSource.GetFiles: TStrings;
begin
Result := FFileFormat.Files;
end;
function TDropFileSource.GetMappedNames: TStrings;
begin
Result := FFileMapFormat.FileMaps;
end;
procedure TDropFileSource.SetFiles(AFiles: TStrings);
begin
FFileFormat.Files.Assign(AFiles);
end;
procedure TDropFileSource.SetMappedNames(ANames: TStrings);
begin
FFileMapFormat.FileMaps.Assign(ANames);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Initialization/Finalization
//
////////////////////////////////////////////////////////////////////////////////
initialization
// Data format registration
TFileDataFormat.RegisterDataFormat;
TFileMapDataFormat.RegisterDataFormat;
// Clipboard format registration
TFileDataFormat.RegisterCompatibleFormat(TFileClipboardFormat, 0, csSourceTarget, [ddRead]);
TFileDataFormat.RegisterCompatibleFormat(TPIDLClipboardFormat, 1, csSourceTarget, [ddRead]);
TFileDataFormat.RegisterCompatibleFormat(TFilenameClipboardFormat, 2, csSourceTarget, [ddRead]);
TFileDataFormat.RegisterCompatibleFormat(TFilenameWClipboardFormat, 2, csSourceTarget, [ddRead]);
TFileMapDataFormat.RegisterCompatibleFormat(TFilenameMapClipboardFormat, 0, csSourceTarget, [ddRead]);
TFileMapDataFormat.RegisterCompatibleFormat(TFilenameMapWClipboardFormat, 0, csSourceTarget, [ddRead]);
finalization
// Data format unregistration
TFileDataFormat.UnregisterDataFormat;
TFileMapDataFormat.UnregisterDataFormat;
// Clipboard format unregistration
TFileClipboardFormat.UnregisterClipboardFormat;
TFilenameClipboardFormat.UnregisterClipboardFormat;
TFilenameWClipboardFormat.UnregisterClipboardFormat;
TFilenameMapClipboardFormat.UnregisterClipboardFormat;
TFilenameMapWClipboardFormat.UnregisterClipboardFormat;
end.
|
unit TestAdvanceTextPos;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestAdvanceTextPos
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
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/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ test cases for AdvanceTextPos function
which Adem Baba is trying to speed up
This regression will ensure that the functionality is unchanged }
uses
{ DUnit }
TestFrameWork,
{ Local }
JcfStringUtils,
JcfMiscFunctions;
type
TTestAdvanceTextPos = class(TTestCase)
published
procedure TestNull;
procedure TestShortString;
procedure TestReturns;
procedure TestReturnsAtEnd;
procedure TestMultipleReturns;
end;
implementation
uses SysUtils;
{ 1 - idiot test.
Adding an empty string should not advance the text pos }
procedure TTestAdvanceTextPos.TestNull;
const
MAX_LOOP = 20;
var
liXLoop, liYLoop: Integer;
lix, liy: Integer;
begin
for liXLoop := 0 to MAX_LOOP do
begin
for liYLoop := 0 to MAX_LOOP do
begin
liX := liXLoop;
liy := liYLoop;
AdvanceTextPos('', lix, liy);
CheckEquals(liXLoop, liX);
CheckEquals(liYLoop, liY);
end;
end;
end;
{ 2 - simple test. Adding a string of (x) chars long should increase the X pos by (x)
and leave the Y pos unchanged }
procedure TTestAdvanceTextPos.TestShortString;
const
MAX_LOOP = 20;
var
liStringLengthLoop: Integer;
liXLoop, liYLoop: Integer;
lix, liy: Integer;
lsTest: string;
begin
for liStringLengthLoop := 1 to 5 do
begin
lsTest := StrRepeat('X', liStringLengthLoop);
for liXLoop := 0 to MAX_LOOP do
begin
for liYLoop := 0 to MAX_LOOP do
begin
liX := liXLoop;
liy := liYLoop;
AdvanceTextPos(lsTest, lix, liy);
CheckEquals(liXLoop + liStringLengthLoop, liX,
'X value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
CheckEquals(liYLoop, liY,
'Y value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
end;
end;
end;
end;
{ 3 - test returns. Adding a return increments the Y pos and resets the X pos }
procedure TTestAdvanceTextPos.TestReturns;
const
MAX_LOOP = 10;
var
liStringLengthLoop: Integer;
liXLoop, liYLoop: Integer;
lix, liy: Integer;
lsTest: string;
begin
for liStringLengthLoop := 1 to 20 do
begin
{ add one or more returns }
lsTest := StrRepeat(NativeLineBreak, liStringLengthLoop);
for liXLoop := 0 to MAX_LOOP do
begin
for liYLoop := 0 to MAX_LOOP do
begin
liX := liXLoop;
liy := liYLoop;
AdvanceTextPos(lsTest, liX, liY);
CheckEquals(1, liX,
'X value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
CheckEquals(liYLoop + liStringLengthLoop, liY,
'Y value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
end;
end;
end;
end;
{ 4 - returns test. Adding on a string that ends in a return
should increment the y pos and set the x pos to 1
It doesn't matter what comes before the return }
procedure TTestAdvanceTextPos.TestReturnsAtEnd;
const
MAX_LOOP = 10;
var
liStringLengthLoop: Integer;
liXLoop, liYLoop: Integer;
lix, liy: Integer;
lsTest: string;
begin
for liStringLengthLoop := 1 to 10 do
begin
lsTest := StrRepeat('X', liStringLengthLoop) + NativeLineBreak;
for liXLoop := 0 to MAX_LOOP do
begin
for liYLoop := 0 to MAX_LOOP do
begin
liX := liXLoop;
liy := liYLoop;
AdvanceTextPos(lsTest, liX, liY);
CheckEquals(1, liX,
'X value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
CheckEquals(liYLoop + 1, liY,
'Y value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
end;
end;
end;
end;
{ 5 - complex returns test with a string that contains returns
and has chars after the last return
Adding on a string that contains returns
Should increment the Y pos by the number of returns in the string
and set the X pos to the length of the text after the final return }
procedure TTestAdvanceTextPos.TestMultipleReturns;
const
MAX_LOOP = 10;
var
liStringLengthLoop: Integer;
liXLoop, liYLoop: Integer;
lix, liy: Integer;
lsLine, lsTest, lsTest2: string;
begin
for liStringLengthLoop := 1 to 10 do
begin
{ as liStringLengthLoop, the lines get longer, and there's more of them }
lsLine := StrRepeat('X', liStringLengthLoop);
lsTest := StrRepeat(lsLine + NativeLineBreak, liStringLengthLoop) + lsLine;
for liXLoop := 0 to MAX_LOOP do
begin
for liYLoop := 0 to MAX_LOOP do
begin
liX := liXLoop;
liy := liYLoop;
AdvanceTextPos(lsTest, liX, liY);
CheckEquals(liStringLengthLoop, liX,
'X value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
CheckEquals(liYLoop + liStringLengthLoop, liY,
'Y value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
{ and if it ends in a return... }
liX := liXLoop;
liy := liYLoop;
lsTest2 := lsTest + 'fooo' + NativeLineBreak;
AdvanceTextPos(lsTest2, liX, liY);
CheckEquals(1, liX,
'X2 value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
CheckEquals(liYLoop + liStringLengthLoop + 1, liY,
'Y2 value for ' + IntToStr(liXLoop) + ' ' + IntToStr(liYLoop) + ' ' + IntToStr(liStringLengthLoop));
end;
end;
end;
end;
initialization
TestFramework.RegisterTest('Procs', TTestAdvanceTextPos.Suite);
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, Outline, ComCtrls, ImgList, ExtCtrls;
type
TRegForm = class(TForm)
TreeView1: TTreeView;
ListView1: TListView;
ImageList1: TImageList;
ImageList2: TImageList;
Splitter1: TSplitter;
procedure FormCreate(Sender: TObject);
procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
procedure FormDestroy(Sender: TObject);
procedure TreeView1Expanded(Sender: TObject; Node: TTreeNode);
procedure TreeView1GetImageIndex(Sender: TObject; Node: TTreeNode);
private
{ Private declarations }
public
{ Public declarations }
procedure ShowSubKeys(ParentNode: TTreeNode;depth: Integer);
function GetFullNodeName(Node: TTreeNode):string;
end;
var
RegForm: TRegForm;
implementation
uses registry;
{$R *.DFM}
var reg : TRegistry;
function TRegForm.GetFullNodeName(Node: TTreeNode):string;
var CurNode : TTreeNode;
begin
Result:=''; CurNode := Node;
while CurNode.Parent<>nil do
begin
Result:= '\'+CurNode.Text + Result;
CurNode := CurNode.Parent;
end;
end;
procedure TRegForm.TreeView1Change(Sender: TObject; Node: TTreeNode);
var s: string;
KeyInfo : TRegKeyInfo;
ValueNames : TStringList;
i : Integer;
DataType : TRegDataType;
begin
ListView1.Items.Clear;
s:= GetFullNodeName(Node);
if not Reg.OpenKeyReadOnly(s) then Exit;
Reg.GetKeyInfo(KeyInfo);
if KeyInfo.NumValues<=0 then Exit;
ValueNames := TStringList.Create;
Reg.GetValueNames(ValueNames);
for i := 0 to ValueNames.Count-1 do
with ListView1.Items.Add do
begin
Caption := ValueNames[i];
DataType := Reg.GetDataType(ValueNames[i]);
Case DataType of
rdString: s := Reg.ReadString(ValueNames[i]);
rdInteger: s:= '0x'+IntToHex(Reg.ReadInteger(ValueNames[i]),8);
rdBinary: s:='Binary';
else s:= '???';
end;
SubItems.Add(s);
ImageIndex :=1;
end;
ValueNames.Free;
end;
procedure TRegForm.ShowSubKeys(ParentNode: TTreeNode;depth: Integer);
var ParentKey: string;
KeyNames : TStringList;
KeyInfo : TRegKeyInfo;
CurNode : TTreeNode;
i : Integer;
begin
Cursor := crHourglass;
TreeView1.Items.BeginUpdate;
ParentKey := GetFullNodeName(ParentNode);
if ParentKey<>'' then
Reg.OpenKeyReadOnly(ParentKey)
else
Reg.OpenKeyReadOnly('\');
Reg.GetKeyInfo(KeyInfo);
if KeyInfo.NumSubKeys<=0 then Exit;
KeyNames := TStringList.Create;
Reg.GetKeyNames(KeyNames);
While ParentNode.GetFirstChild<>nil do ParentNode.GetFirstChild.Delete;
if (KeyNames.Count>0) then for i:=0 to KeyNames.Count-1 do
begin
Reg.OpenKeyReadOnly(ParentKey+'\'+KeyNames[i]);
Reg.GetKeyInfo(KeyInfo);
CurNode := TreeView1.Items.AddChild(ParentNode,KeyNames[i]);
if KeyInfo.NumSubKeys>0 then
begin
TreeView1.Items.AddChild(CurNode,'');//
end;
end;
KeyNames.Free;
TreeView1.Items.EndUpdate;
Cursor := crDefault;
end;
procedure TRegForm.FormCreate(Sender: TObject);
var root : TTreeNode;
begin
Reg := TRegistry.Create;
ListView1.ViewStyle := vsReport;
with ListView1 do
begin
with Columns.Add do begin Width := ListView1.Width div 3 - 2;Caption := 'Name';end;
with Columns.Add do begin Width := ListView1.Width div 3 * 2 - 2;Caption := 'Value';end;
end;
TreeView1.Items.Clear;
Reg.RootKey := HKEY_LOCAL_MACHINE;
Root := TreeView1.Items.Add(nil,'HKEY_LOCAL_MACHINE');
TreeView1.Items.AddChild(root,'');
end;
procedure TRegForm.FormDestroy(Sender: TObject);
begin
Reg.Free;
end;
procedure TRegForm.TreeView1Expanded(Sender: TObject; Node: TTreeNode);
begin
ShowSubKeys(Node,1);
end;
procedure TRegForm.TreeView1GetImageIndex(Sender: TObject; Node: TTreeNode);
begin
with Node do
begin
if Expanded then ImageIndex := 2
else ImageIndex := 3;
end;
end;
end.
|
unit SMCnst;
interface
{Indonesian strings}
const
strMessage = 'Mencetak...';
strSaveChanges = 'Rekam perubahan-perubahan pada Database Server?';
strErrSaveChanges = 'Gagal merekam data! Cek Server connection atau data validation.';
strDeleteWarning = 'Hapus table %s?';
strEmptyWarning = 'Hapus semua record dari table %s?';
const
PopUpCaption: array [0..24] of string[33] =
('Tambah record',
'Sisipkan record',
'Ubah record',
'Hapus record',
'-',
'Cetak ...',
'Export ...',
'Filter ...',
'Cari ...',
'-',
'Save perubahan-perubahan',
'Batalkan perubahan-perubahan',
'Refresh',
'-',
'Pilih/jangan pilih record-2',
'Pilih record',
'Pilih semua record',
'-',
'Jangan pilih record',
'Jangan pilih semua record',
'-',
'Save layout kolom',
'Restore layout kolom',
'-',
'Setup...');
const //for TSMSetDBGridDialog
SgbTitle = ' Title ';
SgbData = ' Data ';
STitleCaption = 'Caption:';
STitleAlignment = 'Alignment:';
STitleColor = 'Background:';
STitleFont = 'Font:';
SWidth = 'Lebar:';
SWidthFix = 'huruf';
SAlignLeft = 'kiri';
SAlignRight = 'kanan';
SAlignCenter = 'tengah';
const //for TSMDBFilterDialog
strEqual = 'sama dengan';
strNonEqual = 'tidak sama dengan';
strNonMore = 'tidak lebih dari';
strNonLess = 'tidak kurang dari';
strLessThan = 'kurang dari';
strLargeThan = 'lebih dari';
strExist = 'kosong';
strNonExist = 'tidak kosong';
strIn = 'pada list';
strBetween = 'diantara';
strLike = 'seperti';
strOR = 'ATAU';
strAND = 'DAN';
strField = 'Field';
strCondition = 'Kondisi';
strValue = 'Nilai';
strAddCondition = ' Tambahkan kondisi-kondisi:';
strSelection = ' Pilih record-record sesuai kondisi-kondisi berikut:';
strAddToList = 'Tambahkan ke list';
strEditInList = 'Ubah pada list';
strDeleteFromList = 'Hapus dari list';
strTemplate = 'Filter template dialog';
strFLoadFrom = 'Load dari...';
strFSaveAs = 'Save sebagai..';
strFDescription = 'Deskripsi';
strFFileName = 'Nama file';
strFCreate = 'Dibuat: %s';
strFModify = 'Diubah: %s';
strFProtect = 'Di Protek untuk tidak dapat diubah';
strFProtectErr = 'File diprotek!';
const //for SMDBNavigator
SFirstRecord = 'Record pertama';
SPriorRecord = 'Record sebelumnya';
SNextRecord = 'Record berikutnya';
SLastRecord = 'Record terakhir';
SInsertRecord = 'Tambahkan record';
SCopyRecord = 'Copy record';
SDeleteRecord = 'Hapus record';
SEditRecord = 'Ubah record';
SFilterRecord = 'Kondisi-2 Filter';
SFindRecord = 'Cari record';
SPrintRecord = 'Cetak record-2';
SExportRecord = 'Ekspor record-2';
SPostEdit = 'Save perubahan-perubahan';
SCancelEdit = 'Batalkan perubahan-perubahan';
SRefreshRecord = 'Refresh data';
SChoice = 'Pilih sebuah record';
SClear = 'Batalkan pilihan pada sebuah record';
SDeleteRecordQuestion = 'Hapus record ini?';
SDeleteMultipleRecordsQuestion = 'Hapus record-2 yang dipilih?';
SRecordNotFound = 'Record tidak diketemukan';
SFirstName = 'Pertama';
SPriorName = 'Sebelumnya';
SNextName = 'Berikutnya';
SLastName = 'Terakhir';
SInsertName = 'Tambah';
SCopyName = 'Copy';
SDeleteName = 'Hapus';
SEditName = 'Ubah';
SFilterName = 'Filter';
SFindName = 'Cari';
SPrintName = 'Cetak';
SExportName = 'Ekspor';
SPostName = 'Save';
SCancelName = 'Batal';
SRefreshName = 'Refresh';
SChoiceName = 'Pilih';
SClearName = 'Reset';
SBtnOk = '&OK';
SBtnCancel = '&Batal';
SBtnLoad = 'Load';
SBtnSave = 'Save';
SBtnCopy = 'Copy';
SBtnPaste = 'Paste';
SBtnClear = 'Reset';
SRecNo = 'rec.';
SRecOf = ' dari ';
const //for EditTyped
etValidNumber = 'angka valid';
etValidInteger = 'angka integer valid';
etValidDateTime = 'tanggal/jam valid';
etValidDate = 'tanggal valid';
etValidTime = 'jam valid';
etValid = 'valid';
etIsNot = 'bukan sebuah';
etOutOfRange = 'Nilai %s diluar rentang %s..%s';
SApplyAll = 'Terapkan ke semua';
implementation
end.
|
unit uPing;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.TypInfo,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, TypInfo,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.Ping;
type
TForm8 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Button2: TButton;
Memo1: TMemo;
CnPing1: TCnPing;
procedure CnPing1PingCompleted(sender: TObject; e: _PingCompletedEventArgs); // When the PingCompleted event is raised, the PingCompletedCallback method is called.
procedure Button2Click(Sender: TObject);
private
procedure DisplayReply(reply: _PingReply);
procedure PingHostAsync(Host: String);
public
{ Public declarations }
end;
var
Form8: TForm8;
implementation
uses
{$IF CompilerVersion > 22}
Winapi.ActiveX, System.Rtti,
{$ELSE}
ActiveX, Rtti,
{$IFEND}
CNClrlib.Core, CNClrlib.Host.Utils, CNClrlib.EnumArrays, CNClrlib.Host;
{$R *.dfm}
function GetStatus(AStatus: TOleEnum): TIPStatus;
begin
Result := TIPStatus(OleEnumToOrd(IPStatusValues, AStatus));
end;
procedure TForm8.Button2Click(Sender: TObject);
begin
PingHostAsync(Edit1.Text);
end;
procedure TForm8.CnPing1PingCompleted(sender: TObject;
e: _PingCompletedEventArgs);
var
AutoResetEvent: _AutoResetEvent;
reply: IPingReply;
begin
AutoResetEvent := nil;
// If the operation was canceled, display a message to the user.
if e.Cancelled then
begin
Memo1.Lines.Add('Ping canceled.');
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
AutoResetEvent := CoAutoResetEvent.Wrap(e.UserState);
AutoResetEvent.Set_;
end;
// If an error occurred, display the exception to the user.
if e.Error <> nil then
begin
Memo1.Lines.Add('Ping failed:');
Memo1.Lines.Add(e.Error.ToString);
// Let the main thread resume.
AutoResetEvent := CoAutoResetEvent.Wrap(e.UserState);
AutoResetEvent.Set_;
end;
DisplayReply(e.Reply);
// Let the main thread resume.
if AutoResetEvent = nil then
begin
AutoResetEvent := CoAutoResetEvent.Wrap(e.UserState);
AutoResetEvent.Set_;
end;
end;
procedure TForm8.DisplayReply(reply: _PingReply);
var
status: TIPStatus;
begin
if reply = nil then
Exit;
status := GetStatus(reply.Status);
{$IF CompilerVersion > 23}
Memo1.Lines.Add(Format('ping status: %s', [TRttiEnumerationType.GetName(status)]));
{$ELSE}
Memo1.Lines.Add(Format('ping status: %s', [GetEnumName(TypeInfo(TIPStatus), Ord(status))]));
{$IFEND}
if status = TIPStatus.ipsSuccess then
begin
Memo1.Lines.Add(Format('Address: %s', [reply.Address.ToString]));
Memo1.Lines.Add(Format('RoundTrip time: %s', [IntToStr(reply.RoundtripTime)]));
Memo1.Lines.Add(Format('Time to live: %s', [IntToStr(reply.Options.Ttl)]));
Memo1.Lines.Add(Format('Don''t fragment: %s', [BoolToStr(reply.Options.DontFragment, True)]));
Memo1.Lines.Add(Format('Buffer size: %s', [IntToStr(reply.Buffer.Length)]));
end;
end;
procedure TForm8.PingHostAsync(Host: String);
var
waiter: _AutoResetEvent;
buffer: _ByteArray;
data: String;
timeout: Integer;
options: _PingOptions;
begin
if Host = '' then
raise EClrArgumentNullException.Create('Host');
waiter := CoAutoResetEvent.CreateInstance(false);
// Create a buffer of 32 bytes of data to be transmitted.
data := 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
buffer := CoEncodingHelper.CreateInstance.ASCII.GetBytes_3(data);
// Wait 12 seconds for a reply.
timeout := 12000;
// Set options for transmission:
// The data can go through 64 gateways or routers
// before it is destroyed, and the data packet
// cannot be fragmented.
options := TPingOptionsActivator.CreateInstance(64, true);
Memo1.Lines.Add(Format('Time to live: %s', [IntToStr(options.Ttl)]));
Memo1.Lines.Add(Format('Don''t fragment: %s', [boolToStr(options.DontFragment, True)]));
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
cnPing1.SendAsync(Host, timeout, buffer, options, waiter);
// Prevent this example application from ending.
// A real application should do something useful
// when possible.
waiter.WaitOne_2;
Memo1.Lines.Add('Ping example completed.');
Memo1.Lines.Add('==========================================');
Memo1.Lines.Add('');
end;
end.
|
// *************** ДОБАВЛЕНИЕ ТАЙМЕРА НА КНОПКИ ДИАЛОГОВ *************** \\
unit DlgCountdown;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes;
type
// Как искать кнопку:
// cdsByClass - по классу и индексу.
// BtnID - индекс, BtnStr - класс.
// Выполняется перебор дочерних окон в Z-порядке и берётся BtnID-ое (начиная с 1) окно с классом BtnStr.
// Для VCL окон это название класса объекта ('TButton' etc), для WinApi -
// название класса *окна* (обычно 'Button').
// !! Перебор выполняется по Z-order, а не в порядке табуляции или создания !!
// cdsByDlgID - по dialog ID (только для диалогов, загруженных из ресурсов).
// BtnID - dialog ID, BtnStr - не используется.
// cdsByText - по тексту (WindowText). Возвращается первое найденное окно с таким текстом
// BtnID - не используется, BtnStr - текст окна
// cdsHwnd - по хэндлу (для предварительно созданных диалогов, форм)
// BtnID - хэндл, BtnStr - не используется.
TCountdownDlgSearchType = (cdsByClass, cdsByDlgID, cdsByText, cdsHwnd);
// Запустить тред, который добавит обратный отсчет на вызванный диалог.
// ParentWnd - хэндл окна, вызывающего диалог (служит для определения момента
// появления диалога; диалогом будет считаться модальное окно, которое будет
// иметь ParentWnd как owner
// Secs - величина обратного отсчета
// SearchType - тип поиска контрола
// BtnID - см. TCountdownDlgSearchType
// BtnStr - см. TCountdownDlgSearchType
// BtnCaption [opt] - Базовая часть надписи, которая будет присвоена кнопке
// Имеет смысл, если изначально на кнопке нет надписи вообще
procedure LaunchCountdown(ParentWnd: HWND; Secs: Integer;
SearchType: TCountdownDlgSearchType;
BtnID: NativeInt;
const BtnStr: string;
const BtnCaption: string = '');
implementation
// Имитирует нажатие на кнопку.
procedure PushButton(ParentWnd, ButtonWnd: HWND);
begin
// Если окно не диалог - GetDlgCtrlID вернет ButtonWnd, так что обрезаем его до Word;
// в этом случае значение и не будет использоваться
SendMessage(ParentWnd, WM_COMMAND, MakeWParam(Word(GetDlgCtrlID(ButtonWnd)), BN_CLICKED), ButtonWnd);
end;
// Поиск кнопки по указанным опциям
// ParentWnd - родительское окно
// SearchType - тип поиска контрола
// BtnID - см. TCountdownDlgSearchType
// BtnStr - см. TCountdownDlgSearchType
function FindButton(ParentWnd: HWND;
SearchType: TCountdownDlgSearchType;
BtnID: NativeInt;
const BtnStr: string): HWND;
var
Counter: Integer;
begin
case SearchType of
// BtnID = item index
// BtnStr = item window class
cdsByClass:
begin
Result := FindWindowEx(ParentWnd, 0, PChar(BtnStr), nil);
Counter := 0;
while Result <> 0 do
begin
Inc(Counter);
if Counter = BtnID then
Break;
Result := FindWindowEx(ParentWnd, Result, PChar(BtnStr), nil);
end;
end;
// BtnID = Dlg item ID
cdsByDlgID:
Result := GetDlgItem(ParentWnd, BtnID);
// BtnStr = button text
cdsByText:
Result := FindWindowEx(ParentWnd, 0, nil, PChar(BtnStr));
// BtnID = button HWND
cdsHwnd:
Result := BtnID;
end;
end;
type
TEnumThreadWndData = record
OwnerWnd: HWND;
ModalWnd: HWND;
end;
PEnumThreadWndData = ^TEnumThreadWndData;
// Коллбэк для EnumThreadWindows
// Отбирает enabled окна, у которых owner disabled и совпадает с переданным в lParam
// Если окно найдено, возвращает его в lParam
function EnumThreadWndProc(Wnd: HWND; lPar: LPARAM): BOOL; stdcall;
var
Owner: HWND;
begin
if IsWindowEnabled(Wnd) then
begin
Owner := GetWindow(Wnd, GW_OWNER);
if ( (lPar <> 0) and (Owner = PEnumThreadWndData(lPar).OwnerWnd) ) or
( (Owner <> 0) and not IsWindowEnabled(Owner) ) then
begin
PEnumThreadWndData(lPar).ModalWnd := Wnd;
Exit(BOOL(0)); // Прервать перебор
end;
end;
Result := BOOL(1); // Продолжить перебор
end;
function GetModalWindow(OwnerWnd: HWND; ThreadID: DWORD): HWND;
var
etwdata: TEnumThreadWndData;
begin
etwdata.OwnerWnd := OwnerWnd;
etwdata.ModalWnd := 0;
EnumThreadWindows(ThreadID, @EnumThreadWndProc, LPARAM(@etwdata));
Result := etwdata.ModalWnd;
end;
// Запустить тред, который добавит обратный отсчет на вызванный диалог.
// ParentWnd - хэндл окна, вызывающего диалог (служит для определения момента
// появления диалога; диалогом будет считаться модальное окно, которое будет
// иметь ParentWnd как owner, и при этом ParentWnd будет disabled)
// Secs - величина обратного отсчета
// SearchType - тип поиска контрола
// BtnID - см. TCountdownDlgSearchType
// BtnStr - см. TCountdownDlgSearchType
// BtnCaption [opt] - Базовая часть надписи, которая будет присвоена кнопке
// Имеет смысл, если изначально на кнопке нет надписи вообще
procedure LaunchCountdown(ParentWnd: HWND; Secs: Integer;
SearchType: TCountdownDlgSearchType;
BtnID: NativeInt;
const BtnStr: string;
const BtnCaption: string);
var
CurrThreadID: DWORD;
begin
CurrThreadID := GetCurrentThreadId;
TThread.CreateAnonymousThread(
procedure
var
Counter: Integer;
DlgWnd, BtnWnd: HWND;
Buf: array of Char;
BtnLabelFmt: string;
Len: Integer;
CurrProcID, WndProcID: DWORD;
const
CounterFmt = '(%d)';
begin
// Ждем, пока диалог не появится. Диалогом считаем любое окно, отличное от
// ParentWnd, которое появится в данном треде поверх остальных.
repeat
DlgWnd := GetModalWindow(ParentWnd, CurrThreadID);
if (DlgWnd <> 0) and (DlgWnd <> ParentWnd) then
Break;
Sleep(100);
until False;
// Находим нужную кнопку
BtnWnd := FindButton(DlgWnd, SearchType, BtnID, BtnStr);
if not IsWindow(BtnWnd) then
Exit;
// Определяем надпись на кнопке: из параметра, из имеющегося или просто отсчет, если оба пусты
BtnLabelFmt := ''; Len := 0;
if BtnCaption <> '' then
BtnLabelFmt := BtnCaption + ' ' + CounterFmt
else
begin
Len := GetWindowTextLength(BtnWnd);
if Len > 0 then
begin
SetLength(Buf, Len + 1); // + завершающий нулевой
if GetWindowText(BtnWnd, PChar(Buf), Length(Buf)) > 0 then
BtnLabelFmt := StrPas(PChar(Buf)) + ' ' + CounterFmt;
end;
end;
if BtnLabelFmt = '' then
BtnLabelFmt := CounterFmt; // текста нет или ошибка получения
Counter := Secs;
SetWindowText(BtnWnd, Format(BtnLabelFmt, [Counter]));
while Counter > 0 do
begin
// Уменьшить счётчик
Sleep(1*MSecsPerSec);
Dec(Counter);
// Если диалог уже закрыли
if not IsWindow(DlgWnd) then
Exit;
SetWindowText(BtnWnd, Format(BtnLabelFmt, [Counter]));
end;
// Счетчик дошел до конца - вернуть надпись (на всякий случай) и нажать кнопку
if Len > 0
then SetWindowText(BtnWnd, PChar(Buf))
else SetWindowText(BtnWnd, nil);
PushButton(DlgWnd, BtnWnd);
end
).Start;
end;
end.
|
unit UUser;
interface
uses
System.JSON.Types, System.JSON.Readers, System.JSON.BSON,
System.JSON.Builders, FireDAC.Phys.MongoDBWrapper, UDMMongo,
IdHashMessageDigest, SysUtils, IdHash, FireDAC.Phys.MongoDBDataSet;
type TUser = class
private
FUsename: string;
FName: string;
FPassword: string;
FActive: boolean;
procedure SetUsername(Value: string);
function GetUsername: string;
procedure SetName(Value: string);
function GetName: string;
procedure SetPassword(Value: string);
function GetPassword: string;
procedure SetActive(Value: boolean);
function GetActive: boolean;
function GetMD5Password: string;
public
property Username: string read GetUsername write SetUsername;
property Name: string read GetName write SetName;
property Password: string read GetPassword write SetPassword;
property Active: boolean read GetActive write SetActive;
//Operation with DB
function Save: boolean;
function GetAll : IMongoCursor;
end;
implementation
{ TUser }
function TUser.GetActive: boolean;
begin
Result := FActive;
end;
function TUser.GetAll: IMongoCursor;
var
MongoDataSet: TFDMongoDataSet;
DMMongo: TDMMongo;
begin
DMMongo := TDMMongo.Create(nil);
Result := DMMongo.SearchAll('users');
end;
function TUser.GetMD5Password: string;
var
MD5: TIdHashMessageDigest5;
begin
MD5 := TIdHashMessageDigest5.Create;
try
Result := MD5.HashStringAsHex(FPassword);
finally
FreeAndNil(MD5);
end;
end;
function TUser.GetName: string;
begin
Result := FName;
end;
function TUser.GetPassword: string;
begin
Result := FPassword;
end;
function TUser.GetUsername: string;
begin
Result := FUsename;
end;
function TUser.Save: boolean;
var
Doc: TMongoDocument;
DBMongo: TDMMongo;
begin
DBMongo := TDMMongo.Create(nil);
Doc := DBMongo.GetNewDocument;
try
Doc
.Add('name', FName)
.Add('username', FUsename)
.Add('password', GetMD5Password)
.Add('active', FActive);
Result := DBMongo.Insert('users',Doc)
finally
FreeAndNil(DBMongo);
FreeAndNil(Doc);
end;
Result := False;
end;
procedure TUser.SetActive(Value: boolean);
begin
FActive := Value;
end;
procedure TUser.SetName(Value: string);
begin
FName := Value;
end;
procedure TUser.SetPassword(Value: string);
begin
FPassword := Value;
end;
procedure TUser.SetUsername(Value: string);
begin
FUsename := Value;
end;
end.
|
{ 25/05/2007 11:10:25 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 11:08:25 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:43:02 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: MAU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Set Data example to Delphi
History:
-----------------------------------------------------------------------------}
unit MAU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
//These must copy the GUIDS from the mission file
GuidCustomAction1: TGuid = '{CDA37D47-3645-4149-8CF6-F11553829B55}';
GuidCustomAction2: TGuid = '{C342D8DE-1FC6-4027-9E18-EE9581BEC7E4}';
GuidMissionAction1: TGuid = '{E47162A7-3FED-46B1-B16C-9B331B91A825}';
GuidMissionAction2: TGuid = '{3D2D8194-A5F8-43D5-8CB8-89081BD2C0CC}';
type
// Use enumerated types to create unique IDs as required
TEventID = (EventMissionAction, EventMissionCompleted);
// The form
TMissionActionForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
end;
var
MissionActionForm: TMissionActionForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
MissionActionForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TMissionActionForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr: HRESULT;
Evt: PSimconnectRecvEvent;
OpenData: PSimConnectRecvOpen;
pCustomAction: PSimConnectRecvCustomAction;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EventMissionAction:
Memo.Lines.Add(Format('Mission Action : %d', [Evt^.dwData]));
EventMissionCompleted:
Memo.Lines.Add(Format('Mission Completed : %d', [Evt^.dwData]));
end;
end;
SIMCONNECT_RECV_ID_CUSTOM_ACTION:
begin
pCustomAction := PSimConnectRecvCustomAction(pData);
if GUIDToString(pCustomAction^.guidInstanceId) = GUIDToString(GuidCustomAction1) then
begin
Memo.Lines.Add(Format('Custom Action 1, payload: %s',
[pCustomAction^.szPayLoad]));
// Custom actions can include calls to actions within the mission xml file, though
// if this is done we cannot know if the actions have been completed within this
// section of code (the actions may initiate triggers and it may be some time
// before the sequence is ended).
hr := SimConnect_ExecuteMissionAction(hSimConnect, GuidMissionAction1);
hr := SimConnect_ExecuteMissionAction(hSimConnect, GuidMissionAction2);
end
else
if GUIDToString(pCustomAction^.guidInstanceId) = GUIDToString(GuidCustomAction2) then
begin
Memo.Lines.Add(Format('Custom Action 2, payload: %s',
[pCustomAction^.szPayLoad]));
// This action simply notifies the Mission system that the first action
// is complete
hr := SimConnect_CompleteCustomMissionAction(hSimConnect,
GuidCustomAction1);
end else
Memo.Lines.Add(Format('Unknown custom action: %s',
[GUIDToString(pCustomAction^.guidInstanceId)]));
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TMissionActionForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TMissionActionForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TMissionActionForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TMissionActionForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Subscribe to the mission completed event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect,
Ord(EventMissionCompleted), 'MissionCompleted');
// Subscribe to a notification when a custom action executes
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventMissionAction),
'CustomMissionActionExecuted');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TMissionActionForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Mission Action', 0, 0, 0, 0)))
then
begin
StatusBar.Panels[0].Text := 'Connected';
// Subscribe to the mission completed event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect,
Ord(EventMissionCompleted), 'MissionCompleted');
// Subscribe to a notification when a custom action executes
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventMissionAction),
'CustomMissionActionExecuted');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit uFizzBuzz;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure fizzbuzz;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
memo1.Clear;
fizzbuzz;
end;
procedure TForm1.fizzbuzz;
var
cnt : integer;
function fizzOrBuzz(i: integer): string;
begin
if ((i mod 3) + (i mod 5))=0 then //or (i mod 15)
result := 'FIZZBUZZ'
else if (i mod 3) = 0 then
result := 'FIZZ'
else if (i mod 5) = 0 then
result := 'BUZZ'
else
result := inttostr(i);
end;
begin
for cnt := 1 to 100 do
begin
memo1.Lines.add(fizzOrBuzz(cnt));
end
end;
end.
|
{ Portable BP compatible Dos unit
This unit supports most of the routines and declarations of BP's
Dos unit.
Notes:
- The procedures Keep, GetIntVec, SetIntVec are not supported
since they make only sense for Dos real-mode programs (and GPC
compiled programs do not run in real-mode, even on IA32 under
Dos). The procedures Intr and MsDos are only supported under
DJGPP if `__BP_UNPORTABLE_ROUTINES__' is defined (with the
`-D__BP_UNPORTABLE_ROUTINES__' option). A few other routines are
also only supported with this define, but on all platforms (but
they are crude hacks, that's why they are not supported without
this define).
- The internal structure of file variables (FileRec and TextRec)
is different in GPC. However, as far as TFDDs are concerned,
there are other ways to achieve the same in GPC, see the GPC
unit.
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Authors: Frank Heckenbach <frank@pascal.gnu.de>
Prof. Abimbola A. Olowofoyeku <African_Chief@bigfoot.com>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-,maximum-field-alignment 0}
{$if __GPC_RELEASE__ < 20030412}
{$error This unit requires GPC release 20030412 or newer.}
{$endif}
module Dos;
{ GPC and this unit use `AnyFile' for different meanings. Export
renaming helps us to avoid a conflict here. If you use both units,
the meaning of the latter one will be effective, but you always
get the built-in meaning by using `GPC_AnyFile'. }
export Dos = all (DosAnyFile => AnyFile, FSearch, FExpand, FSplit, GetEnv);
import GPC (MaxLongInt => GPC_Orig_MaxLongInt); System;
type
GPC_AnyFile = AnyFile;
Byte8 = Cardinal attribute (Size = 8);
Word16 = Cardinal attribute (Size = 16);
Word32 = Cardinal attribute (Size = 32);
TDosAttr = Word;
const
{ File attribute constants }
ReadOnly = $01;
Hidden = $02; { set for dot files except '.' and '..' }
SysFile = $04; { not supported }
VolumeID = $08; { not supported }
Directory = $10;
Archive = $20; { means: not executable }
DosAnyFile = $3f;
{ Flag bit masks -- only used by the unportable Dos routines }
FCarry = 1;
FParity = 4;
FAuxiliary = $10;
FZero = $40;
FSign = $80;
FOverflow = $800;
{ DosError codes }
DosError_FileNotFound = 2;
DosError_PathNotFound = 3;
DosError_AccessDenied = 5;
DosError_InvalidMem = 9;
DosErorr_InvalidEnv = 10;
DosError_NoMoreFiles = 18;
DosError_IOError = 29;
DosError_ReadFault = 30;
type
{ String types. Not used in this unit, but declared for
compatibility. }
ComStr = String [127]; { Command line string }
PathStr = String [79]; { File pathname string }
DirStr = String [67]; { Drive and directory string }
NameStr = String [8]; { File name string }
ExtStr = String [4]; { File extension string }
TextBuf = array [0 .. 127] of Char;
{ Search record used by FindFirst and FindNext }
SearchRecFill = packed array [1 .. 21] of Byte8;
SearchRec = record
Fill: SearchRecFill;
Attr: Byte8;
Time,
Size: LongInt;
Name: {$ifdef __BP_TYPE_SIZES__}
String [12]
{$else}
TString
{$endif}
end;
{ Date and time record used by PackTime and UnpackTime }
DateTime = record
Year, Month, Day, Hour, Min, Sec: Word
end;
{ 8086 CPU registers -- only used by the unportable Dos routines }
Registers = record
case Boolean of
False: (ax, bx, cx, dx, bp, si, di, ds, es, Flags: Word16);
True : (al, ah, bl, bh, cl, ch, dl, dh: Byte8)
end;
var
{ Error status variable }
DosError: Integer = 0;
procedure GetDate (var Year, Month, Day, DayOfWeek: Word);
procedure GetTime (var Hour, Minute, Second, Sec100: Word);
procedure GetCBreak (var BreakOn: Boolean);
procedure SetCBreak (BreakOn: Boolean);
{ GetVerify and SetVerify are dummies except for DJGPP (in the
assumption that any real OS knows by itself when and how to verify
its disks). }
procedure GetVerify (var VerifyOn: Boolean);
procedure SetVerify (VerifyOn: Boolean);
function DiskFree (Drive: Byte): LongInt;
function DiskSize (Drive: Byte): LongInt;
procedure GetFAttr (var f: GPC_AnyFile; var Attr: TDosAttr);
procedure SetFAttr (var f: GPC_AnyFile; Attr: TDosAttr);
procedure GetFTime (var f: GPC_AnyFile; var MTime: LongInt);
procedure SetFTime (var f: GPC_AnyFile; MTime: LongInt);
{ FindFirst and FindNext are quite inefficient since they emulate
all the brain-dead Dos stuff. If at all possible, the standard
routines OpenDir, ReadDir and CloseDir (in the GPC unit) should be
used instead. }
procedure FindFirst (const Path: String; Attr: TDosAttr; var SR: SearchRec);
procedure FindNext (var SR: SearchRec);
procedure FindClose (var SR: SearchRec);
procedure UnpackTime (p: LongInt; var t: DateTime);
procedure PackTime (const t: DateTime; var p: LongInt);
function EnvCount: Integer;
function EnvStr (EnvIndex: Integer): TString;
procedure SwapVectors;
{ Exec executes a process via Execute, so RestoreTerminal is called
with the argument True before and False after executing the
process. }
procedure Exec (const Path, Params: String);
function DosExitCode: Word;
{ Unportable Dos-only routines and declarations }
{$ifdef __BP_UNPORTABLE_ROUTINES__}
{$ifdef __GO32__}
{ These are unportable Dos-only declarations and routines, since
interrupts are Dos and CPU specific (and have no place in a
high-level program, anyway). }
procedure Intr (IntNo: Byte; var Regs: Registers);
procedure MsDos (var Regs: Registers);
{$endif}
{ Though probably all non-Dos systems have versions numbers as well,
returning them here would usually not do what is expected, e.g.
testing if certain Dos features are present by comparing the
version number. Therefore, this routine always returns 7 (i.e.,
version 7.0) on non-Dos systems, in the assumption that any real
OS has at least the features of Dos 7. }
function DosVersion: Word;
{ Changing the system date and time is a system administration task,
not allowed to a normal process. On non-Dos systems, these
routines emulate the changed date/time, but only for GetTime and
GetDate (not the RTS date/time routines), and only for this
process, not for child processes or even the parent process or
system-wide. }
procedure SetDate (Year, Month, Day: Word);
procedure SetTime (Hour, Minute, Second, Sec100: Word);
{$endif}
end;
type
PLongInt = ^LongInt;
var
DosExitCodeVar: Word = 0;
TimeDelta: MicroSecondTimeType = 0;
procedure GetDate (var Year, Month, Day, DayOfWeek: Word);
var
t: MicroSecondTimeType;
ts: TimeStamp;
begin
t := GetMicroSecondTime + TimeDelta;
UnixTimeToTimeStamp (t div 1000000, ts);
Year := ts.Year;
Month := ts.Month;
Day := ts.Day;
DayOfWeek := ts.DayOfWeek
end;
procedure GetTime (var Hour, Minute, Second, Sec100: Word);
var
t: MicroSecondTimeType;
ts: TimeStamp;
begin
t := GetMicroSecondTime + TimeDelta;
UnixTimeToTimeStamp (t div 1000000, ts);
Hour := ts.Hour;
Minute := ts.Minute;
Second := ts.Second;
Sec100 := (t mod 1000000) div 10000
end;
function DiskFree (Drive: Byte): LongInt;
var
Path: String (2);
Buf: StatFSBuffer;
begin
DiskFree := 0; { @@ spurious gcc-2.95 warning on m68k, S390 }
if Drive = 0 then
Path := DirSelf
else
Path := Succ ('a', Drive - 1) + ':';
if StatFS (Path, Buf) then
DiskFree := Buf.BlockSize * Buf.BlocksFree
else
begin
DosError := DosError_AccessDenied;
DiskFree := -1
end
end;
function DiskSize (Drive: Byte): LongInt;
var
Path: String (2);
Buf: StatFSBuffer;
begin
DiskSize := 0; { @@ spurious gcc-2.95 warning on m68k }
if Drive = 0 then
Path := DirSelf
else
Path := Succ ('a', Drive - 1) + ':';
if StatFS (Path, Buf) then
DiskSize := Buf.BlockSize * Buf.BlocksTotal
else
begin
DosError := DosError_AccessDenied;
DiskSize := -1
end
end;
procedure GetFAttr (var f: GPC_AnyFile; var Attr: TDosAttr);
var
b: BindingType;
d: OrigInt;
begin
b := Binding (f);
Attr := 0;
if not (b.Bound and (b.Existing or b.Directory or b.Special)) then
DosError := DosError_FileNotFound
else
begin
DosError := 0;
if b.Directory then Attr := Attr or Directory;
if not b.Writable then Attr := Attr or ReadOnly;
if not b.Executable then Attr := Attr or Archive;
d := Length (b.Name);
while (d > 0) and not (b.Name[d] in DirSeparators) do Dec (d);
if (Length (b.Name) > d + 1) and (b.Name[d + 1] = '.') and
((Length (b.Name) > d + 2) or (b.Name[d + 2] <> '.')) then
Attr := Attr or Hidden
end
end;
procedure SetFAttr (var f: GPC_AnyFile; Attr: TDosAttr);
var b: BindingType;
begin
b := Binding (f);
if not b.Bound then
begin
DosError := DosError_FileNotFound;
Exit
end;
if (Attr and ReadOnly) = 0 then
or (b.Mode, fm_UserWritable) { Set only user write permissions, for reasons of safety! }
else
and (b.Mode, not (fm_UserWritable or fm_GroupWritable or fm_OthersWritable));
if (Attr and Archive) = 0 then
or (b.Mode, fm_UserExecutable or fm_GroupExecutable or fm_OthersExecutable)
else
and (b.Mode, not (fm_UserExecutable or fm_GroupExecutable or fm_OthersExecutable));
ChMod (f, b.Mode);
if IOResult <> 0 then DosError := DosError_AccessDenied
end;
procedure GetFTime (var f: GPC_AnyFile; var MTime: LongInt);
var
b: BindingType;
Year, Month, Day, Hour, Minute, Second: CInteger;
dt: DateTime;
begin
b := Binding (f);
if not (b.Bound and (b.Existing or b.Directory or b.Special)) then
DosError := DosError_FileNotFound
else
begin
if b.ModificationTime >= 0 then
begin
UnixTimeToTime (b.ModificationTime, Year, Month, Day, Hour, Minute, Second, Null, Null, Null, Null);
dt.Year := Year;
dt.Month := Month;
dt.Day := Day;
dt.Hour := Hour;
dt.Min := Minute;
dt.Sec := Second;
PackTime (dt, MTime)
end
else
MTime := 0;
DosError := 0
end
end;
procedure SetFTime (var f: GPC_AnyFile; MTime: LongInt);
var
dt: DateTime;
ut: UnixTimeType;
begin
UnpackTime (MTime, dt);
with dt do ut := TimeToUnixTime (Year, Month, Day, Hour, Min, Sec);
DosError := DosError_AccessDenied;
if ut >= 0 then
begin
SetFileTime (f, ut, ut);
if IOResult = 0 then DosError := 0
end
end;
{ Since there's no explicit closing of FindFirst/FindNext, FindList keeps
tracks of all running searches so they can be closed automatically when
necessary, and Magic indicates if a SearchRec is currently in use. }
const
srOpened = $2424d00f;
srDone = $4242f00d;
type
TSRFillInternal = packed record
Magic: OrigInt;
Unused: packed array [1 .. SizeOf (SearchRecFill) - SizeOf (OrigInt)] of Byte
end;
PPFindList = ^PFindList;
PFindList = ^TFindList;
TFindList = record
Next: PFindList;
SR : ^SearchRec;
Dir,
BaseName,
Ext : TString;
Attr: TDosAttr;
PDir: Pointer
end;
var
FindList: PFindList = nil;
procedure CloseFind (PTemp: PPFindList);
var Temp: PFindList;
begin
Temp := PTemp^;
CloseDir (Temp^.PDir);
TSRFillInternal (Temp^.SR^.Fill).Magic := srDone;
PTemp^ := Temp^.Next;
Dispose (Temp)
end;
procedure FindFirst (const Path: String; Attr: TDosAttr; var SR: SearchRec);
var
Temp: PFindList;
PTemp: PPFindList;
begin
{ If SR was used before, close it first }
PTemp := @FindList;
while (PTemp^ <> nil) and (PTemp^^.SR <> @SR) do PTemp := @PTemp^^.Next;
if PTemp^ <> nil then
begin
CloseFind (PTemp);
if IOResult <> 0 then DosError := DosError_ReadFault
end;
if (Attr and not (ReadOnly or Archive)) = VolumeID then
begin
DosError := DosError_NoMoreFiles;
Exit
end;
SetReturnAddress (ReturnAddress (0));
New (Temp);
RestoreReturnAddress;
FSplit (Path, Temp^.Dir, Temp^.BaseName, Temp^.Ext);
if Temp^.Dir = '' then Temp^.Dir := DirSelf + DirSeparator;
if Temp^.Ext = '' then Temp^.Ext := ExtSeparator;
Temp^.SR := @SR;
Temp^.Attr := Attr;
Temp^.PDir := OpenDir (Temp^.Dir);
if IOResult <> 0 then
begin
TSRFillInternal (SR.Fill).Magic := srDone;
Dispose (Temp);
DosError := DosError_NoMoreFiles;
Exit
end;
TSRFillInternal (SR.Fill).Magic := srOpened;
Temp^.Next := FindList;
FindList := Temp;
SetReturnAddress (ReturnAddress (0));
FindNext (SR);
RestoreReturnAddress
end;
procedure FindNext (var SR: SearchRec);
var
Temp: PFindList;
PTemp: PPFindList;
FileName, Dir, BaseName, Ext: TString;
f: Text;
TmpAttr: TDosAttr;
TmpTime: LongInt;
{ Emulate Dos brain-damaged file name wildcard matching }
function MatchPart (const aName, Mask: String): Boolean;
var i: OrigInt;
begin
for i := 1 to Length (Mask) do
case Mask[i] of
'?': ;
'*': Return True;
else
if (i > Length (aName)) or (FileNameLoCase (aName[i]) <> FileNameLoCase (Mask[i])) then Return False
end;
MatchPart := Length (Mask) >= Length (aName)
end;
begin
DosError := 0;
{ Check if SR is still valid }
case TSRFillInternal (SR.Fill).Magic of
srOpened: ;
srDone: begin
DosError := DosError_NoMoreFiles;
Exit
end;
else
DosError := DosError_InvalidMem;
Exit
end;
PTemp := @FindList;
while (PTemp^ <> nil) and (PTemp^^.SR <> @SR) do PTemp := @PTemp^^.Next;
Temp := PTemp^;
if Temp = nil then
begin
DosError := DosError_InvalidMem;
Exit
end;
repeat
FileName := ReadDir (Temp^.PDir);
if FileName = '' then
begin
CloseFind (PTemp);
if IOResult = 0 then
DosError := DosError_NoMoreFiles
else
DosError := DosError_ReadFault;
Exit
end;
SetReturnAddress (ReturnAddress (0));
Assign (f, Temp^.Dir + FileName);
RestoreReturnAddress;
GetFAttr (f, TmpAttr);
SR.Attr := TmpAttr;
FSplit (FileName, Dir, BaseName, Ext);
if Ext = '' then Ext := ExtSeparator
until MatchPart (BaseName, Temp^.BaseName) and MatchPart (Ext, Temp^.Ext) and
{ Emulate Dos brain-damaged file attribute matching }
(((Temp^.Attr and (Hidden or SysFile)) <> 0) or ((TmpAttr and Hidden) = 0)) and
(((Temp^.Attr and Directory) <> 0) or ((TmpAttr and Directory) = 0));
SR.Name := FileName;
if DosError <> 0 then Exit;
GetFTime (f, TmpTime);
SR.Time := TmpTime;
if Binding (f).Existing then
begin
Reset (f);
SR.Size := FileSize (f);
Close (f)
end
else
SR.Size := 0
end;
procedure FindClose (var SR: SearchRec);
var PTemp: PPFindList;
begin
PTemp := @FindList;
while (PTemp^ <> nil) and (PTemp^^.SR <> @SR) do PTemp := @PTemp^^.Next;
if PTemp^ <> nil then
begin
CloseFind (PTemp);
if IOResult <> 0 then DosError := DosError_ReadFault
end
end;
procedure UnpackTime (p: LongInt; var t: DateTime);
begin
t.Year := (p shr 25) and $7f + 1980;
t.Month := (p shr 21) and $f;
t.Day := (p shr 16) and $1f;
t.Hour := (p shr 11) and $1f;
t.Min := (p shr 5) and $3f;
t.Sec := 2 * (p and $1f)
end;
procedure PackTime (const t: DateTime; var p: LongInt);
begin
p := (LongInt (t.Year) - 1980) shl 25 + LongInt (t.Month) shl 21 + LongInt (t.Day) shl 16
+ t.Hour shl 11 + t.Min shl 5 + t.Sec div 2
end;
function EnvCount: Integer;
begin
EnvCount := Environment^.Count
end;
function EnvStr (EnvIndex: Integer): TString;
begin
if (EnvIndex < 1) or (EnvIndex > EnvCount) then
EnvStr := ''
else
EnvStr := CString2String (Environment^.CStrings[EnvIndex])
end;
procedure SwapVectors;
begin
{ Nothing to be done }
end;
procedure Exec (const Path, Params: String);
begin
DosExitCodeVar := Execute (Path + ' ' + Params);
if IOResult <> 0 then DosError := DosError_FileNotFound
end;
function DosExitCode: Word;
begin
DosExitCode := DosExitCodeVar
end;
{$ifdef __GO32__}
type
TDPMIRegs = record
edi, esi, ebp, Reserved, ebx, edx, ecx, eax: Word32;
Flags, es, ds, fs, gs, ip, cs, sp, ss: Word16
end;
procedure RealModeInterrupt (InterruptNumber: Integer; var Regs: TDPMIRegs); external name '__dpmi_int';
procedure Intr (IntNo: Byte; var Regs: Registers);
var DPMIRegs: TDPMIRegs;
begin
FillChar (DPMIRegs, SizeOf (DPMIRegs), 0);
with DPMIRegs do
begin
edi := Regs.di;
esi := Regs.si;
ebp := Regs.bp;
ebx := Regs.bx;
edx := Regs.dx;
ecx := Regs.cx;
eax := Regs.ax;
Flags := Regs.Flags;
es := Regs.es;
ds := Regs.ds;
RealModeInterrupt (IntNo, DPMIRegs);
Regs.di := edi;
Regs.si := esi;
Regs.bp := ebp;
Regs.bx := ebx;
Regs.dx := edx;
Regs.cx := ecx;
Regs.ax := eax;
Regs.Flags := Flags;
Regs.es := es;
Regs.ds := ds
end
end;
procedure MsDos (var Regs: Registers);
begin
Intr ($21, Regs)
end;
procedure GetCBreak (var BreakOn: Boolean);
var Regs: Registers;
begin
Regs.ax := $3300;
MsDos (Regs);
BreakOn := Regs.dl <> 0
end;
procedure SetCBreak (BreakOn: Boolean);
var Regs: Registers;
begin
Regs.ax := $3301;
Regs.dx := Ord (BreakOn);
MsDos (Regs)
end;
procedure GetVerify (var VerifyOn: Boolean);
var Regs: Registers;
begin
Regs.ax := $5400;
MsDos (Regs);
VerifyOn := Regs.al <> 0
end;
procedure SetVerify (VerifyOn: Boolean);
var Regs: Registers;
begin
Regs.ax := $2e00 + Ord (VerifyOn);
MsDos (Regs)
end;
function DosVersion: Word;
var Regs: Registers;
begin
Regs.ax := $3000;
MsDos (Regs);
DosVersion := Regs.ax
end;
{$else}
{$ifdef _WIN32}
{$define WINAPI(X) external name X; attribute (stdcall)}
const
StdInputHandle = -10;
EnableProcessedInput = 1;
function GetConsoleMode (ConsoleHandle: Integer; var Mode: Integer): Boolean; WINAPI ('GetConsoleMode');
function SetConsoleMode (ConsoleHandle: Integer; Mode: Integer): Boolean; WINAPI ('SetConsoleMode');
function GetStdHandle (StdHandle: Integer): Integer; WINAPI ('GetStdHandle');
procedure GetCBreak (var BreakOn: Boolean);
var Mode: Integer;
begin
if GetConsoleMode (GetStdHandle (StdInputHandle), Mode) then
BreakOn := (Mode and EnableProcessedInput) <> 0
else
BreakOn := True
end;
procedure SetCBreak (BreakOn: Boolean);
var i: Integer;
begin
if GetConsoleMode (GetStdHandle (StdInputHandle), i) then
begin
if BreakOn then
i := i or EnableProcessedInput
else
i := i and not EnableProcessedInput;
Discard (SetConsoleMode (GetStdHandle (StdInputHandle), i))
end
end;
{$else}
procedure GetCBreak (var BreakOn: Boolean);
begin
BreakOn := GetInputSignals
end;
procedure SetCBreak (BreakOn: Boolean);
begin
SetInputSignals (BreakOn)
end;
{$endif}
var
LastVerify: Boolean = True;
procedure GetVerify (var VerifyOn: Boolean);
begin
VerifyOn := LastVerify
end;
procedure SetVerify (VerifyOn: Boolean);
begin
LastVerify := VerifyOn
end;
function DosVersion: Word;
begin
DosVersion := 7
end;
{$endif}
{$ifdef __BP_UNPORTABLE_ROUTINES__}
{$ifdef __GO32__}
procedure SetDate (Year, Month, Day: Word);
var Regs: Registers;
begin
Regs.ax := $2b00;
Regs.cx := Year;
Regs.dx := $100 * Month + Day;
MsDos (Regs)
end;
procedure SetTime (Hour, Minute, Second, Sec100: Word);
var Regs: Registers;
begin
Regs.ax := $2d00;
Regs.cx := $100 * Hour + Minute;
Regs.dx := $100 * Second + Sec100;
MsDos (Regs)
end;
{$else}
{ We cannot easily set the date without the time or vice versa while
treating DST correctly under all circumstances. }
procedure SetDateTime (Year, Month, Day, Hour, Minute, Second, Sec100: Word);
begin
TimeDelta := MicroSecondTimeType (TimeToUnixTime (Year, Month, Day, Hour, Minute, Second)) * 1000000 + Sec100 * 10000 - GetMicroSecondTime
end;
procedure SetDate (Year, Month, Day: Word);
var Hour, Minute, Second, Sec100: Word;
begin
GetTime (Hour, Minute, Second, Sec100);
SetDateTime (Year, Month, Day, Hour, Minute, Second, Sec100)
end;
procedure SetTime (Hour, Minute, Second, Sec100: Word);
var Year, Month, Day, DayOfWeek: Word;
begin
GetDate (Year, Month, Day, DayOfWeek);
SetDateTime (Year, Month, Day, Hour, Minute, Second, Sec100)
end;
{$endif}
{$endif}
to end do
while FindList <> nil do
begin
var i: OrigInt = IOResult;
CloseFind (@FindList);
InOutRes := i
end;
end.
|
unit ncFirewall;
{
ResourceString: Dario 12/03/13
}
interface
uses
ActiveX, ComObj, ncDebug, SysUtils;
procedure addPortToFirewall(EntryName:string;PortNumber:Cardinal);
procedure allowexceptionsOnFirewall;
procedure addApplicationToFirewall(EntryName:string;ApplicationPathAndExe:string);
implementation
Const
NET_FW_PROFILE_DOMAIN = 0;
NET_FW_PROFILE_STANDARD = 1;
NET_FW_IP_VERSION_ANY = 2;
NET_FW_IP_PROTOCOL_UDP = 17;
NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_SCOPE_ALL = 0;
NET_FW_SCOPE_LOCAL_SUBNET = 1;
procedure allowexceptionsOnFirewall;
var
fwMgr, fwPolicies:OleVariant;
begin
try
fwMgr := CreateOLEObject('HNetCfg.FwMgr'); // do not localize
fwPolicies := fwMgr.LocalPolicy.CurrentProfile;
fwPolicies.ExceptionsNotAllowed := False;
except
on E: Exception do
DebugMsg('allowexceptionsOnFirewall - Exception: '+E.Message); // do not localize
end;
end;
procedure addPortToFirewall(EntryName:string;PortNumber:Cardinal);
var
fwMgr,port:OleVariant;
profile:OleVariant;
begin
try
fwMgr := CreateOLEObject('HNetCfg.FwMgr'); // do not localize
profile := fwMgr.LocalPolicy.CurrentProfile;
port := CreateOLEObject('HNetCfg.FWOpenPort'); // do not localize
port.Name := EntryName;
port.Protocol := NET_FW_IP_PROTOCOL_TCP;
port.Port := PortNumber;
port.Scope := NET_FW_SCOPE_ALL;
port.Enabled := true;
profile.GloballyOpenPorts.Add(port);
except
on E: Exception do
DebugMsg('addPortToFirewall - Exception: ' + E.Message); // do not localize
end;
end;
procedure addApplicationToFirewall(EntryName:string;ApplicationPathAndExe:string);
var
fwMgr,app,port:OleVariant;
profile:OleVariant;
begin
try
fwMgr := CreateOLEObject('HNetCfg.FwMgr'); // do not localize
profile := fwMgr.LocalPolicy.CurrentProfile;
app := CreateOLEObject('HNetCfg.FwAuthorizedApplication'); // do not localize
app.ProcessImageFileName := ApplicationPathAndExe;
app.Name := EntryName;
app.Scope := NET_FW_SCOPE_ALL;
app.IpVersion := NET_FW_IP_VERSION_ANY;
app.Enabled :=true;
profile.AuthorizedApplications.Add(app);
except
on E: Exception do
DebugMsg('addApplicationToFirewall - Exception: '+E.Message); // do not localize
end;
end;
end.
|
unit umutex;
interface
uses Windows, SysUtils;
type
tMutexLog = procedure(msg:string) of object;
tMutex = class
private
onLog : tMutexLog;
handle : cardinal;
f_name : string;
procedure log(s:string);
function name_local : string;
function name_global : string;
function name_current : string;
public
constructor create(v_name : string; v_onLog : tMutexLog = nil);
destructor destroy; override;
function open(create_new : boolean = false) : boolean;
procedure close;
procedure Lock;
procedure UnLock;
property name : string read name_current;
end;
var
open_mutex_local : boolean;
implementation
uses
AccCtrl, AclAPI;
constructor tMutex.create(v_name : string; v_onLog : tMutexLog = nil);
begin
inherited create;
handle := 0;
f_name := 'SpRecordNEW_'+self.ClassName+'_'+v_name;
onLog := v_onLog;
end;
destructor tMutex.destroy;
begin
if self = nil then exit;
if handle <> 0 then
self.close;
inherited destroy;
end;
procedure tMutex.log(s:string);
begin
if self = nil then exit;
if @onLog = nil then exit;
onLog(self.ClassName+#9+s);
end;
function tMutex.name_local : string;
begin
if self = nil then exit;
result := 'Local\'+f_name;
end;
function tMutex.name_global : string;
begin
if self = nil then exit;
result := 'Global\'+f_name;
end;
function tMutex.name_current : string;
begin
if self = nil then exit;
if open_mutex_local then
result :=name_local
else
result :=name_global;
end;
function tMutex.open(create_new : boolean = false) : boolean;
var
error_code : cardinal;
begin
result := false;
if self = nil then exit;
self.close;
handle := CreateMutex(nil, false, pchar(name_current));
if handle = 0 then
begin
log('ERROR: tMutex "'+name_current+'" create error: '+SysErrorMessage(GetLastError));
result := false;
exit;
end;
if (GetLastError = ERROR_ALREADY_EXISTS) and create_new then
begin
log('ERROR: tMutex "'+name_current+'" param create_new = TRUE, '+SysErrorMessage(GetLastError));
self.close;
result := false;
exit;
end;
error_code := SetSecurityInfo(handle,
SE_KERNEL_OBJECT,
DACL_SECURITY_INFORMATION,
nil,
nil,
nil,
nil);
if error_code <> ERROR_SUCCESS then
log('ERROR: Map file of "'+name_current+'" SetSecurityInfo return : '+inttostr(error_code));
result := true;
end;
procedure tMutex.close;
begin
if self = nil then exit;
if handle <> 0 then
if not CloseHandle(handle) then
log('ERROR: tMutex "'+name_current+'" CloseHandle return false: '+SysErrorMessage(GetLastError));
handle := 0;
end;
procedure TMutex.Lock;
var
result : cardinal;
begin
if self = nil then exit;
if handle = 0 then
begin
log('Lock with handle = 0');
exit;
end;
Result := WaitForSingleObject(handle, 2000);
if result = WAIT_OBJECT_0 then exit;
if result = WAIT_ABANDONED then
log('Lock WAIT_ABANDONED')
else
if result = WAIT_TIMEOUT then
log('Lock WAIT_TIMEOUT')
else
raise Exception.Create('Mutex lock error'); //WAIT_FAILED and ect
end;
procedure TMutex.UnLock;
begin
if self = nil then exit;
if handle = 0 then
begin
log('UnLock with handle = 0');
exit;
end;
if not ReleaseMutex(Handle) then
raise Exception.Create('Mutex unlock error')
end;
end. |
unit uUnidadeModel;
interface
uses
uEnumerado, FireDAC.Comp.Client;
type
TUnidadeModel = class
private
FAcao: TAcao;
FCodigo: integer;
FNome: string;
FCep: string;
FCidade: string;
procedure SetCep(const Value: string);
procedure SetCidade(const Value: string);
procedure SetCodigo(const Value: integer);
procedure SetNome(const Value: string);
procedure SetAcao(const Value: TAcao);
public
function Obter: TFDQuery;
function Salvar: Boolean;
property Acao: TAcao read FAcao write SetAcao;
property Codigo: integer read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Cep: string read FCep write SetCep;
property Cidade: string read FCidade write SetCidade;
end;
implementation
{ TUnidadeModel }
uses uUnidadeDao;
function TUnidadeModel.Obter: TFDQuery;
var
Dao: TUnidadeDao;
begin
Dao := TUnidadeDao.Create;
try
Result := Dao.Obter;
finally
Dao.Free;
end;
end;
function TUnidadeModel.Salvar: Boolean;
var
Dao: TUnidadeDao;
begin
Result := False;
Dao := TUnidadeDao.Create;
try
case FAcao of
tacIncluir:
Result := Dao.Incluir(Self);
tacExcluir:
Result := Dao.Excluir(Self);
end;
finally
Dao.Free;
end;
end;
procedure TUnidadeModel.SetAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TUnidadeModel.SetCep(const Value: string);
begin
FCep := Value;
end;
procedure TUnidadeModel.SetCidade(const Value: string);
begin
FCidade := Value;
end;
procedure TUnidadeModel.SetCodigo(const Value: integer);
begin
FCodigo := Value;
end;
procedure TUnidadeModel.SetNome(const Value: string);
begin
FNome := Value;
end;
end.
|
unit NtUtils.Exec.Wmi;
interface
uses
NtUtils.Exec, NtUtils.Exceptions;
type
TExecCallWmi = class(TExecMethod)
class function Supports(Parameter: TExecParam): Boolean; override;
class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo):
TNtxStatus; override;
end;
implementation
uses
Winapi.ActiveX, System.SysUtils, Ntapi.ntpsapi, Ntapi.ntstatus,
Winapi.ProcessThreadsApi, NtUtils.Exec.Win32, NtUtils.Tokens.Impersonate,
NtUtils.Objects;
function GetWMIObject(const objectName: String; out Status: TNtxStatus):
IDispatch;
var
chEaten: Integer;
BindCtx: IBindCtx;
Moniker: IMoniker;
begin
Status.Location := 'CreateBindCtx';
Status.HResult := CreateBindCtx(0, BindCtx);
if not Status.IsSuccess then
Exit;
Status.Location := 'MkParseDisplayName';
Status.HResult := MkParseDisplayName(BindCtx, StringToOleStr(objectName),
chEaten, Moniker);
if not Status.IsSuccess then
Exit;
Status.Location := 'Moniker.BindToObject';
Status.HResult := Moniker.BindToObject(BindCtx, nil, IDispatch, Result);
end;
function PrepareProcessStartup(ParamSet: IExecProvider): OleVariant;
var
Status: TNtxStatus;
Flags: Cardinal;
begin
Result := GetWMIObject('winmgmts:Win32_ProcessStartup', Status);
Status.RaiseOnError;
// For some reason when specifing Win32_ProcessStartup.CreateFlags
// processes would not start without CREATE_BREAKAWAY_FROM_JOB.
Flags := CREATE_BREAKAWAY_FROM_JOB;
if ParamSet.Provides(ppCreateSuspended) and ParamSet.CreateSuspended then
Flags := Flags or CREATE_SUSPENDED;
Result.CreateFlags := Flags;
if ParamSet.Provides(ppShowWindowMode) then
Result.ShowWindow := ParamSet.ShowWindowMode;
end;
function PrepareCurrentDir(ParamSet: IExecProvider): String;
begin
if ParamSet.Provides(ppCurrentDirectory) then
Result := ParamSet.CurrentDircetory
else
Result := GetCurrentDir;
end;
{ TExecCallWmi }
class function TExecCallWmi.Execute(ParamSet: IExecProvider;
out Info: TProcessInfo): TNtxStatus;
var
objProcess: OleVariant;
hxOldToken: IHandle;
ProcessId: Integer;
begin
if ParamSet.Provides(ppToken) and Assigned(ParamSet.Token) then
begin
// Backup current impersonation
hxOldToken := NtxBackupImpersonation(NtCurrentThread);
// Impersonate the passed token
Result := NtxImpersonateAnyToken(ParamSet.Token.Handle);
if not Result.IsSuccess then
Exit;
end;
objProcess := GetWMIObject('winmgmts:Win32_Process', Result);
if Result.IsSuccess then
try
objProcess.Create(
PrepareCommandLine(ParamSet),
PrepareCurrentDir(ParamSet),
PrepareProcessStartup(ParamSet),
ProcessId
);
except
on E: Exception do
begin
Result.Location := 'winmgmts:Win32_Process.Create';
Result.Status := STATUS_UNSUCCESSFUL;
end;
end;
// Revert impersonation
if ParamSet.Provides(ppToken) then
NtxRestoreImpersonation(NtCurrentThread, hxOldToken);
// Only process ID is available to return to the caller
if Result.IsSuccess then
with Info do
begin
ClientId.UniqueProcess := ProcessId;
ClientId.UniqueThread := 0;
hxProcess := nil;
hxThread := nil;
end;
end;
class function TExecCallWmi.Supports(Parameter: TExecParam): Boolean;
begin
case Parameter of
ppParameters, ppCurrentDirectory, ppToken, ppCreateSuspended,
ppShowWindowMode:
Result := True;
else
Result := False;
end;
end;
end.
|
unit Connection.Base;
interface
uses Windows, GMConst, GMGlobals, ScktComp, StrUtils, StdResponce;
type
TExchangeType = (etSend, etRec, etSenRec);
TCheckCOMResult = (ccrBytes, ccrEmpty, ccrError);
BoolReturningFunc = function: bool of object;
TRequestUniversalXmlContent = (ruxcRequest, ruxcResponce);
TConnectionObjectBase = class
private
FNumAttempts: int;
FLogPrefix: string;
FCheckTerminated: BoolReturningFunc;
FExternalCheckGetAllData: BoolReturningFunc;
FInitEquipmentBeforeExchange: bool;
FWaitFirst, FWaitNext: int;
function GetParentTerminated: bool;
procedure SetWaitFirst(const Value: int);
procedure SetWaitWaitNext(const Value: int);
protected
procedure PrepareEquipment; virtual;
function ConnectionEquipmentInitialized(): bool; virtual;
function LogSignature: string; virtual; abstract;
procedure LogBufSend(AddCOMState: bool = false);
procedure LogBufRec(logEmpty: bool = false);
function MakeExchange(etAction: TExchangeType): TCheckCOMResult; virtual; abstract;
function InternalCheckGetAllData: bool; virtual;
function GetLastConnectionError: string; virtual;
function DefaultWaitFirst: int; virtual;
function DefaultWaitNext: int; virtual;
public
buffers: TTwoBuffers;
constructor Create(); virtual;
destructor Destroy; override;
function ExchangeBlockData(etAction: TExchangeType): TCheckCOMResult; virtual;
function RequestUniversal(const xml, login: string; bUseLogin: bool; contentType: TRequestUniversalXmlContent; var responce: IXMLGMIOResponceType): TCheckCOMResult;
procedure FreePort; virtual;
function CheckBufHeader(buf0, buf1, cnt: int): bool;
function CheckGetAllData: bool;
property WaitFirst: int read FWaitFirst write SetWaitFirst;
property WaitNext: int read FWaitNext write SetWaitWaitNext;
property NumAttempts: int read FNumAttempts write FNumAttempts;
property CheckTerminated: BoolReturningFunc read FCheckTerminated write FCheckTerminated;
property ExternalCheckGetAllData: BoolReturningFunc read FExternalCheckGetAllData write FExternalCheckGetAllData;
property ParentTerminated: bool read GetParentTerminated;
property LogPrefix: string read FLogPrefix write FLogPrefix;
property LastError: string read GetLastConnectionError;
property InitEquipmentBeforeExchange: bool read FInitEquipmentBeforeExchange write FInitEquipmentBeforeExchange;
end;
TConnectionObjectClass = class of TConnectionObjectBase;
implementation
{ TConnectionObjectBase }
uses ProgramLogFile, Math, EsLogging, System.SysUtils;
function TConnectionObjectBase.CheckBufHeader(buf0, buf1, cnt: int): bool;
begin
Result := (buffers.BufRec[0] = buf0) and (buffers.BufRec[1] = buf1) and (buffers.NumberOfBytesRead >= cnt);
end;
function TConnectionObjectBase.CheckGetAllData: bool;
begin
Result := InternalCheckGetAllData()
or (Assigned(FExternalCheckGetAllData) and FExternalCheckGetAllData());
end;
function TConnectionObjectBase.ConnectionEquipmentInitialized: bool;
begin
Result := true;
end;
constructor TConnectionObjectBase.Create;
begin
inherited;
FInitEquipmentBeforeExchange := true;
FWaitFirst := DefaultWaitFirst();
FWaitNext := DefaultWaitNext();
FNumAttempts := 1;
end;
destructor TConnectionObjectBase.Destroy;
begin
FreePort();
inherited;
end;
function TConnectionObjectBase.ExchangeBlockData(etAction: TExchangeType): TCheckCOMResult;
var Attempt: word;
begin
if FInitEquipmentBeforeExchange or not ConnectionEquipmentInitialized() then
PrepareEquipment();
//выход если нет инициализации
if not ConnectionEquipmentInitialized() then
begin
Result := ccrError;
end
else
begin
if etAction in [etSend, etSenRec] then
LogBufSend(true);
Attempt := 0;
repeat
Result := MakeExchange(etAction);
Inc(Attempt);
until (Result = ccrBytes)
or ((etAction = etSend) and (Result = ccrEmpty))
or (Attempt >= FNumAttempts);
if etAction = etSend then
Exit;
case Result of
ccrBytes:
LogBufRec();
ccrEmpty:
if etAction = etSenRec then
DefaultLogger.Debug(LogSignature() + ' - no answer, timeout = ' + IntToStr(WaitFirst));
ccrError:
DefaultLogger.Debug(LogSignature() + ' - error: ' + LastError);
end;
end;
end;
function TConnectionObjectBase.RequestUniversal(const xml, login: string; bUseLogin: bool; contentType: TRequestUniversalXmlContent; var responce: IXMLGMIOResponceType): TCheckCOMResult;
var len: int;
respXml: string;
buf0, buf1: byte;
begin
Result := ccrEmpty;
responce := nil;
buf0 := IfThen(contentType = ruxcResponce, 250, 255);
buf1 := IfThen(contentType = ruxcResponce, 10, 0);
if not buffers.RequestUniversal(xml, login, bUseLogin, buf0, buf1) then Exit;
Programlog.AddExchangeBuf('RequestUniversal', COM_LOG_OUT, xml);
Result := ExchangeBlockData(etSenRec);
if Result <> ccrBytes then Exit;
Result := ccrEmpty;
if not buffers.CheckBufRecHeader(buf0, buf1, 6) then Exit;
len := ReadUINT(buffers.BufRec, 2);
if buffers.NumberOfBytesRead < len + 6 then Exit;
try
respXml := string(DecompressBufferToString(buffers.BufRec, 6, len));
Programlog.AddExchangeBuf('RequestUniversal', COM_LOG_IN, respXml);
responce := LoadXMLData_GMIOResponce(respXml);
if responce <> nil then
Result := ccrBytes;
except
Result := ccrError;
end;
end;
function TConnectionObjectBase.DefaultWaitFirst: int;
begin
Result := CommonWaitFirst;
end;
function TConnectionObjectBase.DefaultWaitNext: int;
begin
Result := CommonWaitNext;
end;
procedure TConnectionObjectBase.SetWaitFirst(const Value: int);
begin
if Value > 0 then
FWaitFirst := Value
else
FWaitFirst := DefaultWaitFirst;
end;
procedure TConnectionObjectBase.SetWaitWaitNext(const Value: int);
begin
if Value > 0 then
FWaitNext := Value
else
FWaitNext := DefaultWaitNext;
end;
procedure TConnectionObjectBase.FreePort;
begin
end;
function TConnectionObjectBase.GetLastConnectionError: string;
begin
Result := ''
end;
function TConnectionObjectBase.GetParentTerminated: bool;
begin
Result := Assigned(FCheckTerminated) and FCheckTerminated();
end;
function TConnectionObjectBase.InternalCheckGetAllData: bool;
begin
Result := false;
end;
procedure TConnectionObjectBase.LogBufRec(logEmpty: bool);
begin
if logEmpty or (buffers.NumberOfBytesRead > 0) then
ProgramLog.AddExchangeBuf(LogSignature(), COM_LOG_IN, buffers.BufRec, buffers.NumberOfBytesRead);
end;
procedure TConnectionObjectBase.LogBufSend(AddCOMState: bool);
begin
ProgramLog.AddExchangeBuf(LogSignature() + IfThen(AddCOMState, IfThen(not ConnectionEquipmentInitialized(), '-')), COM_LOG_OUT, buffers.BufSend, buffers.LengthSend);
end;
procedure TConnectionObjectBase.PrepareEquipment;
begin
end;
end.
|
unit ClassAdresy;
interface
uses DBTables, StdCtrls;
type TAdresy = class
private
Query : TQuery;
procedure NacitajAdresy;
procedure OpravDiakritiku;
public
Adresy : array of array of string;
Active : integer;
constructor Create;
destructor Destroy; override;
procedure NapisAdresu( Memo : TMemo; Cislo : integer; SetActive : boolean );
end;
var Adresy : TAdresy;
implementation
uses Dialogs;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TAdresy.Create;
begin
inherited;
Query := TQuery.Create(nil);
with Query do
begin
Active := False;
DatabaseName := 'PcPrompt';
SQL.Add( 'SELECT (adresy.odber1), (adresy.odber2), (adresy.odber3) , (adresy.odber4)' );
SQL.Add( 'FROM adresy' );
SQL.Add( 'ORDER BY odber1' );
try
Active := True;
except
MessageDlg( 'Vyskytla sa chyba pri inicialzácii komunikácie s BDE' , mtError , [mbOk] , 0 );
exit;
end;
end;
NacitajAdresy;
OpravDiakritiku;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TAdresy.Destroy;
begin
Query.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Pomocné procedúry
//
//==============================================================================
//==============================================================================
procedure TAdresy.NacitajAdresy;
var I, J, Poc : integer;
begin
SetLength( Adresy , Query.RecordCount );
I := 0;
Poc := 0;
Query.First;
while not Query.EoF do
begin
SetLength( Adresy[I] , 4 );
for J := 0 to 3 do
if Query.Fields[J].AsString = '' then
begin
SetLength( Adresy[I] , J );
if J = 0 then
begin
Dec( I );
Inc( Poc );
end;
break;
end
else
Adresy[I][J] := Query.Fields[J].AsString;
Query.Next;
Inc( I );
end;
SetLength( Adresy , Query.RecordCount-Poc );
end;
procedure TAdresy.OpravDiakritiku;
const MJK : array[$00..$0F,$08..$0A] of char =
(('Č','É','á'),
('ü','ž','í'),
('é','Ž','ó'),
('ď','ô','ú'),
('ä','ö','ň'),
('Ď','Ó','Ň'),
('Ť','ů','Ů'),
('č','Ú','Ô'),
('ě','ý','š'),
('Ě','Ö','ř'),
('Ĺ','Ü','ŕ'),
('Í','Š','Ŕ'),
('ľ','Ľ',' '),
('ĺ','Ý','§'),
('Ä','Ř',' '),
('Á','ť',' '));
var I, J : integer;
procedure Oprav( var s : string );
var I : integer;
begin
for I := 1 to Length(s) do
if (Ord(s[I]) div $10 in [$08..$0A]) then
s[I] := MJK[ Ord(s[I]) mod $10 , Ord(s[I]) div $10 ];
end;
begin
for I := 0 to Length( Adresy )-1 do
for J := 0 to Length( Adresy[I] )-1 do
Oprav( Adresy[I][J] );
end;
//==============================================================================
//==============================================================================
//
// I N T E R F A C E
//
//==============================================================================
//==============================================================================
procedure TAdresy.NapisAdresu( Memo : TMemo; Cislo : integer; SetActive : boolean );
var I : integer;
begin
if Cislo < 0 then Cislo := Length( Adresy )-1;
if Cislo > Length( Adresy )-1 then Cislo := 0;
if SetActive then Active := Cislo;
Memo.Clear;
for I := 0 to Length( Adresy[Cislo] )-1 do
Memo.Lines.Add( Adresy[Cislo][I] );
end;
end.
|
unit UMinecraftLoader;
interface
uses WinApi.Windows, classes, UFileUtilities, SysUtils, ULauncherProfileLoader,
SuperObject;
type
TMinecraftLibrary = class
public
OldText, Formatted:string;
RuleCount:integer;
RulesAction:array[1..8]of string;
RulesOSName:array[1..8]of string;
RulesOSVersion:array[1..8]of string;
end;
TMinecraftUnPackingLibrary = class(TMinecraftLibrary)
public
NativeLinux, NativeWindows, NativeOSX: string;
ExtractExcludes: array[1..5]of string;
ExtractExcludeCount: Integer;
end;
TMinecraftLoader = class
public
MinecraftVersionText: string;
MinecraftVersionJson: ISuperObject;
profile: TProfile;
MinecraftPath: string;
ID, Time, ReleaseTime, MType, ProcessArguments, MinecraftArguments,
MainClass, JavaPath, Session: string;
UseJava: Boolean;
PlayerName, AuthSession, VersionName, GameDir, GameAssets, LaunchMode: string;
MinimumLauncherVersion, MaxMemory: Integer;
UnpackingLibraries: array[1..100] of TMinecraftUnPackingLibrary;
Libraries:array[1..100] of TMinecraftLibrary;
LibraryCount, UnpackingLibraryCount: Integer;
// MinecraftPath, MinecraftVersionText, JavaPath, LaunchMode, PlayerName, MaxMemory
constructor Create
(mcp, mvt, jp, lm, pn, ss:string; mm:Integer; pro: TProfile; usejava: Boolean);
function GenerateLaunchString:string;
procedure FormatLibrary
(name:string; var res:TMinecraftLibrary; Rules:ISuperObject);
procedure FormatUnpackingLibrary
(name:string; var res:TMinecraftUnpackingLibrary; Rules, Natives:ISuperObject);
private
protected
end;
implementation
function IntegerToString(i:Integer): string;
begin
str(i, Result);
end;
function SplitString(const Source,ch:String):TStringList;
var
temp:String;
i:Integer;
begin
SplitString:=TStringList.Create;
//如果是空自符串则返回空列表
if Source='' then exit;
temp:=Source;
i:=pos(ch,Source);
while i<>0 do
begin
SplitString.add(copy(temp,0,i-1));
Delete(temp,1,i);
i:=pos(ch,temp);
end;
SplitString.add(temp);
end;
constructor TMinecraftLoader.Create
(mcp, mvt, jp, lm, pn, ss: string; mm:Integer; pro: TProfile; usejava: Boolean);
var lib: TSuperArray; i: Integer; tmp: ISuperObject;
begin
Self.UseJava := usejava;
Self.MinecraftPath := mcp;
Self.MaxMemory := mm;
Self.JavaPath := jp;
Self.UseJava := usejava;
Self.LaunchMode := lm;
Self.PlayerName := pn;
Self.Session := ss;
Self.GameDir := mcp;
Self.GameAssets := mcp + '\assets';
Self.MinecraftVersionText := mvt;
Self.MinecraftVersionJson := SO(mvt);
Self.ID := Self.MinecraftVersionJSON.S['id'];
Self.VersionName := ID;
Self.Time := Self.MinecraftVersionJson.S['time'];
Self.ReleaseTime := Self.MinecraftVersionJson.S['releaseTime'];
Self.MType := Self.MinecraftVersionJson.S['type'];
Self.ProcessArguments := Self.MinecraftVersionJson.S['processArguments'];
Self.MinecraftArguments := Self.MinecraftVersionJson.S['minecraftArguments'];
Self.MinimumLauncherVersion := Self.MinecraftVersionJson.I['minimumLauncherVersion'];
Self.MainClass := Self.MinecraftVersionJson.S['mainClass'];
if pro = nil then
begin
Self.profile := TProfile.Create(ID);
Self.profile.HasGameDir := false;
Self.profile.HasJavaDir := false;
Self.profile.HasJavaArgs := false;
Self.profile.HasResolution := false;
Self.profile.HasAllowedReleaseTypes := false;
Self.profile.HasLastVersionId := false;
end
else
begin
Self.profile := pro;
if profile.HasGameDir then
GameDir := profile.gameDir;
if profile.HasJavaDir then
JavaPath := profile.javaDir;
end;
lib := Self.MinecraftVersionJson.A['libraries'];
LibraryCount := 0;
for i := 0 to lib.Length - 1 do
begin
tmp := lib[i];
if(SOFindField(tmp, 'natives') <> nil)then
begin
inc(UnpackingLibraryCount);
UnpackingLibraries[UnpackingLibraryCount] :=
TMinecraftUnpackingLibrary.Create;
FormatUnpackingLibrary(tmp.S['name'],
UnpackingLibraries[UnpackingLibraryCount],
SOFindField(tmp, 'rules'), SOFindField(tmp, 'natives'));
end else
begin
inc(LibraryCount);
Libraries[LibraryCount] := TMinecraftLibrary.Create;
FormatLibrary(tmp.S['name'],
Libraries[LibraryCount],
SOFindField(tmp, 'rules'));
end;
end;
end;
procedure TMinecraftLoader.FormatLibrary
(name:string; var res:TMinecraftLibrary; Rules:ISuperObject);
var s:TStringList; str:string; j: Integer;
rule, os: ISuperObject; rulesArr: TSuperArray;
begin
res.OldText := name;
s := SplitString(res.OldText, ':');
str := s[0];
for j := 1 to length(str) do
if str[j] = '.' then
str[j] := '\';
str := str + '\' + s[1] + '\' + s[2] + '\' + s[1] + '-' + s[2] + '.jar';
res.Formatted := str;
if(rules <> nil) then
begin
rulesArr := rules.AsArray;
res.RuleCount := rulesArr.Length;
for j := 0 to rulesArr.Length - 1 do
begin
rule := rulesArr[j];
res.RulesAction[j+1] := rule.S['action'];
if SOFindField(rule, 'os') <> nil then
begin
os := rule['os'];
res.RulesOSName[j+1] := os.S['name'];
res.RulesOSVersion[j+1] := os.S['version'];
end
else
begin
res.RulesOSName[j+1] := '';
res.RulesOSVersion[j+1] := '';
end;
end;
end;
end;
procedure TMinecraftLoader.FormatUnpackingLibrary
(name:string; var res: TMinecraftUnpackingLibrary; Rules, Natives:ISuperObject);
var s:TStringList; str:string; j: Integer;
rule, os, nat: ISuperObject; rulesArr: TSuperArray;
begin
res.OldText := name;
s := SplitString(res.OldText, ':');
str := s[0];
for j := 1 to length(str) do
if str[j] = '.' then
str[j] := '\';
if Natives<>nil then
begin
nat := SOFindField(Natives, 'windows');
if nat <> nil then
res.NativeWindows := nat.AsString
else
res.NativeWindows := 'natives-windows';
nat := SOFindField(Natives, 'linux');
if nat <> nil then
res.NativeLinux := nat.AsString
else
res.NativeLinux := 'natives-linux';
if nat <> nil then
res.NativeOSX := nat.AsString
else
res.NativeOSX := 'natives-osx';
end;
str := str + '\' + s[1] + '\' + s[2] + '\' + s[1] + '-' + s[2] + '-' + res.NativeWindows + '.jar';
res.Formatted := str;
if(rules <> nil) then
begin
rulesArr := rules.AsArray;
res.RuleCount := rulesArr.Length;
for j := 0 to rulesArr.Length - 1 do
begin
rule := rulesArr[j];
res.RulesAction[j+1] := rule.S['action'];
if SOFindField(rule, 'os') <> nil then
begin
os := rule['os'];
res.RulesOSName[j+1] := os.S['name'];
res.RulesOSVersion[j+1] := os.S['version'];
end
else
begin
res.RulesOSName[j+1] := '';
res.RulesOSVersion[j+1] := '';
end;
end;
end;
end;
function TMinecraftLoader.GenerateLaunchString;
var res, t, pa:string;
i, j: Integer;
flag: Boolean;
begin
res := '"';
pa := Trim(JavaPath);
if UseJava then
if length(pa) = 0 then
res := res + 'java.exe'
else
res := res + TFileUtilities.AddSeparator(pa) + 'java.exe'
else
if length(pa) = 0 then
res := res + 'javaw.exe'
else
res := res + TFileUtilities.AddSeparator(pa) + 'javaw.exe';
res := res + '" ';
if profile.HasJavaArgs then
begin
if pos(profile.javaArgs, '-d') = 0 then
res := res + LaunchMode + ' ';
if pos(profile.javaArgs, '-Xmx') = 0 then
res := res + '-Xmx' + IntegerToString(MaxMemory) + 'm ';
res := res + profile.javaArgs + ' ';
end
else
begin
res := res + LaunchMode + ' -Xincgc -Xmx';
res := res + IntegerToString(MaxMemory) + 'm ';
end;
res := res + '-Dfml.ignoreInvalidMinecraftCertificates=true -Dfml.ignorePatchDiscrepancies=true ';
res := res + '-Djava.library.path="';
res := res + TFileUtilities.AddSeparator(MinecraftPath) + 'versions\' + ID + '\' + ID + '-natives"' + ' -cp ';
for i := 1 to LibraryCount do
begin
flag := false;
if(Libraries[i].RuleCount = 0)then
flag := true;
for j := 1 to Libraries[i].RuleCount do
if Libraries[i].RulesAction[j] = 'disallow' then
begin
if (Libraries[i].RulesOSName[j] = '')
or(Trim(LowerCase(Libraries[i].RulesOSName[j])) = 'windows') then
begin
flag := false;
break;
end;
end
else
begin
if (Libraries[i].RulesOSName[j] = '')
or(Trim(LowerCase(Libraries[i].RulesOSName[j])) = 'windows') then
begin
flag := true;
break;
end;
end;
if flag then
res := res + '"' + TFileUtilities.AddSeparator(MinecraftPath) + 'libraries\' + Libraries[i].Formatted + '";';
end;
res := res + '"' + MinecraftPath + '\versions\' + ID + '\' + ID + '.jar" ';
res := res + MainClass + ' ';
t := MinecraftArguments;
t := StringReplace(t, '${auth_player_name}', PlayerName, [rfReplaceAll]);
t := StringReplace(t, '${auth_session}', Session, [rfReplaceAll]);
t := StringReplace(t, '${version_name}', VersionName, [rfReplaceAll]);
t := StringReplace(t, '${game_directory}', '"' + GameDir + '"', [rfReplaceAll]);
t := StringReplace(t, '${game_assets}', '"' + GameAssets + '"', [rfReplaceAll]);
if profile.HasResolution then
t := t + ' --height ' + IntegerToString(profile.Height) + ' --width ' + IntegerToString(profile.Width);
res := res + t;
//--username ' + PlayerName + ' --version ' + VersionName + ' --gameDir ' + GameDir + ' --assetsDir ' + GameAssets;
exit(res);
end;
end.
|
unit MD5.Message;
interface
uses
MD5.Globals,
MD5.Utils;
type
{ TScreenMessage }
TScreenMessageShowMode = (smNORMAL, smFORCE, smDONE);
TScreenMessageParameters = array[0..10] of Cardinal; // Параметры статистики
/// <summary>
/// Ссылка на процедуру, которая умеет
/// показывать статистическую информацию
/// </summary>
TScreenMessageProc = reference to procedure(var P: TScreenMessageParameters);
TScreenMessage = class
private
LineSize: Integer;
Interval: Cardinal; // update interval in ms
Proc: TScreenMessageProc;
Timer: TTimer;
FParams: TScreenMessageParameters;
public
constructor Create(Proc: TScreenMessageProc; Interval: Cardinal); overload;
destructor Destroy; override;
procedure Show(Mode: TScreenMessageShowMode); overload;
procedure Show(Mode: TScreenMessageShowMode; P: array of Cardinal); overload;
procedure Clear;
function Passed: Cardinal;
//
procedure SetParams(Index: Integer; Value: Cardinal);
function GetParams(Index: Integer): Cardinal;
property Params[Index: Integer]: Cardinal read GetParams write SetParams; default;
end;
implementation
{=== TScreenMessages ===}
constructor TScreenMessage.Create(Proc: TScreenMessageProc; Interval: Cardinal);
var
i: Integer;
begin
inherited Create;
// Init vars
Self.Interval := Interval;
Self.Proc := Proc;
Self.Timer := TTimer.Create;
LineSize := 0;
for i := Low(FParams) to High(FParams) do FParams[i] := 0;
end;
destructor TScreenMessage.Destroy;
begin
Timer.Free;
inherited;
end;
function TScreenMessage.GetParams(Index: Integer): Cardinal;
begin
if (Index >= Low(FParams)) AND (Index <= High(FParams)) then Result := FParams[Index]
else Result := 0;
end;
function TScreenMessage.Passed: Cardinal;
begin
Result := Timer.Passed;
end;
procedure TScreenMessage.Clear;
begin
Console.UpdateClear(LineSize);
end;
procedure TScreenMessage.SetParams(Index: Integer; Value: Cardinal);
begin
if (Index >= Low(FParams)) AND (Index <= High(FParams)) then FParams[Index] := Value;
end;
procedure TScreenMessage.Show(Mode: TScreenMessageShowMode; P: array of Cardinal);
var
i: Integer;
begin
for i := Low(P) to High(P) do Params[i] := P[i];
Show(Mode);
end;
procedure TScreenMessage.Show(Mode: TScreenMessageShowMode);
begin
case Mode of
smDONE: Clear;
smFORCE:
begin
Console.UpdateBegin(LineSize);
if Assigned(Proc) then Proc(FParams);
Console.UpdateEnd(LineSize);
end;
smNORMAL:
if Timer.CheckInterval(Interval) then
begin
Console.UpdateBegin(LineSize);
if Assigned(Proc) then Proc(FParams);
Console.UpdateEnd(LineSize);
end;
else Clear;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSServerExpertsTemplateProperties;
interface
uses InetExpertsTemplateProperties;
const
// Template file sections.
// These are typically set in designer. View Creator datamodule as text.
sDataSnapConsoleSource = 'DataSnapConsoleSource';
sDataSnapServiceSource = 'DataSnapServiceSource';
sDataSnapVCLSource = 'DataSnapVCLSource';
sDataSnapModuleSource = 'DataSnapModuleSource';
sDataSnapModuleIntf = 'DataSnapModuleIntf';
sDataSnapModuleDFMSource = 'DataSnapModuleDFMSource';
sDataSnapVCLFormSource = 'DataSnapVCLFormSource';
sDataSnapVCLFormIntf = 'DataSnapVCLFormIntf';
sDSServerModuleTemplateIntf = 'DSServerModuleTemplateIntf';
sDSServerModuleTemplate = 'DSServerModuleTemplate';
sDataSnapServerMethodsClassTemplateIntf = 'DataSnapServerMethodsClassTemplateIntf';
sDataSnapServerMethodsClassTemplate = 'DataSnapServerMethodsClassTemplate';
sDataSnapWebModuleIntf = 'DataSnapWebModuleIntf';
sDataSnapWebModuleSource = 'DataSnapWebModuleSource';
sDataSnapWebModuleDFMSource = 'DataSnapWebModuleDFMSource';
// Template options
sServerMethodsClass_1 = 'ServerMethodsClass';
sAuthorization_2 = 'Authorization';
sAuthentication_3 = 'Authentication';
sServiceMethods_4 = 'ServiceMethods';
sRunDSServer_5 = 'RunDSServer';
sTCPIPProtocol_6 = 'TCPIPProtocol';
sHTTPProtocol_7 = 'HTTPProtocol';
sIncludeSampleMethods_8 = 'IncludeSampleMethods';
sIncludeSampleWebFiles_9 = 'IncludeSampleWebFiles';
sDataSnapREST_10 = 'DataSnapREST';
sMethodInfoOn_11 = 'MethodInfoOn';
sIncludeEncryptionFilters_12 = 'IncludeEncryptionFilters';
sIncludeFilters_13 = 'IncludeFilters';
sIncludeCompressionFilter_14 = 'IncludeCompressionFilter';
sHTTPSProtocol_15 = 'HTTPSProtocol';
sDataSnapConnectors_16 = 'IncludeDataSnapConnectors';
sIncludeJavaScriptFiles_17 = 'IncludeJavaScriptFiles';
sServerModule_18 = 'IncludeServerModule';
sRESTDispatcher_19 = 'RESTDispatcher';
// Template properties
sHTTPPort_1 = 'HTTPPort';
sTCPIPPort_2 = 'TCPIPPort';
sServerMethodsUnitName_3 = 'ServerMethodsUnitName';
sServerMethodsClassName_4 = 'ServerMethodsClassName';
sKeyFilePassword_5 = InetExpertsTemplateProperties.sKeyFilePassword; // 'KeyFilePassword';
sRootCertFile_6 = InetExpertsTemplateProperties.sRootCertFile; // 'RootCertFile';
sCertFile_7 = InetExpertsTemplateProperties.sCertFile; // 'CertFile';
sKeyFile_8 = InetExpertsTemplateProperties.sKeyFile; // 'KeyFile';
sHTTPSPort_9 = 'HTTPSPort';
sServerModuleUnitName_10 = 'ServerModuleUnitName';
sFrameWorkType = 'FrameWorkType';
sTrue = 'TRUE';
sFalse = 'FALSE';
sDSServerConstUnitName = 'ServerConstUnitName';
sDSServerConstSource = 'ServerConstSource';
implementation
end.
|
{
*
* Copyright (C) 2005-2009 UDW-SOFTWARE <http://udw.altervista.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
}
unit Spec;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TSpec1 = class(TForm)
NameApp: TLabeledEdit;
OkBtn: TBitBtn;
AnnullBtn: TBitBtn;
OpenDialog1: TOpenDialog;
DisableBox: TCheckBox;
ErrWin: TLabeledEdit;
Procedure HandleClose(arg:string;arg2:string;row:integer);
procedure OkBtnClick(Sender: TObject);
procedure OpenDialog1CanClose(Sender: TObject; var CanClose: Boolean);
procedure AnnullBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
SelRow:integer;
end;
var
Spec1: TSpec1;
implementation
uses Restart,engine;
{$R *.dfm}
Procedure TSpec1.HandleClose(arg:string;arg2:string;row:integer);
var I:integer;
begin
if row=-1 then
begin
inc(Form1.ProcCount);
inc(Form1.APPNum);
I:=Length(Reg)+1;
SetLength(Reg,I);
SetLength(Form1.Tempo2,I);
I:=High(Reg);
Init(Reg,I);
Reg[I].APPName:=Arg;
Reg[I].APPPath:=expandfilename(OpenDialog1.FileName);
Reg[I].blocca:=DisableBox.Checked;
Reg[I].added:=true;
Reg[I].ErrWindowName:=arg2;
Form1.Timers.RowCount:=Form1.Timers.RowCount+1;//:=Form1.ProcCount+1;
Form1.Timers.Rows[I+1].Clear;
Form1.Timers.cols[GrdName].Add(Arg);
Form1.Timers.Cols[GrdPath].Add(expandfilename(OpenDialog1.FileName));
Form1.Timers.cols[GrdID].Add('NEWAPP'+inttostr(Form1.ProcCount));
Form1.Timers.cols[GrdErrWin].Add(arg2);
Form1.Timers.row:=I+1; //anticrash per l'handlename
Form1.CheckEnabling;
// ora se tutto e pronto e se i timers erano spenti li avvia
end
else
begin
Reg[row-1].APPName:=arg;
Reg[row-1].ErrWindowName:=arg2;
Form1.Timers.Cells[grdname,row]:=arg;
Form1.Timers.Cells[grderrwin,row]:=arg2;
end;
Form1.HandleName(arg,Form1.Timers.row);
Form1.ChangeStopBtn(Form1.Timers.row); // dopo l'handle
Form1.SaveBtn.Enabled:=true;
Form1.RestoreBtn.Enabled:=true;
Spec1.Close;
end;
procedure TSpec1.OkBtnClick(Sender: TObject);
begin
if DisableBox.visible then
HandleClose(NameApp.Text,ErrWin.text,-1)
else
HandleClose(NameApp.Text,ErrWin.text,SelRow);
end;
procedure TSpec1.OpenDialog1CanClose(Sender: TObject;
var CanClose: Boolean);
begin
Spec1.Show;
end;
procedure TSpec1.AnnullBtnClick(Sender: TObject);
begin
Spec1.close;
end;
procedure TSpec1.FormShow(Sender: TObject);
begin
form1.Enabled:=false;
if DisableBox.visible then
begin
NameApp.Text:='';
ErrWin.Text:='';
end
else
begin
NameApp.Text:=Form1.Timers.Cells[grdname,SelRow];
ErrWin.Text:=Form1.Timers.Cells[grderrwin,SelRow];;
end;
end;
procedure TSpec1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
form1.Enabled:=true;
end;
end.
|
unit ComboBoxImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB;
type
TComboBoxX = class(TActiveXControl, IComboBoxX)
private
{ Private declarations }
FDelphiControl: TComboBox;
FEvents: IComboBoxXEvents;
procedure ChangeEvent(Sender: TObject);
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure DropDownEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
procedure MeasureItemEvent(Control: TWinControl; Index: Integer;
var Height: Integer);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_CharCase: TxEditCharCase; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_DropDownCount: Integer; safecall;
function Get_DroppedDown: WordBool; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_ImeMode: TxImeMode; safecall;
function Get_ImeName: WideString; safecall;
function Get_ItemHeight: Integer; safecall;
function Get_ItemIndex: Integer; safecall;
function Get_Items: IStrings; safecall;
function Get_MaxLength: Integer; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_SelLength: Integer; safecall;
function Get_SelStart: Integer; safecall;
function Get_SelText: WideString; safecall;
function Get_Sorted: WordBool; safecall;
function Get_Style: TxComboBoxStyle; safecall;
function Get_Text: WideString; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure Clear; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure SelectAll; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_CharCase(Value: TxEditCharCase); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_DropDownCount(Value: Integer); safecall;
procedure Set_DroppedDown(Value: WordBool); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_ImeMode(Value: TxImeMode); safecall;
procedure Set_ImeName(const Value: WideString); safecall;
procedure Set_ItemHeight(Value: Integer); safecall;
procedure Set_ItemIndex(Value: Integer); safecall;
procedure Set_Items(const Value: IStrings); safecall;
procedure Set_MaxLength(Value: Integer); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_SelLength(Value: Integer); safecall;
procedure Set_SelStart(Value: Integer); safecall;
procedure Set_SelText(const Value: WideString); safecall;
procedure Set_Sorted(Value: WordBool); safecall;
procedure Set_Style(Value: TxComboBoxStyle); safecall;
procedure Set_Text(const Value: WideString); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About7;
{ TComboBoxX }
procedure TComboBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_ComboBoxXPage); }
end;
procedure TComboBoxX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IComboBoxXEvents;
end;
procedure TComboBoxX.InitializeControl;
begin
FDelphiControl := Control as TComboBox;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnDropDown := DropDownEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
FDelphiControl.OnMeasureItem := MeasureItemEvent;
end;
function TComboBoxX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TComboBoxX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TComboBoxX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TComboBoxX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TComboBoxX.Get_CharCase: TxEditCharCase;
begin
Result := Ord(FDelphiControl.CharCase);
end;
function TComboBoxX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TComboBoxX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TComboBoxX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TComboBoxX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TComboBoxX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TComboBoxX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TComboBoxX.Get_DropDownCount: Integer;
begin
Result := FDelphiControl.DropDownCount;
end;
function TComboBoxX.Get_DroppedDown: WordBool;
begin
Result := FDelphiControl.DroppedDown;
end;
function TComboBoxX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TComboBoxX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TComboBoxX.Get_ImeMode: TxImeMode;
begin
Result := Ord(FDelphiControl.ImeMode);
end;
function TComboBoxX.Get_ImeName: WideString;
begin
Result := WideString(FDelphiControl.ImeName);
end;
function TComboBoxX.Get_ItemHeight: Integer;
begin
Result := FDelphiControl.ItemHeight;
end;
function TComboBoxX.Get_ItemIndex: Integer;
begin
Result := FDelphiControl.ItemIndex;
end;
function TComboBoxX.Get_Items: IStrings;
begin
GetOleStrings(FDelphiControl.Items, Result);
end;
function TComboBoxX.Get_MaxLength: Integer;
begin
Result := FDelphiControl.MaxLength;
end;
function TComboBoxX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TComboBoxX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TComboBoxX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TComboBoxX.Get_SelLength: Integer;
begin
Result := FDelphiControl.SelLength;
end;
function TComboBoxX.Get_SelStart: Integer;
begin
Result := FDelphiControl.SelStart;
end;
function TComboBoxX.Get_SelText: WideString;
begin
Result := WideString(FDelphiControl.SelText);
end;
function TComboBoxX.Get_Sorted: WordBool;
begin
Result := FDelphiControl.Sorted;
end;
function TComboBoxX.Get_Style: TxComboBoxStyle;
begin
Result := Ord(FDelphiControl.Style);
end;
function TComboBoxX.Get_Text: WideString;
begin
Result := WideString(FDelphiControl.Text);
end;
function TComboBoxX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TComboBoxX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TComboBoxX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TComboBoxX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TComboBoxX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TComboBoxX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TComboBoxX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TComboBoxX.AboutBox;
begin
ShowComboBoxXAbout;
end;
procedure TComboBoxX.Clear;
begin
FDelphiControl.Clear;
end;
procedure TComboBoxX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TComboBoxX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TComboBoxX.SelectAll;
begin
FDelphiControl.SelectAll;
end;
procedure TComboBoxX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TComboBoxX.Set_CharCase(Value: TxEditCharCase);
begin
FDelphiControl.CharCase := TEditCharCase(Value);
end;
procedure TComboBoxX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TComboBoxX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TComboBoxX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TComboBoxX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TComboBoxX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TComboBoxX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TComboBoxX.Set_DropDownCount(Value: Integer);
begin
FDelphiControl.DropDownCount := Value;
end;
procedure TComboBoxX.Set_DroppedDown(Value: WordBool);
begin
FDelphiControl.DroppedDown := Value;
end;
procedure TComboBoxX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TComboBoxX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TComboBoxX.Set_ImeMode(Value: TxImeMode);
begin
FDelphiControl.ImeMode := TImeMode(Value);
end;
procedure TComboBoxX.Set_ImeName(const Value: WideString);
begin
FDelphiControl.ImeName := TImeName(Value);
end;
procedure TComboBoxX.Set_ItemHeight(Value: Integer);
begin
FDelphiControl.ItemHeight := Value;
end;
procedure TComboBoxX.Set_ItemIndex(Value: Integer);
begin
FDelphiControl.ItemIndex := Value;
end;
procedure TComboBoxX.Set_Items(const Value: IStrings);
begin
SetOleStrings(FDelphiControl.Items, Value);
end;
procedure TComboBoxX.Set_MaxLength(Value: Integer);
begin
FDelphiControl.MaxLength := Value;
end;
procedure TComboBoxX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TComboBoxX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TComboBoxX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TComboBoxX.Set_SelLength(Value: Integer);
begin
FDelphiControl.SelLength := Value;
end;
procedure TComboBoxX.Set_SelStart(Value: Integer);
begin
FDelphiControl.SelStart := Value;
end;
procedure TComboBoxX.Set_SelText(const Value: WideString);
begin
FDelphiControl.SelText := String(Value);
end;
procedure TComboBoxX.Set_Sorted(Value: WordBool);
begin
FDelphiControl.Sorted := Value;
end;
procedure TComboBoxX.Set_Style(Value: TxComboBoxStyle);
begin
FDelphiControl.Style := TComboBoxStyle(Value);
end;
procedure TComboBoxX.Set_Text(const Value: WideString);
begin
FDelphiControl.Text := TCaption(Value);
end;
procedure TComboBoxX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TComboBoxX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TComboBoxX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TComboBoxX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TComboBoxX.DropDownEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDropDown;
end;
procedure TComboBoxX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
procedure TComboBoxX.MeasureItemEvent(Control: TWinControl; Index: Integer;
var Height: Integer);
var
TempHeight: Integer;
begin
TempHeight := Integer(Height);
if FEvents <> nil then FEvents.OnMeasureItem(Index, TempHeight);
Height := Integer(TempHeight);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TComboBoxX,
TComboBox,
Class_ComboBoxX,
7,
'{695CDB07-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit Unit1;
interface
uses
{$IFDEF TESTING}
TestFramework,
{$ENDIF}
Classes, SysUtils;
type
TMyObject = class(TObject)
public
procedure DoSomething;
end;
{$IFDEF TESTING}
TTestMyObject = class(TTestCase)
private
FMyObject: TMyObject;
public
procedure Setup; override;
procedure TearDown; override;
published
procedure testMyObject;
end;
{$ENDIF}
implementation
{ TMyObject }
procedure TMyObject.DoSomething;
begin
// do something
end;
{$IFDEF TESTING}
function Suite: ITestSuite;
begin
Result := TTestSuite.Create('Test MyObject');
Result.AddTest(TTestMyObject.Create('testMyObject'));
end;
{ TTestMyObject }
procedure TTestMyObject.Setup;
begin
FMyObject := TMyObject.Create;
end;
procedure TTestMyObject.TearDown;
begin
FMyObject.Free;
end;
procedure TTestMyObject.testMyObject;
begin
try
FMyObject.DoSomething;
except
check(false);
end;
end;
{$ENDIF}
initialization
{$IFDEF TESTING}
RegisterTest('', TTestMyObject.Suite);
{$ENDIF}
end.
|
unit Soccer.Voting.RulePreferenceList;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
Soccer.Voting.AbstractRule;
type
TSoccerVotingRulePreferenceList = class
private
FList: TList<ISoccerVotingRule>;
FPreferenceFile: string;
function IsBiggerThan(ARule: ISoccerVotingRule;
ALessPreferred: ISoccerVotingRule): boolean;
function GetItems(i: integer): ISoccerVotingRule;
function GetCount: integer;
public
constructor Create(APreferenceFileName: string);
procedure Add(ARule: ISoccerVotingRule);
property Items[i: integer]: ISoccerVotingRule read GetItems;
property Count: integer read GetCount;
destructor Destroy; override;
end;
function GetPreferenceFilePath: string;
implementation
function GetPreferenceFilePath: string;
begin
{$IFDEF DEBUG}
Result := '..\..\..\..\deploy\data\rules.soccfg';
{$ELSE}
Result := 'rules.soccfg';
{$ENDIF}
end;
{ TSoccerVotingRulePreferenceList }
procedure TSoccerVotingRulePreferenceList.Add(ARule: ISoccerVotingRule);
var
i: integer;
begin
for i := 0 to FList.Count - 1 do
begin
if IsBiggerThan(ARule, FList[i]) then
begin
FList.Insert(i, ARule);
exit;
end;
end;
FList.Add(ARule);
end;
constructor TSoccerVotingRulePreferenceList.Create(APreferenceFileName: string);
begin
FList := TList<ISoccerVotingRule>.Create;
FPreferenceFile := APreferenceFileName;
end;
destructor TSoccerVotingRulePreferenceList.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
function TSoccerVotingRulePreferenceList.GetCount: integer;
begin
Result := FList.Count;
end;
function TSoccerVotingRulePreferenceList.GetItems(i: integer)
: ISoccerVotingRule;
begin
Result := FList[i];
end;
function TSoccerVotingRulePreferenceList.IsBiggerThan(ARule, ALessPreferred
: ISoccerVotingRule): boolean;
var
LStr: string;
LStringList: TStringList;
begin
Result := false;
LStringList := TStringList.Create;
try
LStringList.LoadFromFile(FPreferenceFile);
for LStr in LStringList do
begin
if ARule.GetName = LStr.Trim then
begin
Result := true;
exit;
end;
if ALessPreferred.GetName = LStr.Trim then
exit;
end;
finally
FreeAndNil(LStringList);
end;
end;
end.
|
unit uConexao;
interface
uses
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.MySQLDef,
FireDAC.Phys.FB, System.SysUtils, FireDAC.DApt, FireDAC.VCLUI.Wait;
type
TConexao = class
class var FInstancia: TConexao;
private
FConexao : TFDConnection;
public
class function GetInstancia():TConexao;
function ConectaBaseDeDados(pServidor, pDatabase, pUsuario : string ) : Boolean;
function CriaQuery: TFDQuery;
function CriaConexao : TFDConnection;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TConexao }
function TConexao.ConectaBaseDeDados(pServidor, pDatabase, pUsuario : string ) : Boolean;
begin
FConexao.Params.Values['DriverID'] := 'MSSQL';
FConexao.Params.values ['Server'] := pServidor;
FConexao.Params.Values['Database'] := pDatabase;
FConexao.Params.Values['User_name'] := pUsuario;
FConexao.Params.Values['Password'] := '';
FConexao.Connected := True;
Result := FConexao.Connected;
end;
constructor TConexao.Create;
begin
FConexao := TFDConnection.Create(nil);
FInstancia := nil;
end;
function TConexao.CriaConexao: TFDConnection;
begin
Result := FConexao;
end;
function TConexao.CriaQuery: TFDQuery;
var
Query: TFDQuery;
begin
Query := TFDQuery.Create(nil);
Query.Connection := FConexao;
Result := Query;
end;
destructor TConexao.Destroy;
begin
FConexao.Free;
FInstancia.Free;
inherited;
end;
class function TConexao.GetInstancia: TConexao;
begin
if not Assigned(FInstancia) then
FInstancia := TConexao.Create;
Result := FInstancia;
end;
end.
|
unit ANU_CBC;
(*************************************************************************
DESCRIPTION : Anubis (tweaked) CBC functions
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.3
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 05.08.08 W.Ehrhardt Initial version analog AES_CBC
0.11 24.11.08 we Uses BTypes
0.12 01.08.10 we Longint ILen in ANU_CBC_En/Decrypt
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, ANU_Base;
{$ifdef CONST}
function ANU_CBC_Init_Encr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if invalid key size, encrypt IV}
{$ifdef DLL} stdcall; {$endif}
function ANU_CBC_Init_Decr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if invalid key size, encrypt IV}
{$ifdef DLL} stdcall; {$endif}
{$else}
function ANU_CBC_Init_Encr(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_CBC_Init_Decr(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if invalid key size, encrypt IV}
{$endif}
function ANU_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
{$ifdef DLL} stdcall; {$endif}
function ANU_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
{$ifdef CONST}
function ANU_CBC_Init_Encr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
{$else}
function ANU_CBC_Init_Encr(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer;
{$endif}
{-Anubis key expansion, error if invalid key size, encrypt IV}
begin
{-Anubis key expansion, error if invalid key size}
ANU_CBC_Init_Encr := ANU_Init_Encr(Key, KeyBits, ctx);
ctx.IV := IV;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function ANU_CBC_Init_Decr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
{$else}
function ANU_CBC_Init_Decr(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer;
{$endif}
{-Anubis key expansion, error if invalid key size, encrypt IV}
begin
{-Anubis key expansion, error if invalid key size}
ANU_CBC_Init_Decr := ANU_Init_Decr(Key, KeyBits, ctx);
ctx.IV := IV;
end;
{---------------------------------------------------------------------------}
function ANU_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
var
i,n: longint;
m: word;
begin
ANU_CBC_Encrypt := 0;
if ILen<0 then ILen := 0;
if ctx.Decrypt<>0 then begin
ANU_CBC_Encrypt := ANU_Err_Invalid_Mode;
exit;
end;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
ANU_CBC_Encrypt := ANU_Err_NIL_Pointer;
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
ANU_CBC_Encrypt := ANU_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
n := ILen div ANUBLKSIZE; {Full blocks}
m := ILen mod ANUBLKSIZE; {Remaining bytes in short block}
if m<>0 then begin
if n=0 then begin
ANU_CBC_Encrypt := ANU_Err_Invalid_Length;
exit;
end;
dec(n); {CTS: special treatment of last TWO blocks}
end;
{Short block must be last, no more processing allowed}
if ctx.Flag and 1 <> 0 then begin
ANU_CBC_Encrypt := ANU_Err_Data_After_Short_Block;
exit;
end;
with ctx do begin
for i:=1 to n do begin
{ct[i] = encr(ct[i-1] xor pt[i]), cf. [3] 6.2}
ANU_XorBlock(PANUBlock(ptp)^, IV, IV);
ANU_Encrypt(ctx, IV, IV);
PANUBlock(ctp)^ := IV;
inc(Ptr2Inc(ptp),ANUBLKSIZE);
inc(Ptr2Inc(ctp),ANUBLKSIZE);
end;
if m<>0 then begin
{Cipher text stealing}
ANU_XorBlock(PANUBlock(ptp)^, IV, IV);
ANU_Encrypt(ctx, IV, IV);
buf := IV;
inc(Ptr2Inc(ptp),ANUBLKSIZE);
for i:=0 to m-1 do IV[i] := IV[i] xor PANUBlock(ptp)^[i];
ANU_Encrypt(ctx, IV, PANUBlock(ctp)^);
inc(Ptr2Inc(ctp),ANUBLKSIZE);
move(buf,PANUBlock(ctp)^,m);
{Set short block flag}
Flag := Flag or 1;
end;
end;
end;
{---------------------------------------------------------------------------}
function ANU_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
var
i,n: longint;
m: word;
tmp: TANUBlock;
begin
ANU_CBC_Decrypt := 0;
if ILen<0 then ILen := 0;
if ctx.Decrypt=0 then begin
ANU_CBC_Decrypt := ANU_Err_Invalid_Mode;
exit;
end;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
ANU_CBC_Decrypt := ANU_Err_NIL_Pointer;
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
ANU_CBC_Decrypt := ANU_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
n := ILen div ANUBLKSIZE; {Full blocks}
m := ILen mod ANUBLKSIZE; {Remaining bytes in short block}
if m<>0 then begin
if n=0 then begin
ANU_CBC_Decrypt := ANU_Err_Invalid_Length;
exit;
end;
dec(n); {CTS: special treatment of last TWO blocks}
end;
{Short block must be last, no more processing allowed}
if ctx.Flag and 1 <> 0 then begin
ANU_CBC_Decrypt := ANU_Err_Data_After_Short_Block;
exit;
end;
with ctx do begin
for i:=1 to n do begin
{pt[i] = decr(ct[i]) xor ct[i-1]), cf. [3] 6.2}
buf := IV;
IV := PANUBlock(ctp)^;
ANU_Decrypt(ctx, IV, PANUBlock(ptp)^);
ANU_XorBlock(PANUBlock(ptp)^, buf, PANUBlock(ptp)^);
inc(Ptr2Inc(ptp),ANUBLKSIZE);
inc(Ptr2Inc(ctp),ANUBLKSIZE);
end;
if m<>0 then begin
{Cipher text stealing, L=ILen (Schneier's n)}
buf := IV; {C(L-2)}
ANU_Decrypt(ctx, PANUBlock(ctp)^, IV);
inc(Ptr2Inc(ctp),ANUBLKSIZE);
fillchar(tmp,sizeof(tmp),0);
move(PANUBlock(ctp)^,tmp,m); {c[L]|0}
ANU_XorBlock(tmp,IV,IV);
tmp := IV;
move(PANUBlock(ctp)^,tmp,m); {c[L]| C'}
ANU_Decrypt(ctx,tmp,tmp);
ANU_XorBlock(tmp, buf, PANUBlock(ptp)^);
inc(Ptr2Inc(ptp),ANUBLKSIZE);
move(IV,PANUBlock(ptp)^,m);
{Set short block flag}
Flag := Flag or 1;
end;
end;
end;
end.
|
unit BrickCamp.Common.JsonContract;
// this too via Sir Rufo.
interface
type
TJsonContractBase = class abstract
protected
procedure DisposeObjectArray<T: class>( var arr: TArray<T> );
class function _FromJson( const aJsonStr: string ): TObject; overload;
class procedure _FromJson( aResult: TObject; const aJsonStr: string ); overload;
public
function ToJson( ): string; virtual;
function ToKey( ): string; virtual;abstract;
end;
implementation
uses
System.Sysutils,
System.JSON,
REST.JSON;
{ TJsonContractBase }
procedure TJsonContractBase.DisposeObjectArray<T>( var arr: TArray<T> );
var
I: Integer;
begin
for I := low( arr ) to high( arr ) do
FreeAndNil( arr[ I ] );
SetLength( arr, 0 );
end;
class function TJsonContractBase._FromJson( const aJsonStr: string ): TObject;
begin
Result := Self.Create;
try
_FromJson( Result, aJsonStr );
except
Result.Free;
raise;
end;
end;
class procedure TJsonContractBase._FromJson( aResult: TObject; const aJsonStr: string );
var
lJson: TJsonObject;
begin
lJson := TJsonObject.ParseJSONValue( aJsonStr ) as TJsonObject;
try
TJson.JsonToObject( aResult, lJson );
finally
lJson.Free;
end;
end;
function TJsonContractBase.ToJson: string;
begin
Result := TJson.ObjectToJsonString( Self );
end;
end.
|
unit gsPLScript;
interface
uses
Windows, Classes, SysUtils
, swiprolog
;
type
TgsPL = class(TObject)
public
constructor Create;
destructor Destroy; override;
end;
TgsPLScript = class(TgsPL)
private
FInput: String;
FOutput: String;
FReturnValue: String;
procedure SetInput(const AInput: String);
function GetInput(): String;
function GetOutput(): String;
function GetReturnValue(): String;
public
constructor Create;
destructor Destroy; override;
function Call(): Boolean;
property Input: String read GetInput write SetInput;
property Output: String read GetOutput;
property ReturnValue: String read GetReturnValue;
end;
EgsPLScriptException = class(Exception);
implementation
constructor TgsPL.Create;
var
PL: Integer;
argc: Integer;
argv: array of PChar;
begin
inherited;
argc := 10;
SetLength(argv, argc+1);
argv[0] := PChar('libswipl.dll');
argv[1] := PChar('--quiet');
argv[2] := PChar('--nodebug');
argv[3] := PChar('--nosignals');
argv[4] := PChar('-x');
argv[5] := PChar('gd_pl_state');
argv[6] := PChar('-g');
argv[7] := PChar('true');
argv[8] := PChar('-t');
argv[9] := PChar('true');
argv[10] := nil;
PL := PL_is_initialised(argc, argv);
if PL <> 0 then
Exit;
PL := PL_initialise(argc, argv);
if PL = 0 then
raise EgsPLScriptException.Create('SWI-Prolog initialisation failed!');
end;
destructor TgsPL.Destroy;
var
PL: Integer;
begin
PL := PL_cleanup(0);
if PL = 0 then
raise EgsPLScriptException.Create('SWI-Prolog cleanup failed!');
inherited;
end;
constructor TgsPLScript.Create;
begin
inherited;
end;
destructor TgsPLScript.Destroy;
begin
inherited;
end;
function TgsPLScript.Call(): Boolean;
var
a1, a2, a3, e: term_t;
p: predicate_t;
q: qid_t;
S2, S3: PChar;
L2, L3: Cardinal;
begin
FOutput := ''; FReturnValue := '';
a1 := PL_new_term_refs(3);
a2 := a1 + 1; a3 := a1 + 2;
PL_put_string_chars(a1, PChar(FInput));
p := PL_predicate(PChar('pl_run'), 3, PChar('user'));
q := PL_open_query(PChar('user'), PL_Q_CATCH_EXCEPTION, p, a1);
if q <> 0 then
begin
if PL_next_solution(q) <> 0 then
begin
if PL_get_string(a2, S2, L2) <> 0 then
begin
SetLength(FOutput, L2);
FOutput := String(S2);
end;
if PL_get_string(a3, S3, L3) <> 0 then
begin
SetLength(FReturnValue, L3);
FReturnValue := String(S3);
end;
end
else
begin
e := PL_exception(q);
if Integer(e) = 0 then
FReturnValue := 'call failed'
else
if PL_get_atom_chars(e, S3) <> 0 then
begin
FReturnValue := String(S3);
end
else
FReturnValue := 'call exception failed'
end;
end
else
begin
raise EgsPLScriptException.Create('Not enough space on the environment stack!')
end;
Result := FReturnValue = 'true'
end;
procedure TgsPLScript.SetInput(const AInput: String);
begin
if FInput <> AInput then
FInput := AInput;
end;
function TgsPLScript.GetInput(): String;
begin
Result := FInput;
end;
function TgsPLScript.GetOutput(): String;
begin
Result := FOutput;
end;
function TgsPLScript.GetReturnValue(): String;
begin
Result := FReturnValue;
end;
end.
|
unit UnitFormChart;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VclTee.TeeGDIPlus, VclTee.TeEngine,
Vcl.ExtCtrls, VclTee.TeeProcs, VclTee.Chart, VclTee.Series, Vcl.Grids,
UnitApiClient, Vcl.ComCtrls, Vcl.ToolWin, System.ImageList, Vcl.ImgList,
myutils, Vcl.Menus;
type
TFormChart = class(TForm)
Chart1: TChart;
StringGrid1: TStringGrid;
ImageList1: TImageList;
Panel5: TPanel;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton3: TToolButton;
Panel11: TPanel;
GridPanel1: TGridPanel;
PanelX: TPanel;
PanelY: TPanel;
ToolButton4: TToolButton;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
TimerRepaint: TTimer;
ToolButton5: TToolButton;
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Chart1AfterDraw(Sender: TObject);
procedure Chart1UndoZoom(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure ToolButton4Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure Chart1BeforeDrawChart(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure ToolButton3Click(Sender: TObject);
procedure TimerRepaintTimer(Sender: TObject);
procedure StringGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ToolButton5Click(Sender: TObject);
private
{ Private declarations }
function SeriesOfColRow(ACol, ARow: Integer): TFastLineSeries;
procedure ShowCurrentScaleValues;
procedure optimizeChart;
public
{ Public declarations }
procedure SetupStringGrid;
procedure ChangeAxisOrder(c: TWinControl; WheelDelta: Integer);
end;
var
FormChart: TFormChart;
implementation
{$R *.dfm}
uses System.types, dateutils, teechartutils, apitypes, math, stringgridutils,
UnitFormCurrentParty, UnitAToolMainForm, logfile, UnitFormWorkLogRecords,
Thrift.Collections, unitappini;
const
col_count = 6;
procedure TFormChart.optimizeChart;
var
i: Integer;
ser: TFastLineSeries;
begin
// When using only a single thread, disable locking:
Chart1.Canvas.ReferenceCanvas.Pen.OwnerCriticalSection := nil;
Chart1.ClipPoints := False;
Chart1.Title.Visible := False;
Chart1.Legend.Visible := False;
Chart1.View3D := False;
Chart1.Axes.FastCalc := True;
Chart1.Axes.Bottom.Increment:=DateTimeStep[dtOneSecond];
Chart1.Axes.Bottom.DateTimeFormat:='dd/mm HH:nn:ss';
for i := 0 to Chart1.AxesList.Count - 1 do
begin
Chart1.Axes[i].Axis.Width := 1;
Chart1.Axes[i].RoundFirstLabel := False;
end;
for i := 0 to Chart1.SeriesCount - 1 do
begin
ser := Chart1.Series[i] as TFastLineSeries;
ser.LinePen.OwnerCriticalSection := nil;
ser.AutoRepaint := False;
ser.FastPen := True;
ser.DrawAllPoints := False;
ser.LinePen.Width := 2;
end;
end;
procedure TFormChart.Chart1AfterDraw(Sender: TObject);
var
i, xPos, yPos, a, b: Integer;
ser: TChartSeries;
marker_place: boolean;
marker_rects: array of TRect;
marker_rect, r2: TRect;
marker_text: string;
function pow2(X: Extended): Extended;
begin
exit(IntPower(X, 2));
end;
begin
ShowCurrentScaleValues;
if (not ToolButton1.Down) and (not ToolButton3.Down) then
exit;
Chart1.Canvas.Pen.Style := psSolid;
Chart1.Canvas.Pen.Width := 1;
Chart1.Canvas.Pen.Mode := pmCopy;
Chart1.Canvas.Font.Size := 9;
for ser in Chart1.SeriesList do
begin
if not ser.Active then
Continue;
Chart1.Canvas.Pen.Color := ser.Color;
if ser.Tag > 0 then
Chart1.Canvas.Brush.Color := ser.Color;
for i := ser.FirstValueIndex to ser.LastValueIndex do
begin
try
xPos := ser.CalcXPos(i);
yPos := ser.CalcYPos(i);
except
Continue;
end;
if not PtInRect(Chart1.ChartRect, Point(xPos, yPos)) then
Continue;
if (i > ser.FirstValueIndex) AND (i < ser.LastValueIndex) AND
(pow2(xPos - a) + pow2(yPos - b) < pow2(7)) then
Continue;
if ser.Tag > 0 then
begin
Chart1.Canvas.Ellipse(xPos - 5, yPos - 5, xPos + 5, yPos + 5);
end
else
begin
// Parameters are
// X-Coord, Y-Coord, X-Radius, Y-Radius, Start Angle, End Angle, Hole%
Chart1.Canvas.Donut(xPos, yPos, 3, 3, -1, 361, 100);
end;
a := xPos;
b := yPos;
marker_text := Format('%s • %g',
[formatDatetime('h:n:s.zzz', ser.XValues[i]), ser.YValues[i]]);
with marker_rect do
begin
Left := xPos;
Top := yPos - Canvas.TextHeight(marker_text);
Right := xPos + Canvas.TextWidth(marker_text);
Bottom := yPos;
end;
marker_place := ToolButton3.Down;
for r2 in marker_rects do
begin
if System.types.IntersectRect(marker_rect, r2) then
begin
marker_place := False;
break;
end;
end;
if marker_place then
begin
Chart1.Canvas.Font.Color := ser.Color;
Chart1.Canvas.TextOut(marker_rect.Left, marker_rect.Top,
marker_text);
SetLength(marker_rects, length(marker_rects) + 1);
marker_rects[length(marker_rects) - 1] := marker_rect;
end;
end;
end;
// ser := ActiveSeries;
// if not Assigned(ser) then
// exit;
end;
procedure TFormChart.Chart1BeforeDrawChart(Sender: TObject);
begin
try
optimizeChart;
except
on e: exception do
LogfileWriteException(e);
end;
end;
procedure TFormChart.Chart1UndoZoom(Sender: TObject);
begin
Chart1.BottomAxis.Automatic := True;
Chart1.LeftAxis.Automatic := True;
end;
procedure TFormChart.FormCreate(Sender: TObject);
begin
teeChart_setOptimizedChart(Chart1);
teeChart_setOptimizedAxis(Chart1.BottomAxis);
teeChart_setOptimizedAxis(Chart1.LeftAxis);
end;
procedure TFormChart.N1Click(Sender: TObject);
var
r: IDeleteChartPointsRequest;
ser: TFastLineSeries;
i, n: Integer;
label
GotoLabel;
begin
r := TDeleteChartPointsRequestImpl.Create;
r.Chart := Caption;
r.TimeFrom := DateTimeToUnixMillis(Chart1.BottomAxis.Minimum);
r.TimeTo := DateTimeToUnixMillis(Chart1.BottomAxis.Maximum);
r.ValueFrom := Chart1.LeftAxis.Minimum;
r.ValueTo := Chart1.LeftAxis.Maximum;
ProductsClient.deleteChartPoints(r);
GotoLabel:
for i := 0 to Chart1.SeriesCount - 1 do
begin
ser := Chart1.Series[i] as TFastLineSeries;
for n := 0 to ser.Count - 1 do
begin
if (ser.XValue[n] >= Chart1.BottomAxis.Minimum) AND
(ser.XValue[n] <= Chart1.BottomAxis.Maximum) AND
(ser.YValue[n] >= Chart1.LeftAxis.Minimum) AND
(ser.YValue[n] <= Chart1.LeftAxis.Maximum) then
begin
ser.Delete(n);
goto GotoLabel;
end;
end;
end;
Chart1.UndoZoom;
end;
procedure TFormChart.ShowCurrentScaleValues;
var
s, s1, s2, s3: string;
v: double;
procedure ShowAxisOrders(ax: TChartAxis; pn: TPanel; prefix: string);
begin
with ax do
begin
if Maximum = Minimum then
pn.Caption := prefix + ': нет значений'
else
pn.Caption := prefix + ': ' + FormatFloat('#0.0##',
Maximum - Minimum);
end;
end;
begin
with Chart1.Axes.Bottom do
begin
v := Maximum - Minimum;
s1 := TimetoStr(Minimum);
s2 := TimetoStr(Maximum);
s3 := TimetoStr(v);
if v = 0 then
s := 'нет значений'
else if v < IncSecond(0, 1) then
s := inttostr(MilliSecondsBetween(Maximum, Minimum)) + 'мс'
else if v < IncMinute(0, 1) then
s := inttostr(SecondsBetween(Maximum, Minimum)) + ' c'
else if v < Inchour(0, 1) then
s := inttostr(minutesBetween(Maximum, Minimum)) + ' минут'
else if v < Incday(0, 1) then
s := inttostr(hoursBetween(Maximum, Minimum)) + ' часов'
else
s := inttostr(daysBetween(Maximum, Minimum)) + ' дней';
end;
PanelX.Caption := Format('X: %s', [s]);
ShowAxisOrders(Chart1.Axes.Left, PanelY, 'Y');
end;
procedure TFormChart.ChangeAxisOrder(c: TWinControl; WheelDelta: Integer);
var
a: TChartAxis;
step: double;
begin
if c = PanelY then
a := Chart1.LeftAxis
else if c = PanelX then
a := Chart1.BottomAxis
else
exit;
if a.Minimum = a.Maximum then
exit;
step := (a.Maximum - a.Minimum) * 0.03;
if WheelDelta < 0 then
step := step * -1;
if a.Minimum - step >= a.Maximum + step then
exit;
a.SetMinMax(a.Minimum - step, a.Maximum + step);
end;
function TFormChart.SeriesOfColRow(ACol, ARow: Integer): TFastLineSeries;
var
n: Integer;
begin
n := ARow * col_count + ACol;
if n >= Chart1.SeriesCount then
exit(nil);
exit(Chart1.Series[n] AS TFastLineSeries);
end;
procedure TFormChart.SetupStringGrid;
begin
with StringGrid1 do
begin
ColCount := col_count;
RowCount := Chart1.SeriesCount div col_count + 1;
end;
StringGrid_Redraw(StringGrid1);
end;
procedure TFormChart.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
cnv: TCanvas;
ser: TFastLineSeries;
// pv: TProductVar;
AText: string;
d: Integer;
brushColor: TColor;
r: TRect;
// p: IProduct;
s: string;
function newRect(l, t, r, b: Integer): TRect;
begin
Result.Left := l;
Result.Top := t;
Result.Right := r;
Result.Bottom := b;
end;
begin
AText := '';
cnv := StringGrid1.Canvas;
cnv.Font.Assign(StringGrid1.Font);
cnv.Brush.Color := clWhite;
if gdSelected in State then
cnv.Brush.Color := clGradientInactiveCaption;
cnv.FillRect(Rect);
ser := SeriesOfColRow(ACol, ARow);
if not Assigned(ser) then
begin
exit;
end;
// pv := FormCurrentParty.GetSeriesInfo(ser);
// p := FormCurrentParty.GetProductByID(pv.ProductID);
StringGrid_DrawCheckBoxCell(StringGrid1, ACol, ARow, Rect, State,
ser.Active);
r := Rect;
r.Left := r.Left + 20;
r.Right := r.Left + 30;
d := round(r.Top + r.Height / 2);
brushColor := cnv.Brush.Color;
cnv.Brush.Color := ser.SeriesColor;
cnv.FillRect(newRect(r.Left + 5, d - 2, r.Right - 5, d + 2));
cnv.Brush.Color := brushColor;
r.Left := r.Right;
r.Right := Rect.Right;
StringGrid_DrawCellText(StringGrid1, ACol, ARow, r, taLeftJustify,
ser.Title);
// r.Left := r.Right + 1;
// r.Right := Rect.Right;
// StringGrid_DrawCellText(StringGrid1, ACol, ARow, r, taLeftJustify,
// Format('%s',[p.Device]));
end;
procedure TFormChart.StringGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
ACol, ARow: Integer;
ser: TFastLineSeries;
prod_param: IProductParamSeries;
Rect: TRect;
sel: TGridRect;
AActive: boolean;
begin
if not((Key = VK_SPACE) or (Key = VK_ESCAPE)) then
exit;
sel := StringGrid1.Selection;
AActive := False;
for ACol := sel.Left to sel.Right do
for ARow := sel.Top to sel.Bottom do
begin
ser := SeriesOfColRow(ACol, ARow);
if not Assigned(ser) then
Continue;
if ser.Active then
begin
AActive := True;
break;
end;
end;
for ACol := sel.Left to sel.Right do
for ARow := sel.Top to sel.Bottom do
begin
ser := SeriesOfColRow(ACol, ARow);
if not Assigned(ser) then
Continue;
ser.Active := not AActive;
with StringGrid1 do
Cells[ACol, ARow] := Cells[ACol, ARow];
end;
end;
procedure TFormChart.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
ACol, ARow: Integer;
ser: TFastLineSeries;
prod_param: IProductParamSeries;
Rect: TRect;
begin
if not(ssLeft in Shift) then
exit;
with StringGrid1 do
begin
MouseToCell(X, Y, ACol, ARow);
Rect := StringGrid1.CellRect(ACol, ARow);
ser := SeriesOfColRow(ACol, ARow);
if not Assigned(ser) then
exit;
if X < Rect.Left + 30 then
begin
ser.Active := not ser.Active;
Cells[ACol, ARow] := Cells[ACol, ARow];
with FormCurrentParty.GetSeriesInfo(ser) do
prod_param := ProductsClient.GetProductParamSeries(ProductID,
ParamAddr);
prod_param.SeriesActive := ser.Active;
ProductsClient.setProductParamSeries(prod_param);
end;
end;
end;
procedure TFormChart.TimerRepaintTimer(Sender: TObject);
begin
Chart1.Repaint;
TimerRepaint.Enabled := False;
end;
procedure TFormChart.ToolButton1Click(Sender: TObject);
begin
if ToolButton1.Down then
ToolButton3.Down := False;
Chart1.Repaint;
end;
procedure TFormChart.ToolButton3Click(Sender: TObject);
begin
if ToolButton3.Down then
ToolButton1.Down := False;
Chart1.Repaint;
end;
procedure TFormChart.ToolButton4Click(Sender: TObject);
var
pnt: TPoint;
begin
if GetCursorPos(pnt) then
PopupMenu1.Popup(pnt.X, pnt.Y);
end;
procedure TFormChart.ToolButton5Click(Sender: TObject);
var
dlg: TOpenDialog;
TimeFrom, TimeTo: TTimeUnixMillis;
AFileName: string;
begin
dlg := TSaveDialog.Create(nil);
dlg.Filter := 'Страницы excel (*.xlsx)|*.xlsx|Файлы csv (*.csv)|*.csv';
dlg.InitialDir := AppIni.ReadString('AToolMainForm',
'charts_files_dialog_idir', ExtractFileDir(Application.ExeName));
if not dlg.Execute() then
exit;
if dlg.FilterIndex = 1 then
AFileName := ChangeFileExt(dlg.FileName, '.xlsx')
else if dlg.FilterIndex = 2 then
AFileName := ChangeFileExt(dlg.FileName, '.csv')
else
raise exception.Create('unexpected: ' + inttostr(dlg.FilterIndex));
try
TimeFrom := DateTimeToUnixMillis(Chart1.BottomAxis.Minimum);
TimeTo := DateTimeToUnixMillis(Chart1.BottomAxis.Maximum);
CurrFileClient.exportChart(AFileName, TimeFrom, TimeTo, Caption);
finally
AppIni.WriteString('AToolMainForm', 'charts_files_dialog_idir',
ExtractFilePath(AFileName));
dlg.Free;
end;
end;
procedure TFormChart.N2Click(Sender: TObject);
var
i: Integer;
pv: TProductVar;
prod_param: IProductParamSeries;
begin
for i := 0 to Chart1.SeriesCount - 1 do
begin
pv := FormCurrentParty.GetSeriesInfo
(Chart1.Series[i] as TFastLineSeries);
prod_param := TProductParamSeriesImpl.Create;
prod_param.ProductID := pv.ProductID;
prod_param.ParamAddr := pv.ParamAddr;
prod_param.Chart := '';
ProductsClient.setProductParamSeries(prod_param);
end;
FormCurrentParty.upload;
end;
procedure TFormChart.N3Click(Sender: TObject);
var
newName: string;
n: Integer;
begin
if not InputQuery('Переименовать график ' + Caption, 'Новое имя графика:',
newName) then
exit;
CurrFileClient.renameChart(Caption, newName);
n := AToolMainForm.PageControlMain.ActivePageIndex;
FormCurrentParty.upload;
if (n > -1) AND (n < AToolMainForm.PageControlMain.PageCount) then
AToolMainForm.PageControlMain.ActivePageIndex := n;
end;
end.
|
unit HSLUtils;
interface
uses
Windows, Graphics,System.Classes;
// Получить цвет, темнее исходного на Percent процентов
function DarkerColor(const Color : TColor; Percent : Integer) : TColor;
// Получить цвет, светлее исходного на Percent процентов
function LighterColor(const Color : TColor; Percent : Integer) : TColor;
// Смешать несколько цветов и получить средний
function MixColors(Colors: TStringList{array of TColor}): TColor;
// Сделать цвет черно-белым
function GrayColor(Color : TColor) : TColor;
implementation
uses
System.SysUtils;
function DarkerColor(const Color: TColor; Percent: Integer): TColor;
var
R, G, B: Byte;
begin
Result := Color;
if Percent <= 0 then
Exit;
if Percent > 100 then
Percent := 100;
Result := ColorToRGB(Color);
R := GetRValue(Result);
G := GetGValue(Result);
B := GetBValue(Result);
R := R - R * Percent div 100;
G := G - G * Percent div 100;
B := B - B * Percent div 100;
Result := RGB(R, G, B);
end;
function LighterColor(const Color: TColor; Percent: Integer): TColor;
var
R, G, B: Byte;
begin
Result := Color;
if Percent <= 0 then
Exit;
if Percent > 100 then
Percent := 100;
Result := ColorToRGB(Result);
R := GetRValue(Result);
G := GetGValue(Result);
B := GetBValue(Result);
R := R + (255 - R) * Percent div 100;
G := G + (255 - G) * Percent div 100;
B := B + (255 - B) * Percent div 100;
Result := RGB(R, G, B);
end;
function MixColors(Colors: TStringList{array of TColor}): TColor;
var
R, G, B: Integer;
i: Integer;
L: Integer;
begin
R := 0;
G := 0;
B := 0;
for i := 0 to Colors.Count-1 do
begin
Result := ColorToRGB( TColor(StrToInt(Colors[i])) );
R := R + GetRValue(Result);
G := G + GetGValue(Result);
B := B + GetBValue(Result);
end;
L := Colors.Count;
Result := RGB(R div L, G div L, B div L);
end;
function GrayColor(Color: TColor): TColor;
var
Gray: Byte;
begin
Result := ColorToRGB(Color);
Gray := (GetRValue(Result) + GetGValue(Result) + GetBValue(Result)) div 3;
Result := RGB(Gray, Gray, Gray);
end;
end.
|
unit U.Converters;
interface
procedure RegisterStringToListBoxConverter;
procedure RegisterStringToBrushColorConverter;
implementation
uses
System.Bindings.Outputs,
System.Rtti,
Vcl.StdCtrls,
Vcl.Graphics,
System.SysUtils;
procedure RegisterStringToListBoxConverter;
var
LConverterDescription: TConverterDescription;
begin
// Create the converter description object
LConverterDescription := TConverterDescription.Create(
procedure(const InValue: TValue; var OutValue: TValue)
var
LListBox: TListBox;
begin
LListBox := OutValue.AsObject as TListBox;
if LListBox.ItemIndex > -1 then
LListBox.Items[LListBox.ItemIndex] := InValue.AsString;
end,
'StringToListBox', // Converter ID
'StringToListBox', // Converter name
'U.Converters', // Unit name
True, // Enabled
'StringToListBox', // Converter long description (hint)
nil // Converter platform (TComponent=VCL; TFMXComponent=FMX; nil=both)
);
// Register in the converter factory
TValueRefConverterFactory.RegisterConversion(
TypeInfo(String),
TypeInfo(TListBox),
LConverterDescription
);
end;
procedure RegisterStringToBrushColorConverter;
var
LConverterDescription: TConverterDescription;
begin
// Create the converter description object
LConverterDescription := TConverterDescription.Create(
procedure(const InValue: TValue; var OutValue: TValue)
var
LBrush: TBrush;
LColorStr: String;
LColor: TColor;
begin
// In & out value extraction
LBrush := OutValue.AsObject as TBrush;
LColorStr := LowerCase(InValue.AsString.Trim);
// Color recognition
if LColorStr = 'red' then
LColor := clRed
else if LColorStr = 'green' then
LColor := clGreen
else if LColorStr = 'lime' then
LColor := clLime
else if LColorStr = 'blue' then
LColor := clBlue
else if LColorStr = 'yellow' then
LColor := clYellow
else if LColorStr = 'gray' then
LColor := clGray
else if LColorStr = 'black' then
LColor := clblack
else
LColor := clWhite;
// Set the color
LBrush.Color := LColor;
end,
'StringToBrushColor', // Converter ID
'StringToBrushColor', // Converter name
'U.Converters', // Unit name
True, // Enabled
'StringToBrushColor', // Converter long description (hint)
nil // Converter platform (TComponent=VCL; TFMXComponent=FMX; nil=both)
);
// Register in the converter factory
TValueRefConverterFactory.RegisterConversion(
TypeInfo(String),
TypeInfo(TBrush),
LConverterDescription
);
end;
end.
|
unit string_seg_count;
interface
implementation
type Integer = Int32;
function Pos(const SubStr, Str: string; Offset: Int32): Int32;
var
I, LIterCnt, L, J: Int32;
begin
L := Length(SubStr);
LIterCnt := Length(Str) - L - Offset;
if (Offset >= 0) and (LIterCnt >= 0) and (L > 0) then
begin
for I := 0 to LIterCnt do
begin
J := 0;
while (J >= 0) and (J < L) do
begin
if Str[Offset + I + J] = SubStr[J] then
Inc(J)
else
J := -1;
end;
if J >= L then
Exit(Offset + I);
end;
end;
Result := -1;
end;
function StringSegCount(const Str: string; const Separator: string): Integer;
var
SPos, StrLen: integer;
begin
SPos := -1;
Result := 0;
StrLen := Length(Str);
repeat
Inc(Result);
Inc(SPos);
SPos := Pos(separator, Str, SPos);
until (SPos = -1) or (SPos >= StrLen);
end;
var G: Int32;
procedure Test;
begin
G := StringSegCount('111;222', ';');
end;
initialization
Test();
finalization
Assert(G = 2);
end. |
{-------------------------------------------------------------------------------
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: SynUniHighlighter.pas, released 2003-01
All Rights Reserved.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
{
@abstract(Provides UltraEdit highlighting schemes import)
@authors(Fantasist [walking_in_the_sky@yahoo.com], Vit [nevzorov@yahoo.com],
Vitalik [vetal-x@mail.ru], Quadr0 [quadr02005@yahoo.com])
@created(2003)
@lastmod(2005-05-17)
}
unit SynUniImportUltraEdit;
interface
uses
Classes,
Graphics,
SysUtils,
SynUniImport,
SynUniClasses,
SynUniRules;
type
{ Base class for UltraEdit highlighting schemes import }
TSynUniImportUltraEdit = class(TSynUniImport)
FileList: TStringList;
FilePos: integer;
FileName: string;
{ Constructor of TSynUniImportUltraEdit }
constructor Create();
{ Destructor of TSynUniImportUltraEdit }
destructor Destroy();
function Import(Rules: TSynRange; Info: TSynInfo): boolean;
{ Import from stream }
function LoadFromStream(Stream: TStream): boolean;
{ Import from file }
function LoadFromFile(FileName: string): boolean;
end;
implementation
constructor TSynUniImportUltraEdit.Create();
begin
FileList := TStringList.Create;
end;
destructor TSynUniImportUltraEdit.Destroy();
begin
FileList.Free;
end;
function TSynUniImportUltraEdit.Import(Rules: TSynRange; Info: TSynInfo): boolean;
var
i, j, qn1, qn2, bn1, bn2, cur, Nc: integer;
qc1, qc2: char;
word, buf: string;
Cnames: array [1..8] of string;
Created: array [1..8] of integer;
isLoading: boolean;
keyword: TSynKeyList;
const
colors: array [1..8] of TColor =
(clBlue, clRed, $0080FF, clGreen, clMaroon, clBlue, clBlue, clBlue);
badsymb: array [0..8] of char = ('\', '/', ':', '*', '?', '"', '<', '>', '|');
LINE_COMMENT = 1;
BLOCK_COMMENT = 2;
STRING_CHARS = 3;
LINE_COMM_NUM = 4;
SINGLE_WORD = 5;
WHOLE_STRING = 6;
ESCAPE_CHAR = 7;
function GetAttribute(Key: string; Style: integer): boolean;
var pos_start, space1_pos, space2_pos, len: integer;
begin
Result := False;
if pos(key, buf) = 0 then Exit;
pos_start := pos(key, buf) + length(key);
if (Style = LINE_COMMENT) or (Style = BLOCK_COMMENT) or (Style = STRING_CHARS) then begin
if Style = LINE_COMMENT then len := 5 else
if Style = BLOCK_COMMENT then len := 19 else
if Style = STRING_CHARS then len := 2 else len := 5;
word := copy(buf, pos_start, len);
space1_pos := pos(' ', word);
if space1_pos > 0 then
if space1_pos = 1 then begin
space2_pos := pos(' ', copy(word, 2, len-1));
if space2_pos > 0 then
word := copy(word, 1, space2_pos);
end else
word := copy(word, 1, space1_pos-1)
end
else if Style = LINE_COMM_NUM then begin
len := StrToInt(buf[pos_start]);
word := copy(buf, pos_start+1, len);
space1_pos := pos(' ', word);
if space1_pos > 0 then
end
else if Style = WHOLE_STRING then
word := copy(buf, pos_start, length(buf) - pos_start + 1)
else if Style = ESCAPE_CHAR then
word := buf[pos_start]
else if Style = SINGLE_WORD then ;
if word <> '' then Result := True;
end;
function GetToken: string;
begin
cur := pos(' ', buf);
if cur > 0 then begin
Result := copy(buf, 1, cur-1);
buf := copy(buf, cur+1, length(buf)-cur);
end else begin
Result := buf; buf := '';
end;
end;
begin
if not Assigned(FileList) then
if FileName <> '' then begin
//'File was loaded.'
FileList := TStringList.Create;
FileList.LoadFromFile(FileName);
FileName := FileName;
FilePos := 0;
end
else begin
//'File was not assigned and not loaded. Exiting...'
Result := False;
Exit;
end
else begin
if (FileName = FileName) and (FilePos >= FileList.Count-1) or (FileName = '') then begin
//'Variables are deleted. Exiting...'
if Assigned(FileList) then begin
FileList.Free;
FileList := nil;
end;
FileName := '';
FilePos := 0;
Result := False;
Exit;
end;
if FileName <> FileName then begin
//'New File was loaded.'
FileList.LoadFromFile(FileName);
FileName := FileName;
FilePos := 0;
end;
end;
Rules.Clear;
isLoading := False;
qc1 := #0; qc2 := #0; Nc := 0; qn1 := -1; qn2 := -1;
for i := FilePos to FileList.Count-1 do begin
buf := FileList.Strings[i];
FilePos := i;
if buf = '' then continue;
if copy(buf, 1, 2) = '/L' then begin
if not isLoading then
isLoading := True
else begin // isLoading = True?
Info.Author.Remark := 'Created with UltraEdit Converter. (c) Vitalik';
Result := True;
Exit;
end;
Nc := 0; bn1 := -1; bn2 := -1; qn1 := -1; qn2 := -1; qc1 := #0; qc2 := #0;
for j := 1 to 8 do begin Cnames[j] := ''; Created[j] := -1; end;
if (buf[4] = '"') or (buf[5] = '"') then begin
cur := pos('"', copy(buf, pos('"',buf)+1, length(buf)-pos('"',buf))) + pos('"', buf);
Info.General.Name := copy(buf, pos('"',buf)+1, cur-pos('"',buf)-1);
end;
if Info.General.Name = '' then
Info.General.Name := ExtractFileName(FileName);
if GetAttribute('File Extensions = ', WHOLE_STRING) then begin
Info.General.Extensions := word;
end;
Rules.AddSet('Numbers', ['0','1','2','3','4','5','6','7','8','9'], clRed);
if GetAttribute('Nocase', SINGLE_WORD) then
Rules.CaseSensitive := False
else
Rules.CaseSensitive := True;
if not GetAttribute('Noquote', SINGLE_WORD) then begin
if not GetAttribute('String Chars = ', STRING_CHARS) then
word := '"''';
qn1 := Rules.RangeCount;
qc1 := word[1];
with Rules.AddRange(qc1, qc1, 'String', clGray) do
fRule.fCloseOnEol := true;
if length(word) > 1 then begin
qn2 := Rules.RangeCount;
qc2 := word[2];
with Rules.AddRange(qc2, qc2, 'String', clGray) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Escape Char = ', ESCAPE_CHAR) then begin
with Rules.Ranges[qn1].AddKeyList('Escape', clGray) do
KeyList.Text := word + word + #13#10 + word + qc1;
if qn2 > -1 then
with Rules.Ranges[qn2].AddKeyList('Escape', clGray) do
KeyList.Text := word + word + #13#10 + word + qc2;
end;
end;
if GetAttribute('Line Comment = ', LINE_COMMENT) then begin
with Rules.AddRange(word, '', 'Line Comment', clTeal) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Line Comment Alt = ', LINE_COMMENT) then begin
with Rules.AddRange(word, '', 'Line Comment Alt', clTeal) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Line Comment Num = ', LINE_COMM_NUM) then begin
with Rules.AddRange(word, '', 'Line Comment Num', clTeal) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Block Comment On = ', BLOCK_COMMENT) then begin
bn1 := Rules.RangeCount;
with Rules.AddRange(word, '', 'Block Comment', clTeal) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Block Comment Off = ', BLOCK_COMMENT) then begin
if bn1 = -1 then
Rules.AddRange('', word, 'Block Comment', clTeal)
else begin
Rules.Ranges[bn1].fRule.fCloseSymbol.Symbol := word;
Rules.Ranges[bn1].fRule.fCloseOnEol := false;
end;
end;
if GetAttribute('Block Comment On Alt = ', BLOCK_COMMENT) then begin
bn2 := Rules.RangeCount;
with Rules.AddRange(word, '', 'Block Comment Alt', clTeal) do
fRule.fCloseOnEol := true;
end;
if GetAttribute('Block Comment Off Alt = ', BLOCK_COMMENT) then begin
if bn2 = -1 then
Rules.AddRange('', word, 'Block Comment Alt', clTeal)
else begin
Rules.Ranges[bn2].fRule.fCloseSymbol.Symbol := word;
Rules.Ranges[bn2].fRule.fCloseOnEol := false;
end;
end;
end else begin
if not isLoading then isLoading := True;
if copy(buf, 1, 13) = '/Delimiters =' then
Rules.SetDelimiters(StrToSet(copy(buf, pos('=',buf)+1, length(buf)-pos('=',buf)+1)))
else
if copy(buf, 1, 2) = '/C' then begin
Nc := StrToInt(buf[3]);
if buf[4] = '"' then begin
cur := pos('"', copy(buf, 5, length(buf)-4)) + 4;
Cnames[Nc] := copy(buf, 5, cur-5);
if Created[Nc] > -1 then // already created
Rules.KeyLists[Created[Nc]].Name := Cnames[Nc];
end
else
if Created[Nc] = -1 then // haven't created
Cnames[Nc] := 'Word list ' + IntToStr(Nc);
end else
if (buf[1] = '/') and (buf[2] <> '/') then // "/XXXXXXX = ...."
else begin
if (buf[1] = qc1) and (qn1 <> -1) then begin
Rules.Ranges[qn1].Attribs.Foreground := colors[Nc];
Rules.Ranges[qn1].Attribs.ParentForeground := False;
end;
if (buf[1] = qc2) and (qn2 <> -1) then begin
Rules.Ranges[qn2].Attribs.Foreground := colors[Nc];
Rules.Ranges[qn2].Attribs.ParentForeground := False;
end;
word := GetToken;
if word = '**' then begin
repeat
word := GetToken;
with Rules.AddRange(word, '', Cnames[Nc], colors[Nc]) do begin
TermSymbols := Rules.TermSymbols;
fRule.fCloseOnTerm := true;
end;
until buf = '';
end else begin
if Created[Nc] = -1 then begin
Created[Nc] := Rules.KeyListCount;
keyword := Rules.AddKeyList(Cnames[Nc], colors[Nc]);
end else
keyword := Rules.KeyLists[Created[Nc]];
if word = '//' then
word := GetToken;
keyword.KeyList.Add(word);
while buf <> '' do begin
word := GetToken;
keyword.KeyList.Add(word);
end;
end;
end;
end;
end;
Info.Author.Remark := 'Created with UltraEdit Converter (c) Vitalik';
Result := True;
end;
function TSynUniImportUltraEdit.LoadFromStream(Stream: TStream): boolean;
begin
FileList.LoadFromStream(Stream);
end;
function TSynUniImportUltraEdit.LoadFromFile(FileName: string): boolean;
begin
FileList.LoadFromFile(FileName);
end;
end.
|
unit EmployerList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB,
System.ImageList, Vcl.ImgList, RzButton, Vcl.StdCtrls, Vcl.Mask,
RzEdit, RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls,
RzPanel, RzRadChk, RzDBChk, RzDBEdit, Vcl.DBCtrls, RzDBCmbo, Vcl.Imaging.pngimage,
RzCmboBx, RzBtnEdt, RzDBBnEd;
type
TfrmEmployerList = class(TfrmBaseGridDetail)
edEmployerName: TRzDBEdit;
RzDBMemo1: TRzDBMemo;
cmbBranch: TRzComboBox;
bteGroup: TRzButtonEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmbBranchChange(Sender: TObject);
procedure bteGroupButtonClick(Sender: TObject);
procedure grListCellClick(Column: TColumn);
procedure grListKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure FilterList;
procedure SetUnboundControls;
public
{ Public declarations }
procedure Cancel; override;
procedure New; override;
protected
function EntryIsValid: boolean; override;
function NewIsAllowed: boolean; override;
function EditIsAllowed: boolean; override;
procedure SearchList; override;
procedure BindToObject; override;
end;
var
frmEmployerList: TfrmEmployerList;
implementation
{$R *.dfm}
uses
EntitiesData, IFinanceDialogs, FormsUtil, GroupSearch, Group, Employer;
procedure TfrmEmployerList.FormClose(Sender: TObject; var Action: TCloseAction);
begin
dmEntities.Free;
emp.Free;
inherited;
end;
procedure TfrmEmployerList.SetUnboundControls;
begin
if (Assigned(emp)) and (Assigned(emp.Group)) then
bteGroup.Text := emp.Group.GroupName;
end;
procedure TfrmEmployerList.FormCreate(Sender: TObject);
begin
dmEntities := TdmEntities.Create(self);
PopulateBranchComboBox(cmbBranch);
inherited;
end;
procedure TfrmEmployerList.FormShow(Sender: TObject);
begin
inherited;
SetUnboundControls;
end;
procedure TfrmEmployerList.grListCellClick(Column: TColumn);
begin
inherited;
SetUnboundControls;
end;
procedure TfrmEmployerList.grListKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key in [VK_UP, VK_DOWN] then SetUnboundControls;
end;
procedure TfrmEmployerList.BindToObject;
begin
inherited;
end;
procedure TfrmEmployerList.bteGroupButtonClick(Sender: TObject);
begin
inherited;
with TfrmGroupSearch.Create(self,cmbBranch.Value) do
begin
try
try
grp := TGroup.Create;
ShowModal;
if ModalResult = mrOK then
begin
with grList.DataSource.DataSet do
begin
if State <> dsInsert then Edit;
FieldByName('grp_id').AsString := grp.GroupId;
bteGroup.Text := grp.GroupName;
end;
end;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
finally
Free;
end;
end;
end;
procedure TfrmEmployerList.FilterList;
var
filterStr: string;
begin
if cmbBranch.ItemIndex > -1 then
filterStr := 'loc_code = ''' + cmbBranch.Value + ''''
else
filterStr := '';
grList.DataSource.DataSet.Filter := filterStr;
SetUnboundControls;
end;
procedure TfrmEmployerList.cmbBranchChange(Sender: TObject);
begin
inherited;
FilterList;
end;
function TfrmEmployerList.EditIsAllowed: boolean;
begin
Result := true;
end;
function TfrmEmployerList.EntryIsValid: boolean;
var
error: string;
begin
if Trim(edEmployerName.Text) = '' then error := 'Please enter an employer name.'
else if Trim(bteGroup.Text) = '' then error := 'Please select a group.';
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
procedure TfrmEmployerList.SearchList;
begin
grList.DataSource.DataSet.Locate('emp_name',edSearchKey.Text,
[loPartialKey,loCaseInsensitive]);
end;
procedure TfrmEmployerList.Cancel;
begin
inherited Cancel;
SetUnboundControls;
end;
procedure TfrmEmployerList.New;
begin
if Assigned(emp) then emp.Group := nil;
bteGroup.Clear;
inherited New;
end;
function TfrmEmployerList.NewIsAllowed: boolean;
begin
Result := true;
end;
end.
|
unit SevenZipIntfWrapper;
interface
type
TThreadParam = packed record
fileName: string;
end;
PTThreadParam = ^TThreadParam;
TProgressCallback = function(value: Cardinal): Integer;
procedure SZNewArchive(const archTypeName: PAnsiChar; const libDir: PAnsiChar); stdcall;
procedure SZAddFile(const fileName: PAnsiChar; const filePath: PAnsiChar); stdcall;
procedure SZAddFiles(const dir: PAnsiChar; const path: PAnsiChar; const wildCard: PAnsiChar; isRecurse: Boolean); stdcall;
procedure SZSetCompressionLevel(level: Cardinal); stdcall;
procedure SZSetCompressionMethod(const method: PAnsiChar); stdcall;
procedure SZSetProgressCallback(callback: Pointer); stdcall;
procedure SZSetProgressHandles(inWindowHandle: THandle; inProgressBarHandle: THandle); stdcall;
function SZSaveToFile(const fileName: PAnsiChar): THandle; stdcall;
function SZIsThreadRunning(handle: THandle; timeToWait: Cardinal): Boolean; stdcall;
function SZProgressCallback(sender: Pointer; isTotal: Boolean; value: Int64): HRESULT; stdcall;
implementation
uses
Dialogs,
StrUtils,
SysUtils,
Messages,
Windows,
CommCtrl,
SevenZipIntf;
const
ExceptionTitle = 'IS ArchMan.dll Error ';
var
OArch: I7zOutArchive;
IArch: I7zInArchive;
ProgressTotal: Int64;
ProgressCurrent: Int64;
ProgressCallback: TProgressCallback;
WindowHandle: THandle;
ProgressBarHandle: THandle;
ThreadParam: TThreadParam;
// =============================================================================
// Common
// =============================================================================
function SZProgressCallback(sender: Pointer; isTotal: Boolean; value: Int64): HRESULT; stdcall;
begin
if (isTotal)
then ProgressTotal := value
else begin
ProgressCurrent := value;
if (ProgressBarHandle <> INVALID_HANDLE_VALUE)
then PostMessage(ProgressBarHandle, PBM_SETPOS, Round(ProgressCurrent / (ProgressTotal / 100)), 0);
//if (Assigned(ProgressCallback))
// then ProgressCallback(Round(ProgressCurrent / (ProgressTotal / 1000)));
end;
Result := S_OK;
end;
// =============================================================================
// Creation
// =============================================================================
function IsOutArchiveExists(): Boolean;
begin
if (not Assigned(OArch))
then begin
ShowMessage(ExceptionTitle + ' #124' + #10#13 + 'Before do any action with archive - you need init it.');
Result := false;
end else
Result := true;
end;
function SaveToFileThread(PParam: Pointer): Integer; // stdcall winapi; - not user for BeginThread
var
PThreadParam: PTThreadParam;
begin
Result := 0;
if (not IsOutArchiveExists()) then Exit;
try
PThreadParam := PParam;
OArch.SaveToFile(PThreadParam.fileName);
OArch := nil;
except
on E: Exception do begin
ShowMessage(ExceptionTitle + ' #512' + #10#13 + E.Message + #10#13 + SysErrorMessage(GetLastError()));
EndThread(1);
end;
end;
EndThread(0);
end;
procedure SZNewArchive(const archTypeName: PAnsiChar; const libDir: PAnsiChar);
var
archType: TGUID;
begin
if (Assigned(OArch))
then OArch := nil;
case AnsiIndexStr(string(archTypeName), ['7z', 'zip', 'rar']) of
0: archType := CLSID_CFormat7z;
1: archType := CLSID_CFormatZip;
2: archType := CLSID_CFormatRar;
else archType := CLSID_CFormat7z;
end;
try
OArch := CreateOutArchive(archType, string(libDir));
except
on E: Exception do
ShowMessage(ExceptionTitle + ' #812' + #10#13 + E.Message + #10#13 + SysErrorMessage(GetLastError()));
end;
end;
procedure SZAddFile(const fileName: PAnsiChar; const filePath: PAnsiChar);
begin
if (not IsOutArchiveExists()) then Exit;
OArch.AddFile(string(fileName), string(filePath));
end;
procedure SZAddFiles(const dir: PAnsiChar; const path: PAnsiChar; const wildCard: PAnsiChar; isRecurse: Boolean);
begin
if (not IsOutArchiveExists()) then Exit;
OArch.AddFiles(string(dir), string(path), string(wildCard), isRecurse);
end;
procedure SZSetCompressionLevel(level: Cardinal);
begin
if (not IsOutArchiveExists()) then Exit;
SetCompressionLevel(OArch, level);
end;
// For ZIP: 'COPY', 'DEFLATE', 'DEFLATE64', 'BZIP2'
// For 7Zip: 'COPY', 'LZMA', 'LZMA2', 'BZIP2', 'PPMD', 'DEFLATE', 'DEFLATE64'
procedure SZSetCompressionMethod(const method: PAnsiChar);
begin
if (not IsOutArchiveExists()) then Exit;
if (IsEqualGUID(OArch.ClassId, CLSID_CFormatZip))
then OArch.SetPropertie('M', string(method));
if (IsEqualGUID(OArch.ClassId, CLSID_CFormat7z))
then OArch.SetPropertie('0', string(method));
end;
procedure SZSetProgressCallback(callback: Pointer);
begin
if (not IsOutArchiveExists()) then Exit;
ProgressCallback := callback;
OArch.SetProgressCallback(nil, SZProgressCallback);
end;
procedure SZSetProgressHandles(inWindowHandle: THandle; inProgressBarHandle: THandle);
begin
if (not IsOutArchiveExists()) then Exit;
WindowHandle := inWindowHandle;
ProgressBarHandle := inProgressBarHandle;
SendMessage(ProgressBarHandle, PBM_SETRANGE, 0, MakeLParam(0, 100));
OArch.SetProgressCallback(nil, SZProgressCallback)
end;
function SZSaveToFile(const fileName: PAnsiChar): THandle;
var
ThreadID: Cardinal;
begin
Result := 0;
if (not IsOutArchiveExists()) then
Exit()
else begin
try
ThreadParam.fileName := string(fileName);
Result := BeginThread(nil, 0, @SaveToFileThread, @ThreadParam, 0, ThreadID);
except
on E: Exception do
ShowMessage(ExceptionTitle + ' #815' + #10#13 + E.Message + #10#13 + SysErrorMessage(GetLastError()));
end;
end;
end;
function SZIsThreadRunning(handle: THandle; timeToWait: Cardinal): Boolean;
begin
try
Result := not (WaitForSingleObject(handle, timeToWait) <> WAIT_TIMEOUT);
except
on E: Exception do begin
ShowMessage(ExceptionTitle + ' #156' + #10#13 + E.Message + #10#13 + SysErrorMessage(GetLastError()));
Result := false;
end;
end;
end;
// =============================================================================
// System section
// =============================================================================
initialization
WindowHandle := INVALID_HANDLE_VALUE;
ProgressBarHandle := INVALID_HANDLE_VALUE;
finalization
if (Assigned(OArch)) then OArch := nil;
if (Assigned(IArch)) then IArch := nil;
end.
|
Program ScopeDemo;
Var
A: integer;
Procedure ScopeInner;
Var
A: integer;
Begin
A := 10;
WriteLn(A);
End;
Begin
A := 20;
WriteLn(A);
ScopeInner;
WriteLn(A);
End.
|
UNIT GraphPrm;
{ Graphic Primitives from FRACTALS IN C }
{ ===========================================================}
interface
{ ===========================================================}
VAR
DisplayWidth,
DisplayHeight : INTEGER;
HalfWidth,
HalfHeight : INTEGER;
PROCEDURE SetMode(mode : BYTE);
{ set video mode }
PROCEDURE Plot(x,y,color : WORD);
PROCEDURE DrawLine(x1,y1,x2,y2,color : INTEGER);
{ on a 640x400 display with center 0,0 coordinate system}
PROCEDURE Cls(color : WORD);
{clear screen}
{ ===========================================================}
implementation
{ ===========================================================}
USES
GRAPH
(*, Dos {Intr, registers} *)
;
PROCEDURE SetMode(mode : BYTE);
{ set video mode }
VAR
{ regs : registers;}
grDriver : Integer;
grMode : Integer;
ErrCode : Integer;
begin
IF Mode = 0 THEN
CloseGraph
ELSE
BEGIN
grDriver := Detect;
InitGraph(grDriver,grMode,'');
ErrCode := GraphResult;
if ErrCode <> grOk THEN HALT;
END;
(*
regs.AH := 0;
regs.AL := mode;
Intr($10,regs);
*)
END {SetMode};
PROCEDURE Plot(x,y,color : WORD);
BEGIN
PutPixel(x,y,color);
END {Plot};
PROCEDURE DrawLine(x1,y1,x2,y2,color : INTEGER);
BEGIN
SetColor(color);
x1 := HalfWidth + x1;
x2 := HalfWidth + x2;
y1 := HalfHeight - y1;
y2 := HalfHeight - y2;
Line(x1,y1,x2,y2);
END;
PROCEDURE Cls(color : WORD);
{clear screen}
BEGIN
SetBkColor(color);
ClearViewPort;
END {CLS};
BEGIN
SetMode(16);
DisplayHeight := GetMaxY;
DisplayWidth := GetMaxX;
HalfWidth := DisplayWidth div 2;
HalfHeight := DisplayHeight div 2;
CloseGraph;
END {GraphPrm}.
|
unit uDeleteFiles;
interface
uses
Windows, SysUtils, classes, SyncObjs, uDirUtils;
type
TFolderEvent = procedure(Sender: TObject; Dirname : string) of object;
TDeleteFilesThread = class(TThread)
private
fOnDelete : TFolderEvent;
fDirName : string;
fPasta : string;
fFileNames : TStringList;
procedure SyncDelete;
procedure doOnDelete(Dirname : string);
protected
procedure Execute; override;
public
property OnDelete : TFolderEvent read fOnDelete write fOnDelete;
constructor Create(aPasta:string; aFileNames:TStringList);
destructor Destroy; override;
end;
implementation
uses
uLogs;
{ TDeleteFilesThread }
constructor TDeleteFilesThread.Create(aPasta:string; aFileNames:TStringList);
begin
inherited Create(true);
fPasta := aPasta;
fFileNames := TStringList.create;
fFileNames.assign(aFileNames);
FreeOnTerminate := true;
end;
destructor TDeleteFilesThread.Destroy;
begin
fFileNames.free;
inherited;
end;
procedure TDeleteFilesThread.doOnDelete(Dirname: string);
begin
fDirName := DirName;
Synchronize(SyncDelete);
end;
procedure TDeleteFilesThread.SyncDelete;
begin
{$IFNDEF NOLOG} GLog.Log(self,[lcTrace],'fOnDelete '+fDirName );{$ENDIF}
if (assigned(fOnDelete)) then
fOnDelete(self, fDirName);
end;
procedure TDeleteFilesThread.Execute;
var
ok : boolean;
i : integer;
begin
{$IFNDEF NOLOG} GLog.Log(self,[lcTrace],'executing '+fPasta );{$ENDIF}
ok := false;
for i:=0 to fFileNames.count-1 do begin
ok := false;
repeat
if deletefile(fFileNames[i]) then
ok := true
else
sleep(250);
until ok or terminated;
end;
if ok then begin
CleanUpAndDeleteDirectory(fPasta, nil,nil);
doOnDelete(fPasta);
end;
{$IFNDEF NOLOG} GLog.Log(self,[lcTrace],'Terminating '+fPasta );{$ENDIF}
{$IFNDEF NOLOG} GLog.ForceLogWrite;{$ENDIF}
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.