text
stringlengths
14
6.51M
{ File: HIToolbox/HIShape.h Contains: Generic Abstract Shape API Version: HIToolbox-219.4.81~2 Copyright: © 2001-2005 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { File: HIShape.p(.pas) } { } { Contains: CodeWarrior Pascal(GPC) translation of Apple's Mac OS X 10.2 introduced HIShape.h. } { Translation compatible with make-gpc-interfaces.pl generated MWPInterfaces } { (GPCPInterfaces) and Mac OS X 10.2.x or higher. The CodeWarrior Pascal translation } { is linkable with Mac OS X 10.2.x or higher CFM CarbonLib. The GPC translation is } { linkable with Mac OS X 10.2.x or higher Mach-O Carbon.framework. } { } { Version: 1.0 } { } { Pascal Translation: Gale Paeper, <gpaeper@empirenet.com>, 2004 } { } { Copyright: Subject to the constraints of Apple's original rights, you're free to use this } { translation as you deem fit. } { } { Bugs?: This is an AS IS translation with no express guarentees of any kind. } { If you do find a bug, please help out the Macintosh Pascal programming community by } { reporting your bug finding and possible fix to either personal e-mail to Gale Paeper } { or a posting to the MacPascal mailing list. } { } { Translation assisted by: } {This file was processed by Dan's Source Converter} {version 1.3 (this version modified by Ingemar Ragnemalm)} { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit HIShape; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CGContext,Drag,Quickdraw,CarbonEvents,HIGeometry; {$ALIGN POWER} { * HIShape * * Discussion: * HIShape is an abstract shape object for use with some of the * HIToolbox APIs. It is designed as a replacement for RgnHandles * (though it is currently implemented in terms of them at the time * of this writing). This abstraction will allow us to avoid using * QD types in our APIs, particularly in HIView. * * One of the biggest benefits of HIShape is that we have mutable * and immutable variants. This means that immutable shapes can be * created and passed around and 'copied' very quickly, since they * are actually refcounted when copied. This avoids needing to do * the handle-to-handle copies that occur right now with * RgnHandle-based APIs. } type HIShapeRef = ^SInt32; { an opaque 32-bit type } type HIMutableShapeRef = ^SInt32; { an opaque 32-bit type } { * HIShapeGetTypeID() * * Discussion: * Returns the CF type ID for the HIShape class. * * Mac OS X threading: * Not thread safe * * Result: * A CF type ID. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeGetTypeID: CFTypeID; external name '_HIShapeGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {======================================================================================} { IMMUTABLE FUNCTIONS } {======================================================================================} { * HIShapeCreateEmpty() * * Discussion: * Creates an immutable empty shape. Useful at times. * * Mac OS X threading: * Not thread safe * * Result: * An immutable, empty HIShape reference. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIShapeCreateEmpty: HIShapeRef; external name '_HIShapeCreateEmpty'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIShapeCreateWithQDRgn() * * Discussion: * Creates an immutable shape based on an existing Quickdraw region * handle. * * Mac OS X threading: * Not thread safe * * Parameters: * * inRgn: * The Quickdraw region from which to create the HIShape. * * Result: * An immutable HIShape reference. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateWithQDRgn( inRgn: RgnHandle ): HIShapeRef; external name '_HIShapeCreateWithQDRgn'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateWithRect() * * Discussion: * Creates an immutable, rectangular shape based on a given * rectangle. * * Mac OS X threading: * Not thread safe * * Parameters: * * inRect: * The HIRect from which to create the resulting shape. * * Result: * An immutable HIShape reference. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateWithRect( const (*var*) inRect: HIRect ): HIShapeRef; external name '_HIShapeCreateWithRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateCopy() * * Discussion: * Creates an immutable copy of a mutable or immutable HIShape. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * The existing HIShapeRef you wish to copy. * * Result: * An immutable HIShape reference. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateCopy( inShape: HIShapeRef ): HIShapeRef; external name '_HIShapeCreateCopy'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateIntersection() * * Discussion: * Creates a new immutable shape which is the intersection of two * others. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * An existing HIShapeRef. * * inShape2: * An existing HIShapeRef. * * Result: * A new immutable HIShapeRef. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateIntersection( inShape1: HIShapeRef; inShape2: HIShapeRef ): HIShapeRef; external name '_HIShapeCreateIntersection'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateDifference() * * Discussion: * Creates a new immutable shape which is the difference of two * others. The second shape is subtracted from the first. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * An existing HIShapeRef. * * inShape2: * An existing HIShapeRef. * * Result: * A new immutable HIShapeRef. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateDifference( inShape1: HIShapeRef; inShape2: HIShapeRef ): HIShapeRef; external name '_HIShapeCreateDifference'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateUnion() * * Discussion: * Creates a new immutable shape which is the union of two others. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * An existing HIShapeRef. * * inShape2: * An existing HIShapeRef. * * Result: * A new immutable HIShapeRef. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateUnion( inShape1: HIShapeRef; inShape2: HIShapeRef ): HIShapeRef; external name '_HIShapeCreateUnion'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeIsEmpty() * * Discussion: * Returns true if the given HIShapeRef is empty, i.e. its area is * empty. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * The existing HIShapeRef you wish to test. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeIsEmpty( inShape: HIShapeRef ): Boolean; external name '_HIShapeIsEmpty'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeIsRectangular() * * Discussion: * Returns true if the given HIShapeRef is rectangular. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * The existing HIShapeRef you wish to test. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeIsRectangular( inShape: HIShapeRef ): Boolean; external name '_HIShapeIsRectangular'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeContainsPoint() * * Discussion: * Returns true if the given HIShapeRef contains the point passed in. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * inPoint: * The point to check. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeContainsPoint( inShape: HIShapeRef; const (*var*) inPoint: HIPoint ): Boolean; external name '_HIShapeContainsPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeIntersectsRect() * * Discussion: * Returns true if the given HIShapeRef intersects the rect passed * in. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * inRect: * The rectangle to check. * * Result: * A boolean result. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function HIShapeIntersectsRect( inShape: HIShapeRef; const (*var*) inRect: HIRect ): Boolean; external name '_HIShapeIntersectsRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * HIShapeGetBounds() * * Discussion: * Returns the bounding rectangle of a given HIShapeRef. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * outRect: * Receives the bounding rectangle. * * Result: * A pointer to the rectangle you passed in, for convenience. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeGetBounds( inShape: HIShapeRef; var outRect: HIRect ): HIRectPtr; external name '_HIShapeGetBounds'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeGetAsQDRgn() * * Discussion: * Changes a given Quickdraw region handle to have the same shape as * a given HIShapeRef. Essentially you are converting an HIShapeRef * into a RgnHandle. This conversion may lose fidelity depending on * how the shape was created originally. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * outRgn: * An existing region to change. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeGetAsQDRgn( inShape: HIShapeRef; outRgn: RgnHandle ): OSStatus; external name '_HIShapeGetAsQDRgn'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeReplacePathInCGContext() * * Discussion: * Given an HIShapeRef and a CGContextRef, make the current path in * the context represent the shape. You might use this to clip to a * shape, for example. You could call this function and then * immediately call CGContextClip. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * inContext: * The context to apply the shape to. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeReplacePathInCGContext( inShape: HIShapeRef; inContext: CGContextRef ): OSStatus; external name '_HIShapeReplacePathInCGContext'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeSetQDClip() * * Discussion: * Given an HIShapeRef and a Quickdraw port, set the current clip in * the port to the shape. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * An existing HIShapeRef. * * inPort: * The port to set the clip for. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeSetQDClip( inShape: HIShapeRef; inPort: CGrafPtr ): OSStatus; external name '_HIShapeSetQDClip'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {======================================================================================} { MUTABLE FUNCTIONS } {======================================================================================} { * HIShapeCreateMutable() * * Discussion: * Creates a new, mutable, empty shape. * * Mac OS X threading: * Not thread safe * * Result: * A mutable shape reference. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateMutable: HIMutableShapeRef; external name '_HIShapeCreateMutable'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeCreateMutableCopy() * * Discussion: * Given an existing HIShapeRef, creates a new mutable copy. * * Mac OS X threading: * Not thread safe * * Parameters: * * inOrig: * The shape to copy. * * Result: * A mutable shape reference. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeCreateMutableCopy( inOrig: HIShapeRef ): HIMutableShapeRef; external name '_HIShapeCreateMutableCopy'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeSetEmpty() * * Discussion: * Sets a mutable shape to be an empty shape. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * The shape to empty. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeSetEmpty( inShape: HIMutableShapeRef ): OSStatus; external name '_HIShapeSetEmpty'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeIntersect() * * Discussion: * Takes two shapes and sets a third to be their intersection. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * The first shape. * * inShape2: * The second shape. * * outResult: * The shape to receive the result of the intersection. This can * be one of the source shapes. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeIntersect( inShape1: HIShapeRef; inShape2: HIShapeRef; outResult: HIMutableShapeRef ): OSStatus; external name '_HIShapeIntersect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeDifference() * * Discussion: * Takes two shapes and sets a third to be their difference. The * second shape is subtracted from the first. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * The first shape. * * inShape2: * The second shape. * * outResult: * The shape to receive the result of the intersection. This can * be one of the source shapes. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeDifference( inShape1: HIShapeRef; inShape2: HIShapeRef; outResult: HIMutableShapeRef ): OSStatus; external name '_HIShapeDifference'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeUnion() * * Discussion: * Takes two shapes and sets a third to be their union. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape1: * The first shape. * * inShape2: * The second shape. * * outResult: * The shape to receive the result of the union. This can be one * of the source shapes. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeUnion( inShape1: HIShapeRef; inShape2: HIShapeRef; outResult: HIMutableShapeRef ): OSStatus; external name '_HIShapeUnion'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * HIShapeOffset() * * Discussion: * Offsets a shape by some delta. * * Mac OS X threading: * Not thread safe * * Parameters: * * inShape: * The shape to offset. * * inDX: * The delta to move the shape on the X axis. * * inDY: * The delta to move the shape on the Y axis. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Non-Carbon CFM: not available } function HIShapeOffset( inShape: HIMutableShapeRef; inDX: Float32; inDY: Float32 ): OSStatus; external name '_HIShapeOffset'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) end.
unit TrackingHistoryRequestUnit; interface uses REST.Json.Types, HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit; type TTrackingHistoryRequest = class(TGenericParameters) private [HttpQueryMember('route_id')] FRouteId: String; [HttpQueryMember('format')] [Nullable] FFormat: NullableString; [HttpQueryMember('last_position')] [Nullable] FLastPosition: NullableBoolean; [HttpQueryMember('time_period')] FTimePeriod: String; [HttpQueryMember('start_date')] [Nullable] FStartDate: NullableString; [HttpQueryMember('end_date')] [Nullable] FEndDate: NullableString; public constructor Create(RouteId: String); reintroduce; property RouteId: String read FRouteId write FRouteId; property Format: NullableString read FFormat write FFormat; property LastPosition: NullableBoolean read FLastPosition write FLastPosition; property TimePeriod: String read FTimePeriod write FTimePeriod; property StartDate: NullableString read FStartDate write FStartDate; property EndDate: NullableString read FEndDate write FEndDate; end; implementation { TTrackingHistoryRequest } constructor TTrackingHistoryRequest.Create(RouteId: String); begin inherited Create; FRouteId := RouteId; FFormat := NullableString.Null; FLastPosition := NullableBoolean.Null; FStartDate := NullableString.Null; FEndDate := NullableString.Null; end; end.
unit toki_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,seibu_sound,rom_engine, pal_engine,sound_engine,misc_functions; function iniciar_toki:boolean; implementation const toki_rom:array[0..3] of tipo_roms=( (n:'l10_6.bin';l:$20000;p:0;crc:$94015d91),(n:'k10_4e.bin';l:$20000;p:$1;crc:$531bd3ef), (n:'tokijp.005';l:$10000;p:$40000;crc:$d6a82808),(n:'tokijp.003';l:$10000;p:$40001;crc:$a01a5b10)); toki_char:array[0..1] of tipo_roms=( (n:'tokijp.001';l:$10000;p:0;crc:$8aa964a2),(n:'tokijp.002';l:$10000;p:$10000;crc:$86e87e48)); toki_sprites:array[0..1] of tipo_roms=( (n:'toki.ob1';l:$80000;p:0;crc:$a27a80ba),(n:'toki.ob2';l:$80000;p:$80000;crc:$fa687718)); toki_tiles1:tipo_roms=(n:'toki.bk1';l:$80000;p:0;crc:$fdaa5f4b); toki_tiles2:tipo_roms=(n:'toki.bk2';l:$80000;p:0;crc:$d86ac664); toki_sound:array[0..1] of tipo_roms=( (n:'tokijp.008';l:$2000;p:0;crc:$6c87c4c5),(n:'tokijp.007';l:$10000;p:$10000;crc:$a67969c4)); toki_adpcm:tipo_roms=(n:'tokijp.009';l:$20000;p:0;crc:$ae7a6b8b); toki_dip:array [0..9] of def_dip=( (mask:$1f;name:'Coinage';number:16;dip:((dip_val:$15;dip_name:'6C 1C'),(dip_val:$17;dip_name:'5C 1C'),(dip_val:$19;dip_name:'4C 1C'),(dip_val:$1b;dip_name:'3C 1C'),(dip_val:$3;dip_name:'8C 3C'),(dip_val:$1d;dip_name:'2C 1C'),(dip_val:$5;dip_name:'5C 3C'),(dip_val:$7;dip_name:'3C 2C'),(dip_val:$1f;dip_name:'1C 1C'),(dip_val:$9;dip_name:'2C 3C'),(dip_val:$13;dip_name:'1C 2C'),(dip_val:$11;dip_name:'1C 3C'),(dip_val:$f;dip_name:'1C 4C'),(dip_val:$d;dip_name:'1C 5C'),(dip_val:$b;dip_name:'1C 6C'),(dip_val:$1e;dip_name:'A 1C 1C/B 1/2'))), (mask:$20;name:'Joysticks';number:2;dip:((dip_val:$20;dip_name:'1'),(dip_val:$0;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$300;name:'Lives';number:4;dip:((dip_val:$200;dip_name:'2'),(dip_val:$300;dip_name:'3'),(dip_val:$100;dip_name:'5'),(dip_val:$0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c00;name:'Bonus Life';number:4;dip:((dip_val:$800;dip_name:'50k 150k'),(dip_val:$0;dip_name:'70k 140k 210k'),(dip_val:$c00;dip_name:'70k'),(dip_val:$400;dip_name:'100k 200k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$3000;name:'Difficulty';number:4;dip:((dip_val:$2000;dip_name:'Easy'),(dip_val:$3000;dip_name:'Medium'),(dip_val:$1000;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4000;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$4000;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8000;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8000;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$2ffff] of word; ram:array[0..$7fff] of word; sprite_ram:array[0..$3ff] of word; scroll_x2_tmp,scroll_x1,scroll_y1,scroll_y2:word; scroll_x2:array[0..$ff] of word; prioridad_pant:boolean; procedure update_video_toki; var f,color,sy,x,y,nchar,atrib,atrib2,atrib3:word; begin for f:=0 to $3ff do begin //Background 1 atrib:=ram[$7400+f]; color:=atrib shr 12; if (gfx[2].buffer[f] or buffer_color[color+$10]) then begin x:=f mod 32; y:=f div 32; nchar:=atrib and $fff; if prioridad_pant then put_gfx(x*16,y*16,nchar,(color shl 4)+$200,2,2) else put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$200,2,2); gfx[2].buffer[f]:=false; end; //Background 2 atrib:=ram[$7800+f]; color:=atrib shr 12; if (gfx[3].buffer[f] or buffer_color[color+$20]) then begin x:=f mod 32; y:=f div 32; nchar:=atrib and $fff; if prioridad_pant then put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$300,4,3) else put_gfx(x*16,y*16,nchar,(color shl 4)+$300,4,3); gfx[3].buffer[f]:=false; end; //Foreground atrib:=ram[$7c00+f]; color:=atrib shr 12; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f mod 32; y:=f div 32; nchar:=atrib and $fff; put_gfx_trans(x*8,y*8,nchar,(color shl 4)+$100,1,0); gfx[0].buffer[f]:=false; end; end; if prioridad_pant then begin scroll_x_y(2,3,scroll_x1,scroll_y1); scroll__x_part2(4,3,1,@scroll_x2,0,scroll_y2); end else begin scroll_x_y(4,3,scroll_x2_tmp,scroll_y2); scroll_x_y(2,3,scroll_x1,scroll_y1); end; for f:=$ff downto 0 do begin atrib:=sprite_ram[f*4]; atrib2:=sprite_ram[(f*4)+2]; if ((atrib2<>$f000) and (atrib<>$ffff)) then begin x:=atrib2+(atrib and $f0); sy:=(atrib and $0f) shl 4; y:=sprite_ram[(f*4)+3]+sy; atrib3:=sprite_ram[(f*4)+1]; color:=(atrib3 shr 8) and $f0; nchar:=(atrib3 and $fff)+((atrib2 and $8000) shr 3); put_gfx_sprite(nchar,color,(atrib and $100)<>0,false,1); actualiza_gfx_sprite(x and $1ff,y and $1ff,3,1); end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,3); actualiza_trozo_final(0,16,256,224,3); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_toki; begin if event.arcade then begin if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $0001); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $0002); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $0004); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $0008); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $0010); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $0020); if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $0100); if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $0200); if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $0400); if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $0800); if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000); if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000); if arcade_input.coin[0] then seibu_snd_0.input:=(seibu_snd_0.input or $1) else seibu_snd_0.input:=(seibu_snd_0.input and $fe); if arcade_input.coin[1] then seibu_snd_0.input:=(seibu_snd_0.input or $2) else seibu_snd_0.input:=(seibu_snd_0.input and $fd); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10); end; end; procedure toki_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=seibu_snd_0.z80.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //Sound CPU seibu_snd_0.z80.run(frame_s); frame_s:=frame_s+seibu_snd_0.z80.tframes-seibu_snd_0.z80.contador; if f=239 then begin m68000_0.irq[1]:=HOLD_LINE; update_video_toki; copymemory(@sprite_ram[0],@ram[$6c00],$800); end; scroll_x2[f]:=scroll_x2_tmp; end; eventos_toki; video_sync; end; end; function toki_getword(direccion:dword):word; begin case direccion of $0..$5ffff:toki_getword:=rom[direccion shr 1]; $60000..$6dfff,$6e800..$6ffff:toki_getword:=ram[(direccion and $ffff) shr 1]; $6e000..$6e7ff:toki_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $80000..$8000d:toki_getword:=seibu_snd_0.get((direccion and $e) shr 1); $c0000:toki_getword:=marcade.dswa; $c0002:toki_getword:=marcade.in0; $c0004:toki_getword:=marcade.in1; end; end; procedure toki_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.b:=pal4bit(tmp_color shr 8); color.g:=pal4bit(tmp_color shr 4); color.r:=pal4bit(tmp_color); set_pal_color(color,numero); case numero of 256..511:buffer_color[(numero shr 4) and $f]:=true; 512..767:buffer_color[((numero shr 4) and $f)+$10]:=true; 768..1023:buffer_color[((numero shr 4) and $f)+$20]:=true; end; end; begin case direccion of 0..$5ffff:; //ROM $60000..$6dfff:ram[(direccion and $ffff) shr 1]:=valor; $6e000..$6e7ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,((direccion and $7ff) shr 1)); end; $6e800..$6efff:if ram[(direccion and $ffff) shr 1]<>valor then begin ram[(direccion and $ffff) shr 1]:=valor; gfx[2].buffer[(direccion and $7ff) shr 1]:=true; end; $6f000..$6f7ff:if ram[(direccion and $ffff) shr 1]<>valor then begin ram[(direccion and $ffff) shr 1]:=valor; gfx[3].buffer[(direccion and $7ff) shr 1]:=true; end; $6f800..$6ffff:if ram[(direccion and $ffff) shr 1]<>valor then begin ram[(direccion and $ffff) shr 1]:=valor; gfx[0].buffer[(direccion and $7ff) shr 1]:=true; end; $80000..$8000d:seibu_snd_0.put((direccion and $e) shr 1,valor); $a0000..$a005f:case (direccion and $ff) of $0a:scroll_x1:=(scroll_x1 and $ff) or ((valor and $10) shl 4); $0c:scroll_x1:=(scroll_x1 and $100) or ((valor and $7f) shl 1) or ((valor and $80) shr 7); $1a:scroll_y1:=(scroll_y1 and $ff) or ((valor and $10) shl 4); $1c:scroll_y1:=(scroll_y1 and $100) or ((valor and $7f) shl 1) or ((valor and $80) shr 7); $2a:scroll_x2_tmp:=(scroll_x2_tmp and $ff) or ((valor and $10) shl 4); $2c:scroll_x2_tmp:=(scroll_x2_tmp and $100) or ((valor and $7f) shl 1) or ((valor and $80) shr 7); $3a:scroll_y2:=(scroll_y2 and $ff) or ((valor and $10) shl 4); $3c:scroll_y2:=(scroll_y2 and $100) or ((valor and $7f) shl 1) or ((valor and $80) shr 7); $50:begin main_screen.flip_main_screen:=(valor and $8000)=0; if prioridad_pant<>((valor and $100)<>0) then begin prioridad_pant:=(valor and $100)<>0; fillchar(gfx[2].buffer[0],$400,1); fillchar(gfx[3].buffer[0],$400,1); end; end; end; end; end; //Main procedure reset_toki; begin m68000_0.reset; seibu_snd_0.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; seibu_snd_0.input:=0; scroll_x1:=0; scroll_y1:=0; scroll_x2_tmp:=0; fillchar(scroll_x2,$100,0); scroll_y2:=0; end; function iniciar_toki:boolean; const pc_x:array[0..7] of dword=(3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0); pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16); ps_x:array[0..15] of dword=(3, 2, 1, 0, 16+3, 16+2, 16+1, 16+0, 64*8+3, 64*8+2, 64*8+1, 64*8+0, 64*8+16+3, 64*8+16+2, 64*8+16+1, 64*8+16+0); ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32); var memoria_temp,ptemp:pbyte; f:dword; begin llamadas_maquina.bucle_general:=toki_principal; llamadas_maquina.reset:=reset_toki; llamadas_maquina.fps_max:=59.61; iniciar_toki:=false; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,512,512,true); screen_mod_scroll(2,512,256,511,512,256,511); screen_init(3,512,512,false,true); screen_init(4,512,512,true); screen_mod_scroll(4,512,256,511,512,256,511); iniciar_video(256,224); getmem(memoria_temp,$100000); //Main CPU m68000_0:=cpu_m68000.create(10000000,256); m68000_0.change_ram16_calls(toki_getword,toki_putword); if not(roms_load16w(@rom,toki_rom)) then exit; //sound if not(roms_load(memoria_temp,toki_sound)) then exit; seibu_snd_0:=seibu_snd_type.create(SEIBU_OKI,3579545,256,memoria_temp,true); copymemory(@seibu_snd_0.sound_rom[0,0],@memoria_temp[$10000],$8000); copymemory(@seibu_snd_0.sound_rom[1,0],@memoria_temp[$18000],$8000); if not(roms_load(memoria_temp,toki_adpcm)) then exit; ptemp:=seibu_snd_0.oki_6295_get_rom_addr; for f:=0 to $1ffff do ptemp[f]:=memoria_temp[BITSWAP24(f,23,22,21,20,19,18,17,16,13,14,15,12,11,10,9,8,7,6,5,4,3,2,1,0)]; //convertir chars if not(roms_load(memoria_temp,toki_char)) then exit; init_gfx(0,8,8,4096); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,16*8,4096*16*8+0,4096*16*8+4,0,4); convert_gfx(0,0,memoria_temp,@pc_x,@pc_y,false,false); //sprites if not(roms_load(memoria_temp,toki_sprites)) then exit; init_gfx(1,16,16,8192); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,128*8,2*4,3*4,0*4,1*4); convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false); //tiles if not(roms_load(memoria_temp,toki_tiles1)) then exit; init_gfx(2,16,16,4096); gfx[2].trans[15]:=true; convert_gfx(2,0,memoria_temp,@ps_x,@ps_y,false,false); if not(roms_load(memoria_temp,toki_tiles2)) then exit; init_gfx(3,16,16,4096); gfx[3].trans[15]:=true; convert_gfx(3,0,memoria_temp,@ps_x,@ps_y,false,false); //DIP marcade.dswa:=$ffdf; marcade.dswa_val:=@toki_dip; //final freemem(memoria_temp); reset_toki; iniciar_toki:=true; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.9 2/16/2005 7:58:56 AM DSiders Modified TIdRequestHeaderInfo to restore the Range property. Modified TIdRequestHeaderInfo methods AssignTo, Clear, ProcessHeaders, and SetHeaders to include Range property. Rev 1.8 11/11/2004 12:55:38 AM DSiders Modified TIdEntityHeaderInfo to fix problems with content-range header handling. Added ContentRangeInstanceLength property. Added HasContentRange property (read-ony). Added HasContentRangeInstance property (read-only). Moved reading and writing methods to ProcessHeaders and SetHeaders in TIdEntityHeaderInfo. Rev 1.7 6/8/2004 10:35:46 AM BGooijen fixed overflow Rev 1.6 2004.02.03 5:43:46 PM czhower Name changes Rev 1.5 1/22/2004 7:10:08 AM JPMugaas Tried to fix AnsiSameText depreciation. Rev 1.4 13.1.2004 ã. 17:17:44 DBondzhev moved few methods into protected section to remove some warnings Rev 1.3 10/17/2003 12:09:28 AM DSiders Added localization comments. Rev 1.2 20/4/2003 3:46:34 PM SGrobety Fix to previous fix... (Dumb me) Rev 1.1 20/4/2003 3:33:58 PM SGrobety Changed Content-type default in TIdEntityHeaderInfo back to empty string and changed the default of the response object. Solved compatibility issue with Netscape servers Rev 1.0 11/13/2002 07:54:24 AM JPMugaas } unit IdHTTPHeaderInfo; { HTTP Header definition - RFC 2616 Author: Doychin Bondzhev (doychin@dsoft-bg.com) } interface {$i IdCompilerDefines.inc} uses Classes, IdAuthentication, IdGlobal, IdGlobalProtocols, IdHeaderList; type TIdEntityHeaderInfo = class(TPersistent) protected FOwner: TPersistent; FCacheControl: String; FRawHeaders: TIdHeaderList; FCharSet: String; FConnection: string; FContentDisposition: string; FContentEncoding: string; FContentLanguage: string; FContentLength: Int64; FContentRangeEnd: Int64; FContentRangeStart: Int64; FContentRangeInstanceLength: Int64; FContentRangeUnits: String; FContentType: string; FContentVersion: string; FCustomHeaders: TIdHeaderList; FDate: TDateTime; FExpires: TDateTime; FETag: string; FLastModified: TDateTime; FPragma: string; FHasContentLength: Boolean; FTransferEncoding: String; // procedure AssignTo(Destination: TPersistent); override; procedure ProcessHeaders; virtual; procedure SetHeaders; virtual; function GetOwner: TPersistent; override; function GetOwnerComponent: TComponent; procedure SetContentLength(const AValue: Int64); procedure SetContentType(const AValue: String); procedure SetCustomHeaders(const AValue: TIdHeaderList); function GetHasContentRange: Boolean; function GetHasContentRangeInstance: Boolean; public procedure AfterConstruction; override; procedure Clear; virtual; constructor Create(AOwner: TPersistent); virtual; destructor Destroy; override; // property OwnerComponent: TComponent read GetOwnerComponent; property HasContentLength: Boolean read FHasContentLength; property HasContentRange: Boolean read GetHasContentRange; property HasContentRangeInstance: Boolean read GetHasContentRangeInstance; property RawHeaders: TIdHeaderList read FRawHeaders; published property CacheControl: String read FCacheControl write FCacheControl; property CharSet: String read FCharSet write FCharSet; property Connection: string read FConnection write FConnection; property ContentDisposition: string read FContentDisposition write FContentDisposition; property ContentEncoding: string read FContentEncoding write FContentEncoding; property ContentLanguage: string read FContentLanguage write FContentLanguage; property ContentLength: Int64 read FContentLength write SetContentLength; property ContentRangeEnd: Int64 read FContentRangeEnd write FContentRangeEnd; property ContentRangeStart: Int64 read FContentRangeStart write FContentRangeStart; property ContentRangeInstanceLength: Int64 read FContentRangeInstanceLength write FContentRangeInstanceLength; property ContentRangeUnits: String read FContentRangeUnits write FContentRangeUnits; property ContentType: string read FContentType write SetContentType; property ContentVersion: string read FContentVersion write FContentVersion; property CustomHeaders: TIdHeaderList read FCustomHeaders write SetCustomHeaders; property Date: TDateTime read FDate write FDate; property ETag: string read FETag write FETag; property Expires: TDateTime read FExpires write FExpires; property LastModified: TDateTime read FLastModified write FLastModified; property Pragma: string read FPragma write FPragma; property TransferEncoding: string read FTransferEncoding write FTransferEncoding; end; TIdProxyConnectionInfo = class(TPersistent) protected FAuthentication: TIdAuthentication; FPassword: string; FPort: Integer; FServer: string; FUsername: string; FBasicByDefault: Boolean; procedure AssignTo(Destination: TPersistent); override; procedure SetProxyPort(const Value: Integer); procedure SetProxyServer(const Value: string); public procedure AfterConstruction; override; constructor Create; procedure Clear; destructor Destroy; override; procedure SetHeaders(Headers: TIdHeaderList); // property Authentication: TIdAuthentication read FAuthentication write FAuthentication; published property BasicAuthentication: boolean read FBasicByDefault write FBasicByDefault; property ProxyPassword: string read FPassword write FPassword; property ProxyPort: Integer read FPort write SetProxyPort; property ProxyServer: string read FServer write SetProxyServer; property ProxyUsername: string read FUsername write FUserName; end; TIdEntityRange = class(TCollectionItem) protected FStartPos: Int64; FEndPos: Int64; FSuffixLength: Int64; function GetText: String; procedure SetText(const AValue: String); public constructor Create(Collection: TCollection); override; published property StartPos: Int64 read FStartPos write FStartPos; property EndPos: Int64 read FEndPos write FEndPos; property SuffixLength: Int64 read FSuffixLength write FSuffixLength; property Text: String read GetText write SetText; end; TIdEntityRanges = class(TOwnedCollection) protected FUnits: String; function GetRange(Index: Integer): TIdEntityRange; procedure SetRange(Index: Integer; AValue: TIdEntityRange); function GetText: String; procedure SetText(const AValue: String); procedure SetUnits(const AValue: String); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdEntityRange; reintroduce; property Ranges[Index: Integer]: TIdEntityRange read GetRange write SetRange; default; published property Text: String read GetText write SetText; property Units: String read FUnits write SetUnits; end; TIdRequestHeaderInfo = class(TIdEntityHeaderInfo) protected FAccept: String; FAcceptCharSet: String; FAcceptEncoding: String; FAcceptLanguage: String; FExpect: String; FFrom: String; FPassword: String; FReferer: String; FUserAgent: String; FUserName: String; FHost: String; FProxyConnection: String; FRanges: TIdEntityRanges; FBasicByDefault: Boolean; FAuthentication: TIdAuthentication; FMethodOverride: String; // procedure AssignTo(Destination: TPersistent); override; procedure ProcessHeaders; override; procedure SetHeaders; override; function GetRange: String; procedure SetRange(const AValue: String); procedure SetRanges(AValue: TIdEntityRanges); public // constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Clear; override; property Authentication: TIdAuthentication read FAuthentication write FAuthentication; published property Accept: String read FAccept write FAccept; property AcceptCharSet: String read FAcceptCharSet write FAcceptCharSet; property AcceptEncoding: String read FAcceptEncoding write FAcceptEncoding; property AcceptLanguage: String read FAcceptLanguage write FAcceptLanguage; property BasicAuthentication: boolean read FBasicByDefault write FBasicByDefault; property Host: String read FHost write FHost; property From: String read FFrom write FFrom; property Password: String read FPassword write FPassword; property Referer: String read FReferer write FReferer; property UserAgent: String read FUserAgent write FUserAgent; property Username: String read FUsername write FUsername; property ProxyConnection: String read FProxyConnection write FProxyConnection; property Range: String read GetRange write SetRange; //deprecated 'Use Ranges property'; property Ranges: TIdEntityRanges read FRanges write SetRanges; property MethodOverride: String read FMethodOverride write FMethodOverride; end; TIdResponseHeaderInfo = class(TIdEntityHeaderInfo) protected FAcceptRanges: string; FLocation: string; FServer: string; FProxyConnection: string; FProxyAuthenticate: TIdHeaderList; FWWWAuthenticate: TIdHeaderList; // procedure SetProxyAuthenticate(const Value: TIdHeaderList); procedure SetWWWAuthenticate(const Value: TIdHeaderList); procedure SetAcceptRanges(const Value: string); procedure ProcessHeaders; override; procedure SetHeaders; override; public procedure Clear; override; constructor Create(AOwner: TPersistent); override; destructor Destroy; override; published property AcceptRanges: string read FAcceptRanges write SetAcceptRanges; property Location: string read FLocation write FLocation; property ProxyConnection: string read FProxyConnection write FProxyConnection; property ProxyAuthenticate: TIdHeaderList read FProxyAuthenticate write SetProxyAuthenticate; property Server: string read FServer write FServer; property WWWAuthenticate: TIdHeaderList read FWWWAuthenticate write SetWWWAuthenticate; end; TIdMetaHTTPEquiv = class(TIdEntityHeaderInfo) public procedure ProcessMetaHTTPEquiv(AStream: TStream); end; implementation uses SysUtils; const DefaultUserAgent = 'Mozilla/3.0 (compatible; Indy Library)'; {do not localize} { TIdEntityHeaderInfo } constructor TIdEntityHeaderInfo.Create(AOwner: TPersistent); begin inherited Create; FOwner := AOwner; FRawHeaders := TIdHeaderList.Create(QuoteHTTP); FRawHeaders.FoldLength := 1024; FCustomHeaders := TIdHeaderList.Create(QuoteHTTP); end; procedure TIdEntityHeaderInfo.AfterConstruction; begin inherited AfterConstruction; Clear; end; destructor TIdEntityHeaderInfo.Destroy; begin FreeAndNil(FRawHeaders); FreeAndNil(FCustomHeaders); inherited Destroy; end; procedure TIdEntityHeaderInfo.AssignTo(Destination: TPersistent); begin if Destination is TIdEntityHeaderInfo then begin with Destination as TIdEntityHeaderInfo do begin FRawHeaders.Assign(Self.FRawHeaders); FCacheControl := Self.FCacheControl; FCharSet := Self.FCharSet; FContentDisposition := Self.FContentDisposition; FContentEncoding := Self.FContentEncoding; FContentLanguage := Self.FContentLanguage; FContentType := Self.FContentType; FContentVersion := Self.FContentVersion; FContentLength := Self.FContentLength; FContentRangeEnd:= Self.FContentRangeEnd; FContentRangeStart:= Self.FContentRangeStart; FContentRangeInstanceLength := Self.FContentRangeInstanceLength; FContentRangeUnits := Self.FContentRangeUnits; FDate := Self.FDate; FETag := Self.FETag; FExpires := Self.FExpires; FLastModified := Self.FLastModified; end; end else begin inherited AssignTo(Destination); end; end; procedure TIdEntityHeaderInfo.Clear; begin FCacheControl := ''; FCharSet := ''; FConnection := ''; FContentVersion := ''; FContentDisposition := ''; FContentEncoding := ''; FContentLanguage := ''; { S.G. 20/4/2003 Was FContentType := 'Text/HTML' Shouldn't be set here but in response. Requests, by default, have NO content-type. This caused problems with some netscape servers } FContentType := ''; FContentLength := -1; FContentRangeStart := -1; FContentRangeEnd := -1; FContentRangeInstanceLength := -1; FContentRangeUnits := ''; FDate := 0; FLastModified := 0; FETag := ''; FExpires := 0; FRawHeaders.Clear; end; procedure TIdEntityHeaderInfo.ProcessHeaders; var LSecs: Int64; lValue: string; lCRange: string; lILength: string; begin with FRawHeaders do begin FCacheControl := Values['Cache-control']; {do not localize} FConnection := Values['Connection']; {do not localize} FContentVersion := Values['Content-Version']; {do not localize} FContentDisposition := Values['Content-Disposition']; {do not localize} FContentEncoding := Values['Content-Encoding']; {do not localize} FContentLanguage := Values['Content-Language']; {do not localize} ContentType := Values['Content-Type']; {do not localize} FContentLength := IndyStrToInt64(Values['Content-Length'], -1); {do not localize} FHasContentLength := FContentLength >= 0; FContentRangeStart := -1; FContentRangeEnd := -1; FContentRangeInstanceLength := -1; FContentRangeUnits := ''; { handle content-range headers, like: content-range: bytes 1-65536/102400 content-range: bytes */102400 content-range: bytes 1-65536/* } lValue := Values['Content-Range']; {do not localize} if lValue <> '' then begin // strip the bytes unit, and keep the range and instance info FContentRangeUnits := Fetch(lValue); lCRange := Fetch(lValue, '/'); lILength := Fetch(lValue); FContentRangeStart := IndyStrToInt64(Fetch(lCRange, '-'), -1); FContentRangeEnd := IndyStrToInt64(lCRange, -1); FContentRangeInstanceLength := IndyStrToInt64(lILength, -1); end; // RLebeau 03/04/2009: RFC 2616 Section 14.18 says: // // "A received message that does not have a Date header field MUST be // assigned one by the recipient if the message will be cached by that // recipient or gatewayed via a protocol which requires a Date." lValue := Values['Date']; {do not localize} if lValue <> '' then begin FDate := GMTToLocalDateTime(lValue); end else begin FDate := Now; end; FLastModified := GMTToLocalDateTime(Values['Last-Modified']); {do not localize} // RLebeau 01/23/2006 - IIS fix lValue := Values['Expires']; {do not localize} if IsNumeric(lValue) then begin // This is happening when expires is an integer number in seconds LSecs := IndyStrToInt64(lValue); // RLebeau 01/23/2005 - IIS sometimes sends an 'Expires: -1' header // should we be handling it as actually meaning "Now minus 1 second" instead? if LSecs >= 0 then begin FExpires := Now + (LSecs / SecsPerDay); end else begin FExpires := 0.0; end; end else begin // RLebeau 03/04/2009: RFC 2616 Section 14.21 says: // // "The format is an absolute date and time as defined by HTTP-date in // section 3.3.1; it MUST be in RFC 1123 date format: // // Expires = "Expires" ":" HTTP-date // // HTTP/1.1 clients and caches MUST treat other invalid date formats, // especially including the value "0", as in the past (i.e., "already // expired")." try FExpires := GMTToLocalDateTime(lValue); except FExpires := Now - (1 / SecsPerDay); end; end; FETag := Values['ETag']; {do not localize} FPragma := Values['Pragma']; {do not localize} FTransferEncoding := Values['Transfer-Encoding']; {do not localize} end; end; procedure TIdEntityHeaderInfo.SetHeaders; begin RawHeaders.Clear; with RawHeaders do begin if Length(FConnection) > 0 then begin Values['Connection'] := FConnection; {do not localize} end; if Length(FContentVersion) > 0 then begin Values['Content-Version'] := FContentVersion; {do not localize} end; if Length(FContentDisposition) > 0 then begin Values['Content-Disposition'] := FContentDisposition; {do not localize} end; if Length(FContentEncoding) > 0 then begin Values['Content-Encoding'] := FContentEncoding; {do not localize} end; if Length(FContentLanguage) > 0 then begin Values['Content-Language'] := FContentLanguage; {do not localize} end; if Length(FContentType) > 0 then begin Values['Content-Type'] := FContentType; {do not localize} Params['Content-Type', 'charset'] := FCharSet; {do not localize} end; if FContentLength >= 0 then begin Values['Content-Length'] := IntToStr(FContentLength); {do not localize} end; { removed setting Content-Range header for entities... deferred to response } if Length(FCacheControl) > 0 then begin Values['Cache-control'] := FCacheControl; {do not localize} end; if FDate > 0 then begin Values['Date'] := LocalDateTimeToHttpStr(FDate); {do not localize} end; if Length(FETag) > 0 then begin Values['ETag'] := FETag; {do not localize} end; if FExpires > 0 then begin Values['Expires'] := LocalDateTimeToHttpStr(FExpires); {do not localize} end; if Length(FPragma) > 0 then begin Values['Pragma'] := FPragma; {do not localize} end; if Length(FTransferEncoding) > 0 then begin Values['Transfer-Encoding'] := FTransferEncoding; {do not localize} end; if FCustomHeaders.Count > 0 then begin // append custom headers Text := Text + FCustomHeaders.Text; end; end; end; procedure TIdEntityHeaderInfo.SetCustomHeaders(const AValue: TIdHeaderList); begin FCustomHeaders.Assign(AValue); end; procedure TIdEntityHeaderInfo.SetContentLength(const AValue: Int64); begin FContentLength := AValue; FHasContentLength := FContentLength >= 0; end; procedure TIdEntityHeaderInfo.SetContentType(const AValue: String); var S, LCharSet: string; LComp: TComponent; begin if AValue <> '' then begin FContentType := RemoveHeaderEntry(AValue, 'charset', LCharSet, QuoteHTTP); {do not localize} {RLebeau: the ContentType property is streamed after the CharSet property, so do not overwrite it during streaming} LComp := OwnerComponent; if Assigned(LComp) and (csReading in LComp.ComponentState) then begin Exit; end; // RLebeau: per RFC 2616 Section 3.7.1: // // The "charset" parameter is used with some media types to define the // character set (section 3.4) of the data. When no explicit charset // parameter is provided by the sender, media subtypes of the "text" // type are defined to have a default charset value of "ISO-8859-1" when // received via HTTP. Data in character sets other than "ISO-8859-1" or // its subsets MUST be labeled with an appropriate charset value. See // section 3.4.1 for compatibility problems. // RLebeau: per RFC 3023 Sections 3.1, 3.3, 3.6, and 8.5: // // Conformant with [RFC2046], if a text/xml entity is received with // the charset parameter omitted, MIME processors and XML processors // MUST use the default charset value of "us-ascii"[ASCII]. In cases // where the XML MIME entity is transmitted via HTTP, the default // charset value is still "us-ascii". (Note: There is an // inconsistency between this specification and HTTP/1.1, which uses // ISO-8859-1[ISO8859] as the default for a historical reason. Since // XML is a new format, a new default should be chosen for better // I18N. US-ASCII was chosen, since it is the intersection of UTF-8 // and ISO-8859-1 and since it is already used by MIME.) // // ... // // The charset parameter of text/xml-external-parsed-entity is // handled the same as that of text/xml as described in Section 3.1 // // ... // // The following list applies to text/xml, text/xml-external-parsed- // entity, and XML-based media types under the top-level type "text" // that define the charset parameter according to this specification: // // - If the charset parameter is not specified, the default is "us- // ascii". The default of "iso-8859-1" in HTTP is explicitly // overridden. // // ... // // Omitting the charset parameter is NOT RECOMMENDED for text/xml. For // example, even if the contents of the XML MIME entity are UTF-16 or // UTF-8, or the XML MIME entity has an explicit encoding declaration, // XML and MIME processors MUST assume the charset is "us-ascii". if (LCharSet = '') and IsHeaderMediaType(FContentType, 'text') then begin {do not localize} S := ExtractHeaderMediaSubType(FContentType); if (PosInStrArray(S, ['xml', 'xml-external-parsed-entity'], False) >= 0) or TextEndsWith(S, '+xml') then begin {do not localize} LCharSet := 'us-ascii'; {do not localize} end else begin LCharSet := 'ISO-8859-1'; {do not localize} end; end; {RLebeau: override the current CharSet only if the header specifies a new value} if LCharSet <> '' then begin FCharSet := LCharSet; end; end else begin FContentType := ''; FCharSet := ''; end; end; function TIdEntityHeaderInfo.GetHasContentRange: Boolean; begin Result := (FContentRangeEnd >= 0); end; function TIdEntityHeaderInfo.GetHasContentRangeInstance: Boolean; begin Result := (FContentRangeInstanceLength >= 0); end; function TIdEntityHeaderInfo.GetOwner: TPersistent; begin Result := FOwner; end; type TPersistentAccess = class(TPersistent) end; function TIdEntityHeaderInfo.GetOwnerComponent: TComponent; var LOwner: TPersistent; begin Result := nil; LOwner := GetOwner; while LOwner <> nil do begin if LOwner is TComponent then begin Result := TComponent(LOwner); Exit; end; LOwner := TPersistentAccess(LOwner).GetOwner; end; end; { TIdProxyConnectionInfo } constructor TIdProxyConnectionInfo.Create; begin inherited Create; end; procedure TIdProxyConnectionInfo.AfterConstruction; begin inherited AfterConstruction; Clear; end; destructor TIdProxyConnectionInfo.Destroy; begin FreeAndNil(FAuthentication); inherited Destroy; end; procedure TIdProxyConnectionInfo.AssignTo(Destination: TPersistent); begin if Destination is TIdProxyConnectionInfo then begin with Destination as TIdProxyConnectionInfo do begin FPassword := Self.FPassword; FPort := Self.FPort; FServer := Self.FServer; FUsername := Self.FUsername; FBasicByDefault := Self.FBasicByDefault; end; end else begin inherited AssignTo(Destination); end; end; procedure TIdProxyConnectionInfo.Clear; begin FServer := ''; FUsername := ''; FPassword := ''; FPort := 0; end; procedure TIdProxyConnectionInfo.SetHeaders(Headers: TIdHeaderList); Var S: String; begin with Headers do begin if Assigned(Authentication) then begin S := Authentication.Authentication; if Length(S) > 0 then begin Values['Proxy-Authorization'] := S; {do not localize} end; end else begin // Use Basic authentication by default if FBasicByDefault then begin FAuthentication := TIdBasicAuthentication.Create; with Authentication do begin Params.Values['Username'] := Self.FUsername; {do not localize} Params.Values['Password'] := Self.FPassword; {do not localize} S := Authentication; end; if Length(S) > 0 then begin Values['Proxy-Authorization'] := S; {do not localize} end; end; end; end; end; procedure TIdProxyConnectionInfo.SetProxyPort(const Value: Integer); begin if Value <> FPort then begin FreeAndNil(FAuthentication); end; FPort := Value; end; procedure TIdProxyConnectionInfo.SetProxyServer(const Value: string); begin if not TextIsSame(Value, FServer) then begin FreeAndNil(FAuthentication); end; FServer := Value; end; { TIdEntityRange } constructor TIdEntityRange.Create(Collection: TCollection); begin inherited Create(Collection); FStartPos := -1; FEndPos := -1; FSuffixLength := -1; end; function TIdEntityRange.GetText: String; begin if (FStartPos >= 0) or (FEndPos >= 0) then begin if FEndPos >= 0 then begin Result := IntToStr(FStartPos) + '-' + IntToStr(FEndPos); {do not localize} end else begin Result := IntToStr(FStartPos) + '-'; {do not localize} end; end else if FSuffixLength >= 0 then begin Result := '-' + IntToStr(FSuffixLength); end else begin Result := ''; end; end; procedure TIdEntityRange.SetText(const AValue: String); var LValue, S: String; begin LValue := Trim(AValue); if LValue <> '' then begin S := Fetch(LValue, '-'); {do not localize} if S <> '' then begin FStartPos := StrToInt64Def(S, -1); FEndPos := StrToInt64Def(Fetch(LValue), -1); FSuffixLength := -1; end else begin FStartPos := -1; FEndPos := -1; FSuffixLength := StrToInt64Def(Fetch(LValue), -1); end; end else begin FStartPos := -1; FEndPos := -1; FSuffixLength := -1; end; end; { TIdEntityRanges } constructor TIdEntityRanges.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdEntityRange); FUnits := 'bytes'; {do not localize} end; function TIdEntityRanges.Add: TIdEntityRange; begin Result := TIdEntityRange(inherited Add); end; function TIdEntityRanges.GetRange(Index: Integer): TIdEntityRange; begin Result := TIdEntityRange(inherited GetItem(Index)); end; procedure TIdEntityRanges.SetRange(Index: Integer; AValue: TIdEntityRange); begin inherited SetItem(Index, AValue); end; function TIdEntityRanges.GetText: String; var I: Integer; S: String; begin Result := ''; for I := 0 to Count-1 do begin S := Ranges[I].Text; if S <> '' then begin if Result <> '' then begin Result := Result + ','; {do not localize} end; Result := Result + S; end; end; if Result <> '' then begin Result := FUnits + '=' + Result; {do not localize} end; end; procedure TIdEntityRanges.SetText(const AValue: String); var LUnits, LTmp: String; LRanges: TStringList; I: Integer; LRange: TIdEntityRange; begin LTmp := Trim(AValue); BeginUpdate; try Clear; if Pos('=', LTmp) > 0 then begin {do not localize} LUnits := Fetch(LTmp, '='); {do not localize} end; SetUnits(LUnits); LRanges := TStringList.Create; try SplitColumns(LTmp, LRanges, ','); {do not localize} for I := 0 to LRanges.Count-1 do begin LTmp := Trim(LRanges[I]); if LTmp <> '' then begin LRange := Add; try LRange.Text := LTmp; except LRange.Free; raise; end; end; end; finally LRanges.Free; end; finally EndUpdate; end; end; procedure TIdEntityRanges.SetUnits(const AValue: String); var LUnits: String; begin LUnits := Trim(AValue); if LUnits <> '' then begin FUnits := LUnits; end else begin FUnits := 'bytes'; {do not localize} end; end; { TIdRequestHeaderInfo } constructor TIdRequestHeaderInfo.Create(AOwner: TPersistent); begin inherited Create(AOwner); FRanges := TIdEntityRanges.Create(Self); end; destructor TIdRequestHeaderInfo.Destroy; begin FreeAndNil(FAuthentication); FreeAndNil(FRanges); inherited Destroy; end; procedure TIdRequestHeaderInfo.ProcessHeaders; begin inherited ProcessHeaders; with FRawHeaders do begin FAccept := Values['Accept']; {do not localize} FAcceptCharSet := Values['Accept-Charset']; {do not localize} FAcceptEncoding := Values['Accept-Encoding']; {do not localize} FAcceptLanguage := Values['Accept-Language']; {do not localize} FHost := Values['Host']; {do not localize} FFrom := Values['From']; {do not localize} FReferer := Values['Referer']; {do not localize} FUserAgent := Values['User-Agent']; {do not localize} FRanges.Text := Values['Range']; {do not localize} FMethodOverride := Values['X-HTTP-Method-Override']; {do not localize} end; end; procedure TIdRequestHeaderInfo.AssignTo(Destination: TPersistent); begin if Destination is TIdRequestHeaderInfo then begin with Destination as TIdRequestHeaderInfo do begin FAccept := Self.FAccept; FAcceptCharSet := Self.FAcceptCharset; FAcceptEncoding := Self.FAcceptEncoding; FAcceptLanguage := Self.FAcceptLanguage; FFrom := Self.FFrom; FUsername := Self.FUsername; FPassword := Self.FPassword; FReferer := Self.FReferer; FUserAgent := Self.FUserAgent; FBasicByDefault := Self.FBasicByDefault; FRanges.Assign(Self.FRanges); FMethodOverride := Self.FMethodOverride; // TODO: omitted intentionally? // FHost := Self.FHost; // FProxyConnection := Self.FProxyConnection; end; end else begin inherited AssignTo(Destination); end; end; procedure TIdRequestHeaderInfo.Clear; begin FAccept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; // 'text/html, */*'; {do not localize} FAcceptCharSet := ''; FUserAgent := DefaultUserAgent; FBasicByDefault := false; FRanges.Text := ''; FMethodOverride := ''; // TODO: omitted intentionally? // FAcceptEncoding := ''; // FAcceptLanguage := ''; // FHost := ''; // FFrom := ''; // FPassword := ''; // FUsername := ''; // FReferer := ''; // FProxyConnection := ''; inherited Clear; end; function TIdRequestHeaderInfo.GetRange: String; begin Result := FRanges.Text; end; procedure TIdRequestHeaderInfo.SetRange(const AValue: String); begin FRanges.Text := AValue; end; procedure TIdRequestHeaderInfo.SetRanges(AValue: TIdEntityRanges); begin FRanges.Assign(AValue); end; procedure TIdRequestHeaderInfo.SetHeaders; var S: String; begin inherited SetHeaders; with RawHeaders do begin if Length(FProxyConnection) > 0 then begin Values['Proxy-Connection'] := FProxyConnection; {do not localize} end; if Length(FHost) > 0 then begin Values['Host'] := FHost; {do not localize} end; if Length(FAccept) > 0 then begin Values['Accept'] := FAccept; {do not localize} end; if Length(FAcceptCharset) > 0 then begin Values['Accept-Charset'] := FAcceptCharSet; {do not localize} end; if Length(FAcceptEncoding) > 0 then begin Values['Accept-Encoding'] := FAcceptEncoding; {do not localize} end; if Length(FAcceptLanguage) > 0 then begin Values['Accept-Language'] := FAcceptLanguage; {do not localize} end; if Length(FFrom) > 0 then begin Values['From'] := FFrom; {do not localize} end; if Length(FReferer) > 0 then begin Values['Referer'] := FReferer; {do not localize} end; if Length(FUserAgent) > 0 then begin Values['User-Agent'] := FUserAgent; {do not localize} end; S := FRanges.Text; if Length(S) > 0 then begin Values['Range'] := S; {do not localize} end; // use 'Last-Modified' entity header in the conditional request if FLastModified > 0 then begin Values['If-Modified-Since'] := LocalDateTimeToHttpStr(FLastModified); {do not localize} end; if Assigned(Authentication) then begin S := Authentication.Authentication; if Length(S) > 0 then begin Values['Authorization'] := S; {do not localize} end; end else begin if FBasicByDefault then begin Authentication := TIdBasicAuthentication.Create; with Authentication do begin Params.Values['Username'] := Self.FUserName; {do not localize} Params.Values['Password'] := Self.FPassword; {do not localize} S := Authentication; end; if Length(S) > 0 then begin Values['Authorization'] := S; {do not localize} end; end; end; if Length(FMethodOverride) > 0 then begin Values['X-HTTP-Method-Override'] := FMethodOverride; {Do not Localize} end; end; end; { TIdResponseHeaderInfo } constructor TIdResponseHeaderInfo.Create(AOwner: TPersistent); begin inherited Create(AOwner); // RLebeau 5/15/2012: don't set any default ContentType, make the user set it... FContentType := ''; FCharSet := ''; FWWWAuthenticate := TIdHeaderList.Create(QuoteHTTP); FProxyAuthenticate := TIdHeaderList.Create(QuoteHTTP); FAcceptRanges := ''; end; destructor TIdResponseHeaderInfo.Destroy; begin FreeAndNil(FWWWAuthenticate); FreeAndNil(FProxyAuthenticate); inherited Destroy; end; procedure TIdResponseHeaderInfo.SetProxyAuthenticate(const Value: TIdHeaderList); begin FProxyAuthenticate.Assign(Value); end; procedure TIdResponseHeaderInfo.SetWWWAuthenticate(const Value: TIdHeaderList); begin FWWWAuthenticate.Assign(Value); end; procedure TIdResponseHeaderInfo.ProcessHeaders; begin inherited ProcessHeaders; with FRawHeaders do begin; FLocation := Values['Location']; {do not localize} FServer := Values['Server']; {do not localize} FProxyConnection := Values['Proxy-Connection']; {do not localize} FWWWAuthenticate.Clear; Extract('WWW-Authenticate', FWWWAuthenticate); {do not localize} FProxyAuthenticate.Clear; Extract('Proxy-Authenticate', FProxyAuthenticate);{do not localize} FAcceptRanges := Values['Accept-Ranges']; {do not localize} end; end; procedure TIdResponseHeaderInfo.SetHeaders; var sUnits: String; sCR: String; sCI: String; begin inherited SetHeaders; { setting the content-range header is allowed in server responses... moved here TIdEntityHeaderInfo } if HasContentRange or HasContentRangeInstance then begin sUnits := iif(FContentRangeUnits <> '', FContentRangeUnits, 'bytes'); {do not localize} sCR := iif(HasContentRange, IndyFormat('%d-%d', [FContentRangeStart, FContentRangeEnd]), '*'); {do not localize} sCI := iif(HasContentRangeInstance, IndyFormat('%d', [FContentRangeInstanceLength]), '*'); {do not localize} RawHeaders.Values['Content-Range'] := sUnits + ' ' + sCR + '/' + sCI; end; if Length(FAcceptRanges) > 0 then begin RawHeaders.Values['Accept-Ranges'] := FAcceptRanges; end; if FLastModified > 0 then begin RawHeaders.Values['Last-Modified'] := DateTimeGMTToHttpStr(FLastModified); {do not localize} end; end; procedure TIdResponseHeaderInfo.Clear; begin inherited Clear; // RLebeau 5/15/2012: don't set any default ContentType, make the user set it... FContentType := ''; FCharSet := ''; FLocation := ''; FServer := ''; FAcceptRanges := ''; if Assigned(FProxyAuthenticate) then begin FProxyAuthenticate.Clear; end; if Assigned(FWWWAuthenticate) then begin FWWWAuthenticate.Clear; end; end; procedure TIdResponseHeaderInfo.SetAcceptRanges(const Value: string); begin FAcceptRanges := Value; end; { TIdMetaHTTPEquiv } procedure TIdMetaHTTPEquiv.ProcessMetaHTTPEquiv(AStream: TStream); begin ParseMetaHTTPEquiv(AStream, RawHeaders); if FRawHeaders.Count > 0 then begin ProcessHeaders; end; end; end.
unit aeGeometry; interface uses aeSceneNode, types, aeMesh, System.Generics.Collections, aeMaterial, aeMaths, aeOBB, aeConst, aeBoundingVolume, aetypes, aeLoggingManager; type TaeGeometry = class(TaeSceneNode) private _meshes: TList<TaeMesh>; _material: TaeMaterial; _MID: int64; _boundingvolume_obb: TaeOBB; /// <summary> /// This method intersects a given mesh with a ray, by checking every triangle for intersection. /// </summary> function IntersectTriangles(ray: TaeRay3; m: TaeMesh; var t: single): boolean; public property Material: TaeMaterial read _material write _material; /// <summary> /// Material ID. Can be asigned at will. /// </summary> property MID: int64 read _MID write _MID; constructor Create(name: string); overload; constructor Create; overload; destructor Destroy; override; procedure addMesh(m: TaeMesh; lod: TaeMeshLevelOfDetail = AE_MESH_LOD_HIGH); function getMeshes: TList<TaeMesh>; function GetMesh(lod: TaeMeshLevelOfDetail = AE_MESH_LOD_HIGH): TaeMesh; function Clone: TaeGeometry; procedure SetRenderPrimitive(prim: Cardinal); function GetTriangleCount: Cardinal; /// <remarks> /// Updates the bounding volume Data. /// </remarks> function updateBoundingVolume: boolean; function getBoundingVolume: TaeOBB; function Intersect(other: TaeGeometry): boolean; overload; function Intersect(ray: TaeRay3): boolean; overload; end; implementation { TaeGeometry } constructor TaeGeometry.Create(name: string); begin inherited Create(name); self._meshes := TList<TaeMesh>.Create; self._material := TaeMaterial.Create; self._NodeType := AE_SCENENODE_TYPE_GEOMETRY; self._boundingvolume_obb := TaeOBB.Create; end; constructor TaeGeometry.Create; begin inherited; self._meshes := TList<TaeMesh>.Create; self._material := TaeMaterial.Create; self._NodeType := AE_SCENENODE_TYPE_GEOMETRY; self._boundingvolume_obb := TaeOBB.Create; end; destructor TaeGeometry.Destroy; begin self._meshes.Free; self._material.Free; self._boundingvolume_obb.Free; inherited; end; function TaeGeometry.Clone: TaeGeometry; var i: Integer; begin result := TaeGeometry.Create(self._name); for i := 0 to self.getMeshes.Count - 1 do result.addMesh(self._meshes[i]); result.Material.Color.setColor(self.Material.Color.getColor); result.Material.Rendermode := self.Material.Rendermode; result.GetLocalTransform.CopyTransformFrom(self.GetLocalTransform); end; function TaeGeometry.GetMesh(lod: TaeMeshLevelOfDetail): TaeMesh; var i: Integer; begin if (self._meshes.Count > 0) then begin for i := 0 to self._meshes.Count - 1 do if (self._meshes[i].GetLOD = lod) then result := self._meshes[i]; // no mesh with that LOD found. We return the first we have. if (result = nil) then result := self._meshes[0]; end else begin AE_LOGGING.AddEntry('TaeGeometry.GetMesh() : No mesh attached to return!', AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); end; end; function TaeGeometry.updateBoundingVolume: boolean; var mesh4bounding: TaeMesh; begin mesh4bounding := self.GetMesh(AE_MESH_LOD_HIGH); if (mesh4bounding <> nil) then begin if (mesh4bounding.GetVertexBuffer <> nil) and (mesh4bounding.GetindexBuffer <> nil) then begin if (mesh4bounding.GetVertexBuffer.Count > 2) and (mesh4bounding.GetindexBuffer.Count > 2) then begin result := self._boundingvolume_obb.calculateBoundingVolume(mesh4bounding.GetVertexIndexBuffer, true); end; end else begin AE_LOGGING.AddEntry('TaeGeometry.updateBoundingVolume() : Either indices or vertices are not assigned! Cannot calculate bounding volume!', AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); result := false; end; end else begin AE_LOGGING.AddEntry('TaeGeometry.updateBoundingVolume() : No mesh attached, cannot calculate BoundingVolume!', AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); end; end; procedure TaeGeometry.addMesh(m: TaeMesh; lod: TaeMeshLevelOfDetail = AE_MESH_LOD_HIGH); begin m.SetLOD(lod); self._meshes.Add(m); end; function TaeGeometry.getBoundingVolume: TaeOBB; begin result := self._boundingvolume_obb; end; function TaeGeometry.getMeshes: TList<TaeMesh>; begin result := self._meshes; end; function TaeGeometry.GetTriangleCount: Cardinal; var i: Integer; begin result := 0; for i := 0 to self._meshes.Count - 1 do begin if (self._meshes[i].GetVertexBuffer <> nil) then result := result + (self._meshes[i].GetVertexBuffer.Count div 3); end; end; function TaeGeometry.Intersect(ray: TaeRay3): boolean; var i: Integer; t: single; begin for i := 0 to self._meshes.Count - 1 do begin result := self._boundingvolume_obb.Intersect(ray, self.GetWorldTransformationMatrix); if (result = true) then begin result := self.IntersectTriangles(ray, self._meshes[i], t); end; end; end; function TaeGeometry.IntersectTriangles(ray: TaeRay3; m: TaeMesh; var t: single): boolean; var i: Integer; _v0, _v1, _v2: TVectorArray; v0, v1, v2: TPoint3D; indexCount, indexPos, indexValue: word; worldTransformMatrix: TaeMatrix44; tri: TaeTriangle; vib: TaeVertexIndexBuffer; begin vib := m.GetVertexIndexBuffer; if (vib.vertexBuffer <> nil) and (vib.indexBuffer <> nil) then begin try vib.vertexBuffer.Lock; vib.indexBuffer.Lock; indexCount := vib.indexBuffer.Count; indexPos := 0; t := 0.0; if (indexCount > 0) and (vib.vertexBuffer.Count > 0) then begin result := false; worldTransformMatrix := self.GetWorldTransformationMatrix; // loop all triangles... while (indexPos < indexCount) do begin indexValue := vib.indexBuffer.GetIndex(indexPos); // get vertices of a triangle _v0 := vib.vertexBuffer.GetVector(indexValue); // _v0 := TaeTVectorArrayPointer(dword(meshDataPointer) + (indexValue * 12))^; v0.Create(_v0[0], _v0[1], _v0[2]); indexValue := vib.indexBuffer.GetIndex(indexPos + 1); _v1 := vib.vertexBuffer.GetVector(indexValue); // _v1 := TaeTVectorArrayPointer(dword(meshDataPointer) + ((indexValue) * 12))^; v1.Create(_v1[0], _v1[1], _v1[2]); indexValue := vib.indexBuffer.GetIndex(indexPos + 2); _v2 := vib.vertexBuffer.GetVector(indexValue); // _v2 := TaeTVectorArrayPointer(dword(meshDataPointer) + ((indexValue) * 12))^; v2.Create(_v2[0], _v2[1], _v2[2]); tri.Create(v0, v1, v2); tri := tri * worldTransformMatrix; indexPos := indexPos + 3; // we got the transformed triangle... now we need to test it for an intersection! // Möller–Trumbore intersection algorithm result := tri.Intersect(ray, t); if (result) then exit; end; end; finally vib.indexBuffer.Unlock; vib.vertexBuffer.Unlock; end; end; end; procedure TaeGeometry.SetRenderPrimitive(prim: Cardinal); var i: Integer; begin for i := 0 to self._meshes.Count - 1 do self._meshes[i].SetRenderPrimitive(prim); end; function TaeGeometry.Intersect(other: TaeGeometry): boolean; begin end; end.
unit Providers.Mascara.Telefone; interface uses Providers.Mascaras.Intf, System.MaskUtils, System.SysUtils; type TMascaraTelefone = class(TInterfacedObject, IMascaras) private procedure RemoveParenteses(var Value: string); public function ExecMask(Value: string): string; end; implementation { TMascaraTelefone } function TMascaraTelefone.ExecMask(Value: string): string; begin RemoveParenteses(Value); Result := FormatMaskText('\(00\)0000\-0000;0;', Value); end; procedure TMascaraTelefone.RemoveParenteses(var Value: string); begin Delete(Value, AnsiPos('-', Value), 1); Delete(Value, AnsiPos('-', Value), 1); Delete(Value, AnsiPos('(', Value), 1); Delete(Value, AnsiPos(')', Value), 1); end; end.
{$MODE OBJFPC} program HashValue; uses Math; const InputFile = 'HASH.INP'; OutputFile = 'HASH.OUT'; maxM = 2000; maxN = 5000; maxR = 32; type TNumber = array[0..maxM - 1] of Integer; TNumberR = array[0..maxM - 1] of Extended; TIndex = array[1..maxN] of Integer; PIndex = ^TIndex; var a: array[1..maxN] of TNumber; n, m, modulus: Integer; x, y: TIndex; p, q: PIndex; code: array[1..maxN] of Integer; res: Integer; procedure StrToNumber(const s: AnsiString; var x: TNumber); var i: Integer; begin for i := Length(s) downto 1 do x[Length(s) - i] := Ord(s[i]) - Ord('0'); FillDWord(x[Length(s)], maxM - Length(s), 0); end; function Check(const x, y: TNumber; r, s: Integer): Boolean; const hm = 1234567; var i: Integer; r1, r2: Integer; begin r1 := 0; r2 := 0; for i := maxM - 1 downto 0 do begin r1 := (r1 * r + x[i]) mod hm; r2 := (r2 * s + y[i]) mod hm; end; Result := r1 = r2; if not Result then WriteLn(r1, ' ', r2); end; procedure Convert(const x: TNumber; var y: TNumber; r, s: Integer); var d, k: Integer; pow, logsr: Extended; rnum: TNumberR; ipart, fpart: Extended; begin FillChar(rnum, SizeOf(rnum), 0); logsr := logn(s, r); for d := maxM - 1 downto 0 do if x[d] <> 0 then begin pow := d * logsr; k := Trunc(pow); rnum[k] := rnum[k] + x[d] * Power(s, pow - k); end; for d := maxM - 1 downto 0 do begin ipart := Int(rnum[d]); fpart := rnum[d] - ipart; y[d] := Round(ipart); if d > 0 then rnum[d - 1] := rnum[d - 1] + fpart * s else //d = 0 if fpart > 0.5 then Inc(y[d]); end; for d := 0 to maxM - 2 do begin Inc(y[d + 1], y[d] div s); y[d] := y[d] mod s; end; if not Check(x, y, r, s) then begin k := maxM - 1; while (k >= 0) and (x[k] = 0) do Dec(k); WriteLn(k); end; end; procedure Enter; var f: TextFile; s: AnsiString; temp: TNumber; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n, modulus); Inc(modulus); for i := 1 to n do begin ReadLn(f, s); StrToNumber(s, temp); Convert(temp, a[i], 10, modulus); end; finally CloseFile(f); end; end; procedure Init2; var i: Integer; begin FillDWord(code[1], n, 0); for i := 1 to n do x[i] := i; end; function Solve: Integer; var i, j, i1: Integer; count: array[0..maxR - 1] of Integer; c: Integer; prev, k: Integer; r: PIndex; begin p := @x; q := @y; for j := 0 to maxM - 1 do begin FillChar(count, SizeOf(count), 0); for i := 1 to n do Inc(count[a[i, j]]); for c := 1 to modulus - 1 do Inc(count[c], count[pred(c)]); for i := n downto 1 do begin c := a[p^[i], j]; q^[count[c]] := p^[i]; Dec(count[c]); end; prev := -1; c := -1; k := 0; for i := 1 to n do begin i1 := q^[i]; if (a[i1, j] <> c) or (code[i1] <> prev) then begin c := a[i1, j]; prev := code[i1]; Inc(k); end; code[i1] := k; end; if k = n then Exit(j + 1); r := p; p := q; q := r; end; Result := 0; end; procedure PrintResult; var f: TextFile; begin AssignFile(f, OutputFile); Rewrite(f); try Write(f, res); finally CloseFile(f); end; end; begin Enter; Init2; res := Solve; PrintResult; end. 4 2 65 40 20 37
unit WinSockRDOConnection; interface uses SmartThreads, Classes, ComObj, Windows, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces, SocketComp, SyncObjs, RDOQueries; type TWinSockRDOConnection = {$IFDEF AutoServer} class(TAutoObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection) {$ELSE} class(TInterfacedObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection) {$ENDIF} private fConnected : boolean; fPort : integer; fServer : string; fUnsentQueries : TList; fSentQueries : TList; fSenderThread : TSmartThread; fMsgLoopThread : TSmartThread; fUnsentQueriesLock : TCriticalSection; fSentQueriesLock : TCriticalSection; fSocketComponent : TClientSocket; fReceivedData : TQueryStream; fConnectionEvent : THandle; fUnsentQueryWaiting : THandle; fQueryServer : IRDOQueryServer; fQueryQueue : TList; fQueryWaiting : THandle; fQueryQueueLock : TCriticalSection; fQueryThreads : TList; fMaxQueryThreads : integer; fTerminateEvent : THandle; fOnConnect : TRDOClientConnectEvent; fOnDisconnect : TRDOClientDisconnectEvent; procedure DoRead(Sender : TObject; Socket : TCustomWinSocket); procedure HandleError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer); procedure HandleConnect(Sender : TObject; Socket : TCustomWinSocket); procedure HandleDisconnect(Sender : TObject; Socket : TCustomWinSocket); protected function Get_Server : WideString; safecall; procedure Set_Server(const Value : WideString); safecall; function Get_Port : Integer; safecall; procedure Set_Port(Value : Integer); safecall; function Connect(TimeOut : Integer) : WordBool; safecall; procedure Disconnect; safecall; protected procedure SetQueryServer(const QueryServer : IRDOQueryServer); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads(MaxQueryThreads : integer); public function Alive : boolean; function SendReceive(Query : TRDOQuery; out ErrorCode : integer; TimeOut : integer) : TRDOQuery; stdcall; procedure Send(Query : TRDOQuery); stdcall; function GetLocalAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; function GetOnConnect : TRDOClientConnectEvent; procedure SetOnConnect(OnConnectHandler : TRDOClientConnectEvent); function GetOnDisconnect : TRDOClientDisconnectEvent; procedure SetOnDisconnect(OnDisconnectHandler : TRDOClientDisconnectEvent); {$IFDEF AutoServer} protected procedure Initialize; override; {$ELSE} public constructor Create; {$ENDIF} destructor Destroy; override; end; implementation uses {$IFDEF AutoServer} ComServ, {$ENDIF} SysUtils, WinSock, RDOUtils, RDOProtocol, {$IFDEF Logs} LogFile, {$ENDIF} ErrorCodes; // Query id generation routines and variables const DefRDOPort = 5000; const DefMaxQueryThreads = 5; var LastQueryId : word; function GenerateQueryId : integer; begin Result := LastQueryId; LastQueryId := (LastQueryId + 1) mod 65536 end; type PQueryToSend = ^TQueryToSend; TQueryToSend = record Query : TRDOQuery; WaitForAnsw : boolean; Result : TRDOQuery; Event : THandle; ErrorCode : integer; end; // Delphi classes associated to the threads in charge of the connection type TSenderThread = class(TSmartThread) private fConnection : TWinSockRDOConnection; constructor Create(theConnection : TWinSockRDOConnection); protected procedure Execute; override; end; type TMsgLoopThread = class(TSmartThread) private fConnection : TWinSockRDOConnection; public constructor Create(theConnection : TWinSockRDOConnection); protected procedure Execute; override; public property Connection : TWinSockRDOConnection read fConnection write fConnection; private procedure TerminateLoop(Sender : TObject); end; type TServicingQueryThread = class(TSmartThread) private fConnection : TWinSockRDOConnection; fQueryStatus : integer; public constructor Create(theConnection : TWinSockRDOConnection); procedure Execute; override; end; // TSenderThread constructor TSenderThread.Create(theConnection : TWinSockRDOConnection); begin inherited Create(true); fConnection := theConnection; Resume; end; procedure TSenderThread.Execute; var QueryToSend : PQueryToSend; SenderThreadEvents : array [ 1 .. 2 ] of THandle; begin with fConnection do begin SenderThreadEvents[ 1 ] := fUnsentQueryWaiting; SenderThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects(2, @SenderThreadEvents[ 1 ], false, INFINITE); if not Terminated then begin fUnsentQueriesLock.Acquire; try if fUnsentQueries.Count <> 0 then begin QueryToSend := fUnsentQueries[ 0 ]; fUnsentQueries.Delete(0) end else begin QueryToSend := nil; ResetEvent(fUnsentQueryWaiting) end finally fUnsentQueriesLock.Release end; end else QueryToSend := nil; if QueryToSend <> nil then if QueryToSend.WaitForAnsw then begin fSentQueriesLock.Acquire; try fSentQueries.Add(QueryToSend) finally fSentQueriesLock.Release end; try RDOUtils.SendQuery(QueryToSend.Query, fSocketComponent.Socket); except {$IFDEF Logs} LogThis('Error sending query'); {$ENDIF} fSentQueriesLock.Acquire; try fSentQueries.Remove(QueryToSend) finally fSentQueriesLock.Release end; QueryToSend.ErrorCode := errSendError; SetEvent(QueryToSend.Event) end end else begin try RDOUtils.SendQuery(QueryToSend.Query, fSocketComponent.Socket); except {$IFDEF Logs} LogThis('Error sending query'); {$ENDIF} end; QueryToSend.Query.Free; Dispose(QueryToSend); end; end end end; // TMsgLoopThread constructor TMsgLoopThread.Create(theConnection : TWinSockRDOConnection); begin inherited Create(true); fConnection := theConnection; FreeOnTerminate := true; OnTerminate := TerminateLoop; Resume; end; procedure TMsgLoopThread.Execute; var Msg : TMsg; begin try try fConnection.fSocketComponent.Open; except Terminate; {$IFDEF Logs} LogThis('Error establishing connection') {$ENDIF} end; while not Terminated and (fConnection <> nil) do if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then try DispatchMessage(Msg); except // aguanta como un macho!!! end else if fConnection <> nil then MsgWaitForMultipleObjects(1, fConnection.fTerminateEvent, false, INFINITE, QS_ALLINPUT) except // aguanta como un macho!!! end; end; procedure TMsgLoopThread.TerminateLoop(Sender : TObject); begin if fConnection <> nil then begin fConnection.fMsgLoopThread := nil; fConnection := nil; end; end; // TServicingQueryThread constructor TServicingQueryThread.Create(theConnection : TWinSockRDOConnection); begin fConnection := theConnection; inherited Create(false) end; procedure TServicingQueryThread.Execute; var QueryResult : TRDOQuery; QueryToService : TRDOQuery; QueryThreadEvents : array [ 1 .. 2 ] of THandle; begin with fConnection do begin QueryThreadEvents[ 1 ] := fQueryWaiting; QueryThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects(2, @QueryThreadEvents[ 1 ], false, INFINITE); if not Terminated then begin fQueryQueueLock.Acquire; try if fQueryQueue.Count <> 0 then begin QueryToService := fQueryQueue[ 0 ]; fQueryQueue.Delete(0) end else begin QueryToService := nil; ResetEvent(fQueryWaiting) end finally fQueryQueueLock.Release end; end else QueryToService := nil; if QueryToService <> nil then begin try QueryResult := fQueryServer.ExecQuery(QueryToService, integer(fSocketComponent.Socket), fQueryStatus); finally QueryToService.Free; end; if QueryResult <> nil then try try RDOUtils.SendQuery(QueryResult, fSocketComponent.Socket); finally QueryResult.Free; end; {$IFDEF Logs} LogThis('Result : ' + QueryResult.ToStr); {$ENDIF} except {$IFDEF Logs} LogThis('Error sending query result') {$ENDIF} end else begin {$IFDEF Logs} LogThis('No result') {$ENDIF} end end end end end; // TWinSockRDOConnection {$IFDEF AutoServer} procedure TWinSockRDOConnection.Initialize; {$ELSE} constructor TWinSockRDOConnection.Create; {$ENDIF} begin inherited; fSocketComponent := TClientSocket.Create(nil); fSocketComponent.Active := false; fUnsentQueriesLock := TCriticalSection.Create; fSentQueriesLock := TCriticalSection.Create; fUnsentQueries := TList.Create; fSentQueries := TList.Create; fPort := DefRDOPort; fUnsentQueryWaiting := CreateEvent(nil, true, false, nil); fQueryQueue := TList.Create; //fQueryThreads := TList.Create; //fMaxQueryThreads := DefMaxQueryThreads; fQueryWaiting := CreateEvent(nil, true, false, nil); fQueryQueueLock := TCriticalSection.Create; fTerminateEvent := CreateEvent(nil, true, false, nil); fReceivedData := TQueryStream.Create; end; destructor TWinSockRDOConnection.Destroy; procedure FreeQueryQueue; var QueryIdx : integer; begin for QueryIdx := 0 to fQueryQueue.Count - 1 do TRDOQuery(fQueryQueue[QueryIdx]).Free; fQueryQueue.Free; end; begin Disconnect; fUnsentQueriesLock.Free; fSentQueriesLock.Free; fSocketComponent.Free; fUnsentQueries.Free; fSentQueries.Free; CloseHandle(fUnsentQueryWaiting); FreeQueryQueue; CloseHandle(fQueryWaiting); fQueryQueueLock.Free; CloseHandle(fTerminateEvent); inherited end; function TWinSockRDOConnection.Get_Server : WideString; begin Result := fServer end; procedure TWinSockRDOConnection.Set_Server(const Value : WideString); begin fServer := Value end; function TWinSockRDOConnection.Get_Port : Integer; begin Result := fPort end; procedure TWinSockRDOConnection.Set_Port(Value : Integer); begin fPort := Value end; function TWinSockRDOConnection.GetLocalHost : string; begin Result := fSocketComponent.Socket.LocalHost end; function TWinSockRDOConnection.GetLocalAddress : string; begin Result := fSocketComponent.Socket.LocalAddress end; function TWinSockRDOConnection.GetLocalPort : integer; begin Result := fSocketComponent.Socket.LocalPort end; function TWinSockRDOConnection.GetOnConnect : TRDOClientConnectEvent; begin result := fOnConnect; end; procedure TWinSockRDOConnection.SetOnConnect(OnConnectHandler : TRDOClientConnectEvent); begin fOnConnect := OnConnectHandler end; function TWinSockRDOConnection.GetOnDisconnect : TRDOClientDisconnectEvent; begin result := fOnDisconnect; end; procedure TWinSockRDOConnection.SetOnDisconnect(OnDisconnectHandler : TRDOClientDisconnectEvent); begin fOnDisconnect := OnDisconnectHandler end; function TWinSockRDOConnection.Connect(TimeOut : Integer) : WordBool; var WaitRes : cardinal; begin Result := true; try ResetEvent(fTerminateEvent); with fSocketComponent do if not Active then begin //ClientType := ctNonBlocking; if inet_addr(PChar(fServer)) = u_long(INADDR_NONE) // >> Delphi 4 then Host := fServer else Address := fServer; Port := fPort; OnRead := DoRead; OnError := HandleError; OnConnect := HandleConnect; OnDisconnect := HandleDisconnect; fConnectionEvent := CreateEvent(nil, false, false, nil); try fMsgLoopThread := TMsgLoopThread.Create(Self); WaitRes := WaitForSingleObject(fConnectionEvent, TimeOut); if WaitRes = WAIT_OBJECT_0 then begin fSenderThread := TSenderThread.Create(Self); SetMaxQueryThreads(fMaxQueryThreads); end else begin fMsgLoopThread.Terminate; SetEvent(fTerminateEvent); fMsgLoopThread := nil end; Result := WaitRes = WAIT_OBJECT_0 finally CloseHandle(fConnectionEvent) end end except Disconnect; Result := false end end; procedure TWinSockRDOConnection.Disconnect; procedure FreeQueryThreads; var ThreadIdx : integer; aQueryThread : TSmartThread; begin for ThreadIdx := 0 to fQueryThreads.Count - 1 do begin aQueryThread := TSmartThread(fQueryThreads[ ThreadIdx ]); aQueryThread.Free end; fQueryThreads.Free; end; begin if fMsgLoopThread <> nil then begin TMsgLoopThread(fMsgLoopThread).fConnection := nil; fMsgLoopThread := nil end; SetEvent(fTerminateEvent); if fSocketComponent.Active then try fSocketComponent.Close; except {$IFDEF Logs} LogThis('Error closing connection') {$ENDIF} end; if fSenderThread <> nil then begin fSenderThread.Free; fSenderThread := nil end; if fQueryThreads <> nil then begin FreeQueryThreads; fQueryThreads := nil end; end; procedure TWinSockRDOConnection.SetQueryServer(const QueryServer : IRDOQueryServer); begin fQueryServer := QueryServer end; function TWinSockRDOConnection.GetMaxQueryThreads : integer; begin Result := fMaxQueryThreads end; procedure TWinSockRDOConnection.SetMaxQueryThreads(MaxQueryThreads : integer); var i : integer; begin if fConnected then begin if (fQueryThreads = nil) and (MaxQueryThreads > 0) then begin fMaxQueryThreads := MaxQueryThreads; fQueryThreads := TList.Create; for i := 1 to fMaxQueryThreads do fQueryThreads.Add(TServicingQueryThread.Create(Self)); end; end else fMaxQueryThreads := MaxQueryThreads; end; function TWinSockRDOConnection.Alive : boolean; begin result := fConnected; end; function TWinSockRDOConnection.SendReceive(Query : TRDOQuery; out ErrorCode : integer; TimeOut : integer) : TRDOQuery; var theQuery : PQueryToSend; Events : array [0..1] of THandle; begin result := nil; if fConnected then try New(theQuery); try Query.Id := GenerateQueryId; theQuery.Query := Query; {$IFDEF Logs} LogThis('Sending and waiting: ' + Query.ToStr); {$ENDIF} theQuery.WaitForAnsw := true; theQuery.Result := nil; theQuery.Event := CreateEvent(nil, false, false, nil); try theQuery.ErrorCode := errNoError; try fUnsentQueriesLock.Acquire; try fUnsentQueries.Add(theQuery); if fUnsentQueries.Count = 1 then SetEvent(fUnsentQueryWaiting); finally fUnsentQueriesLock.Release; end; Events[0] := theQuery.Event; Events[1] := fTerminateEvent; case WaitForMultipleObjects(2, @Events[0], false, TimeOut) of WAIT_OBJECT_0 : begin result := theQuery.Result; ErrorCode := theQuery.ErrorCode; {$IFDEF Logs} LogThis('Result : ' + result.ToStr) {$ENDIF} end; WAIT_OBJECT_0 + 1 : ErrorCode := errQueryTimedOut; else // WAIT_TIMEOUT begin {$IFDEF Logs} LogThis('Query timed out'); {$ENDIF} ErrorCode := errQueryTimedOut; end; end; except ErrorCode := errQueryQueueOverflow end; finally // remove the query fSentQueriesLock.Acquire; try fSentQueries.Remove(theQuery); CloseHandle(theQuery.Event); finally fSentQueriesLock.Release end; end; finally dispose(theQuery); end; except result := nil; ErrorCode := errUnknownError end else result := nil; end; procedure TWinSockRDOConnection.Send(Query : TRDOQuery); var theQuery : PQueryToSend; begin if fConnected then begin new(theQuery); theQuery.Query := Query; {$IFDEF Logs} LogThis('Sending : ' + Query.ToStr); {$ENDIF} theQuery.WaitForAnsw := false; fUnsentQueriesLock.Acquire; try try fUnsentQueries.Add(theQuery); if fUnsentQueries.Count = 1 then SetEvent(fUnsentQueryWaiting); except Query.Free; dispose(theQuery); end finally fUnsentQueriesLock.Release end end; end; procedure TWinSockRDOConnection.DoRead(Sender : TObject; Socket : TCustomWinSocket); function FindServicedQuery(Query : TRDOQuery) : PQueryToSend; var QueryIdx : integer; SentQueries : integer; begin QueryIdx := 0; SentQueries := fSentQueries.Count; while (QueryIdx < SentQueries) and (Query.Id <> PQueryToSend(fSentQueries[ QueryIdx ]).Query.Id) do inc(QueryIdx); if QueryIdx < SentQueries then result := fSentQueries[QueryIdx] else result := nil; end; var ServicedQuery : PQueryToSend; Query : TRDOQuery; flag : boolean; begin flag := false; try flag := fReceivedData.Receive(Socket); except {$IFDEF Logs} on E : ERDOCorruptQuery do LogThis('Invalid query size found'); else LogThis('Unknow error reading from socket'); {$ENDIF} end; if flag then begin fReceivedData.Position := 0; Query := TRDOQuery.Read(fReceivedData); fReceivedData.Clear; if Query.QKind = qkAnswer then begin ServicedQuery := FindServicedQuery(Query); fSentQueriesLock.Acquire; try if ServicedQuery <> nil then begin ServicedQuery.Result := Query; fSentQueries.Remove(ServicedQuery); ServicedQuery.ErrorCode := errNoError; SetEvent(ServicedQuery.Event); end else Query.Free; finally // parche fSentQueriesLock.Release; //if fSentQueriesLock <> nil //then fSentQueriesLock.Release; end; end else if fQueryServer <> nil then begin fQueryQueueLock.Acquire; try fQueryQueue.Add(Query); if fQueryQueue.Count = 1 then SetEvent(fQueryWaiting); finally fQueryQueueLock.Release end end else Query.Free; // >> should reply with an error code end; end; procedure TWinSockRDOConnection.HandleError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer); begin case ErrorEvent of {$IFDEF Logs} eeGeneral: LogThis('General socket error'); eeSend: LogThis('Error writing to socket'); eeReceive: LogThis('Error reading from socket'); {$ENDIF} eeConnect: begin ErrorCode := 0; {$IFDEF Logs} LogThis('Error establishing connection') {$ENDIF} end; eeDisconnect: begin ErrorCode := 0; {$IFDEF Logs} LogThis('Error closing connection') {$ENDIF} end; {$IFDEF Logs} eeAccept: LogThis('Error accepting connection') {$ENDIF} end end; procedure TWinSockRDOConnection.HandleConnect(Sender : TObject; Socket : TCustomWinSocket); begin fConnected := true; SetEvent(fConnectionEvent); if Assigned(fOnConnect) then fOnConnect(Self as IRDOConnection); end; procedure TWinSockRDOConnection.HandleDisconnect(Sender : TObject; Socket : TCustomWinSocket); begin fConnected := false; if Assigned(fOnDisconnect) then fOnDisconnect(Self as IRDOConnection); Disconnect; end; initialization LastQueryId := 0; {$IFDEF AutoServer} TAutoObjectFactory.Create(ComServer, TWinSockRDOConnection, Class_WinSockRDOConnection, ciMultiInstance) {$ENDIF} end.
program Sort4; type top_ptr=^top; {тип "указатель на вершину дерева"} top=record {тип вершины дерева} value:integer; {целое число} left, right:top_ptr; {указатели на левое и правое поддеревья} end; var next_number:integer; r,pass:top_ptr; {корень бинарного дерева} {процедура добавления вершины к дереву} Procedure Add(var r:top_ptr; pass:top_ptr); begin if r=nil then r:=pass {если место свободно, то добавляем} else {иначе идем налево или направо} if (pass^.value<r^.value) then Add(r^.left,pass) else Add(r^.right,pass); end; {процедура сортировки - обход дерева} procedure Tree(r:top_ptr); begin if r<>nil then begin {если есть поддерево} Tree(r^.left); {обход левого поддерева} write(r^.value:4); {вывод значения из корня} tree(r^.right); {обход правого поддерева} end; end; {основная программа} begin {формирование исходного дерева} writeln('Vvodite cisla'); r:=nil; read(next_number); while not EOF do begin new(pass); {выделяем память для нового элемента} with pass^ do {заносим значения} begin value:=next_number; left:=nil; right:=nil; end; Add(r,pass); {добавляем элемент к дереву} read(next_number) end; readln; writeln('Sortirovannaya posledovatelnost:'); tree(r); end.
PROGRAM Pseudo(INPUT, OUTPUT); { Programm writes letters in pseudographics } CONST Rows = 5; Columns = 5; TYPE SignsPlace = SET OF 1 .. 25; PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace); VAR PositionInRow: INTEGER; BEGIN {WritePseudo} FOR PositionInRow := 1 TO (Rows * Columns) DO BEGIN IF PositionInRow IN PseudoLetter THEN WRITE('#') ELSE WRITE(' '); IF (PositionInRow MOD 5) = 0 THEN WRITELN END; WRITELN END; {WritePseudo} VAR PseudoLetter: SignsPlace; BEGIN {Pseudo} PseudoLetter := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25]; WRITE(Letters, PseudoLetter); PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 25]; WritePseudo(PseudoLetter) END. {Pseudo}
unit DW.Androidapi.JNI.Timer; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android Androidapi.JNIBridge, Androidapi.JNI.JavaTypes; type JTimerTask = interface; JTimer = interface; JTimerClass = interface(JObjectClass) ['{07C8270D-52FF-4B70-B364-A4E86A4F3411}'] function init: JTimer; cdecl; overload; function init(name: JString): JTimer; cdecl; overload; function init(name: JString; isDaemon: boolean): JTimer; cdecl; overload; function init(isDaemon: boolean): JTimer; cdecl; overload; end; [JavaSignature('java/util/Timer')] JTimer = interface(JObject) ['{25D25103-F3A3-417F-AE53-7B434258D54D}'] procedure cancel; cdecl; function purge: Integer; cdecl; procedure schedule(task: JTimerTask; delay: Int64); cdecl; overload; procedure schedule(task: JTimerTask; delay: Int64; period: Int64); cdecl; overload; procedure schedule(task: JTimerTask; firstTime: JDate; period: Int64); cdecl; overload; procedure schedule(task: JTimerTask; time: JDate); cdecl; overload; procedure scheduleAtFixedRate(task: JTimerTask; delay: Int64; period: Int64); cdecl; overload; procedure scheduleAtFixedRate(task: JTimerTask; firstTime: JDate; period: Int64); cdecl; overload; end; TJTimer = class(TJavaGenericImport<JTimerClass, JTimer>) end; JTimerTaskClass = interface(JObjectClass) ['{8A91DFA8-92B7-49CE-88DB-931B6D4D679F}'] end; [JavaSignature('java/util/TimerTask')] JTimerTask = interface(JObject) ['{E5CEEEE4-88C0-4488-9E7C-86249258C30E}'] function cancel: boolean; cdecl; procedure run; cdecl; function scheduledExecutionTime: Int64; cdecl; end; TJTimerTask = class(TJavaGenericImport<JTimerTaskClass, JTimerTask>) end; implementation end.
unit aeColor; interface uses types, classes, graphics; type TaeColorCode = array [0 .. 2] of byte; type TaeColor = class public constructor Create(r, g, b: byte); overload; constructor Create; overload; procedure setColor(r, g, b: byte); overload; procedure setColor(c: TColor); overload; procedure setColor(c: TaeColorCode); overload; function getColor: TaeColorCode; function getRed(): byte; function getGreen(): byte; function getBlue(): byte; procedure setRandomColor(); private _color: TaeColorCode; end; implementation { TaeColor } constructor TaeColor.Create; begin self._color[0] := 255; self._color[1] := 255; self._color[2] := 255; end; function TaeColor.getBlue: byte; begin result := self._color[2]; end; function TaeColor.getColor: TaeColorCode; begin result := self._color; end; function TaeColor.getGreen: byte; begin result := self._color[1]; end; function TaeColor.getRed: byte; begin result := self._color[0]; end; procedure TaeColor.setColor(c: TaeColorCode); begin self._color := c; end; procedure TaeColor.setRandomColor; begin self._color[0] := Random(255); self._color[1] := Random(255); self._color[2] := Random(255); end; procedure TaeColor.setColor(c: TColor); var winColor: Integer; begin // Delphi color to Windows color winColor := ColorToRGB(c); // convert 0..255 range into 0..1 range self._color[0] := (winColor and $FF); self._color[1] := ((winColor shr 8) and $FF); self._color[2] := ((winColor shr 16) and $FF); end; constructor TaeColor.Create(r, g, b: byte); begin self._color[0] := r; self._color[1] := g; self._color[2] := b; end; procedure TaeColor.setColor(r, g, b: byte); begin self._color[0] := r; self._color[1] := g; self._color[2] := b; end; end.
unit glr_filesystem; {$i defines.inc} interface uses glr_utils; { FileSystem } const PACK_FILE_MAGIC: Word = $0F86; PACK_FILE_MAGIC_LZO: Word = $0F87; PACK_FILE_EXT = '.glrpack'; type NameString = String[255]; TglrPackFileResource = record FileName: NameString; Stride, CompressedSize, OriginalSize: LongInt; end; FileSystem = class protected type { TglrPackFile } TglrPackFile = record PackName: AnsiString; Files: array of TglrPackFileResource; Loaded, LZO: Boolean; PackData: TglrStream; PackDataPointer: Pointer; procedure Load(); procedure Unload(); function GetFileIndex(FileName: AnsiString): Integer; function ReadResource(FileIndex: Integer): TglrStream; end; var class var fPackFilesPath: AnsiString; class var fPackFiles: array of TglrPackFile; class function GetPackIndexByPackName(const aPackName: AnsiString): Integer; public class procedure Init(const aPackFilesPath: AnsiString); class procedure DeInit(); class procedure LoadPack(const aPackFileName: AnsiString); //loads entire pack file into memory class procedure UnloadPack(const aPackFileName: AnsiString); class function ReadResource(const aFileName: AnsiString; aSearchInPackFiles: Boolean = True): TglrStream; class function ReadResourceLZO(const aFileName: AnsiString; aSearchInPackFiles: Boolean = True): TglrStream; class procedure WriteResource(const aFileName: AnsiString; const aStream: TglrStream); overload; class procedure WriteResource(const aFileName: AnsiString; const aContent: AnsiString); overload; end; procedure CompressData(const InData: Pointer; InSize: LongInt; out OutData: Pointer; out OutSize: LongInt); procedure DecompressData(const InData: Pointer; InSize: LongInt; const OutData: Pointer; var OutSize: LongInt); implementation {$IFDEF WIN32} uses glr_os_win; {$ENDIF} { FileSystem } function lzo_compress(const Data; Size: LongInt; var CData; var CSize: LongInt; var WorkBuf): LongInt; cdecl; asm //{$IFDEF WIN32} //jmp lzo_compress+$2F0+8+3 ///{$ELSE} pop ebp lea eax, @dest + $2F0 jmp eax @dest: //{$ENDIF} DD $83EC8B55,$5653E8C4,$C458B57,$308558B,$FC5589D0,$89F3C283,$458BF855,$F4458918,$8B10558B DD $F08B0845,$3304C083,$8ADB33C9,$588A0348,$6E1C102,$DB33CB33,$8A05E1C1,$CB330158,$E1C1DB33 DD $33188A05,$C1D98BCB,$CB0305E1,$8105E9C1,$3FFFE1,$EC4D8900,$8BF44D8B,$C8BEC5D,$3BD98B99 DD $7E72085D,$FB2BF88B,$85F07D89,$817376FF,$BFFFF07D,$6A770000,$F07D81,$76000008,$3598A51 DD $7403583A,$EC4D8B49,$7FFE181,$F1810000,$201F,$8BEC4D89,$5D8BF44D,$990C8BEC,$5D3BD98B DD $8B377208,$89FB2BF8,$FF85F07D,$7D812C76,$BFFFF0,$81237700,$800F07D,$A760000,$3A03598A DD $2740358,$8B6610EB,$183B6619,$598A0875,$2583A02,$4D8B1874,$EC5D8BF4,$40990489,$FF8453B DD $1D883,$FF25E900,$5D8BFFFF,$EC7D8BF4,$8BBB0489,$85DE2BD8,$89567EDB,$7D83E85D,$87703E8 DD $8E85D8A,$3AEBFE5A,$12E87D83,$5D8A0B77,$3EB80E8,$EB421A88,$E87D8B29,$420002C6,$8112EF83 DD $FFFF,$81127600,$FFEF,$2C600,$FFFF8142,$77000000,$88DF8BEE,$1E8A421A,$421A8846,$75E84DFF DD $3C083F5,$4003598A,$75FF583A,$4598A2D,$FF583A40,$598A2475,$583A4005,$8A1B75FF,$3A400659 DD $1275FF58,$4007598A,$75FF583A,$8598A09,$FF583A40,$8B487674,$81CE2BC8,$800F07D,$F18B0000 DD $4DFF2577,$49CE8BF0,$8A05E1C1,$E380F05D,$2E3C107,$A88CB0A,$F04D8B42,$8803E9C1,$F2E9420A DD $81000000,$4000F07D,$13770000,$8BF04DFF,$2E980CE,$8820C980,$C1E9420A,$81000000,$4000F06D DD $4D8B0000,$81DE8BF0,$4000E1,$2EB8000,$800BE9C1,$CB0A10C9,$E9420A88,$9C,$83FC7D8B,$2EB09C1 DD $F83B4041,$198A0676,$F474183A,$CE2BC88B,$7D81F18B,$4000F0,$FF1E7700,$FE83F04D,$8B0D7721 DD $2E980CE,$8820C980,$64EB420A,$C621EE83,$EB422002,$F06D813C,$4000,$7709FE83,$F04D8B1B DD $E181DE8B,$4000,$C102EB80,$C9800BE9,$88CB0A10,$34EB420A,$8B09EE83,$E181F04D,$4000 DD $800BE9C1,$A8810C9,$FFFE8142,$76000000,$FFEE8112,$C6000000,$81420002,$FFFE,$8BEE7700 DD $420A88CE,$80F04D8A,$E1C13FE1,$420A8802,$C1F04D8B,$A8806E9,$3BF08B42,$573F845,$FFFD52E9 DD $10552BFF,$8914458B,$FC458B10,$5E5FC62B,$5DE58B5B,$909090C3,$53EC8B55,$758B5756,$C7D8B10 DD $FF83DE8B,$8B04770D,$8B1BEBC7,$8B521855,$5351144D,$8458B57,$FCE6E850,$C483FFFF,$14558B14 DD $C0851A03,$4D8B6676,$2BCF0308,$8BF33BC8,$3D1175F9,$EE,$D08B0A77,$8811C280,$3FEB4313 DD $7703F883,$FE430805,$F88335EB,$8B0A7712,$3E980C8,$EB430B88,$C6D08B26,$83430003,$FA8112EA DD $FF,$EA811276,$FF,$430003C6,$FFFA81,$EE770000,$8A431388,$B88470F,$F7754843,$431103C6,$430003C6 DD $430003C6,$458BDE2B,$33188914,$5B5E5FC0,$9090C35D end; function lzo_decompress(const CData; CSize: LongInt; var Data; var Size: LongInt): LongInt; cdecl; asm DB $51 DD $458B5653,$C558B08,$F08BD003,$33FC5589,$144D8BD2,$68A1189,$3C10558B,$331C7611,$83C88AC9 DD $8346EFC1,$820F04F9,$1C9,$8846068A,$75494202,$3366EBF7,$460E8AC9,$F10F983,$8D83,$75C98500,$8107EB18 DD $FFC1,$3E804600,$33F47400,$83068AC0,$C8030FC0,$83068B46,$28904C6,$4904C283,$F9832F74,$8B217204,$83028906 DD $C68304C2,$4E98304,$7304F983,$76C985EE,$46068A14,$49420288,$9EBF775,$8846068A,$75494202,$8AC933F7 DD $F983460E,$C12B7310,$828D02E9,$FFFFF7FF,$C933C12B,$C1460E8A,$C12B02E1,$8840088A,$88A420A,$420A8840 DD $288008A,$113E942,$F9830000,$8B207240,$FF428DD9,$8302EBC1,$C32B07E3,$1E8ADB33,$3E3C146,$2B05E9C1 DD $D9E949C3,$83000000,$2F7220F9,$851FE183,$EB1875C9,$FFC18107,$46000000,$74003E80,$8AC033F4,$1FC08306 DD $F46C803,$FBC11EB7,$FF428D02,$C683C32B,$8369EB02,$457210F9,$D98BC28B,$C108E383,$C32B0BE3,$8507E183 DD $EB1875C9,$FFC18107,$46000000,$74003E80,$8ADB33F4,$7C3831E,$F46CB03,$FBC11EB7,$83C32B02,$D03B02C6 DD $9A840F,$2D0000,$EB000040,$2E9C11F,$2BFF428D,$8AC933C1,$E1C1460E,$8AC12B02,$A884008,$88008A42 DD $51EB4202,$7206F983,$2BDA8B37,$4FB83D8,$188B2E7C,$8904C083,$4C2831A,$8B02E983,$831A8918,$C08304C2 DD $4E98304,$7304F983,$76C985EE,$40188A20,$49421A88,$15EBF775,$8840188A,$188A421A,$421A8840,$8840188A DD $7549421A,$8AC933F7,$E183FE4E,$FC98503,$FFFE4284,$46068AFF,$49420288,$C933F775,$E9460E8A,$FFFFFECA DD $8B10552B,$10891445,$75FC753B,$EBC03304,$FFF8B80D,$753BFFFF,$830372FC,$5B5E04C0,$90C35D59 end; procedure CompressData(const InData: Pointer; InSize: LongInt; out OutData: Pointer; out OutSize: LongInt); var WorkBuf : array [Word] of Byte; begin // в случае брутфорс сжатия нужно менять данные в WorkBuf FillChar(WorkBuf, SizeOf(WorkBuf), 0); OutSize := InSize + ((InSize div 1024) + 1) * 16; OutData := GetMemory(OutSize); lzo_compress(InData^, InSize, OutData^, OutSize, WorkBuf); end; procedure DecompressData(const InData: Pointer; InSize: LongInt; const OutData: Pointer; var OutSize: LongInt); begin lzo_decompress(InData^, InSize, OutData^, OutSize); end; { FileSystem.TglrPackFile } procedure FileSystem.TglrPackFile.Load; var FileStream: TglrStream; begin FileStream := TglrStream.Init(PackName); PackDataPointer := GetMem(FileStream.Size); PackData := TglrStream.Init(PackDataPointer, FileStream.Size, True); PackData.CopyFrom(FileStream); Loaded := True; FileStream.Free(); end; procedure FileSystem.TglrPackFile.Unload; begin PackData.Free(); PackData := nil; PackDataPointer := nil; Loaded := False; end; function FileSystem.TglrPackFile.GetFileIndex(FileName: AnsiString): Integer; var i: Integer; begin Result := -1; for i := 0 to High(Files) do if (Files[i].FileName = FileName) then Exit(i); end; function FileSystem.TglrPackFile.ReadResource(FileIndex: Integer): TglrStream; var PackFile: TglrStream; compressedBuffer, uncompressedBuffer: Pointer; bytesRead: LongInt; begin // Load pack file from PackData (memory), uncompress if necessary if (Loaded) then begin if (LZO) then begin // Read compressed data from pack compressedBuffer := GetMem(Files[FileIndex].CompressedSize); PackData.Pos := Files[FileIndex].Stride; PackData.Read(compressedBuffer^, Files[FileIndex].CompressedSize); uncompressedBuffer := GetMem(Files[FileIndex].OriginalSize); DecompressData(compressedBuffer, Files[FileIndex].CompressedSize, uncompressedBuffer, bytesRead); if (bytesRead <> Files[FileIndex].OriginalSize) then Log.Write(lError, 'FileSystem: error occured while decompressing LZO compressed resource "' + Files[FileIndex].FileName + '" from pack file "' + PackName + '"'); FreeMem(compressedBuffer); Result := TglrStream.Init(uncompressedBuffer, bytesRead, True); end else Result := TglrStream.Init(PackDataPointer + Files[FileIndex].Stride, Files[FileIndex].CompressedSize, False); end // Read pack file, seek to requested file's stride, read it into new Stream, // uncompress if necessary else begin PackFile := TglrStream.Init(PackName); PackFile.Pos := Files[FileIndex].Stride; compressedBuffer := GetMem(Files[FileIndex].CompressedSize); bytesRead := PackFile.Read(compressedBuffer^, Files[FileIndex].CompressedSize); PackFile.Free(); if (bytesRead <> Files[FileIndex].CompressedSize) then Log.Write(lError, 'FileSystem: error occured while reading resource "' + Files[FileIndex].FileName + '" from pack file "' + PackName + '"'); if (LZO) then begin uncompressedBuffer := GetMem(Files[FileIndex].OriginalSize); DecompressData(compressedBuffer, Files[FileIndex].CompressedSize, uncompressedBuffer, bytesRead); if (bytesRead <> Files[FileIndex].OriginalSize) then Log.Write(lError, 'FileSystem: error occured while decompressing LZO compressed resource "' + Files[FileIndex].FileName + '" from pack file "' + PackName + '"'); FreeMem(compressedBuffer); end else uncompressedBuffer := compressedBuffer; Result := TglrStream.Init(uncompressedBuffer, bytesRead, True); end; end; class procedure FileSystem.Init(const aPackFilesPath: AnsiString); var packFilesList: TglrStringList; i, l, j: Integer; stream: TglrStream; WordBuf, bytesRead: Word; begin fPackFilesPath := aPackFilesPath; packFilesList := TglrStringList.Create(); FindFiles(fPackFilesPath, PACK_FILE_EXT, packFilesList); Log.Write(lInformation, 'FileSystem: pack files found at "' + fPackFilesPath + '": ' + Convert.ToString(packFilesList.Count)); SetLength(fPackFiles, packFilesList.Count); l := 0; for i := 0 to packFilesList.Count - 1 do begin stream := FileSystem.ReadResource(packFilesList[i], False); // Read magic header bytesRead := stream.Read(WordBuf, SizeOf(Word)); if ((WordBuf <> PACK_FILE_MAGIC) and (WordBuf <> PACK_FILE_MAGIC_LZO)) or (bytesRead < SizeOf(Word)) then begin Log.Write(lError, #9 + packFilesList[i] + ' is not a correct pack file'); SetLength(fPackFiles, Length(fPackFiles) - 1); stream.Free(); continue; end; // Set main params for record fPackFiles[l].PackName := packFilesList[i]; fPackFiles[l].Loaded := False; fPackFiles[l].LZO := (WordBuf = PACK_FILE_MAGIC_LZO); // Read files count bytesRead := stream.Read(WordBuf, SizeOf(Word)); if (bytesRead <> SizeOf(Word)) then begin log.Write(lError, #9 + packFilesList[i] + ': error occured while reading files count'); SetLength(fPackFiles, Length(fPackFiles) - 1); stream.Free(); continue; end; // Read file headers: name, stride and sizes (compressed and original) SetLength(fPackFiles[l].Files, WordBuf); for j := 0 to WordBuf - 1 do begin fPackFiles[l].Files[j].FileName := stream.ReadAnsi(); stream.Read(fPackFiles[l].Files[j].Stride, SizeOf(LongInt)); stream.Read(fPackFiles[l].Files[j].CompressedSize, SizeOf(LongInt)); stream.Read(fPackFiles[l].Files[j].OriginalSize, SizeOf(LongInt)); end; Log.Write(lInformation, #9 + packFilesList[i] + ': header loaded. Files inside: ' + Convert.ToString(WordBuf)); for j := 0 to Length(fPackFiles[l].Files) - 1 do Log.Write(lInformation, #9#9 + fPackFiles[l].Files[j].FileName + #9#9' - c ' + Convert.ToString(Integer(fPackFiles[l].Files[j].CompressedSize)) + ' bytes' + #9#9' - o ' + Convert.ToString(Integer(fPackFiles[l].Files[j].OriginalSize)) + ' bytes'); stream.Free(); l += 1; end; packFilesList.Free(); end; class procedure FileSystem.DeInit; var i: Integer; begin for i := 0 to High(fPackFiles) do if (fPackFiles[i].Loaded) then fPackFiles[i].Unload(); SetLength(fPackFiles, 0); end; class function FileSystem.GetPackIndexByPackName(const aPackName: AnsiString): Integer; var i: Integer; begin Result := -1; for i := 0 to Length(fPackFiles) - 1 do if (fPackFiles[i].PackName = aPackName) then Exit(i); end; class procedure FileSystem.LoadPack(const aPackFileName: AnsiString); var i: Integer; begin i := GetPackIndexByPackName(aPackFileName); if (i = -1) then Log.Write(lError, 'FileSystem: Unable to load pack "' + aPackFileName + '". No pack was found.') else begin fPackFiles[i].Load(); Log.Write(lInformation, 'FileSystem: Load pack "' + aPackFileName + '" is completed'); end; end; class procedure FileSystem.UnloadPack(const aPackFileName: AnsiString); var i: Integer; begin i := GetPackIndexByPackName(aPackFileName); if (i = -1) then Log.Write(lError, 'FileSystem: Unable to unload pack "' + aPackFileName + '". No pack was found.') else begin fPackFiles[i].Unload(); Log.Write(lInformation, 'FileSystem: Pack unload "' + aPackFileName + '" is completed'); end; end; class function FileSystem.ReadResource(const aFileName: AnsiString; aSearchInPackFiles: Boolean): TglrStream; var i, fileIndex: Integer; begin if (FileExists(aFileName)) then begin // ToDo: load directly into memory? Log.Write(lInformation, 'FileSystem: start reading resource "' + aFileName + '" directly from file'); Result := TglrStream.Init(aFileName); Log.Write(lInformation, 'FileSystem: read successfully'); Exit(); end // Try read from pack files else if (aSearchInPackFiles) then for i := 0 to Length(fPackFiles) - 1 do begin fileIndex := fPackFiles[i].GetFileIndex(aFileName); if (fileIndex <> -1) then begin Log.Write(lInformation, 'FileSystem: start reading resource "' + aFileName + '" from pack file "' + fPackFiles[i].PackName + '"'); Result := fPackFiles[i].ReadResource(fileIndex); Log.Write(lInformation, 'FileSystem: read successfully'); Exit(); end; end; Log.Write(lError, 'FileSystem: requested resource "' + aFileName + '" was not found'); end; class function FileSystem.ReadResourceLZO(const aFileName: AnsiString; aSearchInPackFiles: Boolean): TglrStream; var fileStream: TglrStream; mIn, mOut: Pointer; originalSize, outSize: LongInt; wordBuf: Word; i, fileIndex: Integer; begin if (FileExists(aFileName)) then begin Log.Write(lInformation, 'FileSystem: start reading LZO resource "' + aFileName + '" directly from file'); fileStream := TglrStream.Init(aFileName); // Read magic fileStream.Read(wordBuf, SizeOf(Word)); if (wordBuf <> PACK_FILE_MAGIC_LZO) then Log.Write(lCritical, 'FileSystem: resource "' + aFileName + '" is not LZO, no magic found'); // Read original size fileStream.Read(originalSize, SizeOf(LongInt)); // Prepare buffers mIn := GetMem(fileStream.Size - fileStream.Pos); mOut := GetMem(originalSize); // Read compressed data fileStream.Read(mIn^, fileStream.Size); DecompressData(mIn, fileStream.Size, mOut, outSize); if (outSize <> originalSize) then Log.Write(lError, 'FileSystem: error occured while decompressing LZO compressed resource "' + aFileName); Result := TglrStream.Init(mOut, outSize, True); fileStream.Free(); FreeMem(mIn); Log.Write(lInformation, 'FileSystem: read successfully'); Exit(); end // Try read from pack files else if (aSearchInPackFiles) then for i := 0 to Length(fPackFiles) - 1 do begin fileIndex := fPackFiles[i].GetFileIndex(aFileName); if (fileIndex <> -1) then begin Log.Write(lInformation, 'FileSystem: start reading resource "' + aFileName + '" from pack file "' + fPackFiles[i].PackName + '"'); Result := fPackFiles[i].ReadResource(fileIndex); Log.Write(lInformation, 'FileSystem: read successfully'); Exit(); end; end; Log.Write(lError, 'FileSystem: requested resource "' + aFileName + '" was not found'); end; class procedure FileSystem.WriteResource(const aFileName: AnsiString; const aStream: TglrStream); var FileStream: TglrStream; begin if PathExists(ExtractFilePath(aFileName)) then begin FileStream := TglrStream.Init(aFileName, True); FileStream.CopyFrom(aStream); FileStream.Free(); end else Log.Write(lError, 'FileSystem: Unable to write resource "' + aFileName + '", path is not exists'); end; class procedure FileSystem.WriteResource(const aFileName: AnsiString; const aContent: AnsiString); var t: Text; begin if PathExists(ExtractFilePath(aFileName)) then begin AssignFile(t, aFileName); Rewrite(t); Write(t, aContent); CloseFile(t); end else Log.Write(lError, 'FileSystem: Unable to write resource "' + aFileName + '", path is not exists'); end; end.
unit pgDataProvider; // Модуль: "w:\common\components\rtl\Garant\PG\pgDataProvider.pas" // Стереотип: "SimpleClass" // Элемент модели: "TpgDataProvider" MUID: (55D6DA9E00BF) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , l3ProtoObject , daInterfaces , pgDataProviderParams , pgInterfaces , daLongProcessSubscriberList , daProgressSubscriberList , pgConnection , daTypes , l3Languages , daUserIDList , pgRenumerator , pgFunctionFactory , pgFreeIDHelperHolder , pgFamilyHelper , l3DatLst ; type TpgDataProvider = class(Tl3ProtoObject, IdaDataProvider, IdaComboAccessDataProviderHelper) private f_Params: TpgDataProviderParams; f_DataConverter: IpgDataConverter; f_NeedClearGlobalDataProvider: Boolean; f_LongProcessList: TdaLongProcessSubscriberList; f_ProgressList: TdaProgressSubscriberList; f_ForCheckLogin: Boolean; f_AllowClearLocks: Boolean; f_RequireAdminRights: Boolean; f_Connection: TpgConnection; f_RegionID: TdaRegionID; f_BaseName: AnsiString; f_BaseLang: TLanguageObj; f_Factory: IdaTableQueryFactory; f_Journal: IdaJournal; f_ImpersonatedUserList: TdaUserIDList; f_UserManager: IdaUserManager; f_IsStarted: Boolean; f_RegionQuery: IdaTabledQuery; f_CurHomePath: AnsiString; f_LockCounter: Integer; f_Renum: TpgRenumerator; f_FunctionFactory: TpgFunctionFactory; f_SetGlobalDataProvider: Boolean; f_HasAdminRights: Boolean; f_AlienSessionID: TdaSessionID; f_FamilyHelper: TpgFamilyHelper; f_FreeIDHelperHolder: TpgFreeIDHelperHolder; private procedure ReadIniFile; function RegionQuery: IdaTabledQuery; function RegionResultSet(anID: TdaRegionID): IdaResultSet; function FamilyHelper: TpgFamilyHelper; function GetAliasValue(const aAlias: AnsiString): AnsiString; function Renum: TpgRenumerator; function ExtDocIDsFromRange: Boolean; function CheckFreeResource(aFamilyID: TdaFamilyID; const aKey: AnsiString): Boolean; protected function Get_UserID: TdaUserID; function Get_RegionID: TdaRegionID; function CheckLogin(const aLogin: AnsiString; const aPassword: AnsiString; IsRequireAdminRights: Boolean): TdaLoginError; procedure InitRegionFromIni(aDefaultRegion: TdaRegionID); function IsRegionExists(anID: TdaRegionID): Boolean; function GetRegionName(anID: TdaRegionID): AnsiString; procedure FillRegionDataList(aList: Tl3StringDataList; Caps: Boolean); function Get_BaseName: AnsiString; function Get_AdminRights: Boolean; function Get_CurUserIsServer: Boolean; procedure LoginAsServer; function GetFreeExtObjID(aFamily: TdaFamilyID): TdaDocID; function GetFreeExtDocID(aFamily: TdaFamilyID): TdaDocID; function LockAll: Boolean; procedure UnlockAll; function Get_BaseLanguage(aFamily: TdaFamilyID): TLanguageObj; function Get_TextBase(aFamily: TdaFamilyID): AnsiString; function GetHomePathName(aUserID: TdaUserID): TdaPathStr; function GetHomePath(aUserID: TdaUserID): TdaPathStr; function Get_CurHomePath: TdaPathStr; function Get_GlobalHomePath: TdaPathStr; function ConvertAliasPath(const CurPath: TdaPathStr): TdaPathStr; procedure SubscribeLongProcess(const aSubscriber: IdaLongProcessSubscriber); procedure UnSubscribeLongProcess(const aSubscriber: IdaLongProcessSubscriber); procedure SubscribeProgress(const aSubscriber: IdaProgressSubscriber); procedure UnSubscribeProgress(const aSubscriber: IdaProgressSubscriber); procedure Start; procedure Stop; function Get_Journal: IdaJournal; function Get_TableQueryFactory: IdaTableQueryFactory; function Get_DataConverter: IdaDataConverter; function Get_ImpersonatedUserID: TdaUserID; procedure BeginImpersonate(anUserID: TdaUserID); procedure EndImpersonate; function Get_UserManager: IdaUserManager; function RegisterFreeExtObjID(aFamilyID: TdaFamilyID; const aKey: AnsiString; anID: TdaDocID): Boolean; function RegisterFreeExtDocID(aFamilyID: TdaFamilyID; const aKey: AnsiString; anID: TdaDocID): Boolean; procedure SetAlienJournalData(aSessionID: TdaSessionID); function HasJournal: Boolean; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aParams: TpgDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalDataProvider: Boolean = True); reintroduce; class function Make(aParams: TpgDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalDataProvider: Boolean = True): IdaDataProvider; reintroduce; protected property FreeIDHelperHolder: TpgFreeIDHelperHolder read f_FreeIDHelperHolder; end;//TpgDataProvider {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses , SysUtils , pgDataConverter , daDataProvider , daUtils , l3IniFile , pgTableQueryFactory , pgJournal , l3Base , pgUserManager , daScheme {$If Defined(l3Requires_m0)} , m2XLtLib {$IfEnd} // Defined(l3Requires_m0) , l3FileUtils , StrUtils , daSchemeConsts //#UC START# *55D6DA9E00BFimpl_uses* //#UC END# *55D6DA9E00BFimpl_uses* ; constructor TpgDataProvider.Create(aParams: TpgDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalDataProvider: Boolean = True); //#UC START# *55E00D5A0297_55D6DA9E00BF_var* //#UC END# *55E00D5A0297_55D6DA9E00BF_var* begin //#UC START# *55E00D5A0297_55D6DA9E00BF_impl* inherited Create; f_SetGlobalDataProvider := SetGlobalDataProvider; f_DataConverter := TpgDataConverter.Make; f_ForCheckLogin := ForCheckLogin; f_LongProcessList := TdaLongProcessSubscriberList.Make; f_ProgressList := TdaProgressSubscriberList.Make; aParams.SetRefTo(f_Params); // f_Helper := ThtDataSchemeHelper.Make(f_Params); f_AllowClearLocks := AllowClearLocks; f_CurHomePath:=aParams.HomeDirPath; f_Connection := TpgConnection.Create(f_LongProcessList); f_FunctionFactory := TpgFunctionFactory.Create(f_Connection, f_DataConverter); f_AlienSessionID := BlankSession; f_Factory := TpgTableQueryFactory.Make(f_DataConverter, f_Connection); f_FreeIDHelperHolder := TpgFreeIDHelperHolder.Create(f_Connection, f_Factory, f_FunctionFactory); f_ImpersonatedUserList := TdaUserIDList.Make; //#UC END# *55E00D5A0297_55D6DA9E00BF_impl* end;//TpgDataProvider.Create class function TpgDataProvider.Make(aParams: TpgDataProviderParams; ForCheckLogin: Boolean; AllowClearLocks: Boolean; SetGlobalDataProvider: Boolean = True): IdaDataProvider; var l_Inst : TpgDataProvider; begin l_Inst := Create(aParams, ForCheckLogin, AllowClearLocks, SetGlobalDataProvider); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TpgDataProvider.Make procedure TpgDataProvider.ReadIniFile; //#UC START# *55F7F8080115_55D6DA9E00BF_var* var l_BaseIni: TCfgList; //#UC END# *55F7F8080115_55D6DA9E00BF_var* begin //#UC START# *55F7F8080115_55D6DA9E00BF_impl* if f_RegionID = 0 then InitRegionFromIni(0); l_BaseIni := f_Params.MakeBaseIni; try l_BaseIni.Section:= 'Base'; f_BaseName := l_BaseIni.ReadParamStrDef('Name', ''); finally FreeAndNil(l_BaseIni); end; //#UC END# *55F7F8080115_55D6DA9E00BF_impl* end;//TpgDataProvider.ReadIniFile function TpgDataProvider.RegionQuery: IdaTabledQuery; //#UC START# *56448A910213_55D6DA9E00BF_var* //#UC END# *56448A910213_55D6DA9E00BF_var* begin //#UC START# *56448A910213_55D6DA9E00BF_impl* if f_RegionQuery = nil then begin f_RegionQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtRegions))); f_RegionQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtRegions).Field['Name'])); f_RegionQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtRegions).Field['ID'], da_copEqual, 'p_RegionID'); f_RegionQuery.Prepare; end; Result := f_RegionQuery; //#UC END# *56448A910213_55D6DA9E00BF_impl* end;//TpgDataProvider.RegionQuery function TpgDataProvider.RegionResultSet(anID: TdaRegionID): IdaResultSet; //#UC START# *56448ABA03B4_55D6DA9E00BF_var* //#UC END# *56448ABA03B4_55D6DA9E00BF_var* begin //#UC START# *56448ABA03B4_55D6DA9E00BF_impl* RegionQuery.Param['p_RegionID'].AsInteger := anID; Result := RegionQuery.OpenResultSet; //#UC END# *56448ABA03B4_55D6DA9E00BF_impl* end;//TpgDataProvider.RegionResultSet function TpgDataProvider.FamilyHelper: TpgFamilyHelper; //#UC START# *5645BD9C0153_55D6DA9E00BF_var* //#UC END# *5645BD9C0153_55D6DA9E00BF_var* begin //#UC START# *5645BD9C0153_55D6DA9E00BF_impl* if f_FamilyHelper = nil then f_FamilyHelper := TpgFamilyHelper.Create(f_Factory); Result := f_FamilyHelper; //#UC END# *5645BD9C0153_55D6DA9E00BF_impl* end;//TpgDataProvider.FamilyHelper function TpgDataProvider.GetAliasValue(const aAlias: AnsiString): AnsiString; //#UC START# *56499CBF03D2_55D6DA9E00BF_var* //#UC END# *56499CBF03D2_55D6DA9E00BF_var* begin //#UC START# *56499CBF03D2_55D6DA9E00BF_impl* Result := ''; if f_Params.AliasesList.Count > 0 then Result := f_Params.AliasesList.Values[aAlias]; if (Result = '') and (aAlias = 'FamilyPath') then Result := f_Params.DocStoragePath; if (Result = '') then raise EPgError.Create('Путь не найден'); //#UC END# *56499CBF03D2_55D6DA9E00BF_impl* end;//TpgDataProvider.GetAliasValue function TpgDataProvider.Renum: TpgRenumerator; //#UC START# *5652B5DD02FA_55D6DA9E00BF_var* //#UC END# *5652B5DD02FA_55D6DA9E00BF_var* begin //#UC START# *5652B5DD02FA_55D6DA9E00BF_impl* if f_Renum = nil then f_Renum := TpgRenumerator.Create(f_Factory); Result := f_Renum; //#UC END# *5652B5DD02FA_55D6DA9E00BF_impl* end;//TpgDataProvider.Renum function TpgDataProvider.ExtDocIDsFromRange: Boolean; //#UC START# *56558A1600EA_55D6DA9E00BF_var* //#UC END# *56558A1600EA_55D6DA9E00BF_var* begin //#UC START# *56558A1600EA_55D6DA9E00BF_impl* Result := CheckFreeResource(CurrentFamily, ftnDocIDExternal); //#UC END# *56558A1600EA_55D6DA9E00BF_impl* end;//TpgDataProvider.ExtDocIDsFromRange function TpgDataProvider.CheckFreeResource(aFamilyID: TdaFamilyID; const aKey: AnsiString): Boolean; //#UC START# *56558A4A01D1_55D6DA9E00BF_var* //#UC END# *56558A4A01D1_55D6DA9E00BF_var* begin //#UC START# *56558A4A01D1_55D6DA9E00BF_impl* Result := FreeIDHelperHolder.FreeIDHelper[aFamilyID].AnyRangesPresent(aKey); //#UC END# *56558A4A01D1_55D6DA9E00BF_impl* end;//TpgDataProvider.CheckFreeResource function TpgDataProvider.Get_UserID: TdaUserID; //#UC START# *551A929E02D5_55D6DA9E00BFget_var* //#UC END# *551A929E02D5_55D6DA9E00BFget_var* begin //#UC START# *551A929E02D5_55D6DA9E00BFget_impl* Result := f_Params.UserID; //#UC END# *551A929E02D5_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_UserID function TpgDataProvider.Get_RegionID: TdaRegionID; //#UC START# *551A933F02AE_55D6DA9E00BFget_var* //#UC END# *551A933F02AE_55D6DA9E00BFget_var* begin //#UC START# *551A933F02AE_55D6DA9E00BFget_impl* Result := f_RegionID; //#UC END# *551A933F02AE_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_RegionID function TpgDataProvider.CheckLogin(const aLogin: AnsiString; const aPassword: AnsiString; IsRequireAdminRights: Boolean): TdaLoginError; //#UC START# *551BE2D701DE_55D6DA9E00BF_var* var l_UserID: TdaUserID; //#UC END# *551BE2D701DE_55D6DA9E00BF_var* begin //#UC START# *551BE2D701DE_55D6DA9E00BF_impl* try Result := Get_UserManager.CheckPassword(aLogin, aPassword, IsRequireAdminRights, l_UserID); if Result = da_leOk then begin f_Params.UserID := l_UserID; f_CurHomePath := GetHomePath(l_UserID); f_RequireAdminRights := IsRequireAdminRights; end; except on E: Exception do begin l3System.Exception2Log(E); Result := da_leSQLError; end; end; //#UC END# *551BE2D701DE_55D6DA9E00BF_impl* end;//TpgDataProvider.CheckLogin procedure TpgDataProvider.InitRegionFromIni(aDefaultRegion: TdaRegionID); //#UC START# *551D25D00024_55D6DA9E00BF_var* var l_BaseIni: TCfgList; //#UC END# *551D25D00024_55D6DA9E00BF_var* begin //#UC START# *551D25D00024_55D6DA9E00BF_impl* Assert(Assigned(f_Params)); l_BaseIni := f_Params.MakeBaseIni; try l_BaseIni.Section:= 'Tables'; f_RegionID := l_BaseIni.ReadParamIntDef('Region', aDefaultRegion); finally FreeAndNil(l_BaseIni); end; //#UC END# *551D25D00024_55D6DA9E00BF_impl* end;//TpgDataProvider.InitRegionFromIni function TpgDataProvider.IsRegionExists(anID: TdaRegionID): Boolean; //#UC START# *551D2C300060_55D6DA9E00BF_var* //#UC END# *551D2C300060_55D6DA9E00BF_var* begin //#UC START# *551D2C300060_55D6DA9E00BF_impl* Result := not RegionResultSet(anId).IsEmpty; //#UC END# *551D2C300060_55D6DA9E00BF_impl* end;//TpgDataProvider.IsRegionExists function TpgDataProvider.GetRegionName(anID: TdaRegionID): AnsiString; //#UC START# *551D2C3603E0_55D6DA9E00BF_var* var l_ResultSet: IdaResultSet; //#UC END# *551D2C3603E0_55D6DA9E00BF_var* begin //#UC START# *551D2C3603E0_55D6DA9E00BF_impl* l_ResultSet := RegionResultSet(anId); if l_ResultSet.IsEmpty then Result := '' else Result := l_ResultSet.Field['Name'].AsString; //#UC END# *551D2C3603E0_55D6DA9E00BF_impl* end;//TpgDataProvider.GetRegionName procedure TpgDataProvider.FillRegionDataList(aList: Tl3StringDataList; Caps: Boolean); //#UC START# *551D35040362_55D6DA9E00BF_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; procedure lp_FillListFromResultSet(const aResultSet : IdaResultSet; aList : Tl3StringDataList; Caps : Boolean); var l_SaveState : Boolean; l_Str: AnsiString; l_ID: TdaDictID; begin l_SaveState := aList.NeedAllocStr; aList.NeedAllocStr := False; try while not aResultSet.EOF do begin l_ID := aResultSet.Field['ID'].AsByte; l_Str := aResultSet.Field['Name'].AsString; if Caps then m2XLTConvertBuff(PAnsiChar(l_Str), Length(l_Str), Cm2XLTANSI2Upper); aList.AddStr(l_Str, @l_ID); aResultSet.Next; end; finally aList.NeedAllocStr := l_SaveState; end; end; //#UC END# *551D35040362_55D6DA9E00BF_var* begin //#UC START# *551D35040362_55D6DA9E00BF_impl* l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtRegions))); try l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtRegions).Field['ID'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtRegions).Field['Name'])); l_ResultSet := l_Query.OpenResultSet; try aList.Changing; try aList.Clear; aList.DataSize:=SizeOf(TdaDictID); aList.NeedAllocStr:=True; if l_ResultSet.IsEmpty then exit; lp_FillListFromResultSet(l_ResultSet,aList,Caps); finally aList.Changed; end; finally l_ResultSet := nil; end; finally l_Query := nil; end; //#UC END# *551D35040362_55D6DA9E00BF_impl* end;//TpgDataProvider.FillRegionDataList function TpgDataProvider.Get_BaseName: AnsiString; //#UC START# *551E636F0314_55D6DA9E00BFget_var* //#UC END# *551E636F0314_55D6DA9E00BFget_var* begin //#UC START# *551E636F0314_55D6DA9E00BFget_impl* Result := f_BaseName; //#UC END# *551E636F0314_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_BaseName function TpgDataProvider.Get_AdminRights: Boolean; //#UC START# *551E6389027F_55D6DA9E00BFget_var* //#UC END# *551E6389027F_55D6DA9E00BFget_var* begin //#UC START# *551E6389027F_55D6DA9E00BFget_impl* Result := f_HasAdminRights; //#UC END# *551E6389027F_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_AdminRights function TpgDataProvider.Get_CurUserIsServer: Boolean; //#UC START# *551E63A1025A_55D6DA9E00BFget_var* //#UC END# *551E63A1025A_55D6DA9E00BFget_var* begin //#UC START# *551E63A1025A_55D6DA9E00BFget_impl* Result := UserIsService(Get_UserID); //#UC END# *551E63A1025A_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_CurUserIsServer procedure TpgDataProvider.LoginAsServer; //#UC START# *551E63B5008C_55D6DA9E00BF_var* //#UC END# *551E63B5008C_55D6DA9E00BF_var* begin //#UC START# *551E63B5008C_55D6DA9E00BF_impl* f_RequireAdminRights := True; f_Params.UserID := usServerService; //#UC END# *551E63B5008C_55D6DA9E00BF_impl* end;//TpgDataProvider.LoginAsServer function TpgDataProvider.GetFreeExtObjID(aFamily: TdaFamilyID): TdaDocID; //#UC START# *551E7E1501D8_55D6DA9E00BF_var* //#UC END# *551E7E1501D8_55D6DA9E00BF_var* begin //#UC START# *551E7E1501D8_55D6DA9E00BF_impl* try Result := FreeIDHelperHolder.FreeIDHelper[aFamily].GetFree(ftnImgHandle); except Result := 0; end; if (Result <= 0) then try Result := FreeIDHelperHolder.FreeIDHelper[aFamily].GetFree(ftnDocIDExternal); except Result := 0; end; //#UC END# *551E7E1501D8_55D6DA9E00BF_impl* end;//TpgDataProvider.GetFreeExtObjID function TpgDataProvider.GetFreeExtDocID(aFamily: TdaFamilyID): TdaDocID; //#UC START# *551E7E35030B_55D6DA9E00BF_var* //#UC END# *551E7E35030B_55D6DA9E00BF_var* begin //#UC START# *551E7E35030B_55D6DA9E00BF_impl* if not ExtDocIDsFromRange then Result := 0 else repeat Result := FreeIDHelperHolder.FreeIDHelper[aFamily].GetFree(ftnDocIDExternal); until Renum.ConvertToRealNumber(Result) = cUndefDocID; //#UC END# *551E7E35030B_55D6DA9E00BF_impl* end;//TpgDataProvider.GetFreeExtDocID function TpgDataProvider.LockAll: Boolean; //#UC START# *5522326E0355_55D6DA9E00BF_var* //#UC END# *5522326E0355_55D6DA9E00BF_var* begin //#UC START# *5522326E0355_55D6DA9E00BF_impl* f_Connection.Unlock(pg_llShared); Result := f_Connection.Lock(pg_llExclusive); if Result then Inc(f_LockCounter) else f_Connection.Lock(pg_llShared); //#UC END# *5522326E0355_55D6DA9E00BF_impl* end;//TpgDataProvider.LockAll procedure TpgDataProvider.UnlockAll; //#UC START# *5522327B01D9_55D6DA9E00BF_var* //#UC END# *5522327B01D9_55D6DA9E00BF_var* begin //#UC START# *5522327B01D9_55D6DA9E00BF_impl* f_Connection.Unlock(pg_llExclusive); Dec(f_LockCounter); if not f_Connection.Lock(pg_llShared) then EPgError.Create('Не удалось захватить базу'); //#UC END# *5522327B01D9_55D6DA9E00BF_impl* end;//TpgDataProvider.UnlockAll function TpgDataProvider.Get_BaseLanguage(aFamily: TdaFamilyID): TLanguageObj; //#UC START# *5522496C00CD_55D6DA9E00BFget_var* var l_BaseIni: TCfgList; //#UC END# *5522496C00CD_55D6DA9E00BFget_var* begin //#UC START# *5522496C00CD_55D6DA9E00BFget_impl* if f_BaseLang = nil then begin f_BaseLang:= TLanguageObj.Create; l_BaseIni := f_Params.MakeBaseIni; try l_BaseIni.Section:= 'Settings'; f_BaseLang.LanguageID := l_BaseIni.ReadParamIntDef('Language', -1); finally FreeAndNil(l_BaseIni); end; end; Result:= f_BaseLang; //#UC END# *5522496C00CD_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_BaseLanguage function TpgDataProvider.Get_TextBase(aFamily: TdaFamilyID): AnsiString; //#UC START# *55226E4B01E0_55D6DA9E00BFget_var* //#UC END# *55226E4B01E0_55D6DA9E00BFget_var* begin //#UC START# *55226E4B01E0_55D6DA9E00BFget_impl* Result := FamilyHelper.FamilyPath(aFamily) + 'bserv' + IntToHex(aFamily, 3); //#UC END# *55226E4B01E0_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_TextBase function TpgDataProvider.GetHomePathName(aUserID: TdaUserID): TdaPathStr; //#UC START# *552391490184_55D6DA9E00BF_var* //#UC END# *552391490184_55D6DA9E00BF_var* begin //#UC START# *552391490184_55D6DA9E00BF_impl* Result := IncludeTrailingPathDelimiter(ConcatDirName(f_Params.HomeDirPath, GetHomePathCode(aUserID))); //#UC END# *552391490184_55D6DA9E00BF_impl* end;//TpgDataProvider.GetHomePathName function TpgDataProvider.GetHomePath(aUserID: TdaUserID): TdaPathStr; //#UC START# *552391830231_55D6DA9E00BF_var* //#UC END# *552391830231_55D6DA9E00BF_var* begin //#UC START# *552391830231_55D6DA9E00BF_impl* Result := GetHomePathName(aUserID); ForceDirectories(Result); //#UC END# *552391830231_55D6DA9E00BF_impl* end;//TpgDataProvider.GetHomePath function TpgDataProvider.Get_CurHomePath: TdaPathStr; //#UC START# *5523983D0254_55D6DA9E00BFget_var* //#UC END# *5523983D0254_55D6DA9E00BFget_var* begin //#UC START# *5523983D0254_55D6DA9E00BFget_impl* Result := f_CurHomePath; //#UC END# *5523983D0254_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_CurHomePath function TpgDataProvider.Get_GlobalHomePath: TdaPathStr; //#UC START# *5523984A0349_55D6DA9E00BFget_var* //#UC END# *5523984A0349_55D6DA9E00BFget_var* begin //#UC START# *5523984A0349_55D6DA9E00BFget_impl* Result := f_Params.HomeDirPath; //#UC END# *5523984A0349_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_GlobalHomePath function TpgDataProvider.ConvertAliasPath(const CurPath: TdaPathStr): TdaPathStr; //#UC START# *5523BD100174_55D6DA9E00BF_var* var SecondPos : Byte; CfgPath, PathConst: AnsiString; SaveSection : AnsiString; //#UC END# *5523BD100174_55D6DA9E00BF_var* begin //#UC START# *5523BD100174_55D6DA9E00BF_impl* If CurPath[1]='%' then Begin SecondPos:=PosEx('%',CurPath,2); If SecondPos=0 then raise EPgError.Create('Путь не найден'); PathConst:= AnsiDequotedStr(CurPath, '%'); // Copy(CurPath,2,SecondPos-2); CfgPath := IncludeTrailingBackslash(GetAliasValue(PathConst)); If SecondPos=Length(CurPath) then Result:=CfgPath else Begin If CurPath[SecondPos+1]='\' then Result:=CfgPath+Copy(CurPath,SecondPos+2,Length(CurPath)) else Result:=CfgPath+Copy(CurPath,SecondPos+1,Length(CurPath)); end; end else Result := CurPath; Result := IncludeTrailingBackslash(Result); //#UC END# *5523BD100174_55D6DA9E00BF_impl* end;//TpgDataProvider.ConvertAliasPath procedure TpgDataProvider.SubscribeLongProcess(const aSubscriber: IdaLongProcessSubscriber); //#UC START# *5524D30D007F_55D6DA9E00BF_var* //#UC END# *5524D30D007F_55D6DA9E00BF_var* begin //#UC START# *5524D30D007F_55D6DA9E00BF_impl* if f_LongProcessList.IndexOf(aSubscriber) = -1 then f_LongProcessList.Add(aSubscriber); //#UC END# *5524D30D007F_55D6DA9E00BF_impl* end;//TpgDataProvider.SubscribeLongProcess procedure TpgDataProvider.UnSubscribeLongProcess(const aSubscriber: IdaLongProcessSubscriber); //#UC START# *5524D33101AC_55D6DA9E00BF_var* //#UC END# *5524D33101AC_55D6DA9E00BF_var* begin //#UC START# *5524D33101AC_55D6DA9E00BF_impl* if Self <> nil then f_LongProcessList.Remove(aSubscriber); //#UC END# *5524D33101AC_55D6DA9E00BF_impl* end;//TpgDataProvider.UnSubscribeLongProcess procedure TpgDataProvider.SubscribeProgress(const aSubscriber: IdaProgressSubscriber); //#UC START# *552514320149_55D6DA9E00BF_var* //#UC END# *552514320149_55D6DA9E00BF_var* begin //#UC START# *552514320149_55D6DA9E00BF_impl* if f_ProgressList.IndexOf(aSubscriber) = -1 then f_ProgressList.Add(aSubscriber); //#UC END# *552514320149_55D6DA9E00BF_impl* end;//TpgDataProvider.SubscribeProgress procedure TpgDataProvider.UnSubscribeProgress(const aSubscriber: IdaProgressSubscriber); //#UC START# *5525144701F3_55D6DA9E00BF_var* //#UC END# *5525144701F3_55D6DA9E00BF_var* begin //#UC START# *5525144701F3_55D6DA9E00BF_impl* if Self <> nil then f_ProgressList.Remove(aSubscriber); //#UC END# *5525144701F3_55D6DA9E00BF_impl* end;//TpgDataProvider.UnSubscribeProgress procedure TpgDataProvider.Start; //#UC START# *5526537A00CE_55D6DA9E00BF_var* var l_UserGroups: TdaUserGroupIDArray; //#UC END# *5526537A00CE_55D6DA9E00BF_var* begin //#UC START# *5526537A00CE_55D6DA9E00BF_impl* if f_IsStarted then Exit; if f_SetGlobalDataProvider then begin Assert(GlobalDataProvider = nil); if GlobalDataProvider = nil then begin SetGlobalDataProvider(Self); f_NeedClearGlobalDataProvider := True; end; end; try f_Connection.Connect(f_Params); If not f_ForCheckLogin then begin if f_RequireAdminRights or ((Get_UserID <> usSupervisor) and (Get_UserID < usAdminReserved)) then begin l_UserGroups := Get_UserManager.GetUserGroups(Get_UserID); f_CurHomePath:=GetHomePath(Get_UserID); //!! !!! Need to be implemented !!! // AccessServer.CurrentUserGroup := l_UserGroups; // AccessServer.ReLoadMasks(MainTblsFamily); // Перегружаем маски доступа к документам end; f_HasAdminRights := Get_UserManager.IsUserAdmin(Get_UserID); end; except Stop; raise; end; ReadIniFile; if not f_ForCheckLogin then begin if f_AlienSessionID <> BlankSession then (Get_Journal as IdaComboAccessJournalHelper).SetAlienData(Get_UserID, f_AlienSessionID) else Get_Journal.UserID := Get_UserID; end; f_IsStarted := True; //#UC END# *5526537A00CE_55D6DA9E00BF_impl* end;//TpgDataProvider.Start procedure TpgDataProvider.Stop; //#UC START# *5526538202A5_55D6DA9E00BF_var* //#UC END# *5526538202A5_55D6DA9E00BF_var* begin //#UC START# *5526538202A5_55D6DA9E00BF_impl* if f_NeedClearGlobalDataProvider then SetGlobalDataProvider(nil); if not f_IsStarted then Exit; if Assigned(f_Journal) then f_Journal.SessionDone; f_Journal := nil; if f_Connection.Connected then f_Connection.Disconnect; FreeAndNil(f_BaseLang); f_IsStarted := False; //#UC END# *5526538202A5_55D6DA9E00BF_impl* end;//TpgDataProvider.Stop function TpgDataProvider.Get_Journal: IdaJournal; //#UC START# *55409258013F_55D6DA9E00BFget_var* //#UC END# *55409258013F_55D6DA9E00BFget_var* begin //#UC START# *55409258013F_55D6DA9E00BFget_impl* if f_Journal = nil then begin f_Journal := TpgJournal.Make(f_Connection, Get_TableQueryFactory); if f_AlienSessionID <> BlankSession then (f_Journal as IdaComboAccessJournalHelper).SetAlienData(Get_UserID, f_AlienSessionID) else f_Journal.UserID := Get_UserID; f_UserManager := nil; // ??? end; Result := f_Journal; //#UC END# *55409258013F_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_Journal function TpgDataProvider.Get_TableQueryFactory: IdaTableQueryFactory; //#UC START# *554C7A3002BF_55D6DA9E00BFget_var* //#UC END# *554C7A3002BF_55D6DA9E00BFget_var* begin //#UC START# *554C7A3002BF_55D6DA9E00BFget_impl* Result := f_Factory; //#UC END# *554C7A3002BF_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_TableQueryFactory function TpgDataProvider.Get_DataConverter: IdaDataConverter; //#UC START# *555995CF0292_55D6DA9E00BFget_var* //#UC END# *555995CF0292_55D6DA9E00BFget_var* begin //#UC START# *555995CF0292_55D6DA9E00BFget_impl* Result := f_DataConverter; //#UC END# *555995CF0292_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_DataConverter function TpgDataProvider.Get_ImpersonatedUserID: TdaUserID; //#UC START# *561795EA02BF_55D6DA9E00BFget_var* //#UC END# *561795EA02BF_55D6DA9E00BFget_var* begin //#UC START# *561795EA02BF_55D6DA9E00BFget_impl* if f_ImpersonatedUserList.Count = 0 then Result := Get_UserID else Result := f_ImpersonatedUserList.Last; //#UC END# *561795EA02BF_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_ImpersonatedUserID procedure TpgDataProvider.BeginImpersonate(anUserID: TdaUserID); //#UC START# *561796070253_55D6DA9E00BF_var* //#UC END# *561796070253_55D6DA9E00BF_var* begin //#UC START# *561796070253_55D6DA9E00BF_impl* f_ImpersonatedUserList.Add(anUserID); //#UC END# *561796070253_55D6DA9E00BF_impl* end;//TpgDataProvider.BeginImpersonate procedure TpgDataProvider.EndImpersonate; //#UC START# *5617961F0105_55D6DA9E00BF_var* //#UC END# *5617961F0105_55D6DA9E00BF_var* begin //#UC START# *5617961F0105_55D6DA9E00BF_impl* f_ImpersonatedUserList.Delete(f_ImpersonatedUserList.Count - 1); //#UC END# *5617961F0105_55D6DA9E00BF_impl* end;//TpgDataProvider.EndImpersonate function TpgDataProvider.Get_UserManager: IdaUserManager; //#UC START# *5628D25600E6_55D6DA9E00BFget_var* //#UC END# *5628D25600E6_55D6DA9E00BFget_var* begin //#UC START# *5628D25600E6_55D6DA9E00BFget_impl* if f_UserManager = nil then f_UserManager := TpgUserManager.Make(Get_TableQueryFactory, Get_Journal, f_FunctionFactory, f_FreeIDHelperHolder, f_Connection); Result := f_UserManager; //#UC END# *5628D25600E6_55D6DA9E00BFget_impl* end;//TpgDataProvider.Get_UserManager function TpgDataProvider.RegisterFreeExtObjID(aFamilyID: TdaFamilyID; const aKey: AnsiString; anID: TdaDocID): Boolean; //#UC START# *56BC642200D0_55D6DA9E00BF_var* //#UC END# *56BC642200D0_55D6DA9E00BF_var* begin //#UC START# *56BC642200D0_55D6DA9E00BF_impl* FreeIDHelperHolder.FreeIDHelper[aFamilyID].ExcludeFree(aKey, anID); //#UC END# *56BC642200D0_55D6DA9E00BF_impl* end;//TpgDataProvider.RegisterFreeExtObjID function TpgDataProvider.RegisterFreeExtDocID(aFamilyID: TdaFamilyID; const aKey: AnsiString; anID: TdaDocID): Boolean; //#UC START# *56BC6437030F_55D6DA9E00BF_var* //#UC END# *56BC6437030F_55D6DA9E00BF_var* begin //#UC START# *56BC6437030F_55D6DA9E00BF_impl* FreeIDHelperHolder.FreeIDHelper[aFamilyID].ExcludeFree(aKey, anID); //#UC END# *56BC6437030F_55D6DA9E00BF_impl* end;//TpgDataProvider.RegisterFreeExtDocID procedure TpgDataProvider.SetAlienJournalData(aSessionID: TdaSessionID); //#UC START# *56EBDD7002F8_55D6DA9E00BF_var* //#UC END# *56EBDD7002F8_55D6DA9E00BF_var* begin //#UC START# *56EBDD7002F8_55D6DA9E00BF_impl* f_AlienSessionID := aSessionID; if Assigned(f_Journal) then (f_Journal as IdaComboAccessJournalHelper).SetAlienData(Get_UserID, f_AlienSessionID); //#UC END# *56EBDD7002F8_55D6DA9E00BF_impl* end;//TpgDataProvider.SetAlienJournalData function TpgDataProvider.HasJournal: Boolean; //#UC START# *56F0F6180156_55D6DA9E00BF_var* //#UC END# *56F0F6180156_55D6DA9E00BF_var* begin //#UC START# *56F0F6180156_55D6DA9E00BF_impl* Result := Assigned(f_Journal); //#UC END# *56F0F6180156_55D6DA9E00BF_impl* end;//TpgDataProvider.HasJournal procedure TpgDataProvider.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_55D6DA9E00BF_var* //#UC END# *479731C50290_55D6DA9E00BF_var* begin //#UC START# *479731C50290_55D6DA9E00BF_impl* Assert(not f_Connection.Connected); FreeAndNil(f_FunctionFactory); FreeAndNil(f_FreeIDHelperHolder); FreeAndNil(f_Renum); FreeAndNil(f_FamilyHelper); f_RegionQuery := nil; FreeAndNil(f_BaseLang); FreeAndNil(f_Params); FreeAndNil(f_LongProcessList); FreeAndNil(f_ProgressList); f_Factory := nil; f_UserManager := nil; f_Journal := nil; f_DataConverter := nil; FreeANdNil(f_Connection); FreeAndNil(f_ImpersonatedUserList); inherited; //#UC END# *479731C50290_55D6DA9E00BF_impl* end;//TpgDataProvider.Cleanup {$IfEnd} // Defined(UsePostgres) end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Arno Garrels <arno.garrels@gmx.de> Description: A few header translations from MS mlang.h. Requires Internet Explorer 5 or better, all functions fail with HRESULT E_NOTIMPL if the library isn't loaded. Creation: March 19, 2010 Version: 1.00 EMail: http://www.overbyte.be francois.piette@overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) Microsoft Corporation. All Rights Reserved. Translator Arno Garrels <arno.garrels@gmx.de> History: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsMLang; {$WEAKPACKAGEUNIT} interface uses Windows; function ConvertINetString( var lpdwMode: DWORD; dwSrcEncoding: DWORD; dwDstEncoding: DWORD; lpSrcStr: LPCSTR; var lpnSrcSize: Integer; lpDstStr: PBYTE; var lpnDstSize: Integer ): HRESULT; function ConvertINetMultibyteToUnicode( var lpdwMode: DWORD; dwSrcEncoding: DWORD; lpSrcStr: LPCSTR; var lpnMultiCharCount: Integer; lpDstStr: LPWSTR; var lpnWideCharCount: Integer ): HRESULT; function ConvertINetUnicodeToMultibyte( var lpdwMode: DWORD; dwEncoding: DWORD; lpSrcStr: LPCWSTR; var lpnWideCharCount: Integer; lpDstStr: LPSTR; var lpnMultiCharCount: Integer ): HRESULT; function IsConvertINetStringAvailable( dwSrcEncoding: DWORD; dwDstEncoding: DWORD ): HRESULT; function Load_MLang: Boolean; implementation type TConvertINetString = function( var lpdwMode: DWORD; dwSrcEncoding: DWORD; dwDstEncoding: DWORD; lpSrcStr: LPCSTR; var lpnSrcSize: Integer; lpDstStr: PBYTE; var lpnDstSize: Integer ): HRESULT; stdcall; TConvertINetMultibyteToUnicode = function( var lpdwMode: DWORD; dwSrcEncoding: DWORD; lpSrcStr: LPCSTR; var lpnMultiCharCount: Integer; lpDstStr: LPWSTR; var lpnWideCharCount: Integer ): HRESULT; stdcall; TConvertINetUnicodeToMultibyte = function( var lpdwMode: DWORD; dwEncoding: DWORD; lpSrcStr: LPCWSTR; var lpnWideCharCount: Integer; lpDstStr: LPSTR; var lpnMultiCharCount: Integer ): HRESULT; stdcall; TIsConvertINetStringAvailable = function( dwSrcEncoding: DWORD; dwDstEncoding: DWORD ): HRESULT; stdcall; var fptrConvertINetString : TConvertINetString = nil; fptrConvertINetMultibyteToUnicode : TConvertINetMultibyteToUnicode = nil; fptrConvertINetUnicodeToMultibyte : TConvertINetUnicodeToMultibyte = nil; fptrIsConvertINetStringAvailable : TIsConvertINetStringAvailable = nil; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Load_MLang: Boolean; var h : HMODULE; begin if Assigned(fptrConvertINetString) then Result := TRUE else begin h := LoadLibrary('mlang.dll'); if h = 0 then Result := FALSE else begin fptrConvertINetString := GetProcAddress(h, 'ConvertINetString'); fptrConvertINetMultiByteToUnicode := GetProcAddress(h, 'ConvertINetMultiByteToUnicode'); fptrConvertINetUnicodeToMultiByte := GetProcAddress(h, 'ConvertINetUnicodeToMultiByte'); fptrIsConvertINetStringAvailable := GetProcAddress(h, 'IsConvertINetStringAvailable'); Result := TRUE; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { S_OK Performed the conversion successfully. } { S_FALSE The specified conversion is not supported on the system. } { E_FAIL An error has occurred. } function ConvertINetString( var lpdwMode: DWORD; dwSrcEncoding: DWORD; dwDstEncoding: DWORD; lpSrcStr: LPCSTR; var lpnSrcSize: Integer; lpDstStr: PBYTE; var lpnDstSize: Integer ): HRESULT; begin if Assigned(fptrConvertINetString) or Load_MLang then Result := fptrConvertINetString(lpdwMode, dwSrcEncoding, dwDstEncoding, lpSrcStr, lpnSrcSize, lpDstStr, lpnDstSize) else Result := E_NOTIMPL; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { S_OK Performed the conversion successfully. } { S_FALSE The specified conversion is not supported on the system. } { E_FAIL An error has occurred. } function ConvertINetMultibyteToUnicode( var lpdwMode: DWORD; dwSrcEncoding: DWORD; lpSrcStr: LPCSTR; var lpnMultiCharCount: Integer; lpDstStr: LPWSTR; var lpnWideCharCount: Integer ): HRESULT; begin if Assigned(fptrConvertINetString) or Load_MLang then Result := fptrConvertINetMultibyteToUnicode(lpdwMode, dwSrcEncoding, lpSrcStr, lpnMultiCharCount, lpDstStr, lpnWideCharCount) else Result := E_NOTIMPL; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { S_OK Performed the conversion successfully. } { S_FALSE The specified conversion is not supported on the system. } { E_FAIL An error has occurred. } function ConvertINetUnicodeToMultibyte( var lpdwMode: DWORD; dwEncoding: DWORD; lpSrcStr: LPCWSTR; var lpnWideCharCount: Integer; lpDstStr: LPSTR; var lpnMultiCharCount: Integer ): HRESULT; begin if Assigned(fptrConvertINetString) or Load_MLang then Result := fptrConvertINetUnicodeToMultibyte(lpdwMode, dwEncoding, lpSrcStr, lpnWideCharCount, lpDstStr, lpnMultiCharCount) else Result := E_NOTIMPL; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { S_OK The function can perform the conversion. } { S_FALSE The conversion is not supported on the system. } { E_INVALIDARG One or more arguments are invalid. } function IsConvertINetStringAvailable( dwSrcEncoding: DWORD; dwDstEncoding: DWORD ): HRESULT; begin if Assigned(fptrConvertINetString) or Load_MLang then Result := fptrIsConvertINetStringAvailable(dwSrcEncoding, dwDstEncoding) else Result := E_NOTIMPL; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
namespace Sugar.Test; interface uses Sugar, Sugar.Data.JSON, RemObjects.Elements.EUnit; type JsonArrayTest = public class (Test) private Obj: JsonArray; public method Setup; override; method &Add; method AddValue; method AddValueFailsWithNil; method Insert; method InsertFailsWithOutOfRange; method InsertValue; method InsertValueFailsWithNil; method InsertValueFailsWithOutOfRange; method Clear; method RemoveAt; method RemoveAtFailsWithOutOfRange; method Count; method GetItem; method GetItemFailsWithOutOfRange; method SetItem; method SetItemFailsWithNil; method SetItemFailsWithOutOfRange; method Enumerator; end; implementation method JsonArrayTest.Setup; begin Obj := new JsonArray; end; method JsonArrayTest.Add; begin Obj.Add(42); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj[0].ToInteger, 42); end; method JsonArrayTest.AddValue; begin Obj.AddValue(new JsonValue(42)); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj[0].ToInteger, 42); end; method JsonArrayTest.AddValueFailsWithNil; begin Assert.Throws(->Obj.AddValue(nil)); end; method JsonArrayTest.Insert; begin Obj.Add(1); Obj.Add(2); Obj.Add(3); Obj.Insert(1, "a"); Assert.AreEqual(Obj.Count, 4); Assert.AreEqual(Obj[1].ToStr, "a"); end; method JsonArrayTest.InsertFailsWithOutOfRange; begin Insert; Assert.Throws(->Obj.Insert(233, 1)); Assert.Throws(->Obj.Insert(-5, 1)); end; method JsonArrayTest.InsertValue; begin Obj.Add(1); Obj.Add(2); Obj.Add(3); Obj.InsertValue(1, new JsonValue("a")); Assert.AreEqual(Obj.Count, 4); Assert.AreEqual(Obj[1].ToStr, "a"); end; method JsonArrayTest.InsertValueFailsWithNil; begin Assert.Throws(->Obj.InsertValue(0, nil)); end; method JsonArrayTest.InsertValueFailsWithOutOfRange; begin Insert; Assert.Throws(->Obj.InsertValue(233, new JsonValue(1))); Assert.Throws(->Obj.InsertValue(-5, new JsonValue(1))); end; method JsonArrayTest.Clear; begin Insert; Obj.Clear; Assert.AreEqual(Obj.Count, 0); end; method JsonArrayTest.RemoveAt; begin Insert; Obj.RemoveAt(1); Assert.AreEqual(Obj.Count, 3); Assert.AreEqual(Obj[1].ToInteger, 2); end; method JsonArrayTest.RemoveAtFailsWithOutOfRange; begin Insert; Assert.Throws(->Obj.RemoveAt(55)); Assert.Throws(->Obj.RemoveAt(-55)); end; method JsonArrayTest.Count; begin Assert.AreEqual(Obj.Count, 0); Insert; Assert.AreEqual(Obj.Count, 4); end; method JsonArrayTest.GetItem; begin Insert; Assert.AreEqual(Obj.Item[1], new JsonValue("a")); Assert.AreEqual(Obj[0].ToInteger, 1); end; method JsonArrayTest.GetItemFailsWithOutOfRange; begin Insert; Assert.Throws(->Obj[55]); Assert.Throws(->Obj.Item[-55]); end; method JsonArrayTest.SetItem; begin Insert; Obj[1] := new JsonValue(true); Assert.AreEqual(Obj.Count, 4); Assert.AreEqual(Obj[1].ToBoolean, true); end; method JsonArrayTest.SetItemFailsWithNil; begin Insert; Assert.Throws(->begin Obj[1] := nil; end); end; method JsonArrayTest.SetItemFailsWithOutOfRange; begin Insert; Assert.Throws(->begin Obj[55] := new JsonValue(true); end); Assert.Throws(->begin Obj[-55] := new JsonValue(nil); end); end; method JsonArrayTest.Enumerator; begin Assert.IsEmpty(Obj); Insert; Assert.AreEqual(Obj, [new JsonValue(1), new JsonValue("a"), new JsonValue(2), new JsonValue(3)]); end; end.
unit nsPictureScaleMap; {* реализация мапы "строка"-"процент %" со спец значением "Во все окно"} {$Include nsDefine.inc } interface uses Classes, l3Interfaces, l3BaseWithID, l3ValueMap, l3Types, l3VCLStrings, vcmExternalInterfaces, vcmInterfaces, L10nInterfaces, nsStringValueMap ; type TnsPictureScaleMap = class(Tl3ValueMap, InsStringValueMap, InsSpecialStringValueMap, InsStringsSource) private f_SpecialValue : TnsStringValueMapRecord; f_Values : Tl3Strings; f_MinValue : Integer; f_MaxValue : Integer; private // InsSpecialStringValueMap function DisplayNameToValue(const aDisplayName: Il3CString): Il3CString; function ValueToDisplayName(const aValue: Il3CString): Il3CString; function Get_SpecialDisplayName: Il3CString; function Get_SpecialValue: Il3CString; function Get_MinValue: Integer; function Get_MaxValue: Integer; // InsStringsSource procedure FillStrings(const aStrings: IvcmStrings); private procedure CheckValue(aValue: integer); procedure ValueError; protected procedure DoGetDisplayNames(const aList: Il3StringsEx); override; function GetMapSize: Integer; override; protected procedure Cleanup; override; public constructor Create(aID: TnsValueMapID; const aValues: array of integer; aMinValue: Integer; aMaxValue: Integer; const aSpecialValue: TnsStringValueMapRecord); reintroduce; class function Make(aID: TnsValueMapID; const aValues: array of integer; aMinValue: Integer; aMaxValue: Integer; const aSpecialValue: TnsStringValueMapRecord): InsStringValueMap; reintroduce; end;//TnsPictureScaleMap implementation uses SysUtils, l3Base, l3String, vcmBase, vcmUtils, nsTypes ; { TnsPictureScaleMap } { TnsPictureScaleMap } procedure TnsPictureScaleMap.CheckValue(aValue: integer); begin if (aValue > f_MaxValue) or (aValue < f_MinValue) then ValueError; end; procedure TnsPictureScaleMap.Cleanup; begin vcmFree(f_Values); Finalize(f_SpecialValue); inherited Cleanup; end; constructor TnsPictureScaleMap.Create(aID: TnsValueMapID; const aValues: array of integer; aMinValue, aMaxValue: Integer; const aSpecialValue: TnsStringValueMapRecord); var l_Index: Integer; begin if aMinValue > aMaxValue then raise El3ValueMap.Create('Invalid parameter. min greater than max'); inherited Create(aID); f_SpecialValue := aSpecialValue; f_MinValue := aMinValue; f_MaxValue := aMaxValue; f_Values := Tl3Strings.Create; for l_index := Low(aValues) to High(aValues) do begin CheckValue(aValues[l_index]); f_Values.Add(l3Fmt('%d %%', [aValues[l_index]])); end;//for l_index f_Values.Add(vcmCStr(f_SpecialValue.rN)); end; function TnsPictureScaleMap.DisplayNameToValue(const aDisplayName: Il3CString): Il3CString; var l_Temp: Il3CString; begin if l3Same(Get_SpecialDisplayName, aDisplayName) then Result := Get_SpecialValue else begin l_Temp := l3Trim(aDisplayName); if l3IsNil(l_Temp) then ValueError; if l3IsChar(l_Temp, l3Len(l_Temp) - 1, '%') then l3SetLen(l_Temp, l3Len(l_Temp) - 1); try Result := l3Trim(l_Temp); CheckValue(StrToInt(l3Str(Result))); except on EConvertError do ValueError; end//try..except end;//l3Same(aDisplayName, Get_SpecialDisplayName) end; procedure TnsPictureScaleMap.FillStrings(const aStrings: IvcmStrings); begin aStrings.Clear; aStrings.Assign(f_Values); end; procedure TnsPictureScaleMap.DoGetDisplayNames(const aList: Il3StringsEx); begin inherited; aList.Assign(f_Values); end; class function TnsPictureScaleMap.Make(aID: TnsValueMapID; const aValues: array of integer; aMinValue, aMaxValue: Integer; const aSpecialValue: TnsStringValueMapRecord): InsStringValueMap; var l_Map: TnsPictureScaleMap; begin l_Map := Create(aID, aValues, aMinValue, aMaxValue, aSpecialValue); try Result := l_Map; finally vcmFree(l_Map); end; end; function TnsPictureScaleMap.GetMapSize: Integer; begin Result := f_Values.Count; end; function TnsPictureScaleMap.Get_MaxValue: Integer; begin Result := f_MaxValue; end; function TnsPictureScaleMap.Get_MinValue: Integer; begin Result := f_MinValue; end; function TnsPictureScaleMap.Get_SpecialDisplayName: Il3CString; begin Result := vcmCStr(f_SpecialValue.rN); end; function TnsPictureScaleMap.Get_SpecialValue: Il3CString; begin Result := f_SpecialValue.rV; end; procedure TnsPictureScaleMap.ValueError; begin raise El3ValueMapValueNotFound.CreateFmt('Must be integer value between %d-%d', [f_MinValue, f_MaxValue]); end; function TnsPictureScaleMap.ValueToDisplayName(const aValue: Il3CString): Il3CString; begin if l3Same(Get_SpecialValue, aValue) then Result := Get_SpecialDisplayName else Result := l3Fmt('%s %%', [aValue]); end; end.
unit Police; interface uses PublicFacility, Surfaces, BackupInterfaces; const modPoliceStrength = 1; type TPoliceBlock = class( TPublicFacility ) public destructor Destroy; override; protected procedure AutoConnect; override; private fCrimeModifier : TSurfaceModifier; public procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses Classes, Kernel, PyramidalModifier; destructor TPoliceBlock.Destroy; begin fCrimeModifier.Delete; inherited; end; procedure TPoliceBlock.AutoConnect; begin inherited; fCrimeModifier := TPyramidalModifier.Create( tidEnvironment_Crime, Point(xOrigin, yOrigin), -TMetaPublicFacility(MetaBlock).Strength, modPoliceStrength ); end; procedure TPoliceBlock.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'CrimeModifier', fCrimeModifier, nil ); end; procedure TPoliceBlock.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteLooseObject( 'CrimeModifier', fCrimeModifier ); end; // RegisterBackup procedure RegisterBackup; begin BackupInterfaces.RegisterClass( TPoliceBlock ); end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.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; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPTaskband; interface uses Classes, QExtCtrls, uCommon, QControls, uXPPNG, QGraphics, uWMConsts, XLib, Types, Sysutils; type TXPTask=class; { TODO : Add group behaviour } TXPTaskband=class(TPanel) private activetasks: TList; FNormalTask: TBitmap; FOriginalOver: TBitmap; FOverTask: TBitmap; FOriginalPressed: TBitmap; FPressedTask: TBitmap; public procedure resizeBitmaps(const width:integer); procedure updatetaskswidth; procedure releasetasks; procedure updatetask(const client:IWMClient); procedure activatetask(const client:IWMClient); procedure addtask(const client:IWMClient); procedure removetask(const client:IWMClient); procedure setup; constructor Create(AOwner:TComponent);override; destructor Destroy;override; end; TXPTask=class(TPanel) private FIcon:TBitmap; FTaskName: string; FDown: boolean; procedure SetTaskName(const Value: string); procedure SetDown(const Value: boolean); public window: TWindow; procedure mouseenter(AControl:TControl);override; procedure mouseleave(AControl:TControl);override; procedure MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; procedure MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; procedure paint;override; procedure setup; constructor Create(AOwner:TComponent);override; destructor Destroy;override; property TaskName:string read FTaskName write SetTaskName; property Icon: TBitmap read FIcon write FIcon; property Down: boolean read FDown write SetDown; end; implementation uses uWindowManager; { TXPTaskband } procedure TXPTaskband.activatetask(const client: IWMClient); var task: TXPTask; btask: TXPTask; i:integer; w: TWindow; k: integer; begin if assigned(client) then begin w:=client.getwindow; for i := 0 to activetasks.count-1 do begin task:=activetasks[i]; if task.window=w then begin for k := 0 to activetasks.count-1 do begin btask:=activetasks[k]; if (btask<>task) then btask.down:=false; end; task.down:=true; break; end; end; end else begin releaseTasks; end; end; procedure TXPTaskband.addtask(const client: IWMClient); var task: TXPTask; found: boolean; i:integer; w: TWindow; begin w:=client.getwindow; found:=false; for i:=activetasks.count-1 downto 0 do begin task:=activetasks[i]; if (task.window=w) then begin found:=true; break; task.taskname:=client.getTitle; task.Hint:=client.getTitle; task.PopupMenu:=client.getSystemMenu; end; end; if not found then begin task:=TXPTask.create(nil); task.window:=w; task.TaskName:=client.getTitle; task.Hint:=client.getTitle; task.PopupMenu:=client.getSystemMenu; //t.OnMouseUp:=toolbutton1mouseup; task.Icon.Assign(client.getbitmap); activetasks.add(task); updatetaskswidth; task.Left:=clientwidth; task.Parent:=self; end; end; constructor TXPTaskband.Create(AOwner: TComponent); begin inherited; FNormalTask:=TBitmap.create; FOriginalOver:=TBitmap.create; FOverTask:=TBitmap.create; FOriginalPressed:=TBitmap.create; FPressedTask:=TBitmap.create; activetasks:=TList.create; setup; end; destructor TXPTaskband.Destroy; begin FOriginalPressed.free; FPressedTask.free; FOriginalOver.free; FOverTask.free; FNormalTask.free; activetasks.free; inherited; end; procedure TXPTaskband.releasetasks; var task: TXPTask; i:integer; begin for i := 0 to activetasks.count-1 do begin task:=activetasks[i]; task.down:=false; end; end; procedure TXPTaskband.removetask(const client: IWMClient); var task: TXPTask; i:integer; w: TWindow; begin w:=client.getwindow; for i := 0 to activetasks.count - 1 do begin task:=activetasks[I]; if (task.window=w) then begin activetasks.remove(task); task.free; updatetaskswidth; break; end; end; end; procedure TXPTaskband.resizeBitmaps(const width: integer); var temp:TBitmap; begin { TODO : Take how to resize backgrounds from the theme instead do it hardcoded } FOverTask.Width:=width; FOverTask.Canvas.CopyRect(rect(0,0,3,FOverTask.height),FOriginalOver.canvas,rect(0,0,3,FOverTask.height)); FOverTask.Canvas.CopyRect(rect(width-3,0,width,FOverTask.height),FOriginalOver.canvas,rect(FOriginalOver.width-3,0,FOriginalOver.width,FOverTask.height)); FPressedTask.Width:=width; FPressedTask.Canvas.CopyRect(rect(0,0,3,FPressedTask.height),FOriginalPressed.canvas,rect(0,0,3,FPressedTask.height)); FPressedTask.Canvas.CopyRect(rect(width-3,0,width,FPressedTask.height),FOriginalPressed.canvas,rect(FOriginalPressed.width-3,0,FOriginalPressed.width,FPressedTask.height)); temp:=TBitmap.create; try temp.width:=FOriginalOver.Width-8; temp.height:=FOverTask.height; temp.Canvas.copyrect(rect(0,0,FOriginalOver.width-6,FOverTask.height),FOriginalOver.canvas,rect(4,0,FOriginalOver.width-4,FOriginalOver.height)); FOverTask.canvas.stretchdraw(rect(4,0,width-3,FOverTask.height),temp); temp.width:=FOriginalPressed.Width-8; temp.height:=FPressedTask.height; temp.Canvas.copyrect(rect(0,0,FOriginalPressed.width-6,FPressedTask.height),FOriginalPressed.canvas,rect(4,0,FOriginalPressed.width-4,FOriginalPressed.height)); FPressedTask.canvas.stretchdraw(rect(4,0,width-3,FPressedTask.height),temp); finally temp.Free; end end; procedure TXPTaskband.setup; var dir: string; begin BevelOuter:=bvNone; dir:=getSystemInfo(XP_TASKBAR_DIR); { TODO : Allow any width or height, tasks must organize depending on the dimension controls } bitmap.LoadFromFile(dir+'/taskbar_background_bottom.png'); FNormalTask.LoadFromFile(dir+'/taskband_button_normal.png'); FOverTask.LoadFromFile(dir+'/taskband_button_over.png'); FOriginalOver.Assign(FOverTask); FPressedTask.LoadFromFile(dir+'/taskband_button_press.png'); FOriginalPressed.Assign(FPressedTask); end; procedure TXPTaskband.updatetask(const client: IWMClient); var task: TXPTask; i:integer; w: TWindow; begin w:=client.getwindow; for i := 0 to activetasks.count - 1 do begin task:=activetasks[i]; if (task.window=w) then begin task.TaskName:=client.getTitle; break; end; end; end; procedure TXPTaskband.updatetaskswidth; var bw: integer; i: integer; task: TXPTask; begin if activetasks.count>0 then begin bw:=trunc((clientWidth-2) / activetasks.count); if bw>163 then bw:=163; for i := 0 to activetasks.count - 1 do begin task:=activetasks[I]; task.width:=bw; end; resizeBitmaps(bw); end; end; { TXPTask } constructor TXPTask.Create(AOwner: TComponent); begin inherited; FDown:=false; FTaskName:='(no name)'; FIcon:=TBitmap.create; setup; end; destructor TXPTask.Destroy; begin FIcon.free; inherited; end; procedure TXPTask.MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited; bitmap.Assign((parent as TXPTaskBand).FPressedTask); end; procedure TXPTask.mouseenter(AControl: TControl); begin inherited; bitmap.Assign((parent as TXPTaskBand).FOverTask); end; procedure TXPTask.mouseleave(AControl: TControl); begin inherited; if (FDown) then bitmap.Assign((parent as TXPTaskBand).FPressedTask) else bitmap.Assign((parent as TXPTaskBand).FNormalTask); end; procedure TXPTask.MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer); var c: TWMClient; begin inherited; c:=XPWindowManager.findClient(window); if assigned(c) then c.activate; if ptinrect(clientrect,point(x,y)) then bitmap.assign((parent as TXPTaskBand).FOverTask) else begin if (FDown) then bitmap.Assign((parent as TXPTaskBand).FPressedTask) else bitmap.Assign((parent as TXPTaskBand).FNormalTask); end; end; procedure TXPTask.paint; var text: string; k: integer; begin inherited; text:=FTaskName; FIcon.transparent:=true; Canvas.Draw(11,((height-FIcon.Height) div 2)+2,FIcon); canvas.font.color:=clWhite; k:=0; while (canvas.TextWidth(text)>width-16-FIcon.width) do begin text:=copy(FTaskName,1,length(FTaskName)-k)+'...'; inc(k); end; Canvas.TextOut(FIcon.width+5+11,((height-Canvas.textheight(text)) div 2)+1,text); end; procedure TXPTask.SetDown(const Value: boolean); begin if (FDown<>Value) then begin FDown := Value; if (FDown) then bitmap.Assign((parent as TXPTaskBand).FPressedTask) else bitmap.Assign((parent as TXPTaskBand).FNormalTask); invalidate; end; end; procedure TXPTask.SetTaskName(const Value: string); begin if (Value<>FTaskName) then begin FTaskName := Value; invalidate; end; end; procedure TXPTask.setup; var dir: string; begin BevelOuter:=bvNone; dir:=getSystemInfo(XP_TASKBAR_DIR); bitmap.LoadFromFile(dir+'/taskband_button_normal.png'); FIcon.LoadFromFile(dir+'/no_icon.png'); width:=163; //Default task width align:=alLeft; end; end.
unit SDFrameStockInstant; interface uses Windows, Messages, Classes, Forms, SysUtils, BaseFrame, define_dealitem, StockInstantData_Get_Sina, Controls, VirtualTrees; type PfmeStockInstantData = ^TfmeStockInstantData; TfmeStockInstantData = record OnGetDealItem: TOnDealItemFunc; StockQuoteInstants: TInstantArray; RefreshThreadHandle: THandle; RefreshThreadId: DWORD; end; TfmeStockInstant = class(TfmeBase) vtInstant: TVirtualStringTree; private { Private declarations } fStockInstantData: TfmeStockInstantData; procedure InitVirtualTreeView; procedure InstantDataViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure BuildInstantTreeView; public { Public declarations } constructor Create(Owner: TComponent); override; procedure Initialize; override; procedure NotifyDealItem(ADealItem: PRT_DealItem); property OnGetDealItem: TOnDealItemFunc read fStockInstantData.OnGetDealItem write fStockInstantData.OnGetDealItem; end; implementation uses BaseApp, BaseStockFormApp, UtilsHttp, define_stock_quotes_instant; {$R *.dfm} { TfmeStockClass } type PInstantNodeData = ^TInstantNodeData; TInstantNodeData = record StockItem: PRT_DealItem; InstantQuote: PRT_InstantQuote; end; constructor TfmeStockInstant.Create(Owner: TComponent); begin inherited; FillChar(fStockInstantData, SizeOf(fStockInstantData), 0); InitVirtualTreeView; end; procedure TfmeStockInstant.InitVirtualTreeView; begin vtInstant.NodeDataSize := SizeOf(TInstantNodeData); vtInstant.Header.Options := [hoColumnResize, hoVisible]; vtInstant.Indent := 1; vtInstant.OnGetText := InstantDataViewGetText; end; procedure TfmeStockInstant.Initialize; begin inherited; BuildInstantTreeView; end; procedure TfmeStockInstant.InstantDataViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpVNodeData: PInstantNodeData; tmpStr: string; begin CellText := ''; tmpVNodeData := Sender.GetNodeData(Node); if nil <> tmpVNodeData then begin if nil <> tmpVNodeData.StockItem then begin tmpStr := ''; if nil <> tmpVNodeData.InstantQuote then begin tmpStr := FormatFloat('0.00', tmpVNodeData.InstantQuote.PriceRange.PriceClose.Value / 1000); //tmpStr := tmpVNodeData.InstantQuote.PriceRange.PriceClose.Value; end; CellText := tmpVNodeData.StockItem.sCode + '(' + tmpVNodeData.StockItem.Name + ')' + tmpStr; end; end; end; function CheckOutInstantQuote: PRT_InstantQuote; begin Result := System.New(PRT_InstantQuote); FillChar(Result^, SizeOf(TRT_InstantQuote), 0); end; function CheckQuoteItem(AStockItem: PRT_DealItem): PRT_InstantQuote; begin Result := nil; if nil <> AStockItem then begin Result := CheckOutInstantQuote; Result.Item := AStockItem; Result.Item.sCode := AStockItem.sCode; end; end; function ThreadProc_RefreshData(AParam: PfmeStockInstantData): HResult; stdcall; var tmpHttpSession: UtilsHttp.THttpClientSession; begin Result := 0; if nil = AParam then exit; while True do begin Sleep(20); DataGet_InstantArray_Sina(nil, @AParam.StockQuoteInstants, @tmpHttpSession, nil); end; ExitThread(Result); end; procedure TfmeStockInstant.BuildInstantTreeView; var tmpIndex: integer; procedure AddStockItemNode(AStockCode: string); var tmpStockItem: PRT_DealItem; tmpVNode: PVirtualNode; tmpVNodeData: PInstantNodeData; begin tmpStockItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(AStockCode); if nil <> tmpStockItem then begin tmpVNode := vtInstant.AddChild(nil); tmpVNodeData := vtInstant.GetNodeData(tmpVNode); tmpVNodeData.StockItem := tmpStockItem; tmpVNodeData.InstantQuote := CheckOutInstantQuote; tmpVNodeData.InstantQuote.Item := tmpStockItem; fStockInstantData.StockQuoteInstants.Data[tmpIndex] := tmpVNodeData.InstantQuote; Inc(tmpIndex); end; end; begin tmpIndex := 0; AddStockItemNode('600000'); AddStockItemNode('002414'); AddStockItemNode('600170'); fStockInstantData.RefreshThreadHandle := Windows.CreateThread(nil, 0, @ThreadProc_RefreshData, @fStockInstantData, Create_Suspended, fStockInstantData.RefreshThreadId); Windows.ResumeThread(fStockInstantData.RefreshThreadHandle); end; procedure TfmeStockInstant.NotifyDealItem(ADealItem: PRT_DealItem); begin end; end.
program FeldSort (input, output); { sortiert ein einzulesendes Feld von integer-Zahlen } const FELDGROESSE = 5; type tIndex = 1..FELDGROESSE; tFeld = array [tIndex] of integer; var EingabeFeld : tFeld; MinPos, i : tIndex; Tausch: integer; function FeldMinimumPos (Feld : tFeld; von, bis : tIndex) : tIndex; var MinimumPos, j : tIndex; begin MinimumPos := von; for j := von + 1 to bis do if Feld[j] < Feld[MinimumPos] then MinimumPos := j; FeldMinimumPos := MinimumPos; end; { FeldMinimumPos } begin { Einlesen des Feldes } writeln ('Geben Sie ', FELDGROESSE, ' Werte ein: '); for i := 1 to FELDGROESSE do readln (EingabeFeld[i]); { sortieren } for i := 1 to FELDGROESSE - 1 do begin MinPos := FeldMinimumPos (EingabeFeld, i, FELDGROESSE); Tausch := EingabeFeld[MinPos]; EingabeFeld[MinPos] := EingabeFeld[i]; EingabeFeld[i] := Tausch; end; for i := 1 to FELDGROESSE do write (EingabeFeld[i]:6); writeln; end. { Feldsort }
unit Control.ControleAWB; interface uses FireDAC.Comp.Client, Common.ENum, Control.Sistema, System.Classes, Model.ControleAWB; type TControleAWBControl = class private FControleAWB: TControleAWB; public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): TFDQuery; function LocalizarExato(aParam: array of variant): Boolean; function GetId(): Integer; property ControleAWB: TControleAWB read FControleAWB write FControleAWB; end; implementation { TControleAWBControl } constructor TControleAWBControl.Create; begin FControleAWB := TControleAWB.Create; end; destructor TControleAWBControl.Destroy; begin FControleAWB.Free; inherited; end; function TControleAWBControl.GetId: Integer; begin Result := FControleAWB.GetID(); end; function TControleAWBControl.Gravar: Boolean; begin Result := FControleAWB.Gravar(); end; function TControleAWBControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FControleAWB.Localizar(aParam); end; function TControleAWBControl.LocalizarExato(aParam: array of variant): Boolean; begin Result := FControleAWB.LocalizarExato(aParam); end; end.
{$include lem_directives.inc} unit LemStrings; interface uses LemCore; // version 0.8.0.0 added optional overriding with LVL files // version 0.8.0.1 added fixes to LemGame.pas: // 1) fix incorrect entrance order for 3 entrances, non-original DOS // 2) adds support for replaying the steel-digging glitch in replays // 3) adds support for nuke glitch const SVersion = 'V29I'; //@styledef SCheatCode = 'cheatcodes'; resourcestring SProgramName = 'Lemmix Player'; SDummyString = ''; {------------------------------------------------------------------------------- Errors -------------------------------------------------------------------------------} SMetaPieceLoadError = 'MetaPiece LoadFromStream is not defined'; SVgaSpecDimensionError_dd = 'Special Dos level graphics must be %d x %d pixels'; {------------------------------------------------------------------------------- MenuScreen -------------------------------------------------------------------------------} //@styledef SProgramText = {$ifdef orig} 'Lemmings Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef ohno} 'Oh No! More Lemmings! Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef H94} 'Holiday Lemmings 1994 Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef xmas} 'Xmas Lemmings 1991 & 1992 Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef covox} 'Save the Lemmings Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef prima} 'Lemmings Official Companion Clone (' + SVersion + ')' + #13 + {$endif} {$ifdef extra} 'Extra Levels Lemmix Player (' + SVersion + ')' + #13 + {$endif} {$ifdef cust} {$ifndef flexi}'Customized Lemmings Clone (' + SVersion + ')' +{$endif} #13 + {$endif} {$ifndef flexi}'By Eric Langedijk, ccexplore, namida'{$else}'Flexible Lemmix Player'{$endif}; // max size for string that fits in the scrolling reel = 34 // 1234567890123456789012345678901234 SCredits = {$ifdef flexi}'Flexi Player ' + SVersion + #13 +{$endif} 'Thanks to...' + #13 + {$ifdef flexi}'EricLang for base Lemmix' + #13 + 'ccexplore for Lemmix 0.8.0.1' + #13 + 'namida for Flexi player and' + #13 + 'general updates to Lemmix' + #13 +{$endif} 'DMA for the original game' + #13 + 'ccexplore for game mechanics' + #13 + 'Alex A. Denisov for Graphics32' + #13 + 'Erik Turner for ZLibEx' + #13 + 'Peter Morris for FastStrings' + #13 + 'Un4seen Development for Bassmod at' + #13 + 'http://www.un4seen.com/' + #13 + 'The Lemmings Forums at' + #13 + 'https://www.lemmingsforums.net/' + #13 + 'Volker Oth, ccexplore and Mindless for sharing source code, resources ' + 'and technical information about Lemmings' + #13 + 'Add''l updates from Aaron Kelley' + #13 + 'Original credits...' + #13 + 'Lemmings By DMA Design' + #13 + 'Programming By Russell Kay' + #13 + 'Animation By Gary Timmons' + #13 + 'Graphics By Scott Johnston' + #13 + 'Music By Brian Johnston & Tim Wright' + #13 + 'PC Music By Tony Williams' + #13 + 'Copyright 1991 Psygnosis Ltd.'; {------------------------------------------------------------------------------- LevelCodeScreen -------------------------------------------------------------------------------} SEnterCode = 'Enter Code'; SIncorrectCode = 'INCORRECT CODE'; SCodeForLevel_sd = 'Code for %s' + #13 + 'Level %d'; {------------------------------------------------------------------------------- PreviewScreen -------------------------------------------------------------------------------} SPreviewString = 'Level %d ' + '%s' + #13#13#13 + ' Number of Lemmings %d' + #13#13 + ' %s To Be Saved' + #13#13 + ' Release Rate %d' + #13#13 + ' Time %d Minutes' + #13#13 + ' Rating %s' + #13#13#13 + ' Press mouse button to continue'; {------------------------------------------------------------------------------- Game Screen Info Panel -------------------------------------------------------------------------------} SSkillPanelTemplate = '..............' + 'OUT_.....' + 'IN_.....' + 'TIME_.-..'; SAthlete = 'Athlete'; SWalker = 'Walker'; SJumper = 'Jumper'; SDigger = 'Digger'; SClimber = 'Climber'; SDrowner = 'Drowner'; SHoister = 'Hoister'; SBuilder = 'Builder'; SBasher = 'Basher'; SMiner = 'Miner'; SFaller = 'Faller'; SFloater = 'Floater'; SSplatter = 'Splatter'; SExiter = 'Exiter'; SVaporizer = 'Frier'; SBlocker = 'Blocker'; SShrugger = 'Shrugger'; SOhnoer = 'Ohnoer'; SExploder = 'Bomber'; {------------------------------------------------------------------------------- Postview Screen -------------------------------------------------------------------------------} SYourTimeIsUp = 'Your time is up!'; SAllLemmingsAccountedFor = 'All lemmings accounted for.'; SYouRescuedYouNeeded_ss = 'You rescued %s' + #13 + 'You needed %s'; SResult0 = 'ROCK BOTTOM! I hope for your sake' + #13 + 'that you nuked that level.'; SResult1 = 'Better rethink your strategy before' + #13 + 'you try this level again!'; SResult2 = 'A little more practice on this level' + #13 + 'is definitely recommended.'; SResult3 = 'You got pretty close that time.' + #13 + 'Now try again for that few % extra.'; SResult4 = 'OH NO, So near and yet so far (teehee)' + #13 + 'Maybe this time.....'; SResult5 = 'RIGHT ON. You can''t get much closer' + #13 + 'than that. Let''s try the next...'; SResult6 = 'That level seemed no problem to you on' + #13 + 'that attempt. Onto the next....'; SResult7 = 'You totally stormed that level!' + #13 + 'Let''s see if you can storm the next...'; SResult8 = 'Superb! You rescued every lemmings on' + #13 + 'that level. Can you do it again....'; SCongratulationOrig = #13 + #13 + 'Congratulations!' + #13 + #13 + #13 + #13 + #13 + 'Everybody here at DMA Design salutes you' + #13 + 'as a MASTER Lemmings player. Not many' + #13 + 'people will complete the Mayhem levels,' + #13 + 'you are definitely one of the elite' + #13 + #13 + #13 + #13 + #13 + #13 + 'Now hold your breath for the data disk'; SResultOhNo0 = 'Oh dear, not even one poor Lemming' + #13 + 'saved. Try a little harder next time.'; SResultOhNo1 = 'Yes, well, err, erm, maybe that is' + #13 + 'NOT the way to do this level.'; SResultOhNo2 = 'We are not too impressed with your' + #13 + 'attempt at that level!'; SResultOhNo3 = 'Getting close. You are either pretty' + #13 + 'good, or simply lucky.'; SResultOhNo4 = 'Shame, You were short by a tiny amount.' + #13 + 'Go for it this time.'; SResultOhNo5 = 'Just made it by the skin of your' + #13 + 'teeth. Time to progress...'; SResultOhNo6 = 'More than enough. You have the makings' + #13 + 'of a master Lemmings player.'; SResultOhNo7 = 'What a fine display of Lemmings control.' + #13 + 'Take a bow then carry on with the game.'; SResultOhNo8 = 'WOW! You saved every Lemming.' + #13 + 'TOTALLY EXCELLENT!'; SCongratulationOhNo = #13 + #13 + 'Congratulations!' + #13 + #13 + #13 + #13 + #13 + #13 + 'You are truly an Excellent' + #13 + 'Lemmings player' + #13 + #13 + 'The Lemmings Saga continues at a' + #13 + 'later date, watch this space'; SYourAccessCode_ds = 'Your Access Code for Level %d' + #13 + 'is %s'; SPressLeftMouseForNextLevel = 'Press left mouse button for next level'; SPressLeftMouseToRetryLevel = 'Press left mouse button to retry level'; SPressRightMouseForMenu = 'Press right mouse button for menu'; SPressMouseToContinue = 'Press mouse button to continue'; {------------------------------------------------------------------------------- SkillPanel hints (not used yet) -------------------------------------------------------------------------------} SDigHint = 'Dig'; SClimbHint = 'Climb'; SBuildHint = 'Build'; SBashHint = 'Bash'; SMineHint = 'Mine'; SFloatHint = 'Umbrella'; SBlockHint = 'Block'; SExplodeHint = 'Bomb'; const LemmingActionStrings: array[TBasicLemmingAction] of string = ( SDummyString, SWalker, SJumper, SDigger, SClimber, SDrowner, SHoister, SBuilder, SBasher, SMiner, SFaller, SFloater, SSplatter, SExiter, SVaporizer, SBlocker, SShrugger, SOhnoer, SExploder ); //@styledef {$ifdef orig} ResultStrings: array[0..8] of string = ( SResult0, SResult1, SResult2, SResult3, SResult4, SResult5, SResult6, SResult7, SResult8 ); SCongrats: string = SCongratulationOrig; {$endif} {$ifdef ohno} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef h94} {TODO: check this ones out} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef xmas} {TODO: check this ones out} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef covox} {TODO: check this ones out} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef prima} {TODO: check this ones out} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef extra} {TODO: check this ones out} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} {$ifdef cust} ResultStrings: array[0..8] of string = ( SResultOhNo0, SResultOhNo1, SResultOhNo2, SResultOhNo3, SResultOhNo4, SResultOhNo5, SResultOhNo6, SResultOhNo7, SResultOhNo8 ); SCongrats: string = SCongratulationOhNo; {$endif} implementation end.
Unit TERRA_ClipRect; {$I terra.inc} Interface Uses TERRA_Vector2D, TERRA_Vector3D, TERRA_Matrix3x3; Type ClipRectStyle = ( clipNothing = 0, clipSomething = 1, clipEverything = 2 ); ClipRect = Object Protected _Style:ClipRectStyle; _X, _Y:Single; _Width, _Height:Single; Public Procedure SetHeight(const Value: Single); Procedure SetWidth(const Value: Single); Procedure SetX(const Value: Single); Procedure SetY(const Value: Single); Procedure SetStyle(Const ClipStyle:ClipRectStyle); Procedure GetRealRect(Out X1, Y1, X2, Y2:Single{; Landscape:Boolean}); Procedure Transform(Const M:Matrix3x3); Procedure Merge(Const Other:ClipRect); Property X:Single Read _X Write SetX; Property Y:Single Read _Y Write SetY; Property Style:ClipRectStyle Read _Style Write SetStyle; Property Width:Single Read _Width Write SetWidth; Property Height:Single Read _Height Write SetHeight; End; Function ClipRectCreate(X,Y, Width, Height:Single):ClipRect; Implementation { ClipRect } Procedure ClipRect.GetRealRect(Out X1, Y1, X2, Y2: Single{; Landscape:Boolean}); Var UIWidth, UIHeight:Integer; Begin { If (Landscape) Then Begin UIWidth := GraphicsManager.Instance.UIViewport.Width; UIHeight := GraphicsManager.Instance.UIViewport.Height; X2 := UIWidth - (Self.Y); X1 := UIWidth - (X2 + Self.Height); Y2 := UIHeight - (Self.X); Y1 := UIHeight - (Y2 + Self.Width); End Else} Begin X1 := Self.X; X2 := X1 + Self.Width; Y1 := Self.Y; Y2 := Y1 + Self.Height; End; End; Procedure ClipRect.SetStyle(Const ClipStyle:ClipRectStyle); Begin _Style := ClipStyle; End; Procedure ClipRect.SetHeight(const Value: Single); Begin _Height := Value; _Style := clipSomething; End; Procedure ClipRect.SetWidth(const Value: Single); Begin _Width := Value; _Style := clipSomething; End; Procedure ClipRect.SetX(const Value: Single); Begin _X := Value; _Style := clipSomething; End; Procedure ClipRect.SetY(const Value: Single); Begin _Y := Value; _Style := clipSomething; End; Procedure ClipRect.Transform(const M: Matrix3x3); Var I:Integer; P:Array[0..3] Of Vector2D; T:Vector2D; MinX, MinY, MaxX, MaxY:Single; Begin P[0].X := _X; P[0].Y := _Y; P[1].X := _X + _Width; P[1].Y := _Y; P[2].X := _X + _Width; P[2].Y := _Y + _Height; P[3].X := _X; P[3].Y := _Y + _Height; MaxX := -9999; MaxY := -9999; MinX := 9999; MinY := 9999; For I:=0 To 3 Do Begin T := M.Transform(P[I]); If (T.X>MaxX) Then MaxX := T.X; If (T.Y>MaxY) Then MaxY := T.Y; If (T.X<MinX) Then MinX := T.X; If (T.Y<MinY) Then MinY := T.Y; End; Self.X := MinX; Self.Y := MinY; Self.Width := MaxX - MinX; Self.Height := MaxY - MinY; End; Procedure ClipRect.Merge(const Other: ClipRect); Var Diff:Single; X1, Y1, X2, Y2: Single; PX1, PY1, PX2, PY2: Single; Begin If (_Style = clipEverything) Or (Other._Style = clipNothing) Then Begin Exit; End; If (_Style = clipNothing) Then Begin _X := Other._X; _Y := Other._Y; _Width := Other._Width; _Height := Other._Height; _Style := Other._Style; Exit; End; Self.GetRealRect(X1, Y1, X2, Y2); Other.GetRealRect(PX1, PY1, PX2, PY2); If (PX1>X1) Then X1 := PX1; If (PY1>Y1) Then Y1 := PY1; If (PX2<X2) Then X2 := PX2; If (PY2>Y2) Then Y2 := PY2; _X := X1; _Y := Y1; _Width := X2-X1; _Height := Y2-Y1; End; Function ClipRectCreate(X,Y, Width, Height:Single):ClipRect; Begin Result._Style := clipSomething; Result._X := X; Result._Y := Y; Result._Width := Width; Result._Height := Height; End; End.
unit SingleDriverRoundTripGenericUnit; interface uses SysUtils, Route4MeExamplesUnit, BaseExampleUnit, NullableBasicTypesUnit; type TSingleDriverRoundTripGeneric = class(TBaseExample) public function Execute: NullableString; end; implementation uses IOptimizationParametersProviderUnit, OptimizationParametersUnit, AddressUnit, SingleDriverRoundTripGenericRequestUnit, SingleDriverRoundTripGenericResponseUnit, SingleDriverRoundTripGenericTestDataProviderUnit, RouteParametersUnit, SettingsUnit, EnumsUnit; function TSingleDriverRoundTripGeneric.Execute: NullableString; var DataProvider: IOptimizationParametersProvider; ErrorString: String; Request: TSingleDriverRoundTripGenericRequest; Response: TSingleDriverRoundTripGenericResponse; Address: TAddress; Parameters: TOptimizationParameters; begin Result := NullableString.Null; DataProvider := TSingleDriverRoundTripGenericTestDataProvider.Create; Request := TSingleDriverRoundTripGenericRequest.Create; try Parameters := DataProvider.OptimizationParameters; try Request.Parameters := Parameters.Parameters.Value as TRouteParameters; Request.Addresses := Parameters.Addresses; Response := Route4MeManager.Connection.Post(TSettings.EndPoints.Optimization, Request, TSingleDriverRoundTripGenericResponse, ErrorString) as TSingleDriverRoundTripGenericResponse; try WriteLn(''); if (Response <> nil) then begin WriteLn('SingleDriverRoundTripGeneric executed successfully'); WriteLn(''); WriteLn(Format('Optimization Problem ID: %s', [Response.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(Response.MyState)]])); WriteLn(''); for Address in Response.Addresses do begin WriteLn(Format('Address: %s', [Address.AddressString])); WriteLn(Format('Route ID: %s', [Address.RouteId.ToString])); end; Result := Response.OptimizationProblemId; end else WriteLn(Format('SingleDriverRoundTripGeneric error "%s"', [ErrorString])); finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; finally FreeAndNil(Request); end; end; end.
unit FPLIL; {$MODE OBJFPC}{$H+} // Enable recursion limit (similar to C LIL, but uses constant value below) { $DEFINE LIL_ENABLE_RECLIMIT} interface uses Classes, SysUtils; const LIL_VERSION_STRING = '0.1'; type TLILValue = class; TLILVariable = class; TLILEnvironment = class; TLILFunction = class; TLIL = class; TLILFunctionProcArgs = array of TLILValue; TLILFunctionProc = function(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; TLILOnSetVarAction = (losaDefault, losaReplace, losaIgnore); TLILOnGetVarAction = (logaDefault, logaReplace); TLILOnExit = procedure(LIL: TLIL; Arg: TLILValue) of object; TLILOnWrite = procedure(LIL: TLIL; Chars: string) of object; TLILOnRead = procedure(LIL: TLIL; AFileName: string; out AContent: string) of object; TLILOnStore = procedure(LIL: TLIL; AFileName, AContent: string) of object; TLILOnSource = procedure(LIL: TLIL; AFileName: string; out AContent: string) of object; TLILOnError = procedure(LIL: TLIL; APosition: Integer; AMessage: string) of object; TLILOnSetVar = procedure(LIL: TLIL; AName: string; const AValue: TLILValue; var AReplacement: TLILValue; var ASetVarAction: TLILOnSetVarAction) of object; TLILOnGetVar = procedure(LIL: TLIL; AName: string; const AValue: TLILValue; var AReplacement: TLILValue; var AGetVarAction: TLILOnGetVarAction) of object; TLILSetVarLocality = (lsvlGlobal, lsvlLocal, lsvlLocalNew, lsvlLocalOnly); TLILValue = class private FData: string; FLength: Integer; function ToInteger: Int64; function ToFloat: Extended; function ToBoolean: Boolean; public procedure AppendChar(Ch: Char); procedure AppendString(Str: string); procedure AppendValue(AValue: TLILValue); function Clone: TLILValue; function Equals(StrVal: string): Boolean; function Equals(IntVal: Int64): Boolean; function Equals(FloatVal: Extended): Boolean; function Equals(LILVal: TLILValue): Boolean; property StringValue: string read FData; property IntegerValue: Int64 read ToInteger; property FloatValue: Extended read ToFloat; property BooleanValue: Boolean read ToBoolean; property Length: Integer read FLength; end; { TLILVariable } TLILVariable = class private FName: string; FEnvironment: TLILEnvironment; FValue: TLILValue; FWatches: array of TMethod; FCodeWatch: string; procedure SetValue(AValue: TLILValue); public constructor Create(AName: string; AEnvironment: TLILEnvironment); destructor Destroy; override; procedure AddWatch(const AWatch: TNotifyEvent); procedure RemoveWatch(const AWatch: TNotifyEvent); property Name: string read FName; property Environment: TLILEnvironment read FEnvironment; property Value: TLILValue read FValue write SetValue; end; { TLILEnvironment } TLILEnvironment = class private FLIL: TLIL; Parent: TLILEnvironment; Func: TLILFunction; CatcherFor: TLILValue; Vars: TFPList; RetVal: TLILValue; RetValSet: Boolean; BreakRun: Boolean; procedure RegisterVariable(AVariable: TLILVariable); public constructor Create(ALIL: TLIL; AParent: TLILEnvironment); destructor Destroy; override; property LIL: TLIL read FLIL; end; { TLILList } TLILList = class private FValues: TFPList; function GetCount: Integer; function GetValue(AIndex: Integer): TLILValue; function ToFunctionArgs: TLILFunctionProcArgs; public constructor Create; destructor Destroy; override; procedure Add(AValue: TLILValue); procedure AddString(AString: string); procedure AddInteger(AInteger: Int64); procedure AddFloat(AFloat: Extended); procedure AddBoolean(ABoolean: Boolean); function IndexOf(AValue: TLILValue): Integer; function IndexOfString(AString: string): Integer; function IndexOfInteger(AInteger: Int64): Integer; function IndexOfFloat(AFloat: Extended): Integer; function IndexOfBoolean(ABoolean: Boolean): Integer; function Has(AValue: TLILValue): Boolean; inline; function HasString(AString: string): Boolean; inline; function HasInteger(AInteger: Int64): Boolean; inline; function HasFloat(AFloat: Extended): Boolean; inline; function HasBoolean(ABoolean: Boolean): Boolean; inline; function ToValue(DoEscape: Boolean=True): TLILValue; property Count: Integer read GetCount; property Values[AIndex: Integer]: TLILValue read GetValue; default; end; TLILFunction = class private FName: string; Code: TLILValue; ArgNames: TLILList; Proc: TLILFunctionProc; function GetBody: string; inline; function IsNative: Boolean; inline; function GetArguments: Integer; inline; function GetArgument(AIndex: Integer): string; inline; public constructor Create; destructor Destroy; override; property Name: string read FName; property Body: string read GetBody; property Native: Boolean read IsNative; property FunctionProc: TLILFunctionProc read Proc; property Arguments: Integer read GetArguments; property Argument[AIndex: Integer]: string read GetArgument; end; TLIL = class(TComponent) private Code: string; RootCode: string; CLen: Integer; Head: Integer; IgnoreEOL: Boolean; Funcs: array of TLILFunction; FFuncName: string; SysFuncs: Integer; Catcher: string; InCatcher: Integer; DollarPrefix: string; Env: TLILEnvironment; RootEnv: TLILEnvironment; DownEnv: TLILEnvironment; Empty: TLILValue; FError: Boolean; FErrorHead: Integer; FErrorMessage: string; ParseDepth: Integer; FData: Pointer; FixHead: Boolean; FOnExit: TLILOnExit; FOnWrite: TLILOnWrite; FOnRead: TLILOnRead; FOnStore: TLILOnStore; FOnSource: TLILOnSource; FOnError: TLILOnError; FOnSetVar: TLILOnSetVar; FOnGetVar: TLILOnGetVar; procedure RegisterStandardFunctions; function FindLocalVar(AEnv: TLILEnvironment; AName: string): TLILVariable; function FindVar(AEnv: TLILEnvironment; AName: string): TLILVariable; function FindFunction(AName: string): TLILFunction; function AddFunction(AName: string): TLILFunction; function AtEol: Boolean; procedure SkipSpaces; function GetBracketPart: TLILValue; function GetDollarPart: TLILValue; function NextWord: TLILValue; function Substitute: TLILList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function AllocString(Str: string): TLILValue; inline; class function AllocInteger(Int: Int64): TLILValue; inline; class function AllocFloat(Float: Extended): TLILValue; inline; class function AllocBoolean(Bool: Boolean): TLILValue; inline; class function ToString(AValue: TLILValue): string; inline; class function ToInteger(AValue: TLILValue): Int64; inline; class function ToFloat(AValue: TLILValue): Extended; inline; class function ToBoolean(AValue: TLILValue): Boolean; inline; class function Clone(AValue: TLILValue): TLILValue; inline; procedure SetError(AErrorMessage: string); procedure Register(AName: string; AProc: TLILFunctionProc); function GetFunction(AName: string): TLILFunction; inline; function SetVar(AName: string; AValue: TLILValue; Locality: TLILSetVarLocality): TLILVariable; function GetVar(AName: string; DefaultValue: TLILValue=nil): TLILValue; function FindVar(AName: string): TLILVariable; function FindGlobal(AName: string): TLILVariable; function UnusedName(Part: string): string; procedure PushEnv; procedure PopEnv; function SubstituteToList(ACode: TLILValue): TLILList; function SubstituteToValue(ACode: TLILValue): TLILValue; function EvaluateExpression(ACode: string): TLILValue; function EvaluateExpressionValue(AValue: TLILValue): TLILValue; function Parse(ACommand: string; FuncLevel: Boolean=False): TLILValue; function ParseValue(ACmdValue: TLILValue; FuncLevel: Boolean=False): TLILValue; procedure WriteString(Chars: string); function ToString: string; override; property FuncName: string read FFuncName; property Error: Boolean read FError; property ErrorHead: Integer read FErrorHead; property ErrorMessage: string read FErrorMessage; property Data: Pointer read FData write FData; published property EvaluatedCode: string read Code; property OnExit: TLILOnExit read FOnExit write FOnExit; property OnWrite: TLILOnWrite read FOnWrite write FOnWrite; property OnRead: TLILOnRead read FOnRead write FOnRead; property OnStore: TLILOnStore read FOnStore write FOnStore; property OnSource: TLILOnSource read FOnSource write FOnSource; property OnError: TLILOnError read FOnError write FOnError; property OnSetVar: TLILOnSetVar read FOnSetVar write FOnSetVar; property OnGetVar: TLILOnGetVar read FOnGetVar write FOnGetVar; end; var LILFormatSettings: TFormatSettings; procedure Register; implementation {$HINTS-} {$COPERATORS ON} {$IFDEF LAZFPLIL} uses LResources; {$ENDIF} const MAX_CATCHER_DEPTH = 16384; {$IFDEF LIL_ENABLE_RECLIMIT} MAX_RECLIMIT = 10000; {$ENDIF} function Sign(a: Extended): Extended; inline; begin if a < 0 then Result:=-1 else Result:=1; end; function FMod(a, b: Extended): Extended; inline; begin Result:=Sign(a)*(Abs(a) - Trunc(Abs(a/b))*Abs(b)); end; function IsPunct(Ch: Char): Boolean; inline; begin Result:=Ch in [#33, #34, #35, #36, #37, #38, #39, #40, #41, #42, #43, #44, #45, #46, #47, #58, #59, #60, #61, #62, #63, #64, #91, #92, #93, #94, #95, #96, #123, #124, #125, #126]; end; function IsSpace(Ch: Char): Boolean; inline; begin Result:=Ch in [#9..#13, #32]; end; function IsDigit(Ch: Char): Boolean; inline; begin Result:=Ch in ['0'..'9']; end; function IsXDigit(Ch: Char): Boolean; inline; begin Result:=Ch in ['0'..'9', 'A'..'F', 'a'..'f']; end; function IsAlpha(Ch: Char): Boolean; inline; begin Result:=Ch in ['A'..'Z', 'a'..'z']; end; function IsAlNum(Ch: Char): Boolean; inline; begin Result:=IsAlpha(Ch) or IsDigit(Ch); end; function IsIdpart(Ch: Char): Boolean; inline; begin Result:=IsAlNum(Ch) or (Ch='_'); end; function IsSpecial(Ch: Char): Boolean; inline; begin Result:=Ch in [';', '$', '[', ']', '{', '}', '"', '''']; end; { Standard functions } function FncReflect(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var RefType: string; Func: TLILFunction; Funcs, Vars: TLILList; Env: TLILEnvironment; i: Integer; begin Result:=nil; if Length(Args)=0 then exit; RefType:=Args[0].StringValue; if RefType='version' then begin Result:=TLIL.AllocString(LIL_VERSION_STRING); end else if RefType='args' then begin if Length(Args) < 2 then exit; Func:=LIL.FindFunction(Args[1].StringValue); if not Assigned(Func) or not Assigned(Func.ArgNames) then exit; Result:=Func.ArgNames.ToValue; end else if RefType='body' then begin if Length(Args) < 2 then exit; Func:=LIL.FindFunction(Args[1].StringValue); if not Assigned(Func) or Func.Native then exit; Result:=TLIL.Clone(Func.Code); end else if RefType='func-count' then begin Result:=TLIL.AllocInteger(Length(LIL.Funcs)); end else if RefType='funcs' then begin Funcs:=TLILList.Create; for i:=0 to Length(LIL.Funcs) - 1 do Funcs.AddString(LIL.Funcs[i].Name); Result:=Funcs.ToValue; FreeAndNil(Funcs); end else if RefType='vars' then begin Env:=LIL.Env; Vars:=TLILList.Create; for i:=0 to Env.Vars.Count - 1 do Vars.AddString(TLILVariable(Env.Vars[i]).Name); Result:=Vars.ToValue; FreeAndNil(Vars); end else if RefType='globals' then begin Env:=LIL.RootEnv; Vars:=TLILList.Create; for i:=0 to Env.Vars.Count - 1 do Vars.AddString(TLILVariable(Env.Vars[i]).Name); Result:=Vars.ToValue; FreeAndNil(Vars); end else if RefType='has-func' then begin if Length(Args) < 2 then exit; if Assigned(LIL.FindFunction(Args[1].StringValue)) then Result:=TLIL.AllocString('1'); end else if RefType='has-var' then begin if Length(Args) < 2 then exit; if Assigned(LIL.FindVar(LIL.Env, Args[1].StringValue)) then Result:=TLIL.AllocString('1'); end else if RefType='has-global' then begin if Length(Args) < 2 then exit; if Assigned(LIL.FindVar(LIL.RootEnv, Args[1].StringValue)) then Result:=TLIL.AllocString('1'); end else if RefType='error' then begin if LIL.Error then Result:=TLIL.AllocString(LIL.ErrorMessage); end else if RefType='dollar-prefix' then begin Result:=TLIL.AllocString(LIL.DollarPrefix); if Length(Args) > 1 then LIL.DollarPrefix:=Args[1].StringValue; end else if RefType='this' then begin Env:=LIL.Env; while (Env <> LIL.RootEnv) and not Assigned(Env.CatcherFor) and not Assigned(Env.Func) do Env:=Env.Parent; if Assigned(Env.CatcherFor) then Result:=TLIL.AllocString(LIL.Catcher) else if Env=LIL.RootEnv then Result:=TLIL.AllocString(LIL.RootCode) else if Assigned(Env.Func) then Result:=Env.Func.Code.Clone; end else if RefType='name' then begin Env:=LIL.Env; while (Env <> LIL.RootEnv) and not Assigned(Env.CatcherFor) and not Assigned(Env.Func) do Env:=Env.Parent; if Assigned(Env.CatcherFor) then Result:=Env.CatcherFor else if Env=LIL.RootEnv then Result:=nil else if Assigned(Env.Func) then Result:=TLIL.AllocString(Env.Func.Name); end; end; function FncFunc(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Name: string; Func: TLILFunction; FArgs: TLILList; begin if Length(Args)=0 then exit(nil); if Length(Args) >= 3 then begin Result:=TLIL.Clone(Args[0]); FArgs:=LIL.SubstituteToList(Args[1]); Func:=LIL.AddFunction(TLIL.ToString(Result)); FreeAndNil(Func.ArgNames); Func.ArgNames:=FArgs; Func.Code:=TLIL.Clone(Args[2]); end else begin Name:=LIL.UnusedName('anonymous-function'); if Name='' then exit(nil); Result:=TLIL.AllocString(Name); if Length(Args) < 2 then begin Func:=LIL.AddFunction(Name); Func.ArgNames:=TLILList.Create; Func.ArgNames.AddString('args'); Func.Code:=TLIL.Clone(Args[0]); end else begin FArgs:=LIL.SubstituteToList(Args[0]); Func:=LIL.AddFunction(Name); Func.ArgNames:=FArgs; Func.Code:=TLIL.Clone(Args[1]); end; end; end; function FncRename(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Func: TLILFunction; begin if Length(Args) < 2 then exit(nil); Func:=LIL.FindFunction(TLIL.ToString(Args[0])); if Func=nil then begin LIL.SetError('Unknown function ''' + TLIL.ToString(Args[0]) + ''''); exit(nil); end; Result:=TLIL.AllocString(Func.Name); Func.FName:=TLIL.ToString(Args[1]); end; function FncUnusedName(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) > 0 then Result:=TLIL.AllocString(LIL.UnusedName(Args[0].StringValue)) else Result:=TLIL.AllocString(LIL.UnusedName('unusedname')); end; function FncQuote(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i: Integer; s: string = ''; begin for i:=0 to Length(Args) - 1 do begin if i > 0 then s += ' '; s += TLIL.ToString(Args[i]); end; Result:=TLIL.AllocString(s); end; function FncSet(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i: Integer = 0; Variable: TLILVariable = nil; Locality: TLILSetVarLocality = lsvlLocal; begin if Length(Args)=0 then exit(nil); if Args[0].Equals('global') then begin Locality:=lsvlGlobal; i:=1; end; while i < Length(Args) do begin if Length(Args)=i + 1 then exit(TLIL.Clone(LIL.GetVar(TLIL.ToString(Args[i])))); Variable:=LIL.SetVar(TLIL.ToString(Args[i]), Args[i + 1], Locality); Inc(i, 2); end; if Variable=nil then Result:=nil else Result:=TLIL.Clone(Variable.Value); end; function FncLocal(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i: Integer; VarName: string; begin for i:=0 to Length(Args) - 1 do begin VarName:=TLIL.ToString(Args[i]); if not Assigned(LIL.FindLocalVar(LIL.Env, VarName)) then LIL.SetVar(VarName, LIL.Empty, lsvlLocalNew); end; Result:=nil; end; function FncWrite(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Msg: string = ''; i: Integer; begin for i:=0 to Length(Args) - 1 do begin if i > 0 then Msg += ' '; Msg += TLIL.ToString(Args[i]); end; LIL.WriteString(Msg); Result:=nil; end; function FncPrint(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin Result:=FncWrite(LIL, Args); LIL.WriteString(#10); end; function FncEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Cmd: string; i: Integer; begin if Length(Args)=1 then exit(LIL.ParseValue(Args[0])); if Length(Args) > 1 then begin Cmd:=''; for i:=0 to Length(Args) - 1 do begin if i > 0 then Cmd += ' '; Cmd += TLIL.ToString(Args[i]); end; Result:=LIL.Parse(Cmd); end else Result:=nil; end; function FncTopEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var ThisEnv, ThisDownEnv: TLILEnvironment; begin ThisEnv:=LIL.Env; ThisDownEnv:=LIL.DownEnv; LIL.Env:=LIL.RootEnv; LIL.DownEnv:=ThisEnv; Result:=FncEval(LIL, Args); LIL.Env:=ThisEnv; LIL.DownEnv:=ThisDownEnv; end; function FncUpEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var ThisEnv, ThisDownEnv: TLILEnvironment; begin if LIL.RootEnv=LIL.Env then exit(FncEval(LIL, Args)); ThisEnv:=LIL.Env; ThisDownEnv:=LIL.DownEnv; LIL.Env:=LIL.Env.Parent; LIL.DownEnv:=ThisEnv; Result:=FncEval(LIL, Args); LIL.Env:=ThisEnv; LIL.DownEnv:=ThisDownEnv; end; function FncDownEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var UpEnv, DownEnv: TLILEnvironment; begin if LIL.DownEnv=nil then exit(FncEval(LIL, Args)); UpEnv:=LIL.Env; DownEnv:=LIL.DownEnv; LIL.Env:=DownEnv; LIL.DownEnv:=nil; Result:=FncEval(LIL, Args); LIL.Env:=UpEnv; LIL.DownEnv:=DownEnv; end; function FncEnvEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var InVars: TLILList = nil; OutVars: TLILList = nil; VarValues: array of TLILValue; CodeIndex: Integer = 0; i: Integer; begin if Length(Args)=0 then Exit(nil) else if Length(Args)=1 then CodeIndex:=0 else if Length(Args) >= 2 then begin InVars:=LIL.SubstituteToList(Args[0]); SetLength(VarValues, InVars.Count); for i:=0 to InVars.Count - 1 do VarValues[i]:=TLIL.Clone(LIL.GetVar(TLIL.ToString(InVars[i]))); if Length(Args) > 2 then begin CodeIndex:=2; OutVars:=LIL.SubstituteToList(Args[1]); end else CodeIndex:=1; end; LIL.PushEnv; if Assigned(InVars) then for i:=0 to InVars.Count - 1 do begin LIL.SetVar(TLIL.ToString(InVars[i]), VarValues[i], lsvlLocalNew); FreeAndNil(VarValues[i]); end; Result:=LIL.ParseValue(Args[CodeIndex], False); if Assigned(InVars) or Assigned(OutVars) then if Assigned(OutVars) then for i:=0 to OutVars.Count - 1 do VarValues[i]:=TLIL.Clone(LIL.GetVar(TLIL.ToString(OutVars[i]))) else for i:=0 to InVars.Count - 1 do VarValues[i]:=TLIL.Clone(LIL.GetVar(TLIL.ToString(InVars[i]))); LIL.PopEnv; if Assigned(InVars) then begin if Assigned(OutVars) then for i:=0 to OutVars.Count - 1 do begin LIL.SetVar(TLIL.ToString(OutVars[i]), VarValues[i], lsvlLocal); FreeAndNil(VarValues[i]); end else for i:=0 to InVars.Count - 1 do begin LIL.SetVar(TLIL.ToString(InVars[i]), VarValues[i], lsvlLocal); FreeAndNil(VarValues[i]); end; FreeAndNil(InVars); FreeAndNil(OutVars); end; end; function FncJailEval(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Base, i: Integer; SubLIL: TLIL; begin if Length(Args)=0 then exit(nil); if Args[0].Equals('clean') then begin Base:=1; if Length(Args)=1 then exit(nil); end else Base:=0; SubLIL:=TLIL.Create(LIL); if Base <> 1 then begin for i:=LIL.SysFuncs to Length(LIL.Funcs) - 1 do begin if LIL.Funcs[i].Native then SubLIL.Register(LIL.Funcs[i].Name, LIL.Funcs[i].Proc); end; end; Result:=SubLIL.ParseValue(Args[Base], True); FreeAndNil(SubLIL); end; function FncCount(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; begin if Length(Args)=0 then exit(TLIL.AllocString('0')); List:=LIL.SubstituteToList(Args[0]); Result:=TLIL.AllocInteger(List.Count); FreeAndNil(List); end; function FncIndex(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; Index: Integer; begin if Length(Args) < 2 then exit(nil); List:=LIL.SubstituteToList(Args[0]); Index:=TLIL.ToInteger(Args[1]); Result:=TLIL.Clone(List[Index]); FreeAndNil(List); end; function FncIndexOf(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; i, Index: Integer; begin if Length(Args) < 2 then exit(nil); List:=LIL.SubstituteToList(Args[0]); Index:=-1; for i:=0 to List.Count - 1 do if List[i].Equals(Args[1]) then begin Index:=i; break; end; Result:=TLIL.AllocInteger(Index); FreeAndNil(List); end; function FncFilter(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List, Filtered: TLILList; i: Integer; VarName: string = 'x'; Base: Integer = 0; begin Result:=nil; if Length(Args) < 1 then exit; if Length(Args) < 2 then exit(TLIL.Clone(Args[0])); if Length(Args) > 2 then begin Base:=1; VarName:=Args[0].StringValue; end; List:=LIL.SubstituteToList(Args[Base]); Filtered:=TLILList.Create; for i:=0 to List.Count - 1 do begin if LIL.Env.BreakRun then Break; LIL.SetVar(VarName, List[i], lsvlLocalOnly); Result:=LIL.EvaluateExpressionValue(Args[Base + 1]); if TLIL.ToBoolean(Result) then Filtered.Add(List[i].Clone); FreeAndNil(Result); end; FreeAndNil(List); Result:=Filtered.ToValue; FreeAndNil(Filtered); end; function FncAppend(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; Base, i: Integer; VarName: string; Locality: TLILSetVarLocality = lsvlLocal; begin if Length(Args) < 2 then exit(nil); Base:=1; VarName:=TLIL.ToString(Args[0]); if VarName='global' then begin if Length(Args) < 3 then exit(nil); VarName:=TLIL.ToString(Args[1]); Base:=2; Locality:=lsvlGlobal; end; List:=LIL.SubstituteToList(LIL.GetVar(VarName)); for i:=Base to Length(Args) - 1 do List.Add(Args[i]); Result:=List.ToValue; FreeAndNil(List); LIL.SetVar(VarName, Result, Locality); end; function FncSlice(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List, Slice: TLILList; i, FromIndex, ToIndex: Integer; begin if Length(Args) < 1 then exit(nil); if Length(Args) < 2 then exit(TLIL.Clone(Args[0])); FromIndex:=TLIL.ToInteger(Args[1]); if FromIndex < 0 then FromIndex:=0; List:=LIL.SubstituteToList(Args[0]); if Length(Args) > 2 then ToIndex:=TLIL.ToInteger(Args[2]) else ToIndex:=List.Count; if ToIndex > List.Count then ToIndex:=List.Count; if ToIndex < FromIndex then ToIndex:=FromIndex; Slice:=TLILList.Create; for i:=FromIndex to ToIndex - 1 do Slice.Add(List[i]); FreeAndNil(List); Result:=Slice.ToValue; FreeAndNil(Slice); end; function FncList(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; i: Integer; begin List:=TLILList.Create; for i:=0 to Length(Args) - 1 do List.Add(Args[i]); Result:=List.ToValue; FreeAndNil(List); end; function FncSubst(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args)=0 then Result:=nil else Result:=LIL.SubstituteToValue(Args[0]); end; function FncConcat(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i: Integer; s: string = ''; List: TLILList; begin for i:=0 to Length(Args) - 1 do begin List:=LIL.SubstituteToList(Args[i]); Result:=List.ToValue; s += TLIL.ToString(Result); FreeAndNil(Result); end; Result:=TLIL.AllocString(s); end; function FncForEach(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i, ListIndex, CodeIndex: Integer; VarName: string = 'i'; List, RetList: TLILList; begin if Length(Args) < 2 then exit(nil); if Length(Args) >= 3 then begin VarName:=TLIL.ToString(Args[0]); ListIndex:=1; CodeIndex:=2; end else begin ListIndex:=0; CodeIndex:=1; end; RetList:=TLILList.Create; List:=LIL.SubstituteToList(Args[ListIndex]); for i:=0 to List.Count - 1 do begin if LIL.Env.BreakRun then Break; LIL.SetVar(VarName, List[i], lsvlLocalOnly); Result:=LIL.ParseValue(Args[CodeIndex]); if Result.Length > 0 then RetList.Add(Result); FreeAndNil(Result); if LIL.Error then break; end; Result:=RetList.ToValue; FreeAndNil(RetList); FreeAndNil(List); end; function FncReturn(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin LIL.Env.BreakRun:=True; FreeAndNil(LIL.Env.RetVal); if Length(Args) > 0 then begin LIL.Env.RetVal:=TLIL.Clone(Args[0]); Result:=TLIL.Clone(Args[0]); end else Result:=nil; LIL.Env.RetValSet:=True; end; function FncResult(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) > 0 then begin FreeAndNil(LIL.Env.RetVal); LIL.Env.RetVal:=TLIL.Clone(Args[0]); LIL.Env.RetValSet:=True; end; if LIL.Env.RetValSet then Result:=TLIL.Clone(LIL.Env.RetVal) else Result:=nil; end; function FncExpr(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i: Integer; Expr: TLILValue; begin if Length(Args)=0 then exit(nil); if Length(Args)=1 then exit(LIL.EvaluateExpressionValue(Args[0])); Expr:=TLILValue.Create; for i:=0 to Length(Args) - 1 do begin if i > 0 then Expr.AppendChar(' '); Expr.AppendValue(Args[i]); end; Result:=LIL.EvaluateExpressionValue(Expr); FreeAndNil(Expr); end; function RealInc(LIL: TLIL; VarName: string; v: Extended): TLILValue; var Value: Extended; begin Result:=LIL.GetVar(VarName); Value:=LIL.ToFloat(Result) + v; if FMod(Value, 1) <> 0 then Result:=LIL.AllocFloat(Value) else Result:=LIL.AllocInteger(Trunc(Value)); LIL.SetVar(VarName, Result, lsvlLocal); end; function FncInc(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var v: Extended; begin if Length(Args) < 1 then exit(nil); if Length(Args) > 1 then v:=TLIL.ToFloat(Args[1]) else v:=1; Result:=RealInc(LIL, TLIL.ToString(Args[0]), v); end; function FncDec(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var v: Extended; begin if Length(Args) < 1 then exit(nil); if Length(Args) > 1 then v:=-TLIL.ToFloat(Args[1]) else v:=-1; Result:=RealInc(LIL, TLIL.ToString(Args[0]), v); end; function FncRead(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var f: file; Content: string; Buffer: PChar; Part: array [0..16384] of Char; Pos: Integer = 0; nr: Integer = 0; begin if Length(Args) < 1 then exit(nil); if Assigned(LIL.FOnRead) then begin LIL.OnRead(LIL, TLIL.ToString(Args[0]), Content); Result:=TLIL.AllocString(Content); end else begin Assign(f, TLIL.ToString(Args[0])); {$I-} Reset(f, 1); {$I+} if IOResult <> 0 then exit(nil); Buffer:=GetMem(FileSize(f) + 1); while not Eof(f) do begin BlockRead(f, Part, SizeOf(Part), nr); if nr > 0 then begin Move(Part, Pointer(Buffer + Pos)^, nr); Inc(Pos, nr); end else break; end; Buffer[FileSize(f)]:=#0; Close(f); Result:=TLIL.AllocString(UTF8String(Buffer)); FreeMem(Buffer); end; end; function FncStore(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var f: file; s: UTF8String; begin if Length(Args) < 2 then exit(nil); if Assigned(LIL.FOnStore) then begin LIL.FOnStore(LIL, TLIL.ToString(Args[0]), TLIL.ToString(Args[1])); end else begin Assign(f, TLIL.ToString(Args[0])); {$I-} Rewrite(f, 1); {$I+} if IOResult <> 0 then exit(nil); s:=TLIL.ToString(Args[1]); BlockWrite(f, s[1], Length(s)); Close(f); end; Result:=TLIL.Clone(Args[1]); end; function FncIf(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Value: TLILValue = nil; Base: Integer = 0; TruthNeeded: Boolean = True; v: Boolean; begin Result:=nil; if Length(Args) < 1 then exit; if Args[0].Equals('not') then begin TruthNeeded:=False; Base:=1; end; if Length(Args) < Base + 2 then exit; Value:=LIL.EvaluateExpressionValue(Args[Base]); if LIL.Error or not Assigned(Value) then exit; v:=TLIL.ToBoolean(Value); if not TruthNeeded then v:=not v; if v then Result:=LIL.ParseValue(Args[Base + 1]) else if Length(Args) > Base + 2 then Result:=LIL.ParseValue(Args[Base + 2]); FreeAndNil(Value); end; function FncWhile(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Value: TLILValue = nil; Base: Integer = 0; TruthNeeded: Boolean = True; v: Boolean; begin Result:=nil; if Length(Args) < 1 then exit; if Args[0].Equals('not') then begin TruthNeeded:=False; Base:=1; end; if Length(Args) < Base + 2 then exit; while (not LIL.Error) and (not LIL.Env.BreakRun) do begin Value:=LIL.EvaluateExpressionValue(Args[Base]); if LIL.Error or not Assigned(Value) then exit; v:=TLIL.ToBoolean(Value); if not TruthNeeded then v:=not v; if not v then begin FreeAndNil(Value); break; end; if Assigned(Result) then FreeAndNil(Result); Result:=LIL.ParseValue(Args[Base + 1]); FreeAndNil(Value); end; end; function FncFor(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var Value: TLILValue; begin Result:=nil; if Length(Args) < 4 then exit; Value:=LIL.ParseValue(Args[0]); FreeAndNil(Value); while (not LIL.Error) and (not LIL.Env.BreakRun) do begin Value:=LIL.EvaluateExpressionValue(Args[1]); if LIL.Error or not Assigned(Value) then exit; if not TLIL.ToBoolean(Value) then begin FreeAndNil(Value); break; end; FreeAndNil(Value); if Assigned(Result) then FreeAndNil(Result); Result:=LIL.ParseValue(Args[3]); Value:=LIL.ParseValue(Args[2]); FreeAndNil(Value); end; end; function FncChar(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then exit(nil); Result:=TLIL.AllocString(Chr(Ord(TLIL.ToInteger(Args[0])))); end; function FncCharAt(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var s: string; Index: Integer; begin if Length(Args) < 2 then exit(nil); s:=TLIL.ToString(Args[0]); Index:=TLIL.ToInteger(Args[1]); if (Index < 0) or (Index >= Length(s)) then exit(nil); Result:=TLIL.AllocString(s[Index + 1]); end; function FncCodeAt(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var s: string; Index: Integer; begin if Length(Args) < 2 then exit(nil); s:=TLIL.ToString(Args[0]); Index:=TLIL.ToInteger(Args[1]); if (Index < 0) or (Index >= Length(s)) then exit(nil); Result:=TLIL.AllocInteger(Ord(s[Index + 1])); end; function FncSubStr(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var s: string; First, Last: Integer; begin if Length(Args) < 2 then exit(nil); s:=TLIL.ToString(Args[0]); if s='' then exit(nil); First:=TLIL.ToInteger(Args[1]); if Length(Args) < 3 then Last:=Length(s) else Last:=TLIL.ToInteger(Args[2]); if Last > Length(s) then Last:=Length(s); if First >= Last then exit(nil); Result:=TLIL.AllocString(Copy(s, First + 1, Last - First)); end; function FncStrPos(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var a, b: string; begin if Length(Args) < 2 then exit(TLIL.AllocInteger(-1)); a:=TLIL.ToString(Args[0]); b:=TLIL.ToString(Args[1]); Result:=TLIL.AllocInteger(Int64(Pos(b, a)) - 1); end; function FncLength(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var i, Total: Integer; begin if Length(Args) < 1 then exit(TLIL.AllocInteger(0)); Total:=0; for i:=0 to Length(Args) - 1 do begin if i > 0 then Inc(Total); Inc(Total, Length(TLIL.ToString(Args[i]))); end; Result:=TLIL.AllocInteger(Total); end; function FncTrim(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then exit(nil); Result:=TLIL.AllocString(Trim(TLIL.ToString(Args[0]))); end; Function FncLTrim(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then exit(nil); Result:=TLIL.AllocString(TrimLeft(TLIL.ToString(Args[0]))); end; function FncRTrim(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then exit(nil); Result:=TLIL.AllocString(TrimRight(TLIL.ToString(Args[0]))); end; function FncStrCmp(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 2 then exit(nil); Result:=TLIL.AllocInteger(CompareStr(TLIL.ToString(Args[0]), TLIL.ToString(Args[1]))); end; function FncStrEq(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 2 then exit(nil); if TLIL.ToString(Args[0])=TLIL.ToString(Args[1]) then Result:=TLIL.AllocInteger(1) else Result:=TLIL.AllocInteger(0); end; function FncRepStr(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then exit(nil); if Length(Args) < 3 then exit(TLIL.Clone(Args[0])); Result:=TLIL.AllocString(StringReplace(TLIL.ToString(Args[0]), TLIL.ToString(Args[1]), TLIL.ToString(Args[2]), [rfReplaceAll])); end; function FncSplit(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; Separators: string = ' '; i: Integer; Str, Part: string; begin if Length(Args) < 1 then exit(nil); if Length(Args) > 1 then begin Separators:=TLIL.ToString(Args[1]); if Separators='' then exit(TLIL.Clone(Args[0])); end; Part:=''; Str:=TLIL.ToString(Args[0]); List:=TLILList.Create; for i:=1 to Length(Str) do begin if Pos(Str[i], Separators) > 0 then begin List.AddString(Part); Part:=''; end else Part += Str[i]; end; List.AddString(Part); Result:=List.ToValue(True); FreeAndNil(List); end; function FncTry(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if (Length(Args) < 1) or (LIL.FError) then exit(nil); Result:=LIL.ParseValue(Args[0]); if LIL.FError then begin LIL.FError:=False; LIL.FErrorMessage:=''; LIL.FErrorHead:=0; FreeAndNil(Result); if Length(Args) > 1 then Result:=LIL.ParseValue(Args[1]); end; end; function FncError(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) > 0 then LIL.SetError(TLIL.ToString(Args[0])) else LIL.SetError('Script initiated error'); Result:=nil; end; function FncExit(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var ExitCode: Integer; begin if Length(Args) > 0 then ExitCode:=TLIL.ToInteger(Args[0]) else ExitCode:=0; if Assigned(LIL.FOnExit) then begin if Length(Args) > 0 then LIL.FOnExit(LIL, Args[0]) else LIL.FOnExit(LIL, LIL.Empty); end else Halt(ExitCode); Result:=nil; end; function FncSource(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var f: file; Code: string; Buffer: PChar; Part: array [0..16384] of Char; Pos: Integer = 0; nr: Integer = 0; begin if Length(Args) < 1 then exit(nil); if Assigned(LIL.FOnSource) then begin LIL.FOnSource(LIL, TLIL.ToString(Args[0]), Code); Result:=LIL.Parse(Code); end else if Assigned(LIL.FOnRead) then begin LIL.FOnRead(LIL, TLIL.ToString(Args[0]), Code); Result:=LIL.Parse(Code); end else begin Assign(f, TLIL.ToString(Args[0])); {$I-} Reset(f, 1); {$I+} if IOResult <> 0 then exit(nil); Buffer:=GetMem(FileSize(f) + 1); while not Eof(f) do begin BlockRead(f, Part, SizeOf(Part), nr); if nr > 0 then begin Move(Part, Pointer(Buffer + Pos)^, nr); Inc(Pos, nr); end else break; end; Buffer[FileSize(f)]:=#0; Close(f); Result:=LIL.Parse(Buffer); FreeMem(Buffer); end; end; function FncLMap(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var List: TLILList; i: Integer; begin Result:=nil; if Length(Args) < 2 then exit; List:=LIL.SubstituteToList(Args[0]); for i:=1 to Length(Args) - 1 do LIL.SetVar(TLIL.ToString(Args[i]), List[i - 1], lsvlLocal); FreeAndNil(List); end; function FncRand(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin Result:=TLIL.AllocFloat(Random); end; function FncCatcher(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; begin if Length(Args) < 1 then begin Result:=TLIL.AllocString(LIL.Catcher); end else begin LIL.Catcher:=TLIL.ToString(Args[0]); Result:=nil; end; end; function FncWatch(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue; var V: TLILVariable; I: Integer; VName: string; begin if Length(Args) < 2 then Exit(nil); for I:=0 to High(Args) - 1 do begin VName:=TLIL.ToString(Args[I]); if VName='' then Continue; V:=LIL.FindVar(VName); if not Assigned(V) then V:=LIL.SetVar(TLIL.ToString(Args[I]), nil, lsvlLocalNew); V.FCodeWatch:=TLIL.ToString(Args[High(Args)]); end; Result:=nil; end; procedure Register; begin RegisterComponents('Misc', [TLIL]); end; { TLILValue } function TLILValue.ToInteger: Int64; begin Result:=StrToInt64Def(FData, Trunc(StrToFloatDef(FData, 0, LILFormatSettings))); end; function TLILValue.ToFloat: Extended; begin try Result:=StrToFloat(FData, LILFormatSettings); except Result:=0; end; end; function TLILValue.ToBoolean: Boolean; var i: Integer; Dots: Boolean = False; begin if FData='' then exit(false); for i:=1 to FLength do begin if not (FData[i] in ['0', '.']) then exit(true); if FData[i]='.' then begin if Dots then exit(true); Dots:=True; end; end; Result:=false; end; procedure TLILValue.AppendChar(Ch: Char); begin FData += Ch; Inc(FLength); end; procedure TLILValue.AppendString(Str: string); begin FData += Str; Inc(FLength, System.Length(Str)); end; procedure TLILValue.AppendValue(AValue: TLILValue); begin if Assigned(AValue) then begin FData += AValue.FData; Inc(FLength, AValue.FLength); end; end; function TLILValue.Clone: TLILValue; begin Result:=TLILValue.Create; Result.FData:=FData; Result.FLength:=FLength; end; function TLILValue.Equals(StrVal: string): Boolean; begin Result:=StrVal=FData; end; function TLILValue.Equals(IntVal: Int64): Boolean; begin Result:=IntVal=ToInteger; end; function TLILValue.Equals(FloatVal: Extended): Boolean; begin Result:=FloatVal=ToFloat; end; function TLILValue.Equals(LILVal: TLILValue): Boolean; begin Result:=(LILVal <> nil) and (LILVal.FData=FData); end; { TLILVariable } procedure TLILVariable.SetValue(AValue: TLILValue); var OldValue: TLILValue; I: Integer; LIL: TLIL; SaveEnv: TLILEnvironment; begin OldValue:=FValue; FValue:=TLIL.Clone(AValue); FreeAndNil(OldValue); for I:=0 to High(FWatches) do TNotifyEvent(FWatches[I])(Self); if FCodeWatch <> '' then begin LIL:=Environment.LIL; SaveEnv:=LIL.Env; LIL.Env:=Environment; LIL.Parse(FCodeWatch, True).Free; LIL.Env:=SaveEnv; end; end; constructor TLILVariable.Create(AName: string; AEnvironment: TLILEnvironment); begin inherited Create; FName:=AName; FEnvironment:=AEnvironment; end; destructor TLILVariable.Destroy; begin FreeAndNil(FValue); inherited Destroy; end; procedure TLILVariable.AddWatch(const AWatch: TNotifyEvent); begin SetLength(FWatches, Length(FWatches) + 1); FWatches[High(FWatches)]:=TMethod(AWatch); end; procedure TLILVariable.RemoveWatch(const AWatch: TNotifyEvent); var I, J: Integer; begin for I:=0 to High(FWatches) do if CompareMem(@FWatches[I], @TMethod(AWatch), SizeOf(TMethod)) then begin for J:=I to High(FWatches) - 1 do FWatches[J]:=FWatches[J + 1]; SetLength(FWatches, Length(FWatches) - 1); Exit; end; end; { TLILEnvironment } constructor TLILEnvironment.Create(ALIL: TLIL; AParent: TLILEnvironment); begin inherited Create; FLIL:=ALIL; Parent:=AParent; Vars:=TFPList.Create; end; destructor TLILEnvironment.Destroy; var i: Integer; begin FreeAndNil(RetVal); for i:=0 to Vars.Count - 1 do TLILVariable(Vars[i]).Free; FreeAndNil(Vars); inherited Destroy; end; procedure TLILEnvironment.RegisterVariable(AVariable: TLILVariable); begin Vars.Add(AVariable); end; { TLILList } function TLILList.GetCount: Integer; begin Result:=FValues.Count; end; function TLILList.GetValue(AIndex: Integer): TLILValue; begin if (AIndex < 0) or (AIndex >= FValues.Count) then Result:=nil else Result:=TLILValue(FValues[AIndex]); end; constructor TLILList.Create; begin inherited Create; FValues:=TFPList.Create; end; destructor TLILList.Destroy; var i: Integer; begin for i:=0 to FValues.Count - 1 do TLILValue(FValues[i]).Free; FreeAndNil(FValues); inherited Destroy; end; procedure TLILList.Add(AValue: TLILValue); begin FValues.Add(TLIL.Clone(AValue)); end; procedure TLILList.AddString(AString: string); begin FValues.Add(TLIL.AllocString(AString)); end; procedure TLILList.AddInteger(AInteger: Int64); begin FValues.Add(TLIL.AllocInteger(AInteger)); end; procedure TLILList.AddFloat(AFloat: Extended); begin FValues.Add(TLIL.AllocFloat(AFloat)); end; procedure TLILList.AddBoolean(ABoolean: Boolean); begin FValues.Add(TLIL.AllocBoolean(ABoolean)); end; function TLILList.IndexOf(AValue: TLILValue): Integer; var i: Integer; begin for i:=0 to Count - 1 do if AValue.Equals(Values[i]) then Exit(i); Result:=-1; end; function TLILList.IndexOfString(AString: string): Integer; var i: Integer; begin for i:=0 to Count - 1 do if AString=TLIL.ToString(Values[i]) then Exit(i); Result:=-1; end; function TLILList.IndexOfInteger(AInteger: Int64): Integer; var i: Integer; begin for i:=0 to Count - 1 do if AInteger=TLIL.ToInteger(Values[i]) then Exit(i); Result:=-1; end; function TLILList.IndexOfFloat(AFloat: Extended): Integer; var i: Integer; begin for i:=0 to Count - 1 do if AFloat=TLIL.ToFloat(Values[i]) then Exit(i); Result:=-1; end; function TLILList.IndexOfBoolean(ABoolean: Boolean): Integer; var i: Integer; begin for i:=0 to Count - 1 do if ABoolean=TLIL.ToBoolean(Values[i]) then Exit(i); Result:=-1; end; function TLILList.Has(AValue: TLILValue): Boolean; begin Result:=IndexOf(AValue) <> -1; end; function TLILList.HasString(AString: string): Boolean; begin Result:=IndexOfString(AString) <> -1; end; function TLILList.HasInteger(AInteger: Int64): Boolean; begin Result:=IndexOfInteger(AInteger) <> -1; end; function TLILList.HasFloat(AFloat: Extended): Boolean; begin Result:=IndexOfFloat(AFloat) <> -1; end; function TLILList.HasBoolean(ABoolean: Boolean): Boolean; begin Result:=IndexOfBoolean(ABoolean) <> -1; end; function TLILList.ToValue(DoEscape: Boolean=True): TLILValue; var i: Integer; Escape: Boolean; Value: TLILValue; function NeedsEscape(s: string): Boolean; var i: Integer; begin if s='' then exit(True); for i:=1 to Length(s) do if (IsPunct(s[i]) or IsSpace(s[i])) then exit(True); Result:=False; end; begin Result:=TLILValue.Create; for i:=0 to FValues.Count - 1 do begin Value:=TLILValue(FValues[i]); Escape:=DoEscape and NeedsEscape(TLIL.ToString(Value)); if i > 0 then Result.AppendChar(' '); if Escape then Result.AppendChar('{'); Result.AppendValue(Value); if Escape then Result.AppendChar('}'); end; end; function TLILList.ToFunctionArgs: TLILFunctionProcArgs; var i: Integer; begin SetLength(Result, FValues.Count - 1); for i:=1 to FValues.Count - 1 do Result[i - 1]:=TLILValue(FValues[i]); end; { TLILFunction } constructor TLILFunction.Create; begin inherited Create; ArgNames:=TLILList.Create; end; destructor TLILFunction.Destroy; begin FreeAndNil(ArgNames); FreeAndNil(Code); inherited Destroy; end; function TLILFunction.GetBody: string; begin Result:=TLIL.ToString(Code); end; function TLILFunction.IsNative: Boolean; begin Result:=Assigned(Proc); end; function TLILFunction.GetArguments: Integer; begin if Assigned(ArgNames) then Result:=ArgNames.Count else Result:=0; end; function TLILFunction.GetArgument(AIndex: Integer): string; begin if Assigned(ArgNames) and (AIndex >= 0) and (AIndex < ArgNames.Count) then Result:=TLIL.ToString(ArgNames[AIndex]) else Result:=''; end; { TLIL } procedure TLIL.RegisterStandardFunctions; begin Register('reflect', @FncReflect); Register('func', @FncFunc); Register('rename', @FncRename); Register('unusedname', @FncUnusedName); Register('quote', @FncQuote); Register('set', @FncSet); Register('local', @FncLocal); Register('write', @FncWrite); Register('print', @FncPrint); Register('eval', @FncEval); Register('topeval', @FncTopEval); Register('upeval', @FncUpEval); Register('downeval', @FncDownEval); Register('enveval', @FncEnvEval); Register('jaileval', @FncJailEval); Register('count', @FncCount); Register('index', @FncIndex); Register('indexof', @FncIndexOf); Register('filter', @FncFilter); Register('append', @FncAppend); Register('slice', @FncSlice); Register('list', @FncList); Register('subst', @FncSubst); Register('concat', @FncConcat); Register('foreach', @FncForeach); Register('return', @FncReturn); Register('result', @FncResult); Register('expr', @FncExpr); Register('inc', @FncInc); Register('dec', @FncDec); Register('read', @FncRead); Register('store', @FncStore); Register('if', @FncIf); Register('while', @FncWhile); Register('for', @FncFor); Register('char', @FncChar); Register('charat', @FncCharAt); Register('codeat', @FncCodeAt); Register('substr', @FncSubStr); Register('strpos', @FncStrPos); Register('length', @FncLength); Register('trim', @FncTrim); Register('ltrim', @FncLTrim); Register('rtrim', @FncRTrim); Register('strcmp', @FncStrCmp); Register('streq', @FncStrEq); Register('repstr', @FncRepStr); Register('split', @FncSplit); Register('try', @FncTry); Register('error', @FncError); Register('exit', @FncExit); Register('source', @FncSource); Register('lmap', @FncLMap); Register('rand', @FncRand); Register('catcher', @FncCatcher); Register('watch', @FncWatch); SysFuncs:=Length(Funcs); end; function TLIL.FindLocalVar(AEnv: TLILEnvironment; AName: string): TLILVariable; var i: Integer; begin for i:=AEnv.Vars.Count - 1 downto 0 do if TLILVariable(AEnv.Vars[i]).Name=AName then exit(TLILVariable(AEnv.Vars[i])); Result:=nil; end; function TLIL.FindVar(AEnv: TLILEnvironment; AName: string): TLILVariable; begin Result:=FindLocalVar(AEnv, AName); if not Assigned(Result) and (AEnv <> RootEnv) then Result:=FindVar(RootEnv, AName); end; function TLIL.FindFunction(AName: string): TLILFunction; var i: Integer; begin for i:=Length(Funcs) - 1 downto 0 do if Funcs[i].Name=AName then exit(Funcs[i]); Result:=nil; end; function TLIL.AddFunction(AName: string): TLILFunction; begin Result:=FindFunction(AName); if Result <> nil then begin FreeAndNil(Result.ArgNames); FreeAndNil(Result.Code); Result.Proc:=nil; Exit(Result); end; Result:=TLILFunction.Create; Result.FName:=AName; SetLength(Funcs, Length(Funcs) + 1); Funcs[Length(Funcs) - 1]:=Result; end; procedure TLIL.Register(AName: string; AProc: TLILFunctionProc); var Func: TLILFunction; begin Func:=AddFunction(AName); Func.Proc:=AProc; end; function TLIL.GetFunction(AName: string): TLILFunction; begin Result:=FindFunction(AName); end; function TLIL.AtEol: Boolean; begin Result:=(Head <= CLen) and (Code[Head] in [#10, #13, ';']) and not IgnoreEOL; end; procedure TLIL.SkipSpaces; begin while Head <= CLen do begin if Code[Head]='#' then begin if (Head < CLen) and (Code[Head + 1]='#') then begin Inc(Head, 2); while Head <= CLen do begin if (Code[Head]='#') and (Head < CLen) and (Code[Head + 1]='#') then begin Inc(Head, 2); Break; end; Inc(Head); end; end else begin while (Head <= CLen) and (not AtEol) do Inc(Head); end; end else if (Code[Head]='\') and (Code[Head + 1] in [#10, #13]) then begin Inc(Head); while (Head <= CLen) and AtEol do Inc(Head); end else if Code[Head] in [#10, #13] then begin if IgnoreEOL then Inc(Head) else Break; end else if Code[Head] in ['\', '#', #9, #11, #12, #32] then Inc(Head) else Break; end; end; function TLIL.GetBracketPart: TLILValue; var Counter: Integer = 1; Command: string = ''; begin Inc(Head); while Head <= CLen do begin if Code[Head]='[' then begin Inc(Head); Inc(Counter); Command += '['; end else if Code[Head]=']' then begin Inc(Head); Dec(Counter); if Counter=0 then break; Command += ']'; end else begin Command += Code[Head]; Inc(Head); end; end; Result:=Parse(Command); end; function TLIL.GetDollarPart: TLILValue; var TheNextWord: TLILValue; Command: string; begin Inc(Head); TheNextWord:=NextWord; Command:=DollarPrefix + ToString(TheNextWord); FreeAndNil(TheNextWord); Result:=Parse(Command); end; function TLIL.NextWord: TLILValue; var Counter: Integer; Str: string; Sc: Char; Temp: TLILValue; begin Result:=nil; SkipSpaces; if Head > CLen then exit; if Code[Head]='$' then begin Result:=GetDollarPart; end else if Code[Head]='{' then begin Counter:=1; Inc(Head); Str:=''; while Head <= CLen do begin if Code[Head]='{' then begin Inc(Head); Inc(Counter); Str += '{'; end else if Code[Head]='}' then begin Inc(Head); Dec(Counter); if Counter=0 then break; Str += '}'; end else begin Str += Code[Head]; Inc(Head); end; end; Result:=TLIL.AllocString(Str); end else if Code[Head]='[' then begin Result:=GetBracketPart; end else if Code[Head] in ['"', ''''] then begin Result:=TLILValue.Create; Sc:=Code[Head]; Inc(Head); while Head <= CLen do begin if Code[Head]='[' then begin Temp:=GetBracketPart; Result.AppendValue(Temp); FreeAndNil(Temp); Dec(Head); // Avoid skipping the character at the end of 'while' end else if Code[Head]='$' then begin Temp:=GetDollarPart; Result.AppendValue(Temp); FreeAndNil(Temp); Dec(Head); // Avoid skipping the character at the end of 'while' end else if Code[Head]='\' then begin Inc(Head); case Code[Head] of 'b': Result.AppendChar(#8); 't': Result.AppendChar(#9); 'n': Result.AppendChar(#10); 'v': Result.AppendChar(#11); 'f': Result.AppendChar(#12); 'r': Result.AppendChar(#13); '0': Result.AppendChar(#0); 'a': Result.AppendChar(#7); 'c': Result.AppendChar('}'); 'o': Result.AppendChar('{'); else Result.AppendChar(Code[Head]); end; end else if Code[Head]=Sc then begin Inc(Head); break; end else begin Result.AppendChar(Code[Head]); end; Inc(Head); end; end else begin Str:=''; while (Head <= Clen) and (not IsSpace(Code[Head])) and (not IsSpecial(Code[Head])) do begin Str += Code[Head]; Inc(Head); end; Result:=TLIL.AllocString(Str); end; if Result=nil then Result:=TLILValue.Create; end; function TLIL.Substitute: TLILList; var W, WP: TLILValue; SHead: Integer; begin Result:=TLILList.Create; SkipSpaces; while (Head <= CLen) and (not AtEol) and (not FError) do begin W:=TLILValue.Create; repeat SHead:=Head; WP:=NextWord; if SHead=Head then begin { something went wrong, the parser can't proceed } FreeAndNil(W); FreeAndNil(WP); FreeAndNil(Result); exit; end; W.AppendValue(WP); FreeAndNil(WP); until (Head > CLen) or AtEol or IsSpace(Code[Head]) or FError; SkipSpaces; Result.Add(W); FreeAndNil(W); end; end; constructor TLIL.Create(AOwner: TComponent); begin inherited Create(AOwner); RootEnv:=TLILEnvironment.Create(Self, nil); Empty:=TLILValue.Create; DollarPrefix:='set '; RegisterStandardFunctions; end; destructor TLIL.Destroy; var i: Integer; begin for i:=0 to Length(Funcs) - 1 do Funcs[i].Free; FreeAndNil(RootEnv); FreeAndNil(Empty); inherited Destroy; end; class function TLIL.AllocString(Str: string): TLILValue; begin Result:=TLILValue.Create; Result.FData:=Str; Result.FLength:=System.Length(Str); end; class function TLIL.AllocInteger(Int: Int64): TLILValue; begin Result:=AllocString(IntToStr(Int)); end; class function TLIL.AllocFloat(Float: Extended): TLILValue; begin if Trunc(Float)=Float then Result:=AllocString(IntToStr(Trunc(Float))+'.0') else Result:=AllocString(FloatToStrF(Float, ffFixed, 15, 10, LILFormatSettings)); end; class function TLIL.AllocBoolean(Bool: Boolean): TLILValue; begin if Bool then Result:=AllocString('1') else Result:=AllocString(''); end; class function TLIL.ToString(AValue: TLILValue): string; begin if AValue=nil then Result:='' else Result:=AValue.StringValue; end; class function TLIL.ToInteger(AValue: TLILValue): Int64; begin if AValue=nil then Result:=0 else Result:=AValue.IntegerValue; end; class function TLIL.ToFloat(AValue: TLILValue): Extended; begin if AValue=nil then Result:=0 else Result:=AValue.FloatValue; end; class function TLIL.ToBoolean(AValue: TLILValue): Boolean; begin if AValue=nil then Result:=False else Result:=AValue.BooleanValue; end; class function TLIL.Clone(AValue: TLILValue): TLILValue; begin if AValue=nil then Result:=nil else Result:=AValue.Clone; end; procedure TLIL.SetError(AErrorMessage: string); begin if not FError then begin FError:=True; FErrorHead:=Head; FErrorMessage:=AErrorMessage; end; end; function TLIL.SetVar(AName: string; AValue: TLILValue; Locality: TLILSetVarLocality): TLILVariable; var TargetEnv: TLILEnvironment; Variable: TLILVariable; SetVarAction: TLILOnSetVarAction = losaDefault; Replacement: TLILValue = nil; FreeValue: Boolean = False; begin Result:=nil; if AName='' then exit; if Locality=lsvlGlobal then TargetEnv:=RootEnv else TargetEnv:=Env; if Locality <> lsvlLocalNew then begin Variable:=FindVar(TargetEnv, AName); if (Locality=lsvlLocalOnly) and Assigned(Variable) and (Variable.Environment=RootEnv) and (Variable.Environment <> TargetEnv) then Variable:=nil; if Assigned(FOnSetVar) and (Env=RootEnv) then begin FOnSetVar(Self, AName, AValue, Replacement, SetVarAction); case SetVarAction of losaIgnore: exit; losaReplace: begin AValue:=Replacement; FreeValue:=True; end; end; end; if Variable <> nil then begin Variable.Value:=AValue; Result:=Variable; if FreeValue then FreeAndNil(AValue); exit; end; end; Result:=TLILVariable.Create(AName, TargetEnv); Result.Value:=AValue; TargetEnv.RegisterVariable(Result); if FreeValue then FreeAndNil(AValue); end; function TLIL.GetVar(AName: string; DefaultValue: TLILValue=nil): TLILValue; var Variable: TLILVariable; Replacement: TLILValue = nil; GetVarAction: TLILOnGetVarAction = logaDefault; begin Variable:=FindVar(Env, AName); if Variable=nil then Result:=DefaultValue else Result:=Variable.Value; if Assigned(FOnGetVar) then begin FOnGetVar(Self, AName, Result, Replacement, GetVarAction); if GetVarAction=logaReplace then begin Result:=Replacement; end; end; end; function TLIL.FindVar(AName: string): TLILVariable; begin Result:=FindVar(Env, AName); end; function TLIL.FindGlobal(AName: string): TLILVariable; begin Result:=FindVar(RootEnv, AName); end; function TLIL.UnusedName(Part: string): string; var i: Integer; begin for i:=0 to MaxInt do begin Result:='!!un!' + Part + '!' + IntToStr(i) + '!nu!!'; if (FindFunction(Result) <> nil) or (FindVar(Env, Result) <> nil) then continue; exit; end; Result:=''; end; procedure TLIL.PushEnv; begin Env:=TLILEnvironment.Create(Self, Env); end; procedure TLIL.PopEnv; var Next: TLILEnvironment; begin if Env.Parent=nil then exit; Next:=Env.Parent; Env.Free; Env:=Next; end; function TLIL.SubstituteToList(ACode: TLILValue): TLILList; var SaveCode: string; SaveHead, SaveCLen: Integer; SaveIgnoreEOL: Boolean; begin SaveCode:=Code; SaveHead:=Head; SaveCLen:=CLen; SaveIgnoreEOL:=IgnoreEOL; Code:=TLIL.ToString(ACode); CLen:=Length(Code); Head:=1; IgnoreEOL:=True; Result:=Substitute; IgnoreEOL:=SaveIgnoreEOL; Head:=SaveHead; CLen:=SaveCLen; Code:=SaveCode; end; function TLIL.SubstituteToValue(ACode: TLILValue): TLILValue; var Words: TLILList; begin Words:=SubstituteToList(ACode); if Words=nil then exit(TLIL.Clone(ACode)); Result:=Words.ToValue(False); FreeAndNil(Words); end; function TLIL.EvaluateExpression(ACode: string): TLILValue; var Temp: TLILValue; begin Temp:=TLIL.AllocString(ACode); Result:=EvaluateExpressionValue(Temp); FreeAndNil(Temp); end; function LIL_EvaluateExpressionValue(LIL: TLIL; AValue: TLILValue): TLILValue; type TExprEvalType = (eeInt, eeFloat); TExprEvalError = (eeNoError, eeSyntaxError, eeInvalidType, eeDivisionByZero, eeInvalidExpression); var Code: string; Len, Head: Integer; IVal: Int64; FVal: Extended; XType: TExprEvalType; Error: TExprEvalError; procedure SubExpression; forward; function InvalidPunctuation(Ch: Char): Boolean; inline; begin Result:=IsPunct(Ch) and not (Ch in ['!', '~', '(', ')', '-', '+']); end; procedure SkipSpaces; inline; begin while (Head <= Len) and IsSpace(Code[Head]) do Inc(Head); end; procedure NumericElement; var FPart: Int64; FPartLen: Int64; begin XType:=eeInt; IVal:=0; FVal:=0; SkipSpaces; FPart:=0; FPartLen:=1; while (Head <= Len) do begin if Code[Head]='.' then begin if XType=eeFloat then break; XType:=eeFloat; Inc(Head); continue; end else if not IsDigit(Code[Head]) then break; if XType=eeInt then IVal:=IVal*10 + (Int64(Ord(Code[Head])) - Ord('0')) else begin FPart:=FPart*10 + (Int64(Ord(Code[Head])) - Ord('0')); FPartLen:=FPartLen*10; end; Inc(Head); end; if XType=eeFloat then FVal:=IVal + FPart/FPartLen; end; procedure Element; begin SkipSpaces; if (Head <= Len) and IsDigit(Code[Head]) then begin NumericElement; end else begin // Assume that anything else is a string that was used to evaluate // as a "true" value. XType:=eeInt; IVal:=1; Error:=eeInvalidExpression; // this will be cleared end; end; procedure Paren; begin SkipSpaces; if Head > Len then exit; if Code[Head]='(' then begin Inc(Head); SubExpression; SkipSpaces; if (Head <= Len) and (Code[Head]=')') then Inc(Head) else Error:=eeSyntaxError; end else begin Element; end; end; procedure Unary; var Op: Char; begin SkipSpaces; if (Head < Len) and (Error=eeNoError) and (Code[Head] in ['-', '+', '~', '!']) then begin Op:=Code[Head]; Inc(Head); Unary; if Error <> eeNoError then exit; case Op of '-': case XType of eeFloat: FVal:=-FVal; eeInt: IVal:=-IVal; else Error:=eeInvalidType; end; // Ignore '+' '~': case XType of eeFloat: FVal:=not Trunc(FVal); eeInt: IVal:=not IVal; else Error:=eeInvalidType; end; '!': case XType of eeFloat: if FVal=0 then FVal:=1 else FVal:=0; eeInt: if IVal=0 then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; end else begin Paren; end; end; procedure MulDiv; var OFVal: Extended; OIVal: Int64; begin Unary; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and (not InvalidPunctuation(Code[Head + 1])) and (Code[Head] in ['*', '/', '\', '%']) do begin OFVal:=FVal; OIVal:=IVal; case Code[Head] of '*': case XType of eeFloat: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OFVal*FVal; eeInt: begin FVal:=OFVal*IVal; XType:=eeFloat; end; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OIVal*FVal; eeInt: IVal:=OIVal*IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; '%': case XType of eeFloat: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else FVal:=FMod(OFVal, FVal); eeInt: if IVal=0 then Error:=eeDivisionByZero else begin FVal:=FMod(OFVal, IVal); XType:=eeFloat; end; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else FVal:=FMod(OIVal, FVal); eeInt: if IVal=0 then Error:=eeDivisionByZero else IVal:=OIVal mod IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; '/': case XType of eeFloat: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else FVal:=OFVal/FVal; eeInt: if IVal=0 then Error:=eeDivisionByZero else begin FVal:=OFVal/IVal; XType:=eeFloat; end; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else FVal:=OIVal/FVal; eeInt: if IVal=0 then Error:=eeDivisionByZero else IVal:=OIVal div IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; '\': case XType of eeFloat: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else begin IVal:=Trunc(OFVal/FVal); XType:=eeInt; end; eeInt: if IVal=0 then Error:=eeDivisionByZero else IVal:=Trunc(OFVal/IVal); else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Unary; if Error <> eeNoError then exit; case XType of eeFloat: if FVal=0 then Error:=eeDivisionByZero else begin FVal:=Trunc(OIVal/FVal); XType:=eeFloat; end; eeInt: if IVal=0 then Error:=eeDivisionByZero else IVal:=OIVal div IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; end; SkipSpaces; end; end; procedure AddSub; var OFVal: Extended; OIVal: Int64; begin MulDiv; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and (not InvalidPunctuation(Code[Head + 1])) and (Code[Head] in ['+', '-']) do begin OFVal:=FVal; OIVal:=IVal; case Code[Head] of '+': case XType of eeFloat: begin Inc(Head); MulDiv; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OFVal + FVal; eeInt: begin FVal:=OFVal + IVal; XType:=eeFloat; end; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); MulDiv; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OIVal + FVal; eeInt: IVal:=OIVal + IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; '-': case XType of eeFloat: begin Inc(Head); MulDiv; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OFVal - FVal; eeInt: begin FVal:=OFVal - IVal; XType:=eeFloat; end; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); MulDiv; if Error <> eeNoError then exit; case XType of eeFloat: FVal:=OIVal - FVal; eeInt: IVal:=OIVal - IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; end; SkipSpaces; end; end; procedure Shift; var OFVal: Extended; OIVal: Int64; begin AddSub; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ( ((Code[Head]='>') and (Code[Head + 1]='>')) or ((Code[Head]='<') and (Code[Head + 1]='<')) ) do begin OFVal:=FVal; OIVal:=IVal; Inc(Head); case Code[Head] of '<': case XType of eeFloat: begin Inc(Head); AddSub; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=Trunc(OFVal) shl Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=Trunc(OFVal) shl IVal; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); AddSub; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=OIVal shl Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=OIVal shl IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; '>': case XType of eeFloat: begin Inc(Head); AddSub; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=Trunc(OFVal) shr Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=Trunc(OFVal) shr IVal; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); AddSub; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=OIVal shr Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=OIVal shr IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; end; SkipSpaces; end; end; procedure Compare; var OFVal: Extended; OIVal: Int64; Op: Integer; begin Shift; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ( ((Code[Head]='<') and (not InvalidPunctuation(Code[Head + 1]))) or ((Code[Head]='>') and (not InvalidPunctuation(Code[Head + 1]))) or ((Code[Head]='<') and (Code[Head + 1]='=')) or ((Code[Head]='>') and (Code[Head + 1]='=')) ) do begin Op:=4; if (Code[Head]='<') and (not InvalidPunctuation(Code[Head + 1])) then Op:=1 else if (Code[Head]='>') and (not InvalidPunctuation(Code[Head + 1])) then Op:=2 else if (Code[Head]='<') and (Code[Head + 1]='=') then Op:=3; if Op > 2 then Inc(Head, 2) else Inc(Head); OFVal:=FVal; OIVal:=IVal; case Op of 1: case XType of eeFloat: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal < FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal < IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal < FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal < IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; 2: case XType of eeFloat: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal > FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal > IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal > FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal > IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; 3: case XType of eeFloat: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal <= FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal <= IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal <= FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal <= IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; 4: case XType of eeFloat: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal >= FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal >= IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Shift; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal >= FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal >= IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; end; SkipSpaces; end; end; procedure Equals; var OFVal: Extended; OIVal: Int64; Op: Integer; begin Compare; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ( ((Code[Head]='=') and (Code[Head + 1]='=')) or ((Code[Head]='!') and (Code[Head + 1]='=')) ) do begin if (Code[Head]='=') then Op:=1 else Op:=2; Inc(Head); OFVal:=FVal; OIVal:=IVal; case Op of 1: case XType of eeFloat: begin Inc(Head); Compare; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal=FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal=IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Compare; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal=FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal=IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; 2: case XType of eeFloat: begin Inc(Head); Compare; if Error <> eeNoError then exit; case XType of eeFloat: begin if OFVal <> FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OFVal <> IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin Inc(Head); Compare; if Error <> eeNoError then exit; case XType of eeFloat: begin if OIVal <> FVal then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if OIVal <> IVal then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; end; SkipSpaces; end; end; procedure BitwiseAnd; var OFVal: Extended; OIVal: Int64; begin Equals; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ((Code[Head]='&') and (not InvalidPunctuation(Code[head + 1]))) do begin OFVal:=FVal; OIVal:=IVal; Inc(Head); case XType of eeFloat: begin Equals; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=Trunc(OFVal) and Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=Trunc(OFVal) and IVal; else Error:=eeInvalidType; end; end; eeInt: begin Equals; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=OIVal and Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=OIVal and IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; SkipSpaces; end; end; procedure BitwiseOr; var OFVal: Extended; OIVal: Int64; begin BitwiseAnd; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ((Code[Head]='|') and (not InvalidPunctuation(Code[head + 1]))) do begin OFVal:=FVal; OIVal:=IVal; Inc(Head); case XType of eeFloat: begin BitwiseAnd; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=Trunc(OFVal) or Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=Trunc(OFVal) or IVal; else Error:=eeInvalidType; end; end; eeInt: begin BitwiseAnd; if Error <> eeNoError then exit; case XType of eeFloat: begin IVal:=OIVal or Trunc(FVal); XType:=eeInt; end; eeInt: IVal:=OIVal or IVal; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; SkipSpaces; end; end; procedure LogicalAnd; var OFVal: Extended; OIVal: Int64; begin BitwiseOr; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ((Code[Head]='&') and (Code[Head + 1]='&')) do begin OFVal:=FVal; OIVal:=IVal; Inc(Head, 2); case XType of eeFloat: begin BitwiseOr; if Error <> eeNoError then exit; case XType of eeFloat: begin if (OFVal <> 0) and (FVal <> 0) then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if (OFVal <> 0) and (IVal <> 0) then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin BitwiseOr; if Error <> eeNoError then exit; case XType of eeFloat: begin if (OIVal <> 0) and (FVal <> 0) then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if (OIVal <> 0) and (IVal <> 0) then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; SkipSpaces; end; end; procedure LogicalOr; var OFVal: Extended; OIVal: Int64; begin LogicalAnd; if Error <> eeNoError then exit; SkipSpaces; while (Head < Len) and (Error=eeNoError) and ((Code[Head]='|') and (Code[Head + 1]='|')) do begin OFVal:=FVal; OIVal:=IVal; Inc(Head, 2); case XType of eeFloat: begin LogicalAnd; if Error <> eeNoError then exit; case XType of eeFloat: begin if (OFVal <> 0) or (FVal <> 0) then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if (OFVal <> 0) or (IVal <> 0) then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; eeInt: begin LogicalAnd; if Error <> eeNoError then exit; case XType of eeFloat: begin if (OIVal <> 0) or (FVal <> 0) then IVal:=1 else IVal:=0; XType:=eeInt; end; eeInt: if (OIVal <> 0) or (IVal <> 0) then IVal:=1 else IVal:=0; else Error:=eeInvalidType; end; end; else Error:=eeInvalidType; end; SkipSpaces; end; end; procedure SubExpression; inline; begin LogicalOr; if Error=eeInvalidExpression then begin Error:=eeNoError; IVal:=1; XType:=eeInt; end; end; begin Code:=TLIL.ToString(AValue); Len:=AValue.Length; Head:=1; IVal:=0; FVal:=0; XType:=eeInt; Error:=eeNoError; SubExpression; if Error <> eeNoError then begin case Error of eeSyntaxError: LIL.SetError('expression syntax error'); eeInvalidType: LIL.SetError('mixing invalid types in expression'); eeDivisionByZero: LIL.SetError('division by zero in expression'); end; exit(nil); end; if XType=eeInt then Result:=TLIL.AllocInteger(IVal) else Result:=TLIL.AllocFloat(FVal); end; function TLIL.EvaluateExpressionValue(AValue: TLILValue): TLILValue; begin AValue:=SubstituteToValue(AValue); if AValue.Equals('') then begin FreeAndNil(AValue); exit(TLIL.AllocInteger(0)); end; Result:=LIL_EvaluateExpressionValue(self, AValue); FreeAndNil(AValue); end; function TLIL.Parse(ACommand: string; FuncLevel: Boolean=False): TLILValue; label cleanup; var SaveCode: string; SHead, SaveHead, SaveCLen, i: Integer; SaveFixHead: Boolean; Words: TLILList; Func: TLILFunction; Args: TLILValue; begin SaveCode:=Code; SaveHead:=Head; SaveCLen:=CLen; Code:=ACommand; CLen:=Length(Code); Inc(ParseDepth); if ParseDepth=1 then begin RootCode:=Code; Env:=RootEnv; FError:=False; FErrorMessage:=''; FErrorHead:=1; end; Head:=1; SkipSpaces; Words:=nil; Result:=nil; {$IFDEF LIL_ENABLE_RECLIMIT} if ParseDepth > MAX_RECLIMIT then begin SetError('Too many recursive calls'); goto cleanup; end; {$ENDIF} if FuncLevel then Env.BreakRun:=False; while (Head <= CLen) and (not FError) do begin if Words <> nil then FreeAndNil(Words); if Result <> nil then FreeAndNil(Result); Words:=Substitute; if (Words=nil) or FError then goto cleanup; if Words.Count > 0 then begin Func:=FindFunction(ToString(Words[0])); if Func=nil then begin if Words[0].Length > 0 then begin if Catcher <> '' then begin if InCatcher < MAX_CATCHER_DEPTH then begin Inc(InCatcher); PushEnv; Env.CatcherFor:=Words[0].Clone; Args:=Words.ToValue; SetVar('args', Args, lsvlLocalNew); FreeAndNil(Args); Result:=Parse(Catcher, True); PopEnv; Env.CatcherFor.Free; Env.CatcherFor:=nil; Dec(InCatcher); end else begin SetError('Catcher limit reached while trying to call unknown function ' + ToString(Words[0])); goto cleanup; end; end else begin SetError('Unknown function ' + ToString(Words[0])); goto cleanup; end; end; end else begin if Func.Native then begin SHead:=Head; SaveFixHead:=FixHead; FFuncName:=ToString(Words[0]); Result:=Func.Proc(Self, Words.ToFunctionArgs); if FixHead then Head:=SHead; FixHead:=SaveFixHead; end else begin PushEnv; Env.Func:=Func; if (Func.ArgNames.Count=1) and (ToString(Func.ArgNames[0])='args') then begin Args:=Words.ToValue; SetVar('args', Args, lsvlLocalNew); FreeAndNil(Args); end else begin for i:=0 to Func.ArgNames.Count - 1 do begin if i < Words.Count - 1 then SetVar(ToString(Func.ArgNames[i]), Words[i + 1], lsvlLocalNew) else SetVar(ToString(Func.ArgNames[i]), Empty, lsvlLocalNew); end; end; Result:=ParseValue(Func.Code, True); PopEnv; end; end; end; if Env.BreakRun then goto cleanup; SkipSpaces; while AtEol do Inc(Head); SkipSpaces; end; cleanup: if FError and Assigned(FOnError) and (ParseDepth=1) then FOnError(Self, ErrorHead, ErrorMessage); FreeAndNil(Words); Head:=SaveHead; CLen:=SaveCLen; Code:=SaveCode; if FuncLevel and Env.RetValSet then begin FreeAndNil(Result); Result:=Env.RetVal; Env.RetVal:=nil; Env.RetValSet:=False; Env.BreakRun:=False; end; Dec(ParseDepth); if Result=nil then Result:=TLILValue.Create; end; function TLIL.ParseValue(ACmdValue: TLILValue; FuncLevel: Boolean=False): TLILValue; begin if (ACmdValue=nil) or (ACmdValue.Length=0) then exit(TLILValue.Create); Result:=Parse(ToString(ACmdValue), FuncLevel); end; procedure TLIL.WriteString(Chars: string); var Tmp: string; I: Integer; begin if Assigned(FOnWrite) then FOnWrite(Self, Chars) else if IsConsole then begin Tmp:=''; for I:=1 to Length(Chars) do if Chars[I]=#10 then begin WriteLn(Tmp); Tmp:=''; end else Tmp += Chars[I]; if Tmp <> '' then Write(Tmp); end; end; function TLIL.ToString: string; begin Result:='<LIL Runtime>'; end; {$HINTS+} initialization LILFormatSettings:=DefaultFormatSettings; with LILFormatSettings do begin ThousandSeparator:=','; DecimalSeparator:='.'; end; {$IFDEF LAZFPLIL} {$I fplilpackage.lrs} {$ENDIF} end.
unit d03.mocking.DelphiMocks; interface uses SysUtils, Rtti, DUnitX.TestFramework, Delphi.Mocks, d03.mocking.Driver, d03.mocking.Car, d03.mocking.AirCondition, d03.mocking.ACmode; type [TestFixture] TDriverTests_DelphiMock = class public [Test] procedure cannot_drive_a_running_car; [Test] procedure AC_is_set_before_we_drive; [Test] procedure AC_is_set_on_before_we_drive; [Test] procedure check_raising_exception; [Test] procedure custom_execution; [Setup] procedure Setup(); [TearDown] procedure TearDown(); end; implementation var mockRunningCar: TMock<ICar>; Driver: TDriver; procedure TDriverTests_DelphiMock.Setup(); begin mockRunningCar := TMock<ICar>.Create(); Driver := TDriver.Create(mockRunningCar); end; procedure TDriverTests_DelphiMock.TearDown(); begin mockRunningCar.Free; Driver.Free; end; procedure TDriverTests_DelphiMock.cannot_drive_a_running_car; begin mockRunningCar.Setup.WillReturn(true).When.IsRunning(); Assert.IsFalse(Driver.CanDrive()); end; procedure TDriverTests_DelphiMock.AC_is_set_before_we_drive; begin mockRunningCar.Setup.Expect.AtLeastOnce.When.SetAC (It(0).IsAny<TAirCondition>); Driver.Drive; mockRunningCar.Verify(); end; procedure TDriverTests_DelphiMock.AC_is_set_on_before_we_drive; var dummyAC: TAirCondition; begin dummyAC := TAirCondition.Create(AcOn); mockRunningCar.Setup.Expect.AtLeastOnce.When.SetAC( It(0).AreSameFieldsAndPropertiedThat(dummyAC)); Driver.Drive; mockRunningCar.Verify; end; procedure TDriverTests_DelphiMock.check_raising_exception; begin mockRunningCar.Setup.WillRaise(Exception, 'ss').When.Start; Assert.WillRaise(procedure begin mockRunningCar.Instance.Start; end ) end; procedure TDriverTests_DelphiMock.custom_execution; var num : Integer; begin num := 0; mockRunningCar.Setup.WillExecute(function (const args : TArray<TValue>; const returnType : TRttiType) : TValue begin num := 3; end ).When.Start; mockRunningCar.Instance.Start; Assert.AreEqual(3, num); end; end.
unit RemoteProcessClient; interface uses SysUtils, SimpleSocket, TypeControl, FacilityControl, FacilityTypeControl, GameControl, MoveControl, PlayerContextControl, PlayerControl, TerrainTypeControl, UnitControl, VehicleControl, VehicleTypeControl, VehicleUpdateControl, WeatherTypeControl, WorldControl; const UNKNOWN_MESSAGE : LongInt = 0; GAME_OVER : LongInt = 1; AUTHENTICATION_TOKEN: LongInt = 2; TEAM_SIZE : LongInt = 3; PROTOCOL_VERSION : LongInt = 4; GAME_CONTEXT : LongInt = 5; PLAYER_CONTEXT : LongInt = 6; MOVE_MESSAGE : LongInt = 7; LITTLE_ENDIAN_BYTE_ORDER = true; INTEGER_SIZE_BYTES = sizeof(LongInt); LONG_SIZE_BYTES = sizeof(Int64); type TMessageType = LongInt; TRemoteProcessClient = class private FSocket: ClientSocket; FPreviousPlayers: TPlayerArray; FPreviousFacilities: TFacilityArray; FTerrainByCellXY: TTerrainTypeArray2D; FWeatherByCellXY: TWeatherTypeArray2D; FPreviousPlayerById: TPlayerArray; FPreviousFacilityById: TFacilityArray; {$HINTS OFF} function ReadFacility: TFacility; procedure WriteFacility(facility: TFacility); function ReadFacilities: TFacilityArray; procedure WriteFacilities(facilities: TFacilityArray); function ReadGame: TGame; procedure WriteGame(game: TGame); function ReadGames: TGameArray; procedure WriteGames(games: TGameArray); procedure WriteMove(move: TMove); procedure WriteMoves(moves: TMoveArray); function ReadPlayer: TPlayer; procedure WritePlayer(player: TPlayer); function ReadPlayers: TPlayerArray; procedure WritePlayers(players: TPlayerArray); function ReadPlayerContext: TPlayerContext; procedure WritePlayerContext(playerContext: TPlayerContext); function ReadPlayerContexts: TPlayerContextArray; procedure WritePlayerContexts(playerContexts: TPlayerContextArray); function ReadVehicle: TVehicle; procedure WriteVehicle(vehicle: TVehicle); function ReadVehicles: TVehicleArray; procedure WriteVehicles(vehicles: TVehicleArray); function ReadVehicleUpdate: TVehicleUpdate; procedure WriteVehicleUpdate(vehicleUpdate: TVehicleUpdate); function ReadVehicleUpdates: TVehicleUpdateArray; procedure WriteVehicleUpdates(vehicleUpdates: TVehicleUpdateArray); function ReadWorld: TWorld; procedure WriteWorld(world: TWorld); function ReadWorlds: TWorldArray; procedure WriteWorlds(worlds: TWorldArray); {$HINTS ON} procedure EnsureMessageType(actualType: LongInt; expectedType: LongInt); {$HINTS OFF} function ReadByteArray(nullable: Boolean): TByteArray; procedure WriteByteArray(value: TByteArray); function ReadEnum: LongInt; function ReadEnumArray: TLongIntArray; function ReadEnumArray2D: TLongIntArray2D; procedure WriteEnum(value: LongInt); procedure WriteEnumArray(value: TLongIntArray); procedure WriteEnumArray2D(value: TLongIntArray2D); function ReadString: String; procedure WriteString(value: String); function ReadInt: LongInt; function ReadIntArray: TLongIntArray; function ReadIntArray2D: TLongIntArray2D; procedure WriteInt(value: LongInt); procedure WriteIntArray(value: TLongIntArray); procedure WriteIntArray2D(value: TLongIntArray2D); function ReadByte(): Byte; procedure WriteByte(byte: Byte); function ReadBytes(byteCount: LongInt): TByteArray; procedure WriteBytes(bytes: TByteArray); function ReadBoolean: Boolean; procedure WriteBoolean(value: Boolean); function ReadDouble: Double; procedure WriteDouble(value: Double); function ReadLong: Int64; procedure WriteLong(value: Int64); {$HINTS ON} function IsLittleEndianMachine: Boolean; procedure Reverse(var bytes: TByteArray); public constructor Create(host: String; port: LongInt); procedure WriteTokenMessage(token: String); procedure WriteProtocolVersionMessage; function ReadTeamSizeMessage: LongInt; function ReadGameContextMessage: TGame; function ReadPlayerContextMessage: TPlayerContext; procedure WriteMoveMessage(move: TMove); destructor Destroy; override; end; implementation constructor TRemoteProcessClient.Create(host: String; port: LongInt); begin FSocket := ClientSocket.Create(host, port); FPreviousPlayers := nil; FPreviousFacilities := nil; FTerrainByCellXY := nil; FWeatherByCellXY := nil; SetLength(FPreviousPlayerById, 100000); SetLength(FPreviousFacilityById, 100000); end; procedure TRemoteProcessClient.EnsureMessageType(actualType: LongInt; expectedType: LongInt); begin if actualType <> expectedType then begin HALT(10001); end; end; procedure TRemoteProcessClient.WriteTokenMessage(token: String); begin WriteEnum(AUTHENTICATION_TOKEN); WriteString(token); end; procedure TRemoteProcessClient.WriteProtocolVersionMessage; begin WriteEnum(PROTOCOL_VERSION); WriteInt(3); end; function TRemoteProcessClient.ReadTeamSizeMessage: LongInt; begin EnsureMessageType(ReadEnum, TEAM_SIZE); result := ReadInt; end; function TRemoteProcessClient.ReadGameContextMessage: TGame; begin EnsureMessageType(ReadEnum, GAME_CONTEXT); result := ReadGame; end; function TRemoteProcessClient.ReadPlayerContextMessage: TPlayerContext; var messageType: TMessageType; begin messageType := ReadEnum; if messageType = GAME_OVER then begin result := nil; exit; end; EnsureMessageType(messageType, PLAYER_CONTEXT); result := ReadPlayerContext; end; procedure TRemoteProcessClient.WriteMoveMessage(move: TMove); begin WriteEnum(MOVE_MESSAGE); WriteMove(move); end; function TRemoteProcessClient.ReadFacility: TFacility; var flag: Byte; id: Int64; facilityType: TFacilityType; ownerPlayerId: Int64; left: Double; top: Double; capturePoints: Double; vehicleType: TVehicleType; productionProgress: LongInt; begin flag := ReadByte; if flag = 0 then begin result := nil; exit; end; if flag = 127 then begin result := TFacility.Create(FPreviousFacilityById[ReadLong]); exit; end; id := ReadLong; facilityType := ReadEnum; ownerPlayerId := ReadLong; left := ReadDouble; top := ReadDouble; capturePoints := ReadDouble; vehicleType := ReadEnum; productionProgress := ReadInt; if Assigned(FPreviousFacilityById[id]) then begin FPreviousFacilityById[id].Free; end; FPreviousFacilityById[id] := TFacility.Create(id, facilityType, ownerPlayerId, left, top, capturePoints, vehicleType, productionProgress); result := TFacility.Create(FPreviousFacilityById[id]); end; procedure TRemoteProcessClient.WriteFacility(facility: TFacility); begin if facility = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteLong(facility.GetId); WriteEnum(facility.GetType); WriteLong(facility.GetOwnerPlayerId); WriteDouble(facility.GetLeft); WriteDouble(facility.GetTop); WriteDouble(facility.GetCapturePoints); WriteEnum(facility.GetVehicleType); WriteInt(facility.GetProductionProgress); end; function TRemoteProcessClient.ReadFacilities: TFacilityArray; var facilityIndex: LongInt; facilityCount: LongInt; begin facilityCount := ReadInt; if facilityCount < 0 then begin SetLength(result, Length(FPreviousFacilities)); for facilityIndex := High(FPreviousFacilities) downto 0 do begin result[facilityIndex] := TFacility.Create(FPreviousFacilities[facilityIndex]); end; exit; end; if Assigned(FPreviousFacilities) then begin for facilityIndex := High(FPreviousFacilities) downto 0 do begin if Assigned(FPreviousFacilities[facilityIndex]) then begin FPreviousFacilities[facilityIndex].Free; end; end; end; SetLength(FPreviousFacilities, facilityCount); SetLength(result, facilityCount); for facilityIndex := 0 to facilityCount - 1 do begin FPreviousFacilities[facilityIndex] := ReadFacility; result[facilityIndex] := TFacility.Create(FPreviousFacilities[facilityIndex]); end; end; procedure TRemoteProcessClient.WriteFacilities(facilities: TFacilityArray); var facilityIndex: LongInt; facilityCount: LongInt; begin if facilities = nil then begin WriteInt(-1); exit; end; facilityCount := Length(facilities); WriteInt(facilityCount); for facilityIndex := 0 to facilityCount - 1 do begin WriteFacility(facilities[facilityIndex]); end; end; function TRemoteProcessClient.ReadGame: TGame; var randomSeed: Int64; tickCount: LongInt; worldWidth: Double; worldHeight: Double; fogOfWarEnabled: Boolean; victoryScore: LongInt; facilityCaptureScore: LongInt; vehicleEliminationScore: LongInt; actionDetectionInterval: LongInt; baseActionCount: LongInt; additionalActionCountPerControlCenter: LongInt; maxUnitGroup: LongInt; terrainWeatherMapColumnCount: LongInt; terrainWeatherMapRowCount: LongInt; plainTerrainVisionFactor: Double; plainTerrainStealthFactor: Double; plainTerrainSpeedFactor: Double; swampTerrainVisionFactor: Double; swampTerrainStealthFactor: Double; swampTerrainSpeedFactor: Double; forestTerrainVisionFactor: Double; forestTerrainStealthFactor: Double; forestTerrainSpeedFactor: Double; clearWeatherVisionFactor: Double; clearWeatherStealthFactor: Double; clearWeatherSpeedFactor: Double; cloudWeatherVisionFactor: Double; cloudWeatherStealthFactor: Double; cloudWeatherSpeedFactor: Double; rainWeatherVisionFactor: Double; rainWeatherStealthFactor: Double; rainWeatherSpeedFactor: Double; vehicleRadius: Double; tankDurability: LongInt; tankSpeed: Double; tankVisionRange: Double; tankGroundAttackRange: Double; tankAerialAttackRange: Double; tankGroundDamage: LongInt; tankAerialDamage: LongInt; tankGroundDefence: LongInt; tankAerialDefence: LongInt; tankAttackCooldownTicks: LongInt; tankProductionCost: LongInt; ifvDurability: LongInt; ifvSpeed: Double; ifvVisionRange: Double; ifvGroundAttackRange: Double; ifvAerialAttackRange: Double; ifvGroundDamage: LongInt; ifvAerialDamage: LongInt; ifvGroundDefence: LongInt; ifvAerialDefence: LongInt; ifvAttackCooldownTicks: LongInt; ifvProductionCost: LongInt; arrvDurability: LongInt; arrvSpeed: Double; arrvVisionRange: Double; arrvGroundDefence: LongInt; arrvAerialDefence: LongInt; arrvProductionCost: LongInt; arrvRepairRange: Double; arrvRepairSpeed: Double; helicopterDurability: LongInt; helicopterSpeed: Double; helicopterVisionRange: Double; helicopterGroundAttackRange: Double; helicopterAerialAttackRange: Double; helicopterGroundDamage: LongInt; helicopterAerialDamage: LongInt; helicopterGroundDefence: LongInt; helicopterAerialDefence: LongInt; helicopterAttackCooldownTicks: LongInt; helicopterProductionCost: LongInt; fighterDurability: LongInt; fighterSpeed: Double; fighterVisionRange: Double; fighterGroundAttackRange: Double; fighterAerialAttackRange: Double; fighterGroundDamage: LongInt; fighterAerialDamage: LongInt; fighterGroundDefence: LongInt; fighterAerialDefence: LongInt; fighterAttackCooldownTicks: LongInt; fighterProductionCost: LongInt; maxFacilityCapturePoints: Double; facilityCapturePointsPerVehiclePerTick: Double; facilityWidth: Double; facilityHeight: Double; baseTacticalNuclearStrikeCooldown: LongInt; tacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; maxTacticalNuclearStrikeDamage: Double; tacticalNuclearStrikeRadius: Double; tacticalNuclearStrikeDelay: LongInt; begin if not ReadBoolean then begin result := nil; exit; end; randomSeed := ReadLong; tickCount := ReadInt; worldWidth := ReadDouble; worldHeight := ReadDouble; fogOfWarEnabled := ReadBoolean; victoryScore := ReadInt; facilityCaptureScore := ReadInt; vehicleEliminationScore := ReadInt; actionDetectionInterval := ReadInt; baseActionCount := ReadInt; additionalActionCountPerControlCenter := ReadInt; maxUnitGroup := ReadInt; terrainWeatherMapColumnCount := ReadInt; terrainWeatherMapRowCount := ReadInt; plainTerrainVisionFactor := ReadDouble; plainTerrainStealthFactor := ReadDouble; plainTerrainSpeedFactor := ReadDouble; swampTerrainVisionFactor := ReadDouble; swampTerrainStealthFactor := ReadDouble; swampTerrainSpeedFactor := ReadDouble; forestTerrainVisionFactor := ReadDouble; forestTerrainStealthFactor := ReadDouble; forestTerrainSpeedFactor := ReadDouble; clearWeatherVisionFactor := ReadDouble; clearWeatherStealthFactor := ReadDouble; clearWeatherSpeedFactor := ReadDouble; cloudWeatherVisionFactor := ReadDouble; cloudWeatherStealthFactor := ReadDouble; cloudWeatherSpeedFactor := ReadDouble; rainWeatherVisionFactor := ReadDouble; rainWeatherStealthFactor := ReadDouble; rainWeatherSpeedFactor := ReadDouble; vehicleRadius := ReadDouble; tankDurability := ReadInt; tankSpeed := ReadDouble; tankVisionRange := ReadDouble; tankGroundAttackRange := ReadDouble; tankAerialAttackRange := ReadDouble; tankGroundDamage := ReadInt; tankAerialDamage := ReadInt; tankGroundDefence := ReadInt; tankAerialDefence := ReadInt; tankAttackCooldownTicks := ReadInt; tankProductionCost := ReadInt; ifvDurability := ReadInt; ifvSpeed := ReadDouble; ifvVisionRange := ReadDouble; ifvGroundAttackRange := ReadDouble; ifvAerialAttackRange := ReadDouble; ifvGroundDamage := ReadInt; ifvAerialDamage := ReadInt; ifvGroundDefence := ReadInt; ifvAerialDefence := ReadInt; ifvAttackCooldownTicks := ReadInt; ifvProductionCost := ReadInt; arrvDurability := ReadInt; arrvSpeed := ReadDouble; arrvVisionRange := ReadDouble; arrvGroundDefence := ReadInt; arrvAerialDefence := ReadInt; arrvProductionCost := ReadInt; arrvRepairRange := ReadDouble; arrvRepairSpeed := ReadDouble; helicopterDurability := ReadInt; helicopterSpeed := ReadDouble; helicopterVisionRange := ReadDouble; helicopterGroundAttackRange := ReadDouble; helicopterAerialAttackRange := ReadDouble; helicopterGroundDamage := ReadInt; helicopterAerialDamage := ReadInt; helicopterGroundDefence := ReadInt; helicopterAerialDefence := ReadInt; helicopterAttackCooldownTicks := ReadInt; helicopterProductionCost := ReadInt; fighterDurability := ReadInt; fighterSpeed := ReadDouble; fighterVisionRange := ReadDouble; fighterGroundAttackRange := ReadDouble; fighterAerialAttackRange := ReadDouble; fighterGroundDamage := ReadInt; fighterAerialDamage := ReadInt; fighterGroundDefence := ReadInt; fighterAerialDefence := ReadInt; fighterAttackCooldownTicks := ReadInt; fighterProductionCost := ReadInt; maxFacilityCapturePoints := ReadDouble; facilityCapturePointsPerVehiclePerTick := ReadDouble; facilityWidth := ReadDouble; facilityHeight := ReadDouble; baseTacticalNuclearStrikeCooldown := ReadInt; tacticalNuclearStrikeCooldownDecreasePerControlCenter := ReadInt; maxTacticalNuclearStrikeDamage := ReadDouble; tacticalNuclearStrikeRadius := ReadDouble; tacticalNuclearStrikeDelay := ReadInt; result := TGame.Create(randomSeed, tickCount, worldWidth, worldHeight, fogOfWarEnabled, victoryScore, facilityCaptureScore, vehicleEliminationScore, actionDetectionInterval, baseActionCount, additionalActionCountPerControlCenter, maxUnitGroup, terrainWeatherMapColumnCount, terrainWeatherMapRowCount, plainTerrainVisionFactor, plainTerrainStealthFactor, plainTerrainSpeedFactor, swampTerrainVisionFactor, swampTerrainStealthFactor, swampTerrainSpeedFactor, forestTerrainVisionFactor, forestTerrainStealthFactor, forestTerrainSpeedFactor, clearWeatherVisionFactor, clearWeatherStealthFactor, clearWeatherSpeedFactor, cloudWeatherVisionFactor, cloudWeatherStealthFactor, cloudWeatherSpeedFactor, rainWeatherVisionFactor, rainWeatherStealthFactor, rainWeatherSpeedFactor, vehicleRadius, tankDurability, tankSpeed, tankVisionRange, tankGroundAttackRange, tankAerialAttackRange, tankGroundDamage, tankAerialDamage, tankGroundDefence, tankAerialDefence, tankAttackCooldownTicks, tankProductionCost, ifvDurability, ifvSpeed, ifvVisionRange, ifvGroundAttackRange, ifvAerialAttackRange, ifvGroundDamage, ifvAerialDamage, ifvGroundDefence, ifvAerialDefence, ifvAttackCooldownTicks, ifvProductionCost, arrvDurability, arrvSpeed, arrvVisionRange, arrvGroundDefence, arrvAerialDefence, arrvProductionCost, arrvRepairRange, arrvRepairSpeed, helicopterDurability, helicopterSpeed, helicopterVisionRange, helicopterGroundAttackRange, helicopterAerialAttackRange, helicopterGroundDamage, helicopterAerialDamage, helicopterGroundDefence, helicopterAerialDefence, helicopterAttackCooldownTicks, helicopterProductionCost, fighterDurability, fighterSpeed, fighterVisionRange, fighterGroundAttackRange, fighterAerialAttackRange, fighterGroundDamage, fighterAerialDamage, fighterGroundDefence, fighterAerialDefence, fighterAttackCooldownTicks, fighterProductionCost, maxFacilityCapturePoints, facilityCapturePointsPerVehiclePerTick, facilityWidth, facilityHeight, baseTacticalNuclearStrikeCooldown, tacticalNuclearStrikeCooldownDecreasePerControlCenter, maxTacticalNuclearStrikeDamage, tacticalNuclearStrikeRadius, tacticalNuclearStrikeDelay); end; procedure TRemoteProcessClient.WriteGame(game: TGame); begin if game = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteLong(game.GetRandomSeed); WriteInt(game.GetTickCount); WriteDouble(game.GetWorldWidth); WriteDouble(game.GetWorldHeight); WriteBoolean(game.GetFogOfWarEnabled); WriteInt(game.GetVictoryScore); WriteInt(game.GetFacilityCaptureScore); WriteInt(game.GetVehicleEliminationScore); WriteInt(game.GetActionDetectionInterval); WriteInt(game.GetBaseActionCount); WriteInt(game.GetAdditionalActionCountPerControlCenter); WriteInt(game.GetMaxUnitGroup); WriteInt(game.GetTerrainWeatherMapColumnCount); WriteInt(game.GetTerrainWeatherMapRowCount); WriteDouble(game.GetPlainTerrainVisionFactor); WriteDouble(game.GetPlainTerrainStealthFactor); WriteDouble(game.GetPlainTerrainSpeedFactor); WriteDouble(game.GetSwampTerrainVisionFactor); WriteDouble(game.GetSwampTerrainStealthFactor); WriteDouble(game.GetSwampTerrainSpeedFactor); WriteDouble(game.GetForestTerrainVisionFactor); WriteDouble(game.GetForestTerrainStealthFactor); WriteDouble(game.GetForestTerrainSpeedFactor); WriteDouble(game.GetClearWeatherVisionFactor); WriteDouble(game.GetClearWeatherStealthFactor); WriteDouble(game.GetClearWeatherSpeedFactor); WriteDouble(game.GetCloudWeatherVisionFactor); WriteDouble(game.GetCloudWeatherStealthFactor); WriteDouble(game.GetCloudWeatherSpeedFactor); WriteDouble(game.GetRainWeatherVisionFactor); WriteDouble(game.GetRainWeatherStealthFactor); WriteDouble(game.GetRainWeatherSpeedFactor); WriteDouble(game.GetVehicleRadius); WriteInt(game.GetTankDurability); WriteDouble(game.GetTankSpeed); WriteDouble(game.GetTankVisionRange); WriteDouble(game.GetTankGroundAttackRange); WriteDouble(game.GetTankAerialAttackRange); WriteInt(game.GetTankGroundDamage); WriteInt(game.GetTankAerialDamage); WriteInt(game.GetTankGroundDefence); WriteInt(game.GetTankAerialDefence); WriteInt(game.GetTankAttackCooldownTicks); WriteInt(game.GetTankProductionCost); WriteInt(game.GetIfvDurability); WriteDouble(game.GetIfvSpeed); WriteDouble(game.GetIfvVisionRange); WriteDouble(game.GetIfvGroundAttackRange); WriteDouble(game.GetIfvAerialAttackRange); WriteInt(game.GetIfvGroundDamage); WriteInt(game.GetIfvAerialDamage); WriteInt(game.GetIfvGroundDefence); WriteInt(game.GetIfvAerialDefence); WriteInt(game.GetIfvAttackCooldownTicks); WriteInt(game.GetIfvProductionCost); WriteInt(game.GetArrvDurability); WriteDouble(game.GetArrvSpeed); WriteDouble(game.GetArrvVisionRange); WriteInt(game.GetArrvGroundDefence); WriteInt(game.GetArrvAerialDefence); WriteInt(game.GetArrvProductionCost); WriteDouble(game.GetArrvRepairRange); WriteDouble(game.GetArrvRepairSpeed); WriteInt(game.GetHelicopterDurability); WriteDouble(game.GetHelicopterSpeed); WriteDouble(game.GetHelicopterVisionRange); WriteDouble(game.GetHelicopterGroundAttackRange); WriteDouble(game.GetHelicopterAerialAttackRange); WriteInt(game.GetHelicopterGroundDamage); WriteInt(game.GetHelicopterAerialDamage); WriteInt(game.GetHelicopterGroundDefence); WriteInt(game.GetHelicopterAerialDefence); WriteInt(game.GetHelicopterAttackCooldownTicks); WriteInt(game.GetHelicopterProductionCost); WriteInt(game.GetFighterDurability); WriteDouble(game.GetFighterSpeed); WriteDouble(game.GetFighterVisionRange); WriteDouble(game.GetFighterGroundAttackRange); WriteDouble(game.GetFighterAerialAttackRange); WriteInt(game.GetFighterGroundDamage); WriteInt(game.GetFighterAerialDamage); WriteInt(game.GetFighterGroundDefence); WriteInt(game.GetFighterAerialDefence); WriteInt(game.GetFighterAttackCooldownTicks); WriteInt(game.GetFighterProductionCost); WriteDouble(game.GetMaxFacilityCapturePoints); WriteDouble(game.GetFacilityCapturePointsPerVehiclePerTick); WriteDouble(game.GetFacilityWidth); WriteDouble(game.GetFacilityHeight); WriteInt(game.GetBaseTacticalNuclearStrikeCooldown); WriteInt(game.GetTacticalNuclearStrikeCooldownDecreasePerControlCenter); WriteDouble(game.GetMaxTacticalNuclearStrikeDamage); WriteDouble(game.GetTacticalNuclearStrikeRadius); WriteInt(game.GetTacticalNuclearStrikeDelay); end; function TRemoteProcessClient.ReadGames: TGameArray; var gameIndex: LongInt; gameCount: LongInt; begin gameCount := ReadInt; if gameCount < 0 then begin result := nil; exit; end; SetLength(result, gameCount); for gameIndex := 0 to gameCount - 1 do begin result[gameIndex] := ReadGame; end; end; procedure TRemoteProcessClient.WriteGames(games: TGameArray); var gameIndex: LongInt; gameCount: LongInt; begin if games = nil then begin WriteInt(-1); exit; end; gameCount := Length(games); WriteInt(gameCount); for gameIndex := 0 to gameCount - 1 do begin WriteGame(games[gameIndex]); end; end; procedure TRemoteProcessClient.WriteMove(move: TMove); begin if move = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteEnum(move.Action); WriteInt(move.Group); WriteDouble(move.Left); WriteDouble(move.Top); WriteDouble(move.Right); WriteDouble(move.Bottom); WriteDouble(move.X); WriteDouble(move.Y); WriteDouble(move.Angle); WriteDouble(move.Factor); WriteDouble(move.MaxSpeed); WriteDouble(move.MaxAngularSpeed); WriteEnum(move.VehicleType); WriteLong(move.FacilityId); WriteLong(move.VehicleId); end; procedure TRemoteProcessClient.WriteMoves(moves: TMoveArray); var moveIndex: LongInt; moveCount: LongInt; begin if moves = nil then begin WriteInt(-1); exit; end; moveCount := Length(moves); WriteInt(moveCount); for moveIndex := 0 to moveCount - 1 do begin WriteMove(moves[moveIndex]); end; end; function TRemoteProcessClient.ReadPlayer: TPlayer; var flag: Byte; id: Int64; me: Boolean; strategyCrashed: Boolean; score: LongInt; remainingActionCooldownTicks: LongInt; remainingNuclearStrikeCooldownTicks: LongInt; nextNuclearStrikeVehicleId: Int64; nextNuclearStrikeTickIndex: LongInt; nextNuclearStrikeX: Double; nextNuclearStrikeY: Double; begin flag := ReadByte; if flag = 0 then begin result := nil; exit; end; if flag = 127 then begin result := TPlayer.Create(FPreviousPlayerById[ReadLong]); exit; end; id := ReadLong; me := ReadBoolean; strategyCrashed := ReadBoolean; score := ReadInt; remainingActionCooldownTicks := ReadInt; remainingNuclearStrikeCooldownTicks := ReadInt; nextNuclearStrikeVehicleId := ReadLong; nextNuclearStrikeTickIndex := ReadInt; nextNuclearStrikeX := ReadDouble; nextNuclearStrikeY := ReadDouble; if Assigned(FPreviousPlayerById[id]) then begin FPreviousPlayerById[id].Free; end; FPreviousPlayerById[id] := TPlayer.Create(id, me, strategyCrashed, score, remainingActionCooldownTicks, remainingNuclearStrikeCooldownTicks, nextNuclearStrikeVehicleId, nextNuclearStrikeTickIndex, nextNuclearStrikeX, nextNuclearStrikeY); result := TPlayer.Create(FPreviousPlayerById[id]); end; procedure TRemoteProcessClient.WritePlayer(player: TPlayer); begin if player = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteLong(player.GetId); WriteBoolean(player.GetMe); WriteBoolean(player.GetStrategyCrashed); WriteInt(player.GetScore); WriteInt(player.GetRemainingActionCooldownTicks); WriteInt(player.GetRemainingNuclearStrikeCooldownTicks); WriteLong(player.GetNextNuclearStrikeVehicleId); WriteInt(player.GetNextNuclearStrikeTickIndex); WriteDouble(player.GetNextNuclearStrikeX); WriteDouble(player.GetNextNuclearStrikeY); end; function TRemoteProcessClient.ReadPlayers: TPlayerArray; var playerIndex: LongInt; playerCount: LongInt; begin playerCount := ReadInt; if playerCount < 0 then begin SetLength(result, Length(FPreviousPlayers)); for playerIndex := High(FPreviousPlayers) downto 0 do begin result[playerIndex] := TPlayer.Create(FPreviousPlayers[playerIndex]); end; exit; end; if Assigned(FPreviousPlayers) then begin for playerIndex := High(FPreviousPlayers) downto 0 do begin if Assigned(FPreviousPlayers[playerIndex]) then begin FPreviousPlayers[playerIndex].Free; end; end; end; SetLength(FPreviousPlayers, playerCount); SetLength(result, playerCount); for playerIndex := 0 to playerCount - 1 do begin FPreviousPlayers[playerIndex] := ReadPlayer; result[playerIndex] := TPlayer.Create(FPreviousPlayers[playerIndex]); end; end; procedure TRemoteProcessClient.WritePlayers(players: TPlayerArray); var playerIndex: LongInt; playerCount: LongInt; begin if players = nil then begin WriteInt(-1); exit; end; playerCount := Length(players); WriteInt(playerCount); for playerIndex := 0 to playerCount - 1 do begin WritePlayer(players[playerIndex]); end; end; function TRemoteProcessClient.ReadPlayerContext: TPlayerContext; var player: TPlayer; world: TWorld; begin if not ReadBoolean then begin result := nil; exit; end; player := ReadPlayer; world := ReadWorld; result := TPlayerContext.Create(player, world); end; procedure TRemoteProcessClient.WritePlayerContext(playerContext: TPlayerContext); begin if playerContext = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WritePlayer(playerContext.GetPlayer); WriteWorld(playerContext.GetWorld); end; function TRemoteProcessClient.ReadPlayerContexts: TPlayerContextArray; var playerContextIndex: LongInt; playerContextCount: LongInt; begin playerContextCount := ReadInt; if playerContextCount < 0 then begin result := nil; exit; end; SetLength(result, playerContextCount); for playerContextIndex := 0 to playerContextCount - 1 do begin result[playerContextIndex] := ReadPlayerContext; end; end; procedure TRemoteProcessClient.WritePlayerContexts(playerContexts: TPlayerContextArray); var playerContextIndex: LongInt; playerContextCount: LongInt; begin if playerContexts = nil then begin WriteInt(-1); exit; end; playerContextCount := Length(playerContexts); WriteInt(playerContextCount); for playerContextIndex := 0 to playerContextCount - 1 do begin WritePlayerContext(playerContexts[playerContextIndex]); end; end; function TRemoteProcessClient.ReadVehicle: TVehicle; var id: Int64; x: Double; y: Double; radius: Double; playerId: Int64; durability: LongInt; maxDurability: LongInt; maxSpeed: Double; visionRange: Double; squaredVisionRange: Double; groundAttackRange: Double; squaredGroundAttackRange: Double; aerialAttackRange: Double; squaredAerialAttackRange: Double; groundDamage: LongInt; aerialDamage: LongInt; groundDefence: LongInt; aerialDefence: LongInt; attackCooldownTicks: LongInt; remainingAttackCooldownTicks: LongInt; vehicleType: TVehicleType; aerial: Boolean; selected: Boolean; groups: TLongIntArray; begin if not ReadBoolean then begin result := nil; exit; end; id := ReadLong; x := ReadDouble; y := ReadDouble; radius := ReadDouble; playerId := ReadLong; durability := ReadInt; maxDurability := ReadInt; maxSpeed := ReadDouble; visionRange := ReadDouble; squaredVisionRange := ReadDouble; groundAttackRange := ReadDouble; squaredGroundAttackRange := ReadDouble; aerialAttackRange := ReadDouble; squaredAerialAttackRange := ReadDouble; groundDamage := ReadInt; aerialDamage := ReadInt; groundDefence := ReadInt; aerialDefence := ReadInt; attackCooldownTicks := ReadInt; remainingAttackCooldownTicks := ReadInt; vehicleType := ReadEnum; aerial := ReadBoolean; selected := ReadBoolean; groups := ReadIntArray; result := TVehicle.Create(id, x, y, radius, playerId, durability, maxDurability, maxSpeed, visionRange, squaredVisionRange, groundAttackRange, squaredGroundAttackRange, aerialAttackRange, squaredAerialAttackRange, groundDamage, aerialDamage, groundDefence, aerialDefence, attackCooldownTicks, remainingAttackCooldownTicks, vehicleType, aerial, selected, groups); end; procedure TRemoteProcessClient.WriteVehicle(vehicle: TVehicle); begin if vehicle = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteLong(vehicle.GetId); WriteDouble(vehicle.GetX); WriteDouble(vehicle.GetY); WriteDouble(vehicle.GetRadius); WriteLong(vehicle.GetPlayerId); WriteInt(vehicle.GetDurability); WriteInt(vehicle.GetMaxDurability); WriteDouble(vehicle.GetMaxSpeed); WriteDouble(vehicle.GetVisionRange); WriteDouble(vehicle.GetSquaredVisionRange); WriteDouble(vehicle.GetGroundAttackRange); WriteDouble(vehicle.GetSquaredGroundAttackRange); WriteDouble(vehicle.GetAerialAttackRange); WriteDouble(vehicle.GetSquaredAerialAttackRange); WriteInt(vehicle.GetGroundDamage); WriteInt(vehicle.GetAerialDamage); WriteInt(vehicle.GetGroundDefence); WriteInt(vehicle.GetAerialDefence); WriteInt(vehicle.GetAttackCooldownTicks); WriteInt(vehicle.GetRemainingAttackCooldownTicks); WriteEnum(vehicle.GetType); WriteBoolean(vehicle.GetAerial); WriteBoolean(vehicle.GetSelected); WriteIntArray(vehicle.GetGroups); end; function TRemoteProcessClient.ReadVehicles: TVehicleArray; var vehicleIndex: LongInt; vehicleCount: LongInt; begin vehicleCount := ReadInt; if vehicleCount < 0 then begin result := nil; exit; end; SetLength(result, vehicleCount); for vehicleIndex := 0 to vehicleCount - 1 do begin result[vehicleIndex] := ReadVehicle; end; end; procedure TRemoteProcessClient.WriteVehicles(vehicles: TVehicleArray); var vehicleIndex: LongInt; vehicleCount: LongInt; begin if vehicles = nil then begin WriteInt(-1); exit; end; vehicleCount := Length(vehicles); WriteInt(vehicleCount); for vehicleIndex := 0 to vehicleCount - 1 do begin WriteVehicle(vehicles[vehicleIndex]); end; end; function TRemoteProcessClient.ReadVehicleUpdate: TVehicleUpdate; var id: Int64; x: Double; y: Double; durability: LongInt; remainingAttackCooldownTicks: LongInt; selected: Boolean; groups: TLongIntArray; begin if not ReadBoolean then begin result := nil; exit; end; id := ReadLong; x := ReadDouble; y := ReadDouble; durability := ReadInt; remainingAttackCooldownTicks := ReadInt; selected := ReadBoolean; groups := ReadIntArray; result := TVehicleUpdate.Create(id, x, y, durability, remainingAttackCooldownTicks, selected, groups); end; procedure TRemoteProcessClient.WriteVehicleUpdate(vehicleUpdate: TVehicleUpdate); begin if vehicleUpdate = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteLong(vehicleUpdate.GetId); WriteDouble(vehicleUpdate.GetX); WriteDouble(vehicleUpdate.GetY); WriteInt(vehicleUpdate.GetDurability); WriteInt(vehicleUpdate.GetRemainingAttackCooldownTicks); WriteBoolean(vehicleUpdate.GetSelected); WriteIntArray(vehicleUpdate.GetGroups); end; function TRemoteProcessClient.ReadVehicleUpdates: TVehicleUpdateArray; var vehicleUpdateIndex: LongInt; vehicleUpdateCount: LongInt; begin vehicleUpdateCount := ReadInt; if vehicleUpdateCount < 0 then begin result := nil; exit; end; SetLength(result, vehicleUpdateCount); for vehicleUpdateIndex := 0 to vehicleUpdateCount - 1 do begin result[vehicleUpdateIndex] := ReadVehicleUpdate; end; end; procedure TRemoteProcessClient.WriteVehicleUpdates(vehicleUpdates: TVehicleUpdateArray); var vehicleUpdateIndex: LongInt; vehicleUpdateCount: LongInt; begin if vehicleUpdates = nil then begin WriteInt(-1); exit; end; vehicleUpdateCount := Length(vehicleUpdates); WriteInt(vehicleUpdateCount); for vehicleUpdateIndex := 0 to vehicleUpdateCount - 1 do begin WriteVehicleUpdate(vehicleUpdates[vehicleUpdateIndex]); end; end; function TRemoteProcessClient.ReadWorld: TWorld; var tickIndex: LongInt; tickCount: LongInt; width: Double; height: Double; players: TPlayerArray; newVehicles: TVehicleArray; vehicleUpdates: TVehicleUpdateArray; facilities: TFacilityArray; begin if not ReadBoolean then begin result := nil; exit; end; tickIndex := ReadInt; tickCount := ReadInt; width := ReadDouble; height := ReadDouble; players := ReadPlayers; newVehicles := ReadVehicles; vehicleUpdates := ReadVehicleUpdates; if not Assigned(FTerrainByCellXY) then begin FTerrainByCellXY := ReadEnumArray2D; end; if not Assigned(FWeatherByCellXY) then begin FWeatherByCellXY := ReadEnumArray2D; end; facilities := ReadFacilities; result := TWorld.Create(tickIndex, tickCount, width, height, players, newVehicles, vehicleUpdates, FTerrainByCellXY, FWeatherByCellXY, facilities); end; procedure TRemoteProcessClient.WriteWorld(world: TWorld); begin if world = nil then begin WriteBoolean(false); exit; end; WriteBoolean(true); WriteInt(world.GetTickIndex); WriteInt(world.GetTickCount); WriteDouble(world.GetWidth); WriteDouble(world.GetHeight); WritePlayers(world.GetPlayers); WriteVehicles(world.GetNewVehicles); WriteVehicleUpdates(world.GetVehicleUpdates); WriteEnumArray2D(world.GetTerrainByCellXY); WriteEnumArray2D(world.GetWeatherByCellXY); WriteFacilities(world.GetFacilities); end; function TRemoteProcessClient.ReadWorlds: TWorldArray; var worldIndex: LongInt; worldCount: LongInt; begin worldCount := ReadInt; if worldCount < 0 then begin result := nil; exit; end; SetLength(result, worldCount); for worldIndex := 0 to worldCount - 1 do begin result[worldIndex] := ReadWorld; end; end; procedure TRemoteProcessClient.WriteWorlds(worlds: TWorldArray); var worldIndex: LongInt; worldCount: LongInt; begin if worlds = nil then begin WriteInt(-1); exit; end; worldCount := Length(worlds); WriteInt(worldCount); for worldIndex := 0 to worldCount - 1 do begin WriteWorld(worlds[worldIndex]); end; end; function TRemoteProcessClient.ReadByteArray(nullable: Boolean): TByteArray; var len: LongInt; begin len := ReadInt; if nullable then begin if len < 0 then begin result := nil; exit; end; end else begin if len <= 0 then begin SetLength(result, 0); exit; end; end; result := ReadBytes(len); end; procedure TRemoteProcessClient.WriteByteArray(value: TByteArray); begin if value = nil then begin WriteInt(-1); exit; end; WriteInt(Length(value)); WriteBytes(value); end; procedure TRemoteProcessClient.WriteEnum(value: LongInt); var bytes: TByteArray; begin SetLength(bytes, 1); bytes[0] := value; WriteBytes(bytes); Finalize(bytes); end; procedure TRemoteProcessClient.WriteEnumArray(value: TLongIntArray); var i, len: LongInt; begin if value = nil then begin WriteInt(-1); exit; end; len := Length(value); WriteInt(len); for i := 0 to len - 1 do begin WriteEnum(value[i]); end; end; procedure TRemoteProcessClient.WriteEnumArray2D(value: TLongIntArray2D); var i, len: LongInt; begin if value = nil then begin WriteInt(-1); exit; end; len := Length(value); WriteInt(len); for i := 0 to len - 1 do begin WriteEnumArray(value[i]); end; end; function TRemoteProcessClient.ReadEnum: TMessageType; var bytes: TByteArray; begin bytes := ReadBytes(1); result := bytes[0]; Finalize(bytes); end; function TRemoteProcessClient.ReadEnumArray: TLongIntArray; var i, len: LongInt; begin len := ReadInt; if len < 0 then begin result := nil; exit; end; SetLength(result, len); for i := 0 to len - 1 do begin result[i] := ReadEnum; end; end; function TRemoteProcessClient.ReadEnumArray2D: TLongIntArray2D; var i, len: LongInt; begin len := ReadInt; if len < 0 then begin result := nil; exit; end; SetLength(result, len); for i := 0 to len - 1 do begin result[i] := ReadEnumArray; end; end; function TRemoteProcessClient.ReadByte(): Byte; var bytes: TByteArray; begin SetLength(bytes, 1); FSocket.StrictReceive(bytes, 1); result := bytes[0]; Finalize(bytes); end; procedure TRemoteProcessClient.WriteByte(byte: Byte); var bytes: TByteArray; begin SetLength(bytes, 1); bytes[0] := byte; FSocket.StrictSend(bytes, 1); Finalize(bytes); end; function TRemoteProcessClient.ReadBytes(byteCount: LongInt): TByteArray; var bytes: TByteArray; begin SetLength(bytes, byteCount); FSocket.StrictReceive(bytes, byteCount); result := bytes; end; procedure TRemoteProcessClient.WriteBytes(bytes: TByteArray); begin FSocket.StrictSend(bytes, Length(bytes)); end; procedure TRemoteProcessClient.WriteString(value: String); var len, i: LongInt; bytes: TByteArray; AnsiValue: AnsiString; begin AnsiValue := AnsiString(value); len := Length(AnsiValue); SetLength(bytes, len); for i := 1 to len do begin bytes[i - 1] := Ord(AnsiValue[i]); end; WriteInt(len); WriteBytes(bytes); Finalize(bytes); end; procedure TRemoteProcessClient.WriteBoolean(value: Boolean); begin WriteByte(Ord(value)); end; function TRemoteProcessClient.ReadBoolean: Boolean; begin result := (ReadByte() <> 0); end; function TRemoteProcessClient.ReadString: String; var len, i: LongInt; bytes: TByteArray; res: AnsiString; begin len := ReadInt; if len = -1 then begin HALT(10014); end; res := ''; bytes := ReadBytes(len); for i := 0 to len - 1 do begin res := res + AnsiChar(bytes[i]); end; Finalize(bytes); result := string(res); end; procedure TRemoteProcessClient.WriteDouble(value: Double); var pl: ^Int64; pd: ^Double; p: Pointer; begin New(pd); pd^ := value; p := pd; pl := p; WriteLong(pl^); Dispose(pd); end; function TRemoteProcessClient.ReadDouble: Double; var pl: ^Int64; pd: ^Double; p: Pointer; begin New(pl); pl^ := ReadLong; p := pl; pd := p; result := pd^; Dispose(pl); end; procedure TRemoteProcessClient.WriteInt(value: LongInt); var bytes: TByteArray; i: LongInt; begin SetLength(bytes, INTEGER_SIZE_BYTES); for i := 0 to INTEGER_SIZE_BYTES - 1 do begin bytes[i] := (value shr ({24 -} i * 8)) and 255; end; if (IsLittleEndianMachine <> LITTLE_ENDIAN_BYTE_ORDER) then begin Reverse(bytes); end; WriteBytes(bytes); Finalize(bytes); end; procedure TRemoteProcessClient.WriteIntArray(value: TLongIntArray); var i, len: LongInt; begin if value = nil then begin WriteInt(-1); exit; end; len := Length(value); WriteInt(len); for i := 0 to len - 1 do begin WriteInt(value[i]); end; end; procedure TRemoteProcessClient.WriteIntArray2D(value: TLongIntArray2D); var i, len: LongInt; begin if value = nil then begin WriteInt(-1); exit; end; len := Length(value); WriteInt(len); for i := 0 to len - 1 do begin WriteIntArray(value[i]); end; end; function TRemoteProcessClient.ReadInt: LongInt; var bytes: TByteArray; res: LongInt; i: LongInt; begin res := 0; bytes := readBytes(INTEGER_SIZE_BYTES); for i := INTEGER_SIZE_BYTES - 1 downto 0 do begin res := (res shl 8) or bytes[i]; end; Finalize(bytes); result := res; end; function TRemoteProcessClient.ReadIntArray: TLongIntArray; var i, len: LongInt; begin len := ReadInt; if len < 0 then begin result := nil; exit; end; SetLength(result, len); for i := 0 to len - 1 do begin result[i] := ReadInt; end; end; function TRemoteProcessClient.ReadIntArray2D: TLongIntArray2D; var i, len: LongInt; begin len := ReadInt; if len < 0 then begin result := nil; exit; end; SetLength(result, len); for i := 0 to len - 1 do begin result[i] := ReadIntArray; end; end; function TRemoteProcessClient.ReadLong: Int64; var bytes: TByteArray; res: Int64; i: LongInt; begin res := 0; bytes := readBytes(LONG_SIZE_BYTES); for i := LONG_SIZE_BYTES - 1 downto 0 do begin res := (res shl 8) or bytes[i]; end; Finalize(bytes); result := res; end; procedure TRemoteProcessClient.WriteLong(value: Int64); var bytes: TByteArray; i: LongInt; begin SetLength(bytes, LONG_SIZE_BYTES); for i := 0 to LONG_SIZE_BYTES - 1 do begin bytes[i] := (value shr ({24 -} i*8)) and 255; end; if IsLittleEndianMachine <> LITTLE_ENDIAN_BYTE_ORDER then begin Reverse(bytes); end; WriteBytes(bytes); Finalize(bytes); end; function TRemoteProcessClient.IsLittleEndianMachine: Boolean; begin result := true; end; procedure TRemoteProcessClient.Reverse(var bytes: TByteArray); var i, len: LongInt; buffer: Byte; begin len := Length(bytes); for i := 0 to (len div 2) do begin buffer := bytes[i]; bytes[i] := bytes[len - i - 1]; bytes[len - i - 1] := buffer; end; end; destructor TRemoteProcessClient.Destroy; var playerIndex: LongInt; facilityIndex: LongInt; begin FSocket.Free; if Assigned(FPreviousPlayers) then begin for playerIndex := High(FPreviousPlayers) downto 0 do begin if Assigned(FPreviousPlayers[playerIndex]) then begin FPreviousPlayers[playerIndex].Free; end; end; end; if Assigned(FPreviousFacilities) then begin for facilityIndex := High(FPreviousFacilities) downto 0 do begin if Assigned(FPreviousFacilities[facilityIndex]) then begin FPreviousFacilities[facilityIndex].Free; end; end; end; if Assigned(FPreviousPlayerById) then begin for playerIndex := High(FPreviousPlayerById) downto 0 do begin if Assigned(FPreviousPlayerById[playerIndex]) then begin FPreviousPlayerById[playerIndex].Free; end; end; end; if Assigned(FPreviousFacilityById) then begin for facilityIndex := High(FPreviousFacilityById) downto 0 do begin if Assigned(FPreviousFacilityById[facilityIndex]) then begin FPreviousFacilityById[facilityIndex].Free; end; end; end; end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcDateTimeZone.pas } { File version: 5.09 } { Description: Date/Time Zone functions } { } { Copyright: Copyright (c) 2000-2021, David J Butler } { } { Revision history: } { } { 2000/03/05 1.01 Added Time Zone functions from cInternetStandards. } { 2000/08/16 1.02 Fixed bug in UTBias reported by Gerhard Steinwedel. } { 2005/08/19 4.03 Compilable with FreePascal 2.0.1 Win32 i386. } { 2005/08/21 4.04 Compilable with FreePascal 2.0.1 Linux i386. } { 2009/10/09 4.05 Compilable with Delphi 2009 Win32/.NET. } { 2010/06/27 4.06 Compilable with FreePascal 2.4.0 OSX x86-64 } { 2018/08/13 5.07 String type changes. } { 2020/10/27 5.08 Move Time zone function into unit. } { 2021/10/19 5.09 Add conditional defines for tests. } { } { Supported compilers: } { } { Delphi 10.2 Win32/Win64 5.08 2021/08/06 } { Delphi 10.2 Linux64 5.08 2021/08/06 } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$IFDEF TEST} {$DEFINE DATETIME_TEST} {$ENDIF} unit flcDateTimeZone; interface { } { Universal Time (UT) Bias } { } { Returns the UT bias (in minutes) } function UTBias: Integer; { } { Universal Time (UT) } { } { Returns Universal Time (UT) in local date/time } function UTToLocalDateTime(const AValue: TDateTime): TDateTime; { Returns a date/time in Universal Time (UT) } function LocalDateTimeToUT(const AValue: TDateTime): TDateTime; { Returns the current time in Universal Time (UT) } function NowUT: TDateTime; { } { Test } { } {$IFDEF DATETIME_TEST} procedure Test; {$ENDIF} implementation uses {$IFDEF MSWIN} Windows, {$ENDIF} SysUtils, {$IFDEF DATETIME_TEST} flcTimers, {$ENDIF} {$IFDEF DELPHI} {$IFDEF POSIX} Posix.SysTime, {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFDEF DELPHI6_UP} DateUtils; {$ENDIF} {$ENDIF} {$IFDEF UNIX} {$IFDEF FREEPASCAL} BaseUnix, Unix; {$ENDIF} {$ENDIF} { } { UTBias } { Returns the UT bias (in minutes) from the operating system's regional } { settings. } { } {$UNDEF UTBiasDefined} {$IFDEF DELPHIXE2_UP} {$IFNDEF UTBiasDefined} {$DEFINE UTBiasDefined} function UTBias: Integer; var N : TDateTime; begin N := Now; Result := Round((TTimeZone.Local.ToUniversalTime(N) - N) * 24 * 60); end; {$ENDIF} {$ENDIF} {$IFDEF WindowsPlatform} {$IFNDEF UTBiasDefined} {$DEFINE UTBiasDefined} function UTBias: Integer; var TZI : TTimeZoneInformation; begin case GetTimeZoneInformation(TZI) of TIME_ZONE_ID_STANDARD : Result := TZI.StandardBias; TIME_ZONE_ID_DAYLIGHT : Result := TZI.DaylightBias else Result := 0; end; Result := Result + TZI.Bias; end; {$ENDIF} {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF POSIX} {$IFNDEF UTBiasDefined} {$DEFINE UTBiasDefined} function UTBias: Integer; var TV : TTimeVal; TZ : PTimeZone; begin TZ := nil; fpGetTimeOfDay(@TV, TZ); if Assigned(TZ) then Result := TZ^.tz_minuteswest else Result := 0; end; {$ENDIF} {$ENDIF} {$ENDIF} {$IFNDEF UTBiasDefined} {$DEFINE UTBiasDefined} function UTBias: Integer; begin Result := 0; end; {$ENDIF} { } { Universal Time (UT) } { } function UTToLocalDateTime(const AValue: TDateTime): TDateTime; begin Result := AValue - UTBias / (24 * 60) end; function LocalDateTimeToUT(const AValue: TDateTime): TDateTime; begin Result := AValue + UTBias / (24 * 60) end; function NowUT: TDateTime; begin Result := LocalDateTimeToUT(Now); end; { } { Test } { } {$IFDEF DATETIME_TEST} procedure Test; const MiDa = 12 * 60; var D, E : TDateTime; begin Assert(UTBias <= MiDa); Assert(UTBias >= -MiDa); D := NowUT; E := UTToLocalDateTime(D); Assert(LocalDateTimeToUT(E) = D); D := Now; E := LocalDateTimeToUT(D); Assert(UTToLocalDateTime(E) = D); end; {$ENDIF} end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.47 1/7/05 3:29:34 PM RLebeau Fix for AV in Notification() Rev 1.46 11/28/04 2:31:38 PM RLebeau Updated Authenticate() to create the TIdEncoderMIME instance before sending the 'AUTH LOGIN' command. Rev 1.45 11/27/2004 8:58:14 PM JPMugaas Compile errors. Rev 1.44 11/27/04 3:21:30 AM RLebeau Fixed bug in ownership of SASLMechanisms property. Recoded Authenticate() to use a "case of" statement instead. Rev 1.43 10/26/2004 10:55:34 PM JPMugaas Updated refs. Rev 1.42 6/11/2004 9:38:40 AM DSiders Added "Do not Localize" comments. Rev 1.41 2004.03.06 1:31:52 PM czhower To match Disconnect changes to core. Rev 1.40 2/25/2004 5:41:28 AM JPMugaas Authentication bug fixed. Rev 1.39 2004.02.03 5:44:20 PM czhower Name changes Rev 1.38 1/31/2004 3:12:56 AM JPMugaas Removed dependancy on Math unit. It isn't needed and is problematic in some versions of Dlephi which don't include it. Rev 1.37 26/01/2004 01:51:38 CCostelloe Changed implementation of supressing BCC List generation Rev 1.36 25/01/2004 21:16:16 CCostelloe Added support for SuppressBCCListInHeader Rev 1.35 1/25/2004 3:11:44 PM JPMugaas SASL Interface reworked to make it easier for developers to use. SSL and SASL reenabled components. Rev 1.34 2004.01.22 10:29:56 PM czhower Now supports default login mechanism with just username and pw. Rev 1.33 1/21/2004 4:03:22 PM JPMugaas InitComponent Rev 1.32 12/28/2003 4:47:02 PM BGooijen Removed ChangeReplyClass Rev 1.31 22/12/2003 00:46:16 CCostelloe .NET fixes Rev 1.30 24/10/2003 20:53:02 CCostelloe Bug fix of LRecipients.EMailAddresses in Send. Rev 1.29 2003.10.17 6:15:16 PM czhower Bug fix with quit. Rev 1.28 10/17/2003 1:01:04 AM DSiders Added localization comments. Rev 1.27 2003.10.14 1:28:04 PM czhower DotNet Rev 1.26 10/11/2003 7:14:36 PM BGooijen Changed IdCompilerDefines.inc path Rev 1.25 10/10/2003 10:45:10 PM BGooijen DotNet Rev 1.24 2003.10.02 9:27:52 PM czhower DotNet Excludes Rev 1.23 6/15/2003 03:28:30 PM JPMugaas Minor class change. Rev 1.22 6/15/2003 01:13:40 PM JPMugaas Now uses new base class. Rev 1.21 6/5/2003 04:54:08 AM JPMugaas Reworkings and minor changes for new Reply exception framework. Rev 1.20 6/4/2003 04:10:40 PM JPMugaas Removed hacked GetInternelResponse. Updated to use Kudzu's new string reply code. Rev 1.19 5/26/2003 12:24:04 PM JPMugaas Rev 1.18 5/25/2003 03:54:48 AM JPMugaas Rev 1.17 5/25/2003 12:13:22 AM JPMugaas SMTP StartTLS code moved into IdSMTPCommon for sharing with TIdDirectSMTP. StartTLS is now called in Authenticate to prevent unintentional unencrypted password transmission (e.g. AUTH LOGIN being called before STARTTLS). Rev 1.16 5/23/2003 04:52:26 AM JPMugaas Work started on TIdDirectSMTP to support enhanced error codes. Rev 1.15 5/22/2003 05:26:16 PM JPMugaas RFC 2034 Rev 1.14 5/18/2003 02:31:42 PM JPMugaas Reworked some things so IdSMTP and IdDirectSMTP can share code including stuff for pipelining. Rev 1.13 5/15/2003 11:09:46 AM JPMugaas "RFC 2197 SMTP Service Extension for Command Pipelining" now supported. It should increase efficiency in TIdSMTP. Rev 1.12 5/13/2003 07:35:06 AM JPMugaas Made UseEHLO a requirement for explicit TLS because explicit TLS using EHLO to determine if the server supports explicit TLS. Setting UseEHLO will the UseTLS property be the default (no encryption) and setting UseTLS to an explicit TLS setting will cause the UseEHLO property to be true. Rev 1.11 5/13/2003 07:03:48 AM JPMugaas Ciaran Costelloe reported a bug in the Assign method. Username and Password were still being assigned even though the SMTP component does not publish or use them. I have updated the SMTP assign method with the new properties and removed the references to Password and Username. Rev 1.10 5/10/2003 10:10:40 PM JPMugaas Bug fixes. Rev 1.9 5/8/2003 08:44:22 PM JPMugaas Moved some SASL authentication code down to an anscestor for reuse. WIll clean up soon. Rev 1.8 5/8/2003 03:18:30 PM JPMugaas Flattened ou the SASL authentication API, made a custom descendant of SASL enabled TIdMessageClient classes. Rev 1.7 5/8/2003 11:28:14 AM JPMugaas Moved feature negoation properties down to the ExplicitTLSClient level as feature negotiation goes hand in hand with explicit TLS support. Rev 1.6 5/8/2003 02:18:18 AM JPMugaas Fixed an AV in IdPOP3 with SASL list on forms. Made exceptions for SASL mechanisms missing more consistant, made IdPOP3 support feature feature negotiation, and consolidated some duplicate code. Rev 1.5 4/5/2003 02:06:32 PM JPMugaas TLS handshake itself can now be handled. Rev 1.4 3/27/2003 05:46:50 AM JPMugaas Updated framework with an event if the TLS negotiation command fails. Cleaned up some duplicate code in the clients. Rev 1.3 3/26/2003 04:19:34 PM JPMugaas Cleaned-up some code and illiminated some duplicate things. Rev 1.2 3/13/2003 09:49:32 AM JPMugaas Now uses an abstract SSL base class instead of OpenSSL so 3rd-party vendors can plug-in their products. Rev 1.1 12/15/2002 05:50:18 PM JPMugaas SMTP and IMAP4 compile. IdPOP3, IdFTP, IMAP4, and IdSMTP now restored in IdRegister. Rev 1.0 11/13/2002 08:00:48 AM JPMugaas } unit IdSMTP; interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdEMailAddress, IdException, IdExplicitTLSClientServerBase, IdHeaderList, IdMessage, IdMessageClient, IdSASL, IdSASLCollection, IdSMTPBase, IdBaseComponent, IdGlobal, SysUtils; type TIdSMTPAuthenticationType = (satNone, satDefault, satSASL); const DEF_SMTP_AUTH = satDefault; type //FSASLMechanisms TIdSMTP = class(TIdSMTPBase) protected FAuthType: TIdSMTPAuthenticationType; // This is just an internal flag we use to determine if we already authenticated to the server. FDidAuthenticate: Boolean; FValidateAuthLoginCapability: Boolean; // FSASLMechanisms : TIdSASLList; FSASLMechanisms : TIdSASLEntries; // procedure SetAuthType(const AValue: TIdSMTPAuthenticationType); procedure SetUseEhlo(const AValue: Boolean); override; procedure SetUseTLS(AValue: TIdUseTLS); override; procedure SetSASLMechanisms(AValue: TIdSASLEntries); procedure InitComponent; override; procedure InternalSend(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; // // holger: .NET compatibility change, OnConnected being reintroduced property OnConnected; public destructor Destroy; override; procedure Assign(Source: TPersistent); override; function Authenticate: Boolean; virtual; procedure Connect; override; procedure Disconnect(ANotifyPeer: Boolean); override; procedure DisconnectNotifyPeer; override; class procedure QuickSend(const AHost, ASubject, ATo, AFrom, AText: string); overload; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use ContentType overload of QuickSend()'{$ENDIF};{$ENDIF} class procedure QuickSend(const AHost, ASubject, ATo, AFrom, AText, AContentType, ACharset, AContentTransferEncoding: string); overload; procedure Expand(AUserName : String; AResults : TStrings); virtual; function Verify(AUserName : String) : String; virtual; // property DidAuthenticate: Boolean read FDidAuthenticate; published property AuthType: TIdSMTPAuthenticationType read FAuthType write FAuthType default DEF_SMTP_AUTH; property Host; property Password; property Port default IdPORT_SMTP; // property SASLMechanisms: TIdSASLList read FSASLMechanisms write FSASLMechanisms; property SASLMechanisms : TIdSASLEntries read FSASLMechanisms write SetSASLMechanisms; property UseTLS; property Username; property ValidateAuthLoginCapability: Boolean read FValidateAuthLoginCapability write FValidateAuthLoginCapability default True; // property OnTLSNotAvailable; end; implementation uses IdCoderMIME, IdGlobalProtocols, IdReplySMTP, IdSSL, IdResourceStringsProtocols, IdTCPConnection; { TIdSMTP } procedure TIdSMTP.Assign(Source: TPersistent); var LS: TIdSMTP; begin if Source is TIdSMTP then begin LS := Source as TIdSMTP; AuthType := LS.AuthType; HeloName := LS.HeloName; SASLMechanisms := LS.SASLMechanisms; UseEhlo := LS.UseEhlo; UseTLS := LS.UseTLS; Host := LS.Host; MailAgent := LS.MailAgent; Port := LS.Port; Username := LS.Username; Password := LS.Password; Pipeline := LS.Pipeline; end else begin inherited Assign(Source); end; end; function TIdSMTP.Authenticate : Boolean; var s : TStrings; begin if FDidAuthenticate then begin Result := True; Exit; end; //This will look strange but we have logic in that method to make //sure that the STARTTLS command is used appropriately. //Note we put this in Authenticate only to ensure that TLS negotiation //is done before a password is sent over a network unencrypted. StartTLS; //note that we pass the reply numbers as strings so the SASL stuff can work //with IMAP4 and POP3 where non-numeric strings are used for reply codes case FAuthType of satNone: begin //do nothing FDidAuthenticate := True; end; satDefault: begin if Username <> '' then begin if FValidateAuthLoginCapability then begin s := TStringList.Create; try SASLMechanisms.ParseCapaReplyToList(Capabilities, s); //many servers today do not use username/password authentication if s.IndexOf('LOGIN') = -1 then begin Result := False; Exit; end; finally FreeAndNil(s); end; end; with TIdEncoderMIME.Create(nil) do try SendCmd('AUTH LOGIN', 334); if SendCmd(Encode(Username), [235, 334]) = 334 then begin SendCmd(Encode(Password), 235); end; finally Free; end; FDidAuthenticate := True; end; { RLebeau: TODO - implement the following code in the future instead of the code above. This way, TIdSASLLogin can be utilized. SASLMechanisms.LoginSASL('AUTH', 'LOGIN', ['235'], ['334'], Self, Capabilities); FDidAuthenticate := True; } end; satSASL: begin SASLMechanisms.LoginSASL('AUTH', FHost, IdGSKSSN_smtp, ['235'], ['334'], Self, Capabilities); {do not localize} FDidAuthenticate := True; end; end; Result := FDidAuthenticate; end; procedure TIdSMTP.Connect; begin FDidAuthenticate := False; inherited Connect; try GetResponse(220); SendGreeting; except Disconnect(False); raise; end; end; procedure TIdSMTP.InitComponent; begin inherited InitComponent; FSASLMechanisms := TIdSASLEntries.Create(Self); FAuthType := DEF_SMTP_AUTH; FValidateAuthLoginCapability := True; end; procedure TIdSMTP.DisconnectNotifyPeer; begin inherited DisconnectNotifyPeer; SendCmd('QUIT', 221); {Do not Localize} end; procedure TIdSMTP.Expand(AUserName: String; AResults: TStrings); begin SendCMD('EXPN ' + AUserName, [250, 251]); {Do not Localize} end; procedure InternalQuickSend(const AHost, ASubject, ATo, AFrom, AText, AContentType, ACharset, AContentTransferEncoding: String); {$IFDEF USE_INLINE}inline;{$ENDIF} var LSMTP: TIdSMTP; LMsg: TIdMessage; begin LSMTP := TIdSMTP.Create(nil); try LMsg := TIdMessage.Create(LSMTP); try with LMsg do begin Subject := ASubject; Recipients.EMailAddresses := ATo; From.Text := AFrom; Body.Text := AText; ContentType := AContentType; CharSet := ACharset; ContentTransferEncoding := AContentTransferEncoding; end; with LSMTP do begin Host := AHost; Connect; try; Send(LMsg); finally Disconnect; end; end; finally FreeAndNil(LMsg); end; finally FreeAndNil(LSMTP); end; end; class procedure TIdSMTP.QuickSend(const AHost, ASubject, ATo, AFrom, AText: String); begin InternalQuickSend(AHost, ASubject, ATo, AFrom, AText, '', '', ''); end; class procedure TIdSMTP.QuickSend(const AHost, ASubject, ATo, AFrom, AText, AContentType, ACharset, AContentTransferEncoding: String); begin InternalQuickSend(AHost, ASubject, ATo, AFrom, AText, AContentType, ACharset, AContentTransferEncoding); end; procedure TIdSMTP.InternalSend(AMsg: TIdMessage; const AFrom: String; ARecipients: TIdEMailAddressList); begin //Authenticate now calls StartTLS //so that you do not send login information before TLS negotiation (big oops security wise). //It also should see if authentication should be done according to your settings. Authenticate; AMsg.ExtraHeaders.Values[XMAILER_HEADER] := MailAgent; inherited InternalSend(AMsg, AFrom, ARecipients); end; procedure TIdSMTP.SetAuthType(const AValue: TIdSMTPAuthenticationType); Begin FAuthType := AValue; if AValue = satSASL then begin FUseEhlo := True; end; end; procedure TIdSMTP.SetUseEhlo(const AValue: Boolean); Begin FUseEhlo := AValue; if not AValue then begin FAuthType := satDefault; if FUseTLS in ExplicitTLSVals then begin FUseTLS := DEF_USETLS; FPipeLine := False; end; end; End; function TIdSMTP.Verify(AUserName: string): string; begin SendCMD('VRFY ' + AUserName, [250, 251]); {Do not Localize} Result := LastCmdResult.Text[0]; end; procedure TIdSMTP.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (FSASLMechanisms <> nil) then begin FSASLMechanisms.RemoveByComp(AComponent); end; inherited Notification(AComponent, Operation); end; procedure TIdSMTP.SetUseTLS(AValue: TIdUseTLS); begin inherited SetUseTLS(AValue); if FUseTLS in ExplicitTLSVals then begin UseEhlo := True; end; end; procedure TIdSMTP.SetSASLMechanisms(AValue: TIdSASLEntries); begin FSASLMechanisms.Assign(AValue); end; destructor TIdSMTP.Destroy; begin FreeAndNil(FSASLMechanisms); inherited Destroy; end; procedure TIdSMTP.Disconnect(ANotifyPeer: Boolean); begin try inherited Disconnect(ANotifyPeer); finally FDidAuthenticate := False; end; end; end.
unit TTSCITMTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCITMRecord = record PLenderNum: String[4]; PCollCode: String[8]; PTrackCode: String[8]; PModCount: Integer; PCritical: Boolean; PCIFDate: String[8]; End; TTTSCITMBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCITMRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCITM = (TTSCITMPrimaryKey, TTSCITMbyTrackCode); TTTSCITMTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCollCode: TStringField; FDFTrackCode: TStringField; FDFModCount: TIntegerField; FDFCritical: TBooleanField; FDFCIFDate: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCollCode(const Value: String); function GetPCollCode:String; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPCritical(const Value: Boolean); function GetPCritical:Boolean; procedure SetPCIFDate(const Value: String); function GetPCIFDate:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSCITM); function GetEnumIndex: TEITTSCITM; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCITMRecord; procedure StoreDataBuffer(ABuffer:TTTSCITMRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCollCode: TStringField read FDFCollCode; property DFTrackCode: TStringField read FDFTrackCode; property DFModCount: TIntegerField read FDFModCount; property DFCritical: TBooleanField read FDFCritical; property DFCIFDate: TStringField read FDFCIFDate; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCollCode: String read GetPCollCode write SetPCollCode; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PModCount: Integer read GetPModCount write SetPModCount; property PCritical: Boolean read GetPCritical write SetPCritical; property PCIFDate: String read GetPCIFDate write SetPCIFDate; published property Active write SetActive; property EnumIndex: TEITTSCITM read GetEnumIndex write SetEnumIndex; end; { TTTSCITMTable } procedure Register; implementation function TTTSCITMTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSCITMTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSCITMTable.GenerateNewFieldName } function TTTSCITMTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSCITMTable.CreateField } procedure TTTSCITMTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCollCode := CreateField( 'CollCode' ) as TStringField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFCritical := CreateField( 'Critical' ) as TBooleanField; FDFCIFDate := CreateField( 'CIFDate' ) as TStringField; end; { TTTSCITMTable.CreateFields } procedure TTTSCITMTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCITMTable.SetActive } procedure TTTSCITMTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCITMTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCITMTable.SetPCollCode(const Value: String); begin DFCollCode.Value := Value; end; function TTTSCITMTable.GetPCollCode:String; begin result := DFCollCode.Value; end; procedure TTTSCITMTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSCITMTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSCITMTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSCITMTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSCITMTable.SetPCritical(const Value: Boolean); begin DFCritical.Value := Value; end; function TTTSCITMTable.GetPCritical:Boolean; begin result := DFCritical.Value; end; procedure TTTSCITMTable.SetPCIFDate(const Value: String); begin DFCIFDate.Value := Value; end; function TTTSCITMTable.GetPCIFDate:String; begin result := DFCIFDate.Value; end; procedure TTTSCITMTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CollCode, String, 8, N'); Add('TrackCode, String, 8, N'); Add('ModCount, Integer, 0, N'); Add('Critical, Boolean, 0, N'); Add('CIFDate, String, 8, N'); end; end; procedure TTTSCITMTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CollCode;TrackCode, Y, Y, N, N'); Add('byTrackCode, LenderNum;TrackCode, N, N, Y, N'); end; end; procedure TTTSCITMTable.SetEnumIndex(Value: TEITTSCITM); begin case Value of TTSCITMPrimaryKey : IndexName := ''; TTSCITMbyTrackCode : IndexName := 'byTrackCode'; end; end; function TTTSCITMTable.GetDataBuffer:TTTSCITMRecord; var buf: TTTSCITMRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCollCode := DFCollCode.Value; buf.PTrackCode := DFTrackCode.Value; buf.PModCount := DFModCount.Value; buf.PCritical := DFCritical.Value; buf.PCIFDate := DFCIFDate.Value; result := buf; end; procedure TTTSCITMTable.StoreDataBuffer(ABuffer:TTTSCITMRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCollCode.Value := ABuffer.PCollCode; DFTrackCode.Value := ABuffer.PTrackCode; DFModCount.Value := ABuffer.PModCount; DFCritical.Value := ABuffer.PCritical; DFCIFDate.Value := ABuffer.PCIFDate; end; function TTTSCITMTable.GetEnumIndex: TEITTSCITM; var iname : string; begin result := TTSCITMPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCITMPrimaryKey; if iname = 'BYTRACKCODE' then result := TTSCITMbyTrackCode; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCITMTable, TTTSCITMBuffer ] ); end; { Register } function TTTSCITMBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('LENDERNUM','COLLCODE','TRACKCODE','MODCOUNT','CRITICAL','CIFDATE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TTTSCITMBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftBoolean; 6 : result := ftString; end; end; function TTTSCITMBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCollCode; 3 : result := @Data.PTrackCode; 4 : result := @Data.PModCount; 5 : result := @Data.PCritical; 6 : result := @Data.PCIFDate; end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_LogWindow * Implements a Window widget that displays the current engine log *********************************************************************************************************************** } Unit TERRA_LogWindow; Interface Uses TERRA_Utils, TERRA_Log, TERRA_UI, TERRA_Widgets; {$I terra.inc} Procedure ActivateLogWindow; Implementation Const MaxLines = 16; Var LogLines:Array[0..MaxLines] Of TERRAString; LogWnd:UIWindow; LogText:UILabel; Working:Boolean = False; Procedure MyLogFilter(Module, Desc:TERRAString); Var N,I:Integer; S:TERRAString; Begin If (UI.Instance.DefaultFont=Nil) Or (Working) Then Exit; N := -1; For I:=0 To Pred(MaxLines) Do If (LogLines[I]='') Then Begin N := I; Break; End; If (N<0) Then Begin For I:=0 To Pred(MaxLines-1) Do LogLines[I] := LogLines[I+1]; N := Pred(MaxLines); End; LogLines[N] := Module+':'+Desc; S := ''; For I:=0 To Pred(MaxLines) Do S := S+LogLines[I]+'\n'; If (LogWnd=Nil) Then Begin Working := True; LogWnd := UIWindow.Create('logwnd_', 0,0,99, 8, 10); LogWnd.AllowDragging := True; LogWnd.CenterOnScreen(); LogText := UILabel.Create('logtext_', LogWnd, 20, 20, 0.1, ''); Working := False; End; LogText.Caption := S; End; Procedure ActivateLogWindow; Begin Log.Instance.SetFilter(logDebug, MyLogFilter); End; Initialization End.
unit ChampionUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ChampionsLogic; type TChampionForm = class(TForm) LolLogo: TImage; ChampionImage: TImage; InputField: TEdit; SearchButton: TButton; ClearButton: TButton; ExitButton: TButton; ChampionStats: TLabel; ChampNotFound: TLabel; procedure FormCreate(Sender: TObject); procedure ExitButtonClick(Sender: TObject); procedure InputFieldClick(Sender: TObject); procedure SearchButtonClick(Sender: TObject); procedure ClearButtonClick(Sender: TObject); private function ShowChampion(Champion : TChampion) : String; function CheckResourceType(Champion : TChampion) : String; function ShowInputDlg() : String; procedure SetChampionImage(ChampionName : String); procedure ClearChampionInfo(); procedure ChampionNotFound(); public end; var ChampionForm: TChampionForm; implementation {$R *.dfm} function TChampionForm.ShowInputDlg() : String; var ChampName : String; DoContinue : boolean; begin repeat DoContinue := InputQuery('Welcome...', 'Input champion''s name:', ChampName); if DoContinue then begin if DoesChampionExists(ChampName) then begin Result := ChampName; Break; end else MessageDlg('Champion not found. Try again!', mtInformation,[mbOk],0); end until (DoContinue = False); end; function TChampionForm.CheckResourceType(Champion : TChampion) : String; begin if Champion.ResourceType = 'Mana' then Result := 'Resource type: Mana' + sLineBreak + 'Resource regen: ' + IntToStr(Champion.ResourceRegen) + ' / second' else if Champion.ResourceType = 'Energy' then Result := 'Resource type: Energy' + sLineBreak + 'Resource regen: ' + IntToStr(Champion.ResourceRegen) + ' / second' else if Champion.ResourceType = 'Rage' then Result := 'Resource type: Rage' + sLineBreak + 'Resource gain: ' + IntToStr(Champion.ResourceRegen) + ' / attack or damage' else if Champion.ResourceType = 'Ferocity' then Result := 'Resource type: Ferocity' + sLineBreak + 'Resource gain: ' + IntToStr(Champion.ResourceRegen) + ' / ability' else if Champion.ResourceType = 'Courage' then Result := 'Resource type: Courage' + sLineBreak + 'Resource gain: ' + IntToStr(Champion.ResourceRegen) + ' / attack' else if Champion.ResourceType = 'Health' then Result := 'Resource type: Health' else if Champion.ResourceType = 'None' then Result := 'Resource type: None'; end; procedure TChampionForm.ChampionNotFound(); begin ChampionStats.Caption := ''; ChampionImage.Picture := nil; ChampNotFound.Caption := 'Champion not found.'; end; procedure TChampionForm.ClearChampionInfo(); begin InputField.Clear; ChampionImage.Picture := nil; ChampionStats.Caption := ''; ChampNotFound.Caption := ''; end; procedure TChampionForm.SetChampionImage(ChampionName : String); var FixedChampionName : String; begin FixedChampionName := StringReplace(ChampionName, ' ', '', [rfReplaceAll, rfIgnoreCase]); try ChampionImage.Picture.LoadFromFile('images\' + FixedChampionName + '.bmp'); except on EFOpenError do begin ChampionImage.Picture := nil; ShowMessage('Champion''s image not found.'); end; end; end; function TChampionForm.ShowChampion(Champion : TChampion) : String; begin ChampionStats.Caption := 'Name: ' + Champion.Name + sLineBreak + 'Role: ' + Champion.Role + sLineBreak + 'Health: ' + IntToStr(Champion.Health) + sLineBreak + 'Health regen: ' + IntToStr(Champion.HealthRegen) + ' / second' + sLineBreak + CheckResourceType(Champion) + sLineBreak + 'Ability power: ' + IntToStr(Champion.AbilityPower) + sLineBreak + 'Attack type: ' + Champion.AttackType + sLineBreak + 'Attack damage: ' + IntToStr(Champion.AttackDamage) + sLineBreak + 'Attack speed: ' + FloatToStr(Champion.AttackSpeed) + sLineBreak + 'Attack range: ' + IntToStr(Champion.AttackRange) + sLineBreak + 'Armor: ' + IntToStr(Champion.Armor) + sLineBreak + 'Magic resist: ' + IntToStr(Champion.MagicResist) + sLineBreak + 'Movement speed: ' + IntToStr(Champion.MovementSpeed); SetChampionImage(Champion.Name); end; procedure TChampionForm.FormCreate(Sender: TObject); var UserInput : String; begin UserInput := ShowInputDlg(); if UserInput = '' then Application.Terminate else begin ShowChampion(GetChampion(UserInput)); LolLogo.Picture.LoadFromFile('images\leagueoflegends.bmp'); end; end; procedure TChampionForm.ExitButtonClick(Sender: TObject); begin Application.Terminate; end; procedure TChampionForm.InputFieldClick(Sender: TObject); begin InputField.Clear; end; procedure TChampionForm.SearchButtonClick(Sender: TObject); begin if DoesChampionExists(InputField.Text) then begin ShowChampion(GetChampion(InputField.Text)); ChampNotFound.Caption := ''; end else ChampionNotFound(); end; procedure TChampionForm.ClearButtonClick(Sender: TObject); begin ClearChampionInfo(); end; end.
{$include lem_directives.inc} unit FMain; {------------------------------------------------------------------------------- This is the main form which does almost nothing. It's black and fullscreen to prevent seeing the desktop when changing forms. -------------------------------------------------------------------------------} { DONE : releaserate adjusting } { DONE : better animated objects drawing } { DONE : make levelcode screen type-able } { DONE : mouse scrolling and minimap click } { DONE : perfect level logic GUI } { DONE : enable saving, replaying from postviewscreen } { TODO: make use of tbitmap32.drawto(dst, x, y, srcrect) } { TODO: make sure sounds en music can be set off before the bassmod is loaded } { TODO: safe load bassmod?} { TODO : maybe create palette class? } { TODO : Strip UTools } { TODO : Remove refs to kernel, when making opensource } { TODO : add levelcode system, randomize codesystem } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FBaseDosForm, //LemSettings, LemGame, AppController; const LM_START = WM_USER + 1; type TMainForm = class(TBaseDosForm) procedure FormActivate(Sender: TObject); private Started: Boolean; AppController: TAppController; procedure LMStart(var Msg: TMessage); message LM_START; procedure PlayGame; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.LMStart(var Msg: TMessage); begin //Hide; PlayGame; end; constructor TMainForm.Create(aOwner: TComponent); begin inherited; //ProgramSettings := TProgramSettings.Create; GlobalGame := TLemmingGame.Create(nil); AppController := TAppController.Create(nil); end; destructor TMainForm.Destroy; begin GlobalGame.Free; AppController.Free; // ProgramSettings.Free; inherited; end; procedure TMainForm.PlayGame; begin try AppController.Execute; Close; except on E: Exception do begin Application.ShowException(E); Close; end; end; end; procedure TMainForm.FormActivate(Sender: TObject); begin if Started then Exit; Started := True; PostMessage(Handle, LM_START, 0, 0); end; end. //system
unit Search_ScalingSupport_Controls; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search_ScalingSupport_Controls.pas" // Стереотип: "VCMControls" // Элемент модели: "ScalingSupport" MUID: (5278E45101D3) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin)} uses l3IntfUses {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} // NOT Defined(NoVCM) ; type TCanChangeScale = ( ccsUnknown , ccsNo , ccsYes , ccsYesIfPossible );//TCanChangeScale IScalable_ChangeScale_Params = interface {* Параметры для операции Scalable.ChangeScale } function Get_Inc: Boolean; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); property Inc: Boolean read Get_Inc; property ResultValue: Boolean read Get_ResultValue write Set_ResultValue; end;//IScalable_ChangeScale_Params Op_Scalable_ChangeScale = {final} class {* Класс для вызова операции Scalable.ChangeScale } public class function Call(const aTarget: IvcmEntity; aInc: Boolean): Boolean; overload; {* Вызов операции Scalable.ChangeScale у сущности } class function Call(const aTarget: IvcmAggregate; aInc: Boolean): Boolean; overload; {* Вызов операции Scalable.ChangeScale у агрегации } class function Call(const aTarget: IvcmEntityForm; aInc: Boolean): Boolean; overload; {* Вызов операции Scalable.ChangeScale у формы } class function Call(const aTarget: IvcmContainer; aInc: Boolean): Boolean; overload; {* Вызов операции Scalable.ChangeScale у контейнера } end;//Op_Scalable_ChangeScale IScalable_CanChangeScale_Params = interface {* Параметры для операции Scalable.CanChangeScale } function Get_nInc: Boolean; function Get_ResultValue: TCanChangeScale; procedure Set_ResultValue(aValue: TCanChangeScale); property nInc: Boolean read Get_nInc; property ResultValue: TCanChangeScale read Get_ResultValue write Set_ResultValue; end;//IScalable_CanChangeScale_Params Op_Scalable_CanChangeScale = {final} class {* Класс для вызова операции Scalable.CanChangeScale } public class function Call(const aTarget: IvcmEntity; anInc: Boolean): TCanChangeScale; overload; {* Вызов операции Scalable.CanChangeScale у сущности } class function Call(const aTarget: IvcmAggregate; anInc: Boolean): TCanChangeScale; overload; {* Вызов операции Scalable.CanChangeScale у агрегации } class function Call(const aTarget: IvcmEntityForm; anInc: Boolean): TCanChangeScale; overload; {* Вызов операции Scalable.CanChangeScale у формы } class function Call(const aTarget: IvcmContainer; anInc: Boolean): TCanChangeScale; overload; {* Вызов операции Scalable.CanChangeScale у контейнера } end;//Op_Scalable_CanChangeScale const en_Scalable = 'Scalable'; en_capScalable = 'Масштабируемый объект'; op_ChangeScale = 'ChangeScale'; op_capChangeScale = 'Изменить масштаб'; op_CanChangeScale = 'CanChangeScale'; op_capCanChangeScale = 'Масштабирование запрещено'; var opcode_Scalable_ChangeScale: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Scalable_CanChangeScale: TvcmOPID = (rEnID : -1; rOpID : -1); {$IfEnd} // NOT Defined(Admin) implementation {$If NOT Defined(Admin)} uses l3ImplUses , l3CProtoObject {$If NOT Defined(NoVCM)} , vcmOperationsForRegister {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmOperationStatesForRegister {$IfEnd} // NOT Defined(NoVCM) , l3Base {$If NOT Defined(NoVCM)} , vcmBase {$IfEnd} // NOT Defined(NoVCM) ; type TScalable_ChangeScale_Params = {final} class(Tl3CProtoObject, IScalable_ChangeScale_Params) {* Реализация IScalable_ChangeScale_Params } private f_Inc: Boolean; f_ResultValue: Boolean; protected function Get_Inc: Boolean; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); public constructor Create(aInc: Boolean); reintroduce; class function Make(aInc: Boolean): IScalable_ChangeScale_Params; reintroduce; end;//TScalable_ChangeScale_Params TScalable_CanChangeScale_Params = {final} class(Tl3CProtoObject, IScalable_CanChangeScale_Params) {* Реализация IScalable_CanChangeScale_Params } private f_nInc: Boolean; f_ResultValue: TCanChangeScale; protected function Get_nInc: Boolean; function Get_ResultValue: TCanChangeScale; procedure Set_ResultValue(aValue: TCanChangeScale); public constructor Create(anInc: Boolean); reintroduce; class function Make(anInc: Boolean): IScalable_CanChangeScale_Params; reintroduce; end;//TScalable_CanChangeScale_Params constructor TScalable_ChangeScale_Params.Create(aInc: Boolean); begin inherited Create; f_Inc := aInc; end;//TScalable_ChangeScale_Params.Create class function TScalable_ChangeScale_Params.Make(aInc: Boolean): IScalable_ChangeScale_Params; var l_Inst : TScalable_ChangeScale_Params; begin l_Inst := Create(aInc); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TScalable_ChangeScale_Params.Make function TScalable_ChangeScale_Params.Get_Inc: Boolean; begin Result := f_Inc; end;//TScalable_ChangeScale_Params.Get_Inc function TScalable_ChangeScale_Params.Get_ResultValue: Boolean; begin Result := f_ResultValue; end;//TScalable_ChangeScale_Params.Get_ResultValue procedure TScalable_ChangeScale_Params.Set_ResultValue(aValue: Boolean); begin f_ResultValue := aValue; end;//TScalable_ChangeScale_Params.Set_ResultValue class function Op_Scalable_ChangeScale.Call(const aTarget: IvcmEntity; aInc: Boolean): Boolean; {* Вызов операции Scalable.ChangeScale у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TScalable_ChangeScale_Params.Make(aInc)); aTarget.Operation(opcode_Scalable_ChangeScale, l_Params); with l_Params do begin if Done then begin Result := IScalable_ChangeScale_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Scalable_ChangeScale.Call class function Op_Scalable_ChangeScale.Call(const aTarget: IvcmAggregate; aInc: Boolean): Boolean; {* Вызов операции Scalable.ChangeScale у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TScalable_ChangeScale_Params.Make(aInc)); aTarget.Operation(opcode_Scalable_ChangeScale, l_Params); with l_Params do begin if Done then begin Result := IScalable_ChangeScale_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Scalable_ChangeScale.Call class function Op_Scalable_ChangeScale.Call(const aTarget: IvcmEntityForm; aInc: Boolean): Boolean; {* Вызов операции Scalable.ChangeScale у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aInc); end;//Op_Scalable_ChangeScale.Call class function Op_Scalable_ChangeScale.Call(const aTarget: IvcmContainer; aInc: Boolean): Boolean; {* Вызов операции Scalable.ChangeScale у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aInc); end;//Op_Scalable_ChangeScale.Call constructor TScalable_CanChangeScale_Params.Create(anInc: Boolean); begin inherited Create; f_nInc := anInc; end;//TScalable_CanChangeScale_Params.Create class function TScalable_CanChangeScale_Params.Make(anInc: Boolean): IScalable_CanChangeScale_Params; var l_Inst : TScalable_CanChangeScale_Params; begin l_Inst := Create(anInc); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TScalable_CanChangeScale_Params.Make function TScalable_CanChangeScale_Params.Get_nInc: Boolean; begin Result := f_nInc; end;//TScalable_CanChangeScale_Params.Get_nInc function TScalable_CanChangeScale_Params.Get_ResultValue: TCanChangeScale; begin Result := f_ResultValue; end;//TScalable_CanChangeScale_Params.Get_ResultValue procedure TScalable_CanChangeScale_Params.Set_ResultValue(aValue: TCanChangeScale); begin f_ResultValue := aValue; end;//TScalable_CanChangeScale_Params.Set_ResultValue class function Op_Scalable_CanChangeScale.Call(const aTarget: IvcmEntity; anInc: Boolean): TCanChangeScale; {* Вызов операции Scalable.CanChangeScale у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TScalable_CanChangeScale_Params.Make(anInc)); aTarget.Operation(opcode_Scalable_CanChangeScale, l_Params); with l_Params do begin if Done then begin Result := IScalable_CanChangeScale_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Scalable_CanChangeScale.Call class function Op_Scalable_CanChangeScale.Call(const aTarget: IvcmAggregate; anInc: Boolean): TCanChangeScale; {* Вызов операции Scalable.CanChangeScale у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TScalable_CanChangeScale_Params.Make(anInc)); aTarget.Operation(opcode_Scalable_CanChangeScale, l_Params); with l_Params do begin if Done then begin Result := IScalable_CanChangeScale_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Scalable_CanChangeScale.Call class function Op_Scalable_CanChangeScale.Call(const aTarget: IvcmEntityForm; anInc: Boolean): TCanChangeScale; {* Вызов операции Scalable.CanChangeScale у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, anInc); end;//Op_Scalable_CanChangeScale.Call class function Op_Scalable_CanChangeScale.Call(const aTarget: IvcmContainer; anInc: Boolean): TCanChangeScale; {* Вызов операции Scalable.CanChangeScale у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, anInc); end;//Op_Scalable_CanChangeScale.Call initialization with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Scalable, op_ChangeScale, en_capScalable, op_capChangeScale, True, False, opcode_Scalable_ChangeScale)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Scalable, op_CanChangeScale, en_capScalable, op_capCanChangeScale, True, False, opcode_Scalable_CanChangeScale)) do begin end; {$IfEnd} // NOT Defined(Admin) end.
{ Subroutine SST_W_C_CONT_DEF * * This routine is called when a continuation line has just been created * within a DEFINE statement. When installed, this routine is called by * using SST_W.LINE_NEW_CONT^. * * DEFINE statements are continued by writing "\" to the end of the * line being continued. } module sst_w_c_CONT_DEF; define sst_w_c_cont_def; %include 'sst_w_c.ins.pas'; procedure sst_w_c_cont_def; {does continuation line in DEFINE statement} begin string_append1 (sst_out.dyn_p^.str_p^.s, '\'); {write continuation char} sst_w.line_insert^; {create the new line} end;
// AKTools. akSysСover unit. // Модуль, содержащий обертки системных функций. //============================================================================= unit akSysCover; interface uses FileUtil, Windows, Classes{$IFNDEF NOFORMS}, forms, graphics, controls{$ENDIF}, Sysutils; resourcestring exUnableOpen = 'Unable to open target: "%s"'; const ExtendedKeys: set of Byte = [// incomplete list VK_INSERT, VK_DELETE, VK_HOME, VK_END, VK_PRIOR, VK_NEXT, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_NUMLOCK ]; CM_RES_SOURCE = false; CM_RES_DEST = true; type PDWordArray = ^TDWordArray; TDWordArray = array[0..8192] of DWord; TIntArray = array[0..8192] of Integer; PIntArray = ^TIntArray; TDriveState = (DS_NO_DISK, DS_UNFORMATTED_DISK, DS_EMPTY_DISK, DS_DISK_WITH_FILES); // Возвращает True, если даты одинаковы function IsDateEqual(date1, date2: TDateTime): boolean; function WinExecAndWait32V2(FileName: string; Visibility: integer): DWORD; // Регистрирует системный хот-кей, пользуясь TShortCut function RegisterShortCut(hWnd: HWND; id: Integer; key: TShortCut): Boolean; // Возвращает описание ошибки по ее Win32-коду function GetErrorByCode(ercode: DWORD): string; // Возвращает хандл указанного процесса. // После окончания работы с хандлом его необходимо закрыть функцией // CloseHandle function GetProcessHandle(ProcessID: DWORD): THandle; // Возвращает то, что написано на кнопке в таскбаре указанного приложения function GetProcessTitleByID(ProcessID: DWORD; var hndl: THandle): string; {$IFNDEF NOFORMS} // Возвращает маленькую и большую иконку к указанному файлу // Если SmallIcon/LargeIcon установить в nil, то соотествующая иконка извлекаться не будет. function ExtractIconForFile(Filen: string; SmallIcon, LargeIcon: TIcon): Boolean; // Аналог ExtractIconForFile, но иконку извлекает по ProcessID function ExtractIconForProcessID(ProcessID: THandle; SmallIcon, LargeIcon: TIcon): Boolean; {$ENDIF} // Возвращает уникальный идентификатор указанного процесса function GetUniqueProcessName(fn: string): string; // Возвращает строку с полной информацией об OS. function GetOSInfo: string; // Возвращает имя процесса ProcessID. procedure GetProcessInfo(ProcessID: DWord; var Path: string; ReturnWithPath: Boolean = false); // Делает окно hndl полупрозрачным. Perc - уровень прозрачности // в процентах (1-100). Только для Win2k. procedure SetWindowTransp(hndl: THandle; Perc: byte); // Возвращает имя системной директории function GetSystemDir: string; // Аналог Application.ProcessMessages procedure ConsoleProcessMessages; // Если reg = true, то функция регистрирует DLL, в противном случае - удаляет // информацию о ней из реестра. procedure RegisterDLL(fn: string; Reg: boolean = true); // Возвращает время компиляции проекта function GetBuildTime: TDateTime; // Отключает анимацию (выезжающие списки, менюшки и т.п.) procedure EnableAnimation(anim: Boolean; msg: Integer = SPI_SETANIMATION); // Возвращает true, если сейчас анимация включена. function GetAnimationState(msg: Integer = SPI_GETANIMATION): Boolean; // Восстанавливает системное значение анимации. procedure RestoreAnimation; procedure StoreAnimation; // Посылает окно выше всех во всех операционках: function SetForegroundWindowSp(hWnd: THandle): Boolean; // Число, привязанное к компьютеру function GetComputerID: Integer; // Возвращает класс окна function GetWindowClass(hwnd: THandle): string; // Возвращает кэпшин окна function GetWindowCaption(hwnd: THandle): string; // Возвращает хандл MDIClient'а окна hwnd. Если это не MDI-окно, то вернется 0. function GetMDIFormHandle(hwnd: THandle): THandle; // Возвращает хандл активного MDIChild'а от MDIClient'а hwnd function GetActiveMDIChildHandle(client: THandle): THandle; // Возвращает хандл активного окна. Если это MDI-форма, то вернется хандл активного чаилда. function GetActiveWindowEx(OnlyMDI: Boolean = false): THandle; // Возвращает true, если левая кнопка мыши нажата function IsLMButtonPressed: Boolean; // Возвращает true, если правая кнопка мыши нажата function IsRMButtonPressed: Boolean; // Копирует файл. Если он уже существует и имеет другой регистр букв, то он // удаляется и создается по новой. // Если в src указать маску, то будут скопированы все файлы, соответствующие // маске в каталог trg procedure CopyFileCase(src: string; trg: string); function ForceDirectoriesCase(Dir: string): Boolean; procedure TryOpenUrl(url: string; showerr: Boolean = true); function EncodeHtml(const S: string): string; // Запускает программу prg с параметром ShortFileName(fn) через Shell Execute procedure OpenFileIn(prog: string; fn: string); // Запускает программу prg с параметром fn через Shell Execute procedure ExecuteApp(prog: string; param: string); // Возвращает версию InternetExplorer (если она выше либо равна 4.0) function GetIEVersion(var major, minor: Integer): string; // Уничтожает объект, а затем присваивает ему значение nil procedure SafeFreeAndNil(var Obj); // Читает/пишет одну переменную в реестр procedure StoreParamsInReg(SoftwareKey, SoftwareSubKey: string; const Vl: Variant; ParamName: string = 'Default'); function RestoreParamsFromReg(SoftwareKey, SoftwareSubKey: string; const Def: Variant; ParamName: string = 'Default'): Variant; // Возвращает 1, если скринсэйвер выполняется. // 0, если не выполняется // -1, если неизвестно function IsScreenSaverRunning: Integer; // Если при использовании ConsoleProcessMessages эта переменная // установилась в true, то нужно выходить из приложения. var TerminateApp: Boolean; MenuAnimationOn, ComboboxAnimationOn, AnimationOn: Boolean; // Эмулирует нажатие кнопок procedure SimulateKeyDown(Key: byte); procedure SimulateKeyUp(Key: byte); procedure SimulateKeystroke(Key: byte); procedure SimulateStringEnter(str: string); // Функи для сохранения/чтения информации в стерим/память: function SaveStrToMem(const Ptr: Pointer; const str: string): Pointer; function ReadStrFromMem(const Ptr: Pointer; out ResPtr: Pointer): string; function CopyMem(const Destination: Pointer; const Source: Pointer; Length: DWORD; ReturnDestPtr: Boolean = true): Pointer; function ReadMem(const Destination: Pointer; const Source: Pointer; Length: DWORD): Pointer; function WriteMem(const Destination: Pointer; const Source: Pointer; Length: DWORD): Pointer; function SizeOfStrMem(Str: string): Integer; //////////////////////////////////////////////// function notBool(bool: Boolean): Boolean; procedure ListLocalDrives(Strings: TStringList); // Грузит иконку из ресурса resname // Если запущены из Win2k/XP то также пытается загрузить иконку из ресурса // resnameXP function LoadImageXP(hInst: LongWord; resname: string; sizeX, sizeY: Integer): HIcon; function DrawIconXP(posx, posy: Integer; resname: string; where: TCanvas; sizeX, sizeY: Integer): Boolean; // Tooltips: procedure ShowBalloonTip(Control: TWinControl; Icon: integer; Title: pchar; Text: PWideChar; BackCL, TextCL: TColor); type EFileMappingError = class(Exception); //--------------------------------------------------------------------------- // Класс предназначеный для упрощения обмена данными между приложениями. EChannel = class(Exception); TChannel = class(TObject) fChannelName: string; // fMemory: THandle; fFMObject: Integer; fFMMem: Pointer; fFMLen: Integer; private procedure Close; public procedure Clean; constructor Create(Channel: string; var Data; Len: Integer); destructor Destroy; override; end; //--------------------------------------------------------------------------- // Класс предназначеный для работы с файлами, отображенными на память. TFileMapping = class(TObject) private FPtr: Pointer; FSz: Integer; hFile, hMapFile: THandle; procedure Finalize; public constructor Create(fn: string); destructor Destroy; override; property Data: Pointer read FPtr; property Size: Integer read FSz; end; // Создает список всех окон процесса, указанного в DetectNow. TProcessWindows = class private hForProc: THandle; // Хандл процесса, по которому строим список окон fResultList: TStringList; // сюда запишутся все найденный онка процесса hForProc public procedure Clear; constructor Create; destructor Destroy; override; // Возвращает список окон, принаддежащих процессу forProc // Поле object на самом деле имеет тип THandle и содержит хандлы соответсвующих окон function DetectNow(forProc: THandle): TStringList; end; implementation uses TlHelp32, psapi, ShellAPI, Messages, akDataUtils, Menus, FileCtrl, Registry, akStrUtils, rxVerInf, akFileUtils, rxShell; const WS_EX_LAYERED = $80000; LWA_COLORKEY = 1; LWA_ALPHA = 2; type TSetLayeredWindowAttributes = function( hwnd: HWND; // handle to the layered window crKey: Integer; // specifies the color key bAlpha: byte; // value for the blend function dwFlags: DWORD // action ): BOOL; stdcall; type TgptInfo = record procID: DWORD; hndl: THandle; buff: string; end; function EncodeHtml(const S: string): string; var I: Integer; begin Result := ''; for I := 1 to Length(S) do if (Ord(S[I]) in [33..36, 39..42, 48..57, 64..90, 97..122]) then Result := Result + S[I] else Result := Result + '%' + IntToHex(Ord(S[I]), 2); end; function IsDateEqual(date1, date2: TDateTime): boolean; var d1, m1, y1, d2, m2, y2: word; begin DecodeDate(date1, d1, m1, y1); DecodeDate(date2, d2, m2, y2); Result := (d1 = d2) and (m1 = m2) and (y1 = y2); end; function RegisterShortCut(hWnd: HWND; id: Integer; key: TShortCut): Boolean; var vk: Word; fsModifiers: Integer; shift: TShiftState; begin ShortCutToKey(key, vk, Shift); fsModifiers := 0; if ssShift in shift then fsModifiers := fsModifiers or MOD_SHIFT; if ssAlt in shift then fsModifiers := fsModifiers or MOD_ALT; if ssCtrl in shift then fsModifiers := fsModifiers or MOD_CONTROL; Result := RegisterHotKey(hwnd, id, fsModifiers, vk); end; procedure SafeFreeAndNil(var Obj); var P: TObject; begin P := TObject(Obj); P.Free; TObject(Obj) := nil; // clear the reference after destroying the object end; function SizeOfStrMem(Str: string): Integer; begin Result := Length(Str) + 4; end; function ReadMem(const Destination: Pointer; const Source: Pointer; Length: DWORD): Pointer; begin Result := CopyMem(Destination, Source, Length, CM_RES_SOURCE); end; function WriteMem(const Destination: Pointer; const Source: Pointer; Length: DWORD): Pointer; begin Result := CopyMem(Destination, Source, Length, CM_RES_DEST); end; function CopyMem(const Destination: Pointer; const Source: Pointer; Length: DWORD; ReturnDestPtr: Boolean): Pointer; begin CopyMemory(Destination, Source, Length); if ReturnDestPtr then Result := Pointer(DWORD(Destination) + Length) else Result := Pointer(DWORD(Source) + Length); end; function SaveStrToMem(const Ptr: Pointer; const str: string): Pointer; var len: Integer; lptr: Pointer; begin len := Length(str); lptr := CopyMem(Ptr, @len, 4); Result := CopyMem(lptr, @(str[1]), len); end; function ReadStrFromMem(const Ptr: Pointer; out ResPtr: Pointer): string; var len: Integer; lptr: Pointer; begin lptr := CopyMem(@len, Ptr, 4, CM_RES_SOURCE); SetLength(Result, len); ResPtr := CopyMem(@(Result[1]), lptr, len, CM_RES_SOURCE); end; function GetErrorByCode(ercode: DWORD): string; var szMsgBuff: PChar; function MAKELANGID(p, s: Word): Word; begin Result := (s shl 10) or p; end; begin szMsgBuff := nil; // Default system message handling FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ALLOCATE_BUFFER, nil, ercode, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), @szMsgBuff, 0, nil); // end; if szMsgBuff <> nil then begin Result := StrPas(szMsgBuff); LocalFree(HLOCAL(szMsgBuff)); end else Result := ''; end; function GetUniqueProcessName(fn: string): string; var cmp: string; // hndl: THandle; vi: TVersionInfo; begin { GetProcessInfo(prc, pn, true); GetProcessTitleByID(prc, hndl); jo07-- cls := GetWindowClass(hndl); if Copy(cls, 1, 4) = 'Afx:' then cls := 'Dynamic';} cmp := ''; vi := TVersionInfo.Create(fn); try cmp := vi.CompanyName + ',' + vi.ProductName; finally vi.Free; end; Result := Format('%s:%s', [IntToHex(GetStringCrc(cmp), 8), GetFileNameWOExt(ExtractFileName(fn))]); end; procedure SimulateKeyDown(Key: byte); var flags: DWORD; begin if Key in ExtendedKeys then flags := KEYEVENTF_EXTENDEDKEY else flags := 0; keybd_event(Key, MapVirtualKey(Key, 0), flags, 0); end; procedure SimulateKeyUp(Key: byte); var flags: DWORD; begin if Key in ExtendedKeys then flags := KEYEVENTF_EXTENDEDKEY else flags := 0; keybd_event(Key, MapVirtualKey(Key, 0), KEYEVENTF_KEYUP or flags, 0); end; procedure SimulateKeystroke(Key: byte); var flags: DWORD; scancode: BYTE; begin if Key in ExtendedKeys then flags := KEYEVENTF_EXTENDEDKEY else flags := 0; scancode := MapVirtualKey(Key, 0); keybd_event(Key, scancode, flags, 0); keybd_event(Key, scancode, KEYEVENTF_KEYUP or flags, 0); end; procedure SimulateStringEnter(str: string); var i: Integer; shift: Boolean; c: Char; begin for i := 1 to Length(str) do begin c := str[i]; shift := c = '$'; if shift then begin SimulateKeyDown(VK_SHIFT); end; SimulateKeystroke(Ord(str[i])); if shift then SimulateKeyUp(VK_SHIFT); end; end; function gptEnumProc(WinHandle: HWnd; Param: LongInt): Boolean; stdcall; var gptinfo: ^TgptInfo; prc: DWORD; bf: array[0..127] of Char; begin gptinfo := Pointer(Param); Result := True; if IsWindowVisible(WinHandle) and // -Hевидимые окна (GetWindow(WinHandle, gw_Owner) = 0) and // -Дочерние окна (GetWindowText(WinHandle, bf, 128) <> 0) // -Окна без заголовков then begin GetWindowThreadProcessId(WinHandle, @prc); if (prc = gptInfo^.ProcID) then begin gptinfo^.buff := string(bf); gptinfo^.hndl := WinHandle; Result := FALSE; end; end; end; function GetProcessTitleByID(ProcessID: DWORD; var hndl: THandle): string; var gptinf: TgptInfo; begin Result := ''; gptInf.ProcID := ProcessID; gptInf.buff := ''; gptInf.hndl := 0; EnumWindows(@gptEnumProc, Integer(@gptInf)); Result := gptInf.buff; hndl := gptInf.hndl; end; function ForceDirectoriesCase(Dir: string): Boolean; var sucs: Boolean; begin Result := True; if Length(Dir) = 0 then raise Exception.Create('Error creating folder'); Dir := ExcludeTrailingBackslash(Dir); if (Length(Dir) < 3) or DirectoryExists(Dir) or (ExtractFilePath(Dir) = Dir) then begin if DirectoryExists(Dir) then RenameFile(Dir, Dir); Exit; // avoid 'xyz:\' problem. end; sucs := CreateDir(Dir); Result := ForceDirectoriesCase(ExtractFilePath(Dir)) and sucs; end; procedure CopyFileCase(src: string; trg: string); procedure _CopyFileCase(src: string; trg: string); begin if FileExists(trg) then DeleteFile(PChar(trg)); FileUtil.CopyFile(src, trg, nil); end; var isMask: Boolean; srcpth, trgpth: string; sr: TSearchRec; res: Integer; begin isMask := (Pos('*', src) <> 0) or (Pos('?', src) <> 0); if not isMask then begin _CopyFileCase(src, trg); end else begin srcpth := GetDirectory(ExtractFilePath(src)); trgpth := GetDirectory(trg); res := FindFirst(src, faArchive, sr); while res = 0 do begin _CopyFileCase(srcpth + sr.Name, trgpth + sr.Name); res := FindNext(sr); end; FindClose(sr); end; end; {$IFNDEF NOFORMS} function ExtractIconForFile(Filen: string; SmallIcon, LargeIcon: TIcon): Boolean; var largei: HIcon; smalli: HIcon; icn: Integer; begin icn := ExtractIconEx(PChar(FileN), 0, largei, smalli, 1); if icn <> 0 then begin Result := True; if not Assigned(SmallIcon) then DestroyIcon(smalli) else begin if not SmallIcon.Empty then begin DestroyIcon(SmallIcon.Handle); SmallIcon.ReleaseHandle; end; SmallIcon.Handle := smalli; end; if not Assigned(LargeIcon) then DestroyIcon(largei) else begin if not LargeIcon.Empty then begin DestroyIcon(LargeIcon.Handle); LargeIcon.ReleaseHandle; end; LargeIcon.Handle := largei; end; end else begin Result := False; end; end; function ExtractIconForProcessID(ProcessID: THandle; SmallIcon, LargeIcon: TIcon): Boolean; var pn: string; begin GetProcessInfo(ProcessID, pn, true); if pn <> '' then begin Result := ExtractIconForFile(pn, SmallIcon, LargeIcon); end else Result := false; end; {$ENDIF} function IsScreenSaverRunning: Integer; var runs: Boolean; begin // Проверяем только если это Win98/Win2k и более поздние версии : if (((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (Win32MinorVersion > 0)) or ((Win32Platform = VER_PLATFORM_WIN32_NT) and (win32MajorVersion >= 5))) and SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, @runs, 0) then begin if runs then Result := 1 else Result := 0; end else result := -1; end; function RestoreParamsFromReg(SoftwareKey, SoftwareSubKey: string; const Def: Variant; ParamName: string = 'Default'): Variant; var reg: TRegIniFile; begin reg := TRegIniFile.Create(SoftwareKey); with reg do try case VarType(Def) of varBoolean: Result := ReadBool(SoftwareSubKey, ParamName, Def); varString: Result := ReadString(SoftwareSubKey, ParamName, Def); varInteger: Result := ReadInteger(SoftwareSubKey, ParamName, Def); else raise EVariantError.Create('Unknown variant type'); end; finally Free; end; end; procedure StoreParamsInReg(SoftwareKey, SoftwareSubKey: string; const Vl: Variant; ParamName: string); var reg: TRegIniFile; begin reg := TRegIniFile.Create(SoftwareKey); with reg do try case TVarData(Vl).VType of varBoolean: WriteBool(SoftwareSubKey, ParamName, Vl); varString: WriteString(SoftwareSubKey, ParamName, Vl); varInteger: WriteInteger(SoftwareSubKey, ParamName, Vl); else raise EVariantError.Create('Unknown variant type'); end; finally Free; end; end; function GetOSInfo: string; var Platform: string; winver, BuildNumber: Integer; ver: string; begin Platform := 'Windows'; winver := win32MajorVersion * 10 + Win32MinorVersion; case Win32Platform of VER_PLATFORM_WIN32_WINDOWS: begin if Win32MinorVersion = 0 then Platform := 'Windows 95'; if Win32MinorVersion > 0 then platform := 'Windows 98'; BuildNumber := Win32BuildNumber and $0000FFFF; if BuildNumber = 3000 then Platform := 'Windows ME'; end; VER_PLATFORM_WIN32_NT: begin Platform := 'Windows NT'; if winver >= 50 then Platform := 'Windows 2000'; if winver >= 51 then Platform := 'Windows XP'; if winver >= 60 then Platform := 'Windows Vista'; BuildNumber := Win32BuildNumber; end; else begin Platform := 'Windows'; BuildNumber := 0; end; end; if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) or (Win32Platform = VER_PLATFORM_WIN32_NT) then begin if (Win32Platform = VER_PLATFORM_WIN32_NT) and (winver >= 50) then ver := '' else ver := Format(' %d.%d', [Win32MajorVersion, Win32MinorVersion]); if Trim(Win32CSDVersion) = '' then Result := Format('%s%s (Build %d)', [Platform, ver, BuildNumber]) else Result := Format('%s%s (Build %d: %s)', [Platform, ver, BuildNumber, Win32CSDVersion]); end else Result := Format('%s %d.%d', [Platform, Win32MajorVersion, Win32MinorVersion]) end; function GetIEVersion(var major, minor: Integer): string; begin Result := ''; with TRegistry.Create do try Access := KEY_QUERY_VALUE; RootKey := HKEY_LOCAL_MACHINE; OpenKey('\Software\Microsoft\Internet Explorer', False); Result := ReadString('Version'); finally CloseKey; Free; end; major := StrToIntDef(GetLeftSegment(0, Result, '.'), 0); minor := StrToIntDef(GetLeftSegment(1, Result, '.'), 0); end; function IsLMButtonPressed: Boolean; var virtKey: Integer; begin if GetSystemMetrics(SM_SWAPBUTTON) <> 0 then virtKey := VK_RBUTTON else virtKey := VK_LBUTTON; Result := GetAsyncKeyState(virtKey) <> 0; end; function IsRMButtonPressed: Boolean; var virtKey: Integer; begin if GetSystemMetrics(SM_SWAPBUTTON) = 0 then virtKey := VK_RBUTTON else virtKey := VK_LBUTTON; Result := GetAsyncKeyState(virtKey) <> 0; end; function GetComputerID: Integer; var VolumeSerialNumber: DWORD; MaximumComponentLength: DWORD; FileSystemFlags: DWORD; begin GetVolumeInformation('C:\', nil, 0, @VolumeSerialNumber, MaximumComponentLength, FileSystemFlags, nil, 0); Result := VolumeSerialNumber; end; function GetProcessHandle(ProcessID: DWORD): THandle; begin Result := OpenProcess(PROCESS_ALL_ACCESS, True, ProcessID); end; procedure GetProcessInfo(ProcessID: DWord; var Path: string; ReturnWithPath: Boolean); var hSnapshoot: THandle; pe32: TProcessEntry32; cbNeeded: Dword; hMod: HModule; hProcess: THandle; ModName: array[0..255] of char; begin Path := ''; if Win32Platform = VER_PLATFORM_WIN32_NT then // Мы в NT, используем PSAPI : begin hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ProcessID); if Boolean(hProcess) then try if EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cbNeeded) then begin GetModuleFileNameEx(hProcess, hMod, ModName, SizeOf(ModName)); Path := ModName; end else Path := IntToStr(GetLastError); finally CloseHandle(hProcess); end; end else // Мы в Win9x, используем TOOLHLP : begin hSnapshoot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); begin pe32.dwSize := SizeOf(TProcessEntry32); if (Process32First(hSnapshoot, pe32)) then repeat if pe32.th32ProcessID = ProcessID then begin Path := pe32.szExeFile; Break; end; until not Process32Next(hSnapshoot, pe32); CloseHandle(hSnapshoot); end; end; Path := lowercase(Path); if not ReturnWithPath then Path := ExtractFileName(Path); end; //****************************************************************************** //============================================================================== // TChanel //============================================================================== //****************************************************************************** procedure TChannel.Clean; begin FillChar(fFMMem^, fFMLen, 0); end; procedure TChannel.Close; begin UnMapViewOfFile(fFMMem); CloseHandle(fFMObject); // CloseHandle(fMemory); fChannelName := ''; end; constructor TChannel.Create(Channel: string; var Data; Len: Integer); begin Pointer(Data) := nil; fFMLen := Len; fChannelName := Channel; fFMObject := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, fFMLen, PChar(Channel)); if (DWORD(fFMObject) = INVALID_HANDLE_VALUE) then raise EChannel.Create('Impossible create a channel.'); fFMMem := MapViewOfFile(fFMObject, FILE_MAP_ALL_ACCESS, 0, 0, 0); if GetLastError <> ERROR_ALREADY_EXISTS then Clean; if fFMMem = nil then begin CloseHandle(fFMObject); raise EChannel.Create('Impossible map a channel object.'); end; Pointer(Data) := fFMMem; end; destructor TChannel.Destroy; begin Close; inherited; end; function GetWindowClass(hwnd: THandle): string; var winCls: string; buf: array[1..1024] of char; begin SetLength(WinCls, GetClassName(hwnd, @buf, 1024)); Move(buf[1], WinCls[1], Length(WinCls)); Result := WinCls; end; function GetWindowCaption(hwnd: THandle): string; var winTit: string; buf: array[1..1024] of char; begin if hwnd = 0 then Result := '' else begin SetLength(WinTit, GetWindowText(hwnd, @buf, 1024)); Move(buf[1], WinTit[1], Length(WinTit)); Result := WinTit; end; end; //****************************************************************************** //============================================================================== // TFileMapping //============================================================================== //****************************************************************************** constructor TFileMapping.Create(fn: string); var newfile: Boolean; begin FPtr := nil; hMapFile := 0; hFile := 0; try newfile := not FileExists(fn); hFile := CreateFile(PChar(fn), GENERIC_WRITE or GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_ALWAYS, 0, 0); if (hFile = 0) then raise EFileMappingError.CreateFmt('Could not open file "%s"', [fn]); FSz := GetFileSize(hFile, nil); hMapFile := CreateFileMapping(hFile, nil, PAGE_READWRITE, 0, 1024 * 2048, nil); if (hMapFile = 0) then raise EFileMappingError.CreateFmt('Could not create file-mapping object. %d', [GetLastError]); FPtr := MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (FPtr = nil) then raise EFileMappingError.Create('Could not map view of file.') else if newfile then FillChar(fPtr^, 1024 * 2048, 0); except on EFileMappingError do begin Finalize; raise; end else raise; end; end; destructor TFileMapping.Destroy; begin inherited; Finalize; end; procedure TFileMapping.Finalize; begin if Assigned(FPtr) then UnMapViewOfFile(FPtr); if hMapFile <> 0 then CloseHandle(hMapFile); if hFile <> 0 then CloseHandle(hFile); end; //****************************************************************************** //============================================================================== // TProcessWindows //============================================================================== //****************************************************************************** function ProcessWindowsEnumProc(hwnd: THandle; lParam: LPARAM): bool; stdcall; var fProc: THandle; begin Result := true; with TProcessWindows(lParam) do begin GetWindowThreadProcessId(hwnd, @fProc); if hForProc = fProc then fResultList.AddObject(GetWindowCaption(hwnd), TObject(hwnd)); end; end; procedure TProcessWindows.Clear; begin hForProc := 0; fResultList.Clear; end; constructor TProcessWindows.Create; begin fResultList := nil; fResultList := TStringList.Create; end; destructor TProcessWindows.Destroy; begin if Assigned(fResultList) then fResultList.Free; inherited; end; function TProcessWindows.DetectNow(forProc: THandle): TStringList; begin Clear; Result := fResultList; hForProc := forProc; Result.BeginUpdate; try EnumWindows(@ProcessWindowsEnumProc, Integer(Self)); finally Result.EndUpdate; end; end; //============================================================================== procedure SetWindowTransp(hndl: THandle; Perc: byte); var mh: THandle; SetLayeredWindowAttributes: TSetLayeredWindowAttributes; par: Integer; begin if Perc <= 100 then begin mh := GetModuleHandle('user32.dll'); @SetLayeredWindowAttributes := GetProcAddress(mh, 'SetLayeredWindowAttributes'); if @SetLayeredWindowAttributes <> nil then begin par := GetWindowLong(hndl, GWL_EXSTYLE); if perc = 100 then par := par and (not WS_EX_LAYERED) else par := par or WS_EX_LAYERED; SetWindowLong(hndl, GWL_EXSTYLE, par); if par <> 100 then SetLayeredWindowAttributes(hndl, 0, Round(Perc / 100 * 255), LWA_ALPHA); end; end; end; function GetSystemDir: string; begin SetLength(Result, 1024); SetLength(Result, GetSystemDirectory(PChar(Result), Length(Result))); end; procedure RegisterDLL(fn: string; Reg: boolean = true); type TRegProc = function: HResult; stdcall; var LibHandle: THandle; ProcName: string; RegProc: TRegProc; begin if Reg then ProcName := 'DllRegisterServer' else ProcName := 'DllUnregisterServer'; LibHandle := LoadLibrary(PChar(FN)); if LibHandle = 0 then raise Exception.CreateFmt('Failed to load "%s"', [FN]); try @RegProc := GetProcAddress(LibHandle, PChar(ProcName)); if @RegProc = nil then raise Exception.CreateFmt('%s procedure not found in "%s"', [ProcName, FN]); if RegProc <> 0 then raise Exception.CreateFmt('Call to %s failed in "%s"', [ProcName, FN]); finally FreeLibrary(LibHandle); end; end; function ConsoleProcessMessage(var Msg: TMsg): Boolean; begin Result := False; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := True; if Msg.Message = WM_QUIT then TerminateApp := True; DispatchMessage(Msg); end; end; procedure ConsoleProcessMessages; var Msg: TMsg; begin while ConsoleProcessMessage(Msg) do {loop} ; end; function GetBuildTime: TDateTime; type UShort = Word; TImageDosHeader = packed record e_magic: UShort; // магическое число e_cblp: UShort; // количество байт на последней странице файла e_cp: UShort; // количество страниц вфайле e_crlc: UShort; // Relocations e_cparhdr: UShort; // размер заголовка в параграфах e_minalloc: UShort; // Minimum extra paragraphsneeded e_maxalloc: UShort; // Maximum extra paragraphsneeded e_ss: UShort; // начальное( относительное ) значение регистра SS e_sp: UShort; // начальное значениерегистра SP e_csum: UShort; // контрольная сумма e_ip: UShort; // начальное значение регистра IP e_cs: UShort; // начальное( относительное ) значение регистра CS e_lfarlc: UShort; // адрес в файле на таблицу переадресации e_ovno: UShort; // количество оверлеев e_res: array[0..3] of UShort; // Зарезервировано e_oemid: UShort; // OEM identifier (for e_oeminfo) e_oeminfo: UShort; // OEM information; e_oemid specific e_res2: array[0..9] of UShort; // Зарезервировано e_lfanew: LongInt; // адрес в файле нового .exeзаголовка end; TImageResourceDirectory = packed record Characteristics: DWord; TimeDateStamp: DWord; MajorVersion: Word; MinorVersion: Word; NumberOfNamedEntries: Word; NumberOfIdEntries: Word; // IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]; end; PImageResourceDirectory = ^TImageResourceDirectory; var hExeFile: HFile; ImageDosHeader: TImageDosHeader; Signature: Cardinal; ImageFileHeader: TImageFileHeader; ImageOptionalHeader: TImageOptionalHeader; ImageSectionHeader: TImageSectionHeader; ImageResourceDirectory: TImageResourceDirectory; Temp: Cardinal; i: Integer; begin hExeFile := CreateFile(PChar(ParamStr(0)), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); try ReadFile(hExeFile, ImageDosHeader, SizeOf(ImageDosHeader), Temp, nil); SetFilePointer(hExeFile, ImageDosHeader.e_lfanew, nil, FILE_BEGIN); ReadFile(hExeFile, Signature, SizeOf(Signature), Temp, nil); ReadFile(hExeFile, ImageFileHeader, SizeOf(ImageFileHeader), Temp, nil); ReadFile(hExeFile, ImageOptionalHeader, SizeOf(ImageOptionalHeader), Temp, nil); for i := 0 to ImageFileHeader.NumberOfSections - 1 do begin ReadFile(hExeFile, ImageSectionHeader, SizeOf(ImageSectionHeader), Temp, nil); if StrComp(@ImageSectionHeader.Name, '.rsrc') = 0 then Break; end; SetFilePointer(hExeFile, ImageSectionHeader.PointerToRawData, nil, FILE_BEGIN); ReadFile(hExeFile, ImageResourceDirectory, SizeOf(ImageResourceDirectory), Temp, nil); finally FileClose(hExeFile); end; Result := FileDateToDateTime(ImageResourceDirectory.TimeDateStamp); end; procedure EnableAnimation(anim: Boolean; msg: Integer = SPI_SETANIMATION); var an: TAnimationInfo; begin an.cbSize := SizeOf(TAnimationInfo); an.iMinAnimate := iifs(anim, 1, 0); SystemParametersInfo(msg, SizeOf(an), @an, 0); end; function GetAnimationState(msg: Integer = SPI_GETANIMATION): Boolean; var an: TAnimationInfo; begin an.cbSize := SizeOf(TAnimationInfo); if SystemParametersInfo(msg, SizeOf(an), @an, 0) then Result := an.iMinAnimate <> 0 else Result := False; end; procedure RestoreAnimation; begin EnableAnimation(AnimationOn, SPI_SETANIMATION); EnableAnimation(MenuAnimationOn, SPI_SETMENUANIMATION); EnableAnimation(ComboboxAnimationOn, SPI_SETCOMBOBOXANIMATION); end; procedure StoreAnimation; begin AnimationOn := GetAnimationState(SPI_GETANIMATION); MenuAnimationOn := GetAnimationState(SPI_GETMENUANIMATION); ComboboxAnimationOn := GetAnimationState(SPI_GETCOMBOBOXANIMATION); end; function GetMDIFormHandle_EnumWnd(hwnd: HWND; lParam: LPARAM): bool; stdcall; var cpm: Integer; WinFound: PInteger; begin WinFound := Pointer(lParam); Result := WinFound^ = 0; if WinFound^ = 0 then begin cpm := SendMessage(hwnd, WM_MDIGETACTIVE, 0, 0); if cpm <> 0 then begin WinFound^ := hwnd; Result := false; end { else EnumChildWindows(hwnd, @GetMDIFormHandle_EnumWnd, lParam)}; end; end; function GetMDIFormHandle(hwnd: THandle): THandle; const Prev: THandle = 0; PrevRes: THandle = 0; PrevCap: string = ''; var cap: string; begin cap := GetWindowCaption(hwnd); if Prev = hwnd then begin if (PrevCap = cap) then begin Result := PrevRes; exit; end; end; Result := 0; EnumChildWindows(hwnd, @GetMDIFormHandle_EnumWnd, Integer(@Result)); Prev := hwnd; PrevCap := cap; PrevRes := Result; end; function GetActiveMDIChildHandle(client: THandle): THandle; begin if Client <> 0 then Result := SendMessage(client, WM_MDIGETACTIVE, 0, 0) else Result := 0; end; function GetActiveWindowEx(OnlyMDI: Boolean): THandle; var fhrg: THandle; begin fhrg := GetForegroundWindow; if fhrg = 0 then Result := 0 else begin Result := GetActiveMDIChildHandle(GetMDIFormHandle(fhrg)); if (not OnlyMDI) and (Result = 0) then Result := GetForegroundWindow; end; end; procedure TryOpenUrl(url: string; showerr: Boolean); var urlow, path: string; isurl: Boolean; ismail: Boolean; res: Integer; { Info: TShellExecuteInfo; ExitCode: DWORD;} begin urlow := LowerCase(url); isurl := pos('://', urlow) <= 6; ismail := pos('mailto:', urlow) = 1; if isurl or ismail then path := url else path := '"' + ExtractShortPathName(url) + '"'; res := ShellExecute(0, 'open', PChar(path), nil, nil, SW_NORMAL); if (res < 32) and (ShowErr) then MessageBox(0, PChar(Format(exUnableOpen, [path])), 'Error', MB_OK or MB_ICONERROR); end; procedure OpenFileIn(prog: string; fn: string); var fle: string; begin fle := '"' + ExtractShortPathName(fn) + '"'; if ShellExecute(0, 'open', PChar(prog), PChar(fle), PChar(ExtractFilePath(fn)), SW_SHOW) < 32 then MessageBox(0, PChar(Format(exUnableOpen, [prog])), 'Error', MB_OK or MB_ICONERROR); end; procedure ExecuteApp(prog: string; param: string); begin if ShellExecute(0, 'open', PChar(prog), PChar(param), nil, SW_SHOW) < 32 then MessageBox(0, PChar(Format(exUnableOpen, [prog])), 'Error', MB_OK or MB_ICONERROR); end; function SetForegroundWindowSp(hWnd: THandle): Boolean; type TSendInput = function(cInputs: UINT; var pInputs: TInput; cbSize: Integer): UINT; stdcall; var hUser32: THandle; pSendInput: TSendInput; Input: TInput; begin FillChar(Input, SizeOf(Input), 0); Input.Itype := INPUT_MOUSE; Result := False; if (not IsWindow(hWnd)) then exit; SetForegroundWindow(hWnd); if (hWnd = GetForegroundWindow) then begin Result := True; exit; end; hUser32 := LoadLibraryEx(PChar('User32.dll'), 0, DONT_RESOLVE_DLL_REFERENCES); if (hUser32 = 0) then exit; try pSendInput := GetProcAddress(hUser32, PChar('SendInput')); if Assigned(pSendInput) then pSendInput(1, Input, sizeof(Input)); finally FreeLibrary(hUser32); end; Result := SetForegroundWindow(hWnd); if (IsIconic(hWnd)) then OpenIcon(hWnd); end; function LoadImageXP(hInst: LongWord; resname: string; sizeX, sizeY: Integer): HIcon; var h: HDC; begin Result := 0; h := GetDC(0); try if (Win32Platform = VER_PLATFORM_WIN32_NT) and (win32MajorVersion >= 5) and (Win32MinorVersion >= 1) and (GetDeviceCaps(h, BITSPIXEL) >= 16) then Result := LoadImage(hInst, PChar(resname + 'XP'), IMAGE_ICON, sizeX, sizeY, 0); finally ReleaseDC(0, h); end; if Result = 0 then Result := LoadImage(hInst, PChar(resname), IMAGE_ICON, sizeX, sizeY, 0); end; function DrawIconXP(posx, posy: Integer; resname: string; where: TCanvas; sizeX, sizeY: Integer): Boolean; var icn: TIcon; begin Result := False; icn := TIcon.Create; try icn.Handle := LoadImageXP(hInstance, resname, sizeX, sizeY); if icn.Handle = 0 then exit; where.Draw(posx, posy, icn); finally icn.Free; end; Result := True; end; function WinExecAndWait32V2(FileName: string; Visibility: integer): DWORD; procedure WaitFor(processHandle: THandle); var msg: TMsg; ret: DWORD; begin repeat ret := MsgWaitForMultipleObjects( 1, { 1 handle to wait on } processHandle, { the handle } False, { wake on any event } INFINITE, { wait without timeout } QS_PAINT or { wake on paint messages } QS_SENDMESSAGE { or messages from other threads } ); if ret = WAIT_FAILED then Exit; { can do little here } if ret = (WAIT_OBJECT_0 + 1) then begin { Woke on a message, process paint messages only. Calling PeekMessage gets messages send from other threads processed. } while PeekMessage(msg, 0, WM_PAINT, WM_PAINT, PM_REMOVE) do DispatchMessage(msg); end; until ret = WAIT_OBJECT_0; end; { Waitfor } var { V1 by Pat Ritchey, V2 by P.Below } zAppName: array[0..512] of char; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin { WinExecAndWait32V2 } StrPCopy(zAppName, FileName); FillChar(StartupInfo, Sizeof(StartupInfo), #0); StartupInfo.cb := Sizeof(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; if not CreateProcess(nil, zAppName, { pointer to command line string } nil, { pointer to process security attributes } nil, { pointer to thread security attributes } false, { handle inheritance flag } CREATE_NEW_CONSOLE or { creation flags } NORMAL_PRIORITY_CLASS, nil, { pointer to new environment block } nil, { pointer to current directory name } StartupInfo, { pointer to STARTUPINFO } ProcessInfo) { pointer to PROCESS_INF } then Result := DWORD(-1) { failed, GetLastError has error code } else begin Waitfor(ProcessInfo.hProcess); GetExitCodeProcess(ProcessInfo.hProcess, Result); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; { Else } end; { WinExecAndWait32V2 } function notBool(bool: Boolean): Boolean; begin if bool then Result := true else Result := false; end; function DriveState(driveletter: Char): TDriveState; var mask: string[6]; sRec: TSearchRec; oldMode: Cardinal; retcode: Integer; begin oldMode := SetErrorMode(SEM_FAILCRITICALERRORS); mask := '?:\*.*'; mask[1] := driveletter; retcode := FindFirst(mask, faAnyfile, SRec); if retcode = 0 then FindClose(SRec); case Abs(retcode) of 0: Result := DS_DISK_WITH_FILES; { found at least one file } 18, 2: Result := DS_EMPTY_DISK; { found no files but otherwise ok } 21, 3: Result := DS_NO_DISK; { DOS ERROR_NOT_READY on WinNT,} { ERROR_PATH_NOT_FOUND on Win 3.1 } else Result := DS_UNFORMATTED_DISK; end; SetErrorMode(oldMode); end; { DriveState } procedure ListLocalDrives(Strings: TStringList); const BufSize = 256; var Buffer: PChar; P: PChar; lt: string; begin GetMem(Buffer, BufSize); try Strings.BeginUpdate; try Strings.Clear; if GetLogicalDriveStrings(BufSize, Buffer) <> 0 then begin P := Buffer; while P^ <> #0 do begin lt := copy(p, 1, 1); if Length(lt) > 0 then begin if DriveState(lt[1]) = DS_DISK_WITH_FILES then Strings.Add(P); end; Inc(P, StrLen(P) + 1); end; //while end; //if finally Strings.EndUpdate; end; //try 2 finally FreeMem(Buffer, BufSize); end; //try 1 end; //ListDrives procedure ShowBalloonTip(Control: TWinControl; Icon: integer; Title: pchar; Text: PWideChar; BackCL, TextCL: TColor); const hWndTip: THandle = 0; TOOLTIPS_CLASS = 'tooltips_class32'; TTS_ALWAYSTIP = $01; TTS_NOPREFIX = $02; TTS_BALLOON = $40; TTF_SUBCLASS = $0010; TTF_TRANSPARENT = $0100; TTF_CENTERTIP = $0002; TTF_TRACK = $0020; ICC_WIN95_CLASSES = $000000FF; TTM_SETTIPBKCOLOR = $000000FF; TTM_SETTIPTEXTCOLOR = $000000FF; TTM_SETDELAYTIME = WM_USER + 3; TTM_ACTIVATE = WM_USER + 1; TTM_ADDTOOL = WM_USER + 50; TTM_TRACKACTIVATE = WM_USER + 17; TTM_TRACKPOSITION = WM_USER + 18; TTM_SETTITLE = WM_USER + 32; TTM_SETMAXTIPWIDTH = WM_USER + 24; TTDT_AUTOPOP = 2; TTDT_INITIAL = 3; type TOOLINFO = packed record cbSize: Integer; uFlags: Integer; hwnd: THandle; uId: Integer; rect: TRect; hinst: THandle; lpszText: PWideChar; lParam: Integer; end; var ti: TOOLINFO; hWnd: THandle; begin if (hWndTip <> 0) and (not IsWindow(hWndTip)) then exit; hWnd := Control.Handle; hWndTip := CreateWindow(TOOLTIPS_CLASS, nil, WS_POPUP or TTS_NOPREFIX or TTS_BALLOON or TTS_ALWAYSTIP, 0, 0, 0, 0, hWnd, 0, HInstance, nil); if hWndTip <> 0 then begin SetWindowPos(hWndTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE); ti.cbSize := SizeOf(ti); ti.uFlags := TTF_CENTERTIP or TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := hWnd; ti.lpszText := Text; Windows.GetClientRect(hWnd, ti.rect); SendMessage(hWndTip, TTM_SETTIPBKCOLOR, BackCL, 0); SendMessage(hWndTip, TTM_SETTIPTEXTCOLOR, TextCL, 0); SendMessage(hWndTip, TTM_SETMAXTIPWIDTH, 0, 300); SendMessage(hWndTip, TTM_SETTITLE, Icon mod 4, Integer(Title)); SendMessage(hWndTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, 32000); SendMessage(hWndTip, TTM_SETDELAYTIME, TTDT_INITIAL, 0); SendMessage(hWndTip, TTM_ADDTOOL, 1, Integer(@ti)); end; {var ti: TOOLINFO; hWnd: THandle; MyPos: TPoint; begin if hWndTip > 0 then DestroyWindow(hWndTip); if Control = nil then exit; hWnd := Control.Handle; hWndTip := CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, nil, TTS_ALWAYSTIP or TTS_BALLOON, integer(CW_USEDEFAULT), integer(CW_USEDEFAULT), integer(CW_USEDEFAULT), integer(CW_USEDEFAULT), hWnd, 0, hInstance, nil); if hWndTip <> 0 then begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRACK; ti.hwnd := hWnd; ti.lpszText := PWideChar(Text); Windows.GetClientRect(hWnd, ti.rect); SendMessage(hWndTip, TTM_ADDTOOL, 1, Integer(@ti)); SendMessage(hWndTip, TTM_SETTITLE, Icon mod 4, Integer(Title)); GetCaretPos(Mypos); SendMessage(hWndTip, TTM_TRACKPOSITION, 0, MakelParam(Control.ClientOrigin.X + Mypos.X, Control.ClientOrigin.Y + Control.ClientHeight - Mypos.Y)); // SendMessage(hWndTip, TTM_TRACKACTIVATE, 1, Integer(@ti)); end; } end; initialization TerminateApp := False; StoreAnimation; finalization end.
unit uFrmMQTTConfig; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,IniFiles,MQTT,UFrmMQTTClient, Vcl.ComCtrls; type TFrmMQTTConfig = class(TForm) pnl2: TPanel; pnl1: TPanel; BtnCSLJ: TBitBtn; BtnMod: TBitBtn; BtnSave: TBitBtn; BtnCancel: TBitBtn; lbl1: TLabel; EdtServer: TEdit; lbl2: TLabel; EdtClientID: TEdit; lbl3: TLabel; EdtUserName: TEdit; EdtPass: TEdit; lbl5: TLabel; ckReConnect: TCheckBox; lbl4: TLabel; EdtSub: TEdit; ckSub: TCheckBox; lbl6: TLabel; EdtPub: TEdit; cbbSubQos: TComboBox; ckAutoPing: TCheckBox; ckRetain: TCheckBox; ckclearsession: TCheckBox; stat1: TStatusBar; ckMQTT: TCheckBox; procedure BtnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnModClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure BtnCSLJClick(Sender: TObject); procedure ckMQTTClick(Sender: TObject); private procedure ReadConfig; function BSTATUS(ISTATUS: Boolean): boolean; procedure SetMQTTStatus; { Private declarations } public YxSCKTINI:string; procedure OnSocketConnect(Sender: TObject;Connected:Boolean); procedure OnConnAck(Sender: TObject; ReturnCode: integer); procedure OnPubAck(Sender: TObject; MsgId:Word); procedure OnPubRec(Sender: TObject; MsgId:Word); procedure OnPubRel(Sender: TObject; MsgId:Word); procedure OnPubComp(Sender: TObject; MsgId:Word); procedure OnSubAck(Sender: TObject; MessageID: integer; GrantedQoS: Integer); procedure OnPublish(Sender: TObject;const msg:TRecvPublishMessage); //Qos:TQosLevel;MsgID:Word;Retain:Boolean;const topic, payload: AnsiString); procedure OnPingResp(Sender: TObject); procedure OnUnSubAck(Sender: TObject; MsgId:Word); procedure OnDisConnect(Sender: TObject); { Public declarations } end; var FrmMQTTConfig: TFrmMQTTConfig; implementation {$R *.dfm} procedure TFrmMQTTConfig.BtnCancelClick(Sender: TObject); begin BSTATUS(false); ReadConfig; end; procedure TFrmMQTTConfig.BtnCSLJClick(Sender: TObject); begin with TFrmMQTTClient.Create(self) do try Position := poScreenCenter; ShowModal; finally Free; end; end; procedure TFrmMQTTConfig.BtnModClick(Sender: TObject); begin BSTATUS(True); end; procedure TFrmMQTTConfig.BtnSaveClick(Sender: TObject); var AINI: TIniFile; begin AINI := TIniFile.Create(YxSCKTINI); try AINI.WriteString('MQTT', 'Server', EdtServer.Text); AINI.WriteString('MQTT', 'ClientID', EdtClientId.Text); AINI.WriteString('MQTT', 'User', EdtUserName.Text); AINI.WriteString('MQTT', 'Pass', EdtPass.Text); AINI.WriteString('MQTT', 'SubTopic', EdtSub.Text); AINI.WriteString('MQTT', 'PubTopic', EdtPub.Text); AINI.WriteBool('MQTT', 'BSub', ckSub.CHECKED); AINI.WriteBool('MQTT', 'Retain', ckRetain.CHECKED); AINI.WriteBool('MQTT', 'ReConnect', ckReConnect.CHECKED); AINI.WriteBool('MQTT', 'ClearSession', ckclearsession.CHECKED); AINI.WriteBool('MQTT', 'AutoPing', ckAutoPing.CHECKED); AINI.WriteInteger('MQTT', 'Qos', cbbSubQos.ItemIndex); AINI.WriteBool('MQTT', 'BMQTT', CKMQTT.CHECKED); finally FreeAndNil(AINI); end; MessageBox(Handle, '配置保存成功!请重启程序生效!', '提示', MB_ICONASTERISK and MB_ICONINFORMATION); ReadConfig; BSTATUS(false); end; procedure TFrmMQTTConfig.FormShow(Sender: TObject); begin BSTATUS(false); ReadConfig; end; function TFrmMQTTConfig.BSTATUS(ISTATUS: Boolean): boolean; begin pnl1.Enabled := ISTATUS; BtnCancel.Enabled := ISTATUS; BtnSave.Enabled := ISTATUS; BtnMod.Enabled := not ISTATUS; Result := True; end; procedure TFrmMQTTConfig.ReadConfig; var Inifile: TIniFile; begin YxSCKTINI := ExtractFileDir(ParamStr(0)) + '\YxDServer.ini'; if FileExists(YxSCKTINI) then begin Inifile := TIniFile.Create(YxSCKTINI); try EdtServer.Text := Inifile.ReadString('MQTT', 'Server', ''); EdtClientId.Text := Inifile.ReadString('MQTT', 'ClientID', ''); EdtUserName.Text := Inifile.ReadString('MQTT', 'User', ''); EdtPass.Text := Inifile.ReadString('MQTT', 'Pass', ''); EdtSub.Text := Inifile.ReadString('MQTT', 'SubTopic', ''); EdtPub.Text := Inifile.ReadString('MQTT', 'PubTopic', ''); ckSub.CHECKED := Inifile.ReadBool('MQTT', 'BSub', False); ckRetain.CHECKED := Inifile.ReadBool('MQTT', 'Retain', False); ckReConnect.CHECKED := Inifile.ReadBool('MQTT', 'ReConnect', False); ckclearsession.CHECKED := Inifile.ReadBool('MQTT', 'ClearSession', False); ckAutoPing.CHECKED := Inifile.ReadBool('MQTT', 'AutoPing', False); cbbSubQos.ItemIndex := Inifile.ReadInteger('MQTT', 'Qos', -1); CKMQTT.CHECKED := Inifile.ReadBool('MQTT', 'BMQTT', false); finally FreeAndNil(Inifile); end; end; end; procedure TFrmMQTTConfig.ckMQTTClick(Sender: TObject); var AINI: TIniFile; begin AINI := TIniFile.Create(YxSCKTINI); try AINI.WriteBool('MQTT', 'BMQTT', CKMQTT.CHECKED); finally FreeAndNil(AINI); if ckMQTT.Checked then GetMQTT else begin if MQ.Connected then MQ.DisConnect; end; end; end; procedure TFrmMQTTConfig.OnConnAck(Sender: TObject; ReturnCode: integer); function ReturnCodeToStr():string; begin case ReturnCode of 0: Result := 'OK'; 1: Result := 'ConnectAckState'; 2: Result := 'InvalidClientID'; 3: Result := 'Serverunavailable'; 4: Result := 'InvalidUserOrPassWord'; 5: Result := 'NoAuthorizd'; else Result := 'Unknown'; end; end; begin {WriteLog('OnConnAck ReturnCode=' + IntToStr(ReturnCode) + ',Status=' + ReturnCodeToStr()); if ReturnCode = 0 then begin Connect.Enabled := FALSE; end; } end; procedure TFrmMQTTConfig.OnDisConnect(Sender: TObject); var Msg:string; Obj:TMQTTClient; begin Obj := Sender as TMQTTClient; Msg := Format('OnDisConnect...,UserCancel[%s],ErrDesc[%s]',[ BoolToStr(Obj.UserCancelSocket,true), Obj.ErrDesc]); //gConnectError := Obj.ErrDesc <> ''; //WriteLog(Msg); end; procedure TFrmMQTTConfig.OnPingResp(Sender: TObject); begin //WriteLog('OnPingResp'); end; procedure TFrmMQTTConfig.OnPubAck(Sender: TObject; MsgId: Word); begin //WriteLog('OnPubAck MsgId=' + IntToStr(MsgId)); end; procedure TFrmMQTTConfig.OnPubComp(Sender: TObject; MsgId: Word); begin //WriteLog('OnPubComp MsgId=' + IntToStr(MsgId)); end; procedure TFrmMQTTConfig.OnPublish(Sender: TObject; const msg: TRecvPublishMessage); var Text:string; MsgContent:AnsiString; begin {if cb_utf8.Checked then MsgContent := Utf8ToAnsi(msg.MsgContent) else } MsgContent := UTF8Decode(msg.MsgContent); Text := format('OnPublish,Dup=%s,Qos=%d,MsgID[%d],Retain[%s],Topic=%s,payload=%s', [BoolToStr(msg.Dup,TRUE), Integer(msg.Qos), msg.MsgID, BoolToStr(msg.Retain,TRUE), msg.topic, msg.MsgContent]); showmessage(msg.MsgContent); //WriteLog(Text); end; procedure TFrmMQTTConfig.OnPubRec(Sender: TObject; MsgId: Word); begin //WriteLog('OnPubRec MsgId=' + IntToStr(MsgId)); end; procedure TFrmMQTTConfig.OnPubRel(Sender: TObject; MsgId: Word); begin //WriteLog('OnPubRel MsgId=' + IntToStr(MsgId)); end; procedure TFrmMQTTConfig.OnSocketConnect(Sender: TObject; Connected: Boolean); var Msg:string; Obj :TMQTTClient; begin Obj := Sender as TMQTTClient; Msg := Format('OnSocketConnect,Connected[%s],ErrDesc[%s]',[ BoolToStr(Connected,TRUE), Obj.ErrDesc]); // WriteLog(Msg); end; procedure TFrmMQTTConfig.OnSubAck(Sender: TObject; MessageID, GrantedQoS: Integer); var Msg:string; begin Msg := Format('OnSubAck MsgId=%d,GrantedQoS=%d',[MessageID,GrantedQoS]); //WriteLog(Msg); end; procedure TFrmMQTTConfig.OnUnSubAck(Sender: TObject; MsgId: Word); var Msg:string; begin Msg := Format('OnUnSubAck,MsgId=%d',[MsgId]); //WriteLog(Msg); end; procedure TFrmMQTTConfig.SetMQTTStatus; begin MQ.OnFConnAck := OnConnAck; MQ.OnPubAck := OnPubAck; MQ.OnPubRec := OnPubRec; MQ.OnPubRel := OnPubRel; MQ.OnPubComp := OnPubComp; MQ.onSubAck := OnSubAck; MQ.OnUnSubAck := OnUnSubAck; MQ.OnPublish := OnPublish; MQ.OnPingResp := OnPingResp; MQ.OnSocketConnect := OnSocketConnect; MQ.OnDisConnect := OnDisConnect; end; end.
unit ScriptClasses_R; { Inno Setup Copyright (C) 1997-2008 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Script support classes (run time) $Id: ScriptClasses_R.pas,v 1.61 2012/02/05 18:59:23 mlaan Exp $ } interface {$I VERSION.INC} uses uPSRuntime; function ScriptClassesLibraryRegister_R(ScriptInterpreter: TPSExec): TPSRuntimeClassImporter; implementation uses Windows, Controls, Forms, StdCtrls, Graphics, uPSR_std, uPSR_classes, uPSR_graphics, uPSR_controls, uPSR_forms, uPSR_stdctrls, uPSR_extctrls, uPSR_comobj, {$IFNDEF UNICODE} uPSUtils, {$ENDIF} NewStaticText, NewCheckListBox, NewProgressBar, RichEditViewer, ExtCtrls, UIStateForm, SetupForm, Main, Wizard, SetupTypes, PasswordEdit, FolderTreeView, BitmapImage, NewNotebook, ScriptDlg, BidiCtrls, UninstProgressForm; type TWinControlAccess = class(TWinControl); procedure TWinControlParentBackground_R(Self: TWinControl; var T: Boolean); begin {$IFDEF IS_D7} T := TWinControlAccess(Self).ParentBackground {$ELSE} T := False {$ENDIF}; end; procedure TWinControlParentBackground_W(Self: TWinControl; const T: Boolean); begin {$IFDEF IS_D7} TWinControlAccess(Self).ParentBackground := T; {$ENDIF} end; procedure RegisterWinControl_R(Cl: TPSRuntimeClassImporter); begin RIRegisterTWinControl(Cl); {$IFNDEF UNICODE} with Cl.FindClass(FastUppercase(TWinControl.ClassName)) do {$ELSE} with Cl.FindClass(AnsiString(TWinControl.ClassName)) do {$ENDIF} begin RegisterPropertyHelper(@TWinControlParentBackground_R, @TWinControlParentBackground_W, 'ParentBackground'); end; end; procedure RegisterNewStaticText_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TNewStaticText) do begin RegisterMethod(@TNewStaticText.AdjustHeight, 'AdjustHeight'); end; end; procedure TNewCheckListBoxChecked_R(Self: TNewCheckListBox; var T: Boolean; t1: Integer); begin T := Self.Checked[t1]; end; procedure TNewCheckListBoxChecked_W(Self: TNewCheckListBox; const T: Boolean; t1: Integer); begin Self.Checked[t1] := T; end; procedure TNewCheckListBoxState_R(Self: TNewCheckListBox; var T: TCheckBoxState; t1: Integer); begin T := Self.State[t1]; end; procedure TNewCheckListBoxItemCaption_R(Self: TNewCheckListBox; var T: String; t1: Integer); begin T := Self.ItemCaption[t1]; end; procedure TNewCheckListBoxItemCaption_W(Self: TNewCheckListBox; const T: String; t1: Integer); begin Self.ItemCaption[t1] := T; end; procedure TNewCheckListBoxItemEnabled_R(Self: TNewCheckListBox; var T: Boolean; t1: Integer); begin T := Self.ItemEnabled[t1]; end; procedure TNewCheckListBoxItemEnabled_W(Self: TNewCheckListBox; const T: Boolean; t1: Integer); begin Self.ItemEnabled[t1] := T; end; procedure TNewCheckListBoxItemLevel_R(Self: TNewCheckListBox; var T: Byte; t1: Integer); begin T := Self.ItemLevel[t1]; end; procedure TNewCheckListBoxItemObject_R(Self: TNewCheckListBox; var T: TObject; t1: Integer); begin T := Self.ItemObject[t1]; end; procedure TNewCheckListBoxItemObject_W(Self: TNewCheckListBox; const T: TObject; t1: Integer); begin Self.ItemObject[t1] := T; end; procedure TNewCheckListBoxItemSubItem_R(Self: TNewCheckListBox; var T: String; t1: Integer); begin T := Self.ItemSubItem[t1]; end; procedure TNewCheckListBoxItemSubItem_W(Self: TNewCheckListBox; const T: String; t1: Integer); begin Self.ItemSubItem[t1] := T; end; procedure RegisterNewCheckListBox_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TNewCheckListBox) do begin RegisterMethod(@TNewCheckListBox.AddCheckBox, 'AddCheckBox'); RegisterMethod(@TNewCheckListBox.AddGroup, 'AddGroup'); RegisterMethod(@TNewCheckListBox.AddRadioButton, 'AddRadioButton'); RegisterMethod(@TNewCheckListBox.CheckItem, 'CheckItem'); RegisterPropertyHelper(@TNewCheckListBoxChecked_R, @TNewCheckListBoxChecked_W, 'Checked'); RegisterPropertyHelper(@TNewCheckListBoxState_R, nil, 'State'); RegisterPropertyHelper(@TNewCheckListBoxItemCaption_R, @TNewCheckListBoxItemCaption_W, 'ItemCaption'); RegisterPropertyHelper(@TNewCheckListBoxItemEnabled_R, @TNewCheckListBoxItemEnabled_W, 'ItemEnabled'); RegisterPropertyHelper(@TNewCheckListBoxItemLevel_R, nil, 'ItemLevel'); RegisterPropertyHelper(@TNewCheckListBoxItemObject_R, @TNewCheckListBoxItemObject_W, 'ItemObject'); RegisterPropertyHelper(@TNewCheckListBoxItemSubItem_R, @TNewCheckListBoxItemSubItem_W, 'ItemSubItem'); end; end; procedure RegisterNewProgressBar_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TNewProgressBar); end; procedure TRichEditViewerRTFText_W(Self: TRichEditViewer; const T: AnsiString); begin Self.RTFText := T; end; procedure RegisterRichEditViewer_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TRichEditViewer) do begin RegisterPropertyHelper(nil, @TRichEditViewerRTFText_W, 'RTFText'); end; end; procedure RegisterPasswordEdit_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TPasswordEdit); end; procedure TCustomFolderTreeViewDirectory_W(Self: TCustomFolderTreeView; const T: String); begin Self.Directory := T; end; procedure TCustomFolderTreeViewDirectory_R(Self: TCustomFolderTreeView; var T: String); begin T := Self.Directory; end; procedure RegisterCustomFolderTreeView_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TCustomFolderTreeView) do begin RegisterMethod(@TCustomFolderTreeView.ChangeDirectory, 'ChangeDirectory'); RegisterMethod(@TCustomFolderTreeView.CreateNewDirectory, 'CreateNewDirectory'); RegisterPropertyHelper(@TCustomFolderTreeViewDirectory_R,@TCustomFolderTreeViewDirectory_W,'Directory'); end; end; procedure RegisterStartMenuFolderTreeView_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TStartMenuFolderTreeView) do begin RegisterMethod(@TStartMenuFolderTreeView.SetPaths, 'SetPaths'); end; end; procedure RegisterFolderTreeView_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TFolderTreeView); end; procedure RegisterBitmapImage_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TBitmapImage); end; procedure RegisterBidiCtrls_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TNewEdit); Cl.Add(TNewMemo); Cl.Add(TNewComboBox); Cl.Add(TNewListBox); Cl.Add(TNewButton); Cl.Add(TNewCheckBox); Cl.Add(TNewRadioButton); end; procedure TNewNotebookPages_R(Self: TNewNotebook; var T: TNewNotebookPage; const t1: Integer); begin T := Self.Pages[t1]; end; procedure TNewNotebookPageCount_R(Self: TNewNotebook; var T: Integer); begin T := Self.PageCount; end; procedure RegisterNewNotebook_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TNewNotebook) do begin RegisterMethod(@TNewNotebook.FindNextPage, 'FindNextPage'); RegisterPropertyHelper(@TNewNotebookPageCount_R,nil,'PageCount'); RegisterPropertyHelper(@TNewNotebookPages_R,nil,'Pages'); end; end; procedure TNewNotebookPageNotebook_W(Self: TNewNotebookPage; const T: TNewNotebook); begin Self.Notebook := T; end; procedure TNewNotebookPageNotebook_R(Self: TNewNotebookPage; var T: TNewNotebook); begin T := Self.Notebook; end; procedure RegisterNewNotebookPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TNewNotebookPage) do begin RegisterPropertyHelper(@TNewNotebookPageNotebook_R,@TNewNotebookPageNotebook_W,'Notebook'); end; end; procedure RegisterUIStateForm_R(Cl: TPSRuntimeClassImporter); begin Cl.Add(TUIStateForm); end; procedure TSetupFormControlsFlipped_R(Self: TSetupForm; var T: Boolean); begin T := Self.ControlsFlipped; end; procedure TSetupFormFlipControlsOnShow_W(Self: TSetupForm; const T: Boolean); begin Self.FlipControlsOnShow := T; end; procedure TSetupFormFlipControlsOnShow_R(Self: TSetupForm; var T: Boolean); begin T := Self.FlipControlsOnShow; end; procedure TSetupFormRightToLeft_R(Self: TSetupForm; var T: Boolean); begin T := Self.RightToLeft; end; procedure RegisterSetupForm_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TSetupForm) do begin RegisterMethod(@TSetupForm.Center, 'Center'); RegisterMethod(@TSetupForm.CenterInsideControl, 'CenterInsideControl'); RegisterPropertyHelper(@TSetupFormControlsFlipped_R, nil, 'ControlsFlipped'); RegisterPropertyHelper(@TSetupFormFlipControlsOnShow_R, @TSetupFormFlipControlsOnShow_W, 'FlipControlsOnShow'); RegisterPropertyHelper(@TSetupFormRightToLeft_R, nil, 'RightToLeft'); end; end; procedure RegisterMainForm_R(Cl: TPSRuntimeClassImporter); begin with CL.Add(TMainForm) do begin RegisterMethod(@TMainForm.ShowAboutBox, 'ShowAboutBox'); end; end; procedure TWizardFormCancelButton_R(Self: TWizardForm; var T: TNewButton); begin T := Self.CancelButton; end; procedure TWizardFormNextButton_R(Self: TWizardForm; var T: TNewButton); begin T := Self.NextButton; end; procedure TWizardFormBackButton_R(Self: TWizardForm; var T: TNewButton); begin T := Self.BackButton; end; procedure TWizardFormOuterNotebook_R(Self: TWizardForm; var T: TNewNotebook); begin T := Self.OuterNotebook; end; procedure TWizardFormInnerNotebook_R(Self: TWizardForm; var T: TNewNotebook); begin T := Self.InnerNotebook; end; procedure TWizardFormInfoAfterPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.InfoAfterPage; end; procedure TWizardFormInstallingPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.InstallingPage; end; procedure TWizardFormPreparingPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.PreparingPage; end; procedure TWizardFormReadyPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.ReadyPage; end; procedure TWizardFormSelectTasksPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.SelectTasksPage; end; procedure TWizardFormSelectProgramGroupPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.SelectProgramGroupPage; end; procedure TWizardFormSelectComponentsPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.SelectComponentsPage; end; procedure TWizardFormSelectDirPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.SelectDirPage; end; procedure TWizardFormUserInfoPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.UserInfoPage; end; procedure TWizardFormInfoBeforePage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.InfoBeforePage; end; procedure TWizardFormPasswordPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.PasswordPage; end; procedure TWizardFormLicensePage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.LicensePage; end; procedure TWizardFormFinishedPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.FinishedPage; end; procedure TWizardFormInnerPage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.InnerPage; end; procedure TWizardFormWelcomePage_R(Self: TWizardForm; var T: TNewNotebookPage); begin T := Self.WelcomePage; end; procedure TWizardFormDiskSpaceLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.DiskSpaceLabel; end; procedure TWizardFormDirEdit_R(Self: TWizardForm; var T: TEdit); begin T := Self.DirEdit; end; procedure TWizardFormGroupEdit_R(Self: TWizardForm; var T: TNewEdit); begin T := Self.GroupEdit; end; procedure TWizardFormNoIconsCheck_R(Self: TWizardForm; var T: TNewCheckBox); begin T := Self.NoIconsCheck; end; procedure TWizardFormPasswordLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.PasswordLabel; end; procedure TWizardFormPasswordEdit_R(Self: TWizardForm; var T: TPASSWORDEDIT); begin T := Self.PasswordEdit; end; procedure TWizardFormPasswordEditLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.PasswordEditLabel; end; procedure TWizardFormReadyMemo_R(Self: TWizardForm; var T: TNewMemo); begin T := Self.ReadyMemo; end; procedure TWizardFormTypesCombo_R(Self: TWizardForm; var T: TNewComboBox); begin T := Self.TypesCombo; end; procedure TWizardFormBevel_R(Self: TWizardForm; var T: TBevel); begin T := Self.Bevel; end; procedure TWizardFormWizardBitmapImage_R(Self: TWizardForm; var T: TBitmapImage); begin T := Self.WizardBitmapImage; end; procedure TWizardFormWelcomeLabel1_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.WelcomeLabel1; end; procedure TWizardFormInfoBeforeMemo_R(Self: TWizardForm; var T: TRichEditViewer); begin T := Self.InfoBeforeMemo; end; procedure TWizardFormInfoBeforeClickLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.InfoBeforeClickLabel; end; procedure TWizardFormMainPanel_R(Self: TWizardForm; var T: TPanel); begin T := Self.MainPanel; end; procedure TWizardFormBevel1_R(Self: TWizardForm; var T: TBevel); begin T := Self.Bevel1; end; procedure TWizardFormPageNameLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.PageNameLabel; end; procedure TWizardFormPageDescriptionLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.PageDescriptionLabel; end; procedure TWizardFormWizardSmallBitmapImage_R(Self: TWizardForm; var T: TBitmapImage); begin T := Self.WizardSmallBitmapImage; end; procedure TWizardFormReadyLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.ReadyLabel; end; procedure TWizardFormFinishedLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.FinishedLabel; end; procedure TWizardFormYesRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.YesRadio; end; procedure TWizardFormNoRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.NoRadio; end; procedure TWizardFormWizardBitmapImage2_R(Self: TWizardForm; var T: TBitmapImage); begin T := Self.WizardBitmapImage2; end; procedure TWizardFormWelcomeLabel2_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.WelcomeLabel2; end; procedure TWizardFormLicenseLabel1_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.LicenseLabel1; end; procedure TWizardFormLicenseMemo_R(Self: TWizardForm; var T: TRichEditViewer); begin T := Self.LicenseMemo; end; procedure TWizardFormInfoAfterMemo_R(Self: TWizardForm; var T: TRichEditViewer); begin T := Self.InfoAfterMemo; end; procedure TWizardFormInfoAfterClickLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.InfoAfterClickLabel; end; procedure TWizardFormComponentsList_R(Self: TWizardForm; var T: TNewCheckListBox); begin T := Self.ComponentsList; end; procedure TWizardFormComponentsDiskSpaceLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.ComponentsDiskSpaceLabel; end; procedure TWizardFormBeveledLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.BeveledLabel; end; procedure TWizardFormStatusLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.StatusLabel; end; procedure TWizardFormFilenameLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.FilenameLabel; end; procedure TWizardFormProgressGauge_R(Self: TWizardForm; var T: TNewProgressBar); begin T := Self.ProgressGauge; end; procedure TWizardFormSelectDirLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectDirLabel; end; procedure TWizardFormSelectStartMenuFolderLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectStartMenuFolderLabel; end; procedure TWizardFormSelectComponentsLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectComponentsLabel; end; procedure TWizardFormSelectTasksLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectTasksLabel; end; procedure TWizardFormLicenseAcceptedRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.LicenseAcceptedRadio; end; procedure TWizardFormLicenseNotAcceptedRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.LicenseNotAcceptedRadio; end; procedure TWizardFormUserInfoNameLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.UserInfoNameLabel; end; procedure TWizardFormUserInfoNameEdit_R(Self: TWizardForm; var T: TNewEdit); begin T := Self.UserInfoNameEdit; end; procedure TWizardFormUserInfoOrgLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.UserInfoOrgLabel; end; procedure TWizardFormUserInfoOrgEdit_R(Self: TWizardForm; var T: TNewEdit); begin T := Self.UserInfoOrgEdit; end; procedure TWizardFormPreparingErrorBitmapImage_R(Self: TWizardForm; var T: TBitmapImage); begin T := Self.PreparingErrorBitmapImage; end; procedure TWizardFormPreparingLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.PreparingLabel; end; procedure TWizardFormFinishedHeadingLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.FinishedHeadingLabel; end; procedure TWizardFormUserInfoSerialLabel_R(Self: TWizardForm; var T: TNewStaticText); begin T := Self.UserInfoSerialLabel; end; procedure TWizardFormUserInfoSerialEdit_R(Self: TWizardForm; var T: TNewEdit); begin T := Self.UserInfoSerialEdit; end; procedure TWizardFormTasksList_R(Self: TWizardForm; var T: TNewCheckListBox); begin T := Self.TasksList; end; procedure TWizardFormRunList_R(Self: TWizardForm; var T: TNewCheckListBox); begin T := Self.RunList; end; procedure TWizardFormCurPageID_R(Self: TWizardForm; var T: Integer); begin T := Self.CurPageID; end; procedure TWizardFormDirBrowseButton_R(Self: TWizardForm; var T: TNewButton); begin T := Self.DirBrowseButton; end; procedure TWizardFormGroupBrowseButton_R(Self: TWizardForm; var T: TNewButton); begin T := Self.GroupBrowseButton; end; procedure TWizardFormSelectDirBitmapImage(Self: TWizardForm; var T: TBitmapImage); begin T := Self.SelectDirBitmapImage; end; procedure TWizardFormSelectGroupBitmapImage(Self: TWizardForm; var T: TBitmapImage); begin T := Self.SelectGroupBitmapImage; end; procedure TWizardFormSelectDirBrowseLabel(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectDirBrowseLabel; end; procedure TWizardFormSelectStartMenuFolderBrowseLabel(Self: TWizardForm; var T: TNewStaticText); begin T := Self.SelectStartMenuFolderBrowseLabel; end; procedure TWizardFormPreparingYesRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.PreparingYesRadio; end; procedure TWizardFormPreparingNoRadio_R(Self: TWizardForm; var T: TNewRadioButton); begin T := Self.PreparingNoRadio; end; procedure TWizardFormPreparingMemo_R(Self: TWizardForm; var T: TNewMemo); begin T := Self.PreparingMemo; end; procedure TWizardFormPrevAppDir_R(Self: TWizardForm; var T: String); begin T := Self.PrevAppDir; end; procedure RegisterWizardForm_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TWizardForm) do begin RegisterPropertyHelper(@TWizardFormCancelButton_R, nil, 'CancelButton'); RegisterPropertyHelper(@TWizardFormNextButton_R, nil, 'NextButton'); RegisterPropertyHelper(@TWizardFormBackButton_R, nil, 'BackButton'); RegisterPropertyHelper(@TWizardFormOuterNotebook_R, nil, 'OuterNotebook'); RegisterPropertyHelper(@TWizardFormInnerNotebook_R, nil, 'InnerNotebook'); RegisterPropertyHelper(@TWizardFormWelcomePage_R,nil,'WelcomePage'); RegisterPropertyHelper(@TWizardFormInnerPage_R,nil,'InnerPage'); RegisterPropertyHelper(@TWizardFormFinishedPage_R,nil,'FinishedPage'); RegisterPropertyHelper(@TWizardFormLicensePage_R,nil,'LicensePage'); RegisterPropertyHelper(@TWizardFormPasswordPage_R,nil,'PasswordPage'); RegisterPropertyHelper(@TWizardFormInfoBeforePage_R,nil,'InfoBeforePage'); RegisterPropertyHelper(@TWizardFormUserInfoPage_R,nil,'UserInfoPage'); RegisterPropertyHelper(@TWizardFormSelectDirPage_R,nil,'SelectDirPage'); RegisterPropertyHelper(@TWizardFormSelectComponentsPage_R,nil,'SelectComponentsPage'); RegisterPropertyHelper(@TWizardFormSelectProgramGroupPage_R,nil,'SelectProgramGroupPage'); RegisterPropertyHelper(@TWizardFormSelectTasksPage_R,nil,'SelectTasksPage'); RegisterPropertyHelper(@TWizardFormReadyPage_R,nil,'ReadyPage'); RegisterPropertyHelper(@TWizardFormPreparingPage_R,nil,'PreparingPage'); RegisterPropertyHelper(@TWizardFormInstallingPage_R,nil,'InstallingPage'); RegisterPropertyHelper(@TWizardFormInfoAfterPage_R,nil,'InfoAfterPage'); RegisterPropertyHelper(@TWizardFormDiskSpaceLabel_R, nil, 'DiskSpaceLabel'); RegisterPropertyHelper(@TWizardFormDirEdit_R, nil, 'DirEdit'); RegisterPropertyHelper(@TWizardFormGroupEdit_R, nil, 'GroupEdit'); RegisterPropertyHelper(@TWizardFormNoIconsCheck_R, nil, 'NoIconsCheck'); RegisterPropertyHelper(@TWizardFormPasswordLabel_R, nil, 'PasswordLabel'); RegisterPropertyHelper(@TWizardFormPasswordEdit_R, nil, 'PasswordEdit'); RegisterPropertyHelper(@TWizardFormPasswordEditLabel_R, nil, 'PasswordEditLabel'); RegisterPropertyHelper(@TWizardFormReadyMemo_R, nil, 'ReadyMemo'); RegisterPropertyHelper(@TWizardFormTypesCombo_R, nil, 'TypesCombo'); RegisterPropertyHelper(@TWizardFormBevel_R, nil, 'Bevel'); RegisterPropertyHelper(@TWizardFormWizardBitmapImage_R, nil, 'WizardBitmapImage'); RegisterPropertyHelper(@TWizardFormWelcomeLabel1_R, nil, 'WelcomeLabel1'); RegisterPropertyHelper(@TWizardFormInfoBeforeMemo_R, nil, 'InfoBeforeMemo'); RegisterPropertyHelper(@TWizardFormInfoBeforeClickLabel_R, nil, 'InfoBeforeClickLabel'); RegisterPropertyHelper(@TWizardFormMainPanel_R, nil, 'MainPanel'); RegisterPropertyHelper(@TWizardFormBevel1_R, nil, 'Bevel1'); RegisterPropertyHelper(@TWizardFormPageNameLabel_R, nil, 'PageNameLabel'); RegisterPropertyHelper(@TWizardFormPageDescriptionLabel_R, nil, 'PageDescriptionLabel'); RegisterPropertyHelper(@TWizardFormWizardSmallBitmapImage_R, nil, 'WizardSmallBitmapImage'); RegisterPropertyHelper(@TWizardFormReadyLabel_R, nil, 'ReadyLabel'); RegisterPropertyHelper(@TWizardFormFinishedLabel_R, nil, 'FinishedLabel'); RegisterPropertyHelper(@TWizardFormYesRadio_R, nil, 'YesRadio'); RegisterPropertyHelper(@TWizardFormNoRadio_R, nil, 'NoRadio'); RegisterPropertyHelper(@TWizardFormWizardBitmapImage2_R, nil, 'WizardBitmapImage2'); RegisterPropertyHelper(@TWizardFormWelcomeLabel2_R, nil, 'WelcomeLabel2'); RegisterPropertyHelper(@TWizardFormLicenseLabel1_R, nil, 'LicenseLabel1'); RegisterPropertyHelper(@TWizardFormLicenseMemo_R, nil, 'LicenseMemo'); RegisterPropertyHelper(@TWizardFormInfoAfterMemo_R, nil, 'InfoAfterMemo'); RegisterPropertyHelper(@TWizardFormInfoAfterClickLabel_R, nil, 'InfoAfterClickLabel'); RegisterPropertyHelper(@TWizardFormComponentsList_R, nil, 'ComponentsList'); RegisterPropertyHelper(@TWizardFormComponentsDiskSpaceLabel_R, nil, 'ComponentsDiskSpaceLabel'); RegisterPropertyHelper(@TWizardFormBeveledLabel_R, nil, 'BeveledLabel'); RegisterPropertyHelper(@TWizardFormStatusLabel_R, nil, 'StatusLabel'); RegisterPropertyHelper(@TWizardFormFilenameLabel_R, nil, 'FilenameLabel'); RegisterPropertyHelper(@TWizardFormProgressGauge_R, nil, 'ProgressGauge'); RegisterPropertyHelper(@TWizardFormSelectDirLabel_R, nil, 'SelectDirLabel'); RegisterPropertyHelper(@TWizardFormSelectStartMenuFolderLabel_R, nil, 'SelectStartMenuFolderLabel'); RegisterPropertyHelper(@TWizardFormSelectComponentsLabel_R, nil, 'SelectComponentsLabel'); RegisterPropertyHelper(@TWizardFormSelectTasksLabel_R, nil, 'SelectTasksLabel'); RegisterPropertyHelper(@TWizardFormLicenseAcceptedRadio_R, nil, 'LicenseAcceptedRadio'); RegisterPropertyHelper(@TWizardFormLicenseNotAcceptedRadio_R, nil, 'LicenseNotAcceptedRadio'); RegisterPropertyHelper(@TWizardFormUserInfoNameLabel_R, nil, 'UserInfoNameLabel'); RegisterPropertyHelper(@TWizardFormUserInfoNameEdit_R, nil, 'UserInfoNameEdit'); RegisterPropertyHelper(@TWizardFormUserInfoOrgLabel_R, nil, 'UserInfoOrgLabel'); RegisterPropertyHelper(@TWizardFormUserInfoOrgEdit_R, nil, 'UserInfoOrgEdit'); RegisterPropertyHelper(@TWizardFormPreparingErrorBitmapImage_R, nil, 'PreparingErrorBitmapImage'); RegisterPropertyHelper(@TWizardFormPreparingLabel_R, nil, 'PreparingLabel'); RegisterPropertyHelper(@TWizardFormFinishedHeadingLabel_R, nil, 'FinishedHeadingLabel'); RegisterPropertyHelper(@TWizardFormUserInfoSerialLabel_R, nil, 'UserInfoSerialLabel'); RegisterPropertyHelper(@TWizardFormUserInfoSerialEdit_R, nil, 'UserInfoSerialEdit'); RegisterPropertyHelper(@TWizardFormTasksList_R, nil, 'TasksList'); RegisterPropertyHelper(@TWizardFormRunList_R, nil, 'RunList'); RegisterPropertyHelper(@TWizardFormDirBrowseButton_R, nil, 'DirBrowseButton'); RegisterPropertyHelper(@TWizardFormGroupBrowseButton_R, nil, 'GroupBrowseButton'); RegisterPropertyHelper(@TWizardFormSelectDirBitmapImage, nil, 'SelectDirBitmapImage'); RegisterPropertyHelper(@TWizardFormSelectGroupBitmapImage, nil, 'SelectGroupBitmapImage'); RegisterPropertyHelper(@TWizardFormSelectDirBrowseLabel, nil, 'SelectDirBrowseLabel'); RegisterPropertyHelper(@TWizardFormSelectStartMenuFolderBrowseLabel, nil,'SelectStartMenuFolderBrowseLabel'); RegisterPropertyHelper(@TWizardFormPreparingYesRadio_R, nil, 'PreparingYesRadio'); RegisterPropertyHelper(@TWizardFormPreparingNoRadio_R, nil, 'PreparingNoRadio'); RegisterPropertyHelper(@TWizardFormPreparingMemo_R, nil, 'PreparingMemo'); RegisterPropertyHelper(@TWizardFormCurPageID_R, nil, 'CurPageID'); RegisterMethod(@TWizardForm.AdjustLabelHeight, 'AdjustLabelHeight'); RegisterMethod(@TWizardForm.IncTopDecHeight, 'IncTopDecHeight'); RegisterPropertyHelper(@TWizardFormPrevAppDir_R, nil, 'PrevAppDir'); end; end; procedure TUninstallProgressFormOuterNotebook_R(Self: TUninstallProgressForm; var T: TNewNotebook); begin T := Self.OuterNotebook; end; procedure TUninstallProgressFormInnerPage_R(Self: TUninstallProgressForm; var T: TNewNotebookPage); begin T := Self.InnerPage; end; procedure TUninstallProgressFormInnerNotebook_R(Self: TUninstallProgressForm; var T: TNewNotebook); begin T := Self.InnerNotebook; end; procedure TUninstallProgressFormInstallingPage_R(Self: TUninstallProgressForm; var T: TNewNotebookPage); begin T := Self.InstallingPage; end; procedure TUninstallProgressFormMainPanel_R(Self: TUninstallProgressForm; var T: TPanel); begin T := Self.MainPanel; end; procedure TUninstallProgressFormPageNameLabel_R(Self: TUninstallProgressForm; var T: TNewStaticText); begin T := Self.PageNameLabel; end; procedure TUninstallProgressFormPageDescriptionLabel_R(Self: TUninstallProgressForm; var T: TNewStaticText); begin T := Self.PageDescriptionLabel; end; procedure TUninstallProgressFormWizardSmallBitmapImage_R(Self: TUninstallProgressForm; var T: TBitmapImage); begin T := Self.WizardSmallBitmapImage; end; procedure TUninstallProgressFormBevel1_R(Self: TUninstallProgressForm; var T: TBevel); begin T := Self.Bevel1; end; procedure TUninstallProgressFormStatusLabel_R(Self: TUninstallProgressForm; var T: TNewStaticText); begin T := Self.StatusLabel; end; procedure TUninstallProgressFormProgressBar_R(Self: TUninstallProgressForm; var T: TNewProgressBar); begin T := Self.ProgressBar; end; procedure TUninstallProgressFormBeveledLabel_R(Self: TUninstallProgressForm; var T: TNewStaticText); begin T := Self.BeveledLabel; end; procedure TUninstallProgressFormBevel_R(Self: TUninstallProgressForm; var T: TBevel); begin T := Self.Bevel; end; procedure TUninstallProgressFormCancelButton_R(Self: TUninstallProgressForm; var T: TNewButton); begin T := Self.CancelButton; end; procedure RegisterUninstallProgressForm_R(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TUninstallProgressForm) do begin RegisterPropertyHelper(@TUninstallProgressFormOuterNotebook_R, nil, 'OuterNotebook'); RegisterPropertyHelper(@TUninstallProgressFormInnerPage_R, nil, 'InnerPage'); RegisterPropertyHelper(@TUninstallProgressFormInnerNotebook_R, nil, 'InnerNotebook'); RegisterPropertyHelper(@TUninstallProgressFormInstallingPage_R, nil, 'InstallingPage'); RegisterPropertyHelper(@TUninstallProgressFormMainPanel_R, nil, 'MainPanel'); RegisterPropertyHelper(@TUninstallProgressFormPageNameLabel_R, nil, 'PageNameLabel'); RegisterPropertyHelper(@TUninstallProgressFormPageDescriptionLabel_R, nil, 'PageDescriptionLabel'); RegisterPropertyHelper(@TUninstallProgressFormWizardSmallBitmapImage_R, nil, 'WizardSmallBitmapImage'); RegisterPropertyHelper(@TUninstallProgressFormBevel1_R, nil, 'Bevel1'); RegisterPropertyHelper(@TUninstallProgressFormStatusLabel_R, nil, 'StatusLabel'); RegisterPropertyHelper(@TUninstallProgressFormProgressBar_R, nil, 'ProgressBar'); RegisterPropertyHelper(@TUninstallProgressFormBeveledLabel_R, nil, 'BeveledLabel'); RegisterPropertyHelper(@TUninstallProgressFormBevel_R, nil, 'Bevel'); RegisterPropertyHelper(@TUninstallProgressFormCancelButton_R, nil, 'CancelButton'); end; end; procedure TWizardPageID_R(Self: TWizardPage; var T: Integer); begin T := Self.ID; end; procedure TWizardPageCaption_R(Self: TWizardPage; var T: String); begin T := Self.Caption; end; procedure TWizardPageCaption_W(Self: TWizardPage; T: String); begin Self.Caption := T; end; procedure TWizardPageDescription_R(Self: TWizardPage; var T: String); begin T := Self.Description; end; procedure TWizardPageDescription_W(Self: TWizardPage; T: String); begin Self.Description := T; end; procedure TWizardPageSurface_R(Self: TWizardPage; var T: TNewNotebookPage); begin T := Self.Surface; end; procedure TWizardPageSurfaceHeight_R(Self: TWizardPage; var T: Integer); begin T := Self.SurfaceHeight; end; procedure TWizardPageSurfaceWidth_R(Self: TWizardPage; var T: Integer); begin T := Self.SurfaceWidth; end; procedure TWizardPageOnActivate_R(Self: TWizardPage; var T: TWizardPageNotifyEvent); begin T := Self.OnActivate; end; procedure TWizardPageOnActivate_W(Self: TWizardPage; T: TWizardPageNotifyEvent); begin Self.OnActivate := T; end; procedure TWizardPageOnBackButtonClick_R(Self: TWizardPage; var T: TWizardPageButtonEvent); begin T := Self.OnBackButtonClick; end; procedure TWizardPageOnBackButtonClick_W(Self: TWizardPage; T: TWizardPageButtonEvent); begin Self.OnBackButtonClick := T; end; procedure TWizardPageOnCancelButtonClick_R(Self: TWizardPage; var T: TWizardPageCancelEvent); begin T := Self.OnCancelButtonClick; end; procedure TWizardPageOnCancelButtonClick_W(Self: TWizardPage; T: TWizardPageCancelEvent); begin Self.OnCancelButtonClick := T; end; procedure TWizardPageOnNextButtonClick_R(Self: TWizardPage; var T: TWizardPageButtonEvent); begin T := Self.OnNextButtonClick; end; procedure TWizardPageOnNextButtonClick_W(Self: TWizardPage; T: TWizardPageButtonEvent); begin Self.OnNextButtonClick := T; end; procedure TWizardPageOnShouldSkipPage_R(Self: TWizardPage; var T: TWizardPageShouldSkipEvent); begin T := Self.OnShouldSkipPage; end; procedure TWizardPageOnShouldSkipPage_W(Self: TWizardPage; T: TWizardPageShouldSkipEvent); begin Self.OnShouldSkipPage := T; end; procedure RegisterWizardPage_R(Cl: TIFPSRuntimeClassImporter); begin with Cl.Add(TWizardPage) do begin RegisterPropertyHelper(@TWizardPageID_R, nil, 'ID'); RegisterPropertyHelper(@TWizardPageCaption_R, @TWizardPageCaption_W, 'Caption'); RegisterPropertyHelper(@TWizardPageDescription_R, @TWizardPageDescription_W, 'Description'); RegisterPropertyHelper(@TWizardPageSurface_R, nil, 'Surface'); RegisterPropertyHelper(@TWizardPageSurfaceHeight_R, nil, 'SurfaceHeight'); RegisterPropertyHelper(@TWizardPageSurfaceWidth_R, nil, 'SurfaceWidth'); RegisterPropertyHelper(@TWizardPageOnActivate_R, @TWizardPageOnActivate_W, 'OnActivate'); RegisterPropertyHelper(@TWizardPageOnBackButtonClick_R, @TWizardPageOnBackButtonClick_W, 'OnBackButtonClick'); RegisterPropertyHelper(@TWizardPageOnCancelButtonClick_R, @TWizardPageOnCancelButtonClick_W, 'OnCancelButtonClick'); RegisterPropertyHelper(@TWizardPageOnNextButtonClick_R, @TWizardPageOnNextButtonClick_W, 'OnNextButtonClick'); RegisterPropertyHelper(@TWizardPageOnShouldSkipPage_R, @TWizardPageOnShouldSkipPage_W, 'OnShouldSkipPage'); end; end; procedure TInputQueryWizardPageEdits_R(Self: TInputQueryWizardPage; var T: TPasswordEdit; const t1: Integer); begin T := Self.Edits[t1]; end; procedure TInputQueryWizardPagePromptLabels_R(Self: TInputQueryWizardPage; var T: TNewStaticText; const t1: Integer); begin T := Self.PromptLabels[t1]; end; procedure TInputQueryWizardPageValues_R(Self: TInputQueryWizardPage; var T: String; const t1: Integer); begin T := Self.Values[t1]; end; procedure TInputQueryWizardPageSubCaptionLabel_R(Self: TInputQueryWizardPage; var T: TNewStaticText); begin T := Self.SubCaptionLabel; end; procedure TInputQueryWizardPageValues_W(Self: TInputQueryWizardPage; const T: String; const t1: Integer); begin Self.Values[t1] := T; end; procedure RegisterInputQueryWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TInputQueryWizardPage) do begin RegisterMethod(@TInputQueryWizardPage.Add, 'Add'); RegisterPropertyHelper(@TInputQueryWizardPageEdits_R,nil,'Edits'); RegisterPropertyHelper(@TInputQueryWizardPagePromptLabels_R,nil,'PromptLabels'); RegisterPropertyHelper(@TInputQueryWizardPageSubcaptionLabel_R,nil,'SubCaptionLabel'); RegisterPropertyHelper(@TInputQueryWizardPageValues_R,@TInputQueryWizardPageValues_W,'Values'); end; end; procedure TInputOptionWizardPageCheckListBox_R(Self: TInputOptionWizardPage; var T: TNewCheckListBox); begin T := Self.CheckListBox; end; procedure TInputOptionWizardPageSelectedValueIndex_R(Self: TInputOptionWizardPage; var T: Integer); begin T := Self.SelectedValueIndex; end; procedure TInputOptionWizardPageSelectedValueIndex_W(Self: TInputOptionWizardPage; const T: Integer); begin Self.SelectedValueIndex := T; end; procedure TInputOptionWizardPageSubCaptionLabel_R(Self: TInputOptionWizardPage; var T: TNewStaticText); begin T := Self.SubCaptionLabel; end; procedure TInputOptionWizardPageValues_W(Self: TInputOptionWizardPage; const T: Boolean; const t1: Integer); begin Self.Values[t1] := T; end; procedure TInputOptionWizardPageValues_R(Self: TInputOptionWizardPage; var T: Boolean; const t1: Integer); begin T := Self.Values[t1]; end; procedure RegisterInputOptionWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TInputOptionWizardPage) do begin RegisterMethod(@TInputOptionWizardPage.Add, 'Add'); RegisterMethod(@TInputOptionWizardPage.AddEx, 'AddEx'); RegisterPropertyHelper(@TInputOptionWizardPageCheckListBox_R,nil,'CheckListBox'); RegisterPropertyHelper(@TInputOptionWizardPageSelectedValueIndex_R,@TInputOptionWizardPageSelectedValueIndex_W,'SelectedValueIndex'); RegisterPropertyHelper(@TInputOptionWizardPageSubcaptionLabel_R,nil,'SubCaptionLabel'); RegisterPropertyHelper(@TInputOptionWizardPageValues_R,@TInputOptionWizardPageValues_W,'Values'); end; end; procedure TInputDirWizardPageButtons_R(Self: TInputDirWizardPage; var T: TNewButton; const t1: Integer); begin T := Self.Buttons[t1]; end; procedure TInputDirWizardPageEdits_R(Self: TInputDirWizardPage; var T: TEdit; const t1: Integer); begin T := Self.Edits[t1]; end; procedure TInputDirWizardPagePromptLabels_R(Self: TInputDirWizardPage; var T: TNewStaticText; const t1: Integer); begin T := Self.PromptLabels[t1]; end; procedure TInputDirWizardPageSubCaptionLabel_R(Self: TInputDirWizardPage; var T: TNewStaticText); begin T := Self.SubCaptionLabel; end; procedure TInputDirWizardPageValues_W(Self: TInputDirWizardPage; const T: String; const t1: Integer); begin Self.Values[t1] := T; end; procedure TInputDirWizardPageValues_R(Self: TInputDirWizardPage; var T: String; const t1: Integer); begin T := Self.Values[t1]; end; procedure RegisterInputDirWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TInputDirWizardPage) do begin RegisterMethod(@TInputDirWizardPage.Add, 'Add'); RegisterPropertyHelper(@TInputDirWizardPageButtons_R,nil,'Buttons'); RegisterPropertyHelper(@TInputDirWizardPageEdits_R,nil,'Edits'); RegisterPropertyHelper(@TInputDirWizardPagePromptLabels_R,nil,'PromptLabels'); RegisterPropertyHelper(@TInputDirWizardPageSubcaptionLabel_R,nil,'SubCaptionLabel'); RegisterPropertyHelper(@TInputDirWizardPageValues_R,@TInputDirWizardPageValues_W,'Values'); end; end; procedure TInputFileWizardPageButtons_R(Self: TInputFileWizardPage; var T: TNewButton; const t1: Integer); begin T := Self.Buttons[t1]; end; procedure TInputFileWizardPagePromptLabels_R(Self: TInputFileWizardPage; var T: TNewStaticText; const t1: Integer); begin T := Self.PromptLabels[t1]; end; procedure TInputFileWizardPageEdits_R(Self: TInputFileWizardPage; var T: TEdit; const t1: Integer); begin T := Self.Edits[t1]; end; procedure TInputFileWizardPageSubCaptionLabel_R(Self: TInputFileWizardPage; var T: TNewStaticText); begin T := Self.SubCaptionLabel; end; procedure TInputFileWizardPageValues_W(Self: TInputFileWizardPage; const T: String; const t1: Integer); begin Self.Values[t1] := T; end; procedure TInputFileWizardPageValues_R(Self: TInputFileWizardPage; var T: String; const t1: Integer); begin T := Self.Values[t1]; end; procedure TInputFileWizardPageIsSaveButton_W(Self: TInputFileWizardPage; const T: Boolean; const t1: Integer); begin Self.IsSaveButton[t1] := T; end; procedure TInputFileWizardPageIsSaveButton_R(Self: TInputFileWizardPage; var T: Boolean; const t1: Integer); begin T := Self.IsSaveButton[t1]; end; procedure RegisterInputFileWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TInputFileWizardPage) do begin RegisterMethod(@TInputFileWizardPage.Add, 'Add'); RegisterPropertyHelper(@TInputFileWizardPageButtons_R,nil,'Buttons'); RegisterPropertyHelper(@TInputFileWizardPageEdits_R,nil,'Edits'); RegisterPropertyHelper(@TInputFileWizardPagePromptLabels_R,nil,'PromptLabels'); RegisterPropertyHelper(@TInputFileWizardPageSubcaptionLabel_R,nil,'SubCaptionLabel'); RegisterPropertyHelper(@TInputFileWizardPageValues_R,@TInputFileWizardPageValues_W,'Values'); RegisterPropertyHelper(@TInputFileWizardPageIsSaveButton_R,@TInputFileWizardPageIsSaveButton_W,'IsSaveButton'); end; end; procedure TOutputMsgWizardPageMsgLabel_R(Self: TOutputMsgWizardPage; var T: TNewStaticText); begin T := Self.MsgLabel; end; procedure RegisterOutputMsgWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TOutputMsgWizardPage) do begin RegisterPropertyHelper(@TOutputMsgWizardPageMsgLabel_R,nil,'MsgLabel'); end; end; procedure TOutputMsgMemoWizardPageRichEditViewer_R(Self: TOutputMsgMemoWizardPage; var T: TRichEditViewer); begin T := Self.RichEditViewer; end; procedure TOutputMsgMemoWizardPageSubCaptionLabel_R(Self: TOutputMsgMemoWizardPage; var T: TNewStaticText); begin T := Self.SubCaptionLabel; end; procedure RegisterOutputMsgMemoWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TOutputMsgMemoWizardPage) do begin RegisterPropertyHelper(@TOutputMsgMemoWizardPageRichEditViewer_R,nil,'RichEditViewer'); RegisterPropertyHelper(@TOutputMsgMemoWizardPageSubcaptionLabel_R,nil,'SubCaptionLabel'); end; end; procedure TOutputProgressWizardPageMsg1Label_R(Self: TOutputProgressWizardPage; var T: TNewStaticText); begin T := Self.Msg1Label; end; procedure TOutputProgressWizardPageMsg2Label_R(Self: TOutputProgressWizardPage; var T: TNewStaticText); begin T := Self.Msg2Label; end; procedure TOutputProgressWizardPageProgressBar_R(Self: TOutputProgressWizardPage; var T: TNewProgressBar); begin T := Self.ProgressBar; end; procedure RegisterOutputProgressWizardPage_R(CL: TPSRuntimeClassImporter); begin with CL.Add(TOutputProgressWizardPage) do begin RegisterMethod(@TOutputProgressWizardPage.Hide, 'Hide'); RegisterPropertyHelper(@TOutputProgressWizardPageMsg1Label_R,nil,'Msg1Label'); RegisterPropertyHelper(@TOutputProgressWizardPageMsg2Label_R,nil,'Msg2Label'); RegisterPropertyHelper(@TOutputProgressWizardPageProgressBar_R,nil,'ProgressBar'); RegisterMethod(@TOutputProgressWizardPage.SetProgress, 'SetProgress'); RegisterMethod(@TOutputProgressWizardPage.SetText, 'SetText'); RegisterMethod(@TOutputProgressWizardPage.Show, 'Show'); end; end; procedure RegisterHandCursor_R(Cl: TPSRuntimeClassImporter); const IDC_HAND = MakeIntResource(32649); begin Screen.Cursors[crHand] := LoadCursor(0, IDC_HAND); end; function ScriptClassesLibraryRegister_R(ScriptInterpreter: TPSExec): TPSRuntimeClassImporter; var Cl: TPSRuntimeClassImporter; begin Cl := TPSRuntimeClassImporter.Create(); try { Std } RIRegisterTObject(Cl); RIRegisterTPersistent(Cl); RIRegisterTComponent(Cl); { Classes } RIRegisterTStream(Cl); RIRegisterTStrings(Cl, True); RIRegisterTStringList(Cl); RIRegisterTHandleStream(Cl); RIRegisterTFileStream(Cl); { Graphics } RIRegisterTGraphicsObject(Cl); RIRegisterTFont(Cl); RIRegisterTCanvas(Cl); RIRegisterTPen(Cl); RIRegisterTBrush(Cl); RIRegisterTGraphic(Cl); RIRegisterTBitmap(Cl, True); { Controls } RIRegisterTControl(Cl); RegisterWinControl_R(Cl); RIRegisterTGraphicControl(Cl); RIRegisterTCustomControl(Cl); RIRegister_TDragObject(Cl); { Forms } RIRegisterTScrollingWinControl(Cl); RIRegisterTForm(Cl); { StdCtrls } RIRegisterTCustomLabel(Cl); RIRegisterTLabel(Cl); RIRegisterTCustomEdit(Cl); RIRegisterTEdit(Cl); RIRegisterTCustomMemo(Cl); RIRegisterTMemo(Cl); RIRegisterTCustomComboBox(Cl); RIRegisterTComboBox(Cl); RIRegisterTButtonControl(Cl); RIRegisterTButton(Cl); RIRegisterTCustomCheckBox(Cl); RIRegisterTCheckBox(Cl); RIRegisterTRadioButton(Cl); RIRegisterTCustomListBox(Cl); RIRegisterTListBox(Cl); { ExtCtrls } RIRegisterTBevel(Cl); RIRegisterTCustomPanel(Cl); RIRegisterTPanel(Cl); { ComObj } RIRegister_ComObj(ScriptInterpreter); RegisterNewStaticText_R(Cl); RegisterNewCheckListBox_R(Cl); RegisterNewProgressBar_R(Cl); RegisterRichEditViewer_R(Cl); RegisterPasswordEdit_R(Cl); RegisterCustomFolderTreeView_R(Cl); RegisterFolderTreeView_R(Cl); RegisterStartMenuFolderTreeView_R(Cl); RegisterBitmapImage_R(Cl); RegisterBidiCtrls_R(Cl); RegisterNewNotebook_R(Cl); RegisterNewNotebookPage_R(Cl); RegisterUIStateForm_R(Cl); RegisterSetupForm_R(Cl); RegisterMainForm_R(Cl); RegisterWizardForm_R(Cl); RegisterUninstallProgressForm_R(Cl); RegisterWizardPage_R(Cl); RegisterInputQueryWizardPage_R(Cl); RegisterInputOptionWizardPage_R(Cl); RegisterInputDirWizardPage_R(Cl); RegisterInputFileWizardPage_R(Cl); RegisterOutputMsgWizardPage_R(Cl); RegisterOutputMsgMemoWizardPage_R(Cl); RegisterOutputProgressWizardPage_R(Cl); RegisterHandCursor_R(Cl); RegisterClassLibraryRuntime(ScriptInterpreter, Cl); except Cl.Free; raise; end; Result := Cl; end; end.
unit umain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, {$if defined(Darwin) or defined(Linux)} cthreads, {$endif} SynEdit, Utils.Logger, Utils.UDP, blcksock; type { TMainFrm } TMainFrm = class(TForm) Button1: TButton; edIP: TEdit; Memo1: TMemo; Panel1: TPanel; SynEdit1: TSynEdit; ToggleBox1: TToggleBox; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ToggleBox1Change(Sender: TObject); private FLog : ILog; FUDP : TUDP; procedure OnServerReceive(const Data : String; Socket : TUDPBlockSocket); public end; var MainFrm: TMainFrm; implementation {$R *.lfm} uses strutils, uXmlDoc; { TMainFrm } procedure TMainFrm.FormCreate(Sender: TObject); begin FUDP := TUDP.Create(@OnServerReceive); FLog := GetIlog(ChangeFileExt(Application.ExeName, '.log'), True, 10, True); end; procedure TMainFrm.FormDestroy(Sender: TObject); begin FLog := nil; FUDP.Free; end; procedure TMainFrm.ToggleBox1Change(Sender: TObject); begin ToggleBox1.Caption:= ifthen(ToggleBox1.State = cbChecked, 'Stop', 'Start') + ' Server'; if Assigned(FUDP) then if (ToggleBox1.State = cbChecked) and not FUDP.Connected then FUDP.StartServer else FUdp.Disconnect; end; procedure TMainFrm.OnServerReceive(const Data: String; Socket: TUDPBlockSocket); var ln, i : integer; ip : string; Doc : TXmlDoc; begin Doc := TXmlDoc.Create; try Doc.AsString := Data; with Doc.DocumentElement do for i := 0 to NbElements - 1 do if Elements[i].TagName = 'data' then begin Memo1.Lines.Add(Elements[i].Text); end; finally Doc.Free; end; end; procedure TMainFrm.Button1Click(Sender: TObject); var ln, i : integer; ip : string; Doc : TXmlDoc; begin if FUDP.Connected then FUDP.Disconnect; FUDP.ConnectToServer(edIP.Text); Doc := TXmlDoc.Create; try with Doc.CreateNewDocumentElement('doc').AddChildNode('cmd') do begin Text := 'register'; SetAttribute('IP', '10.211.55.34'); end; FUDP.Send(Doc.AsString); finally Doc.Free; end; end; end.
unit FlicPlayback; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses GDI, Flics, Windows; // For extension purposes: type TChunkPlayerProc = function( Chunk : pointer; const FliSize : TPoint; Dest : pointer; DestWidth : integer ) : pointer; // Player procedure PlayFrame( Frame : PFliFrame; const FliSize : TPoint; Dest : pointer; DestWidth : integer; UnkChunkPlayer : TChunkPlayerProc); function PlayChunks( FirstChunk : pointer; const FliSize : TPoint; Dest : pointer; DestWidth : integer; Count : integer; UnkChunkPlayer : TChunkPlayerProc) : pointer; procedure GetUpdatedBounds( Frame : PFliFrame; const FliSize : TPoint; var Rect : TRect ); // Other Flic related stuff function CreatePaletteChunk( ChangedColors : ColorSet; var RgbQuads ) : pointer; implementation procedure PlayFrame( Frame : PFliFrame; const FliSize : TPoint; Dest : pointer; DestWidth : integer; UnkChunkPlayer : TChunkPlayerProc); begin try PlayChunks( pchar(Frame) + sizeof(TFliFrame), FliSize, Dest, DestWidth, Frame.Chunks, UnkChunkPlayer ); except // Avoid any exception due to an invalid chunk end; end; // Chunk Players procedure GetUpdatedBounds( Frame : PFliFrame; const FliSize : TPoint; var Rect : TRect ); begin // !! end; {$WARNINGS OFF} function PlayChunks( FirstChunk : pointer; const FliSize : TPoint; Dest : pointer; DestWidth : integer; Count : integer; UnkChunkPlayer : TChunkPlayerProc) : pointer; const idLastKnownChunk = 18; var SaveEAX : integer; SaveECX : integer; SaveEDX : integer; SaveEBX : integer; SaveESI : integer; SaveEDI : integer; TempVar : integer; var LastPixel : word; label JumpTable; asm // EAX = FirstChunk, EDX = @FliSize, ECX = Dest cmp Count, 0 je @Exit mov SaveEAX, eax mov SaveEDX, edx mov SaveECX, ecx mov SaveEBX, ebx mov SaveESI, esi mov SaveEDI, edi @PlayChunk: xor ebx, ebx mov bx, TFliChunkGeneric([eax]).Magic cmp ebx, idLastKnownChunk ja @PlayUnknown jmp dword ptr JumpTable[ebx * 4] // --------------------------------------------------------------------------------------------- @PlayBlack: // Uses esi, edi, eax, ebx, ecx, edx mov edi, SaveECX mov edx, SaveEDX mov ecx, TPoint(edx).X // FliSize.X mov edx, TPoint(edx).Y // FliSize.Y sub DestWidth, ecx mov ebx, ecx xor eax, eax shr ecx, 2 and ebx, 3 mov TempVar, ecx @@BlackLine: mov ecx, TempVar rep stosd mov ecx, ebx rep stosb add edi, DestWidth dec edx jnz @@BlackLine jmp @NextChunk // --------------------------------------------------------------------------------------------- @PlayLC: // This chunk is found only in 320x200 FLIs // Uses esi, edi, eax, ebx, ecx, edx mov esi, SaveEAX mov edi, SaveECX xor eax, eax add esi, type TFliChunkGeneric lodsw // Lines to skip mul DestWidth add edi, eax xor eax, eax lodsw // Line count mov edx, eax @@LCLine: push edi lodsb mov ebx, eax // Packet count or eax, eax jz @@LCLineFinished @@LCPacket: // Process each packet lodsb // Columns to skip add edi, eax lodsb // Type/Size byte test al, al js @@LCFill @@LCMove: mov ecx, eax and eax, 3 // shr ecx, 2 // rep movsd // mov ecx, eax // rep movsb dec ebx jnz @@LCPacket jmp @@LCLineFinished @@LCFill: neg al mov ecx, eax lodsb // value to repeat in al shr ecx, 1 mov ah, al rep stosw adc cl, cl rep stosb dec ebx mov ah, 0 jnz @@LCPacket @@LCLineFinished: pop edi add edi, DestWidth dec edx jnz @@LCLine jmp @NextChunk // --------------------------------------------------------------------------------------------- @PlaySS2: // Uses esi, edi, eax, ebx, ecx, edx xor ecx, ecx xor eax, eax mov esi, SaveEAX mov LastPixel, cx add esi, type TFliChunkGeneric lodsw // Line count mov edi, SaveECX mov TempVar, eax @@SS2Line: lodsw test ah, $40 jnz @@SS2SkipLines @@SS2OddWidth: push edi test ah, $80 jz @@SS2PacketCount mov LastPixel, ax lodsw // The packet count always follows this word or eax, eax jz @@SS2LastPixel @@SS2PacketCount: mov ebx, eax xor eax, eax @@SS2Packet: // Process each packet mov cl, [esi + 0] mov al, [esi + 1] add edi, ecx add esi, 2 test al, al js @@SS2Fill @@SS2Move: mov ecx, eax shr ecx, 1 and eax, 1 rep movsd mov ecx, eax rep movsw dec ebx jnz @@SS2Packet @@SS2LineFinished: mov ax, LastPixel // If AH = $80, we have to copy the last pixel (odd width flic) or ah, ah jz @@SS2Cont @@SS2LastPixel: stosb @@SS2Cont: pop edi add edi, DestWidth dec TempVar jnz @@SS2Line jmp @NextChunk @@SS2SkipLines: neg ax mul DestWidth add edi, eax xor eax, eax jmp @@SS2Line @@SS2Fill: neg al mov ecx, eax mov ax, [esi] // value to repeat in AX shl eax, 16 lodsw shr ecx, 1 rep stosd adc cl, cl rep stosw xor eax, eax dec ebx jnz @@SS2Packet jmp @@SS2LineFinished // --------------------------------------------------------------------------------------------- @PlayBRun: mov esi, SaveEAX mov edi, SaveECX mov edx, SaveEDX add esi, type TFliChunkGeneric xor eax, eax mov ecx, TPoint(edx).X // FliSize.X mov edx, TPoint(edx).Y // FliSize.Y sub DestWidth, ecx mov TempVar, ecx @@BRunLine: inc esi // Skip packet count byte TLinePacket.Count mov ebx, TempVar @@BRunLoop: lodsb // Type/Size byte test al, al js @@BRunMove @@BRunFill: mov ecx, eax sub ebx, ecx lodsb shr ecx, 1 mov ah, al rep stosw adc cl, cl rep stosb or ebx, ebx mov ah, 0 jnz @@BRunLoop jmp @@BRunPacketDone @@BRunMove: neg al mov ecx, eax sub ebx, eax and ax, 3 // shr ecx, 2 // rep movsd // mov ecx, eax // rep movsb or ebx, ebx jnz @@BRunLoop @@BRunPacketDone: add edi, DestWidth dec dx jnz @@BRunLine jmp @NextChunk // --------------------------------------------------------------------------------------------- @PlayCopy: mov esi, SaveEAX mov edi, SaveECX mov edx, SaveEDX add esi, type TFliChunkGeneric mov ecx, TPoint(edx).X // FliSize.X mov edx, TPoint(edx).Y // FliSize.Y mov ebx, ecx sub DestWidth, ecx shr ecx, 2 and ebx, 3 mov TempVar, ecx @@CopyLine: mov ecx, TempVar rep movsd mov ecx, ebx rep movsb add edi, DestWidth dec edx jnz @@CopyLine jmp @NextChunk // --------------------------------------------------------------------------------------------- @PlayUnknown: cmp UnkChunkPlayer, 0 jz @NextChunk mov eax, SaveEAX mov edx, SaveEDX mov ecx, SaveECX mov ebx, SaveEBX mov esi, SaveESI mov edi, SaveEDI // Chunk, FliSize and Dest are already passsed in EAX,EDX,ECX push DestWidth // Pass DestWidth call UnkChunkPlayer jmp @NextChunk // --------------------------------------------------------------------------------------------- JumpTable: dd @PlayUnknown // 0 ? dd @PlayUnknown // 1 ? dd @PlayUnknown // 2 ? dd @PlayUnknown // 3 ? dd @PlayUnknown // 4 o FLI_COLOR256 dd @PlayUnknown // 5 ? dd @PlayUnknown // 6 ? dd @PlaySS2 // 7 x FLI_SS2 dd @PlayUnknown // 8 ? dd @PlayUnknown // 9 ? dd @PlayUnknown // 10 ? dd @PlayUnknown // 11 o FLI_COLOR dd @PlayLC // 12 x FLI_LC dd @PlayBlack // 13 x FLI_BLACK dd @PlayUnknown // 14 ? dd @PlayBRun // 15 x FLI_BRUN dd @PlayCopy // 16 x FLI_COPY dd @PlayUnknown // 17 ? dd @PlayUnknown // 18 o FLI_PSTAMP @NextChunk: mov eax, SaveEAX add eax, TFliChunkGeneric([eax]).Size mov SaveEAX, eax dec Count jnz @PlayChunk mov ebx, SaveEBX mov esi, SaveESI mov edi, SaveEDI @Exit: end; {$WARNINGS ON} function CreatePaletteChunk( ChangedColors : ColorSet; var RgbQuads ) : pointer; var ColorPacket : ^TColorPacket; ColorPacketOfs : integer; i, ColorIndx : integer; SkipCnt : integer; PaletteChunk : ^TFliChunkColor256 absolute Result; RgbEntries : TRgbPalette absolute RgbQuads; begin new( PaletteChunk ); ColorPacket := @PaletteChunk.Packets; with PaletteChunk^ do begin Magic := idColor256; Count := 0; Size := 0; end; ColorIndx := 0; repeat Inc( PaletteChunk.Count ); with PaletteChunk^, ColorPacket^ do begin // How many colors to skip Skip := 0; while not ( ( ColorIndx + Skip ) in ChangedColors ) do inc( Skip ); Inc( ColorIndx, Skip ); Count := 0; repeat while ( (ColorIndx + Count) in ChangedColors ) and ( ColorIndx + Count < 256 ) do Inc( Count ); // Check if SkipCnt > 3, otherwise we should include the colors in this ColorPacket SkipCnt := 0; while not ( (ColorIndx + Count + SkipCnt) in ChangedColors ) and ( ColorIndx + Count + SkipCnt < 256 )do Inc( SkipCnt ); if SkipCnt <= 3 then Inc( Count, SkipCnt ); until SkipCnt > 3; ColorPacketOfs := pchar( ColorPacket ) - PaletteChunk; Inc( Size, sizeof( ColorPacket ) + sizeof( Rgb[0] ) * ( Count - 1 ) ); ReallocMem( PaletteChunk, Size ); end; pchar(ColorPacket) := pchar(PaletteChunk) + ColorPacketOfs; // Relocate ColorPacket pointer with PaletteChunk^, ColorPacket^ do begin for i := 0 to ColorPacket.Count - 1 do with Rgb[i], RgbEntries[ColorIndx + i] do begin r := rgbRed; g := rgbGreen; b := rgbBlue; end; inc( ColorIndx, Count ); end; until ColorIndx >= 255; end; end.
unit WpcScriptExecutor; {$mode objfpc}{$H+} {$GOTO ON} interface uses Classes, SysUtils, WpcScriptCommons, WpcStatements, WpcScript, WpcExceptions, WallpaperSetter; type { TWpcScriptExecutor } TWpcScriptExecutor = class(TObject) private FScript : TWpcScript; FWallpaperSetter : IWallpaperSetter; FIsStopStatementReached : Boolean; FIsSwitchBranchTriggered : Boolean; FSwithToBranchName : String; public constructor Create(Script : TWpcScript; WpSetter : IWallpaperSetter); destructor Destroy(); override; public procedure ExecuteScript(); private procedure ExecuteBranch(BranchName : String); procedure ExecuteStatement(Statement : IWpcBaseScriptStatement); procedure ExecuteWaitStatement(Statement : TWpcWaitStatement); procedure ExecuteWallpaperStatement(Statement : TWpcWallpaperStatement); procedure ExecuteStopStatement(Statement : TWpcStopStatement); procedure ExecuteSwitchBranchStatement(Statement : TWpcSwitchBranchStatement); procedure ExecuteUseBtranchStatement(Statement : TWpcUseBranchStatement); procedure ExecuteWallpaperChooserStatement(Statement : TWpcWallpaperChooserStatement); procedure ExecuteBranchToUseChooserStatement(Statement : TWpcUseBranchChooserStatement); procedure ExecuteBranchToSwitchChooserStatement(Statement : TWpcSwitchBranchChooserStatement); function IsTriggered(Probability : Byte) : Boolean; end; implementation { TWpcScriptExecutor } constructor TWpcScriptExecutor.Create(Script: TWpcScript; WpSetter : IWallpaperSetter); begin FScript := Script; FWallpaperSetter := WpSetter; FIsStopStatementReached := False; end; destructor TWpcScriptExecutor.Destroy; begin FScript.Free(); inherited Destroy(); end; { Executes Wallpaper Changer script. Entry point is branch with 'Main' name. When executor reach end of branch then Main branch will be executed again. Execution will be stopped only if it reach Stop statement. } procedure TWpcScriptExecutor.ExecuteScript(); begin repeat ExecuteBranch(MAIN_BARNCH); until (FIsStopStatementReached); end; { Helper methods } procedure TWpcScriptExecutor.ExecuteBranch(BranchName: String); label StartBranchLabel; var CurrentBranch : TWpcBranchStatement; CurrentStatementNumber : Integer; begin CurrentBranch := FScript.GetBranch(BranchName); StartBranchLabel: for CurrentStatementNumber:=0 to (CurrentBranch.CountStatements() - 1) do begin if (FIsStopStatementReached) then break; if (FIsSwitchBranchTriggered) then begin FIsSwitchBranchTriggered := False; CurrentBranch := FScript.GetBranch(FSwithToBranchName); goto StartBranchLabel; end; ExecuteStatement(CurrentBranch.GetStatement(CurrentStatementNumber)); end; end; { Applies given script statement. } procedure TWpcScriptExecutor.ExecuteStatement(Statement: IWpcBaseScriptStatement); begin // Type casting is safe here because of IDs. case (Statement.GetId()) of WPC_WAIT_STATEMENT_ID: ExecuteWaitStatement(TWpcWaitStatement(Statement)); WPC_WALLPAPER_STATEMENT_ID: ExecuteWallpaperStatement(TWpcWallpaperStatement(Statement)); WPC_STOP_STATEMENT_ID: ExecuteStopStatement(TWpcStopStatement(Statement)); WPC_SWITCH_BRANCH_STATEMENT_ID: ExecuteSwitchBranchStatement(TWpcSwitchBranchStatement(Statement)); WPC_USE_BRANCH_STATEMENT_ID: ExecuteUseBtranchStatement(TWpcUseBranchStatement(Statement)); WPC_WALLPAPER_CHOOSER_STATEMENT_ID: ExecuteWallpaperChooserStatement(TWpcWallpaperChooserStatement(Statement)); WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID: ExecuteBranchToUseChooserStatement(TWpcUseBranchChooserStatement(Statement)); WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID: ExecutebranchToSwitchChooserStatement(TWpcSwitchBranchChooserStatement(Statement)); else raise TWpcUseErrorException.Create('Script Executor: unknown statement: ' + StatementIdToStr(Statement.GetId())); end; end; procedure TWpcScriptExecutor.ExecuteWaitStatement(Statement: TWpcWaitStatement); var i : Integer; begin for i:=1 to Statement.GetTimes() do if (IsTriggered(Statement.GetProbability())) then Sleep(Statement.GetDelay()); end; procedure TWpcScriptExecutor.ExecuteWallpaperStatement(Statement: TWpcWallpaperStatement); begin if (IsTriggered(Statement.GetProbability())) then begin FWallpaperSetter.SetDesktopWallpaper(Statement.GetImage().GetPath(), Statement.GetStyle()); if (Statement.GetDelay() <> 0) then Sleep(Statement.GetDelay()); end; end; procedure TWpcScriptExecutor.ExecuteStopStatement(Statement: TWpcStopStatement); begin if (IsTriggered(Statement.GetProbability())) then FIsStopStatementReached := True; end; { Replaces current branch execution with new branch. } procedure TWpcScriptExecutor.ExecuteSwitchBranchStatement(Statement: TWpcSwitchBranchStatement); begin if (IsTriggered(Statement.GetProbability())) then begin FIsSwitchBranchTriggered := True; FSwithToBranchName := Statement.GetBranchName(); end; end; { Executes subbranch and returns to the next statement of current branch. } procedure TWpcScriptExecutor.ExecuteUseBtranchStatement(Statement: TWpcUseBranchStatement); var i : Integer; begin for i:=1 to Statement.GetTimes() do if (IsTriggered(Statement.GetProbability())) then ExecuteBranch(Statement.GetBranchName()); end; procedure TWpcScriptExecutor.ExecuteWallpaperChooserStatement(Statement: TWpcWallpaperChooserStatement); begin ExecuteWallpaperStatement(Statement.ChooseItem()); end; procedure TWpcScriptExecutor.ExecuteBranchToUseChooserStatement(Statement: TWpcUseBranchChooserStatement); begin ExecuteUseBtranchStatement(Statement.ChooseItem()); end; procedure TWpcScriptExecutor.ExecuteBranchToSwitchChooserStatement(Statement: TWpcSwitchBranchChooserStatement); begin ExecuteSwitchBranchStatement(Statement.ChooseItem()); end; function TWpcScriptExecutor.IsTriggered(Probability: Byte): Boolean; begin if (Probability = 100) then Result := true else if (Probability = 0) then Result := false else Result := (Random(101) < Probability); end; end.
unit evDropCombo; // Модуль: "w:\common\components\gui\Garant\Everest\qf\evDropCombo.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevDropCombo" MUID: (48D399A20288) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evDropControl , evQueryCardInt , evQueryCardDropControlsInt , nevBase , l3Interfaces , l3TreeInterfaces , nevTools ; type TEditableState = ( esNone , esSemiCompleted , esCompleted , esWrong );//TEditableState TevDropCombo = class(TevDropControl, IevEditorFieldWithTree, IevDropCombo) private f_SelectedValue: InevSimpleNode; {* Выбранное пользователем значение } f_State: TEditableState; {* Состояние редактора } f_IsAsterisk: Boolean; {* Есть ли символ звездочки. Выставляется только для полей с признаком IsNumList! } f_IsAsteriskLastChar: Boolean; {* Символ звездочки - последний символ в тексте } f_ComboStyle: TevComboStyle; f_NeedAdd: Boolean; f_ItemCachedText: Il3CString; {* Текст выбранного значения (чтобы лишний раз не фильтровать дерево) } f_Tree: InevSimpleTree; {* Дерево реквизитов } f_TreeInit: Boolean; {* Дерево было загружено из реквизитов } f_RootNode: InevNode; {* Корневой узел } f_TreeIsFiltered: Boolean; {* Дерево было отфильтровано (чтобы не делать лишний раз Deselect Hidden) } f_Asterisk: AnsiChar; {* Символ звездочки } f_LastGoodContext: Il3CString; f_HistoryRoot: InevNode; f_PromptTree: InevSimpleTree; f_ShowHistoryList: Boolean; f_LockShowPrompts: Integer; f_SavedText: Il3CString; f_LockSaveText: Boolean; f_InputWithTree: Boolean; {* Режим ввода с выпадающим деревом } private function GetFullPath(const aNode: InevSimpleNode): Il3CString; procedure CheckAsterisk; function ComboReq: IevComboReq; procedure InitTree; function MakeNodesFromItems: Boolean; procedure ChangeDropTreeForHistory(ForHistory: Boolean); procedure SetRootNode(const Value: InevNode); procedure Change(const aView: InevView; const aPara: InevPara); procedure DefilterTree; procedure SetRoot(const aRoot: InevNode); procedure ChooseMean(NeedHide: Boolean); procedure FilterPromptTree; procedure FilterNewTree; function Filter(const aExpTree: Il3FilterableTree; const aContext: Il3CString; out anIndex: Integer; AutoOpen: Boolean; NeedRefilter: Boolean): Il3SimpleTree; procedure DoSetContextText(const aText: Il3CString); protected procedure SetNodeByIndex(aIndex: Integer); function GetNodeIndex(const aNode: InevSimpleNode): Integer; {* Возвращает номер узла. } procedure ShowNode(const aNode: InevSimpleNode); {* Отображает узел в поле. } function Get_Value: InevSimpleNode; function Get_IsAsterisk: Boolean; function Get_DefaultNode: InevSimpleNode; function Get_Asterisk: AnsiChar; procedure Set_Asterisk(aValue: AnsiChar); function Get_SourceTree: InevSimpleTree; function Get_ComboStyle: TevComboStyle; procedure Set_ComboStyle(aValue: TevComboStyle); function Get_LogicalState: Integer; procedure Set_LogicalState(aValue: Integer); function Get_Down: Boolean; procedure Set_Down(aValue: Boolean); procedure CheckTextVersusValue; {* Заточка на тот случай когда после Undo текст в контроле не совпадает с выбранной нодой - в этом случае очищаем все. } function GetNode(anIndex: Integer): InevSimpleNode; {* Возвращает узел. } procedure ChooseNode(const Value: InevSimpleNode; NeedHide: Boolean = True); {* Обработчик выбора узла в дереве при его закрытии. } function Get_IsList: Boolean; function NeedClearOnEscape: Boolean; procedure DoDrop(const aPoint: TPoint; AInvert: Boolean; AWidth: Integer; ByUser: Boolean); override; {* Вываливает выпадающий виджет по указанным координатам } function Get_IsLogicalStateButtonEnabled: Boolean; procedure SetMaskText(const aText: Il3CString); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure SetText(const Value: Il3CString); override; procedure DoTextChange(const aView: InevView; const aPara: InevPara; const anOp: InevOp); override; procedure DoInsertRow(const aView: InevView); override; procedure AfterSetText(const Value: Il3CString); override; function GetSelectAllOnFocus: Boolean; override; procedure DoClearText; override; function DoAnalyzeString(const aValue: Il3CString; aPos: Integer; out aRslt: Il3CString): Boolean; override; procedure DoEscPressed; override; procedure DoDropDownCurrentChanged(const aNode: InevSimpleNode); override; procedure DoAfterHideControl; override; procedure DoSynchronizeSelectedValueWithText; override; public constructor Create(const aPara: InevPara); override; end;//TevDropCombo implementation uses l3ImplUses , SysUtils , l3Chars , evControlParaTools , l3String , l3Const , k2Tags {$If Defined(k2ForEditor)} , evParaTools {$IfEnd} // Defined(k2ForEditor) , l3Tree , l3Base , l3Nodes , evTextStyle_Const , l3Types {$If Defined(k2ForEditor)} , evTextParaTools {$IfEnd} // Defined(k2ForEditor) , evdTextStyle_Const , l3Tree_TLB //#UC START# *48D399A20288impl_uses* //#UC END# *48D399A20288impl_uses* ; function TevDropCombo.GetFullPath(const aNode: InevSimpleNode): Il3CString; //#UC START# *48D3A26202FD_48D399A20288_var* //#UC END# *48D3A26202FD_48D399A20288_var* begin //#UC START# *48D3A26202FD_48D399A20288_impl* if (aNode = nil) then //пусть эта проверка будет. :-) Result := nil else Result := evGetFullPathStr(Get_SourceTree, aNode); //#UC END# *48D3A26202FD_48D399A20288_impl* end;//TevDropCombo.GetFullPath procedure TevDropCombo.CheckAsterisk; //#UC START# *48D3A3D800BB_48D399A20288_var* var l_Pos : Integer; l_Text : Il3Cstring; //#UC END# *48D3A3D800BB_48D399A20288_var* begin //#UC START# *48D3A3D800BB_48D399A20288_impl* l_Text := Get_Caption; l_Pos := l3Pos(l_Text, f_Asterisk); if (l_Pos <> l3NotFound) then begin f_IsAsterisk := ComboReq.NeedAsterisk and (l_Pos <> l3NotFound); f_IsAsteriskLastChar := (l_Pos = l3Len(l_Text) - 1); end//l_Pos <> l3NotFound else begin f_IsAsterisk := false; f_IsAsteriskLastChar := false; end;//l_Pos <> l3NotFound //#UC END# *48D3A3D800BB_48D399A20288_impl* end;//TevDropCombo.CheckAsterisk function TevDropCombo.ComboReq: IevComboReq; //#UC START# *48D3A51B02F0_48D399A20288_var* //#UC END# *48D3A51B02F0_48D399A20288_var* begin //#UC START# *48D3A51B02F0_48D399A20288_impl* Supports(Get_Req, IevComboReq, Result); //#UC END# *48D3A51B02F0_48D399A20288_impl* end;//TevDropCombo.ComboReq procedure TevDropCombo.InitTree; //#UC START# *48D3A67D02B2_48D399A20288_var* {$IFDEF TEST_MODEL} var l_Tree : Tl3Tree; {$ENDIF TEST_MODEL} function Search(const anIntf: InevNode): Boolean; begin Result := l3Same(anIntf.Text, Get_Caption); end; //#UC END# *48D3A67D02B2_48D399A20288_var* begin //#UC START# *48D3A67D02B2_48D399A20288_impl* {$IFDEF TEST_MODEL} l_Tree := Tl3Tree.Create; try with l_Tree.RootNode do begin with InsertChild(MakeNode('Node 1')) do begin InsertChild(MakeNode('Child 1')); InsertChild(MakeNode('Child 2')); end;//with InsertChild(MakeNode('Node1')) InsertChild(MakeNode('Node 2')); end;//with l_Tree.RootNode f_Tree := l_Tree; finally l3Free(l_Tree); end;//try..finally {$ELSE} if ComboReq.IsContext then begin f_PromptTree := ComboReq.GetPromptTreeFromAdapter; MakeNodesFromItems; f_TreeInit := True; end//ComboReq.IsContext else begin f_Tree := ComboReq.GetTreeFromAdapter; f_LastGoodContext := nil; if (f_Tree <> nil) then begin f_TreeInit := True; f_TreeIsFiltered := True; DefilterTree; end//f_Tree <> nil else begin if MakeNodesFromItems then SetRootNode(f_HistoryRoot) else begin if Assigned(f_RootNode) then f_SelectedValue := f_RootNode.IterateF(l3L2NA(@Search), imOneLevel or imCheckResult) else f_SelectedValue := nil; end;//MakeNodesFromItems if f_SelectedValue = nil then DropContainer.Current := 0; f_TreeInit := (f_Tree <> nil); end;//f_Tree <> nil end;//ComboReq.IsContext {$ENDIF TEST_MODEL} //#UC END# *48D3A67D02B2_48D399A20288_impl* end;//TevDropCombo.InitTree function TevDropCombo.MakeNodesFromItems: Boolean; //#UC START# *48D3A6C30115_48D399A20288_var* var i : Integer; l_Root : Tl3UsualNode; l_SubNode : Tl3UsualNode; l_Count : Integer; l_HistoryList : Il3StringsEx; l_Text : string; //#UC END# *48D3A6C30115_48D399A20288_var* begin //#UC START# *48D3A6C30115_48D399A20288_impl* {$IFNDEF TEST_MODEL} Result := False; l_HistoryList := ComboReq.HistoryList; if (l_HistoryList = nil) OR (l_HistoryList.Items = nil) then Exit; l_Text := l_HistoryList.Items.Text; if not l3Same(f_ItemCachedText, l_Text) then begin f_SelectedValue := nil; Result := true; l_Root := Tl3UsualNode.Create; try l_Count := l_HistoryList.Count - 1; for i := 0 to l_Count do begin l_SubNode := Tl3UsualNode.Create; try l_SubNode.Text := l3PCharLen(l_HistoryList.ItemC[i]); if (f_SelectedValue = nil) and l3Same(l_HistoryList.ItemC[i], Get_Caption) then f_SelectedValue := l_SubNode; Il3Node(l_Root).InsertChild(l_SubNode); finally l3Free(l_SubNode); end;//try..finally end;//for i f_HistoryRoot := l_Root; f_ItemCachedText := l3CStr(l_Text); finally l3Free(l_Root); end;//try..finally end//not l3Same(f_ItemCachedText, l_Text) {$ENDIF TEST_MODEL} //#UC END# *48D3A6C30115_48D399A20288_impl* end;//TevDropCombo.MakeNodesFromItems procedure TevDropCombo.ChangeDropTreeForHistory(ForHistory: Boolean); //#UC START# *48D3A6D703E0_48D399A20288_var* //#UC END# *48D3A6D703E0_48D399A20288_var* begin //#UC START# *48D3A6D703E0_48D399A20288_impl* if ForHistory then begin if DropContainer.Tree = f_PromptTree then begin f_Tree := nil; DropContainer.Tree := nil; DropContainer.DropTextStyle := evd_saGUI; DropContainer.AllowEmptyCurrent := False; end; end else begin if DropContainer.Tree <> f_PromptTree then begin f_Tree := f_PromptTree; DropContainer.Tree := f_PromptTree; DropContainer.DropTextStyle := ev_saPromptTree; DropContainer.AllowEmptyCurrent := True; DropContainer.Current := -1; end; end; //#UC END# *48D3A6D703E0_48D399A20288_impl* end;//TevDropCombo.ChangeDropTreeForHistory procedure TevDropCombo.SetRootNode(const Value: InevNode); //#UC START# *48D3A70201C8_48D399A20288_var* //#UC END# *48D3A70201C8_48D399A20288_var* begin //#UC START# *48D3A70201C8_48D399A20288_impl* if (Value <> nil) and not Value.IsSame(f_RootNode) then begin f_RootNode := Value; SetRoot(Value); end;//Value <> nil //#UC END# *48D3A70201C8_48D399A20288_impl* end;//TevDropCombo.SetRootNode procedure TevDropCombo.Change(const aView: InevView; const aPara: InevPara); //#UC START# *48D3A7710129_48D399A20288_var* (* function FindCurrent(const aTree : InevSimpleTree; const aText : Il3CString): Il3SimpleNode; function FindCurr(const aIterNode: Il3SimpleNode): boolean; begin//FindCurr Result := l3Same(aIterNode.Text, aText, true); end;//FindCurr begin if (aTree = nil) then Result := nil else Result := aTree.SimpleIterateF(l3L2SNA(@FindCurr), imCheckResult); end;*) procedure lp_SelectTail(aStartPos: Integer; aEndPos: Integer; const aSelection: InevSelection); var l_Start: InevBasePoint; l_End: InevBasePoint; l_StartMI: InevBasePoint; l_EndMI: InevBasePoint; l_View: InevView; begin//lp_SelectTail l_View := aSelection.View; Assert(aSelection.Point.MostInner.AsObject.IsSame(Self.Para.AsObject)); // http://mdp.garant.ru/pages/viewpage.action?pageId=290952615 // http://mdp.garant.ru/pages/viewpage.action?pageId=290951667&focusedCommentId=290953794#comment-290953794 l_Start := aSelection.Point.ClonePoint(l_View); l_End := aSelection.Point.ClonePoint(l_View); l_StartMI := l_Start.MostInner; l_StartMI.PositionW := aStartPos; l_EndMI := l_End.MostInner; l_EndMI.PositionW := aEndPos; l_EndMI.SetAtEnd(l_View, True); aSelection.Select(Para.Range(l_StartMI, l_EndMI), false); end;//lp_SelectTail var l_Text: Tl3PCharLen; l_Selection: InevSelection; l_EditorControl: InevControl; l_Editor: IevQueryCardEditor; //#UC END# *48D3A7710129_48D399A20288_var* begin //#UC START# *48D3A7710129_48D399A20288_impl* if ComboReq.IsContext then begin if f_LockSaveText then Exit; f_SavedText := l3CStr(Get_Caption.AsWStr); if not f_TreeInit then InitTree; if Assigned(f_PromptTree) and not l3IsNil(Get_Caption) and (f_LockShowPrompts = 0) then begin FilterPromptTree; if Assigned(f_PromptTree) and (f_PromptTree.CountView > 0) then begin if DropContainer.IsDropTreeVisible and f_ShowHistoryList then CloseTree; f_ShowHistoryList := False; if not DropContainer.IsDropTreeVisible then DropDown(aView, aPara, False); end//Assigned(f_PromptTree) else CloseTree; end;//Assigned(f_PromptTree) if l3IsNil(Get_Caption) and not f_ShowHistoryList then CloseTree; end//ComboReq.IsContext else begin FilterNewTree; if f_IsAsterisk then Set_Valid(f_IsAsteriskLastChar) else Set_Valid(f_State <> esWrong); if (f_State = esWrong) then begin l_EditorControl := Get_Req.QueryCard.Editor; l_Selection := l_EditorControl.Selection; with l_Selection.Point.MostInner do begin l_Text := Para.AsObject.PCharLenA[k2_tiText]; Supports(l_EditorControl, IevQueryCardEditor, l_Editor); Assert(Assigned(l_Editor)); if (Position >= l_Text.SLen) or l_Editor.DroppingData then begin l_Editor.SignalDisableUnselectAfterDrop; lp_SelectTail(l3CommonPartLen(l3CStr(l_Text), f_LastGoodContext), l_Text.SLen, l_Selection); ComboReq.NotifyContextWrong; end;//Position >= l_Text.SLen end;//with l_Selection.Point.MostInner end//f_State = esWrong else if (f_State = esSemiCompleted) then begin // - ничего не надо, см. SynchronizeSelectedValueWithText // - иначе наступает рассинхронизация текста и данных // http://mdp.garant.ru/pages/viewpage.action?pageId=290952615 // http://mdp.garant.ru/pages/viewpage.action?pageId=290951667&focusedCommentId=290953794#comment-290953794 // f_SelectedValue := FindCurrent(f_Tree, Get_Caption); (* if not f_LockSaveText then begin if DropContainer.IsDropTreeVisible then CloseTree; if not DropContainer.IsDropTreeVisible then DropDown(aView, aPara, False); // - чтобы выбрать нужную ноду end;//not f_LockSaveText*) end;//f_State = esSemiCompleted end;//ComboReq.IsContext inherited; //#UC END# *48D3A7710129_48D399A20288_impl* end;//TevDropCombo.Change procedure TevDropCombo.DefilterTree; //#UC START# *48D3A9340213_48D399A20288_var* {$IFNDEF TEST_MODEL} var l_Tree : InevTree; l_ExpTree : Il3FilterableTree; l_Index: Integer; {$ENDIF TEST_MODEL} //#UC END# *48D3A9340213_48D399A20288_var* begin //#UC START# *48D3A9340213_48D399A20288_impl* {$IFNDEF TEST_MODEL} if f_TreeIsFiltered then begin if Supports(f_Tree, InevTree, l_Tree) then try if not f_Tree.RootNode.IsSame(f_RootNode) then f_Tree.RootNode := f_RootNode as Il3SimpleRootNode else l_Tree.SetAllFlag(sbDeselect, nfHidden) finally l_Tree := nil; end//try..finally else begin if Supports(f_Tree, Il3FilterableTree, l_ExpTree) then try f_Tree := Filter(l_ExpTree, nil, l_Index, false, False); finally l_ExpTree := nil; end;//try..finally end; f_TreeIsFiltered := False; end;//f_TreeIsFiltered {$ENDIF TEST_MODEL} //#UC END# *48D3A9340213_48D399A20288_impl* end;//TevDropCombo.DefilterTree procedure TevDropCombo.SetRoot(const aRoot: InevNode); //#UC START# *48D3AC90019B_48D399A20288_var* var l_Tree: InevTree; //#UC END# *48D3AC90019B_48D399A20288_var* begin //#UC START# *48D3AC90019B_48D399A20288_impl* with DropContainer do if not IsSameTreeRoot(aRoot) then begin if f_Tree = nil then f_Tree := Tl3Tree.Make; if Supports(f_Tree, InevTree, l_Tree) then l_Tree.SetRootAndCountView(aRoot as InevRootNode, l3_DelayedCountView) else f_Tree.RootNode := aRoot as Il3SimpleRootNode; f_TreeIsFiltered := False; end;//not IsSameTreeRoot(aRoot) //#UC END# *48D3AC90019B_48D399A20288_impl* end;//TevDropCombo.SetRoot procedure TevDropCombo.ChooseMean(NeedHide: Boolean); //#UC START# *48D3ACC90036_48D399A20288_var* //#UC END# *48D3ACC90036_48D399A20288_var* begin //#UC START# *48D3ACC90036_48D399A20288_impl* if f_InputWithTree and (not l3IsNil(Get_Caption)) then ChooseNode(DropContainer.GetCurrentNode, NeedHide); //#UC END# *48D3ACC90036_48D399A20288_impl* end;//TevDropCombo.ChooseMean procedure TevDropCombo.FilterPromptTree; //#UC START# *48D3AEF40349_48D399A20288_var* var l_FilterableTree : Il3FilterableTree; l_SyncIndex : Integer; //#UC END# *48D3AEF40349_48D399A20288_var* begin //#UC START# *48D3AEF40349_48D399A20288_impl* if Supports(f_PromptTree, Il3FilterableTree, l_FilterableTree) then begin f_PromptTree := l_FilterableTree.MakeFiltered(l_FilterableTree. CloneFilters. SetContext(Get_Caption), nil, l_SyncIndex); ChangeDropTreeForHistory(False); f_RootNode := nil; end//if Supports(f_PromptTree, Il3FilterableTree, l_FilterableTree) //#UC END# *48D3AEF40349_48D399A20288_impl* end;//TevDropCombo.FilterPromptTree procedure TevDropCombo.FilterNewTree; //#UC START# *48D3AF010084_48D399A20288_var* var l_ExpTree : Il3FilterableTree; l_Index : Integer; l_Tree : Il3SimpleTree; l_NeedCalcNewFilter: Boolean; //#UC END# *48D3AF010084_48D399A20288_var* begin //#UC START# *48D3AF010084_48D399A20288_impl* f_TreeIsFiltered := not l3IsNil(Get_Caption); with DropContainer do if Supports(Tree, Il3FilterableTree, l_ExpTree) then try if not Assigned(f_LastGoodContext) then begin l_Tree := Filter(l_ExpTree, Get_Caption, l_Index, True, True); Supports(l_Tree, Il3FilterableTree, l_ExpTree); f_LastGoodContext := l_ExpTree.CloneFilters.Context; Assert(Assigned(l_ExpTree)); Tree := l_Tree; end; l_Tree := Filter(l_ExpTree, Get_Caption, l_Index, True, False); try if (l_Tree.CountView > 0) then begin f_LastGoodContext := l3CStr(Get_Caption.AsWStr); Tree := l_Tree; if (l_Index >= 0) then Current := l_Index; if (Tree.CountView = 1) then f_State := esCompleted else f_State := esSemiCompleted; end//Tree.CountView > 0 else f_State := esWrong; finally l_Tree := nil; end;//try..finally finally l_ExpTree := nil; end;//try..finally //#UC END# *48D3AF010084_48D399A20288_impl* end;//TevDropCombo.FilterNewTree function TevDropCombo.Filter(const aExpTree: Il3FilterableTree; const aContext: Il3CString; out anIndex: Integer; AutoOpen: Boolean; NeedRefilter: Boolean): Il3SimpleTree; //#UC START# *48D3AF180338_48D399A20288_var* //#UC END# *48D3AF180338_48D399A20288_var* begin //#UC START# *48D3AF180338_48D399A20288_impl* Result := aExpTree.MakeFiltered(aExpTree.CloneFilters.SetContext(aContext), nil, anIndex, AutoOpen, NeedRefilter); //#UC END# *48D3AF180338_48D399A20288_impl* end;//TevDropCombo.Filter procedure TevDropCombo.DoSetContextText(const aText: Il3CString); //#UC START# *48D3B15501B0_48D399A20288_var* //#UC END# *48D3B15501B0_48D399A20288_var* begin //#UC START# *48D3B15501B0_48D399A20288_impl* if not l3Same(Get_Caption, aText) then SetText(aText); //#UC END# *48D3B15501B0_48D399A20288_impl* end;//TevDropCombo.DoSetContextText procedure TevDropCombo.SetNodeByIndex(aIndex: Integer); //#UC START# *47CD7C460280_48D399A20288_var* //#UC END# *47CD7C460280_48D399A20288_var* begin //#UC START# *47CD7C460280_48D399A20288_impl* if Get_SourceTree.ShowRoot then ShowNode(Get_SourceTree.Nodes[aIndex + 1]) else ShowNode(Get_SourceTree.Nodes[aIndex]); //#UC END# *47CD7C460280_48D399A20288_impl* end;//TevDropCombo.SetNodeByIndex function TevDropCombo.GetNodeIndex(const aNode: InevSimpleNode): Integer; {* Возвращает номер узла. } //#UC START# *47CD7C53028D_48D399A20288_var* //#UC END# *47CD7C53028D_48D399A20288_var* begin //#UC START# *47CD7C53028D_48D399A20288_impl* Result := f_Tree.GetIndex(aNode); //#UC END# *47CD7C53028D_48D399A20288_impl* end;//TevDropCombo.GetNodeIndex procedure TevDropCombo.ShowNode(const aNode: InevSimpleNode); {* Отображает узел в поле. } //#UC START# *47CD7C6C0211_48D399A20288_var* //#UC END# *47CD7C6C0211_48D399A20288_var* begin //#UC START# *47CD7C6C0211_48D399A20288_impl* if (aNode <> f_SelectedValue) then begin f_SelectedValue := aNode; f_State := esCompleted; //Именно это значение, т.к. будет UpdateState с Set_Valid(True); //вызовом Value if aNode <> nil then SetText(GetFullPath(aNode)); end;//aNode <> f_SelectedValue //#UC END# *47CD7C6C0211_48D399A20288_impl* end;//TevDropCombo.ShowNode function TevDropCombo.Get_Value: InevSimpleNode; //#UC START# *47CD7C8200EF_48D399A20288get_var* //#UC END# *47CD7C8200EF_48D399A20288get_var* begin //#UC START# *47CD7C8200EF_48D399A20288get_impl* if ((Get_ComboStyle = ev_cbFilterable) and ((f_State = esCompleted) or (f_State = esSemiCompleted))) then Result := f_SelectedValue else Result := nil; //#UC END# *47CD7C8200EF_48D399A20288get_impl* end;//TevDropCombo.Get_Value function TevDropCombo.Get_IsAsterisk: Boolean; //#UC START# *47CD7C9601D6_48D399A20288get_var* //#UC END# *47CD7C9601D6_48D399A20288get_var* begin //#UC START# *47CD7C9601D6_48D399A20288get_impl* CheckAsterisk; Result := f_IsAsterisk; //#UC END# *47CD7C9601D6_48D399A20288get_impl* end;//TevDropCombo.Get_IsAsterisk function TevDropCombo.Get_DefaultNode: InevSimpleNode; //#UC START# *47CD7CA301A9_48D399A20288get_var* var l_Req : IevReq; //#UC END# *47CD7CA301A9_48D399A20288get_var* begin //#UC START# *47CD7CA301A9_48D399A20288get_impl* l_Req := Get_Req; if (l_Req = nil) then Result := nil else Supports(l_Req.Para.AsObject.Attr[k2_tiDefaultNode], InevSimpleNode, Result); //#UC END# *47CD7CA301A9_48D399A20288get_impl* end;//TevDropCombo.Get_DefaultNode function TevDropCombo.Get_Asterisk: AnsiChar; //#UC START# *47CD7CB7026F_48D399A20288get_var* //#UC END# *47CD7CB7026F_48D399A20288get_var* begin //#UC START# *47CD7CB7026F_48D399A20288get_impl* Result := f_Asterisk; //#UC END# *47CD7CB7026F_48D399A20288get_impl* end;//TevDropCombo.Get_Asterisk procedure TevDropCombo.Set_Asterisk(aValue: AnsiChar); //#UC START# *47CD7CB7026F_48D399A20288set_var* //#UC END# *47CD7CB7026F_48D399A20288set_var* begin //#UC START# *47CD7CB7026F_48D399A20288set_impl* f_Asterisk := aValue; //#UC END# *47CD7CB7026F_48D399A20288set_impl* end;//TevDropCombo.Set_Asterisk function TevDropCombo.Get_SourceTree: InevSimpleTree; //#UC START# *47CD7CD10203_48D399A20288get_var* //#UC END# *47CD7CD10203_48D399A20288get_var* begin //#UC START# *47CD7CD10203_48D399A20288get_impl* if not f_TreeInit then InitTree; Result := f_Tree; //#UC END# *47CD7CD10203_48D399A20288get_impl* end;//TevDropCombo.Get_SourceTree function TevDropCombo.Get_ComboStyle: TevComboStyle; //#UC START# *47CD7CEE0396_48D399A20288get_var* //#UC END# *47CD7CEE0396_48D399A20288get_var* begin //#UC START# *47CD7CEE0396_48D399A20288get_impl* Result := f_ComboStyle; //#UC END# *47CD7CEE0396_48D399A20288get_impl* end;//TevDropCombo.Get_ComboStyle procedure TevDropCombo.Set_ComboStyle(aValue: TevComboStyle); //#UC START# *47CD7CEE0396_48D399A20288set_var* //#UC END# *47CD7CEE0396_48D399A20288set_var* begin //#UC START# *47CD7CEE0396_48D399A20288set_impl* f_ComboStyle := aValue; //#UC END# *47CD7CEE0396_48D399A20288set_impl* end;//TevDropCombo.Set_ComboStyle function TevDropCombo.Get_LogicalState: Integer; //#UC START# *47CD7CFB0250_48D399A20288get_var* var l_Control : IevEditorControl; l_BTN : IevEditorStateButton; //#UC END# *47CD7CFB0250_48D399A20288get_var* begin //#UC START# *47CD7CFB0250_48D399A20288get_impl* Result := 0; l_Control := FindButton(ev_btLogical); if (l_Control <> nil) and Supports(l_Control, IevEditorStateButton, l_BTN) then try Result := l_BTN.GetStateIndex; finally l_Control := nil; end; //#UC END# *47CD7CFB0250_48D399A20288get_impl* end;//TevDropCombo.Get_LogicalState procedure TevDropCombo.Set_LogicalState(aValue: Integer); //#UC START# *47CD7CFB0250_48D399A20288set_var* var l_Control : IevEditorControl; l_BTN : IevEditorStateButton; //#UC END# *47CD7CFB0250_48D399A20288set_var* begin //#UC START# *47CD7CFB0250_48D399A20288set_impl* l_Control := FindButton(ev_btLogical); if Supports(l_Control, IevEditorStateButton, l_BTN) then try Assert((aValue >= 0) or (aValue <= l_BTN.StateCount), 'Неподдерживаемое логическое значение!'); l_BTN.CurrentIndex := l_BTN.ImageIndex + aValue; finally l_Control := nil; end; //#UC END# *47CD7CFB0250_48D399A20288set_impl* end;//TevDropCombo.Set_LogicalState function TevDropCombo.Get_Down: Boolean; //#UC START# *47CD7D0700F5_48D399A20288get_var* //#UC END# *47CD7D0700F5_48D399A20288get_var* begin //#UC START# *47CD7D0700F5_48D399A20288get_impl* Result := inherited Get_Down; //#UC END# *47CD7D0700F5_48D399A20288get_impl* end;//TevDropCombo.Get_Down procedure TevDropCombo.Set_Down(aValue: Boolean); //#UC START# *47CD7D0700F5_48D399A20288set_var* //#UC END# *47CD7D0700F5_48D399A20288set_var* begin //#UC START# *47CD7D0700F5_48D399A20288set_impl* inherited Set_Down(aValue); //#UC END# *47CD7D0700F5_48D399A20288set_impl* end;//TevDropCombo.Set_Down procedure TevDropCombo.CheckTextVersusValue; {* Заточка на тот случай когда после Undo текст в контроле не совпадает с выбранной нодой - в этом случае очищаем все. } //#UC START# *47CD9A1B00EC_48D399A20288_var* var l_Node: InevSimpleNode; //#UC END# *47CD9A1B00EC_48D399A20288_var* begin //#UC START# *47CD9A1B00EC_48D399A20288_impl* l_Node := Get_Value; if (Get_ComboStyle = ev_cbFilterable) and not l3Same(GetFullPath(l_Node), Get_Caption) then begin evDir_DeleteText(Para as InevTextPara, 0, MaxInt); f_State := esNone; Set_Valid(True); Set_ErrorColor(False); f_SelectedValue := nil; end;//Get_ComboStyle = ev_cbFilterable //#UC END# *47CD9A1B00EC_48D399A20288_impl* end;//TevDropCombo.CheckTextVersusValue function TevDropCombo.GetNode(anIndex: Integer): InevSimpleNode; {* Возвращает узел. } //#UC START# *47CEA0C8006E_48D399A20288_var* //#UC END# *47CEA0C8006E_48D399A20288_var* begin //#UC START# *47CEA0C8006E_48D399A20288_impl* if DropContainer.IsDropTreeVisible then Result := DropContainer.GetDropTreeNode(anIndex) else Result := f_Tree.Nodes[anIndex]; //#UC END# *47CEA0C8006E_48D399A20288_impl* end;//TevDropCombo.GetNode procedure TevDropCombo.ChooseNode(const Value: InevSimpleNode; NeedHide: Boolean = True); {* Обработчик выбора узла в дереве при его закрытии. } //#UC START# *47CEA0D903B6_48D399A20288_var* var l_Op : InevOp; //#UC END# *47CEA0D903B6_48D399A20288_var* begin //#UC START# *47CEA0D903B6_48D399A20288_impl* with Get_Req.QueryCard do begin l_Op := GetDocumentContainer.Processor.StartOp; Inc(f_LockShowPrompts); try f_SelectedValue := Value; f_State := esCompleted; if (Value <> nil) and not f_IsAsterisk then begin SetText(GetFullPath(Value)); f_SavedText := Get_Caption; if not Get_ErrorColor then Set_Valid(True); Get_Req.SetFocus(Self, True); end; if NeedHide then begin DropContainer.EscPressed := True; try HideControl; finally DropContainer.EscPressed := False; end;//try..finally end;//NeedHide Get_Req.UpdateState(Self, nil); finally l_Op := nil; Dec(f_LockShowPrompts); end;//try..finally end;//with Get_Req.QueryCard //#UC END# *47CEA0D903B6_48D399A20288_impl* end;//TevDropCombo.ChooseNode function TevDropCombo.Get_IsList: Boolean; //#UC START# *47CEA0F901D9_48D399A20288get_var* var l_Req : IevReq; //#UC END# *47CEA0F901D9_48D399A20288get_var* begin //#UC START# *47CEA0F901D9_48D399A20288get_impl* l_Req := Get_Req; if (l_Req = nil) then Result := false else Result := l_Req.Para.AsObject.BoolA[k2_tiNumList]; //#UC END# *47CEA0F901D9_48D399A20288get_impl* end;//TevDropCombo.Get_IsList function TevDropCombo.NeedClearOnEscape: Boolean; //#UC START# *486C75F002CD_48D399A20288_var* //#UC END# *486C75F002CD_48D399A20288_var* begin //#UC START# *486C75F002CD_48D399A20288_impl* if ComboReq.IsContext then Result := False else Result := ((not l3IsNil(Get_Caption)) and (Get_Value = nil)); //#UC END# *486C75F002CD_48D399A20288_impl* end;//TevDropCombo.NeedClearOnEscape procedure TevDropCombo.DoDrop(const aPoint: TPoint; AInvert: Boolean; AWidth: Integer; ByUser: Boolean); {* Вываливает выпадающий виджет по указанным координатам } //#UC START# *48D37D66029A_48D399A20288_var* function FindCurrent(const aTree : InevSimpleTree; const aText : Il3CString): Il3SimpleNode; function FindCurr(const aIterNode: Il3SimpleNode): boolean; begin//FindCurr Result := l3Same(aIterNode.Text, aText, true); end;//FindCurr begin if (aTree = nil) then Result := nil else Result := aTree.SimpleIterateF(l3L2SNA(@FindCurr), imCheckResult); end; //#UC END# *48D37D66029A_48D399A20288_var* begin //#UC START# *48D37D66029A_48D399A20288_impl* f_LastGoodContext := nil; f_InputWithTree := False; if ComboReq.IsContext then begin if byUser then f_ShowHistoryList := True; if f_ShowHistoryList then begin MakeNodesFromItems; ChangeDropTreeForHistory(True); SetRootNode(f_HistoryRoot); f_SelectedValue := FindCurrent(f_Tree, Get_Caption); end else begin ChangeDropTreeForHistory(False); f_RootNode := nil; end; end else begin DropContainer.DropTextStyle := evd_saGUI; DropContainer.AllowEmptyCurrent := False; end; DropContainer.DoDrop(aPoint, AInvert, AWidth, ByUser); if not ComboReq.IsContext or f_ShowHistoryList then if (f_SelectedValue <> nil) and not f_IsAsterisk then DropContainer.Current := f_Tree.GetIndex(f_SelectedValue); inherited; //#UC END# *48D37D66029A_48D399A20288_impl* end;//TevDropCombo.DoDrop function TevDropCombo.Get_IsLogicalStateButtonEnabled: Boolean; //#UC START# *50F01D1902E4_48D399A20288get_var* var l_Control : IevEditorControl; l_BTN : IevEditorStateButton; //#UC END# *50F01D1902E4_48D399A20288get_var* begin //#UC START# *50F01D1902E4_48D399A20288get_impl* Result := False; l_Control := FindButton(ev_btLogical); if (l_Control <> nil) and Supports(l_Control, IevEditorStateButton, l_BTN) then try Result := l_BTN.Enabled; finally l_Control := nil; end; //#UC END# *50F01D1902E4_48D399A20288get_impl* end;//TevDropCombo.Get_IsLogicalStateButtonEnabled procedure TevDropCombo.SetMaskText(const aText: Il3CString); //#UC START# *54E2F4B6034D_48D399A20288_var* //#UC END# *54E2F4B6034D_48D399A20288_var* begin //#UC START# *54E2F4B6034D_48D399A20288_impl* inherited SetText(aText); // - http://mdp.garant.ru/pages/viewpage.action?pageId=588810734 // Чтобы не было поиска ноды с совпадающим текстом, // ибо в случае с маской её скорее всего не будет, а перебрать может // потребоваться немало //#UC END# *54E2F4B6034D_48D399A20288_impl* end;//TevDropCombo.SetMaskText procedure TevDropCombo.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48D399A20288_var* //#UC END# *479731C50290_48D399A20288_var* begin //#UC START# *479731C50290_48D399A20288_impl* f_ItemCachedText := nil; f_SelectedValue := nil; f_RootNode := nil; f_Tree := nil; f_LastGoodContext := nil; f_HistoryRoot := nil; f_PromptTree := nil; f_SavedText := nil; inherited; //#UC END# *479731C50290_48D399A20288_impl* end;//TevDropCombo.Cleanup constructor TevDropCombo.Create(const aPara: InevPara); //#UC START# *47CFE07602FE_48D399A20288_var* //#UC END# *47CFE07602FE_48D399A20288_var* begin //#UC START# *47CFE07602FE_48D399A20288_impl* inherited; f_ComboStyle := ev_cbFilterable; f_Asterisk := #0; f_IsAsterisk := False; f_IsAsteriskLastChar := False; //#UC END# *47CFE07602FE_48D399A20288_impl* end;//TevDropCombo.Create procedure TevDropCombo.SetText(const Value: Il3CString); //#UC START# *48D148F7020F_48D399A20288_var* //#UC END# *48D148F7020F_48D399A20288_var* begin //#UC START# *48D148F7020F_48D399A20288_impl* inherited SetText(Value); // это нужно для того, чтобы в DropCombo можно было присваивать текст. // K: 371630544 if Value <> nil then DoSynchronizeSelectedValueWithText; //#UC END# *48D148F7020F_48D399A20288_impl* end;//TevDropCombo.SetText procedure TevDropCombo.DoTextChange(const aView: InevView; const aPara: InevPara; const anOp: InevOp); //#UC START# *48D14C0E023E_48D399A20288_var* var l_Cap : Il3CString; //#UC END# *48D14C0E023E_48D399A20288_var* begin //#UC START# *48D14C0E023E_48D399A20288_impl* if l3IsNil(Get_Caption) then f_SelectedValue := nil; if f_NeedAdd then begin f_NeedAdd := false; Get_Req.AddField(aView, True); end//f_NeedAdd else if ComboReq.IsContext then begin if not Get_Req.QueryCard.InsertRowMode then Change(aView, aPara); end else if f_ComboStyle <> ev_cbDropDown then if not Get_Req.QueryCard.InsertRowMode then begin with DropContainer do begin if not IsDropTreeVisible then begin DropDown(aView, aPara, False); // http://mdp.garant.ru/pages/viewpage.action?pageId=227478809&focusedCommentId=227967079#comment-227967079 // Старый код: (* if not l3IsNil(Get_Caption) then f_SelectedValue := nil;*) // Новый код: l_Cap := Get_Caption; if l3IsNil(l_Cap) then f_SelectedValue := nil else if (f_SelectedValue <> nil) then if not l3Same(l_Cap, f_SelectedValue.Text) then f_SelectedValue := nil; f_InputWithTree := True; //Именно здесь, т.к. в предыдущем вызове флаг обнуляется end;//not IsDropTreeVisible CheckAsterisk; Change(aView, aPara); end;//with DropContainer end;//not Get_Req.QueryCard.InsertRowMode inherited; //#UC END# *48D14C0E023E_48D399A20288_impl* end;//TevDropCombo.DoTextChange procedure TevDropCombo.DoInsertRow(const aView: InevView); //#UC START# *48D14FA70154_48D399A20288_var* //#UC END# *48D14FA70154_48D399A20288_var* begin //#UC START# *48D14FA70154_48D399A20288_impl* Get_Req.AddField(aView, True); //#UC END# *48D14FA70154_48D399A20288_impl* end;//TevDropCombo.DoInsertRow procedure TevDropCombo.AfterSetText(const Value: Il3CString); //#UC START# *48D247CA0077_48D399A20288_var* //#UC END# *48D247CA0077_48D399A20288_var* begin //#UC START# *48D247CA0077_48D399A20288_impl* Get_Req.AfterSetText(Self); inherited; //#UC END# *48D247CA0077_48D399A20288_impl* end;//TevDropCombo.AfterSetText function TevDropCombo.GetSelectAllOnFocus: Boolean; //#UC START# *48D249F00054_48D399A20288_var* //#UC END# *48D249F00054_48D399A20288_var* begin //#UC START# *48D249F00054_48D399A20288_impl* Result := not ComboReq.IsContext and inherited GetSelectAllOnFocus; //#UC END# *48D249F00054_48D399A20288_impl* end;//TevDropCombo.GetSelectAllOnFocus procedure TevDropCombo.DoClearText; //#UC START# *48D24C9F02F5_48D399A20288_var* var l_DN : InevSimpleNode; //#UC END# *48D24C9F02F5_48D399A20288_var* begin //#UC START# *48D24C9F02F5_48D399A20288_impl* inherited; f_SelectedValue := nil; l_DN := Get_DefaultNode; if (l_DN <> nil) then ShowNode(l_DN); //#UC END# *48D24C9F02F5_48D399A20288_impl* end;//TevDropCombo.DoClearText function TevDropCombo.DoAnalyzeString(const aValue: Il3CString; aPos: Integer; out aRslt: Il3CString): Boolean; //#UC START# *48D24F5F02BF_48D399A20288_var* const cZ = cc_Austerisk; function WasAteriks: Boolean; var l_Text : Il3CString; begin//WasAteriks l_Text := Get_Caption; if ComboReq.IsContext then begin if l3Same(aValue, cZ) then begin if (aPos >= 0) then Result := l3IsChar(l_Text, aPos, cZ) else Result := true; if not Result then Result := (aPos > 0) and l3IsChar(l_Text, aPos - 1, cZ); if not Result then Result := l3IsChar(l_Text, aPos + 1, cZ); end//l3Same(aValue, cZ) else Result := False; end//ComboReq.IsContext else Result := l3Same(aValue, cZ) and (l3Pos(l_Text, cZ) <> l3NotFound); end;//WasAteriks //#UC END# *48D24F5F02BF_48D399A20288_var* begin //#UC START# *48D24F5F02BF_48D399A20288_impl* Result := false; if f_IsAsterisk then if l3IsNil(Get_Caption) then f_IsAsterisk := false; // - ну не бывает в ПУСТОЙ строке никаких звездочек if (Get_Req.Para.AsObject.BoolA[k2_tiNumList] and f_IsAsterisk) then begin Result := True; if f_IsAsterisk then if l3Same(aValue, cZ) then aRslt := nil; f_NeedAdd := False; end//Get_Req.Para.BoolA[k2_tiNumList] and f_IsAsterisk else if WasAteriks then // f_IsAsterisk - выставляется только для полей IsNumList begin Result := True; aRslt := nil; f_NeedAdd := False; end//WasAteriks else if l3Same(aValue, ';') then begin Result := True; aRslt := nil; f_NeedAdd := True; end//l3Same(aValue, ';') else if ComboReq.IsContext then Result := Get_Req.AnalyzeString(aValue, aRslt); //#UC END# *48D24F5F02BF_48D399A20288_impl* end;//TevDropCombo.DoAnalyzeString procedure TevDropCombo.DoEscPressed; //#UC START# *48D3824000D5_48D399A20288_var* //#UC END# *48D3824000D5_48D399A20288_var* begin //#UC START# *48D3824000D5_48D399A20288_impl* ComboReq.EscPressed(Self); if ComboReq.IsContext and not f_ShowHistoryList then begin Inc(f_LockShowPrompts); try DoSetCOntextText(f_SavedText); finally Dec(f_LockShowPrompts); end; end; //#UC END# *48D3824000D5_48D399A20288_impl* end;//TevDropCombo.DoEscPressed procedure TevDropCombo.DoDropDownCurrentChanged(const aNode: InevSimpleNode); //#UC START# *48D38273036D_48D399A20288_var* //#UC END# *48D38273036D_48D399A20288_var* begin //#UC START# *48D38273036D_48D399A20288_impl* if ComboReq.IsContext and not f_ShowHistoryList then begin f_LockSaveText := True; try if Assigned(aNode) then DoSetCOntextText(getFullPath(aNode)) else DoSetCOntextText(f_SavedText); finally f_LockSaveText := False; end;//try..finally end;//ComboReq.IsContext and not f_ShowHistoryList //#UC END# *48D38273036D_48D399A20288_impl* end;//TevDropCombo.DoDropDownCurrentChanged procedure TevDropCombo.DoAfterHideControl; //#UC START# *48D382AA012A_48D399A20288_var* //#UC END# *48D382AA012A_48D399A20288_var* begin //#UC START# *48D382AA012A_48D399A20288_impl* ChooseMean(False); Get_Req.UpdateState(Self, nil); if (Get_DefaultNode <> nil) and (Get_Value = nil) then ShowNode(Get_DefaultNode); //#UC END# *48D382AA012A_48D399A20288_impl* end;//TevDropCombo.DoAfterHideControl procedure TevDropCombo.DoSynchronizeSelectedValueWithText; //#UC START# *4E93093B00C1_48D399A20288_var* function FindCurrent(const aTree : InevSimpleTree; const aText : Il3CString): Il3SimpleNode; function FindCurr(const aIterNode: Il3SimpleNode): boolean; begin//FindCurr Result := l3Same(l3GetFullPathCStr(aTree.RootNode, aIterNode), aText, true); //Result := l3Same(aIterNode.Text, aText, true); end;//FindCurr begin if (aTree = nil) then Result := nil else Result := aTree.SimpleIterateF(l3L2SNA(@FindCurr), imCheckResult); end; var l_Text: Il3CString; //#UC END# *4E93093B00C1_48D399A20288_var* begin //#UC START# *4E93093B00C1_48D399A20288_impl* inherited; // http://mdp.garant.ru/pages/viewpage.action?pageId=290952615 // http://mdp.garant.ru/pages/viewpage.action?pageId=290951667&focusedCommentId=290953794#comment-290953794 if not f_TreeInit then InitTree; l_Text := Get_Caption; if l3IsNil(l_Text) then f_SelectedValue := nil else if not (Assigned(f_SelectedValue) and l3Same(l_Text, f_SelectedValue.Text)) then f_SelectedValue := FindCurrent(f_Tree, l_Text); if not (l3IsNil(l_Text) and (f_SelectedValue = nil)) then // почему бы и не разрешить пустое значение if f_InputWithTree then // этот if вырос вот отсюда: http://mdp.garant.ru/pages/viewpage.action?pageId=508186273&focusedCommentId=509115803#comment-509115803 Assert((f_Tree = nil) or (f_SelectedValue <> nil)); // - либо это атрибут без словаря, либо значение должно найтись f_State := esCompleted; //#UC END# *4E93093B00C1_48D399A20288_impl* end;//TevDropCombo.DoSynchronizeSelectedValueWithText end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpOSRandomNumberGenerator; {$I ..\..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpOSRandom, ClpIOSRandomNumberGenerator, ClpRandomNumberGenerator; type TOSRandomNumberGenerator = class sealed(TRandomNumberGenerator, IOSRandomNumberGenerator) public constructor Create(); procedure GetBytes(const data: TCryptoLibByteArray); override; procedure GetNonZeroBytes(const data: TCryptoLibByteArray); override; end; implementation { TOSRandomNumberGenerator } constructor TOSRandomNumberGenerator.Create; begin inherited Create(); end; procedure TOSRandomNumberGenerator.GetBytes(const data: TCryptoLibByteArray); begin TOSRandom.GetBytes(data); end; procedure TOSRandomNumberGenerator.GetNonZeroBytes(const data: TCryptoLibByteArray); begin TOSRandom.GetNonZeroBytes(data); end; end.
unit fpcorm_dbcore_utils; {< This unit contains helper/utility functions, for the fpcORM database object super classes. } {$mode objfpc}{$H+} interface uses Classes, SysUtils; { Prepares a data string for use, in a SQL statement. Also secures against SQL injection. @param(aString is any source string) @returns(A String, quoted for usage in an SQL statement and with all quote characters inside escaped.) } function ToSqlStr(aString: String): String; implementation function ToSqlStr(aString: String): String; begin { replace all occurrences of the string seperator char ' with two of them in order to avoid SQL injection. finally wrap the string with a quote character on each side. } Result := StringReplace(aString, '''', '''''', [rfReplaceAll]); Result := '''' + Result + ''''; end; end.
{ - | | --- | | ----- | | ------- | | --------- | | ----------- | | ------------- | | ======================================================= The objective is to move the 8 disks to the rightmost needle using the middle one as temporary stage, but ensuring that at any moment there is a bigger disks on top of a little one. movetower(n, 1, 3, 2) = movetower(n - 1, 1, 2, 3) movedisk(1, 3) movetower(n - 1, 2, 3, 1) INPUT: 3 OUTPUT: 1 -> 3 1 -> 2 3 -> 2 1 -> 3 2 -> 1 2 -> 3 1 -> 3 } program hanoi(input, output); (* ================== GLOBAL VARIABLES ================== *) var disks : integer; { Number of disks } procedure movetower(disks, from, destiny, temporary : integer); (* ================== NESTED PROCEDURES ================== *) procedure movedisk(initial_spot, final_spot : integer); begin writeln(initial_spot, ' => ', final_spot) end; begin if disks > 0 then begin movetower(disks - 1, from, temporary, destiny); movedisk(from, destiny); movetower(disks - 1, temporary, destiny, from) end end; begin writeln('Welcome to HANOI SOLVER 3000.'); write('Number of disks: '); read(disks); movetower(disks, 1, 3, 2) end.
unit GMServerRDOMger; interface uses GMServer, WinSockRDOConnectionsServer, RDOObjectProxy, RDOServer, RDOInterfaces, GMKernel; type TGMServerRDOMger = class public procedure SetupRDO( RDOPort : integer ); procedure DoneRDO; function GetIntServerConnection( ClientId : integer; ISId : integer; out RDOConnection : IRDOConnection ) : IIServerConnection; function GetGameMaster( ClientId : integer; GMId : integer; out RDOConnection : IRDOConnection ) : IGameMaster; private fRDOConnectionsServer : IRDOConnectionsServer; fRDOServer : TRDOServer; fGameMasterServer : TGMServer; public property GameMasterServer : TGMServer read fGameMasterServer; end; var TheRD0Mger : TGMServerRDOMger; procedure InitRD0Mger; procedure DneRD0Mger; implementation uses SysUtils, Logs; type TIServerConnection = class(TInterfacedObject, IIServerConnection) public constructor Create( aProxy : variant ); private function GameMasterMsg( ClientId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant; procedure GMNotify( ClientId : TCustomerId; notID : integer; Info : WideString ); private fProxy : variant; end; TGameMaster = class(TInterfacedObject, IGameMaster) public constructor Create( aProxy : variant ); private function AddCustomer( ISId : TIServerId; CustomerId : TCustomerId; ClientInfo : widestring ) : olevariant; procedure CustomerMsg( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString ); procedure UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId ); procedure UnRegisterIServer( aIsId : TIServerId ); private fProxy : variant; end; // TIServerConnection constructor TIServerConnection.Create( aProxy : variant ); begin inherited Create; fProxy := aProxy; end; function TIServerConnection.GameMasterMsg( ClientId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant; begin result := fProxy.GameMasterMsg( ClientId, Msg, Info ); end; procedure TIServerConnection.GMNotify( ClientId : TCustomerId; notID : integer; Info : WideString ); begin fProxy.GMNotify( ClientId, notID, Info ); end; // TGameMaster constructor TGameMaster.Create( aProxy : variant ); begin inherited Create; fProxy := aProxy; end; function TGameMaster.AddCustomer( ISId : TIServerId; CustomerId : TCustomerId; ClientInfo : widestring ) : olevariant; begin result := fProxy.AddCustomer( ISId, CustomerId, ClientInfo ); end; procedure TGameMaster.CustomerMsg( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString ); begin fProxy.CustomerMsg( ISId, CustomerId, Msg ); end; procedure TGameMaster.UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId ); begin fProxy.UnRegisterCustomer( ISId, aCustomerId ); end; procedure TGameMaster.UnRegisterIServer( aIsId : TIServerId ); begin fProxy.UnRegisterIServer( aIsId ); end; // TGMServerRDOMger procedure TGMServerRDOMger.SetupRDO( RDOPort : integer ); const MaxThreads = 5; // ? begin fGameMasterServer := TGMServer.Create; fRDOConnectionsServer := TWinSockRDOConnectionsServer.Create( RDOPort ); fRDOServer := TRDOServer.Create( fRDOConnectionsServer as IRDOServerConnection, MaxThreads, nil ); fRDOServer.RegisterObject( tidRDOHook_GMServer, integer(fGameMasterServer) ); fRDOConnectionsServer.StartListening; fRDOServer.OnClientDisconnect := fGameMasterServer.OnClientDisconnect; end; procedure TGMServerRDOMger.DoneRDO; begin fRDOConnectionsServer.StopListening; fRDOServer.Free; fGameMasterServer.Free; end; function TGMServerRDOMger.GetIntServerConnection( ClientId : integer; ISId : integer; out RDOConnection : IRDOConnection ) : IIServerConnection; var Proxy : variant; Connection : IRDOConnection; begin try Proxy := TRDOObjectProxy.Create as IDispatch; Connection := fRDOConnectionsServer.GetClientConnectionById( ClientId ); if Connection <> nil then begin Proxy.Timeout := 3*60*1000; Proxy.WaitForAnswer := false; Proxy.SetConnection( Connection ); Proxy.BindTo( ISId ); RDOConnection := Connection; result := TIServerConnection.Create( Proxy ); end else begin RDOConnection := nil; result := nil; end; except RDOConnection := nil; result := nil; end; end; function TGMServerRDOMger.GetGameMaster( ClientId : integer; GMId : integer; out RDOConnection : IRDOConnection ) : IGameMaster; var Proxy : variant; Connection : IRDOConnection; str : string; begin try Proxy := TRDOObjectProxy.Create as IDispatch; Connection := fRDOConnectionsServer.GetClientConnectionById( ClientId ); if Connection <> nil then begin Proxy.Timeout := 3*60*1000; Proxy.WaitForAnswer := false; Proxy.SetConnection( Connection ); Proxy.BindTo( GMId ); RDOConnection := Connection; result := TGameMaster.Create( Proxy ); end else begin try str := TObject(ClientId).ClassName; except str := 'NIENTE!!'; end; Log( getLogId, str + ' GetClientConnection failed for client address ' + IntToStr(ClientId) ); RDOConnection := nil; result := nil; end; except Log( getLogId, 'failure binding ' + IntToStr(ClientId) ); RDOConnection := nil; result := nil; end; end; procedure InitRD0Mger; begin TheRD0Mger := TGMServerRDOMger.Create; end; procedure DneRD0Mger; begin TheRD0Mger.Free; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: Delphi encapsulation for LIBEAY32.DLL (OpenSSL) This is only the subset needed by ICS. Creation: Jan 12, 2003 Version: 1.17 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list ics-ssl@elists.org Follow "SSL" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2003-2011 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> SSL implementation includes code written by Arno Garrels, Berlin, Germany, contact: <arno.garrels@gmx.de> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Dec 07, 2005 A. Garrels support of OSSL v0.9.8a added. New version check, see comments in source. In order to disable version check uncomment define NO_OSSL_VERSION_CHECK below and rebuild all. New functions OpenSslVersion, OpenSslCompilerFlags, OpenSslBuiltOn, OpenSslPlatForm, OpenSslDir all return a string type. Jan 27, 2006 A. Garrels, made BDS2006 (BCB & Pascal) compilers happy. Mar 03, 2006 A. Garrels: Added functions f_Ics_X509_get_notBefore, f_Ics_X509_get_notAfter, Asn1ToUTDateTime. Mar 03, 2007 A. Garrels: Small changes to support OpenSSL 0.9.8e. Read comments in OverbyteIcsSslDefs.inc. May 24, 2007 A.Garrels: Added code to handle ASN1 BMPString and Utf8 string types. Jun 30, 2008 A.Garrels made some changes to prepare code for Unicode. Jul 18, 2008 A. Garrels made some changes to get rid of some string cast warnings. Jun 05, 2008 A.Garrels revised Asn1ToString(), made some string casts explicit. Aug 19, 2008 A.Garrels checked against OpenSSL v0.9.8h and added that version as maximum version. Nov 17, 2008 A.Garrels checked against OpenSSL v0.9.8i and added that version as maximum version. Apr 10, 2009 A.Garrels checked against OpenSSL v0.9.8k and made it the maximum supported version. Sep 24, 2009 Arno - Use OverbyteIcsUtils.IcsBufferToHex() Nov 05, 2009 A.Garrels checked against OpenSSL v0.9.8L and made it the maximum supported version. OpenSSL V0.9.8L disables session renegotiation due to TLS renegotiation vulnerability. Dec 20, 2009 A.Garrels added plenty of stuff. Some is not yet used some is, like Server Name Indication (SNI) and an option to let OpenSSL use the default Delphi memory manager (both needs to be turned on in OverbyteIcsSslDefs.inc). May 07, 2010 A. Garrels moved declaration of size_t to OverbyteIcsTypes, changed user type CRYPTO_dynlock_value to use TRTLCriticalSection. May 08, 2010 Arno Garrels added support for OpenSSL 0.9.8n. In OSSL v0.9.8L and v0.9.8m renegotiation support was disabled due to vulnerability of the SSL protocol. In v0.9.8n renegotiation support was re-enabled and RFC5746 implemented but require the extension as needed. It's also possible to enable unsafe legacy renegotiation explicitly by setting new option sslOpt_ALLOW_UNSAFE_LEGACY_RENEGOTIATION of TSslContext. Apr 15, 2011 Arno prepared for 64-bit. Apr 23, 2011 Arno added support for OpenSSL 0.9.8r and 1.0.0d. Apr 24, 2011 Arno added some helper rountines since record TEVP_PKEY_st changed in 1.0.0 and had to be declared as dummy. May 03, 2011 Arno added some function declarations. May 08, 2011 Arno added function f_ERR_remove_thread_state new in v1.0.0+. May 17, 2011 Arno made one hack thread-safe and got rid of another hack with OSSL v1.0.0+. May 31, 2011 Arno changed the 64-bit hack in Ics_Ssl_EVP_PKEY_GetKey. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$WARN SYMBOL_DEPRECATED OFF} {$I OverbyteIcsDefs.inc} {$I OverbyteIcsSslDefs.inc} {$IFDEF COMPILER12_UP} { These are usefull for debugging !} {$WARN IMPLICIT_STRING_CAST OFF} {$WARN IMPLICIT_STRING_CAST_LOSS ON} {$WARN EXPLICIT_STRING_CAST OFF} {$WARN EXPLICIT_STRING_CAST_LOSS OFF} {$ENDIF} unit OverbyteIcsLIBEAY; interface {$IFDEF USE_SSL} uses {$IFDEF MSWINDOWS} Windows, {$ENDIF} OverbyteIcsTypes, // size_t {$IFDEF POSIX} PosixSysTypes, {$ENDIF} SysUtils, SyncObjs, OverbyteIcsSSLEAY; const IcsLIBEAYVersion = 117; CopyRight : String = ' IcsLIBEAY (c) 2003-2011 F. Piette V1.17 '; type EIcsLibeayException = class(Exception); TStatLockLockCallback = procedure(Mode : Integer; N : Integer; const _File : PAnsiChar; Line : Integer); cdecl; TStatLockIDCallback = function : Longword; cdecl; TCryptoThreadIDCallback = procedure (ID : PCRYPTO_THREADID) cdecl; TCRYPTO_dynlock_value_st = record Mutex : TRTLCriticalSection; end; PCRYPTO_dynlock_value = ^TCRYPTO_dynlock_value_st; CRYPTO_dynlock_value = TCRYPTO_dynlock_value_st; TDynLockCreateCallback = function(const _file : PAnsiChar; Line: Integer): PCRYPTO_dynlock_value; cdecl; TDynLockLockCallback = procedure(Mode : Integer; L : PCRYPTO_dynlock_value; _File : PAnsiChar; Line: Integer); cdecl; TDynLockDestroyCallback = procedure(L : PCRYPTO_dynlock_value; _File : PAnsiChar; Line: Integer); cdecl; const V_ASN1_UNIVERSAL = $00; V_ASN1_APPLICATION = $40; V_ASN1_CONTEXT_SPECIFIC = $80; V_ASN1_PRIVATE = $c0; V_ASN1_CONSTRUCTED = $20; V_ASN1_PRIMITIVE_TAG = $1f; V_ASN1_UNDEF = -1; V_ASN1_EOC = 0; V_ASN1_BOOLEAN = 1; V_ASN1_INTEGER = 2; V_ASN1_BIT_STRING = 3; V_ASN1_OCTET_STRING = 4; V_ASN1_NULL = 5; V_ASN1_OBJECT = 6; V_ASN1_OBJECT_DESCRIPTOR = 7; V_ASN1_EXTERNAL = 8; V_ASN1_REAL = 9; V_ASN1_ENUMERATED = 10; V_ASN1_UTF8STRING = 12; V_ASN1_SEQUENCE = 16; V_ASN1_SET = 17; V_ASN1_NUMERICSTRING = 18; { An ASN.1 NumericString object may represent any arbitrary string of numeric } { characters including the space character: 0,1,2,...,9,SPACE } V_ASN1_PRINTABLESTRING = 19; { An ASN.1 PrintableString may represent any arbitrary string of printable } { characters (A,B,...,Z; a,b,...,z; 0,1,...,9; space ' () + , - . / : = ?) } V_ASN1_T61STRING = 20; V_ASN1_TELETEXSTRING = 20; (* alias *) V_ASN1_VIDEOTEXSTRING = 21; V_ASN1_IA5STRING = 22; { An ASN.1 IA5String object may represent any arbitrary string of ASCII } { characters. The term IA5 denotes International Alphabet 5 (= ASCII). } V_ASN1_UTCTIME = 23; V_ASN1_GENERALIZEDTIME = 24; V_ASN1_GRAPHICSTRING = 25; V_ASN1_ISO64STRING = 26; V_ASN1_VISIBLESTRING = 26; (* alias *) V_ASN1_GENERALSTRING = 27; { The ASN.1 character string type GeneralString encompasses all registered } { graphic and character sets (see ISO 2375) plus SPACE and DELETE. } V_ASN1_UNIVERSALSTRING = 28; { UniversalString is defined in ASN.1:1993. } V_ASN1_BMPSTRING = 30; { BMPString is a subtype of the UniversalString type and models the Basic } { Multilingual Plane of ISO/IEC/ITU 10646-1, a two-octet (USC-2) encoding } { form, which is identical to Unicode 1.1. } {ERR_NUM_ERRORS = 10; ERR_TXT_MALLOCED = 1; } ERR_TXT_STRING = 2; { Changed from 32 in v0.9.7 up } ERR_R_FATAL = 64; // Libraries for SSLErr() { Currently not used, commented 12/07/05 ERR_LIB_NONE = 1; ERR_LIB_SYS = 2; ERR_LIB_BN = 3; ERR_LIB_RSA = 4; ERR_LIB_DH = 5; ERR_LIB_EVP = 6; ERR_LIB_BUF = 7; ERR_LIB_OBJ = 8; ERR_LIB_PEM = 9; ERR_LIB_DSA = 10; ERR_LIB_X509 = 11; ERR_LIB_METH = 12; ERR_LIB_ASN1 = 13; ERR_LIB_CONF = 14; ERR_LIB_CRYPTO = 15; ERR_LIB_SSL = 20; ERR_LIB_SSL23 = 21; ERR_LIB_SSL2 = 22; ERR_LIB_SSL3 = 23; ERR_LIB_RSAREF = 30; ERR_LIB_PROXY = 31; ERR_LIB_BIO = 32; ERR_LIB_PKCS7 = 33; ERR_LIB_X509V3 = 34; ERR_LIB_PKCS12 = 35; ERR_LIB_RAND = 36; ERR_LIB_DSO = 37; ERR_LIB_COMP = 41; ERR_LIB_USER = 128; } NID_undef = 0; //AG NID_rsaEncryption = 6; //AG NID_commonName = 13; //AG NID_countryName = 14; //AG NID_localityName = 15; //AG NID_stateOrProvinceName = 16; //AG NID_organizationName = 17; //AG NID_organizationalUnitName = 18; //AG NID_pkcs7 = 20; NID_pkcs7_data = 21; NID_pkcs7_signed = 22; NID_pkcs7_enveloped = 23; NID_pkcs7_signedAndEnveloped = 24; NID_pkcs7_digest = 25; NID_pkcs7_encrypted = 26; NID_pkcs9_emailAddress = 48; //AG NID_netscape = 57; NID_netscape_cert_extension = 58; NID_netscape_data_type = 59; NID_netscape_base_url = 72; NID_netscape_ca_revocation_url = 74; NID_netscape_cert_type = 71; NID_netscape_revocation_url = 73; NID_netscape_renewal_url = 75; NID_netscape_ca_policy_url = 76; NID_netscape_ssl_server_name = 77; NID_netscape_comment = 78; NID_netscape_cert_sequence = 79; NID_subject_key_identifier = 82; NID_key_usage = 83; NID_private_key_usage_period = 84; NID_subject_alt_name = 85; //AG NID_issuer_alt_name = 86; NID_basic_constraints = 87; NID_certificate_policies = 89; NID_crl_distribution_points = 103; //AG NID_dsa = 116; NID_ext_key_usage = 126; NID_X9_62_id_ecPublicKey = 408; { Asn1.h - For use with ASN1_mbstring_copy() } //AG MBSTRING_FLAG = $1000; //AG MBSTRING_ASC = MBSTRING_FLAG or 1; //AG MBSTRING_BMP = MBSTRING_FLAG or 2; //AG { 0.9.7 } MBSTRING_UNIV : Longword = MBSTRING_FLAG or 3; MBSTRING_UTF8 : Longword = MBSTRING_FLAG or 4; (* { 0.9.8 they are set dynamically on load } MBSTRING_UNIV = MBSTRING_FLAG or 4; //AG MBSTRING_UTF8 = MBSTRING_FLAG; //AG *) RSA_F4 = $10001; //AG EVP_PKEY_RSA = NID_rsaEncryption; //AG EVP_PKEY_DSA = NID_dsa; EVP_PKEY_EC = NID_X9_62_id_ecPublicKey; EVP_MAX_MD_SIZE = 64; //* longest known is SHA512 */ { Crypto.h - params for f_SSLeay_version() } SSLEAY_VERSION = 0; SSLEAY_OPTIONS = 1; //no longer supported SSLEAY_CFLAGS = 2; SSLEAY_BUILT_ON = 3; SSLEAY_PLATFORM = 4; SSLEAY_DIR = 5; // since 0.9.7 X509_V_OK = 0; // illegal error (for uninitialized values, to avoid X509_V_OK): 1 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2; X509_V_ERR_UNABLE_TO_GET_CRL = 3; X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4; X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5; X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6; X509_V_ERR_CERT_SIGNATURE_FAILURE = 7; X509_V_ERR_CRL_SIGNATURE_FAILURE = 8; X509_V_ERR_CERT_NOT_YET_VALID = 9; X509_V_ERR_CERT_HAS_EXPIRED = 10; X509_V_ERR_CRL_NOT_YET_VALID = 11; X509_V_ERR_CRL_HAS_EXPIRED = 12; X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13; X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14; X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15; X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16; X509_V_ERR_OUT_OF_MEM = 17; X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18; X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19; X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20; X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21; X509_V_ERR_CERT_CHAIN_TOO_LONG = 22; X509_V_ERR_CERT_REVOKED = 23; X509_V_ERR_INVALID_CA = 24; X509_V_ERR_PATH_LENGTH_EXCEEDED = 25; X509_V_ERR_INVALID_PURPOSE = 26; X509_V_ERR_CERT_UNTRUSTED = 27; X509_V_ERR_CERT_REJECTED = 28; // These are 'informational' when looking for issuer cert X509_V_ERR_SUBJECT_ISSUER_MISMATCH = 29; X509_V_ERR_AKID_SKID_MISMATCH = 30; X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 31; X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32; X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33; X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34; X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35; X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36; X509_V_ERR_INVALID_NON_CA = 37; X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED = 38; X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39; X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED = 40; X509_V_ERR_INVALID_EXTENSION = 41; X509_V_ERR_INVALID_POLICY_EXTENSION = 42; X509_V_ERR_NO_EXPLICIT_POLICY = 43; X509_V_ERR_UNNESTED_RESOURCE = 44; // The application is not happy X509_V_ERR_APPLICATION_VERIFICATION = 50; {$IFDEF OPENSSL_USE_RESOURCE_STRINGS} resourcestring { Verify error strings from x509_txt.c } sX509_V_OK = 'ok'; sX509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 'unable to get issuer certificate'; sX509_V_ERR_UNABLE_TO_GET_CRL = 'unable to get certificate CRL'; sX509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = 'unable to decrypt certificate''s signature'; sX509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 'unable to decrypt CRL''s signature'; sX509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 'unable to decode issuer public key'; sX509_V_ERR_CERT_SIGNATURE_FAILURE = 'certificate signature failure'; sX509_V_ERR_CRL_SIGNATURE_FAILURE = 'CRL signature failure'; sX509_V_ERR_CERT_NOT_YET_VALID = 'certificate is not yet valid'; sX509_V_ERR_CRL_NOT_YET_VALID = 'CRL is not yet valid'; sX509_V_ERR_CERT_HAS_EXPIRED = 'certificate has expired'; sX509_V_ERR_CRL_HAS_EXPIRED = 'CRL has expired'; sX509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 'format error in certificate''s notBefore field'; sX509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 'format error in certificate''s notAfter field'; sX509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 'format error in CRL''s lastUpdate field'; sX509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 'format error in CRL''s nextUpdate field'; sX509_V_ERR_OUT_OF_MEM = 'out of memory'; sX509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 'self signed certificate'; sX509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 'self signed certificate in certificate chain'; sX509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 'unable to get local issuer certificate'; sX509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 'unable to verify the first certificate'; sX509_V_ERR_CERT_CHAIN_TOO_LONG = 'certificate chain too long'; sX509_V_ERR_CERT_REVOKED = 'certificate revoked'; sX509_V_ERR_INVALID_CA = 'invalid CA certificate'; sX509_V_ERR_INVALID_NON_CA = 'invalid non-CA certificate (has CA markings)'; sX509_V_ERR_PATH_LENGTH_EXCEEDED = 'path length constraint exceeded'; sX509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED = 'proxy path length constraint exceeded'; sX509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED = 'proxy certificates not allowed, please set the appropriate flag'; sX509_V_ERR_INVALID_PURPOSE = 'unsupported certificate purpose'; sX509_V_ERR_CERT_UNTRUSTED = 'certificate not trusted'; sX509_V_ERR_CERT_REJECTED = 'certificate rejected'; sX509_V_ERR_APPLICATION_VERIFICATION = 'application verification failure'; sX509_V_ERR_SUBJECT_ISSUER_MISMATCH = 'subject issuer mismatch'; sX509_V_ERR_AKID_SKID_MISMATCH = 'authority and subject key identifier mismatch'; sX509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 'authority and issuer serial number mismatch'; sX509_V_ERR_KEYUSAGE_NO_CERTSIGN = 'key usage does not include certificate signing'; sX509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 'unable to get CRL issuer certificate'; sX509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 'unhandled critical extension'; sX509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 'key usage does not include CRL signing'; sX509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 'key usage does not include digital signature'; sX509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 'unhandled critical CRL extension'; sX509_V_ERR_INVALID_EXTENSION = 'invalid or inconsistent certificate extension'; sX509_V_ERR_INVALID_POLICY_EXTENSION = 'invalid or inconsistent certificate policy extension'; sX509_V_ERR_NO_EXPLICIT_POLICY = 'no explicit policy'; sX509_V_ERR_UNNESTED_RESOURCE = 'RFC 3779 resource not subset of parent''s resources'; sX509_V_ERR_NUMBER = 'Error number '; const {$ENDIF} { Lock IDs for use with CRYPTO_lock() } CRYPTO_LOCK_ERR = 1; CRYPTO_LOCK_EX_DATA = 2; CRYPTO_LOCK_X509 = 3; CRYPTO_LOCK_X509_INFO = 4; CRYPTO_LOCK_X509_PKEY = 5; CRYPTO_LOCK_X509_CRL = 6; CRYPTO_LOCK_X509_REQ = 7; CRYPTO_LOCK_DSA = 8; CRYPTO_LOCK_RSA = 9; CRYPTO_LOCK_EVP_PKEY = 10; CRYPTO_LOCK_X509_STORE = 11; CRYPTO_LOCK_SSL_CTX = 12; CRYPTO_LOCK_SSL_CERT = 13; CRYPTO_LOCK_SSL_SESSION = 14; CRYPTO_LOCK_SSL_SESS_CERT = 15; CRYPTO_LOCK_SSL = 16; CRYPTO_LOCK_SSL_METHOD = 17; CRYPTO_LOCK_RAND = 18; CRYPTO_LOCK_RAND2 = 19; CRYPTO_LOCK_MALLOC = 20; CRYPTO_LOCK_BIO = 21; CRYPTO_LOCK_GETHOSTBYNAME = 22; CRYPTO_LOCK_GETSERVBYNAME = 23; CRYPTO_LOCK_READDIR = 24; CRYPTO_LOCK_RSA_BLINDING = 25; CRYPTO_LOCK_DH = 26; CRYPTO_LOCK_MALLOC2 = 27; CRYPTO_LOCK_DSO = 28; CRYPTO_LOCK_DYNLOCK = 29; CRYPTO_LOCK_ENGINE = 30; CRYPTO_LOCK_UI = 31; CRYPTO_LOCK_ECDSA = 32; CRYPTO_LOCK_EC = 33; CRYPTO_LOCK_ECDH = 34; CRYPTO_LOCK_BN = 35; CRYPTO_LOCK_EC_PRE_COMP = 36; CRYPTO_LOCK_STORE = 37; CRYPTO_LOCK_COMP = 38; CRYPTO_LOCK_FIPS = 39; CRYPTO_LOCK_FIPS2 = 40; CRYPTO_NUM_LOCKS = 41; { mode param of CRYPTO_lock() } { These values are pairwise exclusive, with undefined behaviour if misused } {(for example, CRYPTO_READ and CRYPTO_WRITE should not be used together): } CRYPTO_LOCK = 1; CRYPTO_UNLOCK = 2; CRYPTO_READ = 4; CRYPTO_WRITE = 8; // Certificate verify flags // Send issuer+subject checks to verify_cb X509_V_FLAG_CB_ISSUER_CHECK = $1; // Use check time instead of current time X509_V_FLAG_USE_CHECK_TIME = $2; // Lookup CRLs X509_V_FLAG_CRL_CHECK = $4; // Lookup CRLs for whole chain X509_V_FLAG_CRL_CHECK_ALL = $8; // Ignore unhandled critical extensions X509_V_FLAG_IGNORE_CRITICAL = $10; // Disable workarounds for broken certificates X509_V_FLAG_X509_STRICT = $20; // Enable proxy certificate validation X509_V_FLAG_ALLOW_PROXY_CERTS = $40; //Purposes X509_PURPOSE_SSL_CLIENT = 1; X509_PURPOSE_SSL_SERVER = 2; X509_PURPOSE_NS_SSL_SERVER = 3; X509_PURPOSE_SMIME_SIGN = 4; X509_PURPOSE_SMIME_ENCRYPT = 5; X509_PURPOSE_CRL_SIGN = 6; X509_PURPOSE_ANY = 7; X509_PURPOSE_OCSP_HELPER = 8; X509_PURPOSE_MIN = 1; X509_PURPOSE_MAX = 8; {$IFNDEF OPENSSL_NO_ENGINE} //const // engine.h // //* These flags are used to control combinations of algorithm (methods) //* by bitwise "OR"ing. ENGINE_METHOD_RSA = $0001; ENGINE_METHOD_DSA = $0002; ENGINE_METHOD_DH = $0004; ENGINE_METHOD_RAND = $0008; ENGINE_METHOD_ECDH = $0010; ENGINE_METHOD_ECDSA = $0020; ENGINE_METHOD_CIPHERS = $0040; ENGINE_METHOD_DIGESTS = $0080; ENGINE_METHOD_STORE = $0100; //* Obvious all-or-nothing cases. */ ENGINE_METHOD_ALL = $FFFF; ENGINE_METHOD_NONE = $0000; //* Error codes for the ENGINE functions. */ //* Function codes. */ { ENGINE_F_DYNAMIC_CTRL = 180; ENGINE_F_DYNAMIC_GET_DATA_CTX = 181; ENGINE_F_DYNAMIC_LOAD = 182; ENGINE_F_DYNAMIC_SET_DATA_CTX = 183; ENGINE_F_ENGINE_ADD = 105; ENGINE_F_ENGINE_BY_ID = 106; ENGINE_F_ENGINE_CMD_IS_EXECUTABLE = 170; ENGINE_F_ENGINE_CTRL = 142; ENGINE_F_ENGINE_CTRL_CMD = 178; ENGINE_F_ENGINE_CTRL_CMD_STRING = 171; ENGINE_F_ENGINE_FINISH = 107; ENGINE_F_ENGINE_FREE_UTIL = 108; ENGINE_F_ENGINE_GET_CIPHER = 185; ENGINE_F_ENGINE_GET_DEFAULT_TYPE = 177; ENGINE_F_ENGINE_GET_DIGEST = 186; ENGINE_F_ENGINE_GET_NEXT = 115; ENGINE_F_ENGINE_GET_PREV = 116; ENGINE_F_ENGINE_INIT = 119; ENGINE_F_ENGINE_LIST_ADD = 120; ENGINE_F_ENGINE_LIST_REMOVE = 121; ENGINE_F_ENGINE_LOAD_PRIVATE_KEY = 150; ENGINE_F_ENGINE_LOAD_PUBLIC_KEY = 151; ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT = 192; ENGINE_F_ENGINE_NEW = 122; ENGINE_F_ENGINE_REMOVE = 123; ENGINE_F_ENGINE_SET_DEFAULT_STRING = 189; ENGINE_F_ENGINE_SET_DEFAULT_TYPE = 126; ENGINE_F_ENGINE_SET_ID = 129; ENGINE_F_ENGINE_SET_NAME = 130; ENGINE_F_ENGINE_TABLE_REGISTER = 184; ENGINE_F_ENGINE_UNLOAD_KEY = 152; ENGINE_F_ENGINE_UNLOCKED_FINISH = 191; ENGINE_F_ENGINE_UP_REF = 190; ENGINE_F_INT_CTRL_HELPER = 172; ENGINE_F_INT_ENGINE_CONFIGURE = 188; ENGINE_F_INT_ENGINE_MODULE_INIT = 187; ENGINE_F_LOG_MESSAGE = 141; } //* Reason codes. */ { ENGINE_R_ALREADY_LOADED = 100; ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER = 133; ENGINE_R_CMD_NOT_EXECUTABLE = 134; ENGINE_R_COMMAND_TAKES_INPUT = 135; ENGINE_R_COMMAND_TAKES_NO_INPUT = 136; ENGINE_R_CONFLICTING_ENGINE_ID = 103; ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED = 119; ENGINE_R_DH_NOT_IMPLEMENTED = 139; ENGINE_R_DSA_NOT_IMPLEMENTED = 140; ENGINE_R_DSO_FAILURE = 104; ENGINE_R_DSO_NOT_FOUND = 132; ENGINE_R_ENGINES_SECTION_ERROR = 148; ENGINE_R_ENGINE_IS_NOT_IN_LIST = 105; ENGINE_R_ENGINE_SECTION_ERROR = 149; ENGINE_R_FAILED_LOADING_PRIVATE_KEY = 128; ENGINE_R_FAILED_LOADING_PUBLIC_KEY = 129; ENGINE_R_FINISH_FAILED = 106; ENGINE_R_GET_HANDLE_FAILED = 107; ENGINE_R_ID_OR_NAME_MISSING = 108; ENGINE_R_INIT_FAILED = 109; ENGINE_R_INTERNAL_LIST_ERROR = 110; ENGINE_R_INVALID_ARGUMENT = 143; ENGINE_R_INVALID_CMD_NAME = 137; ENGINE_R_INVALID_CMD_NUMBER = 138; ENGINE_R_INVALID_INIT_VALUE = 151; ENGINE_R_INVALID_STRING = 150; ENGINE_R_NOT_INITIALISED = 117; ENGINE_R_NOT_LOADED = 112; ENGINE_R_NO_CONTROL_FUNCTION = 120; ENGINE_R_NO_INDEX = 144; ENGINE_R_NO_LOAD_FUNCTION = 125; ENGINE_R_NO_REFERENCE = 130; ENGINE_R_NO_SUCH_ENGINE = 116; ENGINE_R_NO_UNLOAD_FUNCTION = 126; ENGINE_R_PROVIDE_PARAMETERS = 113; ENGINE_R_RSA_NOT_IMPLEMENTED = 141; ENGINE_R_UNIMPLEMENTED_CIPHER = 146; ENGINE_R_UNIMPLEMENTED_DIGEST = 147; ENGINE_R_VERSION_INCOMPATIBILITY = 145; } {$ENDIF} //const BIO_CTRL_RESET = 1; // opt - rewind/zero etc BIO_CTRL_EOF = 2; // opt - are we at the eof BIO_CTRL_INFO = 3; // opt - extra tit-bits BIO_CTRL_SET = 4; // man - set the 'IO' type BIO_CTRL_GET = 5; // man - get the 'IO' type BIO_CTRL_PUSH = 6; // opt - internal, used to signify change BIO_CTRL_POP = 7; // opt - internal, used to signify change BIO_CTRL_GET_CLOSE = 8; // man - set the 'close' on free BIO_CTRL_SET_CLOSE = 9; // man - set the 'close' on free BIO_CTRL_PENDING = 10; // opt - is their more data buffered BIO_CTRL_FLUSH = 11; // opt - 'flush' buffered output BIO_CTRL_DUP = 12; // man - extra stuff for 'duped' BIO BIO_CTRL_WPENDING = 13; // opt - number of bytes still to write BIO_CTRL_SET_CALLBACK = 14; // opt - set callback function BIO_CTRL_GET_CALLBACK = 15; // opt - set callback function BIO_CTRL_SET_FILENAME = 30; // BIO_s_file special BIO_C_SET_CONNECT = 100; BIO_C_DO_STATE_MACHINE = 101; BIO_C_SET_NBIO = 102; BIO_C_SET_PROXY_PARAM = 103; BIO_C_SET_FD = 104; BIO_C_GET_FD = 105; BIO_C_SET_FILE_PTR = 106; BIO_C_GET_FILE_PTR = 107; BIO_C_SET_FILENAME = 108; BIO_C_SET_SSL = 109; BIO_C_GET_SSL = 110; BIO_C_SET_MD = 111; BIO_C_GET_MD = 112; BIO_C_GET_CIPHER_STATUS = 113; BIO_C_SET_BUF_MEM = 114; BIO_C_GET_BUF_MEM_PTR = 115; BIO_C_GET_BUFF_NUM_LINES = 116; BIO_C_SET_BUFF_SIZE = 117; BIO_C_SET_ACCEPT = 118; BIO_C_SSL_MODE = 119; BIO_C_GET_MD_CTX = 120; BIO_C_GET_PROXY_PARAM = 121; BIO_C_SET_BUFF_READ_DATA = 122; // data to read first BIO_C_GET_CONNECT = 123; BIO_C_GET_ACCEPT = 124; BIO_C_SET_SSL_RENEGOTIATE_BYTES = 125; BIO_C_GET_SSL_NUM_RENEGOTIATES = 126; BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT = 127; BIO_C_FILE_SEEK = 128; BIO_C_GET_CIPHER_CTX = 129; BIO_C_SET_BUF_MEM_EOF_RETURN = 130; // return end of input value BIO_C_SET_BIND_MODE = 131; BIO_C_GET_BIND_MODE = 132; BIO_C_FILE_TELL = 133; BIO_C_GET_SOCKS = 134; BIO_C_SET_SOCKS = 135; BIO_C_SET_WRITE_BUF_SIZE = 136; // for BIO_s_bio BIO_C_GET_WRITE_BUF_SIZE = 137; BIO_C_MAKE_BIO_PAIR = 138; BIO_C_DESTROY_BIO_PAIR = 139; BIO_C_GET_WRITE_GUARANTEE = 140; BIO_C_GET_READ_REQUEST = 141; BIO_C_SHUTDOWN_WR = 142; BIO_C_NREAD0 = 143; BIO_C_NREAD = 144; BIO_C_NWRITE0 = 145; BIO_C_NWRITE = 146; BIO_C_RESET_READ_REQUEST = 147; BIO_NOCLOSE = 0; BIO_CLOSE = 1; //const BIO_FLAGS_READ = 1; BIO_FLAGS_WRITE = 2; BIO_FLAGS_IO_SPECIAL = 4; BIO_FLAGS_RWS = (BIO_FLAGS_READ or BIO_FLAGS_WRITE or BIO_FLAGS_IO_SPECIAL); BIO_FLAGS_SHOULD_RETRY = 8; //const // These are passed by the BIO callback // BIO_CB_FREE = $01; BIO_CB_READ = $02; BIO_CB_WRITE = $03; BIO_CB_PUTS = $04; BIO_CB_GETS = $05; BIO_CB_CTRL = $06; // The callback is called before and after the underling operation, // The BIO_CB_RETURN flag indicates if it is after the call BIO_CB_RETURN = $80; //const X509V3_EXT_DYNAMIC = $1; X509V3_EXT_CTX_DEP = $2; X509V3_EXT_MULTILINE = $4; {$IFNDEF OPENSSL_NO_ENGINE} type TUi_method_st = record Dummy : array [0..0] of Byte; end; PUI_METHOD = ^TUi_method_st; TUi_st = record Dummy : array [0..0] of Byte; end; PUI = ^TUi_st; TUi_string_st = record Dummy : array [0..0] of Byte; end; PUI_STRING = ^TUi_string_st; TPinCallBack = function(ui: PUI; uis: PUI_STRING): Integer; cdecl; //AG {$ENDIF} {$IFDEF OPENSSL_USE_DELPHI_MM} type TCryptoMallocFunc = function(Size: size_t): Pointer; cdecl; TCryptoReallocFunc = function(P: Pointer; Size: size_t): Pointer; cdecl; TCryptoFreeMemFunc = procedure(P: Pointer); cdecl; {$ENDIF} const f_SSLeay : function: Longword; cdecl = nil; //AG f_SSLeay_version : function(t: Integer): PAnsiChar; cdecl = nil; //AG f_ERR_get_error_line_data : function(const FileName: PPAnsiChar; Line: PInteger; const Data: PPAnsiChar; Flags: PInteger): Cardinal; cdecl = nil; f_ERR_peek_error : function : Cardinal; cdecl = nil; f_ERR_peek_last_error : function : Cardinal; cdecl = nil; f_ERR_get_error : function: Cardinal; cdecl = nil; f_ERR_error_string : function(Err: Cardinal; Buf: PAnsiChar): PAnsiChar; cdecl = nil; f_ERR_error_string_n : procedure(Err: Cardinal; Buf: PAnsiChar; Len: size_t); cdecl = nil; f_ERR_clear_error : procedure; cdecl = nil; //empties the current thread's error queue { Note that ERR_remove_state() is now deprecated, because it is tied to the assumption that thread IDs are numeric. ERR_remove_state(0) to free the current thread's error state should be replaced by ERR_remove_thread_state(nil). } f_ERR_remove_state : procedure(ThreadID: Longword); cdecl = nil; { Next is v1.0.0+ ** check for nil ** } f_ERR_remove_thread_state : procedure(tid: PCRYPTO_THREADID); cdecl = nil; f_ERR_free_strings : procedure; cdecl = nil; //"Brutal" (thread-unsafe) Application-global cleanup functions f_RAND_seed : procedure(Buf: Pointer; Num: Integer); cdecl = nil; f_BIO_new : function(BioMethods: PBIO_METHOD): PBIO; cdecl = nil; f_BIO_new_socket : function(Sock: Integer; CloseFlag: Integer): PBIO; cdecl = nil; f_BIO_new_fd : function(Fd: Integer; CloseFlag: Integer): PBIO; cdecl = nil; f_BIO_new_file : function(FileName: PAnsiChar; Mode: PAnsiChar): PBIO; cdecl = nil; f_BIO_new_mem_buf : function(Buf : Pointer; Len : Integer): PBIO; cdecl = nil; f_BIO_new_bio_pair : function(Bio1: PPBIO; WriteBuf1: size_t; Bio2: PPBIO; WriteBuf2: size_t): Integer; cdecl = nil; f_BIO_ctrl : function(bp: PBIO; Cmd: Integer; LArg: LongInt; PArg: Pointer): LongInt; cdecl = nil; f_BIO_ctrl_pending : function(b: PBIO): size_t; cdecl = nil; f_BIO_ctrl_get_write_guarantee : function(b: PBIO): size_t; cdecl = nil; f_BIO_ctrl_get_read_request : function(b: PBIO): size_t; cdecl = nil; f_BIO_s_mem : function : PBIO_METHOD; cdecl = nil; f_BIO_get_retry_BIO : function(B: PBIO; Reason : PInteger): PBIO; cdecl = nil; f_BIO_get_retry_reason : function(B: PBIO): Integer; cdecl = nil; f_BIO_free : function(B: PBIO): Integer; cdecl = nil; f_BIO_read : function(B: PBIO; Buf: Pointer; Len: Integer): Integer; cdecl = nil; f_BIO_nread : function(B: PBIO; PBuf: PPAnsiChar; Num: Integer): Integer; cdecl = nil; f_BIO_nread0 : function(B: PBIO; PBuf: PPAnsiChar): Integer; cdecl = nil; f_BIO_nwrite : function(B: PBIO; PBuf: PPAnsiChar; Num: Integer): Integer; cdecl = nil; f_BIO_nwrite0 : function(B: PBIO; PBuf: PPAnsiChar): Integer; cdecl = nil; f_BIO_gets : function(B: PBIO; Buf: PAnsiChar; Size: Integer): Integer; cdecl = nil; f_BIO_puts : function(B: PBIO; Buf: PAnsiChar): Integer; cdecl = nil; f_BIO_push : function(B: PBIO; B_Append: PBIO): PBIO; cdecl = nil; f_BIO_write : function(B: PBIO; Buf: Pointer; Len: Integer): Integer; cdecl = nil; f_d2i_X509_bio : function(B: PBIO; X509: PPX509): PX509; cdecl = nil; f_i2d_X509_bio : function(B: PBIO; X509: PX509): Integer; cdecl = nil; f_d2i_PrivateKey_bio : function(B: PBIO; A: PPEVP_PKEY): PEVP_PKEY; cdecl = nil;//AG f_i2d_PrivateKey_bio : function(B: PBIO; pkey: PEVP_PKEY): Integer; cdecl = nil;//AG f_d2i_X509 : function(C509: PPX509; Buf: PPAnsiChar; Len: Integer): PX509; cdecl = nil; f_d2i_PKCS12_bio : function(B: PBIO; p12: PPPKCS12): PPKCS12; cdecl = nil; //AG f_i2d_PKCS12_bio : function(B: PBIO; p12: PPKCS12): Integer; cdecl = nil; f_d2i_PKCS7_bio: function(B: PBIO; p7: PPKCS7): PPKCS7; cdecl = nil; //AG f_CRYPTO_lock : procedure(mode, n: Longint; file_: PAnsiChar; line: Longint); cdecl = nil; //AG f_CRYPTO_add_lock : procedure(IntPtr: PInteger; amount: Integer; type_: Integer; const file_ : PAnsiChar; line: Integer); cdecl = nil; f_CRYPTO_num_locks : function: Integer; cdecl = nil; f_CRYPTO_set_id_callback : procedure(CB : TStatLockIDCallback); cdecl = nil; { Next three functions are v1.0.0+ only. ** Check for nil at runtime ** } f_CRYPTO_THREADID_set_callback : function(CB : TCryptoThreadIDCallback) : Integer; cdecl = nil; // Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks f_CRYPTO_THREADID_set_numeric : procedure(id : PCRYPTO_THREADID; val: LongWord); cdecl = nil; f_CRYPTO_THREADID_set_pointer : procedure(id : PCRYPTO_THREADID; ptr: Pointer); cdecl = nil; f_CRYPTO_set_locking_callback : procedure(CB : TStatLockLockCallback); cdecl = nil; f_CRYPTO_set_dynlock_create_callback : procedure(CB : TDynLockCreateCallBack); cdecl = nil; f_CRYPTO_set_dynlock_lock_callback : procedure(CB : TDynLockLockCallBack); cdecl = nil; f_CRYPTO_set_dynlock_destroy_callback : procedure(CB : TDynLockDestroyCallBack); cdecl = nil; {$IFDEF OPENSSL_USE_DELPHI_MM} f_CRYPTO_set_mem_functions : function(M: TCryptoMallocFunc; R: TCryptoReallocFunc; F: TCryptoFreeMemFunc): Integer; cdecl = nil; //AG {$ENDIF} f_CRYPTO_cleanup_all_ex_data : procedure; cdecl = nil; f_X509_dup : function(X: PX509): PX509; cdecl = nil;//AG; f_X509_check_ca : function(X: PX509): Integer; cdecl = nil;//AG; f_X509_STORE_new : function: PX509_STORE; cdecl = nil;//AG; f_X509_STORE_free : procedure(Store: PX509_STORE); cdecl = nil;//AG; f_X509_STORE_add_cert : function(Store: PX509_STORE; Cert: PX509): Integer; cdecl = nil;//AG; f_X509_STORE_add_crl : function(Store: PX509_STORE; CRL: PX509_CRL): Integer; cdecl = nil;//AG; f_X509_STORE_add_lookup : function(Store: PX509_STORE; Meth: PX509_LOOKUP_METHOD): PX509_LOOKUP; cdecl = nil;//AG; f_X509_STORE_set_flags : procedure(Store: PX509_STORE; Flags: Longword); cdecl = nil;//AG; f_X509_STORE_CTX_new : function: PX509_STORE_CTX; cdecl = nil;//AG; f_X509_STORE_CTX_free : procedure(Ctx: PX509_STORE_CTX); cdecl = nil;//AG; f_X509_STORE_CTX_init : function(Ctx: PX509_STORE_CTX; Store: PX509_STORE; Cert: PX509; UnTrustedChain: PSTACK_OF_X509): Integer; cdecl = nil;//AG; f_X509_STORE_CTX_cleanup : procedure(Ctx: PX509_STORE_CTX); cdecl = nil;//AG; f_X509_STORE_CTX_get_ex_data : function(Ctx: PX509_STORE_CTX; Idx: Integer): Pointer; cdecl = nil; f_X509_STORE_CTX_get_current_cert : function(Ctx: PX509_STORE_CTX): PX509; cdecl = nil; f_X509_STORE_CTX_get_error : function(Ctx: PX509_STORE_CTX): Integer; cdecl = nil; f_X509_STORE_CTX_set_error : procedure(Ctx: PX509_STORE_CTX; s: Integer); cdecl = nil; f_X509_STORE_CTX_get_error_depth : function(Ctx: PX509_STORE_CTX): Integer; cdecl = nil; f_X509_STORE_CTX_get_chain : function(Ctx: PX509_STORE_CTX): PSTACK_OF_X509; cdecl = nil;//AG; f_X509_STORE_CTX_trusted_stack : procedure(Ctx: PX509_STORE_CTX; STACK_OF_X509: PSTACK_OF_X509); cdecl = nil;//AG; f_X509_STORE_CTX_set_purpose : function(Ctx: PX509_STORE_CTX; Purpose: Integer): Integer; cdecl = nil;//AG; f_X509_STORE_CTX_set_verify_cb : procedure(Ctx: PX509_STORE_CTX; Cb: TSetVerify_cb); cdecl = nil;//AG; f_X509_STORE_CTX_set_ex_data : function(Ctx: PX509_STORE_CTX; Idx: Integer; Data: Pointer): Integer; cdecl = nil;//AG; f_X509_load_crl_file : function(Ctx: PX509_LOOKUP; const Filename: PAnsiChar; type_: Integer): Integer; cdecl = nil;//AG; f_X509_LOOKUP_file : function: PX509_LOOKUP_METHOD; cdecl = nil;//AG; f_X509_LOOKUP_hash_dir : function: PX509_LOOKUP_METHOD; cdecl = nil;//AG; f_X509_LOOKUP_new : function(Method: PX509_LOOKUP_METHOD): PX509_LOOKUP; cdecl = nil;//AG; f_X509_LOOKUP_free : procedure(Ctx: PX509_LOOKUP); cdecl = nil;//AG; f_X509_LOOKUP_by_issuer_serial : function(Ctx: PX509_LOOKUP; Typ_: Integer; Name: PX509_NAME; Serial: PASN1_INTEGER; Ret: PX509_OBJECT): Integer; cdecl = nil;//AG; f_X509_LOOKUP_by_fingerprint : function(Ctx: PX509_LOOKUP; Typ_: Integer; Bytes: PAnsiChar; Len: Integer; Ret: PX509_OBJECT ): Integer; cdecl = nil;//AG; f_X509_LOOKUP_ctrl : function(Ctx: PX509_LOOKUP; Cmd: Integer; Argc: PAnsiChar; Argl: Cardinal; Ret: PPAnsiChar): Integer; cdecl = nil;//AG; f_X509_check_issued : function(Issuer: PX509; Subject: PX509): Integer; cdecl = nil;//AG; f_X509_verify_cert : function(Ctx: PX509_STORE_CTX): Integer; cdecl = nil;//AG; f_X509_verify_cert_error_string : function(ErrCode : Integer): PAnsiChar; cdecl = nil; f_X509_get_issuer_name : function(Cert: PX509): PX509_NAME; cdecl = nil; f_X509_get_subject_name : function(Cert: PX509): PX509_NAME; cdecl = nil; f_X509_get_serialNumber : function(Cert: PX509): PASN1_INTEGER; cdecl = nil; f_X509_NAME_oneline : function(CertName: PX509_NAME; Buf: PAnsiChar; BufSize: Integer): PAnsiChar; cdecl = nil; f_X509_NAME_get_text_by_NID : function(CertName: PX509_NAME; Nid: Integer; Buf : PAnsiChar; Len : Integer): Integer; cdecl = nil; f_X509_NAME_get_index_by_NID: function(CertName: PX509_NAME; Nid: Integer; LastPos: Integer): Integer; cdecl = nil; //AG f_X509_NAME_free : procedure(AName: PX509_NAME); cdecl = nil;//AG; f_X509_NAME_cmp : function(const a: PX509_NAME; const b: PX509_NAME): Integer; cdecl = nil;//AG; f_X509_get_ext : function(Cert: PX509; Loc : Integer): PX509_EXTENSION; cdecl = nil; f_X509_get_ext_count : function(Cert: PX509): Integer; cdecl = nil; f_X509_free : procedure(Cert: PX509); cdecl = nil; f_X509_CRL_free : procedure(CRL: PX509_CRL); cdecl = nil;//AG f_X509V3_EXT_get : function(Ext: PX509_EXTENSION): PX509V3_EXT_METHOD; cdecl = nil; f_X509V3_EXT_print : function(B: PBIO; Ext: PX509_EXTENSION; Flag: Integer; Indent: Integer):Integer; cdecl = nil;//AG; f_X509V3_EXT_d2i : function(Ext: PX509_EXTENSION): Pointer; cdecl = nil;//AG; f_X509V3_conf_free : procedure(Val: PCONF_VALUE); cdecl = nil;//AG f_X509_EXTENSION_get_object : function(Ext: PX509_EXTENSION): PASN1_OBJECT; cdecl = nil; f_X509_EXTENSION_get_data : function(Ext : PX509_EXTENSION): PASN1_OCTET_STRING; cdecl = nil;//AG; f_X509_EXTENSION_get_critical : function(Ext: PX509_EXTENSION): Integer; cdecl = nil;//AG; f_X509_subject_name_hash : function(Cert: PX509): Cardinal; cdecl = nil; f_X509_print : function(B: PBIO; Cert: PX509): Integer; cdecl = nil; f_X509_digest : function(Cert: PX509; Type_: PEVP_MD; Buf: PAnsiChar; BufSize: PInteger): Integer; cdecl = nil; //AG f_X509_check_private_key : function(Cert: PX509; PKey: PEVP_PKEY): Integer; cdecl = nil; //AG f_EVP_sha1 : function: PEVP_MD; cdecl = nil;//AG f_EVP_sha256 : function: PEVP_MD; cdecl = nil;//AG f_EVP_md5 : function: PEVP_MD; cdecl = nil;//AG f_EVP_PKEY_free : procedure(PKey: PEVP_PKEY); cdecl = nil;//AG { Next is v1.0.0+ ** check for nil ** } f_EVP_PKEY_get0 : function(PKey: PEVP_PKEY): Pointer; cdecl = nil;//AG f_EVP_PKEY_new : function: PEVP_PKEY; cdecl = nil;//AG f_EVP_PKEY_assign : function(PKey: PEVP_PKEY; Type_: Integer; Key: PAnsiChar): Integer; cdecl = nil;//AG f_EVP_PKEY_size : function(Pkey: PEVP_PKEY): Integer; cdecl = nil;//AG f_EVP_PKEY_bits : function(Pkey: PEVP_PKEY): Integer; cdecl = nil;//AG f_EVP_get_cipherbyname : function(name: PAnsiChar): PEVP_CIPHER; cdecl = nil;//AG f_EVP_des_ede3_cbc : function: PEVP_CIPHER; cdecl = nil;//AG f_EVP_cleanup : procedure; cdecl = nil; f_RSA_generate_key : function(Num: Integer; E: Cardinal; CallBack: TRSA_genkey_cb; cb_arg: Pointer): PRSA; cdecl = nil;//AG f_RSA_print : function(B: PBIO; Rsa: PRSA; Offset: Integer): Integer; cdecl = nil;//AG; f_DSA_print : function(B: PBIO; Dsa: PDSA; Offset: Integer): Integer; cdecl = nil;//AG; f_EC_KEY_print : function(B: PBIO; const EC: PEC_KEY; Offset: Integer): Integer; cdecl = nil;//AG; f_OBJ_nid2sn : function(N: Integer): PAnsiChar; cdecl = nil; f_OBJ_nid2ln : function(N: Integer): PAnsiChar; cdecl = nil; f_OBJ_obj2nid : function(O: PASN1_OBJECT): Integer; cdecl = nil; f_sk_num : function(Stack: PSTACK): Integer; cdecl = nil; f_sk_value : function(Stack: PSTACK; Item: Integer): PAnsiChar; cdecl = nil; f_sk_new_null: function: PSTACK; cdecl = nil;//AG; { This function free()'s a stack structure. The elements in the stack will not be freed } f_sk_free : procedure(Stack: PSTACK); cdecl = nil;//AG; { This function calls 'func' for each element on the stack, passing the element as the argument. sk_free() is then called to free the 'stack' structure.} f_sk_pop_free : procedure(Stack: PSTACK; PFreeProc: Pointer); cdecl = nil;//AG; { Append 'data' to the stack. 0 is returned if there is a failure (due to a malloc failure), else 1 } f_sk_push : function(Stack: PSTACK; Data: PAnsiChar): Integer; cdecl = nil;//AG; { Remove the item at location 'loc' from the stack and returns it. Returns NULL if the 'loc' is out of range } f_sk_delete : function(Stack: PSTACK; Item: Integer): PAnsiChar; cdecl = nil;//AG; { Return and delete the last element on the stack } f_sk_pop : function(Stack: PSTACK): PAnsiChar; cdecl = nil;//AG; f_sk_find : function(Stack: PSTACK; Data: PAnsiChar): Integer; cdecl = nil;//AG; f_sk_insert : function(Stack: PSTACK; Data: PAnsiChar; Index: Integer): Integer; cdecl = nil;//AG; f_sk_dup : function(Stack: PSTACK): PSTACK; cdecl = nil;//AG; f_sk_set : function(Stack: PSTACK; Index: Integer; value: PAnsiChar): PAnsiChar; cdecl = nil;//AG; f_PEM_write_bio_X509 : function(B: PBIO; Cert: PX509): Integer; cdecl = nil; f_PEM_write_bio_X509_REQ : function(B: PBIO; Cert_Req: PX509_REQ) : Integer; cdecl = nil; f_PEM_write_bio_X509_CRL : function(B: PBIO; CRL: PX509_CRL) : Integer; cdecl = nil; f_PEM_read_bio_X509_CRL : function(B: PBIO; CRL: PPX509_CRL; CallBack: TPem_password_cb; UData: PAnsiChar): PX509_CRL; cdecl = nil;//AG f_PEM_read_bio_X509 : function(B: PBIO; C509: PPX509; CallBack: TPem_password_cb; UData: PAnsiChar): PX509; cdecl = nil; f_PEM_read_bio_PKCS7 : function(B: PBIO; X: PPPKCS7; CallBack: TPem_password_cb; UData: PAnsiChar): PPKCS7; cdecl = nil;//AG; f_PEM_write_bio_PKCS7 : function(B: PBIO; P7: PPKCS7): Integer; cdecl = nil; f_PEM_do_header : function(cipher: PEVP_CIPHER_INFO; data: PAnsiChar; var len: Integer; callback: TPem_password_cb; u: Pointer): Integer; cdecl = nil;//AG; f_PEM_X509_INFO_read_bio : function(B: PBIO; Stack: PSTACK_OF_X509_INFO; CallBack: TPem_password_cb; UData: PAnsiChar): PSTACK_OF_X509_INFO; cdecl = nil;//AG; f_CRYPTO_free : procedure(P: Pointer); cdecl = nil;//AG f_X509_NAME_ENTRY_get_object : function(Ne: PX509_NAME_ENTRY): PASN1_OBJECT; cdecl = nil;//AG f_X509_NAME_get_entry : function(Name: PX509_NAME; Loc: Integer): PX509_NAME_ENTRY; cdecl = nil;//AG f_X509_NAME_entry_count : function(Name: PX509_NAME) : Integer; cdecl = nil; //AG f_X509_NAME_ENTRY_get_data : function(Ne: PX509_NAME_ENTRY) : PASN1_STRING; cdecl = nil;//AG f_X509_set_version : function(Cert: PX509; Version: LongInt): Integer; cdecl = nil;//AG f_ASN1_INTEGER_get : function(Asn1_Int : PASN1_INTEGER): Integer; cdecl = nil; f_ASN1_STRING_print : function(B: PBIO; v: PASN1_STRING): integer; cdecl = nil;//AG; f_ASN1_item_free : procedure(Val: PASN1_VALUE; const It: PASN1_ITEM); cdecl = nil; //AG f_ASN1_STRING_to_UTF8 : function(POut: PPAnsiChar; PIn: PASN1_STRING) : Integer; cdecl = nil;//AG f_ASN1_INTEGER_set : function(a: PASN1_INTEGER; v: LongInt) : Integer; cdecl = nil;//AG f_ASN1_item_d2i : function(Val: PPASN1_VALUE; _In: PPAnsiChar; Len: Longword; const It: PASN1_ITEM): PASN1_VALUE; cdecl = nil;//AG; f_ASN1_STRING_free : procedure(a: PASN1_STRING); cdecl = nil;//AG; //ASN1_VALUE * ASN1_item_d2i(ASN1_VALUE **val, unsigned char **in, long len, const ASN1_ITEM *it); f_i2a_ASN1_OBJECT : function(B: PBIO; A: PASN1_OBJECT): Integer; cdecl = nil;//AG; f_X509_gmtime_adj : function(S: PASN1_TIME; Adj: LongInt): PASN1_TIME; cdecl = nil;//AG f_X509_set_pubkey : function(Cert: PX509; PKey: PEVP_PKEY): Integer; cdecl = nil;//AG f_X509_new : function: PX509; cdecl = nil;//AG f_X509_NAME_add_entry_by_txt : function(Name: PX509_NAME; Field: PAnsiChar; Type_: Integer; Buf: PAnsiChar; BufferSize: Integer; Loc: Integer; Set_: Integer): Integer; cdecl = nil;//AG f_X509_NAME_add_entry_by_NID : function(Name: PX509_NAME; Nid: Integer; Type_: Integer; Buf: PAnsiChar; BufferSize: Integer; Loc: Integer; Set_: Integer): Integer; cdecl = nil;//AG f_X509_NAME_new : function: PX509_NAME; cdecl = nil;//AG f_X509_set_issuer_name : function(Cert: PX509; Name: PX509_NAME): Integer; cdecl = nil;//AG f_X509_sign : function(Cert: PX509; PKey: PEVP_PKEY; const Md: PEVP_MD): Integer; cdecl = nil;//AG f_X509_INFO_free : procedure(Xi: PX509_INFO); cdecl = nil;//AG; f_X509_CRL_dup : function(CRL: PX509_CRL): PX509_CRL; cdecl = nil;//AG; f_X509_PKEY_free : procedure(PKey: PX509_PKEY); cdecl = nil;//AG; f_i2d_X509 : function(Cert: PX509; pOut: PPAnsiChar): Integer; cdecl = nil;//AG f_i2d_PrivateKey : function(A: PEVP_PKEY; PP: PPAnsiChar): Integer; cdecl = nil;//AG f_d2i_PrivateKey : function(type_: Integer; var a: PEVP_PKEY; var pp : PAnsiChar; length: Integer): PEVP_PKEY; cdecl = nil;//AG f_PEM_read_bio_PrivateKey : function(B: PBIO; X:PPEVP_PKEY; CB: TPem_password_cb; UData: PAnsiChar): PEVP_PKEY; cdecl = nil; //AG f_PEM_write_bio_PrivateKey : function(B: PBIO; X: PEVP_PKEY; const Enc: PEVP_CIPHER; Kstr: PAnsiChar; Klen: Integer; CallBack: TPem_password_cb; U: Pointer): Integer; cdecl = nil;//AG f_i2d_ASN1_bytes : function(A : PASN1_STRING; var p: PAnsiChar; tag: Integer; xclass: Integer): Integer; cdecl = nil;//AG f_X509_get_pubkey : function(Cert: PX509): PEVP_PKEY; cdecl = nil; //AG; f_X509_PUBKEY_free : procedure(Key: PEVP_PKEY); cdecl = nil; //AG; f_X509_check_purpose : function(Cert: PX509; ID: Integer; CA: Integer): Integer; cdecl = nil;//AG; f_X509_PURPOSE_get_id : function(XP: PX509_PURPOSE): Integer; cdecl = nil;//AG; f_X509_PURPOSE_get0 : function(Idx: Integer): PX509_PURPOSE; cdecl = nil;//AG; f_X509_PURPOSE_get0_name : function(XP: PX509_PURPOSE): PAnsiChar; cdecl = nil;//AG; f_X509_PURPOSE_get0_sname : function(XP: PX509_PURPOSE): PAnsiChar; cdecl = nil;//AG; f_X509_PURPOSE_get_count : function: Integer; cdecl = nil;//AG; f_CONF_modules_unload : procedure(all: Integer); cdecl = nil;//AG; { f_OPENSSL_add_all_algorithms_noconf : procedure; cdecl = nil; f_OPENSSL_add_all_algorithms_conf : procedure; cdecl = nil; } f_OpenSSL_add_all_ciphers : procedure; cdecl = nil; f_OpenSSL_add_all_digests : procedure; cdecl = nil; f_PKCS7_new : function: PPKCS7; cdecl = nil;//AG; f_PKCS7_free : procedure(P7: PPKCS7); cdecl = nil;//AG; f_PKCS7_set_type : function(P7: PPKCS7; type_: Integer): Integer; cdecl = nil;//AG; f_PKCS7_content_new : function(P7: PPKCS7; nid: Integer): Integer; cdecl = nil;//AG; f_PKCS7_add_certificate : function (p7: PPKCS7; x509: PX509): Integer; cdecl = nil;//AG; f_PKCS12_parse : function(P12: PPKCS12; Pass: PAnsiChar; var Pkey: PEVP_PKEY; var Cert: PX509; var Ca: PSTACK_OF_X509): Integer; cdecl = nil;//AG f_PKCS12_verify_mac : function(p12: PPKCS12; const pass: PAnsiChar; passlen: Integer): Integer; cdecl = nil;//AG; f_PKCS12_free : procedure(P12: PPKCS12); cdecl = nil;//AG; f_PKCS12_create : function(pass: PAnsiChar; name: PAnsiChar; pkey: PEVP_PKEY; cert: PX509; ca: PSTACK_OF_X509; nid_key, nid_cert, iter, mac_iter, keytype: Integer):PPKCS12; cdecl = nil;//AG; {$IFNDEF OPENSSL_NO_ENGINE} f_ENGINE_load_builtin_engines : procedure; cdecl = nil; //AG; f_ENGINE_register_all_complete : procedure; cdecl = nil; //AG; f_ENGINE_cleanup : procedure; cdecl = nil; //AG; f_ENGINE_by_id : function(const id: PAnsiChar): PENGINE; cdecl = nil; //AG; f_ENGINE_init : function(e: PENGINE): Integer; cdecl = nil; //AG; f_ENGINE_finish : function(e: PENGINE): Integer; cdecl = nil; //AG; f_ENGINE_set_default : function(e: PENGINE; flags: Cardinal): Integer; cdecl = nil; //AG; f_ENGINE_ctrl_cmd_string : function(e: PENGINE; const cmd_name: PAnsiChar; const arg: PAnsiChar; cmd_optional: Integer): Integer; cdecl = nil; //AG; f_ENGINE_free : function(e: PENGINE): Integer; cdecl = nil; //AG; //* The following functions handle keys that are stored in some secondary //* location, handled by the engine. The storage may be on a card or //* whatever. */ f_ENGINE_load_private_key : function(e: PENGINE; key_id: PAnsiChar; ui_method: PUI_METHOD; callback_data: Pointer): PEVP_PKEY; cdecl = nil; //AG; f_ENGINE_load_public_key : function(e: PENGINE; const key_id: PAnsiChar; ui_method: PUI_METHOD; callback_data: Pointer): PEVP_PKEY; cdecl = nil; //AG; { Since V0.98i there's also: int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s, STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **ppkey, STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data); } f_ENGINE_load_ssl_client_cert : function(e: PENGINE; SSL: PSSL; ca_dn: PSTACK_OF_X509_NAME; pcert: PPX509; ppkey: PPEVP_PKEY; pother: PSTACK_OF_X509; ui_method: PUI_METHOD; callback_data: Pointer): Integer; cdecl = nil; // ui.h // f_UI_new : function: PUI; cdecl = nil; //AG; f_UI_new_method : function(const method: PUI_METHOD): PUI; cdecl = nil; //AG; f_UI_free : procedure(ui: PUI); cdecl = nil; //AG; f_UI_create_method : function(name: PAnsiChar): PUI_METHOD; cdecl = nil; //AG; f_UI_destroy_method : procedure(ui_method: PUI_METHOD); cdecl = nil; //AG; f_UI_set_ex_data : function(r: PUI; idx: Integer; arg: Pointer): Integer; cdecl = nil; //AG; f_UI_get_ex_data : function(r: PUI; idx: Integer): Pointer; cdecl = nil; //AG; f_UI_method_set_reader : function(method: PUI_METHOD; reader: TPinCallBack):Integer; cdecl = nil; //AG; f_UI_set_result : function(ui: PUI; uis: PUI_STRING; const result: PAnsiChar): Integer; cdecl = nil; //AG; f_UI_OpenSSL : function: PUI_METHOD; cdecl = nil; //AG; (* http://openssl.org/docs/crypto/engine.html Here we'll assume we want to load and register all ENGINE implementations bundled with OpenSSL, such that for any cryptographic algorithm required by OpenSSL - if there is an ENGINE that implements it and can be initialise, it should be used. The following code illustrates how this can work; /* Load all bundled ENGINEs into memory and make them visible */ ENGINE_load_builtin_engines(); /* Register all of them for every algorithm they collectively implement */ ENGINE_register_all_complete(); That's all that's required. Eg. the next time OpenSSL tries to set up an RSA key, any bundled ENGINEs that implement RSA_METHOD will be passed to ENGINE_init() and if any of those succeed, that ENGINE will be set as the default for RSA use from then on. *) {$ENDIF} { Function name constants } FN_SSLeay = 'SSLeay'; FN_SSLeay_version = 'SSLeay_version'; FN_ERR_get_error_line_data = 'ERR_get_error_line_data'; FN_ERR_peek_error = 'ERR_peek_error'; FN_ERR_peek_last_error = 'ERR_peek_last_error'; FN_ERR_get_error = 'ERR_get_error'; FN_ERR_error_string = 'ERR_error_string'; FN_ERR_error_string_n = 'ERR_error_string_n'; FN_ERR_clear_error = 'ERR_clear_error'; FN_ERR_remove_state = 'ERR_remove_state'; FN_ERR_remove_thread_state = 'ERR_remove_thread_state'; FN_ERR_free_strings = 'ERR_free_strings'; FN_RAND_seed = 'RAND_seed'; FN_BIO_new = 'BIO_new'; FN_BIO_new_socket = 'BIO_new_socket'; FN_BIO_new_fd = 'BIO_new_fd'; FN_BIO_new_file = 'BIO_new_file'; FN_BIO_new_mem_buf = 'BIO_new_mem_buf'; FN_BIO_new_bio_pair = 'BIO_new_bio_pair'; FN_BIO_ctrl = 'BIO_ctrl'; FN_BIO_ctrl_pending = 'BIO_ctrl_pending'; FN_BIO_ctrl_get_write_guarantee = 'BIO_ctrl_get_write_guarantee'; FN_BIO_ctrl_get_read_request = 'BIO_ctrl_get_read_request'; FN_BIO_read = 'BIO_read'; FN_BIO_nread = 'BIO_nread'; FN_BIO_nread0 = 'BIO_nread0'; FN_BIO_nwrite = 'BIO_nwrite'; FN_BIO_nwrite0 = 'BIO_nwrite0'; FN_BIO_write = 'BIO_write'; FN_BIO_free = 'BIO_free'; FN_BIO_gets = 'BIO_gets'; FN_BIO_puts = 'BIO_puts'; FN_BIO_push = 'BIO_push'; FN_BIO_s_mem = 'BIO_s_mem'; FN_BIO_get_retry_BIO = 'BIO_get_retry_BIO'; FN_BIO_get_retry_reason = 'BIO_get_retry_reason'; FN_d2i_X509_bio = 'd2i_X509_bio'; FN_i2d_X509_bio = 'i2d_X509_bio'; FN_d2i_PrivateKey_bio = 'd2i_PrivateKey_bio'; FN_i2d_PrivateKey_bio = 'i2d_PrivateKey_bio'; FN_d2i_X509 = 'd2i_X509'; FN_d2i_PKCS12_bio = 'd2i_PKCS12_bio'; FN_i2d_PKCS12_bio = 'i2d_PKCS12_bio'; FN_d2i_PKCS7_bio = 'd2i_PKCS7_bio'; FN_CRYPTO_lock = 'CRYPTO_lock'; FN_CRYPTO_add_lock = 'CRYPTO_add_lock'; FN_CRYPTO_num_locks = 'CRYPTO_num_locks'; FN_CRYPTO_set_locking_callback = 'CRYPTO_set_locking_callback'; FN_CRYPTO_set_id_callback = 'CRYPTO_set_id_callback'; FN_CRYPTO_THREADID_set_callback = 'CRYPTO_THREADID_set_callback'; FN_CRYPTO_THREADID_set_numeric = 'CRYPTO_THREADID_set_numeric'; FN_CRYPTO_THREADID_set_pointer = 'CRYPTO_THREADID_set_pointer'; FN_CRYPTO_set_dynlock_create_callback = 'CRYPTO_set_dynlock_create_callback'; FN_CRYPTO_set_dynlock_lock_callback = 'CRYPTO_set_dynlock_lock_callback'; FN_CRYPTO_set_dynlock_destroy_callback = 'CRYPTO_set_dynlock_destroy_callback'; {$IFDEF OPENSSL_USE_DELPHI_MM} FN_CRYPTO_set_mem_functions = 'CRYPTO_set_mem_functions'; {$ENDIF} FN_CRYPTO_cleanup_all_ex_data = 'CRYPTO_cleanup_all_ex_data'; FN_X509_dup = 'X509_dup'; //AG FN_X509_check_ca = 'X509_check_ca'; //AG FN_X509_STORE_new = 'X509_STORE_new'; //AG FN_X509_STORE_free = 'X509_STORE_free'; //AG FN_X509_STORE_add_cert = 'X509_STORE_add_cert'; //AG FN_X509_STORE_add_crl = 'X509_STORE_add_crl'; //AG FN_X509_STORE_add_lookup = 'X509_STORE_add_lookup'; //AG FN_X509_STORE_set_flags = 'X509_STORE_set_flags'; //AG FN_X509_STORE_CTX_new = 'X509_STORE_CTX_new'; //AG FN_X509_STORE_CTX_free = 'X509_STORE_CTX_free'; //AG FN_X509_STORE_CTX_init = 'X509_STORE_CTX_init'; //AG FN_X509_STORE_CTX_cleanup = 'X509_STORE_CTX_cleanup'; //AG FN_X509_STORE_CTX_get_ex_data = 'X509_STORE_CTX_get_ex_data'; FN_X509_STORE_CTX_get_current_cert = 'X509_STORE_CTX_get_current_cert'; FN_X509_STORE_CTX_get_error = 'X509_STORE_CTX_get_error'; FN_X509_STORE_CTX_set_error = 'X509_STORE_CTX_set_error'; FN_X509_STORE_CTX_get_error_depth = 'X509_STORE_CTX_get_error_depth'; FN_X509_STORE_CTX_get_chain = 'X509_STORE_CTX_get_chain'; //AG FN_X509_STORE_CTX_trusted_stack = 'X509_STORE_CTX_trusted_stack'; //AG FN_X509_STORE_CTX_set_purpose = 'X509_STORE_CTX_set_purpose'; //AG FN_X509_STORE_CTX_set_verify_cb = 'X509_STORE_CTX_set_verify_cb'; //AG FN_X509_STORE_CTX_set_ex_data = 'X509_STORE_CTX_set_ex_data'; //AG FN_X509_load_crl_file = 'X509_load_crl_file'; //AG FN_X509_LOOKUP_file = 'X509_LOOKUP_file'; //AG FN_X509_LOOKUP_hash_dir = 'X509_LOOKUP_hash_dir'; //AG FN_X509_LOOKUP_new = 'X509_LOOKUP_new'; //AG FN_X509_LOOKUP_free = 'X509_LOOKUP_free'; //AG FN_X509_LOOKUP_by_issuer_serial = 'X509_LOOKUP_by_issuer_serial'; //AG FN_X509_LOOKUP_by_fingerprint = 'X509_LOOKUP_by_fingerprint'; //AG FN_X509_LOOKUP_ctrl = 'X509_LOOKUP_ctrl'; //AG FN_X509_check_issued = 'X509_check_issued'; //AG FN_X509_verify_cert = 'X509_verify_cert'; //AG FN_X509_verify_cert_error_string = 'X509_verify_cert_error_string'; FN_X509_get_issuer_name = 'X509_get_issuer_name'; FN_X509_get_subject_name = 'X509_get_subject_name'; FN_X509_get_serialNumber = 'X509_get_serialNumber'; FN_X509_NAME_oneline = 'X509_NAME_oneline'; FN_X509_NAME_get_text_by_NID = 'X509_NAME_get_text_by_NID'; FN_X509_NAME_get_index_by_NID = 'X509_NAME_get_index_by_NID'; //AG FN_X509_NAME_free = 'X509_NAME_free'; FN_X509_NAME_cmp = 'X509_NAME_cmp'; FN_X509_get_ext = 'X509_get_ext'; FN_X509_get_ext_count = 'X509_get_ext_count'; FN_X509_free = 'X509_free'; FN_X509_CRL_free = 'X509_CRL_free'; FN_X509V3_EXT_get = 'X509V3_EXT_get'; FN_X509V3_EXT_print = 'X509V3_EXT_print'; //AG FN_X509V3_EXT_d2i = 'X509V3_EXT_d2i'; //AG FN_X509V3_conf_free = 'X509V3_conf_free'; //AG FN_X509_EXTENSION_get_object = 'X509_EXTENSION_get_object'; FN_X509_EXTENSION_get_data = 'X509_EXTENSION_get_data'; //AG FN_X509_EXTENSION_get_critical = 'X509_EXTENSION_get_critical'; //AG FN_X509_subject_name_hash = 'X509_subject_name_hash'; FN_X509_print = 'X509_print'; FN_X509_digest = 'X509_digest'; //AG FN_X509_check_private_key = 'X509_check_private_key'; //AG FN_EVP_sha1 = 'EVP_sha1'; //AG FN_EVP_sha256 = 'EVP_sha256';//AG FN_EVP_md5 = 'EVP_md5'; //AG FN_EVP_PKEY_new = 'EVP_PKEY_new'; //AG FN_EVP_PKEY_free = 'EVP_PKEY_free'; //AG FN_EVP_PKEY_get0 = 'EVP_PKEY_get0'; // AG FN_EVP_PKEY_assign = 'EVP_PKEY_assign'; //AG FN_EVP_PKEY_size = 'EVP_PKEY_size'; //AG FN_EVP_PKEY_bits = 'EVP_PKEY_bits'; //AG FN_EVP_get_cipherbyname = 'EVP_get_cipherbyname'; //AG FN_EVP_des_ede3_cbc = 'EVP_des_ede3_cbc'; //AG FN_EVP_cleanup = 'EVP_cleanup'; FN_RSA_generate_key = 'RSA_generate_key'; //AG FN_RSA_print = 'RSA_print'; //AG FN_DSA_print = 'DSA_print'; //AG FN_EC_KEY_print = 'EC_KEY_print'; //AG FN_OBJ_nid2sn = 'OBJ_nid2sn'; FN_OBJ_nid2ln = 'OBJ_nid2ln'; FN_OBJ_obj2nid = 'OBJ_obj2nid'; FN_sk_num = 'sk_num'; FN_sk_value = 'sk_value'; FN_sk_new_null = 'sk_new_null'; //AG FN_sk_free = 'sk_free'; //AG FN_sk_pop_free = 'sk_pop_free'; //AG FN_sk_push = 'sk_push'; //AG FN_sk_delete = 'sk_delete'; //AG FN_sk_pop = 'sk_pop'; //AG FN_sk_find = 'sk_find'; //AG FN_sk_insert = 'sk_insert'; //AG FN_sk_dup = 'sk_dup'; //AG FN_sk_set = 'sk_set'; //AG FN_PEM_write_bio_X509 = 'PEM_write_bio_X509'; FN_PEM_write_bio_X509_REQ = 'PEM_write_bio_X509_REQ'; FN_PEM_write_bio_X509_CRL = 'PEM_write_bio_X509_CRL'; FN_PEM_read_bio_X509_CRL = 'PEM_read_bio_X509_CRL';//AG FN_PEM_read_bio_X509 = 'PEM_read_bio_X509'; FN_PEM_read_bio_PKCS7 = 'PEM_read_bio_PKCS7'; FN_PEM_write_bio_PKCS7 = 'PEM_write_bio_PKCS7'; FN_PEM_do_header = 'PEM_do_header'; FN_PEM_X509_INFO_read_bio = 'PEM_X509_INFO_read_bio'; //AG FN_CRYPTO_free = 'CRYPTO_free'; //AG FN_X509_NAME_ENTRY_get_object = 'X509_NAME_ENTRY_get_object'; //AG FN_X509_NAME_get_entry = 'X509_NAME_get_entry'; //AG FN_X509_NAME_entry_count = 'X509_NAME_entry_count'; //AG FN_X509_NAME_ENTRY_get_data = 'X509_NAME_ENTRY_get_data'; //AG FN_X509_set_version = 'X509_set_version'; //AG FN_ASN1_STRING_to_UTF8 = 'ASN1_STRING_to_UTF8'; //AG FN_ASN1_INTEGER_set = 'ASN1_INTEGER_set'; //AG FN_ASN1_INTEGER_get = 'ASN1_INTEGER_get'; FN_ASN1_STRING_print = 'ASN1_STRING_print'; //AG FN_ASN1_item_d2i = 'ASN1_item_d2i'; //AG FN_ASN1_item_free = 'ASN1_item_free'; //AG FN_ASN1_STRING_free = 'ASN1_STRING_free'; //AG FN_i2a_ASN1_OBJECT = 'i2a_ASN1_OBJECT'; //AG FN_X509_gmtime_adj = 'X509_gmtime_adj'; //AG FN_X509_set_pubkey = 'X509_set_pubkey'; //AG FN_X509_new = 'X509_new'; //AG FN_X509_NAME_add_entry_by_txt = 'X509_NAME_add_entry_by_txt'; //AG FN_X509_NAME_add_entry_by_NID = 'X509_NAME_add_entry_by_NID'; //AG FN_X509_NAME_new = 'X509_NAME_new'; //AG FN_X509_set_issuer_name = 'X509_set_issuer_name'; //AG FN_X509_sign = 'X509_sign'; //AG FN_X509_INFO_free = 'X509_INFO_free'; //AG FN_X509_CRL_dup = 'X509_CRL_dup'; //AG FN_X509_PKEY_free = 'X509_PKEY_free'; //AG FN_i2d_X509 = 'i2d_X509'; //AG FN_i2d_PrivateKey = 'i2d_PrivateKey'; //AG FN_d2i_PrivateKey = 'd2i_PrivateKey'; //AG FN_PEM_write_bio_PrivateKey = 'PEM_write_bio_PrivateKey'; //AG FN_PEM_read_bio_PrivateKey = 'PEM_read_bio_PrivateKey'; //AG FN_i2d_ASN1_bytes = 'i2d_ASN1_bytes'; //AG FN_X509_get_pubkey = 'X509_get_pubkey';//AG FN_X509_PUBKEY_free = 'X509_PUBKEY_free'; //AG FN_X509_check_purpose = 'X509_check_purpose'; //AG FN_X509_PURPOSE_get_id = 'X509_PURPOSE_get_id'; //AG FN_X509_PURPOSE_get0 = 'X509_PURPOSE_get0'; //AG FN_X509_PURPOSE_get0_name = 'X509_PURPOSE_get0_name'; //AG FN_X509_PURPOSE_get0_sname = 'X509_PURPOSE_get0_sname'; //AG FN_X509_PURPOSE_get_count = 'X509_PURPOSE_get_count'; //AG FN_CONF_modules_unload = 'CONF_modules_unload'; //AG { FN_OPENSSL_add_all_algorithms_noconf = 'OPENSSL_add_all_algorithms_noconf'; FN_OPENSSL_add_all_algorithms_conf = 'OPENSSL_add_all_algorithms_conf'; } FN_OpenSSL_add_all_ciphers = 'OpenSSL_add_all_ciphers'; FN_OpenSSL_add_all_digests = 'OpenSSL_add_all_digests'; FN_PKCS7_new = 'PKCS7_new'; FN_PKCS7_free = 'PKCS7_free'; FN_PKCS7_set_type = 'PKCS7_set_type'; FN_PKCS7_content_new = 'PKCS7_content_new'; FN_PKCS7_add_certificate = 'PKCS7_add_certificate'; FN_PKCS12_parse = 'PKCS12_parse'; FN_PKCS12_verify_mac = 'PKCS12_verify_mac'; FN_PKCS12_free = 'PKCS12_free'; FN_PKCS12_create = 'PKCS12_create'; {$IFNDEF OPENSSL_NO_ENGINE} FN_ENGINE_load_builtin_engines = 'ENGINE_load_builtin_engines'; //AG FN_ENGINE_register_all_complete = 'ENGINE_register_all_complete'; //AG FN_ENGINE_cleanup = 'ENGINE_cleanup'; //AG FN_ENGINE_by_id = 'ENGINE_by_id'; //AG FN_ENGINE_init = 'ENGINE_init'; //AG FN_ENGINE_finish = 'ENGINE_finish'; //AG FN_ENGINE_set_default = 'ENGINE_set_default'; //AG FN_ENGINE_ctrl_cmd_string = 'ENGINE_ctrl_cmd_string'; //AG FN_ENGINE_free = 'ENGINE_free'; //AG FN_ENGINE_load_private_key = 'ENGINE_load_private_key'; //AG FN_ENGINE_load_public_key = 'ENGINE_load_public_key'; //AG FN_ENGINE_load_ssl_client_cert = 'ENGINE_load_ssl_client_cert';//AG FN_UI_new = 'UI_new'; //AG FN_UI_new_method = 'UI_new_method'; //AG FN_UI_free = 'UI_free'; //AG FN_UI_create_method = 'UI_create_method'; //AG FN_UI_destroy_method = 'UI_destroy_method'; //AG FN_UI_set_ex_data = 'UI_set_ex_data'; //AG FN_UI_get_ex_data = 'UI_get_ex_data'; //AG FN_UI_method_set_reader = 'UI_method_set_reader'; //AG FN_UI_set_result = 'UI_set_result'; //AG FN_UI_OpenSSL = 'UI_OpenSSL'; //AG {$ENDIF} function Load : Boolean; function WhichFailedToLoad : String; function ERR_GET_REASON(ErrCode : Cardinal) : Cardinal; {$IFDEF USE_INLINE} inline; {$ENDIF} function ERR_GET_LIB(ErrCode : Cardinal) : Cardinal; {$IFDEF USE_INLINE} inline; {$ENDIF} function ERR_GET_FUNC(ErrCode : Cardinal) : Cardinal; {$IFDEF USE_INLINE} inline; {$ENDIF} function ERR_FATAL_ERROR(ErrCode : Cardinal) : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_get_flags(b: PBIO): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_should_retry(b: PBIO): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_should_read(b: PBIO): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_should_write(b: PBIO): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_should_io_special(b: PBIO): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function BIO_retry_type(b: PBIO): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function ASN1_ITEM_ptr(iptr: PASN1_ITEM_EXP): PASN1_ITEM; {$IFDEF USE_INLINE} inline; {$ENDIF} function OpenSslVersion : String; function OpenSslCompilerFlags : String; {$IFDEF USE_INLINE} inline; {$ENDIF} function OpenSslBuiltOn : String; {$IFDEF USE_INLINE} inline; {$ENDIF} function OpenSslPlatForm : String; {$IFDEF USE_INLINE} inline; {$ENDIF} function OpenSslDir : String; {$IFDEF USE_INLINE} inline; {$ENDIF} function IcsX509VerifyErrorToStr(ErrCode: Integer): String; function f_Ics_X509_get_notBefore(X: PX509): PASN1_TIME; function f_Ics_X509_get_notAfter(X: PX509): PASN1_TIME; function f_Ics_X509_CRL_get_issuer(crl: PX509_CRL): PX509_NAME; {$IFDEF USE_INLINE} inline; {$ENDIF}// Macro function f_Ics_X509_get_version(X509: PX509): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function Asn1ToUTDateTime(Asn1Time: PASN1_TIME; out UT: TDateTime): Boolean; function Asn1ToString(PAsn1 : PASN1_STRING): String; {$IFNDEF OPENSSL_NO_ENGINE} function f_Ics_UI_set_app_data(r: PUI; arg: Pointer): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_Ics_UI_get_app_data(r: PUI): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF} {$ENDIF} function f_Ics_X509_LOOKUP_load_file(Ctx: PX509_LOOKUP; FileName: PAnsiChar; Type_: Longword): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_Ics_X509_LOOKUP_add_dir(Ctx: PX509_LOOKUP; DirName: PAnsiChar; Type_: Longword): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} function f_Ics_X509_get_signature_algorithm(X509: PX509): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} procedure Ics_Ssl_EVP_PKEY_IncRefCnt(K: PEVP_PKEY; Increment: Integer = 1); {$IFDEF USE_INLINE} inline; {$ENDIF} function Ics_Ssl_EVP_PKEY_GetKey(K: PEVP_PKEY): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF} function Ics_Ssl_EVP_PKEY_GetType(K: PEVP_PKEY): Integer; {$IFDEF USE_INLINE} inline; {$ENDIF} { 0.9.8n } function f_SSL_get_secure_renegotiation_support(S: PSSL): Longint; {$IFDEF USE_INLINE} inline; {$ENDIF} const GLIBEAY_DLL_Handle : THandle = 0; GLIBEAY_DLL_Name : String = 'LIBEAY32.DLL'; GLIBEAY_DLL_FileName : String = '*NOT LOADED*'; { Version stuff added 07/12/05 } ICS_OPENSSL_VERSION_NUMBER : Longword = 0; ICS_SSL_NO_RENEGOTIATION : Boolean = FALSE; { MMNNFFPPS: major minor fix patch status } { The status nibble has one of the values 0 for development, 1 to e for } { betas 1 to 14, and f for release. } { for example } { 0x000906000 == 0.9.6 dev } { 0x000906023 == 0.9.6b beta 3 } { 0x00090605f == 0.9.6e release } { Versions prior to 0.9.3 have identifiers < 0x0930. Versions between } { 0.9.3 and 0.9.5 had a version identifier with this interpretation: } { MMNNFFRBB major minor fix final beta/patch } { for example } { 0x000904100 == 0.9.4 release } { 0x000905000 == 0.9.5 dev } { Version 0.9.5a had an interim interpretation that is like the current } { one, except the patch level got the highest bit set, to keep continuity.} { The number was therefore 0x0090581f. } //OSSL_VER_0906G = $0090607f; no longer supported OSSL_VER_0907G = $0090707f; OSSL_VER_0907I = $0090709f; OSSL_VER_0908 = $00908000; OSSL_VER_0908A = $0090801f; OSSL_VER_0908E = $0090805f; OSSL_VER_0908F = $0090806f; OSSL_VER_0908H = $0090808f; OSSL_VER_0908I = $0090809f; OSSL_VER_0908K = $009080bf; OSSL_VER_0908L = $009080cf; OSSL_VER_0908N = $009080ef; OSSL_VER_0908R = $0090812f; OSSL_VER_1000 = $10000000; // Untested, did not build with MinGW OSSL_VER_1000D = $1000004f; // Might be still buggy, had to incl. one workaround so far, see TSslContext.InitContext OSSL_VER_1000J = $100000af; // just briefly tested { Basically versions listed above are tested if not otherwise commented. } { Versions between are assumed to work, however they are untested. } { OpenSSL libraries for ICS are available for download here: } { http://wiki.overbyte.be/wiki/index.php/ICS_Download } {$IFDEF BEFORE_OSSL_098E} MIN_OSSL_VER = OSSL_VER_0907G; MAX_OSSL_VER = OSSL_VER_1000J; {$ELSE} {$IFNDEF OPENSSL_NO_TLSEXT} MIN_OSSL_VER = OSSL_VER_0908F; {$ELSE} MIN_OSSL_VER = OSSL_VER_0908E; {$ENDIF} MAX_OSSL_VER = OSSL_VER_1000J; {$ENDIF} {$ENDIF} // USE_SSL implementation {$IFDEF USE_SSL} uses OverbyteIcsUtils; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IcsMalloc(Size: size_t): Pointer; cdecl; begin GetMem(Result, Size); FillChar(Result^, Size, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IcsRealloc(P: Pointer; Size: size_t): Pointer; cdecl; begin Result := P; ReallocMem(Result, Size); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure IcsFreeMem(P: Pointer); cdecl; begin FreeMem(P); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Load : Boolean; var ErrCode : Integer; begin ICS_OPENSSL_VERSION_NUMBER := 0; if GLIBEAY_DLL_Handle <> 0 then begin Result := TRUE; Exit; // Already loaded end; GLIBEAY_DLL_Handle := LoadLibrary(PChar(GLIBEAY_DLL_Name)); if GLIBEAY_DLL_Handle < HINSTANCE_ERROR then begin ErrCode := GLIBEAY_DLL_Handle; GLIBEAY_DLL_Handle := 0; raise EIcsLIBEAYException.Create('Unable to load ' + GLIBEAY_DLL_Name + '. Error #' + IntToStr(ErrCode) + #13#10 + SysErrorMessage(GetLastError)); end; SetLength(GLIBEAY_DLL_FileName, 256); SetLength(GLIBEAY_DLL_FileName, GetModuleFileName(GLIBEAY_DLL_Handle, PChar(GLIBEAY_DLL_FileName), Length(GLIBEAY_DLL_FileName))); //This function is available in all versions so we can safely call it f_SSLeay := GetProcAddress(GLIBEAY_DLL_Handle, FN_SSLeay); if @f_SSLeay = nil then begin Result := False; Exit; end; ICS_OPENSSL_VERSION_NUMBER := f_SSLeay; ICS_SSL_NO_RENEGOTIATION := (ICS_OPENSSL_VERSION_NUMBER >= OSSL_VER_0908L) and (ICS_OPENSSL_VERSION_NUMBER < OSSL_VER_0908N); {$IFNDEF OPENSSL_NO_ENGINE} if ICS_OPENSSL_VERSION_NUMBER < OSSL_VER_0908I then begin FreeLibrary(OverbyteIcsLIBEAY.GLIBEAY_DLL_Handle); OverbyteIcsLIBEAY.GLIBEAY_DLL_Handle := 0; raise EIcsLibeayException.Create('Experimental engine code requires ' + 'at least OpenSSL v0.9.8i'); end; {$ENDIF} { Version Check } {$IFNDEF NO_OSSL_VERSION_CHECK} if (ICS_OPENSSL_VERSION_NUMBER < MIN_OSSL_VER) or (ICS_OPENSSL_VERSION_NUMBER > MAX_OSSL_VER) then begin FreeLibrary(OverbyteIcsLIBEAY.GLIBEAY_DLL_Handle); OverbyteIcsLIBEAY.GLIBEAY_DLL_Handle := 0; raise EIcsLibeayException.Create( 'Unsupported OpenSSL version (0x' + IntToHex(ICS_OPENSSL_VERSION_NUMBER, 8) + ') !'#13#10 + 'Supported versions are 0x' + IntToHex(MIN_OSSL_VER, 8) + ' - 0x' + IntToHex(MAX_OSSL_VER, 8) + #13#10 + 'FileName: ' + GLIBEAY_DLL_FileName); end; {$ENDIF} { Let's set some values of constants having changed in v0.9.8 } if ICS_OPENSSL_VERSION_NUMBER >= OSSL_VER_0908 then begin SSL_CTRL_EXTRA_CHAIN_CERT := 14; // Ssl.h SSL_CTRL_GET_SESSION_REUSED := 8; // Ssl.h MBSTRING_UNIV := MBSTRING_FLAG or 4; // Asn1.h MBSTRING_UTF8 := MBSTRING_FLAG; // Asn1.h end else begin {SSL_CTRL_EXTRA_CHAIN_CERT := 12; // Ssl.h SSL_CTRL_GET_SESSION_REUSED := 6; // Ssl.h MBSTRING_UNIV := MBSTRING_FLAG or 3; // Asn1.h MBSTRING_UTF8 := MBSTRING_FLAG or 4; // Asn1.h } end; f_SSLeay_version := GetProcAddress(GLIBEAY_DLL_Handle, FN_SSLeay_version); f_ERR_get_error_line_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_get_error_line_data); f_ERR_peek_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_peek_error); f_ERR_peek_last_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_peek_last_error); f_ERR_get_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_get_error); f_ERR_error_string := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_error_string); f_ERR_error_string_n := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_error_string_n); f_ERR_clear_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_clear_error); f_ERR_remove_state := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_remove_state); f_ERR_remove_thread_state := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_remove_thread_state); f_ERR_free_strings := GetProcAddress(GLIBEAY_DLL_Handle, FN_ERR_free_strings); f_RAND_seed := GetProcAddress(GLIBEAY_DLL_Handle, FN_RAND_seed); f_BIO_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new); f_BIO_new_socket := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new_socket); f_BIO_new_fd := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new_fd); f_BIO_new_file := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new_file); f_BIO_new_mem_buf := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new_mem_buf); f_BIO_new_bio_pair := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_new_bio_pair); f_BIO_ctrl := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_ctrl); f_BIO_ctrl_pending := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_ctrl_pending); f_BIO_ctrl_get_write_guarantee := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_ctrl_get_write_guarantee); f_BIO_ctrl_get_read_request := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_ctrl_get_read_request); f_BIO_read := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_read); f_BIO_nread := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_nread); f_BIO_nread0 := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_nread0); f_BIO_nwrite := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_nwrite); f_BIO_nwrite0 := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_nwrite0); f_BIO_write := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_write); f_BIO_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_free); f_BIO_gets := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_gets); f_BIO_puts := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_puts); f_BIO_push := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_push); f_BIO_s_mem := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_s_mem); f_BIO_get_retry_BIO := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_get_retry_BIO); f_BIO_get_retry_reason := GetProcAddress(GLIBEAY_DLL_Handle, FN_BIO_get_retry_reason); f_d2i_X509_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_X509_bio); f_i2d_X509_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_X509_bio); f_d2i_PrivateKey_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_PrivateKey_bio); f_i2d_PrivateKey_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_PrivateKey_bio); f_d2i_X509 := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_X509); f_d2i_PKCS12_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_PKCS12_bio); f_i2d_PKCS12_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_PKCS12_bio); f_d2i_PKCS7_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_PKCS7_bio); f_CRYPTO_lock := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_lock); f_CRYPTO_add_lock := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_add_lock); f_CRYPTO_num_locks := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_num_locks); f_CRYPTO_set_locking_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_locking_callback); f_CRYPTO_set_id_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_id_callback); f_CRYPTO_THREADID_set_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_THREADID_set_callback); f_CRYPTO_THREADID_set_numeric := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_THREADID_set_numeric); f_CRYPTO_THREADID_set_pointer := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_THREADID_set_pointer); f_CRYPTO_set_dynlock_create_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_dynlock_create_callback); f_CRYPTO_set_dynlock_lock_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_dynlock_lock_callback); f_CRYPTO_set_dynlock_destroy_callback := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_dynlock_destroy_callback); {$IFDEF OPENSSL_USE_DELPHI_MM} f_CRYPTO_set_mem_functions := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_set_mem_functions); {$ENDIF} f_CRYPTO_cleanup_all_ex_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_cleanup_all_ex_data); f_X509_dup := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_dup); //AG f_X509_check_ca := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_check_ca); //AG f_X509_STORE_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_new); //AG f_X509_STORE_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_free); //AG f_X509_STORE_add_cert := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_add_cert); //AG f_X509_STORE_add_crl := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_add_crl); //AG f_X509_STORE_add_lookup := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_add_lookup); //AG f_X509_STORE_set_flags := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_set_flags); //AG f_X509_STORE_CTX_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_new); //AG f_X509_STORE_CTX_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_free); //AG f_X509_STORE_CTX_init := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_init); //AG f_X509_STORE_CTX_cleanup := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_cleanup); //AG f_X509_STORE_CTX_get_ex_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_get_ex_data); f_X509_STORE_CTX_get_current_cert := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_get_current_cert); f_X509_STORE_CTX_get_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_get_error); f_X509_STORE_CTX_set_error := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_set_error); f_X509_STORE_CTX_get_error_depth := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_get_error_depth); f_X509_STORE_CTX_get_chain := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_get_chain); //AG f_X509_STORE_CTX_trusted_stack := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_trusted_stack); //AG f_X509_STORE_CTX_set_purpose := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_set_purpose); //AG f_X509_STORE_CTX_set_verify_cb := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_set_verify_cb); //AG f_X509_STORE_CTX_set_ex_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_STORE_CTX_set_ex_data); //AG f_X509_load_crl_file := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_load_crl_file); //AG f_X509_LOOKUP_file := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_file); //AG f_X509_LOOKUP_hash_dir := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_hash_dir); //AG f_X509_LOOKUP_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_new); //AG f_X509_LOOKUP_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_free); //AG f_X509_LOOKUP_by_issuer_serial := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_by_issuer_serial); //AG f_X509_LOOKUP_by_fingerprint := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_by_fingerprint); //AG f_X509_LOOKUP_ctrl := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_LOOKUP_ctrl); //AG f_X509_check_issued := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_check_issued); //AG f_X509_verify_cert := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_verify_cert); //AG f_X509_verify_cert_error_string := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_verify_cert_error_string); f_X509_get_issuer_name := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_issuer_name); f_X509_get_subject_name := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_subject_name); f_X509_get_serialNumber := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_serialNumber); f_X509_NAME_oneline := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_oneline); f_X509_NAME_get_text_by_NID := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_get_text_by_NID); f_X509_NAME_get_index_by_NID := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_get_index_by_NID); //AG f_X509_NAME_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_free); f_X509_NAME_cmp := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_cmp); f_X509_get_ext := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_ext); f_X509_get_ext_count := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_ext_count); f_X509_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_free); f_X509_CRL_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_CRL_free); f_X509V3_EXT_get := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509V3_EXT_get); f_X509V3_EXT_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509V3_EXT_print); //AG f_X509V3_EXT_d2i := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509V3_EXT_d2i); //AG f_X509V3_conf_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509V3_conf_free); //AG f_X509_EXTENSION_get_object := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_EXTENSION_get_object); f_X509_EXTENSION_get_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_EXTENSION_get_data); //AG f_X509_EXTENSION_get_critical := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_EXTENSION_get_critical); //AG f_X509_subject_name_hash := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_subject_name_hash); f_X509_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_print); f_X509_digest := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_digest); //AG f_X509_check_private_key := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_check_private_key); //AG f_EVP_sha1 := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_sha1); //AG f_EVP_sha256 := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_sha256); //AG f_EVP_md5 := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_md5); //AG f_EVP_PKEY_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_new); //AG f_EVP_PKEY_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_free); //AG { Next is v1.0.0+ ** check for nil ** } f_EVP_PKEY_get0 := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_get0); //AG f_EVP_PKEY_assign := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_assign); //AG f_EVP_PKEY_size := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_size); //AG f_EVP_PKEY_bits := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_PKEY_bits); //AG f_EVP_get_cipherbyname := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_get_cipherbyname); //AG f_EVP_des_ede3_cbc := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_des_ede3_cbc); //AG f_EVP_cleanup := GetProcAddress(GLIBEAY_DLL_Handle, FN_EVP_cleanup); f_RSA_generate_key := GetProcAddress(GLIBEAY_DLL_Handle, FN_RSA_generate_key); //AG f_RSA_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_RSA_print); //AG f_DSA_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_DSA_print); //AG f_EC_KEY_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_EC_KEY_print); //AG f_OBJ_nid2sn := GetProcAddress(GLIBEAY_DLL_Handle, FN_OBJ_nid2sn); f_OBJ_nid2ln := GetProcAddress(GLIBEAY_DLL_Handle, FN_OBJ_nid2ln); f_OBJ_obj2nid := GetProcAddress(GLIBEAY_DLL_Handle, FN_OBJ_obj2nid); f_sk_num := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_num); f_sk_value := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_value); f_sk_new_null := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_new_null); //AG f_sk_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_free); //AG f_sk_pop_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_pop_free); //AG f_sk_push := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_push); //AG f_sk_delete := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_delete); //AG f_sk_pop := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_pop); //AG f_sk_find := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_find); //AG f_sk_insert := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_insert); //AG f_sk_dup := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_dup); //AG f_sk_set := GetProcAddress(GLIBEAY_DLL_Handle, FN_sk_set); //AG f_PEM_write_bio_X509 := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_write_bio_X509); f_PEM_write_bio_X509_REQ := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_write_bio_X509_REQ); f_PEM_write_bio_X509_CRL := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_write_bio_X509_CRL); f_PEM_read_bio_X509_CRL := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_read_bio_X509_CRL);//AG f_PEM_read_bio_X509 := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_read_bio_X509); f_PEM_read_bio_PKCS7 := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_read_bio_PKCS7); f_PEM_write_bio_PKCS7 := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_write_bio_PKCS7); f_PEM_do_header := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_do_header); f_PEM_X509_INFO_read_bio := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_X509_INFO_read_bio); //AG f_PEM_write_bio_PrivateKey := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_write_bio_PrivateKey); //AG f_PEM_read_bio_PrivateKey := GetProcAddress(GLIBEAY_DLL_Handle, FN_PEM_read_bio_PrivateKey); //AG f_CRYPTO_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_CRYPTO_free); //AG f_X509_NAME_ENTRY_get_object := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_ENTRY_get_object); //AG f_X509_NAME_get_entry := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_get_entry); //AG f_X509_NAME_entry_count := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_entry_count); //AG f_X509_NAME_ENTRY_get_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_ENTRY_get_data); //AG f_X509_set_version := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_set_version); //AG f_ASN1_STRING_to_UTF8 := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_STRING_to_UTF8); //AG f_ASN1_INTEGER_set := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_INTEGER_set); //AG f_ASN1_INTEGER_get := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_INTEGER_get); f_ASN1_STRING_print := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_STRING_print); //AG f_ASN1_item_d2i := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_item_d2i); //AG f_ASN1_item_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_item_free); //AG f_ASN1_STRING_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_ASN1_STRING_free); //AG f_i2a_ASN1_OBJECT := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2a_ASN1_OBJECT); //AG f_X509_gmtime_adj := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_gmtime_adj); //AG f_X509_set_pubkey := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_set_pubkey); //AG f_X509_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_new); //AG f_X509_NAME_add_entry_by_txt := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_add_entry_by_txt); //AG f_X509_NAME_add_entry_by_NID := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_add_entry_by_NID); //AG f_X509_NAME_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_NAME_new); //AG f_X509_set_issuer_name := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_set_issuer_name); //AG f_X509_sign := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_sign); //AG f_X509_INFO_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_INFO_free); //AG f_X509_CRL_dup := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_CRL_dup); //AG f_X509_PKEY_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PKEY_free); //AG f_i2d_X509 := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_X509); //AG f_i2d_PrivateKey := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_PrivateKey); //AG f_d2i_PrivateKey := GetProcAddress(GLIBEAY_DLL_Handle, FN_d2i_PrivateKey); //AG f_i2d_ASN1_bytes := GetProcAddress(GLIBEAY_DLL_Handle, FN_i2d_ASN1_bytes); //AG f_X509_get_pubkey := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_get_pubkey);//AG f_X509_PUBKEY_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PUBKEY_free); //AG f_X509_check_purpose := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_check_purpose); //AG f_X509_PURPOSE_get_id := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PURPOSE_get_id); //AG f_X509_PURPOSE_get0 := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PURPOSE_get0); //AG f_X509_PURPOSE_get0_name := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PURPOSE_get0_name); //AG f_X509_PURPOSE_get0_sname := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PURPOSE_get0_sname); //AG f_X509_PURPOSE_get_count := GetProcAddress(GLIBEAY_DLL_Handle, FN_X509_PURPOSE_get_count); //AG f_CONF_modules_unload := GetProcAddress(GLIBEAY_DLL_Handle, FN_CONF_modules_unload); //AG { f_OPENSSL_add_all_algorithms_noconf := GetProcAddress(GLIBEAY_DLL_Handle, FN_OPENSSL_add_all_algorithms_noconf); f_OPENSSL_add_all_algorithms_conf := GetProcAddress(GLIBEAY_DLL_Handle, FN_OPENSSL_add_all_algorithms_conf); } f_OpenSSL_add_all_ciphers := GetProcAddress(GLIBEAY_DLL_Handle, FN_OpenSSL_add_all_ciphers); f_OpenSSL_add_all_digests := GetProcAddress(GLIBEAY_DLL_Handle, FN_OpenSSL_add_all_digests); f_PKCS7_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS7_new); f_PKCS7_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS7_free); f_PKCS7_set_type := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS7_set_type); f_PKCS7_content_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS7_content_new); f_PKCS7_add_certificate := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS7_add_certificate); f_PKCS12_parse := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS12_parse); f_PKCS12_verify_mac := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS12_verify_mac); f_PKCS12_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS12_free); f_PKCS12_create := GetProcAddress(GLIBEAY_DLL_Handle, FN_PKCS12_create); {$IFNDEF OPENSSL_NO_ENGINE} f_ENGINE_load_builtin_engines := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_load_builtin_engines); //AG f_ENGINE_register_all_complete := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_register_all_complete); //AG f_ENGINE_cleanup := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_cleanup); //AG f_ENGINE_by_id := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_by_id); //AG f_ENGINE_init := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_init); //AG f_ENGINE_finish := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_finish); //AG f_ENGINE_set_default := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_set_default); //AG f_ENGINE_ctrl_cmd_string := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_ctrl_cmd_string); //AG f_ENGINE_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_free); //AG f_ENGINE_load_private_key := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_load_private_key); //AG f_ENGINE_load_public_key := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_load_public_key); //AG f_ENGINE_load_ssl_client_cert := GetProcAddress(GLIBEAY_DLL_Handle, FN_ENGINE_load_ssl_client_cert); //AG f_UI_new := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_new); //AG f_UI_new_method := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_new_method); //AG f_UI_free := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_free); //AG f_UI_create_method := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_create_method); //AG f_UI_destroy_method := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_destroy_method); //AG f_UI_set_ex_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_set_ex_data); //AG f_UI_get_ex_data := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_get_ex_data); //AG f_UI_method_set_reader := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_method_set_reader); //AG f_UI_set_result := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_set_result); //AG f_UI_OpenSSL := GetProcAddress(GLIBEAY_DLL_Handle, FN_UI_OpenSSL); //AG {$ENDIF} // Check if any failed Result := not ((@f_SSLeay = nil) or (@f_SSLeay_version = nil) or (@f_ERR_get_error_line_data = nil) or (@f_ERR_peek_error = nil) or (@f_ERR_peek_last_error = nil) or (@f_ERR_get_error = nil) or (@f_ERR_error_string = nil) or (@f_ERR_error_string_n = nil) or (@f_ERR_clear_error = nil) or (@f_ERR_remove_state = nil) or //(@f_ERR_remove_thread_state = nil) or v1.0.0+ check for nil (@f_ERR_free_strings = nil) or (@f_RAND_seed = nil) or (@f_BIO_new = nil) or (@f_BIO_new_socket = nil) or (@f_BIO_new_fd = nil) or (@f_BIO_new_file = nil) or (@f_BIO_new_mem_buf = nil) or (@f_BIO_new_bio_pair = nil) or (@f_BIO_ctrl = nil) or (@f_BIO_ctrl_pending = nil) or (@f_BIO_ctrl_get_read_request = nil) or // B.S. (@f_BIO_ctrl_get_write_guarantee = nil) or (@f_BIO_s_mem = nil) or (@f_BIO_get_retry_BIO = nil) or (@f_BIO_get_retry_reason = nil) or (@f_BIO_free = nil) or (@f_BIO_read = nil) or (@f_BIO_nread = nil) or (@f_BIO_nread0 = nil) or (@f_BIO_gets = nil) or (@f_BIO_puts = nil) or (@f_BIO_push = nil) or (@f_BIO_write = nil) or (@f_BIO_nwrite = nil) or (@f_BIO_nwrite0 = nil) or (@f_d2i_X509_bio = nil) or (@f_i2d_X509_bio = nil) or (@f_d2i_PrivateKey_bio = nil) or (@f_i2d_PrivateKey_bio = nil) or (@f_d2i_X509 = nil) or (@f_d2i_PKCS12_bio = nil) or (@f_i2d_PKCS12_bio = nil) or (@f_d2i_PKCS7_bio = nil) or (@f_CRYPTO_lock = nil) or (@f_CRYPTO_add_lock = nil) or (@f_CRYPTO_num_locks = nil) or (@f_CRYPTO_set_locking_callback = nil) or (@f_CRYPTO_set_id_callback = nil) or //(@f_CRYPTO_THREADID_set_callback = nil) or // check for nil at runtime //(@f_CRYPTO_THREADID_set_numeric = nil) or // check for nil at runtime //(@f_CRYPTO_THREADID_set_pointer = nil) or // check for nil at runtime (@f_CRYPTO_set_dynlock_create_callback = nil) or (@f_CRYPTO_set_dynlock_lock_callback = nil) or (@f_CRYPTO_set_dynlock_destroy_callback = nil) or {$IFDEF OPENSSL_USE_DELPHI_MM} (@f_CRYPTO_set_mem_functions = nil) or {$ENDIF} (@f_CRYPTO_cleanup_all_ex_data = nil) or (@f_X509_dup = nil) or (@f_X509_check_ca = nil) or (@f_X509_STORE_new = nil) or (@f_X509_STORE_free = nil) or (@f_X509_STORE_add_cert = nil) or (@f_X509_STORE_add_crl = nil) or (@f_X509_STORE_add_lookup = nil) or (@f_X509_STORE_set_flags = nil) or (@f_X509_STORE_CTX_new = nil) or (@f_X509_STORE_CTX_free = nil) or (@f_X509_STORE_CTX_init = nil) or (@f_X509_STORE_CTX_cleanup = nil) or (@f_X509_STORE_CTX_get_ex_data = nil) or (@f_X509_STORE_CTX_get_current_cert = nil) or (@f_X509_STORE_CTX_get_error = nil) or (@f_X509_STORE_CTX_set_error = nil) or (@f_X509_STORE_CTX_get_error_depth = nil) or (@f_X509_STORE_CTX_get_chain = nil) or (@f_X509_STORE_CTX_trusted_stack = nil) or (@f_X509_STORE_CTX_set_purpose = nil) or (@f_X509_STORE_CTX_set_verify_cb = nil) or (@f_X509_STORE_CTX_set_ex_data = nil) or (@f_X509_load_crl_file = nil) or (@f_X509_LOOKUP_file = nil) or (@f_X509_LOOKUP_hash_dir = nil) or (@f_X509_LOOKUP_new = nil) or (@f_X509_LOOKUP_free = nil) or (@f_X509_LOOKUP_by_issuer_serial = nil) or (@f_X509_LOOKUP_by_fingerprint = nil) or //AG (@f_X509_LOOKUP_ctrl = nil) or (@f_X509_check_issued = nil) or (@f_X509_verify_cert = nil) or (@f_X509_verify_cert_error_string = nil) or (@f_X509_get_issuer_name = nil) or (@f_X509_get_subject_name = nil) or (@f_X509_get_serialNumber = nil) or (@f_X509_NAME_oneline = nil) or (@f_X509_NAME_get_text_by_NID = nil) or (@f_X509_NAME_get_index_by_NID = nil) or //AG (@f_X509_NAME_cmp = nil) or //AG (@f_X509_NAME_free = nil) or (@f_X509_get_ext = nil) or (@f_X509_get_ext_count = nil) or (@f_X509_free = nil) or (@f_X509_CRL_free = nil) or (@f_X509V3_EXT_get = nil) or (@f_X509V3_EXT_print = nil) or (@f_X509V3_EXT_d2i = nil) or (@f_X509V3_conf_free = nil) or (@f_X509_EXTENSION_get_object = nil) or (@f_X509_EXTENSION_get_data = nil) or (@f_X509_EXTENSION_get_critical = nil) or (@f_X509_subject_name_hash = nil) or (@f_X509_print = nil) or (@f_X509_digest = nil) or //AG (@f_X509_check_private_key = nil) or //AG (@f_EVP_sha1 = nil) or //AG (@f_EVP_sha256 = nil) or //AG (@f_EVP_md5 = nil) or //AG (@f_EVP_PKEY_free = nil) or //AG { Next is v1.0.0+ ** check for nil ** } //(@f_EVP_PKEY_get0 = nil) or //AG (@f_EVP_PKEY_new = nil) or //AG (@f_EVP_PKEY_assign = nil) or //AG (@f_EVP_PKEY_size = nil) or //AG (@f_EVP_PKEY_bits = nil) or //AG (@f_EVP_get_cipherbyname = nil) or //AG (@f_EVP_des_ede3_cbc = nil) or //AG (@f_EVP_cleanup = nil) or (@f_RSA_generate_key = nil) or //AG (@f_RSA_print = nil) or //AG (@f_DSA_print = nil) or //AG (@f_EC_KEY_print = nil) or //AG (@f_OBJ_nid2sn = nil) or (@f_OBJ_nid2ln = nil) or (@f_OBJ_obj2nid = nil) or (@f_sk_num = nil) or (@f_sk_value = nil) or (@f_sk_new_null = nil) or (@f_sk_free = nil) or (@f_sk_pop_free = nil) or (@f_sk_push = nil) or (@f_sk_delete = nil) or (@f_sk_pop = nil) or (@f_sk_find = nil) or (@f_sk_insert = nil) or (@f_sk_dup = nil) or (@f_sk_set = nil) or (@f_PEM_write_bio_X509 = nil) or (@f_PEM_write_bio_X509_REQ = nil) or (@f_PEM_write_bio_X509_CRL = nil) or (@f_PEM_read_bio_X509_CRL = nil) or (@f_PEM_read_bio_X509 = nil) or (@f_PEM_read_bio_PKCS7 = nil) or (@f_PEM_write_bio_PKCS7 = nil) or (@f_PEM_do_header = nil) or (@f_PEM_X509_INFO_read_bio = nil) or (@f_PEM_read_bio_PrivateKey = nil) or (@f_PEM_write_bio_PrivateKey = nil) or (@f_CRYPTO_free = nil) or (@f_X509_NAME_get_entry = nil) or (@f_X509_NAME_ENTRY_get_object = nil) or (@f_X509_NAME_entry_count = nil) or (@f_X509_NAME_ENTRY_get_data = nil) or (@f_X509_set_version = nil) or (@f_ASN1_STRING_to_UTF8 = nil) or (@f_ASN1_INTEGER_set = nil) or (@f_ASN1_INTEGER_get = nil) or (@f_ASN1_STRING_print = nil) or (@f_ASN1_item_free = nil) or (@f_ASN1_item_d2i = nil) or (@f_ASN1_STRING_free = nil) or //AG (@f_i2a_ASN1_OBJECT = nil) or (@f_X509_gmtime_adj = nil) or (@f_X509_set_pubkey = nil) or (@f_X509_new = nil) or (@f_X509_NAME_add_entry_by_txt = nil) or (@f_X509_NAME_add_entry_by_NID = nil) or (@f_X509_NAME_new = nil) or (@f_X509_set_issuer_name = nil) or (@f_X509_sign = nil) or (@f_X509_INFO_free = nil) or (@f_X509_CRL_dup = nil) or (@f_i2d_X509 = nil) or (@f_i2d_PrivateKey = nil) or (@f_d2i_PrivateKey = nil) or (@f_i2d_ASN1_bytes = nil) or (@f_X509_get_pubkey = nil) or (@f_X509_PUBKEY_free = nil) or (@f_X509_check_purpose = nil) or (@f_X509_PURPOSE_get_id = nil) or (@f_X509_PURPOSE_get0 = nil) or (@f_X509_PURPOSE_get0_name = nil) or (@f_X509_PURPOSE_get0_sname = nil) or (@f_X509_PURPOSE_get_count = nil) or (@f_CONF_modules_unload = nil) or (@f_X509_PUBKEY_free = nil) or (@f_CONF_modules_unload = nil) or { (@f_OPENSSL_add_all_algorithms_noconf = nil) or (@f_OPENSSL_add_all_algorithms_conf = nil) or } (@f_OpenSSL_add_all_ciphers = nil) or (@f_OpenSSL_add_all_digests = nil) or (@f_PKCS7_new = nil) or (@f_PKCS7_free = nil) or (@f_PKCS7_set_type = nil) or (@f_PKCS7_content_new = nil) or (@f_PKCS7_add_certificate = nil) or (@f_PKCS12_parse = nil) or (@f_PKCS12_verify_mac = nil) or (@f_PKCS12_free = nil) or (@f_PKCS12_create = nil) {$IFNDEF OPENSSL_NO_ENGINE} or (@f_ENGINE_load_builtin_engines = nil) or (@f_ENGINE_register_all_complete = nil) or (@f_ENGINE_cleanup = nil) or (@f_ENGINE_by_id = nil) or (@f_ENGINE_init = nil) or (@f_ENGINE_finish = nil) or (@f_ENGINE_set_default = nil) or (@f_ENGINE_ctrl_cmd_string = nil) or (@f_ENGINE_free = nil) or (@f_ENGINE_load_private_key = nil) or (@f_ENGINE_load_public_key = nil) or (@f_ENGINE_load_ssl_client_cert = nil) or (@f_UI_new = nil) or (@f_UI_new_method = nil) or (@f_UI_free = nil) or (@f_UI_create_method = nil) or (@f_UI_destroy_method = nil) or (@f_UI_set_ex_data = nil) or (@f_UI_get_ex_data = nil) or (@f_UI_method_set_reader = nil) or (@f_UI_set_result = nil) or (@f_UI_OpenSSL = nil) {$ENDIF} ); {$IFDEF OPENSSL_USE_DELPHI_MM} if Result then Assert(f_CRYPTO_set_mem_functions(@IcsMalloc, @IcsRealloc, @IcsFreeMem) <> 0); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function WhichFailedToLoad : String; const SP = #32; begin Result := ''; if @f_SSLeay = nil then Result := Result + SP + FN_SSLeay; if @f_SSLeay_version = nil then Result := Result + SP + FN_SSLeay_version; if @f_ERR_get_error_line_data = nil then Result := Result + SP + FN_ERR_get_error_line_data; if @f_ERR_peek_error = nil then Result := Result + SP + FN_ERR_peek_error; if @f_ERR_peek_last_error = nil then Result := Result + SP + FN_ERR_peek_last_error; if @f_ERR_get_error = nil then Result := Result + SP + FN_ERR_get_error; if @f_ERR_error_string = nil then Result := Result + SP + FN_ERR_error_string; if @f_ERR_error_string_n = nil then Result := Result + SP + FN_ERR_error_string_n; if @f_ERR_clear_error = nil then Result := Result + SP + FN_ERR_clear_error; if @f_ERR_remove_state = nil then Result := Result + SP + FN_ERR_remove_state; //if @f_ERR_remove_thread_state = nil then Result := Result + SP + FN_ERR_remove_thread_state; v1.0.0+ check for nil if @f_ERR_free_strings = nil then Result := Result + SP + FN_ERR_free_strings; if @f_RAND_seed = nil then Result := Result + SP + FN_RAND_seed; if @f_BIO_new = nil then Result := Result + SP + FN_BIO_new; if @f_BIO_new_socket = nil then Result := Result + SP + FN_BIO_new_socket; if @f_BIO_new_fd = nil then Result := Result + SP + FN_BIO_new_fd; if @f_BIO_new_file = nil then Result := Result + SP + FN_BIO_new_file; if @f_BIO_new_mem_buf = nil then Result := Result + SP + FN_BIO_new_mem_buf; if @f_BIO_new_bio_pair = nil then Result := Result + SP + FN_BIO_new_bio_pair; if @f_BIO_ctrl = nil then Result := Result + SP + FN_BIO_ctrl; if @f_BIO_ctrl_get_read_request = nil then Result := Result + SP + FN_BIO_ctrl_get_read_request; // B.S. if @f_BIO_ctrl_pending = nil then Result := Result + SP + FN_BIO_ctrl_pending; if @f_BIO_ctrl_get_write_guarantee = nil then Result := Result + SP + FN_BIO_ctrl_get_write_guarantee; if @f_BIO_s_mem = nil then Result := Result + SP + FN_BIO_s_mem; if @f_BIO_get_retry_BIO = nil then Result := Result + SP + FN_BIO_get_retry_BIO; if @f_BIO_get_retry_reason = nil then Result := Result + SP + FN_BIO_get_retry_reason; if @f_BIO_free = nil then Result := Result + SP + FN_BIO_free; if @f_BIO_read = nil then Result := Result + SP + FN_BIO_read; if @f_BIO_nread = nil then Result := Result + SP + FN_BIO_nread; if @f_BIO_nread0 = nil then Result := Result + SP + FN_BIO_nread0; if @f_BIO_gets = nil then Result := Result + SP + FN_BIO_gets; if @f_BIO_puts = nil then Result := Result + SP + FN_BIO_puts; if @f_BIO_push = nil then Result := Result + SP + FN_BIO_push; if @f_BIO_write = nil then Result := Result + SP + FN_BIO_write; if @f_BIO_nwrite = nil then Result := Result + SP + FN_BIO_nwrite; if @f_BIO_nwrite0 = nil then Result := Result + SP + FN_BIO_nwrite0; if @f_d2i_X509_bio = nil then Result := Result + SP + FN_d2i_X509_bio; if @f_i2d_X509_bio = nil then Result := Result + SP + FN_i2d_X509_bio; if @f_d2i_PrivateKey_bio = nil then Result := Result + SP + FN_d2i_PrivateKey_bio; if @f_i2d_PrivateKey_bio = nil then Result := Result + SP + FN_i2d_PrivateKey_bio; if @f_d2i_X509 = nil then Result := Result + SP + FN_d2i_X509; if @f_d2i_PKCS12_bio = nil then Result := Result + SP + FN_d2i_PKCS12_bio; if @f_i2d_PKCS12_bio = nil then Result := Result + SP + FN_i2d_PKCS12_bio; if @f_d2i_PKCS7_bio = nil then Result := Result + SP + FN_d2i_PKCS7_bio; if @f_CRYPTO_lock = nil then Result := Result + SP + FN_CRYPTO_lock; if @f_CRYPTO_add_lock = nil then Result := Result + SP + FN_CRYPTO_add_lock; if @f_CRYPTO_num_locks = nil then Result := Result + SP + FN_CRYPTO_num_locks; if @f_CRYPTO_set_locking_callback = nil then Result := Result + SP + FN_CRYPTO_set_locking_callback; if @f_CRYPTO_set_id_callback = nil then Result := Result + SP + FN_CRYPTO_set_id_callback; //if @f_CRYPTO_THREADID_set_callback = nil then Result := Result + SP + FN_CRYPTO_THREADID_set_callback; // check for nil at runtime //if @f_CRYPTO_THREADID_set_numeric = nil then Result := Result + SP + FN_CRYPTO_THREADID_set_numeric; // check for nil at runtime //if @f_CRYPTO_THREADID_set_pointer = nil then Result := Result + SP + FN_CRYPTO_THREADID_set_pointer; // check for nil at runtime if @f_CRYPTO_set_dynlock_create_callback = nil then Result := Result + SP + FN_CRYPTO_set_dynlock_create_callback; if @f_CRYPTO_set_dynlock_lock_callback = nil then Result := Result + SP + FN_CRYPTO_set_dynlock_lock_callback; if @f_CRYPTO_set_dynlock_destroy_callback = nil then Result := Result + SP + FN_CRYPTO_set_dynlock_destroy_callback; {$IFDEF OPENSSL_USE_DELPHI_MM} if @f_CRYPTO_set_mem_functions = nil then Result := Result + SP + FN_CRYPTO_set_mem_functions; {$ENDIF} if @f_CRYPTO_cleanup_all_ex_data = nil then Result := Result + SP + FN_CRYPTO_cleanup_all_ex_data; if @f_X509_dup = nil then Result := Result + SP + FN_X509_dup;//AG if @f_X509_check_ca = nil then Result := Result + SP + FN_X509_check_ca;//AG if @f_X509_STORE_new = nil then Result := Result + SP + FN_X509_STORE_new;//AG if @f_X509_STORE_free = nil then Result := Result + SP + FN_X509_STORE_free;//AG if @f_X509_STORE_add_cert = nil then Result := Result + SP + FN_X509_STORE_add_cert;//AG if @f_X509_STORE_add_crl = nil then Result := Result + SP + FN_X509_STORE_add_crl;//AG if @f_X509_STORE_add_lookup = nil then Result := Result + SP + FN_X509_STORE_add_lookup;//AG if @f_X509_STORE_set_flags = nil then Result := Result + SP + FN_X509_STORE_set_flags;//AG if @f_X509_STORE_CTX_new = nil then Result := Result + SP + FN_X509_STORE_CTX_new;//AG if @f_X509_STORE_CTX_free = nil then Result := Result + SP + FN_X509_STORE_CTX_free;//AG if @f_X509_STORE_CTX_init = nil then Result := Result + SP + FN_X509_STORE_CTX_init;//AG if @f_X509_STORE_CTX_cleanup = nil then Result := Result + SP + FN_X509_STORE_CTX_cleanup;//AG if @f_X509_STORE_CTX_get_ex_data = nil then Result := Result + SP + FN_X509_STORE_CTX_get_ex_data; if @f_X509_STORE_CTX_get_current_cert = nil then Result := Result + SP + FN_X509_STORE_CTX_get_current_cert; if @f_X509_STORE_CTX_get_error = nil then Result := Result + SP + FN_X509_STORE_CTX_get_error; if @f_X509_STORE_CTX_set_error = nil then Result := Result + SP + FN_X509_STORE_CTX_set_error; if @f_X509_STORE_CTX_get_error_depth = nil then Result := Result + SP + FN_X509_STORE_CTX_get_error_depth; if @f_X509_STORE_CTX_get_chain = nil then Result := Result + SP + FN_X509_STORE_CTX_get_chain;//AG if @f_X509_STORE_CTX_trusted_stack = nil then Result := Result + SP + FN_X509_STORE_CTX_trusted_stack;//AG if @f_X509_STORE_CTX_set_purpose = nil then Result := Result + SP + FN_X509_STORE_CTX_set_purpose;//AG if @f_X509_STORE_CTX_set_verify_cb = nil then Result := Result + SP + FN_X509_STORE_CTX_set_verify_cb;//AG if @f_X509_STORE_CTX_set_ex_data = nil then Result := Result + SP + FN_X509_STORE_CTX_set_ex_data;//AG if @f_X509_load_crl_file = nil then Result := Result + SP + FN_X509_load_crl_file;//AG if @f_X509_LOOKUP_file = nil then Result := Result + SP + FN_X509_LOOKUP_file;//AG if @f_X509_LOOKUP_hash_dir = nil then Result := Result + SP + FN_X509_LOOKUP_hash_dir;//AG if @f_X509_LOOKUP_new = nil then Result := Result + SP + FN_X509_LOOKUP_new;//AG if @f_X509_LOOKUP_free = nil then Result := Result + SP + FN_X509_LOOKUP_free;//AG if @f_X509_LOOKUP_by_issuer_serial = nil then Result := Result + SP + FN_X509_LOOKUP_by_issuer_serial;//AG if @f_X509_LOOKUP_by_fingerprint = nil then Result := Result + SP + FN_X509_LOOKUP_by_fingerprint;//AG if @f_X509_LOOKUP_ctrl = nil then Result := Result + SP + FN_X509_LOOKUP_ctrl;//AG if @f_X509_check_issued = nil then Result := Result + SP + FN_X509_check_issued;//AG if @f_X509_verify_cert = nil then Result := Result + SP + FN_X509_verify_cert;//AG if @f_X509_verify_cert_error_string = nil then Result := Result + SP + FN_X509_verify_cert_error_string; if @f_X509_get_issuer_name = nil then Result := Result + SP + FN_X509_get_issuer_name; if @f_X509_get_subject_name = nil then Result := Result + SP + FN_X509_get_subject_name; if @f_X509_get_serialNumber = nil then Result := Result + SP + FN_X509_get_serialNumber; if @f_X509_NAME_oneline = nil then Result := Result + SP + FN_X509_NAME_oneline; if @f_X509_NAME_get_text_by_NID = nil then Result := Result + SP + FN_X509_NAME_get_text_by_NID; if @f_X509_NAME_get_index_by_NID = nil then Result := Result + SP + FN_X509_NAME_get_index_by_NID;//AG if @f_X509_NAME_free = nil then Result := Result + SP + FN_X509_NAME_free; if @f_X509_NAME_cmp = nil then Result := Result + SP + FN_X509_NAME_cmp; if @f_X509_get_ext = nil then Result := Result + SP + FN_X509_get_ext; if @f_X509_get_ext_count = nil then Result := Result + SP + FN_X509_get_ext_count; if @f_X509_CRL_free = nil then Result := Result + SP + FN_X509_CRL_free;//AG if @f_X509_free = nil then Result := Result + SP + FN_X509_free;//AG if @f_X509V3_EXT_get = nil then Result := Result + SP + FN_X509V3_EXT_get; if @f_X509V3_EXT_print = nil then Result := Result + SP + FN_X509V3_EXT_print;//AG if @f_X509V3_EXT_d2i = nil then Result := Result + SP + FN_X509V3_EXT_d2i;//AG if @f_X509V3_conf_free = nil then Result := Result + SP + FN_X509V3_conf_free;//AG if @f_X509_EXTENSION_get_object = nil then Result := Result + SP + FN_X509_EXTENSION_get_object; if @f_X509_EXTENSION_get_data = nil then Result := Result + SP + FN_X509_EXTENSION_get_data;//AG if @f_X509_EXTENSION_get_critical = nil then Result := Result + SP + FN_X509_EXTENSION_get_critical;//AG if @f_X509_subject_name_hash = nil then Result := Result + SP + FN_X509_subject_name_hash; if @f_X509_print = nil then Result := Result + SP + FN_X509_print; if @f_X509_digest = nil then Result := Result + SP + FN_X509_digest; //AG if @f_X509_check_private_key = nil then Result := Result + SP + FN_X509_check_private_key; //AG if @f_EVP_sha1 = nil then Result := Result + SP + FN_EVP_sha1; //AG if @f_EVP_sha256 = nil then Result := Result + SP + FN_EVP_sha256; //AG if @f_EVP_md5 = nil then Result := Result + SP + FN_EVP_md5; //AG if @f_EVP_PKEY_free = nil then Result := Result + SP + FN_EVP_PKEY_free; //AG { Next is v1.0.0+ ** check for nil ** } //if @f_EVP_PKEY_get0 = nil then Result := Result + SP + FN_EVP_PKEY_get0; //AG if @f_EVP_PKEY_new = nil then Result := Result + SP + FN_EVP_PKEY_new; //AG if @f_EVP_PKEY_assign = nil then Result := Result + SP + FN_EVP_PKEY_assign; //AG if @f_EVP_PKEY_size = nil then Result := Result + SP + FN_EVP_PKEY_size; //AG if @f_EVP_PKEY_bits = nil then Result := Result + SP + FN_EVP_PKEY_bits; //AG if @f_EVP_get_cipherbyname = nil then Result := Result + SP + FN_EVP_get_cipherbyname; //AG if @f_EVP_des_ede3_cbc = nil then Result := Result + SP + FN_EVP_des_ede3_cbc; //AG if @f_EVP_cleanup = nil then Result := Result + SP + FN_EVP_cleanup; if @f_RSA_generate_key = nil then Result := Result + SP + FN_RSA_generate_key; //AG if @f_RSA_print = nil then Result := Result + SP + FN_RSA_print; //AG if @f_DSA_print = nil then Result := Result + SP + FN_DSA_print; //AG if @f_EC_KEY_print = nil then Result := Result + SP + FN_EC_KEY_print; //AG if @f_OBJ_nid2sn = nil then Result := Result + SP + FN_OBJ_nid2sn; if @f_OBJ_nid2ln = nil then Result := Result + SP + FN_OBJ_nid2ln; if @f_OBJ_obj2nid = nil then Result := Result + SP + FN_OBJ_obj2nid; if @f_sk_num = nil then Result := Result + SP + FN_sk_num; if @f_sk_value = nil then Result := Result + SP + FN_sk_value; if @f_sk_new_null = nil then Result := Result + SP + FN_sk_new_null;//AG if @f_sk_free = nil then Result := Result + SP + FN_sk_free;//AG if @f_sk_pop_free = nil then Result := Result + SP + FN_sk_pop_free;//AG if @f_sk_push = nil then Result := Result + SP + FN_sk_push;//AG if @f_sk_delete = nil then Result := Result + SP + FN_sk_delete;//AG if @f_sk_pop = nil then Result := Result + SP + FN_sk_pop;//AG if @f_sk_find = nil then Result := Result + SP + FN_sk_find;//AG if @f_sk_insert = nil then Result := Result + SP + FN_sk_insert;//AG if @f_sk_dup = nil then Result := Result + SP + FN_sk_dup;//AG if @f_sk_set = nil then Result := Result + SP + FN_sk_set;//AG if @f_PEM_write_bio_X509_REQ = nil then Result := Result + SP + FN_PEM_write_bio_X509_REQ; if @f_PEM_write_bio_X509_CRL = nil then Result := Result + SP + FN_PEM_write_bio_X509_CRL; if @f_PEM_read_bio_X509_CRL = nil then Result := Result + SP + FN_PEM_read_bio_X509_CRL; //AG if @f_PEM_read_bio_X509 = nil then Result := Result + SP + FN_PEM_read_bio_X509; if @f_PEM_read_bio_PKCS7 = nil then Result := Result + SP + FN_PEM_read_bio_PKCS7; if @f_PEM_write_bio_PKCS7 = nil then Result := Result + SP + FN_PEM_write_bio_PKCS7; if @f_PEM_do_header = nil then Result := Result + SP + FN_PEM_do_header; if @f_PEM_X509_INFO_read_bio = nil then Result := Result + SP + FN_PEM_X509_INFO_read_bio; //AG if @f_PEM_read_bio_PrivateKey = nil then Result := Result + SP + FN_PEM_read_bio_PrivateKey;//AG if @f_PEM_write_bio_PrivateKey = nil then Result := Result + SP + FN_PEM_write_bio_PrivateKey;//AG if @f_CRYPTO_free = nil then Result := Result + SP + FN_CRYPTO_free;//AG if @f_X509_NAME_ENTRY_get_object = nil then Result := Result + SP + FN_X509_NAME_ENTRY_get_object;//AG if @f_X509_NAME_get_entry = nil then Result := Result + SP + FN_X509_NAME_get_entry;//AG if @f_X509_NAME_entry_count = nil then Result := Result + SP + FN_X509_NAME_entry_count;//AG if @f_X509_NAME_ENTRY_get_data = nil then Result := Result + SP + FN_X509_NAME_ENTRY_get_data;//AG if @f_X509_set_version = nil then Result := Result + SP + FN_X509_set_version;//AG if @f_ASN1_STRING_to_UTF8 = nil then Result := Result + SP + FN_ASN1_STRING_to_UTF8;//AG if @f_ASN1_INTEGER_set = nil then Result := Result + SP + FN_ASN1_INTEGER_set;//AG if @f_ASN1_INTEGER_get = nil then Result := Result + SP + FN_ASN1_INTEGER_get; if @f_ASN1_STRING_print = nil then Result := Result + SP + FN_ASN1_STRING_print;//AG if @f_ASN1_item_d2i = nil then Result := Result + SP + FN_ASN1_item_d2i;//AG if @f_ASN1_item_free = nil then Result := Result + SP + FN_ASN1_item_free;//AG if @f_ASN1_STRING_free = nil then Result := Result + SP + FN_ASN1_STRING_free;//AG if @f_i2a_ASN1_OBJECT = nil then Result := Result + SP + FN_i2a_ASN1_OBJECT;//AG if @f_X509_gmtime_adj = nil then Result := Result + SP + FN_X509_gmtime_adj;//AG if @f_X509_set_pubkey = nil then Result := Result + SP + FN_X509_set_pubkey;//AG if @f_X509_new = nil then Result := Result + SP + FN_X509_new;//AG if @f_X509_NAME_add_entry_by_txt = nil then Result := Result + SP + FN_X509_NAME_add_entry_by_txt;//AG if @f_X509_NAME_add_entry_by_NID = nil then Result := Result + SP + FN_X509_NAME_add_entry_by_NID;//AG if @f_X509_NAME_new = nil then Result := Result + SP + FN_X509_NAME_new;//AG if @f_X509_set_issuer_name = nil then Result := Result + SP + FN_X509_set_issuer_name;//AG if @f_X509_sign = nil then Result := Result + SP + FN_X509_sign;//AG if @f_X509_INFO_free = nil then Result := Result + SP + FN_X509_INFO_free;//AG if @f_X509_CRL_dup = nil then Result := Result + SP + FN_X509_CRL_dup;//AG if @f_X509_PKEY_free = nil then Result := Result + SP + FN_X509_PKEY_free;//AG if @f_i2d_X509 = nil then Result := Result + SP + FN_i2d_X509;//AG if @f_i2d_PrivateKey = nil then Result := Result + SP + FN_i2d_PrivateKey;//AG if @f_d2i_PrivateKey = nil then Result := Result + SP + FN_d2i_PrivateKey;//AG if @f_i2d_ASN1_bytes = nil then Result := Result + SP + FN_i2d_ASN1_bytes;//AG if @f_X509_get_pubkey = nil then Result := Result + SP + FN_X509_get_pubkey;//AG if @f_X509_PUBKEY_free = nil then Result := Result + SP + FN_X509_PUBKEY_free;//AG if @f_X509_check_purpose = nil then Result := Result + SP + FN_X509_check_purpose;//AG if @f_X509_PURPOSE_get_id = nil then Result := Result + SP + FN_X509_PURPOSE_get_id;//AG if @f_X509_PURPOSE_get0 = nil then Result := Result + SP + FN_X509_PURPOSE_get0;//AG if @f_X509_PURPOSE_get0_name = nil then Result := Result + SP + FN_X509_PURPOSE_get0_name;//AG if @f_X509_PURPOSE_get0_sname = nil then Result := Result + SP + FN_X509_PURPOSE_get0_sname;//AG if @f_X509_PURPOSE_get_count = nil then Result := Result + SP + FN_X509_PURPOSE_get_count;//AG if @f_CONF_modules_unload = nil then Result := Result + SP + FN_CONF_modules_unload;//AG { if @f_OPENSSL_add_all_algorithms_noconf = nil then Result := Result + SP + FN_OPENSSL_add_all_algorithms_noconf; if @f_OPENSSL_add_all_algorithms_conf = nil then Result := Result + SP + FN_OPENSSL_add_all_algorithms_conf; } if @f_OpenSSL_add_all_ciphers = nil then Result := Result + SP + FN_OpenSSL_add_all_ciphers; if @f_OpenSSL_add_all_digests = nil then Result := Result + SP + FN_OpenSSL_add_all_digests; if @f_PKCS7_new = nil then Result := Result + SP + FN_PKCS7_new; if @f_PKCS7_free = nil then Result := Result + SP + FN_PKCS7_free; if @f_PKCS7_set_type = nil then Result := Result + SP + FN_PKCS7_set_type; if @f_PKCS7_content_new = nil then Result := Result + SP + FN_PKCS7_content_new; if @f_PKCS7_add_certificate = nil then Result := Result + SP + FN_PKCS7_add_certificate; if @f_PKCS12_parse = nil then Result := Result + SP + FN_PKCS12_parse; if @f_PKCS12_verify_mac = nil then Result := Result + SP + FN_PKCS12_verify_mac; if @f_PKCS12_free = nil then Result := Result + SP + FN_PKCS12_free; if @f_PKCS12_create = nil then Result := Result + SP + FN_PKCS12_create; {$IFNDEF OPENSSL_NO_ENGINE} if @f_ENGINE_load_builtin_engines = nil then Result := Result + SP + FN_ENGINE_load_builtin_engines;//AG if @f_ENGINE_register_all_complete = nil then Result := Result + SP + FN_ENGINE_register_all_complete;//AG if @f_ENGINE_cleanup = nil then Result := Result + SP + FN_ENGINE_cleanup;//AG if @f_ENGINE_by_id = nil then Result := Result + SP + FN_ENGINE_by_id;//AG if @f_ENGINE_init = nil then Result := Result + SP + FN_ENGINE_init;//AG if @f_ENGINE_finish = nil then Result := Result + SP + FN_ENGINE_finish;//AG if @f_ENGINE_set_default = nil then Result := Result + SP + FN_ENGINE_set_default;//AG if @f_ENGINE_ctrl_cmd_string = nil then Result := Result + SP + FN_ENGINE_ctrl_cmd_string;//AG if @f_ENGINE_free = nil then Result := Result + SP + FN_ENGINE_free;//AG if @f_ENGINE_load_private_key = nil then Result := Result + SP + FN_ENGINE_load_private_key;//AG if @f_ENGINE_load_public_key = nil then Result := Result + SP + FN_ENGINE_load_public_key;//AG if @f_ENGINE_load_ssl_client_cert = nil then Result := Result + SP + FN_ENGINE_load_ssl_client_cert;//AG if @f_UI_new = nil then Result := Result + SP + FN_UI_new;//AG if @f_UI_new_method = nil then Result := Result + SP + FN_UI_new_method;//AG if @f_UI_free = nil then Result := Result + SP + FN_UI_free;//AG if @f_UI_create_method = nil then Result := Result + SP + FN_UI_create_method;//AG if @f_UI_destroy_method = nil then Result := Result + SP + FN_UI_destroy_method;//AG if @f_UI_set_ex_data = nil then Result := Result + SP + FN_UI_set_ex_data;//AG if @f_UI_get_ex_data = nil then Result := Result + SP + FN_UI_get_ex_data;//AG if @f_UI_method_set_reader = nil then Result := Result + SP + FN_UI_method_set_reader;//AG if @f_UI_set_result = nil then Result := Result + SP + FN_UI_set_result;//AG if @f_UI_OpenSSL = nil then Result := Result + SP + FN_UI_OpenSSL;//AG {$ENDIF} if Length(Result) > 0 then Delete(Result, 1, 1); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IcsX509VerifyErrorToStr(ErrCode: Integer): String; begin {$IFNDEF OPENSSL_USE_RESOURCE_STRINGS} Result := String(AnsiString(f_X509_verify_cert_error_string(ErrCode))); {$ELSE} case ErrCode of X509_V_OK : Result := sX509_V_OK; X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: Result := sX509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; X509_V_ERR_UNABLE_TO_GET_CRL: Result := sX509_V_ERR_UNABLE_TO_GET_CRL; X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: Result := sX509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE; X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: Result := sX509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE; X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: Result := sX509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; X509_V_ERR_CERT_SIGNATURE_FAILURE: Result := sX509_V_ERR_CERT_SIGNATURE_FAILURE; X509_V_ERR_CRL_SIGNATURE_FAILURE: Result := sX509_V_ERR_CRL_SIGNATURE_FAILURE; X509_V_ERR_CERT_NOT_YET_VALID: Result := sX509_V_ERR_CERT_NOT_YET_VALID; X509_V_ERR_CRL_NOT_YET_VALID: Result := sX509_V_ERR_CRL_NOT_YET_VALID; X509_V_ERR_CERT_HAS_EXPIRED: Result := sX509_V_ERR_CERT_HAS_EXPIRED; X509_V_ERR_CRL_HAS_EXPIRED: Result := sX509_V_ERR_CRL_HAS_EXPIRED; X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: Result := sX509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD; X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: Result := sX509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD; X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: Result := sX509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD; X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: Result := sX509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD; X509_V_ERR_OUT_OF_MEM: Result := sX509_V_ERR_OUT_OF_MEM; X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: Result := sX509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: Result := sX509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: Result := sX509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: Result := sX509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE; X509_V_ERR_CERT_CHAIN_TOO_LONG: Result := sX509_V_ERR_CERT_CHAIN_TOO_LONG; X509_V_ERR_CERT_REVOKED: Result := sX509_V_ERR_CERT_REVOKED; X509_V_ERR_INVALID_CA: Result := sX509_V_ERR_INVALID_CA; X509_V_ERR_INVALID_NON_CA: Result := sX509_V_ERR_INVALID_NON_CA; X509_V_ERR_PATH_LENGTH_EXCEEDED: Result := sX509_V_ERR_PATH_LENGTH_EXCEEDED; X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: Result := sX509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED; X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: Result := sX509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED; X509_V_ERR_INVALID_PURPOSE: Result := sX509_V_ERR_INVALID_PURPOSE; X509_V_ERR_CERT_UNTRUSTED: Result := sX509_V_ERR_CERT_UNTRUSTED; X509_V_ERR_CERT_REJECTED: Result := sX509_V_ERR_CERT_REJECTED; X509_V_ERR_APPLICATION_VERIFICATION: Result := sX509_V_ERR_APPLICATION_VERIFICATION; X509_V_ERR_SUBJECT_ISSUER_MISMATCH: Result := sX509_V_ERR_SUBJECT_ISSUER_MISMATCH; X509_V_ERR_AKID_SKID_MISMATCH: Result := sX509_V_ERR_AKID_SKID_MISMATCH; X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: Result := sX509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH; X509_V_ERR_KEYUSAGE_NO_CERTSIGN: Result := sX509_V_ERR_KEYUSAGE_NO_CERTSIGN; X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: Result := sX509_V_ERR_UNABLE_TO_GET_CRL_ISSUER; X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: Result := sX509_V_ERR_UNHANDLED_CRITICAL_EXTENSION; X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: Result := sX509_V_ERR_KEYUSAGE_NO_CRL_SIGN; X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: Result := sX509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE; X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: Result := sX509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION; X509_V_ERR_INVALID_EXTENSION: Result := sX509_V_ERR_INVALID_EXTENSION; X509_V_ERR_INVALID_POLICY_EXTENSION: Result := sX509_V_ERR_INVALID_POLICY_EXTENSION; X509_V_ERR_NO_EXPLICIT_POLICY: Result := sX509_V_ERR_NO_EXPLICIT_POLICY; X509_V_ERR_UNNESTED_RESOURCE: Result := sX509_V_ERR_UNNESTED_RESOURCE; else Result := sX509_V_ERR_NUMBER + IntToStr(ErrCode); end; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_X509_CRL_get_issuer(crl: PX509_CRL): PX509_NAME; begin Result := crl^.crl^.issuer; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_X509_get_version(X509: PX509): Integer; begin Result := f_ASN1_INTEGER_get(X509^.cert_info^.version); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_X509_get_signature_algorithm(X509: PX509): Integer; begin Result := f_OBJ_obj2nid(X509^.sig_alg^.algorithm); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF OPENSSL_NO_ENGINE} function f_Ics_UI_set_app_data(r: PUI; arg: Pointer): Integer; begin Result := f_UI_set_ex_data(r, 0, arg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_UI_get_app_data(r: PUI): Pointer; begin Result := f_UI_get_ex_data(r, 0); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} const X509_L_FILE_LOAD = 1; X509_L_ADD_DIR = 2; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Openssl macro } function f_Ics_X509_LOOKUP_load_file(Ctx: PX509_LOOKUP; FileName: PAnsiChar; Type_: Longword): Integer; begin Result := f_X509_LOOKUP_ctrl(Ctx, X509_L_FILE_LOAD, FileName, Type_, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Openssl macro } function f_Ics_X509_LOOKUP_add_dir(Ctx: PX509_LOOKUP; DirName: PAnsiChar; Type_: Longword): Integer; begin Result := f_X509_LOOKUP_ctrl(Ctx, X509_L_ADD_DIR, DirName, Type_, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ERR_GET_REASON(ErrCode : Cardinal) : Cardinal; begin Result := (ErrCode and $FFF); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ERR_GET_LIB(ErrCode : Cardinal) : Cardinal; begin Result := ((ErrCode shr 24) and $FF); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ERR_GET_FUNC(ErrCode : Cardinal) : Cardinal; begin Result := ((ErrCode shr 12) and $FFF); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ERR_FATAL_ERROR(ErrCode : Cardinal) : Boolean; begin Result := ((ErrCode and ERR_R_FATAL) <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_X509_get_notBefore(X: PX509): PASN1_TIME; {AG 03/03/06} var PCInfo : PX509_CINF; begin if Assigned(X) then begin PCInfo := Pointer(PINT_PTR(X)^); Result := PCInfo^.Validity^.notBefore; end else Result := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_Ics_X509_get_notAfter(X: PX509): PASN1_TIME; {AG 03/03/06} var PCInfo : PX509_CINF; begin if Assigned(X) then begin PCInfo := Pointer(PINT_PTR(X)^); Result := PCInfo^.Validity^.notAfter; end else Result := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Asn1ToUTDateTime(Asn1Time: PASN1_TIME; {AG 03/03/06} out UT: TDateTime): Boolean; function IncHour(const DT: TDateTime; const IncBy: Integer): TDateTime; begin Result := ((DT * 24) + IncBy) / 24; end; function IncMin(const DT: TDateTime; const IncBy: Integer): TDateTime; begin Result := ((DT * 1440) + IncBy) / 1440; end; var Y, M, D, H, N, S : Word; I : Integer; YC : Word; { Current century } P : PAnsiChar; Offset : Integer; Str : AnsiString; IntH, IntM : Integer; Sign : Boolean; begin Result := FALSE; UT := MinDateTime; if not Assigned(Asn1Time) then Exit; try I := Asn1Time^.length; if I < 10 then Exit; P := Asn1Time.data; Y := 0; M := 0; D := 0; {H := 0; N := 0;} S := 0; if Asn1Time^.Type_ = V_ASN1_UTCTIME then begin {if I < 10 then Exit;} for I := 0 to 10 - 1 do if not (P[I] in ['0'..'9']) then Exit; DecodeDate(Now, Y, M, D); YC := (Trunc(Y / 100) * 100); Y := atoi(P[0] + P[1]); if Y < 50 then { fix century } Y := Y + YC else Y := Y + YC - 100; M := atoi(P[2] + P[3]); if (M > 12) or (M < 1) then Exit; D := atoi(P[4] + P[5]); H := atoi(P[6] + P[7]); N := atoi(P[8] + P[9]); { Do we have seconds? } if (P[10] in ['0'..'9']) and (P[11] in ['0'..'9']) then S := atoi(P[10] + P[11]); end else if Asn1Time^.Type_ = V_ASN1_GENERALIZEDTIME then begin if I < 12 then Exit; for I := 0 to 12 - 1 do if not (P[I] in ['0'..'9']) then Exit; Y := atoi(P[0] + P[1] + P[2] + P[3]); M := atoi(P[4] + P[5]); if (M > 12) or (M < 1) then Exit; D := atoi(P[6] + P[7]); H := atoi(P[8] + P[9]); N := atoi(P[10] + P[11]); { Do we have seconds? } if (P[12] in ['0'..'9']) and (P[13] in ['0'..'9']) then S := atoi(P[12] + P[13]); end else Exit; UT := EncodeDate(Y, M, D) + EncodeTime(H, N, S, 0); { Timezone Offset } { '980101000000Z' sample V_ASN1_UTCTIME GMT } { '990630000000+1000' sample timezone + 10 hours } { '20000322085551Z' sample V_ASN1_GENERALIZEDTIME GMT } I := Asn1Time^.length; if P[I - 1] <> 'Z' then // Z = GMT = offset = 0 { Offset := 0 // offset 0 else} begin // get the offset SetLength(Str, I); Dec(I); while I >= 0 do begin if P[I] in ['0'..'9'] then Dec(I) else begin if P[I] in ['-', '+'] then begin if P[I] = '-' then Sign := TRUE else Sign := FALSE; StrECopy(PAnsiChar(Str), PAnsiChar(@P[I + 1])); SetLength(Str, StrLen(PAnsiChar(Str))); Offset := atoi(Str); if Sign then Offset := -Offset; if (Offset <> 0) and (Offset >= -1200) and (Offset <= 1300) then begin IntH := (Offset div 100); IntM := (Offset mod 100); if IntH <> 0 then UT := IncHour(UT, IntH); if IntM <> 0 then UT := IncMin(UT, IntM); end; end; Break; end; end; end; Result := True; except // do nothing end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_get_flags(b: PBIO): Integer; begin // This is a hack : BIO structure has not been defined. But I know // flags member is the 6th field in the structure (index is 5) // This could change when OpenSSL is updated. Check "struct bio_st". Result := PInteger(PAnsiChar(b) + 3 * SizeOf(Pointer) + 2 * SizeOf(Integer))^; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_should_retry(b: PBIO): Boolean; begin Result := ((BIO_get_flags(b) and BIO_FLAGS_SHOULD_RETRY) <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ASN1_ITEM_ptr(iptr: PASN1_ITEM_EXP): PASN1_ITEM; begin Result := iptr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_should_read(b: PBIO): Boolean; begin Result := ((BIO_get_flags(b) and BIO_FLAGS_READ) <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_should_write(b: PBIO): Boolean; begin Result := ((BIO_get_flags(b) and BIO_FLAGS_WRITE) <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_should_io_special(b: PBIO): Boolean; begin Result := ((BIO_get_flags(b) and BIO_FLAGS_IO_SPECIAL) <> 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BIO_retry_type(b: PBIO): Integer; begin Result := (BIO_get_flags(b) and BIO_FLAGS_RWS); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OpenSslVersion : String; begin Result := String(StrPas(f_SSLeay_version(SSLEAY_VERSION))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OpenSslCompilerFlags : String; begin Result := String(StrPas(f_SSLeay_version(SSLEAY_CFLAGS))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OpenSslBuiltOn : String; begin Result := String(StrPas(f_SSLeay_version(SSLEAY_BUILT_ON))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OpenSslPlatForm : String; begin Result := String(StrPas(f_SSLeay_version(SSLEAY_PLATFORM))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function OpenSslDir : String; begin Result := String(StrPas(f_SSLeay_version(SSLEAY_DIR))); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function BMPStrToWideStr(Str : PAnsiChar; Len : Integer): UnicodeString; var I : Integer; begin SetLength(Result, Len shr 1); for I := 0 to (Len shr 1) - 1 do Result[I + 1] := WideChar(Byte(Str[I * 2 + 1]) or Byte(Str[I * 2]) shl 8); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* function EncodeOctetStr(Str : PAnsiChar; Len : Integer) : String; var I : Integer; Item : String; begin if (Len = 0) or (Str = nil) then Exit; SetLength(Result, Len * 3); I := 0; while I <= Len - 1 do begin Item := IntToHex(Ord(Str[I]), 2) + ':'; Move(Item[1], Result[I * 3 + 1], 3 * SizeOf(Char)); Inc(I); end; SetLength(Result, Length(Result) - 1); end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Asn1ToString(PAsn1 : PASN1_STRING): String; {$IFDEF UNICODE} var Len : Integer; {$ENDIF} begin if (PAsn1 = nil) or (PAsn1^.data = nil) or (PAsn1^.length <= 0) then Exit; case PAsn1^.type_ of V_ASN1_OCTET_STRING : //Result := EncodeOctetStr(PAsn1^.data, PAsn1^.length); Result := IcsBufferToHex(PAsn1^.data, PAsn1^.length, ':'); {$IFNDEF UNICODE} V_ASN1_UTF8STRING : begin { Slow, but rarely used } SetLength(Result, PAsn1^.length); Move(PAnsiChar(PAsn1^.data)^, PAnsiChar(Result)^, PAsn1^.length); Result := Utf8ToStringA(Result); { convert to Ansi } end; V_ASN1_BMPSTRING : { Reverse byte order and convert to Ansi } Result := UnicodeToAnsi(BMPStrToWideStr(PAsn1^.data, PAsn1^.length)); else { dump } SetLength(Result, PAsn1^.length); Move(Pointer(PAsn1^.data)^, Pointer(Result)^, PAsn1^.length); {$ELSE} V_ASN1_UTF8STRING : begin Len := MultiByteToWideChar(CP_UTF8, 0, PAsn1^.data, PAsn1^.length, nil, 0); SetLength(Result, Len); if Len > 0 then MultiByteToWideChar(CP_UTF8, 0, PAsn1^.data, PAsn1^.length, Pointer(Result), Len); end; V_ASN1_BMPSTRING : { Reverse byte order } Result := BMPStrToWideStr(PAsn1^.data, PAsn1^.length); else { dump } Len := MultiByteToWideChar(CP_ACP, 0, PAsn1^.data, PAsn1^.length, nil, 0); SetLength(Result, Len); if Len > 0 then MultiByteToWideChar(CP_ACP, 0, PAsn1^.data, PAsn1^.length, Pointer(Result), Len); {$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function f_SSL_get_secure_renegotiation_support(S: PSSL): Longint; begin if ICS_OPENSSL_VERSION_NUMBER >= OSSL_VER_0908N then Result := f_SSL_ctrl(S, SSL_CTRL_GET_RI_SUPPORT, 0, nil) else Result := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Ics_Ssl_EVP_PKEY_IncRefCnt(K: PEVP_PKEY; Increment: Integer = 1); begin { This is thread-safe only with a TSslStaticLock or TSslDynamicLock. } { From the OpenSSL sources I know that lock-ID CRYPTO_LOCK_EVP_PKEY is } { used by OpenSSL to protect EVP_PKEY_st.references field. } f_Crypto_lock(CRYPTO_LOCK, CRYPTO_LOCK_EVP_PKEY, PAnsiChar('Ics_Ssl_EVP_PKEY_IncRefCnt'), 0); try { This is a hack and might change with new OSSL version, search for } { "struct EVP_PKEY_st" field "references". } Inc(PInteger(PAnsiChar(K) + 2 * SizeOf(Longint))^, Increment); finally f_Crypto_lock(CRYPTO_UNLOCK, CRYPTO_LOCK_EVP_PKEY, PAnsiChar('Ics_Ssl_EVP_PKEY_IncRefCnt'), 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Ics_Ssl_EVP_PKEY_GetKey(K: PEVP_PKEY): Pointer; begin if @f_EVP_PKEY_get0 <> nil then // v1.0.0+ Result := f_EVP_PKEY_get0(K) else { * This is a hack * } {$IFDEF CPUX64} // Alignment of OSSL records is 8 bytes! Result := Pointer(PSize_t(PAnsiChar(K) + 4 * SizeOf(Longint))^); {$ELSE} Result := Pointer(PSize_t(PAnsiChar(K) + 3 * SizeOf(Longint))^); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Ics_Ssl_EVP_PKEY_GetType(K: PEVP_PKEY): Integer; begin { This is a hack and might change with new OSSL version, search } { for "struct EVP_PKEY_st" } Result := PInteger(K)^; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$ENDIF} //USE_SSL end.
(* JCore WebServices, Public Interfaces Copyright (C) 2015 Joao Morais See the file LICENSE.txt, included in this distribution, for details about the copyright. This library 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. *) unit JCoreWSIntf; {$I jcore.inc} interface uses Classes, HTTPDefs; type { IJCoreWSRequestHandler } IJCoreWSRequestHandler = interface(IInterface) ['{9456CC12-A428-DB7F-B6D8-6BA4B4877E52}'] procedure HandleRequest(const ARequest: TRequest; const AResponse: TResponse); end; { IJCoreWSRequestRouter } IJCoreWSRequestRouter = interface(IInterface) ['{631AEA60-951D-8E5C-784A-29ADA11D7FCD}'] procedure AddRequestHandler(const ARequestHandler: IJCoreWSRequestHandler; const APattern: string); procedure RouteRequest(const ARequest: TRequest; const AResponse: TResponse); end; { IJCoreWSApplicationHandler } IJCoreWSApplicationHandler = interface(IInterface) ['{9A538879-A492-0E74-397F-2E397D1A480C}'] function Params: TStrings; procedure Run; end; implementation end.
unit DAO.Departamentos; interface uses DAO.Base, Model.Departamentos, Generics.Collections, System.Classes; type TDepartamentosDAO = class(TDAO) public function Insert(aDepartamentos: Model.Departamentos.TDepartamentos): Boolean; function Update(aDepartamentos: Model.Departamentos.TDepartamentos): Boolean; function Delete(sFiltro: String): Boolean; function FindDepartamento(sFiltro: String): TObjectList<Model.Departamentos.TDepartamentos>; end; const TABLENAME = 'CAD_DEPARTAMENTOS'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TDepartamentosDAO.Insert(aDepartamentos: TDepartamentos): Boolean; var sSQL : System.string; begin Result := False; aDepartamentos.Codigo := GetKeyValue(TABLENAME, 'COD_DEPARTAMENTO'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(COD_DEPARTAMENTO, DES_DEPARTAMENTO, DES_LOG) ' + 'VALUES ' + '(:CODIGO, :DESCRICAO, :LOG);'; Connection.ExecSQL(sSQL,[aDepartamentos.Codigo, aDepartamentos.Descricao, aDepartamentos.Log], [ftInteger, ftString, ftString]); Result := True; end; function TDepartamentosDAO.Update(aDepartamentos: TDepartamentos): Boolean; var sSQL: System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DES_DEPARTAMENTO = :DESCRICAO, DES_LOG = :LOG ' + 'WHERE COD_DEPARTAMENTO = :CODIGO;'; Connection.ExecSQL(sSQL,[aDepartamentos.Descricao, aDepartamentos.Log, aDepartamentos.Codigo], [ftString, ftString, ftInteger]); Result := True; end; function TDepartamentosDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Connection.ExecSQL(sSQL); Result := True; end; function TDepartamentosDAO.FindDepartamento(sFiltro: string): TObjectList<Model.Departamentos.TDepartamentos>; var FDQuery: TFDQuery; departamentos: TObjectList<TDepartamentos>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); departamentos := TObjectList<TDepartamentos>.Create(); while not FDQuery.Eof do begin departamentos.Add(TDepartamentos.Create(FDQuery.FieldByName('COD_DEPARTAMENTO').AsInteger, FDQuery.FieldByName('DES_DEPARTAMENTO').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := departamentos; end; end.
unit FIFOUtils; interface uses Windows, FIFOIntf; function CreateFIFO : IFIFO; implementation uses FIFO; type TFIFOAdapter = class(TInterfacedObject, IFIFO) public constructor Create; destructor Destroy; override; private // IFIFO function Write(const Data; Size : integer) : hResult; stdcall; function Read(out Data; Size : integer; out Actual : integer) : hResult; stdcall; function Peek(out Data; Size : integer; out Actual : integer) : hResult; stdcall; function Advance(Size : integer; out Actual : integer) : hResult; stdcall; function Clear : hResult; stdcall; function GetSize(out Size : integer) : integer; stdcall; private fFIFO : TFIFO; end; constructor TFIFOAdapter.Create; begin inherited; fFIFO := TFIFO.Create; end; destructor TFIFOAdapter.Destroy; begin fFIFO.Free; inherited; end; function TFIFOAdapter.Write(const Data; Size : integer) : hResult; begin fFIFO.Write(Data, Size); Result := S_OK; end; function TFIFOAdapter.Read(out Data; Size : integer; out Actual : integer) : hResult; begin Actual := fFIFO.Read(Data, Size); Result := S_OK; end; function TFIFOAdapter.Peek(out Data; Size : integer; out Actual : integer) : hResult; begin Actual := fFIFO.Peek(Data, Size); Result := S_OK; end; function TFIFOAdapter.Advance(Size : integer; out Actual : integer) : hResult; begin Actual := fFIFO.Advance(Size); Result := S_OK; end; function TFIFOAdapter.Clear : hResult; begin fFIFO.Clear; Result := S_OK; end; function TFIFOAdapter.GetSize(out Size : integer) : integer; begin Size := fFIFO.Size; Result := S_OK; end; function CreateFIFO : IFIFO; begin Result := TFIFOAdapter.Create; end; end.
unit FeedbackFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommUnit, StdCtrls, ComCtrls; type TFeedbackForm = class(TForm, IFeedback) ProgressBar1: TProgressBar; Memo1: TMemo; private { Private-Deklarationen } procedure WriteMessage(const msg:string); procedure SetProgressMinMax(min,max:Integer); procedure SetPosition(position:Integer); public { Public-Deklarationen } end; var FeedbackForm: TFeedbackForm; implementation {$R *.dfm} { TForm2 } procedure TFeedbackForm.SetPosition(position: Integer); begin ProgressBar1.Position := position; end; procedure TFeedbackForm.SetProgressMinMax(min, max: Integer); begin progressbar1.Min := min; ProgressBar1.Max := max; end; procedure TFeedbackForm.WriteMessage(const msg: string); begin Memo1.Lines.Add(msg); BringToFront; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIDerBitString; {$I ..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpIDerStringBase; type IDerBitString = interface(IDerStringBase) ['{2EBCCC24-BF14-4EB1-BADA-C521439682BE}'] function GetmData: TCryptoLibByteArray; property mData: TCryptoLibByteArray read GetmData; function GetmPadBits: Int32; property mPadBits: Int32 read GetmPadBits; function GetOctets(): TCryptoLibByteArray; function GetBytes(): TCryptoLibByteArray; function GetInt32Value: Int32; property Int32Value: Int32 read GetInt32Value; end; implementation end.
program Weihnachtsbaum (input,output); { Stellt nach Eingabe der Höhe und des Zeichens einen Weihnachtsbaum dar } { Unterste Reihe des Baums ist (Hoehe*2)-1 } const LEER = ' '; var i, j, k, Hoehe : integer; Zeichen : char; begin write ('Bitte geben Sie die Höhe des Weihnachtsbaums ein: '); readln (Hoehe); write ('Bitte geben Sie das Zeichen ein, aus dem der Weihnachtsbaum erstellt werden soll: '); readln (Zeichen); if Hoehe <= 0 then writeln ('Der Weihnachtsbaum muss schon mindestens eine Einheit hoch sein!') else begin for i := 1 to Hoehe do begin j := ((i*2)-1); { Formel zur Ausgabe der Zeichen } k := Hoehe - i; { Formel zur Ausgabe der Leerzeichen } write(stringofChar(LEER, k)); { Ausgabe Leerzeichen } writeln(stringofChar(Zeichen, j)); { Ausgabe Zeichen } end; end end. { Weihnachtsbaum }
unit nscInterfaces; // Библиотека : Интерфейсы компонентов проекта "Немезис"; } // Автор : Морозов М.А; } // Начат : 16.02.2005 14.44; } // Модуль : nscInterfaces; } // Описание : Бизнес объект формы "fcSynchroView"; } // Версия : $Id: nscInterfaces.pas,v 1.43 2016/03/29 09:16:01 kostitsin Exp $ } (*------------------------------------------------------------------------------- $Log: nscInterfaces.pas,v $ Revision 1.43 2016/03/29 09:16:01 kostitsin {requestlink: 620672440 } Revision 1.42 2012/10/26 14:57:56 lulin {RequestLink:406489593} Revision 1.41 2010/03/10 19:41:58 lulin {RequestLink:196445017}. Revision 1.40 2010/03/10 17:50:39 lulin {RequestLink:196445017}. Revision 1.39 2010/03/10 16:46:28 lulin {RequestLink:196445017}. Revision 1.38 2010/03/10 13:22:16 lulin {RequestLink:196445017}. - чистка кода. Revision 1.37 2009/11/17 10:34:39 oman - fix: {RequestLink:171967027} Revision 1.36 2009/10/13 15:11:16 lulin - даём возможность указывать ячейке минимальную высоту. Revision 1.35 2009/10/12 16:35:05 lulin - исправляем по результатам [$166428831]. Revision 1.34 2009/10/12 11:27:13 lulin - коммитим после падения CVS. Revision 1.34 2009/10/08 09:50:53 lulin - показываем скроллеры и максимально подгоняем под макет. Revision 1.33 2009/10/06 13:19:01 lulin - bug fix: не собиралось. Revision 1.32 2009/10/06 13:14:05 lulin {RequestLink:162596818}. Добился правильной вёрстки. Revision 1.31 2009/04/13 12:54:38 oman - new: Локализация текста - [$143392959] Revision 1.30 2009/01/28 11:14:12 lulin - <K>: 133138664. №26. Revision 1.29 2009/01/12 17:38:11 lulin - <K>: 133138664. № 24. Revision 1.28 2008/10/29 12:04:23 lulin - <K>: 121166314. Revision 1.27 2008/08/06 16:57:06 mmorozov - bugfix: заливаем только область панели задач без детей (K<104435077>); Revision 1.26 2008/07/01 12:46:08 oman - new: При вставке из клипборда перефильтровываем дерево посимвольно (К-96474339) Revision 1.25 2008/06/26 11:18:35 oman - fix: Боремся с перетрансляцией ввода (cq11768) Revision 1.24 2008/05/15 12:39:55 oman - fix: Передаем новое описание для операций в статусбаре (cq28402) Revision 1.23 2008/03/19 06:28:30 mmorozov - new: использование константной строки при перетаскивании (в рамках CQ: OIT5-28528); Revision 1.22 2007/11/02 12:23:22 mmorozov - new: при перемещении между столбцами таблицы перехода фокуса учитываем не порядковый номер ячейки в столбце из которого переходим, а координаты ячейки (в рамках работы над CQ: OIT5-27189) + сопутствующий рефакторинг; Revision 1.21 2007/10/30 12:36:29 mmorozov В рамках работы над CQ: OIT5-27189: - TvtHideField теперь компонент с фокусом ввода; - Подключаем TvtHideField к обработке ввода с клавиатуры; - Подключаем TvtHideField к таблице перехода фокуса; Revision 1.20 2007/09/17 10:42:55 mmorozov New: - выделен интерфейс для получения уведомления о блокировке\разблокировки диспетчера форм на время выполенения операций модуля любым желающим (раньше только IvcmForm); - панель задач должна работать побыстрее, посколько перечитываем операции после добавления последней формы прецедента, а не каждой как это было раньше; - избавились от анимации в панели задач, при навигации между прецедентами; - почищен код; В рамках задачи CQ: OIT5-26623; Revision 1.19 2007/08/20 09:06:07 mmorozov - new: уведомление об изменении активной вкладки (CQ: OIT5-26352); Revision 1.18 2007/08/16 06:58:50 mmorozov - new behaviour: пишем событие фильтрации дерева также при разрушении компонета фильтрации (CQ: OIT5-26366); Revision 1.17 2007/08/03 09:39:49 oman - new: Готовимся к пабликации операций на статусбаре (cq25326) Revision 1.16 2007/07/26 09:38:38 mmorozov - new: возможность подписки на события контекстного фильтра (в рамках CQ: OIT5-25852); Revision 1.15 2007/03/30 11:02:53 oman Cleanup (ContextParams) Revision 1.14 2007/03/28 13:12:09 mmorozov - new: очистка таблицы перехода фокуса; Revision 1.13 2007/03/28 11:39:38 mmorozov - подключаем таблицу перехода фокуса к панели задач; Revision 1.12 2007/03/28 11:02:54 mmorozov - "таблица перехода фокуса" перенесена в библиотеку визуальных компонентов проекта Немезис; Revision 1.11 2007/03/27 13:59:09 mmorozov - cleanup; Revision 1.10 2007/03/27 07:41:24 mmorozov - вставка строки в сетку контролов (начало); Revision 1.9 2007/03/23 12:56:11 mmorozov - в рамках работы над представлением панели задач, представление обновляет своё содержимое при изменении данных; -------------------------------------------------------------------------------*) interface uses Controls, Classes, Windows, l3Interfaces, afwInterfaces {$IfNDef NoVCM} , vcmExternalInterfaces {$EndIf NoVCM} ; type {----------------------------------------------------------------------------} { ArrangeGrid - сетка контролов. } {----------------------------------------------------------------------------} IagRow = interface; IagColumn = interface; IagBaseCell = interface(IUnknown) {* Ячейка с компонентом. } ['{71868E30-C9ED-43C9-9ECD-63B1FE8E14FB}'] // property methods function pm_GetMinWidth: Integer; procedure pm_SetMinWidth(const aValue: Integer); {* - минимальная ширина, до которой можно уменьшать компонент. } function pm_GetFullWidth: Integer; {* - ширина, при которой компонент будет показан полностью. } function pm_GetMinHeight: Integer; procedure pm_SetMinHeight(const aValue: Integer); {* - минимальная высота, до которой можно уменьшать компонент. } function pm_GetFullHeight: Integer; {* - высота, при которой компонент будет показан полностью. } function pm_GetStartColumn: IagColumn; procedure pm_SetStartColumn(const Value: IagColumn); {-} function pm_GetEndColumn: IagColumn; procedure pm_SetEndColumn(const Value: IagColumn); {-} function pm_GetStartRow: IagRow; procedure pm_SetStartRow(const Value: IagRow); {-} function pm_GetEndRow: IagRow; procedure pm_SetEndRow(const Value: IagRow); {-} // public methods procedure ArrangeContent; {* - разместить содержимое ячейки. } procedure Constraints(const aMinWidth : Integer; const aFullWidth : Integer; const aMinHeight : Integer; const aFullHeight : Integer); {* - ограничения на размер ячейки. } procedure Attached; {* - вызывается при присоединении ячейки к таблице. } procedure RecalcConstraints; {* - пересчитать ограничения ячейки. } function TwoStageBuild: Boolean; {-} // properties property MinWidth: Integer read pm_GetMinWidth write pm_SetMinWidth; {* - минимальная ширина, до которой можно уменьшать компонент. } property FullWidth: Integer read pm_GetFullWidth; {* - ширина, при которой компонент будет показан полностью. } property MinHeight: Integer read pm_GetMinHeight write pm_SetMinHeight; {* - минимальная высота, до которой можно уменьшать компонент. } property FullHeight: Integer read pm_GetFullHeight; {* - высота, при которой компонент будет показан полностью. } property StartColumn: IagColumn read pm_GetStartColumn write pm_SetStartColumn; {-} property EndColumn: IagColumn read pm_GetEndColumn write pm_SetEndColumn; {-} property StartRow: IagRow read pm_GetStartRow write pm_SetStartRow; {-} property EndRow: IagRow read pm_GetEndRow write pm_SetEndRow; {-} end;//IagBaseCell IagControlCell = interface(IagBaseCell) {* Ячейка содержащая компонент. } ['{7E9F2C03-6B50-4CBF-B05B-D10C222EE60B}'] // property methods function pm_GetControl: TControl; procedure pm_SetControl(const aValue: TControl); {* - компонент ячейки. } // properties property Control: TControl read pm_GetControl write pm_SetControl; {* - компонент ячейки. } end;//IagControlCell IagCellsOwner = interface(IUnknown) {* Владелец ячеек. } ['{08D9593E-872C-4EEB-983B-FAEBB7825A87}'] // property methods function pm_GetCell(const aIndex: Integer): IagBaseCell; procedure pm_SetCell(const aIndex : Integer; const Value : IagBaseCell); {-} function pm_GetCellCount: Integer; {-} // public methods procedure AddCell(const aCell: IagBaseCell); {-} procedure DeleteCell(const aIndex: Integer); {-} procedure CellChanged; {-} procedure RecalcCells; {* - пересчитать размеры ячеек. } procedure ResetConstraints; {-} procedure Delete; {-} // properties property Cell[const aIndex: Integer]: IagBaseCell read pm_GetCell write pm_SetCell; {-} property CellCount: Integer read pm_GetCellCount; {-} end;//IagCellsOwner IagRow = interface(IagCellsOwner) {* Строка компонентов. } ['{7E071A62-DBAF-495E-9C98-BAA2C406F104}'] // property methods function pm_GetHeight: Integer; {-} function pm_GetTop: Integer; {-} function pm_GetBottom: Integer; {-} function pm_GetMinHeight: Integer; procedure pm_SetMinHeight(const aValue: Integer); {-} function pm_GetFullHeight: Integer; {-} function pm_GetFixedHeight: Integer; procedure pm_SetFixedHeight(const aValue: Integer); {* - строка имеет высоту фиксированного размера. } // public methods procedure SetBounds(const aTop, aBottom: Integer); {-} function TwoStageBuild: Boolean; {-} // properties property Top: Integer read pm_GetTop; {-} property Bottom: Integer read pm_GetBottom; {-} property MinHeight: Integer read pm_GetMinHeight write pm_SetMinHeight; {-} property FullHeight: Integer read pm_GetFullHeight; {-} property FixedHeight: Integer read pm_GetFixedHeight write pm_SetFixedHeight; {* - строка имеет высоту фиксированного размера. } property Height: Integer read pm_GetHeight; {-} end;//IagRow IagColumn = interface(IagCellsOwner) {* Столбец компонентов. } ['{36ECB62C-4D85-491D-A97C-1EC677AC03B9}'] // property methods function pm_GetLeft: Integer; {-} function pm_GetRight: Integer; {-} function pm_GetMinWidth: Integer; procedure pm_SetMinWidth(const aValue: Integer); {-} function pm_GetFullWidth: Integer; {-} function pm_GetWidth: Integer; {* - реальная ширина столбца. } function pm_GetFixedWidth: Integer; procedure pm_SetFixedWidth(const aValue: Integer); {* - строка имеет высоту фиксированного размера. } // public methods procedure SetBounds(const aLeft, aRight: Integer); {-} // properties property Left: Integer read pm_GetLeft; {-} property Right: Integer read pm_GetRight; {-} property MinWidth: Integer read pm_GetMinWidth write pm_SetMinWidth; {* - минимальная ширина для отображения содержимого столбца. } property FullWidth: Integer read pm_GetFullWidth; {* - ширина при которой отображается всё содержимое. } property Width: Integer read pm_GetWidth; {* - реальная ширина столбца. } property FixedWidth: Integer read pm_GetFixedWidth write pm_SetFixedWidth; {* - строка имеет высоту фиксированного размера. } end;//IagColumn InscArrangeGrid = interface(IUnknown) {* Сетка компонентов. } ['{80C2D058-A990-4CBA-8576-AAC95BF4C47D}'] // property methods function pm_GetIsEmpty: Boolean; {* - является ли таблица пустой. } function pm_GetColumn(const aIndex: Integer): IagColumn; {-} function pm_GetRow(const aIndex: Integer): IagRow; {-} function pm_GetHeight: Integer; {* - высота таблицы. } function pm_GetWidth: Integer; {* - ширина таблицы. } function pm_GetRowCount: Integer; {-} function pm_GetColumnCount: Integer; {-} function pm_GetCell(const aRow : Integer; const aCol : Integer): IagBaseCell; procedure pm_SetCell(const aRow : Integer; const aCol : Integer; const Value : IagBaseCell); {-} function pm_GetMinHeight: Integer; {-} function pm_GetMinWidth: Integer; {-} function pm_GetFullWidth: Integer; {* - ширина при которой содержимое ячейки показывается полностью. } function pm_GetFullHeight: Integer; {* - высота при которой содержимое ячейки показывается полностью. } function pm_GetLeft: Integer; {-} function pm_GetTop: Integer; {-} function pm_GetLastColumn: IagColumn; {-} function pm_GetLastRow: IagRow; {-} // property of events function pm_GetOnSizeChanged: TNotifyEvent; procedure pm_SetOnSizeChanged(const aValue: TNotifyEvent); {* - измененился размер таблицы. } // public methods function AddRow: IagRow; {* - добавить строку. } function AddColumn: IagColumn; {* - добавить столбец. } procedure SetBounds(const aLeft : Integer; const aTop : Integer; const aWidth : Integer; const aHeight : Integer); {-} procedure Recalc; {* - пересчитать размеры ячеек. } procedure MergeCells(const aRow : Integer; const aFrom : Integer; const aTo : Integer; const aCell : IagBaseCell); {* - объединить ячейки. } procedure BeginUpdate; {* - начата процедура обновления, в этот момент перестроения делать не нужно. } procedure EndUpdate; {* - закончена процедура обновления, нужно перестроить сетку, если до этого были запросы на перестроение. } function TwoStageBuild: Boolean; {-} // properties property Left: Integer read pm_GetLeft; {-} property Top: Integer read pm_GetTop; {-} property Height: Integer read pm_GetHeight; {* - высота таблицы. } property Width: Integer read pm_GetWidth; {* - ширина таблицы. } property MinHeight: Integer read pm_GetMinHeight; {-} property MinWidth: Integer read pm_GetMinWidth; {-} property FullWidth: Integer read pm_GetFullWidth; {* - ширина при которой содержимое ячейки показывается полностью. } property FullHeight: Integer read pm_GetFullHeight; {* - высота при которой содержимое ячейки показывается полностью. } property Cell[const aRow: Integer; const aCol: Integer]: IagBaseCell read pm_GetCell write pm_SetCell; {-} property Row[const aIndex: Integer]: IagRow read pm_GetRow; {-} property RowCount: Integer read pm_GetRowCount; {-} property Column[const aIndex: Integer]: IagColumn read pm_GetColumn; {-} property ColumnCount: Integer read pm_GetColumnCount; {-} property LastColumn: IagColumn read pm_GetLastColumn; {-} property LastRow: IagRow read pm_GetLastRow; {-} property IsEmpty: Boolean read pm_GetIsEmpty; {* - является ли таблица пустой. } // events property OnSizeChanged: TNotifyEvent read pm_GetOnSizeChanged write pm_SetOnSizeChanged; {* - измененился размер таблицы. } end;//InscArrangeGrid {----------------------------------------------------------------------------} { TabTable - таблица перехода фокуса. } {----------------------------------------------------------------------------} TnscTabTableKey = ( {* Команды нажатия на клавиши. } ns_kLeft, ns_kRight, ns_kUp, ns_kDown, ns_kNone );//TnscTabTableKey TnscOnProcessKey = procedure (const aKey : TnscTabTableKey) of Object; {* Событие нажатия на кнопку в компоненте, если False, то компоненту не нужно обрабатывать нажатие. } InscTabTableCell = interface(IUnknown) {* Элемент таблицы с деревьями. } ['{CCF8B348-7903-4874-9498-59D4A4C25AC5}'] // private methods function pm_GetBounds: TRect; {* - размеры ячейки в координатах экрана. } function pm_GetCurrent: Integer; procedure pm_SetCurrent(const aValue : Integer); {-} function pm_GetCount : Integer; {-} function pm_GetOnProcessKey : TnscOnProcessKey; {-} procedure pm_SetOnProcessKey(const aValue : TnscOnProcessKey); {-} function pm_GetControl: TWinControl; {-} // public methods procedure SetFocus(const aFromNext: Boolean = True); {* - установить фокус, который был у следующего элемента. Это нужно для установки на первый\последний элемент деревьев. } // public properties property Current : Integer read pm_GetCurrent write pm_SetCurrent; {-} property Count : Integer read pm_GetCount; {-} property Bounds: TRect read pm_GetBounds; {* - размеры ячейки в координатах экрана. } // public events property OnProcessKey : TnscOnProcessKey read pm_GetOnProcessKey write pm_SetOnProcessKey; {* - обработчик события нажатия на клавишу в компоненте. } property Control : TWinControl read pm_GetControl; {-} end;//InscTabTableCell InscTabTableColumn = interface(IUnknown) {* Столбец таблицы с деревьями. } ['{516A139E-15C7-465E-AC19-D9AA8596B555}'] // public methods procedure AddItem(const aItem: InscTabTableCell); {* - добавляет элемент в список. } end;//InscTabTableColumn InscTabTable = interface(IUnknown) {* Таблица с деревьями для переключения фокуса между деревьями с клавиатуры. } ['{33052648-30B9-4718-9F30-99AE85313C61}'] // property methods function pm_GetColumnCount: Integer; {-} function pm_GetColumn(const aIndex: Integer): InscTabTableColumn; {-} // public methods function AddColumn : InscTabTableColumn; {* - добавляет новый столбец. } procedure Clear; {-} // properties property ColumnCount: Integer read pm_GetColumnCount; {-} property Column[const aIndex: Integer]: InscTabTableColumn read pm_GetColumn; {-} end;//InscTabTable implementation end.
unit ProgressIndicatorKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ProgressIndicator } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\ProgressIndicatorKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ProgressIndicatorKeywordsPack" MUID: (F2E44CE2B086) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses {$If NOT Defined(NoVCL)} , ComCtrls {$IfEnd} // NOT Defined(NoVCL) ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , ProgressIndicator_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_ProgressIndicator = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ProgressIndicator ---- *Пример использования*: [code] 'aControl' форма::ProgressIndicator TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ProgressIndicator Tkw_ProgressIndicator_Control_ProgressBar = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ProgressBar ---- *Пример использования*: [code] контрол::ProgressBar TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ProgressIndicator_Control_ProgressBar Tkw_ProgressIndicator_Control_ProgressBar_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ProgressBar ---- *Пример использования*: [code] контрол::ProgressBar:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ProgressIndicator_Control_ProgressBar_Push TkwEfProgressIndicatorProgressBar = {final} class(TtfwPropertyLike) {* Слово скрипта .TefProgressIndicator.ProgressBar } private function ProgressBar(const aCtx: TtfwContext; aefProgressIndicator: TefProgressIndicator): TProgressBar; {* Реализация слова скрипта .TefProgressIndicator.ProgressBar } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfProgressIndicatorProgressBar function Tkw_Form_ProgressIndicator.GetString: AnsiString; begin Result := 'efProgressIndicator'; end;//Tkw_Form_ProgressIndicator.GetString class function Tkw_Form_ProgressIndicator.GetWordNameForRegister: AnsiString; begin Result := 'форма::ProgressIndicator'; end;//Tkw_Form_ProgressIndicator.GetWordNameForRegister function Tkw_ProgressIndicator_Control_ProgressBar.GetString: AnsiString; begin Result := 'ProgressBar'; end;//Tkw_ProgressIndicator_Control_ProgressBar.GetString class procedure Tkw_ProgressIndicator_Control_ProgressBar.RegisterInEngine; begin inherited; TtfwClassRef.Register(TProgressBar); end;//Tkw_ProgressIndicator_Control_ProgressBar.RegisterInEngine class function Tkw_ProgressIndicator_Control_ProgressBar.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ProgressBar'; end;//Tkw_ProgressIndicator_Control_ProgressBar.GetWordNameForRegister procedure Tkw_ProgressIndicator_Control_ProgressBar_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ProgressBar'); inherited; end;//Tkw_ProgressIndicator_Control_ProgressBar_Push.DoDoIt class function Tkw_ProgressIndicator_Control_ProgressBar_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ProgressBar:push'; end;//Tkw_ProgressIndicator_Control_ProgressBar_Push.GetWordNameForRegister function TkwEfProgressIndicatorProgressBar.ProgressBar(const aCtx: TtfwContext; aefProgressIndicator: TefProgressIndicator): TProgressBar; {* Реализация слова скрипта .TefProgressIndicator.ProgressBar } begin Result := aefProgressIndicator.ProgressBar; end;//TkwEfProgressIndicatorProgressBar.ProgressBar class function TkwEfProgressIndicatorProgressBar.GetWordNameForRegister: AnsiString; begin Result := '.TefProgressIndicator.ProgressBar'; end;//TkwEfProgressIndicatorProgressBar.GetWordNameForRegister function TkwEfProgressIndicatorProgressBar.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TProgressBar); end;//TkwEfProgressIndicatorProgressBar.GetResultTypeInfo function TkwEfProgressIndicatorProgressBar.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfProgressIndicatorProgressBar.GetAllParamsCount function TkwEfProgressIndicatorProgressBar.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefProgressIndicator)]); end;//TkwEfProgressIndicatorProgressBar.ParamsTypes procedure TkwEfProgressIndicatorProgressBar.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ProgressBar', aCtx); end;//TkwEfProgressIndicatorProgressBar.SetValuePrim procedure TkwEfProgressIndicatorProgressBar.DoDoIt(const aCtx: TtfwContext); var l_aefProgressIndicator: TefProgressIndicator; begin try l_aefProgressIndicator := TefProgressIndicator(aCtx.rEngine.PopObjAs(TefProgressIndicator)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefProgressIndicator: TefProgressIndicator : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ProgressBar(aCtx, l_aefProgressIndicator)); end;//TkwEfProgressIndicatorProgressBar.DoDoIt initialization Tkw_Form_ProgressIndicator.RegisterInEngine; {* Регистрация Tkw_Form_ProgressIndicator } Tkw_ProgressIndicator_Control_ProgressBar.RegisterInEngine; {* Регистрация Tkw_ProgressIndicator_Control_ProgressBar } Tkw_ProgressIndicator_Control_ProgressBar_Push.RegisterInEngine; {* Регистрация Tkw_ProgressIndicator_Control_ProgressBar_Push } TkwEfProgressIndicatorProgressBar.RegisterInEngine; {* Регистрация efProgressIndicator_ProgressBar } TtfwTypeRegistrator.RegisterType(TypeInfo(TefProgressIndicator)); {* Регистрация типа TefProgressIndicator } TtfwTypeRegistrator.RegisterType(TypeInfo(TProgressBar)); {* Регистрация типа TProgressBar } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit uAbstractProtoBufClasses; interface uses SysUtils, Classes, {$IFDEF FPC} fgl, {$ELSE} System.Generics.Collections, {$ENDIF} pbInput, pbOutput; type TFieldState = set of (fsRequired, fsHasValue); TAbstractProtoBufClass = class(TObject) strict private type {$IFDEF FPC} TFieldStates = TFPGMap<Integer, TFieldState>; {$ELSE} TFieldStates = TDictionary<integer, TFieldState>; {$ENDIF} strict private FFieldStates: TFieldStates; function GetFieldState(Tag: Integer): TFieldState; procedure AddFieldState(Tag: Integer; AFieldState: TFieldState); procedure ClearFieldState(Tag: Integer; AFieldState: TFieldState); function GetFieldHasValue(Tag: Integer): Boolean; procedure SetFieldHasValue(Tag: Integer; const Value: Boolean); strict protected procedure AddLoadedField(Tag: integer); procedure RegisterRequiredField(Tag: integer); procedure BeforeLoad; virtual; procedure AfterLoad; virtual; function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: integer; WireType: integer): Boolean; virtual; procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); virtual; procedure SaveMessageFieldToBuf(AField: TAbstractProtoBufClass; AFieldNumber: Integer; AFieldProtoBufOutput, AMainProtoBufOutput: TProtoBufOutput); public constructor Create; virtual; destructor Destroy; override; procedure LoadFromMem(const Mem: Pointer; const Size: Integer; const OwnsMem: Boolean = False); procedure LoadFromStream(Stream: TStream); procedure SaveToStream(Stream: TStream); procedure LoadFromBuf(ProtoBuf: TProtoBufInput); procedure SaveToBuf(ProtoBuf: TProtoBufOutput); function Copy: TAbstractProtoBufClass; function AllRequiredFieldsValid: Boolean; property FieldHasValue[Tag: Integer]: Boolean read GetFieldHasValue write SetFieldHasValue; end; {$IFDEF FPC} TProtoBufClassList<T: TAbstractProtoBufClass> = class(TFPGObjectList<T>) {$ELSE} TProtoBufClassList<T: TAbstractProtoBufClass, constructor> = class(TObjectList<T>) {$ENDIF} public function AddFromBuf(ProtoBuf: TProtoBufInput; FieldNum: integer): Boolean; virtual; procedure SaveToBuf(ProtoBuf: TProtoBufOutput; FieldNumForItems: integer); virtual; end; //ideally TAbstractProtoBufClass would be called TProtoBufMessage, so create an alias //for future code to use TProtoBufMessage = TAbstractProtoBufClass; TProtoBufMessageClass = class of TAbstractProtoBufClass; {$IFDEF FPC} TPBList<T> = class(TFPGList<T>); {$ELSE} TPBList<T> = class(TList<T>); {$ENDIF} implementation uses pbPublic; { TAbstractProtoBufClass } function TAbstractProtoBufClass.GetFieldState(Tag: Integer): TFieldState; {$IFDEF FPC} var idx: Integer; begin if FFieldStates.Find(Tag, idx) then Result:= FFieldStates.Data[idx] else Result:= []; {$ELSE} begin Result:= []; FFieldStates.TryGetValue(Tag, Result); {$ENDIF} end; procedure TAbstractProtoBufClass.AddFieldState(Tag: integer; AFieldState: TFieldState); begin {$IFDEF FPC} FFieldStates[Tag]:= GetFieldState(Tag) + AFieldState; {$ELSE} FFieldStates.AddOrSetValue(Tag, GetFieldState(Tag) + AFieldState); {$ENDIF} end; procedure TAbstractProtoBufClass.AddLoadedField(Tag: integer); begin AddFieldState(Tag, [fsHasValue]); end; procedure TAbstractProtoBufClass.AfterLoad; begin end; procedure TAbstractProtoBufClass.BeforeLoad; {$IFDEF FPC} var i: Integer; begin for i:= 0 to FFieldStates.Count - 1 do FFieldStates.Data[i]:= FFieldStates.Data[i] - [fsHasValue]; {$ELSE} var pair: TPair<integer, TFieldState>; begin //clear HasValue flags for pair in FFieldStates do FFieldStates.Items[pair.Key]:= pair.Value - [fsHasValue]; {$ENDIF} end; procedure TAbstractProtoBufClass.ClearFieldState(Tag: Integer; AFieldState: TFieldState); begin {$IFDEF FPC} FFieldStates[Tag]:= GetFieldState(Tag) - AFieldState; {$ELSE} FFieldStates.AddOrSetValue(Tag, GetFieldState(Tag) - AFieldState); {$ENDIF} end; function TAbstractProtoBufClass.Copy: TAbstractProtoBufClass; var Stream: TStream; begin Result:= TProtoBufMessageClass(Self.ClassType).Create; Stream:= TMemoryStream.Create; try SaveToStream(Stream); Stream.Seek(0, soBeginning); Result.LoadFromStream(Stream); finally Stream.Free; end; end; constructor TAbstractProtoBufClass.Create; begin inherited Create; FFieldStates:= TFieldStates.Create; {$IFDEF FPC} FFieldStates.Sorted:= True; {$ENDIF} end; destructor TAbstractProtoBufClass.Destroy; begin FreeAndNil(FFieldStates); inherited; end; function TAbstractProtoBufClass.GetFieldHasValue(Tag: Integer): Boolean; begin Result:= fsHasValue in GetFieldState(Tag); end; function TAbstractProtoBufClass.AllRequiredFieldsValid: Boolean; {$IFDEF FPC} var i: Integer; begin Result := True; for i:= 0 to FFieldStates.Count - 1 do if FFieldStates.Data[i] * [fsRequired, fsHasValue] = [fsRequired] then Exit(False); {$ELSE} var state: TFieldState; begin Result := True; for state in FFieldStates.Values do if state * [fsRequired, fsHasValue] = [fsRequired] then begin Result:= False; Break; end; {$ENDIF} end; procedure TAbstractProtoBufClass.LoadFromBuf(ProtoBuf: TProtoBufInput); var FieldNumber: integer; Tag: integer; begin BeforeLoad; Tag := ProtoBuf.readTag; while Tag <> 0 do begin FieldNumber := getTagFieldNumber(Tag); if not LoadSingleFieldFromBuf(ProtoBuf, FieldNumber, getTagWireType(Tag)) then ProtoBuf.skipField(Tag) else AddLoadedField(FieldNumber); Tag := ProtoBuf.readTag; end; if not AllRequiredFieldsValid then raise EStreamError.CreateFmt('Loading %s: not all required fields have been loaded', [ClassName]); AfterLoad; end; procedure TAbstractProtoBufClass.LoadFromMem(const Mem: Pointer; const Size: Integer; const OwnsMem: Boolean); var pb: TProtoBufInput; begin pb := TProtoBufInput.Create(Mem, Size, OwnsMem); try LoadFromBuf(pb); finally pb.Free; end; end; procedure TAbstractProtoBufClass.LoadFromStream(Stream: TStream); var pb: TProtoBufInput; tmpStream: TStream; begin pb := TProtoBufInput.Create; try tmpStream := TMemoryStream.Create; try tmpStream.CopyFrom(Stream, Stream.Size - Stream.Position); tmpStream.Seek(0, soBeginning); pb.LoadFromStream(tmpStream); finally tmpStream.Free; end; LoadFromBuf(pb); finally pb.Free; end; end; function TAbstractProtoBufClass.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: integer; WireType: integer): Boolean; begin Result := False; end; procedure TAbstractProtoBufClass.RegisterRequiredField(Tag: integer); begin AddFieldState(Tag, [fsRequired]); end; procedure TAbstractProtoBufClass.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); begin if not AllRequiredFieldsValid then raise EStreamError.CreateFmt('Saving %s: not all required fields have been set', [ClassName]); end; procedure TAbstractProtoBufClass.SaveMessageFieldToBuf( AField: TAbstractProtoBufClass; AFieldNumber: Integer; AFieldProtoBufOutput, AMainProtoBufOutput: TProtoBufOutput); begin AFieldProtoBufOutput.Clear; AField.SaveToBuf(AFieldProtoBufOutput); AMainProtoBufOutput.writeMessage(AFieldNumber, AFieldProtoBufOutput); end; procedure TAbstractProtoBufClass.SaveToBuf(ProtoBuf: TProtoBufOutput); begin SaveFieldsToBuf(ProtoBuf); end; procedure TAbstractProtoBufClass.SaveToStream(Stream: TStream); var pb: TProtoBufOutput; begin pb := TProtoBufOutput.Create; try SaveToBuf(pb); pb.SaveToStream(Stream); finally pb.Free; end; end; procedure TAbstractProtoBufClass.SetFieldHasValue(Tag: Integer; const Value: Boolean); begin if Value then AddFieldState(Tag, [fsHasValue]) else ClearFieldState(Tag, [fsHasValue]); end; { TProtoBufList<T> } function TProtoBufClassList<T>.AddFromBuf(ProtoBuf: TProtoBufInput; FieldNum: integer): Boolean; var tmpBuf: TProtoBufInput; Item: T; begin if ProtoBuf.LastTag <> makeTag(FieldNum, WIRETYPE_LENGTH_DELIMITED) then begin Result := False; exit; end; tmpBuf := ProtoBuf.ReadSubProtoBufInput; try Item := T.Create; try Item.LoadFromBuf(tmpBuf); Add(Item); Item := nil; finally Item.Free; end; finally tmpBuf.Free; end; Result := True; end; procedure TProtoBufClassList<T>.SaveToBuf(ProtoBuf: TProtoBufOutput; FieldNumForItems: integer); var i: integer; tmpBuf: TProtoBufOutput; begin tmpBuf := TProtoBufOutput.Create; try for i := 0 to Count - 1 do begin tmpBuf.Clear; Items[i].SaveToBuf(tmpBuf); ProtoBuf.writeMessage(FieldNumForItems, tmpBuf); end; finally tmpBuf.Free; end; end; end.
program ZahlenListeEinAus (input,output); {Liest eine Folge natürlicher Zahlen in eine lineare Liste ein und gibt diese anschließend wieder in der gleichen Reihenfolge aus} type tRefListe = ^tListe; tListe = record info : integer; next : tRefListe end; var Zahl : integer; ListenAnfang, ListenEnde, Zeiger : tRefListe; procedure ElementAnhaengen ( inZahl : integer; var ioRefAnfang, ioRefEnde : tRefListe); var ZeigerNeu : tRefListe; begin {neuen Zeiger erzeugen} new(ZeigerNeu); ZeigerNeu^.info := inZahl; ZeigerNeu^.next := nil; if (ioRefAnfang = nil) then {Liste ist leer} begin ioRefAnfang := ZeigerNeu; ioRefEnde := ZeigerNeu; end {if} else {Liste hat schon Element(e)} begin ioRefEnde^.next := ZeigerNeu; ioRefEnde := ZeigerNeu; end;{else} end;{procedure ElementAnhaengen} begin {Initialisierung} ListenAnfang := nil; ListenEnde := nil; writeln('Bitte geben Sie natürliche Zahlen ein, die 0 beendet die Eingabe'); read(Zahl); while (Zahl <> 0) do {Zahlen einlesen bis zur Eingabe 0} begin ElementAnhaengen(Zahl,ListenAnfang,ListenEnde); read(Zahl); end; writeln; {Liste wird ausgegeben, bei leere Liste wird nil ausgegeben} Zeiger := ListenAnfang; while (Zeiger <> nil) do begin write(Zeiger^.info:6); Zeiger := Zeiger^.next; end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSConsts.pas } { File version: 5.02 } { Description: TLS Constants } { } { Copyright: Copyright (c) 2008-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { 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 REGENTS 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2008/01/18 0.01 Initial development. } { 2020/05/09 5.02 Create flcTLSConsts unit from flcTLSUtils unit. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSConsts; interface { } { Fundamentals TLS library } { } const FundamentalsTLSLibraryVersion = '1.00'; { } { TLS Limits } { } const TLS_PLAINTEXT_FRAGMENT_MAXSIZE = 16384 - 1; // 2^14 - 1 TLS_COMPRESSED_FRAGMENT_MAXSIZE = 16384 + 1024; // 2^14 + 1024 implementation end.
program Ch2; {$mode objfpc} uses SysUtils,GVector; type TVec = specialize TVector<Integer>; TFunc = function(N:Integer):Boolean; var I:Integer; Vec:TVec; function ReverseNum(N:Integer):Integer; begin Result := 0; while(N <> 0) do begin Result := (Result * 10) + (N mod 10); N := N div 10; end; end; function SplitNum(N:Integer):TVec; begin Result := TVec.Create; while(N <> 0) do begin Result.PushBack(N mod 10); N := N div 10; end; end; function All(Vec:TVec;P:TFunc):Boolean; var I:Integer; begin for I in Vec do if not P(I) then Exit(False); Exit(True); end; function IsReversibleNumber(N:Integer):Boolean; var Sum:Integer; begin Sum := N + ReverseNum(N); if All(SplitNum(Sum), @Odd) then Exit(True); Exit(False); end; begin I := 1; while(I < 100) do begin if IsReversibleNumber(I) then Write(I, ' '); Inc(I); end; end.
{***************************************************************************} { } { 功能:Scintilla类封装 } { 名称:ScintillaClass.pas } { 版本:1.0 } { 环境:Win7 Sp1 32bit } { 工具:Delphi 7 } { 日期:2013/5/30 13:38:34 } { 作者:ying32 } { QQ :396506155 } { MSN :ying_32@live.cn } { E-mail:yuanfen3287@vip.qq.com } { Website:http://www.ying32.tk } { 版权所有 (C) 2013-2013 ying32.tk All Rights Reserved } { } {***************************************************************************} unit ScintillaClass; {$I Notpad_Plugin.inc} interface uses Windows, SysUtils, NppMacro, NppPluginInc; { TScintilla } type TScintilla = class private FNppData: TNppData; FSciHandle: HWND; private procedure SetCurSci; function GetCurSciHandle: HWND; function GetLength: Integer; function GetLine: Integer; procedure SetGoToLine(Lines: Integer); procedure SetZoomLevel(Level: Integer); function GetZoomLevel: Integer; procedure SetGoToPos(Posi: Integer); function GetPos: Integer; procedure SetText(const Text: string); function GetText:string; public constructor Create(NppData: TNppData);overload; destructor Destroy;override; procedure ReplaceSel(const Text: string); procedure AppedText(const Text: string); procedure EnSureVisible(Lines: Integer); public property Handle : HWND read GetCurSciHandle; property Length : Integer read GetLength; property Lines : Integer read GetLine write SetGoToLine; property ZoomLevel: Integer read GetZoomLevel write SetZoomLevel; property Position : Integer read GetPos write SetGoToPos; property Text: string read GetText write SetText; end; implementation { TScintilla } constructor TScintilla.Create(NppData: TNppData); begin inherited Create; FNppData := NppData; end; destructor TScintilla.Destroy; begin inherited; end; procedure TScintilla.AppedText(const Text: string); begin SetCurSci; Npp_SciAppedText(FSciHandle, Text); end; procedure TScintilla.EnSureVisible(Lines: Integer); begin SetCurSci; Npp_SciEnSureVisible(FSciHandle, Lines); end; function TScintilla.GetLength: Integer; begin SetCurSci; Result := Npp_SciGetLength(FSciHandle); end; function TScintilla.GetLine: Integer; begin SetCurSci; Result := Npp_SciGetLine(FSciHandle); end; function TScintilla.GetZoomLevel: Integer; begin SetCurSci; Result := Npp_SciGetZoomLevel(FSciHandle); end; procedure TScintilla.SetGoToLine(Lines: Integer); begin SetCurSci; Npp_SciGoToLine(FSciHandle, Lines); end; procedure TScintilla.SetGoToPos(Posi: Integer); begin SetCurSci; Npp_SciGoToPos(FSciHandle, Posi); end; procedure TScintilla.ReplaceSel(const Text: string); begin SetCurSci; Npp_SciReplaceSel(FSciHandle, Text); end; procedure TScintilla.SetText(const Text: string); begin SetCurSci; Npp_SciSetText(FSciHandle, Text); end; function TScintilla.GetText:string; begin SetCurSci; Result := Npp_SciGetText(FSciHandle); end; procedure TScintilla.SetZoomLevel(Level: Integer); begin SetCurSci; Npp_SciSetZoomLevel(FSciHandle, Level); end; function TScintilla.GetPos: Integer; begin SetCurSci; Result := 0;//Npp_Sci_ end; procedure TScintilla.SetCurSci; begin FSciHandle := Npp_GetCurrentScintillaHandle(FNppData); end; function TScintilla.GetCurSciHandle: HWND; begin SetCurSci; Result := FSciHandle; end; end.
const cGain_ExpFactor = 0.840896415; cGain_ScaledOne_4_12 = $1000; cGain_ScaledOne_0_8 = $FF; procedure UpdateFromTrackbar_4_12(aLink : ISignalLink; aTrackbar : TInstrumentTrackBar; aLabel : TInstrumentLabel); var Gain : Double; Scaled : Cardinal; DB : Double; begin Gain := Power(cGain_ExpFactor, (aTrackBar.MaxValue div 2) - aTrackBar.Value); Scaled := Round(cGain_ScaledOne_4_12 * Gain); aLink.Value := Scaled; DB := 20 * Log10(Gain); aLabel.Caption := FloatToStrF(DB, ffFixed, 4, 0) + ' dB'; end; procedure UpdateFromTrackbar_0_8(aLink : ISignalLink; aTrackbar : TInstrumentTrackBar; aLabel : TInstrumentLabel); var Gain : Double; Scaled : Cardinal; DB : Double; begin Gain := Power(cGain_ExpFactor, (aTrackBar.MaxValue) - aTrackBar.Value); Scaled := Round(cGain_ScaledOne_0_8 * Gain); aLink.Value := Scaled; DB := 20 * Log10(Gain/2.0); aLabel.Caption := FloatToStrF(DB, ffFixed, 4, 0) + ' dB'; end; // widths <= 32 supported function ValueFromSignedSignal(aLink : SignalLink; aWidth : Integer) : Integer; var ShiftedUnsigned32Bit : Cardinal; begin ShiftedUnsigned32Bit := aLink.Value Shl (32 - aWidth); Result := ShiftedUnsigned32Bit; Result := Result div Power(2, (32 - aWidth)); end; function ValueFromSignedFixedPointSignal(aLink : SignalLink; aWidth : Integer; aFractionBits : Integer) : Double; begin Result := ValueFromSignedSignal(aLink, aWidth); Result := Result / Power(2, (aFractionBits)); end;
unit ATxIconsProc; interface uses Windows, Controls; procedure FSaveIcons(IL: TImageList; const FN: string); procedure FLoadIcons(IL: TImageList; const FN: string); implementation uses SysUtils, Classes, Graphics, ATxParamStr; const clTool: TColor = $00FFFFEF; //Back color for saving //---------------------------------------------------------- //Get sizes from "Name WWxHH text.bmp". // 0 if size not found. procedure FGetIconSizes(const FN: string; var Width, Height: Integer); const Dig = ['0'..'9']; var S, S1, S2: string; i, i1, i2: integer; begin Width:= 0; Height:= 0; S:= FN; i:= Length(S) - 1; //Search last 'x' with next digit: while (i > 0) and not ( (S[i] = 'x') and (S[i+1] in Dig) ) do Dec(i); if i = 0 then Exit; i1:= i - 1; while (i1 > 0) and (S[i1] in Dig) do Dec(i1); if i1 = 0 then Exit; i2:= i + 1; while (i2 <= Length(S)) and (S[i2] in Dig) do Inc(i2); if i2 >= Length(S) then Exit; S1:= Copy(S, i1 + 1, i - i1 - 1); S2:= Copy(S, i + 1, i2 - i - 1); //MessageBox(0, PChar(S1 + #13 + S2), 'Test', MB_OK); Width:= StrToIntDef(S1, Width); Height:= StrToIntDef(S2, Height); end; //---------------------------------------------------------- procedure FSaveIcons(IL: TImageList; const FN: string); var b: TBitmap; i: Integer; begin b := TBitmap.Create; b.PixelFormat := pf24bit; try with IL do begin b.Height := Height; b.Width := Width * Count; b.Canvas.Brush.Color := clTool; b.Canvas.FillRect(Rect(0, 0, b.Width, b.Height)); for i := 0 to Count - 1 do Draw(b.Canvas, i * Width, 0, i); end; b.SaveToFile(FN); finally b.Free; end; end; //---------------------------------------------------------- procedure FLoadIcons(IL: TImageList; const FN: string); var b: TBitmap; W, H: Integer; begin b:= TBitmap.Create; try try b.LoadFromFile(FN); except Exit; end; with IL do begin Clear; FGetIconSizes(FN, W, H); if W = 0 then W := b.Height; if H = 0 then H := b.Height; Width := W; Height := H; AddMasked(b, b.Canvas.Pixels[0, H - 1]); end; finally b.Free; end; end; end.
Program cjpeg; { Original: cjpeg.c ; Copyright (C) 1991-1996, Thomas G. Lane. } { This file contains a command-line user interface for the JPEG compressor. } { Two different command line styles are permitted, depending on the compile-time switch TWO_FILE_COMMANDLINE: cjpeg [options] inputfile outputfile cjpeg [options] [inputfile] In the second style, output is always to standard output, which you'd normally redirect to a file or pipe to some other program. Input is either from a named file or from standard input (typically redirected). The second style is convenient on Unix but is unhelpful on systems that don't support pipes. Also, you MUST use the first style if your system doesn't do binary I/O to stdin/stdout. To simplify script writing, the "-outfile" switch is provided. The syntax cjpeg [options] -outfile outputfile inputfile works regardless of which command line style is used. } {$I jconfig.inc} {$undef PPM_SUPPORTED} uses jmorecfg, cdjpeg, { Common decls for cjpeg/djpeg applications } {jversion,} { for version message } jpeglib, jerror, jinclude, JDataDst, JcAPImin, JcAPIstd, JcParam, {$ifdef TARGA_SUPPORTED} rdtarga, {$endif} {$ifdef BMP_SUPPORTED} rdbmp, {$endif} {$ifdef EXT_SWITCH} rdswitch, {$endif} {cderror,} jdeferr; { This routine determines what format the input file is, and selects the appropriate input-reading module. To determine which family of input formats the file belongs to, we may look only at the first byte of the file, since C does not guarantee that more than one character can be pushed back with ungetc. Looking at additional bytes would require one of these approaches: 1) assume we can fseek() the input file (fails for piped input); 2) assume we can push back more than one character (works in some C implementations, but unportable); 3) provide our own buffering (breaks input readers that want to use stdio directly, such as the RLE library); or 4) don't put back the data, and modify the input_init methods to assume they start reading after the start of file (also breaks RLE library). #1 is attractive for MS-DOS but is untenable on Unix. The most portable solution for file types that can't be identified by their first byte is to make the user tell us what they are. This is also the only approach for "raw" file types that contain only arbitrary values. We presently apply this method for Targa files. Most of the time Targa files start with $00, so we recognize that case. Potentially, however, a Targa file could start with any byte value (byte 0 is the length of the seldom-used ID field), so we provide a switch to force Targa input mode. } var is_targa : boolean; { records user -targa switch } function GetFirstChar(cinfo : j_compress_ptr; fptr : fileptr) : char; var c : char; begin if JFREAD(fptr, @c, 1) <> 1 then ERREXIT(j_common_ptr(cinfo), JERR_INPUT_EMPTY); {$ifndef delphi_stream} Seek(fptr^, 0); { Nomssi: probably not portable } {$else} Fptr^.Seek(0,0); {$endif} if (IOresult <> 0) then ERREXIT(j_common_ptr(cinfo), JERR_UNGETC_FAILED); GetFirstChar := c; end; {LOCAL} function select_file_type (cinfo : j_compress_ptr; var infile : FILE) : cjpeg_source_ptr; var c : char; begin if (is_targa) then begin {$ifdef TARGA_SUPPORTED} select_file_type := jinit_read_targa(cinfo); exit; {$else} ERREXIT(j_common_ptr(cinfo), JERR_TGA_NOTCOMP); {$endif} end; c := GetFirstChar(cinfo, @infile); select_file_type := NIL; { suppress compiler warnings } case c of {$ifdef BMP_SUPPORTED} 'B': select_file_type := jinit_read_bmp(cinfo); {$endif} {$ifdef GIF_SUPPORTED} 'G': select_file_type := jinit_read_gif(cinfo); {$endif} {$ifdef PPM_SUPPORTED} 'P': select_file_type := jinit_read_ppm(cinfo); {$endif} {$ifdef RLE_SUPPORTED} 'R': select_file_type := jinit_read_rle(cinfo); {$endif} {$ifdef TARGA_SUPPORTED} char($00): select_file_type := jinit_read_targa(cinfo); {$endif} else ERREXIT(j_common_ptr(cinfo), JERR_UNKNOWN_FORMAT); end; end; { Argument-parsing code. The switch parser is designed to be useful with DOS-style command line syntax, ie, intermixed switches and file names, where only the switches to the left of a given file name affect processing of that file. The main program in this file doesn't actually use this capability... } var progname, { program name for error messages } outfilename : string[79]; { for -outfile switch } {LOCAL} procedure usage; { complain about bad command line } begin Write(output, 'usage: ', progname, ' [switches] '); {$ifdef TWO_FILE_COMMANDLINE} WriteLn(output, 'inputfile outputfile'); {$else} WriteLn(output, '[inputfile]'); {$endif} WriteLn(output, 'Switches (names may be abbreviated):'); WriteLn(output, ' -quality N Compression quality (0..100; 5-95 is useful range)'); WriteLn(output, ' -grayscale Create monochrome JPEG file'); {$ifdef ENTROPY_OPT_SUPPORTED} WriteLn(output, ' -optimize Optimize Huffman table (smaller file, but slow compression)'); {$endif} {$ifdef C_PROGRESSIVE_SUPPORTED} WriteLn(output, ' -progressive Create progressive JPEG file'); {$endif} {$ifdef TARGA_SUPPORTED} WriteLn(output, ' -targa Input file is Targa format (usually not needed)'); {$endif} WriteLn(output, 'Switches for advanced users:'); {$ifdef DCT_ISLOW_SUPPORTED} if (JDCT_DEFAULT = JDCT_ISLOW) then WriteLn(output, ' -dct int Use integer DCT method (default)') else WriteLn(output, ' -dct int Use integer DCT method'); {$endif} {$ifdef DCT_IFAST_SUPPORTED} if (JDCT_DEFAULT = JDCT_IFAST) then WriteLn(output, ' -dct fast Use fast integer DCT (less accurate) (default)') else WriteLn(output, ' -dct fast Use fast integer DCT (less accurate)'); {$endif} {$ifdef DCT_FLOAT_SUPPORTED} if (JDCT_DEFAULT = JDCT_FLOAT) then WriteLn(output, ' -dct float Use floating-point DCT method (default)') else WriteLn(output, ' -dct float Use floating-point DCT method'); {$endif} WriteLn(output, ' -restart N Set restart interval in rows, or in blocks with B'); {$ifdef INPUT_SMOOTHING_SUPPORTED} WriteLn(output, ' -smooth N Smooth dithered input (N=1..100 is strength)'); {$endif} WriteLn(output, ' -maxmemory N Maximum memory to use (in kbytes)'); WriteLn(output, ' -outfile name Specify name for output file'); WriteLn(output, ' -verbose or -debug Emit debug output'); {$IFDEF EXT_SWITCH} WriteLn(output, 'Switches for wizards:'); {$ifdef C_ARITH_CODING_SUPPORTED} WriteLn(output, ' -arithmetic Use arithmetic coding'); {$endif} WriteLn(output, ' -baseline Force baseline output'); WriteLn(output, ' -qtables file Use quantization tables given in file'); WriteLn(output, ' -qslots N[,...] Set component quantization tables'); WriteLn(output, ' -sample HxV[,...] Set component sampling factors'); {$ifdef C_MULTISCAN_FILES_SUPPORTED} WriteLn(output, ' -scans file Create multi-scan JPEG per script file'); {$endif} {$ENDIF} Halt(EXIT_FAILURE); end; {LOCAL} function parse_switches (cinfo : j_compress_ptr; last_file_arg_seen : int; for_real : boolean) : int; { Parse optional switches. Returns argv[] index of first file-name argument (== argc if none). Any file names with indexes <= last_file_arg_seen are ignored; they have presumably been processed in a previous iteration. (Pass 0 for last_file_arg_seen on the first or only iteration.) for_real is FALSE on the first (dummy) pass; we may skip any expensive processing. } var argn, argc : int; arg : string; var value : int; code : integer; var quality : int; { -quality parameter } q_scale_factor : int; { scaling percentage for -qtables } force_baseline : boolean; simple_progressive : boolean; qtablefile, { saves -qtables filename if any } qslotsarg, { saves -qslots parm if any } samplearg, { saves -sample parm if any } scansarg : string; { saves -scans parm if any } var lval : long; ch : char; const printed_version : boolean = FALSE; begin qtablefile := ''; qslotsarg := ''; samplearg := ''; scansarg := ''; { Set up default JPEG parameters. } { Note that default -quality level need not, and does not, match the default scaling for an explicit -qtables argument. } quality := 75; { default -quality value } q_scale_factor := 100; { default to no scaling for -qtables } force_baseline := FALSE; { by default, allow 16-bit quantizers } simple_progressive := FALSE; is_targa := FALSE; outfilename := ''; cinfo^.err^.trace_level := 0; { Scan command line options, adjust parameters } argn := 0; argc := ParamCount; while argn < argc do begin Inc(argn); arg := ParamStr(argn); if (arg[1] <> '-') then begin { Not a switch, must be a file name argument } if (argn <= last_file_arg_seen) then begin outfilename := ''; { -outfile applies to just one input file } continue; { ignore this name if previously processed } end; break; { else done parsing switches } end; {Inc(arg); - advance past switch marker character } if (keymatch(arg, '-arithmetic', 2)) then begin { Use arithmetic coding. } {$ifdef C_ARITH_CODING_SUPPORTED} cinfo^.arith_code := TRUE; {$else} WriteLn(output, progname, ': sorry, arithmetic coding not supported'); Halt(EXIT_FAILURE); {$endif} end else if (keymatch(arg, '-baseline', 2)) then begin { Force baseline output (8-bit quantizer values). } force_baseline := TRUE; end else if (keymatch(arg, '-dct', 3)) then begin { Select DCT algorithm. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; if (keymatch(ParamStr(argn), 'int', 1)) then begin cinfo^.dct_method := JDCT_ISLOW; end else if (keymatch(ParamStr(argn), 'fast', 2)) then begin cinfo^.dct_method := JDCT_IFAST; end else if (keymatch(ParamStr(argn), 'float', 2)) then begin cinfo^.dct_method := JDCT_FLOAT; end else usage; end else if keymatch(arg, '-debug', 2) or keymatch(arg, '-verbose', 2) then begin { Enable debug printouts. } { On first -d, print version identification } if (not printed_version) then begin WriteLn(output, 'Independent JPEG Group''s CJPEG, version ', JVERSION); WriteLn(output, JCOPYRIGHT); WriteLn(output, JNOTICE); printed_version := TRUE; end; Inc(cinfo^.err^.trace_level); end else if (keymatch(arg, '-grayscale', 3)) or (keymatch(arg, '-greyscale',3)) then begin { Force a monochrome JPEG file to be generated. } jpeg_set_colorspace(cinfo, JCS_GRAYSCALE); end else if (keymatch(arg, '-maxmemory', 4)) then begin ch := 'x'; Inc(argn); if (argn >= argc) then { advance to next argument } usage; arg := ParamStr(argn); if (length(arg) > 1) and (arg[length(arg)] in ['m','M']) then begin ch := arg[length(arg)]; arg := Copy(arg, 1, Length(arg)-1); end; Val(arg, lval, code); if (code <> 1) then usage; if (ch = 'm') or (ch = 'M') then lval := lval * long(1000); cinfo^.mem^.max_memory_to_use := lval * long(1000); end else if (keymatch(arg, '-optimize', 2)) or (keymatch(arg, '-optimise', 2)) then begin { Enable entropy parm optimization. } {$ifdef ENTROPY_OPT_SUPPORTED} cinfo^.optimize_coding := TRUE; {$else} WriteLn(output, progname, ': sorry, entropy optimization was not compiled'); exit(EXIT_FAILURE); {$endif} end else if (keymatch(arg, '-outfile', 5)) then begin { Set output file name. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; outfilename := ParamStr(argn); { save it away for later use } end else if (keymatch(arg, '-progressive', 2)) then begin { Select simple progressive mode. } {$ifdef C_PROGRESSIVE_SUPPORTED} simple_progressive := TRUE; { We must postpone execution until num_components is known. } {$else} WriteLn(output, progname, ': sorry, progressive output was not compiled'); Halt(EXIT_FAILURE); {$endif} end else if (keymatch(arg, '-quality', 2)) then begin { Quality factor (quantization table scaling factor). } Inc(argn); if (argn >= argc) then { advance to next argument } usage; Val(ParamStr(argn), quality, code); if code <> 0 then usage; { Change scale factor in case -qtables is present. } q_scale_factor := jpeg_quality_scaling(quality); end else if (keymatch(arg, '-qslots', 3)) then begin { Quantization table slot numbers. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; qslotsarg := ParamStr(argn); { Must delay setting qslots until after we have processed any colorspace-determining switches, since jpeg_set_colorspace sets default quant table numbers. } end else if (keymatch(arg, '-qtables', 3)) then begin { Quantization tables fetched from file. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; qtablefile := ParamStr(argn); { We postpone actually reading the file in case -quality comes later. } end else if (keymatch(arg, '-restart', 2)) then begin { Restart interval in MCU rows (or in MCUs with 'b'). } ch := 'x'; Inc(argn); if (argn >= argc) then { advance to next argument } usage; arg := ParamStr(argn); if (length(arg) > 1) and (arg[length(arg)] in ['b','B']) then begin ch := arg[length(arg)]; arg := Copy(arg, 1, Length(arg)-1); end; Val(arg, lval, Code); if (code <> 1) then usage; if (lval < 0) or (lval > long(65535)) then usage; if (ch = 'b') or (ch = 'B') then begin cinfo^.restart_interval := uInt (lval); cinfo^.restart_in_rows := 0; { else prior '-restart n' overrides me } end else begin cinfo^.restart_in_rows := int (lval); { restart_interval will be computed during startup } end; end else if (keymatch(arg, '-sample', 3)) then begin { Set sampling factors. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; samplearg := ParamStr(argn); { Must delay setting sample factors until after we have processed any colorspace-determining switches, since jpeg_set_colorspace sets default sampling factors. } end else if (keymatch(arg, '-scans', 3)) then begin { Set scan script. } {$ifdef C_MULTISCAN_FILES_SUPPORTED} Inc(argn); if (argn >= argc) then { advance to next argument } usage; scansarg := ParamStr(argn); { We must postpone reading the file in case -progressive appears. } {$else} WriteLn(output, progname, ': sorry, multi-scan output was not compiled'); Halt(EXIT_FAILURE); {$endif} end else if (keymatch(arg, '-smooth', 3)) then begin { Set input smoothing factor. } Inc(argn); if (argn >= argc) then { advance to next argument } usage; Val(ParamStr(argn), value, code); if (value < 0) or (value > 100) or (code <> 0) then usage; cinfo^.smoothing_factor := value; end else if (keymatch(arg, '-targa', 2)) then begin { Input file is Targa format. } is_targa := TRUE; end else begin usage; { bogus switch } end; end; { Post-switch-scanning cleanup } if (for_real) then begin { Set quantization tables for selected quality. } { Some or all may be overridden if -qtables is present. } jpeg_set_quality(cinfo, quality, force_baseline); {$IFDEF EXT_SWITCH} if (qtablefile <> '') then { process -qtables if it was present } if (not read_quant_tables(cinfo, qtablefile, q_scale_factor, force_baseline)) then usage; if (qslotsarg <> '') then { process -qslots if it was present } if (not set_quant_slots(cinfo, qslotsarg)) then usage; if (samplearg <> '') then { process -sample if it was present } if (not set_sample_factors(cinfo, samplearg)) then usage; {$ENDIF} {$ifdef C_PROGRESSIVE_SUPPORTED} if (simple_progressive) then { process -progressive; -scans can override } jpeg_simple_progression(cinfo); {$endif} {$IFDEF EXT_SWITCH} {$ifdef C_MULTISCAN_FILES_SUPPORTED} if (scansarg <> '') then { process -scans if it was present } if (not read_scan_script(cinfo, scansarg)) then usage; {$endif} {$ENDIF} end; parse_switches := argn; { return index of next arg (file name) } end; { The main program. } var cinfo : jpeg_compress_struct; jerr : jpeg_error_mgr; {$ifdef PROGRESS_REPORT} progress : cdjpeg_progress_mgr; {$endif} file_index : int; src_mgr : cjpeg_source_ptr; input_file : FILE; output_file : FILE; num_scanlines : JDIMENSION; var argc : int; begin argc := ParamCount; progname := ParamStr(0); { Initialize the JPEG compression object with default error handling. } cinfo.err := jpeg_std_error(jerr); jpeg_create_compress(@cinfo); { Add some application-specific error messages (from cderror.h) } {jerr.addon_message_table := cdjpeg_message_table;} jerr.first_addon_message := JMSG_FIRSTADDONCODE; jerr.last_addon_message := JMSG_LASTADDONCODE; { Now safe to enable signal catcher. } {$ifdef NEED_SIGNAL_CATCHER} enable_signal_catcher(j_common_ptr ( @cinfo); {$endif} { Initialize JPEG parameters. Much of this may be overridden later. In particular, we don't yet know the input file's color space, but we need to provide some value for jpeg_set_defaults() to work. } cinfo.in_color_space := JCS_RGB; { arbitrary guess } jpeg_set_defaults(@cinfo); { Scan command line to find file names. It is convenient to use just one switch-parsing routine, but the switch values read here are ignored; we will rescan the switches after opening the input file. } file_index := parse_switches(@cinfo, 0, FALSE); {$ifdef TWO_FILE_COMMANDLINE} { Must have either -outfile switch or explicit output file name } if (outfilename = '') then begin if (file_index <> argc-2+1) then begin WriteLn(output, progname, ': must name one input and one output file'); usage; end; outfilename := ParamStr(file_index+1); end else begin if (file_index <> argc-1) then begin WriteLn(output, progname, ': must name one input and one output file'); usage; end; end; {$else} { Unix style: expect zero or one file name } if (file_index < argc-1) then begin WriteLn(output, progname, ': only one input file'); usage; end; {$endif} { TWO_FILE_COMMANDLINE } { Open the input file. } if (file_index < argc) then begin Assign(input_file, ParamStr(file_index)); {$I-} Reset(input_file, 1); {$ifdef IOcheck} {$I+} {$endif} if (IOresult <> 0) then begin WriteLn(output, progname, ': can''t open ', ParamStr(file_index)); Halt(EXIT_FAILURE); end; end else begin WriteLn(output, progname, ': no input file'); Halt(EXIT_FAILURE); end; { Open the output file. } if (outfilename <> '') then begin Assign(output_file, outfilename); {$I-} Reset(output_file, 1); {$ifdef IOcheck} {$I+} {$endif} if (IOresult = 0) then begin WriteLn(output, outfilename, ': already exists.'); close(output_file); Halt(EXIT_FAILURE); end; {$I-} ReWrite(output_file, 1); {$ifdef IOcheck} {$I+} {$endif} if (IOresult <> 0) then begin WriteLn(output, progname, ': can''t create ', outfilename); Halt(EXIT_FAILURE); end; end else begin WriteLn(output, progname, ': no output file'); Halt(EXIT_FAILURE); end; {$ifdef PROGRESS_REPORT} start_progress_monitor(j_common_ptr (@cinfo), @progress); {$endif} { Figure out the input file format, and set up to read it. } src_mgr := select_file_type(@cinfo, input_file); src_mgr^.input_file := @input_file; { Read the input file header to obtain file size & colorspace. } src_mgr^.start_input (@cinfo, src_mgr); { Now that we know input colorspace, fix colorspace-dependent defaults } jpeg_default_colorspace(@cinfo); { Adjust default compression parameters by re-parsing the options } file_index := parse_switches(@cinfo, 0, TRUE); { Specify data destination for compression } jpeg_stdio_dest(@cinfo, @output_file); { Start compressor } jpeg_start_compress(@cinfo, TRUE); { Process data } while (cinfo.next_scanline < cinfo.image_height) do begin num_scanlines := src_mgr^.get_pixel_rows (@cinfo, src_mgr); {void} jpeg_write_scanlines(@cinfo, src_mgr^.buffer, num_scanlines); end; { Finish compression and release memory } src_mgr^.finish_input (@cinfo, src_mgr); jpeg_finish_compress(@cinfo); jpeg_destroy_compress(@cinfo); { Close files, if we opened them } close(input_file); close(output_file); {$ifdef PROGRESS_REPORT} end_progress_monitor(j_common_ptr (@cinfo)); {$endif} { All done. } if jerr.num_warnings <> 0 then Halt(EXIT_WARNING) else Halt(EXIT_SUCCESS); end.
unit Unit1; {$mode delphi}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Variants, DateUtils; type { an interface definition } IRecyclable = Interface(IInterface) { a single function supporting the property } function GetIsRecyclable: Boolean; { a single property } property isRecyclable: Boolean read GetIsRecyclable; end; { define car class } TCar = class(TInterfacedObject, IRecyclable) private carName: String; carAge: Byte; carIsRecyclable: boolean; function GetIsRecyclable: Boolean; { added for IRecyclable} public { car propertyies } property name: String read carName; property Age: Byte read carAge write carAge; { added for IRecyclable } property isRecyclable: Boolean read GetIsRecyclable; { car constructor } constructor Create(name: String); end; { define bicycle class } TBicycle = class(TInterFacedObject, IRecyclable) private bikeIsMale: Boolean; bikeWheelSize: Byte; function GetIsRecyclable: Boolean; { added for IRecyclable } public { bicycles properties } property isMale: Boolean read bikeIsMale; property wheelSize: Byte read bikeWheelSize write bikeWheelSize; { added for IRecyclable } property isRecyclable: Boolean read GetIsRecyclable; { bicycle constructor } constructor Create(isMale: Boolean; wheelSize: Byte); end; { TForm1 } TForm1 = class(TForm) procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { constructor implementation for the clar class } constructor TCar.Create(name: String); begin { save the car name and set default age and miles } carName := name; carAge := 0; carIsRecyclable := True; { sets the recyclable indicator } end; { car function required for isRecyclable attribute } function TCar.GetIsRecyclable: Boolean; begin Result := carIsRecyclable; end; { constructor implementation for the bicycle class } constructor TBicycle.Create(isMale: Boolean; wheelSize: Byte); begin { save the passed parameters } bikeIsMale := isMale; bikeWheelSize := wheelSize; end; { bicycle function required for IsRecyclable attribute } function TBicycle.GetIsRecyclable: Boolean; begin { only make bicycles are recyclable } if self.isMale then Result := True else Result := false; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); var mumsBike: TBicycle; dadsCar: TCar; begin { instantiate our bike and car objects } mumsBike := TBicycle.Create(False, 24); dadsCar := TCar.Create('Nissan Bluebird'); { ask if each is recyclable } if dadsCar.isRecyclable then ShowMessage('Dads car is recyclable') else ShowMessage('Dads car is not recyclable'); if mumsBike.isRecyclable then ShowMessage('Mums bike is recyclable') else ShowMessage('Mums bike is not recyclable'); end; end.
program TESTSET2 ( OUTPUT ) ; (********) (*$A+ *) (********) type ERRTYPE = 1 .. 999 ; ERRSET = set of ERRTYPE ; var X : ERRTYPE ; S : ERRSET ; procedure WRITESET ( S : ERRSET ) ; var I : ERRTYPE ; begin (* WRITESET *) WRITE ( 'writeset:' ) ; for I := 1 to 999 do if I in S then WRITE ( ' ' , I : 1 ) ; WRITELN end (* WRITESET *) ; begin (* HAUPTPROGRAMM *) S := [ ] ; S := [ 1 , 4 , 9 , 16 , 25 ] ; WRITESET ( S ) ; X := 400 ; S := S + [ X ] ; WRITESET ( S ) ; end (* HAUPTPROGRAMM *) .
unit NLDTExp; interface procedure Register; implementation uses ToolsAPI, ToolsAPITools, DesignIntf, Windows, CommCtrl, SysUtils, Classes, Controls, Forms, Menus, FTranslate, MImages; type TEventHandler = class(TObject) public procedure TranslateFormClick(Sender: TObject); procedure UpdateMenu(Sender: TObject); end; var FEventHandler: TEventHandler; FNLDTMenu: TMenuItem; FNLDTTranslateForm: TMenuItem; FImages: TdmImages; procedure Register; // GRAAAAAAWL! :yell: // // Yes, I mean that. Somehow, setting SubMenuImages won't work in the IDE. // It seems even GExperts uses bitmaps, so I'll use it too... *sigh* procedure SetImageIndex(const AMenu: TMenuItem; const AImageIndex: Integer); begin AMenu.ImageIndex := -1; FImages.ilsMenu.GetBitmap(AImageIndex, AMenu.Bitmap); end; var pMain: TMainMenu; pTools: TMenuItem; pSubItem: TMenuItem; begin FEventHandler := TEventHandler.Create(); FImages := TdmImages.Create(nil); // Find main menu pMain := (BorlandIDEServices as INTAServices).MainMenu; if Assigned(pMain) then begin // Create NLDTranslate menu item FNLDTMenu := TMenuItem.Create(nil); FNLDTMenu.Caption := '&NLDTranslate'; FNLDTMenu.OnClick := FEventHandler.UpdateMenu; // Create subitems FNLDTTranslateForm := TMenuItem.Create(FNLDTMenu); with FNLDTTranslateForm do begin Caption := '&Translate form'; OnClick := FEventHandler.TranslateFormClick; SetImageIndex(FNLDTTranslateForm, 0); end; FNLDTMenu.Add(FNLDTTranslateForm); pSubItem := TMenuItem.Create(FNLDTMenu); with pSubItem do begin Caption := '-'; end; FNLDTMenu.Add(pSubItem); pSubItem := TMenuItem.Create(FNLDTMenu); with pSubItem do begin Caption := '&Repository'; Enabled := False; end; FNLDTMenu.Add(pSubItem); // Check for 'Tools' item pTools := pMain.Items.Find('Tools'); if Assigned(pTools) then pMain.Items.Insert(pTools.MenuIndex + 1, FNLDTMenu) else // No 'Tools' item found, just add it at the back pMain.Items.Add(FNLDTMenu); FNLDTMenu.SubMenuImages := FImages.ilsMenu; end; end; {**************************************** TEventHandler ****************************************} procedure TEventHandler.UpdateMenu; var otaFormEditor: IOTAFormEditor; begin // Get active form editor otaFormEditor := GetActiveFormEditor(); try FNLDTTranslateForm.Enabled := (otaFormEditor <> nil); finally otaFormEditor := nil; end; end; procedure TEventHandler.TranslateFormClick; var otaFormEditor: IOTAFormEditor; begin // Get active form editor otaFormEditor := GetActiveFormEditor(); try if otaFormEditor <> nil then begin // Show translation form with TfrmNLDTTranslate.Create(nil) do begin Editor := otaFormEditor; ShowModal(); Free(); end; end; finally otaFormEditor := nil; end; end; initialization finalization // Remove menu item FreeAndNil(FNLDTMenu); FreeAndNil(FImages); // Remove event handler FreeAndNil(FEventHandler); end.
unit InfoXDRACCTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoXDRACCTRecord = record PAcctID: String[2]; PModCount: String[1]; PName: String[30]; PNextDraftNo: String[6]; End; TInfoXDRACCTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoXDRACCTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoXDRACCT = (InfoXDRACCTPrimaryKey); TInfoXDRACCTTable = class( TDBISAMTableAU ) private FDFAcctID: TStringField; FDFModCount: TStringField; FDFName: TStringField; FDFNextDraftNo: TStringField; FDFTemplate: TBlobField; procedure SetPAcctID(const Value: String); function GetPAcctID:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPNextDraftNo(const Value: String); function GetPNextDraftNo:String; procedure SetEnumIndex(Value: TEIInfoXDRACCT); function GetEnumIndex: TEIInfoXDRACCT; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoXDRACCTRecord; procedure StoreDataBuffer(ABuffer:TInfoXDRACCTRecord); property DFAcctID: TStringField read FDFAcctID; property DFModCount: TStringField read FDFModCount; property DFName: TStringField read FDFName; property DFNextDraftNo: TStringField read FDFNextDraftNo; property DFTemplate: TBlobField read FDFTemplate; property PAcctID: String read GetPAcctID write SetPAcctID; property PModCount: String read GetPModCount write SetPModCount; property PName: String read GetPName write SetPName; property PNextDraftNo: String read GetPNextDraftNo write SetPNextDraftNo; published property Active write SetActive; property EnumIndex: TEIInfoXDRACCT read GetEnumIndex write SetEnumIndex; end; { TInfoXDRACCTTable } procedure Register; implementation procedure TInfoXDRACCTTable.CreateFields; begin FDFAcctID := CreateField( 'AcctID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFNextDraftNo := CreateField( 'NextDraftNo' ) as TStringField; FDFTemplate := CreateField( 'Template' ) as TBlobField; end; { TInfoXDRACCTTable.CreateFields } procedure TInfoXDRACCTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXDRACCTTable.SetActive } procedure TInfoXDRACCTTable.SetPAcctID(const Value: String); begin DFAcctID.Value := Value; end; function TInfoXDRACCTTable.GetPAcctID:String; begin result := DFAcctID.Value; end; procedure TInfoXDRACCTTable.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TInfoXDRACCTTable.GetPModCount:String; begin result := DFModCount.Value; end; procedure TInfoXDRACCTTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoXDRACCTTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoXDRACCTTable.SetPNextDraftNo(const Value: String); begin DFNextDraftNo.Value := Value; end; function TInfoXDRACCTTable.GetPNextDraftNo:String; begin result := DFNextDraftNo.Value; end; procedure TInfoXDRACCTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AcctID, String, 2, N'); Add('ModCount, String, 1, N'); Add('Name, String, 30, N'); Add('NextDraftNo, String, 6, N'); Add('Template, Memo, 0, N'); end; end; procedure TInfoXDRACCTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AcctID, Y, Y, N, N'); end; end; procedure TInfoXDRACCTTable.SetEnumIndex(Value: TEIInfoXDRACCT); begin case Value of InfoXDRACCTPrimaryKey : IndexName := ''; end; end; function TInfoXDRACCTTable.GetDataBuffer:TInfoXDRACCTRecord; var buf: TInfoXDRACCTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAcctID := DFAcctID.Value; buf.PModCount := DFModCount.Value; buf.PName := DFName.Value; buf.PNextDraftNo := DFNextDraftNo.Value; result := buf; end; procedure TInfoXDRACCTTable.StoreDataBuffer(ABuffer:TInfoXDRACCTRecord); begin DFAcctID.Value := ABuffer.PAcctID; DFModCount.Value := ABuffer.PModCount; DFName.Value := ABuffer.PName; DFNextDraftNo.Value := ABuffer.PNextDraftNo; end; function TInfoXDRACCTTable.GetEnumIndex: TEIInfoXDRACCT; var iname : string; begin result := InfoXDRACCTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoXDRACCTPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoXDRACCTTable, TInfoXDRACCTBuffer ] ); end; { Register } function TInfoXDRACCTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..4] of string = ('ACCTID','MODCOUNT','NAME','NEXTDRAFTNO' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 4) and (flist[x] <> s) do inc(x); if x <= 4 then result := x else result := 0; end; function TInfoXDRACCTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; end; end; function TInfoXDRACCTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAcctID; 2 : result := @Data.PModCount; 3 : result := @Data.PName; 4 : result := @Data.PNextDraftNo; end; end; end.
unit InfoNOTESTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoNOTESRecord = record PNoteNumber: SmallInt; End; TInfoNOTESBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoNOTESRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoNOTES = (InfoNOTESPrimaryKey, InfoNOTESNote); TInfoNOTESTable = class( TDBISAMTableAU ) private FDFNoteNumber: TSmallIntField; FDFNotes: TBlobField; procedure SetPNoteNumber(const Value: SmallInt); function GetPNoteNumber:SmallInt; procedure SetEnumIndex(Value: TEIInfoNOTES); function GetEnumIndex: TEIInfoNOTES; protected procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoNOTESRecord; procedure StoreDataBuffer(ABuffer:TInfoNOTESRecord); property DFNoteNumber: TSmallIntField read FDFNoteNumber; property DFNotes: TBlobField read FDFNotes; property PNoteNumber: SmallInt read GetPNoteNumber write SetPNoteNumber; published property Active write SetActive; property EnumIndex: TEIInfoNOTES read GetEnumIndex write SetEnumIndex; end; { TInfoNOTESTable } procedure Register; implementation procedure TInfoNOTESTable.CreateFields; begin FDFNoteNumber := CreateField( 'NoteNumber' ) as TSmallIntField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoNOTESTable.CreateFields } procedure TInfoNOTESTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoNOTESTable.SetActive } procedure TInfoNOTESTable.SetPNoteNumber(const Value: SmallInt); begin DFNoteNumber.Value := Value; end; function TInfoNOTESTable.GetPNoteNumber:SmallInt; begin result := DFNoteNumber.Value; end; procedure TInfoNOTESTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('NoteNumber, SmallInt, 0, N'); Add('Notes, Memo, 0, N'); end; end; procedure TInfoNOTESTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, NoteNumber, Y, Y, N, N'); Add('Note, NoteNumber, N, N, Y, N'); end; end; procedure TInfoNOTESTable.SetEnumIndex(Value: TEIInfoNOTES); begin case Value of InfoNOTESPrimaryKey : IndexName := ''; InfoNOTESNote : IndexName := 'Note'; end; end; function TInfoNOTESTable.GetDataBuffer:TInfoNOTESRecord; var buf: TInfoNOTESRecord; begin fillchar(buf, sizeof(buf), 0); buf.PNoteNumber := DFNoteNumber.Value; result := buf; end; procedure TInfoNOTESTable.StoreDataBuffer(ABuffer:TInfoNOTESRecord); begin DFNoteNumber.Value := ABuffer.PNoteNumber; end; function TInfoNOTESTable.GetEnumIndex: TEIInfoNOTES; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoNOTESPrimaryKey; if iname = 'NOTE' then result := InfoNOTESNote; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoNOTESTable, TInfoNOTESBuffer ] ); end; { Register } function TInfoNOTESBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..1] of string = ('NOTENUMBER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 1) and (flist[x] <> s) do inc(x); if x <= 1 then result := x else result := 0; end; function TInfoNOTESBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftSmallInt; end; end; function TInfoNOTESBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PNoteNumber; end; end; end.
unit eInterestSimulator.Model.Interfaces.Calculadora; interface uses System.Generics.Collections, eInterestSimulator.Model.Interfaces, eInterestSimulator.Controller.Observer.Interfaces; type iCalculadora = interface ['{44213C01-9F0A-47A5-9B39-CC53BAE1123A}'] function Resultados: Tlist<iResultado>; function Calcular: iCalculadora; function Simulador: iSimulador; overload; function Simulador(Value: iSimulador): iCalculadora; overload; function ObserverResultado(Value : iSubjectResultado): iCalculadora; overload; function ObserverResultado: iSubjectResultado; overload; end; iCalculadoraFactory = interface function PagamentoUnico: iCalculadora; function PagamentoVariavel: iCalculadora; function Americano: iCalculadora; function AmortizacaoConstante: iCalculadora; function Price: iCalculadora; function AmortizacaoMisto: iCalculadora; function Alemao: iCalculadora; end; implementation end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC 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. CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.Chroma; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Def, CP.FFT, CP.FeatureVectorConsumer; type TChroma = class(TFFTFrameConsumer) private FInterpolate: boolean; FMinIndex: integer; FMaxIndex: integer; FNotes: array of byte; // char in c++ FNotesFrac: TDoubleArray; FFeatures: TDoubleArray; FConsumer: TFeatureVectorConsumer; procedure PrepareNotes(min_freq, max_freq, frame_size, sample_rate: integer); public property Interpolate: boolean read FInterpolate write FInterpolate; public constructor Create(min_freq, max_freq, frame_size, sample_rate: integer; consumer: TFeatureVectorConsumer); destructor Destroy; override; procedure Reset; procedure Consume(Frame: TFFTFrame); override; end; implementation uses CP.Utils, Math {$IFDEF FPC} , DaMath {$ENDIF}; { TChroma } procedure TChroma.PrepareNotes(min_freq, max_freq, frame_size, sample_rate: integer); var i: integer; freq, octave, note: double; cn: byte; j: integer; begin FMinIndex := Math.Max(1, FreqToIndex(min_freq, frame_size, sample_rate)); FMaxIndex := Math.Min(frame_size div 2, FreqToIndex(max_freq, frame_size, sample_rate)); for i := FMinIndex to FMaxIndex - 1 do begin freq := IndexToFreq(i, frame_size, sample_rate); octave := FreqToOctave(freq); note := NUM_BANDS * (octave - floor(octave)); cn := byte(trunc(note)); FNotes[i] := cn; FNotesFrac[i] := note - FNotes[i]; end; end; constructor TChroma.Create(min_freq, max_freq, frame_size, sample_rate: integer; consumer: TFeatureVectorConsumer); begin FInterpolate := False; SetLength(FNotes, frame_size); SetLength(FNotesFrac, frame_size); SetLength(FFeatures, NUM_BANDS); FConsumer := consumer; PrepareNotes(min_freq, max_freq, frame_size, sample_rate); end; destructor TChroma.Destroy; begin SetLength(FNotes, 0); SetLength(FNotesFrac, 0); SetLength(FFeatures, 0); FConsumer := nil; inherited Destroy; end; procedure TChroma.Reset; begin { nothing to do } end; procedure TChroma.Consume(Frame: TFFTFrame); var lNote, i, lNote2, n: integer; lEnergy, a: double; j: integer; s: string; begin n := Length(FFeatures); for i := 0 to n - 1 do begin FFeatures[i] := 0.0; end; for i := FMinIndex to FMaxIndex - 1 do begin lNote := FNotes[i]; lEnergy := Frame.energy(i); if (FInterpolate) then begin lNote2 := lNote; a := 1.0; if (FNotesFrac[i] < 0.5) then begin lNote2 := (lNote + NUM_BANDS - 1) mod NUM_BANDS; a := 0.5 + FNotesFrac[i]; end; if (FNotesFrac[i] > 0.5) then begin lNote2 := (lNote + 1) mod NUM_BANDS; a := 1.5 - FNotesFrac[i]; end; FFeatures[lNote] := FFeatures[lNote] + lEnergy * a; FFeatures[lNote2] := FFeatures[lNote2] + lEnergy * (1.0 - a); end else begin FFeatures[lNote] := FFeatures[lNote] + lEnergy; end; end; FConsumer.Consume(FFeatures); end; end.
unit InfoCLMNOTSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCLMNOTSRecord = record PClaimNumber: String[6]; PModCount: Integer; End; TInfoCLMNOTSClass2 = class public PClaimNumber: String[6]; PModCount: Integer; End; // function CtoRInfoCLMNOTS(AClass:TInfoCLMNOTSClass):TInfoCLMNOTSRecord; // procedure RtoCInfoCLMNOTS(ARecord:TInfoCLMNOTSRecord;AClass:TInfoCLMNOTSClass); TInfoCLMNOTSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCLMNOTSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoCLMNOTS = (InfoCLMNOTSPrimaryKey, InfoCLMNOTSClaim); TInfoCLMNOTSTable = class( TDBISAMTableAU ) private FDFClaimNumber: TStringField; FDFModCount: TIntegerField; FDFNotes: TBlobField; procedure SetPClaimNumber(const Value: String); function GetPClaimNumber:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoCLMNOTS); function GetEnumIndex: TEIInfoCLMNOTS; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCLMNOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoCLMNOTSRecord); property DFClaimNumber: TStringField read FDFClaimNumber; property DFModCount: TIntegerField read FDFModCount; property DFNotes: TBlobField read FDFNotes; property PClaimNumber: String read GetPClaimNumber write SetPClaimNumber; property PModCount: Integer read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoCLMNOTS read GetEnumIndex write SetEnumIndex; end; { TInfoCLMNOTSTable } TInfoCLMNOTSQuery = class( TDBISAMQueryAU ) private FDFClaimNumber: TStringField; FDFModCount: TIntegerField; FDFNotes: TBlobField; procedure SetPClaimNumber(const Value: String); function GetPClaimNumber:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoCLMNOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoCLMNOTSRecord); property DFClaimNumber: TStringField read FDFClaimNumber; property DFModCount: TIntegerField read FDFModCount; property DFNotes: TBlobField read FDFNotes; property PClaimNumber: String read GetPClaimNumber write SetPClaimNumber; property PModCount: Integer read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoCLMNOTSTable } procedure Register; implementation function TInfoCLMNOTSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoCLMNOTSTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoCLMNOTSTable.GenerateNewFieldName } function TInfoCLMNOTSTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoCLMNOTSTable.CreateField } procedure TInfoCLMNOTSTable.CreateFields; begin FDFClaimNumber := CreateField( 'ClaimNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoCLMNOTSTable.CreateFields } procedure TInfoCLMNOTSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCLMNOTSTable.SetActive } procedure TInfoCLMNOTSTable.SetPClaimNumber(const Value: String); begin DFClaimNumber.Value := Value; end; function TInfoCLMNOTSTable.GetPClaimNumber:String; begin result := DFClaimNumber.Value; end; procedure TInfoCLMNOTSTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoCLMNOTSTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TInfoCLMNOTSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('ClaimNumber, String, 6, N'); Add('ModCount, Integer, 0, N'); Add('Notes, Memo, 0, N'); end; end; procedure TInfoCLMNOTSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, ClaimNumber, Y, Y, N, N'); Add('Claim, ClaimNumber, N, N, N, N'); end; end; procedure TInfoCLMNOTSTable.SetEnumIndex(Value: TEIInfoCLMNOTS); begin case Value of InfoCLMNOTSPrimaryKey : IndexName := ''; InfoCLMNOTSClaim : IndexName := 'Claim'; end; end; function TInfoCLMNOTSTable.GetDataBuffer:TInfoCLMNOTSRecord; var buf: TInfoCLMNOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PClaimNumber := DFClaimNumber.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoCLMNOTSTable.StoreDataBuffer(ABuffer:TInfoCLMNOTSRecord); begin DFClaimNumber.Value := ABuffer.PClaimNumber; DFModCount.Value := ABuffer.PModCount; end; function TInfoCLMNOTSTable.GetEnumIndex: TEIInfoCLMNOTS; var iname : string; begin result := InfoCLMNOTSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoCLMNOTSPrimaryKey; if iname = 'CLAIM' then result := InfoCLMNOTSClaim; end; function TInfoCLMNOTSQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoCLMNOTSQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoCLMNOTSQuery.GenerateNewFieldName } function TInfoCLMNOTSQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoCLMNOTSQuery.CreateField } procedure TInfoCLMNOTSQuery.CreateFields; begin FDFClaimNumber := CreateField( 'ClaimNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoCLMNOTSQuery.CreateFields } procedure TInfoCLMNOTSQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCLMNOTSQuery.SetActive } procedure TInfoCLMNOTSQuery.SetPClaimNumber(const Value: String); begin DFClaimNumber.Value := Value; end; function TInfoCLMNOTSQuery.GetPClaimNumber:String; begin result := DFClaimNumber.Value; end; procedure TInfoCLMNOTSQuery.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoCLMNOTSQuery.GetPModCount:Integer; begin result := DFModCount.Value; end; function TInfoCLMNOTSQuery.GetDataBuffer:TInfoCLMNOTSRecord; var buf: TInfoCLMNOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PClaimNumber := DFClaimNumber.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoCLMNOTSQuery.StoreDataBuffer(ABuffer:TInfoCLMNOTSRecord); begin DFClaimNumber.Value := ABuffer.PClaimNumber; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCLMNOTSTable, TInfoCLMNOTSQuery, TInfoCLMNOTSBuffer ] ); end; { Register } function TInfoCLMNOTSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..2] of string = ('CLAIMNUMBER','MODCOUNT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 2) and (flist[x] <> s) do inc(x); if x <= 2 then result := x else result := 0; end; function TInfoCLMNOTSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftInteger; end; end; function TInfoCLMNOTSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PClaimNumber; 2 : result := @Data.PModCount; end; end; end.
unit fColOptions; interface uses Dialogs, ImgList, ssSpeedButton, ssPanel, dxTL6, dxDBCtrl6, dxDBGrid6, dxCntner6, dxDBTLCl6, dxGrClms6, cxControls, cxContainer, cxEdit, cxCheckBox, ssDBGrid, ssMemDS, ssBevel, ssBaseSkinForm, ssGradientPanel, xButton, ActnList, xLngManager, StdCtrls, ExtCtrls, DB, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms; type TfrmColOptions = class(TfrmBaseSkin) aApply: TAction; aCancel: TAction; ActionList: TActionList; aHelp: TAction; aLockScreen: TAction; aOK: TAction; aSendErrMessage: TAction; btnApply: TxButton; btnCancel: TxButton; btnDown: TssSpeedButton; btnHelp: TssSpeedButton; btnLock: TssSpeedButton; btnOK: TxButton; btnSendErrMessage: TssSpeedButton; btnUp: TssSpeedButton; bvlMain: TssBevel; chbAllowGrouping: TcxCheckBox; colColName: TdxDBGridColumn; colIndex: TdxDBGridColumn; colName: TdxDBGridColumn; colVisible: TdxDBGridImageColumn; grdMain: TssDBGrid; imgFun: TImage; lName: TLabel; mdCols: TssMemoryData; mdColscolindex: TIntegerField; mdColscolname: TStringField; mdColsen: TIntegerField; mdColsname: TStringField; mdColsvis: TIntegerField; panButtons: TPanel; srcCols: TDataSource; procedure aCancelExecute(Sender: TObject); procedure aOKExecute(Sender: TObject); procedure aApplyExecute(Sender: TObject); procedure grdMainMouseDown(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure colIndexGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); procedure btnUpClick(Sender: TObject); procedure btnDownClick(Sender: TObject); procedure grdMainDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure aLockScreenExecute(Sender: TObject); procedure aSendErrMessageExecute(Sender: TObject); procedure aHelpExecute(Sender: TObject); procedure grdMainColumnSorting(Sender: TObject; Column: TdxDBTreeListColumn; var Allow: Boolean); procedure chbAllowGroupingPropertiesChange(Sender: TObject); procedure FormCreate(Sender: TObject); private FGrid: TCustomdxDBTreeListControl; FModified: Boolean; procedure SetGrid(const Value: TCustomdxDBTreeListControl); public procedure SetCaptions(ALng: TxLngManager); property Grid: TCustomdxDBTreeListControl read FGrid write SetGrid; end; var frmColOptions: TfrmColOptions; implementation {$R *.dfm} {$IFNDEF PKG} uses prFun, prConst; {$ENDIF} //============================================================================================== procedure TfrmColOptions.SetCaptions(ALng: TxLngManager); begin if Assigned(ALng) then with ALng do begin aOK.Caption := GetRS('Common', 'OK'); aCancel.Caption := GetRS('Common', 'Cancel'); aApply.Caption := GetRS('Common', 'Apply'); Self.Caption := GetRS('Common', 'ColOptions'); colName.Caption := GetRS('Common', 'ColName'); colVisible.Caption := GetRS('Common', 'ColVis'); btnLock.Hint := GetRS('Common', 'Lock'); btnHelp.Hint := GetRS('Common', 'Help'); btnSendErrMessage.Hint := GetRS('Common', 'SendErrMessage'); chbAllowGrouping.Properties.Caption := GetRS('Common', 'ColOptionsAG'); end; end; //============================================================================================== procedure TfrmColOptions.SetGrid(const Value: TCustomdxDBTreeListControl); var i: Integer; begin FGrid := Value; if Assigned(Value) then begin if Value is TssDBGrid then begin lName.Caption := (Value as TssDBGrid).GetTitle; TssDBGrid(Value).FImgList.GetBitmap(TssDBGrid(Value).FImgIndex, imgFun.Picture.Bitmap); //colVisible.Images := TssDBGrid(Value).FImgList; //colVisible.Values[54] := '1'; end else begin lName.Caption := (Value as TssDBTreeList).GetTitle; TssDBTreeList(Value).FImgList.GetBitmap(TssDBTreeList(Value).FImgIndex, imgFun.Picture.Bitmap); end; end; with mdCols do begin Close; Open; for i := 0 to Value.ColumnCount - 1 do begin if Value.Columns[i].Tag > 0 then begin Append; FieldByName('colname').AsString := Value.Columns[i].Name; FieldByName('name').AsString := Value.Columns[i].Caption; FieldByName('vis').AsInteger := Integer(Value.Columns[i].Visible); FieldByName('en').AsInteger := Integer(Value.Columns[i].Tag = 1); FieldByName('colindex').AsInteger := Value.Columns[i].Index; Post; end; end; First; end; if Value is TssDBGrid then begin chbAllowGrouping.Checked := (Value as TssDBGrid).AutoHideGroupPanel and (Value as TssDBGrid).AllowGrouping; chbAllowGrouping.Enabled := (Value as TssDBGrid).AllowGrouping; end else begin chbAllowGrouping.Checked := False; chbAllowGrouping.Enabled := False; end; end; //============================================================================================== procedure TfrmColOptions.aCancelExecute(Sender: TObject); begin ModalResult := mrCancel; end; //============================================================================================== procedure TfrmColOptions.aOKExecute(Sender: TObject); begin ModalResult := mrOk; end; //============================================================================================== procedure TfrmColOptions.aApplyExecute(Sender: TObject); begin ModalResult := mrYes; end; //============================================================================================== procedure TfrmColOptions.grdMainMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var FNode: TdxTreeListNode; FCol: TdxTreeListColumn; begin if Button = mbLeft then begin FNode := grdMain.GetNodeAt(X, Y); FCol := grdMain.GetColumnAt(X, Y); if Assigned(FNode) and Assigned(FCol) and (FCol = colVisible) then begin if mdCols.Locate('colname', FNode.Values[colColName.Index], []) and (mdCols.FieldByName('en').AsInteger = 1) then begin mdCols.Edit; mdCols.FieldByName('vis').AsInteger := 1 - mdCols.FieldByName('vis').AsInteger; mdCols.Post; FModified := True; end; end; end; end; //============================================================================================== procedure TfrmColOptions.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin aOk.Enabled := FModified; aApply.Enabled := aOk.Enabled; end; //============================================================================================== procedure TfrmColOptions.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var BM: TBookmark; begin if ModalResult in [mrOk, mrYes] then begin CanClose := False; with Grid do begin BM := mdCols.GetBookmark; mdCols.DisableControls; try mdCols.First; while not mdCols.Eof do begin with ColumnByName(mdCols.FieldByName('colname').AsString) do begin Visible := mdCols.FieldByName('vis').AsInteger = 1; Index := mdCols.FieldByName('colindex').AsInteger; end; mdCols.Next; end; finally mdCols.GotoBookmark(BM); mdCols.FreeBookmark(BM); mdCols.EnableControls; end; if Grid is TssDBGrid then begin (Grid as TssDBGrid).AutoHideGroupPanel := chbAllowGrouping.Checked; if not chbAllowGrouping.Checked then begin Grid.ClearGroupColumns; (Grid as TssDBGrid).ShowGroupPanel := False; end; end; PostMessage(Grid.Handle, WM_OK_NEEDADJUST, 0, 0); end; if ModalResult = mrOk then CanClose := True else FModified := False; end; end; //============================================================================================== procedure TfrmColOptions.colIndexGetText(Sender: TObject; ANode: TdxTreeListNode; var AText: String); begin AText := IntToStr(ANode.Index + 1); end; //============================================================================================== procedure TfrmColOptions.btnUpClick(Sender: TObject); var I1, I2: Integer; begin with mdCols do begin if RecNo <> 0 then begin DisableControls; try I1 := FieldByName('colindex').AsInteger; Prior; I2 := FieldByName('colindex').AsInteger; Edit; FieldByName('colindex').AsInteger := I1; Post; Next; Edit; FieldByName('colindex').AsInteger := I2; Post; SortOnFields('colindex'); finally EnableControls; end; end; FModified := True; end; end; //============================================================================================== procedure TfrmColOptions.btnDownClick(Sender: TObject); var I1, I2: Integer; begin with mdCols do begin if RecNo <> mdCols.RecordCount - 1 then begin DisableControls; try I1 := FieldByName('colindex').AsInteger; Next; I2 := FieldByName('colindex').AsInteger; Edit; FieldByName('colindex').AsInteger := I1; Post; Prior; Edit; FieldByName('colindex').AsInteger := I2; Post; SortOnFields('colindex'); finally EnableControls; end; end; FModified := True; end; end; //============================================================================================== procedure TfrmColOptions.grdMainDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := True; end; //============================================================================================== procedure TfrmColOptions.aLockScreenExecute(Sender: TObject); begin {$IFNDEF PKG} LockScreen; {$ENDIF} end; //============================================================================================== procedure TfrmColOptions.aSendErrMessageExecute(Sender: TObject); begin {$IFNDEF PKG} SendMsg; {$ENDIF} end; //============================================================================================== procedure TfrmColOptions.aHelpExecute(Sender: TObject); begin {$IFNDEF PKG} ShowHelpTopic('colOptions'); {$ENDIF} end; //============================================================================================== procedure TfrmColOptions.grdMainColumnSorting(Sender: TObject; Column: TdxDBTreeListColumn; var Allow: Boolean); begin Allow := False; end; //============================================================================================== procedure TfrmColOptions.chbAllowGroupingPropertiesChange(Sender: TObject); begin FModified := True; end; //============================================================================================== procedure TfrmColOptions.FormCreate(Sender: TObject); begin inherited; {$IFNDEF PKG} lName.Font.Name := Font_Main.Name; lName.Font.Charset := Font_Main.Charset; {$ENDIF} end; end.
Program VAR_PARAM_EXAMPLE; Procedure Square(Index : Integer; Var Result : Integer); Begin Result := Index * Index; End; Var Res : Integer; Begin Writeln('The square of 5 is: '); Square(5, Res); Writeln(Res); End.
unit evOutTextParaEliminator; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Модуль: "w:/common/components/gui/Garant/Everest/evOutTextParaEliminator.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::Generators::TevOutTextParaEliminator // // Фильтр удаляющий мусорные текстовые параграфы за пределами документа. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses k2TagFilter ; type TevOutTextParaEliminator = class(Tk2TagFilter) {* Фильтр удаляющий мусорные текстовые параграфы за пределами документа. } private // private fields f_InDocument : Integer; protected // overridden protected methods procedure InitFields; override; procedure DoStartChild(TypeID: Integer); override; function NeedTranslateChildToNext: Boolean; override; procedure DoCloseStructure(NeedUndo: Boolean); override; end;//TevOutTextParaEliminator implementation uses Document_Const ; // start class TevOutTextParaEliminator procedure TevOutTextParaEliminator.InitFields; //#UC START# *47A042E100E2_4F7D3EB4039D_var* //#UC END# *47A042E100E2_4F7D3EB4039D_var* begin //#UC START# *47A042E100E2_4F7D3EB4039D_impl* f_InDocument := 0; inherited; //#UC END# *47A042E100E2_4F7D3EB4039D_impl* end;//TevOutTextParaEliminator.InitFields procedure TevOutTextParaEliminator.DoStartChild(TypeID: Integer); //#UC START# *4A2D1217037A_4F7D3EB4039D_var* //#UC END# *4A2D1217037A_4F7D3EB4039D_var* begin //#UC START# *4A2D1217037A_4F7D3EB4039D_impl* if CurrentType.InheritsFrom(k2_idDocument) then Inc(f_InDocument); inherited; //#UC END# *4A2D1217037A_4F7D3EB4039D_impl* end;//TevOutTextParaEliminator.DoStartChild function TevOutTextParaEliminator.NeedTranslateChildToNext: Boolean; //#UC START# *4CA3006302BC_4F7D3EB4039D_var* //#UC END# *4CA3006302BC_4F7D3EB4039D_var* begin //#UC START# *4CA3006302BC_4F7D3EB4039D_impl* Result := f_InDocument > 0; //#UC END# *4CA3006302BC_4F7D3EB4039D_impl* end;//TevOutTextParaEliminator.NeedTranslateChildToNext procedure TevOutTextParaEliminator.DoCloseStructure(NeedUndo: Boolean); //#UC START# *4E45166B0156_4F7D3EB4039D_var* //#UC END# *4E45166B0156_4F7D3EB4039D_var* begin //#UC START# *4E45166B0156_4F7D3EB4039D_impl* if CurrentType.InheritsFrom(k2_idDocument) then Dec(f_InDocument); inherited; //#UC END# *4E45166B0156_4F7D3EB4039D_impl* end;//TevOutTextParaEliminator.DoCloseStructure end.
unit Controller.ListagemMovimentacoesJornal; interface uses System.SysUtils, FireDAC.Comp.Client, Common.ENum, Controller.Sistema, Model.ListagemMovimentacoesJornal, Controller.PlanilhaMovimentacoesJornal, Generics.Collections, System.Classes, Common.Utils, System.DateUtils, Model.PlanilhaMovimentacaoJornal; type TListagemMovimentacoesJornalControl = class private FListagem : TMovimentacoes; public constructor Create(); destructor Destroy(); override; property Lista: TMovimentacoes read FListagem write FListagem; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function ImportData(sFile: String; dateData: TDate): Boolean; function DeleteEdicao(): Boolean; end; implementation { TListagemMovimentacoesJornalControl } constructor TListagemMovimentacoesJornalControl.Create; begin FListagem := TMovimentacoes.Create; end; function TListagemMovimentacoesJornalControl.DeleteEdicao: Boolean; begin if not Flistagem.DeleteEdicao() then begin TUtils.Dialog('Atenção', 'Erro ao excluir a data do banco de dados!', 0); end; end; destructor TListagemMovimentacoesJornalControl.Destroy; begin FListagem.Free; inherited; end; function TListagemMovimentacoesJornalControl.Gravar: Boolean; begin Result := False; Result := FListagem.Gravar; end; function TListagemMovimentacoesJornalControl.ImportData(sFile: String; dateData: TDate): Boolean; var FPlanilha: TPlanilhaListagem; FDados: TObjectList<TPlanilhaListagem>; i: Integer; fdMovimento : TFDQuery; begin try try Result := False; FPlanilha := TPlanilhaListagem.Create; fdMovimento := FListagem.QueryInsertMode(); Flistagem.Edicao := IncDay(dateData, -7); FListagem.DeleteEdicao(); FDados := TObjectList<TPlanilhaListagem>.Create; FDados := FPlanilha.GetPlanilha(sFile); if FDados = nil then Exit; if FDados.Count = 0 then Exit; for i := 0 to FDados.Count - 1 do begin fdMovimento.Params.ArraySize := i + 1; fdMovimento.ParamByName('cod_agente').AsIntegers[i] := StrToIntDef(FDados[i].CodigoAgente,0); fdMovimento.ParamByName('dat_edicao').AsDateTimes[i] := dateData; fdMovimento.ParamByName('des_status').AsStrings[i] := FDados[i].DescricaoStatus; fdMovimento.ParamByName('des_endereco').AsStrings[i] := FDados[i].Logradouro; fdMovimento.ParamByName('des_complemento').AsStrings[i] := FDados[i].Complemento; fdMovimento.ParamByName('des_bairro').AsStrings[i] := FDados[i].Bairro; fdMovimento.ParamByName('cod_assinante').AsStrings[i] := FDados[i].CodigoAssinante; fdMovimento.ParamByName('nom_assinante').AsStrings[i] := FDados[i].NomeAssinante; fdMovimento.ParamByName('des_produto').AsStrings[i] := FDados[i].SiglaProduto; fdMovimento.ParamByName('cod_modalidade').AsIntegers[i] := StrToIntDef(FDados[i].Modalidade,0); end; fdMovimento.Execute(i,0); Result := True; Except on E: Exception do begin TUtils.Dialog('Erro', 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message, 0); end; end; finally FPlanilha.Free; fdMovimento.Free; end; end; function TListagemMovimentacoesJornalControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FListagem.Localizar(aParam); end; end.
unit INFOCLAIMMASTERCODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TINFOCLAIMMASTERCODERecord = record PRecID: Word; PComponentNumber: Word; PCodeNumber: Word; PCode: String[6]; PDescription: String[30]; End; TINFOCLAIMMASTERCODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TINFOCLAIMMASTERCODERecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIINFOCLAIMMASTERCODE = (INFOCLAIMMASTERCODEPrimaryKey, INFOCLAIMMASTERCODEComponentCode, INFOCLAIMMASTERCODEDataCode); TINFOCLAIMMASTERCODETable = class( TDBISAMTableAU ) private FDFRecID: TWordField; FDFComponentNumber: TWordField; FDFCodeNumber: TWordField; FDFCode: TStringField; FDFDescription: TStringField; procedure SetPRecID(const Value: Word); function GetPRecID:Word; procedure SetPComponentNumber(const Value: Word); function GetPComponentNumber:Word; procedure SetPCodeNumber(const Value: Word); function GetPCodeNumber:Word; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIINFOCLAIMMASTERCODE); function GetEnumIndex: TEIINFOCLAIMMASTERCODE; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TINFOCLAIMMASTERCODERecord; procedure StoreDataBuffer(ABuffer:TINFOCLAIMMASTERCODERecord); property DFRecID: TWordField read FDFRecID; property DFComponentNumber: TWordField read FDFComponentNumber; property DFCodeNumber: TWordField read FDFCodeNumber; property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property PRecID: Word read GetPRecID write SetPRecID; property PComponentNumber: Word read GetPComponentNumber write SetPComponentNumber; property PCodeNumber: Word read GetPCodeNumber write SetPCodeNumber; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; published property Active write SetActive; property EnumIndex: TEIINFOCLAIMMASTERCODE read GetEnumIndex write SetEnumIndex; end; { TINFOCLAIMMASTERCODETable } procedure Register; implementation function TINFOCLAIMMASTERCODETable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TINFOCLAIMMASTERCODETable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TINFOCLAIMMASTERCODETable.GenerateNewFieldName } function TINFOCLAIMMASTERCODETable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TINFOCLAIMMASTERCODETable.CreateField } procedure TINFOCLAIMMASTERCODETable.CreateFields; begin FDFRecID := CreateField( 'RecID' ) as TWordField; FDFComponentNumber := CreateField( 'ComponentNumber' ) as TWordField; FDFCodeNumber := CreateField( 'CodeNumber' ) as TWordField; FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TINFOCLAIMMASTERCODETable.CreateFields } procedure TINFOCLAIMMASTERCODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TINFOCLAIMMASTERCODETable.SetActive } procedure TINFOCLAIMMASTERCODETable.SetPRecID(const Value: Word); begin DFRecID.Value := Value; end; function TINFOCLAIMMASTERCODETable.GetPRecID:Word; begin result := DFRecID.Value; end; procedure TINFOCLAIMMASTERCODETable.SetPComponentNumber(const Value: Word); begin DFComponentNumber.Value := Value; end; function TINFOCLAIMMASTERCODETable.GetPComponentNumber:Word; begin result := DFComponentNumber.Value; end; procedure TINFOCLAIMMASTERCODETable.SetPCodeNumber(const Value: Word); begin DFCodeNumber.Value := Value; end; function TINFOCLAIMMASTERCODETable.GetPCodeNumber:Word; begin result := DFCodeNumber.Value; end; procedure TINFOCLAIMMASTERCODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TINFOCLAIMMASTERCODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TINFOCLAIMMASTERCODETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TINFOCLAIMMASTERCODETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TINFOCLAIMMASTERCODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('RecID, Word, 0, N'); Add('ComponentNumber, Word, 0, N'); Add('CodeNumber, Word, 0, N'); Add('Code, String, 6, N'); Add('Description, String, 30, N'); end; end; procedure TINFOCLAIMMASTERCODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, RecID, Y, Y, N, N'); Add('ComponentCode, ComponentNumber;CodeNumber, N, Y, N, N'); Add('DataCode, ComponentNumber;Code, N, Y, N, N'); end; end; procedure TINFOCLAIMMASTERCODETable.SetEnumIndex(Value: TEIINFOCLAIMMASTERCODE); begin case Value of INFOCLAIMMASTERCODEPrimaryKey : IndexName := ''; INFOCLAIMMASTERCODEComponentCode : IndexName := 'ComponentCode'; INFOCLAIMMASTERCODEDataCode : IndexName := 'DataCode'; end; end; function TINFOCLAIMMASTERCODETable.GetDataBuffer:TINFOCLAIMMASTERCODERecord; var buf: TINFOCLAIMMASTERCODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PRecID := DFRecID.Value; buf.PComponentNumber := DFComponentNumber.Value; buf.PCodeNumber := DFCodeNumber.Value; buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TINFOCLAIMMASTERCODETable.StoreDataBuffer(ABuffer:TINFOCLAIMMASTERCODERecord); begin DFRecID.Value := ABuffer.PRecID; DFComponentNumber.Value := ABuffer.PComponentNumber; DFCodeNumber.Value := ABuffer.PCodeNumber; DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; end; function TINFOCLAIMMASTERCODETable.GetEnumIndex: TEIINFOCLAIMMASTERCODE; var iname : string; begin result := INFOCLAIMMASTERCODEPrimaryKey; iname := uppercase(indexname); if iname = '' then result := INFOCLAIMMASTERCODEPrimaryKey; if iname = 'COMPONENTCODE' then result := INFOCLAIMMASTERCODEComponentCode; if iname = 'DATACODE' then result := INFOCLAIMMASTERCODEDataCode; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TINFOCLAIMMASTERCODETable, TINFOCLAIMMASTERCODEBuffer ] ); end; { Register } function TINFOCLAIMMASTERCODEBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('RECID','COMPONENTNUMBER','CODENUMBER','CODE','DESCRIPTION' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TINFOCLAIMMASTERCODEBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftWord; 2 : result := ftWord; 3 : result := ftWord; 4 : result := ftString; 5 : result := ftString; end; end; function TINFOCLAIMMASTERCODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PRecID; 2 : result := @Data.PComponentNumber; 3 : result := @Data.PCodeNumber; 4 : result := @Data.PCode; 5 : result := @Data.PDescription; end; end; end.
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Adapter_EControl; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, ExtCtrls, ComCtrls, Forms, Dialogs, ATSynEdit, ATSynEdit_CanvasProc, ATSynEdit_Adapters, ATSynEdit_Carets, ATStringProc, ATStringProc_TextBuffer, ATStrings, ec_SyntAnal; var //interval of TimerDuringAnalyze cAdapterTimerDuringAnalyzeInterval: integer = 200; //ATSynEdit.OnIdle timer interval cAdapterIdleInterval: integer = 500; //ATSynEdit.OnIdle will fire only if text size is bigger cAdapterIdleTextSize: integer = 10*1000; type { TATRangeInCodeTree } TATRangeInCodeTree = class public PosBegin: TPoint; PosEnd: TPoint; procedure Assign(Src: TATRangeInCodeTree); end; type { TATRangeColored } TATRangeColored = class public Pos1, Pos2: TPoint; Token1, Token2: integer; Color: TColor; Rule: TecTagBlockCondition; ActiveAlways: boolean; Active: array[0..Pred(cMaxStringsClients)] of boolean; constructor Create( APos1, APos2: TPoint; AToken1, AToken2: integer; AColor: TColor; ARule: TecTagBlockCondition; AActiveAlways: boolean); end; TATRangeCond = (cCondInside, cCondAtBound, cCondOutside); procedure ClearTreeviewWithData(ATree: TTreeView); type { TATAdapterEControl } TATAdapterEControl = class(TATAdapterHilite) private EdList: TList; Buffer: TATStringBuffer; ListColoredRanges: TList; TimerDuringAnalyze: TTimer; CurrentIdleInterval: integer; FEnabledLineSeparators: boolean; FEnabledSublexerTreeNodes: boolean; FBusyTreeUpdate: boolean; FBusyTimer: boolean; FStopTreeUpdate: boolean; FTimeParseBegin: QWORD; FTimeParseElapsed: integer; FOnLexerChange: TNotifyEvent; FOnParseBegin: TNotifyEvent; FOnParseDone: TNotifyEvent; procedure DoCheckEditorList; procedure DoFindTokenOverrideStyle(var ATokenStyle: TecSyntaxFormat; ATokenIndex, AEditorIndex: integer); procedure DoFoldAdd(AX, AY, AY2: integer; AStaple: boolean; const AHint: string); procedure DoCalcParts(var AParts: TATLineParts; ALine, AX, ALen: integer; AColorFont, AColorBG: TColor; var AColorAfter: TColor; AEditorIndex: integer); procedure DoClearRanges; function DoFindToken(APos: TPoint): integer; procedure DoFoldFromLinesHidden; procedure DoChangeLog(Sender: TObject; ALine, ACount: integer); procedure DoParseBegin; procedure DoParseDone; function GetIdleInterval: integer; function GetRangeParent(R: TecTextRange): TecTextRange; function IsCaretInRange(AEdit: TATSynEdit; APos1, APos2: TPoint; ACond: TATRangeCond): boolean; function GetTokenColorBG_FromColoredRanges(APos: TPoint; ADefColor: TColor; AEditorIndex: integer): TColor; function GetTokenColorBG_FromMultiLineTokens(APos: TPoint; ADefColor: TColor; AEditorIndex: integer): TColor; function EditorRunningCommand: boolean; procedure TimerDuringAnalyzeTimer(Sender: TObject); procedure UpdateRanges; procedure UpdateRangesActive(AEdit: TATSynEdit); procedure UpdateRangesActiveAll; procedure UpdateSeparators; procedure UpdateRangesSublex; procedure UpdateData(AUpdateBuffer, AAnalyze: boolean); procedure UpdateRangesFold; procedure UpdateEditors(ARepaint, AClearCache: boolean); function GetLexer: TecSyntAnalyzer; procedure SetLexer(AAnalizer: TecSyntAnalyzer); procedure SetEnabledLineSeparators(AValue: boolean); function GetLexerSuportsDynamicHilite: boolean; function IsDynamicHiliteEnabled: boolean; public AnClient: TecClientSyntAnalyzer; // constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddEditor(AEditor: TComponent); override; // property Lexer: TecSyntAnalyzer read GetLexer write SetLexer; property LexerParsingElapsed: integer read FTimeParseElapsed; function LexerAtPos(Pnt: TPoint): TecSyntAnalyzer; property EnabledLineSeparators: boolean read FEnabledLineSeparators write SetEnabledLineSeparators; property EnabledSublexerTreeNodes: boolean read FEnabledSublexerTreeNodes write FEnabledSublexerTreeNodes default false; procedure DoAnalize(AEdit: TATSynEdit; AForceAnalizeAll: boolean); procedure DoAnalyzeFromLine(ALine: integer; AWait: boolean); procedure Stop; procedure StopTreeUpdate; //tokens procedure GetTokenWithIndex(AIndex: integer; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); procedure GetTokenAtPos(APos: TPoint; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); function GetTokenString(token: TecSyntToken): string; procedure GetTokenProps(token: TecSyntToken; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); //support for syntax-tree property TreeBusy: boolean read FBusyTreeUpdate; procedure TreeFill(ATree: TTreeView); procedure TreeShowItemForCaret(ATree: TTreeView; APos: TPoint); procedure TreeGetPositionOfRange_EC(R: TecTextRange; out APosBegin, APosEnd: TPoint); function TreeGetRangeOfPosition(APos: TPoint): TecTextRange; //sublexers function SublexerRangeCount: integer; function SublexerRangeProps(AIndex: integer; out AStart, AEnd: TPoint; out ALexerName: string): boolean; public procedure OnEditorCaretMove(Sender: TObject); override; procedure OnEditorChange(Sender: TObject); override; procedure OnEditorIdle(Sender: TObject); override; procedure OnEditorCalcHilite(Sender: TObject; var AParts: TATLineParts; ALineIndex, ACharIndex, ALineLen: integer; var AColorAfterEol: TColor); override; procedure OnEditorCalcPosColor(Sender: TObject; AX, AY: integer; var AColor: TColor); override; published property OnLexerChange: TNotifyEvent read FOnLexerChange write FOnLexerChange; property OnParseBegin: TNotifyEvent read FOnParseBegin write FOnParseBegin; property OnParseDone: TNotifyEvent read FOnParseDone write FOnParseDone; end; procedure ApplyPartStyleFromEcontrolStyle(var part: TATLinePart; st: TecSyntaxFormat); implementation uses Math; const cBorderEc: array[TecBorderLineType] of TATLineStyle = ( cLineStyleNone, cLineStyleSolid, cLineStyleDash, cLineStyleDash, cLineStyleDash, cLineStyleDash, cLineStyleSolid2px, cLineStyleSolid2px, cLineStyleWave, cLineStyleDotted ); function ComparePoints(P1, P2: TPoint): integer; begin if (P1.X=P2.X) and (P1.Y=P2.Y) then exit(0); if (P1.Y>P2.Y) then exit(1); if (P1.Y<P2.Y) then exit(-1); if (P1.X>P2.X) then exit(1) else exit(-1); end; procedure ClearTreeviewWithData(ATree: TTreeView); var i: integer; begin for i:= ATree.Items.Count-1 downto 0 do with ATree.Items[i] do if Data<>nil then begin TObject(Data).Free; Data:= nil; end; ATree.Items.Clear; end; procedure ApplyPartStyleFromEcontrolStyle(var part: TATLinePart; st: TecSyntaxFormat); begin if Assigned(st.Font) then if st.FormatType in [ftCustomFont, ftFontAttr, ftColor] then begin if st.Font.Color<>clNone then part.ColorFont:= st.Font.Color; end; if st.FormatType in [ftCustomFont, ftFontAttr, ftColor, ftBackGround] then begin if st.BgColor<>clNone then part.ColorBG:= st.BgColor; end; if Assigned(st.Font) then if st.FormatType in [ftCustomFont, ftFontAttr] then begin part.FontBold:= fsBold in st.Font.Style; part.FontItalic:= fsItalic in st.Font.Style; part.FontStrikeOut:= fsStrikeOut in st.Font.Style; end; part.ColorBorder:= st.BorderColorBottom; part.BorderUp:= cBorderEc[st.BorderTypeTop]; part.BorderDown:= cBorderEc[st.BorderTypeBottom]; part.BorderLeft:= cBorderEc[st.BorderTypeLeft]; part.BorderRight:= cBorderEc[st.BorderTypeRight]; end; { TATRangeInCodeTree } procedure TATRangeInCodeTree.Assign(Src: TATRangeInCodeTree); begin PosBegin:= Src.PosBegin; PosEnd:= Src.PosEnd; end; { TATRangeColored } constructor TATRangeColored.Create(APos1, APos2: TPoint; AToken1, AToken2: integer; AColor: TColor; ARule: TecTagBlockCondition; AActiveAlways: boolean); var i: integer; begin Pos1:= APos1; Pos2:= APos2; Token1:= AToken1; Token2:= AToken2; Color:= AColor; Rule:= ARule; ActiveAlways:= AActiveAlways; for i:= Low(Active) to High(Active) do Active[i]:= false; end; { TATAdapterEControl } procedure TATAdapterEControl.DoCheckEditorList; begin if EdList.Count=0 then raise Exception.Create('Adapter: Empty editor list'); end; procedure TATAdapterEControl.OnEditorCalcHilite(Sender: TObject; var AParts: TATLineParts; ALineIndex, ACharIndex, ALineLen: integer; var AColorAfterEol: TColor); var Ed: TATSynEdit; Str: atString; begin DoCheckEditorList; Ed:= Sender as TATSynEdit; if not Assigned(AnClient) then Exit; Str:= Copy(Ed.Strings.Lines[ALineIndex], ACharIndex, ALineLen); ALineLen:= Length(Str); AColorAfterEol:= clNone; DoCalcParts(AParts, ALineIndex, ACharIndex-1, ALineLen, Ed.Colors.TextFont, clNone, AColorAfterEol, Ed.EditorIndex); end; procedure TATAdapterEControl.OnEditorCalcPosColor(Sender: TObject; AX, AY: integer; var AColor: TColor); var Ed: TATSynEdit; begin Ed:= Sender as TATSynEdit; AColor:= GetTokenColorBG_FromColoredRanges(Point(AX, AY), AColor, Ed.EditorIndex); end; function TATAdapterEControl.IsCaretInRange(AEdit: TATSynEdit; APos1, APos2: TPoint; ACond: TATRangeCond): boolean; var Caret: TATCaretItem; Pnt: TPoint; dif1, dif2: integer; i: integer; ok: boolean; begin Result:= false; for i:= 0 to AEdit.Carets.Count-1 do begin Caret:= AEdit.Carets[i]; Pnt:= Point(Caret.PosX, Caret.PosY); dif1:= ComparePoints(Pnt, APos1); dif2:= ComparePoints(Pnt, APos2); case ACond of cCondInside: ok:= (dif1>=0) and (dif2<0); cCondOutside: ok:= (dif1<0) or (dif2>=0); cCondAtBound: ok:= (dif1=0) or (dif2=0); else ok:= false; end; if ok then exit(true); end; end; procedure TATAdapterEControl.SetEnabledLineSeparators(AValue: boolean); begin if FEnabledLineSeparators=AValue then Exit; FEnabledLineSeparators:= AValue; if Assigned(AnClient) then AnClient.EnabledLineSeparators:= EnabledLineSeparators; end; function TATAdapterEControl.GetTokenColorBG_FromMultiLineTokens(APos: TPoint; ADefColor: TColor; AEditorIndex: integer): TColor; var Token: TecSyntToken; n: integer; begin Result:= ADefColor; n:= DoFindToken(APos); if n<0 then exit; Token:= AnClient.Tags[n]; if IsPosInRange( APos.X, APos.Y, Token.PointStart.X, Token.PointStart.Y, Token.PointEnd.X, Token.PointEnd.Y) = cRelateInside then if Token.Style<>nil then Result:= Token.Style.BgColor; end; function TATAdapterEControl.GetTokenColorBG_FromColoredRanges(APos: TPoint; ADefColor: TColor; AEditorIndex: integer): TColor; var Rng: TATRangeColored; act: boolean; i: integer; begin Result:= ADefColor; //todo: binary search in ListColoredRanges... for i:= ListColoredRanges.Count-1 downto 0 do begin Rng:= TATRangeColored(ListColoredRanges[i]); act:= false; if Rng.ActiveAlways then act:= true else act:= Rng.Active[AEditorIndex] and Assigned(Rng.Rule) and (Rng.Rule.DynHighlight in [dhRange, dhRangeNoBound]); if act then if IsPosInRange( APos.X, APos.Y, Rng.Pos1.X, Rng.Pos1.Y, Rng.Pos2.X, Rng.Pos2.Y ) = cRelateInside then Exit(Rng.Color); end; end; procedure TATAdapterEControl.UpdateRangesActive(AEdit: TATSynEdit); var Rng, RngOut: TATRangeColored; i, j: integer; act: boolean; begin if not IsDynamicHiliteEnabled then Exit; for i:= 0 to ListColoredRanges.Count-1 do begin Rng:= TATRangeColored(ListColoredRanges[i]); if Rng.ActiveAlways then act:= true else begin if Rng.Rule=nil then Continue; if not (Rng.Rule.DynHighlight in [dhRange, dhRangeNoBound, dhBound]) then Continue; case Rng.Rule.HighlightPos of cpAny: act:= true; cpBound: act:= IsCaretInRange(AEdit, Rng.Pos1, Rng.Pos2, cCondAtBound); cpBoundTag: act:= false;//todo cpRange: act:= IsCaretInRange(AEdit, Rng.Pos1, Rng.Pos2, cCondInside); cpBoundTagBegin: act:= false;//todo cpOutOfRange: act:= IsCaretInRange(AEdit, Rng.Pos1, Rng.Pos2, cCondOutside); else act:= false; end; end; Rng.Active[AEdit.EditorIndex]:= act; end; //deactivate ranges by DynSelectMin //cycle back, to see first nested ranges for i:= ListColoredRanges.Count-1 downto 0 do begin Rng:= TATRangeColored(ListColoredRanges[i]); if not Rng.Active[AEdit.EditorIndex] then Continue; if Rng.Rule=nil then Continue; if not Rng.Rule.DynSelectMin then Continue; if not (Rng.Rule.DynHighlight in [dhBound, dhRange, dhRangeNoBound]) then Continue; //take prev ranges which contain this range for j:= i-1 downto 0 do begin RngOut:= TATRangeColored(ListColoredRanges[j]); if RngOut.Rule=Rng.Rule then if RngOut.Active[AEdit.EditorIndex] then if (ComparePoints(RngOut.Pos1, Rng.Pos1)<=0) and (ComparePoints(RngOut.Pos2, Rng.Pos2)>=0) then RngOut.Active[AEdit.EditorIndex]:= false; end; end; //ShowMessage('ColoredRanges: '+IntToStr(ListColoredRanges.Count)); end; procedure TATAdapterEControl.DoCalcParts(var AParts: TATLineParts; ALine, AX, ALen: integer; AColorFont, AColorBG: TColor; var AColorAfter: TColor; AEditorIndex: integer); var Ed: TATSynEdit; Strings: TATStrings; nColorText: TColor; partindex: integer; // procedure AddMissingPart(AOffset, ALen: integer); var part: PATLinePart; begin if ALen<=0 then Exit; part:= @AParts[partindex]; FillChar(part^, SizeOf(TATLinePart), 0); part^.Offset:= AOffset; part^.Len:= ALen; (* ////cannot make this code OK for test Markdown file with long wrapped lines, ////some text chars have clNone, like white //check that part's last char is space (ie it's space part), //and set for it clNone if Strings.LineSub(ALine, AOffset+ALen+AX-1, 1)=' ' then part^.ColorFont:= clNone else *) part^.ColorFont:= nColorText; part^.ColorBG:= GetTokenColorBG_FromColoredRanges( Point(AX+AOffset, ALine), AColorBG, AEditorIndex); Inc(partindex); end; // var tokenStart, tokenEnd, TestPoint: TPoint; startindex, mustOffset: integer; token: TecSyntToken; tokenStyle: TecSyntaxFormat; part: TATLinePart; nColor: TColor; i: integer; begin partindex:= 0; FillChar(part{%H-}, SizeOf(part), 0); Ed:= TATSynEdit(EdList[0]); Strings:= Ed.Strings; nColorText:= Ed.Colors.TextFont; startindex:= DoFindToken(Point(0, ALine)); if startindex<0 then startindex:= 0; //debug //Application.MainForm.Caption:= Format('adapter startindex %d', [startindex]); for i:= startindex to AnClient.TagCount-1 do begin token:= AnClient.Tags[i]; tokenStart:= token.PointStart; tokenEnd:= token.PointEnd; Dec(tokenStart.x, AX); Dec(tokenEnd.x, AX); if (tokenStart.y>ALine) then Break; if (tokenStart.y>ALine) or (tokenEnd.y<ALine) then Continue; if (tokenEnd.y<=ALine) and (tokenEnd.x<0) then Continue; if (tokenStart.y>=ALine) and (tokenStart.x>=ALen) then Continue; FillChar(part{%H-}, SizeOf(part), 0); if (tokenStart.y<ALine) or (tokenStart.x<0) then part.Offset:= 0 else part.Offset:= tokenStart.X; if (tokenEnd.y>ALine) or (tokenEnd.x>=ALen) then part.Len:= ALen-part.Offset else part.Len:= tokenEnd.X-part.Offset; part.ColorFont:= AColorFont; part.ColorBG:= GetTokenColorBG_FromColoredRanges(token.PointStart, AColorBG, AEditorIndex); tokenStyle:= token.Style; DoFindTokenOverrideStyle(tokenStyle, i, AEditorIndex); if tokenStyle<>nil then ApplyPartStyleFromEcontrolStyle(part, tokenStyle); //add missing part if partindex=0 then mustOffset:= 0 else with AParts[partindex-1] do mustOffset:= Offset+Len; if part.Offset>mustOffset then begin AddMissingPart(mustOffset, part.Offset-mustOffset); if partindex>=High(AParts) then Exit; end; //add calculated part if part.Len>0 then begin AParts[partindex]:= part; Inc(partindex); if partindex>=High(AParts) then Exit; end; end; //application.MainForm.Caption:= 'startindex '+inttostr(startindex)+' count-tokens '+inttostr(count); //add ending missing part //(not only if part.Len>0) mustOffset:= part.Offset+part.Len; if mustOffset<ALen then AddMissingPart(mustOffset, ALen-mustOffset); //calc AColorAfter TestPoint:= Point(AX+ALen, ALine); //a) calc it from colored-ranges nColor:= GetTokenColorBG_FromColoredRanges(TestPoint, clNone, AEditorIndex); //if (nColor=clNone) and (ALen>0) then // nColor:= GetTokenColorBG_FromColoredRanges(mustOffset-1, clNone, AEditorIndex); //b) calc it from multi-line tokens (with bg-color) if (nColor=clNone) then nColor:= GetTokenColorBG_FromMultiLineTokens(TestPoint, clNone, AEditorIndex); if (nColor=clNone) then nColor:= AColorAfter; AColorAfter:= nColor; end; procedure TATAdapterEControl.DoClearRanges; var j: integer; Ed: TATSynEdit; begin ListColoredRanges.Clear; for j:= 0 to EdList.Count-1 do begin Ed:= TATSynEdit(EdList[j]); Ed.Fold.Clear; Ed.Strings.ClearSeparators; end; end; constructor TATAdapterEControl.Create(AOwner: TComponent); begin inherited; EdList:= TList.Create; AnClient:= nil; Buffer:= TATStringBuffer.Create; ListColoredRanges:= TList.Create; FEnabledLineSeparators:= false; FEnabledSublexerTreeNodes:= false; TimerDuringAnalyze:= TTimer.Create(Self); TimerDuringAnalyze.Enabled:= false; TimerDuringAnalyze.Interval:= cAdapterTimerDuringAnalyzeInterval; TimerDuringAnalyze.OnTimer:= @TimerDuringAnalyzeTimer; end; destructor TATAdapterEControl.Destroy; var i: integer; begin AddEditor(nil); if Assigned(AnClient) then FreeAndNil(AnClient); for i:= ListColoredRanges.Count-1 downto 0 do TObject(ListColoredRanges[i]).Free; FreeAndNil(ListColoredRanges); FreeAndNil(Buffer); FreeAndNil(EdList); inherited; end; procedure TATAdapterEControl.AddEditor(AEditor: TComponent); var i: integer; begin if AEditor=nil then begin for i:= 0 to EdList.Count-1 do TATSynEdit(EdList[i]).AdapterForHilite:= nil; EdList.Clear; end else begin if EdList.IndexOf(AEditor)<0 then begin EdList.Add(AEditor); TATSynEdit(AEditor).Strings.OnLog:= @DoChangeLog; TATSynEdit(AEditor).AdapterForHilite:= Self; end; end; end; function TATAdapterEControl.LexerAtPos(Pnt: TPoint): TecSyntAnalyzer; begin Result:= nil; if AnClient<>nil then Result:= AnClient.AnalyzerAtPos(Buffer.CaretToStr(Pnt)); end; procedure TATAdapterEControl.StopTreeUpdate; begin FStopTreeUpdate:= true; end; procedure TATAdapterEControl.Stop; begin TimerDuringAnalyze.Enabled:= false; if not Application.Terminated then begin if FBusyTreeUpdate then begin Sleep(100); //Application.ProcessMessages; end; if FBusyTimer then begin Sleep(TimerDuringAnalyze.Interval+50); //Application.ProcessMessages; end; end; if Assigned(AnClient) then AnClient.Stop; end; function TATAdapterEControl.GetTokenString(token: TecSyntToken): string; begin if Assigned(Buffer) then Result:= Utf8Encode(Buffer.SubString(token.StartPos+1, token.EndPos-token.StartPos)) else Result:= ''; end; procedure TATAdapterEControl.GetTokenProps(token: TecSyntToken; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); begin APntFrom:= token.PointStart; APntTo:= token.PointEnd; ATokenString:= GetTokenString(token); if Assigned(token.Style) then ATokenStyle:= token.Style.DisplayName else ATokenStyle:= ''; end; procedure TATAdapterEControl.GetTokenWithIndex(AIndex: integer; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); begin APntFrom:= Point(-1, -1); APntTo:= Point(-1, -1); ATokenString:= ''; ATokenStyle:= ''; if AnClient=nil then exit; if Buffer=nil then exit; if (AIndex>=0) and (AIndex<AnClient.TagCount) then GetTokenProps(AnClient.Tags[AIndex], APntFrom, APntTo, ATokenString, ATokenStyle); end; procedure TATAdapterEControl.GetTokenAtPos(APos: TPoint; out APntFrom, APntTo: TPoint; out ATokenString, ATokenStyle: string); var n: integer; begin APntFrom:= Point(-1, -1); APntTo:= Point(-1, -1); ATokenString:= ''; ATokenStyle:= ''; if AnClient=nil then exit; if Buffer=nil then exit; n:= DoFindToken(APos); if n>=0 then GetTokenProps(AnClient.Tags[n], APntFrom, APntTo, ATokenString, ATokenStyle); end; function TATAdapterEControl.GetRangeParent(R: TecTextRange): TecTextRange; //cannot use R.Parent! var RTest: TecTextRange; i: integer; begin Result:= nil; for i:= R.Index-1 downto 0 do begin RTest:= AnClient.Ranges[i]; if (RTest.StartIdx<=R.StartIdx) and (RTest.EndIdx>=R.EndIdx) and (RTest.Level<R.Level) then begin Result:= RTest; Exit end; end; end; function TreeFindNode(ATree: TTreeView; ANode: TTreeNode; const ANodeText: string): TTreeNode; var N: TTreeNode; begin Result:= nil; if ATree.Items.Count=0 then exit; if ANode<>nil then N:= ANode.GetFirstChild else N:= ATree.Items[0]; repeat if N=nil then exit; if N.Text=ANodeText then Exit(N); N:= N.GetNextSibling; until false; end; procedure TATAdapterEControl.TreeFill(ATree: TTreeView); const cProgressRangeCount = 5000; var R, RangeParent: TecTextRange; NodeParent, NodeGroup: TTreeNode; NodeText, NodeTextGroup, SItem: string; NameRule, NameLexer: string; NodeData: pointer; RangeNew: TATRangeInCodeTree; i: integer; begin FStopTreeUpdate:= false; FBusyTreeUpdate:= true; //ATree.Items.BeginUpdate; try ClearTreeviewWithData(ATree); if AnClient=nil then exit; NameLexer:= AnClient.Owner.LexerName; for i:= 0 to AnClient.RangeCount-1 do begin if FStopTreeUpdate then exit; if Application.Terminated then exit; if (i mod cProgressRangeCount)=0 then Application.ProcessMessages; R:= AnClient.Ranges[i]; if R.Rule=nil then Continue; if not R.Rule.DisplayInTree then Continue; if not FEnabledSublexerTreeNodes then begin NameRule:= R.Rule.SyntOwner.LexerName; //must allow lexer name "PHP_" if main lexer is "PHP" if NameRule[Length(NameRule)]='_' then SetLength(NameRule, Length(NameRule)-1); if NameRule<>NameLexer then Continue; end; NodeText:= Trim(Utf8Encode(AnClient.GetRangeName(R))); NodeTextGroup:= Trim(Utf8Encode(AnClient.GetRangeGroup(R))); NodeData:= R; NodeParent:= nil; NodeGroup:= nil; //strip tree items from #10 SDeleteFromEol(NodeText); SDeleteFromEol(NodeTextGroup); RangeParent:= GetRangeParent(R); while (RangeParent<>nil) and (not RangeParent.Rule.DisplayInTree) do RangeParent:= GetRangeParent(RangeParent); if RangeParent<>nil then NodeParent:= ATree.Items.FindNodeWithData(RangeParent); if NodeTextGroup<>'' then repeat SItem:= SGetItem(NodeTextGroup, '\'); if (SItem='') and (NodeTextGroup='') then Break; if SItem='' then NodeGroup:= nil else begin NodeGroup:= TreeFindNode(ATree, NodeParent, SItem); if NodeGroup=nil then begin NodeGroup:= ATree.Items.AddChild(NodeParent, SItem); NodeGroup.ImageIndex:= R.Rule.TreeGroupImage; NodeGroup.SelectedIndex:= NodeGroup.ImageIndex; end; end; NodeParent:= NodeGroup; until false; NodeParent:= ATree.Items.AddChildObject(NodeParent, NodeText, NodeData); NodeParent.ImageIndex:= R.Rule.TreeItemImage; NodeParent.SelectedIndex:= NodeParent.ImageIndex; end; //tree filled with Data as TecTextRange //now replace all Data to TATRangeInCodetree for i:= 0 to ATree.Items.Count-1 do begin NodeParent:= ATree.Items[i]; if NodeParent.Data=nil then Continue; R:= TecTextRange(NodeParent.Data); RangeNew:= TATRangeInCodeTree.Create; if R.StartIdx>=0 then RangeNew.PosBegin:= AnClient.Tags[R.StartIdx].PointStart else RangeNew.PosBegin:= Point(-1, -1); if R.EndIdx>=0 then RangeNew.PosEnd:= AnClient.Tags[R.EndIdx].PointEnd else RangeNew.PosEnd:= Point(-1, -1); NodeParent.Data:= RangeNew; end; finally //ATree.Items.EndUpdate; ATree.Invalidate; FBusyTreeUpdate:= false; end; end; procedure TATAdapterEControl.TreeGetPositionOfRange_EC(R: TecTextRange; out APosBegin, APosEnd: TPoint); begin APosBegin:= Point(-1, -1); APosEnd:= Point(-1, -1); if R=nil then exit; if AnClient=nil then exit; if R.StartIdx>=0 then APosBegin:= AnClient.Tags[R.StartIdx].PointStart; if R.EndIdx>=0 then APosEnd:= AnClient.Tags[R.EndIdx].PointEnd; end; function TATAdapterEControl.TreeGetRangeOfPosition(APos: TPoint): TecTextRange; var R: TecTextRange; NTokenOrig: integer; i: integer; begin Result:= nil; if AnClient=nil then exit; NTokenOrig:= DoFindToken(APos); if NTokenOrig<0 then exit; //find last range, which contains our token for i:= AnClient.RangeCount-1 downto 0 do begin R:= AnClient.Ranges[i]; if not R.Rule.DisplayInTree then Continue; if (R.StartIdx<=NTokenOrig) and (R.EndIdx>=NTokenOrig) then exit(R); end; end; function TATAdapterEControl.SublexerRangeCount: integer; begin if Assigned(AnClient) then Result:= AnClient.SubLexerRangeCount else Result:= 0; end; function TATAdapterEControl.SublexerRangeProps(AIndex: integer; out AStart, AEnd: TPoint; out ALexerName: string): boolean; var Range: TecSubLexerRange; begin Result:= false; AStart:= Point(0, 0); AEnd:= Point(0, 0); ALexerName:= ''; if AnClient=nil then exit; if Buffer=nil then exit; Result:= (AIndex>=0) and (AIndex<SublexerRangeCount); if Result then begin Range:= AnClient.SubLexerRanges[AIndex]; if Range=nil then exit; AStart:= Buffer.StrToCaret(Range.StartPos); AEnd:= Buffer.StrToCaret(Range.EndPos); if Assigned(Range.Rule) and Assigned(Range.Rule.SyntAnalyzer) then ALexerName:= Range.Rule.SyntAnalyzer.LexerName; end; end; procedure TATAdapterEControl.TreeShowItemForCaret(ATree: TTreeView; APos: TPoint); var Node, NodeResult: TTreeNode; Range: TATRangeInCodeTree; Pos1, Pos2: TPoint; i: integer; begin NodeResult:= nil; //ranges are sorted, so we find _last_ range which //includes APos for i:= ATree.Items.Count-1 downto 0 do begin Node:= ATree.Items[i]; if Node.Data<>nil then if TObject(Node.Data) is TATRangeInCodeTree then begin Range:= TATRangeInCodeTree(Node.Data); Pos1:= Range.PosBegin; Pos2:= Range.PosEnd; if IsPosInRange( APos.X, APos.Y, Pos1.X, Pos1.Y, Pos2.X, Pos2.Y, true) = cRelateInside then begin NodeResult:= Node; Break; end; end; end; if Assigned(NodeResult) then begin NodeResult.MakeVisible; ATree.Selected:= NodeResult; end; end; procedure TATAdapterEControl.OnEditorCaretMove(Sender: TObject); begin UpdateRangesActive(Sender as TATSynEdit); end; procedure TATAdapterEControl.SetLexer(AAnalizer: TecSyntAnalyzer); begin DoClearRanges; UpdateEditors(false, true); if Assigned(AnClient) then FreeAndNil(AnClient); DoParseBegin; if Assigned(AAnalizer) then begin AnClient:= TecClientSyntAnalyzer.Create(AAnalizer, Buffer, nil); AnClient.EnabledLineSeparators:= EnabledLineSeparators; UpdateData(true, true); end; if Assigned(FOnLexerChange) then FOnLexerChange(Self); DynamicHiliteSupportedInCurrentSyntax:= GetLexerSuportsDynamicHilite; end; procedure TATAdapterEControl.OnEditorChange(Sender: TObject); begin DoCheckEditorList; //if CurrentIdleInterval=0, OnEditorIdle will not fire, analyze here UpdateData(true, CurrentIdleInterval=0); end; procedure TATAdapterEControl.OnEditorIdle(Sender: TObject); begin DoCheckEditorList; UpdateData(false, true); UpdateEditors(true, true); end; procedure TATAdapterEControl.UpdateData(AUpdateBuffer, AAnalyze: boolean); var Ed: TATSynEdit; Lens: array of integer; i: integer; begin if EdList.Count=0 then Exit; if not Assigned(AnClient) then Exit; Ed:= TATSynEdit(EdList[0]); if AUpdateBuffer then begin SetLength(Lens, Ed.Strings.Count); for i:= 0 to Length(Lens)-1 do Lens[i]:= Ed.Strings.LinesLen[i]; Buffer.Setup(Ed.Strings.TextString_Unicode, Lens); end; if AAnalyze then begin DoAnalize(Ed, false); //dont clear ranges too early (and flicker with empty fold bar) if not EditorRunningCommand or IsDynamicHiliteEnabled then UpdateRanges; end; end; procedure TATAdapterEControl.UpdateRanges; begin DoClearRanges; UpdateRangesFold; UpdateRangesSublex; //sublexer ranges last if EnabledLineSeparators then UpdateSeparators; UpdateRangesActiveAll; end; procedure TATAdapterEControl.UpdateRangesActiveAll; var i: integer; begin for i:= 0 to EdList.Count-1 do UpdateRangesActive(TATSynEdit(EdList[i])); end; function TATAdapterEControl.EditorRunningCommand: boolean; var i: integer; begin Result:= false; if EdList.Count>0 then for i:= 0 to EdList.Count-1 do if TATSynEdit(EdList[i]).IsRunningCommand then exit(true); end; procedure TATAdapterEControl.DoAnalize(AEdit: TATSynEdit; AForceAnalizeAll: boolean); var NLine, NPos: integer; begin if AnClient=nil then exit; if Buffer.TextLength=0 then exit; DoParseBegin; if AForceAnalizeAll then begin AnClient.TextChanged(0, 1); //chg 1 char at pos 0 AnClient.Analyze; AnClient.IdleAppend; end else begin //LineBottom=0, if file just opened at beginning. //or >0 of file is edited at some scroll pos NLine:= AEdit.LineBottom; if NLine=0 then NLine:= AEdit.GetVisibleLines; NLine:= Min(NLine, Buffer.Count-1); NPos:= Buffer.CaretToStr(Point(0, NLine)); AnClient.AppendToPos(NPos); AnClient.IdleAppend; end; if AnClient.IsFinished then begin DoParseDone; end else begin UpdateEditors(true, true); //some portion is parsed already TimerDuringAnalyze.Enabled:= true; end; end; procedure TATAdapterEControl.DoFoldAdd(AX, AY, AY2: integer; AStaple: boolean; const AHint: string); var j: integer; begin if EdList.Count>0 then for j:= 0 to EdList.Count-1 do TATSynEdit(EdList[j]).Fold.Add(AX, AY, AY2, AStaple, AHint); end; procedure TATAdapterEControl.UpdateEditors(ARepaint, AClearCache: boolean); var Ed: TATSynEdit; i: integer; begin for i:= 0 to EdList.Count-1 do begin Ed:= TATSynEdit(EdList[i]); CurrentIdleInterval:= GetIdleInterval; Ed.OptIdleInterval:= CurrentIdleInterval; if AClearCache then Ed.InvalidateHilitingCache; if ARepaint then Ed.Update; end; end; procedure TATAdapterEControl.DoFoldFromLinesHidden; var i: integer; begin for i:= 0 to EdList.Count-1 do TATSynEdit(EdList[i]).UpdateFoldedFromLinesHidden; end; procedure TATAdapterEControl.UpdateSeparators; var Ed: TATSynEdit; Break: TecLineBreak; Sep: TATLineSeparator; i, j: integer; begin if EdList.Count=0 then Exit; Ed:= TATSynEdit(EdList[0]); for i:= 0 to Ed.Strings.Count-1 do Ed.Strings.LinesSeparator[i]:= cLineSepNone; if AnClient.LineBreaks.Count>0 then begin Break:= TecLineBreak(AnClient.LineBreaks[0]); for j:= 0 to EdList.Count-1 do TATSynEdit(EdList[j]).Colors.BlockSepLine:= Break.Rule.Style.BgColor; for i:= 0 to AnClient.LineBreaks.Count-1 do begin Break:= TecLineBreak(AnClient.LineBreaks[i]); Sep:= cLineSepTop; //parser considered top/bottom already //if Break.Rule.LinePos=lbTop then // Sep:= cLineSepTop //else // Sep:= cLineSepBottom; if Ed.Strings.IsIndexValid(Break.Line) then Ed.Strings.LinesSeparator[Break.Line]:= Sep; end; end; end; procedure TATAdapterEControl.UpdateRangesFold; var R: TecTextRange; Pnt1, Pnt2: TPoint; Style: TecSyntaxFormat; SHint: string; tokenStart, tokenEnd: TecSyntToken; i: integer; begin if not Assigned(AnClient) then Exit; //check folding enabled if EdList.Count>0 then if not TATSynEdit(EdList[0]).OptFoldEnabled then exit; for i:= 0 to AnClient.RangeCount-1 do begin if Application.Terminated then exit; R:= AnClient.Ranges[i]; if R.Rule.BlockType<>btRangeStart then Continue; /////issue: rules in C# with 'parent' set give wrong ranges; //rule "function begin", "prop begin"; //e.g. range from } bracket to some token before "else" //temp workard: skip rule with 'parent' {$ifdef skip_some_rules} if R.Rule.NotParent then Continue; {$endif} if R.StartIdx<0 then Continue; if R.EndIdx<0 then Continue; tokenStart:= AnClient.Tags[R.StartIdx]; tokenEnd:= AnClient.Tags[R.EndIdx]; Pnt1:= tokenStart.PointStart; Pnt2:= tokenEnd.PointEnd; if Pnt1.Y<0 then Continue; if Pnt2.Y<0 then Continue; //fill fold ranges if not R.Rule.NotCollapsed then begin SHint:= UTF8Encode(AnClient.GetCollapsedText(R)); //+'/'+R.Rule.GetNamePath; DoFoldAdd(Pnt1.X+1, Pnt1.Y, Pnt2.Y, R.Rule.DrawStaple, SHint); end; //fill ListColoredRanges //not only if DymamicHilite enabled (e.g. AutoIt has always hilited blocks) if R.Rule.DynHighlight<>dhNone then begin Style:= R.Rule.Style; if Style<>nil then if Style.BgColor<>clNone then begin //support lexer opt "Hilite lines of block" if R.Rule.Highlight then begin Pnt2.X:= Buffer.LineLength(Pnt2.Y) + 1; //+1 to make range longer, to hilite line to screen end end; ListColoredRanges.Add(TATRangeColored.Create( Pnt1, Pnt2, R.StartIdx, R.EndIdx, Style.BgColor, R.Rule, (R.Rule.HighlightPos=cpAny) )); end; end; end; //keep folded blks that were folded DoFoldFromLinesHidden; end; procedure TATAdapterEControl.UpdateRangesSublex; var R: TecSubLexerRange; Style: TecSyntaxFormat; i: integer; begin for i:= 0 to AnClient.SubLexerRangeCount-1 do begin if Application.Terminated then exit; R:= AnClient.SubLexerRanges[i]; if R.Rule=nil then Continue; if R.StartPos<0 then Continue; if R.EndPos<0 then Continue; Style:= R.Rule.Style; if Style=nil then Continue; if Style.BgColor<>clNone then ListColoredRanges.Add(TATRangeColored.Create( Buffer.StrToCaret(R.StartPos), Buffer.StrToCaret(R.EndPos), -1, -1, Style.BgColor, nil, true )); end; end; function TATAdapterEControl.DoFindToken(APos: TPoint): integer; var a, b, m, dif: integer; begin Result:= -1; a:= 0; b:= AnClient.TagCount-1; if b<0 then Exit; repeat dif:= ComparePoints(AnClient.Tags[a].PointStart, APos); if dif=0 then Exit(a); //middle, which is near b if not exact middle m:= (a+b+1) div 2; dif:= ComparePoints(AnClient.Tags[m].PointStart, APos); if dif=0 then Exit(m); if Abs(a-b)<=1 then Break; if dif>0 then b:= m else a:= m; until false; if m=0 then Result:= 0 else begin Result:= m; with AnClient.Tags[Result] do if (ComparePoints(PointStart, APos)<=0) and (ComparePoints(APos, PointEnd)<0) then exit; Result:= m-1; end; end; function TATAdapterEControl.GetLexer: TecSyntAnalyzer; begin if Assigned(AnClient) then Result:= AnClient.Owner else Result:= nil; end; procedure TATAdapterEControl.DoChangeLog(Sender: TObject; ALine, ACount: integer); var Pos: integer; begin if not Assigned(AnClient) then Exit; //clear? if ALine=-1 then begin AnClient.TextChanged(-1, 0); Exit end; //Count>0: add EolLen=1 //Count<0 means delete: minus EolLen if ACount>0 then Inc(ACount) else if ACount<0 then Dec(ACount); if ALine>=Buffer.Count then Pos:= Buffer.TextLength else Pos:= Buffer.CaretToStr(Point(0, ALine)); AnClient.TextChanged(Pos, ACount); end; procedure TATAdapterEControl.TimerDuringAnalyzeTimer(Sender: TObject); begin if Application.Terminated then begin TimerDuringAnalyze.Enabled:= false; exit end; if not Assigned(AnClient) then Exit; FBusyTimer:= true; try if AnClient.IsFinished then begin TimerDuringAnalyze.Enabled:= false; UpdateRanges; DoParseDone; end; finally FBusyTimer:= false; end; end; procedure TATAdapterEControl.DoFindTokenOverrideStyle(var ATokenStyle: TecSyntaxFormat; ATokenIndex, AEditorIndex: integer); var Rng: TATRangeColored; i: integer; begin //todo: binary search for i:= 0 to ListColoredRanges.Count-1 do begin Rng:= TATRangeColored(ListColoredRanges[i]); if Rng.Active[AEditorIndex] then if Rng.Rule<>nil then if Rng.Rule.DynHighlight=dhBound then if (Rng.Token1=ATokenIndex) or (Rng.Token2=ATokenIndex) then begin ATokenStyle:= Rng.Rule.Style; Exit end; end; end; function TATAdapterEControl.GetLexerSuportsDynamicHilite: boolean; var An: TecSyntAnalyzer; Rule: TecTagBlockCondition; i: integer; begin Result:= false; if not Assigned(AnClient) then exit; An:= AnClient.Owner; for i:= 0 to An.BlockRules.Count-1 do begin Rule:= An.BlockRules[i]; if Assigned(Rule) and (Rule.HighlightPos in [cpBound, cpRange, cpOutOfRange]) and (Rule.DynHighlight in [dhRange, dhRangeNoBound, dhBound]) then exit(true); end; end; function TATAdapterEControl.IsDynamicHiliteEnabled: boolean; var Ed: TATSynEdit; begin Ed:= TATSynEdit(EdList[0]); Result:= DynamicHiliteActiveNow(Ed.Strings.Count); end; procedure TATAdapterEControl.DoParseBegin; begin if Assigned(FOnParseBegin) then FOnParseBegin(Self); FStopTreeUpdate:= false; FTimeParseBegin:= GetTickCount64; end; procedure TATAdapterEControl.DoParseDone; begin //UpdateRanges call needed for small files, which are parsed to end by one IdleAppend call, //and timer didn't tick UpdateRanges; FTimeParseElapsed:= GetTickCount64-FTimeParseBegin; if Assigned(FOnParseDone) then FOnParseDone(Self); UpdateEditors(true, true); end; procedure TATAdapterEControl.DoAnalyzeFromLine(ALine: integer; AWait: boolean); var NPos: integer; begin if not Assigned(AnClient) then exit; DoParseBegin; NPos:= Buffer.CaretToStr(Point(0, ALine)); AnClient.ChangedAtPos(NPos); AnClient.AppendToPos(Buffer.TextLength); AnClient.IdleAppend; if AnClient.IsFinished then begin DoParseDone; end else begin TimerDuringAnalyze.Enabled:= true; if AWait then while not AnClient.IsFinished do begin Sleep(TimerDuringAnalyze.Interval+20); Application.ProcessMessages; end; end; end; function TATAdapterEControl.GetIdleInterval: integer; begin if Buffer.TextLength < cAdapterIdleTextSize then Result:= 0 else Result:= cAdapterIdleInterval; end; end.
var i: integer; max, min: real; x: array[1..5] of real := (1, 6, 9, 2, 4); begin max := x[1]; min := x[1]; for i := 1 to 5 do begin if max < x[i] then max := x[i]; if min > x[i] then min := x[i]; end; writeln('Max = ', Max); writeln('Min = ', Min); end.
unit FFSLOGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TFFSLOGRecord = record PLogID: Integer; PDateStamp: String[20]; PUserID: String[10]; PRecordType: String[10]; PLogMessage: String[100]; End; TFFSLOGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TFFSLOGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIFFSLOG = (FFSLOGPrimaryKey); TFFSLOGTable = class( TDBISAMTableAU ) private FDFLogID: TAutoIncField; FDFDateStamp: TStringField; FDFUserID: TStringField; FDFRecordType: TStringField; FDFLogMessage: TStringField; procedure SetPDateStamp(const Value: String); function GetPDateStamp:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPRecordType(const Value: String); function GetPRecordType:String; procedure SetPLogMessage(const Value: String); function GetPLogMessage:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIFFSLOG); function GetEnumIndex: TEIFFSLOG; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TFFSLOGRecord; procedure StoreDataBuffer(ABuffer:TFFSLOGRecord); property DFLogID: TAutoIncField read FDFLogID; property DFDateStamp: TStringField read FDFDateStamp; property DFUserID: TStringField read FDFUserID; property DFRecordType: TStringField read FDFRecordType; property DFLogMessage: TStringField read FDFLogMessage; property PDateStamp: String read GetPDateStamp write SetPDateStamp; property PUserID: String read GetPUserID write SetPUserID; property PRecordType: String read GetPRecordType write SetPRecordType; property PLogMessage: String read GetPLogMessage write SetPLogMessage; published property Active write SetActive; property EnumIndex: TEIFFSLOG read GetEnumIndex write SetEnumIndex; end; { TFFSLOGTable } procedure Register; implementation function TFFSLOGTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TFFSLOGTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TFFSLOGTable.GenerateNewFieldName } function TFFSLOGTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TFFSLOGTable.CreateField } procedure TFFSLOGTable.CreateFields; begin FDFLogID := CreateField( 'LogID' ) as TAutoIncField; FDFDateStamp := CreateField( 'DateStamp' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFRecordType := CreateField( 'RecordType' ) as TStringField; FDFLogMessage := CreateField( 'LogMessage' ) as TStringField; end; { TFFSLOGTable.CreateFields } procedure TFFSLOGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TFFSLOGTable.SetActive } procedure TFFSLOGTable.SetPDateStamp(const Value: String); begin DFDateStamp.Value := Value; end; function TFFSLOGTable.GetPDateStamp:String; begin result := DFDateStamp.Value; end; procedure TFFSLOGTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TFFSLOGTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TFFSLOGTable.SetPRecordType(const Value: String); begin DFRecordType.Value := Value; end; function TFFSLOGTable.GetPRecordType:String; begin result := DFRecordType.Value; end; procedure TFFSLOGTable.SetPLogMessage(const Value: String); begin DFLogMessage.Value := Value; end; function TFFSLOGTable.GetPLogMessage:String; begin result := DFLogMessage.Value; end; procedure TFFSLOGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LogID, AutoInc, 0, N'); Add('DateStamp, String, 20, N'); Add('UserID, String, 10, N'); Add('RecordType, String, 10, N'); Add('LogMessage, String, 100, N'); end; end; procedure TFFSLOGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LogID, Y, Y, N, Y'); end; end; procedure TFFSLOGTable.SetEnumIndex(Value: TEIFFSLOG); begin case Value of FFSLOGPrimaryKey : IndexName := ''; end; end; function TFFSLOGTable.GetDataBuffer:TFFSLOGRecord; var buf: TFFSLOGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLogID := DFLogID.Value; buf.PDateStamp := DFDateStamp.Value; buf.PUserID := DFUserID.Value; buf.PRecordType := DFRecordType.Value; buf.PLogMessage := DFLogMessage.Value; result := buf; end; procedure TFFSLOGTable.StoreDataBuffer(ABuffer:TFFSLOGRecord); begin DFDateStamp.Value := ABuffer.PDateStamp; DFUserID.Value := ABuffer.PUserID; DFRecordType.Value := ABuffer.PRecordType; DFLogMessage.Value := ABuffer.PLogMessage; end; function TFFSLOGTable.GetEnumIndex: TEIFFSLOG; var iname : string; begin result := FFSLOGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := FFSLOGPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'FFS Tables', [ TFFSLOGTable, TFFSLOGBuffer ] ); end; { Register } function TFFSLOGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('LOGID','DATESTAMP','USERID','RECORDTYPE','LOGMESSAGE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TFFSLOGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; end; end; function TFFSLOGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLogID; 2 : result := @Data.PDateStamp; 3 : result := @Data.PUserID; 4 : result := @Data.PRecordType; 5 : result := @Data.PLogMessage; end; end; end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } { *************************************************************************** } { Amarildo Lacerda 03/10/2016 pluginService - Utilizado no plugin a ser consumido pelo Manager. } {$D+} unit Plugin.Service; interface uses WinApi.Windows, System.Classes, System.SysUtils, {$IFDEF FMX} FMX.Forms, FMX.Controls, System.UITypes, {$ELSE} VCL.Forms, VCL.Controls, {$ENDIF} Plugin.Interf, System.Generics.collections; Type // List of plugins TPluginItemsInterfacedClass = class of TPluginItemsInterfaced; TPluginItemsInterfaced = class(TInterfacedObject, IPluginItems) protected FItems: TList<IPluginInfo>; public constructor Create; destructor Destroy; override; procedure Connection(const AConnectionString: string); virtual; function Count: integer; function GetItem(idx: integer): IPluginInfo; procedure Add(APlugin: IPluginInfo); procedure Install; virtual; procedure UnInstall; virtual; end; // plugin base TPluginService = class(TComponent, IPluginInfo) private FTypeID: Int64; FParentHandle: THandle; protected FForm: TForm; FOwned: boolean; function GetTypeID: Int64; virtual; procedure SetTypeID(const Value: Int64); virtual; procedure Perform(AMsg: Cardinal; WParam: NativeUInt; LParam: NativeUInt); public constructor Create; overload; destructor Destroy; override; function GetAuthor: string; virtual; procedure DoStart; virtual; function GetInterface: IPluginExecuteBase; virtual; function PluginName: string; virtual; procedure Embedded(const AParent: THandle); virtual; function CanClose: boolean; virtual; published property TypeID: Int64 read GetTypeID write SetTypeID; end; // register one plugin to list of plugins procedure RegisterPlugin(AInfo: IPluginInfo); procedure RegisterPluginClass(AClass: TPluginItemsInterfacedClass); // exported plugins from DLL // return list of plugins in DLL function LoadPlugin(AAplication: IPluginApplication): IPluginItems; // exported unload plugins procedure UnloadPlugin; function GetPluginItems: IPluginItems; procedure Register; var PluginExitProc: TProc; PluginEnterProc: TProc; implementation var LPlugin: IPluginItems; LPluginClass: TPluginItemsInterfacedClass; procedure Register; begin RegisterComponents('Store', [TPluginService]); end; procedure RegisterPluginClass(AClass: TPluginItemsInterfacedClass); begin LPluginClass := AClass; end; function GetPluginItems: IPluginItems; begin result := LPlugin; end; { TPluginService<T> } function TPluginService.GetAuthor: string; begin result := 'storeware'; end; function TPluginService.GetInterface: IPluginExecuteBase; begin if Supports(FForm, IPluginExecuteBase) then result := FForm as IPluginExecuteBase; end; destructor TPluginService.Destroy; begin FreeAndNil(FForm); inherited; end; procedure TPluginService.DoStart; begin end; function TPluginService.PluginName: string; begin if assigned(FForm) then result := FForm.Caption else result := self.Name; end; procedure TPluginService.Perform(AMsg: Cardinal; WParam, LParam: NativeUInt); var WindRect: TRect; begin if assigned(FForm) then begin if AMsg = SW_MAXIMIZE then begin GetWindowRect(FParentHandle, WindRect); FForm.Height := WindRect.Height; FForm.Width := WindRect.Width; end else {$IFDEF FMX} {$ELSE} FForm.Perform(AMsg, WParam, LParam); {$ENDIF} end; end; procedure TPluginService.SetTypeID(const Value: Int64); begin FTypeID := Value; end; function TPluginService.GetTypeID: Int64; begin result := FTypeID; end; function TPluginService.CanClose: boolean; begin result := true; if not assigned(FForm) then exit; if Supports(FForm, IPluginExecuteBase) then result := (FForm as IPluginExecuteBase).CanClose else begin result := FForm.CloseQuery; end; end; constructor TPluginService.Create; begin inherited create(nil); // PluginService := self; end; procedure TPluginService.Embedded(const AParent: THandle); begin if not assigned(FForm) then exit; FParentHandle := AParent; FForm.Left := 0; FForm.Top := 0; FForm.BorderIcons := []; {$IFDEF FMX} FForm.WindowState := TWindowState.wsMaximized; FForm.Show; {$ELSE} WinApi.Windows.SetParent(FForm.Handle, AParent); FForm.BorderStyle := bsNone; FForm.Align := alClient; FForm.Show; ShowWindowAsync(FForm.Handle, SW_MAXIMIZE); {$ENDIF} end; function LoadPlugin(AAplication: IPluginApplication): IPluginItems; var i: integer; begin PluginApplication := AAplication; result := LPlugin; for i := 0 to result.Count - 1 do result.GetItem(i).DoStart; if assigned(PluginEnterProc) then PluginEnterProc; end; procedure UnloadPlugin; var i:integer; begin {$IFDEF DLL} {$ELSE} {$ENDIF} if assigned(PluginExitProc) then PluginExitProc; Application.ProcessMessages; end; procedure RegisterPlugin(AInfo: IPluginInfo); begin if not assigned(LPlugin) then LPlugin := LPluginClass.Create; LPlugin.Add(AInfo); end; { TPluginInterfaced } procedure TPluginItemsInterfaced.Add(APlugin: IPluginInfo); begin FItems.Add(APlugin); end; procedure TPluginItemsInterfaced.Connection(const AConnectionString: string); begin end; function TPluginItemsInterfaced.Count: integer; begin result := FItems.Count; end; constructor TPluginItemsInterfaced.Create; begin inherited; FItems := TList<IPluginInfo>.Create; end; destructor TPluginItemsInterfaced.Destroy; var i: IPluginInfo; begin while FItems.Count > 0 do begin try i := FItems.Items[0]; i := nil; FItems.delete(0); except end; end; FItems.Free; inherited; end; function TPluginItemsInterfaced.GetItem(idx: integer): IPluginInfo; begin result := FItems.Items[idx]; end; procedure TPluginItemsInterfaced.Install; begin end; procedure TPluginItemsInterfaced.UnInstall; begin end; exports LoadPlugin, UnloadPlugin; initialization RegisterPluginClass(TPluginItemsInterfaced); finalization {$IFDEF DLL} // LPlugin := nil; {$ENDIF} end.
unit chessdrawer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, LCLType, IntfGraphics, fpimage, Math, chessgame, chessconfig; type { dsIdle - Accepts user input dsDragging - During an user input dsRunningAnimation - Does not accept user input because it is running an animation } TDrawerState = (dsIdle, dsDragging, dsRunningAnimation); { TChessAnimation } TChessAnimation = class CurrentStep: Integer; FinalStep: Integer; constructor Create; procedure DrawToIntfImg(AIntfImg: TLazIntfImage); virtual; abstract; procedure ExecuteFinal; virtual; abstract; function SkipDrawingPiece(col, row: Integer): Boolean; virtual; abstract; end; { TChessMoveAnimation } TChessMoveAnimation = class(TChessAnimation) public AFrom, ATo: TPoint; procedure DrawToIntfImg(AIntfImg: TLazIntfImage); override; procedure ExecuteFinal; override; function SkipDrawingPiece(col, row: Integer): Boolean; override; end; TChessDrawerDelegate = class public procedure HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); virtual; abstract; procedure HandleMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; abstract; procedure HandleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; abstract; end; { TChessDrawer } TChessDrawer = class(TCustomControl) private imgBoard, imgWPawn, imgWKnight, imgWBishop, imgWRook, imgWQueen, imgWKing, imgBPawn, imgBKnight, imgBBishop, imgBRook, imgBQueen, imgBKing: TPortableNetworkGraphic; { bmpBoard, bmpWPawn, bmpWKnight, bmpWBishop, bmpWRook, bmpWQueen, bmpWKing, bmpBPawn, bmpBKnight, bmpBBishop, bmpBRook, bmpBQueen, bmpBKing: TBitmap;} FDrawerState: TDrawerState; FDelegate: TChessDrawerDelegate; FAnimation: TChessAnimation; public constructor Create(AOwner: TComponent); override; procedure EraseBackground(DC: HDC); override; procedure Paint; override; procedure DrawToCanvas(ACanvas: TCanvas); procedure DrawImageWithTransparentColor( ADest: TLazIntfImage; const ADestX, ADestY: Integer; AColor: TFPColor; AImage: TFPImageBitmap); function GetChessTileImage(ATile: TChessTile): TPortableNetworkGraphic; procedure LoadImages(); procedure SetDelegate(ADelegate: TChessDrawerDelegate); procedure HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure HandleMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HandleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HandleOnTimer(Sender: TObject); procedure AddAnimation(AAnimation: TChessAnimation); end; var vChessDrawer: TChessDrawer; implementation { TChessMoveAnimation } procedure TChessMoveAnimation.DrawToIntfImg(AIntfImg: TLazIntfImage); var lTileBmp: TPortableNetworkGraphic; X, Y, SourceX, SourceY, DestX, DestY: integer; dx, dy: Integer; t: Double; lTile: TChessTile; begin // Draw the moving tile //WriteLn(Format('[TChessMoveAnimation.DrawToIntfImg] Afrom=%d,%d', [AFrom.X, AFrom.Y])); lTile := vChessGame.Board[AFrom.X][AFrom.Y]; lTileBmp := vChessDrawer.GetChessTileImage(lTile); if lTileBmp = nil then Exit; SourceX := (AFrom.X - 1) * INT_CHESSTILE_SIZE; SourceY := (8 - AFrom.Y) * INT_CHESSTILE_SIZE; DestX := (ATo.X - 1) * INT_CHESSTILE_SIZE; DestY := (8 - ATo.Y) * INT_CHESSTILE_SIZE; t := CurrentStep / FinalStep; X := Round(t * DestX + (1-t) * SourceX); Y := Round(t * DestY + (1-t) * SourceY); vChessDrawer.DrawImageWithTransparentColor(AIntfImg, X, Y, FPCOLOR_TRANSPARENT_TILE, lTileBmp); end; procedure TChessMoveAnimation.ExecuteFinal; begin vChessGame.MovePiece(AFrom, ATo); end; function TChessMoveAnimation.SkipDrawingPiece(col, row: Integer): Boolean; begin Result := (col = AFrom.X) and (row = AFrom.Y); end; { TChessAnimation } constructor TChessAnimation.Create; begin inherited Create; CurrentStep := 0; FinalStep := 20; end; constructor TChessDrawer.Create(AOwner: TComponent); begin inherited Create(AOwner); imgBoard := TPortableNetworkGraphic.Create; imgWPawn := TPortableNetworkGraphic.Create; imgWKnight := TPortableNetworkGraphic.Create; imgWBishop := TPortableNetworkGraphic.Create; imgWRook := TPortableNetworkGraphic.Create; imgWQueen := TPortableNetworkGraphic.Create; imgWKing := TPortableNetworkGraphic.Create; imgBPawn := TPortableNetworkGraphic.Create; imgBKnight := TPortableNetworkGraphic.Create; imgBBishop := TPortableNetworkGraphic.Create; imgBRook := TPortableNetworkGraphic.Create; imgBQueen := TPortableNetworkGraphic.Create; imgBKing := TPortableNetworkGraphic.Create; { bmpBoard := TBitmap.Create; bmpWPawn := TBitmap.Create; bmpWKnight := TBitmap.Create; bmpWBishop := TBitmap.Create; bmpWRook := TBitmap.Create; bmpWQueen := TBitmap.Create; bmpWKing := TBitmap.Create; bmpBPawn := TBitmap.Create; bmpBKnight := TBitmap.Create; bmpBBishop := TBitmap.Create; bmpBRook := TBitmap.Create; bmpBQueen := TBitmap.Create; bmpBKing := TBitmap.Create; } // Events OnMouseMove := @HandleMouseMove; OnMouseUp := @HandleMouseUp; OnMouseDown := @HandleMouseDown; end; procedure TChessDrawer.EraseBackground(DC: HDC); begin // Uncomment this to enable default background erasing //inherited EraseBackground(DC); end; procedure TChessDrawer.Paint; var x, y: integer; Bitmap: TBitmap; begin Bitmap := TBitmap.Create; try // Initializes the Bitmap Size Bitmap.Height := Height; Bitmap.Width := Width; DrawToCanvas(Bitmap.Canvas); Canvas.Draw(0, 0, Bitmap); finally Bitmap.Free; end; // inherited Paint; end; procedure TChessDrawer.DrawToCanvas(ACanvas: TCanvas); var col, row: integer; lIntfImage: TLazIntfImage; lTmpBmp: TBitmap; lTileBmp: TPortableNetworkGraphic; X, Y: integer; begin lIntfImage := TLazIntfImage.Create(0, 0); lTmpBmp := TBitmap.Create; try // First draw the board lIntfImage.LoadFromBitmap(imgBoard.Handle, 0{bmpBoard.MaskHandle}); // Now all pieces for col := 1 to 8 do for row := 1 to 8 do begin // Check if the animation wants us to skip drawing this piece if Assigned(FAnimation) and FAnimation.SkipDrawingPiece(col, row) then Continue; lTileBmp := GetChessTileImage(vChessGame.Board[col][row]); if lTileBmp = nil then Continue; X := (col - 1) * INT_CHESSTILE_SIZE; Y := (8 - row) * INT_CHESSTILE_SIZE; DrawImageWithTransparentColor(lIntfImage, X, Y, FPCOLOR_TRANSPARENT_TILE, lTileBmp); end; // Now animations if Assigned(FAnimation) then FAnimation.DrawToIntfImg(lIntfImage); lTmpBmp.LoadFromIntfImage(lIntfImage); ACanvas.Draw(0, 0, lTmpBmp); finally lTmpBmp.Free; lIntfImage.Free; end; end; procedure TChessDrawer.DrawImageWithTransparentColor(ADest: TLazIntfImage; const ADestX, ADestY: Integer; AColor: TFPColor; AImage: TFPImageBitmap); var x, y, CurX, CurY: Integer; IntfImage: TLazIntfImage; lDrawWidth, lDrawHeight: Integer; CurColor: TFPColor; lCurColorDiv, lTranspColorDiv: Byte; begin IntfImage := TLazIntfImage.Create(0,0); try IntfImage.LoadFromBitmap(AImage.Handle, AImage.MaskHandle); // Take care not to draw outside the destination area lDrawWidth := Min(ADest.Width - ADestX, AImage.Width); lDrawHeight := Min(ADest.Height - ADestY, AImage.Height); for y := 0 to lDrawHeight - 1 do begin for x := 0 to lDrawWidth - 1 do begin CurX := ADestX + x; CurY := ADestY + y; // Never draw outside the destination if (CurX < 0) or (CurY < 0) then Continue; CurColor := IntfImage.Colors[x, y]; // Good for debugging lCurColorDiv := CurColor.Green div $FF; lTranspColorDiv := AColor.Green div $FF; if lCurColorDiv <> lTranspColorDiv then ADest.Colors[CurX, CurY] := IntfImage.Colors[x, y]; end; end; finally IntfImage.Free; end; end; function TChessDrawer.GetChessTileImage(ATile: TChessTile): TPortableNetworkGraphic; begin case ATile of ctWPawn: Result := imgWPawn; ctWKnight: Result := imgWKnight; ctWBishop: Result := imgWBishop; ctWRook: Result := imgWRook; ctWQueen: Result := imgWQueen; ctWKing: Result := imgWKing; ctBPawn: Result := imgBPawn; ctBKnight: Result := imgBKnight; ctBBishop: Result := imgBBishop; ctBRook: Result := imgBRook; ctBQueen: Result := imgBQueen; ctBKing: Result := imgBKing; else Result := nil; end; end; procedure TChessDrawer.LoadImages(); var lDir: string; begin lDir := vChessConfig.GetCurrentSkinDir(); imgBoard.LoadFromFile(lDir + 'base.png'); imgWPawn.LoadFromFile(lDir + 'wpawn.png'); imgWKnight.LoadFromFile(lDir + 'wknight.png'); imgWBishop.LoadFromFile(lDir + 'wbishop.png'); imgWRook.LoadFromFile(lDir + 'wrook.png'); imgWQueen.LoadFromFile(lDir + 'wqueen.png'); imgWKing.LoadFromFile(lDir + 'wking.png'); imgBPawn.LoadFromFile(lDir + 'bpawn.png'); imgBKnight.LoadFromFile(lDir + 'bknight.png'); imgBBishop.LoadFromFile(lDir + 'bbishop.png'); imgBRook.LoadFromFile(lDir + 'brook.png'); imgBQueen.LoadFromFile(lDir + 'bqueen.png'); imgBKing.LoadFromFile(lDir + 'bking.png'); { bmpWKnight.Assign(imgWKnight); bmpWKnight.Assign(imgWBishop); bmpWKnight.Assign(imgWRook); bmpWKnight.Assign(imgWQueen); bmpWKnight.Assign(imgWKing); bmpWKnight.Assign(imgBPawn); bmpWKnight.Assign(imgBKnight); bmpWKnight.Assign(imgBBishop); bmpWKnight.Assign(imgBRook); bmpWKnight.Assign(imgBQueen); bmpWKnight.Assign(imgBKing); } end; procedure TChessDrawer.SetDelegate(ADelegate: TChessDrawerDelegate); begin FDelegate := ADelegate; end; procedure TChessDrawer.HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseMove(Sender, Shift, X, Y); end; procedure TChessDrawer.HandleMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseUp(Sender, Button, Shift, X, Y); end; procedure TChessDrawer.HandleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseDown(Sender, Button, Shift, X, Y); end; procedure TChessDrawer.HandleOnTimer(Sender: TObject); begin if FDrawerState = dsRunningAnimation then begin Inc(FAnimation.CurrentStep); if FAnimation.CurrentStep >= FAnimation.FinalStep then begin FAnimation.ExecuteFinal; FAnimation.Free; FAnimation := nil; FDrawerState := dsIdle; end; Invalidate(); end; end; procedure TChessDrawer.AddAnimation(AAnimation: TChessAnimation); begin FDrawerState := dsRunningAnimation; FAnimation := AAnimation; end; end.
unit RDOVariantUtils; interface const varPointer = $201; type TMarshalPtr = packed record ptr : pointer; size : integer; end; procedure MarshalReturnPtr(buffer : pointer; size : integer; var v : variant); function MarshalPtr(buffer : pointer; size : integer) : variant; function UnMarshalPtr(const v : variant) : pointer; function GetMarshalPtr(const v : variant) : TMarshalPtr; function IsVarParam(const v : variant) : boolean; function IsPtrParam(const v : variant) : boolean; implementation procedure MarshalReturnPtr(buffer : pointer; size : integer; var v : variant); var aux : double; begin TVarData(v).vType := varPointer; TMarshalPtr(aux).ptr := buffer; TMarshalPtr(aux).size := size; TVarData(v).vDouble := aux; end; function MarshalPtr(buffer : pointer; size : integer) : variant; var aux : double; begin TVarData(result).vType := varPointer; TMarshalPtr(aux).ptr := buffer; TMarshalPtr(aux).size := size; TVarData(result).vDouble := aux; end; function UnMarshalPtr(const v : variant) : pointer; begin result := TVarData(v).vPointer; end; function GetMarshalPtr(const v : variant) : TMarshalPtr; begin result := TMarshalPtr(TVarData(v).vDouble); end; function IsVarParam(const v : variant) : boolean; var aux : PVariant; begin if TVarData(v).VType and varTypeMask = varVariant then begin aux := TVarData(v).vPointer; result := (aux = nil) or (TVarData(aux^).VType <> varPointer); end else result := false; end; function IsPtrParam(const v : variant) : boolean; var aux : PVariant; begin if TVarData(v).VType and varTypeMask = varVariant then begin aux := TVarData(v).vPointer; result := (aux <> nil) or (TVarData(aux^).VType = varPointer); end else result := false; end; end.
unit UAStarSearch; //Fully annotated interface uses UListHandlerNodes, UListHandler, UMazeHandler, UInterface, SysUtils; type TState = record WasOutside, Open: boolean; Position: TCoord; end; TNodeStates = Array of TState; function FindSolution(Maze: TMazeHandler): TRoute; procedure MoveNode(x, y: integer; fromThis, toThis: TListHandlerNodes); function FindPossibleParents(x, y: integer; OutsideList, OpenList, ClosedList: TListHandlerNodes; Maze: TMazeHandler; var PossibleParentsLength: integer): TNodeStates; procedure CalculateGValues(currentX, currentY: integer; PossibleParents: TNodeStates; PossibleParentsLength: integer; OutsideList, OpenList, ClosedList: TListHandlerNodes); procedure PickNextNode(var currentX, currentY: integer; OpenList, ClosedList: TListHandlerNodes); implementation // Moves a node from one list to another procedure MoveNode(x, y: integer; fromThis, toThis: TListHandlerNodes); var tempNode: TNode; begin tempNode := fromThis.RemoveNode(x, y); // If it could remove the node from the list it is being moved from, then add // it to the list it is being moved if tempNode.Position.x <> -1 then toThis.AddNode(tempNode); end; // Finds the possible parents in the OpenList and OutsideList function FindPossibleParents(x, y: integer; OutsideList, OpenList, ClosedList: TListHandlerNodes; Maze: TMazeHandler; var PossibleParentsLength: integer): TNodeStates; var ItemsToFind: TwoDArray; ItemsToFindLength, index, Position: integer; begin // Finds the positions of the nodes which are adjacent to the square whose // parents are being found setLength(ItemsToFind, 4, 2); UInterface.ReturnItemsToFind(x, y, Maze.GetLastIndex, ItemsToFind, ItemsToFindLength); // Initialises the list where the positions will be stored setLength(result, ItemsToFindLength); PossibleParentsLength := 0; for index := 0 to (ItemsToFindLength - 1) do begin // If the adjacent node is in the OpenList if (OpenList.GetIndex(ItemsToFind[index, 0], ItemsToFind[index, 1]) <> -1) then begin // Sets the adjacent nodes position result[PossibleParentsLength].Position.x := ItemsToFind[index, 0]; result[PossibleParentsLength].Position.y := ItemsToFind[index, 1]; // Marks that it wasn't in the OutsideList result[PossibleParentsLength].WasOutside := false; // Marks that it was in the OpenList result[PossibleParentsLength].Open := true; // Increments the actual list length so that the next parent does not // overwrite the current one inc(PossibleParentsLength); end // Else if the adjacent node is in the OutsideList else if (OutsideList.GetIndex(ItemsToFind[index, 0], ItemsToFind[index, 1]) <> -1) then begin result[PossibleParentsLength].Position.x := ItemsToFind[index, 0]; result[PossibleParentsLength].Position.y := ItemsToFind[index, 1]; result[PossibleParentsLength].WasOutside := true; result[PossibleParentsLength].Open := false; //Move the node from the OutSide list into the Open list MoveNode(result[PossibleParentsLength].Position.x, result[PossibleParentsLength].Position.y, OutsideList, OpenList); inc(PossibleParentsLength); end; end; end; // Determines the G-values and whether the current node should be made the // parent of each adjacent node or not procedure CalculateGValues(currentX, currentY: integer; PossibleParents: TNodeStates; PossibleParentsLength: integer; OutsideList, OpenList, ClosedList: TListHandlerNodes); var index, tempGValue, oldGValue, checkedX, checkedY: integer; begin // Finds the G-value to move to the adjacent node from the considered node tempGValue := ClosedList.GetGValue(currentX, currentY) + 1; // Loop through each adjacent node for index := 0 to PossibleParentsLength - 1 do begin // Gets the position of a possible parent being considered checkedX := PossibleParents[index].Position.x; checkedY := PossibleParents[index].Position.y; // If its in the open list if PossibleParents[index].Open then begin oldGValue := OpenList.GetGValue(checkedX, checkedY); // If the g value to reach it from the considered node is greater than // its current g value, make its parent the considered node if tempGValue < oldGValue then begin OpenList.SetParent(checkedX, checkedY, currentX, currentY, tempGValue); end; end // If it was in the outside list else if PossibleParents[index].WasOutside then begin // Make the considered node a parent of the adjacent node OpenList.SetParent(checkedX, checkedY, currentX, currentY, tempGValue); end; end; end; // Picks the next node to be the considered node procedure PickNextNode(var currentX, currentY: integer; OpenList, ClosedList: TListHandlerNodes); var index, HValue: integer; begin // Finds the node with the lowest f value, and makes it the considered node OpenList.GetPositionOfLowestFValue(currentX, currentY); // Moves the considered node to the closed list MoveNode(currentX, currentY, OpenList, ClosedList); end; // Caries out the A* Search function FindSolution(Maze: TMazeHandler): TRoute; var OpenList, ClosedList, OutsideList: TListHandlerNodes; index, targetX, targetY, currentX, currentY, checkedX, checkedY, PossibleParentsLength: integer; parentNotFound: boolean; PossibleParents: TNodeStates; begin // Initialises the lists OutsideList := TListHandlerNodes.Create(Maze, true); OpenList := TListHandlerNodes.Create(Maze, false); ClosedList := TListHandlerNodes.Create(Maze, false); // Carries out step 2 of the algorithm MoveNode(Maze.GetStartX, Maze.GetStartY, OutsideList, ClosedList); targetX := Maze.GetEndX; targetY := Maze.GetEndY; currentX := Maze.GetStartX; currentY := Maze.GetStartY; parentNotFound := true; // While the target node is not next to the considered cell while parentNotFound do begin // Carries out step 3 of the algorithm PossibleParents := FindPossibleParents(currentX, currentY, OutsideList, OpenList, ClosedList, Maze, PossibleParentsLength); index := 0; // Checks that the target node is not adjacent to the node being considered while (index < PossibleParentsLength) and (parentNotFound) do begin checkedX := PossibleParents[index].Position.x; checkedY := PossibleParents[index].Position.y; if (checkedX = targetX) and (checkedY = targetY) then begin parentNotFound := false; end; inc(index); end; // If the considered node is not next to the target node, and it has 1 or // more possible parent if (parentNotFound) and (PossibleParentsLength > 0) then begin CalculateGValues(currentX, currentY, PossibleParents, PossibleParentsLength, OutsideList, OpenList, ClosedList); PickNextNode(currentX, currentY, OpenList, ClosedList); end // Else if the target node is adjacent to the current node else if parentNotFound = false then begin // Move it to the Closed list MoveNode(checkedX, checkedY, OpenList, ClosedList); // Make it a parent of the current node ClosedList.SetParent(checkedX, checkedY, currentX, currentY, ClosedList.GetGValue(currentX, currentY) + 1); end // Else if the considered node does not have any possible parents, remove // it from consideration and pick another node to be considered else if PossibleParentsLength = 0 then begin ClosedList.RemoveNode(currentX, currentY); PickNextNode(currentX, currentY, OpenList, ClosedList); end; end; // Returns the ordered route as result ClosedList.GetRoute(result, targetX, targetY); // Destroys the classes FreeAndNil(ClosedList); FreeAndNil(OpenList); FreeAndNil(OutsideList); end; end.
unit Unit32; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMensagemEvent = procedure(const msg:string) of object; TForm32 = class(TForm) Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormResize(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Memo1KeyPress(Sender: TObject; var Key: Char); private FConnection: TObject; FOnMensagem: TMensagemEvent; procedure SetConnection(const Value: TObject); procedure SetOnMensagem(const Value: TMensagemEvent); { Private declarations } public { Public declarations } property Connection:TObject read FConnection write SetConnection; property OnMensagem: TMensagemEvent read FOnMensagem write SetOnMensagem; end; {var Form32: TForm32; } implementation {$R *.dfm} procedure TForm32.Button1Click(Sender: TObject); begin FOnMensagem('click'); end; procedure TForm32.FormCreate(Sender: TObject); begin // FOnMensagem('onFormCreate'); end; procedure TForm32.FormResize(Sender: TObject); begin caption := self.Width.ToString; end; procedure TForm32.FormShow(Sender: TObject); begin if not assigned(FConnection) then FOnMensagem('esqueceu de inicializar a conex„o'); FOnMensagem('onShow: '+FConnection.ClassName); end; procedure TForm32.Memo1KeyPress(Sender: TObject; var Key: Char); begin FOnMensagem(key); end; procedure TForm32.SetConnection(const Value: TObject); begin FConnection := Value; end; procedure TForm32.SetOnMensagem(const Value: TMensagemEvent); begin FOnMensagem := Value; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998 Alex Shovkoplyas } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElBaseComp; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, {$ifdef VCL_6_USED} Types, {$endif} ElTools; type EBaseEnabledFailed = class(Exception) end; TElBaseComponent = class(TComponent) protected FHandle : THandle; FEnabled : boolean; FDesignActive : boolean; procedure WMQueryEndSession(var Message : TMessage); message WM_QUERYENDSESSION; procedure WndProc(var Message : TMessage); virtual; procedure SetEnabled(AEnabled : boolean); virtual; procedure DoSetEnabled(AEnabled : boolean); virtual; procedure Loaded; override; //procedure WMDestroy(var Message: TMessage); message WM_DESTROY; property Handle : THandle read FHandle; public property Enabled : boolean read FEnabled write SetEnabled default false; constructor Create(AOwner : TComponent); override; destructor Destroy; override; end; implementation { TElBaseComponent } // var WindowAtom : TAtom; constructor TElBaseComponent.Create(AOwner : TComponent); begin inherited Create(AOwner); FHandle := 0; FEnabled := false; end; destructor TElBaseComponent.Destroy; begin Enabled := false; inherited Destroy; end; procedure TElBaseComponent.Loaded; begin inherited; if Enabled then begin FEnabled := false; SetEnabled(true); end; end; procedure TElBaseComponent.WndProc(var Message : TMessage); begin if Message.Msg = WM_QUERYENDSESSION then Message.Result := 1 else try Dispatch(Message); except Application.HandleException(Self); end; end; procedure TElBaseComponent.WMQueryEndSession(var Message : TMessage); begin try Enabled := false; except; end; inherited; Message.Result := integer(true); end; procedure TElBaseComponent.SetEnabled(AEnabled : boolean); begin try if (FDesignActive or (not (csDesigning in ComponentState))) and (not (csLoading in ComponentState)) and (AEnabled <> FEnabled) then DoSetEnabled(AEnabled); FEnabled := AEnabled; except raise; end; end; procedure TElBaseComponent.DoSetEnabled(AEnabled : boolean); begin if AEnabled then {$warnings off} begin FHandle := AllocateHwnd(WndProc); //SetProp(FHandle, MakeIntAtom(WindowAtom), THandle(Self)); end else begin if FHandle <> 0 then DeallocateHwnd(FHandle); {$warnings on} FHandle := 0; end; end; {procedure TElBaseComponent.WMDestroy(var Message: TMessage); begin inherited; // RemoveProp(FHandle, MakeIntAtom(WindowAtom)); end; var AtomText: array[0..31] of Char; initialization WindowAtom := GlobalAddAtom(StrFmt(AtomText, 'Delphi%.8X', [GetCurrentProcessID])); finalization GlobalDeleteAtom(WindowAtom); {} end.
unit tdDataExport; interface uses System.Classes, System.SysUtils, System.SyncObjs, Winapi.Windows, System.Win.ComObj, Winapi.ActiveX, System.IOUtils, System.Variants, Data.DB, Data.Win.ADODB, ActiveDs_TLB, Vcl.Imaging.jpeg, ADC.Types, ADC.AD, ADC.LDAP, ADC.ADObject, System.TypInfo, System.AnsiStrings, ADC.ADObjectList, ADC.Attributes, ADC.ExcelEnum, ADC.Common, ADOX_TLB, ADC.Elevation, ADC.ImgProcessor; const DB_PROVIDER_JET = 'Microsoft.Jet.OLEDB.4.0'; DB_PROVIDER_ACE120 = 'Microsoft.ACE.OLEDB.12.0'; type TADCExporter = class(TThread) private FOwner: HWND; FAPI: Integer; FLDAP: PLDAP; FRootDSE: IADs; FSrc: TADObjectList<TADObject>; FAttrCat: TAttrCatalog; FFormat: TADCExportFormat; FFileName: TFileName; FSyncObject: TCriticalSection; FProgressProc: TProgressProc; FExceptionProc: TExceptionProc; FDBConnectionString: string; FObj: TADObject; FProgressValue: Integer; FExceptionCode: ULONG; FExceptionMsg: string; FCancelFlag: TSimpleEvent; FPauseFlag: TSimpleEvent; FWaitList: array of THandle; procedure Initialize(AOwner: HWND; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc); procedure Clear; function GenerateFileName(AFileName: TFileName): TFileName; procedure SetPaused(APaused: Boolean); function GetPaused: Boolean; procedure SyncProgress; procedure SyncException; procedure DoProgress(AProgress: Integer); procedure DoException(AMsg: string; ACode: ULONG); procedure DoDataExport_Access; procedure DoDataExport_Excel; protected procedure Execute; override; public constructor Create(AOwner: HWND; ARootDSE: IADs; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; overload; constructor Create(AOwner: HWND; ALDAP: PLDAP; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; overload; property OnException: TExceptionProc read FExceptionProc write FExceptionProc; property OnProgress: TProgressProc read FProgressProc write FProgressProc; property Paused: Boolean read GetPaused write SetPaused; end; implementation { TADExporter } constructor TADCExporter.Create(AOwner: HWND; ARootDSE: IADs; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); begin inherited Create(CreateSuspended); if (ARootDSE = nil) or (ASourceList = nil) then Self.Terminate; Initialize( AOwner, ASourceList, AAttrCatalog, AFormat, AFileName, ASyncObject, AProgressProc, AExceptionProc ); FAPI := ADC_API_ADSI; FRootDSE := ARootDSE; end; function TADCExporter.GenerateFileName(AFileName: TFileName): TFileName; var res: string; SaveAsName: string; SaveAsExt: string; SaveAsCount: Integer; fHandle: THandle; begin res := AFileName; if FileExists(res) then begin SaveAsExt := ExtractFileExt(AFileName); SaveAsName := Copy(AFileName, 1, Length(AFileName) - Length(SaveAsExt)); SaveAsCount := 1; repeat res := SaveAsName + ' (' + IntToStr(SaveAsCount) + ')' + SaveAsExt; Inc(SaveAsCount); until not FileExists(res); end; Result := res; // { Проверяем, можно ли создать файл } // fHandle := CreateFile( // PChar(res), // GENERIC_READ or GENERIC_WRITE, // 0, // nil, // CREATE_NEW, // FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, // 0 // ); // // if fHandle = INVALID_HANDLE_VALUE // then Result := '' // else Result := res; // // { В CreateFile используем флаг FILE_FLAG_DELETE_ON_CLOSE, поэтому } // { после вызова CloseHandle файл должен автоматически удалиться. Но } // { на всякий случай вызываем DeleteFile, чтобы на верняка... ;) } // CloseHandle(fHandle); // DeleteFile(PChar(res)); end; function TADCExporter.GetPaused: Boolean; begin Result := (FPauseFlag.WaitFor(0) <> wrSignaled); end; procedure TADCExporter.Initialize(AOwner: HWND; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc); var a: PADAttribute; begin FOwner := AOwner; FAPI := -1; FLDAP := nil; FRootDSE := nil; FSrc := ASourceList; FAttrCat := TAttrCatalog.Create(False); FFormat := AFormat; FFileName := GenerateFileName(AFileName); FSyncObject := ASyncObject; FProgressProc := AProgressProc; FExceptionProc := AExceptionProc; FObj := nil; FProgressValue := 0; FExceptionCode := 0; FExceptionMsg := ''; FPauseFlag := TSimpleEvent.Create; FPauseFlag.SetEvent; FCancelFlag := TSimpleEvent.Create; FCancelFlag.ResetEvent; SetLength(FWaitList, 2); FWaitList[0] := FPauseFlag.Handle; FWaitList[1] := FCancelFlag.Handle; case FFormat of efAccess: FDBConnectionString := Format('Provider=%s;Data Source=%s;', [DB_PROVIDER_JET, FFileName]); efAccess2007: FDBConnectionString := Format('Provider=%s;Data Source=%s;', [DB_PROVIDER_ACE120, FFileName]); else FDBConnectionString := ''; end; // Экспортируем только отображаемые поля, а также не экспортируем поле, // содержащее изображение пользователя т.к. лень было заморачиваться. // Да и по предыдущему опыту (реализовывал в ADUserInfo) знаю, что // если экспортировать изобрежения, то это занимает очень много времени for a in AAttrCatalog do if (a^.IsExportRequired) or ((a^.Visible) and (not a^.IsNotExported)) then FAttrCat.Add(a); end; procedure TADCExporter.Clear; begin FAPI := -1; FLDAP := nil; FRootDSE := nil; FSrc := nil; FFormat := efNone; FFileName := ''; FProgressProc := nil; FExceptionProc := nil; FAttrCat.Free; FCancelFlag.Free; FPauseFlag.Free; CoUninitialize; if FSyncObject <> nil then begin FSyncObject.Leave; FSyncObject := nil; end; end; constructor TADCExporter.Create(AOwner: HWND; ALDAP: PLDAP; ASourceList: TADObjectList<TADObject>; AAttrCatalog: TAttrCatalog; AFormat: TADCExportFormat; AFileName: TFileName; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); begin inherited Create(CreateSuspended); if (ALDAP = nil) or (ASourceList = nil) then Self.Terminate; Initialize( AOwner, ASourceList, AAttrCatalog, AFormat, AFileName, ASyncObject, AProgressProc, AExceptionProc ); FAPI := ADC_API_LDAP; FLDAP := ALDAP; end; procedure TADCExporter.DoException(AMsg: string; ACode: ULONG); begin FExceptionCode := ACode; FExceptionMsg := AMsg; Synchronize(SyncException); end; procedure TADCExporter.DoProgress(AProgress: Integer); begin FProgressValue := AProgress; Synchronize(SyncProgress); end; procedure TADCExporter.Execute; begin CoInitialize(nil); if FSyncObject <> nil then if not FSyncObject.TryEnter then begin FSyncObject := nil; Self.OnTerminate := nil; Self.Terminate; end; if Terminated then begin Clear; Exit; end; try case FFormat of efAccess..efAccess2007: begin DoDataExport_Access; end; efExcel..efExcel2007: begin DoDataExport_Excel; end; efCommaSeparated: begin DoDataExport_Excel; end; end; except on E: Exception do begin DoException(E.Message, 0); end; end; if Terminated then DeleteFile(PChar(FFileName)); Clear; end; procedure TADCExporter.DoDataExport_Access; var oCatalog: Catalog; oConnection: OleVariant; sTableName: string; sFieldValues: string; sValue: string; a: PADAttribute; i: Integer; j: Integer; o: TADObject; thumbnailPhoto: TImgByteArray; lstMembers: TADGroupMemberList; begin lstMembers := TADGroupMemberList.Create; oCatalog := CreateAccessDatabase( FOwner, PChar(FDBConnectionString), FAttrCat.AsIStream, IsCreateFileElevationRequired(ExtractFileDir(FFileName)) ) as Catalog; if oCatalog = nil then begin Self.Terminate; Exit; end; oConnection := oCatalog.Get_ActiveConnection; i := 0; for o in FSrc do begin if Terminated then begin FPauseFlag.ResetEvent; FCancelFlag.SetEvent; end; case WaitForMultipleObjects(2, @FWaitList[0], False, INFINITE) - WAIT_OBJECT_0 of 0: if Terminated then Break; 1: Break; end; FObj := o; // Определяем имя таблицы для вывода значений if o.IsUser then sTableName := EXPORT_TABNAME_USERS else if o.IsGroup then sTableName := EXPORT_TABNAME_GROUPS else sTableName := EXPORT_TABNAME_WORKSTATIONS; // Формируем строку заначений j := 0; for a in FAttrCat do begin Inc(j); case IndexText(a^.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'primaryGroupToken', { 5 } 'thumbnailPhoto' { 6 } ] ) of 0: if o.lastLogon > 0 then sValue := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', o.lastLogon)) else sValue := 'Null'; 1: if o.passwordExpiration > 0 then sValue := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', o.passwordExpiration)) else sValue := 'Null'; 2: sValue := QuotedStr(IntToStr(o.badPwdCount)); 3: sValue := QuotedStr(IntToStr(o.groupType)); 4: sValue := QuotedStr(IntToStr(o.userAccountControl)); 5: sValue := QuotedStr(IntToStr(o.primaryGroupToken)); 6: sValue := 'Null' // 6: if o.thumbnailFileSize = 0 then sValue := 'Null' else // begin // TImgProcessor.ImageToByteArray(o.thumbnailPhoto, @thumbnailPhoto); // sValue := '0x' + thumbnailPhoto.AsBinString; // <- Не работает // SetLength(thumbnailPhoto, 0); // end else if CompareText('nearestEvent', a^.ObjProperty) <> 0 then sValue := QuotedStr(GetPropValue(o, a^.ObjProperty, True)) else if o.nearestEvent > 0 then sValue := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', o.nearestEvent)) else sValue := 'Null'; end; if j = 1 then sFieldValues := Format('%s', [sValue]) else sFieldValues := sFieldValues + Format(',%s', [sValue]); end; // Вставялем запись в таблицу oConnection.Execute( Format('INSERT INTO %s VALUES (%s)', [sTableName, sFieldValues]) ); // // Заполняем таблицу членства в группах безопасности // if o.IsGroup then // begin // case FAPI of // ADC_API_LDAP: o.GetGroupMembers(FLDAP, lstMembers); // ADC_API_ADSI: o.GetGroupMembers(lstMembers); // end; // // for j := 0 to lstMembers.Count - 1 do // begin // sFieldValues := QuotedStr(o.distinguishedName) + ',' + QuotedStr(lstMembers[j].distinguishedName); // oConnection.Execute( // Format('INSERT INTO %s VALUES (%s)', ['Membership', sFieldValues]) // ); // end; // end; i := i + 1; DoProgress(Trunc(i * 100 / FSrc.Count)); end; oConnection := Unassigned; oCatalog := nil; lstMembers.Free; end; procedure TADCExporter.DoDataExport_Excel; var oExcelBook: Variant; oSheet: Variant; oColumns: Variant; oRows: Variant; oCell: Variant; o: TADObject; a: PADAttribute; idxUser: Integer; idxGroup: Integer; idxWorkstation: Integer; iRow: PInteger; iColumn: Integer; i: Integer; s: string; begin oExcelBook := CreateExcelBook( FOwner, FAttrCat.AsIStream, False ); i := 0; idxUser := 2; idxGroup := 2; idxWorkstation := 2; for o in FSrc do begin if Terminated then begin FPauseFlag.ResetEvent; FCancelFlag.SetEvent; end; case WaitForMultipleObjects(2, @FWaitList[0], False, INFINITE) - WAIT_OBJECT_0 of 0: if Terminated then Break; 1: Break; end; FObj := o; // Определяем лист и счетчик строк для вывода значений if o.IsUser then begin iRow := @idxUser; oSheet := oExcelBook.Workbooks[1].Worksheets[EXPORT_TABNAME_USERS] end else if o.IsGroup then begin iRow := @idxGroup; oSheet := oExcelBook.Workbooks[1].Worksheets[EXPORT_TABNAME_GROUPS] end else begin iRow := @idxWorkstation; oSheet := oExcelBook.Workbooks[1].Worksheets[EXPORT_TABNAME_WORKSTATIONS]; end; // Формируем строку заначений iColumn := 1; for a in FAttrCat do begin case IndexText(a^.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'primaryGroupToken', { 5 } 'thumbnailPhoto' { 6 } ] ) of 0: if o.lastLogon > 0 then oSheet.Cells[iRow^, iColumn] := DateTimeToStr(o.lastLogon); 1: if o.passwordExpiration > 0 then oSheet.Cells[iRow^, iColumn] := DateTimeToStr(o.passwordExpiration); 2: oSheet.Cells[iRow^, iColumn] := IntToStr(o.badPwdCount); 3: oSheet.Cells[iRow^, iColumn] := IntToStr(o.groupType); 4: oSheet.Cells[iRow^, iColumn] := IntToStr(o.userAccountControl); 5: oSheet.Cells[iRow^, iColumn] := IntToStr(o.primaryGroupToken); 6: oSheet.Cells[iRow^, iColumn] := o.thumbnailFileSize.AsString; else if CompareText('nearestEvent', a^.ObjProperty) <> 0 then oSheet.Cells[iRow^, iColumn] := string(GetPropValue(o, a^.ObjProperty, True)) else if o.nearestEvent > 0 then oSheet.Cells[iRow^, iColumn] := DateToStr(o.nearestEvent); end; s := a^.ExcelCellFormat(oExcelBook); Inc(iColumn); end; Inc(iRow^); Inc(i); DoProgress(Trunc(i * 100 / FSrc.Count)); end; SaveExcelBook( FOwner, oExcelBook, PChar(FFileName), ShortInt(FFormat), IsCreateFileElevationRequired(ExtractFileDir(FFileName)) ); oExcelBook := Null; end; procedure TADCExporter.SetPaused(APaused: Boolean); begin if APaused then FPauseFlag.ResetEvent else FPauseFlag.SetEvent; end; procedure TADCExporter.SyncException; begin if Assigned(FExceptionProc) then FExceptionProc(FExceptionMsg, FExceptionCode); end; procedure TADCExporter.SyncProgress; begin if Assigned(FProgressProc) then FProgressProc(FObj, FProgressValue); end; end.
unit uConsulta; interface uses Vcl.Forms, System.SysUtils, FireDAC.Comp.Client; function ultimoCodigo(conexao: TFDConnection; tabela, campo: string; condicao: string = ''): string; function buscarDado(conexao: TFDConnection; tabela: string; campoChave: string; campoDesejado: string; value: string; condicao: string = ''): string; function CreateQuery(sql:string):TFDQuery; overload; function CreateQuery(sql:string; conexao:TFDConnection):TFDQuery; overload; implementation uses uConstantes; function ultimoCodigo(conexao: TFDConnection; tabela, campo: string; condicao: string = ''): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT ' + #13 + ' MAX(U.' + campo + ') AS "ULTIMO" ' + #13 + 'FROM ' + tabela + ' U '; if condicao <> '' then strSQLConsulta := strSQLConsulta + ' WHERE ' + condicao; dsConsulta := TFDQuery.Create(Application); // dmPrincipal.frmDmPrincipal.FDConnexao dsConsulta.Connection := conexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try if dsConsulta.FieldByName('ULTIMO').IsNull then Result := '0' else Result := dsConsulta.FieldByName('ULTIMO').AsString; finally FreeAndNil(dsConsulta) end; end; function buscarDado(conexao: TFDConnection; tabela: string; campoChave: string; campoDesejado: string; value: string; condicao: string = ''): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin if value = '' then Exit; strSQLConsulta := 'SELECT ' + #13 + campoDesejado + #13 + ' FROM ' + tabela + ' U ' + #13 + ' WHERE U.' + campoChave + ' = ' + QuotedStr(value); if condicao <> '' then strSQLConsulta := strSQLConsulta + ' AND ' + condicao; dsConsulta := TFDQuery.Create(Application); dsConsulta.Connection := conexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName(campoDesejado).AsString; finally FreeAndNil(dsConsulta) end; end; function CreateQuery(sql:string):TFDQuery; begin try Result := CreateQuery(sql, conexaoSistema); except end; end; function CreateQuery(sql:string; conexao:TFDConnection):TFDQuery; begin Result := TFDQuery.Create(Application); try Result.Connection := conexao; Result.SQL.Text := sql; Result.Active := True; except end; end; end.
unit uCustomerInvoice; interface uses uModel, uPenjualan, System.Generics.Collections, uAR, System.SysUtils, uSupplier; type {$TYPEINFO ON} TCustomerInvoicePenjualan = class; TCustomerInvoicePenjualanItem = class; TCustomerInvoice = class(TAppObject) {$TYPEINFO OFF} private FAR: TAR; FCabang: TCabang; FCustomer: TSupplier; FCustomerInvoicePenjualans: tobjectlist<TCustomerInvoicePenjualan>; FJatuhTempo: TDatetime; FKeterangan: string; FNoBukti: string; FNominal: Double; FTglBukti: TDatetime; function GetCustomerInvoicePenjualans: tobjectlist<TCustomerInvoicePenjualan>; function GetNominal: Double; public destructor Destroy; override; property Nominal: Double read GetNominal write FNominal; published property AR: TAR read FAR write FAR; property Cabang: TCabang read FCabang write FCabang; property Customer: TSupplier read FCustomer write FCustomer; property CustomerInvoicePenjualans: tobjectlist<TCustomerInvoicePenjualan> read GetCustomerInvoicePenjualans write FCustomerInvoicePenjualans; property JatuhTempo: TDatetime read FJatuhTempo write FJatuhTempo; property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property TglBukti: TDatetime read FTglBukti write FTglBukti; end; TCustomerInvoicePenjualan = class(TAppObjectItem) private FCustomerInvoice: TCustomerInvoice; FCustomerInvoicePenjualanItems: tobjectlist<TCustomerInvoicePenjualanItem>; FPenjualan: TPenjualan; function GetCustomerInvoicePenjualanItems: tobjectlist<TCustomerInvoicePenjualanItem>; public destructor Destroy; override; function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; published property CustomerInvoice: TCustomerInvoice read FCustomerInvoice write FCustomerInvoice; property CustomerInvoicePenjualanItems: tobjectlist<TCustomerInvoicePenjualanItem> read GetCustomerInvoicePenjualanItems write FCustomerInvoicePenjualanItems; property Penjualan: TPenjualan read FPenjualan write FPenjualan; end; TCustomerInvoicePenjualanItem = class(TAppObjectItem) private FBarang: TBarang; FBarangSatuangItemID: string; FCustomerInvoicePenjualan: TCustomerInvoicePenjualan; FDiskon: Double; FHarga: Double; FJenisHarga: string; FKonversi: Double; FPPN: Double; FQty: Double; FUOM: TUOM; function GetHargaSetelahDiskon: Double; public destructor Destroy; override; function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; property BarangSatuangItemID: string read FBarangSatuangItemID write FBarangSatuangItemID; property HargaSetelahDiskon: Double read GetHargaSetelahDiskon; published property Barang: TBarang read FBarang write FBarang; property CustomerInvoicePenjualan: TCustomerInvoicePenjualan read FCustomerInvoicePenjualan write FCustomerInvoicePenjualan; property Diskon: Double read FDiskon write FDiskon; property Harga: Double read FHarga write FHarga; property JenisHarga: string read FJenisHarga write FJenisHarga; property Konversi: Double read FKonversi write FKonversi; property PPN: Double read FPPN write FPPN; property Qty: Double read FQty write FQty; property UOM: TUOM read FUOM write FUOM; end; implementation destructor TCustomerInvoicePenjualanItem.Destroy; begin inherited; FreeAndNil(FBarang); FreeAndNil(FUOM); end; function TCustomerInvoicePenjualanItem.GetHargaSetelahDiskon: Double; begin Result := Harga * (100 - Diskon) / 100; end; function TCustomerInvoicePenjualanItem.GetHeaderField: string; begin Result := 'CustomerInvoicePenjualan'; end; procedure TCustomerInvoicePenjualanItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.CustomerInvoicePenjualan := TCustomerInvoicePenjualan(AHeaderProperty); end; destructor TCustomerInvoice.Destroy; var I: Integer; begin inherited; FreeAndNil(FCabang); for I := 0 to CustomerInvoicePenjualans.Count - 1 do begin CustomerInvoicePenjualans[i].Free; end; CustomerInvoicePenjualans.Free; FreeAndNil(FAR); end; function TCustomerInvoice.GetCustomerInvoicePenjualans: tobjectlist<TCustomerInvoicePenjualan>; begin if FCustomerInvoicePenjualans = nil then FCustomerInvoicePenjualans := TObjectList<TCustomerInvoicePenjualan>.Create(False); Result := FCustomerInvoicePenjualans; end; function TCustomerInvoice.GetNominal: Double; var i: Integer; j: Integer; begin FNominal := 0; for i := 0 to CustomerInvoicePenjualans.Count - 1 do begin for j := 0 to CustomerInvoicePenjualans[i].CustomerInvoicePenjualanItems.Count - 1 do begin FNominal := FNominal + (CustomerInvoicePenjualans[i].CustomerInvoicePenjualanItems[j].GetHargaSetelahDiskon * CustomerInvoicePenjualans[i].CustomerInvoicePenjualanItems[j].Qty * (100 + CustomerInvoicePenjualans[i].CustomerInvoicePenjualanItems[j].PPN) / 100); end; end; Result := FNominal; end; destructor TCustomerInvoicePenjualan.Destroy; var i: Integer; begin inherited; for i := 0 to CustomerInvoicePenjualanItems.Count - 1 do begin CustomerInvoicePenjualanItems[i].Free; end; FreeAndNil(FCustomerInvoicePenjualanItems); end; function TCustomerInvoicePenjualan.GetCustomerInvoicePenjualanItems: tobjectlist<TCustomerInvoicePenjualanItem>; begin if FCustomerInvoicePenjualanItems = nil then FCustomerInvoicePenjualanItems := TObjectList<TCustomerInvoicePenjualanItem>.Create(False); Result := FCustomerInvoicePenjualanItems; end; function TCustomerInvoicePenjualan.GetHeaderField: string; begin Result := 'CustomerInvoice'; end; procedure TCustomerInvoicePenjualan.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.CustomerInvoice := TCustomerInvoice(AHeaderProperty); end; end.
unit ActivityParametersUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit; type TActivityParameters = class(TGenericParameters) private [HttpQueryMember('route_id')] [Nullable] FRouteId: NullableString; [HttpQueryMember('device_id')] [Nullable] FDeviceID: NullableString; [HttpQueryMember('member_id')] [Nullable] FMemberId: NullableInteger; [HttpQueryMember('limit')] [Nullable] FLimit: NullableInteger; [HttpQueryMember('offset')] [Nullable] FOffset: NullableInteger; [HttpQueryMember('start')] [Nullable] FStart: NullableInteger; [HttpQueryMember('end')] [Nullable] FEnd: NullableInteger; public constructor Create; overload; override; constructor Create(Limit, Offset: integer); reintroduce; overload; property RouteId: NullableString read FRouteId write FRouteId; property DeviceID: NullableString read FDeviceID write FDeviceID; property MemberId: NullableInteger read FMemberId write FMemberId; property Limit: NullableInteger read FLimit write FLimit; property Offset: NullableInteger read FOffset write FOffset; property Start: NullableInteger read FStart write FStart; property End_: NullableInteger read FEnd write FEnd; end; implementation { TActivityParameters } constructor TActivityParameters.Create; begin Inherited Create; RouteId := NullableString.Null; DeviceID := NullableString.Null; MemberId := NullableInteger.Null; Limit := NullableInteger.Null; Offset := NullableInteger.Null; Start := NullableInteger.Null; End_ := NullableInteger.Null; end; constructor TActivityParameters.Create(Limit, Offset: integer); begin Create(); FLimit := Limit; FOffset := Offset; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBaseInputStream; {$I ..\..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes; type TBaseInputStream = class abstract(TStream) {$IFDEF DELPHI} private function GetPosition: Int64; inline; procedure SetPosition(const Pos: Int64); inline; procedure SetSize64(const NewSize: Int64); inline; {$ENDIF DELPHI} protected {$IFDEF FPC} function GetPosition: Int64; override; procedure SetPosition(const Pos: Int64); override; procedure SetSize64(const NewSize: Int64); override; {$ENDIF FPC} function GetSize: Int64; override; procedure SetSize(NewSize: LongInt); overload; override; procedure SetSize(const NewSize: Int64); overload; override; function QueryInterface({$IFDEF FPC}constref {$ELSE}const {$ENDIF FPC} IID: TGUID; out Obj): HResult; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF MSWINDOWS}; function _AddRef: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF MSWINDOWS}; function _Release: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF MSWINDOWS}; public function ReadByte: Int32; virtual; function Read(var Buffer; Count: LongInt): LongInt; overload; override; function Write(const Buffer; Count: LongInt): LongInt; overload; override; function Read(Buffer: TCryptoLibByteArray; Offset, Count: LongInt) : LongInt; overload; {$IFDEF SUPPORT_TSTREAM_READ_BYTEARRAY_OVERLOAD} override {$ELSE} virtual {$ENDIF SUPPORT_TSTREAM_READ_BYTEARRAY_OVERLOAD}; function Write(const Buffer: TCryptoLibByteArray; Offset, Count: LongInt) : LongInt; overload; {$IFDEF SUPPORT_TSTREAM_WRITE_BYTEARRAY_OVERLOAD} override {$ELSE} virtual {$ENDIF SUPPORT_TSTREAM_WRITE_BYTEARRAY_OVERLOAD}; function Seek(Offset: LongInt; Origin: Word): LongInt; overload; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; override; {$IFNDEF _FIXINSIGHT_} property Size: Int64 read GetSize write SetSize64; {$ENDIF} property Position: Int64 read GetPosition write SetPosition; end; implementation uses // included here to avoid circular dependency :) ClpStreamSorter; { TBaseInputStream } function TBaseInputStream.GetPosition: Int64; begin raise ENotSupportedCryptoLibException.Create(''); end; function TBaseInputStream.GetSize: Int64; begin raise ENotSupportedCryptoLibException.Create(''); end; function TBaseInputStream.QueryInterface({$IFDEF FPC}constref {$ELSE}const {$ENDIF FPC} IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then result := 0 else result := E_NOINTERFACE; end; {$IFNDEF _FIXINSIGHT_} function TBaseInputStream.Read(var Buffer; Count: LongInt): LongInt; begin raise ENotSupportedCryptoLibException.Create(''); end; function TBaseInputStream.Write(const Buffer; Count: LongInt): LongInt; begin raise ENotSupportedCryptoLibException.Create(''); end; {$ENDIF} function TBaseInputStream.ReadByte: Int32; var Buffer: TCryptoLibByteArray; begin System.SetLength(Buffer, 1); // if (Read(Buffer, 0, 1) = 0) then if (TStreamSorter.Read(Self, Buffer, 0, 1) = 0) then begin result := -1; end else begin result := Int32(Buffer[0]); end; end; function TBaseInputStream.Seek(Offset: LongInt; Origin: Word): LongInt; begin result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; {$IFNDEF _FIXINSIGHT_} function TBaseInputStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin raise ENotSupportedCryptoLibException.Create(''); end; procedure TBaseInputStream.SetPosition(const Pos: Int64); begin raise ENotSupportedCryptoLibException.Create(''); end; {$ENDIF} procedure TBaseInputStream.SetSize(const NewSize: Int64); begin SetSize(LongInt(NewSize)); end; procedure TBaseInputStream.SetSize(NewSize: LongInt); begin raise ENotSupportedCryptoLibException.Create(''); end; procedure TBaseInputStream.SetSize64(const NewSize: Int64); begin SetSize(NewSize); end; function TBaseInputStream.Read(Buffer: TCryptoLibByteArray; Offset, Count: LongInt): LongInt; var &pos, endPoint, b: Int32; begin Pos := Offset; try endPoint := Offset + Count; while (Pos < endPoint) do begin b := ReadByte(); if (b = -1) then begin break; end; Buffer[Pos] := Byte(b); System.Inc(Pos); end; except on e: EIOCryptoLibException do begin if (Pos = Offset) then raise; end; end; result := Pos - Offset; end; {$IFNDEF _FIXINSIGHT_} function TBaseInputStream.Write(const Buffer: TCryptoLibByteArray; Offset, Count: LongInt): LongInt; begin raise ENotSupportedCryptoLibException.Create(''); end; {$ENDIF} function TBaseInputStream._AddRef: Integer; begin result := -1; end; function TBaseInputStream._Release: Integer; begin result := -1; end; end.
{ Wolverine Squish Message base extensions } unit WSquish; interface uses WTypes; implementation const sqFrameId = $AFAE4453; {squish frame types} sqftNormal = 0; sqftFree = 1; sqftLZSS = 2; sqftLocked = 3; {frame is being used by another task} sqmaPrivate = 1; sqmaCrash = 2; sqmaRead = 4; sqmaSent = 8; sqmaFile = 16; {filename is in the subject} sqmaFwd = 32; sqmaOrphan = 64; sqmaKill = 128; sqmaLocal = 256; sqmaHold = 512; sqmaFRq = 2048; {file request... name is in the subject} sqmaRRq = 4096; sqmaCpt = 8192; {return receipt} sqmaARq = 16384; {audit trail} sqmaURq = 32768; {update request... name is in the subject field} sqmaScanned = 65536; sqmaMSGUID = $20000; {uid field is valid in TXMSG} type UMSGID = longint; TSQHdr = record Ofs : longint; UId : UMSGID; Hash : longint; end; TSQMsg = record Attr : longint; {message attributes} From : array[1..36] of char; Too : array[1..36] of char; Subject : array[1..72] of char; Orig : TAddr; Dest : TAddr; DateWritten : TDOSDateTime; DateArrived : TDOSDateTime; UTCOfs : integer; {utc offset} ReplyTo : UMSGID; Replies : array[1..9] of UMSGID; UId : UMSGID; FTSCDate : array[1..20] of char; end; TSQFrame = record Id : longint; NextFrame : longint; {0 if no next} PrevFrame : longint; {0 if no prev} FrameLength : longint; { length of frame } MsgLength : longint; { length of data in frame } CLen : longint; { control information field length } FrameType : word; Reserved : word; end; TSQBase = record Len : word; Reserved1 : word; NumMsg : longint; {number of messages in base} HighMsg : longint; {highest message number (equals to nummsg} SkipMsg : longint; HighWater : longint; {UMSGID of highest scanned mail in echo area} UID : longint; {next uid assigned to the message} Base : array[1..80] of char; {message base name (w/o extension)} BeginFrame : longint; {first frame in message chain} LastFrame : longint; FreeFrame : longint; {first free frame offset} LastFreeFrame : longint; EndFrame : longint; {eof offset} MaxMsg : longint; {maximum number of messages for this area} KeepDays : word; {maximum age of messages in this area} SzSQHdr : word; {size of sqhdr field} Reserved2 : array[1..124] of byte; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Remote Data Module support } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} unit DataBkr; {$T-,H+,X+} interface uses Windows, ActiveX, Classes, Midas, Forms, Provider, SysUtils; type { TRemoteDataModule } TRemoteDataModule = class(TDataModule, IAppServer) private FProviders: TList; FLock: TRTLCriticalSection; protected function GetProvider(const ProviderName: string): TCustomProvider; virtual; class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override; { IAppServer } function AS_GetProviderNames: OleVariant; safecall; function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant; safecall; function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall; function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall; procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params, OwnerData: OleVariant); safecall; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegisterProvider(Value: TCustomProvider); virtual; procedure UnRegisterProvider(Value: TCustomProvider); virtual; procedure Lock; virtual; procedure Unlock; virtual; property Providers[const ProviderName: string]: TCustomProvider read GetProvider; end; { TCRemoteDataModule --- a slimmed down RDM that doesn't implement IAppServer, used in C++Builder. +} type TCRemoteDataModule = class(TDataModule) private FProviders: TList; FLock: TRTLCriticalSection; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegisterProvider(Value: TCustomProvider); virtual; procedure UnRegisterProvider(Value: TCustomProvider); virtual; procedure Lock; virtual; procedure UnLock; virtual; function CRDMGetProviderNames: OleVariant; function GetProvider(const ProviderName: string): TCustomProvider; virtual; property Providers[const ProviderName:string]:TCustomProvider read GetProvider; end; procedure RegisterPooled(const ClassID: string; Max, Timeout: Integer; Singleton: Boolean = False); procedure UnregisterPooled(const ClassID: string); procedure EnableSocketTransport(const ClassID: string); procedure DisableSocketTransport(const ClassID: string); procedure EnableWebTransport(const ClassID: string); procedure DisableWebTransport(const ClassID: string); implementation uses ComObj, MidConst; { Utility routines } procedure RegisterPooled(const ClassID: string; Max, Timeout: Integer; Singleton: Boolean = False); begin { Do not localize } CreateRegKey(SClsid + ClassID, SPooled, SFlagOn); CreateRegKey(SClsid + ClassID, SMaxObjects, IntToStr(Max)); CreateRegKey(SClsid + ClassID, STimeout, IntToStr(Timeout)); if Singleton then CreateRegKey(SClsid + ClassID, SSingleton, SFlagOn) else CreateRegKey(SClsid + ClassID, SSingleton, SFlagOff); end; procedure DeleteRegValue(const Key, ValueName: string); var Handle: HKey; Status: Integer; begin Status := RegOpenKey(HKEY_CLASSES_ROOT, PChar(Key), Handle); if Status = 0 then RegDeleteValue(Handle, PChar(ValueName)); end; procedure UnregisterPooled(const ClassID: string); begin DeleteRegValue(SClsid + ClassID, SPooled); DeleteRegValue(SClsid + ClassID, SMaxObjects); DeleteRegValue(SClsid + ClassID, STimeout); DeleteRegValue(SClsid + ClassID, SSingleton); end; procedure EnableSocketTransport(const ClassID: string); begin CreateRegKey(SClsid + ClassID, SSockets, SFlagOn); end; procedure DisableSocketTransport(const ClassID: string); begin DeleteRegValue(SClsid + ClassID, SSockets); end; procedure EnableWebTransport(const ClassID: string); begin CreateRegKey(SClsid + ClassID, SWeb, SFlagOn); end; procedure DisableWebTransport(const ClassID: string); begin DeleteRegValue(SClsid + ClassID, SWeb); end; function VarArrayFromStrings(Strings: TStrings): Variant; var I: Integer; begin Result := Null; if Strings.Count > 0 then begin Result := VarArrayCreate([0, Strings.Count - 1], varOleStr); for I := 0 to Strings.Count - 1 do Result[I] := WideString(Strings[I]); end; end; { TRemoteDataModule } constructor TRemoteDataModule.Create(AOwner: TComponent); begin InitializeCriticalSection(FLock); FProviders := TList.Create; inherited Create(AOwner); end; destructor TRemoteDataModule.Destroy; begin inherited Destroy; FProviders.Free; DeleteCriticalSection(FLock); end; procedure TRemoteDataModule.Lock; begin EnterCriticalSection(FLock); end; procedure TRemoteDataModule.Unlock; begin LeaveCriticalSection(FLock); end; procedure TRemoteDataModule.RegisterProvider(Value: TCustomProvider); begin FProviders.Add(Value); end; procedure TRemoteDataModule.UnRegisterProvider(Value: TCustomProvider); begin FProviders.Remove(Value); end; function TRemoteDataModule.GetProvider(const ProviderName: string): TCustomProvider; var i: Integer; begin Result := nil; for i := 0 to FProviders.Count - 1 do if AnsiCompareStr(TCustomProvider(FProviders[i]).Name, ProviderName) = 0 then begin Result := TCustomProvider(FProviders[i]); if not Result.Exported then Result := nil; Exit; end; if not Assigned(Result) then raise Exception.CreateResFmt(@SProviderNotExported, [ProviderName]); end; function TRemoteDataModule.AS_GetProviderNames: OleVariant; var List: TStringList; i: Integer; begin Lock; try List := TStringList.Create; try for i := 0 to FProviders.Count - 1 do if TCustomProvider(FProviders[i]).Exported then List.Add(TCustomProvider(FProviders[i]).Name); List.Sort; Result := VarArrayFromStrings(List); finally List.Free; end; finally UnLock; end; end; function TRemoteDataModule.AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; begin Lock; try Result := Providers[ProviderName].ApplyUpdates(Delta, MaxErrors, ErrorCount, OwnerData); finally UnLock; end; end; function TRemoteDataModule.AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant; begin Lock; try Result := Providers[ProviderName].GetRecords(Count, RecsOut, Options, CommandText, Params, OwnerData); finally UnLock; end; end; function TRemoteDataModule.AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; begin Lock; try Result := Providers[ProviderName].RowRequest(Row, RequestType, OwnerData); finally UnLock; end; end; function TRemoteDataModule.AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; begin Lock; try Result := Providers[ProviderName].DataRequest(Data); finally UnLock; end; end; function TRemoteDataModule.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; begin Lock; try Result := Providers[ProviderName].GetParams(OwnerData); finally UnLock; end; end; procedure TRemoteDataModule.AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params, OwnerData: OleVariant); begin Lock; try Providers[ProviderName].Execute(CommandText, Params, OwnerData); finally UnLock; end; end; class procedure TRemoteDataModule.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); var CatReg: ICatRegister; Rslt: HResult; CatInfo: TCATEGORYINFO; Description: string; begin Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil, CLSCTX_INPROC_SERVER, ICatRegister, CatReg); if Succeeded(Rslt) then begin if Register then begin CatInfo.catid := CATID_MIDASAppServer; CatInfo.lcid := $0409; StringToWideChar(MIDAS_CatDesc, CatInfo.szDescription, Length(MIDAS_CatDesc) + 1); OleCheck(CatReg.RegisterCategories(1, @CatInfo)); OleCheck(CatReg.RegisterClassImplCategories(StringToGUID(ClassID), 1, @CATID_MIDASAppServer)); end else begin OleCheck(CatReg.UnRegisterClassImplCategories(StringToGUID(ClassID), 1, @CATID_MIDASAppServer)); DeleteRegKey(Format(SCatImplBaseKey, [ClassID])); end; end else begin if Register then begin CreateRegKey('Component Categories\' + GUIDToString(CATID_MIDASAppServer), '409', MIDAS_CatDesc); CreateRegKey(Format(SCatImplKey, [ClassID, GUIDToString(CATID_MIDASAppServer)]), '', ''); end else begin DeleteRegKey(Format(SCatImplKey, [ClassID, GUIDToString(CATID_MIDASAppServer)])); DeleteRegKey(Format(SCatImplBaseKey, [ClassID])); end; end; if Register then begin Description := GetRegStringValue('CLSID\' + ClassID, ''); CreateRegKey('AppID\' + ClassID, '', Description); CreateRegKey('CLSID\' + ClassID, 'AppID', ClassID); end else DeleteRegKey('AppID\' + ClassID); end; {TCRemoteDataModule} constructor TCRemoteDataModule.Create(AOwner: TComponent); begin InitializeCriticalSection(FLock); FProviders := TList.Create; inherited Create(AOwner); end; destructor TCRemoteDataModule.Destroy; begin inherited Destroy; FProviders.Free; DeleteCriticalSection(FLock); end; procedure TCRemoteDataModule.Lock; begin EnterCriticalSection(FLock); end; procedure TCRemoteDataModule.Unlock; begin LeaveCriticalSection(FLock); end; procedure TCRemoteDataModule.RegisterProvider(Value: TCustomProvider); begin FProviders.Add(Value); end; procedure TCRemoteDataModule.UnRegisterProvider(Value: TCustomProvider); begin FProviders.Remove(Value); end; function TCRemoteDataModule.CRDMGetProviderNames: OleVariant; var List: TStringList; I, J: Integer; begin Lock; try List := TStringList.Create; try for I := 0 to FProviders.Count - 1 do if TCustomProvider(FProviders[I]).Exported then List.Add(TCustomProvider(FProviders[I]).Name); List.Sort; if List.Count > 0 then begin Result := VarArrayCreate([0, List.Count -1], varOleStr); for J := 0 to List.Count -1 do Result[J] := WideString(List[J]); end; finally List.Free; end; finally UnLock; end; end; function TCRemoteDataModule.GetProvider(const ProviderName: string): TCustomProvider; var i: Integer; begin Result := nil; for i := 0 to FProviders.Count - 1 do if AnsiCompareStr(TCustomProvider(FProviders[i]).Name, ProviderName) = 0 then begin Result := TCustomProvider(FProviders[i]); if not Result.Exported then Result := nil; Exit; end; if not Assigned(Result) then raise Exception.CreateResFmt(@SProviderNotExported, [ProviderName]); end; end.
unit NurseStationResourceU; // EMS Resource Module interface uses System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, NurseStationStorageU; type [ResourceName('NurseStation')] TNurseStationResource = class(TDataModule) private FNurseStationStorage : TNurseStationStorage; private procedure PushMessageNurses(const AContext: TEndpointContext; const AStatus : string); procedure PushMessagePatient(const AContext: TEndpointContext; const APatientId : string); procedure CheckAuthorized(const AContext: TEndpointContext); procedure HandleException; procedure CheckNurseStorage; public destructor Destroy; override; published [ResourceSuffix('AddPatient')] procedure PostAddPatientData(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('GetPatient/{item}')] procedure GetPatientData(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('SendMessageNurse/{item}')] procedure PostSendMessageNurse(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('{item}/SendMessagePatient')] procedure PostSendMessagePatient(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; EPatientError = class(Exception); EPatientNotFound = class(EPatientError); implementation uses REST.Backend.EMSApi, REST.Backend.PushTypes; {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} function GetModuleDirectory: string; begin Result := ExtractFilePath(StringReplace(GetModuleName(HInstance),'\\?\','',[rfReplaceAll])); end; procedure TNurseStationResource.CheckNurseStorage; begin if FNurseStationStorage = nil then FNurseStationStorage := TNurseStationStorage.Create(Self, GetModuleDirectory()); end; destructor TNurseStationResource.Destroy; begin FNurseStationStorage.Free; inherited; end; procedure TNurseStationResource.GetPatientData(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LUserId : String; LJson : TJSONObject; begin CheckAuthorized(AContext); CheckNurseStorage(); LUserId := ARequest.Params.Values['item']; try LJson := FNurseStationStorage.GetDataPatient(LUserId); AResponse.Body.SetValue(LJson, True); except HandleException; end; end; procedure TNurseStationResource.CheckAuthorized(const AContext: TEndpointContext); begin if AContext.User = nil then AContext.Response.RaiseUnauthorized('The operation is only permitted for logged in users'); end; procedure TNurseStationResource.PostAddPatientData(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LJsonPatient : TJSONObject; begin CheckAuthorized(AContext); CheckNurseStorage(); try // Receive a JSON with the patient health data. if ARequest.Body.TryGetObject(LJsonPatient) then begin // Add the patient data FNurseStationStorage.AddDataPatient(LJsonPatient); end; except HandleException; end; end; procedure TNurseStationResource.PostSendMessageNurse(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LJSON : TJSONObject; LStatus : string; begin CheckAuthorized(AContext); LStatus := ARequest.Params.Values['item']; try LJSON := TJSONObject.Create(); LJSON.AddPair('return', 'OK'); AResponse.Body.SetValue(LJSON, True); PushMessageNurses(AContext, LStatus); except HandleException; end; end; procedure TNurseStationResource.PostSendMessagePatient(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LJSON : TJSONObject; LPatientId : String; begin CheckAuthorized(AContext); LPatientId := ARequest.Params.Values['item']; try LJSON := TJSONObject.Create(); LJSON.AddPair('return', 'OK'); AResponse.Body.SetValue(LJSON, True); PushMessagePatient(AContext, LPatientId); except HandleException; end; end; procedure TNurseStationResource.PushMessageNurses(const AContext: TEndpointContext; const AStatus : string); var LEMSAPI: TEMSInternalAPI; LData: TJSONObject; LWhere: TJSONObject; LJSON: TJSONObject; // Json Message LJsonMess : TJSONObject; begin // Create in-process EMS API LEMSAPI := TEMSInternalAPI.Create(AContext); LWhere := nil; LJSON := nil; LJsonMess := TJSONObject.Create(); LJSON := TJSONObject.Create(); LData := TJSONObject.Create(); try LJSON.AddPair('data', LData); // Message and Status LJsonMess.AddPair('message', AContext.User.UserID); LJsonMess.AddPair('status', AStatus); // Gcm LData.AddPair('title', 'Reminder'); LData.AddPair('message', LJsonMess.ToString()); // IOS LData.AddPair('alert', LJsonMess.ToString()); LWhere := TJSONObject.Create; LWhere.AddPair('nurseuser', 'nurses'); // Target assignee LEMSAPI.PushWhere(LData, LWhere); finally LEMSAPI.Free; LWhere.Free; LJSON.Free; LJsonMess.Free; end; end; procedure TNurseStationResource.PushMessagePatient(const AContext: TEndpointContext; const APatientId : string); var LEMSAPI: TEMSInternalAPI; LData: TJSONObject; LWhere: TJSONObject; LJSON: TJSONObject; begin // Create in-process EMS API LEMSAPI := TEMSInternalAPI.Create(AContext); LWhere := nil; LJSON := nil; try LJSON := TJSONObject.Create; LData := TJSONObject.Create; LJSON.AddPair('data', LData); // Gcm LData.AddPair('title', 'Reminder'); LData.AddPair('message', 'The Nurse is ready to see you now'); // IOS LData.AddPair('alert', 'The Nurse is ready to see you now'); LWhere := TJSONObject.Create; LWhere.AddPair('nurseuser', APatientId); // Target assignee LEMSAPI.PushWhere(LJSON, LWhere); finally LEMSAPI.Free; LWhere.Free; LJSON.Free; end; end; procedure TNurseStationResource.HandleException; var LException: TObject; LMessage: string; begin LException := ExceptObject; Assert(LException <> nil); // should be within an except block if LException is Exception then begin LMessage := Exception(LException).Message; if LException is EPatientError then EEMSHTTPError.RaiseDuplicate(LMessage) else if LException is EPatientNotFound then EEMSHTTPError.RaiseNotFound(LMessage) else begin LException := TObject(AcquireExceptionObject); Assert(LException <> nil); // should be within an except block raise LException; end; end; end; procedure Register; begin RegisterResource(TypeInfo(TNurseStationResource)); end; initialization Register; end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, clFTP, clFTPUtils, clUtils, clTcpClient, ExtCtrls, clTcpClientTls, clTcpCommandClient, DemoBaseFormUnit; type TMainForm = class(TclDemoBaseForm) ProgressBar: TProgressBar; Label1: TLabel; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; edtServer: TEdit; edtPort: TEdit; edtUser: TEdit; edtPassword: TEdit; edtStartDir: TEdit; cbPassiveMode: TCheckBox; cbAsciiMode: TCheckBox; btnLogin: TButton; btnLogout: TButton; btnOpenDir: TButton; btnGoUp: TButton; btnDownload: TButton; btnUpload: TButton; btnAbort: TButton; lbList: TListBox; Label7: TLabel; clFTP: TclFTP; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; Bevel1: TBevel; Label3: TLabel; Label8: TLabel; edtProxyServer: TEdit; edtProxyUser: TEdit; edtProxyPassword: TEdit; edtProxyPort: TEdit; Label9: TLabel; Label10: TLabel; Label11: TLabel; cbProxyType: TComboBox; procedure btnLoginClick(Sender: TObject); procedure btnLogoutClick(Sender: TObject); procedure btnOpenDirClick(Sender: TObject); procedure btnGoUpClick(Sender: TObject); procedure btnAbortClick(Sender: TObject); procedure btnDownloadClick(Sender: TObject); procedure btnUploadClick(Sender: TObject); procedure clFTPDirectoryListing(Sender: TObject; AFileInfo: TclFtpFileInfo; const Source: String); procedure clFTPProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private procedure UpdateStatuses; procedure DoOpenDir(const ADir: string); procedure FillDirList; end; var MainForm: TMainForm; implementation {$R *.dfm} { TMainForm } procedure TMainForm.FormShow(Sender: TObject); begin UpdateStatuses(); end; procedure TMainForm.FormDestroy(Sender: TObject); begin clFTP.Close(); end; procedure TMainForm.UpdateStatuses; const states: array[Boolean] of string = ('Ftp Client Proxy Sample', 'Ftp Client Proxy - Connected'); var enabled: Boolean; begin enabled := clFTP.Active; Caption := states[enabled]; btnOpenDir.Enabled := enabled; btnGoUp.Enabled := enabled; btnDownload.Enabled := enabled; btnUpload.Enabled := enabled; btnAbort.Enabled := enabled; end; procedure TMainForm.btnLoginClick(Sender: TObject); const transferTypes: array[Boolean] of TclFtpTransferType = (ttBinary, ttAscii); begin if clFTP.Active then begin ShowMessage('You are already connected. Please click Logout to disconnect.'); Exit; end; clFTP.Port := StrToInt(edtPort.Text); clFTP.Server := edtServer.Text; clFTP.UserName := edtUser.Text; clFTP.Password := edtPassword.Text; clFTP.PassiveMode := cbPassiveMode.Checked; clFTP.TransferType := transferTypes[cbAsciiMode.Checked]; clFTP.ProxySettings.Server := edtProxyServer.Text; clFTP.ProxySettings.Port := StrToInt(edtProxyPort.Text); clFTP.ProxySettings.UserName := edtProxyUser.Text; clFTP.ProxySettings.Password := edtProxyPassword.Text; clFTP.ProxySettings.ProxyType := TclFtpProxyType(cbProxyType.ItemIndex); clFTP.Open(); if (edtStartDir.Text = '') then begin edtStartDir.Text := clFTP.CurrentDir; end; if (edtStartDir.Text <> '') and (edtStartDir.Text[1] = '/') then begin DoOpenDir(edtStartDir.Text); end; UpdateStatuses(); end; procedure TMainForm.btnLogoutClick(Sender: TObject); begin clFTP.Close(); lbList.Items.Clear(); UpdateStatuses(); end; procedure TMainForm.DoOpenDir(const ADir: string); var dir: string; begin dir := ADir; if (Length(dir) > 1) and (dir[1] = '/') and (dir[2] = '/') then begin system.Delete(dir, 1, 1); end; clFTP.ChangeCurrentDir('/'); clFTP.ChangeCurrentDir(dir); FillDirList(); end; procedure TMainForm.FillDirList; begin lbList.Items.BeginUpdate(); try lbList.Items.Clear(); clFTP.DirectoryListing(); finally lbList.Items.EndUpdate(); end; lbList.Sorted := False; lbList.Sorted := True; end; procedure TMainForm.btnOpenDirClick(Sender: TObject); begin if (lbList.ItemIndex > -1) and (lbList.Items[lbList.ItemIndex] <> '') and (lbList.Items[lbList.ItemIndex][1] = '/') then begin DoOpenDir(clFTP.CurrentDir + lbList.Items[lbList.ItemIndex]); end; end; procedure TMainForm.btnGoUpClick(Sender: TObject); begin clFTP.ChangeToParentDir(); FillDirList(); end; procedure TMainForm.btnAbortClick(Sender: TObject); begin clFTP.Abort(); UpdateStatuses(); end; procedure TMainForm.btnDownloadClick(Sender: TObject); var stream: TStream; begin if (lbList.ItemIndex > -1) and (lbList.Items[lbList.ItemIndex] <> '') and (lbList.Items[lbList.ItemIndex][1] <> '/') then begin SaveDialog.FileName := lbList.Items[lbList.ItemIndex]; if SaveDialog.Execute() then begin stream := TFileStream.Create(SaveDialog.FileName, fmCreate); try ProgressBar.Min := 0; ProgressBar.Max := clFTP.GetFileSize(lbList.Items[lbList.ItemIndex]); ProgressBar.Position := 0; clFTP.GetFile(lbList.Items[lbList.ItemIndex], stream); ShowMessage('Done'); finally stream.Free(); end; end; end; end; procedure TMainForm.btnUploadClick(Sender: TObject); var stream: TStream; begin if OpenDialog.Execute() then begin stream := TFileStream.Create(OpenDialog.FileName, fmOpenRead); try ProgressBar.Min := 0; ProgressBar.Max := stream.Size; ProgressBar.Position := 0; clFTP.PutFile(stream, ExtractFileName(OpenDialog.FileName)); ShowMessage('Done'); finally stream.Free(); end; FillDirList(); end; end; procedure TMainForm.clFTPDirectoryListing(Sender: TObject; AFileInfo: TclFtpFileInfo; const Source: String); const dirPrefix: array[Boolean] of string = ('', '/'); begin lbList.Items.Add(dirPrefix[AFileInfo.IsDirectory or AFileInfo.IsLink] + AFileInfo.FileName); end; procedure TMainForm.clFTPProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin ProgressBar.Position := ABytesProceed; ProgressBar.Max := ATotalBytes; end; end.
{*********************************************************} {* VPSQLDIALECT.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* Hannes Danzl *} {* *} {* ***** END LICENSE BLOCK ***** *} {This unit was provided by Hannes Danzl and is used here with permission } // implements a base class for abstracting different SQL dialects<br> // currently only some basic commands are supported, could be extended in // future unit VPSQLDialect; interface uses db, VPDbIntf, classes, sysutils; type // the base class for all sql dialects TVPBaseSQLDialect = class(TComponent) protected // see Dataset fDataset: TDataset; // see DBEngine fDBEngine: String; // see ConnectionParams fConnectionParams: TStrings; // see SQL fSQL: String; // see TableName fTableName: String; // see Session fSession: TComponent; // see ConnectionParams procedure SetConnectionParams(const Value: TStrings); // see Session procedure SetSession(const Value: TComponent); // see SQL procedure SetSQL(const Value: String); // see DBEngine procedure SetDBEngine(const Value: String); virtual; // creates the an interface dataset according to the given DBEngine class // see swhDatabaseIntf.pas for more info function CreateSQLDataSet(DBEngine: String): TDataset; virtual; // should return the SQL string for definition of the given field // e.g. "Field1 Number" for oracle<br> // <flag>override function SQLGetColumnDef(const aFieldDef: TFieldDef): String; virtual; abstract; // should return the syntax for the create command<br> // default is: create table %TableName% (%Fields%)<br> // %tablename% will be substituted by according name, %Fields% is a commadelimited // list of fielddefinitions created by calls to SQLGetColumnDef // <flag>override function GetCreateSyntax: String; virtual; // should return the syntax for the select command<br> // default is: select * from %tablename%<br> // %tablename% will be substituted by according name; // the result set should be read/write so in oracle e.g. use // select %tableName%.rowid, %tablename%.* from %tablename% // <flag>override function GetSelectSyntax: String; virtual; // should return the syntax for the select command<br> // default is: delete from %tablename%<br> // <flag>override function GetDeleteSyntax: String; virtual; // should return the syntax for checking that a database exists // returns blank here because it is very engine dependant // <flag override> function GetEnsureDatabaseExistsSyntax: String; virtual; public // calls Dataset.Open procedure Open; virtual; // calls Dataset.iExecSQL procedure ExecSQL; virtual; // calls Dataset.Close procedure Close; virtual; // calls GetCreateSyntax and then passes the result to SQL and calls ExecSQL procedure CreateTable(const aTableName: String; const aFieldDefs: TFieldDefs; const aIndexDefs: TIndexDefs); virtual; // there is no standard syntax/method for checking. // requires that the ConnectionParams property has the required params set. procedure EnsureDatabaseExists; virtual; abstract; // constructor constructor Create(aOwner: TComponent); override; // destructor destructor Destroy; override; // should return the syntax for the select command<br> // default is: select * from %tablename%<br> // %tablename% will be substituted by according name; // the result set should be read/write so in oracle e.g. use // select %tableName%.rowid, %tablename%.* from %tablename% property SelectSQL: string read GetSelectSyntax; // should return the syntax for the select command<br> // default is: delete from %tablename%<br> property DeleteSQL: string read GetDeleteSyntax; // the name of the (main)table we are querying property TableName: String read fTableName write fTableName; // the dataset that is used property Dataset: TDataset read fDataset; // the database engine to use property DBEngine: String read fDBEngine write SetDBEngine; // the sql statement property SQL: String read fSQL write SetSQL; // optional connection parameters for the dataset; alternatively use the session // proprty to pass in an external session property ConnectionParams: TStrings read fConnectionParams write SetConnectionParams; // passed through to the Dataset.ISession before it is opened; can be everything // and it's the responsibility of the dataset implementation to check it property Session: TComponent read fSession write SetSession; end; // factory that can register and create instances of registered TVPBaseSQLDialect function sSQLDialectFactory: TDBFactory; implementation { TVPBaseSQLDialect } procedure TVPBaseSQLDialect.Close; begin fDataset.Close; end; {=====} constructor TVPBaseSQLDialect.Create(aOwner: TComponent); begin inherited; fConnectionParams:=TStringList.Create; end; {=====} function TVPBaseSQLDialect.CreateSQLDataSet(DBEngine: String): TDataset; begin result:=TDataset(sSQLDatasetFactory.CreateInstance(DBEngine)); end; {=====} procedure TVPBaseSQLDialect.CreateTable(const aTableName: String; const aFieldDefs: TFieldDefs; const aIndexDefs: TIndexDefs); var j: Integer; Fields: String; SQL: String; IDS: ISQLDataSet; begin for j := 0 to aFieldDefs.Count-1 do // Iterate Fields:=Fields+SQLGetColumnDef(aFieldDefs[j])+', '; SQL:=GetCreateSyntax; SQL:=StringReplace(SQL, '%TableName%', aTableName, [rfIgnoreCase]); SQL:=StringReplace(SQL, '%Fields%', copy(Fields,1,length(Fields)-2), [rfIgnoreCase]); fDataset.GetInterface(ISQLDataSet, ids); try ids.iSQL:=SQL; ids.IExecSQL; finally ids:=nil; end; end; {=====} destructor TVPBaseSQLDialect.Destroy; begin fConnectionParams.free; fDataset.Free; inherited; end; {=====} procedure TVPBaseSQLDialect.ExecSQL; var iDS: ISQLDataSet; begin fDataset.GetInterface(ISQLDataSet, iDS); try iDS.iExecSQL; finally iDS:=nil; end; end; {=====} function TVPBaseSQLDialect.GetCreateSyntax: String; begin result:='create table %TableName% (%Fields%)'; end; {=====} function TVPBaseSQLDialect.GetDeleteSyntax: String; begin result:='delete from %tablename%'; end; {=====} function TVPBaseSQLDialect.GetSelectSyntax: String; begin result:='select * from %tablename%'; end; {=====} procedure TVPBaseSQLDialect.Open; begin fDataset.Open; end; {=====} procedure TVPBaseSQLDialect.SetDBEngine(const Value: String); begin fDBEngine := Value; if fDataset<>nil then FreeAndNil(fDataset); fDataset:=CreateSQLDataSet(fDBEngine); end; {=====} var fSQLDialectFactory: TDBFactory; function sSQLDialectFactory: TDBFactory; begin if fSQLDialectFactory=nil then fSQLDialectFactory:=TDBFactory.Create; result:=fSQLDialectFactory; end; {=====} procedure TVPBaseSQLDialect.SetConnectionParams(const Value: TStrings); var iDS: ISQLDataset; begin Close; fConnectionParams.Assign(Value); Dataset.GetInterface(ISQLDataset, iDS); try iDS.iConnectionParams:=value.Text; finally ids:=nil; end; end; {=====} procedure TVPBaseSQLDialect.SetSession(const Value: TComponent); begin Close; fSession := Value; end; {=====} procedure TVPBaseSQLDialect.SetSQL(const Value: String); var iDS: ISQLDataSet; begin fSQL := Value; fDataset.Close; fDataset.GetInterface(ISQLDataSet, iDS); try iDS.iSQL:=fSQL; finally iDS:=nil; end; end; {=====} function TVPBaseSQLDialect.GetEnsureDatabaseExistsSyntax: String; begin Result := ''; end; {=====} initialization fSQLDialectFactory:=nil; end.
unit SDFrameDataRepair; interface uses Windows, Messages, Forms, BaseFrame, Classes, Controls, Graphics, Sysutils, StdCtrls, ExtCtrls, VirtualTrees, VirtualTree_Editor, define_price, define_dealitem, define_data_sina, define_datasrc, define_stock_quotes, define_dealstore_file, DealItemsTreeView, StockDayDataAccess; type PStockDayDataColumns = ^TStockDayDataColumns; TStockDayDataColumns = record Col_PriceOpen: TVirtualTreeColumn; // 开盘价 Col_PriceHigh: TVirtualTreeColumn; // 最高价 Col_PriceLow: TVirtualTreeColumn; // 最低价 Col_PriceClose: TVirtualTreeColumn; // 收盘价 Col_Weight: TVirtualTreeColumn; // 权重 end; TStockDataTreeCtrlData = record Col_Date: TVirtualTreeColumn; Cols_DataSrc_163: TStockDayDataColumns; Cols_DataSrc_Sina: TStockDayDataColumns; Col_WeightPriceOffset: TVirtualTreeColumn; // 权重 DayDataAccess_163: TStockDayDataAccess; DayDataAccess_Sina: TStockDayDataAccess; end; TfmeDataRepairData = record FocusDealItem: PRT_DealItem; OnGetDealItem: TOnDealItemFunc; StockListTreeCtrl: TDealItemTreeCtrl; StockDataTreeCtrlData: TStockDataTreeCtrlData; end; TfmeDataRepair = class(TfmeBase) pnlDayDataTop: TPanel; pnlMain: TPanel; vtDayData: TVirtualStringTree; pnl1: TPanel; spl1: TSplitter; lstDayDataRecords: TListBox; private { Private declarations } fDataRepairData: TfmeDataRepairData; procedure vtDayDataGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure vtDayDataCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure vtDayDataEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); procedure InitializeStockDayDataListView(ATreeView: TVirtualStringTree); procedure ClearDayData; procedure BuildStocksDayDataVirtualTree(); function vtDayDataGetEditDataType(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): TEditorValueType; function vtDayDataGetEditText(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): WideString; procedure vtDayDataGetEditUpdateData(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex; AData: WideString); procedure vtDayDataBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); procedure vtDayDataAfterItemPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect); procedure vtDayDataPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure Initialize; override; procedure CallDeactivate; override; procedure CallActivate; override; procedure NotifyDealItem(ADealItem: PRT_DealItem); property OnGetDealItem: TOnDealItemFunc read fDataRepairData.OnGetDealItem write fDataRepairData.OnGetDealItem; end; implementation {$R *.dfm} uses StockDayData_Load, StockDayData_Save; { TfmeDataRepair } type PStockDayDataNode = ^TStockDayDataNode; TStockDayDataNode = record Date: Word; QuoteData_163: PRT_Quote_Day; QuoteData_Sina: PRT_Quote_Day; ErrorCheckStatus: Word; end; constructor TfmeDataRepair.Create(Owner: TComponent); begin inherited; FillChar(fDataRepairData, SizeOf(fDataRepairData), 0); end; destructor TfmeDataRepair.Destroy; begin ClearDayData; inherited; end; procedure TfmeDataRepair.Initialize; begin inherited; InitializeStockDayDataListView(vtDayData); end; procedure TfmeDataRepair.CallDeactivate; begin end; procedure TfmeDataRepair.CallActivate; begin end; procedure TfmeDataRepair.NotifyDealItem(ADealItem: PRT_DealItem); begin vtDayData.BeginUpdate; try vtDayData.Clear; ClearDayData; if nil <> ADealItem then begin //edtstock.Text := ADealItem.sCode; fDataRepairData.FocusDealItem := ADealItem; fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163 := TStockDayDataAccess.Create(ADealItem, Src_163, weightNone); LoadStockDayData(App, fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163); fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina := TStockDayDataAccess.Create(ADealItem, Src_Sina, weightBackward); LoadStockDayData(App, fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina); BuildStocksDayDataVirtualTree(); end; finally vtDayData.EndUpdate; end; end; procedure TfmeDataRepair.ClearDayData; begin if nil <> fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163 then begin FreeAndNil(fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163); end; if nil <> fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina then begin FreeAndNil(fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina); end; end; procedure TfmeDataRepair.BuildStocksDayDataVirtualTree(); var tmpVNode: PVirtualNode; tmpVNodeData: PStockDayDataNode; tmpDayData_163: PRT_Quote_Day; tmpDayData_Sina: PRT_Quote_Day; tmpIndex1: integer; tmpIndex2: integer; tmpint64: int64; tmpOffset: double; begin //mmoLogs.Lines.BeginUpdate; lstDayDataRecords.Items.BeginUpdate; vtDayData.BeginUpdate; try //mmoLogs.Lines.Clear; lstDayDataRecords.Items.Clear; vtDayData.Clear; tmpIndex1 := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163.RecordCount - 1; tmpIndex2 := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina.RecordCount - 1; while (tmpIndex1 > 0) and (tmpIndex2 > 0) do begin tmpDayData_163 := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163.RecordItem[tmpIndex1]; tmpDayData_Sina := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina.RecordItem[tmpIndex2]; tmpVNode := vtDayData.AddChild(nil); tmpVNodeData := vtDayData.GetNodeData(tmpVNode); if tmpDayData_163.DealDate.Value = tmpDayData_Sina.DealDate.Value then begin tmpVNodeData.QuoteData_163 := tmpDayData_163; tmpVNodeData.Date := tmpDayData_163.DealDate.Value; tmpVNodeData.QuoteData_Sina := tmpDayData_Sina; Dec(tmpIndex1); Dec(tmpIndex2); if 0 = tmpDayData_Sina.Weight.Value then begin lstDayDataRecords.Items.AddObject('sina0:' + FormatDateTime('yyyy-mm-dd', tmpDayData_Sina.DealDate.Value), TObject(tmpDayData_Sina.DealDate.Value)); end else begin if (0 = tmpDayData_Sina.PriceRange.PriceOpen.Value) or (0 = tmpDayData_Sina.PriceRange.PriceClose.Value) or (0 = tmpDayData_Sina.PriceRange.PriceLow.Value) or (0 = tmpDayData_Sina.PriceRange.PriceHigh.Value) then begin lstDayDataRecords.Items.AddObject('sina err:' + FormatDateTime('yyyy-mm-dd', tmpDayData_Sina.DealDate.Value), TObject(tmpDayData_Sina.DealDate.Value)); end else begin tmpint64 := int64(tmpDayData_163.PriceRange.PriceOpen.Value) * Int64(tmpDayData_Sina.Weight.Value); tmpOffset := tmpint64 / 1000; tmpOffset := Abs(tmpOffset - tmpDayData_Sina.PriceRange.PriceOpen.Value); if 120 < tmpOffset then begin lstDayDataRecords.Items.AddObject('sina weight err:' + FormatDateTime('yyyy-mm-dd', tmpDayData_Sina.DealDate.Value), TObject(tmpDayData_Sina.DealDate.Value)); end; end; end; end else begin if tmpDayData_163.DealDate.Value > tmpDayData_Sina.DealDate.Value then begin tmpVNodeData.QuoteData_163 := tmpDayData_163; tmpVNodeData.Date := tmpDayData_163.DealDate.Value; Dec(tmpIndex1); lstDayDataRecords.Items.AddObject('163:' + FormatDateTime('yyyy-mm-dd', tmpDayData_163.DealDate.Value), TObject(tmpDayData_163.DealDate.Value)); end else begin tmpVNodeData.QuoteData_Sina := tmpDayData_Sina; tmpVNodeData.Date := tmpDayData_Sina.DealDate.Value; Dec(tmpIndex2); lstDayDataRecords.Items.AddObject('sina:' + FormatDateTime('yyyy-mm-dd', tmpDayData_Sina.DealDate.Value), TObject(tmpDayData_Sina.DealDate.Value)); end; end; end; while (tmpIndex1 > 0) do begin tmpVNode := vtDayData.AddChild(nil); tmpVNodeData := vtDayData.GetNodeData(tmpVNode); tmpDayData_163 := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163.RecordItem[tmpIndex1]; tmpVNodeData.QuoteData_163 := tmpDayData_163; tmpVNodeData.Date := tmpDayData_163.DealDate.Value; lstDayDataRecords.Items.AddObject('163:' + FormatDateTime('yyyy-mm-dd', tmpDayData_163.DealDate.Value), TObject(tmpDayData_163.DealDate.Value)); Dec(tmpIndex1); end; while (tmpIndex2 > 0) do begin tmpVNode := vtDayData.AddChild(nil); tmpVNodeData := vtDayData.GetNodeData(tmpVNode); tmpDayData_Sina := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina.RecordItem[tmpIndex2]; tmpVNodeData.QuoteData_Sina := tmpDayData_Sina; tmpVNodeData.Date := tmpDayData_Sina.DealDate.Value; lstDayDataRecords.Items.AddObject('sina:' + FormatDateTime('yyyy-mm-dd', tmpDayData_Sina.DealDate.Value), TObject(tmpDayData_Sina.DealDate.Value)); Dec(tmpIndex2); end; finally vtDayData.EndUpdate; lstDayDataRecords.Items.EndUpdate; //mmoLogs.Lines.EndUpdate; end; end; procedure TfmeDataRepair.vtDayDataGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); function GetDayDataCellText(ADayData: PRT_Quote_Day; ADayDataCols: PStockDayDataColumns): Boolean; begin Result := false; if nil = ADayData then exit; if nil <> ADayDataCols.Col_PriceOpen then begin if Column = ADayDataCols.Col_PriceOpen.Index then begin CellText := IntToStr(ADayData.PriceRange.PriceOpen.Value); Result := true; exit; end; end; if nil <> ADayDataCols.Col_PriceHigh then begin if Column = ADayDataCols.Col_PriceHigh.Index then begin CellText := IntToStr(ADayData.PriceRange.PriceHigh.Value); Result := true; exit; end; end; if nil <> ADayDataCols.Col_PriceLow then begin if Column = ADayDataCols.Col_PriceLow.Index then begin CellText := IntToStr(ADayData.PriceRange.PriceLow.Value); Result := true; exit; end; end; if nil <> ADayDataCols.Col_PriceClose then begin if Column = ADayDataCols.Col_PriceClose.Index then begin CellText := IntToStr(ADayData.PriceRange.PriceClose.Value); Result := true; exit; end; end; if nil <> ADayDataCols.Col_Weight then begin if Column = ADayDataCols.Col_Weight.Index then begin CellText := IntToStr(ADayData.Weight.Value); Result := true; exit; end; end; end; var tmpVData: PStockDayDataNode; tmpOffset: double; tmpInt64: int64; begin inherited; CellText := ''; tmpVData := Sender.GetNodeData(Node); if nil <> tmpVData then begin if nil <> fDataRepairData.StockDataTreeCtrlData.Col_Date then begin if Column = fDataRepairData.StockDataTreeCtrlData.Col_Date.Index then begin CellText := FormatDateTime('yyyy-mm-dd', tmpVData.Date); exit; end; end; if nil <> fDataRepairData.StockDataTreeCtrlData.Col_WeightPriceOffset then begin if Column = fDataRepairData.StockDataTreeCtrlData.Col_WeightPriceOffset.Index then begin CellText := '0'; if (nil <> tmpVData.QuoteData_163) and (nil <> tmpVData.QuoteData_Sina) then begin if tmpVData.QuoteData_Sina.Weight.Value > 1000 then begin tmpInt64 := Int64(tmpVData.QuoteData_163.PriceRange.PriceOpen.Value) * Int64(tmpVData.QuoteData_Sina.Weight.Value); tmpOffset := tmpInt64 / 1000; tmpOffset := tmpOffset - tmpVData.QuoteData_Sina.PriceRange.PriceOpen.Value; //tmpOffset := Abs(tmpOffset); CellText := FloatToStr(tmpOffset); end; end; exit; end; end; if GetDayDataCellText(tmpVData.QuoteData_163, @fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_163) then exit; GetDayDataCellText(tmpVData.QuoteData_Sina, @fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina); end; end; procedure TfmeDataRepair.vtDayDataAfterItemPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect); begin if nil = Node then exit; if vsSelected in node.States then begin if Sender.FocusedNode = Node then begin TargetCanvas.Brush.Color := clGreen; TargetCanvas.FrameRect(ItemRect); end else begin TargetCanvas.Brush.Color := clBlue; TargetCanvas.FrameRect(ItemRect); end; end; end; procedure TfmeDataRepair.vtDayDataBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var tmpVData: PStockDayDataNode; tmpIsErrorMode: Integer; begin tmpIsErrorMode := 0; tmpVData := Sender.GetNodeData(Node); if nil <> tmpVData then begin if (nil = tmpVData.QuoteData_163) or (nil = tmpVData.QuoteData_Sina) then begin end else begin if 0 = tmpVData.QuoteData_Sina.PriceRange.PriceOpen.Value then begin if nil <> fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceOpen then begin if Column = fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceOpen.Index then begin tmpIsErrorMode := 1; end; end; end; if 0 = tmpVData.QuoteData_Sina.PriceRange.PriceClose.Value then begin if nil <> fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceClose then begin if Column = fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceClose.Index then begin tmpIsErrorMode := 1; end; end; end; if 0 = tmpVData.QuoteData_Sina.PriceRange.PriceHigh.Value then begin if nil <> fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceHigh then begin if Column = fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceHigh.Index then begin tmpIsErrorMode := 1; end; end; end; if 0 = tmpVData.QuoteData_Sina.PriceRange.PriceLow.Value then begin if nil <> fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceLow then begin if Column = fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina.Col_PriceLow.Index then begin tmpIsErrorMode := 1; end; end; end; end; if 1 = tmpIsErrorMode then begin TargetCanvas.Brush.Color := clRed; TargetCanvas.FillRect(CellRect); end; end; end; procedure TfmeDataRepair.vtDayDataPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); var tmpVData: PStockDayDataNode; tmpOffset: double; tmpint64: int64; begin inherited; tmpVData := Sender.GetNodeData(Node); if nil <> tmpVData then begin if (nil = tmpVData.QuoteData_163) or (nil = tmpVData.QuoteData_Sina) then begin TargetCanvas.Font.Color := clRed; end else begin if (tmpVData.QuoteData_Sina.Weight.Value > 200) then begin tmpint64 := int64(tmpVData.QuoteData_163.PriceRange.PriceOpen.Value) * Int64(tmpVData.QuoteData_Sina.Weight.Value); tmpOffset := tmpint64 / 1000; tmpOffset := Abs(tmpOffset - tmpVData.QuoteData_Sina.PriceRange.PriceOpen.Value); if tmpOffset > 40 then begin TargetCanvas.Font.Color := clRed; TargetCanvas.Font.Style := TargetCanvas.Font.Style + [fsStrikeOut]; end else begin if tmpOffset > 20 then begin TargetCanvas.Font.Color := clRed; end else begin if tmpOffset > 10 then begin TargetCanvas.Font.Color := clBlue; end; end; end; end else begin // 600083 weight < 1000 995 if tmpVData.QuoteData_Sina.Weight.Value < 100 then begin TargetCanvas.Font.Color := clRed; end; end; end; end; end; procedure TfmeDataRepair.vtDayDataGetEditUpdateData(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex; AData: WideString); function IsInColumns(ADayDataCols: PStockDayDataColumns): Boolean; begin Result := false; if nil = ADayDataCols then exit; if nil <> ADayDataCols.Col_PriceOpen then Result := AColumn = ADayDataCols.Col_PriceOpen.Index; if Result then exit; if nil <> ADayDataCols.Col_PriceHigh then Result := AColumn = ADayDataCols.Col_PriceHigh.Index; if Result then exit; if nil <> ADayDataCols.Col_PriceLow then Result := AColumn = ADayDataCols.Col_PriceLow.Index; if Result then exit; if nil <> ADayDataCols.Col_PriceClose then Result := AColumn = ADayDataCols.Col_PriceClose.Index; if Result then exit; end; function UpdateDayDataCellText(ADayData: PRT_Quote_Day; ADayDataCols: PStockDayDataColumns): Boolean; var intvalue: integer; begin Result := false; if nil = ADayData then exit; if nil <> ADayDataCols.Col_PriceOpen then begin if AColumn = ADayDataCols.Col_PriceOpen.Index then begin intvalue := StrToIntDef(AData, 0); if 0 < intvalue then begin if ADayData.PriceRange.PriceOpen.Value <> intvalue then begin ADayData.PriceRange.PriceOpen.Value := intvalue; end; end; end; end; if nil <> ADayDataCols.Col_PriceHigh then begin if AColumn = ADayDataCols.Col_PriceHigh.Index then begin intvalue := StrToIntDef(AData, 0); if 0 < intvalue then begin if ADayData.PriceRange.PriceHigh.Value <> intvalue then begin ADayData.PriceRange.PriceHigh.Value := intvalue; end; end; end; end; if nil <> ADayDataCols.Col_PriceLow then begin if AColumn = ADayDataCols.Col_PriceLow.Index then begin intvalue := StrToIntDef(AData, 0); if 0 < intvalue then begin if ADayData.PriceRange.PriceLow.Value <> intvalue then begin ADayData.PriceRange.PriceLow.Value := intvalue; end; end; end; end; if nil <> ADayDataCols.Col_PriceClose then begin if AColumn = ADayDataCols.Col_PriceClose.Index then begin intvalue := StrToIntDef(AData, 0); if 0 < intvalue then begin if ADayData.PriceRange.PriceClose.Value <> intvalue then begin ADayData.PriceRange.PriceClose.Value := intvalue; end; end; end; end; if nil <> ADayDataCols.Col_Weight then begin if AColumn = ADayDataCols.Col_Weight.Index then begin intvalue := StrToIntDef(AData, 0); if 0 < intvalue then begin if ADayData.Weight.Value <> intvalue then begin ADayData.Weight.Value := intvalue; end; end; end; end; end; var tmpVData: PStockDayDataNode; begin tmpVData := ATree.GetNodeData(ANode); if nil <> tmpVData then begin if nil = tmpVData.QuoteData_Sina then begin if nil <> tmpVData.QuoteData_163 then begin tmpVData.QuoteData_Sina := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_Sina.CheckOutRecord(tmpVData.QuoteData_163.DealDate.Value); end; end; if nil = tmpVData.QuoteData_163 then begin if IsInColumns(@fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_163) then begin if 0 < tmpVData.Date then begin tmpVData.QuoteData_163 := fDataRepairData.StockDataTreeCtrlData.DayDataAccess_163.CheckOutRecord(tmpVData.Date); end; end; end; UpdateDayDataCellText(tmpVData.QuoteData_163, @fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_163); UpdateDayDataCellText(tmpVData.QuoteData_Sina, @fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina); if (0 = tmpVData.QuoteData_Sina.PriceRange.PriceOpen.Value) and (0 = tmpVData.QuoteData_Sina.PriceRange.PriceClose.Value) and (0 = tmpVData.QuoteData_Sina.PriceRange.PriceHigh.Value) and (0 = tmpVData.QuoteData_Sina.PriceRange.PriceLow.Value) and (0 < tmpVData.QuoteData_Sina.Weight.Value) then begin if nil <> tmpVData.QuoteData_163 then begin tmpVData.QuoteData_Sina.PriceRange.PriceOpen.Value := Trunc((tmpVData.QuoteData_163.PriceRange.PriceOpen.Value * tmpVData.QuoteData_Sina.Weight.Value) / 1000); tmpVData.QuoteData_Sina.PriceRange.PriceLow.Value := Trunc((tmpVData.QuoteData_163.PriceRange.PriceLow.Value * tmpVData.QuoteData_Sina.Weight.Value) / 1000); tmpVData.QuoteData_Sina.PriceRange.PriceHigh.Value := Trunc((tmpVData.QuoteData_163.PriceRange.PriceHigh.Value * tmpVData.QuoteData_Sina.Weight.Value) / 1000); tmpVData.QuoteData_Sina.PriceRange.PriceClose.Value := Trunc((tmpVData.QuoteData_163.PriceRange.PriceClose.Value * tmpVData.QuoteData_Sina.Weight.Value) / 1000); end; end; end; end; procedure TfmeDataRepair.vtDayDataCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); begin EditLink := TPropertyEditLink.Create(vtDayDataGetEditDataType, vtDayDataGetEditText, vtDayDataGetEditUpdateData); end; procedure TfmeDataRepair.vtDayDataEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); begin Allowed := true; end; procedure TfmeDataRepair.InitializeStockDayDataListView(ATreeView: TVirtualStringTree); var tmpCol: TVirtualTreeColumn; procedure InitializeDayDataColumns(ADayDataColumns: PStockDayDataColumns; ATag: string); begin tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'Open_' + ATag; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin + ATreeView.Indent; ADayDataColumns.Col_PriceOpen := tmpCol; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'High_' + ATag; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin + ATreeView.Indent; ADayDataColumns.Col_PriceHigh := tmpCol; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'Low_' + ATag; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin + ATreeView.Indent; ADayDataColumns.Col_PriceLow := tmpCol; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'Close_' + ATag; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin + ATreeView.Indent; ADayDataColumns.Col_PriceClose := tmpCol; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'Weight_' + ATag; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin + ATreeView.Indent; ADayDataColumns.Col_Weight := tmpCol; end; begin ATreeView.NodeDataSize := SizeOf(TStockDayDataNode); ATreeView.Header.Options := [hoVisible, hoColumnResize]; ATreeView.OnGetText := vtDayDataGetText; ATreeView.OnPaintText := vtDayDataPaintText; ATreeView.OnAfterItemPaint := vtDayDataAfterItemPaint; ATreeView.OnBeforeCellPaint := vtDayDataBeforeCellPaint; ATreeView.OnCreateEditor := vtDayDataCreateEditor; ATreeView.OnEditing := vtDayDataEditing; ATreeView.Indent := 4; ATreeView.TreeOptions.AnimationOptions := []; ATreeView.TreeOptions.SelectionOptions := [toExtendedFocus,toFullRowSelect]; ATreeView.TreeOptions.SelectionOptions := [toExtendedFocus, toMultiSelect]; ATreeView.TreeOptions.AutoOptions := []; //ATreeView.TreeOptions.PaintOptions := []; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'Date'; tmpCol.Width := ATreeView.Canvas.TextWidth('2000-12-12'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin * 2 + ATreeView.Indent * 2; tmpCol.Options := tmpCol.Options + [coFixed]; fDataRepairData.StockDataTreeCtrlData.Col_Date := tmpCol; tmpCol := ATreeView.Header.Columns.Add; tmpCol.Text := 'WeightPrice Offset'; tmpCol.Width := ATreeView.Canvas.TextWidth(tmpCol.Text + '00'); tmpCol.Width := tmpCol.Width + ATreeView.TextMargin * 2 + ATreeView.Indent; fDataRepairData.StockDataTreeCtrlData.Col_WeightPriceOffset := tmpCol; InitializeDayDataColumns(@fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_163, '163'); InitializeDayDataColumns(@fDataRepairData.StockDataTreeCtrlData.Cols_DataSrc_Sina, 'sina'); end; function TfmeDataRepair.vtDayDataGetEditDataType(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): TEditorValueType; begin Result := editString; end; function TfmeDataRepair.vtDayDataGetEditText(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): WideString; begin vtDayDataGetText(ATree, ANode, AColumn, ttNormal, Result); end; end.
unit Control.TiposVerbasExpressas; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.TiposVerbasExpressas; type TTiposVerbasExpressasControl = class private FTipos : TTiposVerbasExpressas; public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): TFDQuery; function ValidarCampos(): Boolean; function RetornaListaSimples(memTable: TFDMemTable): boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; property Tipos: TTiposVerbasExpressas read FTipos write FTipos; end; implementation { TTiposVerbasExpressasControl } constructor TTiposVerbasExpressasControl.Create; begin FTipos := TTiposVerbasExpressas.Create; end; destructor TTiposVerbasExpressasControl.Destroy; begin FTipos.Create; inherited; end; function TTiposVerbasExpressasControl.GetField(sField, sKey, sKeyValue: String): String; begin Result := FTipos.GetField(sField, sKey, sKeyValue); end; function TTiposVerbasExpressasControl.Gravar: Boolean; begin Result := FTipos.Gravar; end; function TTiposVerbasExpressasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FTipos.Localizar(aParam); end; function TTiposVerbasExpressasControl.RetornaListaSimples(memTable: TFDMemTable): boolean; begin Result := FTipos.RetornaListaSimples(memTable); end; function TTiposVerbasExpressasControl.ValidarCampos: Boolean; var FDQuery: TFDQuery; aParam: array of variant; begin try Result := False; if FTipos.Codigo = 0 then begin Application.MessageBox('Informe o código do tipo de verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FTipos.Descricao.IsEmpty then begin Application.MessageBox('Informe a descrição do tipo de verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FTipos.Colunas.IsEmpty then begin Application.MessageBox('Informe as colunas do tipo de verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION); Exit; end; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; SetLength(aParam,2); aParam[0] := 'CODIGO'; aParam[1] := FTipos.Codigo; FDQuery := FTipos.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then begin Application.MessageBox('Código de tipo de verba já cadastrado!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION); Exit; end; FDQuery.Free; Result := True; finally FDQuery.Free; end; end; end.
unit uGeradorSQL; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uGeraSQL; type TFGeradorSQL = class(TForm) pnlTop: TPanel; gbxCondicao: TGroupBox; gbxTabela: TGroupBox; gbxColuna: TGroupBox; mmColuna: TMemo; mmTabela: TMemo; mmCondicao: TMemo; btnGerarSQL: TButton; gbxSQLGerado: TGroupBox; mmSQL: TMemo; procedure btnGerarSQLClick(Sender: TObject); private procedure AdicionarColunas(oGerador: TGeradorSQL); procedure AdicionarCondicoes(oGerador: TGeradorSQL); procedure AdicionarTabelas(oGerador: TGeradorSQL); procedure GerarSQL; function ValidarMemosPreenchidos: Boolean; { Private declarations } public { Public declarations } end; var FGeradorSQL: TFGeradorSQL; implementation {$R *.dfm} procedure TFGeradorSQL.btnGerarSQLClick(Sender: TObject); begin if not ValidarMemosPreenchidos then begin ShowMessage('Os campos Colunas, Tabelas e Condição devem ser preenchidos!'); Exit; end; GerarSQL; end; function TFGeradorSQL.ValidarMemosPreenchidos: Boolean; begin Result := (Trim(mmColuna.Text) <> EmptyStr) and (Trim(mmTabela.Text) <> EmptyStr) and (Trim(mmCondicao.Text) <> EmptyStr); end; procedure TFGeradorSQL.GerarSQL; var oGerador: TGeradorSQL; begin try oGerador := TGeradorSQL.Create; AdicionarColunas(oGerador); AdicionarTabelas(oGerador); AdicionarCondicoes(oGerador); mmSQL.Text := oGerador.GerarSQL; finally FreeAndNil(oGerador); end; end; procedure TFGeradorSQL.AdicionarColunas(oGerador: TGeradorSQL); var I: Integer; begin for I := 0 to mmColuna.Lines.Count-1 do oGerador.Colunas.Add(TColuna.New.AdicionarColuna(mmColuna.Lines[i])); end; procedure TFGeradorSQL.AdicionarTabelas(oGerador: TGeradorSQL); var I: Integer; begin for I := 0 to mmTabela.Lines.Count-1 do oGerador.Tabelas.Add(TTabela.New.AdicionarTabela(mmTabela.Lines[i])); end; procedure TFGeradorSQL.AdicionarCondicoes(oGerador: TGeradorSQL); var I: Integer; begin for I := 0 to mmCondicao.Lines.Count-1 do oGerador.Condicao.Add(TCondicao.New.AdicionarCondicao(mmCondicao.Lines[i])); end; end.
unit DibDraw; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Dibs; // GDI routines (Dib to Screen) // ============================================================================================= function DibPaint( dc : HDC; x, y : integer; DibHeader : PDib; DibPixels : pointer; CopyMode : dword ) : integer; function DibBlt( dc : HDC; DstX, DstY : integer; DstWidth, DstHeight : integer; DibHeader : PDib; DibPixels : pointer; SrcX, SrcY : integer; Rop : dword; wUsage : uint ) : integer; function StretchDibBlt( dc : HDC; DstX, DstY : integer; DstWidth, DstHeight : integer; DibHeader : PDib; DibPixels : pointer; SrcX, SrcY : integer; SrcWidth, SrcHeight : integer; Rop : dword; wUsage : uint ) : integer; // Higher level stuff procedure DibClipStretchDraw( DibHeader : PDib; DibPixels : pointer; dc : HDC; const Rect, ClippingRect : TRect; aCopyMode : dword ); // Dib to Dib (neither tested nor finished: nobody uses plain Dibs anymore) // ============================================================================================= // if you don't want any clipping pass nil as ClipArea: procedure DibCopyOpaque( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; x, y : integer; ClipArea : PRect ); // 8 & 24-bit specific routines: function GetPixelAddr( Dib : PDib; Pixels : pointer; x, y : integer ) : pointer; implementation uses Classes, Rects, BitBlt; // GDI stuff // --------- function DibPaint( dc : HDC; x, y : integer; DibHeader : PDib; DibPixels : pointer; CopyMode : dword ) : integer; begin if CopyMode = 0 then CopyMode := SRCCOPY; Result := DibBlt( dc, x, y, 0, 0, DibHeader, DibPixels, 0, 0, CopyMode, 0 ); end; function DibBlt( dc : HDC; DstX, DstY : integer; DstWidth, DstHeight : integer; DibHeader : PDib; DibPixels : pointer; SrcX, SrcY : integer; Rop : dword; wUsage : uint ) : integer; begin if wUsage = 0 then wUsage := DIB_RGB_COLORS; if DibPixels = nil then DibPixels := DibPtr( DibHeader ); if ( DstWidth = -1 ) and ( DstHeight = -1 ) then begin DstWidth := DibHeader.biWidth; DstHeight := DibHeader.biHeight; end; Result := StretchDIBits( dc, DstX, DstY, DstWidth, DstHeight, SrcX, SrcY, DstWidth, DstHeight, DibPixels, PBitmapInfo( DibHeader )^, wUsage, Rop ); end; function StretchDibBlt( dc : HDC; DstX, DstY : integer; DstWidth, DstHeight : integer; DibHeader : PDib; DibPixels : pointer; SrcX, SrcY : integer; SrcWidth, SrcHeight : integer; Rop : dword; wUsage : uint ) : integer; begin if wUsage = 0 then wUsage := DIB_RGB_COLORS; if DibPixels = nil then DibPixels := DibPtr( DibHeader ); if ( SrcWidth = -1 ) and ( SrcHeight = -1 ) then begin SrcWidth := DibHeader.biWidth; SrcHeight := DibHeader.biHeight; end; if ( DstWidth < 0 ) and ( DstHeight < 0 ) then begin DstWidth := SrcWidth * -DstWidth; SrcHeight := SrcHeight * -DstHeight; end; Result := StretchDIBits( dc, DstX, DstY, DstWidth, DstHeight, SrcX, SrcY, SrcWidth, SrcHeight, DibPixels, PBitmapInfo( DibHeader )^, wUsage, Rop ); end; // Higher stuff procedure DibClipDraw( DibHeader : PDib; DibPixels : pointer; dc : HDC; x, y : integer; const ClippingRect : TRect; aCopyMode : dword ); var SrcOfs : TPoint; DstSize : TPoint; DstRect : TRect; Height : integer; begin with DstRect, DibHeader^ do begin Height := abs( biHeight ); DstRect := RectFromBounds( x, y, biWidth, Height ); if IntersectRect( DstRect, DstRect, ClippingRect ) then begin DstSize := RectSize( DstRect ); if x < DstRect.Left then begin SrcOfs.x := DstRect.Left - x; x := DstRect.Left; end else SrcOfs.x := 0; if y < DstRect.Top then begin SrcOfs.y := DstRect.Top - y; y := DstRect.Top; end else SrcOfs.y := 0; DibBlt( dc, x, y, DstSize.x, DstSize.y, DibHeader, DibPixels, SrcOfs.x, SrcOfs.y, aCopyMode, DIB_PAL_COLORS ); end; end; end; procedure DibClipStretchDraw( DibHeader : PDib; DibPixels : pointer; dc : HDC; const Rect, ClippingRect : TRect; aCopyMode : dword ); var SrcOfs : TPoint; SrcSize : TPoint; DstRect : TRect; DstSize : TPoint; Height : integer; begin with DibHeader^ do if IntersectRect( DstRect, ClippingRect, Rect ) then begin DstSize := RectSize( DstRect ); Height := abs( biHeight ); if Rect.Left < DstRect.Left then SrcOfs.x := (DstRect.Left - Rect.Left) * biWidth div (Rect.Right - Rect.Left) else SrcOfs.x := 0; SrcSize.x := DstSize.x * biWidth div (Rect.Right - Rect.Left); if Rect.Top < DstRect.Top then SrcOfs.y := (DstRect.Top - Rect.Top) * Height div (Rect.Bottom - Rect.Top) else SrcOfs.y := 0; SrcSize.y := DstSize.y * Height div (Rect.Bottom - Rect.Top); StretchDibBlt( dc, DstRect.Left, DstRect.Top, DstSize.x, DstSize.y, DibHeader, DibPixels, SrcOfs.x, SrcOfs.y, SrcSize.x, SrcSize.y, aCopyMode, DIB_PAL_COLORS ); end; end; // DIB to DIB procedure DibCopyOpaque( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; x, y : integer; ClipArea : PRect ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyOpaque doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyOpaque!!' ); BltCopyOpaque( DibPixelAddr( SourceHeader, SourcePixels, dx, dy ), DibPixelAddr( DestHeader, DestPixels, x, y ), Size.x, Size.y, SrcWidth, DstWidth ); end; end; // 8-bit specific routines // ----------------------- function GetPixelAddr( Dib : PDib; Pixels : pointer; x, y : integer ) : pointer; begin assert( Dib.biBitCount = 8, 'Bitmap in DibDraw.GetPixelAddr doesn''t have 8 bits!!' ); with Dib^ do if biHeight < 0 then Result := pchar( Pixels ) + y * biWidth + x else Result := pchar( Pixels ) + ( biHeight - y ) * biWidth + x; end; (* // This stuff is no longer supported, since I don't think anybody will use it any way... // Left here in case you want to make some cut&paste procedure DibCopyTrans( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyTrans doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyTrans!!' ); assert( SourceHeader.biBitCount in [8, 24], 'Unsupported bit depth in DibDraw.DibCopyTrans!!' ); if SourceHeader.biBitCount = 8 then BltCopyTrans( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth ) else BltCopyTrans24( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth ); end; end; procedure DibCopyGlassed( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect; MixTable : pointer ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyGlassed doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyGlassed!!' ); assert( SourceHeader.biBitCount in [8, 24], 'Unsupported bit depth in DibDraw.DibCopyGlassed!!' ); if SourceHeader.biBitCount = 8 then BltCopyGlassed( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, MixTable ) else BltCopyGlassed24( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, nil ); end; end; procedure DibCopyShaded( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect; ColorTransTable : pointer ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyGlassed doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyGlassed!!' ); assert( SourceHeader.biBitCount in [8, 24], 'Unsupported bit depth in DibDraw.DibCopyGlassed!!' ); if SourceHeader.biBitCount = 8 then BltCopyDestCTT( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, ColorTransTable ) else BltCopyShaded24( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, nil ); end; end; procedure DibCopyGrid( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyMaskGrid doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyGrid!!' ); assert( SourceHeader.biBitCount in [8, 24], 'Unsupported bit depth in DibDraw.DibCopyGrid!!' ); // SrcPoint := Point( Left - fShadowDistance.x, Top - fShadowDistance.y ); // StartWithX := boolean( ( x and 1 ) and ( y and 1 ) ) or // boolean( ( (x + 1) and 1 ) and ( (y + 1) and 1 ) ); if SourceHeader.biBitCount = 8 then BltCopyGrid( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, true ) else BltCopyGrid24( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, true ); end; end; procedure DibCopyMaskGrid( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Color : integer; Transparent : integer; x, y : integer; ClipArea : PRect ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyMaskGrid doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyMaskGrid!!' ); assert( SourceHeader.biBitCount in [8, 24], 'Unsupported bit depth in DibDraw.DibCopyMaskGrid!!' ); // SrcPoint := Point( Left - fShadowDistance.x, Top - fShadowDistance.y ); // StartWithX := boolean( ( x and 1 ) and ( y and 1 ) ) or // boolean( ( (x + 1) and 1 ) and ( (y + 1) and 1 ) ); if SourceHeader.biBitCount = 8 then BltCopyMaskGrid( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, Color, true ) else BltCopyMaskGrid24( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, Color, true ); end; end; procedure DibCopySourceCTT( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect; ColorTransTable : pointer ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyMaskGrid doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyMaskGrid!!' ); assert( SourceHeader.biBitCount = 8, 'Unsupported bit depth in DibDraw.DibCopyMaskGrid!!' ); BltCopySourceCTT( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, ColorTransTable ); end; end; procedure DibCopyDestCTT( SourceHeader : PDib; SourcePixels : pointer; DestHeader : PDib; DestPixels : pointer; Transparent : integer; x, y : integer; ClipArea : PRect; ColorTransTable : pointer ); var ImageRect : TRect; Size : TPoint; dx, dy : integer; ClipRect : TRect; SrcWidth : integer; DstWidth : integer; begin assert( (SourceHeader.biBitCount = 8) and (DestHeader.biBitCount = 8), 'Bitmap in DibDraw.DibCopyMaskGrid doesn''t have 8 bits!!' ); if not Assigned( ClipArea ) then begin ClipArea := @ClipRect; ClipArea^ := RectFromBounds( x, y, DestHeader.biWidth, abs( DestHeader.biHeight ) ); end; if IntersectRect( ImageRect, RectFromBounds( x, y, SourceHeader.biWidth, abs( SourceHeader.biHeight ) ), ClipArea^ ) then begin Size := RectSize( ImageRect ); if x < ImageRect.Left then begin dx := ImageRect.Left - x; x := ImageRect.Left; end else dx := 0; if y < ImageRect.Top then begin dy := ImageRect.Top - y; y := ImageRect.Top; end else dy := 0; if SourceHeader.biHeight > 0 then SrcWidth := DibWidthBytes( SourceHeader ) else SrcWidth := -DibWidthBytes( SourceHeader ); if DestHeader.biHeight > 0 then DstWidth := DibWidthBytes( DestHeader ) else DstWidth := -DibWidthBytes( DestHeader ); assert( SourceHeader.biBitCount = DestHeader.biBitCount, 'Different bit depth in DibDraw.DibCopyMaskGrid!!' ); assert( SourceHeader.biBitCount = 8, 'Unsupported bit depth in DibDraw.DibCopyMaskGrid!!' ); BltCopyDestCTT( GetPixelAddr( SourceHeader, SourcePixels, dx, dy ), GetPixelAddr( DestHeader, DestPixels, x, y ), Transparent, Size.x, Size.y, SrcWidth, DstWidth, ColorTransTable ); end; end; *) end.