text
stringlengths
14
6.51M
(* * Copyright (c) 2008, Ciobanu Alexandru * 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. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit Tests.Casting; interface uses SysUtils, Windows, TestFramework, HelperLib.Cast; type TTestCasting = class(TTestCase) procedure TestToStringCastingInts(); procedure TestToStringCastingFloats(); procedure TestToStringCastingStrings(); procedure TestToStringCastingBools(); end; implementation { TTestCasting } procedure TTestCasting.TestToStringCastingBools; begin Check(Cast.ToString(Boolean(true)) = 'True', 'Boolean'); Check(Cast.ToString(Boolean(false)) = 'False', 'Boolean'); Check(Cast.ToString(ByteBool(true)) = 'True', 'ByteBool'); Check(Cast.ToString(ByteBool(false)) = 'False', 'ByteBool'); Check(Cast.ToString(WordBool(true)) = 'True', 'WordBool'); Check(Cast.ToString(WordBool(false)) = 'False', 'WordBool'); Check(Cast.ToString(LongBool(true)) = 'True', 'LongBool'); Check(Cast.ToString(LongBool(false)) = 'False', 'LongBool'); end; procedure TTestCasting.TestToStringCastingFloats; var s1, s2 : Single; r1, r2 : Real; u1, u2 : Real48; d1, d2 : Double; e1, e2 : Extended; c1, c2 : Currency; p1, p2 : Comp; Fs : TFormatSettings; Sep : Char; s : String; begin s1 := 1.10; s2 := -0.23; r1 := 1.10; r2 := -0.23; u1 := 1.10; u2 := -0.23; d1 := 1.10; d2 := -0.23; e1 := 1.10; e2 := -0.23; c1 := 1.10; c2 := -0.23; p1 := 123456; p2 := 654321; GetLocaleFormatSettings(GetUserDefaultLCID(), Fs); Sep := Fs.DecimalSeparator; s := Cast.ToString(u2); { Normal mode } Check(Cast.ToString(s1) = '1' + Sep + '10000002384186', 'Single'); Check(Cast.ToString(s2) = '-0' + Sep + '230000004172325', 'Single'); Check(Cast.ToString(r1) = '1' + Sep + '1', 'Real'); Check(Cast.ToString(r2) = '-0' + Sep + '23', 'Real'); Check(Cast.ToString(u1) = '1' + Sep + '10000000000036', 'Real48'); Check(Cast.ToString(u2) = '-0'+ Sep + '230000000000018', 'Real48'); Check(Cast.ToString(d1) = '1' + Sep + '1', 'Double'); Check(Cast.ToString(d2) = '-0' + Sep + '23', 'Double'); Check(Cast.ToString(e1) = '1' + Sep + '1', 'Extended'); Check(Cast.ToString(e2) = '-0' + Sep + '23', 'Extended'); Check(Cast.ToString(c1) = '1' + Sep + '1', 'Currency'); Check(Cast.ToString(c2) = '-0' + Sep + '23', 'Currency'); Check(Cast.ToString(p1) = '123456', 'Comp'); Check(Cast.ToString(p2) = '654321', 'Comp'); Fs.DecimalSeparator := '/'; Sep := Fs.DecimalSeparator; { Locale mode } Check(Cast.ToString(s1, Fs) = '1' + Sep + '10000002384186', 'Single (NewLocale)'); Check(Cast.ToString(s2, Fs) = '-0' + Sep + '230000004172325', 'Single (NewLocale)'); Check(Cast.ToString(r1, Fs) = '1' + Sep + '1', 'Real (NewLocale)'); Check(Cast.ToString(r2, Fs) = '-0' + Sep + '23', 'Real (NewLocale)'); Check(Cast.ToString(u1, Fs) = '1' + Sep + '10000000000036', 'Real48 (NewLocale)'); Check(Cast.ToString(u2, Fs) = '-0' + Sep + '230000000000018', 'Real48 (NewLocale)'); Check(Cast.ToString(d1, Fs) = '1' + Sep + '1', 'Double (NewLocale)'); Check(Cast.ToString(d2, Fs) = '-0' + Sep + '23', 'Double (NewLocale)'); Check(Cast.ToString(e1, Fs) = '1' + Sep + '1', 'Extended (NewLocale)'); Check(Cast.ToString(e2, Fs) = '-0' + Sep + '23', 'Extended (NewLocale)'); Check(Cast.ToString(c1, Fs) = '1' + Sep + '1', 'Currency (NewLocale)'); Check(Cast.ToString(c2, Fs) = '-0' + Sep + '23', 'Currency (NewLocale)'); Check(Cast.ToString(p1, Fs) = '123456', 'Comp (NewLocale)'); Check(Cast.ToString(p2, Fs) = '654321', 'Comp (NewLocale)'); end; procedure TTestCasting.TestToStringCastingInts; begin Check(Cast.ToString(SmallInt(-125)) = '-125', 'SmallInt'); Check(Cast.ToString(SmallInt(10)) = '10', 'SmallInt'); Check(Cast.ToString(Byte(255)) = '255', 'Byte'); Check(Cast.ToString(Byte(0)) = '0', 'Byte'); Check(Cast.ToString(ShortInt(-125)) = '-125', 'ShortInt'); Check(Cast.ToString(ShortInt(10)) = '10', 'ShortInt'); Check(Cast.ToString(Word(8000)) = '8000', 'Word'); Check(Cast.ToString(Word(0)) = '0', 'Word'); Check(Cast.ToString(Integer(-40000)) = '-40000', 'Integer'); Check(Cast.ToString(Integer(10)) = '10', 'Integer'); Check(Cast.ToString(Cardinal(80000)) = '80000', 'Cardinal'); Check(Cast.ToString(Cardinal(0)) = '0', 'Cardinal'); Check(Cast.ToString(Int64(-40000)) = '-40000', 'Int64'); Check(Cast.ToString(Int64(10)) = '10', 'Int64'); Check(Cast.ToString(UInt64(80000)) = '80000', 'UInt64'); Check(Cast.ToString(UInt64(0)) = '0', 'UInt64'); Check(Cast.ToString(Pointer(1)) = '1', 'Pointer'); Check(Cast.ToString(Pointer($FF)) = '255', 'Pointer'); end; procedure TTestCasting.TestToStringCastingStrings; begin Check(Cast.ToString(ShortString('Test1')) = 'Test1', 'ShortString'); Check(Cast.ToString(ShortString('Te' + #0 + 'st2')) = 'Te' + #0 + 'st2', 'ShortString'); Check(Cast.ToString(String('Test1')) = 'Test1', 'String'); Check(Cast.ToString(String('Te' + #0 + 'st2')) = 'Te' + #0 + 'st2', 'String'); Check(Cast.ToString(Char(65)) = 'A', 'Char'); Check(Cast.ToString(String('_')) = '_', 'Char'); Check(Cast.ToString(PChar('Hello')) = 'Hello', 'PChar'); Check(Cast.ToString(PChar('A' + 'B' + 'C')) = 'ABC', 'PChar'); end; initialization TestFramework.RegisterTest(TTestCasting.Suite); end.
{****************************************************************************** Copyright (C) 2008-2012 by Boian Mitov mitov@mitov.com www.mitov.com www.igdiplus.org www.openwire.org 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. ******************************************************************************} {$IFNDEF EMBED_IGDI_PLUS} unit IGDIPlus; {$ENDIF} {$ALIGN ON} {$MINENUMSIZE 4} {$IFDEF VER130} // Delphi 5.0 {$DEFINE DELPHI5_DOWN} {$ENDIF} {$IFNDEF VER130} {$IFNDEF VER140} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} {$ENDIF} {$IFDEF VER230} // Delphi 16.0 {$DEFINE DELPHI16_UP} {$ENDIF} {$IFDEF VER240} // Delphi 17.0 {$DEFINE DELPHI16_UP} {$ENDIF} interface uses Windows, {$IFDEF DELPHI16_UP} // Delphi 16.0 System.UITypes, {$ENDIF} Classes, {$IFNDEF PURE_FMX} {$IFDEF DELPHI16_UP} // Delphi 16.0 VCL.Graphics, {$ELSE} // Delphi 16.0 Graphics, {$ENDIF} // Delphi 16.0 {$ENDIF} SysUtils, ActiveX; type {$IFNDEF DELPHI16_UP} // Delphi 16.0 INT16 = type Smallint; UINT16 = type Word; {$ENDIF} PUINT16 = ^UINT16; // UINT32 = type Cardinal; TGPSingleArray = array of Single; TGPByteArray = array of Byte; {$HPPEMIT '#pragma link "cbgdiplus.lib"'} {$HPPEMIT '__interface _di_IGPFontFamily;' } (**************************************************************************\ * * GDI+ Private Memory Management APIs * \**************************************************************************) (**************************************************************************\ * * GDI+ Enumeration Types * \**************************************************************************) //-------------------------------------------------------------------------- // Default bezier flattening tolerance in device pixels. //-------------------------------------------------------------------------- const {$EXTERNALSYM FlatnessDefault} FlatnessDefault = 0.25; //-------------------------------------------------------------------------- // Graphics and Container State cookies //-------------------------------------------------------------------------- type TGPGraphicsState = Cardinal; TGPGraphicsContainer = Cardinal; //-------------------------------------------------------------------------- // Fill mode constants //-------------------------------------------------------------------------- TGPFillMode = ( FillModeAlternate, // 0 FillModeWinding // 1 ); //-------------------------------------------------------------------------- // Quality mode constants //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPQualityMode = Integer; const QualityModeInvalid = -1; QualityModeDefault = 0; QualityModeLow = 1; // Best performance QualityModeHigh = 2; // Best rendering quality {$ELSE} TGPQualityMode = ( QualityModeInvalid = -1, QualityModeDefault = 0, QualityModeLow = 1, // Best performance QualityModeHigh = 2 // Best rendering quality ); {$ENDIF} //-------------------------------------------------------------------------- // Alpha Compositing mode constants //-------------------------------------------------------------------------- type TGPCompositingMode = ( CompositingModeSourceOver, // 0 CompositingModeSourceCopy // 1 ); //-------------------------------------------------------------------------- // Alpha Compositing quality constants //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPCompositingQuality = Integer; const CompositingQualityInvalid = QualityModeInvalid; CompositingQualityDefault = QualityModeDefault; CompositingQualityHighSpeed = QualityModeLow; CompositingQualityHighQuality = QualityModeHigh; CompositingQualityGammaCorrected = 3; CompositingQualityAssumeLinear = 4; {$ELSE} TGPCompositingQuality = ( CompositingQualityInvalid = Ord(QualityModeInvalid), CompositingQualityDefault = Ord(QualityModeDefault), CompositingQualityHighSpeed = Ord(QualityModeLow), CompositingQualityHighQuality = Ord(QualityModeHigh), CompositingQualityGammaCorrected, CompositingQualityAssumeLinear ); {$ENDIF} //-------------------------------------------------------------------------- // Unit constants //-------------------------------------------------------------------------- type TGPUnit = ( UnitWorld, // 0 -- World coordinate (non-physical unit) UnitDisplay, // 1 -- Variable -- for PageTransform only UnitPixel, // 2 -- Each unit is one device pixel. UnitPoint, // 3 -- Each unit is a printer's point, or 1/72 inch. UnitInch, // 4 -- Each unit is 1 inch. UnitDocument, // 5 -- Each unit is 1/300 inch. UnitMillimeter // 6 -- Each unit is 1 millimeter. ); //-------------------------------------------------------------------------- // MetafileFrameUnit // // The frameRect for creating a metafile can be specified in any of these // units. There is an extra frame unit value (MetafileFrameUnitGdi) so // that units can be supplied in the same units that GDI expects for // frame rects -- these units are in .01 (1/100ths) millimeter units // as defined by GDI. //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPMetafileFrameUnit = Integer; const MetafileFrameUnitPixel = 2; MetafileFrameUnitPoint = 3; MetafileFrameUnitInch = 4; MetafileFrameUnitDocument = 5; MetafileFrameUnitMillimeter = 6; MetafileFrameUnitGdi = 7; // GDI compatible .01 MM units {$ELSE} TGPMetafileFrameUnit = ( MetafileFrameUnitPixel = Ord(UnitPixel), MetafileFrameUnitPoint = Ord(UnitPoint), MetafileFrameUnitInch = Ord(UnitInch), MetafileFrameUnitDocument = Ord(UnitDocument), MetafileFrameUnitMillimeter = Ord(UnitMillimeter), MetafileFrameUnitGdi // GDI compatible .01 MM units ); {$ENDIF} //-------------------------------------------------------------------------- // Coordinate space identifiers //-------------------------------------------------------------------------- type TGPCoordinateSpace = ( CoordinateSpaceWorld, // 0 CoordinateSpacePage, // 1 CoordinateSpaceDevice // 2 ); //-------------------------------------------------------------------------- // Various wrap modes for brushes //-------------------------------------------------------------------------- TGPWrapMode = ( WrapModeTile, // 0 WrapModeTileFlipX, // 1 WrapModeTileFlipY, // 2 WrapModeTileFlipXY, // 3 WrapModeClamp // 4 ); //-------------------------------------------------------------------------- // Various hatch styles //-------------------------------------------------------------------------- TGPHatchStyle = ( HatchStyleHorizontal, // = 0, HatchStyleVertical, // = 1, HatchStyleForwardDiagonal, // = 2, HatchStyleBackwardDiagonal, // = 3, HatchStyleCross, // = 4, HatchStyleDiagonalCross, // = 5, HatchStyle05Percent, // = 6, HatchStyle10Percent, // = 7, HatchStyle20Percent, // = 8, HatchStyle25Percent, // = 9, HatchStyle30Percent, // = 10, HatchStyle40Percent, // = 11, HatchStyle50Percent, // = 12, HatchStyle60Percent, // = 13, HatchStyle70Percent, // = 14, HatchStyle75Percent, // = 15, HatchStyle80Percent, // = 16, HatchStyle90Percent, // = 17, HatchStyleLightDownwardDiagonal, // = 18, HatchStyleLightUpwardDiagonal, // = 19, HatchStyleDarkDownwardDiagonal, // = 20, HatchStyleDarkUpwardDiagonal, // = 21, HatchStyleWideDownwardDiagonal, // = 22, HatchStyleWideUpwardDiagonal, // = 23, HatchStyleLightVertical, // = 24, HatchStyleLightHorizontal, // = 25, HatchStyleNarrowVertical, // = 26, HatchStyleNarrowHorizontal, // = 27, HatchStyleDarkVertical, // = 28, HatchStyleDarkHorizontal, // = 29, HatchStyleDashedDownwardDiagonal, // = 30, HatchStyleDashedUpwardDiagonal, // = 31, HatchStyleDashedHorizontal, // = 32, HatchStyleDashedVertical, // = 33, HatchStyleSmallConfetti, // = 34, HatchStyleLargeConfetti, // = 35, HatchStyleZigZag, // = 36, HatchStyleWave, // = 37, HatchStyleDiagonalBrick, // = 38, HatchStyleHorizontalBrick, // = 39, HatchStyleWeave, // = 40, HatchStylePlaid, // = 41, HatchStyleDivot, // = 42, HatchStyleDottedGrid, // = 43, HatchStyleDottedDiamond, // = 44, HatchStyleShingle, // = 45, HatchStyleTrellis, // = 46, HatchStyleSphere, // = 47, HatchStyleSmallGrid, // = 48, HatchStyleSmallCheckerBoard, // = 49, HatchStyleLargeCheckerBoard, // = 50, HatchStyleOutlinedDiamond, // = 51, HatchStyleSolidDiamond // = 52, ); const HatchStyleTotal = 53; const HatchStyleLargeGrid = HatchStyleCross; // 4 HatchStyleMin = HatchStyleHorizontal; HatchStyleMax = HatchStyleSolidDiamond; //-------------------------------------------------------------------------- // Dash style constants //-------------------------------------------------------------------------- type TGPDashStyle = ( DashStyleSolid, // 0 DashStyleDash, // 1 DashStyleDot, // 2 DashStyleDashDot, // 3 DashStyleDashDotDot, // 4 DashStyleCustom // 5 ); //-------------------------------------------------------------------------- // Dash cap constants //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPDashCap = Integer; const DashCapFlat = 0; DashCapRound = 2; DashCapTriangle = 3; {$ELSE} TGPDashCap = ( DashCapFlat = 0, DashCapRound = 2, DashCapTriangle = 3 ); {$ENDIF} //-------------------------------------------------------------------------- // Line cap constants (only the lowest 8 bits are used). //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} type TGPLineCap = Integer; const LineCapFlat = 0; LineCapSquare = 1; LineCapRound = 2; LineCapTriangle = 3; LineCapNoAnchor = $10; // corresponds to flat cap LineCapSquareAnchor = $11; // corresponds to square cap LineCapRoundAnchor = $12; // corresponds to round cap LineCapDiamondAnchor = $13; // corresponds to triangle cap LineCapArrowAnchor = $14; // no correspondence LineCapCustom = $ff; // custom cap LineCapAnchorMask = $f0; // mask to check for anchor or not. {$ELSE} TGPLineCap = ( LineCapFlat = 0, LineCapSquare = 1, LineCapRound = 2, LineCapTriangle = 3, LineCapNoAnchor = $10, // corresponds to flat cap LineCapSquareAnchor = $11, // corresponds to square cap LineCapRoundAnchor = $12, // corresponds to round cap LineCapDiamondAnchor = $13, // corresponds to triangle cap LineCapArrowAnchor = $14, // no correspondence LineCapCustom = $ff, // custom cap LineCapAnchorMask = $f0 // mask to check for anchor or not. ); {$ENDIF} //-------------------------------------------------------------------------- // Custom Line cap type constants //-------------------------------------------------------------------------- type TGPCustomLineCapType = ( CustomLineCapTypeDefault, CustomLineCapTypeAdjustableArrow ); //-------------------------------------------------------------------------- // Line join constants //-------------------------------------------------------------------------- TGPLineJoin = ( LineJoinMiter, LineJoinBevel, LineJoinRound, LineJoinMiterClipped ); //-------------------------------------------------------------------------- // Path point types (only the lowest 8 bits are used.) // The lowest 3 bits are interpreted as point type // The higher 5 bits are reserved for flags. //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPPathPointType = Byte; const PathPointTypeStart : Byte = $00; // move PathPointTypeLine : Byte = $01; // line PathPointTypeBezier : Byte = $03; // default Bezier (= cubic Bezier) PathPointTypePathTypeMask : Byte = $07; // type mask (lowest 3 bits). PathPointTypeDashMode : Byte = $10; // currently in dash mode. PathPointTypePathMarker : Byte = $20; // a marker for the path. PathPointTypeCloseSubpath : Byte = $80; // closed flag // Path types used for advanced path. PathPointTypeBezier3 : Byte = $03; // cubic Bezier {$ELSE} {$Z1} TGPPathPointType = ( PathPointTypeStart = $00, // move PathPointTypeLine = $01, // line PathPointTypeBezier = $03, // default Bezier (= cubic Bezier) PathPointTypePathTypeMask = $07, // type mask (lowest 3 bits). PathPointTypeDashMode = $10, // currently in dash mode. PathPointTypePathMarker = $20, // a marker for the path. PathPointTypeCloseSubpath = $80, // closed flag // Path types used for advanced path. PathPointTypeBezier3 = $03 // cubic Bezier ); {$Z4} {$ENDIF} //-------------------------------------------------------------------------- // WarpMode constants //-------------------------------------------------------------------------- type TGPWarpMode = ( WarpModePerspective, // 0 WarpModeBilinear // 1 ); //-------------------------------------------------------------------------- // LineGradient Mode //-------------------------------------------------------------------------- TGPLinearGradientMode = ( LinearGradientModeHorizontal, // 0 LinearGradientModeVertical, // 1 LinearGradientModeForwardDiagonal, // 2 LinearGradientModeBackwardDiagonal // 3 ); //-------------------------------------------------------------------------- // Region Comine Modes //-------------------------------------------------------------------------- TGPCombineMode = ( CombineModeReplace, // 0 CombineModeIntersect, // 1 CombineModeUnion, // 2 CombineModeXor, // 3 CombineModeExclude, // 4 CombineModeComplement // 5 (Exclude From) ); //-------------------------------------------------------------------------- // Image types //-------------------------------------------------------------------------- TGPImageType = ( ImageTypeUnknown, // 0 ImageTypeBitmap, // 1 ImageTypeMetafile // 2 ); //-------------------------------------------------------------------------- // Interpolation modes //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPInterpolationMode = Integer; const InterpolationModeInvalid = QualityModeInvalid; InterpolationModeDefault = QualityModeDefault; InterpolationModeLowQuality = QualityModeLow; InterpolationModeHighQuality = QualityModeHigh; InterpolationModeBilinear = 3; InterpolationModeBicubic = 4; InterpolationModeNearestNeighbor = 5; InterpolationModeHighQualityBilinear = 6; InterpolationModeHighQualityBicubic = 7; {$ELSE} TGPInterpolationMode = ( InterpolationModeInvalid = Ord(QualityModeInvalid), InterpolationModeDefault = Ord(QualityModeDefault), InterpolationModeLowQuality = Ord(QualityModeLow), InterpolationModeHighQuality = Ord(QualityModeHigh), InterpolationModeBilinear, InterpolationModeBicubic, InterpolationModeNearestNeighbor, InterpolationModeHighQualityBilinear, InterpolationModeHighQualityBicubic ); {$ENDIF} //-------------------------------------------------------------------------- // Pen types //-------------------------------------------------------------------------- type TGPPenAlignment = ( PenAlignmentCenter, PenAlignmentInset ); //-------------------------------------------------------------------------- // Brush types //-------------------------------------------------------------------------- TGPBrushType = ( BrushTypeSolidColor, BrushTypeHatchFill, BrushTypeTextureFill, BrushTypePathGradient, BrushTypeLinearGradient ); //-------------------------------------------------------------------------- // Pen's Fill types //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPPenType = Integer; const PenTypeSolidColor = 0; PenTypeHatchFill = 1; PenTypeTextureFill = 2; PenTypePathGradient = 3; PenTypeLinearGradient = 4; PenTypeUnknown = -1; {$ELSE} TGPPenType = ( PenTypeSolidColor = Ord(BrushTypeSolidColor), PenTypeHatchFill = Ord(BrushTypeHatchFill), PenTypeTextureFill = Ord(BrushTypeTextureFill), PenTypePathGradient = Ord(BrushTypePathGradient), PenTypeLinearGradient = Ord(BrushTypeLinearGradient), PenTypeUnknown = -1 ); {$ENDIF} //-------------------------------------------------------------------------- // Matrix Order //-------------------------------------------------------------------------- type TGPMatrixOrder = ( MatrixOrderPrepend, MatrixOrderAppend ); //-------------------------------------------------------------------------- // Generic font families //-------------------------------------------------------------------------- TGPGenericFontFamily = ( GenericFontFamilySerif, GenericFontFamilySansSerif, GenericFontFamilyMonospace ); //-------------------------------------------------------------------------- // FontStyle: face types and common styles //-------------------------------------------------------------------------- type { FontStyle = Integer; const FontStyleRegular = Integer(0); FontStyleBold = Integer(1); FontStyleItalic = Integer(2); FontStyleBoldItalic = Integer(3); FontStyleUnderline = Integer(4); FontStyleStrikeout = Integer(8); Type TGPFontStyle = FontStyle; } //--------------------------------------------------------------------------- // Smoothing Mode //--------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPSmoothingMode = Integer; const SmoothingModeInvalid = QualityModeInvalid; SmoothingModeDefault = QualityModeDefault; SmoothingModeHighSpeed = QualityModeLow; SmoothingModeHighQuality = QualityModeHigh; SmoothingModeNone = 3; SmoothingModeAntiAlias = 4; SmoothingModeAntiAlias8x4 = SmoothingModeAntiAlias; SmoothingModeAntiAlias8x8 = 5; {$ELSE} TGPSmoothingMode = ( SmoothingModeInvalid = Ord(QualityModeInvalid), SmoothingModeDefault = Ord(QualityModeDefault), SmoothingModeHighSpeed = Ord(QualityModeLow), SmoothingModeHighQuality = Ord(QualityModeHigh), SmoothingModeNone, SmoothingModeAntiAlias, SmoothingModeAntiAlias8x4 = SmoothingModeAntiAlias, SmoothingModeAntiAlias8x8 = 5 ); {$ENDIF} //--------------------------------------------------------------------------- // Pixel Format Mode //--------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} type TGPPixelOffsetMode = Integer; const PixelOffsetModeInvalid = QualityModeInvalid; PixelOffsetModeDefault = QualityModeDefault; PixelOffsetModeHighSpeed = QualityModeLow; PixelOffsetModeHighQuality = QualityModeHigh; PixelOffsetModeNone = 3; // No pixel offset PixelOffsetModeHalf = 4; // Offset by -0.5, -0.5 for fast anti-alias perf {$ELSE} TGPPixelOffsetMode = ( PixelOffsetModeInvalid = Ord(QualityModeInvalid), PixelOffsetModeDefault = Ord(QualityModeDefault), PixelOffsetModeHighSpeed = Ord(QualityModeLow), PixelOffsetModeHighQuality = Ord(QualityModeHigh), PixelOffsetModeNone, // No pixel offset PixelOffsetModeHalf // Offset by -0.5, -0.5 for fast anti-alias perf ); {$ENDIF} //--------------------------------------------------------------------------- // Text Rendering Hint //--------------------------------------------------------------------------- type TGPTextRenderingHint = ( TextRenderingHintSystemDefault, // Glyph with system default rendering hint TextRenderingHintSingleBitPerPixelGridFit, // Glyph bitmap with hinting TextRenderingHintSingleBitPerPixel, // Glyph bitmap without hinting TextRenderingHintAntiAliasGridFit, // Glyph anti-alias bitmap with hinting TextRenderingHintAntiAlias, // Glyph anti-alias bitmap without hinting TextRenderingHintClearTypeGridFit // Glyph CT bitmap with hinting ); //--------------------------------------------------------------------------- // Metafile Types //--------------------------------------------------------------------------- TGPMetafileType = ( MetafileTypeInvalid, // Invalid metafile MetafileTypeWmf, // Standard WMF MetafileTypeWmfPlaceable, // Placeable WMF MetafileTypeEmf, // EMF (not EMF+) MetafileTypeEmfPlusOnly, // EMF+ without dual, down-level records MetafileTypeEmfPlusDual // EMF+ with dual, down-level records ); //--------------------------------------------------------------------------- // Specifies the type of EMF to record //--------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPEmfType = Integer; const EmfTypeEmfOnly = Ord(MetafileTypeEmf); // no EMF+, only EMF EmfTypeEmfPlusOnly = Ord(MetafileTypeEmfPlusOnly); // no EMF, only EMF+ EmfTypeEmfPlusDual = Ord(MetafileTypeEmfPlusDual); // both EMF+ and EMF {$ELSE} TGPEmfType = ( EmfTypeEmfOnly = Ord(MetafileTypeEmf), // no EMF+, only EMF EmfTypeEmfPlusOnly = Ord(MetafileTypeEmfPlusOnly), // no EMF, only EMF+ EmfTypeEmfPlusDual = Ord(MetafileTypeEmfPlusDual) // both EMF+ and EMF ); {$ENDIF} //--------------------------------------------------------------------------- // EMF+ Persistent object types //--------------------------------------------------------------------------- type TGPObjectType = ( ObjectTypeInvalid, ObjectTypeBrush, ObjectTypePen, ObjectTypePath, ObjectTypeRegion, ObjectTypeImage, ObjectTypeFont, ObjectTypeStringFormat, ObjectTypeImageAttributes, ObjectTypeCustomLineCap ); const ObjectTypeMax = ObjectTypeCustomLineCap; ObjectTypeMin = ObjectTypeBrush; function ObjectTypeIsValid(type_: TGPObjectType) : Boolean; //--------------------------------------------------------------------------- // EMF+ Records //--------------------------------------------------------------------------- // We have to change the WMF record numbers so that they don't conflict with // the EMF and EMF+ record numbers. const GDIP_EMFPLUS_RECORD_BASE = $00004000; {$EXTERNALSYM GDIP_EMFPLUS_RECORD_BASE} GDIP_WMF_RECORD_BASE = $00010000; {$EXTERNALSYM GDIP_WMF_RECORD_BASE} (*$HPPEMIT 'static const Shortint BCBGDIP_EMFPLUS_RECORD_BASE = 0x00004000;' *) (*$HPPEMIT 'static const Shortint BCBGDIP_WMF_RECORD_BASE = 0x00010000;' *) // macros function GDIP_WMF_RECORD_TO_EMFPLUS(n: Integer) : Integer; function GDIP_EMFPLUS_RECORD_TO_WMF(n: Integer) : Integer; function GDIP_IS_WMF_RECORDTYPE(n: Integer) : Boolean; {$IFDEF DELPHI5_DOWN} type TGPEmfPlusRecordType = Integer; // Since we have to enumerate GDI records right along with GDI+ records, // We list all the GDI records here so that they can be part of the // same enumeration type which is used in the enumeration callback. const WmfRecordTypeSetBkColor = (META_SETBKCOLOR or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetBkMode = (META_SETBKMODE or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetMapMode = (META_SETMAPMODE or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetROP2 = (META_SETROP2 or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetRelAbs = (META_SETRELABS or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetPolyFillMode = (META_SETPOLYFILLMODE or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetStretchBltMode = (META_SETSTRETCHBLTMODE or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetTextCharExtra = (META_SETTEXTCHAREXTRA or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetTextColor = (META_SETTEXTCOLOR or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetTextJustification = (META_SETTEXTJUSTIFICATION or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetWindowOrg = (META_SETWINDOWORG or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetWindowExt = (META_SETWINDOWEXT or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetViewportOrg = (META_SETVIEWPORTORG or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetViewportExt = (META_SETVIEWPORTEXT or GDIP_WMF_RECORD_BASE); WmfRecordTypeOffsetWindowOrg = (META_OFFSETWINDOWORG or GDIP_WMF_RECORD_BASE); WmfRecordTypeScaleWindowExt = (META_SCALEWINDOWEXT or GDIP_WMF_RECORD_BASE); WmfRecordTypeOffsetViewportOrg = (META_OFFSETVIEWPORTORG or GDIP_WMF_RECORD_BASE); WmfRecordTypeScaleViewportExt = (META_SCALEVIEWPORTEXT or GDIP_WMF_RECORD_BASE); WmfRecordTypeLineTo = (META_LINETO or GDIP_WMF_RECORD_BASE); WmfRecordTypeMoveTo = (META_MOVETO or GDIP_WMF_RECORD_BASE); WmfRecordTypeExcludeClipRect = (META_EXCLUDECLIPRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeIntersectClipRect = (META_INTERSECTCLIPRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeArc = (META_ARC or GDIP_WMF_RECORD_BASE); WmfRecordTypeEllipse = (META_ELLIPSE or GDIP_WMF_RECORD_BASE); WmfRecordTypeFloodFill = (META_FLOODFILL or GDIP_WMF_RECORD_BASE); WmfRecordTypePie = (META_PIE or GDIP_WMF_RECORD_BASE); WmfRecordTypeRectangle = (META_RECTANGLE or GDIP_WMF_RECORD_BASE); WmfRecordTypeRoundRect = (META_ROUNDRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypePatBlt = (META_PATBLT or GDIP_WMF_RECORD_BASE); WmfRecordTypeSaveDC = (META_SAVEDC or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetPixel = (META_SETPIXEL or GDIP_WMF_RECORD_BASE); WmfRecordTypeOffsetClipRgn = (META_OFFSETCLIPRGN or GDIP_WMF_RECORD_BASE); WmfRecordTypeTextOut = (META_TEXTOUT or GDIP_WMF_RECORD_BASE); WmfRecordTypeBitBlt = (META_BITBLT or GDIP_WMF_RECORD_BASE); WmfRecordTypeStretchBlt = (META_STRETCHBLT or GDIP_WMF_RECORD_BASE); WmfRecordTypePolygon = (META_POLYGON or GDIP_WMF_RECORD_BASE); WmfRecordTypePolyline = (META_POLYLINE or GDIP_WMF_RECORD_BASE); WmfRecordTypeEscape = (META_ESCAPE or GDIP_WMF_RECORD_BASE); WmfRecordTypeRestoreDC = (META_RESTOREDC or GDIP_WMF_RECORD_BASE); WmfRecordTypeFillRegion = (META_FILLREGION or GDIP_WMF_RECORD_BASE); WmfRecordTypeFrameRegion = (META_FRAMEREGION or GDIP_WMF_RECORD_BASE); WmfRecordTypeInvertRegion = (META_INVERTREGION or GDIP_WMF_RECORD_BASE); WmfRecordTypePaintRegion = (META_PAINTREGION or GDIP_WMF_RECORD_BASE); WmfRecordTypeSelectClipRegion = (META_SELECTCLIPREGION or GDIP_WMF_RECORD_BASE); WmfRecordTypeSelectObject = (META_SELECTOBJECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetTextAlign = (META_SETTEXTALIGN or GDIP_WMF_RECORD_BASE); WmfRecordTypeDrawText = ($062F or GDIP_WMF_RECORD_BASE); // META_DRAWTEXT WmfRecordTypeChord = (META_CHORD or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetMapperFlags = (META_SETMAPPERFLAGS or GDIP_WMF_RECORD_BASE); WmfRecordTypeExtTextOut = (META_EXTTEXTOUT or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetDIBToDev = (META_SETDIBTODEV or GDIP_WMF_RECORD_BASE); WmfRecordTypeSelectPalette = (META_SELECTPALETTE or GDIP_WMF_RECORD_BASE); WmfRecordTypeRealizePalette = (META_REALIZEPALETTE or GDIP_WMF_RECORD_BASE); WmfRecordTypeAnimatePalette = (META_ANIMATEPALETTE or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetPalEntries = (META_SETPALENTRIES or GDIP_WMF_RECORD_BASE); WmfRecordTypePolyPolygon = (META_POLYPOLYGON or GDIP_WMF_RECORD_BASE); WmfRecordTypeResizePalette = (META_RESIZEPALETTE or GDIP_WMF_RECORD_BASE); WmfRecordTypeDIBBitBlt = (META_DIBBITBLT or GDIP_WMF_RECORD_BASE); WmfRecordTypeDIBStretchBlt = (META_DIBSTRETCHBLT or GDIP_WMF_RECORD_BASE); WmfRecordTypeDIBCreatePatternBrush = (META_DIBCREATEPATTERNBRUSH or GDIP_WMF_RECORD_BASE); WmfRecordTypeStretchDIB = (META_STRETCHDIB or GDIP_WMF_RECORD_BASE); WmfRecordTypeExtFloodFill = (META_EXTFLOODFILL or GDIP_WMF_RECORD_BASE); WmfRecordTypeSetLayout = ($0149 or GDIP_WMF_RECORD_BASE); // META_SETLAYOUT WmfRecordTypeResetDC = ($014C or GDIP_WMF_RECORD_BASE); // META_RESETDC WmfRecordTypeStartDoc = ($014D or GDIP_WMF_RECORD_BASE); // META_STARTDOC WmfRecordTypeStartPage = ($004F or GDIP_WMF_RECORD_BASE); // META_STARTPAGE WmfRecordTypeEndPage = ($0050 or GDIP_WMF_RECORD_BASE); // META_ENDPAGE WmfRecordTypeAbortDoc = ($0052 or GDIP_WMF_RECORD_BASE); // META_ABORTDOC WmfRecordTypeEndDoc = ($005E or GDIP_WMF_RECORD_BASE); // META_ENDDOC WmfRecordTypeDeleteObject = (META_DELETEOBJECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreatePalette = (META_CREATEPALETTE or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreateBrush = ($00F8 or GDIP_WMF_RECORD_BASE); // META_CREATEBRUSH WmfRecordTypeCreatePatternBrush = (META_CREATEPATTERNBRUSH or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreatePenIndirect = (META_CREATEPENINDIRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreateFontIndirect = (META_CREATEFONTINDIRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreateBrushIndirect = (META_CREATEBRUSHINDIRECT or GDIP_WMF_RECORD_BASE); WmfRecordTypeCreateBitmapIndirect = ($02FD or GDIP_WMF_RECORD_BASE); // META_CREATEBITMAPINDIRECT WmfRecordTypeCreateBitmap = ($06FE or GDIP_WMF_RECORD_BASE); // META_CREATEBITMAP WmfRecordTypeCreateRegion = (META_CREATEREGION or GDIP_WMF_RECORD_BASE); EmfRecordTypeHeader = EMR_HEADER; EmfRecordTypePolyBezier = EMR_POLYBEZIER; EmfRecordTypePolygon = EMR_POLYGON; EmfRecordTypePolyline = EMR_POLYLINE; EmfRecordTypePolyBezierTo = EMR_POLYBEZIERTO; EmfRecordTypePolyLineTo = EMR_POLYLINETO; EmfRecordTypePolyPolyline = EMR_POLYPOLYLINE; EmfRecordTypePolyPolygon = EMR_POLYPOLYGON; EmfRecordTypeSetWindowExtEx = EMR_SETWINDOWEXTEX; EmfRecordTypeSetWindowOrgEx = EMR_SETWINDOWORGEX; EmfRecordTypeSetViewportExtEx = EMR_SETVIEWPORTEXTEX; EmfRecordTypeSetViewportOrgEx = EMR_SETVIEWPORTORGEX; EmfRecordTypeSetBrushOrgEx = EMR_SETBRUSHORGEX; EmfRecordTypeEOF = EMR_EOF; EmfRecordTypeSetPixelV = EMR_SETPIXELV; EmfRecordTypeSetMapperFlags = EMR_SETMAPPERFLAGS; EmfRecordTypeSetMapMode = EMR_SETMAPMODE; EmfRecordTypeSetBkMode = EMR_SETBKMODE; EmfRecordTypeSetPolyFillMode = EMR_SETPOLYFILLMODE; EmfRecordTypeSetROP2 = EMR_SETROP2; EmfRecordTypeSetStretchBltMode = EMR_SETSTRETCHBLTMODE; EmfRecordTypeSetTextAlign = EMR_SETTEXTALIGN; EmfRecordTypeSetColorAdjustment = EMR_SETCOLORADJUSTMENT; EmfRecordTypeSetTextColor = EMR_SETTEXTCOLOR; EmfRecordTypeSetBkColor = EMR_SETBKCOLOR; EmfRecordTypeOffsetClipRgn = EMR_OFFSETCLIPRGN; EmfRecordTypeMoveToEx = EMR_MOVETOEX; EmfRecordTypeSetMetaRgn = EMR_SETMETARGN; EmfRecordTypeExcludeClipRect = EMR_EXCLUDECLIPRECT; EmfRecordTypeIntersectClipRect = EMR_INTERSECTCLIPRECT; EmfRecordTypeScaleViewportExtEx = EMR_SCALEVIEWPORTEXTEX; EmfRecordTypeScaleWindowExtEx = EMR_SCALEWINDOWEXTEX; EmfRecordTypeSaveDC = EMR_SAVEDC; EmfRecordTypeRestoreDC = EMR_RESTOREDC; EmfRecordTypeSetWorldTransform = EMR_SETWORLDTRANSFORM; EmfRecordTypeModifyWorldTransform = EMR_MODIFYWORLDTRANSFORM; EmfRecordTypeSelectObject = EMR_SELECTOBJECT; EmfRecordTypeCreatePen = EMR_CREATEPEN; EmfRecordTypeCreateBrushIndirect = EMR_CREATEBRUSHINDIRECT; EmfRecordTypeDeleteObject = EMR_DELETEOBJECT; EmfRecordTypeAngleArc = EMR_ANGLEARC; EmfRecordTypeEllipse = EMR_ELLIPSE; EmfRecordTypeRectangle = EMR_RECTANGLE; EmfRecordTypeRoundRect = EMR_ROUNDRECT; EmfRecordTypeArc = EMR_ARC; EmfRecordTypeChord = EMR_CHORD; EmfRecordTypePie = EMR_PIE; EmfRecordTypeSelectPalette = EMR_SELECTPALETTE; EmfRecordTypeCreatePalette = EMR_CREATEPALETTE; EmfRecordTypeSetPaletteEntries = EMR_SETPALETTEENTRIES; EmfRecordTypeResizePalette = EMR_RESIZEPALETTE; EmfRecordTypeRealizePalette = EMR_REALIZEPALETTE; EmfRecordTypeExtFloodFill = EMR_EXTFLOODFILL; EmfRecordTypeLineTo = EMR_LINETO; EmfRecordTypeArcTo = EMR_ARCTO; EmfRecordTypePolyDraw = EMR_POLYDRAW; EmfRecordTypeSetArcDirection = EMR_SETARCDIRECTION; EmfRecordTypeSetMiterLimit = EMR_SETMITERLIMIT; EmfRecordTypeBeginPath = EMR_BEGINPATH; EmfRecordTypeEndPath = EMR_ENDPATH; EmfRecordTypeCloseFigure = EMR_CLOSEFIGURE; EmfRecordTypeFillPath = EMR_FILLPATH; EmfRecordTypeStrokeAndFillPath = EMR_STROKEANDFILLPATH; EmfRecordTypeStrokePath = EMR_STROKEPATH; EmfRecordTypeFlattenPath = EMR_FLATTENPATH; EmfRecordTypeWidenPath = EMR_WIDENPATH; EmfRecordTypeSelectClipPath = EMR_SELECTCLIPPATH; EmfRecordTypeAbortPath = EMR_ABORTPATH; EmfRecordTypeReserved_069 = 69; // Not Used EmfRecordTypeGdiComment = EMR_GDICOMMENT; EmfRecordTypeFillRgn = EMR_FILLRGN; EmfRecordTypeFrameRgn = EMR_FRAMERGN; EmfRecordTypeInvertRgn = EMR_INVERTRGN; EmfRecordTypePaintRgn = EMR_PAINTRGN; EmfRecordTypeExtSelectClipRgn = EMR_EXTSELECTCLIPRGN; EmfRecordTypeBitBlt = EMR_BITBLT; EmfRecordTypeStretchBlt = EMR_STRETCHBLT; EmfRecordTypeMaskBlt = EMR_MASKBLT; EmfRecordTypePlgBlt = EMR_PLGBLT; EmfRecordTypeSetDIBitsToDevice = EMR_SETDIBITSTODEVICE; EmfRecordTypeStretchDIBits = EMR_STRETCHDIBITS; EmfRecordTypeExtCreateFontIndirect = EMR_EXTCREATEFONTINDIRECTW; EmfRecordTypeExtTextOutA = EMR_EXTTEXTOUTA; EmfRecordTypeExtTextOutW = EMR_EXTTEXTOUTW; EmfRecordTypePolyBezier16 = EMR_POLYBEZIER16; EmfRecordTypePolygon16 = EMR_POLYGON16; EmfRecordTypePolyline16 = EMR_POLYLINE16; EmfRecordTypePolyBezierTo16 = EMR_POLYBEZIERTO16; EmfRecordTypePolylineTo16 = EMR_POLYLINETO16; EmfRecordTypePolyPolyline16 = EMR_POLYPOLYLINE16; EmfRecordTypePolyPolygon16 = EMR_POLYPOLYGON16; EmfRecordTypePolyDraw16 = EMR_POLYDRAW16; EmfRecordTypeCreateMonoBrush = EMR_CREATEMONOBRUSH; EmfRecordTypeCreateDIBPatternBrushPt = EMR_CREATEDIBPATTERNBRUSHPT; EmfRecordTypeExtCreatePen = EMR_EXTCREATEPEN; EmfRecordTypePolyTextOutA = EMR_POLYTEXTOUTA; EmfRecordTypePolyTextOutW = EMR_POLYTEXTOUTW; EmfRecordTypeSetICMMode = 98; // EMR_SETICMMODE, EmfRecordTypeCreateColorSpace = 99; // EMR_CREATECOLORSPACE, EmfRecordTypeSetColorSpace = 100; // EMR_SETCOLORSPACE, EmfRecordTypeDeleteColorSpace = 101; // EMR_DELETECOLORSPACE, EmfRecordTypeGLSRecord = 102; // EMR_GLSRECORD, EmfRecordTypeGLSBoundedRecord = 103; // EMR_GLSBOUNDEDRECORD, EmfRecordTypePixelFormat = 104; // EMR_PIXELFORMAT, EmfRecordTypeDrawEscape = 105; // EMR_RESERVED_105, EmfRecordTypeExtEscape = 106; // EMR_RESERVED_106, EmfRecordTypeStartDoc = 107; // EMR_RESERVED_107, EmfRecordTypeSmallTextOut = 108; // EMR_RESERVED_108, EmfRecordTypeForceUFIMapping = 109; // EMR_RESERVED_109, EmfRecordTypeNamedEscape = 110; // EMR_RESERVED_110, EmfRecordTypeColorCorrectPalette = 111; // EMR_COLORCORRECTPALETTE, EmfRecordTypeSetICMProfileA = 112; // EMR_SETICMPROFILEA, EmfRecordTypeSetICMProfileW = 113; // EMR_SETICMPROFILEW, EmfRecordTypeAlphaBlend = 114; // EMR_ALPHABLEND, EmfRecordTypeSetLayout = 115; // EMR_SETLAYOUT, EmfRecordTypeTransparentBlt = 116; // EMR_TRANSPARENTBLT, EmfRecordTypeReserved_117 = 117; // Not Used EmfRecordTypeGradientFill = 118; // EMR_GRADIENTFILL, EmfRecordTypeSetLinkedUFIs = 119; // EMR_RESERVED_119, EmfRecordTypeSetTextJustification = 120; // EMR_RESERVED_120, EmfRecordTypeColorMatchToTargetW = 121; // EMR_COLORMATCHTOTARGETW, EmfRecordTypeCreateColorSpaceW = 122; // EMR_CREATECOLORSPACEW, EmfRecordTypeMax = 122; EmfRecordTypeMin = 1; // That is the END of the GDI EMF records. // Now we start the list of EMF+ records. We leave quite // a bit of room here for the addition of any new GDI // records that may be added later. EmfPlusRecordTypeInvalid = GDIP_EMFPLUS_RECORD_BASE; EmfPlusRecordTypeHeader = GDIP_EMFPLUS_RECORD_BASE + 1; EmfPlusRecordTypeEndOfFile = GDIP_EMFPLUS_RECORD_BASE + 2; EmfPlusRecordTypeComment = GDIP_EMFPLUS_RECORD_BASE + 3; EmfPlusRecordTypeGetDC = GDIP_EMFPLUS_RECORD_BASE + 4; EmfPlusRecordTypeMultiFormatStart = GDIP_EMFPLUS_RECORD_BASE + 5; EmfPlusRecordTypeMultiFormatSection = GDIP_EMFPLUS_RECORD_BASE + 6; EmfPlusRecordTypeMultiFormatEnd = GDIP_EMFPLUS_RECORD_BASE + 7; // For all persistent objects EmfPlusRecordTypeObject = GDIP_EMFPLUS_RECORD_BASE + 8; // Drawing Records EmfPlusRecordTypeClear = GDIP_EMFPLUS_RECORD_BASE + 9; EmfPlusRecordTypeFillRects = GDIP_EMFPLUS_RECORD_BASE + 10; EmfPlusRecordTypeDrawRects = GDIP_EMFPLUS_RECORD_BASE + 11; EmfPlusRecordTypeFillPolygon = GDIP_EMFPLUS_RECORD_BASE + 12; EmfPlusRecordTypeDrawLines = GDIP_EMFPLUS_RECORD_BASE + 13; EmfPlusRecordTypeFillEllipse = GDIP_EMFPLUS_RECORD_BASE + 14; EmfPlusRecordTypeDrawEllipse = GDIP_EMFPLUS_RECORD_BASE + 15; EmfPlusRecordTypeFillPie = GDIP_EMFPLUS_RECORD_BASE + 16; EmfPlusRecordTypeDrawPie = GDIP_EMFPLUS_RECORD_BASE + 17; EmfPlusRecordTypeDrawArc = GDIP_EMFPLUS_RECORD_BASE + 18; EmfPlusRecordTypeFillRegion = GDIP_EMFPLUS_RECORD_BASE + 19; EmfPlusRecordTypeFillPath = GDIP_EMFPLUS_RECORD_BASE + 20; EmfPlusRecordTypeDrawPath = GDIP_EMFPLUS_RECORD_BASE + 21; EmfPlusRecordTypeFillClosedCurve = GDIP_EMFPLUS_RECORD_BASE + 22; EmfPlusRecordTypeDrawClosedCurve = GDIP_EMFPLUS_RECORD_BASE + 23; EmfPlusRecordTypeDrawCurve = GDIP_EMFPLUS_RECORD_BASE + 24; EmfPlusRecordTypeDrawBeziers = GDIP_EMFPLUS_RECORD_BASE + 25; EmfPlusRecordTypeDrawImage = GDIP_EMFPLUS_RECORD_BASE + 26; EmfPlusRecordTypeDrawImagePoints = GDIP_EMFPLUS_RECORD_BASE + 27; EmfPlusRecordTypeDrawString = GDIP_EMFPLUS_RECORD_BASE + 28; // Graphics State Records EmfPlusRecordTypeSetRenderingOrigin = GDIP_EMFPLUS_RECORD_BASE + 29; EmfPlusRecordTypeSetAntiAliasMode = GDIP_EMFPLUS_RECORD_BASE + 30; EmfPlusRecordTypeSetTextRenderingHint = GDIP_EMFPLUS_RECORD_BASE + 31; EmfPlusRecordTypeSetTextContrast = GDIP_EMFPLUS_RECORD_BASE + 32; EmfPlusRecordTypeSetInterpolationMode = GDIP_EMFPLUS_RECORD_BASE + 33; EmfPlusRecordTypeSetPixelOffsetMode = GDIP_EMFPLUS_RECORD_BASE + 34; EmfPlusRecordTypeSetCompositingMode = GDIP_EMFPLUS_RECORD_BASE + 35; EmfPlusRecordTypeSetCompositingQuality = GDIP_EMFPLUS_RECORD_BASE + 36; EmfPlusRecordTypeSave = GDIP_EMFPLUS_RECORD_BASE + 37; EmfPlusRecordTypeRestore = GDIP_EMFPLUS_RECORD_BASE + 38; EmfPlusRecordTypeBeginContainer = GDIP_EMFPLUS_RECORD_BASE + 39; EmfPlusRecordTypeBeginContainerNoParams = GDIP_EMFPLUS_RECORD_BASE + 40; EmfPlusRecordTypeEndContainer = GDIP_EMFPLUS_RECORD_BASE + 41; EmfPlusRecordTypeSetWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 42; EmfPlusRecordTypeResetWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 43; EmfPlusRecordTypeMultiplyWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 44; EmfPlusRecordTypeTranslateWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 45; EmfPlusRecordTypeScaleWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 46; EmfPlusRecordTypeRotateWorldTransform = GDIP_EMFPLUS_RECORD_BASE + 47; EmfPlusRecordTypeSetPageTransform = GDIP_EMFPLUS_RECORD_BASE + 48; EmfPlusRecordTypeResetClip = GDIP_EMFPLUS_RECORD_BASE + 49; EmfPlusRecordTypeSetClipRect = GDIP_EMFPLUS_RECORD_BASE + 50; EmfPlusRecordTypeSetClipPath = GDIP_EMFPLUS_RECORD_BASE + 51; EmfPlusRecordTypeSetClipRegion = GDIP_EMFPLUS_RECORD_BASE + 52; EmfPlusRecordTypeOffsetClip = GDIP_EMFPLUS_RECORD_BASE + 53; EmfPlusRecordTypeDrawDriverString = GDIP_EMFPLUS_RECORD_BASE + 54; EmfPlusRecordTotal = GDIP_EMFPLUS_RECORD_BASE + 55; EmfPlusRecordTypeMax = EmfPlusRecordTotal-1; EmfPlusRecordTypeMin = EmfPlusRecordTypeHeader; {$ELSE} {$EXTERNALSYM TGPEmfPlusRecordType} type TGPEmfPlusRecordType = ( // Since we have to enumerate GDI records right along with GDI+ records, // We list all the GDI records here so that they can be part of the // same enumeration type which is used in the enumeration callback. WmfRecordTypeSetBkColor = META_SETBKCOLOR or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetBkMode = META_SETBKMODE or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetMapMode = META_SETMAPMODE or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetROP2 = META_SETROP2 or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetRelAbs = META_SETRELABS or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetPolyFillMode = META_SETPOLYFILLMODE or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetStretchBltMode = META_SETSTRETCHBLTMODE or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetTextCharExtra = META_SETTEXTCHAREXTRA or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetTextColor = META_SETTEXTCOLOR or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetTextJustification = META_SETTEXTJUSTIFICATION or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetWindowOrg = META_SETWINDOWORG or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetWindowExt = META_SETWINDOWEXT or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetViewportOrg = META_SETVIEWPORTORG or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetViewportExt = META_SETVIEWPORTEXT or GDIP_WMF_RECORD_BASE, WmfRecordTypeOffsetWindowOrg = META_OFFSETWINDOWORG or GDIP_WMF_RECORD_BASE, WmfRecordTypeScaleWindowExt = META_SCALEWINDOWEXT or GDIP_WMF_RECORD_BASE, WmfRecordTypeOffsetViewportOrg = META_OFFSETVIEWPORTORG or GDIP_WMF_RECORD_BASE, WmfRecordTypeScaleViewportExt = META_SCALEVIEWPORTEXT or GDIP_WMF_RECORD_BASE, WmfRecordTypeLineTo = META_LINETO or GDIP_WMF_RECORD_BASE, WmfRecordTypeMoveTo = META_MOVETO or GDIP_WMF_RECORD_BASE, WmfRecordTypeExcludeClipRect = META_EXCLUDECLIPRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeIntersectClipRect = META_INTERSECTCLIPRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeArc = META_ARC or GDIP_WMF_RECORD_BASE, WmfRecordTypeEllipse = META_ELLIPSE or GDIP_WMF_RECORD_BASE, WmfRecordTypeFloodFill = META_FLOODFILL or GDIP_WMF_RECORD_BASE, WmfRecordTypePie = META_PIE or GDIP_WMF_RECORD_BASE, WmfRecordTypeRectangle = META_RECTANGLE or GDIP_WMF_RECORD_BASE, WmfRecordTypeRoundRect = META_ROUNDRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypePatBlt = META_PATBLT or GDIP_WMF_RECORD_BASE, WmfRecordTypeSaveDC = META_SAVEDC or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetPixel = META_SETPIXEL or GDIP_WMF_RECORD_BASE, WmfRecordTypeOffsetClipRgn = META_OFFSETCLIPRGN or GDIP_WMF_RECORD_BASE, WmfRecordTypeTextOut = META_TEXTOUT or GDIP_WMF_RECORD_BASE, WmfRecordTypeBitBlt = META_BITBLT or GDIP_WMF_RECORD_BASE, WmfRecordTypeStretchBlt = META_STRETCHBLT or GDIP_WMF_RECORD_BASE, WmfRecordTypePolygon = META_POLYGON or GDIP_WMF_RECORD_BASE, WmfRecordTypePolyline = META_POLYLINE or GDIP_WMF_RECORD_BASE, WmfRecordTypeEscape = META_ESCAPE or GDIP_WMF_RECORD_BASE, WmfRecordTypeRestoreDC = META_RESTOREDC or GDIP_WMF_RECORD_BASE, WmfRecordTypeFillRegion = META_FILLREGION or GDIP_WMF_RECORD_BASE, WmfRecordTypeFrameRegion = META_FRAMEREGION or GDIP_WMF_RECORD_BASE, WmfRecordTypeInvertRegion = META_INVERTREGION or GDIP_WMF_RECORD_BASE, WmfRecordTypePaintRegion = META_PAINTREGION or GDIP_WMF_RECORD_BASE, WmfRecordTypeSelectClipRegion = META_SELECTCLIPREGION or GDIP_WMF_RECORD_BASE, WmfRecordTypeSelectObject = META_SELECTOBJECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetTextAlign = META_SETTEXTALIGN or GDIP_WMF_RECORD_BASE, WmfRecordTypeDrawText = $062F or GDIP_WMF_RECORD_BASE, // META_DRAWTEXT WmfRecordTypeChord = META_CHORD or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetMapperFlags = META_SETMAPPERFLAGS or GDIP_WMF_RECORD_BASE, WmfRecordTypeExtTextOut = META_EXTTEXTOUT or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetDIBToDev = META_SETDIBTODEV or GDIP_WMF_RECORD_BASE, WmfRecordTypeSelectPalette = META_SELECTPALETTE or GDIP_WMF_RECORD_BASE, WmfRecordTypeRealizePalette = META_REALIZEPALETTE or GDIP_WMF_RECORD_BASE, WmfRecordTypeAnimatePalette = META_ANIMATEPALETTE or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetPalEntries = META_SETPALENTRIES or GDIP_WMF_RECORD_BASE, WmfRecordTypePolyPolygon = META_POLYPOLYGON or GDIP_WMF_RECORD_BASE, WmfRecordTypeResizePalette = META_RESIZEPALETTE or GDIP_WMF_RECORD_BASE, WmfRecordTypeDIBBitBlt = META_DIBBITBLT or GDIP_WMF_RECORD_BASE, WmfRecordTypeDIBStretchBlt = META_DIBSTRETCHBLT or GDIP_WMF_RECORD_BASE, WmfRecordTypeDIBCreatePatternBrush = META_DIBCREATEPATTERNBRUSH or GDIP_WMF_RECORD_BASE, WmfRecordTypeStretchDIB = META_STRETCHDIB or GDIP_WMF_RECORD_BASE, WmfRecordTypeExtFloodFill = META_EXTFLOODFILL or GDIP_WMF_RECORD_BASE, WmfRecordTypeSetLayout = $0149 or GDIP_WMF_RECORD_BASE, // META_SETLAYOUT WmfRecordTypeResetDC = $014C or GDIP_WMF_RECORD_BASE, // META_RESETDC WmfRecordTypeStartDoc = $014D or GDIP_WMF_RECORD_BASE, // META_STARTDOC WmfRecordTypeStartPage = $004F or GDIP_WMF_RECORD_BASE, // META_STARTPAGE WmfRecordTypeEndPage = $0050 or GDIP_WMF_RECORD_BASE, // META_ENDPAGE WmfRecordTypeAbortDoc = $0052 or GDIP_WMF_RECORD_BASE, // META_ABORTDOC WmfRecordTypeEndDoc = $005E or GDIP_WMF_RECORD_BASE, // META_ENDDOC WmfRecordTypeDeleteObject = META_DELETEOBJECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreatePalette = META_CREATEPALETTE or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreateBrush = $00F8 or GDIP_WMF_RECORD_BASE, // META_CREATEBRUSH WmfRecordTypeCreatePatternBrush = META_CREATEPATTERNBRUSH or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreatePenIndirect = META_CREATEPENINDIRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreateFontIndirect = META_CREATEFONTINDIRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreateBrushIndirect = META_CREATEBRUSHINDIRECT or GDIP_WMF_RECORD_BASE, WmfRecordTypeCreateBitmapIndirect = $02FD or GDIP_WMF_RECORD_BASE, // META_CREATEBITMAPINDIRECT WmfRecordTypeCreateBitmap = $06FE or GDIP_WMF_RECORD_BASE, // META_CREATEBITMAP WmfRecordTypeCreateRegion = META_CREATEREGION or GDIP_WMF_RECORD_BASE, EmfRecordTypeHeader = EMR_HEADER, EmfRecordTypePolyBezier = EMR_POLYBEZIER, EmfRecordTypePolygon = EMR_POLYGON, EmfRecordTypePolyline = EMR_POLYLINE, EmfRecordTypePolyBezierTo = EMR_POLYBEZIERTO, EmfRecordTypePolyLineTo = EMR_POLYLINETO, EmfRecordTypePolyPolyline = EMR_POLYPOLYLINE, EmfRecordTypePolyPolygon = EMR_POLYPOLYGON, EmfRecordTypeSetWindowExtEx = EMR_SETWINDOWEXTEX, EmfRecordTypeSetWindowOrgEx = EMR_SETWINDOWORGEX, EmfRecordTypeSetViewportExtEx = EMR_SETVIEWPORTEXTEX, EmfRecordTypeSetViewportOrgEx = EMR_SETVIEWPORTORGEX, EmfRecordTypeSetBrushOrgEx = EMR_SETBRUSHORGEX, EmfRecordTypeEOF = EMR_EOF, EmfRecordTypeSetPixelV = EMR_SETPIXELV, EmfRecordTypeSetMapperFlags = EMR_SETMAPPERFLAGS, EmfRecordTypeSetMapMode = EMR_SETMAPMODE, EmfRecordTypeSetBkMode = EMR_SETBKMODE, EmfRecordTypeSetPolyFillMode = EMR_SETPOLYFILLMODE, EmfRecordTypeSetROP2 = EMR_SETROP2, EmfRecordTypeSetStretchBltMode = EMR_SETSTRETCHBLTMODE, EmfRecordTypeSetTextAlign = EMR_SETTEXTALIGN, EmfRecordTypeSetColorAdjustment = EMR_SETCOLORADJUSTMENT, EmfRecordTypeSetTextColor = EMR_SETTEXTCOLOR, EmfRecordTypeSetBkColor = EMR_SETBKCOLOR, EmfRecordTypeOffsetClipRgn = EMR_OFFSETCLIPRGN, EmfRecordTypeMoveToEx = EMR_MOVETOEX, EmfRecordTypeSetMetaRgn = EMR_SETMETARGN, EmfRecordTypeExcludeClipRect = EMR_EXCLUDECLIPRECT, EmfRecordTypeIntersectClipRect = EMR_INTERSECTCLIPRECT, EmfRecordTypeScaleViewportExtEx = EMR_SCALEVIEWPORTEXTEX, EmfRecordTypeScaleWindowExtEx = EMR_SCALEWINDOWEXTEX, EmfRecordTypeSaveDC = EMR_SAVEDC, EmfRecordTypeRestoreDC = EMR_RESTOREDC, EmfRecordTypeSetWorldTransform = EMR_SETWORLDTRANSFORM, EmfRecordTypeModifyWorldTransform = EMR_MODIFYWORLDTRANSFORM, EmfRecordTypeSelectObject = EMR_SELECTOBJECT, EmfRecordTypeCreatePen = EMR_CREATEPEN, EmfRecordTypeCreateBrushIndirect = EMR_CREATEBRUSHINDIRECT, EmfRecordTypeDeleteObject = EMR_DELETEOBJECT, EmfRecordTypeAngleArc = EMR_ANGLEARC, EmfRecordTypeEllipse = EMR_ELLIPSE, EmfRecordTypeRectangle = EMR_RECTANGLE, EmfRecordTypeRoundRect = EMR_ROUNDRECT, EmfRecordTypeArc = EMR_ARC, EmfRecordTypeChord = EMR_CHORD, EmfRecordTypePie = EMR_PIE, EmfRecordTypeSelectPalette = EMR_SELECTPALETTE, EmfRecordTypeCreatePalette = EMR_CREATEPALETTE, EmfRecordTypeSetPaletteEntries = EMR_SETPALETTEENTRIES, EmfRecordTypeResizePalette = EMR_RESIZEPALETTE, EmfRecordTypeRealizePalette = EMR_REALIZEPALETTE, EmfRecordTypeExtFloodFill = EMR_EXTFLOODFILL, EmfRecordTypeLineTo = EMR_LINETO, EmfRecordTypeArcTo = EMR_ARCTO, EmfRecordTypePolyDraw = EMR_POLYDRAW, EmfRecordTypeSetArcDirection = EMR_SETARCDIRECTION, EmfRecordTypeSetMiterLimit = EMR_SETMITERLIMIT, EmfRecordTypeBeginPath = EMR_BEGINPATH, EmfRecordTypeEndPath = EMR_ENDPATH, EmfRecordTypeCloseFigure = EMR_CLOSEFIGURE, EmfRecordTypeFillPath = EMR_FILLPATH, EmfRecordTypeStrokeAndFillPath = EMR_STROKEANDFILLPATH, EmfRecordTypeStrokePath = EMR_STROKEPATH, EmfRecordTypeFlattenPath = EMR_FLATTENPATH, EmfRecordTypeWidenPath = EMR_WIDENPATH, EmfRecordTypeSelectClipPath = EMR_SELECTCLIPPATH, EmfRecordTypeAbortPath = EMR_ABORTPATH, EmfRecordTypeReserved_069 = 69, // Not Used EmfRecordTypeGdiComment = EMR_GDICOMMENT, EmfRecordTypeFillRgn = EMR_FILLRGN, EmfRecordTypeFrameRgn = EMR_FRAMERGN, EmfRecordTypeInvertRgn = EMR_INVERTRGN, EmfRecordTypePaintRgn = EMR_PAINTRGN, EmfRecordTypeExtSelectClipRgn = EMR_EXTSELECTCLIPRGN, EmfRecordTypeBitBlt = EMR_BITBLT, EmfRecordTypeStretchBlt = EMR_STRETCHBLT, EmfRecordTypeMaskBlt = EMR_MASKBLT, EmfRecordTypePlgBlt = EMR_PLGBLT, EmfRecordTypeSetDIBitsToDevice = EMR_SETDIBITSTODEVICE, EmfRecordTypeStretchDIBits = EMR_STRETCHDIBITS, EmfRecordTypeExtCreateFontIndirect = EMR_EXTCREATEFONTINDIRECTW, EmfRecordTypeExtTextOutA = EMR_EXTTEXTOUTA, EmfRecordTypeExtTextOutW = EMR_EXTTEXTOUTW, EmfRecordTypePolyBezier16 = EMR_POLYBEZIER16, EmfRecordTypePolygon16 = EMR_POLYGON16, EmfRecordTypePolyline16 = EMR_POLYLINE16, EmfRecordTypePolyBezierTo16 = EMR_POLYBEZIERTO16, EmfRecordTypePolylineTo16 = EMR_POLYLINETO16, EmfRecordTypePolyPolyline16 = EMR_POLYPOLYLINE16, EmfRecordTypePolyPolygon16 = EMR_POLYPOLYGON16, EmfRecordTypePolyDraw16 = EMR_POLYDRAW16, EmfRecordTypeCreateMonoBrush = EMR_CREATEMONOBRUSH, EmfRecordTypeCreateDIBPatternBrushPt = EMR_CREATEDIBPATTERNBRUSHPT, EmfRecordTypeExtCreatePen = EMR_EXTCREATEPEN, EmfRecordTypePolyTextOutA = EMR_POLYTEXTOUTA, EmfRecordTypePolyTextOutW = EMR_POLYTEXTOUTW, EmfRecordTypeSetICMMode = 98, // EMR_SETICMMODE, EmfRecordTypeCreateColorSpace = 99, // EMR_CREATECOLORSPACE, EmfRecordTypeSetColorSpace = 100, // EMR_SETCOLORSPACE, EmfRecordTypeDeleteColorSpace = 101, // EMR_DELETECOLORSPACE, EmfRecordTypeGLSRecord = 102, // EMR_GLSRECORD, EmfRecordTypeGLSBoundedRecord = 103, // EMR_GLSBOUNDEDRECORD, EmfRecordTypePixelFormat = 104, // EMR_PIXELFORMAT, EmfRecordTypeDrawEscape = 105, // EMR_RESERVED_105, EmfRecordTypeExtEscape = 106, // EMR_RESERVED_106, EmfRecordTypeStartDoc = 107, // EMR_RESERVED_107, EmfRecordTypeSmallTextOut = 108, // EMR_RESERVED_108, EmfRecordTypeForceUFIMapping = 109, // EMR_RESERVED_109, EmfRecordTypeNamedEscape = 110, // EMR_RESERVED_110, EmfRecordTypeColorCorrectPalette = 111, // EMR_COLORCORRECTPALETTE, EmfRecordTypeSetICMProfileA = 112, // EMR_SETICMPROFILEA, EmfRecordTypeSetICMProfileW = 113, // EMR_SETICMPROFILEW, EmfRecordTypeAlphaBlend = 114, // EMR_ALPHABLEND, EmfRecordTypeSetLayout = 115, // EMR_SETLAYOUT, EmfRecordTypeTransparentBlt = 116, // EMR_TRANSPARENTBLT, EmfRecordTypeReserved_117 = 117, // Not Used EmfRecordTypeGradientFill = 118, // EMR_GRADIENTFILL, EmfRecordTypeSetLinkedUFIs = 119, // EMR_RESERVED_119, EmfRecordTypeSetTextJustification = 120, // EMR_RESERVED_120, EmfRecordTypeColorMatchToTargetW = 121, // EMR_COLORMATCHTOTARGETW, EmfRecordTypeCreateColorSpaceW = 122, // EMR_CREATECOLORSPACEW, EmfRecordTypeMax = 122, EmfRecordTypeMin = 1, // That is the END of the GDI EMF records. // Now we start the list of EMF+ records. We leave quite // a bit of room here for the addition of any new GDI // records that may be added later. EmfPlusRecordTypeInvalid = GDIP_EMFPLUS_RECORD_BASE, EmfPlusRecordTypeHeader, EmfPlusRecordTypeEndOfFile, EmfPlusRecordTypeComment, EmfPlusRecordTypeGetDC, EmfPlusRecordTypeMultiFormatStart, EmfPlusRecordTypeMultiFormatSection, EmfPlusRecordTypeMultiFormatEnd, // For all persistent objects EmfPlusRecordTypeObject, // Drawing Records EmfPlusRecordTypeClear, EmfPlusRecordTypeFillRects, EmfPlusRecordTypeDrawRects, EmfPlusRecordTypeFillPolygon, EmfPlusRecordTypeDrawLines, EmfPlusRecordTypeFillEllipse, EmfPlusRecordTypeDrawEllipse, EmfPlusRecordTypeFillPie, EmfPlusRecordTypeDrawPie, EmfPlusRecordTypeDrawArc, EmfPlusRecordTypeFillRegion, EmfPlusRecordTypeFillPath, EmfPlusRecordTypeDrawPath, EmfPlusRecordTypeFillClosedCurve, EmfPlusRecordTypeDrawClosedCurve, EmfPlusRecordTypeDrawCurve, EmfPlusRecordTypeDrawBeziers, EmfPlusRecordTypeDrawImage, EmfPlusRecordTypeDrawImagePoints, EmfPlusRecordTypeDrawString, // Graphics State Records EmfPlusRecordTypeSetRenderingOrigin, EmfPlusRecordTypeSetAntiAliasMode, EmfPlusRecordTypeSetTextRenderingHint, EmfPlusRecordTypeSetTextContrast, EmfPlusRecordTypeSetInterpolationMode, EmfPlusRecordTypeSetPixelOffsetMode, EmfPlusRecordTypeSetCompositingMode, EmfPlusRecordTypeSetCompositingQuality, EmfPlusRecordTypeSave, EmfPlusRecordTypeRestore, EmfPlusRecordTypeBeginContainer, EmfPlusRecordTypeBeginContainerNoParams, EmfPlusRecordTypeEndContainer, EmfPlusRecordTypeSetWorldTransform, EmfPlusRecordTypeResetWorldTransform, EmfPlusRecordTypeMultiplyWorldTransform, EmfPlusRecordTypeTranslateWorldTransform, EmfPlusRecordTypeScaleWorldTransform, EmfPlusRecordTypeRotateWorldTransform, EmfPlusRecordTypeSetPageTransform, EmfPlusRecordTypeResetClip, EmfPlusRecordTypeSetClipRect, EmfPlusRecordTypeSetClipPath, EmfPlusRecordTypeSetClipRegion, EmfPlusRecordTypeOffsetClip, EmfPlusRecordTypeDrawDriverString, EmfPlusRecordTotal, EmfPlusRecordTypeMax = EmfPlusRecordTotal-1, EmfPlusRecordTypeMin = EmfPlusRecordTypeHeader ); (*$HPPEMIT 'enum TGPEmfPlusRecordType' *) (*$HPPEMIT '{' *) (*$HPPEMIT ' WmfRecordTypeSetBkColor = (META_SETBKCOLOR | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetBkMode = (META_SETBKMODE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetMapMode = (META_SETMAPMODE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetROP2 = (META_SETROP2 | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetRelAbs = (META_SETRELABS | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetPolyFillMode = (META_SETPOLYFILLMODE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetStretchBltMode = (META_SETSTRETCHBLTMODE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetTextCharExtra = (META_SETTEXTCHAREXTRA | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetTextColor = (META_SETTEXTCOLOR | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetTextJustification = (META_SETTEXTJUSTIFICATION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetWindowOrg = (META_SETWINDOWORG | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetWindowExt = (META_SETWINDOWEXT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetViewportOrg = (META_SETVIEWPORTORG | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetViewportExt = (META_SETVIEWPORTEXT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeOffsetWindowOrg = (META_OFFSETWINDOWORG | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeScaleWindowExt = (META_SCALEWINDOWEXT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeOffsetViewportOrg = (META_OFFSETVIEWPORTORG | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeScaleViewportExt = (META_SCALEVIEWPORTEXT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeLineTo = (META_LINETO | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeMoveTo = (META_MOVETO | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeExcludeClipRect = (META_EXCLUDECLIPRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeIntersectClipRect = (META_INTERSECTCLIPRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeArc = (META_ARC | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeEllipse = (META_ELLIPSE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeFloodFill = (META_FLOODFILL | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePie = (META_PIE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeRectangle = (META_RECTANGLE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeRoundRect = (META_ROUNDRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePatBlt = (META_PATBLT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSaveDC = (META_SAVEDC | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetPixel = (META_SETPIXEL | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeOffsetClipRgn = (META_OFFSETCLIPRGN | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeTextOut = (META_TEXTOUT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeBitBlt = (META_BITBLT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeStretchBlt = (META_STRETCHBLT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePolygon = (META_POLYGON | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePolyline = (META_POLYLINE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeEscape = (META_ESCAPE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeRestoreDC = (META_RESTOREDC | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeFillRegion = (META_FILLREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeFrameRegion = (META_FRAMEREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeInvertRegion = (META_INVERTREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePaintRegion = (META_PAINTREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSelectClipRegion = (META_SELECTCLIPREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSelectObject = (META_SELECTOBJECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetTextAlign = (META_SETTEXTALIGN | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeDrawText = (0x062F | BCBGDIP_WMF_RECORD_BASE), // META_DRAWTEXT' *) (*$HPPEMIT ' WmfRecordTypeChord = (META_CHORD | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetMapperFlags = (META_SETMAPPERFLAGS | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeExtTextOut = (META_EXTTEXTOUT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetDIBToDev = (META_SETDIBTODEV | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSelectPalette = (META_SELECTPALETTE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeRealizePalette = (META_REALIZEPALETTE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeAnimatePalette = (META_ANIMATEPALETTE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetPalEntries = (META_SETPALENTRIES | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypePolyPolygon = (META_POLYPOLYGON | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeResizePalette = (META_RESIZEPALETTE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeDIBBitBlt = (META_DIBBITBLT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeDIBStretchBlt = (META_DIBSTRETCHBLT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeDIBCreatePatternBrush = (META_DIBCREATEPATTERNBRUSH | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeStretchDIB = (META_STRETCHDIB | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeExtFloodFill = (META_EXTFLOODFILL | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeSetLayout = (0x0149 | BCBGDIP_WMF_RECORD_BASE), // META_SETLAYOUT' *) (*$HPPEMIT ' WmfRecordTypeResetDC = (0x014C | BCBGDIP_WMF_RECORD_BASE), // META_RESETDC' *) (*$HPPEMIT ' WmfRecordTypeStartDoc = (0x014D | BCBGDIP_WMF_RECORD_BASE), // META_STARTDOC' *) (*$HPPEMIT ' WmfRecordTypeStartPage = (0x004F | BCBGDIP_WMF_RECORD_BASE), // META_STARTPAGE' *) (*$HPPEMIT ' WmfRecordTypeEndPage = (0x0050 | BCBGDIP_WMF_RECORD_BASE), // META_ENDPAGE' *) (*$HPPEMIT ' WmfRecordTypeAbortDoc = (0x0052 | BCBGDIP_WMF_RECORD_BASE), // META_ABORTDOC' *) (*$HPPEMIT ' WmfRecordTypeEndDoc = (0x005E | BCBGDIP_WMF_RECORD_BASE), // META_ENDDOC' *) (*$HPPEMIT ' WmfRecordTypeDeleteObject = (META_DELETEOBJECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreatePalette = (META_CREATEPALETTE | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreateBrush = (0x00F8 | BCBGDIP_WMF_RECORD_BASE), // META_CREATEBRUSH' *) (*$HPPEMIT ' WmfRecordTypeCreatePatternBrush = (META_CREATEPATTERNBRUSH | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreatePenIndirect = (META_CREATEPENINDIRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreateFontIndirect = (META_CREATEFONTINDIRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreateBrushIndirect = (META_CREATEBRUSHINDIRECT | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT ' WmfRecordTypeCreateBitmapIndirect = (0x02FD | BCBGDIP_WMF_RECORD_BASE), // META_CREATEBITMAPINDIRECT' *) (*$HPPEMIT ' WmfRecordTypeCreateBitmap = (0x06FE | BCBGDIP_WMF_RECORD_BASE), // META_CREATEBITMAP' *) (*$HPPEMIT ' WmfRecordTypeCreateRegion = (META_CREATEREGION | BCBGDIP_WMF_RECORD_BASE),' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfRecordTypeHeader = EMR_HEADER,' *) (*$HPPEMIT ' EmfRecordTypePolyBezier = EMR_POLYBEZIER,' *) (*$HPPEMIT ' EmfRecordTypePolygon = EMR_POLYGON,' *) (*$HPPEMIT ' EmfRecordTypePolyline = EMR_POLYLINE,' *) (*$HPPEMIT ' EmfRecordTypePolyBezierTo = EMR_POLYBEZIERTO,' *) (*$HPPEMIT ' EmfRecordTypePolyLineTo = EMR_POLYLINETO,' *) (*$HPPEMIT ' EmfRecordTypePolyPolyline = EMR_POLYPOLYLINE,' *) (*$HPPEMIT ' EmfRecordTypePolyPolygon = EMR_POLYPOLYGON,' *) (*$HPPEMIT ' EmfRecordTypeSetWindowExtEx = EMR_SETWINDOWEXTEX,' *) (*$HPPEMIT ' EmfRecordTypeSetWindowOrgEx = EMR_SETWINDOWORGEX,' *) (*$HPPEMIT ' EmfRecordTypeSetViewportExtEx = EMR_SETVIEWPORTEXTEX,' *) (*$HPPEMIT ' EmfRecordTypeSetViewportOrgEx = EMR_SETVIEWPORTORGEX,' *) (*$HPPEMIT ' EmfRecordTypeSetBrushOrgEx = EMR_SETBRUSHORGEX,' *) (*$HPPEMIT ' EmfRecordTypeEOF = EMR_EOF,' *) (*$HPPEMIT ' EmfRecordTypeSetPixelV = EMR_SETPIXELV,' *) (*$HPPEMIT ' EmfRecordTypeSetMapperFlags = EMR_SETMAPPERFLAGS,' *) (*$HPPEMIT ' EmfRecordTypeSetMapMode = EMR_SETMAPMODE,' *) (*$HPPEMIT ' EmfRecordTypeSetBkMode = EMR_SETBKMODE,' *) (*$HPPEMIT ' EmfRecordTypeSetPolyFillMode = EMR_SETPOLYFILLMODE,' *) (*$HPPEMIT ' EmfRecordTypeSetROP2 = EMR_SETROP2,' *) (*$HPPEMIT ' EmfRecordTypeSetStretchBltMode = EMR_SETSTRETCHBLTMODE,' *) (*$HPPEMIT ' EmfRecordTypeSetTextAlign = EMR_SETTEXTALIGN,' *) (*$HPPEMIT ' EmfRecordTypeSetColorAdjustment = EMR_SETCOLORADJUSTMENT,' *) (*$HPPEMIT ' EmfRecordTypeSetTextColor = EMR_SETTEXTCOLOR,' *) (*$HPPEMIT ' EmfRecordTypeSetBkColor = EMR_SETBKCOLOR,' *) (*$HPPEMIT ' EmfRecordTypeOffsetClipRgn = EMR_OFFSETCLIPRGN,' *) (*$HPPEMIT ' EmfRecordTypeMoveToEx = EMR_MOVETOEX,' *) (*$HPPEMIT ' EmfRecordTypeSetMetaRgn = EMR_SETMETARGN,' *) (*$HPPEMIT ' EmfRecordTypeExcludeClipRect = EMR_EXCLUDECLIPRECT,' *) (*$HPPEMIT ' EmfRecordTypeIntersectClipRect = EMR_INTERSECTCLIPRECT,' *) (*$HPPEMIT ' EmfRecordTypeScaleViewportExtEx = EMR_SCALEVIEWPORTEXTEX,' *) (*$HPPEMIT ' EmfRecordTypeScaleWindowExtEx = EMR_SCALEWINDOWEXTEX,' *) (*$HPPEMIT ' EmfRecordTypeSaveDC = EMR_SAVEDC,' *) (*$HPPEMIT ' EmfRecordTypeRestoreDC = EMR_RESTOREDC,' *) (*$HPPEMIT ' EmfRecordTypeSetWorldTransform = EMR_SETWORLDTRANSFORM,' *) (*$HPPEMIT ' EmfRecordTypeModifyWorldTransform = EMR_MODIFYWORLDTRANSFORM,' *) (*$HPPEMIT ' EmfRecordTypeSelectObject = EMR_SELECTOBJECT,' *) (*$HPPEMIT ' EmfRecordTypeCreatePen = EMR_CREATEPEN,' *) (*$HPPEMIT ' EmfRecordTypeCreateBrushIndirect = EMR_CREATEBRUSHINDIRECT,' *) (*$HPPEMIT ' EmfRecordTypeDeleteObject = EMR_DELETEOBJECT,' *) (*$HPPEMIT ' EmfRecordTypeAngleArc = EMR_ANGLEARC,' *) (*$HPPEMIT ' EmfRecordTypeEllipse = EMR_ELLIPSE,' *) (*$HPPEMIT ' EmfRecordTypeRectangle = EMR_RECTANGLE,' *) (*$HPPEMIT ' EmfRecordTypeRoundRect = EMR_ROUNDRECT,' *) (*$HPPEMIT ' EmfRecordTypeArc = EMR_ARC,' *) (*$HPPEMIT ' EmfRecordTypeChord = EMR_CHORD,' *) (*$HPPEMIT ' EmfRecordTypePie = EMR_PIE,' *) (*$HPPEMIT ' EmfRecordTypeSelectPalette = EMR_SELECTPALETTE,' *) (*$HPPEMIT ' EmfRecordTypeCreatePalette = EMR_CREATEPALETTE,' *) (*$HPPEMIT ' EmfRecordTypeSetPaletteEntries = EMR_SETPALETTEENTRIES,' *) (*$HPPEMIT ' EmfRecordTypeResizePalette = EMR_RESIZEPALETTE,' *) (*$HPPEMIT ' EmfRecordTypeRealizePalette = EMR_REALIZEPALETTE,' *) (*$HPPEMIT ' EmfRecordTypeExtFloodFill = EMR_EXTFLOODFILL,' *) (*$HPPEMIT ' EmfRecordTypeLineTo = EMR_LINETO,' *) (*$HPPEMIT ' EmfRecordTypeArcTo = EMR_ARCTO,' *) (*$HPPEMIT ' EmfRecordTypePolyDraw = EMR_POLYDRAW,' *) (*$HPPEMIT ' EmfRecordTypeSetArcDirection = EMR_SETARCDIRECTION,' *) (*$HPPEMIT ' EmfRecordTypeSetMiterLimit = EMR_SETMITERLIMIT,' *) (*$HPPEMIT ' EmfRecordTypeBeginPath = EMR_BEGINPATH,' *) (*$HPPEMIT ' EmfRecordTypeEndPath = EMR_ENDPATH,' *) (*$HPPEMIT ' EmfRecordTypeCloseFigure = EMR_CLOSEFIGURE,' *) (*$HPPEMIT ' EmfRecordTypeFillPath = EMR_FILLPATH,' *) (*$HPPEMIT ' EmfRecordTypeStrokeAndFillPath = EMR_STROKEANDFILLPATH,' *) (*$HPPEMIT ' EmfRecordTypeStrokePath = EMR_STROKEPATH,' *) (*$HPPEMIT ' EmfRecordTypeFlattenPath = EMR_FLATTENPATH,' *) (*$HPPEMIT ' EmfRecordTypeWidenPath = EMR_WIDENPATH,' *) (*$HPPEMIT ' EmfRecordTypeSelectClipPath = EMR_SELECTCLIPPATH,' *) (*$HPPEMIT ' EmfRecordTypeAbortPath = EMR_ABORTPATH,' *) (*$HPPEMIT ' EmfRecordTypeReserved_069 = 69, // Not Used' *) (*$HPPEMIT ' EmfRecordTypeGdiComment = EMR_GDICOMMENT,' *) (*$HPPEMIT ' EmfRecordTypeFillRgn = EMR_FILLRGN,' *) (*$HPPEMIT ' EmfRecordTypeFrameRgn = EMR_FRAMERGN,' *) (*$HPPEMIT ' EmfRecordTypeInvertRgn = EMR_INVERTRGN,' *) (*$HPPEMIT ' EmfRecordTypePaintRgn = EMR_PAINTRGN,' *) (*$HPPEMIT ' EmfRecordTypeExtSelectClipRgn = EMR_EXTSELECTCLIPRGN,' *) (*$HPPEMIT ' EmfRecordTypeBitBlt = EMR_BITBLT,' *) (*$HPPEMIT ' EmfRecordTypeStretchBlt = EMR_STRETCHBLT,' *) (*$HPPEMIT ' EmfRecordTypeMaskBlt = EMR_MASKBLT,' *) (*$HPPEMIT ' EmfRecordTypePlgBlt = EMR_PLGBLT,' *) (*$HPPEMIT ' EmfRecordTypeSetDIBitsToDevice = EMR_SETDIBITSTODEVICE,' *) (*$HPPEMIT ' EmfRecordTypeStretchDIBits = EMR_STRETCHDIBITS,' *) (*$HPPEMIT ' EmfRecordTypeExtCreateFontIndirect = EMR_EXTCREATEFONTINDIRECTW,' *) (*$HPPEMIT ' EmfRecordTypeExtTextOutA = EMR_EXTTEXTOUTA,' *) (*$HPPEMIT ' EmfRecordTypeExtTextOutW = EMR_EXTTEXTOUTW,' *) (*$HPPEMIT ' EmfRecordTypePolyBezier16 = EMR_POLYBEZIER16,' *) (*$HPPEMIT ' EmfRecordTypePolygon16 = EMR_POLYGON16,' *) (*$HPPEMIT ' EmfRecordTypePolyline16 = EMR_POLYLINE16,' *) (*$HPPEMIT ' EmfRecordTypePolyBezierTo16 = EMR_POLYBEZIERTO16,' *) (*$HPPEMIT ' EmfRecordTypePolylineTo16 = EMR_POLYLINETO16,' *) (*$HPPEMIT ' EmfRecordTypePolyPolyline16 = EMR_POLYPOLYLINE16,' *) (*$HPPEMIT ' EmfRecordTypePolyPolygon16 = EMR_POLYPOLYGON16,' *) (*$HPPEMIT ' EmfRecordTypePolyDraw16 = EMR_POLYDRAW16,' *) (*$HPPEMIT ' EmfRecordTypeCreateMonoBrush = EMR_CREATEMONOBRUSH,' *) (*$HPPEMIT ' EmfRecordTypeCreateDIBPatternBrushPt = EMR_CREATEDIBPATTERNBRUSHPT,' *) (*$HPPEMIT ' EmfRecordTypeExtCreatePen = EMR_EXTCREATEPEN,' *) (*$HPPEMIT ' EmfRecordTypePolyTextOutA = EMR_POLYTEXTOUTA,' *) (*$HPPEMIT ' EmfRecordTypePolyTextOutW = EMR_POLYTEXTOUTW,' *) (*$HPPEMIT ' EmfRecordTypeSetICMMode = 98, // EMR_SETICMMODE,' *) (*$HPPEMIT ' EmfRecordTypeCreateColorSpace = 99, // EMR_CREATECOLORSPACE,' *) (*$HPPEMIT ' EmfRecordTypeSetColorSpace = 100, // EMR_SETCOLORSPACE,' *) (*$HPPEMIT ' EmfRecordTypeDeleteColorSpace = 101, // EMR_DELETECOLORSPACE,' *) (*$HPPEMIT ' EmfRecordTypeGLSRecord = 102, // EMR_GLSRECORD,' *) (*$HPPEMIT ' EmfRecordTypeGLSBoundedRecord = 103, // EMR_GLSBOUNDEDRECORD,' *) (*$HPPEMIT ' EmfRecordTypePixelFormat = 104, // EMR_PIXELFORMAT,' *) (*$HPPEMIT ' EmfRecordTypeDrawEscape = 105, // EMR_RESERVED_105,' *) (*$HPPEMIT ' EmfRecordTypeExtEscape = 106, // EMR_RESERVED_106,' *) (*$HPPEMIT ' EmfRecordTypeStartDoc = 107, // EMR_RESERVED_107,' *) (*$HPPEMIT ' EmfRecordTypeSmallTextOut = 108, // EMR_RESERVED_108,' *) (*$HPPEMIT ' EmfRecordTypeForceUFIMapping = 109, // EMR_RESERVED_109,' *) (*$HPPEMIT ' EmfRecordTypeNamedEscape = 110, // EMR_RESERVED_110,' *) (*$HPPEMIT ' EmfRecordTypeColorCorrectPalette = 111, // EMR_COLORCORRECTPALETTE,' *) (*$HPPEMIT ' EmfRecordTypeSetICMProfileA = 112, // EMR_SETICMPROFILEA,' *) (*$HPPEMIT ' EmfRecordTypeSetICMProfileW = 113, // EMR_SETICMPROFILEW,' *) (*$HPPEMIT ' EmfRecordTypeAlphaBlend = 114, // EMR_ALPHABLEND,' *) (*$HPPEMIT ' EmfRecordTypeSetLayout = 115, // EMR_SETLAYOUT,' *) (*$HPPEMIT ' EmfRecordTypeTransparentBlt = 116, // EMR_TRANSPARENTBLT,' *) (*$HPPEMIT ' EmfRecordTypeReserved_117 = 117, // Not Used' *) (*$HPPEMIT ' EmfRecordTypeGradientFill = 118, // EMR_GRADIENTFILL,' *) (*$HPPEMIT ' EmfRecordTypeSetLinkedUFIs = 119, // EMR_RESERVED_119,' *) (*$HPPEMIT ' EmfRecordTypeSetTextJustification = 120, // EMR_RESERVED_120,' *) (*$HPPEMIT ' EmfRecordTypeColorMatchToTargetW = 121, // EMR_COLORMATCHTOTARGETW,' *) (*$HPPEMIT ' EmfRecordTypeCreateColorSpaceW = 122, // EMR_CREATECOLORSPACEW,' *) (*$HPPEMIT ' EmfRecordTypeMax = 122,' *) (*$HPPEMIT ' EmfRecordTypeMin = 1,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // That is the END of the GDI EMF records.' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Now we start the list of EMF+ records. We leave quite' *) (*$HPPEMIT ' // a bit of room here for the addition of any new GDI' *) (*$HPPEMIT ' // records that may be added later.' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeInvalid = BCBGDIP_EMFPLUS_RECORD_BASE,' *) (*$HPPEMIT ' EmfPlusRecordTypeHeader,' *) (*$HPPEMIT ' EmfPlusRecordTypeEndOfFile,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeComment,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeGetDC,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeMultiFormatStart,' *) (*$HPPEMIT ' EmfPlusRecordTypeMultiFormatSection,' *) (*$HPPEMIT ' EmfPlusRecordTypeMultiFormatEnd,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // For all persistent objects' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeObject,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Drawing Records' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeClear,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillRects,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawRects,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillPolygon,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawLines,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillEllipse,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawEllipse,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillPie,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawPie,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawArc,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillRegion,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillPath,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawPath,' *) (*$HPPEMIT ' EmfPlusRecordTypeFillClosedCurve,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawClosedCurve,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawCurve,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawBeziers,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawImage,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawImagePoints,' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawString,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Graphics State Records' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeSetRenderingOrigin,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetAntiAliasMode,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetTextRenderingHint,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetTextContrast,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetInterpolationMode,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetPixelOffsetMode,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetCompositingMode,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetCompositingQuality,' *) (*$HPPEMIT ' EmfPlusRecordTypeSave,' *) (*$HPPEMIT ' EmfPlusRecordTypeRestore,' *) (*$HPPEMIT ' EmfPlusRecordTypeBeginContainer,' *) (*$HPPEMIT ' EmfPlusRecordTypeBeginContainerNoParams,' *) (*$HPPEMIT ' EmfPlusRecordTypeEndContainer,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeResetWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeMultiplyWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeTranslateWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeScaleWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeRotateWorldTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetPageTransform,' *) (*$HPPEMIT ' EmfPlusRecordTypeResetClip,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetClipRect,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetClipPath,' *) (*$HPPEMIT ' EmfPlusRecordTypeSetClipRegion,' *) (*$HPPEMIT ' EmfPlusRecordTypeOffsetClip,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeDrawDriverString,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTotal,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' EmfPlusRecordTypeMax = EmfPlusRecordTotal-1,' *) (*$HPPEMIT ' EmfPlusRecordTypeMin = EmfPlusRecordTypeHeader' *) (*$HPPEMIT '};' *) {$ENDIF} //--------------------------------------------------------------------------- // StringFormatFlags //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // String format flags // // DirectionRightToLeft - For horizontal text, the reading order is // right to left. This value is called // the base embedding level by the Unicode // bidirectional engine. // For vertical text, columns are read from // right to left. // By default, horizontal or vertical text is // read from left to right. // // DirectionVertical - Individual lines of text are vertical. In // each line, characters progress from top to // bottom. // By default, lines of text are horizontal, // each new line below the previous line. // // NoFitBlackBox - Allows parts of glyphs to overhang the // bounding rectangle. // By default glyphs are first aligned // inside the margines, then any glyphs which // still overhang the bounding box are // repositioned to avoid any overhang. // For example when an italic // lower case letter f in a font such as // Garamond is aligned at the far left of a // rectangle, the lower part of the f will // reach slightly further left than the left // edge of the rectangle. Setting this flag // will ensure the character aligns visually // with the lines above and below, but may // cause some pixels outside the formatting // rectangle to be clipped or painted. // // DisplayFormatControl - Causes control characters such as the // left-to-right mark to be shown in the // output with a representative glyph. // // NoFontFallback - Disables fallback to alternate fonts for // characters not supported in the requested // font. Any missing characters will be // be displayed with the fonts missing glyph, // usually an open square. // // NoWrap - Disables wrapping of text between lines // when formatting within a rectangle. // NoWrap is implied when a point is passed // instead of a rectangle, or when the // specified rectangle has a zero line length. // // NoClip - By default text is clipped to the // formatting rectangle. Setting NoClip // allows overhanging pixels to affect the // device outside the formatting rectangle. // Pixels at the end of the line may be // affected if the glyphs overhang their // cells, and either the NoFitBlackBox flag // has been set, or the glyph extends to far // to be fitted. // Pixels above/before the first line or // below/after the last line may be affected // if the glyphs extend beyond their cell // ascent / descent. This can occur rarely // with unusual diacritic mark combinations. //--------------------------------------------------------------------------- type TGPStringFormatFlags = Integer; const StringFormatFlagsDirectionRightToLeft = $00000001; StringFormatFlagsDirectionVertical = $00000002; StringFormatFlagsNoFitBlackBox = $00000004; StringFormatFlagsDisplayFormatControl = $00000020; StringFormatFlagsNoFontFallback = $00000400; StringFormatFlagsMeasureTrailingSpaces = $00000800; StringFormatFlagsNoWrap = $00001000; StringFormatFlagsLineLimit = $00002000; StringFormatFlagsNoClip = $00004000; //--------------------------------------------------------------------------- // TGPStringTrimming //--------------------------------------------------------------------------- type TGPStringTrimming = ( StringTrimmingNone, StringTrimmingCharacter, StringTrimmingWord, StringTrimmingEllipsisCharacter, StringTrimmingEllipsisWord, StringTrimmingEllipsisPath ); //--------------------------------------------------------------------------- // National language digit substitution //--------------------------------------------------------------------------- TGPStringDigitSubstitute = ( StringDigitSubstituteUser, // As NLS setting StringDigitSubstituteNone, StringDigitSubstituteNational, StringDigitSubstituteTraditional ); PGPStringDigitSubstitute = ^TGPStringDigitSubstitute; //--------------------------------------------------------------------------- // Hotkey prefix interpretation //--------------------------------------------------------------------------- TGPHotkeyPrefix = ( HotkeyPrefixNone, HotkeyPrefixShow, HotkeyPrefixHide ); //--------------------------------------------------------------------------- // String alignment flags //--------------------------------------------------------------------------- TGPStringAlignment = ( // Left edge for left-to-right text, // right for right-to-left text, // and top for vertical StringAlignmentNear, StringAlignmentCenter, StringAlignmentFar ); //--------------------------------------------------------------------------- // DriverStringOptions //--------------------------------------------------------------------------- TGPDriverStringOptions = Integer; const DriverStringOptionsCmapLookup = 1; DriverStringOptionsVertical = 2; DriverStringOptionsRealizedAdvance = 4; DriverStringOptionsLimitSubpixel = 8; //--------------------------------------------------------------------------- // Flush Intention flags //--------------------------------------------------------------------------- type TGPFlushIntention = ( FlushIntentionFlush, // Flush all batched rendering operations FlushIntentionSync // Flush all batched rendering operations // and wait for them to complete ); //--------------------------------------------------------------------------- // Image encoder parameter related types //--------------------------------------------------------------------------- TGPEncoderParameterValueType = Integer; const EncoderParameterValueTypeByte : Integer = 1; // 8-bit unsigned int EncoderParameterValueTypeASCII : Integer = 2; // 8-bit byte containing one 7-bit ASCII // code. NULL terminated. EncoderParameterValueTypeShort : Integer = 3; // 16-bit unsigned int EncoderParameterValueTypeLong : Integer = 4; // 32-bit unsigned int EncoderParameterValueTypeRational : Integer = 5; // Two Longs. The first Long is the // numerator, the second Long expresses the // denomintor. EncoderParameterValueTypeLongRange : Integer = 6; // Two longs which specify a range of // integer values. The first Long specifies // the lower end and the second one // specifies the higher end. All values // are inclusive at both ends EncoderParameterValueTypeUndefined : Integer = 7; // 8-bit byte that can take any value // depending on field definition EncoderParameterValueTypeRationalRange : Integer = 8; // Two Rationals. The first Rational // specifies the lower end and the second // specifies the higher end. All values // are inclusive at both ends //--------------------------------------------------------------------------- // Image encoder value types //--------------------------------------------------------------------------- type TGPEncoderValue = ( EncoderValueColorTypeCMYK, EncoderValueColorTypeYCCK, EncoderValueCompressionLZW, EncoderValueCompressionCCITT3, EncoderValueCompressionCCITT4, EncoderValueCompressionRle, EncoderValueCompressionNone, EncoderValueScanMethodInterlaced, EncoderValueScanMethodNonInterlaced, EncoderValueVersionGif87, EncoderValueVersionGif89, EncoderValueRenderProgressive, EncoderValueRenderNonProgressive, EncoderValueTransformRotate90, EncoderValueTransformRotate180, EncoderValueTransformRotate270, EncoderValueTransformFlipHorizontal, EncoderValueTransformFlipVertical, EncoderValueMultiFrame, EncoderValueLastFrame, EncoderValueFlush, EncoderValueFrameDimensionTime, EncoderValueFrameDimensionResolution, EncoderValueFrameDimensionPage ); //--------------------------------------------------------------------------- // Conversion of Emf To WMF Bits flags //--------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPEmfToWmfBitsFlags = Integer; const EmfToWmfBitsFlagsDefault = $00000000; EmfToWmfBitsFlagsEmbedEmf = $00000001; EmfToWmfBitsFlagsIncludePlaceable = $00000002; EmfToWmfBitsFlagsNoXORClip = $00000004; {$ELSE} TGPEmfToWmfBitsFlags = ( EmfToWmfBitsFlagsDefault = $00000000, EmfToWmfBitsFlagsEmbedEmf = $00000001, EmfToWmfBitsFlagsIncludePlaceable = $00000002, EmfToWmfBitsFlagsNoXORClip = $00000004 ); {$ENDIF} (**************************************************************************\ * * GDI+ Types * \**************************************************************************) //-------------------------------------------------------------------------- // Callback functions //-------------------------------------------------------------------------- type TGPImageAbort = function ( callbackData: Pointer ) : BOOL; stdcall; TGPDrawImageAbort = TGPImageAbort; TGPGetThumbnailImageAbort = TGPImageAbort; TGPImageAbortProc = function() : BOOL of object; TGPDrawImageAbortProc = TGPImageAbortProc; TGPGetThumbnailImageAbortProc = TGPImageAbortProc; // Callback for EnumerateMetafile methods. The parameters are: // recordType WMF, EMF, or EMF+ record type // flags (always 0 for WMF/EMF records) // dataSize size of the record data (in bytes), or 0 if no data // data pointer to the record data, or NULL if no data // callbackData pointer to callbackData, if any // This method can then call Metafile::PlayRecord to play the // record that was just enumerated. If this method returns // FALSE, the enumeration process is aborted. Otherwise, it continues. TGPEnumerateMetafileProc = function( recordType: TGPEmfPlusRecordType; flags: UINT; dataSize: UINT; data: PBYTE ) : BOOL of object; //-------------------------------------------------------------------------- // Primitive data types // // NOTE: // Types already defined in standard header files: // INT8 // UINT8 // INT16 // UINT16 // INT32 // UINT32 // INT64 // UINT64 // // Avoid using the following types: // LONG - use INT // ULONG - use UINT // DWORD - use UINT32 //-------------------------------------------------------------------------- const { from float.h } FLT_MAX = 3.402823466e+38; // max value {$EXTERNALSYM FLT_MAX} FLT_MIN = 1.175494351e-38; // min positive value {$EXTERNALSYM FLT_MIN} REAL_MAX = FLT_MAX; {$EXTERNALSYM REAL_MAX} REAL_MIN = FLT_MIN; {$EXTERNALSYM REAL_MIN} REAL_TOLERANCE = (FLT_MIN * 100); {$EXTERNALSYM REAL_TOLERANCE} REAL_EPSILON = 1.192092896e-07; // FLT_EPSILON {$EXTERNALSYM REAL_EPSILON} //-------------------------------------------------------------------------- // Status return values from GDI+ methods //-------------------------------------------------------------------------- type TGPStatus = ( Ok, GenericError, InvalidParameter, OutOfMemory, ObjectBusy, InsufficientBuffer, NotImplemented, Win32Error, WrongState, Aborted, FileNotFound, ValueOverflow, AccessDenied, UnknownImageFormat, FontFamilyNotFound, FontStyleNotFound, NotTrueTypeFont, UnsupportedGdiplusVersion, GdiplusNotInitialized, PropertyNotFound, PropertyNotSupported, ProfileNotFound ); type EGPLoadError = class(Exception); (**************************************************************************\ * * GDI+ base memory allocation class * \**************************************************************************) { type TGdiplusBase = class( TInterfacedObject ) protected class procedure ErrorCheck( AStatus : TGPStatus ); public class function NewInstance() : TObject; override; procedure FreeInstance(); override; end; } //-------------------------------------------------------------------------- // Represents a dimension in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- type PGPSizeF = ^TGPSizeF; TGPSizeF = packed record Width : Single; Height : Single; end; function MakeSizeF( Width, Height: Single) : TGPSizeF; overload; function MakeSizeF( ASize : Single) : TGPSizeF; overload; //-------------------------------------------------------------------------- // Represents a dimension in a 2D coordinate system (integer coordinates) //-------------------------------------------------------------------------- type PGPSize = ^TGPSize; TGPSize = packed record Width : Integer; Height : Integer; end; function MakeSize( Width, Height: Integer ) : TGPSize; overload; function MakeSize( ASize : Integer ) : TGPSize; overload; //-------------------------------------------------------------------------- // Represents a location in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- type PGPPointF = ^TGPPointF; TGPPointF = packed record X : Single; Y : Single; end; //-------------------------------------------------------------------------- // Represents a location in a 2D coordinate system (integer coordinates) //-------------------------------------------------------------------------- type PGPPoint = ^TGPPoint; TGPPoint = TPoint; function MakePointF( X, Y: Single ) : TGPPointF; overload; function MakePointF( XY: Single ) : TGPPointF; overload; function MakePointF( APoint : TGPPoint ) : TGPPointF; overload; function MakePoint( X, Y: Integer ) : TGPPoint; overload; function MakePoint( XY: Integer ) : TGPPoint; overload; function MakePoint( APoint : TPoint ) : TGPPoint; overload; //-------------------------------------------------------------------------- // Represents a rectangle in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- type PGPRectF = ^TGPRectF; TGPRectF = packed record X : Single; Y : Single; Width : Single; Height: Single; end; type PGPRect = ^TGPRect; TGPRect = packed record X : Integer; Y : Integer; Width : Integer; Height: Integer; end; function MakeRectF(x, y, width, height: Single) : TGPRectF; overload; function MakeRectF(location: TGPPointF; size: TGPSizeF) : TGPRectF; overload; function MakeRectF( const Rect: TRect ) : TGPRectF; overload; function MakeRectF( const Rect: TGPRect ) : TGPRectF; overload; function MakeRect(x, y, width, height: Integer) : TGPRect; overload; function MakeRect(location: TGPPoint; size: TGPSize) : TGPRect; overload; function MakeRect(const Rect: TRect) : TGPRect; overload; function RectFrom( const Rect: TGPRect ) : TRect; function GPInflateRect( ARect: TGPRect; CX, CY: Integer ) : TGPRect; overload; function GPInflateRect( ARect: TGPRect; Change: Integer ) : TGPRect; overload; function GPInflateRectF( ARect: TGPRectF; CX, CY: Single ) : TGPRectF; overload; function GPInflateRectF( ARect: TGPRectF; Change: Single ) : TGPRectF; overload; function GPIntersectRect( ARect1 : TGPRect; ARect2 : TGPRect ) : TGPRect; function GPCheckIntersectRect( ARect1 : TGPRect; ARect2 : TGPRect ) : Boolean; function GPEqualRect( ARect1 : TGPRect; ARect2 : TGPRect ) : Boolean; type PGPCharacterRange = ^TGPCharacterRange; TGPCharacterRange = packed record First : Integer; Length : Integer; end; function MakeCharacterRange(First, Length: Integer) : TGPCharacterRange; (************************************************************************** * * GDI+ Startup and Shutdown APIs * **************************************************************************) type TGPDebugEventLevel = ( DebugEventLevelFatal, DebugEventLevelWarning ); // Callback function that GDI+ can call, on debug builds, for assertions // and warnings. TGPDebugEventProc = procedure(level: TGPDebugEventLevel; message: PChar); stdcall; // Notification functions which the user must call appropriately if // "SuppressBackgroundThread" (below) is set. TGPNotificationHookProc = function(out token: Pointer) : TGPStatus; stdcall; TGPNotificationUnhookProc = procedure(token: Pointer); stdcall; // Input structure for GdiplusStartup TGPGdiplusStartupInput = packed record GdiplusVersion : Cardinal; // Must be 1 DebugEventCallback : TGPDebugEventProc; // Ignored on free builds SuppressBackgroundThread: BOOL; // FALSE unless you're prepared to call // the hook/unhook functions properly SuppressExternalCodecs : BOOL; // FALSE unless you want GDI+ only to use end; // its internal image codecs. PGPGdiplusStartupInput = ^TGPGdiplusStartupInput; // Output structure for GdiplusStartup() TGPGdiplusStartupOutput = packed record // The following 2 fields are NULL if SuppressBackgroundThread is FALSE. // Otherwise, they are functions which must be called appropriately to // replace the background thread. // // These should be called on the application's main message loop - i.e. // a message loop which is active for the lifetime of GDI+. // "NotificationHook" should be called before starting the loop, // and "NotificationUnhook" should be called after the loop ends. NotificationHook : TGPNotificationHookProc; NotificationUnhook: TGPNotificationUnhookProc; end; PGPGdiplusStartupOutput = ^TGPGdiplusStartupOutput; // GDI+ initialization. Must not be called from DllMain - can cause deadlock. // // Must be called before GDI+ API's or constructors are used. // // token - may not be NULL - accepts a token to be passed in the corresponding // GdiplusShutdown call. // input - may not be NULL // output - may be NULL only if input->SuppressBackgroundThread is FALSE. (* {$EXTERNALSYM GdiplusStartup} function GdiplusStartup(out token: ULONG; input: PGdiplusStartupInput; output: PGdiplusStartupOutput) : TGPStatus; stdcall; // GDI+ termination. Must be called before GDI+ is unloaded. // Must not be called from DllMain - can cause deadlock. // // GDI+ API's may not be called after GdiplusShutdown. Pay careful attention // to GDI+ object destructors. {$EXTERNALSYM GdiplusShutdown} procedure GdiplusShutdown(token: ULONG); stdcall; *) (**************************************************************************\ * * Copyright (c) 1998-2001, Microsoft Corp. All Rights Reserved. * Module Name: * Gdiplus Pixel Formats * Abstract: * GDI+ Pixel Formats * \**************************************************************************) type {$IFDEF DELPHI16_UP} PGPColor = PAlphaColor; TGPColor = TAlphaColor; {$ELSE} PGPColor = ^TGPColor; TGPColor = 0..$FFFFFFFF; {$ENDIF} type TGPPixelFormat = Integer; const PixelFormatIndexed = $00010000; // Indexes into a palette PixelFormatGDI = $00020000; // Is a GDI-supported format PixelFormatAlpha = $00040000; // Has an alpha component PixelFormatPAlpha = $00080000; // Pre-multiplied alpha PixelFormatExtended = $00100000; // Extended color 16 bits/channel PixelFormatCanonical = $00200000; PixelFormatUndefined = 0; PixelFormatDontCare = 0; PixelFormat1bppIndexed = (1 or ( 1 shl 8) or PixelFormatIndexed or PixelFormatGDI); PixelFormat4bppIndexed = (2 or ( 4 shl 8) or PixelFormatIndexed or PixelFormatGDI); PixelFormat8bppIndexed = (3 or ( 8 shl 8) or PixelFormatIndexed or PixelFormatGDI); PixelFormat16bppGrayScale = (4 or (16 shl 8) or PixelFormatExtended); PixelFormat16bppRGB555 = (5 or (16 shl 8) or PixelFormatGDI); PixelFormat16bppRGB565 = (6 or (16 shl 8) or PixelFormatGDI); PixelFormat16bppARGB1555 = (7 or (16 shl 8) or PixelFormatAlpha or PixelFormatGDI); PixelFormat24bppRGB = (8 or (24 shl 8) or PixelFormatGDI); PixelFormat32bppRGB = (9 or (32 shl 8) or PixelFormatGDI); PixelFormat32bppARGB = (10 or (32 shl 8) or PixelFormatAlpha or PixelFormatGDI or PixelFormatCanonical); PixelFormat32bppPARGB = (11 or (32 shl 8) or PixelFormatAlpha or PixelFormatPAlpha or PixelFormatGDI); PixelFormat48bppRGB = (12 or (48 shl 8) or PixelFormatExtended); PixelFormat64bppARGB = (13 or (64 shl 8) or PixelFormatAlpha or PixelFormatCanonical or PixelFormatExtended); PixelFormat64bppPARGB = (14 or (64 shl 8) or PixelFormatAlpha or PixelFormatPAlpha or PixelFormatExtended); PixelFormatMax = 15; function GetPixelFormatSize(pixfmt: TGPPixelFormat) : Cardinal; function IsIndexedPixelFormat(pixfmt: TGPPixelFormat) : Boolean; function IsAlphaPixelFormat(pixfmt: TGPPixelFormat) : Boolean; function IsExtendedPixelFormat(pixfmt: TGPPixelFormat) : Boolean; //-------------------------------------------------------------------------- // Determine if the Pixel Format is Canonical format: // PixelFormat32bppARGB // PixelFormat32bppPARGB // PixelFormat64bppARGB // PixelFormat64bppPARGB //-------------------------------------------------------------------------- function IsCanonicalPixelFormat(pixfmt: TGPPixelFormat) : Boolean; {$IFDEF DELPHI5_DOWN} type TGPPaletteFlags = Integer; const PaletteFlagsHasAlpha = $0001; PaletteFlagsGrayScale = $0002; PaletteFlagsHalftone = $0004; {$ELSE} type TGPPaletteFlags = ( PaletteFlagsHasAlpha = $0001, PaletteFlagsGrayScale = $0002, PaletteFlagsHalftone = $0004 ); {$ENDIF} type TGPColorPalette = packed record Flags : UINT ; // Palette flags Count : UINT ; // Number of color entries Entries: array [0..0] of TGPColor ; // Palette color entries end; PGPColorPalette = ^TGPColorPalette; (**************************************************************************\ * * GDI+ Color Object * \**************************************************************************) //---------------------------------------------------------------------------- // Color mode //---------------------------------------------------------------------------- TGPColorMode = ( ColorModeARGB32, ColorModeARGB64 ); //---------------------------------------------------------------------------- // Color Channel flags //---------------------------------------------------------------------------- TGPColorChannelFlags = ( ColorChannelFlagsC, ColorChannelFlagsM, ColorChannelFlagsY, ColorChannelFlagsK, ColorChannelFlagsLast ); //---------------------------------------------------------------------------- // Color //---------------------------------------------------------------------------- // Common color constants const aclAliceBlue = $FFF0F8FF; aclAntiqueWhite = $FFFAEBD7; aclAqua = $FF00FFFF; aclAquamarine = $FF7FFFD4; aclAzure = $FFF0FFFF; aclBeige = $FFF5F5DC; aclBisque = $FFFFE4C4; aclBlack = $FF000000; aclBlanchedAlmond = $FFFFEBCD; aclBlue = $FF0000FF; aclBlueViolet = $FF8A2BE2; aclBrown = $FFA52A2A; aclBurlyWood = $FFDEB887; aclCadetBlue = $FF5F9EA0; aclChartreuse = $FF7FFF00; aclChocolate = $FFD2691E; aclCoral = $FFFF7F50; aclCornflowerBlue = $FF6495ED; aclCornsilk = $FFFFF8DC; aclCrimson = $FFDC143C; aclCyan = $FF00FFFF; aclDarkBlue = $FF00008B; aclDarkCyan = $FF008B8B; aclDarkGoldenrod = $FFB8860B; aclDarkGray = $FFA9A9A9; aclDarkGreen = $FF006400; aclDarkKhaki = $FFBDB76B; aclDarkMagenta = $FF8B008B; aclDarkOliveGreen = $FF556B2F; aclDarkOrange = $FFFF8C00; aclDarkOrchid = $FF9932CC; aclDarkRed = $FF8B0000; aclDarkSalmon = $FFE9967A; aclDarkSeaGreen = $FF8FBC8B; aclDarkSlateBlue = $FF483D8B; aclDarkSlateGray = $FF2F4F4F; aclDarkTurquoise = $FF00CED1; aclDarkViolet = $FF9400D3; aclDeepPink = $FFFF1493; aclDeepSkyBlue = $FF00BFFF; aclDimGray = $FF696969; aclDodgerBlue = $FF1E90FF; aclFirebrick = $FFB22222; aclFloralWhite = $FFFFFAF0; aclForestGreen = $FF228B22; aclFuchsia = $FFFF00FF; aclGainsboro = $FFDCDCDC; aclGhostWhite = $FFF8F8FF; aclGold = $FFFFD700; aclGoldenrod = $FFDAA520; aclGray = $FF808080; aclGreen = $FF008000; aclGreenYellow = $FFADFF2F; aclHoneydew = $FFF0FFF0; aclHotPink = $FFFF69B4; aclIndianRed = $FFCD5C5C; aclIndigo = $FF4B0082; aclIvory = $FFFFFFF0; aclKhaki = $FFF0E68C; aclLavender = $FFE6E6FA; aclLavenderBlush = $FFFFF0F5; aclLawnGreen = $FF7CFC00; aclLemonChiffon = $FFFFFACD; aclLightBlue = $FFADD8E6; aclLightCoral = $FFF08080; aclLightCyan = $FFE0FFFF; aclLightGoldenrodYellow = $FFFAFAD2; aclLightGray = $FFD3D3D3; aclLightGreen = $FF90EE90; aclLightPink = $FFFFB6C1; aclLightSalmon = $FFFFA07A; aclLightSeaGreen = $FF20B2AA; aclLightSkyBlue = $FF87CEFA; aclLightSlateGray = $FF778899; aclLightSteelBlue = $FFB0C4DE; aclLightYellow = $FFFFFFE0; aclLime = $FF00FF00; aclLimeGreen = $FF32CD32; aclLinen = $FFFAF0E6; aclMagenta = $FFFF00FF; aclMaroon = $FF800000; aclMediumAquamarine = $FF66CDAA; aclMediumBlue = $FF0000CD; aclMediumOrchid = $FFBA55D3; aclMediumPurple = $FF9370DB; aclMediumSeaGreen = $FF3CB371; aclMediumSlateBlue = $FF7B68EE; aclMediumSpringGreen = $FF00FA9A; aclMediumTurquoise = $FF48D1CC; aclMediumVioletRed = $FFC71585; aclMidnightBlue = $FF191970; aclMintCream = $FFF5FFFA; aclMistyRose = $FFFFE4E1; aclMoccasin = $FFFFE4B5; aclNavajoWhite = $FFFFDEAD; aclNavy = $FF000080; aclOldLace = $FFFDF5E6; aclOlive = $FF808000; aclOliveDrab = $FF6B8E23; aclOrange = $FFFFA500; aclOrangeRed = $FFFF4500; aclOrchid = $FFDA70D6; aclPaleGoldenrod = $FFEEE8AA; aclPaleGreen = $FF98FB98; aclPaleTurquoise = $FFAFEEEE; aclPaleVioletRed = $FFDB7093; aclPapayaWhip = $FFFFEFD5; aclPeachPuff = $FFFFDAB9; aclPeru = $FFCD853F; aclPink = $FFFFC0CB; aclPlum = $FFDDA0DD; aclPowderBlue = $FFB0E0E6; aclPurple = $FF800080; aclRed = $FFFF0000; aclRosyBrown = $FFBC8F8F; aclRoyalBlue = $FF4169E1; aclSaddleBrown = $FF8B4513; aclSalmon = $FFFA8072; aclSandyBrown = $FFF4A460; aclSeaGreen = $FF2E8B57; aclSeaShell = $FFFFF5EE; aclSienna = $FFA0522D; aclSilver = $FFC0C0C0; aclSkyBlue = $FF87CEEB; aclSlateBlue = $FF6A5ACD; aclSlateGray = $FF708090; aclSnow = $FFFFFAFA; aclSpringGreen = $FF00FF7F; aclSteelBlue = $FF4682B4; aclTan = $FFD2B48C; aclTeal = $FF008080; aclThistle = $FFD8BFD8; aclTomato = $FFFF6347; aclTransparent = $00FFFFFF; aclTurquoise = $FF40E0D0; aclViolet = $FFEE82EE; aclWheat = $FFF5DEB3; aclWhite = $FFFFFFFF; aclWhiteSmoke = $FFF5F5F5; aclYellow = $FFFFFF00; aclYellowGreen = $FF9ACD32; // Shift count and bit mask for A, R, G, B components type TGPColorArray = array of TGPColor; function MakeARGBColor( AAlpha : Byte; AColor : TGPColor ) : TGPColor; function MakeColor( AAlpha : Byte; AColor : TColor ) : TGPColor; overload; function MakeColor( AColor : TColor ) : TGPColor; overload; function MakeColor(r, g, b: Byte) : TGPColor; overload; function MakeColor(a, r, g, b: Byte) : TGPColor; overload; function GPMakeColor( AAlpha : Byte; AColor : TColor ) : TGPColor; overload; function GPMakeColor( AColor : TColor ) : TGPColor; overload; function GPMakeColor(r, g, b: Byte) : TGPColor; overload; function GPMakeColor(a, r, g, b: Byte) : TGPColor; overload; function GetAlpha(color: TGPColor) : BYTE; function GetRed(color: TGPColor) : BYTE; function GetGreen(color: TGPColor) : BYTE; function GetBlue(color: TGPColor) : BYTE; function RGBToBGR(color: TGPColor) : TGPColor; function ColorRefToARGB(rgb: COLORREF) : TGPColor; function ARGBToColorRef(Color: TGPColor) : COLORREF; function StringToRGBAColor( AValue : String ) : TGPColor; function RGBAColorToString( AValue : TGPColor ) : String; procedure GetStandardRGBAColorNames( ANames : TStrings ); function GPGetColor( AColor : TGPColor ) : TColor; (**************************************************************************\ * * GDI+ Metafile Related Structures * \**************************************************************************) type {$HPPEMIT '#pragma pack(push, 1)' } {$HPPEMIT 'struct TGPENHMETAHEADER3' } (*$HPPEMIT '{' *) {$HPPEMIT ' unsigned iType;' } {$HPPEMIT ' unsigned nSize;' } {$HPPEMIT ' RECT rclBounds;' } {$HPPEMIT ' RECT rclFrame;' } {$HPPEMIT ' unsigned dSignature;' } {$HPPEMIT ' unsigned nVersion;' } {$HPPEMIT ' unsigned nBytes;' } {$HPPEMIT ' unsigned nRecords;' } {$HPPEMIT ' Word nHandles;' } {$HPPEMIT ' Word sReserved;' } {$HPPEMIT ' unsigned nDescription;' } {$HPPEMIT ' unsigned offDescription;' } {$HPPEMIT ' unsigned nPalEntries;' } {$HPPEMIT ' tagSIZE szlDevice;' } {$HPPEMIT ' tagSIZE szlMillimeters;' } (*$HPPEMIT '};' *) {$HPPEMIT '#pragma pack(pop)' } {$EXTERNALSYM TGPENHMETAHEADER3} TGPENHMETAHEADER3 = packed record iType : DWORD; // Record type EMR_HEADER nSize : DWORD; // Record size in bytes. This may be greater // than the sizeof(ENHMETAHEADER). rclBounds : TRect; // Inclusive-inclusive bounds in device units rclFrame : TRect; // Inclusive-inclusive Picture Frame .01mm unit dSignature : DWORD; // Signature. Must be ENHMETA_SIGNATURE. nVersion : DWORD; // Version number nBytes : DWORD; // Size of the metafile in bytes nRecords : DWORD; // Number of records in the metafile nHandles : WORD; // Number of handles in the handle table // Handle index zero is reserved. sReserved : WORD; // Reserved. Must be zero. nDescription : DWORD; // Number of chars in the unicode desc string // This is 0 if there is no description string offDescription : DWORD; // Offset to the metafile description record. // This is 0 if there is no description string nPalEntries : DWORD; // Number of entries in the metafile palette. szlDevice : TSize; // Size of the reference device in pels szlMillimeters : TSize; // Size of the reference device in millimeters end; PENHMETAHEADER3 = ^TGPENHMETAHEADER3; // Placeable WMFs // Placeable Metafiles were created as a non-standard way of specifying how // a metafile is mapped and scaled on an output device. // Placeable metafiles are quite wide-spread, but not directly supported by // the Windows API. To playback a placeable metafile using the Windows API, // you will first need to strip the placeable metafile header from the file. // This is typically performed by copying the metafile to a temporary file // starting at file offset 22 (0x16). The contents of the temporary file may // then be used as input to the Windows GetMetaFile(), PlayMetaFile(), // CopyMetaFile(), etc. GDI functions. // Each placeable metafile begins with a 22-byte header, // followed by a standard metafile: TPWMFRect16 = packed record Left : INT16; Top : INT16; Right : INT16; Bottom : INT16; end; PPWMFRect16 = ^TPWMFRect16; TGPWmfPlaceableFileHeader = packed record Key : Cardinal; // GDIP_WMF_PLACEABLEKEY Hmf : INT16; // Metafile HANDLE number (always 0) BoundingBox : TPWMFRect16; // Coordinates in metafile units Inch : INT16; // Number of metafile units per inch Reserved : Cardinal; // Reserved (always 0) Checksum : INT16; // Checksum value for previous 10 WORDs end; PGPWmfPlaceableFileHeader = ^TGPWmfPlaceableFileHeader; // Key contains a special identification value that indicates the presence // of a placeable metafile header and is always 0x9AC6CDD7. // Handle is used to stored the handle of the metafile in memory. When written // to disk, this field is not used and will always contains the value 0. // Left, Top, Right, and Bottom contain the coordinates of the upper-left // and lower-right corners of the image on the output device. These are // measured in twips. // A twip (meaning "twentieth of a point") is the logical unit of measurement // used in Windows Metafiles. A twip is equal to 1/1440 of an inch. Thus 720 // twips equal 1/2 inch, while 32,768 twips is 22.75 inches. // Inch contains the number of twips per inch used to represent the image. // Normally, there are 1440 twips per inch; however, this number may be // changed to scale the image. A value of 720 indicates that the image is // double its normal size, or scaled to a factor of 2:1. A value of 360 // indicates a scale of 4:1, while a value of 2880 indicates that the image // is scaled down in size by a factor of two. A value of 1440 indicates // a 1:1 scale ratio. // Reserved is not used and is always set to 0. // Checksum contains a checksum value for the previous 10 WORDs in the header. // This value can be used in an attempt to detect if the metafile has become // corrupted. The checksum is calculated by XORing each WORD value to an // initial value of 0. // If the metafile was recorded with a reference Hdc that was a display. const GDIP_EMFPLUSFLAGS_DISPLAY = $00000001; {$EXTERNALSYM GDIP_EMFPLUSFLAGS_DISPLAY} (**************************************************************************\ * * GDI+ Imaging GUIDs * \**************************************************************************) //--------------------------------------------------------------------------- // Image file format identifiers //--------------------------------------------------------------------------- const ImageFormatUndefined : TGUID = '{b96b3ca9-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatUndefined} ImageFormatMemoryBMP : TGUID = '{b96b3caa-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatMemoryBMP} ImageFormatBMP : TGUID = '{b96b3cab-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatBMP} ImageFormatEMF : TGUID = '{b96b3cac-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatEMF} ImageFormatWMF : TGUID = '{b96b3cad-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatWMF} ImageFormatJPEG : TGUID = '{b96b3cae-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatJPEG} ImageFormatPNG : TGUID = '{b96b3caf-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatPNG} ImageFormatGIF : TGUID = '{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatGIF} ImageFormatTIFF : TGUID = '{b96b3cb1-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatTIFF} ImageFormatEXIF : TGUID = '{b96b3cb2-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatEXIF} ImageFormatIcon : TGUID = '{b96b3cb5-0728-11d3-9d7b-0000f81ef32e}'; {$EXTERNALSYM ImageFormatIcon} //--------------------------------------------------------------------------- // Predefined multi-frame dimension IDs //--------------------------------------------------------------------------- FrameDimensionTime : TGUID = '{6aedbd6d-3fb5-418a-83a6-7f45229dc872}'; {$EXTERNALSYM FrameDimensionTime} FrameDimensionResolution : TGUID = '{84236f7b-3bd3-428f-8dab-4ea1439ca315}'; {$EXTERNALSYM FrameDimensionResolution} FrameDimensionPage : TGUID = '{7462dc86-6180-4c7e-8e3f-ee7333a7a483}'; {$EXTERNALSYM FrameDimensionPage} //--------------------------------------------------------------------------- // Property sets //--------------------------------------------------------------------------- FormatIDImageInformation : TGUID = '{e5836cbe-5eef-4f1d-acde-ae4c43b608ce}'; {$EXTERNALSYM FormatIDImageInformation} FormatIDJpegAppHeaders : TGUID = '{1c4afdcd-6177-43cf-abc7-5f51af39ee85}'; {$EXTERNALSYM FormatIDJpegAppHeaders} //--------------------------------------------------------------------------- // Encoder parameter sets //--------------------------------------------------------------------------- EncoderCompression : TGUID = '{e09d739d-ccd4-44ee-8eba-3fbf8be4fc58}'; {$EXTERNALSYM EncoderCompression} EncoderColorDepth : TGUID = '{66087055-ad66-4c7c-9a18-38a2310b8337}'; {$EXTERNALSYM EncoderColorDepth} EncoderScanMethod : TGUID = '{3a4e2661-3109-4e56-8536-42c156e7dcfa}'; {$EXTERNALSYM EncoderScanMethod} EncoderVersion : TGUID = '{24d18c76-814a-41a4-bf53-1c219cccf797}'; {$EXTERNALSYM EncoderVersion} EncoderRenderMethod : TGUID = '{6d42c53a-229a-4825-8bb7-5c99e2b9a8b8}'; {$EXTERNALSYM EncoderRenderMethod} EncoderQuality : TGUID = '{1d5be4b5-fa4a-452d-9cdd-5db35105e7eb}'; {$EXTERNALSYM EncoderQuality} EncoderTransformation : TGUID = '{8d0eb2d1-a58e-4ea8-aa14-108074b7b6f9}'; {$EXTERNALSYM EncoderTransformation} EncoderLuminanceTable : TGUID = '{edb33bce-0266-4a77-b904-27216099e717}'; {$EXTERNALSYM EncoderLuminanceTable} EncoderChrominanceTable : TGUID = '{f2e455dc-09b3-4316-8260-676ada32481c}'; {$EXTERNALSYM EncoderChrominanceTable} EncoderSaveFlag : TGUID = '{292266fc-ac40-47bf-8cfc-a85b89a655de}'; {$EXTERNALSYM EncoderSaveFlag} CodecIImageBytes : TGUID = '{025d1823-6c7d-447b-bbdb-a3cbc3dfa2fc}'; {$EXTERNALSYM CodecIImageBytes} type IGPImageBytes = Interface(IUnknown) ['{025D1823-6C7D-447B-BBDB-A3CBC3DFA2FC}'] // Return total number of bytes in the IStream function CountBytes(out pcb: UINT) : HRESULT; stdcall; // Locks "cb" bytes, starting from "ulOffset" in the stream, and returns the // pointer to the beginning of the locked memory chunk in "ppvBytes" function LockBytes(cb: UINT; ulOffset: ULONG; out ppvBytes: Pointer) : HRESULT; stdcall; // Unlocks "cb" bytes, pointed by "pvBytes", starting from "ulOffset" in the // stream function UnlockBytes(pvBytes: Pointer; cb: UINT; ulOffset: ULONG) : HRESULT; stdcall; end; //-------------------------------------------------------------------------- // ImageCodecInfo structure //-------------------------------------------------------------------------- TGPImageCodecInfo = packed record Clsid : TGUID; FormatID : TGUID; CodecName : PWCHAR; DllName : PWCHAR; FormatDescription : PWCHAR; FilenameExtension : PWCHAR; MimeType : PWCHAR; Flags : DWORD; Version : DWORD; SigCount : DWORD; SigSize : DWORD; SigPattern : PBYTE; SigMask : PBYTE; end; TGPImageCodecInfoArray = array of TGPImageCodecInfo; PGPImageCodecInfo = ^TGPImageCodecInfo; //-------------------------------------------------------------------------- // Information flags about image codecs //-------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPImageCodecFlags = Integer; const ImageCodecFlagsEncoder = $00000001; ImageCodecFlagsDecoder = $00000002; ImageCodecFlagsSupportBitmap = $00000004; ImageCodecFlagsSupportVector = $00000008; ImageCodecFlagsSeekableEncode = $00000010; ImageCodecFlagsBlockingDecode = $00000020; ImageCodecFlagsBuiltin = $00010000; ImageCodecFlagsSystem = $00020000; ImageCodecFlagsUser = $00040000; {$ELSE} {$EXTERNALSYM TGPImageCodecFlags} TGPImageCodecFlags = ( ImageCodecFlagsEncoder = $00000001, ImageCodecFlagsDecoder = $00000002, ImageCodecFlagsSupportBitmap = $00000004, ImageCodecFlagsSupportVector = $00000008, ImageCodecFlagsSeekableEncode = $00000010, ImageCodecFlagsBlockingDecode = $00000020, ImageCodecFlagsBuiltin = $00010000, ImageCodecFlagsSystem = $00020000, ImageCodecFlagsUser = $00040000 ); (*$HPPEMIT 'enum TGPImageCodecFlags' *) (*$HPPEMIT '{' *) (*$HPPEMIT ' ImageCodecFlagsEncoder = 0x00000001,' *) (*$HPPEMIT ' ImageCodecFlagsDecoder = 0x00000002,' *) (*$HPPEMIT ' ImageCodecFlagsSupportBitmap = 0x00000004,' *) (*$HPPEMIT ' ImageCodecFlagsSupportVector = 0x00000008,' *) (*$HPPEMIT ' ImageCodecFlagsSeekableEncode = 0x00000010,' *) (*$HPPEMIT ' ImageCodecFlagsBlockingDecode = 0x00000020,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' ImageCodecFlagsBuiltin = 0x00010000,' *) (*$HPPEMIT ' ImageCodecFlagsSystem = 0x00020000,' *) (*$HPPEMIT ' ImageCodecFlagsUser = 0x00040000' *) (*$HPPEMIT '};' *) {$ENDIF} //--------------------------------------------------------------------------- // Access modes used when calling Image::LockBits //--------------------------------------------------------------------------- type TGPImageLockMode = Integer; const ImageLockModeRead = $0001; ImageLockModeWrite = $0002; ImageLockModeUserInputBuf = $0004; //--------------------------------------------------------------------------- // Information about image pixel data //--------------------------------------------------------------------------- type TGPBitmapDataRecord = packed record Width : UINT; Height : UINT; Stride : Integer; PixelFormat : TGPPixelFormat; Scan0 : Pointer; Reserved : Pointer; end; //--------------------------------------------------------------------------- // Image flags //--------------------------------------------------------------------------- {$IFDEF DELPHI5_DOWN} TGPImageFlags = Integer; const ImageFlagsNone = 0; // Low-word: shared with SINKFLAG_x ImageFlagsScalable = $0001; ImageFlagsHasAlpha = $0002; ImageFlagsHasTranslucent = $0004; ImageFlagsPartiallyScalable = $0008; // Low-word: color space definition ImageFlagsColorSpaceRGB = $0010; ImageFlagsColorSpaceCMYK = $0020; ImageFlagsColorSpaceGRAY = $0040; ImageFlagsColorSpaceYCBCR = $0080; ImageFlagsColorSpaceYCCK = $0100; // Low-word: image size info ImageFlagsHasRealDPI = $1000; ImageFlagsHasRealPixelSize = $2000; // High-word ImageFlagsReadOnly = $00010000; ImageFlagsCaching = $00020000; {$ELSE} {$EXTERNALSYM TGPImageFlags} TGPImageFlags = ( ImageFlagsNone = 0, // Low-word: shared with SINKFLAG_x ImageFlagsScalable = $0001, ImageFlagsHasAlpha = $0002, ImageFlagsHasTranslucent = $0004, ImageFlagsPartiallyScalable = $0008, // Low-word: color space definition ImageFlagsColorSpaceRGB = $0010, ImageFlagsColorSpaceCMYK = $0020, ImageFlagsColorSpaceGRAY = $0040, ImageFlagsColorSpaceYCBCR = $0080, ImageFlagsColorSpaceYCCK = $0100, // Low-word: image size info ImageFlagsHasRealDPI = $1000, ImageFlagsHasRealPixelSize = $2000, // High-word ImageFlagsReadOnly = $00010000, ImageFlagsCaching = $00020000 ); (*$HPPEMIT 'enum TGPImageFlags' *) (*$HPPEMIT '{' *) (*$HPPEMIT ' ImageFlagsNone = 0x0000,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Low-word: shared with SINKFLAG_x' *) (*$HPPEMIT '' *) (*$HPPEMIT ' ImageFlagsScalable = 0x0001,' *) (*$HPPEMIT ' ImageFlagsHasAlpha = 0x0002,' *) (*$HPPEMIT ' ImageFlagsHasTranslucent = 0x0004,' *) (*$HPPEMIT ' ImageFlagsPartiallyScalable = 0x0008,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Low-word: color space definition' *) (*$HPPEMIT '' *) (*$HPPEMIT ' ImageFlagsColorSpaceRGB = 0x0010,' *) (*$HPPEMIT ' ImageFlagsColorSpaceCMYK = 0x0020,' *) (*$HPPEMIT ' ImageFlagsColorSpaceGRAY = 0x0040,' *) (*$HPPEMIT ' ImageFlagsColorSpaceYCBCR = 0x0080,' *) (*$HPPEMIT ' ImageFlagsColorSpaceYCCK = 0x0100,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // Low-word: image size info' *) (*$HPPEMIT '' *) (*$HPPEMIT ' ImageFlagsHasRealDPI = 0x1000,' *) (*$HPPEMIT ' ImageFlagsHasRealPixelSize = 0x2000,' *) (*$HPPEMIT '' *) (*$HPPEMIT ' // High-word' *) (*$HPPEMIT '' *) (*$HPPEMIT ' ImageFlagsReadOnly = 0x00010000,' *) (*$HPPEMIT ' ImageFlagsCaching = 0x00020000' *) (*$HPPEMIT '};' *) {$ENDIF} {$IFDEF DELPHI5_DOWN} type TGPRotateFlipType = ( RotateNoneFlipNone, // = 0, Rotate90FlipNone, // = 1, Rotate180FlipNone, // = 2, Rotate270FlipNone, // = 3, RotateNoneFlipX, // = 4, Rotate90FlipX, // = 5, Rotate180FlipX, // = 6, Rotate270FlipX // = 7, ); const RotateNoneFlipY = Rotate180FlipX; Rotate90FlipY = Rotate270FlipX; Rotate180FlipY = RotateNoneFlipX; Rotate270FlipY = Rotate90FlipX; RotateNoneFlipXY = Rotate180FlipNone; Rotate90FlipXY = Rotate270FlipNone; Rotate180FlipXY = RotateNoneFlipNone; Rotate270FlipXY = Rotate90FlipNone; {$ELSE} TGPRotateFlipType = ( RotateNoneFlipNone = 0, Rotate90FlipNone = 1, Rotate180FlipNone = 2, Rotate270FlipNone = 3, RotateNoneFlipX = 4, Rotate90FlipX = 5, Rotate180FlipX = 6, Rotate270FlipX = 7, RotateNoneFlipY = Rotate180FlipX, Rotate90FlipY = Rotate270FlipX, Rotate180FlipY = RotateNoneFlipX, Rotate270FlipY = Rotate90FlipX, RotateNoneFlipXY = Rotate180FlipNone, Rotate90FlipXY = Rotate270FlipNone, Rotate180FlipXY = RotateNoneFlipNone, Rotate270FlipXY = Rotate90FlipNone ); {$ENDIF} //--------------------------------------------------------------------------- // Encoder Parameter structure //--------------------------------------------------------------------------- type TGPEncoderParameter = packed record Guid : TGUID; // GUID of the parameter NumberOfValues : ULONG; // Number of the parameter values DataType : ULONG; // Value type, like ValueTypeLONG etc. Value : Pointer; // A pointer to the parameter values end; PGPEncoderParameter = ^TGPEncoderParameter; //--------------------------------------------------------------------------- // Encoder Parameters structure //--------------------------------------------------------------------------- TGPEncoderParameters = packed record Count : UINT; // Number of parameters in this structure Parameter : array[0..0] of TGPEncoderParameter; // Parameter values end; PGPEncoderParameters = ^TGPEncoderParameters; //--------------------------------------------------------------------------- // Property Item //--------------------------------------------------------------------------- TGPPropertyItem = record // NOT PACKED !! id : PROPID; // ID of this property length : ULONG; // Length of the property value, in bytes DataType : WORD; // Type of the value, as one of TAG_TYPE_XXX value : Pointer; // property value end; PGPPropertyItem = ^TGPPropertyItem; //--------------------------------------------------------------------------- // Image property types //--------------------------------------------------------------------------- const PropertyTagTypeByte : Integer = 1; PropertyTagTypeASCII : Integer = 2; PropertyTagTypeShort : Integer = 3; PropertyTagTypeLong : Integer = 4; PropertyTagTypeRational : Integer = 5; PropertyTagTypeUndefined : Integer = 7; PropertyTagTypeSLONG : Integer = 9; PropertyTagTypeSRational : Integer = 10; //--------------------------------------------------------------------------- // Image property ID tags //--------------------------------------------------------------------------- PropertyTagExifIFD = $8769; PropertyTagGpsIFD = $8825; PropertyTagNewSubfileType = $00FE; PropertyTagSubfileType = $00FF; PropertyTagImageWidth = $0100; PropertyTagImageHeight = $0101; PropertyTagBitsPerSample = $0102; PropertyTagCompression = $0103; PropertyTagPhotometricInterp = $0106; PropertyTagThreshHolding = $0107; PropertyTagCellWidth = $0108; PropertyTagCellHeight = $0109; PropertyTagFillOrder = $010A; PropertyTagDocumentName = $010D; PropertyTagImageDescription = $010E; PropertyTagEquipMake = $010F; PropertyTagEquipModel = $0110; PropertyTagStripOffsets = $0111; PropertyTagOrientation = $0112; PropertyTagSamplesPerPixel = $0115; PropertyTagRowsPerStrip = $0116; PropertyTagStripBytesCount = $0117; PropertyTagMinSampleValue = $0118; PropertyTagMaxSampleValue = $0119; PropertyTagXResolution = $011A; // Image resolution in width direction PropertyTagYResolution = $011B; // Image resolution in height direction PropertyTagPlanarConfig = $011C; // Image data arrangement PropertyTagPageName = $011D; PropertyTagXPosition = $011E; PropertyTagYPosition = $011F; PropertyTagFreeOffset = $0120; PropertyTagFreeByteCounts = $0121; PropertyTagGrayResponseUnit = $0122; PropertyTagGrayResponseCurve = $0123; PropertyTagT4Option = $0124; PropertyTagT6Option = $0125; PropertyTagResolutionUnit = $0128; // Unit of X and Y resolution PropertyTagPageNumber = $0129; PropertyTagTransferFuncition = $012D; PropertyTagSoftwareUsed = $0131; PropertyTagDateTime = $0132; PropertyTagArtist = $013B; PropertyTagHostComputer = $013C; PropertyTagPredictor = $013D; PropertyTagWhitePoint = $013E; PropertyTagPrimaryChromaticities = $013F; PropertyTagColorMap = $0140; PropertyTagHalftoneHints = $0141; PropertyTagTileWidth = $0142; PropertyTagTileLength = $0143; PropertyTagTileOffset = $0144; PropertyTagTileByteCounts = $0145; PropertyTagInkSet = $014C; PropertyTagInkNames = $014D; PropertyTagNumberOfInks = $014E; PropertyTagDotRange = $0150; PropertyTagTargetPrinter = $0151; PropertyTagExtraSamples = $0152; PropertyTagSampleFormat = $0153; PropertyTagSMinSampleValue = $0154; PropertyTagSMaxSampleValue = $0155; PropertyTagTransferRange = $0156; PropertyTagJPEGProc = $0200; PropertyTagJPEGInterFormat = $0201; PropertyTagJPEGInterLength = $0202; PropertyTagJPEGRestartInterval = $0203; PropertyTagJPEGLosslessPredictors = $0205; PropertyTagJPEGPointTransforms = $0206; PropertyTagJPEGQTables = $0207; PropertyTagJPEGDCTables = $0208; PropertyTagJPEGACTables = $0209; PropertyTagYCbCrCoefficients = $0211; PropertyTagYCbCrSubsampling = $0212; PropertyTagYCbCrPositioning = $0213; PropertyTagREFBlackWhite = $0214; PropertyTagICCProfile = $8773; // This TAG is defined by ICC // for embedded ICC in TIFF PropertyTagGamma = $0301; PropertyTagICCProfileDescriptor = $0302; PropertyTagSRGBRenderingIntent = $0303; PropertyTagImageTitle = $0320; PropertyTagCopyright = $8298; // Extra TAGs (Like Adobe Image Information tags etc.) PropertyTagResolutionXUnit = $5001; PropertyTagResolutionYUnit = $5002; PropertyTagResolutionXLengthUnit = $5003; PropertyTagResolutionYLengthUnit = $5004; PropertyTagPrintFlags = $5005; PropertyTagPrintFlagsVersion = $5006; PropertyTagPrintFlagsCrop = $5007; PropertyTagPrintFlagsBleedWidth = $5008; PropertyTagPrintFlagsBleedWidthScale = $5009; PropertyTagHalftoneLPI = $500A; PropertyTagHalftoneLPIUnit = $500B; PropertyTagHalftoneDegree = $500C; PropertyTagHalftoneShape = $500D; PropertyTagHalftoneMisc = $500E; PropertyTagHalftoneScreen = $500F; PropertyTagJPEGQuality = $5010; PropertyTagGridSize = $5011; PropertyTagThumbnailFormat = $5012; // 1 = JPEG, 0 = RAW RGB PropertyTagThumbnailWidth = $5013; PropertyTagThumbnailHeight = $5014; PropertyTagThumbnailColorDepth = $5015; PropertyTagThumbnailPlanes = $5016; PropertyTagThumbnailRawBytes = $5017; PropertyTagThumbnailSize = $5018; PropertyTagThumbnailCompressedSize = $5019; PropertyTagColorTransferFunction = $501A; PropertyTagThumbnailData = $501B; // RAW thumbnail bits in // JPEG format or RGB format // depends on // PropertyTagThumbnailFormat // Thumbnail related TAGs PropertyTagThumbnailImageWidth = $5020; // Thumbnail width PropertyTagThumbnailImageHeight = $5021; // Thumbnail height PropertyTagThumbnailBitsPerSample = $5022; // Number of bits per // component PropertyTagThumbnailCompression = $5023; // Compression Scheme PropertyTagThumbnailPhotometricInterp = $5024; // Pixel composition PropertyTagThumbnailImageDescription = $5025; // Image Tile PropertyTagThumbnailEquipMake = $5026; // Manufacturer of Image // Input equipment PropertyTagThumbnailEquipModel = $5027; // Model of Image input // equipment PropertyTagThumbnailStripOffsets = $5028; // Image data location PropertyTagThumbnailOrientation = $5029; // Orientation of image PropertyTagThumbnailSamplesPerPixel = $502A; // Number of components PropertyTagThumbnailRowsPerStrip = $502B; // Number of rows per strip PropertyTagThumbnailStripBytesCount = $502C; // Bytes per compressed // strip PropertyTagThumbnailResolutionX = $502D; // Resolution in width // direction PropertyTagThumbnailResolutionY = $502E; // Resolution in height // direction PropertyTagThumbnailPlanarConfig = $502F; // Image data arrangement PropertyTagThumbnailResolutionUnit = $5030; // Unit of X and Y // Resolution PropertyTagThumbnailTransferFunction = $5031; // Transfer function PropertyTagThumbnailSoftwareUsed = $5032; // Software used PropertyTagThumbnailDateTime = $5033; // File change date and // time PropertyTagThumbnailArtist = $5034; // Person who created the // image PropertyTagThumbnailWhitePoint = $5035; // White point chromaticity PropertyTagThumbnailPrimaryChromaticities = $5036; // Chromaticities of // primaries PropertyTagThumbnailYCbCrCoefficients = $5037; // Color space transforma- // tion coefficients PropertyTagThumbnailYCbCrSubsampling = $5038; // Subsampling ratio of Y // to C PropertyTagThumbnailYCbCrPositioning = $5039; // Y and C position PropertyTagThumbnailRefBlackWhite = $503A; // Pair of black and white // reference values PropertyTagThumbnailCopyRight = $503B; // CopyRight holder PropertyTagLuminanceTable = $5090; PropertyTagChrominanceTable = $5091; PropertyTagFrameDelay = $5100; PropertyTagLoopCount = $5101; PropertyTagPixelUnit = $5110; // Unit specifier for pixel/unit PropertyTagPixelPerUnitX = $5111; // Pixels per unit in X PropertyTagPixelPerUnitY = $5112; // Pixels per unit in Y PropertyTagPaletteHistogram = $5113; // Palette histogram // EXIF specific tag PropertyTagExifExposureTime = $829A; PropertyTagExifFNumber = $829D; PropertyTagExifExposureProg = $8822; PropertyTagExifSpectralSense = $8824; PropertyTagExifISOSpeed = $8827; PropertyTagExifOECF = $8828; PropertyTagExifVer = $9000; PropertyTagExifDTOrig = $9003; // Date & time of original PropertyTagExifDTDigitized = $9004; // Date & time of digital data generation PropertyTagExifCompConfig = $9101; PropertyTagExifCompBPP = $9102; PropertyTagExifShutterSpeed = $9201; PropertyTagExifAperture = $9202; PropertyTagExifBrightness = $9203; PropertyTagExifExposureBias = $9204; PropertyTagExifMaxAperture = $9205; PropertyTagExifSubjectDist = $9206; PropertyTagExifMeteringMode = $9207; PropertyTagExifLightSource = $9208; PropertyTagExifFlash = $9209; PropertyTagExifFocalLength = $920A; PropertyTagExifMakerNote = $927C; PropertyTagExifUserComment = $9286; PropertyTagExifDTSubsec = $9290; // Date & Time subseconds PropertyTagExifDTOrigSS = $9291; // Date & Time original subseconds PropertyTagExifDTDigSS = $9292; // Date & TIme digitized subseconds PropertyTagExifFPXVer = $A000; PropertyTagExifColorSpace = $A001; PropertyTagExifPixXDim = $A002; PropertyTagExifPixYDim = $A003; PropertyTagExifRelatedWav = $A004; // related sound file PropertyTagExifInterop = $A005; PropertyTagExifFlashEnergy = $A20B; PropertyTagExifSpatialFR = $A20C; // Spatial Frequency Response PropertyTagExifFocalXRes = $A20E; // Focal Plane X Resolution PropertyTagExifFocalYRes = $A20F; // Focal Plane Y Resolution PropertyTagExifFocalResUnit = $A210; // Focal Plane Resolution Unit PropertyTagExifSubjectLoc = $A214; PropertyTagExifExposureIndex = $A215; PropertyTagExifSensingMethod = $A217; PropertyTagExifFileSource = $A300; PropertyTagExifSceneType = $A301; PropertyTagExifCfaPattern = $A302; PropertyTagGpsVer = $0000; PropertyTagGpsLatitudeRef = $0001; PropertyTagGpsLatitude = $0002; PropertyTagGpsLongitudeRef = $0003; PropertyTagGpsLongitude = $0004; PropertyTagGpsAltitudeRef = $0005; PropertyTagGpsAltitude = $0006; PropertyTagGpsGpsTime = $0007; PropertyTagGpsGpsSatellites = $0008; PropertyTagGpsGpsStatus = $0009; PropertyTagGpsGpsMeasureMode = $00A; PropertyTagGpsGpsDop = $000B; // Measurement precision PropertyTagGpsSpeedRef = $000C; PropertyTagGpsSpeed = $000D; PropertyTagGpsTrackRef = $000E; PropertyTagGpsTrack = $000F; PropertyTagGpsImgDirRef = $0010; PropertyTagGpsImgDir = $0011; PropertyTagGpsMapDatum = $0012; PropertyTagGpsDestLatRef = $0013; PropertyTagGpsDestLat = $0014; PropertyTagGpsDestLongRef = $0015; PropertyTagGpsDestLong = $0016; PropertyTagGpsDestBearRef = $0017; PropertyTagGpsDestBear = $0018; PropertyTagGpsDestDistRef = $0019; PropertyTagGpsDestDist = $001A; (**************************************************************************\ * * GDI+ Color Matrix object, used with Graphics.DrawImage * \**************************************************************************) //---------------------------------------------------------------------------- // Color matrix //---------------------------------------------------------------------------- type TGPColorMatrix = packed array[0..4, 0..4] of Single; PGPColorMatrix = ^TGPColorMatrix; //---------------------------------------------------------------------------- // Color Matrix flags //---------------------------------------------------------------------------- TGPColorMatrixFlags = ( ColorMatrixFlagsDefault, ColorMatrixFlagsSkipGrays, ColorMatrixFlagsAltGray ); //---------------------------------------------------------------------------- // Color Adjust Type //---------------------------------------------------------------------------- TGPColorAdjustType = ( ColorAdjustTypeDefault, ColorAdjustTypeBitmap, ColorAdjustTypeBrush, ColorAdjustTypePen, ColorAdjustTypeText, ColorAdjustTypeCount, ColorAdjustTypeAny // Reserved ); //---------------------------------------------------------------------------- // Color Map //---------------------------------------------------------------------------- TGPColorMap = packed record oldColor: TGPColor; newColor: TGPColor; end; PGPColorMap = ^TGPColorMap; //--------------------------------------------------------------------------- // Private GDI+ classes for internal type checking //--------------------------------------------------------------------------- GpGraphics = Pointer; GpBrush = Pointer; GpTexture = Pointer; GpSolidFill = Pointer; GpLineGradient = Pointer; GpPathGradient = Pointer; GpHatch = Pointer; GpPen = Pointer; GpCustomLineCap = Pointer; GpAdjustableArrowCap = Pointer; GpImage = Pointer; GpBitmap = Pointer; GpMetafile = Pointer; GpImageAttributes = Pointer; GpPath = Pointer; GpRegion = Pointer; GpPathIterator = Pointer; GpFontFamily = Pointer; GpFont = Pointer; GpStringFormat = Pointer; GpFontCollection = Pointer; GpCachedBitmap = Pointer; GpMatrix = Pointer; TGPBlend = record Position : Single; Value : Single; end; TGPBlendArray = array of TGPBlend; TGPInterpolationColor = record Position : Single; Color : TGPColor; end; TGPInterpolationColorArray = array of TGPInterpolationColor; TGUIDArray = array of TGUID; TGPPropIDArray = array of TPropID; TGPRectFArray = array of TGPRectF; TGPRectArray = array of TGPRect; TGPPointFArray = array of TGPPointF; TGPPointArray = array of TGPPoint; function MakeBlend( APosition : Single; AValue : Single ) : TGPBlend; function MakeInterpolationColor( APosition : Single; AColor : TGPColor ) : TGPInterpolationColor; (**************************************************************************\ * * GDI+ Codec Image APIs * \**************************************************************************) //-------------------------------------------------------------------------- // Codec Management APIs //-------------------------------------------------------------------------- function GetImageDecodersSize(out numDecoders, size: Cardinal) : TGPStatus; function GetImageDecoders() : TGPImageCodecInfoArray; function GetImageEncodersSize(out numEncoders, size: Cardinal) : TGPStatus; function GetImageEncoders() : TGPImageCodecInfoArray; function GetEncoderClsid( format : String; var pClsid : TCLSID ) : Boolean; (**************************************************************************\ * * Private GDI+ header file. * \**************************************************************************) //--------------------------------------------------------------------------- // GDI+ classes for forward reference //--------------------------------------------------------------------------- type TGPGraphics = class; TGPPen = class; TGPBrush = class; TGPMatrix = class; TGPBitmap = class; TGPMetafile = class; TGPFontFamily = class; TGPGraphicsPath = class; TGPRegion = class; TGPImage = class; TGPHatchBrush = class; TGPSolidBrush = class; TGPLinearGradientBrush = class; TGPPathGradientBrush = class; TGPFont = class; TGPFontCollection = class; TGPInstalledFontCollection = class; TGPPrivateFontCollection = class; TGPImageAttributes = class; TGPCachedBitmap = class; TGPCustomLineCap = class; TGPStringFormat = class; TGPTextureBrush = class; TGPGraphicsPathIterator = class; TGPAdjustableArrowCap = class; IGPGraphics = interface; IGPMatrix = interface; IGPFontFamily = interface; IGPGraphicsPath = interface; IGPMetafile = interface; IGPFontCollection = interface; IGPTransformable = interface; TGPFontFamilies = array of IGPFontFamily; (**************************************************************************\ * * GDI+ base memory allocation class * \**************************************************************************) TGPBase = class( TInterfacedObject ) protected class procedure ErrorCheck( AStatus : TGPStatus ); public class function NewInstance() : TObject; override; procedure FreeInstance(); override; end; IGPPathData = interface ['{1CA67396-A73B-4621-830D-989DA20EBE36}'] function GetCount() : Integer; function GetPoints( Index : Integer ) : TGPPointF; function GetTypes( Index : Integer ) : TGPPathPointType; property Count : Integer read GetCount; property Points[ Index : Integer ] : TGPPointF read GetPoints; property Types[ Index : Integer ] : TGPPathPointType read GetTypes; end; IGPMetafileHeader = interface ['{3F6AC13B-46CD-4CA6-B5DE-ACD761649161}'] function GetType() : TGPMetafileType; function GetMetafileSize() : UINT; // If IsEmfPlus, this is the EMF+ version; else it is the WMF or EMF ver function GetVersion() : UINT; // Get the EMF+ flags associated with the metafile function GetEmfPlusFlags() : UINT; function GetDpiX() : Single; function GetDpiY() : Single; function GetBounds() : TGPRect; // Is it any type of WMF (standard or Placeable Metafile)? function IsWmf() : Boolean; // Is this an Placeable Metafile? function IsWmfPlaceable() : Boolean; // Is this an EMF (not an EMF+)? function IsEmf() : Boolean; // Is this an EMF or EMF+ file? function IsEmfOrEmfPlus() : Boolean; // Is this an EMF+ file? function IsEmfPlus() : Boolean; // Is this an EMF+ dual (has dual, down-level records) file? function IsEmfPlusDual() : Boolean; // Is this an EMF+ only (no dual records) file? function IsEmfPlusOnly() : Boolean; // If it's an EMF+ file, was it recorded against a display Hdc? function IsDisplay() : Boolean; // Get the WMF header of the metafile (if it is a WMF) function GetWmfHeader() : PMetaHeader; // Get the EMF header of the metafile (if it is an EMF) function GetEmfHeader() : PENHMETAHEADER3; property MetafileSize : UINT read GetMetafileSize; property Version : UINT read GetVersion; property DpiX : Single read GetDpiX; property DpiY : Single read GetDpiY; property Bounds : TGPRect read GetBounds; end; (**************************************************************************\ * * GDI+ Region, Font, Image, CustomLineCap class definitions. * \**************************************************************************) IGPRegion = interface ['{ECAB7D08-39D0-47AA-8247-9DD3491485EA}'] function GetNativeRegion() : GpRegion; function Clone() : TGPRegion; function MakeInfinite() : TGPRegion; function MakeEmpty() : TGPRegion; function GetDataSize() : Cardinal; // buffer - where to put the data // bufferSize - how big the buffer is (should be at least as big as GetDataSize()) // sizeFilled - if not NULL, this is an OUT param that says how many bytes // of data were written to the buffer. function GetData() : TGPByteArray; function Intersect(const rect: TGPRect) : TGPRegion; overload; function IntersectF(const rect: TGPRectF) : TGPRegion; function Intersect(path: IGPGraphicsPath) : TGPRegion; overload; function Intersect(region: IGPRegion) : TGPRegion; overload; function Union(const rect: TGPRect) : TGPRegion; overload; function UnionF(const rect: TGPRectF) : TGPRegion; function Union(path: IGPGraphicsPath) : TGPRegion; overload; function Union(region: IGPRegion) : TGPRegion; overload; function XorRegion(const rect: TGPRect) : TGPRegion; overload; function XorRegionF(const rect: TGPRectF) : TGPRegion; function XorRegion(path: IGPGraphicsPath) : TGPRegion; overload; function XorRegion(region: IGPRegion) : TGPRegion; overload; function Exclude(const rect: TGPRect) : TGPRegion; overload; function ExcludeF(const rect: TGPRectF) : TGPRegion; function Exclude(path: IGPGraphicsPath) : TGPRegion; overload; function Exclude(region: IGPRegion) : TGPRegion; overload; function Complement(const rect: TGPRect) : TGPRegion; overload; function ComplementF(const rect: TGPRectF) : TGPRegion; function Complement(path: IGPGraphicsPath) : TGPRegion; overload; function Complement(region: IGPRegion) : TGPRegion; overload; function TranslateF(dx, dy: Single) : TGPRegion; function Translate(dx, dy: Integer) : TGPRegion; function Transform(matrix: IGPMatrix) : TGPRegion; function GetBounds( g: IGPGraphics ) : TGPRect; function GetBoundsF( g: IGPGraphics ) : TGPRectF; function GetHRGN(g: IGPGraphics) : HRGN; function IsEmpty(g: IGPGraphics) : Boolean; function IsInfinite(g: IGPGraphics) : Boolean ; function IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(const point: TGPPoint; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(const point: TGPPointF; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(x, y, width, height: Integer; g: IGPGraphics) : Boolean; overload; function IsVisible(const rect: TGPRect; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y, width, height: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(const rect: TGPRectF; g: IGPGraphics = NIL) : Boolean; overload; function Equals(region: IGPRegion; g: IGPGraphics) : Boolean; function GetRegionScansCount(matrix: IGPMatrix) : Cardinal; function GetRegionScansF( matrix: IGPMatrix ) : TGPRectFArray; function GetRegionScans( matrix: IGPMatrix ) : TGPRectArray; end; TGPRegion = class( TGPBase, IGPRegion ) protected FNativeRegion: GpRegion; protected function GetNativeRegion() : GpRegion; procedure SetNativeRegion(nativeRegion: GpRegion); constructor CreateGdiPlus(nativeRegion: GpRegion; Dummy : Boolean ); public constructor Create(); overload; constructor Create(rect: TGPRectF); overload; constructor Create(rect: TGPRect); overload; constructor Create(path: IGPGraphicsPath); overload; constructor Create( regionData: array of BYTE ); overload; constructor Create(hRgn: HRGN); overload; destructor Destroy(); override; public class function FromHRGN(hRgn: HRGN) : TGPRegion; public function Clone() : TGPRegion; function MakeInfinite() : TGPRegion; function MakeEmpty() : TGPRegion; function GetDataSize() : Cardinal; // buffer - where to put the data // bufferSize - how big the buffer is (should be at least as big as GetDataSize()) // sizeFilled - if not NULL, this is an OUT param that says how many bytes // of data were written to the buffer. function GetData() : TGPByteArray; function Intersect(const rect: TGPRect) : TGPRegion; overload; function IntersectF(const rect: TGPRectF) : TGPRegion; function Intersect(path: IGPGraphicsPath) : TGPRegion; overload; function Intersect(region: IGPRegion) : TGPRegion; overload; function Union(const rect: TGPRect) : TGPRegion; overload; function UnionF(const rect: TGPRectF) : TGPRegion; function Union(path: IGPGraphicsPath) : TGPRegion; overload; function Union(region: IGPRegion) : TGPRegion; overload; function XorRegion(const rect: TGPRect) : TGPRegion; overload; function XorRegionF(const rect: TGPRectF) : TGPRegion; function XorRegion(path: IGPGraphicsPath) : TGPRegion; overload; function XorRegion(region: IGPRegion) : TGPRegion; overload; function Exclude(const rect: TGPRect) : TGPRegion; overload; function ExcludeF(const rect: TGPRectF) : TGPRegion; function Exclude(path: IGPGraphicsPath) : TGPRegion; overload; function Exclude(region: IGPRegion) : TGPRegion; overload; function Complement(const rect: TGPRect) : TGPRegion; overload; function ComplementF(const rect: TGPRectF) : TGPRegion; function Complement(path: IGPGraphicsPath) : TGPRegion; overload; function Complement(region: IGPRegion) : TGPRegion; overload; function TranslateF(dx, dy: Single) : TGPRegion; function Translate(dx, dy: Integer) : TGPRegion; function Transform(matrix: IGPMatrix) : TGPRegion; function GetBounds( g: IGPGraphics ) : TGPRect; function GetBoundsF( g: IGPGraphics ) : TGPRectF; function GetHRGN(g: IGPGraphics) : HRGN; function IsEmpty(g: IGPGraphics) : Boolean; function IsInfinite(g: IGPGraphics) : Boolean ; function IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(const point: TGPPoint; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(const point: TGPPointF; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(x, y, width, height: Integer; g: IGPGraphics) : Boolean; overload; function IsVisible(const rect: TGPRect; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y, width, height: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(const rect: TGPRectF; g: IGPGraphics = NIL) : Boolean; overload; function EqualsRegion(region: IGPRegion; g: IGPGraphics) : Boolean; function GetRegionScansCount(matrix: IGPMatrix) : Cardinal; function GetRegionScansF( matrix: IGPMatrix ) : TGPRectFArray; function GetRegionScans( matrix: IGPMatrix ) : TGPRectArray; function IGPRegion.Equals = EqualsRegion; end; TGPRegionArray = array of IGPRegion; //-------------------------------------------------------------------------- // FontFamily //-------------------------------------------------------------------------- IGPFontFamily = interface ['{4678D60A-EA61-410E-B543-AD0FEA23103A}'] function GetFamilyName(language: LANGID = 0) : String; function Clone() : TGPFontFamily; function IsAvailable() : Boolean; function IsStyleAvailable(style: Integer) : Boolean; function GetEmHeight(style: Integer) : UINT16; function GetCellAscent(style: Integer) : UINT16; function GetCellDescent(style: Integer) : UINT16; function GetLineSpacing(style: Integer) : UINT16; function GetNativeFamily() : GpFontFamily; end; TGPFontFamily = class(TGPBase, IGPFontFamily) protected FNativeFamily : GpFontFamily; protected constructor CreateGdiPlus(nativeFamily: GpFontFamily; Dummy : Boolean); public constructor Create(); overload; constructor Create(name: WideString; fontCollection: IGPFontCollection = NIL); overload; destructor Destroy(); override; public class function GenericSansSerif() : TGPFontFamily; class function GenericSerif() : TGPFontFamily; class function GenericMonospace() : TGPFontFamily; public function GetFamilyName(language: LANGID = 0) : String; function Clone() : TGPFontFamily; function IsAvailable() : Boolean; function IsStyleAvailable(style: Integer) : Boolean; function GetEmHeight(style: Integer) : UINT16; function GetCellAscent(style: Integer) : UINT16; function GetCellDescent(style: Integer) : UINT16; function GetLineSpacing(style: Integer) : UINT16; function GetNativeFamily() : GpFontFamily; end; //-------------------------------------------------------------------------- // Font Collection //-------------------------------------------------------------------------- IGPFontCollection = interface ['{856E57C8-CAF2-4824-8DBB-E82DDEABF0BC}'] function GetNativeFontCollection() : GpFontCollection; function GetFamilyCount: Integer; function GetFamilies() : TGPFontFamilies; end; TGPFontCollection = class(TGPBase, IGPFontCollection) protected FNativeFontCollection: GpFontCollection; function GetNativeFontCollection() : GpFontCollection; public constructor Create(); destructor Destroy(); override; public function GetFamilyCount() : Integer; function GetFamilies() : TGPFontFamilies; end; TGPInstalledFontCollection = class(TGPFontCollection) public constructor Create(); reintroduce; destructor Destroy(); override; end; IGPPrivateFontCollection = interface ['{AF596B35-2851-40AD-88E1-48CEB263314E}'] function AddFontFile(filename: WideString) : TGPPrivateFontCollection; function AddMemoryFont(memory: Pointer; length: Integer) : TGPPrivateFontCollection; end; TGPPrivateFontCollection = class(TGPFontCollection, IGPPrivateFontCollection) public constructor Create(); reintroduce; destructor Destroy(); override; public function AddFontFile(filename: WideString) : TGPPrivateFontCollection; function AddMemoryFont(memory: Pointer; length: Integer) : TGPPrivateFontCollection; end; //-------------------------------------------------------------------------- // TFont //-------------------------------------------------------------------------- IGPFont = interface ['{034EF8BC-9EBD-4058-8C18-FFD8873E4883}'] function GetNativeFont() : GpFont; function GetLogFontA( g : IGPGraphics ) : TLogFontA; function GetLogFontW( g : IGPGraphics ) : TLogFontW; function Clone() : TGPFont; function IsAvailable() : Boolean; function GetStyle() : Integer; function GetSize() : Single; function GetUnit() : TGPUnit; function GetHeight(graphics: IGPGraphics) : Single; overload; function GetHeight(dpi: Single) : Single; overload; function GetFamily() : IGPFontFamily; property Style : Integer read GetStyle; property Size : Single read GetSize; property Units : TGPUnit read GetUnit; property Family : IGPFontFamily read GetFamily; end; TGPFont = class( TGPBase, IGPFont ) protected FNativeFont: GpFont; protected procedure SetNativeFont(Font: GpFont); function GetNativeFont() : GpFont; constructor CreateGdiPlus(font: GpFont; Dummy : Boolean ); public constructor Create(hdc: HDC); overload; constructor Create(hdc: HDC; logfont: PLogFontA); overload; constructor Create(hdc: HDC; logfont: PLogFontW); overload; constructor Create(hdc: HDC; hfont: HFONT); overload; constructor Create(family: IGPFontFamily; emSize: Single; style: TFontStyles = []; unit_: TGPUnit = UnitPoint); overload; constructor Create(familyName: WideString; emSize: Single; style: TFontStyles = []; unit_: TGPUnit = UnitPoint; fontCollection: IGPFontCollection = NIL); overload; destructor Destroy(); override; public function GetLogFontA( g : IGPGraphics ) : TLogFontA; function GetLogFontW( g : IGPGraphics ) : TLogFontW; function Clone() : TGPFont; function IsAvailable() : Boolean; function GetStyle() : Integer; function GetSize() : Single; function GetUnit() : TGPUnit; function GetHeight(graphics: IGPGraphics) : Single; overload; function GetHeight(dpi: Single) : Single; overload; function GetFamily() : IGPFontFamily; end; //-------------------------------------------------------------------------- // Abstract base class for Image and Metafile //-------------------------------------------------------------------------- IGPImage = interface ['{3514B659-EAB2-4A2E-80F5-7A6AD9E2A64B}'] function GetNativeImage() : GpImage; function Clone() : TGPImage; function Save(filename: WideString; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; overload; function Save(stream: IStream; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; overload; function SaveAdd(encoderParams: PGPEncoderParameters) : TGPImage; overload; function SaveAdd(newImage: IGPImage; encoderParams: PGPEncoderParameters) : TGPImage; overload; function GetType() : TGPImageType; function GetPhysicalDimension() : TGPSizeF; function GetBounds(out srcRect: TGPRectF; out srcUnit: TGPUnit) : TGPImage; function GetWidth() : Cardinal; function GetHeight() : Cardinal; function GetHorizontalResolution() : Single; function GetVerticalResolution() : Single; function GetFlags() : Cardinal; function GetRawFormat() : TGUID; function GetFormatName() : String; function GetPixelFormat() : TGPPixelFormat; function GetPaletteSize() : Integer; function GetPalette(palette: PGPColorPalette; size: Integer) : TGPImage; function SetPalette(palette: PGPColorPalette) : TGPImage; function GetThumbnailImage(thumbWidth, thumbHeight: Cardinal; callback: TGPGetThumbnailImageAbortProc = NIL) : TGPImage; function GetFrameDimensionsCount() : Cardinal; function GetFrameDimensionsList() : TGUIDArray; function GetFrameCount(const dimensionID: TGUID) : Cardinal; function SelectActiveFrame(const dimensionID: TGUID; frameIndex: Cardinal) : TGPImage; function RotateFlip(rotateFlipType: TGPRotateFlipType) : TGPImage; function GetPropertyCount() : Cardinal; function GetPropertyIdList() : TGPPropIDArray; function GetPropertyItemSize(propId: PROPID) : Cardinal; function GetPropertyItem(propId: PROPID; propSize: Cardinal; buffer: PGPPropertyItem) : TGPImage; function GetPropertySize(out totalBufferSize, numProperties : Cardinal) : TGPImage; function GetAllPropertyItems(totalBufferSize, numProperties: Cardinal; allItems: PGPPropertyItem ) : TGPImage; function RemovePropertyItem(propId: TPROPID) : TGPImage; function SetPropertyItem(const item: TGPPropertyItem) : TGPImage; function GetEncoderParameterListSize(const clsidEncoder: TGUID) : Cardinal; function GetEncoderParameterList(const clsidEncoder: TGUID; size: Cardinal; buffer: PGPEncoderParameters) : TGPImage; property Width : Cardinal read GetWidth; property Height : Cardinal read GetHeight; property PixelFormat : TGPPixelFormat read GetPixelFormat; property ImageType : TGPImageType read GetType; property FormatName : String read GetFormatName; property FrameDimensionsCount : Cardinal read GetFrameDimensionsCount; property FrameDimensionsList : TGUIDArray read GetFrameDimensionsList; property HorizontalResolution : Single read GetHorizontalResolution; property VerticalResolution : Single read GetVerticalResolution; property RawFormat : TGUID read GetRawFormat; property PhysicalDimension : TGPSizeF read GetPhysicalDimension; property PropertyCount : Cardinal read GetPropertyCount; property PropertyIdList : TGPPropIDArray read GetPropertyIdList; end; TGPImage = class( TGPBase, IGPImage ) protected FNativeImage: GpImage; protected procedure SetNativeImage(nativeImage: GpImage); function GetNativeImage() : GpImage; constructor CreateGdiPlus(nativeImage: GpImage; Dummy : Boolean); public constructor Create(filename: WideString; useEmbeddedColorManagement: Boolean = False); overload; constructor Create(stream: IStream; useEmbeddedColorManagement: Boolean = False); overload; destructor Destroy(); override; public class function FromFile(filename: WideString; useEmbeddedColorManagement: Boolean = False) : TGPImage; class function FromStream(stream: IStream; useEmbeddedColorManagement: Boolean = False) : TGPImage; public function Clone() : TGPImage; function Save(filename: WideString; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; overload; function Save(stream: IStream; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; overload; function SaveAdd(encoderParams: PGPEncoderParameters) : TGPImage; overload; function SaveAdd(newImage: IGPImage; encoderParams: PGPEncoderParameters) : TGPImage; overload; function GetType() : TGPImageType; function GetPhysicalDimension() : TGPSizeF; function GetBounds(out srcRect: TGPRectF; out srcUnit: TGPUnit) : TGPImage; function GetWidth() : Cardinal; function GetHeight() : Cardinal; function GetHorizontalResolution() : Single; function GetVerticalResolution() : Single; function GetFlags() : Cardinal; function GetRawFormat() : TGUID; function GetFormatName() : String; function GetPixelFormat() : TGPPixelFormat; function GetPaletteSize() : Integer; function GetPalette(palette: PGPColorPalette; size: Integer) : TGPImage; function SetPalette(palette: PGPColorPalette) : TGPImage; function GetThumbnailImage(thumbWidth, thumbHeight: Cardinal; callback: TGPGetThumbnailImageAbortProc = NIL) : TGPImage; function GetFrameDimensionsCount() : Cardinal; function GetFrameDimensionsList() : TGUIDArray; function GetFrameCount(const dimensionID: TGUID) : Cardinal; function SelectActiveFrame(const dimensionID: TGUID; frameIndex: Cardinal) : TGPImage; function RotateFlip(rotateFlipType: TGPRotateFlipType) : TGPImage; function GetPropertyCount() : Cardinal; function GetPropertyIdList() : TGPPropIDArray; function GetPropertyItemSize(propId: PROPID) : Cardinal; function GetPropertyItem(propId: PROPID; propSize: Cardinal; buffer: PGPPropertyItem) : TGPImage; function GetPropertySize(out totalBufferSize, numProperties : Cardinal) : TGPImage; function GetAllPropertyItems(totalBufferSize, numProperties: Cardinal; allItems: PGPPropertyItem ) : TGPImage; function RemovePropertyItem(propId: TPROPID) : TGPImage; function SetPropertyItem(const item: TGPPropertyItem) : TGPImage; function GetEncoderParameterListSize(const clsidEncoder: TGUID) : Cardinal; function GetEncoderParameterList(const clsidEncoder: TGUID; size: Cardinal; buffer: PGPEncoderParameters) : TGPImage; end; IGPBitmapData = interface ['{5036255F-F234-477D-8493-582198BF2CBB}'] function GetWidth() : UINT; function GetHeight() : UINT; function GetStride() : Integer; function GetPixelFormat() : TGPPixelFormat; function GetScan0() : Pointer; property Width : UINT read GetWidth; property Height : UINT read GetHeight; property Stride : Integer read GetStride; property PixelFormat : TGPPixelFormat read GetPixelFormat; property Scan0 : Pointer read GetScan0; end; IGPBitmap = interface( IGPImage ) ['{A242C124-6A5D-4F1F-9AC4-50A93D12E15B}'] function Clone(rect: TGPRect; format: TGPPixelFormat) : TGPBitmap; overload; function Clone(x, y, width, height: Integer; format: TGPPixelFormat) : TGPBitmap; overload; function CloneF(rect: TGPRectF; format: TGPPixelFormat) : TGPBitmap; overload; function CloneF(x, y, width, height: Single; format: TGPPixelFormat) : TGPBitmap; overload; function LockBits(rect: TGPRect; flags: Cardinal; format: TGPPixelFormat ) : IGPBitmapData; function GetPixel(x, y: Integer) : TGPColor; function SetPixel(x, y: Integer; color: TGPColor) : TGPBitmap; procedure SetPixelProp(x, y: Integer; color: TGPColor); function SetResolution(xdpi, ydpi: Single) : TGPBitmap; function GetHBITMAP( colorBackground: TGPColor ) : HBITMAP; function GetHICON() : HICON; property Pixels[ X, Y : Integer ] : TGPColor read GetPixel write SetPixelProp; default; end; TGPBitmap = class( TGPImage, IGPBitmap ) protected constructor CreateGdiPlus(nativeBitmap: GpBitmap; Dummy : Boolean ); protected procedure LockBitsInternal(rect: TGPRect; flags: Cardinal; format: TGPPixelFormat; var AData : TGPBitmapDataRecord ); function UnlockBits(var lockedBitmapData: TGPBitmapDataRecord) : TGPBitmap; public constructor Create( filename : WideString; useEmbeddedColorManagement : Boolean = False ); overload; constructor Create( stream : IStream; useEmbeddedColorManagement : Boolean = False ); overload; {$IFNDEF PURE_FMX} constructor Create( ABitmap : TBitmap ); overload; constructor Create( AIcon : TIcon ); overload; {$ENDIF} public constructor Create( width, height, stride : Integer; format : TGPPixelFormat; scan0 : PBYTE); overload; constructor Create( width, height : Integer; format : TGPPixelFormat = PixelFormat32bppARGB); overload; constructor Create( width, height : Integer; target : TGPGraphics); overload; public // constructor Create(surface: IDirectDrawSurface7); overload; constructor CreateData( var gdiBitmapInfo : TBITMAPINFO; gdiBitmapData : Pointer ); constructor CreateHBITMAP( hbm : HBITMAP; hpal : HPALETTE ); constructor CreateHICON( hicon : HICON ); constructor CreateRes( hInstance : HMODULE; bitmapName : WideString ); public function Clone(rect: TGPRect; format: TGPPixelFormat) : TGPBitmap; overload; function Clone(x, y, width, height: Integer; format: TGPPixelFormat) : TGPBitmap; overload; function CloneF(rect: TGPRectF; format: TGPPixelFormat) : TGPBitmap; overload; function CloneF(x, y, width, height: Single; format: TGPPixelFormat) : TGPBitmap; overload; function LockBits( rect: TGPRect; flags: Cardinal; format: TGPPixelFormat ) : IGPBitmapData; function GetPixel(x, y: Integer) : TGPColor; function SetPixel(x, y: Integer; color: TGPColor) : TGPBitmap; procedure SetPixelProp(x, y: Integer; color: TGPColor); function SetResolution(xdpi, ydpi: Single) : TGPBitmap; function GetHBITMAP( colorBackground: TGPColor ) : HBITMAP; function GetHICON() : HICON; public // class function FromDirectDrawSurface7(surface: IDirectDrawSurface7) : TGPBitmap; class function FromBITMAPINFO(var gdiBitmapInfo: TBITMAPINFO; gdiBitmapData: Pointer) : TGPBitmap; class function FromFile(filename: WideString; useEmbeddedColorManagement: Boolean = False) : TGPBitmap; class function FromStream(stream: IStream; useEmbeddedColorManagement: Boolean = False) : TGPBitmap; class function FromHBITMAP(hbm: HBITMAP; hpal: HPALETTE) : TGPBitmap; class function FromHICON(hicon: HICON) : TGPBitmap; class function FromResource(hInstance: HMODULE; bitmapName: WideString) : TGPBitmap; end; IGPCustomLineCap = interface ['{C11912FC-5FF7-44D1-A201-ABFDA33184E9}'] function GetNativeCap() : GpCustomLineCap; function Clone() : TGPCustomLineCap; function SetStrokeCap(strokeCap: TGPLineCap) : TGPCustomLineCap; function SetStrokeCaps(startCap, endCap: TGPLineCap) : TGPCustomLineCap; function GetStrokeCaps(out startCap, endCap: TGPLineCap) : TGPCustomLineCap; function SetStrokeJoin(lineJoin: TGPLineJoin) : TGPCustomLineCap; procedure SetStrokeJoinProp(lineJoin: TGPLineJoin); function GetStrokeJoin() : TGPLineJoin; function SetBaseCap(baseCap: TGPLineCap) : TGPCustomLineCap; procedure SetBaseCapProp(baseCap: TGPLineCap); function GetBaseCap() : TGPLineCap; function SetBaseInset(inset: Single) : TGPCustomLineCap; procedure SetBaseInsetProp(inset: Single); function GetBaseInset() : Single; function SetWidthScale(widthScale: Single) : TGPCustomLineCap; procedure SetWidthScaleProp(widthScale: Single); function GetWidthScale() : Single; property StrokeJoin : TGPLineJoin read GetStrokeJoin write SetStrokeJoinProp; property BaseCap : TGPLineCap read GetBaseCap write SetBaseCapProp; property BaseInset : Single read GetBaseInset write SetBaseInsetProp; property WidthScale : Single read GetWidthScale write SetWidthScaleProp; end; TGPCustomLineCap = class( TGPBase, IGPCustomLineCap ) protected FNativeCap : GpCustomLineCap; protected function GetNativeCap() : GpCustomLineCap; procedure SetNativeCap(nativeCap: GpCustomLineCap); constructor CreateGdiPlus(nativeCap: GpCustomLineCap; Dummy : Boolean); public constructor Create(); overload; constructor Create(fillPath, strokePath: IGPGraphicsPath; baseCap: TGPLineCap = LineCapFlat; baseInset: Single = 0); overload; destructor Destroy(); override; public function Clone() : TGPCustomLineCap; function SetStrokeCap(strokeCap: TGPLineCap) : TGPCustomLineCap; function SetStrokeCaps(startCap, endCap: TGPLineCap) : TGPCustomLineCap; function GetStrokeCaps(out startCap, endCap: TGPLineCap) : TGPCustomLineCap; function SetStrokeJoin(lineJoin: TGPLineJoin) : TGPCustomLineCap; procedure SetStrokeJoinProp(lineJoin: TGPLineJoin); function GetStrokeJoin() : TGPLineJoin; function SetBaseCap(baseCap: TGPLineCap) : TGPCustomLineCap; procedure SetBaseCapProp(baseCap: TGPLineCap); function GetBaseCap() : TGPLineCap; function SetBaseInset(inset: Single) : TGPCustomLineCap; procedure SetBaseInsetProp(inset: Single); function GetBaseInset() : Single; function SetWidthScale(widthScale: Single) : TGPCustomLineCap; procedure SetWidthScaleProp(widthScale: Single); function GetWidthScale() : Single; end; IGPCachedBitmap = interface ['{96A926BE-354E-4A88-B4B3-0DB3A648D181}'] function GetNativeCachedBitmap() : GpCachedBitmap; end; TGPCachedBitmap = class(TGPBase, IGPCachedBitmap) protected FNativeCachedBitmap: GpCachedBitmap; protected function GetNativeCachedBitmap() : GpCachedBitmap; public constructor Create(bitmap: IGPBitmap; graphics: IGPGraphics); reintroduce; destructor Destroy(); override; end; (**************************************************************************\ * * GDI+ Image Attributes used with Graphics.DrawImage * * There are 5 possible sets of color adjustments: * ColorAdjustDefault, * ColorAdjustBitmap, * ColorAdjustBrush, * ColorAdjustPen, * ColorAdjustText, * * Bitmaps, Brushes, Pens, and Text will all use any color adjustments * that have been set into the default ImageAttributes until their own * color adjustments have been set. So as soon as any "Set" method is * called for Bitmaps, Brushes, Pens, or Text, then they start from * scratch with only the color adjustments that have been set for them. * Calling Reset removes any individual color adjustments for a type * and makes it revert back to using all the default color adjustments * (if any). The SetToIdentity method is a way to force a type to * have no color adjustments at all, regardless of what previous adjustments * have been set for the defaults or for that type. * \**************************************************************************) IGPImageAttributes = interface ['{330BD1E0-00B5-4399-BAB7-990DE03CC7F4}'] function GetNativeImageAttr() : GpImageAttributes; function Clone() : TGPImageAttributes; function SetToIdentity(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function Reset(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorMatrix(const colorMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorMatrix(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorMatrices(const colorMatrix: TGPColorMatrix; const grayMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorMatrices(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetThreshold(threshold: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearThreshold(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetGamma(gamma: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearGamma( type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetNoOp(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearNoOp(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorKey(colorLow, colorHigh: TGPColor; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorKey(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetOutputChannel(channelFlags: TGPColorChannelFlags; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearOutputChannel(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetOutputChannelColorProfile(colorProfileFilename: WideString; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearOutputChannelColorProfile(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetRemapTable(mapSize: Cardinal; map: PGPColorMap; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearRemapTable(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetBrushRemapTable(mapSize: Cardinal; map: PGPColorMap) : TGPImageAttributes; function ClearBrushRemapTable() : TGPImageAttributes; function SetWrapMode(wrap: TGPWrapMode; color: TGPColor = aclBlack; clamp: Boolean = False) : TGPImageAttributes; // The flags of the palette are ignored. function GetAdjustedPalette(colorPalette: PGPColorPalette; colorAdjustType: TGPColorAdjustType) : TGPImageAttributes; end; TGPImageAttributes = class(TGPBase, IGPImageAttributes) protected FNativeImageAttr: GpImageAttributes; protected function GetNativeImageAttr() : GpImageAttributes; protected procedure SetNativeImageAttr(nativeImageAttr: GpImageAttributes); constructor CreateGdiPlus(imageAttr: GpImageAttributes; Dummy : Boolean ); public constructor Create(); destructor Destroy(); override; public function Clone() : TGPImageAttributes; function SetToIdentity(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function Reset(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorMatrix(const colorMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorMatrix(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorMatrices(const colorMatrix: TGPColorMatrix; const grayMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorMatrices(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetThreshold(threshold: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearThreshold(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetGamma(gamma: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearGamma( type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetNoOp(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearNoOp(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetColorKey(colorLow, colorHigh: TGPColor; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearColorKey(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetOutputChannel(channelFlags: TGPColorChannelFlags; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearOutputChannel(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetOutputChannelColorProfile(colorProfileFilename: WideString; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearOutputChannelColorProfile(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetRemapTable(mapSize: Cardinal; map: PGPColorMap; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function ClearRemapTable(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; function SetBrushRemapTable(mapSize: Cardinal; map: PGPColorMap) : TGPImageAttributes; function ClearBrushRemapTable() : TGPImageAttributes; function SetWrapMode(wrap: TGPWrapMode; color: TGPColor = aclBlack; clamp: Boolean = False) : TGPImageAttributes; // The flags of the palette are ignored. function GetAdjustedPalette(colorPalette: PGPColorPalette; colorAdjustType: TGPColorAdjustType) : TGPImageAttributes; end; (**************************************************************************\ * * GDI+ Matrix class * \**************************************************************************) // TMatrixArray = array[0..5] of Single; TGPMatrixParams = packed record m11 : Single; m12 : Single; m21 : Single; m22 : Single; dx : Single; dy : Single; end; IGPMatrix = interface ['{EBD3DFC3-7740-496E-B074-2AD588B11137}'] function GetNativeMatrix() : GpMatrix; function Clone() : TGPMatrix; function GetElements() : TGPMatrixParams; function SetElements(m11, m12, m21, m22, dx, dy: Single) : TGPMatrix; overload; function SetElements( AElements : TGPMatrixParams ) : TGPMatrix; overload; procedure SetElementsProp( AElements : TGPMatrixParams ); function OffsetX() : Single; function OffsetY() : Single; function Reset() : TGPMatrix; function Multiply(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function Translate(offsetX, offsetY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function Scale(scaleX, scaleY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function Rotate(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function RotateAt(angle: Single; const center: TGPPointF; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function Shear(shearX, shearY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; // ok function Invert() : TGPMatrix; // ok function TransformPointF( var point : TGPPointF ) : TGPMatrix; function TransformPoint( var point : TGPPoint ) : TGPMatrix; function TransformPointsF( var pts : array of TGPPointF ) : TGPMatrix; function TransformPoints( var pts : array of TGPPoint ) : TGPMatrix; function TransformVectorsF( var pts : array of TGPPointF ) : TGPMatrix; function TransformVectors( var pts : array of TGPPoint ) : TGPMatrix; function IsInvertible() : Boolean; function IsIdentity() : Boolean; function Equals(matrix: IGPMatrix) : Boolean; property Elements : TGPMatrixParams read GetElements write SetElementsProp; end; TGPMatrix = class( TGPBase, IGPMatrix ) protected FNativeMatrix : GpMatrix; protected procedure SetNativeMatrix(nativeMatrix: GpMatrix); function GetNativeMatrix() : GpMatrix; constructor CreateGdiPlus(nativeMatrix: GpMatrix; Dummy : Boolean); public // Default constructor is set to identity matrix. constructor Create(); overload; constructor Create(m11, m12, m21, m22, dx, dy: Single); overload; constructor Create(const rect: TGPRectF; const dstplg: TGPPointF); overload; constructor Create(const rect: TGPRect; const dstplg: TGPPoint); overload; destructor Destroy(); override; public function Clone() : TGPMatrix; function GetElements() : TGPMatrixParams; function SetElements(m11, m12, m21, m22, dx, dy: Single) : TGPMatrix; overload; function SetElements( AElements : TGPMatrixParams ) : TGPMatrix; overload; procedure SetElementsProp( AElements : TGPMatrixParams ); function OffsetX() : Single; function OffsetY() : Single; function Reset() : TGPMatrix; function Multiply(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function Translate(offsetX, offsetY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function Scale(scaleX, scaleY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function Rotate(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function RotateAt(angle: Single; const center: TGPPointF; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function Shear(shearX, shearY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; function Invert() : TGPMatrix; function TransformPointF( var point : TGPPointF ) : TGPMatrix; function TransformPoint( var point : TGPPoint ) : TGPMatrix; function TransformPointsF( var pts : array of TGPPointF ) : TGPMatrix; function TransformPoints( var pts : array of TGPPoint ) : TGPMatrix; function TransformVectorsF( var pts : array of TGPPointF ) : TGPMatrix; function TransformVectors( var pts : array of TGPPoint ) : TGPMatrix; function IsInvertible() : Boolean; function IsIdentity() : Boolean; function EqualsMatrix(matrix: IGPMatrix) : Boolean; function IGPMatrix.Equals = EqualsMatrix; end; IGPMatrixStore = interface ['{C43901CD-CF57-485E-9050-F28AB12A63CE}'] end; TGPMatrixStore = class( TInterfacedObject, IGPMatrixStore ) protected FTransformable : IGPTransformable; FMatrix : IGPMatrix; public constructor Create( ATransformable : IGPTransformable ); destructor Destroy(); override; end; (**************************************************************************\ * * GDI+ Brush class * \**************************************************************************) IGPBrush = interface ['{C5A51119-107A-4EE4-8989-83659A5149A1}'] function Clone() : TGPBrush; function GetType() : TGPBrushType; function GetNativeBrush() : GpBrush; property BrushType : TGPBrushType read GetType; end; IGPWrapBrush = interface( IGPBrush ) ['{774EE93A-BFAD-41B2-B68A-D40E975711EA}'] function GetWrapMode() : TGPWrapMode; procedure SetWrapModeProp(wrapMode: TGPWrapMode); procedure SetTransformProp(matrix: IGPMatrix); function GetTransform() : IGPMatrix; property WrapMode : TGPWrapMode read GetWrapMode write SetWrapModeProp; property Transform : IGPMatrix read GetTransform write SetTransformProp; end; IGPBlendBrush = interface( IGPWrapBrush ) ['{3DBE75FD-74EF-48CF-8579-69B9EF730DB1}'] function GetBlendCount() : Integer; function GetBlend() : TGPBlendArray; procedure SetBlendProp( blendFactors : TGPBlendArray ); function GetInterpolationColorCount() : Integer; procedure SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); function GetInterpolationColors() : TGPInterpolationColorArray; procedure SetGammaCorrectionProp(useGammaCorrection: Boolean); function GetGammaCorrection() : Boolean; property Blend : TGPBlendArray read GetBlend write SetBlendProp; property BlendCount : Integer read GetBlendCount; property InterpolationColors : TGPInterpolationColorArray read GetInterpolationColors write SetInterpolationColorsProp; property InterpolationColorCount : Integer read GetInterpolationColorCount; property GammaCorrection : Boolean read GetGammaCorrection write SetGammaCorrectionProp; end; //-------------------------------------------------------------------------- // Abstract base class for various brush types //-------------------------------------------------------------------------- TGPBrush = class( TGPBase, IGPBrush ) protected FNativeBrush : GpBrush; protected procedure SetNativeBrush( nativeBrush: GpBrush ); function GetNativeBrush() : GpBrush; constructor Create(nativeBrush: GpBrush); overload; public constructor Create(); overload; destructor Destroy(); override; public function Clone() : TGPBrush; virtual; function GetType() : TGPBrushType; end; //-------------------------------------------------------------------------- // Solid Fill Brush Object //-------------------------------------------------------------------------- IGPSolidBrush = interface( IGPBrush ) ['{388E717D-5FFA-4262-9B07-0A72FF8CFEC8}'] function GetColor() : TGPColor; function SetColor(color: TGPColor) : TGPSolidBrush; procedure SetColorProp(color: TGPColor); property Color : TGPColor read GetColor write SetColorProp; end; TGPSolidBrush = class(TGPBrush, IGPSolidBrush) protected function GetColor() : TGPColor; function SetColor(color: TGPColor) : TGPSolidBrush; procedure SetColorProp(color: TGPColor); public constructor Create(color: TGPColor); overload; constructor Create(); overload; end; IGPTransformable = interface ['{9EEFBE7F-9DA0-47D4-B426-75A0047CF6BE}'] function GetTransform() : IGPMatrix; function SetTransform(matrix: IGPMatrix) : IGPTransformable; procedure SetTransformProp(matrix: IGPMatrix); function ResetTransform() : IGPTransformable; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; property Transform : IGPMatrix read GetTransform write SetTransformProp; end; //-------------------------------------------------------------------------- // Texture Brush Fill Object //-------------------------------------------------------------------------- IGPTextureBrush = interface( IGPWrapBrush ) ['{F0DE6DAC-4D8D-408D-8D1A-CCCF5A70FF7A}'] function SetTransform(matrix: IGPMatrix) : TGPTextureBrush; function ResetTransform() : TGPTextureBrush; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function SetWrapMode(wrapMode: TGPWrapMode) : TGPTextureBrush; function GetImage() : IGPImage; function SetImage( image : IGPImage ) : TGPTextureBrush; procedure SetImageProp( image : IGPImage ); property Image : IGPImage read GetImage write SetImageProp; end; TGPTextureBrush = class(TGPBrush, IGPTextureBrush, IGPTransformable) public constructor Create(image: IGPImage; wrapMode: TGPWrapMode = WrapModeTile); overload; constructor Create(image: IGPImage; wrapMode: TGPWrapMode; dstRect: TGPRectF); overload; constructor Create(image: IGPImage; dstRect: TGPRectF; imageAttributes: IGPImageAttributes = NIL); overload; constructor Create(image: IGPImage; dstRect: TGPRect; imageAttributes: IGPImageAttributes = NIL); overload; constructor Create(image: IGPImage; wrapMode: TGPWrapMode; dstRect: TGPRect); overload; constructor Create(image: IGPImage; wrapMode: TGPWrapMode; dstX, dstY, dstWidth, dstHeight: Single); overload; constructor Create(image: IGPImage; wrapMode: TGPWrapMode; dstX, dstY, dstWidth, dstHeight: Integer); overload; constructor Create(); overload; protected function SetTransformT(matrix: IGPMatrix) : IGPTransformable; function ResetTransformT() : IGPTransformable; function MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function IGPTransformable.SetTransform = SetTransformT; function IGPTransformable.ResetTransform = ResetTransformT; function IGPTransformable.MultiplyTransform = MultiplyTransformT; function IGPTransformable.TranslateTransform = TranslateTransformT; function IGPTransformable.ScaleTransform = ScaleTransformT; function IGPTransformable.RotateTransform = RotateTransformT; public function SetTransform(matrix: IGPMatrix) : TGPTextureBrush; procedure SetTransformProp(matrix: IGPMatrix); function GetTransform() : IGPMatrix; function ResetTransform() : TGPTextureBrush; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; function GetWrapMode() : TGPWrapMode; function SetWrapMode(wrapMode: TGPWrapMode) : TGPTextureBrush; procedure SetWrapModeProp(wrapMode: TGPWrapMode); function GetImage() : IGPImage; function SetImage( image : IGPImage ) : TGPTextureBrush; procedure SetImageProp( image : IGPImage ); end; //-------------------------------------------------------------------------- // Linear Gradient Brush Object //-------------------------------------------------------------------------- IGPLinearGradientBrush = interface( IGPBlendBrush ) ['{FD7C48BB-0DD6-4F12-8786-940A0308A4C7}'] function SetLinearColors(color1, color2: TGPColor) : TGPLinearGradientBrush; function GetLinearColors(out color1, color2: TGPColor) : TGPLinearGradientBrush; function GetRectangleF() : TGPRectF; function GetRectangle() : TGPRect; function SetGammaCorrection(useGammaCorrection: Boolean) : TGPLinearGradientBrush; function SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPLinearGradientBrush; function SetBlend( blendFactors : array of TGPBlend ) : TGPLinearGradientBrush; function SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPLinearGradientBrush; function SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPLinearGradientBrush; function SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; function SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; function SetTransform(matrix: IGPMatrix) : TGPLinearGradientBrush; overload; function ResetTransform() : TGPLinearGradientBrush; overload; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; overload; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; overload; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; overload; function SetWrapMode(wrapMode: TGPWrapMode) : TGPLinearGradientBrush; end; TGPLinearGradientBrush = class(TGPBrush, IGPLinearGradientBrush, IGPTransformable) public constructor Create(); overload; constructor Create( point1, point2: TGPPointF; color1, color2: TGPColor); overload; constructor Create( point1, point2: TGPPoint; color1, color2: TGPColor); overload; constructor Create(rect: TGPRectF; color1, color2: TGPColor; mode: TGPLinearGradientMode); overload; constructor Create(rect: TGPRect; color1, color2: TGPColor; mode: TGPLinearGradientMode); overload; constructor Create(rect: TGPRectF; color1, color2: TGPColor; angle: Single; isAngleScalable: Boolean = False); overload; constructor Create(rect: TGPRect; color1, color2: TGPColor; angle: Single; isAngleScalable: Boolean = False); overload; public function SetLinearColors(color1, color2: TGPColor) : TGPLinearGradientBrush; function GetLinearColors(out color1, color2: TGPColor) : TGPLinearGradientBrush; function GetRectangleF() : TGPRectF; function GetRectangle() : TGPRect; procedure SetGammaCorrectionProp(useGammaCorrection: Boolean); function SetGammaCorrection(useGammaCorrection: Boolean) : TGPLinearGradientBrush; function GetGammaCorrection() : Boolean; function GetBlendCount() : Integer; function GetBlend() : TGPBlendArray; function SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPLinearGradientBrush; function SetBlend( blendFactors : array of TGPBlend ) : TGPLinearGradientBrush; procedure SetBlendProp( blendFactors : TGPBlendArray ); function GetInterpolationColorCount() : Integer; procedure SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); function SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPLinearGradientBrush; function SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPLinearGradientBrush; function GetInterpolationColors() : TGPInterpolationColorArray; function SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; function SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; function SetTransform(matrix: IGPMatrix) : TGPLinearGradientBrush; procedure SetTransformProp(matrix: IGPMatrix); function GetTransform() : IGPMatrix; function ResetTransform() : TGPLinearGradientBrush; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; procedure SetWrapModeProp(wrapMode: TGPWrapMode); function SetWrapMode(wrapMode: TGPWrapMode) : TGPLinearGradientBrush; function GetWrapMode() : TGPWrapMode; protected function SetTransformT(matrix: IGPMatrix) : IGPTransformable; function ResetTransformT() : IGPTransformable; function MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function IGPTransformable.SetTransform = SetTransformT; function IGPTransformable.ResetTransform = ResetTransformT; function IGPTransformable.MultiplyTransform = MultiplyTransformT; function IGPTransformable.TranslateTransform = TranslateTransformT; function IGPTransformable.ScaleTransform = ScaleTransformT; function IGPTransformable.RotateTransform = RotateTransformT; end; //-------------------------------------------------------------------------- // Hatch Brush Object //-------------------------------------------------------------------------- IGPHatchBrush = interface( IGPBrush ) ['{302E268C-E3B3-421F-8EDD-341FEA9E21D9}'] procedure SetHatchStyleProp( style : TGPHatchStyle ); function SetHatchStyle( style : TGPHatchStyle ) : TGPHatchBrush; function GetHatchStyle() : TGPHatchStyle; procedure SetForegroundColorProp( color : TGPColor ); function SetForegroundColor( color : TGPColor ) : TGPHatchBrush; function GetForegroundColor() : TGPColor; procedure SetBackgroundColorProp( color : TGPColor ); function SetBackgroundColor( color : TGPColor ) : TGPHatchBrush; function GetBackgroundColor() : TGPColor; property HatchStyle : TGPHatchStyle read GetHatchStyle write SetHatchStyleProp; property ForegroundColor : TGPColor read GetForegroundColor write SetForegroundColorProp; property BackgroundColor : TGPColor read GetBackgroundColor write SetBackgroundColorProp; end; TGPHatchBrush = class(TGPBrush, IGPHatchBrush) public constructor Create(); overload; // ok constructor Create(hatchStyle: TGPHatchStyle; foreColor: TGPColor; backColor: TGPColor = aclBlack); overload; // ok public procedure SetHatchStyleProp( style : TGPHatchStyle ); function SetHatchStyle( style : TGPHatchStyle ) : TGPHatchBrush; function GetHatchStyle() : TGPHatchStyle; procedure SetForegroundColorProp( color : TGPColor ); function SetForegroundColor( color : TGPColor ) : TGPHatchBrush; function GetForegroundColor() : TGPColor; procedure SetBackgroundColorProp( color : TGPColor ); function SetBackgroundColor( color : TGPColor ) : TGPHatchBrush; function GetBackgroundColor() : TGPColor; end; (**************************************************************************\ * * GDI+ Pen class * \**************************************************************************) //-------------------------------------------------------------------------- // Pen class //-------------------------------------------------------------------------- IGPPen = interface ['{3078FAF8-1E13-4FF0-A9B0-6350298958B6}'] function GetNativePen() : GpPen; function Clone() : TGPPen; procedure SetWidthProp(width: Single); function SetWidth(width: Single) : TGPPen; function GetWidth() : Single; // Set/get line caps: start, end, and dash // Line cap and join APIs by using LineCap and LineJoin enums. function SetLineCap(startCap, endCap: TGPLineCap; dashCap: TGPDashCap) : TGPPen; procedure SetStartCapProp(startCap: TGPLineCap); function SetStartCap(startCap: TGPLineCap) : TGPPen; function GetStartCap() : TGPLineCap; procedure SetEndCapProp(endCap: TGPLineCap); function SetEndCap(endCap: TGPLineCap) : TGPPen; function GetEndCap() : TGPLineCap; procedure SetDashCapProp(dashCap: TGPDashCap); function SetDashCap(dashCap: TGPDashCap) : TGPPen; function GetDashCap() : TGPDashCap; procedure SetLineJoinProp(lineJoin: TGPLineJoin); function SetLineJoin(lineJoin: TGPLineJoin) : TGPPen; function GetLineJoin() : TGPLineJoin; procedure SetCustomStartCapProp(customCap: IGPCustomLineCap); function SetCustomStartCap(customCap: IGPCustomLineCap) : TGPPen; function GetCustomStartCap() : IGPCustomLineCap; procedure SetCustomEndCapProp(customCap: IGPCustomLineCap); function SetCustomEndCap(customCap: IGPCustomLineCap) : TGPPen; function GetCustomEndCap() : IGPCustomLineCap; procedure SetMiterLimitProp(miterLimit: Single); function SetMiterLimit(miterLimit: Single) : TGPPen; function GetMiterLimit() : Single; procedure SetAlignmentProp( penAlignment: TGPPenAlignment); function SetAlignment( penAlignment: TGPPenAlignment) : TGPPen; function GetAlignment() : TGPPenAlignment; function SetTransform(matrix: IGPMatrix) : TGPPen; procedure SetTransformProp(matrix: IGPMatrix); function GetTransform() : IGPMatrix; function ResetTransform() : TGPPen; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function GetPenType() : TGPPenType; procedure SetColorProp(color: TGPColor); function SetColor(color: TGPColor) : TGPPen; function GetColor() : TGPColor; procedure SetBrushProp( brush: IGPBrush); function SetBrush( brush: IGPBrush) : TGPPen; function GetBrush() : IGPBrush; procedure SetDashStyleProp(dashStyle: TGPDashStyle); function SetDashStyle(dashStyle: TGPDashStyle) : TGPPen; function GetDashStyle() : TGPDashStyle; procedure SetDashOffsetProp( dashOffset: Single ); function SetDashOffset( dashOffset: Single ) : TGPPen; function GetDashOffset() : Single; function GetDashPatternCount() : Integer; function SetDashPattern( dashArray: array of Single ) : TGPPen; procedure SetDashPatternProp( dashArray: TGPSingleArray ); function GetDashPattern() : TGPSingleArray; function GetCompoundArrayCount() : Integer; function SetCompoundArray( compoundArray: array of Single ) : TGPPen; procedure SetCompoundArrayProp( compoundArray: TGPSingleArray ); function GetCompoundArray() : TGPSingleArray; property PenType : TGPPenType read GetPenType; property Width : Single read GetWidth write SetWidthProp; property Color : TGPColor read GetColor write SetColorProp; property Brush : IGPBrush read GetBrush write SetBrushProp; property Alignment : TGPPenAlignment read GetAlignment write SetAlignmentProp; property MiterLimit : Single read GetMiterLimit write SetMiterLimitProp; property DashOffset : Single read GetDashOffset write SetDashOffsetProp; property StartCap : TGPLineCap read GetStartCap write SetStartCapProp; property EndCap : TGPLineCap read GetEndCap write SetEndCapProp; property CustomStartCap : IGPCustomLineCap read GetCustomStartCap write SetCustomStartCapProp; property CustomEndCap : IGPCustomLineCap read GetCustomEndCap write SetCustomEndCapProp; property DashStyle : TGPDashStyle read GetDashStyle write SetDashStyleProp; property DashCap : TGPDashCap read GetDashCap write SetDashCapProp; property DashPattern : TGPSingleArray read GetDashPattern write SetDashPatternProp; property LineJoin : TGPLineJoin read GetLineJoin write SetLineJoinProp; property CompoundArray : TGPSingleArray read GetCompoundArray write SetCompoundArrayProp; property Transform : IGPMatrix read GetTransform write SetTransformProp; end; TGPPen = class( TGPBase, IGPPen, IGPTransformable ) protected FNativePen : GpPen; protected procedure SetNativePen(nativePen: GpPen); function GetNativePen() : GpPen; constructor CreateGdiPlus(nativePen: GpPen; Dummy : Boolean); public constructor Create(color: TGPColor; width: Single = 1.0); overload; constructor Create( brush: IGPBrush; width: Single = 1.0); overload; destructor Destroy(); override; public function Clone() : TGPPen; procedure SetWidthProp(width: Single); function SetWidth(width: Single) : TGPPen; function GetWidth() : Single; // Set/get line caps: start, end, and dash // Line cap and join APIs by using LineCap and LineJoin enums. function SetLineCap(startCap, endCap: TGPLineCap; dashCap: TGPDashCap) : TGPPen; procedure SetStartCapProp(startCap: TGPLineCap); function SetStartCap(startCap: TGPLineCap) : TGPPen; function GetStartCap() : TGPLineCap; procedure SetEndCapProp(endCap: TGPLineCap); function SetEndCap(endCap: TGPLineCap) : TGPPen; function GetEndCap() : TGPLineCap; procedure SetDashCapProp(dashCap: TGPDashCap); function SetDashCap(dashCap: TGPDashCap) : TGPPen; function GetDashCap() : TGPDashCap; procedure SetLineJoinProp(lineJoin: TGPLineJoin); function SetLineJoin(lineJoin: TGPLineJoin) : TGPPen; function GetLineJoin() : TGPLineJoin; procedure SetCustomStartCapProp(customCap: IGPCustomLineCap); function SetCustomStartCap(customCap: IGPCustomLineCap) : TGPPen; function GetCustomStartCap() : IGPCustomLineCap; procedure SetCustomEndCapProp(customCap: IGPCustomLineCap); function SetCustomEndCap(customCap: IGPCustomLineCap) : TGPPen; function GetCustomEndCap() : IGPCustomLineCap; procedure SetMiterLimitProp(miterLimit: Single); function SetMiterLimit(miterLimit: Single) : TGPPen; function GetMiterLimit() : Single; procedure SetAlignmentProp( penAlignment: TGPPenAlignment); function SetAlignment( penAlignment: TGPPenAlignment) : TGPPen; function GetAlignment() : TGPPenAlignment; procedure SetTransformProp(matrix: IGPMatrix); function SetTransform(matrix: IGPMatrix) : TGPPen; function GetTransform() : IGPMatrix; function ResetTransform() : TGPPen; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; function GetPenType() : TGPPenType; procedure SetColorProp(color: TGPColor); function SetColor(color: TGPColor) : TGPPen; function GetColor() : TGPColor; procedure SetBrushProp( brush: IGPBrush); function SetBrush( brush: IGPBrush) : TGPPen; function GetBrush() : IGPBrush; procedure SetDashStyleProp(dashStyle: TGPDashStyle); function SetDashStyle( dashStyle: TGPDashStyle ) : TGPPen; function GetDashStyle() : TGPDashStyle; procedure SetDashOffsetProp( dashOffset: Single ); function SetDashOffset( dashOffset: Single ) : TGPPen; function GetDashOffset() : Single; function GetDashPatternCount() : Integer; function SetDashPattern( dashArray: array of Single ) : TGPPen; procedure SetDashPatternProp( dashArray: TGPSingleArray ); function GetDashPattern() : TGPSingleArray; function GetCompoundArrayCount() : Integer; function SetCompoundArray( compoundArray: array of Single ) : TGPPen; procedure SetCompoundArrayProp( compoundArray: TGPSingleArray ); function GetCompoundArray() : TGPSingleArray; protected function SetTransformT(matrix: IGPMatrix) : IGPTransformable; function ResetTransformT() : IGPTransformable; function MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function IGPTransformable.SetTransform = SetTransformT; function IGPTransformable.ResetTransform = ResetTransformT; function IGPTransformable.MultiplyTransform = MultiplyTransformT; function IGPTransformable.TranslateTransform = TranslateTransformT; function IGPTransformable.ScaleTransform = ScaleTransformT; function IGPTransformable.RotateTransform = RotateTransformT; end; (**************************************************************************\ * * GDI+ StringFormat class * \**************************************************************************) IGPStringFormat = interface ['{F07F7F74-9E3C-4B01-BC57-B892B69B6FD3}'] function GetNativeFormat() : GpStringFormat; function Clone() : TGPStringFormat; function SetFormatFlags(flags: Integer) : TGPStringFormat; procedure SetFormatFlagsProp(flags: Integer); function GetFormatFlags() : Integer; function SetAlignment(align: TGPStringAlignment) : TGPStringFormat; procedure SetAlignmentProp(align: TGPStringAlignment); function GetAlignment() : TGPStringAlignment; function SetLineAlignment(align: TGPStringAlignment) : TGPStringFormat; procedure SetLineAlignmentProp(align: TGPStringAlignment); function GetLineAlignment() : TGPStringAlignment; function SetHotkeyPrefix(hotkeyPrefix: TGPHotkeyPrefix) : TGPStringFormat; procedure SetHotkeyPrefixProp(hotkeyPrefix: TGPHotkeyPrefix); function GetHotkeyPrefix() : TGPHotkeyPrefix; function SetTabStops(firstTabOffset: Single; tabStops : array of Single ) : TGPStringFormat; function GetTabStopCount() : Integer; function GetTabStops( out initialTabOffset : Single ) : TGPSingleArray; overload; function GetTabStops() : TGPSingleArray; overload; function GetTabStopsProp() : TGPSingleArray; function GetInitialTabOffset() : Single; function SetDigitSubstitution(language: LANGID; substitute: TGPStringDigitSubstitute) : TGPStringFormat; function GetDigitSubstitutionLanguage() : LANGID; function GetDigitSubstitutionMethod() : TGPStringDigitSubstitute; function SetTrimming(trimming: TGPStringTrimming) : TGPStringFormat; procedure SetTrimmingProp(trimming: TGPStringTrimming); function GetTrimming() : TGPStringTrimming; function SetMeasurableCharacterRanges( ranges : array of TGPCharacterRange ) : TGPStringFormat; function GetMeasurableCharacterRangeCount() : Integer; property FormatFlags : Integer read GetFormatFlags write SetFormatFlagsProp; property Alignment : TGPStringAlignment read GetAlignment write SetAlignmentProp; property LineAlignment : TGPStringAlignment read GetLineAlignment write SetLineAlignmentProp; property HotkeyPrefix : TGPHotkeyPrefix read GetHotkeyPrefix write SetHotkeyPrefixProp; property TabStopCount : Integer read GetTabStopCount; property TabStops : TGPSingleArray read GetTabStopsProp; property InitialTabOffset : Single read GetInitialTabOffset; property DigitSubstitutionLanguage : LANGID read GetDigitSubstitutionLanguage; property DigitSubstitutionMethod : TGPStringDigitSubstitute read GetDigitSubstitutionMethod; property Trimming : TGPStringTrimming read GetTrimming write SetTrimmingProp; end; TGPStringFormat = class( TGPBase, IGPStringFormat ) protected FNativeFormat: GpStringFormat; function GetNativeFormat() : GpStringFormat; protected procedure Assign(source: TGPStringFormat); constructor CreateGdiPlus(clonedStringFormat: GpStringFormat; Dummy : Boolean); public constructor Create(formatFlags: Integer = 0; language: LANGID = LANG_NEUTRAL); overload; constructor Create(format: TGPStringFormat); overload; destructor Destroy(); override; public function Clone() : TGPStringFormat; function SetFormatFlags(flags: Integer) : TGPStringFormat; procedure SetFormatFlagsProp(flags: Integer); function GetFormatFlags() : Integer; function SetAlignment(align: TGPStringAlignment) : TGPStringFormat; procedure SetAlignmentProp(align: TGPStringAlignment); function GetAlignment() : TGPStringAlignment; function SetLineAlignment(align: TGPStringAlignment) : TGPStringFormat; procedure SetLineAlignmentProp(align: TGPStringAlignment); function GetLineAlignment() : TGPStringAlignment; function SetHotkeyPrefix(hotkeyPrefix: TGPHotkeyPrefix) : TGPStringFormat; procedure SetHotkeyPrefixProp(hotkeyPrefix: TGPHotkeyPrefix); function GetHotkeyPrefix() : TGPHotkeyPrefix; function SetTabStops( firstTabOffset: Single; tabStops : array of Single ) : TGPStringFormat; function GetTabStopCount() : Integer; function GetTabStops( out initialTabOffset : Single ) : TGPSingleArray; overload; function GetTabStops() : TGPSingleArray; overload; function GetTabStopsProp() : TGPSingleArray; function GetInitialTabOffset() : Single; function SetDigitSubstitution(language: LANGID; substitute: TGPStringDigitSubstitute) : TGPStringFormat; function GetDigitSubstitutionLanguage() : LANGID; function GetDigitSubstitutionMethod() : TGPStringDigitSubstitute; function SetTrimming(trimming: TGPStringTrimming) : TGPStringFormat; procedure SetTrimmingProp(trimming: TGPStringTrimming); function GetTrimming() : TGPStringTrimming; function SetMeasurableCharacterRanges( ranges : array of TGPCharacterRange ) : TGPStringFormat; function GetMeasurableCharacterRangeCount() : Integer; public class function GenericDefault() : TGPStringFormat; class function GenericTypographic() : TGPStringFormat; end; (**************************************************************************\ * * GDI+ Graphics Path class * \**************************************************************************) IGPGraphicsPath = interface ['{E83A7063-6F55-4A3C-AC91-0B14DF5D5510}'] function GetNativePath() : GpPath; function Clone() : TGPGraphicsPath; // Reset the path object to empty (and fill mode to FillModeAlternate) function Reset() : TGPGraphicsPath; function GetFillMode() : TGPFillMode; function SetFillMode(fillmode: TGPFillMode) : TGPGraphicsPath; procedure SetFillModeProp(fillmode: TGPFillMode); function GetPathData() : IGPPathData; function StartFigure() : TGPGraphicsPath; function CloseFigure() : TGPGraphicsPath; function CloseAllFigures() : TGPGraphicsPath; function SetMarker() : TGPGraphicsPath; function ClearMarkers() : TGPGraphicsPath; function Reverse() : TGPGraphicsPath; function GetLastPoint() : TGPPointF; function AddLineF(const pt1, pt2: TGPPointF) : TGPGraphicsPath; overload; function AddLineF(x1, y1, x2, y2: Single) : TGPGraphicsPath; overload; function AddLinesF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddLine(const pt1, pt2: TGPPoint) : TGPGraphicsPath; overload; function AddLine(x1, y1, x2, y2: Integer) : TGPGraphicsPath; overload; function AddLines(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddArcF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArcF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArc(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArc(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddBezierF(pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphicsPath; overload; function AddBezierF(x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphicsPath; overload; function AddBeziersF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddBezier(pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphicsPath; overload; function AddBezier(x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphicsPath; overload; function AddBeziers(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddCurveF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; overload; function AddCurveF(points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; overload; function AddClosedCurveF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddClosedCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; overload; function AddClosedCurve(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddClosedCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; overload; function AddRectangleF(rect: TGPRectF) : TGPGraphicsPath; overload; function AddRectangleF(x, y, width, height: Single) : TGPGraphicsPath; overload; function AddRectangle(rect: TGPRect) : TGPGraphicsPath; overload; function AddRectangle(x, y, width, height: Integer) : TGPGraphicsPath; overload; function AddRoundRectangleF( ARect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphicsPath; function AddRoundRectangle( ARect: TGPRect; ACornerSize : TGPSize ) : TGPGraphicsPath; function AddRectanglesF(rects: array of TGPRectF) : TGPGraphicsPath; function AddRectangles(rects: array of TGPRect) : TGPGraphicsPath; function AddEllipseF(rect: TGPRectF) : TGPGraphicsPath; overload; function AddEllipseF(x, y, width, height: Single) : TGPGraphicsPath; overload; function AddEllipse(rect: TGPRect) : TGPGraphicsPath; overload; function AddEllipse(x, y, width, height: Integer) : TGPGraphicsPath; overload; function AddPieF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPieF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPie(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPie(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPolygonF(points: array of TGPPointF) : TGPGraphicsPath; function AddPolygon(points: array of TGPPoint) : TGPGraphicsPath; function AddPath(addingPath: IGPGraphicsPath; connect: Boolean) : TGPGraphicsPath; function AddStringF(string_: WideString; font : IGPFont; origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; font : IGPFont; layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; font : IGPFont; origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; font : IGPFont; layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; overload; function Transform(matrix: IGPMatrix) : TGPGraphicsPath; // This is not always the tightest bounds. function GetBoundsF( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRectF; function GetBounds( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRect; // Once flattened, the resultant path is made of line segments and // the original path information is lost. When matrix is NULL the // identity matrix is assumed. function Flatten(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function Widen( pen: IGPPen; matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function Outline(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; // Once this is called, the resultant path is made of line segments and // the original path information is lost. When matrix is NULL, the // identity matrix is assumed. function Warp( destPoints : array of TGPPointF; srcRect: TGPRectF; matrix: IGPMatrix = NIL; warpMode: TGPWarpMode = WarpModePerspective; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function GetPointCount() : Integer; function GetPathTypes(types: PBYTE; count: Integer) : TGPGraphicsPath; function GetPathPointsF() : TGPPointFArray; function GetPathPoints() : TGPPointArray; function IsVisibleF(point: TGPPointF; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(point: TGPPoint; g : IGPGraphics = NIL) : Boolean; overload; function IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisibleF(point: TGPPointF; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisibleF(x, y: Single; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisible(point: TGPPoint; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisible(x, y: Integer; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; property LastPoint : TGPPointF read GetLastPoint; property FillMode : TGPFillMode read GetFillMode write SetFillModeProp; end; TGPGraphicsPath = class( TGPBase, IGPGraphicsPath ) protected FNativePath: GpPath; protected procedure SetNativePath(nativePath: GpPath); constructor CreateGdiPlus(nativePath: GpPath; Dummy : Boolean); public constructor Create(path: IGPGraphicsPath); overload; constructor Create(fillMode: TGPFillMode = FillModeAlternate); overload; constructor Create( points : array of TGPPointF; types : array of BYTE; fillMode: TGPFillMode = FillModeAlternate ); overload; constructor Create( points : array of TGPPoint; types : array of BYTE; fillMode: TGPFillMode = FillModeAlternate ); overload; destructor Destroy(); override; public function GetNativePath() : GpPath; public function Clone() : TGPGraphicsPath; // Reset the path object to empty (and fill mode to FillModeAlternate) function Reset() : TGPGraphicsPath; function GetFillMode() : TGPFillMode; function SetFillMode(fillmode: TGPFillMode) : TGPGraphicsPath; procedure SetFillModeProp(fillmode: TGPFillMode); function GetPathData() : IGPPathData; function StartFigure() : TGPGraphicsPath; function CloseFigure() : TGPGraphicsPath; function CloseAllFigures() : TGPGraphicsPath; function SetMarker() : TGPGraphicsPath; function ClearMarkers() : TGPGraphicsPath; function Reverse() : TGPGraphicsPath; function GetLastPoint() : TGPPointF; function AddLineF(const pt1, pt2: TGPPointF) : TGPGraphicsPath; overload; function AddLineF(x1, y1, x2, y2: Single) : TGPGraphicsPath; overload; function AddLinesF(points: array of TGPPointF) : TGPGraphicsPath; function AddLine(const pt1, pt2: TGPPoint) : TGPGraphicsPath; overload; function AddLine(x1, y1, x2, y2: Integer) : TGPGraphicsPath; overload; function AddLines(points: array of TGPPoint) : TGPGraphicsPath; function AddArcF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArcF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArc(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddArc(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddBezierF(pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphicsPath; overload; function AddBezierF(x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphicsPath; overload; function AddBeziersF(points: array of TGPPointF) : TGPGraphicsPath; function AddBezier(pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphicsPath; overload; function AddBezier(x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphicsPath; overload; function AddBeziers(points: array of TGPPoint) : TGPGraphicsPath; function AddCurveF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; overload; function AddCurveF(points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; overload; function AddCurve(points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; overload; function AddClosedCurveF(points: array of TGPPointF) : TGPGraphicsPath; overload; function AddClosedCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; overload; function AddClosedCurve(points: array of TGPPoint) : TGPGraphicsPath; overload; function AddClosedCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; overload; function AddRectangleF(rect: TGPRectF) : TGPGraphicsPath; overload; function AddRectangleF(x, y, width, height: Single) : TGPGraphicsPath; overload; function AddRectangle(rect: TGPRect) : TGPGraphicsPath; overload; function AddRectangle(x, y, width, height: Integer) : TGPGraphicsPath; overload; function AddRoundRectangleF( ARect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphicsPath; function AddRoundRectangle( ARect: TGPRect; ACornerSize : TGPSize ) : TGPGraphicsPath; function AddRectanglesF(rects: array of TGPRectF) : TGPGraphicsPath; function AddRectangles(rects: array of TGPRect) : TGPGraphicsPath; function AddEllipseF(rect: TGPRectF) : TGPGraphicsPath; overload; function AddEllipseF(x, y, width, height: Single) : TGPGraphicsPath; overload; function AddEllipse(rect: TGPRect) : TGPGraphicsPath; overload; function AddEllipse(x, y, width, height: Integer) : TGPGraphicsPath; overload; function AddPieF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPieF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPie(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPie(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; overload; function AddPolygonF(points: array of TGPPointF) : TGPGraphicsPath; function AddPolygon(points: array of TGPPoint) : TGPGraphicsPath; function AddPath(addingPath: IGPGraphicsPath; connect: Boolean) : TGPGraphicsPath; function AddStringF(string_: WideString; font : IGPFont; origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; font : IGPFont; layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; font : IGPFont; origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; font : IGPFont; layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddStringF(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; overload; function AddString(string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; overload; function Transform(matrix: IGPMatrix) : TGPGraphicsPath; // This is not always the tightest bounds. function GetBoundsF( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRectF; function GetBounds( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRect; // Once flattened, the resultant path is made of line segments and // the original path information is lost. When matrix is NULL the // identity matrix is assumed. function Flatten(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function Widen( pen: IGPPen; matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function Outline(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; // Once this is called, the resultant path is made of line segments and // the original path information is lost. When matrix is NULL, the // identity matrix is assumed. function Warp( destPoints : array of TGPPointF; srcRect: TGPRectF; matrix: IGPMatrix = NIL; warpMode: TGPWarpMode = WarpModePerspective; flatness: Single = FlatnessDefault) : TGPGraphicsPath; function GetPointCount() : Integer; function GetPathTypes(types: PBYTE; count: Integer) : TGPGraphicsPath; function GetPathPointsF() : TGPPointFArray; function GetPathPoints() : TGPPointArray; function IsVisibleF(point: TGPPointF; g: IGPGraphics = NIL) : Boolean; overload; function IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; overload; function IsVisible(point: TGPPoint; g : IGPGraphics = NIL) : Boolean; overload; function IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisibleF(point: TGPPointF; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisibleF(x, y: Single; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisible(point: TGPPoint; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; function IsOutlineVisible(x, y: Integer; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; overload; end; //-------------------------------------------------------------------------- // GraphisPathIterator class //-------------------------------------------------------------------------- IGPGraphicsPathIterator = interface ['{893BF228-EE25-4FE5-B8F7-20997B95749C}'] function NextSubpath(out startIndex, endIndex: Integer; out isClosed: bool) : Integer; overload; function NextSubpath(path: IGPGraphicsPath; out isClosed: Boolean) : Integer; overload; function NextPathType(out pathType: TGPPathPointType; out startIndex, endIndex: Integer) : Integer; function NextMarker(out startIndex, endIndex: Integer) : Integer; overload; function NextMarker(path: IGPGraphicsPath) : Integer; overload; function GetCount() : Integer; function GetSubpathCount() : Integer; function HasCurve() : Boolean; function Rewind() : TGPGraphicsPathIterator; function Enumerate( out points: TGPPointFArray; out types: TGPByteArray ) : Integer; function CopyData(points: PGPPointF; types: PBYTE; startIndex, endIndex: Integer) : Integer; end; TGPGraphicsPathIterator = class( TGPBase, IGPGraphicsPathIterator ) protected FNativeIterator: GpPathIterator; protected procedure SetNativeIterator(nativeIterator: GpPathIterator); public constructor Create(path: IGPGraphicsPath); reintroduce; destructor Destroy(); override; public function NextSubpath(out startIndex, endIndex: Integer; out isClosed: bool) : Integer; overload; function NextSubpath(path: IGPGraphicsPath; out isClosed: Boolean) : Integer; overload; function NextPathType(out pathType: TGPPathPointType; out startIndex, endIndex: Integer) : Integer; function NextMarker(out startIndex, endIndex: Integer) : Integer; overload; function NextMarker(path: IGPGraphicsPath) : Integer; overload; function GetCount() : Integer; function GetSubpathCount() : Integer; function HasCurve() : Boolean; function Rewind() : TGPGraphicsPathIterator; function Enumerate( out points: TGPPointFArray; out types: TGPByteArray ) : Integer; function CopyData(points: PGPPointF; types: PBYTE; startIndex, endIndex: Integer) : Integer; end; //-------------------------------------------------------------------------- // Path Gradient Brush //-------------------------------------------------------------------------- IGPPathGradientBrush = interface( IGPBlendBrush ) ['{C76439FD-D91B-44B5-91EB-E670B8E94A32}'] function GetCenterColor() : TGPColor; function SetCenterColor(color: TGPColor) : TGPPathGradientBrush; procedure SetCenterColorProp(color: TGPColor); function GetPointCount() : Integer; function GetSurroundColorCount() : Integer; function SetSurroundColors(colors : array of TGPColor ) : TGPPathGradientBrush; procedure SetSurroundColorsProp(colors : TGPColorArray ); function GetSurroundColors() : TGPColorArray; function GetGraphicsPath() : IGPGraphicsPath; function SetGraphicsPath(path: IGPGraphicsPath) : TGPPathGradientBrush; procedure SetGraphicsPathProp(path: IGPGraphicsPath); procedure SetCenterPointFProp(point: TGPPointF); function SetCenterPointF(point: TGPPointF) : TGPPathGradientBrush; function GetCenterPointF() : TGPPointF; function SetCenterPoint(point: TGPPoint) : TGPPathGradientBrush; function GetCenterPoint() : TGPPoint; function GetRectangleF() : TGPRectF; function GetRectangle() : TGPRect; function SetGammaCorrection(useGammaCorrection: Boolean) : TGPPathGradientBrush; function SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPPathGradientBrush; function SetBlend( blendFactors : array of TGPBlend ) : TGPPathGradientBrush; procedure SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); function SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPPathGradientBrush; function SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPPathGradientBrush; function SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; function SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; function SetTransform(matrix: IGPMatrix) : TGPPathGradientBrush; function ResetTransform() : TGPPathGradientBrush; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function GetFocusScales(out xScale, yScale: Single) : TGPPathGradientBrush; function SetFocusScales(xScale, yScale: Single) : TGPPathGradientBrush; function SetWrapMode(wrapMode: TGPWrapMode) : TGPPathGradientBrush; property CenterColor : TGPColor read GetCenterColor write SetCenterColorProp; property CenterPoint : TGPPointF read GetCenterPointF write SetCenterPointFProp; property SurroundColors : TGPColorArray read GetSurroundColors write SetSurroundColorsProp; end; TGPPathGradientBrush = class(TGPBrush, IGPPathGradientBrush, IGPTransformable) public constructor CreateF(points: array of TGPPointF; wrapMode: TGPWrapMode = WrapModeClamp); constructor Create(points: array of TGPPoint; wrapMode: TGPWrapMode = WrapModeClamp); overload; constructor Create(path: IGPGraphicsPath); overload; public function GetCenterColor() : TGPColor; function SetCenterColor(color: TGPColor) : TGPPathGradientBrush; procedure SetCenterColorProp(color: TGPColor); function GetPointCount() : Integer; function GetSurroundColorCount() : Integer; function SetSurroundColors(colors : array of TGPColor ) : TGPPathGradientBrush; procedure SetSurroundColorsProp(colors : TGPColorArray ); function GetSurroundColors() : TGPColorArray; function GetGraphicsPath() : IGPGraphicsPath; function SetGraphicsPath(path: IGPGraphicsPath) : TGPPathGradientBrush; procedure SetGraphicsPathProp(path: IGPGraphicsPath); procedure SetCenterPointFProp(point: TGPPointF); function SetCenterPointF(point: TGPPointF) : TGPPathGradientBrush; function GetCenterPointF() : TGPPointF; function GetCenterPoint() : TGPPoint; function SetCenterPoint(point: TGPPoint) : TGPPathGradientBrush; function GetRectangleF() : TGPRectF; function GetRectangle() : TGPRect; procedure SetGammaCorrectionProp(useGammaCorrection: Boolean); function SetGammaCorrection(useGammaCorrection: Boolean) : TGPPathGradientBrush; function GetGammaCorrection() : Boolean; function GetBlendCount() : Integer; function GetBlend() : TGPBlendArray; function SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPPathGradientBrush; function SetBlend( blendFactors : array of TGPBlend ) : TGPPathGradientBrush; procedure SetBlendProp( blendFactors : TGPBlendArray ); function GetInterpolationColorCount() : Integer; function SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPPathGradientBrush; overload; function SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPPathGradientBrush; procedure SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); function GetInterpolationColors() : TGPInterpolationColorArray; function SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; function SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; function GetTransform() : IGPMatrix; function SetTransform(matrix: IGPMatrix) : TGPPathGradientBrush; procedure SetTransformProp(matrix: IGPMatrix); function ResetTransform() : TGPPathGradientBrush; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; function GetFocusScales(out xScale, yScale: Single) : TGPPathGradientBrush; function SetFocusScales(xScale, yScale: Single) : TGPPathGradientBrush; function GetWrapMode() : TGPWrapMode; function SetWrapMode(wrapMode: TGPWrapMode) : TGPPathGradientBrush; procedure SetWrapModeProp(wrapMode: TGPWrapMode); protected function SetTransformT(matrix: IGPMatrix) : IGPTransformable; function ResetTransformT() : IGPTransformable; function MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function IGPTransformable.SetTransform = SetTransformT; function IGPTransformable.ResetTransform = ResetTransformT; function IGPTransformable.MultiplyTransform = MultiplyTransformT; function IGPTransformable.TranslateTransform = TranslateTransformT; function IGPTransformable.ScaleTransform = ScaleTransformT; function IGPTransformable.RotateTransform = RotateTransformT; end; (**************************************************************************\ * * GDI+ Graphics Object * \**************************************************************************) IGPGraphics = interface ['{95C573E8-DD62-41D4-83DE-2F32799BD922}'] function GetNativeGraphics() : GpGraphics; function Flush(intention: TGPFlushIntention = FlushIntentionFlush) : TGPGraphics; //------------------------------------------------------------------------ // GDI Interop methods //------------------------------------------------------------------------ // Locks the graphics until ReleaseDC is called function GetHDC() : HDC; function ReleaseHDC(hdc: HDC) : TGPGraphics; //------------------------------------------------------------------------ // Rendering modes //------------------------------------------------------------------------ function SetRenderingOrigin( point : TGPPoint ) : TGPGraphics; procedure SetRenderingOriginProp( point : TGPPoint ); function GetRenderingOrigin() : TGPPoint; function SetCompositingMode(compositingMode: TGPCompositingMode) : TGPGraphics; procedure SetCompositingModeProp(compositingMode: TGPCompositingMode); function GetCompositingMode() : TGPCompositingMode; function SetCompositingQuality(compositingQuality: TGPCompositingQuality) : TGPGraphics; procedure SetCompositingQualityProp(compositingQuality: TGPCompositingQuality); function GetCompositingQuality() : TGPCompositingQuality; function SetTextRenderingHint(newMode: TGPTextRenderingHint) : TGPGraphics; procedure SetTextRenderingHintProp(newMode: TGPTextRenderingHint); function GetTextRenderingHint() : TGPTextRenderingHint; function SetTextContrast(contrast: Cardinal) : TGPGraphics; // 0..12 procedure SetTextContrastProp(contrast: Cardinal); // 0..12 function GetTextContrast() : Cardinal; function GetInterpolationMode() : TGPInterpolationMode; function SetInterpolationMode(interpolationMode: TGPInterpolationMode) : TGPGraphics; procedure SetInterpolationModeProp(interpolationMode: TGPInterpolationMode); function GetSmoothingMode() : TGPSmoothingMode; function SetSmoothingMode(smoothingMode: TGPSmoothingMode) : TGPGraphics; procedure SetSmoothingModeProp(smoothingMode: TGPSmoothingMode); function GetPixelOffsetMode() : TGPPixelOffsetMode; function SetPixelOffsetMode(pixelOffsetMode: TGPPixelOffsetMode) : TGPGraphics; procedure SetPixelOffsetModeProp(pixelOffsetMode: TGPPixelOffsetMode); //------------------------------------------------------------------------ // Manipulate current world transform //------------------------------------------------------------------------ function SetTransform(matrix: IGPMatrix) : TGPGraphics; procedure SetTransformProp(matrix: IGPMatrix); function ResetTransform() : TGPGraphics; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function GetTransform() : IGPMatrix; function SetPageUnit( unit_: TGPUnit ) : TGPGraphics; procedure SetPageUnitProp( unit_: TGPUnit ); function SetPageScale( scale: Single ) : TGPGraphics; procedure SetPageScaleProp( scale: Single ); function GetPageUnit() : TGPUnit; function GetPageScale() : Single; function GetDpiX() : Single; function GetDpiY() : Single; function TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPointF ) : TGPGraphics; overload; function TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPoint ) : TGPGraphics; overload; //------------------------------------------------------------------------ // GetNearestColor (for <= 8bpp surfaces). Note: Alpha is ignored. //------------------------------------------------------------------------ function GetNearestColor( AColor : TGPColor ) : TGPColor; // DrawLine(s) function DrawLineF( pen: IGPPen; x1, y1, x2, y2: Single) : TGPGraphics; overload; function DrawLineF( pen: IGPPen; const pt1, pt2: TGPPointF) : TGPGraphics; overload; function DrawLinesF( pen: IGPPen; points : array of TGPPointF ) : TGPGraphics; overload; function DrawLine( pen: IGPPen; x1, y1, x2, y2: Integer) : TGPGraphics; overload; function DrawLine( pen: IGPPen; const pt1, pt2: TGPPoint) : TGPGraphics; overload; function DrawLines( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; overload; // DrawArc function DrawArcF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArcF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArc( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArc( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; overload; // DrawBezier(s) function DrawBezierF( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphics; overload; function DrawBezierF( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphics; overload; function DrawBeziersF( pen: IGPPen; points : array of TGPPointF ) : TGPGraphics; function DrawBezier( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphics; overload; function DrawBezier( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphics; overload; function DrawBeziers( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; // DrawRectangle(s) function DrawRectangleF( pen: IGPPen; rect: TGPRectF) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; x, y, width, height: Single) : TGPGraphics; overload; function DrawRectanglesF( pen: IGPPen; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; rect: TGPRect) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; x, y, width, height: Integer) : TGPGraphics; overload; function DrawRectangles( pen: IGPPen; rects: array of TGPRect ) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; brush: IGPBrush; rect: TGPRectF) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; overload; function DrawRectanglesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; brush: IGPBrush; rect: TGPRect) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; overload; function DrawRectangles( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; overload; // DrawRoundRectangle function DrawRoundRectangleF( pen: IGPPen; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; overload; function DrawRoundRectangle( pen: IGPPen; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; overload; function DrawRoundRectangleF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; overload; function DrawRoundRectangle( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; overload; // DrawEllipse function DrawEllipseF( pen: IGPPen; const rect: TGPRectF) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; x, y, width, height: Single) : TGPGraphics; overload; function DrawEllipsesF( pen: IGPPen; rects: array of TGPRectF) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; const rect: TGPRect) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; x, y, width, height: Integer) : TGPGraphics; overload; function DrawEllipses( pen: IGPPen; rects: array of TGPRect) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; overload; function DrawEllipsesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; brush: IGPBrush; const rect: TGPRect) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; overload; function DrawEllipses( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect) : TGPGraphics; overload; // DrawPie function DrawPieF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPie( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPie( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPie( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawPie( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; overload; // DrawPolygon function DrawPolygonF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode) : TGPGraphics; overload; // DrawPath function DrawPath( pen: IGPPen; path: IGPGraphicsPath) : TGPGraphics; overload; function DrawPath( pen: IGPPen; brush: IGPBrush; path: IGPGraphicsPath) : TGPGraphics; overload; // DrawCurve function DrawCurveF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single) : TGPGraphics; overload; function DrawCurveF( pen: IGPPen; points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint; tension: Single) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; overload; // DrawClosedCurve function DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; points: array of TGPPoint; tension: Single) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; overload; // Clear function Clear( color: TGPColor ) : TGPGraphics; // FillRectangle(s) function FillRectangleF( brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; overload; function FillRectangleF( brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; overload; function FillRectanglesF( brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; function FillRectangle( brush: IGPBrush; const rect: TGPRect) : TGPGraphics; overload; function FillRectangle( brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; overload; function FillRectangles( brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; // FillRoundRectangle function FillRoundRectangleF( brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; function FillRoundRectangle( brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; // FillPolygon function FillPolygonF( brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function FillPolygonF( brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode) : TGPGraphics; overload; function FillPolygon( brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function FillPolygon( brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode) : TGPGraphics; overload; // FillEllipse function FillEllipseF( brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; overload; function FillEllipseF( brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; overload; function FillEllipsesF( brush: IGPBrush; rects: array of TGPRectF) : TGPGraphics; function FillEllipse( brush: IGPBrush; const rect: TGPRect) : TGPGraphics; overload; function FillEllipse( brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; overload; function FillEllipses( brush: IGPBrush; rects: array of TGPRect) : TGPGraphics; // FillPie function FillPieF( brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; overload; function FillPieF( brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; overload; function FillPie( brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; overload; function FillPie( brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; overload; // FillPath function FillPath( brush: IGPBrush; path: IGPGraphicsPath ) : TGPGraphics; // FillClosedCurve function FillClosedCurveF( brush: IGPBrush; points: array of TGPPointF) : TGPGraphics; overload; function FillClosedCurveF( brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5 ) : TGPGraphics; overload; function FillClosedCurve( brush: IGPBrush; points: array of TGPPoint) : TGPGraphics; overload; function FillClosedCurve( brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; overload; // FillRegion function FillRegion( brush: IGPBrush; region: IGPRegion ) : TGPGraphics; // DrawString function DrawStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; // MeasureString function GetStringSizeF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPSizeF; overload; function GetStringSizeF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPSizeF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; overload; // MeasureCharacterRangesF function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; // DrawDriverString function DrawDriverString(text: PUINT16; length: Integer; font: IGPFont; brush: IGPBrush; positions: PGPPointF; flags: Integer; matrix: IGPMatrix) : TGPGraphics; // MeasureDriverString function GetDriverStringBoundingBoxF(text: PUINT16; length: Integer; font: IGPFont; positions: PGPPointF; flags: Integer; matrix: IGPMatrix ) : TGPRectF; // Draw a cached bitmap on this graphics destination offset by // x, y. Note this will fail with WrongState if the CachedBitmap // native format differs from this Graphics. function DrawCachedBitmap(cb: IGPCachedBitmap; x, y: Integer) : TGPGraphics; function DrawImageF(image: IGPImage; const point: TGPPointF) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y: Single) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const rect: TGPRectF) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, width, height: Single) : TGPGraphics; overload; function DrawImage(image: IGPImage; const point: TGPPoint) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y: Integer) : TGPGraphics; overload; function DrawImage(image: IGPImage; const rect: TGPRect) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, width, height: Integer) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const point: TGPPointF; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y: Single; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const rect: TGPRectF; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, width, height: Single; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; const point: TGPPoint; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y: Integer; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; const rect: TGPRect; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, width, height: Integer; Opacity : Single ) : TGPGraphics; overload; // Affine Draw Image // destPoints.length = 3: rect => parallelogram // destPoints[0] <=> top-left corner of the source rectangle // destPoints[1] <=> top-right corner // destPoints[2] <=> bottom-left corner // destPoints.length = 4: rect => quad // destPoints[3] <=> bottom-right corner function DrawImageF(image: IGPImage; destPoints: array of TGPPointF ) : TGPGraphics; overload; function DrawImage(image: IGPImage; destPoints: array of TGPPoint ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const destRect: TGPRectF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImageF(image: IGPImage; destPoints: array of TGPPointF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit) : TGPGraphics; overload; function DrawImage(image: IGPImage; const destRect: TGPRect; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImage(image: IGPImage; destPoints: array of TGPPoint; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; // The following methods are for playing an EMF+ to a graphics // via the enumeration interface. Each record of the EMF+ is // sent to the callback (along with the callbackData). Then // the callback can invoke the Metafile::PlayRecord method // to play the particular record. function EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; const destPoint: TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; const destRect: TGPRect; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; destPoints: array of TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL ) : TGPGraphics; overload; function EnumerateMetafile(metafile : IGPMetafile; const destPoint : TGPPoint; const srcRect : TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL ) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile : IGPMetafile; const destRect, srcRect: TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF( metafile: IGPMetafile; destPoints: array of TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; const srcRect: TGPRect; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; // SetClip function SetClip(g: IGPGraphics; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClipF(rect: TGPRectF; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; function SetClip(rect: TGPRect; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClip(path: IGPGraphicsPath; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClip(region: IGPRegion; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; // This is different than the other SetClip methods because it assumes // that the HRGN is already in device units, so it doesn't transform // the coordinates in the HRGN. function SetClip(hRgn: HRGN; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; procedure SetClipProp( region: IGPRegion ); // IntersectClip function IntersectClipF(const rect: TGPRectF) : TGPGraphics; function IntersectClip(const rect: TGPRect) : TGPGraphics; overload; function IntersectClip(region: IGPRegion) : TGPGraphics; overload; // ExcludeClip function ExcludeClipF(const rect: TGPRectF) : TGPGraphics; function ExcludeClip(const rect: TGPRect) : TGPGraphics; overload; function ExcludeClip(region: IGPRegion) : TGPGraphics; overload; function ResetClip() : TGPGraphics; function TranslateClipF(dx, dy: Single) : TGPGraphics; function TranslateClip(dx, dy: Integer) : TGPGraphics; function GetClip() : IGPRegion; function GetClipBoundsF() : TGPRectF; function GetClipBounds() : TGPRect; function IsClipEmpty() : Boolean; function GetVisibleClipBoundsF() : TGPRectF; function GetVisibleClipBounds() : TGPRect; function IsVisibleClipEmpty: Boolean; function IsVisible(x, y: Integer) : Boolean; overload; function IsVisible(const point: TGPPoint) : Boolean; overload; function IsVisible(x, y, width, height: Integer) : Boolean; overload; function IsVisible(const rect: TGPRect) : Boolean; overload; function IsVisibleF(x, y: Single) : Boolean; overload; function IsVisibleF(const point: TGPPointF) : Boolean; overload; function IsVisibleF(x, y, width, height: Single) : Boolean; overload; function IsVisibleF(const rect: TGPRectF) : Boolean; overload; function Save() : TGPGraphicsState; function Restore(gstate: TGPGraphicsState) : TGPGraphics; function BeginContainerF(const dstrect,srcrect: TGPRectF; unit_: TGPUnit) : TGPGraphicsContainer; overload; function BeginContainer(const dstrect, srcrect: TGPRect; unit_: TGPUnit) : TGPGraphicsContainer; overload; function BeginContainer() : TGPGraphicsContainer; overload; function EndContainer(state: TGPGraphicsContainer) : TGPGraphics; // Only valid when recording metafiles. function AddMetafileComment( data: array of BYTE ) : TGPGraphics; property RenderingOrigin : TGPPoint read GetRenderingOrigin write SetRenderingOriginProp; property CompositingMode : TGPCompositingMode read GetCompositingMode write SetCompositingModeProp; property CompositingQuality : TGPCompositingQuality read GetCompositingQuality write SetCompositingQualityProp; property TextRenderingHint : TGPTextRenderingHint read GetTextRenderingHint write SetTextRenderingHintProp; property TextContrast : Cardinal read GetTextContrast write SetTextContrastProp; property InterpolationMode : TGPInterpolationMode read GetInterpolationMode write SetInterpolationModeProp; property SmoothingMode : TGPSmoothingMode read GetSmoothingMode write SetSmoothingModeProp; property PixelOffsetMode : TGPPixelOffsetMode read GetPixelOffsetMode write SetPixelOffsetModeProp; property Transform : IGPMatrix read GetTransform write SetTransformProp; property Clip : IGPRegion read GetClip write SetClipProp; property PageUnit : TGPUnit read GetPageUnit write SetPageUnitProp; property PageScale : Single read GetPageScale write SetPageScaleProp; property DpiX : Single read GetDpiX; property DpiY : Single read GetDpiY; end; TGPGraphics = class( TGPBase, IGPGraphics, IGPTransformable ) protected FNativeGraphics: GpGraphics; protected procedure SetNativeGraphics(graphics: GpGraphics); function GetNativeGraphics() : GpGraphics; function GetNativePen( pen: TGPPen) : GpPen; constructor CreateGdiPlus(graphics: GpGraphics; Dummy1 : Boolean; Dummy2 : Boolean ); public {$IFNDEF PURE_FMX} constructor Create( canvas : TCanvas ); overload; {$ENDIF} constructor Create( ahdc: HDC ); overload; constructor Create( ahdc: HDC; hdevice: THandle ); overload; constructor Create( hwnd: HWND; icm : Boolean{ = False} ); overload; constructor Create( image: IGPImage ); overload; destructor Destroy(); override; public {$IFNDEF PURE_FMX} class function FromCanvas( canvas : TCanvas ) : TGPGraphics; overload; {$ENDIF} class function FromHDC( ahdc: HDC ) : TGPGraphics; overload; class function FromHDC( ahdc: HDC; hdevice: THandle ) : TGPGraphics; overload; class function FromHWND( hwnd: HWND; icm: Boolean = False ) : TGPGraphics; class function FromImage( image: IGPImage ) : TGPGraphics; public function Flush(intention: TGPFlushIntention = FlushIntentionFlush) : TGPGraphics; //------------------------------------------------------------------------ // GDI Interop methods //------------------------------------------------------------------------ // Locks the graphics until ReleaseDC is called function GetHDC() : HDC; function ReleaseHDC(ahdc: HDC) : TGPGraphics; //------------------------------------------------------------------------ // Rendering modes //------------------------------------------------------------------------ function SetRenderingOrigin( point : TGPPoint ) : TGPGraphics; procedure SetRenderingOriginProp( point : TGPPoint ); function GetRenderingOrigin() : TGPPoint; function SetCompositingMode(compositingMode: TGPCompositingMode) : TGPGraphics; procedure SetCompositingModeProp(compositingMode: TGPCompositingMode); function GetCompositingMode() : TGPCompositingMode; function SetCompositingQuality(compositingQuality: TGPCompositingQuality) : TGPGraphics; procedure SetCompositingQualityProp(compositingQuality: TGPCompositingQuality); function GetCompositingQuality() : TGPCompositingQuality; function SetTextRenderingHint(newMode: TGPTextRenderingHint) : TGPGraphics; procedure SetTextRenderingHintProp(newMode: TGPTextRenderingHint); function GetTextRenderingHint() : TGPTextRenderingHint; function SetTextContrast(contrast: Cardinal) : TGPGraphics; // 0..12 procedure SetTextContrastProp(contrast: Cardinal); // 0..12 function GetTextContrast() : Cardinal; function GetInterpolationMode() : TGPInterpolationMode; function SetInterpolationMode(interpolationMode: TGPInterpolationMode) : TGPGraphics; procedure SetInterpolationModeProp(interpolationMode: TGPInterpolationMode); function GetSmoothingMode() : TGPSmoothingMode; function SetSmoothingMode(smoothingMode: TGPSmoothingMode) : TGPGraphics; procedure SetSmoothingModeProp(smoothingMode: TGPSmoothingMode); function GetPixelOffsetMode() : TGPPixelOffsetMode; function SetPixelOffsetMode(pixelOffsetMode: TGPPixelOffsetMode) : TGPGraphics; procedure SetPixelOffsetModeProp(pixelOffsetMode: TGPPixelOffsetMode); //------------------------------------------------------------------------ // Manipulate current world transform //------------------------------------------------------------------------ function SetTransform(matrix: IGPMatrix) : TGPGraphics; procedure SetTransformProp(matrix: IGPMatrix); function ResetTransform() : TGPGraphics; function MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; function GetTransform() : IGPMatrix; function SetPageUnit( unit_: TGPUnit ) : TGPGraphics; procedure SetPageUnitProp( unit_: TGPUnit ); function SetPageScale( scale: Single ) : TGPGraphics; procedure SetPageScaleProp( scale: Single ); function GetPageUnit() : TGPUnit; function GetPageScale() : Single; function GetDpiX() : Single; function GetDpiY() : Single; function TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPointF ) : TGPGraphics; overload; function TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPoint ) : TGPGraphics; overload; //------------------------------------------------------------------------ // GetNearestColor (for <= 8bpp surfaces). Note: Alpha is ignored. //------------------------------------------------------------------------ function GetNearestColor( AColor : TGPColor ) : TGPColor; // DrawLine(s) function DrawLineF( pen: IGPPen; x1, y1, x2, y2: Single ) : TGPGraphics; overload; function DrawLineF( pen: IGPPen; const pt1, pt2: TGPPointF ) : TGPGraphics; overload; function DrawLinesF( pen: IGPPen; points : array of TGPPointF ) : TGPGraphics; function DrawLine( pen: IGPPen; x1, y1, x2, y2: Integer ) : TGPGraphics; overload; function DrawLine( pen: IGPPen; const pt1, pt2: TGPPoint ) : TGPGraphics; overload; function DrawLines( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; // DrawArc function DrawArcF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArcF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArc( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; overload; function DrawArc( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; overload; // DrawBezier(s) function DrawBezierF( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphics; overload; function DrawBezierF( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphics; overload; function DrawBeziersF( pen: IGPPen; points : array of TGPPointF ) : TGPGraphics; function DrawBezier( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphics; overload; function DrawBezier( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphics; overload; function DrawBeziers( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; // DrawRectangle(s) function DrawRectangleF( pen: IGPPen; rect: TGPRectF) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; x, y, width, height: Single) : TGPGraphics; overload; function DrawRectanglesF( pen: IGPPen; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; rect: TGPRect) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; x, y, width, height: Integer) : TGPGraphics; overload; function DrawRectangles( pen: IGPPen; rects: array of TGPRect ) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; brush: IGPBrush; rect: TGPRectF) : TGPGraphics; overload; function DrawRectangleF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; overload; function DrawRectanglesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; brush: IGPBrush; rect: TGPRect) : TGPGraphics; overload; function DrawRectangle( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; overload; function DrawRectangles( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; overload; // DrawRoundRectangle function DrawRoundRectangleF( pen: IGPPen; const rect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphics; overload; function DrawRoundRectangle( pen: IGPPen; const rect: TGPRect; ACornerSize : TGPSize ) : TGPGraphics; overload; function DrawRoundRectangleF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphics; overload; function DrawRoundRectangle( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize ) : TGPGraphics; overload; // DrawEllipse function DrawEllipseF( pen: IGPPen; const rect: TGPRectF ) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; x, y, width, height: Single ) : TGPGraphics; overload; function DrawEllipsesF( pen: IGPPen; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; const rect: TGPRect ) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; x, y, width, height: Integer ) : TGPGraphics; overload; function DrawEllipses( pen: IGPPen; rects: array of TGPRect ) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF ) : TGPGraphics; overload; function DrawEllipseF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single ) : TGPGraphics; overload; function DrawEllipsesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; brush: IGPBrush; const rect: TGPRect ) : TGPGraphics; overload; function DrawEllipse( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer ) : TGPGraphics; overload; function DrawEllipses( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; overload; // DrawPie function DrawPieF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPie( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPie( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPieF( pen: IGPPen; brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPie( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function DrawPie( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single ) : TGPGraphics; overload; // DrawPolygon function DrawPolygonF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode ) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode ) : TGPGraphics; overload; // DrawPath function DrawPath( pen: IGPPen; path: IGPGraphicsPath ) : TGPGraphics; overload; function DrawPath( pen: IGPPen; brush: IGPBrush; path: IGPGraphicsPath ) : TGPGraphics; overload; // DrawCurve function DrawCurveF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single) : TGPGraphics; overload; function DrawCurveF( pen: IGPPen; points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint; tension: Single) : TGPGraphics; overload; function DrawCurve( pen: IGPPen; points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; overload; // DrawClosedCurve function DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF ) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; points: array of TGPPoint ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; points: array of TGPPoint; tension: Single ) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5 ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5 ) : TGPGraphics; overload; // Clear function Clear( color: TGPColor ) : TGPGraphics; // FillRectangle(s) function FillRectangleF( brush: IGPBrush; const rect: TGPRectF ) : TGPGraphics; overload; function FillRectangleF( brush: IGPBrush; x, y, width, height: Single ) : TGPGraphics; overload; function FillRectanglesF( brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; function FillRectangle( brush: IGPBrush; const rect: TGPRect ) : TGPGraphics; overload; function FillRectangle( brush: IGPBrush; x, y, width, height: Integer ) : TGPGraphics; overload; function FillRectangles( brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; // FillRoundRectangle function FillRoundRectangleF( brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphics; function FillRoundRectangle( brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize ) : TGPGraphics; // FillPolygon function FillPolygonF( brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function FillPolygonF( brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode) : TGPGraphics; overload; function FillPolygon( brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function FillPolygon( brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode) : TGPGraphics; overload; // FillEllipse function FillEllipseF( brush: IGPBrush; const rect: TGPRectF ) : TGPGraphics; overload; function FillEllipseF( brush: IGPBrush; x, y, width, height: Single ) : TGPGraphics; overload; function FillEllipsesF( brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; function FillEllipse( brush: IGPBrush; const rect: TGPRect ) : TGPGraphics; overload; function FillEllipse( brush: IGPBrush; x, y, width, height: Integer ) : TGPGraphics; overload; function FillEllipses( brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; // FillPie function FillPieF( brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function FillPieF( brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single ) : TGPGraphics; overload; function FillPie( brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single ) : TGPGraphics; overload; function FillPie( brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single ) : TGPGraphics; overload; // FillPath function FillPath( brush: IGPBrush; path: IGPGraphicsPath) : TGPGraphics; // FillClosedCurve function FillClosedCurveF( brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; overload; function FillClosedCurveF( brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5 ) : TGPGraphics; overload; function FillClosedCurve( brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; overload; function FillClosedCurve( brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5 ) : TGPGraphics; overload; // FillRegion function FillRegion( brush: IGPBrush; region: IGPRegion ) : TGPGraphics; // DrawString function DrawStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; brush: IGPBrush) : TGPGraphics; overload; function DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; brush: IGPBrush) : TGPGraphics; overload; function DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; { function FillString(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; function FillString(string_: WideString; font: IGPFont; const origin: TGPPointF; brush: IGPBrush) : TGPGraphics; overload; function FillString(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; overload; } // MeasureString function GetStringSizeF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL) : TGPSizeF; overload; function GetStringSizeF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; overload; function GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPSizeF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; overload; function MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; overload; // MeasureCharacterRangesF function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; function MeasureCharacterRangesF(string_: WideString; font: IGPFont; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; overload; // DrawDriverString function DrawDriverString(text: PUINT16; length: Integer; font: IGPFont; brush: IGPBrush; positions: PGPPointF; flags: Integer; matrix: IGPMatrix) : TGPGraphics; // MeasureDriverString function GetDriverStringBoundingBoxF(text: PUINT16; length: Integer; font: IGPFont; positions: PGPPointF; flags: Integer; matrix: IGPMatrix ) : TGPRectF; // Draw a cached bitmap on this graphics destination offset by // x, y. Note this will fail with WrongState if the CachedBitmap // native format differs from this Graphics. function DrawCachedBitmap(cb: IGPCachedBitmap; x, y: Integer) : TGPGraphics; function DrawImageF(image: IGPImage; const point: TGPPointF) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y: Single) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const rect: TGPRectF) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, width, height: Single) : TGPGraphics; overload; function DrawImage(image: IGPImage; const point: TGPPoint) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y: Integer) : TGPGraphics; overload; function DrawImage(image: IGPImage; const rect: TGPRect) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, width, height: Integer) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const point: TGPPointF; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y: Single; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const rect: TGPRectF; Opacity : Single ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, width, height: Single; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; const point: TGPPoint; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y: Integer; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; const rect: TGPRect; Opacity : Single ) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, width, height: Integer; Opacity : Single ) : TGPGraphics; overload; // Affine Draw Image // destPoints.length = 3: rect => parallelogram // destPoints[0] <=> top-left corner of the source rectangle // destPoints[1] <=> top-right corner // destPoints[2] <=> bottom-left corner // destPoints.length = 4: rect => quad // destPoints[3] <=> bottom-right corner function DrawImageF(image: IGPImage; destPoints: array of TGPPointF ) : TGPGraphics; overload; function DrawImage(image: IGPImage; destPoints: array of TGPPoint ) : TGPGraphics; overload; function DrawImageF(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit) : TGPGraphics; overload; function DrawImageF(image: IGPImage; const destRect: TGPRectF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImageF(image: IGPImage; destPoints: array of TGPPointF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImage(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit) : TGPGraphics; overload; function DrawImage(image: IGPImage; const destRect: TGPRect; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; function DrawImage(image: IGPImage; destPoints: array of TGPPoint; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; overload; // The following methods are for playing an EMF+ to a graphics // via the enumeration interface. Each record of the EMF+ is // sent to the callback (along with the callbackData). Then // the callback can invoke the Metafile::PlayRecord method // to play the particular record. function EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; const destPoint: TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; const destRect: TGPRect; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; destPoints: array of TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL ) : TGPGraphics; overload; function EnumerateMetafile(metafile : IGPMetafile; const destPoint : TGPPoint; const srcRect : TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL ) : TGPGraphics; overload; function EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile : IGPMetafile; const destRect, srcRect: TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafileF( metafile: IGPMetafile; destPoints: array of TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; function EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; const srcRect: TGPRect; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; overload; // SetClip function SetClip(g: IGPGraphics; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClipF(rect: TGPRectF; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; function SetClip(rect: TGPRect; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClip(path: IGPGraphicsPath; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; function SetClip(region: IGPRegion; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; // This is different than the other SetClip methods because it assumes // that the HRGN is already in device units, so it doesn't transform // the coordinates in the HRGN. function SetClip(hRgn: HRGN; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; overload; procedure SetClipProp( region: IGPRegion ); // IntersectClip function IntersectClipF(const rect: TGPRectF) : TGPGraphics; function IntersectClip(const rect: TGPRect) : TGPGraphics; overload; function IntersectClip(region: IGPRegion) : TGPGraphics; overload; // ExcludeClip function ExcludeClipF(const rect: TGPRectF) : TGPGraphics; function ExcludeClip(const rect: TGPRect) : TGPGraphics; overload; function ExcludeClip(region: IGPRegion) : TGPGraphics; overload; function ResetClip() : TGPGraphics; function TranslateClipF(dx, dy: Single) : TGPGraphics; overload; function TranslateClip(dx, dy: Integer) : TGPGraphics; overload; function GetClip() : IGPRegion; function GetClipBoundsF() : TGPRectF; function GetClipBounds() : TGPRect; function IsClipEmpty() : Boolean; function GetVisibleClipBoundsF() : TGPRectF; function GetVisibleClipBounds() : TGPRect; function IsVisibleClipEmpty() : Boolean; function IsVisible(x, y: Integer) : Boolean; overload; function IsVisible(const point: TGPPoint) : Boolean; overload; function IsVisible(x, y, width, height: Integer) : Boolean; overload; function IsVisible(const rect: TGPRect) : Boolean; overload; function IsVisibleF(x, y: Single) : Boolean; overload; function IsVisibleF(const point: TGPPointF) : Boolean; overload; function IsVisibleF(x, y, width, height: Single) : Boolean; overload; function IsVisibleF(const rect: TGPRectF) : Boolean; overload; function Save() : TGPGraphicsState; function Restore( gstate: TGPGraphicsState ) : TGPGraphics; function BeginContainerF(const dstrect,srcrect: TGPRectF; unit_: TGPUnit) : TGPGraphicsContainer; overload; function BeginContainer(const dstrect, srcrect: TGPRect; unit_: TGPUnit) : TGPGraphicsContainer; overload; function BeginContainer() : TGPGraphicsContainer; overload; function EndContainer(state: TGPGraphicsContainer) : TGPGraphics; // Only valid when recording metafiles. function AddMetafileComment( data: array of BYTE ) : TGPGraphics; class function GetHalftonePalette() : HPALETTE; protected function SetTransformT(matrix: IGPMatrix) : IGPTransformable; function ResetTransformT() : IGPTransformable; function MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; function IGPTransformable.SetTransform = SetTransformT; function IGPTransformable.ResetTransform = ResetTransformT; function IGPTransformable.MultiplyTransform = MultiplyTransformT; function IGPTransformable.TranslateTransform = TranslateTransformT; function IGPTransformable.ScaleTransform = ScaleTransformT; function IGPTransformable.RotateTransform = RotateTransformT; end; (**************************************************************************\ * * GDI+ CustomLineCap APIs * \**************************************************************************) IGPAdjustableArrowCap = interface( IGPCustomLineCap ) ['{4E024341-42A2-499E-8EA3-884DA121AF7A}'] function SetHeight(height: Single) : TGPAdjustableArrowCap; procedure SetHeightProp(height: Single); function GetHeight() : Single; function SetWidth(width: Single) : TGPAdjustableArrowCap; procedure SetWidthProp(width: Single); function GetWidth() : Single; function SetMiddleInset(middleInset: Single) : TGPAdjustableArrowCap; procedure SetMiddleInsetProp(middleInset: Single); function GetMiddleInset() : Single; function SetFillState(isFilled: Boolean) : TGPAdjustableArrowCap; function IsFilled() : Boolean; property Width : Single read GetWidth write SetWidthProp; property Height : Single read GetHeight write SetHeightProp; property MiddleInset : Single read GetMiddleInset write SetMiddleInsetProp; end; TGPAdjustableArrowCap = class(TGPCustomLineCap, IGPAdjustableArrowCap) public constructor Create(height, width: Single; isFilled: Boolean = True); public function SetHeight(height: Single) : TGPAdjustableArrowCap; procedure SetHeightProp(height: Single); function GetHeight() : Single; function SetWidth(width: Single) : TGPAdjustableArrowCap; procedure SetWidthProp(width: Single); function GetWidth() : Single; function SetMiddleInset(middleInset: Single) : TGPAdjustableArrowCap; procedure SetMiddleInsetProp(middleInset: Single); function GetMiddleInset() : Single; function SetFillState(isFilled: Boolean) : TGPAdjustableArrowCap; function IsFilled() : Boolean; end; (**************************************************************************\ * * GDI+ Metafile class * \**************************************************************************) IGPMetafile = interface( IGPImage ) ['{E9766E82-C370-40C9-AEDA-4A07CBC9BC92}'] function GetMetafileHeader() : IGPMetafileHeader; // Once this method is called, the Metafile object is in an invalid state // and can no longer be used. It is the responsiblity of the caller to // invoke DeleteEnhMetaFile to delete this hEmf. function GetHENHMETAFILE() : HENHMETAFILE; // Used in conjuction with Graphics::EnumerateMetafile to play an EMF+ // The data must be DWORD aligned if it's an EMF or EMF+. It must be // WORD aligned if it's a WMF. function PlayRecord(recordType: TGPEmfPlusRecordType; flags, dataSize: Cardinal; data: PBYTE) : TGPMetafile; // If you're using a printer HDC for the metafile, but you want the // metafile rasterized at screen resolution, then use this API to set // the rasterization dpi of the metafile to the screen resolution, // e.g. 96 dpi or 120 dpi. function SetDownLevelRasterizationLimit(metafileRasterizationLimitDpi: Cardinal) : TGPMetafile; procedure SetDownLevelRasterizationLimitProp(metafileRasterizationLimitDpi: Cardinal); function GetDownLevelRasterizationLimit() : Cardinal; function EmfToWmfBits(hemf: HENHMETAFILE; cbData16: Cardinal; pData16: PBYTE; iMapMode: Integer = MM_ANISOTROPIC; eFlags: TGPEmfToWmfBitsFlags = EmfToWmfBitsFlagsDefault) : Cardinal; property DownLevelRasterizationLimit : Cardinal read GetDownLevelRasterizationLimit write SetDownLevelRasterizationLimitProp; property Header : IGPMetafileHeader read GetMetafileHeader; end; TGPMetafile = class(TGPImage, IGPMetafile) public // Playback a metafile from a HMETAFILE // If deleteWmf is True, then when the metafile is deleted, // the hWmf will also be deleted. Otherwise, it won't be. constructor Create(hWmf: HMETAFILE; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader; deleteWmf: Boolean = False); overload; // Playback a metafile from a HENHMETAFILE // If deleteEmf is True, then when the metafile is deleted, // the hEmf will also be deleted. Otherwise, it won't be. constructor Create(hEmf: HENHMETAFILE; deleteEmf: Boolean = False); overload; constructor Create(filename: WideString); overload; // Playback a WMF metafile from a file. constructor Create(filename: WideString; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader); overload; constructor Create(stream: IStream); overload; // Record a metafile to memory. constructor Create(referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; // Record a metafile to memory. constructor Create(referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; // Record a metafile to memory. constructor Create(referenceHdc: HDC; frameRect: TGPRect; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create(fileName: WideString;referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create(fileName: WideString; referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create( fileName: WideString; referenceHdc: HDC; frameRect: TGPRect; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create(stream: IStream; referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create(stream: IStream; referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); overload; constructor Create(stream : IStream; referenceHdc : HDC; frameRect : TGPRect; frameUnit : TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_ : TGPEmfType = EmfTypeEmfPlusDual; description : PWCHAR = NIL); overload; constructor Create(); overload; public class function GetMetafileHeader(hWmf: HMETAFILE; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader) : IGPMetafileHeader; overload; class function GetMetafileHeader(hEmf: HENHMETAFILE) : IGPMetafileHeader; overload; class function GetMetafileHeader(filename: WideString) : IGPMetafileHeader; overload; class function GetMetafileHeader(stream: IStream) : IGPMetafileHeader; overload; function GetMetafileHeader() : IGPMetafileHeader; overload; // Once this method is called, the Metafile object is in an invalid state // and can no longer be used. It is the responsiblity of the caller to // invoke DeleteEnhMetaFile to delete this hEmf. function GetHENHMETAFILE() : HENHMETAFILE; // Used in conjuction with Graphics::EnumerateMetafile to play an EMF+ // The data must be DWORD aligned if it's an EMF or EMF+. It must be // WORD aligned if it's a WMF. function PlayRecord(recordType: TGPEmfPlusRecordType; flags, dataSize: Cardinal; data: PBYTE) : TGPMetafile; // If you're using a printer HDC for the metafile, but you want the // metafile rasterized at screen resolution, then use this API to set // the rasterization dpi of the metafile to the screen resolution, // e.g. 96 dpi or 120 dpi. function SetDownLevelRasterizationLimit(metafileRasterizationLimitDpi: Cardinal) : TGPMetafile; procedure SetDownLevelRasterizationLimitProp(metafileRasterizationLimitDpi: Cardinal); function GetDownLevelRasterizationLimit: Cardinal; function EmfToWmfBits(hemf: HENHMETAFILE; cbData16: Cardinal; pData16: PBYTE; iMapMode: Integer = MM_ANISOTROPIC; eFlags: TGPEmfToWmfBitsFlags = EmfToWmfBitsFlagsDefault) : Cardinal; end; function GetStatus(Stat: TGPStatus) : String; procedure StartIGDIPlus(); procedure StopIGDIPlus(); implementation uses Math; type TGPBitmapData = class( TGPBase, IGPBitmapData ) protected FData : TGPBitmapDataRecord; FBitmap : TGPBitmap; public function GetWidth() : UINT; function GetHeight() : UINT; function GetStride() : Integer; function GetPixelFormat() : TGPPixelFormat; function GetScan0() : Pointer; protected constructor Create( ABitmap : TGPBitmap ); destructor Destroy(); override; end; TGPPathData = packed class( TGPBase, IGPPathData ) protected FCount : Integer; FPoints : PGPPointF; FTypes : PBYTE; public function GetCount() : Integer; function GetPoints( Index : Integer ) : TGPPointF; function GetTypes( Index : Integer ) : TGPPathPointType; public constructor Create(); destructor Destroy(); override; end; TGPMetafileHeader = packed class( TGPBase, IGPMetafileHeader ) protected FType : TGPMetafileType; FSize : UINT; // Size of the metafile (in bytes) FVersion : UINT; // EMF+, EMF, or WMF version FEmfPlusFlags : UINT; FDpiX : Single; FDpiY : Single; FX : Integer; // Bounds in device units FY : Integer; FWidth : Integer; FHeight : Integer; FHeader : record case Integer of 0: (FWmfHeader: TMETAHEADER); 1: (FEmfHeader: TGPENHMETAHEADER3); end; FEmfPlusHeaderSize : Integer; // size of the EMF+ header in file FLogicalDpiX : Integer; // Logical Dpi of reference Hdc FLogicalDpiY : Integer; // usually valid only for EMF+ public function GetType() : TGPMetafileType; function GetMetafileSize() : UINT; // If IsEmfPlus, this is the EMF+ version; else it is the WMF or EMF ver function GetVersion() : UINT; // Get the EMF+ flags associated with the metafile function GetEmfPlusFlags() : UINT; function GetDpiX() : Single; function GetDpiY() : Single; function GetBounds() : TGPRect; // Is it any type of WMF (standard or Placeable Metafile)? function IsWmf() : Boolean; // Is this an Placeable Metafile? function IsWmfPlaceable() : Boolean; // Is this an EMF (not an EMF+)? function IsEmf() : Boolean; // Is this an EMF or EMF+ file? function IsEmfOrEmfPlus() : Boolean; // Is this an EMF+ file? function IsEmfPlus() : Boolean; // Is this an EMF+ dual (has dual, down-level records) file? function IsEmfPlusDual() : Boolean; // Is this an EMF+ only (no dual records) file? function IsEmfPlusOnly() : Boolean; // If it's an EMF+ file, was it recorded against a display Hdc? function IsDisplay() : Boolean; // Get the WMF header of the metafile (if it is a WMF) function GetWmfHeader() : PMetaHeader; // Get the EMF header of the metafile (if it is an EMF) function GetEmfHeader() : PENHMETAHEADER3; end; {$I IGDIPlusAPI.inc} const AlphaShift = 24; RedShift = 16; GreenShift = 8; BlueShift = 0; AlphaMask = $ff000000; RedMask = $00ff0000; GreenMask = $0000ff00; BlueMask = $000000ff; const StandardAlphaMatrix : TGPColorMatrix = ( ( 1.0, 0.0, 0.0, 0.0, 0.0 ), ( 0.0, 1.0, 0.0, 0.0, 0.0 ), ( 0.0, 0.0, 1.0, 0.0, 0.0 ), ( 0.0, 0.0, 0.0, 1.0, 0.0 ), ( 0.0, 0.0, 0.0, 0.0, 1.0 ) ); var GenericSansSerifFontFamily : TGPFontFamily = NIL; GenericSerifFontFamily : TGPFontFamily = NIL; GenericMonospaceFontFamily : TGPFontFamily = NIL; GenericTypographicStringFormatBuffer: TGPStringFormat = NIL; GenericDefaultStringFormatBuffer : TGPStringFormat = NIL; StartupInput: TGPGDIPlusStartupInput; StartupOutput: TGPGdiplusStartupOutput; gdiplusBGThreadToken : Pointer; gdiplusToken: Pointer; GInitialized : Boolean = False; (**************************************************************************\ * * Image Attributes * * Abstract: * * GDI+ Image Attributes used with Graphics.DrawImage * * There are 5 possible sets of color adjustments: * ColorAdjustDefault, * ColorAdjustBitmap, * ColorAdjustBrush, * ColorAdjustPen, * ColorAdjustText, * * Bitmaps, Brushes, Pens, and Text will all use any color adjustments * that have been set into the default ImageAttributes until their own * color adjustments have been set. So as soon as any "Set" method is * called for Bitmaps, Brushes, Pens, or Text, then they start from * scratch with only the color adjustments that have been set for them. * Calling Reset removes any individual color adjustments for a type * and makes it revert back to using all the default color adjustments * (if any). The SetToIdentity method is a way to force a type to * have no color adjustments at all, regardless of what previous adjustments * have been set for the defaults or for that type. * \********************************************************************F******) constructor TGPImageAttributes.Create(); begin FNativeImageAttr := NIL; ErrorCheck( GdipCreateImageAttributes(FNativeImageAttr)); end; destructor TGPImageAttributes.Destroy(); begin GdipDisposeImageAttributes(FNativeImageAttr); inherited Destroy(); end; function TGPImageAttributes.Clone() : TGPImageAttributes; var clone: GpImageAttributes; begin ErrorCheck( GdipCloneImageAttributes(FNativeImageAttr, clone)); Result := TGPImageAttributes.CreateGdiPlus(clone, False); end; function TGPImageAttributes.SetToIdentity(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesToIdentity(FNativeImageAttr, type_)); Result := Self; end; function TGPImageAttributes.Reset(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipResetImageAttributes(FNativeImageAttr, type_)); Result := Self; end; function TGPImageAttributes.SetColorMatrix(const colorMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorMatrix(FNativeImageAttr, type_, True, @colorMatrix, NIL, mode)); Result := Self; end; function TGPImageAttributes.ClearColorMatrix(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorMatrix(FNativeImageAttr, type_, False, NIL, NIL, ColorMatrixFlagsDefault)); Result := Self; end; function TGPImageAttributes.SetColorMatrices(const colorMatrix: TGPColorMatrix; const grayMatrix: TGPColorMatrix; mode: TGPColorMatrixFlags = ColorMatrixFlagsDefault; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorMatrix(FNativeImageAttr, type_, True, @colorMatrix, @grayMatrix, mode)); Result := Self; end; function TGPImageAttributes.ClearColorMatrices(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorMatrix( FNativeImageAttr, type_, False, NIL, NIL, ColorMatrixFlagsDefault)); Result := Self; end; function TGPImageAttributes.SetThreshold(threshold: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesThreshold( FNativeImageAttr, type_, True, threshold)); Result := Self; end; function TGPImageAttributes.ClearThreshold(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesThreshold(FNativeImageAttr, type_, False, 0.0)); Result := Self; end; function TGPImageAttributes.SetGamma(gamma: Single; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesGamma(FNativeImageAttr, type_, True, gamma)); Result := Self; end; function TGPImageAttributes.ClearGamma( type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesGamma(FNativeImageAttr, type_, False, 0.0)); Result := Self; end; function TGPImageAttributes.SetNoOp(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesNoOp(FNativeImageAttr, type_, True)); Result := Self; end; function TGPImageAttributes.ClearNoOp(Type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesNoOp( FNativeImageAttr, type_, False)); Result := Self; end; function TGPImageAttributes.SetColorKey(colorLow, colorHigh: TGPColor; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorKeys(FNativeImageAttr, type_, True, colorLow, colorHigh)); Result := Self; end; function TGPImageAttributes.ClearColorKey(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesColorKeys(FNativeImageAttr, type_, False, 0, 0)); Result := Self; end; function TGPImageAttributes.SetOutputChannel(channelFlags: TGPColorChannelFlags; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesOutputChannel(FNativeImageAttr, type_, True, channelFlags)); Result := Self; end; function TGPImageAttributes.ClearOutputChannel(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesOutputChannel(FNativeImageAttr, type_, False, ColorChannelFlagsLast)); Result := Self; end; function TGPImageAttributes.SetOutputChannelColorProfile(colorProfileFilename: WideString; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesOutputChannelColorProfile(FNativeImageAttr, type_, True, PWideChar(colorProfileFilename))); Result := Self; end; function TGPImageAttributes.ClearOutputChannelColorProfile(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesOutputChannelColorProfile(FNativeImageAttr, type_, False, NIL)); Result := Self; end; function TGPImageAttributes.SetRemapTable(mapSize: Cardinal; map: PGPColorMap; type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesRemapTable(FNativeImageAttr, type_, True, mapSize, map)); Result := Self; end; function TGPImageAttributes.ClearRemapTable(type_: TGPColorAdjustType = ColorAdjustTypeDefault) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesRemapTable(FNativeImageAttr, type_, False, 0, NIL)); Result := Self; end; function TGPImageAttributes.SetBrushRemapTable(mapSize: Cardinal; map: PGPColorMap) : TGPImageAttributes; begin Result := SetRemapTable(mapSize, map, ColorAdjustTypeBrush); end; function TGPImageAttributes.ClearBrushRemapTable() : TGPImageAttributes; begin Result := ClearRemapTable(ColorAdjustTypeBrush); end; function TGPImageAttributes.SetWrapMode(wrap: TGPWrapMode; color: TGPColor = aclBlack; clamp: Boolean = False) : TGPImageAttributes; begin ErrorCheck( GdipSetImageAttributesWrapMode(FNativeImageAttr, wrap, color, clamp)); Result := Self; end; // The flags of the palette are ignored. function TGPImageAttributes.GetAdjustedPalette(colorPalette: PGPColorPalette; colorAdjustType: TGPColorAdjustType) : TGPImageAttributes; begin ErrorCheck( GdipGetImageAttributesAdjustedPalette(FNativeImageAttr, colorPalette, colorAdjustType)); Result := Self; end; constructor TGPImageAttributes.CreateGdiPlus(imageAttr: GpImageAttributes; Dummy : Boolean); begin SetNativeImageAttr(imageAttr); end; procedure TGPImageAttributes.SetNativeImageAttr(nativeImageAttr: GpImageAttributes); begin FNativeImageAttr := nativeImageAttr; end; function TGPImageAttributes.GetNativeImageAttr() : GpImageAttributes; begin Result := FNativeImageAttr; end; (**************************************************************************\ * * GDI+ Matrix class * \**************************************************************************) // Default constructor is set to identity matrix. constructor TGPMatrix.Create(); var matrix: GpMatrix; begin matrix := NIL; ErrorCheck( GdipCreateMatrix(matrix)); SetNativeMatrix(matrix); end; constructor TGPMatrix.Create(m11, m12, m21, m22, dx, dy: Single); var matrix: GpMatrix; begin matrix := NIL; ErrorCheck( GdipCreateMatrix2(m11, m12, m21, m22, dx, dy, matrix)); SetNativeMatrix(matrix); end; constructor TGPMatrix.Create(const rect: TGPRectF; const dstplg: TGPPointF); var matrix: GpMatrix; begin matrix := NIL; ErrorCheck( GdipCreateMatrix3(@rect, @dstplg, matrix)); SetNativeMatrix(matrix); end; constructor TGPMatrix.Create(const rect: TGPRect; const dstplg: TGPPoint); var matrix: GpMatrix; begin matrix := NIL; ErrorCheck( GdipCreateMatrix3I(@rect, @dstplg, matrix)); SetNativeMatrix(matrix); end; destructor TGPMatrix.Destroy(); begin GdipDeleteMatrix(FNativeMatrix); end; function TGPMatrix.Clone() : TGPMatrix; var cloneMatrix: GpMatrix; begin cloneMatrix := NIL; ErrorCheck( GdipCloneMatrix(FNativeMatrix, cloneMatrix)); Result := TGPMatrix.CreateGdiPlus(cloneMatrix, False); end; function TGPMatrix.GetElements() : TGPMatrixParams; begin ErrorCheck( GdipGetMatrixElements(FNativeMatrix, @Result )); end; function TGPMatrix.SetElements(m11, m12, m21, m22, dx, dy: Single) : TGPMatrix; begin ErrorCheck( GdipSetMatrixElements(FNativeMatrix, m11, m12, m21, m22, dx, dy)); Result := Self; end; function TGPMatrix.SetElements( AElements : TGPMatrixParams ) : TGPMatrix; begin ErrorCheck( GdipSetMatrixElements( FNativeMatrix, AElements.m11, AElements.m12, AElements.m21, AElements.m22, AElements.dx, AElements.dy )); Result := Self; end; procedure TGPMatrix.SetElementsProp( AElements : TGPMatrixParams ); begin ErrorCheck( GdipSetMatrixElements( FNativeMatrix, AElements.m11, AElements.m12, AElements.m21, AElements.m22, AElements.dx, AElements.dy )); end; function TGPMatrix.OffsetX() : Single; begin Result := GetElements().dx;// [4]; end; function TGPMatrix.OffsetY: Single; begin Result := GetElements().dy; // [5]; end; function TGPMatrix.Reset() : TGPMatrix; begin // set identity matrix elements ErrorCheck( GdipSetMatrixElements(FNativeMatrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0)); Result := Self; end; function TGPMatrix.Multiply(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin ErrorCheck( GdipMultiplyMatrix(FNativeMatrix, matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPMatrix.Translate(offsetX, offsetY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin ErrorCheck( GdipTranslateMatrix(FNativeMatrix, offsetX, offsetY, order)); Result := Self; end; function TGPMatrix.Scale(scaleX, scaleY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin ErrorCheck( GdipScaleMatrix(FNativeMatrix, scaleX, scaleY, order)); Result := Self; end; function TGPMatrix.Rotate(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin ErrorCheck( GdipRotateMatrix(FNativeMatrix, angle, order)); Result := Self; end; function TGPMatrix.RotateAt(angle: Single; const center: TGPPointF; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin if(order = MatrixOrderPrepend) then begin ErrorCheck( GdipTranslateMatrix(FNativeMatrix, center.X, center.Y, order)); ErrorCheck( GdipRotateMatrix(FNativeMatrix, angle, order)); ErrorCheck( GdipTranslateMatrix(FNativeMatrix, -center.X, -center.Y, order)); end else begin ErrorCheck( GdipTranslateMatrix(FNativeMatrix, - center.X, - center.Y, order)); ErrorCheck( GdipRotateMatrix(FNativeMatrix, angle, order)); ErrorCheck( GdipTranslateMatrix(FNativeMatrix, center.X, center.Y, order)); end; Result := Self; end; function TGPMatrix.Shear(shearX, shearY: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPMatrix; begin ErrorCheck( GdipShearMatrix(FNativeMatrix, shearX, shearY, order)); Result := Self; end; function TGPMatrix.Invert() : TGPMatrix; begin ErrorCheck( GdipInvertMatrix(FNativeMatrix)); Result := Self; end; function TGPMatrix.TransformPointF( var point : TGPPointF ) : TGPMatrix; var pts : array [ 0..0 ] of TGPPointF; begin pts[ 0 ] := point; Result := TransformPointsF( pts ); point := pts[ 0 ]; end; function TGPMatrix.TransformPoint( var point : TGPPoint ) : TGPMatrix; var pts : array [ 0..0 ] of TGPPoint; begin pts[ 0 ] := point; Result := TransformPoints( pts ); point := pts[ 0 ]; end; // float version function TGPMatrix.TransformPointsF( var pts : array of TGPPointF ) : TGPMatrix; begin ErrorCheck( GdipTransformMatrixPoints( FNativeMatrix, @pts[ 0 ], Length( pts ))); Result := Self; end; function TGPMatrix.TransformPoints( var pts : array of TGPPoint ) : TGPMatrix; begin ErrorCheck( GdipTransformMatrixPointsI(FNativeMatrix, @pts[ 0 ], Length( pts ))); Result := Self; end; function TGPMatrix.TransformVectorsF( var pts : array of TGPPointF ) : TGPMatrix; begin ErrorCheck( GdipVectorTransformMatrixPoints( FNativeMatrix, @pts[ 0 ], Length( pts ))); Result := Self; end; function TGPMatrix.TransformVectors( var pts : array of TGPPoint ) : TGPMatrix; begin ErrorCheck( GdipVectorTransformMatrixPointsI(FNativeMatrix, @pts[ 0 ], Length( pts ))); Result := Self; end; function TGPMatrix.IsInvertible() : Boolean; var AValue : BOOL; begin ErrorCheck( GdipIsMatrixInvertible(FNativeMatrix, AValue )); Result := AValue; end; function TGPMatrix.IsIdentity() : Boolean; var AValue : BOOL; begin ErrorCheck( GdipIsMatrixIdentity(FNativeMatrix, AValue)); Result := AValue; end; function TGPMatrix.EqualsMatrix(matrix: IGPMatrix) : Boolean; var AValue : BOOL; begin ErrorCheck( GdipIsMatrixEqual(FNativeMatrix, matrix.GetNativeMatrix(), AValue )); Result := AValue; end; constructor TGPMatrix.CreateGdiPlus(nativeMatrix: GpMatrix; Dummy : Boolean); begin SetNativeMatrix(nativeMatrix); end; procedure TGPMatrix.SetNativeMatrix(nativeMatrix: GpMatrix); begin FNativeMatrix := nativeMatrix; end; function TGPMatrix.GetNativeMatrix() : GpMatrix; begin Result := FNativeMatrix; end; (**************************************************************************\ \**************************************************************************) constructor TGPMatrixStore.Create( ATransformable : IGPTransformable ); begin inherited Create(); FTransformable := ATransformable; FMatrix := FTransformable.Transform; end; destructor TGPMatrixStore.Destroy(); begin FTransformable.Transform := FMatrix; inherited; end; (**************************************************************************\ * * GDI+ StringFormat class * \**************************************************************************) constructor TGPStringFormat.Create(formatFlags: Integer = 0; language: LANGID = LANG_NEUTRAL); begin FNativeFormat := NIL; ErrorCheck( GdipCreateStringFormat(formatFlags, language, FNativeFormat)); end; class function TGPStringFormat.GenericDefault: TGPStringFormat; begin if( not Assigned(GenericDefaultStringFormatBuffer)) then begin GenericDefaultStringFormatBuffer := TGPStringFormat.Create(); ErrorCheck( GdipStringFormatGetGenericDefault(GenericDefaultStringFormatBuffer.FNativeFormat)); end; Result := GenericDefaultStringFormatBuffer; end; class function TGPStringFormat.GenericTypographic: TGPStringFormat; begin if( not Assigned(GenericTypographicStringFormatBuffer)) then begin GenericTypographicStringFormatBuffer := TGPStringFormat.Create(); ErrorCheck( GdipStringFormatGetGenericTypographic(GenericTypographicStringFormatBuffer.FNativeFormat)); end; Result := GenericTypographicStringFormatBuffer; end; constructor TGPStringFormat.Create(format: TGPStringFormat); var gpstf: GPSTRINGFORMAT; begin FNativeFormat := NIL; if( Assigned(format)) then gpstf := format.FNativeFormat else gpstf := NIL; ErrorCheck( GdipCloneStringFormat(gpstf, FNativeFormat)); end; function TGPStringFormat.Clone() : TGPStringFormat; var clonedStringFormat: GpStringFormat; begin clonedStringFormat := NIL; ErrorCheck( GdipCloneStringFormat(FNativeFormat, clonedStringFormat)); Result := TGPStringFormat.CreateGdiPlus(clonedStringFormat, False); end; destructor TGPStringFormat.Destroy(); begin GdipDeleteStringFormat(FNativeFormat); end; function TGPStringFormat.SetFormatFlags(flags: Integer) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatFlags(FNativeFormat, flags)); Result := Self; end; procedure TGPStringFormat.SetFormatFlagsProp(flags: Integer); begin ErrorCheck( GdipSetStringFormatFlags(FNativeFormat, flags)); end; function TGPStringFormat.GetFormatFlags() : Integer; begin ErrorCheck( GdipGetStringFormatFlags(FNativeFormat, Result)); end; function TGPStringFormat.SetAlignment(align: TGPStringAlignment) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatAlign(FNativeFormat, align)); Result := Self; end; procedure TGPStringFormat.SetAlignmentProp(align: TGPStringAlignment); begin ErrorCheck( GdipSetStringFormatAlign(FNativeFormat, align)); end; function TGPStringFormat.GetAlignment: TGPStringAlignment; begin ErrorCheck( GdipGetStringFormatAlign(FNativeFormat, Result)); end; function TGPStringFormat.SetLineAlignment(align: TGPStringAlignment) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatLineAlign(FNativeFormat, align)); Result := Self; end; procedure TGPStringFormat.SetLineAlignmentProp(align: TGPStringAlignment); begin ErrorCheck( GdipSetStringFormatLineAlign(FNativeFormat, align)); end; function TGPStringFormat.GetLineAlignment: TGPStringAlignment; begin ErrorCheck( GdipGetStringFormatLineAlign(FNativeFormat, Result)); end; function TGPStringFormat.SetHotkeyPrefix(hotkeyPrefix: TGPHotkeyPrefix) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatHotkeyPrefix(FNativeFormat, Integer(hotkeyPrefix))); Result := Self; end; procedure TGPStringFormat.SetHotkeyPrefixProp(hotkeyPrefix: TGPHotkeyPrefix); begin ErrorCheck( GdipSetStringFormatHotkeyPrefix(FNativeFormat, Integer(hotkeyPrefix))); end; function TGPStringFormat.GetHotkeyPrefix: TGPHotkeyPrefix; var HotkeyPrefix: Integer; begin ErrorCheck( GdipGetStringFormatHotkeyPrefix(FNativeFormat, HotkeyPrefix)); Result := TGPHotkeyPrefix(HotkeyPrefix); end; function TGPStringFormat.SetTabStops( firstTabOffset: Single; tabStops : array of Single ) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatTabStops(FNativeFormat, firstTabOffset, Length( tabStops ), @tabStops[ 0 ])); Result := Self; end; function TGPStringFormat.GetTabStopCount() : Integer; begin ErrorCheck( GdipGetStringFormatTabStopCount(FNativeFormat, Result)); end; function TGPStringFormat.GetTabStops( out initialTabOffset : Single ) : TGPSingleArray; var count: Integer; begin ErrorCheck( GdipGetStringFormatTabStopCount( FNativeFormat, count )); SetLength( Result, count ); ErrorCheck( GdipGetStringFormatTabStops(FNativeFormat, count, @initialTabOffset, @Result[ 0 ] )); end; function TGPStringFormat.GetTabStops() : TGPSingleArray; var initialTabOffset : Single; begin Result := GetTabStops( initialTabOffset ); end; function TGPStringFormat.GetTabStopsProp() : TGPSingleArray; var initialTabOffset : Single; begin Result := GetTabStops( initialTabOffset ); end; function TGPStringFormat.GetInitialTabOffset() : Single; begin GetTabStops( Result ); end; function TGPStringFormat.SetDigitSubstitution(language: LANGID; substitute: TGPStringDigitSubstitute) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatDigitSubstitution(FNativeFormat, language, substitute)); Result := Self; end; function TGPStringFormat.GetDigitSubstitutionLanguage() : LANGID; begin ErrorCheck( GdipGetStringFormatDigitSubstitution(FNativeFormat, @Result, NIL)); end; function TGPStringFormat.GetDigitSubstitutionMethod() : TGPStringDigitSubstitute; begin ErrorCheck( GdipGetStringFormatDigitSubstitution(FNativeFormat, NIL, @Result)); end; function TGPStringFormat.SetTrimming(trimming: TGPStringTrimming) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatTrimming(FNativeFormat, trimming)); Result := Self; end; procedure TGPStringFormat.SetTrimmingProp(trimming: TGPStringTrimming); begin ErrorCheck( GdipSetStringFormatTrimming(FNativeFormat, trimming)); end; function TGPStringFormat.GetTrimming: TGPStringTrimming; begin ErrorCheck( GdipGetStringFormatTrimming(FNativeFormat, Result)); end; function TGPStringFormat.SetMeasurableCharacterRanges( ranges : array of TGPCharacterRange ) : TGPStringFormat; begin ErrorCheck( GdipSetStringFormatMeasurableCharacterRanges(FNativeFormat, Length( ranges ), @ranges[ 0 ] )); Result := Self; end; function TGPStringFormat.GetMeasurableCharacterRangeCount: Integer; begin ErrorCheck( GdipGetStringFormatMeasurableCharacterRangeCount(FNativeFormat, Result)); end; procedure TGPStringFormat.Assign(source: TGPStringFormat); begin assert(Assigned(source)); GdipDeleteStringFormat(FNativeFormat); ErrorCheck( GdipCloneStringFormat(source.FNativeFormat, FNativeFormat)); end; constructor TGPStringFormat.CreateGdiPlus(clonedStringFormat: GpStringFormat; Dummy : Boolean); begin FNativeFormat := clonedStringFormat; end; function TGPStringFormat.GetNativeFormat() : GpStringFormat; begin Result := FNativeFormat; end; // --------------------------------------------------------------------------- // TAdjustableArrowCap // --------------------------------------------------------------------------- constructor TGPAdjustableArrowCap.Create(height, width: Single; isFilled: Boolean = True); var cap: GpAdjustableArrowCap; begin cap := NIL; ErrorCheck( GdipCreateAdjustableArrowCap(height, width, isFilled, cap)); SetNativeCap(cap); end; function TGPAdjustableArrowCap.SetHeight(height: Single) : TGPAdjustableArrowCap; begin ErrorCheck( GdipSetAdjustableArrowCapHeight(GpAdjustableArrowCap(FNativeCap), height)); Result := Self; end; procedure TGPAdjustableArrowCap.SetHeightProp(height: Single); begin ErrorCheck( GdipSetAdjustableArrowCapHeight(GpAdjustableArrowCap(FNativeCap), height)); end; function TGPAdjustableArrowCap.GetHeight: Single; begin ErrorCheck( GdipGetAdjustableArrowCapHeight(GpAdjustableArrowCap(FNativeCap), Result)); end; procedure TGPAdjustableArrowCap.SetWidthProp(width: Single); begin ErrorCheck( GdipSetAdjustableArrowCapWidth(GpAdjustableArrowCap(FNativeCap), width)); end; function TGPAdjustableArrowCap.SetWidth(width: Single) : TGPAdjustableArrowCap; begin ErrorCheck( GdipSetAdjustableArrowCapWidth(GpAdjustableArrowCap(FNativeCap), width)); Result := Self; end; function TGPAdjustableArrowCap.GetWidth: Single; begin ErrorCheck( GdipGetAdjustableArrowCapWidth(GpAdjustableArrowCap(FNativeCap), Result)); end; procedure TGPAdjustableArrowCap.SetMiddleInsetProp(middleInset: Single); begin ErrorCheck( GdipSetAdjustableArrowCapMiddleInset(GpAdjustableArrowCap(FNativeCap), middleInset)); end; function TGPAdjustableArrowCap.SetMiddleInset(middleInset: Single) : TGPAdjustableArrowCap; begin ErrorCheck( GdipSetAdjustableArrowCapMiddleInset(GpAdjustableArrowCap(FNativeCap), middleInset)); Result := Self; end; function TGPAdjustableArrowCap.GetMiddleInset: Single; begin ErrorCheck( GdipGetAdjustableArrowCapMiddleInset( GpAdjustableArrowCap(FNativeCap), Result)); end; function TGPAdjustableArrowCap.SetFillState(isFilled: Boolean) : TGPAdjustableArrowCap; begin ErrorCheck( GdipSetAdjustableArrowCapFillState( GpAdjustableArrowCap(FNativeCap), isFilled)); Result := Self; end; function TGPAdjustableArrowCap.IsFilled() : Boolean; var AValue : BOOL; begin ErrorCheck( GdipGetAdjustableArrowCapFillState( GpAdjustableArrowCap(FNativeCap), AValue )); Result := AValue; end; (**************************************************************************\ * * GDI+ Metafile class * \**************************************************************************) // Playback a metafile from a HMETAFILE // If deleteWmf is True, then when the metafile is deleted, // the hWmf will also be deleted. Otherwise, it won't be. constructor TGPMetafile.Create(hWmf: HMETAFILE; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader; deleteWmf: Boolean = False); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipCreateMetafileFromWmf(hWmf, deleteWmf, @wmfPlaceableFileHeader, metafile)); SetNativeImage(metafile); end; // Playback a metafile from a HENHMETAFILE // If deleteEmf is True, then when the metafile is deleted, // the hEmf will also be deleted. Otherwise, it won't be. constructor TGPMetafile.Create(hEmf: HENHMETAFILE; deleteEmf: Boolean = False); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipCreateMetafileFromEmf(hEmf, deleteEmf, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(filename: WideString); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipCreateMetafileFromFile(PWideChar(filename), metafile)); SetNativeImage(metafile); end; // Playback a WMF metafile from a file. constructor TGPMetafile.Create(filename: Widestring; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipCreateMetafileFromWmfFile(PWideChar(filename), @wmfPlaceableFileHeader, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(stream: IStream); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipCreateMetafileFromStream(stream, metafile)); SetNativeImage(metafile); end; // Record a metafile to memory. constructor TGPMetafile.Create(referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafile(referenceHdc, type_, NIL, MetafileFrameUnitGdi, description, metafile)); SetNativeImage(metafile); end; // Record a metafile to memory. constructor TGPMetafile.Create(referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafile(referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; // Record a metafile to memory. constructor TGPMetafile.Create(referenceHdc: HDC; frameRect: TGPRect; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileI(referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(fileName: WideString; referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileFileName(PWideChar(fileName), referenceHdc, type_, NIL, MetafileFrameUnitGdi, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(fileName: WideString; referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileFileName(PWideChar(fileName), referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(fileName: WideString; referenceHdc: HDC; frameRect: TGPRect; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileFileNameI(PWideChar(fileName), referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(stream: IStream; referenceHdc: HDC; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileStream(stream, referenceHdc, type_, NIL, MetafileFrameUnitGdi, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(stream: IStream; referenceHdc: HDC; frameRect: TGPRectF; frameUnit: TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_: TGPEmfType = EmfTypeEmfPlusDual; description: PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileStream(stream, referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; constructor TGPMetafile.Create(stream : IStream; referenceHdc : HDC; frameRect : TGPRect; frameUnit : TGPMetafileFrameUnit = MetafileFrameUnitGdi; type_ : TGPEmfType = EmfTypeEmfPlusDual; description : PWCHAR = NIL); var metafile: GpMetafile; begin metafile := NIL; ErrorCheck( GdipRecordMetafileStreamI(stream, referenceHdc, type_, @frameRect, frameUnit, description, metafile)); SetNativeImage(metafile); end; class function TGPMetafile.GetMetafileHeader(hWmf: HMETAFILE; var wmfPlaceableFileHeader: TGPWmfPlaceableFileHeader) : IGPMetafileHeader; var header : TGPMetafileHeader; begin header := TGPMetafileHeader.Create(); ErrorCheck( GdipGetMetafileHeaderFromWmf(hWmf, @wmfPlaceableFileHeader, @header.FType )); Result := header; end; class function TGPMetafile.GetMetafileHeader(hEmf: HENHMETAFILE) : IGPMetafileHeader; var header : TGPMetafileHeader; begin header := TGPMetafileHeader.Create(); ErrorCheck( GdipGetMetafileHeaderFromEmf(hEmf, @header.FType )); Result := header; end; class function TGPMetafile.GetMetafileHeader(filename: WideString) : IGPMetafileHeader; var header : TGPMetafileHeader; begin header := TGPMetafileHeader.Create(); ErrorCheck( GdipGetMetafileHeaderFromFile(PWideChar(filename), @header.FType )); Result := header; end; class function TGPMetafile.GetMetafileHeader(stream: IStream) : IGPMetafileHeader; var header : TGPMetafileHeader; begin header := TGPMetafileHeader.Create(); ErrorCheck( GdipGetMetafileHeaderFromStream(stream, @header.FType )); Result := header; end; function TGPMetafile.GetMetafileHeader() : IGPMetafileHeader; var header : TGPMetafileHeader; begin header := TGPMetafileHeader.Create(); ErrorCheck( GdipGetMetafileHeaderFromMetafile(GpMetafile(FNativeImage), @header.FType )); Result := header; end; // Once this method is called, the Metafile object is in an invalid state // and can no longer be used. It is the responsiblity of the caller to // invoke DeleteEnhMetaFile to delete this hEmf. function TGPMetafile.GetHENHMETAFILE() : HENHMETAFILE; var AMeta : GPMETAFILE; begin AMeta := GpMetafile(FNativeImage); ErrorCheck( GdipGetHemfFromMetafile( AMeta, Result )); end; // Used in conjuction with Graphics::EnumerateMetafile to play an EMF+ // The data must be DWORD aligned if it's an EMF or EMF+. It must be // WORD aligned if it's a WMF. function TGPMetafile.PlayRecord(recordType: TGPEmfPlusRecordType; flags, dataSize: Cardinal; data: PBYTE) : TGPMetafile; begin ErrorCheck( GdipPlayMetafileRecord(GpMetafile(FNativeImage), recordType, flags, dataSize, data)); Result := Self; end; // If you're using a printer HDC for the metafile, but you want the // metafile rasterized at screen resolution, then use this API to set // the rasterization dpi of the metafile to the screen resolution, // e.g. 96 dpi or 120 dpi. function TGPMetafile.SetDownLevelRasterizationLimit(metafileRasterizationLimitDpi: Cardinal) : TGPMetafile; begin ErrorCheck( GdipSetMetafileDownLevelRasterizationLimit( GpMetafile(FNativeImage), metafileRasterizationLimitDpi)); Result := Self; end; procedure TGPMetafile.SetDownLevelRasterizationLimitProp(metafileRasterizationLimitDpi: Cardinal); begin ErrorCheck( GdipSetMetafileDownLevelRasterizationLimit( GpMetafile(FNativeImage), metafileRasterizationLimitDpi)); end; function TGPMetafile.GetDownLevelRasterizationLimit: Cardinal; var metafileRasterizationLimitDpi: Cardinal; begin metafileRasterizationLimitDpi := 0; ErrorCheck( GdipGetMetafileDownLevelRasterizationLimit( GpMetafile(FNativeImage), metafileRasterizationLimitDpi)); Result := metafileRasterizationLimitDpi; end; function TGPMetafile.EmfToWmfBits(hemf: HENHMETAFILE; cbData16: Cardinal; pData16: PBYTE; iMapMode: Integer = MM_ANISOTROPIC; eFlags: TGPEmfToWmfBitsFlags = EmfToWmfBitsFlagsDefault) : Cardinal; begin Result := GdipEmfToWmfBits(hemf, cbData16, pData16, iMapMode, Integer(eFlags)); end; constructor TGPMetafile.Create(); begin SetNativeImage(NIL); end; (**************************************************************************\ * * GDI+ Codec Image APIs * \**************************************************************************) //-------------------------------------------------------------------------- // Codec Management APIs //-------------------------------------------------------------------------- function GetImageDecodersSize(out numDecoders, size: Cardinal) : TGPStatus; begin Result := GdipGetImageDecodersSize(numDecoders, size); end; function GetImageDecoders() : TGPImageCodecInfoArray; var numDecoders, size: Cardinal; AStatus : TGPStatus; begin AStatus := GdipGetImageDecodersSize(numDecoders, size); if( AStatus <> Ok ) then raise EGPLoadError.Create( GetStatus( AStatus )); SetLength( Result, numDecoders ); AStatus := GdipGetImageDecoders( numDecoders, size, @Result[ 0 ] ); if( AStatus <> Ok ) then raise EGPLoadError.Create( GetStatus( AStatus )); end; function GetImageEncodersSize(out numEncoders, size: Cardinal) : TGPStatus; begin Result := GdipGetImageEncodersSize(numEncoders, size); end; function GetImageEncoders() : TGPImageCodecInfoArray; var numEncoders, size : Cardinal; AStatus : TGPStatus; begin AStatus := GdipGetImageEncodersSize(numEncoders, size); if( AStatus <> Ok ) then raise EGPLoadError.Create( GetStatus( AStatus )); SetLength( Result, numEncoders ); AStatus := GdipGetImageEncoders( numEncoders, size, @Result[ 0 ] ); if( AStatus <> Ok ) then raise EGPLoadError.Create( GetStatus( AStatus )); end; function GetEncoderClsid( format : String; var pClsid : TCLSID ) : Boolean; var num : UINT; // number of image encoders size : UINT; // size of the image encoder array in bytes aImageCodecInfo : PGPImageCodecInfo; j : UINT; begin num := 0; size := 0; Result := False; // aImageCodecInfo := NIL; GetImageEncodersSize( num, size ); if(size = 0) then Exit; // Failure GetMem( aImageCodecInfo, size ); if( aImageCodecInfo = NIL ) then Exit; // Failure // GdipGetImageEncoders(numEncoders, size, @Result[ 0 ] ) GdipGetImageEncoders(num, size, aImageCodecInfo); format := LowerCase( format ); for j := 0 to num - 1 do begin if( LowerCase( PGPImageCodecInfo( PAnsiChar( aImageCodecInfo ) + j * SizeOf( TGPImageCodecInfo )).MimeType ) = format ) then begin pClsid := PGPImageCodecInfo( PAnsiChar( aImageCodecInfo ) + j * SizeOf( TGPImageCodecInfo )).Clsid; FreeMem( aImageCodecInfo, size ); Result := True; Exit; end; end; FreeMem( aImageCodecInfo, size ); end; (**************************************************************************\ * * GDI+ Region class implementation * \**************************************************************************) constructor TGPRegion.Create(); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegion(region) ); SetNativeRegion(region); end; constructor TGPRegion.Create(rect: TGPRectF); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegionRect(@rect, region)); SetNativeRegion(region); end; constructor TGPRegion.Create(rect: TGPRect); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegionRectI(@rect, region)); SetNativeRegion(region); end; constructor TGPRegion.Create(path: IGPGraphicsPath); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegionPath(path.GetNativePath(), region)); SetNativeRegion(region); end; constructor TGPRegion.Create( regionData: array of BYTE ); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegionRgnData( @regionData[ 0 ], Length( regionData ), region)); SetNativeRegion(region); end; constructor TGPRegion.Create(hRgn: HRGN); var region: GpRegion; begin region := NIL; ErrorCheck( GdipCreateRegionHrgn(hRgn, region)); SetNativeRegion(region); end; class function TGPRegion.FromHRGN(hRgn: HRGN) : TGPRegion; var region: GpRegion; begin region := NIL; if (GdipCreateRegionHrgn(hRgn, region) = Ok) then begin Result := TGPRegion.CreateGdiPlus(region, False); if (Result = NIL) then GdipDeleteRegion(region); exit; end else Result := NIL; end; destructor TGPRegion.Destroy(); begin GdipDeleteRegion(FNativeRegion); end; function TGPRegion.Clone: TGPRegion; var region: GpRegion; begin region := NIL; ErrorCheck( GdipCloneRegion(FNativeRegion, region)); Result := TGPRegion.CreateGdiPlus(region, False); end; function TGPRegion.MakeInfinite() : TGPRegion; begin ErrorCheck( GdipSetInfinite(FNativeRegion)); Result := Self; end; function TGPRegion.MakeEmpty() : TGPRegion; begin ErrorCheck( GdipSetEmpty(FNativeRegion)); Result := Self; end; // Get the size of the buffer needed for the GetData method function TGPRegion.GetDataSize() : Cardinal; begin ErrorCheck( GdipGetRegionDataSize(FNativeRegion, Result )); end; // buffer - where to put the data // bufferSize - how big the buffer is (should be at least as big as GetDataSize()) // sizeFilled - if not NIL, this is an OUT param that says how many bytes // of data were written to the buffer. function TGPRegion.GetData() : TGPByteArray; var bufferSize : Cardinal; begin ErrorCheck( GdipGetRegionDataSize( FNativeRegion, bufferSize )); SetLength( Result, bufferSize ); ErrorCheck( GdipGetRegionData( FNativeRegion, @Result[ 0 ], bufferSize, NIL )); end; function TGPRegion.Intersect(const rect: TGPRect) : TGPRegion; begin ErrorCheck( GdipCombineRegionRectI(FNativeRegion, @rect, CombineModeIntersect)); Result := Self; end; function TGPRegion.IntersectF(const rect: TGPRectF) : TGPRegion; begin ErrorCheck( GdipCombineRegionRect(FNativeRegion, @rect, CombineModeIntersect)); Result := Self; end; function TGPRegion.Intersect(path: IGPGraphicsPath) : TGPRegion; begin ErrorCheck( GdipCombineRegionPath(FNativeRegion, path.GetNativePath(), CombineModeIntersect)); Result := Self; end; function TGPRegion.Intersect(region: IGPRegion) : TGPRegion; begin ErrorCheck( GdipCombineRegionRegion(FNativeRegion, region.GetNativeRegion(), CombineModeIntersect)); Result := Self; end; function TGPRegion.Union(const rect: TGPRect) : TGPRegion; begin ErrorCheck( GdipCombineRegionRectI(FNativeRegion, @rect, CombineModeUnion)); Result := Self; end; function TGPRegion.UnionF(const rect: TGPRectF) : TGPRegion; begin ErrorCheck( GdipCombineRegionRect(FNativeRegion, @rect, CombineModeUnion)); Result := Self; end; function TGPRegion.Union(path: IGPGraphicsPath) : TGPRegion; begin ErrorCheck( GdipCombineRegionPath(FNativeRegion, path.GetNativePath(), CombineModeUnion)); Result := Self; end; function TGPRegion.Union(region: IGPRegion) : TGPRegion; begin ErrorCheck( GdipCombineRegionRegion(FNativeRegion, region.GetNativeRegion(), CombineModeUnion)); Result := Self; end; function TGPRegion.XorRegion(const rect: TGPRect) : TGPRegion; begin ErrorCheck( GdipCombineRegionRectI(FNativeRegion, @rect, CombineModeXor)); Result := Self; end; function TGPRegion.XorRegionF(const rect: TGPRectF) : TGPRegion; begin ErrorCheck( GdipCombineRegionRect(FNativeRegion, @rect, CombineModeXor)); Result := Self; end; function TGPRegion.XorRegion(path: IGPGraphicsPath) : TGPRegion; begin ErrorCheck( GdipCombineRegionPath(FNativeRegion, path.GetNativePath(), CombineModeXor)); Result := Self; end; function TGPRegion.XorRegion(region: IGPRegion) : TGPRegion; begin ErrorCheck( GdipCombineRegionRegion(FNativeRegion, region.GetNativeRegion(), CombineModeXor)); Result := Self; end; function TGPRegion.Exclude(const rect: TGPRect) : TGPRegion; begin ErrorCheck( GdipCombineRegionRectI(FNativeRegion, @rect, CombineModeExclude)); Result := Self; end; function TGPRegion.ExcludeF(const rect: TGPRectF) : TGPRegion; begin ErrorCheck( GdipCombineRegionRect(FNativeRegion, @rect, CombineModeExclude)); Result := Self; end; function TGPRegion.Exclude(path: IGPGraphicsPath) : TGPRegion; begin ErrorCheck( GdipCombineRegionPath(FNativeRegion, path.GetNativePath(), CombineModeExclude)); Result := Self; end; function TGPRegion.Exclude(region: IGPRegion) : TGPRegion; begin ErrorCheck( GdipCombineRegionRegion(FNativeRegion, region.GetNativeRegion(), CombineModeExclude)); Result := Self; end; function TGPRegion.Complement(const rect: TGPRect) : TGPRegion; begin ErrorCheck( GdipCombineRegionRectI(FNativeRegion, @rect, CombineModeComplement)); Result := Self; end; function TGPRegion.ComplementF(const rect: TGPRectF) : TGPRegion; begin ErrorCheck( GdipCombineRegionRect(FNativeRegion, @rect, CombineModeComplement)); Result := Self; end; function TGPRegion.Complement(path: IGPGraphicsPath) : TGPRegion; begin ErrorCheck( GdipCombineRegionPath(FNativeRegion, path.GetNativePath(), CombineModeComplement)); Result := Self; end; function TGPRegion.Complement(region: IGPRegion) : TGPRegion; begin ErrorCheck( GdipCombineRegionRegion(FNativeRegion, region.GetNativeRegion(), CombineModeComplement)); Result := Self; end; function TGPRegion.TranslateF(dx, dy: Single) : TGPRegion; begin ErrorCheck( GdipTranslateRegion(FNativeRegion, dx, dy)); Result := Self; end; function TGPRegion.Translate(dx, dy: Integer) : TGPRegion; begin ErrorCheck( GdipTranslateRegionI(FNativeRegion, dx, dy)); Result := Self; end; function TGPRegion.Transform(matrix: IGPMatrix) : TGPRegion; begin ErrorCheck( GdipTransformRegion(FNativeRegion, matrix.GetNativeMatrix())); Result := Self; end; function TGPRegion.GetBounds( g: IGPGraphics ) : TGPRect; begin ErrorCheck( GdipGetRegionBoundsI(FNativeRegion, g.GetNativeGraphics(), @Result)); end; function TGPRegion.GetBoundsF( g: IGPGraphics ) : TGPRectF; begin ErrorCheck( GdipGetRegionBounds(FNativeRegion, g.GetNativeGraphics(), @Result)); end; function TGPRegion.GetHRGN(g: IGPGraphics) : HRGN; begin ErrorCheck( GdipGetRegionHRgn(FNativeRegion, g.GetNativeGraphics(), Result)); end; function TGPRegion.IsEmpty(g: IGPGraphics) : Boolean; var booln : BOOL; begin booln := False; ErrorCheck( GdipIsEmptyRegion(FNativeRegion, g.GetNativeGraphics(), booln)); Result := booln; end; function TGPRegion.IsInfinite(g: IGPGraphics) : Boolean ; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsInfiniteRegion(FNativeRegion, g.GetNativeGraphics(), booln)); Result := booln; end; function TGPRegion.IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionPointI(FNativeRegion, X, Y, gpx, booln)); Result := booln; end; function TGPRegion.IsVisible(const point: TGPPoint; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionPointI(FNativeRegion, point.X, point.Y, gpx, booln)); Result := booln; end; function TGPRegion.IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionPoint(FNativeRegion, X, Y, gpx, booln)); Result := booln; end; function TGPRegion.IsVisibleF(const point: TGPPointF; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionPoint(FNativeRegion, point.X, point.Y, gpx, booln)); Result := booln; end; function TGPRegion.IsVisible(x, y, width, height: Integer; g: IGPGraphics) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionRectI(FNativeRegion, X, Y, Width, Height, gpx, booln)); Result := booln; end; function TGPRegion.IsVisible(const rect: TGPRect; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionRectI(FNativeRegion, rect.X, rect.Y, rect.Width, rect.Height, gpx, booln)); Result := booln; end; function TGPRegion.IsVisibleF(x, y, width, height: Single; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionRect(FNativeRegion, X, Y, Width, Height, gpx, booln)); Result := booln; end; function TGPRegion.IsVisibleF(const rect: TGPRectF; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; GPX: GpGraphics; begin booln := False; if( Assigned(g)) then gpx := g.GetNativeGraphics() else gpx := NIL; ErrorCheck( GdipIsVisibleRegionRect(FNativeRegion, rect.X, rect.Y, rect.Width, rect.Height, gpx, booln)); Result := booln; end; function TGPRegion.EqualsRegion(region: IGPRegion; g: IGPGraphics) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsEqualRegion(FNativeRegion, region.GetNativeRegion(), g.GetNativeGraphics(), booln)); Result := booln; end; function TGPRegion.GetRegionScansCount(matrix: IGPMatrix) : Cardinal; var Count: Cardinal; begin count := 0; ErrorCheck( GdipGetRegionScansCount(FNativeRegion, count, matrix.GetNativeMatrix())); Result := count; end; // If rects is NIL, Result := the count of rects in the region. // Otherwise, assume rects is big enough to hold all the region rects // and fill them in and Result := the number of rects filled in. // The rects are Result :=ed in the units specified by the matrix // (which is typically a world-to-device transform). // Note that the number of rects Result :=ed can vary, depending on the // matrix that is used. function TGPRegion.GetRegionScansF( matrix: IGPMatrix ) : TGPRectFArray; var count : Cardinal; begin ErrorCheck( GdipGetRegionScansCount( FNativeRegion, count, matrix.GetNativeMatrix())); SetLength( Result, count ); ErrorCheck( GdipGetRegionScans(FNativeRegion, @Result[ 0 ], Integer( count ), matrix.GetNativeMatrix())); end; function TGPRegion.GetRegionScans( matrix: IGPMatrix ) : TGPRectArray; var count : Cardinal; begin ErrorCheck( GdipGetRegionScansCount( FNativeRegion, count, matrix.GetNativeMatrix())); SetLength( Result, count ); ErrorCheck( GdipGetRegionScansI(FNativeRegion, @Result[ 0 ], Integer( count ), matrix.GetNativeMatrix())); end; constructor TGPRegion.CreateGdiPlus(nativeRegion: GpRegion; Dummy : Boolean); begin SetNativeRegion(nativeRegion); end; procedure TGPRegion.SetNativeRegion(nativeRegion: GpRegion); begin FNativeRegion := nativeRegion; end; function TGPRegion.GetNativeRegion() : GpRegion; begin Result := FNativeRegion; end; (**************************************************************************\ * * GDI+ CustomLineCap APIs * \**************************************************************************) constructor TGPCustomLineCap.Create(fillPath, strokePath: IGPGraphicsPath; baseCap: TGPLineCap = LineCapFlat; baseInset: Single = 0); var nativeFillPath, nativeStrokePath: GpPath; begin FNativeCap := NIL; nativeFillPath := NIL; nativeStrokePath := NIL; if( Assigned(fillPath)) then nativeFillPath := fillPath.GetNativePath(); if( Assigned(strokePath)) then nativeStrokePath := strokePath.GetNativePath(); ErrorCheck( GdipCreateCustomLineCap(nativeFillPath, nativeStrokePath, baseCap, baseInset, FNativeCap)); end; destructor TGPCustomLineCap.Destroy(); begin GdipDeleteCustomLineCap(FNativeCap); end; function TGPCustomLineCap.Clone: TGPCustomLineCap; var newNativeLineCap: GpCustomLineCap; begin newNativeLineCap := NIL; ErrorCheck( GdipCloneCustomLineCap(FNativeCap, newNativeLineCap)); Result := TGPCustomLineCap.CreateGdiPlus(newNativeLineCap, False); if (Result = NIL) then ErrorCheck( GdipDeleteCustomLineCap(newNativeLineCap)); end; // This changes both the start and end cap. function TGPCustomLineCap.SetStrokeCap(strokeCap: TGPLineCap) : TGPCustomLineCap; begin Result := SetStrokeCaps(strokeCap, strokeCap); end; function TGPCustomLineCap.SetStrokeCaps(startCap, endCap: TGPLineCap) : TGPCustomLineCap; begin ErrorCheck( GdipSetCustomLineCapStrokeCaps(FNativeCap, startCap, endCap)); Result := Self; end; function TGPCustomLineCap.GetStrokeCaps(out startCap, endCap: TGPLineCap) : TGPCustomLineCap; begin ErrorCheck( GdipGetCustomLineCapStrokeCaps(FNativeCap, startCap, endCap)); Result := Self; end; function TGPCustomLineCap.SetStrokeJoin(lineJoin: TGPLineJoin) : TGPCustomLineCap; begin ErrorCheck( GdipSetCustomLineCapStrokeJoin(FNativeCap, lineJoin)); Result := Self; end; procedure TGPCustomLineCap.SetStrokeJoinProp(lineJoin: TGPLineJoin); begin ErrorCheck( GdipSetCustomLineCapStrokeJoin(FNativeCap, lineJoin)); end; function TGPCustomLineCap.GetStrokeJoin() : TGPLineJoin; begin ErrorCheck( GdipGetCustomLineCapStrokeJoin(FNativeCap, Result)); end; function TGPCustomLineCap.SetBaseCap(baseCap: TGPLineCap) : TGPCustomLineCap; begin ErrorCheck( GdipSetCustomLineCapBaseCap(FNativeCap, baseCap)); Result := Self; end; procedure TGPCustomLineCap.SetBaseCapProp(baseCap: TGPLineCap); begin ErrorCheck( GdipSetCustomLineCapBaseCap(FNativeCap, baseCap)); end; function TGPCustomLineCap.GetBaseCap() : TGPLineCap; begin ErrorCheck( GdipGetCustomLineCapBaseCap(FNativeCap, Result)); end; function TGPCustomLineCap.SetBaseInset(inset: Single) : TGPCustomLineCap; begin ErrorCheck( GdipSetCustomLineCapBaseInset(FNativeCap, inset)); Result := Self; end; procedure TGPCustomLineCap.SetBaseInsetProp(inset: Single); begin ErrorCheck( GdipSetCustomLineCapBaseInset(FNativeCap, inset)); end; function TGPCustomLineCap.GetBaseInset() : Single; begin ErrorCheck( GdipGetCustomLineCapBaseInset(FNativeCap, Result)); end; function TGPCustomLineCap.SetWidthScale(widthScale: Single) : TGPCustomLineCap; begin ErrorCheck( GdipSetCustomLineCapWidthScale(FNativeCap, widthScale)); Result := Self; end; procedure TGPCustomLineCap.SetWidthScaleProp(widthScale: Single); begin ErrorCheck( GdipSetCustomLineCapWidthScale(FNativeCap, widthScale)); end; function TGPCustomLineCap.GetWidthScale() : Single; begin ErrorCheck( GdipGetCustomLineCapWidthScale(FNativeCap, Result)); end; constructor TGPCustomLineCap.Create(); begin FNativeCap := NIL; end; constructor TGPCustomLineCap.CreateGdiPlus(nativeCap: GpCustomLineCap; Dummy : Boolean); begin SetNativeCap(nativeCap); end; procedure TGPCustomLineCap.SetNativeCap(nativeCap: GpCustomLineCap); begin FNativeCap := nativeCap; end; function TGPCustomLineCap.GetNativeCap() : GpCustomLineCap; begin Result := FNativeCap; end; (************************************************************************** * * CachedBitmap class definition * * GDI+ CachedBitmap is a representation of an accelerated drawing * that has restrictions on what operations are allowed in order * to accelerate the drawing to the destination. * **************************************************************************) constructor TGPCachedBitmap.Create(bitmap: IGPBitmap; graphics: IGPGraphics); begin FNativeCachedBitmap := NIL; ErrorCheck( GdipCreateCachedBitmap( GpBitmap(bitmap.GetNativeImage()), graphics.GetNativeGraphics(), FNativeCachedBitmap)); end; destructor TGPCachedBitmap.Destroy(); begin GdipDeleteCachedBitmap(FNativeCachedBitmap); end; function TGPCachedBitmap.GetNativeCachedBitmap() : GpCachedBitmap; begin Result := FNativeCachedBitmap; end; (**************************************************************************\ * * GDI+ Pen class * \**************************************************************************) //-------------------------------------------------------------------------- // Pen class //-------------------------------------------------------------------------- constructor TGPPen.Create(color: TGPColor; width: Single = 1.0); var unit_ : TGPUnit; begin unit_ := UnitWorld; FNativePen := NIL; ErrorCheck( GdipCreatePen1(color, width, unit_, FNativePen) ); end; constructor TGPPen.Create(brush: IGPBrush; width: Single = 1.0); var unit_ : TGPUnit; begin unit_ := UnitWorld; FNativePen := NIL; if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipCreatePen2(brush.GetNativeBrush(), width, unit_, FNativePen)); end; destructor TGPPen.Destroy(); begin GdipDeletePen(FNativePen); end; function TGPPen.Clone() : TGPPen; var clonePen: GpPen; begin clonePen := NIL; ErrorCheck( GdipClonePen(FNativePen, clonePen)); Result := TGPPen.CreateGdiPlus(clonePen, False); end; procedure TGPPen.SetWidthProp(width: Single); begin ErrorCheck( GdipSetPenWidth(FNativePen, width) ); end; function TGPPen.SetWidth(width: Single) : TGPPen; begin ErrorCheck( GdipSetPenWidth(FNativePen, width) ); Result := Self; end; function TGPPen.GetWidth() : Single; begin ErrorCheck( GdipGetPenWidth(FNativePen, Result)); end; // Set/get line caps: start, end, and dash // Line cap and join APIs by using LineCap and LineJoin enums. function TGPPen.SetLineCap(startCap, endCap: TGPLineCap; dashCap: TGPDashCap) : TGPPen; begin ErrorCheck( GdipSetPenLineCap197819(FNativePen, startCap, endCap, dashCap)); Result := Self; end; procedure TGPPen.SetStartCapProp(startCap: TGPLineCap); begin ErrorCheck( GdipSetPenStartCap(FNativePen, startCap)); end; function TGPPen.SetStartCap(startCap: TGPLineCap) : TGPPen; begin ErrorCheck( GdipSetPenStartCap(FNativePen, startCap)); Result := Self; end; procedure TGPPen.SetEndCapProp(endCap: TGPLineCap); begin ErrorCheck( GdipSetPenEndCap(FNativePen, endCap)); end; function TGPPen.SetEndCap(endCap: TGPLineCap) : TGPPen; begin ErrorCheck( GdipSetPenEndCap(FNativePen, endCap)); Result := Self; end; procedure TGPPen.SetDashCapProp(dashCap: TGPDashCap); begin ErrorCheck( GdipSetPenDashCap197819(FNativePen, dashCap)); end; function TGPPen.SetDashCap(dashCap: TGPDashCap) : TGPPen; begin ErrorCheck( GdipSetPenDashCap197819(FNativePen, dashCap)); Result := Self; end; function TGPPen.GetStartCap() : TGPLineCap; begin ErrorCheck( GdipGetPenStartCap(FNativePen, Result)); end; function TGPPen.GetEndCap: TGPLineCap; begin ErrorCheck( GdipGetPenEndCap(FNativePen, Result)); end; function TGPPen.GetDashCap: TGPDashCap; begin ErrorCheck( GdipGetPenDashCap197819(FNativePen, Result)); end; procedure TGPPen.SetLineJoinProp(lineJoin: TGPLineJoin); begin ErrorCheck( GdipSetPenLineJoin(FNativePen, lineJoin)); end; function TGPPen.SetLineJoin(lineJoin: TGPLineJoin) : TGPPen; begin ErrorCheck( GdipSetPenLineJoin(FNativePen, lineJoin)); Result := Self; end; function TGPPen.GetLineJoin() : TGPLineJoin; begin ErrorCheck( GdipGetPenLineJoin(FNativePen, Result)); end; procedure TGPPen.SetCustomStartCapProp(customCap: IGPCustomLineCap); begin SetCustomStartCap( customCap ); end; function TGPPen.SetCustomStartCap(customCap: IGPCustomLineCap) : TGPPen; var nativeCap: GpCustomLineCap; begin nativeCap := NIL; if( Assigned(customCap)) then nativeCap := customCap.GetNativeCap(); ErrorCheck( GdipSetPenCustomStartCap(FNativePen, nativeCap)); Result := Self; end; function TGPPen.GetCustomStartCap() : IGPCustomLineCap; var ALineCap : TGPCustomLineCap; begin ALineCap := TGPCustomLineCap.Create(); ErrorCheck( GdipGetPenCustomStartCap(FNativePen, ALineCap.FNativeCap )); Result := ALineCap; end; procedure TGPPen.SetCustomEndCapProp(customCap: IGPCustomLineCap); begin SetCustomEndCap( customCap ); end; function TGPPen.SetCustomEndCap(customCap: IGPCustomLineCap) : TGPPen; var nativeCap: GpCustomLineCap; begin nativeCap := NIL; if( Assigned(customCap)) then nativeCap := customCap.GetNativeCap(); ErrorCheck( GdipSetPenCustomEndCap(FNativePen, nativeCap)); Result := Self; end; function TGPPen.GetCustomEndCap() : IGPCustomLineCap; var ALineCap : TGPCustomLineCap; begin ALineCap := TGPCustomLineCap.Create(); ErrorCheck( GdipGetPenCustomEndCap(FNativePen, ALineCap.FNativeCap)); Result := ALineCap; end; procedure TGPPen.SetMiterLimitProp(miterLimit: Single); begin ErrorCheck( GdipSetPenMiterLimit(FNativePen, miterLimit)); end; function TGPPen.SetMiterLimit(miterLimit: Single) : TGPPen; begin ErrorCheck( GdipSetPenMiterLimit(FNativePen, miterLimit)); Result := Self; end; function TGPPen.GetMiterLimit() : Single; begin ErrorCheck( GdipGetPenMiterLimit(FNativePen, Result)); end; procedure TGPPen.SetAlignmentProp( penAlignment: TGPPenAlignment); begin ErrorCheck( GdipSetPenMode(FNativePen, penAlignment)); end; function TGPPen.SetAlignment( penAlignment: TGPPenAlignment) : TGPPen; begin ErrorCheck( GdipSetPenMode(FNativePen, penAlignment)); Result := Self; end; function TGPPen.GetAlignment() : TGPPenAlignment; begin ErrorCheck( GdipGetPenMode(FNativePen, Result)); end; procedure TGPPen.SetTransformProp(matrix: IGPMatrix); begin ErrorCheck( GdipSetPenTransform(FNativePen, matrix.GetNativeMatrix())); end; function TGPPen.SetTransform(matrix: IGPMatrix) : TGPPen; begin ErrorCheck( GdipSetPenTransform(FNativePen, matrix.GetNativeMatrix())); Result := Self; end; function TGPPen.GetTransform() : IGPMatrix; begin Result := TGPMatrix.Create(); ErrorCheck( GdipGetPenTransform(FNativePen, Result.GetNativeMatrix())); end; function TGPPen.ResetTransform() : TGPPen; begin ErrorCheck( GdipResetPenTransform(FNativePen)); Result := Self; end; function TGPPen.MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; begin ErrorCheck( GdipMultiplyPenTransform(FNativePen, matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPPen.TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; begin ErrorCheck( GdipTranslatePenTransform(FNativePen, dx, dy, order)); Result := Self; end; function TGPPen.ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; begin ErrorCheck( GdipScalePenTransform(FNativePen, sx, sy, order)); Result := Self; end; function TGPPen.RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPen; begin ErrorCheck( GdipRotatePenTransform(FNativePen, angle, order)); Result := Self; end; function TGPPen.SetTransformT(matrix: IGPMatrix) : IGPTransformable; begin ErrorCheck( GdipSetPenTransform(FNativePen, matrix.GetNativeMatrix())); Result := Self; end; function TGPPen.ResetTransformT() : IGPTransformable; begin ErrorCheck( GdipResetPenTransform(FNativePen)); Result := Self; end; function TGPPen.MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipMultiplyPenTransform(FNativePen, matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPPen.TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipTranslatePenTransform(FNativePen, dx, dy, order)); Result := Self; end; function TGPPen.ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipScalePenTransform(FNativePen, sx, sy, order)); Result := Self; end; function TGPPen.RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipRotatePenTransform(FNativePen, angle, order)); Result := Self; end; function TGPPen.GetPenType() : TGPPenType; begin ErrorCheck( GdipGetPenFillType(FNativePen, Result)); end; procedure TGPPen.SetColorProp(color: TGPColor); begin ErrorCheck( GdipSetPenColor(FNativePen, color)); end; function TGPPen.SetColor(color: TGPColor) : TGPPen; begin ErrorCheck( GdipSetPenColor(FNativePen, color)); Result := Self; end; procedure TGPPen.SetBrushProp(brush: IGPBrush); begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipSetPenBrushFill( FNativePen, brush.GetNativeBrush() )); end; function TGPPen.SetBrush(brush: IGPBrush) : TGPPen; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipSetPenBrushFill( FNativePen, brush.GetNativeBrush() )); Result := Self; end; function TGPPen.GetColor() : TGPColor; begin if( GetPenType() <> PenTypeSolidColor ) then ErrorCheck( WrongState ); ErrorCheck( GdipGetPenColor(FNativePen, Result )); end; function TGPPen.GetBrush() : IGPBrush; var type_: TGPPenType; Brush: TGPBrush; nativeBrush: GpBrush; begin type_ := GetPenType(); brush := NIL; case type_ of PenTypeSolidColor : brush := TGPSolidBrush.Create(); PenTypeHatchFill : brush := TGPHatchBrush.Create(); PenTypeTextureFill : brush := TGPTextureBrush.Create(); PenTypePathGradient : brush := TGPBrush.Create(); PenTypeLinearGradient : brush := TGPLinearGradientBrush.Create(); end; if( brush <> NIL ) then begin ErrorCheck( GdipGetPenBrushFill( FNativePen, nativeBrush )); brush.SetNativeBrush(nativeBrush); end; Result := brush; end; function TGPPen.GetDashStyle() : TGPDashStyle; begin ErrorCheck( GdipGetPenDashStyle(FNativePen, Result)); end; procedure TGPPen.SetDashStyleProp(dashStyle: TGPDashStyle); begin ErrorCheck( GdipSetPenDashStyle(FNativePen, dashStyle)); end; function TGPPen.SetDashStyle(dashStyle: TGPDashStyle) : TGPPen; begin ErrorCheck( GdipSetPenDashStyle(FNativePen, dashStyle)); Result := Self; end; function TGPPen.GetDashOffset() : Single; begin ErrorCheck( GdipGetPenDashOffset(FNativePen, Result)); end; procedure TGPPen.SetDashOffsetProp( dashOffset: Single ); begin ErrorCheck( GdipSetPenDashOffset(FNativePen, dashOffset)); end; function TGPPen.SetDashOffset(dashOffset: Single) : TGPPen; begin ErrorCheck( GdipSetPenDashOffset(FNativePen, dashOffset)); Result := Self; end; function TGPPen.SetDashPattern( dashArray: array of Single ) : TGPPen; var ALength : Integer; ADashArray: array of Single; begin ALength := Length( dashArray ); if( ALength and 1 > 0 ) then begin Inc( ALength ); SetLength( ADashArray, ALength ); Move( dashArray[ 0 ], ADashArray[ 0 ], SizeOf( dashArray )); ADashArray[ ALength - 1 ] := 0.0001; ErrorCheck( GdipSetPenDashArray(FNativePen, @ADashArray[ 0 ], ALength )); end else ErrorCheck( GdipSetPenDashArray(FNativePen, @dashArray[ 0 ], ALength )); Result := Self; end; procedure TGPPen.SetDashPatternProp( dashArray: TGPSingleArray ); begin SetDashPattern( dashArray ); end; function TGPPen.GetDashPatternCount() : Integer; begin ErrorCheck( GdipGetPenDashCount(FNativePen, Result)); end; function TGPPen.GetDashPattern() : TGPSingleArray; var count: Integer; begin ErrorCheck( GdipGetPenDashCount( FNativePen, count )); SetLength( Result, count ); ErrorCheck( GdipGetPenDashArray( FNativePen, @Result[ 0 ], count )); end; function TGPPen.SetCompoundArray( compoundArray: array of Single ) : TGPPen; begin ErrorCheck( GdipSetPenCompoundArray(FNativePen, @compoundArray[ 0 ], Length( compoundArray ))); Result := Self; end; procedure TGPPen.SetCompoundArrayProp( compoundArray: TGPSingleArray ); begin ErrorCheck( GdipSetPenCompoundArray(FNativePen, @compoundArray[ 0 ], Length( compoundArray ))); end; function TGPPen.GetCompoundArrayCount() : Integer; begin ErrorCheck( GdipGetPenCompoundCount(FNativePen, Result)); end; function TGPPen.GetCompoundArray() : TGPSingleArray; var count : Integer; begin ErrorCheck( GdipGetPenCompoundCount(FNativePen, count)); SetLength( Result, count ); ErrorCheck( GdipGetPenCompoundArray(FNativePen, @Result[ 0 ], count)); end; constructor TGPPen.CreateGdiPlus(nativePen: GpPen; Dummy : Boolean); begin SetNativePen(nativePen); end; procedure TGPPen.SetNativePen(nativePen: GpPen); begin FNativePen := nativePen; end; function TGPPen.GetNativePen() : GpPen; begin Result := self.FNativePen; end; (**************************************************************************\ * * GDI+ Brush class * \**************************************************************************) //-------------------------------------------------------------------------- // Abstract base class for various brush types //-------------------------------------------------------------------------- destructor TGPBrush.Destroy(); begin GdipDeleteBrush( FNativeBrush ); end; function TGPBrush.Clone() : TGPBrush; var brush: GpBrush; newBrush: TGPBrush; begin brush := NIL; ErrorCheck( GdipCloneBrush(FNativeBrush, brush)); newBrush := TGPBrush.Create(brush); if (newBrush = NIL) then GdipDeleteBrush(brush); Result := newBrush; end; function TGPBrush.GetType() : TGPBrushType; var type_: TGPBrushType; begin type_ := TGPBrushType(-1); ErrorCheck( GdipGetBrushType(FNativeBrush, type_)); Result := type_; end; constructor TGPBrush.Create(); begin ErrorCheck( NotImplemented); end; constructor TGPBrush.Create(nativeBrush: GpBrush); begin SetNativeBrush(nativeBrush); end; procedure TGPBrush.SetNativeBrush(nativeBrush: GpBrush); begin FNativeBrush := nativeBrush; end; function TGPBrush.GetNativeBrush() : GpBrush; begin Result := FNativeBrush; end; //-------------------------------------------------------------------------- // Solid Fill Brush Object //-------------------------------------------------------------------------- constructor TGPSolidBrush.Create(color: TGPColor); var brush: GpSolidFill; begin brush := NIL; ErrorCheck( GdipCreateSolidFill(color, brush)); SetNativeBrush(brush); end; constructor TGPSolidBrush.Create(); begin // hide parent function end; function TGPSolidBrush.GetColor() : TGPColor; begin ErrorCheck( GdipGetSolidFillColor(GpSolidFill(FNativeBrush), Result )); end; function TGPSolidBrush.SetColor(color: TGPColor) : TGPSolidBrush; begin ErrorCheck( GdipSetSolidFillColor(GpSolidFill(FNativeBrush), color)); Result := Self; end; procedure TGPSolidBrush.SetColorProp(color: TGPColor); begin ErrorCheck( GdipSetSolidFillColor(GpSolidFill(FNativeBrush), color)); end; //-------------------------------------------------------------------------- // Texture Brush Fill Object //-------------------------------------------------------------------------- constructor TGPTextureBrush.Create(image: IGPImage; wrapMode: TGPWrapMode = WrapModeTile); var texture: GpTexture; begin //texture := NIL; ErrorCheck( GdipCreateTexture(image.GetNativeImage(), wrapMode, texture)); SetNativeBrush(texture); end; // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. constructor TGPTextureBrush.Create(image: IGPImage; wrapMode: TGPWrapMode; dstRect: TGPRectF); var texture: GpTexture; begin texture := NIL; ErrorCheck( GdipCreateTexture2(image.GetNativeImage(), wrapMode, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, texture)); SetNativeBrush(texture); end; constructor TGPTextureBrush.Create(image: IGPImage; dstRect: TGPRectF; imageAttributes: IGPImageAttributes = NIL); var texture: GpTexture; ImgAtt: GpImageAttributes; begin texture := NIL; if( Assigned(imageAttributes)) then ImgAtt := imageAttributes.GetNativeImageAttr() else ImgAtt := NIL; ErrorCheck( GdipCreateTextureIA(image.GetNativeImage(), ImgAtt, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, texture)); SetNativeBrush(texture); end; constructor TGPTextureBrush.Create(image: IGPImage; dstRect: TGPRect; imageAttributes: IGPImageAttributes = NIL); var texture: GpTexture; ImgAtt: GpImageAttributes; begin texture := NIL; if( Assigned(imageAttributes)) then ImgAtt := imageAttributes.GetNativeImageAttr() else ImgAtt := NIL; ErrorCheck( GdipCreateTextureIAI(image.GetNativeImage(), ImgAtt, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, texture)); SetNativeBrush(texture); end; constructor TGPTextureBrush.Create(image: IGPImage; wrapMode: TGPWrapMode; dstRect: TGPRect); var texture: GpTexture; begin texture := NIL; ErrorCheck( GdipCreateTexture2I(image.GetNativeImage(), wrapMode, dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, texture)); SetNativeBrush(texture); end; constructor TGPTextureBrush.Create(image: IGPImage; wrapMode: TGPWrapMode; dstX, dstY, dstWidth, dstHeight: Single); var texture: GpTexture; begin texture := NIL; ErrorCheck( GdipCreateTexture2(image.GetNativeImage(), wrapMode, dstX, dstY, dstWidth, dstHeight, texture)); SetNativeBrush(texture); end; constructor TGPTextureBrush.Create(image: IGPImage; wrapMode: TGPWrapMode; dstX, dstY, dstWidth, dstHeight: Integer); var texture: GpTexture; begin texture := NIL; ErrorCheck( GdipCreateTexture2I(image.GetNativeImage(), wrapMode, dstX, dstY, dstWidth, dstHeight, texture)); SetNativeBrush(texture); end; function TGPTextureBrush.SetTransform(matrix: IGPMatrix) : TGPTextureBrush; begin ErrorCheck( GdipSetTextureTransform(GpTexture(FNativeBrush), matrix.GetNativeMatrix())); Result := Self; end; procedure TGPTextureBrush.SetTransformProp(matrix: IGPMatrix); begin ErrorCheck( GdipSetTextureTransform(GpTexture(FNativeBrush), matrix.GetNativeMatrix())); end; function TGPTextureBrush.GetTransform() : IGPMatrix; begin Result := TGPMatrix.Create(); ErrorCheck( GdipGetTextureTransform(GpTexture(FNativeBrush), Result.GetNativeMatrix())); end; function TGPTextureBrush.ResetTransform() : TGPTextureBrush; begin ErrorCheck( GdipResetTextureTransform(GpTexture(FNativeBrush))); Result := Self; end; function TGPTextureBrush.MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; begin ErrorCheck( GdipMultiplyTextureTransform(GpTexture(FNativeBrush), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPTextureBrush.TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; begin ErrorCheck( GdipTranslateTextureTransform(GpTexture(FNativeBrush), dx, dy, order)); Result := Self; end; function TGPTextureBrush.ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; begin ErrorCheck( GdipScaleTextureTransform(GpTexture(FNativeBrush), sx, sy, order)); Result := Self; end; function TGPTextureBrush.RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPTextureBrush; begin ErrorCheck( GdipRotateTextureTransform(GpTexture(FNativeBrush), angle, order)); Result := Self; end; function TGPTextureBrush.SetTransformT(matrix: IGPMatrix) : IGPTransformable; begin ErrorCheck( GdipSetTextureTransform(GpTexture(FNativeBrush), matrix.GetNativeMatrix())); Result := Self; end; function TGPTextureBrush.ResetTransformT() : IGPTransformable; begin ErrorCheck( GdipResetTextureTransform(GpTexture(FNativeBrush))); Result := Self; end; function TGPTextureBrush.MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipMultiplyTextureTransform(GpTexture(FNativeBrush), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPTextureBrush.TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipTranslateTextureTransform(GpTexture(FNativeBrush), dx, dy, order)); Result := Self; end; function TGPTextureBrush.ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipScaleTextureTransform(GpTexture(FNativeBrush), sx, sy, order)); Result := Self; end; function TGPTextureBrush.RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipRotateTextureTransform(GpTexture(FNativeBrush), angle, order)); Result := Self; end; function TGPTextureBrush.SetWrapMode(wrapMode: TGPWrapMode) : TGPTextureBrush; begin ErrorCheck( GdipSetTextureWrapMode(GpTexture(FNativeBrush), wrapMode)); Result := Self; end; procedure TGPTextureBrush.SetWrapModeProp(wrapMode: TGPWrapMode); begin ErrorCheck( GdipSetTextureWrapMode(GpTexture(FNativeBrush), wrapMode)); end; function TGPTextureBrush.GetWrapMode: TGPWrapMode; begin ErrorCheck( GdipGetTextureWrapMode(GpTexture(FNativeBrush), Result)); end; function TGPTextureBrush.GetImage() : IGPImage; var image: GpImage; begin ErrorCheck( GdipGetTextureImage(GpTexture(FNativeBrush), image)); Result := TGPImage.CreateGdiPlus(image, False); if (Result = NIL) then GdipDisposeImage(image); end; function TGPTextureBrush.SetImage( image : IGPImage ) : TGPTextureBrush; var texture : GpTexture; wrapMode : TGPWrapMode; begin wrapMode := GetWrapMode(); ErrorCheck( GdipCreateTexture(image.GetNativeImage(), wrapMode, texture)); SetNativeBrush(texture); Result := Self; end; procedure TGPTextureBrush.SetImageProp( image : IGPImage ); begin SetImage( image ); end; constructor TGPTextureBrush.Create(); begin // hide parent function end; //-------------------------------------------------------------------------- // Linear Gradient Brush Object //-------------------------------------------------------------------------- constructor TGPLinearGradientBrush.Create( point1, point2: TGPPointF; color1, color2: TGPColor); var brush: GpLineGradient; begin brush := NIL; if(( point1.X = point2.X ) and ( point1.Y = point2.Y )) then point2.X := point1.X + 1; ErrorCheck( GdipCreateLineBrush(@point1, @point2, color1, color2, WrapModeTile, brush)); SetNativeBrush(brush); end; constructor TGPLinearGradientBrush.Create( point1, point2: TGPPoint; color1, color2: TGPColor); var brush: GpLineGradient; begin brush := NIL; if(( point1.X = point2.X ) and ( point1.Y = point2.Y )) then point2.X := point1.X + 1; ErrorCheck( GdipCreateLineBrushI(@point1, @point2, color1, color2, WrapModeTile, brush)); SetNativeBrush(brush); end; constructor TGPLinearGradientBrush.Create(rect: TGPRectF; color1, color2: TGPColor; mode: TGPLinearGradientMode); var brush: GpLineGradient; begin brush := NIL; if(( rect.Width = 0 ) and ( rect.Height = 0 )) then rect.Width := 1; ErrorCheck( GdipCreateLineBrushFromRect(@rect, color1, color2, mode, WrapModeTile, brush)); SetNativeBrush(brush); end; constructor TGPLinearGradientBrush.Create(rect: TGPRect; color1, color2: TGPColor; mode: TGPLinearGradientMode); var brush: GpLineGradient; begin brush := NIL; ErrorCheck( GdipCreateLineBrushFromRectI(@rect, color1, color2, mode, WrapModeTile, brush)); SetNativeBrush(brush); end; constructor TGPLinearGradientBrush.Create(rect: TGPRectF; color1, color2: TGPColor; angle: Single; isAngleScalable: Boolean = False); var brush: GpLineGradient; begin brush := NIL; ErrorCheck( GdipCreateLineBrushFromRectWithAngle(@rect, color1, color2, angle, isAngleScalable, WrapModeTile, brush)); SetNativeBrush(brush); end; constructor TGPLinearGradientBrush.Create(rect: TGPRect; color1, color2: TGPColor; angle: Single; isAngleScalable: Boolean = False); var brush: GpLineGradient; begin brush := NIL; ErrorCheck( GdipCreateLineBrushFromRectWithAngleI(@rect, color1, color2, angle, isAngleScalable, WrapModeTile, brush)); SetNativeBrush(brush); end; function TGPLinearGradientBrush.SetLinearColors(color1, color2: TGPColor) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineColors(GpLineGradient(FNativeBrush), color1, color2)); Result := Self; end; function TGPLinearGradientBrush.GetLinearColors(out color1, color2: TGPColor) : TGPLinearGradientBrush; var colors: array[0..1] of TGPColor; begin ErrorCheck( GdipGetLineColors(GpLineGradient(FNativeBrush), @colors)); color1 := colors[0]; color2 := colors[1]; Result := Self; end; function TGPLinearGradientBrush.GetRectangleF() : TGPRectF; begin ErrorCheck( GdipGetLineRect(GpLineGradient(FNativeBrush), @Result)); end; function TGPLinearGradientBrush.GetRectangle() : TGPRect; begin ErrorCheck( GdipGetLineRectI(GpLineGradient(FNativeBrush), @Result)); end; procedure TGPLinearGradientBrush.SetGammaCorrectionProp(useGammaCorrection: Boolean); begin ErrorCheck( GdipSetLineGammaCorrection(GpLineGradient(FNativeBrush), useGammaCorrection)); end; function TGPLinearGradientBrush.SetGammaCorrection(useGammaCorrection: Boolean) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineGammaCorrection(GpLineGradient(FNativeBrush), useGammaCorrection)); Result := Self; end; function TGPLinearGradientBrush.GetGammaCorrection: Boolean; var useGammaCorrection: BOOL; begin ErrorCheck( GdipGetLineGammaCorrection(GpLineGradient(FNativeBrush), useGammaCorrection)); Result := useGammaCorrection; end; function TGPLinearGradientBrush.GetBlendCount: Integer; var count: Integer; begin count := 0; ErrorCheck( GdipGetLineBlendCount(GpLineGradient(FNativeBrush), count)); Result := count; end; function TGPLinearGradientBrush.SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineBlend(GpLineGradient(FNativeBrush), @blendFactors[ 0 ], @blendPositions[ 0 ], Min( Length( blendFactors ), Length( blendPositions )) )); Result := Self; end; function TGPLinearGradientBrush.SetBlend( blendFactors : array of TGPBlend ) : TGPLinearGradientBrush; var I : Integer; count : Integer; aFactors : array of Single; aPositions : array of Single; begin count := Length( blendFactors ); SetLength( aFactors, count ); SetLength( aPositions, count ); for I := 0 to count - 1 do begin aFactors[ I ] := blendFactors[ I ].Value; aPositions[ I ] := blendFactors[ I ].Position; end; Result := SetBlendArrays( aFactors, aPositions ); end; procedure TGPLinearGradientBrush.SetBlendProp( blendFactors : TGPBlendArray ); begin SetBlend( blendFactors ); end; function TGPLinearGradientBrush.GetBlend() : TGPBlendArray; var count : Integer; aFactors : array of Single; aPositions : array of Single; I : Integer; begin ErrorCheck( GdipGetLineBlendCount( GetNativeBrush(), count )); SetLength( aFactors, count ); SetLength( aPositions, count ); ErrorCheck( GdipGetLineBlend(GpLineGradient(FNativeBrush), @aFactors[ 0 ], @aPositions[ 0 ], count)); SetLength( Result, count ); for I := 0 to count - 1 do begin Result[ I ].Position := aPositions[ I ]; Result[ I ].Value := aFactors[ I ]; end; end; function TGPLinearGradientBrush.GetInterpolationColorCount() : Integer; var count: Integer; begin count := 0; ErrorCheck( GdipGetLinePresetBlendCount(GpLineGradient(FNativeBrush), count)); Result := count; end; function TGPLinearGradientBrush.SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLinePresetBlend(GpLineGradient(FNativeBrush), PGPColor( @presetColors[ 0 ]), @blendPositions[ 0 ], Min( Length( presetColors ), Length( blendPositions )))); Result := Self; end; function TGPLinearGradientBrush.SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPLinearGradientBrush; var presetColors : array of TGPColor; blendPositions : array of Single; count : Integer; I : Integer; begin count := Length( Colors ); SetLength( presetColors, count ); SetLength( blendPositions, count ); for I := 0 to count - 1 do begin presetColors[ I ] := Colors[ I ].Color; blendPositions[ I ] := Colors[ I ].Position; end; ErrorCheck( GdipSetLinePresetBlend(GpLineGradient(FNativeBrush), PGPColor( @presetColors[ 0 ]), @blendPositions[ 0 ], count )); Result := Self; end; procedure TGPLinearGradientBrush.SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); begin SetInterpolationColors( Colors ); end; function TGPLinearGradientBrush.GetInterpolationColors() : TGPInterpolationColorArray; var presetColors : array of TGPColor; blendPositions : array of Single; count : Integer; I : Integer; begin ErrorCheck( GdipGetLinePresetBlendCount( GpLineGradient(FNativeBrush), count )); SetLength( presetColors, count ); SetLength( blendPositions, count ); ErrorCheck( GdipGetLinePresetBlend(GpLineGradient(FNativeBrush), PGPColor(@presetColors[ 0 ]), @blendPositions[ 0 ], count)); for I := 0 to count - 1 do begin Result[ I ].Color := presetColors[ I ]; Result[ I ].Position := blendPositions[ I ]; end; end; function TGPLinearGradientBrush.SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineSigmaBlend(GpLineGradient(FNativeBrush), focus, scale)); Result := Self; end; function TGPLinearGradientBrush.SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineLinearBlend(GpLineGradient(FNativeBrush), focus, scale)); Result := Self; end; function TGPLinearGradientBrush.SetTransform(matrix: IGPMatrix) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineTransform(GpLineGradient(FNativeBrush), matrix.GetNativeMatrix())); Result := Self; end; procedure TGPLinearGradientBrush.SetTransformProp(matrix: IGPMatrix); begin ErrorCheck( GdipSetLineTransform(GpLineGradient(FNativeBrush), matrix.GetNativeMatrix())); end; function TGPLinearGradientBrush.GetTransform() : IGPMatrix; begin Result := TGPMatrix.Create(); ErrorCheck( GdipGetLineTransform(GpLineGradient(FNativeBrush), Result.GetNativeMatrix())); end; function TGPLinearGradientBrush.ResetTransform() : TGPLinearGradientBrush; begin ErrorCheck( GdipResetLineTransform(GpLineGradient(FNativeBrush))); Result := Self; end; function TGPLinearGradientBrush.MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; begin ErrorCheck( GdipMultiplyLineTransform(GpLineGradient(FNativeBrush), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPLinearGradientBrush.TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; begin ErrorCheck( GdipTranslateLineTransform(GpLineGradient(FNativeBrush), dx, dy, order)); Result := Self; end; function TGPLinearGradientBrush.ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; begin ErrorCheck( GdipScaleLineTransform(GpLineGradient(FNativeBrush), sx, sy, order)); Result := Self; end; function TGPLinearGradientBrush.RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPLinearGradientBrush; begin ErrorCheck( GdipRotateLineTransform(GpLineGradient(FNativeBrush), angle, order)); Result := Self; end; function TGPLinearGradientBrush.SetTransformT(matrix: IGPMatrix) : IGPTransformable; begin ErrorCheck( GdipSetLineTransform(GpLineGradient(FNativeBrush), matrix.GetNativeMatrix())); Result := Self; end; function TGPLinearGradientBrush.ResetTransformT() : IGPTransformable; begin ErrorCheck( GdipResetLineTransform(GpLineGradient(FNativeBrush))); Result := Self; end; function TGPLinearGradientBrush.MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipMultiplyLineTransform(GpLineGradient(FNativeBrush), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPLinearGradientBrush.TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipTranslateLineTransform(GpLineGradient(FNativeBrush), dx, dy, order)); Result := Self; end; function TGPLinearGradientBrush.ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipScaleLineTransform(GpLineGradient(FNativeBrush), sx, sy, order)); Result := Self; end; function TGPLinearGradientBrush.RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipRotateLineTransform(GpLineGradient(FNativeBrush), angle, order)); Result := Self; end; procedure TGPLinearGradientBrush.SetWrapModeProp(wrapMode: TGPWrapMode); begin ErrorCheck( GdipSetLineWrapMode(GpLineGradient(FNativeBrush), wrapMode)); end; function TGPLinearGradientBrush.SetWrapMode(wrapMode: TGPWrapMode) : TGPLinearGradientBrush; begin ErrorCheck( GdipSetLineWrapMode(GpLineGradient(FNativeBrush), wrapMode)); Result := Self; end; function TGPLinearGradientBrush.GetWrapMode() : TGPWrapMode; begin ErrorCheck( GdipGetLineWrapMode(GpLineGradient(FNativeBrush), Result)); end; constructor TGPLinearGradientBrush.Create(); begin // hide parent function end; //-------------------------------------------------------------------------- // Hatch Brush Object //-------------------------------------------------------------------------- constructor TGPHatchBrush.Create(); var brush: GpHatch; begin brush := NIL; ErrorCheck( GdipCreateHatchBrush(Integer(HatchStyleCross), aclWhite, aclBlack, brush)); SetNativeBrush(brush); end; constructor TGPHatchBrush.Create(hatchStyle: TGPHatchStyle; foreColor: TGPColor; backColor: TGPColor = aclBlack); var brush: GpHatch; begin brush := NIL; ErrorCheck( GdipCreateHatchBrush(Integer(hatchStyle), foreColor, backColor, brush)); SetNativeBrush(brush); end; procedure TGPHatchBrush.SetHatchStyleProp( style : TGPHatchStyle ); var brush: GpHatch; begin brush := NIL; ErrorCheck( GdipCreateHatchBrush( Integer( style ), GetForegroundColor(), GetBackgroundColor(), brush)); SetNativeBrush(brush); end; function TGPHatchBrush.SetHatchStyle( style : TGPHatchStyle ) : TGPHatchBrush; begin SetHatchStyleProp( style ); Result := Self; end; function TGPHatchBrush.GetHatchStyle() : TGPHatchStyle; begin ErrorCheck( GdipGetHatchStyle(GpHatch(FNativeBrush), Result)); end; procedure TGPHatchBrush.SetForegroundColorProp( color : TGPColor ); var brush: GpHatch; begin brush := NIL; ErrorCheck( GdipCreateHatchBrush( Integer( GetHatchStyle() ), color, GetBackgroundColor(), brush)); SetNativeBrush(brush); end; function TGPHatchBrush.SetForegroundColor( color : TGPColor ) : TGPHatchBrush; begin SetForegroundColorProp( color ); Result := Self; end; function TGPHatchBrush.GetForegroundColor() : TGPColor; begin ErrorCheck( GdipGetHatchForegroundColor(GpHatch(FNativeBrush), Result )); end; procedure TGPHatchBrush.SetBackgroundColorProp( color : TGPColor ); var brush: GpHatch; begin brush := NIL; ErrorCheck( GdipCreateHatchBrush( Integer( GetHatchStyle() ), GetForegroundColor(), color, brush)); SetNativeBrush(brush); end; function TGPHatchBrush.SetBackgroundColor( color : TGPColor ) : TGPHatchBrush; begin SetBackgroundColorProp( color ); Result := Self; end; function TGPHatchBrush.GetBackgroundColor() : TGPColor; begin ErrorCheck( GdipGetHatchBackgroundColor(GpHatch(FNativeBrush), Result )); end; constructor TGPImage.Create(filename: WideString; useEmbeddedColorManagement: Boolean = False); begin FNativeImage := NIL; if(useEmbeddedColorManagement) then begin ErrorCheck( GdipLoadImageFromFileICM( PWideChar(filename), FNativeImage )); end else begin ErrorCheck( GdipLoadImageFromFile( PWideChar(filename), FNativeImage )); end; end; constructor TGPImage.Create(stream: IStream; useEmbeddedColorManagement: Boolean = False); begin FNativeImage := NIL; if(useEmbeddedColorManagement) then ErrorCheck( GdipLoadImageFromStreamICM(stream, FNativeImage)) else ErrorCheck( GdipLoadImageFromStream(stream, FNativeImage)); end; class function TGPImage.FromFile(filename: WideString; useEmbeddedColorManagement: Boolean = False) : TGPImage; begin Result := TGPImage.Create( PWideChar(filename), useEmbeddedColorManagement ); end; class function TGPImage.FromStream(stream: IStream; useEmbeddedColorManagement: Boolean = False) : TGPImage; begin Result := TGPImage.Create( stream, useEmbeddedColorManagement ); end; destructor TGPImage.Destroy(); begin GdipDisposeImage(FNativeImage); end; function TGPImage.Clone: TGPImage; var cloneimage: GpImage; begin cloneimage := NIL; ErrorCheck( GdipCloneImage(FNativeImage, cloneimage)); Result := TGPImage.CreateGdiPlus(cloneimage, False); end; function TGPImage.Save(filename: WideString; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; begin ErrorCheck( GdipSaveImageToFile(FNativeImage, PWideChar(filename), @clsidEncoder, encoderParams)); Result := Self; end; function TGPImage.Save(stream: IStream; const clsidEncoder: TGUID; encoderParams: PGPEncoderParameters = NIL) : TGPImage; begin ErrorCheck( GdipSaveImageToStream(FNativeImage, stream, @clsidEncoder, encoderParams)); Result := Self; end; function TGPImage.SaveAdd(encoderParams: PGPEncoderParameters) : TGPImage; begin ErrorCheck( GdipSaveAdd(FNativeImage, encoderParams)); Result := Self; end; function TGPImage.SaveAdd(newImage: IGPImage; encoderParams: PGPEncoderParameters) : TGPImage; begin if (newImage = NIL) then ErrorCheck( InvalidParameter); ErrorCheck( GdipSaveAddImage(FNativeImage, newImage.GetNativeImage(), encoderParams)); Result := Self; end; function TGPImage.GetType() : TGPImageType; begin ErrorCheck( GdipGetImageType(FNativeImage, Result)); end; function TGPImage.GetPhysicalDimension() : TGPSizeF; begin ErrorCheck( GdipGetImageDimension(FNativeImage, Result.Width, Result.Height)); end; function TGPImage.GetBounds(out srcRect: TGPRectF; out srcUnit: TGPUnit) : TGPImage; begin ErrorCheck( GdipGetImageBounds(FNativeImage, @srcRect, srcUnit)); Result := Self; end; function TGPImage.GetWidth: Cardinal; var width: Cardinal; begin width := 0; ErrorCheck( GdipGetImageWidth(FNativeImage, width)); Result := width; end; function TGPImage.GetHeight: Cardinal; var height: Cardinal; begin height := 0; ErrorCheck( GdipGetImageHeight(FNativeImage, height)); Result := height; end; function TGPImage.GetHorizontalResolution: Single; var resolution: Single; begin resolution := 0.0; ErrorCheck( GdipGetImageHorizontalResolution(FNativeImage, resolution)); Result := resolution; end; function TGPImage.GetVerticalResolution: Single; var resolution: Single; begin resolution := 0.0; ErrorCheck( GdipGetImageVerticalResolution(FNativeImage, resolution)); Result := resolution; end; function TGPImage.GetFlags: Cardinal; var flags: Cardinal; begin flags := 0; ErrorCheck( GdipGetImageFlags(FNativeImage, flags)); Result := flags; end; function TGPImage.GetRawFormat() : TGUID; begin ErrorCheck( GdipGetImageRawFormat(FNativeImage, @Result )); end; function TGPImage.GetFormatName() : String; var AFormat : TGUID; begin AFormat := GetRawFormat(); if(( IsEqualGUID( AFormat, ImageFormatBMP )) or ( IsEqualGUID( AFormat, ImageFormatMemoryBMP ))) then Result := 'bmp' else if( IsEqualGUID( AFormat, ImageFormatEMF )) then Result := 'emf' else if( IsEqualGUID( AFormat, ImageFormatWMF )) then Result := 'wmf' else if( IsEqualGUID( AFormat, ImageFormatJPEG )) then Result := 'jpeg' else if( IsEqualGUID( AFormat, ImageFormatPNG )) then Result := 'png' else if( IsEqualGUID( AFormat, ImageFormatGIF )) then Result := 'gif' else if( IsEqualGUID( AFormat, ImageFormatEXIF )) then Result := 'exif' else if( IsEqualGUID( AFormat, ImageFormatIcon )) then Result := 'icon' end; function TGPImage.GetPixelFormat: TGPPixelFormat; begin ErrorCheck( GdipGetImagePixelFormat(FNativeImage, Result)); end; function TGPImage.GetPaletteSize: Integer; var size: Integer; begin size := 0; ErrorCheck( GdipGetImagePaletteSize(FNativeImage, size)); Result := size; end; function TGPImage.GetPalette(palette: PGPColorPalette; size: Integer) : TGPImage; begin ErrorCheck( GdipGetImagePalette(FNativeImage, palette, size)); Result := Self; end; function TGPImage.SetPalette(palette: PGPColorPalette) : TGPImage; begin ErrorCheck( GdipSetImagePalette(FNativeImage, palette)); Result := Self; end; type IGPIntAbortDispatcher = interface ['{FA84D400-A98A-46DD-9DBC-5B7BD2853B52}'] end; TGPIntAbortDispatcher = class( TInterfacedObject, IGPIntAbortDispatcher ) public OnCallback : TGPImageAbortProc; public function GPCallback() : BOOL; end; function TGPIntAbortDispatcher.GPCallback() : BOOL; begin if( Assigned( OnCallback )) then Result := OnCallback() else Result := False; end; function GLGPAbortCallback(callbackData: Pointer) : BOOL; stdcall; begin if( callbackData <> NIL ) then Result := TGPIntAbortDispatcher( callbackData ).GPCallback() else Result := False; end; function TGPImage.GetThumbnailImage(thumbWidth, thumbHeight: Cardinal; callback: TGPGetThumbnailImageAbortProc = NIL) : TGPImage; var thumbimage: GpImage; newImage: TGPImage; ADispatcher : TGPIntAbortDispatcher; ADispatcherIntf : IGPIntAbortDispatcher; begin thumbimage := NIL; ADispatcher := TGPIntAbortDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipGetImageThumbnail(FNativeImage, thumbWidth, thumbHeight, thumbimage, GLGPAbortCallback, ADispatcher )); newImage := TGPImage.CreateGdiPlus(thumbimage, False); if (newImage = NIL) then GdipDisposeImage(thumbimage); Result := newImage; end; function TGPImage.GetFrameDimensionsCount: Cardinal; begin ErrorCheck( GdipImageGetFrameDimensionsCount(FNativeImage, Result )); end; function TGPImage.GetFrameDimensionsList() : TGUIDArray; var count: Cardinal; begin ErrorCheck( GdipImageGetFrameDimensionsCount(FNativeImage, count)); SetLength( Result, count ); ErrorCheck( GdipImageGetFrameDimensionsList(FNativeImage, @Result[ 0 ], count)); end; function TGPImage.GetFrameCount(const dimensionID: TGUID) : Cardinal; var count: Cardinal; begin count := 0; ErrorCheck( GdipImageGetFrameCount(FNativeImage, @dimensionID, count)); Result := count; end; function TGPImage.SelectActiveFrame(const dimensionID: TGUID; frameIndex: Cardinal) : TGPImage; begin ErrorCheck( GdipImageSelectActiveFrame(FNativeImage, @dimensionID, frameIndex)); Result := Self; end; function TGPImage.RotateFlip(rotateFlipType: TGPRotateFlipType) : TGPImage; begin ErrorCheck( GdipImageRotateFlip(FNativeImage, rotateFlipType)); Result := Self; end; function TGPImage.GetPropertyCount() : Cardinal; begin ErrorCheck( GdipGetPropertyCount(FNativeImage, Result)); end; function TGPImage.GetPropertyIdList() : TGPPropIDArray; var numProperty: Cardinal; begin ErrorCheck( GdipGetPropertyCount(FNativeImage, numProperty )); SetLength( Result, numProperty ); ErrorCheck( GdipGetPropertyIdList(FNativeImage, numProperty, @Result[ 0 ] )); end; function TGPImage.GetPropertyItemSize(propId: PROPID) : Cardinal; var size: Cardinal; begin size := 0; ErrorCheck( GdipGetPropertyItemSize(FNativeImage, propId, size)); Result := size; end; function TGPImage.GetPropertyItem(propId: PROPID; propSize: Cardinal; buffer: PGPPropertyItem) : TGPImage; begin ErrorCheck( GdipGetPropertyItem(FNativeImage, propId, propSize, buffer)); Result := Self; end; function TGPImage.GetPropertySize(out totalBufferSize, numProperties : Cardinal) : TGPImage; begin ErrorCheck( GdipGetPropertySize(FNativeImage, totalBufferSize, numProperties)); Result := Self; end; function TGPImage.GetAllPropertyItems(totalBufferSize, numProperties: Cardinal; allItems: PGPPropertyItem) : TGPImage; begin ErrorCheck( GdipGetAllPropertyItems(FNativeImage, totalBufferSize, numProperties, allItems)); Result := Self; end; function TGPImage.RemovePropertyItem(propId: TPROPID) : TGPImage; begin ErrorCheck( GdipRemovePropertyItem(FNativeImage, propId)); Result := Self; end; function TGPImage.SetPropertyItem(const item: TGPPropertyItem) : TGPImage; begin ErrorCheck( GdipSetPropertyItem(FNativeImage, @item)); Result := Self; end; function TGPImage.GetEncoderParameterListSize(const clsidEncoder: TGUID) : Cardinal; var size: Cardinal; begin size := 0; ErrorCheck( GdipGetEncoderParameterListSize(FNativeImage, @clsidEncoder, size)); Result := size; end; function TGPImage.GetEncoderParameterList(const clsidEncoder: TGUID; size: Cardinal; buffer: PGPEncoderParameters) : TGPImage; begin ErrorCheck( GdipGetEncoderParameterList(FNativeImage, @clsidEncoder, size, buffer)); Result := Self; end; constructor TGPImage.CreateGdiPlus(nativeImage: GpImage; Dummy : Boolean); begin SetNativeImage(nativeImage); end; procedure TGPImage.SetNativeImage(nativeImage: GpImage); begin FNativeImage := nativeImage; end; function TGPImage.GetNativeImage() : GpImage; begin Result := FNativeImage; end; // TGPBitmapData constructor TGPBitmapData.Create( ABitmap : TGPBitmap ); begin inherited Create(); FBitmap := ABitmap; end; destructor TGPBitmapData.Destroy(); begin FBitmap.UnlockBits( FData ); inherited; end; function TGPBitmapData.GetWidth() : UINT; begin Result := FData.Width; end; function TGPBitmapData.GetHeight() : UINT; begin Result := FData.Height; end; function TGPBitmapData.GetStride() : Integer; begin Result := FData.Stride; end; function TGPBitmapData.GetPixelFormat() : TGPPixelFormat; begin Result := FData.PixelFormat; end; function TGPBitmapData.GetScan0() : Pointer; begin Result := FData.Scan0; end; // TGPBitmap constructor TGPBitmap.Create(filename: WideString; useEmbeddedColorManagement: Boolean = False); var bitmap: GpBitmap; begin bitmap := NIL; if(useEmbeddedColorManagement) then ErrorCheck( GdipCreateBitmapFromFileICM(PWideChar(filename), bitmap)) else ErrorCheck( GdipCreateBitmapFromFile(PWideChar(filename), bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.Create(stream: IStream; useEmbeddedColorManagement: Boolean = False); var bitmap: GpBitmap; begin bitmap := NIL; if(useEmbeddedColorManagement) then ErrorCheck( GdipCreateBitmapFromStreamICM(stream, bitmap)) else ErrorCheck( GdipCreateBitmapFromStream(stream, bitmap)); SetNativeImage(bitmap); end; {$IFNDEF PURE_FMX} constructor TGPBitmap.Create( ABitmap : TBitmap ); begin CreateHBitmap( ABitmap.Handle, ABitmap.Palette ); end; constructor TGPBitmap.Create( AIcon : TIcon ); begin CreateHICON( AIcon.Handle ); end; {$ENDIF} class function TGPBitmap.FromFile(filename: WideString; useEmbeddedColorManagement: Boolean = False) : TGPBitmap; begin Result := TGPBitmap.Create( PWideChar(filename), useEmbeddedColorManagement ); end; class function TGPBitmap.FromStream(stream: IStream; useEmbeddedColorManagement: Boolean = False) : TGPBitmap; begin Result := TGPBitmap.Create( stream, useEmbeddedColorManagement ); end; constructor TGPBitmap.Create(width, height, stride: Integer; format: TGPPixelFormat; scan0: PBYTE); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromScan0(width, height, stride, format, scan0, bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.Create(width, height: Integer; format: TGPPixelFormat = PixelFormat32bppARGB); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromScan0(width, height, 0, format, NIL, bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.Create(width, height: Integer; target: TGPGraphics); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromGraphics(width, height, target.FNativeGraphics, bitmap)); SetNativeImage(bitmap); end; function TGPBitmap.Clone(rect: TGPRect; format: TGPPixelFormat) : TGPBitmap; begin Result := Clone(rect.X, rect.Y, rect.Width, rect.Height, format); end; function TGPBitmap.Clone(x, y, width, height: Integer; format: TGPPixelFormat) : TGPBitmap; var bitmap: TGPBitmap; gpdstBitmap: GpBitmap; begin gpdstBitmap := NIL; ErrorCheck( GdipCloneBitmapAreaI( x, y, width, height, format, GpBitmap(FNativeImage), gpdstBitmap)); bitmap := TGPBitmap.CreateGdiPlus(gpdstBitmap, False); if (bitmap = NIL) then GdipDisposeImage(gpdstBitmap); Result := bitmap; end; function TGPBitmap.CloneF(rect: TGPRectF; format: TGPPixelFormat) : TGPBitmap; begin Result := CloneF(rect.X, rect.Y, rect.Width, rect.Height, format); end; function TGPBitmap.CloneF(x, y, width, height: Single; format: TGPPixelFormat) : TGPBitmap; var gpdstBitmap: GpBitmap; begin gpdstBitmap := NIL; ErrorCheck( GdipCloneBitmapArea( x, y, width, height, format, GpBitmap(FNativeImage), gpdstBitmap)); Result := TGPBitmap.CreateGdiPlus(gpdstBitmap, False); if (Result = NIL) then GdipDisposeImage(gpdstBitmap); end; procedure TGPBitmap.LockBitsInternal(rect: TGPRect; flags: Cardinal; format: TGPPixelFormat; var AData : TGPBitmapDataRecord ); begin ErrorCheck( GdipBitmapLockBits( GpBitmap(FNativeImage), @rect, flags, format, @AData)); end; function TGPBitmap.UnlockBits(var lockedBitmapData: TGPBitmapDataRecord) : TGPBitmap; begin ErrorCheck( GdipBitmapUnlockBits( GpBitmap(FNativeImage), @lockedBitmapData)); Result := Self; end; function TGPBitmap.LockBits( rect: TGPRect; flags: Cardinal; format: TGPPixelFormat ) : IGPBitmapData; var ABitmapData : TGPBitmapData; begin ABitmapData := TGPBitmapData.Create( Self ); LockBitsInternal(rect, flags, format, ABitmapData.FData ); Result := ABitmapData; end; function TGPBitmap.GetPixel(x, y: Integer) : TGPColor; begin ErrorCheck( GdipBitmapGetPixel(GpBitmap(FNativeImage), x, y, Result )); end; function TGPBitmap.SetPixel(x, y: Integer; color: TGPColor) : TGPBitmap; begin ErrorCheck( GdipBitmapSetPixel( GpBitmap(FNativeImage), x, y, color)); Result := Self; end; procedure TGPBitmap.SetPixelProp(x, y: Integer; color: TGPColor); begin ErrorCheck( GdipBitmapSetPixel( GpBitmap(FNativeImage), x, y, color)); end; function TGPBitmap.SetResolution(xdpi, ydpi: Single) : TGPBitmap; begin ErrorCheck( GdipBitmapSetResolution( GpBitmap(FNativeImage), xdpi, ydpi)); Result := Self; end; { constructor TGPBitmap.Create(surface: IDirectDrawSurface7); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromDirectDrawSurface(surface, bitmap)); SetNativeImage(bitmap); end; } constructor TGPBitmap.CreateData(var gdiBitmapInfo: TBITMAPINFO; gdiBitmapData: Pointer); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromGdiDib(@gdiBitmapInfo, gdiBitmapData, bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.CreateHBITMAP(hbm: HBITMAP; hpal: HPALETTE); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromHBITMAP(hbm, hpal, bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.CreateHICON(hicon: HICON); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromHICON(hicon, bitmap)); SetNativeImage(bitmap); end; constructor TGPBitmap.CreateRes(hInstance: HMODULE; bitmapName: WideString); var bitmap: GpBitmap; begin bitmap := NIL; ErrorCheck( GdipCreateBitmapFromResource(hInstance, PWideChar(bitmapName), bitmap)); SetNativeImage(bitmap); end; { class function TGPBitmap.FromDirectDrawSurface7(surface: IDirectDrawSurface7) : TGPBitmap; begin Result := TGPBitmap.Create(surface); end; } class function TGPBitmap.FromBITMAPINFO(var gdiBitmapInfo: TBITMAPINFO; gdiBitmapData: Pointer) : TGPBitmap; begin Result := TGPBitmap.CreateData(gdiBitmapInfo, gdiBitmapData); end; class function TGPBitmap.FromHBITMAP(hbm: HBITMAP; hpal: HPALETTE) : TGPBitmap; begin Result := TGPBitmap.CreateHBitmap(hbm, hpal); end; class function TGPBitmap.FromHICON(hicon: HICON) : TGPBitmap; begin Result := TGPBitmap.CreateHIcon(hicon); end; class function TGPBitmap.FromResource(hInstance: HMODULE; bitmapName: WideString) : TGPBitmap; begin Result := TGPBitmap.CreateRes(hInstance, PWideChar(bitmapName)); end; function TGPBitmap.GetHBITMAP( colorBackground: TGPColor ) : HBITMAP; begin ErrorCheck( GdipCreateHBITMAPFromBitmap( GpBitmap(FNativeImage), Result, colorBackground)); end; function TGPBitmap.GetHICON() : HICON; begin ErrorCheck( GdipCreateHICONFromBitmap( GpBitmap(FNativeImage), Result )); end; constructor TGPBitmap.CreateGdiPlus(nativeBitmap: GpBitmap; Dummy : Boolean ); begin SetNativeImage(nativeBitmap); end; (**************************************************************************\ * * GDI+ Graphics Object * \**************************************************************************) {$IFNDEF PURE_FMX} class function TGPGraphics.FromCanvas( canvas : TCanvas ) : TGPGraphics; begin Result := TGPGraphics.Create(canvas); end; {$ENDIF} class function TGPGraphics.FromHDC(ahdc: HDC) : TGPGraphics; begin Result := TGPGraphics.Create(ahdc); end; class function TGPGraphics.FromHDC(ahdc: HDC; hdevice: THandle) : TGPGraphics; begin Result := TGPGraphics.Create(ahdc, hdevice); end; class function TGPGraphics.FromHWND(hwnd: HWND; icm: Boolean = False) : TGPGraphics; begin Result := TGPGraphics.Create(hwnd, icm); end; class function TGPGraphics.FromImage(image: IGPImage) : TGPGraphics; begin Result := TGPGraphics.Create(image); end; {$IFNDEF PURE_FMX} constructor TGPGraphics.Create( canvas : TCanvas ); var graphics: GpGraphics; begin graphics:= NIL; ErrorCheck( GdipCreateFromHDC( canvas.Handle, graphics)); SetNativeGraphics(graphics); end; {$ENDIF} constructor TGPGraphics.Create( ahdc : HDC ); var graphics: GpGraphics; begin graphics:= NIL; ErrorCheck( GdipCreateFromHDC( ahdc, graphics)); SetNativeGraphics(graphics); end; constructor TGPGraphics.Create( ahdc : HDC; hdevice: THandle ); var graphics: GpGraphics; begin graphics:= NIL; ErrorCheck( GdipCreateFromHDC2( ahdc, hdevice, graphics)); SetNativeGraphics(graphics); end; constructor TGPGraphics.Create(hwnd: HWND; icm: Boolean{ = False}); var graphics: GpGraphics; begin graphics:= NIL; if( icm ) then ErrorCheck( GdipCreateFromHWNDICM(hwnd, graphics)) else ErrorCheck( GdipCreateFromHWND(hwnd, graphics)); SetNativeGraphics(graphics); end; constructor TGPGraphics.Create(image: IGPImage); var graphics: GpGraphics; begin graphics:= NIL; if (image <> NIL) then ErrorCheck( GdipGetImageGraphicsContext(image.GetNativeImage(), graphics)); SetNativeGraphics(graphics); end; destructor TGPGraphics.Destroy(); begin GdipDeleteGraphics(FNativeGraphics); end; function TGPGraphics.Flush(intention: TGPFlushIntention = FlushIntentionFlush) : TGPGraphics; begin ErrorCheck( GdipFlush(FNativeGraphics, intention)); Result := Self; end; //------------------------------------------------------------------------ // GDI Interop methods //------------------------------------------------------------------------ // Locks the graphics until ReleaseDC is called function TGPGraphics.GetHDC() : HDC; begin ErrorCheck( GdipGetDC(FNativeGraphics, Result)); end; function TGPGraphics.ReleaseHDC(ahdc: HDC) : TGPGraphics; begin ErrorCheck( GdipReleaseDC(FNativeGraphics, ahdc)); Result := Self; end; //------------------------------------------------------------------------ // Rendering modes //------------------------------------------------------------------------ function TGPGraphics.SetRenderingOrigin( point : TGPPoint ) : TGPGraphics; begin ErrorCheck( GdipSetRenderingOrigin(FNativeGraphics, point.X, point.Y )); Result := Self; end; procedure TGPGraphics.SetRenderingOriginProp( point : TGPPoint ); begin ErrorCheck( GdipSetRenderingOrigin(FNativeGraphics, point.X, point.Y )); end; function TGPGraphics.GetRenderingOrigin() : TGPPoint; begin ErrorCheck( GdipGetRenderingOrigin(FNativeGraphics, Result.X, Result.Y )); end; function TGPGraphics.SetCompositingMode(compositingMode: TGPCompositingMode) : TGPGraphics; begin ErrorCheck( GdipSetCompositingMode(FNativeGraphics, compositingMode)); Result := Self; end; procedure TGPGraphics.SetCompositingModeProp(compositingMode: TGPCompositingMode); begin ErrorCheck( GdipSetCompositingMode(FNativeGraphics, compositingMode)); end; function TGPGraphics.GetCompositingMode() : TGPCompositingMode; begin ErrorCheck( GdipGetCompositingMode(FNativeGraphics, Result)); end; function TGPGraphics.SetCompositingQuality(compositingQuality: TGPCompositingQuality) : TGPGraphics; begin ErrorCheck( GdipSetCompositingQuality( FNativeGraphics, compositingQuality)); Result := Self; end; procedure TGPGraphics.SetCompositingQualityProp(compositingQuality: TGPCompositingQuality); begin ErrorCheck( GdipSetCompositingQuality( FNativeGraphics, compositingQuality)); end; function TGPGraphics.GetCompositingQuality() : TGPCompositingQuality; begin ErrorCheck( GdipGetCompositingQuality(FNativeGraphics, Result)); end; function TGPGraphics.SetTextRenderingHint(newMode: TGPTextRenderingHint) : TGPGraphics; begin ErrorCheck( GdipSetTextRenderingHint(FNativeGraphics, newMode)); Result := Self; end; procedure TGPGraphics.SetTextRenderingHintProp(newMode: TGPTextRenderingHint); begin ErrorCheck( GdipSetTextRenderingHint(FNativeGraphics, newMode)); end; function TGPGraphics.GetTextRenderingHint() : TGPTextRenderingHint; begin ErrorCheck( GdipGetTextRenderingHint(FNativeGraphics, Result)); end; function TGPGraphics.SetTextContrast(contrast: Cardinal) : TGPGraphics; begin ErrorCheck( GdipSetTextContrast(FNativeGraphics, contrast)); Result := Self; end; procedure TGPGraphics.SetTextContrastProp(contrast: Cardinal); // 0..12 begin ErrorCheck( GdipSetTextContrast(FNativeGraphics, contrast)); end; function TGPGraphics.GetTextContrast() : Cardinal; begin ErrorCheck( GdipGetTextContrast(FNativeGraphics, Result)); end; function TGPGraphics.GetInterpolationMode() : TGPInterpolationMode; begin Result := InterpolationModeInvalid; ErrorCheck( GdipGetInterpolationMode(FNativeGraphics, Result )); end; function TGPGraphics.SetInterpolationMode(interpolationMode: TGPInterpolationMode) : TGPGraphics; begin ErrorCheck( GdipSetInterpolationMode(FNativeGraphics, interpolationMode)); Result := Self; end; procedure TGPGraphics.SetInterpolationModeProp(interpolationMode: TGPInterpolationMode); begin ErrorCheck( GdipSetInterpolationMode(FNativeGraphics, interpolationMode)); end; function TGPGraphics.GetSmoothingMode() : TGPSmoothingMode; begin Result := SmoothingModeInvalid; ErrorCheck( GdipGetSmoothingMode(FNativeGraphics, Result )); end; function TGPGraphics.SetSmoothingMode(smoothingMode: TGPSmoothingMode) : TGPGraphics; begin ErrorCheck( GdipSetSmoothingMode(FNativeGraphics, smoothingMode)); Result := Self; end; procedure TGPGraphics.SetSmoothingModeProp(smoothingMode: TGPSmoothingMode); begin ErrorCheck( GdipSetSmoothingMode(FNativeGraphics, smoothingMode)); end; function TGPGraphics.GetPixelOffsetMode() : TGPPixelOffsetMode; begin Result := PixelOffsetModeInvalid; ErrorCheck( GdipGetPixelOffsetMode(FNativeGraphics, Result )); end; function TGPGraphics.SetPixelOffsetMode(pixelOffsetMode: TGPPixelOffsetMode) : TGPGraphics; begin ErrorCheck( GdipSetPixelOffsetMode(FNativeGraphics, pixelOffsetMode)); Result := Self; end; procedure TGPGraphics.SetPixelOffsetModeProp(pixelOffsetMode: TGPPixelOffsetMode); begin ErrorCheck( GdipSetPixelOffsetMode(FNativeGraphics, pixelOffsetMode)); end; //------------------------------------------------------------------------ // Manipulate current world transform //------------------------------------------------------------------------ function TGPGraphics.SetTransform(matrix: IGPMatrix) : TGPGraphics; begin ErrorCheck( GdipSetWorldTransform(FNativeGraphics, matrix.GetNativeMatrix())); Result := Self; end; procedure TGPGraphics.SetTransformProp(matrix: IGPMatrix); begin ErrorCheck( GdipSetWorldTransform(FNativeGraphics, matrix.GetNativeMatrix())); end; function TGPGraphics.ResetTransform() : TGPGraphics; begin ErrorCheck( GdipResetWorldTransform(FNativeGraphics)); Result := Self; end; function TGPGraphics.MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; begin ErrorCheck( GdipMultiplyWorldTransform(FNativeGraphics, matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPGraphics.TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; begin ErrorCheck( GdipTranslateWorldTransform(FNativeGraphics, dx, dy, order)); Result := Self; end; function TGPGraphics.ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; begin ErrorCheck( GdipScaleWorldTransform(FNativeGraphics, sx, sy, order)); Result := Self; end; function TGPGraphics.RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPGraphics; begin ErrorCheck( GdipRotateWorldTransform(FNativeGraphics, angle, order)); Result := Self; end; function TGPGraphics.GetTransform() : IGPMatrix; begin Result := TGPMatrix.Create(); ErrorCheck( GdipGetWorldTransform(FNativeGraphics, Result.GetNativeMatrix())); end; function TGPGraphics.SetTransformT(matrix: IGPMatrix) : IGPTransformable; begin ErrorCheck( GdipSetWorldTransform(FNativeGraphics, matrix.GetNativeMatrix())); Result := Self; end; function TGPGraphics.ResetTransformT() : IGPTransformable; begin ErrorCheck( GdipResetWorldTransform(FNativeGraphics)); Result := Self; end; function TGPGraphics.MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipMultiplyWorldTransform(FNativeGraphics, matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPGraphics.TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipTranslateWorldTransform(FNativeGraphics, dx, dy, order)); Result := Self; end; function TGPGraphics.ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipScaleWorldTransform(FNativeGraphics, sx, sy, order)); Result := Self; end; function TGPGraphics.RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipRotateWorldTransform(FNativeGraphics, angle, order)); Result := Self; end; function TGPGraphics.SetPageUnit(unit_: TGPUnit) : TGPGraphics; begin ErrorCheck( GdipSetPageUnit(FNativeGraphics, unit_)); Result := Self; end; procedure TGPGraphics.SetPageUnitProp(unit_: TGPUnit); begin ErrorCheck( GdipSetPageUnit(FNativeGraphics, unit_)); end; function TGPGraphics.SetPageScale(scale: Single) : TGPGraphics; begin ErrorCheck( GdipSetPageScale(FNativeGraphics, scale)); Result := Self; end; procedure TGPGraphics.SetPageScaleProp(scale: Single); begin ErrorCheck( GdipSetPageScale(FNativeGraphics, scale)); end; function TGPGraphics.GetPageUnit() : TGPUnit; begin ErrorCheck( GdipGetPageUnit(FNativeGraphics, Result)); end; function TGPGraphics.GetPageScale() : Single; begin ErrorCheck( GdipGetPageScale(FNativeGraphics, Result)); end; function TGPGraphics.GetDpiX() : Single; begin ErrorCheck( GdipGetDpiX(FNativeGraphics, Result)); end; function TGPGraphics.GetDpiY() : Single; begin ErrorCheck( GdipGetDpiY(FNativeGraphics, Result)); end; function TGPGraphics.TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPointF ) : TGPGraphics; begin ErrorCheck( GdipTransformPoints(FNativeGraphics, destSpace, srcSpace, @pts[ 0 ], Length( pts ))); Result := Self; end; function TGPGraphics.TransformPoints(destSpace: TGPCoordinateSpace; srcSpace: TGPCoordinateSpace; var pts : array of TGPPoint ) : TGPGraphics; begin ErrorCheck( GdipTransformPointsI(FNativeGraphics, destSpace, srcSpace, @pts[ 0 ], Length( pts ))); Result := Self; end; //------------------------------------------------------------------------ // GetNearestColor (for <= 8bpp surfaces). Note: Alpha is ignored. //------------------------------------------------------------------------ function TGPGraphics.GetNearestColor( AColor : TGPColor ) : TGPColor; begin ErrorCheck( GdipGetNearestColor(FNativeGraphics, @AColor )); Result := AColor; end; function TGPGraphics.DrawLineF( pen: IGPPen; x1, y1, x2, y2: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawLine(FNativeGraphics, pen.GetNativePen(), x1, y1, x2, y2)); Result := Self; end; function TGPGraphics.DrawLineF( pen: IGPPen; const pt1, pt2: TGPPointF) : TGPGraphics; begin Result := DrawLineF(pen, pt1.X, pt1.Y, pt2.X, pt2.Y); end; function TGPGraphics.DrawLinesF( pen: IGPPen; points : array of TGPPointF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawLines(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawLine( pen: IGPPen; x1, y1, x2, y2: Integer) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawLineI(FNativeGraphics, pen.GetNativePen(), x1, y1, x2, y2)); Result := Self; end; function TGPGraphics.DrawLine( pen: IGPPen; const pt1, pt2: TGPPoint) : TGPGraphics; begin Result := DrawLine( pen, pt1.X, pt1.Y, pt2.X, pt2.Y ); end; function TGPGraphics.DrawLines( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawLinesI(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawArcF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawArc(FNativeGraphics, pen.GetNativePen(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.DrawArcF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single ) : TGPGraphics; begin Result := DrawArcF( pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle ); end; function TGPGraphics.DrawArc( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawArcI(FNativeGraphics, pen.GetNativePen(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.DrawArc( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single ) : TGPGraphics; begin Result := DrawArc(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle ); end; function TGPGraphics.DrawBezierF( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawBezier(FNativeGraphics, pen.GetNativePen(), x1, y1, x2, y2, x3, y3, x4, y4)); Result := Self; end; function TGPGraphics.DrawBezierF( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphics; begin Result := DrawBezierF(pen, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); end; function TGPGraphics.DrawBeziersF( pen: IGPPen; points : array of TGPPointF ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawBeziers(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawBezier( pen: IGPPen; x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawBezierI(FNativeGraphics, pen.GetNativePen(), x1, y1, x2, y2, x3, y3, x4, y4)); Result := Self; end; function TGPGraphics.DrawBezier( pen: IGPPen; const pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphics; begin Result := DrawBezier(pen, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); end; function TGPGraphics.DrawBeziers( pen: IGPPen; points : array of TGPPoint ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawBeziersI(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawRectangleF( pen: IGPPen; rect: TGPRectF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( rect.Width < 0 ) then begin rect.Width := -rect.Width; rect.X := rect.X - rect.Width; end; if( rect.Height < 0 ) then begin rect.Height := -rect.Height; rect.Y := rect.Y - rect.Height; end; Result := DrawRectangleF(pen, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawRectangleF( pen: IGPPen; x, y, width, height: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( width < 0 ) then begin Width := -width; x := x - width; end; if( height < 0 ) then begin Height := -height; y := y - height; end; ErrorCheck( GdipDrawRectangle(FNativeGraphics, pen.GetNativePen(), x, y, width, height)); Result := Self; end; function TGPGraphics.DrawRectanglesF( pen: IGPPen; rects: array of TGPRectF ) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawRectangles(FNativeGraphics, pen.GetNativePen(), @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphics.DrawRectangle( pen: IGPPen; rect: TGPRect) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( rect.Width < 0 ) then begin rect.Width := -rect.Width; Dec( rect.X, rect.Width ); end; if( rect.Height < 0 ) then begin rect.Height := -rect.Height; Dec( rect.Y, rect.Height ); end; Result := DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawRectangle( pen: IGPPen; x, y, width, height: Integer) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( width < 0 ) then begin width := -width; Dec( x, width ); end; if( height < 0 ) then begin height := -height; Dec( y, height ); end; ErrorCheck( GdipDrawRectangleI(FNativeGraphics, pen.GetNativePen(), x, y, width, height)); Result := Self; end; function TGPGraphics.DrawRectangles( pen: IGPPen; rects: array of TGPRect) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawRectanglesI(FNativeGraphics, pen.GetNativePen(), @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphics.DrawRectangleF( pen: IGPPen; brush: IGPBrush; rect: TGPRectF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( brush = NIL ) then ErrorCheck( InvalidParameter ); if( rect.Width < 0 ) then begin rect.Width := -rect.Width; rect.X := rect.X - rect.Width; end; if( rect.Height < 0 ) then begin rect.Height := -rect.Height; rect.Y := rect.Y - rect.Height; end; FillRectangleF( brush, rect ); Result := DrawRectangleF( pen, rect ); end; function TGPGraphics.DrawRectangleF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( brush = NIL ) then ErrorCheck( InvalidParameter ); if( width < 0 ) then begin Width := -width; x := x - width; end; if( height < 0 ) then begin Height := -height; y := y - height; end; FillRectangleF( brush, x, y, width, height ); Result := DrawRectangleF( pen, x, y, width, height ); end; function TGPGraphics.DrawRectanglesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF ) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do begin FillRectangleF( brush, rects[ I ] ); DrawRectangleF( pen, rects[ I ] ); end; Result := Self; end; function TGPGraphics.DrawRectangle( pen: IGPPen; brush: IGPBrush; rect: TGPRect) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( brush = NIL ) then ErrorCheck( InvalidParameter ); if( rect.Width < 0 ) then begin rect.Width := -rect.Width; Dec( rect.X, rect.Width ); end; if( rect.Height < 0 ) then begin rect.Height := -rect.Height; Dec( rect.Y, rect.Height ); end; FillRectangle( brush, rect ); Result := DrawRectangle( pen, rect ); end; function TGPGraphics.DrawRectangle( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); if( brush = NIL ) then ErrorCheck( InvalidParameter ); if( width < 0 ) then begin Width := -width; Dec( x, width ); end; if( height < 0 ) then begin Height := -height; Dec( y, height ); end; FillRectangle( brush, x, y, width, height ); Result := DrawRectangle( pen, x, y, width, height ); end; function TGPGraphics.DrawRectangles( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do begin FillRectangle( brush, rects[ I ] ); DrawRectangle( pen, rects[ I ] ); end; Result := Self; end; function TGPGraphics.DrawRoundRectangleF( pen: IGPPen; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; begin Result := DrawPath( pen, TGPGraphicsPath.Create().AddRoundRectangleF( rect, ACornerSize )); end; function TGPGraphics.DrawRoundRectangle( pen: IGPPen; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; begin Result := DrawPath( pen, TGPGraphicsPath.Create().AddRoundRectangle( rect, ACornerSize )); end; function TGPGraphics.DrawRoundRectangleF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; begin Result := DrawPath( pen, brush, TGPGraphicsPath.Create().AddRoundRectangleF( rect, ACornerSize )); end; function TGPGraphics.DrawRoundRectangle( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; begin Result := DrawPath( pen, brush, TGPGraphicsPath.Create().AddRoundRectangle( rect, ACornerSize )); end; function TGPGraphics.DrawEllipseF( pen: IGPPen; const rect: TGPRectF) : TGPGraphics; begin Result := DrawEllipseF( pen, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawEllipseF( pen: IGPPen; x, y, width, height: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawEllipse(FNativeGraphics, pen.GetNativePen(), x, y, width, height)); Result := Self; end; function TGPGraphics.DrawEllipsesF( pen: IGPPen; rects: array of TGPRectF) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do DrawEllipseF( pen, rects[ I ] ); Result := Self; end; function TGPGraphics.DrawEllipse( pen: IGPPen; const rect: TGPRect) : TGPGraphics; begin Result := DrawEllipse( pen, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawEllipse( pen: IGPPen; x, y, width, height: Integer) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawEllipseI(FNativeGraphics, pen.GetNativePen(), x, y, width, height)); Result := Self; end; function TGPGraphics.DrawEllipses( pen: IGPPen; rects: array of TGPRect) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do DrawEllipse( pen, rects[ I ] ); Result := Self; end; function TGPGraphics.DrawEllipseF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; begin FillEllipseF( brush, rect ); Result := DrawEllipseF( pen, rect ); end; function TGPGraphics.DrawEllipseF( pen: IGPPen; brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; begin FillEllipseF( brush, x, y, width, height ); Result := DrawEllipseF( pen, x, y, width, height ); end; function TGPGraphics.DrawEllipsesF( pen: IGPPen; brush: IGPBrush; rects: array of TGPRectF) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do begin FillEllipseF( brush, rects[ I ] ); DrawEllipseF( pen, rects[ I ] ); end; Result := Self; end; function TGPGraphics.DrawEllipse( pen: IGPPen; brush: IGPBrush; const rect: TGPRect) : TGPGraphics; begin FillEllipse( brush, rect ); Result := DrawEllipse( pen, rect ); end; function TGPGraphics.DrawEllipse( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; begin FillEllipse( brush, x, y, width, height ); Result := DrawEllipse( pen, x, y, width, height ); end; function TGPGraphics.DrawEllipses( pen: IGPPen; brush: IGPBrush; rects: array of TGPRect) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do begin FillEllipse( brush, rects[ I ] ); DrawEllipse( pen, rects[ I ] ); end; Result := Self; end; function TGPGraphics.DrawPieF( pen: IGPPen; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; begin Result := DrawPieF( pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle ); end; function TGPGraphics.DrawPieF( pen: IGPPen; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawPie(FNativeGraphics, pen.GetNativePen(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.DrawPie( pen: IGPPen; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; begin Result := DrawPie( pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle ); end; function TGPGraphics.DrawPie( pen: IGPPen; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawPieI(FNativeGraphics, pen.GetNativePen(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.DrawPieF( pen: IGPPen; brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; begin FillPieF( brush, rect, startAngle, sweepAngle ); Result := DrawPieF( pen, rect, startAngle, sweepAngle ); end; function TGPGraphics.DrawPieF( pen: IGPPen; brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphics; begin FillPieF( brush, x, y, width, height, startAngle, sweepAngle ); Result := DrawPieF( pen, x, y, width, height, startAngle, sweepAngle ); end; function TGPGraphics.DrawPie( pen: IGPPen; brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphics; begin FillPie( brush, rect, startAngle, sweepAngle ); Result := DrawPie( pen, rect, startAngle, sweepAngle ); end; function TGPGraphics.DrawPie( pen: IGPPen; brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; begin FillPie( brush, x, y, width, height, startAngle, sweepAngle ); Result := DrawPie( pen, x, y, width, height, startAngle, sweepAngle ); end; function TGPGraphics.DrawPolygonF( pen: IGPPen; points: array of TGPPointF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawPolygon(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawPolygon( pen: IGPPen; points: array of TGPPoint) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawPolygonI(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; begin FillPolygonF( brush, points ); Result := DrawPolygonF( pen, points ); end; function TGPGraphics.DrawPolygonF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode) : TGPGraphics; begin FillPolygonF( brush, points, fillMode ); Result := DrawPolygonF( pen, points ); end; function TGPGraphics.DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; begin FillPolygon( brush, points ); Result := DrawPolygon( pen, points ); end; function TGPGraphics.DrawPolygon( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode) : TGPGraphics; begin FillPolygon( brush, points, fillMode ); Result := DrawPolygon( pen, points ); end; function TGPGraphics.DrawPath( pen: IGPPen; path: IGPGraphicsPath) : TGPGraphics; var nPen: GpPen; nPath: GpPath; begin if( Assigned(pen) ) then nPen := pen.GetNativePen() else nPen := NIL; if( Assigned(path) ) then nPath := path.GetNativePath() else nPath := NIL; ErrorCheck( GdipDrawPath(FNativeGraphics, nPen, nPath)); Result := Self; end; function TGPGraphics.DrawPath( pen: IGPPen; brush: IGPBrush; path: IGPGraphicsPath) : TGPGraphics; begin FillPath( brush, path ); Result := DrawPath( pen, path ); end; function TGPGraphics.DrawCurveF( pen: IGPPen; points: array of TGPPointF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurve(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurve2(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphics.DrawCurveF( pen: IGPPen; points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurve3(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), offset, numberOfSegments, tension)); Result := Self; end; function TGPGraphics.DrawCurve( pen: IGPPen; points: array of TGPPoint) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurveI(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawCurve( pen: IGPPen; points: array of TGPPoint; tension: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurve2I(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphics.DrawCurve( pen: IGPPen; points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single = 0.5) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawCurve3I(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), offset, numberOfSegments, tension)); Result := Self; end; function TGPGraphics.DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawClosedCurve(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawClosedCurveF( pen: IGPPen; points: array of TGPPointF; tension: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawClosedCurve2(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphics.DrawClosedCurve( pen: IGPPen; points: array of TGPPoint) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawClosedCurveI(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.DrawClosedCurve( pen: IGPPen; points: array of TGPPoint; tension: Single) : TGPGraphics; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipDrawClosedCurve2I(FNativeGraphics, pen.GetNativePen(), @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphics.DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; begin FillClosedCurveF( brush, points ); Result := DrawClosedCurveF( pen, points ); end; function TGPGraphics.DrawClosedCurveF( pen: IGPPen; brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; begin FillClosedCurveF( brush, points, fillMode, tension ); Result := DrawClosedCurveF( pen, points, tension ); end; function TGPGraphics.DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint ) : TGPGraphics; begin FillClosedCurve( brush, points ); Result := DrawClosedCurve( pen, points ); end; function TGPGraphics.DrawClosedCurve( pen: IGPPen; brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; begin FillClosedCurve( brush, points, fillMode, tension ); Result := DrawClosedCurve( pen, points, tension ); end; function TGPGraphics.Clear(color: TGPColor) : TGPGraphics; begin ErrorCheck( GdipGraphicsClear( FNativeGraphics, color)); Result := Self; end; function TGPGraphics.FillRectangleF(brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; begin Result := FillRectangleF(brush, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.FillRectangleF(brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillRectangle(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height)); Result := Self; end; function TGPGraphics.FillRectanglesF(brush: IGPBrush; rects: array of TGPRectF) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillRectangles(FNativeGraphics, brush.GetNativeBrush(), @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphics.FillRectangle(brush: IGPBrush; const rect: TGPRect) : TGPGraphics; begin Result := FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.FillRectangle(brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillRectangleI(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height)); Result := Self; end; function TGPGraphics.FillRectangles(brush: IGPBrush; rects: array of TGPRect) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillRectanglesI(FNativeGraphics, brush.GetNativeBrush(), @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphics.FillRoundRectangleF(brush: IGPBrush; const rect: TGPRectF; ACornerSize : TGPSizeF) : TGPGraphics; begin Result := FillPath( brush, TGPGraphicsPath.Create().AddRoundRectangleF( rect, ACornerSize )); end; function TGPGraphics.FillRoundRectangle(brush: IGPBrush; const rect: TGPRect; ACornerSize : TGPSize) : TGPGraphics; begin Result := FillPath( brush, TGPGraphicsPath.Create().AddRoundRectangle( rect, ACornerSize )); end; function TGPGraphics.FillPolygonF(brush: IGPBrush; points: array of TGPPointF) : TGPGraphics; begin Result := FillPolygonF(brush, points, FillModeAlternate); end; function TGPGraphics.FillPolygonF(brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillPolygon(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ), fillMode)); Result := Self; end; function TGPGraphics.FillPolygon(brush: IGPBrush; points: array of TGPPoint) : TGPGraphics; begin Result := FillPolygon(brush, points, FillModeAlternate); end; function TGPGraphics.FillPolygon(brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillPolygonI(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ), fillMode)); Result := Self; end; function TGPGraphics.FillEllipseF(brush: IGPBrush; const rect: TGPRectF) : TGPGraphics; begin Result := FillEllipseF(brush, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.FillEllipseF(brush: IGPBrush; x, y, width, height: Single) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillEllipse(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height)); Result := Self; end; function TGPGraphics.FillEllipsesF(brush: IGPBrush; rects: array of TGPRectF) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do FillEllipseF( brush, rects[ I ] ); Result := Self; end; function TGPGraphics.FillEllipse(brush: IGPBrush; const rect: TGPRect) : TGPGraphics; begin Result := FillEllipse(brush, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.FillEllipse(brush: IGPBrush; x, y, width, height: Integer) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillEllipseI(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height)); Result := Self; end; function TGPGraphics.FillEllipses(brush: IGPBrush; rects: array of TGPRect ) : TGPGraphics; var I : Integer; begin for I := 0 to Length( rects ) - 1 do FillEllipse( brush, rects[ I ] ); Result := Self; end; function TGPGraphics.FillPieF(brush: IGPBrush; const rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphics; begin Result := FillPieF(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); end; function TGPGraphics.FillPieF( brush: IGPBrush; x, y, width, height, startAngle, sweepAngle: Single ) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillPie(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.FillPie( brush: IGPBrush; const rect: TGPRect; startAngle, sweepAngle: Single ) : TGPGraphics; begin Result := FillPie( brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle ); end; function TGPGraphics.FillPie(brush: IGPBrush; x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillPieI(FNativeGraphics, brush.GetNativeBrush(), x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphics.FillPath( brush: IGPBrush; path: IGPGraphicsPath ) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillPath(FNativeGraphics, brush.GetNativeBrush(), path.GetNativePath())); Result := Self; end; function TGPGraphics.FillClosedCurveF( brush: IGPBrush; points: array of TGPPointF ) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillClosedCurve(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.FillClosedCurveF(brush: IGPBrush; points: array of TGPPointF; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillClosedCurve2(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ), tension, fillMode)); Result := Self; end; function TGPGraphics.FillClosedCurve(brush: IGPBrush; points: array of TGPPoint) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillClosedCurveI(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphics.FillClosedCurve(brush: IGPBrush; points: array of TGPPoint; fillMode: TGPFillMode; tension: Single = 0.5) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillClosedCurve2I(FNativeGraphics, brush.GetNativeBrush(), @points[ 0 ], Length( points ), tension, fillMode)); Result := Self; end; function TGPGraphics.FillRegion(brush: IGPBrush; region: IGPRegion) : TGPGraphics; begin if( brush = NIL ) then ErrorCheck( InvalidParameter ); ErrorCheck( GdipFillRegion(FNativeGraphics, brush.GetNativeBrush(), region.GetNativeRegion() )); Result := Self; end; (* function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: TGPStringFormat; pen: IGPPen) : TGPGraphics; var APath : IGPGraphicsPath; AOldUnit : TGPUnit; begin APath := TGPGraphicsPath.Create(); APath.StartFigure(); APath.AddString( string_, font.GetFamily(), font.GetStyle(), font.GetSize(), layoutRect, stringFormat ); APath.CloseFigure(); AOldUnit := GetPageUnit(); SetPageUnit( UnitPoint ); DrawPath( pen, APath ); SetPageUnit( AOldUnit ); Result := Self; end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const origin: TGPPointF; pen: IGPPen) : TGPGraphics; // var // APath : IGPGraphicsPath; // ABrush : TGPSolidBrush; // AOldUnit : TGPUnit; var I : Integer; J : Integer; begin // ABrush := TGPSolidBrush.Create( MakeColor( clBlue ) ); for I := 0 to 2 do for J := 0 to 2 do FillString( string_, font, MakePoint( origin.X - 1 + I, origin.X - 1 + J ), pen.GetBrush() ); { APath := TGPGraphicsPath.Create(); APath.StartFigure(); APath.AddString( string_, font.GetFamily(), font.GetStyle(), font.GetSize(), origin, NIL ); APath.CloseFigure(); // AOldUnit := GetPageUnit(); // SetPageUnit( UnitPoint ); DrawPath( pen, APath ); // SetPageUnit( AOldUnit ); } Result := Self; end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: TGPStringFormat; pen: IGPPen) : TGPGraphics; var APath : IGPGraphicsPath; AOldUnit : TGPUnit; begin APath := TGPGraphicsPath.Create(); APath.StartFigure(); APath.AddString( string_, font.GetFamily(), font.GetStyle(), font.GetSize(), origin, stringFormat ); APath.CloseFigure(); AOldUnit := GetPageUnit(); SetPageUnit( UnitPoint ); DrawPath( pen, APath ); SetPageUnit( AOldUnit ); Result := Self; end; *) function TGPGraphics.DrawStringF( string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; var nFont: GpFont; nStringFormat: GpStringFormat; nBrush: GpBrush; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat)) then nstringFormat := stringFormat.GetNativeFormat() else nstringFormat := NIL; if( Assigned(brush)) then nbrush := brush.GetNativeBrush() else nbrush := NIL; ErrorCheck( GdipDrawString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, nstringFormat, nbrush)); Result := Self; end; function TGPGraphics.DrawStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; brush: IGPBrush) : TGPGraphics; var nFont: GpFont; nBrush: GpBrush; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(brush)) then nbrush := brush.GetNativeBrush() else nbrush := NIL; ErrorCheck( GdipDrawString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, NIL, nbrush)); Result := Self; end; function TGPGraphics.DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; brush: IGPBrush) : TGPGraphics; var rect: TGPRectF; nfont: Gpfont; nBrush: GpBrush; begin rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0.0; rect.Height := 0.0; if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(Brush)) then nBrush := Brush.GetNativeBrush() else nBrush := NIL; ErrorCheck( GdipDrawString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @rect, NIL, nbrush)); Result := Self; end; function TGPGraphics.DrawStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; var rect: TGPRectF; nFont: GpFont; nStringFormat: GpStringFormat; nBrush: GpBrush; begin rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0.0; rect.Height := 0.0; if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat)) then nstringFormat := stringFormat.GetNativeFormat() else nstringFormat := NIL; if( Assigned(brush)) then nbrush := brush.GetNativeBrush() else nbrush := NIL; ErrorCheck( GdipDrawString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @rect, nstringFormat, nbrush)); Result := Self; end; // procedure TGPGraphics.MeasureString(string_: WideString; length: Integer; font: IGPFont; // const layoutRect: TGPRectF; stringFormat: TGPStringFormat; out boundingBox: TGPRectF; // codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL); function TGPGraphics.GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; var nFont: GpFont; nStringFormat: GpStringFormat; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat)) then nstringFormat := stringFormat.GetNativeFormat() else nstringFormat := NIL; ErrorCheck( GdipMeasureString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, nstringFormat, @Result, codepointsFitted, linesFilled )); end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; begin Result := DrawStringF( string_, font, MakeRectF( layoutRect ), stringFormat, brush ); end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const layoutRect: TGPRect; brush: IGPBrush) : TGPGraphics; begin Result := DrawStringF( string_, font, MakeRectF( layoutRect ), brush ); end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; brush: IGPBrush) : TGPGraphics; begin Result := DrawStringF( string_, font, MakePointF( origin ), brush ); end; function TGPGraphics.DrawString(string_: WideString; font: IGPFont; const origin: TGPPoint; stringFormat: IGPStringFormat; brush: IGPBrush) : TGPGraphics; begin Result := DrawStringF( string_, font, MakePointF( origin ), stringFormat, brush ); end; function TGPGraphics.GetStringSizeF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL) : TGPSizeF; var ARect : TGPRectF; begin ARect := GetStringBoundingBoxF( string_, font, MakePointF( 0, 0 ), stringFormat ); Result.Width := ARect.Width; Result.Height := ARect.Height; end; // procedure TGPGraphics.MeasureString(string_: WideString; length: Integer; font: IGPFont; // const layoutRectSize: TGPSizeF; stringFormat: TGPStringFormat; out size: TGPSizeF; // codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL); function TGPGraphics.GetStringSizeF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; var layoutRect, boundingBox: TGPRectF; nFont: GpFont; nStringFormat: GpStringFormat; begin layoutRect.X := 0; layoutRect.Y := 0; layoutRect.Width := layoutRectSize.Width; layoutRect.Height := layoutRectSize.Height; if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat)) then nstringFormat := stringFormat.GetNativeFormat() else nstringFormat := NIL; ErrorCheck( GdipMeasureString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, nstringFormat, @boundingBox, codepointsFitted, linesFilled )); Result.Width := boundingBox.Width; Result.Height := boundingBox.Height; end; // procedure TGPGraphics.MeasureString(string_: WideString ; length: Integer; font: IGPFont; // const origin: TGPPointF; stringFormat: IGPStringFormat; out boundingBox: TGPRectF); function TGPGraphics.GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; var rect: TGPRectF; nFont: GpFont; nstringFormat: GpstringFormat; begin rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0.0; rect.Height := 0.0; if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat)) then nstringFormat := stringFormat.GetNativeFormat() else nstringFormat := NIL; ErrorCheck( GdipMeasureString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @rect, nstringFormat, @Result, NIL, NIL )); end; // procedure TGPGraphics.MeasureString(string_: WideString; length: Integer; font: IGPFont; // const layoutRect: TGPRectF; out boundingBox: TGPRectF); function TGPGraphics.GetStringBoundingBoxF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; var nFont: GpFont; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; ErrorCheck( GdipMeasureString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, NIL, @Result, NIL, NIL )); end; // procedure TGPGraphics.MeasureString(string_: WideString; length: Integer; font: IGPFont; // const origin: TGPPointF; out boundingBox: TGPRectF); function TGPGraphics.GetStringBoundingBoxF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; var nFont: GpFont; rect: TGPRectF; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0.0; rect.Height := 0.0; ErrorCheck( GdipMeasureString( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @rect, NIL, @Result, NIL, NIL )); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPSizeF; begin Result := GetStringSizeF( string_, font, stringFormat ); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; const layoutRectSize: TGPSizeF; stringFormat: IGPStringFormat = NIL; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPSizeF; begin Result := GetStringSizeF( string_, font, layoutRectSize, stringFormat, codepointsFitted, linesFilled ); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat; codepointsFitted: PInteger = NIL; linesFilled: PInteger = NIL) : TGPRectF; begin Result := GetStringBoundingBoxF( string_, font, layoutRect, stringFormat, codepointsFitted, linesFilled ); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat ) : TGPRectF; begin Result := GetStringBoundingBoxF( string_, font, origin, stringFormat ); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF ) : TGPRectF; begin Result := GetStringBoundingBoxF( string_, font, layoutRect ); end; function TGPGraphics.MeasureStringF(string_: WideString; font: IGPFont; const origin: TGPPointF ) : TGPRectF; begin Result := GetStringBoundingBoxF( string_, font, origin ); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; stringFormat: IGPStringFormat ) : TGPRegionArray; var nativeRegions: Pointer; i: Integer; nFont: GpFont; nstringFormat: GpstringFormat; regionCount : Integer; ARanges : array of TGPCharacterRange; type TArrayGpRegion = array of GpRegion; begin if( Assigned(font) ) then nfont := font.GetNativeFont() else nfont := NIL; if( not Assigned(stringFormat) ) then begin stringFormat := TGPStringFormat.Create(); SetLength( ARanges, Length( string_ )); for i := 0 to Length( string_ ) - 1 do begin ARanges[ i ].First := i; ARanges[ i ].Length := 1; end; stringFormat.SetMeasurableCharacterRanges( ARanges ); end; nstringFormat := stringFormat.GetNativeFormat(); regionCount := stringFormat.GetMeasurableCharacterRangeCount(); GetMem(nativeRegions, Sizeof(GpRegion)* regionCount); SetLength( Result, regionCount ); for i := 0 to regionCount - 1 do begin Result[i] := TGPRegion.Create(); TArrayGpRegion(nativeRegions)[i] := Result[i].GetNativeRegion(); end; ErrorCheck( GdipMeasureCharacterRanges( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, nstringFormat, regionCount, nativeRegions )); FreeMem(nativeRegions, Sizeof(GpRegion)* regionCount); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; begin Result := MeasureCharacterRangesF( string_, font, GetStringBoundingBoxF( string_, font, origin, stringFormat ), stringFormat ); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; begin Result := MeasureCharacterRangesF( string_, font, GetStringBoundingBoxF( string_, font, MakePointF( 0, 0 ), stringFormat ), stringFormat ); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; const layoutRect: TGPRectF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; var nativeRegions: Pointer; i: Integer; nFont: GpFont; nstringFormat: GpstringFormat; regionCount : Integer; AClonedStringFormat : IGPStringFormat; type TArrayGpRegion = array of GpRegion; begin if( Assigned(font) ) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(stringFormat) ) then AClonedStringFormat := stringFormat.Clone() else AClonedStringFormat := TGPStringFormat.Create(); AClonedStringFormat.SetMeasurableCharacterRanges( ranges ); nstringFormat := AClonedStringFormat.GetNativeFormat(); regionCount := AClonedStringFormat.GetMeasurableCharacterRangeCount(); GetMem(nativeRegions, Sizeof(GpRegion)* regionCount); SetLength( Result, regionCount ); for i := 0 to regionCount - 1 do begin Result[i] := TGPRegion.Create(); TArrayGpRegion(nativeRegions)[i] := Result[i].GetNativeRegion(); end; ErrorCheck( GdipMeasureCharacterRanges( FNativeGraphics, PWideChar(string_), Length( string_ ), nfont, @layoutRect, nstringFormat, regionCount, nativeRegions )); FreeMem(nativeRegions, Sizeof(GpRegion)* regionCount); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; const origin: TGPPointF; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; begin Result := MeasureCharacterRangesF( string_, font, GetStringBoundingBoxF( string_, font, origin, stringFormat ), ranges, stringFormat ); end; function TGPGraphics.MeasureCharacterRangesF(string_: WideString; font: IGPFont; ranges : array of TGPCharacterRange; stringFormat: IGPStringFormat = NIL ) : TGPRegionArray; begin Result := MeasureCharacterRangesF( string_, font, GetStringBoundingBoxF( string_, font, MakePointF( 0, 0 ), stringFormat ), ranges, stringFormat ); end; function TGPGraphics.DrawDriverString(text: PUINT16; length: Integer; font: IGPFont; brush: IGPBrush; positions: PGPPointF; flags: Integer; matrix: IGPMatrix) : TGPGraphics; var nfont: Gpfont; nbrush: Gpbrush; nmatrix: Gpmatrix; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(brush)) then nbrush := brush.GetNativeBrush() else nbrush := NIL; if( Assigned(matrix)) then nmatrix := matrix.GetNativeMatrix() else nmatrix := NIL; ErrorCheck( GdipDrawDriverString( FNativeGraphics, text, length, nfont, nbrush, positions, flags, nmatrix)); Result := Self; end; // function TGPGraphics.MeasureDriverString(text: PUINT16; length: Integer; font: IGPFont; // positions: PGPPointF; flags: Integer; matrix: IGPMatrix; // out boundingBox: TGPRectF); function TGPGraphics.GetDriverStringBoundingBoxF(text: PUINT16; length: Integer; font: IGPFont; positions: PGPPointF; flags: Integer; matrix: IGPMatrix ) : TGPRectF; var nfont: Gpfont; nmatrix: Gpmatrix; begin if( Assigned(font)) then nfont := font.GetNativeFont() else nfont := NIL; if( Assigned(matrix)) then nmatrix := matrix.GetNativeMatrix() else nmatrix := NIL; ErrorCheck( GdipMeasureDriverString( FNativeGraphics, text, length, nfont, positions, flags, nmatrix, @Result )); end; // Draw a cached bitmap on this graphics destination offset by // x, y. Note this will fail with WrongState if the CachedBitmap // native format differs from this Graphics. function TGPGraphics.DrawCachedBitmap(cb: IGPCachedBitmap; x, y: Integer) : TGPGraphics; begin ErrorCheck( GdipDrawCachedBitmap( FNativeGraphics, cb.GetNativeCachedBitmap(), x, y )); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; const point: TGPPointF) : TGPGraphics; begin Result := DrawImageF(image, point.X, point.Y); end; function TGPGraphics.DrawImageF(image: IGPImage; x, y: Single) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImage(FNativeGraphics, nImage, x, y)); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; const rect: TGPRectF) : TGPGraphics; begin Result := DrawImageF(image, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawImageF(image: IGPImage; x, y, width, height: Single) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImageRect(FNativeGraphics, nImage, x, y, width, height)); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; const point: TGPPoint) : TGPGraphics; begin Result := DrawImage(image, point.X, point.Y); end; function TGPGraphics.DrawImage(image: IGPImage; x, y: Integer) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImageI(FNativeGraphics, nimage, x, y)); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; const rect: TGPRect) : TGPGraphics; begin Result := DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphics.DrawImage(image: IGPImage; x, y, width, height: Integer) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImageRectI(FNativeGraphics, nimage, x, y, width, height)); Result := Self; end; function TGPGraphics.DrawImageF( image: IGPImage; const point: TGPPointF; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImageF( image, MakeRectF( point.X, point.Y, image.Width, image.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; x, y: Single; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImageF( image, MakeRectF( x, y, image.Width, image.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; const rect: TGPRectF; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImageF( image, MakeRectF( rect.X, rect.Y, rect.Width, rect.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; x, y, width, height: Single; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImageF( image, MakeRectF( x, y, width, height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; const point: TGPPoint; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImage( image, MakeRect( point.X, point.Y, image.Width, image.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; x, y: Integer; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImage( image, MakeRect( x, y, image.Width, image.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; const rect: TGPRect; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImage( image, MakeRect( rect.X, rect.Y, rect.Width, rect.Height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; x, y, width, height: Integer; Opacity : Single ) : TGPGraphics; var AAlphaMatrix : TGPColorMatrix; begin AAlphaMatrix := StandardAlphaMatrix; AAlphaMatrix[ 3, 3 ] := Opacity; DrawImage( image, MakeRect( x, y, width, height ), 0, 0, image.Width, image.Height, UnitPixel, TGPImageAttributes.Create().SetColorMatrix( AAlphaMatrix )); Result := Self; end; // Affine Draw Image // destPoints.length = 3: rect => parallelogram // destPoints[0] <=> top-left corner of the source rectangle // destPoints[1] <=> top-right corner // destPoints[2] <=> bottom-left corner // destPoints.length = 4: rect => quad // destPoints[3] <=> bottom-right corner function TGPGraphics.DrawImageF(image: IGPImage; destPoints: array of TGPPointF ) : TGPGraphics; var nImage: GpImage; count : Integer; begin count := Length( destPoints ); if ((count <> 3) and (count <> 4)) then ErrorCheck( InvalidParameter); if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImagePoints(FNativeGraphics, nimage, @destPoints[ 0 ], count)); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; destPoints: array of TGPPoint) : TGPGraphics; var nImage: GpImage; count : Integer; begin count := Length( destPoints ); if ((count <> 3) and (count <> 4)) then ErrorCheck( InvalidParameter); if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImagePointsI(FNativeGraphics, nimage, @destPoints[ 0 ], count)); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImagePointRect(FNativeGraphics, nimage, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; const destRect: TGPRectF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; var nImage: GpImage; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntAbortDispatcher; ADispatcherIntf : IGPIntAbortDispatcher; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntAbortDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipDrawImageRectRect(FNativeGraphics, nimage, destRect.X, destRect.Y, destRect.Width, destRect.Height, srcx, srcy, srcwidth, srcheight, srcUnit, nimageAttributes, GLGPAbortCallback, ADispatcher )); Result := Self; end; function TGPGraphics.DrawImageF(image: IGPImage; destPoints: array of TGPPointF; srcx, srcy, srcwidth, srcheight: Single; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; var nImage: GpImage; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntAbortDispatcher; ADispatcherIntf : IGPIntAbortDispatcher; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntAbortDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipDrawImagePointsRect(FNativeGraphics, nimage, @destPoints[ 0 ], Length( destPoints ), srcx, srcy, srcwidth, srcheight, srcUnit, nimageAttributes, GLGPAbortCallback, ADispatcher )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; x, y, srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit) : TGPGraphics; var nImage: GpImage; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; ErrorCheck( GdipDrawImagePointRectI(FNativeGraphics, nimage, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; const destRect: TGPRect; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; var nImage: GpImage; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntAbortDispatcher; ADispatcherIntf : IGPIntAbortDispatcher; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntAbortDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipDrawImageRectRectI(FNativeGraphics, nimage, destRect.X, destRect.Y, destRect.Width, destRect.Height, srcx, srcy, srcwidth, srcheight, srcUnit, nimageAttributes, GLGPAbortCallback, ADispatcher )); Result := Self; end; function TGPGraphics.DrawImage(image: IGPImage; destPoints: array of TGPPoint; srcx, srcy, srcwidth, srcheight: Integer; srcUnit: TGPUnit; imageAttributes: IGPImageAttributes = NIL; callback: TGPDrawImageAbortProc = NIL) : TGPGraphics; var nImage: GpImage; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntAbortDispatcher; ADispatcherIntf : IGPIntAbortDispatcher; begin if( Assigned(Image)) then nImage := Image.GetNativeImage() else nImage := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntAbortDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipDrawImagePointsRectI(FNativeGraphics, nimage, @destPoints[ 0 ], Length( destPoints ), srcx, srcy, srcwidth, srcheight, srcUnit, nimageAttributes, GLGPAbortCallback, ADispatcher )); Result := Self; end; type IGPIntDispatcher = interface ['{F2608F3E-119F-45BE-B73E-0CE219FC4A83}'] end; TGPIntDispatcher = class( TInterfacedObject, IGPIntDispatcher ) public OnCallback : TGPEnumerateMetafileProc; public function GPCallback( recordType: TGPEmfPlusRecordType; flags: UINT; dataSize: UINT; data: PBYTE ) : BOOL; end; function TGPIntDispatcher.GPCallback( recordType: TGPEmfPlusRecordType; flags: UINT; dataSize: UINT; data: PBYTE ) : BOOL; begin if( Assigned( OnCallback )) then Result := OnCallback( recordType, flags, dataSize, data ) else Result := False; end; function GLGPCallback(recordType: TGPEmfPlusRecordType; flags: UINT; dataSize: UINT; data: PBYTE; callbackData: Pointer) : BOOL; stdcall; begin if( callbackData <> NIL ) then Result := TGPIntDispatcher( callbackData ).GPCallback( recordType, flags, dataSize, data ) else Result := False; end; // The following methods are for playing an EMF+ to a graphics // via the enumeration interface. Each record of the EMF+ is // sent to the callback (along with the callbackData). Then // the callback can invoke the Metafile::PlayRecord method // to play the particular record. function TGPGraphics.EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestPoint( FNativeGraphics, nmetafile, @destPoint, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile: IGPMetafile; const destPoint: TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestPointI( FNativeGraphics, nmetafile, @destPoint, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestRect( FNativeGraphics, nmetafile, @destRect, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile: IGPMetafile; const destRect: TGPRect; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestRectI( FNativeGraphics, nmetafile, @destRect, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafileF(metafile: IGPMetafile; destPoints: array of TGPPointF; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestPoints( FNativeGraphics, nmetafile, @destPoints[ 0 ], Length( destPoints ), GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileDestPointsI( FNativeGraphics, nmetafile, @destPoints[ 0 ], Length( destPoints ), GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafileF(metafile: IGPMetafile; const destPoint: TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestPoint( FNativeGraphics, nmetafile, @destPoint, @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile : IGPMetafile; const destPoint : TGPPoint; const srcRect : TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestPointI( FNativeGraphics, nmetafile, @destPoint, @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafileF(metafile: IGPMetafile; const destRect: TGPRectF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestRect( FNativeGraphics, nmetafile, @destRect, @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile : IGPMetafile; const destRect, srcRect: TGPRect; srcUnit : TGPUnit; callback : TGPEnumerateMetafileProc; imageAttributes : IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestRectI( FNativeGraphics, nmetafile, @destRect, @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafileF( metafile: IGPMetafile; destPoints: array of TGPPointF; const srcRect: TGPRectF; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestPoints( FNativeGraphics, nmetafile, @destPoints[ 0 ], Length( destPoints ), @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.EnumerateMetafile(metafile: IGPMetafile; destPoints: array of TGPPoint; const srcRect: TGPRect; srcUnit: TGPUnit; callback: TGPEnumerateMetafileProc; imageAttributes: IGPImageAttributes = NIL) : TGPGraphics; var nMetafile: GpMetafile; nimageAttributes: GpimageAttributes; ADispatcher : TGPIntDispatcher; ADispatcherIntf : IGPIntDispatcher; begin if( Assigned(Metafile)) then nMetafile := GpMetafile(Metafile.GetNativeImage()) else nMetafile := NIL; if( Assigned(imageAttributes)) then nimageAttributes := imageAttributes.GetNativeImageAttr() else nimageAttributes := NIL; ADispatcher := TGPIntDispatcher.Create(); ADispatcherIntf := ADispatcher; ErrorCheck( GdipEnumerateMetafileSrcRectDestPointsI( FNativeGraphics, nmetafile, @destPoints[ 0 ], Length( destPoints ), @srcRect, srcUnit, GLGPCallback, ADispatcher, nimageAttributes)); Result := Self; end; function TGPGraphics.SetClip(g: IGPGraphics; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipGraphics(FNativeGraphics, g.GetNativeGraphics(), combineMode)); Result := Self; end; function TGPGraphics.SetClipF(rect: TGPRectF; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipRect(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, combineMode)); Result := Self; end; function TGPGraphics.SetClip(rect: TGPRect; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipRectI(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, combineMode)); Result := Self; end; function TGPGraphics.SetClip(path: IGPGraphicsPath; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipPath(FNativeGraphics, path.GetNativePath(), combineMode)); Result := Self; end; function TGPGraphics.SetClip(region: IGPRegion; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipRegion(FNativeGraphics, region.GetNativeRegion(), combineMode)); Result := Self; end; // This is different than the other SetClip methods because it assumes // that the HRGN is already in device units, so it doesn't transform // the coordinates in the HRGN. function TGPGraphics.SetClip(hRgn: HRGN; combineMode: TGPCombineMode = CombineModeReplace) : TGPGraphics; begin ErrorCheck( GdipSetClipHrgn(FNativeGraphics, hRgn, combineMode)); Result := Self; end; procedure TGPGraphics.SetClipProp( region: IGPRegion ); begin SetClip( region ); end; function TGPGraphics.IntersectClipF(const rect: TGPRectF) : TGPGraphics; begin ErrorCheck( GdipSetClipRect(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, CombineModeIntersect)); Result := Self; end; function TGPGraphics.IntersectClip(const rect: TGPRect) : TGPGraphics; begin ErrorCheck( GdipSetClipRectI(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, CombineModeIntersect)); Result := Self; end; function TGPGraphics.IntersectClip(region: IGPRegion) : TGPGraphics; begin ErrorCheck( GdipSetClipRegion(FNativeGraphics, region.GetNativeRegion(), CombineModeIntersect)); Result := Self; end; function TGPGraphics.ExcludeClipF(const rect: TGPRectF) : TGPGraphics; begin ErrorCheck( GdipSetClipRect(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, CombineModeExclude)); Result := Self; end; function TGPGraphics.ExcludeClip(const rect: TGPRect) : TGPGraphics; begin ErrorCheck( GdipSetClipRectI(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, CombineModeExclude)); Result := Self; end; function TGPGraphics.ExcludeClip(region: IGPRegion) : TGPGraphics; begin ErrorCheck( GdipSetClipRegion(FNativeGraphics, region.GetNativeRegion(), CombineModeExclude)); Result := Self; end; function TGPGraphics.ResetClip() : TGPGraphics; begin ErrorCheck( GdipResetClip(FNativeGraphics)); Result := Self; end; function TGPGraphics.TranslateClipF(dx, dy: Single) : TGPGraphics; begin ErrorCheck( GdipTranslateClip(FNativeGraphics, dx, dy)); Result := Self; end; function TGPGraphics.TranslateClip(dx, dy: Integer) : TGPGraphics; begin ErrorCheck( GdipTranslateClipI(FNativeGraphics, dx, dy)); Result := Self; end; function TGPGraphics.GetClip() : IGPRegion; begin Result := TGPRegion.Create(); ErrorCheck( GdipGetClip(FNativeGraphics, Result.GetNativeRegion() )); end; function TGPGraphics.GetClipBoundsF() : TGPRectF; begin ErrorCheck( GdipGetClipBounds(FNativeGraphics, @Result)); end; function TGPGraphics.GetClipBounds() : TGPRect; begin ErrorCheck( GdipGetClipBoundsI(FNativeGraphics, @Result)); end; function TGPGraphics.IsClipEmpty: Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsClipEmpty(FNativeGraphics, @booln)); Result := booln; end; function TGPGraphics.GetVisibleClipBoundsF() : TGPRectF; begin ErrorCheck( GdipGetVisibleClipBounds(FNativeGraphics, @Result )); end; function TGPGraphics.GetVisibleClipBounds() : TGPRect; begin ErrorCheck( GdipGetVisibleClipBoundsI(FNativeGraphics, @Result )); end; function TGPGraphics.IsVisibleClipEmpty: Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisibleClipEmpty(FNativeGraphics, booln)); Result := booln; end; function TGPGraphics.IsVisible(x, y: Integer) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisiblePointI(FNativeGraphics, x, y, booln)); Result := booln; end; function TGPGraphics.IsVisible(const point: TGPPoint) : Boolean; begin Result := IsVisible( point.X, point.Y ); end; function TGPGraphics.IsVisible(x, y, width, height: Integer) : Boolean; var booln: BOOL; begin booln := True; ErrorCheck( GdipIsVisibleRectI(FNativeGraphics, X, Y, Width, Height, booln)); Result := booln; end; function TGPGraphics.IsVisible(const rect: TGPRect) : Boolean; var booln: BOOL; begin booln := True; ErrorCheck( GdipIsVisibleRectI(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, booln)); Result := booln; end; function TGPGraphics.IsVisibleF(x, y: Single) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisiblePoint(FNativeGraphics, X, Y, booln)); Result := booln; end; function TGPGraphics.IsVisibleF(const point: TGPPointF) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisiblePoint(FNativeGraphics, point.X, point.Y, booln)); Result := booln; end; function TGPGraphics.IsVisibleF(x, y, width, height: Single) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisibleRect(FNativeGraphics, X, Y, Width, Height, booln)); Result := booln; end; function TGPGraphics.IsVisibleF(const rect: TGPRectF) : Boolean; var booln: BOOL; begin booln := False; ErrorCheck( GdipIsVisibleRect(FNativeGraphics, rect.X, rect.Y, rect.Width, rect.Height, booln)); Result := booln; end; function TGPGraphics.Save: TGPGraphicsState; begin ErrorCheck( GdipSaveGraphics(FNativeGraphics, Result)); end; function TGPGraphics.Restore(gstate: TGPGraphicsState) : TGPGraphics; begin ErrorCheck( GdipRestoreGraphics(FNativeGraphics, gstate)); Result := Self; end; function TGPGraphics.BeginContainerF(const dstrect,srcrect: TGPRectF; unit_: TGPUnit) : TGPGraphicsContainer; begin ErrorCheck( GdipBeginContainer(FNativeGraphics, @dstrect, @srcrect, unit_, Result)); end; function TGPGraphics.BeginContainer(const dstrect, srcrect: TGPRect; unit_: TGPUnit) : TGPGraphicsContainer; begin ErrorCheck( GdipBeginContainerI(FNativeGraphics, @dstrect, @srcrect, unit_, Result)); end; function TGPGraphics.BeginContainer: TGPGraphicsContainer; begin ErrorCheck( GdipBeginContainer2(FNativeGraphics, Result)); end; function TGPGraphics.EndContainer(state: TGPGraphicsContainer) : TGPGraphics; begin ErrorCheck( GdipEndContainer(FNativeGraphics, state)); Result := Self; end; // Only valid when recording metafiles. function TGPGraphics.AddMetafileComment( data: array of BYTE ) : TGPGraphics; begin ErrorCheck( GdipComment(FNativeGraphics, Length( data ), @data[ 0 ] )); Result := Self; end; class function TGPGraphics.GetHalftonePalette() : HPALETTE; begin Result := GdipCreateHalftonePalette(); end; constructor TGPGraphics.CreateGdiPlus(graphics: GpGraphics; Dummy1 : Boolean; Dummy2 : Boolean ); begin SetNativeGraphics(graphics); end; procedure TGPGraphics.SetNativeGraphics(graphics: GpGraphics); begin self.FNativeGraphics := graphics; end; function TGPGraphics.GetNativeGraphics: GpGraphics; begin Result := self.FNativeGraphics; end; function TGPGraphics.GetNativePen( pen: TGPPen) : GpPen; begin Result := pen.FNativePen; end; (**************************************************************************\ * * GDI+ Font Family class * \**************************************************************************) constructor TGPFontFamily.Create(); begin FNativeFamily := NIL; end; constructor TGPFontFamily.Create(name: WideString; fontCollection: IGPFontCollection = NIL); var nfontCollection: GpfontCollection; begin FNativeFamily := NIL; if( Assigned(fontCollection)) then nfontCollection := fontCollection.GetNativeFontCollection() else nfontCollection := NIL; ErrorCheck( GdipCreateFontFamilyFromName(PWideChar(name), nfontCollection, FNativeFamily)); end; destructor TGPFontFamily.Destroy(); begin GdipDeleteFontFamily (FNativeFamily); end; class function TGPFontFamily.GenericSansSerif: TGPFontFamily; var nFontFamily: GpFontFamily; begin if (GenericSansSerifFontFamily <> NIL) then begin Result := GenericSansSerifFontFamily; exit; end; GenericSansSerifFontFamily := TGPFontFamily.Create(); ErrorCheck( GdipGetGenericFontFamilySansSerif(nFontFamily)); GenericSansSerifFontFamily.FNativeFamily := nFontFamily; Result := GenericSansSerifFontFamily; end; class function TGPFontFamily.GenericSerif: TGPFontFamily; var nFontFamily: GpFontFamily; begin if (GenericSerifFontFamily <> NIL) then begin Result := GenericSerifFontFamily; exit; end; GenericSerifFontFamily := TGPFontFamily.Create();// (GenericSerifFontFamilyBuffer); ErrorCheck( GdipGetGenericFontFamilySerif(nFontFamily)); GenericSerifFontFamily.FNativeFamily := nFontFamily; Result := GenericSerifFontFamily; end; class function TGPFontFamily.GenericMonospace: TGPFontFamily; var nFontFamily: GpFontFamily; begin if (GenericMonospaceFontFamily <> NIL) then begin Result := GenericMonospaceFontFamily; exit; end; GenericMonospaceFontFamily := TGPFontFamily.Create();// (GenericMonospaceFontFamilyBuffer); ErrorCheck( GdipGetGenericFontFamilyMonospace(nFontFamily)); GenericMonospaceFontFamily.FNativeFamily := nFontFamily; Result := GenericMonospaceFontFamily; end; function TGPFontFamily.GetFamilyName(language: LANGID = 0) : String; var str: array[0..LF_FACESIZE - 1] of WideChar; begin ErrorCheck( GdipGetFamilyName(FNativeFamily, @str, language)); Result := str; end; function TGPFontFamily.Clone() : TGPFontFamily; var clonedFamily: GpFontFamily; begin clonedFamily := NIL; ErrorCheck( GdipCloneFontFamily (FNativeFamily, clonedFamily)); Result := TGPFontFamily.CreateGdiPlus(clonedFamily, False); end; function TGPFontFamily.IsAvailable() : Boolean; begin Result := (FNativeFamily <> NIL); end; function TGPFontFamily.IsStyleAvailable(style: Integer) : Boolean; var StyleAvailable: BOOL; AGPStatus: TGPStatus; begin AGPStatus := GdipIsStyleAvailable(FNativeFamily, style, StyleAvailable); if (AGPStatus <> Ok) then StyleAvailable := False; Result := StyleAvailable; end; function TGPFontFamily.GetEmHeight(style: Integer) : UINT16; begin ErrorCheck( GdipGetEmHeight(FNativeFamily, style, Result)); end; function TGPFontFamily.GetCellAscent(style: Integer) : UINT16; begin ErrorCheck( GdipGetCellAscent(FNativeFamily, style, Result)); end; function TGPFontFamily.GetCellDescent(style: Integer) : UINT16; begin ErrorCheck( GdipGetCellDescent(FNativeFamily, style, Result)); end; function TGPFontFamily.GetLineSpacing(style: Integer) : UINT16; begin ErrorCheck( GdipGetLineSpacing(FNativeFamily, style, Result)); end; constructor TGPFontFamily.CreateGdiPlus(nativeFamily: GpFontFamily; Dummy : Boolean); begin FNativeFamily := nativeFamily; end; function TGPFontFamily.GetNativeFamily() : GpFontFamily; begin Result := FNativeFamily; end; (**************************************************************************\ * * GDI+ Font class * \**************************************************************************) constructor TGPFont.Create(hdc: HDC); var font: GpFont; begin font := NIL; ErrorCheck( GdipCreateFontFromDC(hdc, font)); SetNativeFont(font); end; constructor TGPFont.Create(hdc: HDC; logfont: PLogFontA); var font: GpFont; begin font := NIL; if( Assigned(logfont)) then ErrorCheck( GdipCreateFontFromLogfontA(hdc, logfont, font)) else ErrorCheck( GdipCreateFontFromDC(hdc, font)); SetNativeFont(font); end; constructor TGPFont.Create(hdc: HDC; logfont: PLogFontW); var font: GpFont; begin font := NIL; if( Assigned(logfont)) then ErrorCheck( GdipCreateFontFromLogfontW(hdc, logfont, font)) else ErrorCheck( GdipCreateFontFromDC(hdc, font)); SetNativeFont(font); end; constructor TGPFont.Create(hdc: HDC; hfont: HFONT); var font: GpFont; lf: LOGFONTA; begin font := NIL; if Boolean(hfont) then begin if( Boolean(GetObjectA(hfont, sizeof(LOGFONTA), @lf))) then ErrorCheck( GdipCreateFontFromLogfontA(hdc, @lf, font)) else ErrorCheck( GdipCreateFontFromDC(hdc, font)); end else ErrorCheck( GdipCreateFontFromDC(hdc, font)); SetNativeFont(font); end; constructor TGPFont.Create(family: IGPFontFamily; emSize: Single; style: TFontStyles; unit_: TGPUnit ); var font: GpFont; nFontFamily: GpFontFamily; begin font := NIL; if( Assigned(Family)) then nFontFamily := Family.GetNativeFamily() else nFontFamily := NIL; ErrorCheck( GdipCreateFont(nFontFamily, emSize, PInteger(@style)^, Integer(unit_), font)); SetNativeFont(font); end; constructor TGPFont.Create(familyName: WideString; emSize: Single; style: TFontStyles; unit_: TGPUnit; fontCollection: IGPFontCollection); var family: IGPFontFamily; nativeFamily: GpFontFamily; begin FNativeFont := NIL; family := TGPFontFamily.Create(familyName, fontCollection); nativeFamily := family.GetNativeFamily(); if ( GdipCreateFont(nativeFamily, emSize, PInteger(@style)^, Integer(unit_), FNativeFont) <> Ok) then begin nativeFamily := TGPFontFamily.GenericSansSerif.FNativeFamily; ErrorCheck( GdipCreateFont( nativeFamily, emSize, PInteger(@style)^, Integer(unit_), FNativeFont)); end; end; function TGPFont.GetLogFontA( g: IGPGraphics ) : TLogFontA; var nGraphics : GpGraphics; begin if( Assigned(g)) then nGraphics := g.GetNativeGraphics() else nGraphics := NIL; ErrorCheck( GdipGetLogFontA(FNativeFont, nGraphics, Result )); end; function TGPFont.GetLogFontW(g: IGPGraphics ) : TLogFontW; var nGraphics: GpGraphics; begin if( Assigned(g)) then nGraphics := g.GetNativeGraphics() else nGraphics := NIL; ErrorCheck( GdipGetLogFontW(FNativeFont, nGraphics, Result )); end; function TGPFont.Clone() : TGPFont; var cloneFont: GpFont; begin cloneFont := NIL; ErrorCheck( GdipCloneFont(FNativeFont, cloneFont)); Result := TGPFont.CreateGdiPlus(cloneFont, False); end; destructor TGPFont.Destroy(); begin GdipDeleteFont(FNativeFont); end; function TGPFont.IsAvailable: Boolean; begin Result := (FNativeFont <> NIL); end; function TGPFont.GetStyle: Integer; begin ErrorCheck( GdipGetFontStyle(FNativeFont, Result)); end; function TGPFont.GetSize: Single; begin ErrorCheck( GdipGetFontSize(FNativeFont, Result)); end; function TGPFont.GetUnit: TGPUnit; begin ErrorCheck( GdipGetFontUnit(FNativeFont, Result)); end; function TGPFont.GetHeight(graphics: IGPGraphics) : Single; var ngraphics: Gpgraphics; begin if( Assigned(graphics)) then ngraphics := graphics.GetNativeGraphics() else ngraphics := NIL; ErrorCheck( GdipGetFontHeight(FNativeFont, ngraphics, Result)); end; function TGPFont.GetHeight(dpi: Single) : Single; begin ErrorCheck( GdipGetFontHeightGivenDPI(FNativeFont, dpi, Result)); end; function TGPFont.GetFamily() : IGPFontFamily; var nFamily: GpFontFamily; begin ErrorCheck( GdipGetFamily(FNativeFont, nFamily) ); Result := TGPFontFamily.CreateGdiPlus( nFamily, False ); end; constructor TGPFont.CreateGdiPlus(font: GpFont; Dummy : Boolean); begin SetNativeFont(font); end; procedure TGPFont.SetNativeFont(Font: GpFont); begin FNativeFont := Font; end; function TGPFont.GetNativeFont() : GpFont; begin Result := FNativeFont; end; (**************************************************************************\ * * Font collections (Installed and Private) * \**************************************************************************) constructor TGPFontCollection.Create(); begin FNativeFontCollection := NIL; end; destructor TGPFontCollection.Destroy(); begin inherited Destroy(); end; function TGPFontCollection.GetFamilyCount() : Integer; var numFound: Integer; begin numFound := 0; ErrorCheck( GdipGetFontCollectionFamilyCount(FNativeFontCollection, numFound)); Result := numFound; end; function TGPFontCollection.GetFamilies() : TGPFontFamilies; var nativeFamilyList: Pointer; count : Integer; numFound: Integer; i: Integer; type ArrGpFontFamily = array of GpFontFamily; begin ErrorCheck( GdipGetFontCollectionFamilyCount( FNativeFontCollection, count )); getMem(nativeFamilyList, count * SizeOf(GpFontFamily)); try ErrorCheck( GdipGetFontCollectionFamilyList( FNativeFontCollection, count, nativeFamilyList, numFound )); SetLength( Result, numFound ); for i := 0 to numFound - 1 do Result[ i ] := TGPFontFamily.CreateGdiPlus( ArrGpFontFamily(nativeFamilyList)[i], False ); // GdipCloneFontFamily(ArrGpFontFamily(nativeFamilyList)[i], gpfamilies[i].FNativeFamily); finally Freemem(nativeFamilyList, count * SizeOf(GpFontFamily)); end end; function TGPFontCollection.GetNativeFontCollection() : GpFontCollection; begin Result := FNativeFontCollection; end; { procedure TGPFontCollection.GetFamilies(numSought: Integer; out gpfamilies: array of TGPFontFamily; out numFound: Integer); var nativeFamilyList: Pointer; i: Integer; type ArrGpFontFamily = array of GpFontFamily; begin if ((numSought <= 0) or (length(gpfamilies) = 0)) then ErrorCheck( InvalidParameter); numFound := 0; getMem(nativeFamilyList, numSought * SizeOf(GpFontFamily)); try if nativeFamilyList = NIL then ErrorCheck( OutOfMemory); ErrorCheck( GdipGetFontCollectionFamilyList( FNativeFontCollection, numSought, nativeFamilyList, numFound )); for i := 0 to numFound - 1 do GdipCloneFontFamily(ArrGpFontFamily(nativeFamilyList)[i], gpfamilies[i].FNativeFamily); finally Freemem(nativeFamilyList, numSought * SizeOf(GpFontFamily)); end; end; } constructor TGPInstalledFontCollection.Create(); begin FNativeFontCollection := NIL; ErrorCheck( GdipNewInstalledFontCollection(FNativeFontCollection)); end; destructor TGPInstalledFontCollection.Destroy(); begin inherited Destroy(); end; constructor TGPPrivateFontCollection.Create(); begin FNativeFontCollection := NIL; ErrorCheck( GdipNewPrivateFontCollection(FNativeFontCollection)); end; destructor TGPPrivateFontCollection.Destroy(); begin GdipDeletePrivateFontCollection(FNativeFontCollection); inherited Destroy(); end; function TGPPrivateFontCollection.AddFontFile(filename: WideString) : TGPPrivateFontCollection; begin ErrorCheck( GdipPrivateAddFontFile(FNativeFontCollection, PWideChar(filename))); Result := Self; end; function TGPPrivateFontCollection.AddMemoryFont(memory: Pointer; length: Integer) : TGPPrivateFontCollection; begin ErrorCheck( GdipPrivateAddMemoryFont( FNativeFontCollection, memory, length)); Result := Self; end; (**************************************************************************\ * * GDI+ Graphics Path class * \**************************************************************************) constructor TGPGraphicsPath.Create(fillMode: TGPFillMode = FillModeAlternate); begin FNativePath := NIL; ErrorCheck( GdipCreatePath(fillMode, FNativePath)); end; constructor TGPGraphicsPath.Create( points : array of TGPPointF; types : array of BYTE; fillMode: TGPFillMode = FillModeAlternate ); begin FNativePath := NIL; ErrorCheck( GdipCreatePath2( @points[ 0 ], @types[ 0 ], Min( Length( points ), Length( types )), fillMode, FNativePath)); end; constructor TGPGraphicsPath.Create( points : array of TGPPoint; types : array of BYTE; fillMode: TGPFillMode = FillModeAlternate ); begin FNativePath := NIL; ErrorCheck( GdipCreatePath2I( @points[ 0 ], @types[ 0 ], Min( Length( points ), Length( types )), fillMode, FNativePath)); end; destructor TGPGraphicsPath.Destroy(); begin GdipDeletePath(FNativePath); end; function TGPGraphicsPath.Clone: TGPGraphicsPath; var clonepath: GpPath; begin clonepath := NIL; ErrorCheck( GdipClonePath(FNativePath, clonepath)); Result := TGPGraphicsPath.CreateGdiPlus(clonepath, False); end; // Reset the path object to empty (and fill mode to FillModeAlternate) function TGPGraphicsPath.Reset() : TGPGraphicsPath; begin ErrorCheck( GdipResetPath(FNativePath)); Result := Self; end; function TGPGraphicsPath.GetFillMode() : TGPFillMode; var FMode: TGPFillMode; begin FMode := FillModeAlternate; ErrorCheck( GdipGetPathFillMode(FNativePath, Result)); Result := FMode; end; function TGPGraphicsPath.SetFillMode(fillmode: TGPFillMode) : TGPGraphicsPath; begin ErrorCheck( GdipSetPathFillMode(FNativePath, fillmode)); Result := Self; end; procedure TGPGraphicsPath.SetFillModeProp(fillmode: TGPFillMode); begin ErrorCheck( GdipSetPathFillMode(FNativePath, fillmode)); end; function TGPGraphicsPath.GetPathData() : IGPPathData; var count: Integer; pathData : TGPPathData; begin pathData := TGPPathData.Create(); Result := pathData; count := GetPointCount(); if ((count <= 0) or ((pathData.FCount > 0) and (pathData.FCount < Count))) then begin pathData.FCount := 0; if( Assigned(pathData.FPoints)) then begin FreeMem(pathData.FPoints); pathData.FPoints := NIL; end; if( Assigned(pathData.FTypes)) then begin FreeMem(pathData.FTypes); pathData.FTypes := NIL; end; end; if (pathData.FCount = 0) then begin getmem(pathData.FPoints, SizeOf(TGPPointF) * count); if (pathData.FPoints = NIL) then ErrorCheck( OutOfMemory); Getmem(pathData.FTypes, count); if (pathData.FTypes = NIL) then begin freemem(pathData.FPoints); pathData.FPoints := NIL; ErrorCheck( OutOfMemory); end; pathData.FCount := count; end; ErrorCheck( GdipGetPathData(FNativePath, @pathData.FCount)); end; function TGPGraphicsPath.StartFigure() : TGPGraphicsPath; begin ErrorCheck( GdipStartPathFigure(FNativePath)); Result := Self; end; function TGPGraphicsPath.CloseFigure() : TGPGraphicsPath; begin ErrorCheck( GdipClosePathFigure(FNativePath)); Result := Self; end; function TGPGraphicsPath.CloseAllFigures() : TGPGraphicsPath; begin ErrorCheck( GdipClosePathFigures(FNativePath)); Result := Self; end; function TGPGraphicsPath.SetMarker() : TGPGraphicsPath; begin ErrorCheck( GdipSetPathMarker(FNativePath)); Result := Self; end; function TGPGraphicsPath.ClearMarkers() : TGPGraphicsPath; begin ErrorCheck( GdipClearPathMarkers(FNativePath)); Result := Self; end; function TGPGraphicsPath.Reverse() : TGPGraphicsPath; begin ErrorCheck( GdipReversePath(FNativePath)); Result := Self; end; function TGPGraphicsPath.GetLastPoint() : TGPPointF; begin ErrorCheck( GdipGetPathLastPoint(FNativePath, @Result )); end; function TGPGraphicsPath.AddLineF(const pt1, pt2: TGPPointF) : TGPGraphicsPath; begin Result := AddLineF(pt1.X, pt1.Y, pt2.X, pt2.Y); end; function TGPGraphicsPath.AddLineF(x1, y1, x2, y2: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathLine(FNativePath, x1, y1, x2, y2)); Result := Self; end; function TGPGraphicsPath.AddLinesF(points: array of TGPPointF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathLine2(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddLine(const pt1, pt2: TGPPoint) : TGPGraphicsPath; begin Result := AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y); end; function TGPGraphicsPath.AddLine(x1, y1, x2, y2: Integer) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathLineI(FNativePath, x1, y1, x2, y2)); Result := Self; end; function TGPGraphicsPath.AddLines(points: array of TGPPoint) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathLine2I(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddArcF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin Result := AddArcF(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); end; function TGPGraphicsPath.AddArcF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathArc(FNativePath, x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphicsPath.AddArc(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin Result := AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); end; function TGPGraphicsPath.AddArc(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathArcI(FNativePath, x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphicsPath.AddBezierF(pt1, pt2, pt3, pt4: TGPPointF) : TGPGraphicsPath; begin Result := AddBezierF(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); end; function TGPGraphicsPath.AddBezierF(x1, y1, x2, y2, x3, y3, x4, y4: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathBezier(FNativePath, x1, y1, x2, y2, x3, y3, x4, y4)); Result := Self; end; function TGPGraphicsPath.AddBeziersF(points: array of TGPPointF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathBeziers(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddBezier(pt1, pt2, pt3, pt4: TGPPoint) : TGPGraphicsPath; begin Result := AddBezier(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); end; function TGPGraphicsPath.AddBezier(x1, y1, x2, y2, x3, y3, x4, y4: Integer) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathBezierI(FNativePath, x1, y1, x2, y2, x3, y3, x4, y4)); Result := Self; end; function TGPGraphicsPath.AddBeziers(points: array of TGPPoint) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathBeziersI(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddCurveF(points: array of TGPPointF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurve(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurve2(FNativePath, @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphicsPath.AddCurveF(points: array of TGPPointF; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurve3(FNativePath, @points[ 0 ], Length( points ), offset, numberOfSegments, tension)); Result := Self; end; function TGPGraphicsPath.AddCurve(points: array of TGPPoint) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurveI(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurve2I(FNativePath, @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphicsPath.AddCurve( points: array of TGPPoint; offset, numberOfSegments: Integer; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathCurve3I(FNativePath, @points[ 0 ], Length( points ), offset, numberOfSegments, tension)); Result := Self; end; function TGPGraphicsPath.AddClosedCurveF(points: array of TGPPointF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathClosedCurve(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddClosedCurveF(points: array of TGPPointF; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathClosedCurve2(FNativePath, @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphicsPath.AddClosedCurve(points: array of TGPPoint) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathClosedCurveI(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddClosedCurve(points: array of TGPPoint; tension: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathClosedCurve2I(FNativePath, @points[ 0 ], Length( points ), tension)); Result := Self; end; function TGPGraphicsPath.AddRectangleF(rect: TGPRectF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectangle(FNativePath, rect.X, rect.Y, rect.Width, rect.Height)); Result := Self; end; function TGPGraphicsPath.AddRectangleF(x, y, width, height: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectangle(FNativePath, x, y, width, height)); Result := Self; end; function TGPGraphicsPath.AddRectanglesF(rects: array of TGPRectF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectangles(FNativePath, @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphicsPath.AddRectangle(rect: TGPRect) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectangleI(FNativePath, rect.X, rect.Y, rect.Width, rect.Height)); Result := Self; end; function TGPGraphicsPath.AddRectangle(x, y, width, height: Integer) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectangleI(FNativePath, x, y, width, height)); Result := Self; end; function TGPGraphicsPath.AddRectangles(rects: array of TGPRect) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathRectanglesI(FNativePath, @rects[ 0 ], Length( rects ))); Result := Self; end; function TGPGraphicsPath.AddEllipseF(rect: TGPRectF) : TGPGraphicsPath; begin Result := AddEllipseF(rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphicsPath.AddEllipseF(x, y, width, height: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathEllipse(FNativePath, x, y, width, height)); Result := Self; end; function TGPGraphicsPath.AddEllipse(rect: TGPRect) : TGPGraphicsPath; begin Result := AddEllipse(rect.X, rect.Y, rect.Width, rect.Height); end; function TGPGraphicsPath.AddEllipse(x, y, width, height: Integer) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathEllipseI(FNativePath, x, y, width, height)); Result := Self; end; function TGPGraphicsPath.AddRoundRectangleF( ARect: TGPRectF; ACornerSize : TGPSizeF ) : TGPGraphicsPath; var ARectRight : Single; begin Result := Self; if(( ARect.Width = 0 ) or ( ARect.Height = 0 )) then Exit; if( ACornerSize.Width < 0 ) then ACornerSize.Width := 0; if( ACornerSize.Height < 0 ) then ACornerSize.Height := 0; if(( ACornerSize.Width = 0 ) or ( ACornerSize.Height = 0 )) then begin AddRectangleF( ARect ); Exit; end; ACornerSize.Width := ACornerSize.Width * 2; ACornerSize.Height := ACornerSize.Height * 2; ARectRight := ARect.X + ARect.Width; if( ACornerSize.Width > ARect.Width ) then ACornerSize.Width := ARect.Width; if( ACornerSize.Height > ARect.Height ) then ACornerSize.Height := ARect.Height; StartFigure(); AddArcF( ARect.X, ARect.Y, ACornerSize.Width, ACornerSize.Height, 180, 90); AddArcF( ARectRight - ACornerSize.Width, ARect.Y, ACornerSize.Width, ACornerSize.Height, 270, 90); AddArcF( ARectRight - ACornerSize.Width, ARect.Y + ARect.Height - ACornerSize.Height, ACornerSize.Width, ACornerSize.Height, 0, 90); AddArcF(ARect.X, ARect.Y + ARect.Height - ACornerSize.Height, ACornerSize.Width, ACornerSize.Height, 90, 90); CloseFigure(); end; function TGPGraphicsPath.AddRoundRectangle( ARect: TGPRect; ACornerSize : TGPSize ) : TGPGraphicsPath; var ARectRight : Integer; begin Result := Self; if(( ARect.Width = 0 ) or ( ARect.Height = 0 )) then Exit; ACornerSize.Width := ACornerSize.Width * 2; ACornerSize.Height := ACornerSize.Height * 2; ARectRight := ARect.X + ARect.Width; if( ACornerSize.Width > ARect.Width ) then ACornerSize.Width := ARect.Width; if( ACornerSize.Height > ARect.Height ) then ACornerSize.Height := ARect.Height; StartFigure(); AddArc( ARect.X, ARect.Y, ACornerSize.Width, ACornerSize.Height, 180, 90); AddArc( ARectRight - ACornerSize.Width, ARect.Y, ACornerSize.Width, ACornerSize.Height, 270, 90); AddArc( ARectRight - ACornerSize.Width, ARect.Y + ARect.Height - ACornerSize.Height, ACornerSize.Width, ACornerSize.Height, 0, 90); AddArc(ARect.X, ARect.Y + ARect.Height - ACornerSize.Height, ACornerSize.Width, ACornerSize.Height, 90, 90); CloseFigure(); end; function TGPGraphicsPath.AddPieF(rect: TGPRectF; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin AddPieF(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); Result := Self; end; function TGPGraphicsPath.AddPieF(x, y, width, height, startAngle, sweepAngle: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathPie(FNativePath, x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphicsPath.AddPie(rect: TGPRect; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin Result := AddPie(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); end; function TGPGraphicsPath.AddPie(x, y, width, height: Integer; startAngle, sweepAngle: Single) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathPieI(FNativePath, x, y, width, height, startAngle, sweepAngle)); Result := Self; end; function TGPGraphicsPath.AddPolygonF(points: array of TGPPointF) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathPolygon(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddPolygon(points: array of TGPPoint) : TGPGraphicsPath; begin ErrorCheck( GdipAddPathPolygonI(FNativePath, @points[ 0 ], Length( points ))); Result := Self; end; function TGPGraphicsPath.AddPath(addingPath: IGPGraphicsPath; connect: Boolean) : TGPGraphicsPath; var nativePath2: GpPath; begin nativePath2 := NIL; if( Assigned(addingPath)) then nativePath2 := addingPath.GetNativePath(); ErrorCheck( GdipAddPathPath(FNativePath, nativePath2, connect)); Result := Self; end; function TGPGraphicsPath.AddStringF(string_: WideString; font : IGPFont; origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; begin Result := AddStringF( string_, font.Family, font.Style, font.Size, origin, format ); end; function TGPGraphicsPath.AddStringF(string_: WideString; font : IGPFont; layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; begin Result := AddStringF( string_, font.Family, font.Style, font.Size, layoutRect, format ); end; function TGPGraphicsPath.AddString(string_: WideString; font : IGPFont; origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; begin Result := AddString( string_, font.Family, font.Style, font.Size, origin, format ); end; function TGPGraphicsPath.AddString(string_: WideString; font : IGPFont; layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; begin Result := AddString( string_, font.Family, font.Style, font.Size, layoutRect, format ); end; function TGPGraphicsPath.AddStringF( string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; // World units origin : TGPPointF; format : IGPStringFormat) : TGPGraphicsPath; var rect : TGPRectF; gpff : GPFONTFAMILY; gpsf : GPSTRINGFORMAT; begin rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0.0; rect.Height := 0.0; gpff := NIL; gpsf := NIL; if( Assigned(family)) then gpff := family.GetNativeFamily(); if( Assigned(format)) then gpsf := format.GetNativeFormat(); ErrorCheck( GdipAddPathString(FNativePath, PWideChar(string_), Length( string_ ), gpff, style, emSize, @rect, gpsf)); Result := Self; end; function TGPGraphicsPath.AddStringF( string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; // World units layoutRect: TGPRectF; format : IGPStringFormat) : TGPGraphicsPath; var gpff : GPFONTFAMILY; gpsf : GPSTRINGFORMAT; begin gpff := NIL; gpsf := NIL; if( Assigned(family)) then gpff := family.GetNativeFamily(); if( Assigned(format)) then gpsf := format.GetNativeFormat(); ErrorCheck( GdipAddPathString( FNativePath, PWideChar(string_), Length( string_ ), gpff, style, emSize, @layoutRect, gpsf)); Result := Self; end; function TGPGraphicsPath.AddString( string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; // World units origin : TGPPoint; format : IGPStringFormat) : TGPGraphicsPath; var rect : TGPRect; gpff : GPFONTFAMILY; gpsf : GPSTRINGFORMAT; begin rect.X := origin.X; rect.Y := origin.Y; rect.Width := 0; rect.Height := 0; gpff := NIL; gpsf := NIL; if( Assigned(family)) then gpff := family.GetNativeFamily(); if( Assigned(format)) then gpsf := format.GetNativeFormat(); ErrorCheck( GdipAddPathStringI(FNativePath, PWideChar(string_), Length( string_ ), gpff, style, emSize, @rect, gpsf)); Result := Self; end; function TGPGraphicsPath.AddString( string_: WideString; family : IGPFontFamily; style : Integer; emSize : Single; // World units layoutRect: TGPRect; format : IGPStringFormat) : TGPGraphicsPath; var gpff : GPFONTFAMILY; gpsf : GPSTRINGFORMAT; begin gpff := NIL; gpsf := NIL; if( Assigned(family)) then gpff := family.GetNativeFamily(); if( Assigned(format)) then gpsf := format.GetNativeFormat(); ErrorCheck( GdipAddPathStringI( FNativePath, PWideChar(string_), Length( string_ ), gpff, style, emSize, @layoutRect, gpsf)); Result := Self; end; function TGPGraphicsPath.Transform(matrix: IGPMatrix) : TGPGraphicsPath; begin if( Assigned(matrix)) then ErrorCheck( GdipTransformPath(FNativePath, matrix.GetNativeMatrix())); Result := Self; end; // This is not always the tightest bounds. function TGPGraphicsPath.GetBoundsF( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRectF; var nativeMatrix: GpMatrix; nativePen: GpPen; begin nativeMatrix := NIL; nativePen := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); if( Assigned(pen)) then nativePen := pen.GetNativePen(); ErrorCheck( GdipGetPathWorldBounds(FNativePath, @Result, nativeMatrix, nativePen)); end; function TGPGraphicsPath.GetBounds( matrix: IGPMatrix = NIL; pen: IGPPen = NIL) : TGPRect; var nativeMatrix: GpMatrix; nativePen: GpPen; begin nativeMatrix := NIL; nativePen := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); if( Assigned(pen)) then nativePen := pen.GetNativePen(); ErrorCheck( GdipGetPathWorldBoundsI(FNativePath, @Result, nativeMatrix, nativePen)); end; // Once flattened, the resultant path is made of line segments and // the original path information is lost. When matrix is NIL the // identity matrix is assumed. function TGPGraphicsPath.Flatten(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; var nativeMatrix: GpMatrix; begin nativeMatrix := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); ErrorCheck( GdipFlattenPath(FNativePath, nativeMatrix, flatness)); Result := Self; end; function TGPGraphicsPath.Widen( pen: IGPPen; matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; var nativeMatrix: GpMatrix; begin if( pen = NIL ) then ErrorCheck( InvalidParameter ); nativeMatrix := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); ErrorCheck( GdipWidenPath(FNativePath, pen.GetNativePen(), nativeMatrix, flatness)); Result := Self; end; function TGPGraphicsPath.Outline(matrix: IGPMatrix = NIL; flatness: Single = FlatnessDefault) : TGPGraphicsPath; var nativeMatrix: GpMatrix; begin nativeMatrix := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); ErrorCheck( GdipWindingModeOutline(FNativePath, nativeMatrix, flatness)); Result := Self; end; // Once this is called, the resultant path is made of line segments and // the original path information is lost. When matrix is NIL, the // identity matrix is assumed. function TGPGraphicsPath.Warp( destPoints : array of TGPPointF; srcRect: TGPRectF; matrix: IGPMatrix = NIL; warpMode: TGPWarpMode = WarpModePerspective; flatness: Single = FlatnessDefault) : TGPGraphicsPath; var nativeMatrix: GpMatrix; begin nativeMatrix := NIL; if( Assigned(matrix)) then nativeMatrix := matrix.GetNativeMatrix(); ErrorCheck( GdipWarpPath(FNativePath, nativeMatrix, @destPoints[ 0 ], Length( destPoints ), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness)); Result := Self; end; function TGPGraphicsPath.GetPointCount() : Integer; var count: Integer; begin count := 0; ErrorCheck( GdipGetPointCount(FNativePath, count)); Result := count; end; function TGPGraphicsPath.GetPathTypes(types: PBYTE; count: Integer) : TGPGraphicsPath; begin ErrorCheck( GdipGetPathTypes(FNativePath, types, count)); Result := Self; end; function TGPGraphicsPath.GetPathPointsF() : TGPPointFArray; var count : Integer; begin ErrorCheck( GdipGetPointCount( FNativePath, count )); SetLength( Result, count ); ErrorCheck( GdipGetPathPoints(FNativePath, @Result[ 0 ], count )); end; function TGPGraphicsPath.GetPathPoints() : TGPPointArray; var count : Integer; begin ErrorCheck( GdipGetPointCount( FNativePath, count )); SetLength( Result, count ); ErrorCheck( GdipGetPathPointsI(FNativePath, @Result[ 0 ], count )); end; function TGPGraphicsPath.IsVisibleF(point: TGPPointF; g: IGPGraphics = NIL) : Boolean; begin Result := IsVisibleF(point.X, point.Y, g); end; function TGPGraphicsPath.IsVisibleF(x, y: Single; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; nativeGraphics: GpGraphics; begin booln := False; nativeGraphics := NIL; if( Assigned(g)) then nativeGraphics := g.GetNativeGraphics(); ErrorCheck( GdipIsVisiblePathPoint(FNativePath, x, y, nativeGraphics, booln)); Result := booln; end; function TGPGraphicsPath.IsVisible(point: TGPPoint; g : IGPGraphics = NIL) : Boolean; begin Result := IsVisible(point.X, point.Y, g); end; function TGPGraphicsPath.IsVisible(x, y: Integer; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; nativeGraphics: GpGraphics; begin booln := False; nativeGraphics := NIL; if( Assigned(g)) then nativeGraphics := g.GetNativeGraphics(); ErrorCheck( GdipIsVisiblePathPointI(FNativePath, x, y, nativeGraphics, booln)); Result := booln; end; function TGPGraphicsPath.IsOutlineVisibleF(point: TGPPointF; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; begin Result := IsOutlineVisibleF(point.X, point.Y, pen, g); end; function TGPGraphicsPath.IsOutlineVisibleF(x, y: Single; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; nativeGraphics: GpGraphics; nativePen: GpPen; begin booln := False; nativeGraphics := NIL; nativePen := NIL; if( Assigned(g)) then nativeGraphics := g.GetNativeGraphics(); if( Assigned(pen)) then nativePen := pen.GetNativePen(); ErrorCheck( GdipIsOutlineVisiblePathPoint(FNativePath, x, y, nativePen, nativeGraphics, booln)); Result := booln; end; function TGPGraphicsPath.IsOutlineVisible(point: TGPPoint; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; begin Result := IsOutlineVisible(point.X, point.Y, pen, g); end; function TGPGraphicsPath.IsOutlineVisible(x, y: Integer; pen: IGPPen; g: IGPGraphics = NIL) : Boolean; var booln: BOOL; nativeGraphics: GpGraphics; nativePen: GpPen; begin booln := False; nativeGraphics := NIL; nativePen := NIL; if( Assigned(g)) then nativeGraphics := g.GetNativeGraphics(); if( Assigned(pen)) then nativePen := pen.GetNativePen(); ErrorCheck( GdipIsOutlineVisiblePathPointI(FNativePath, x, y, nativePen, nativeGraphics, booln)); Result := booln; end; constructor TGPGraphicsPath.Create(path: IGPGraphicsPath); var clonepath: GpPath; begin clonepath := NIL; ErrorCheck( GdipClonePath(path.GetNativePath(), clonepath)); SetNativePath(clonepath); end; constructor TGPGraphicsPath.CreateGdiPlus(nativePath: GpPath; Dummy : Boolean); begin SetNativePath(nativePath); end; procedure TGPGraphicsPath.SetNativePath(nativePath: GpPath); begin self.FNativePath := nativePath; end; function TGPGraphicsPath.GetNativePath() : GpPath; begin Result := self.FNativePath; end; //-------------------------------------------------------------------------- // GraphisPathIterator class //-------------------------------------------------------------------------- constructor TGPGraphicsPathIterator.Create(path: IGPGraphicsPath); var nativePath: GpPath; iter: GpPathIterator; begin nativePath := NIL; if( Assigned(path)) then nativePath := path.GetNativePath(); iter := NIL; ErrorCheck( GdipCreatePathIter(iter, nativePath)); SetNativeIterator(iter); end; destructor TGPGraphicsPathIterator.Destroy(); begin GdipDeletePathIter(FNativeIterator); end; function TGPGraphicsPathIterator.NextSubpath(out startIndex, endIndex: Integer; out isClosed: bool) : Integer; begin ErrorCheck( GdipPathIterNextSubpath(FNativeIterator, Result, startIndex, endIndex, isClosed)); end; function TGPGraphicsPathIterator.NextSubpath(path: IGPGraphicsPath; out isClosed: Boolean) : Integer; var nativePath: GpPath; resultCount: Integer; AValue : BOOL; begin nativePath := NIL; if( Assigned(path)) then nativePath := path.GetNativePath(); ErrorCheck( GdipPathIterNextSubpathPath(FNativeIterator, resultCount, nativePath, AValue)); isClosed := AValue; Result := resultCount; end; function TGPGraphicsPathIterator.NextPathType(out pathType: TGPPathPointType; out startIndex, endIndex: Integer) : Integer; var resultCount: Integer; begin ErrorCheck( GdipPathIterNextPathType(FNativeIterator, resultCount, @pathType, startIndex, endIndex)); Result := resultCount; end; function TGPGraphicsPathIterator.NextMarker(out startIndex, endIndex: Integer) : Integer; begin ErrorCheck( GdipPathIterNextMarker(FNativeIterator, Result, startIndex, endIndex)); end; function TGPGraphicsPathIterator.NextMarker(path: IGPGraphicsPath) : Integer; var nativePath: GpPath; begin nativePath := NIL; if( Assigned(path)) then nativePath := path.GetNativePath(); ErrorCheck( GdipPathIterNextMarkerPath(FNativeIterator, Result, nativePath)); end; function TGPGraphicsPathIterator.GetCount: Integer; begin ErrorCheck( GdipPathIterGetCount(FNativeIterator, Result)); end; function TGPGraphicsPathIterator.GetSubpathCount: Integer; begin ErrorCheck( GdipPathIterGetSubpathCount(FNativeIterator, Result)); end; function TGPGraphicsPathIterator.HasCurve: Boolean; var AValue : BOOL; begin ErrorCheck( GdipPathIterHasCurve(FNativeIterator, AValue )); Result := AValue; end; function TGPGraphicsPathIterator.Rewind() : TGPGraphicsPathIterator; begin ErrorCheck( GdipPathIterRewind(FNativeIterator)); Result := Self; end; function TGPGraphicsPathIterator.Enumerate( out points: TGPPointFArray; out types: TGPByteArray ) : Integer; var ACount : Integer; begin ACount := GetCount(); SetLength( points, ACount ); SetLength( types, ACount ); ErrorCheck( GdipPathIterEnumerate( FNativeIterator, Result, @points[ 0 ], @types[ 0 ], ACount )); end; function TGPGraphicsPathIterator.CopyData(points: PGPPointF; types: PBYTE; startIndex, endIndex: Integer) : Integer; begin ErrorCheck( GdipPathIterCopyData(FNativeIterator, Result, points, types, startIndex, endIndex)); end; procedure TGPGraphicsPathIterator.SetNativeIterator(nativeIterator: GpPathIterator); begin self.FNativeIterator := nativeIterator; end; //-------------------------------------------------------------------------- // Path Gradient Brush //-------------------------------------------------------------------------- constructor TGPPathGradientBrush.CreateF(points: array of TGPPointF; wrapMode: TGPWrapMode = WrapModeClamp); var brush: GpPathGradient; begin brush := NIL; ErrorCheck( GdipCreatePathGradient(@points[ 0 ], Length( points ), wrapMode, brush)); SetNativeBrush(brush); end; constructor TGPPathGradientBrush.Create(points: array of TGPPoint; wrapMode: TGPWrapMode = WrapModeClamp); var brush: GpPathGradient; begin brush := NIL; ErrorCheck( GdipCreatePathGradientI(@points[ 0 ], Length( points ), wrapMode, brush)); SetNativeBrush(brush); end; constructor TGPPathGradientBrush.Create(path: IGPGraphicsPath); var brush: GpPathGradient; begin ErrorCheck( GdipCreatePathGradientFromPath( path.GetNativePath(), brush)); SetNativeBrush(brush); end; function TGPPathGradientBrush.GetCenterColor() : TGPColor; begin ErrorCheck( GdipGetPathGradientCenterColor(GpPathGradient(GetNativeBrush()), Result )); end; procedure TGPPathGradientBrush.SetCenterColorProp(color: TGPColor); begin ErrorCheck( GdipSetPathGradientCenterColor(GpPathGradient(GetNativeBrush()),color)); end; function TGPPathGradientBrush.SetCenterColor(color: TGPColor) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientCenterColor(GpPathGradient(GetNativeBrush()),color)); Result := Self; end; function TGPPathGradientBrush.GetPointCount: Integer; begin ErrorCheck( GdipGetPathGradientPointCount(GpPathGradient(GetNativeBrush()), Result)); end; function TGPPathGradientBrush.GetSurroundColorCount: Integer; begin ErrorCheck( GdipGetPathGradientSurroundColorCount(GpPathGradient(GetNativeBrush()), Result)); end; function TGPPathGradientBrush.GetSurroundColors() : TGPColorArray; var count1: Integer; begin ErrorCheck( GdipGetPathGradientSurroundColorCount(GpPathGradient(GetNativeBrush()), count1)); if( count1 <= 0 ) then begin ErrorCheck( InsufficientBuffer); exit; end; SetLength( Result, count1 ); ErrorCheck( GdipGetPathGradientSurroundColorsWithCount(GpPathGradient(GetNativeBrush()), @Result[ 0 ], count1)); end; procedure TGPPathGradientBrush.SetSurroundColorsProp(colors : TGPColorArray ); begin SetSurroundColors( colors ); end; function TGPPathGradientBrush.SetSurroundColors(colors: array of TGPColor ) : TGPPathGradientBrush; var count1: Integer; count: Integer; type TDynArrDWORD = array of DWORD; begin Result := Self; count1 := GetPointCount(); count := Length( colors ); if((count > count1) or (count1 <= 0)) then begin ErrorCheck( InvalidParameter); exit; end; count1 := count; ErrorCheck( GdipSetPathGradientSurroundColorsWithCount( GpPathGradient(GetNativeBrush()), @colors[ 0 ], count1)); end; function TGPPathGradientBrush.GetGraphicsPath() : IGPGraphicsPath; begin Result := TGPGraphicsPath.Create(); ErrorCheck( GdipGetPathGradientPath(GpPathGradient(GetNativeBrush()), Result.GetNativePath())); end; function TGPPathGradientBrush.SetGraphicsPath(path: IGPGraphicsPath) : TGPPathGradientBrush; begin Result := Self; if(path = NIL) then ErrorCheck( InvalidParameter); ErrorCheck( GdipSetPathGradientPath(GpPathGradient(GetNativeBrush()), path.GetNativePath() )); end; procedure TGPPathGradientBrush.SetGraphicsPathProp(path: IGPGraphicsPath); begin SetGraphicsPath( path ); end; function TGPPathGradientBrush.GetCenterPointF() : TGPPointF; begin ErrorCheck( GdipGetPathGradientCenterPoint(GpPathGradient(GetNativeBrush()), @Result)); end; function TGPPathGradientBrush.GetCenterPoint() : TGPPoint; begin ErrorCheck( GdipGetPathGradientCenterPointI(GpPathGradient(GetNativeBrush()), @Result)); end; procedure TGPPathGradientBrush.SetCenterPointFProp(point: TGPPointF); begin ErrorCheck( GdipSetPathGradientCenterPoint(GpPathGradient(GetNativeBrush()), @point)); end; function TGPPathGradientBrush.SetCenterPointF(point: TGPPointF) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientCenterPoint(GpPathGradient(GetNativeBrush()), @point)); Result := Self; end; function TGPPathGradientBrush.SetCenterPoint(point: TGPPoint) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientCenterPointI(GpPathGradient(GetNativeBrush()), @point)); Result := Self; end; function TGPPathGradientBrush.GetRectangleF() : TGPRectF; begin ErrorCheck( GdipGetPathGradientRect(GpPathGradient(GetNativeBrush()), @Result)); end; function TGPPathGradientBrush.GetRectangle() : TGPRect; begin ErrorCheck( GdipGetPathGradientRectI(GpPathGradient(GetNativeBrush()), @Result)); end; procedure TGPPathGradientBrush.SetGammaCorrectionProp(useGammaCorrection: Boolean); begin ErrorCheck( GdipSetPathGradientGammaCorrection(GpPathGradient(GetNativeBrush()), useGammaCorrection)); end; function TGPPathGradientBrush.SetGammaCorrection(useGammaCorrection: Boolean) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientGammaCorrection(GpPathGradient(GetNativeBrush()), useGammaCorrection)); Result := Self; end; function TGPPathGradientBrush.GetGammaCorrection() : Boolean; var AValue : BOOL; begin ErrorCheck( GdipGetPathGradientGammaCorrection(GpPathGradient(GetNativeBrush()), AValue )); Result := AValue; end; function TGPPathGradientBrush.GetBlendCount() : Integer; begin ErrorCheck( GdipGetPathGradientBlendCount(GpPathGradient(GetNativeBrush()), Result)); end; function TGPPathGradientBrush.GetBlend() : TGPBlendArray; var count : Integer; aFactors : array of Single; aPositions : array of Single; I : Integer; begin ErrorCheck( GdipGetPathGradientBlendCount( GetNativeBrush(), count )); SetLength( aFactors, count ); SetLength( aPositions, count ); ErrorCheck( GdipGetPathGradientBlend( GpPathGradient(GetNativeBrush()), @aFactors[ 0 ], @aPositions[ 0 ], count)); SetLength( Result, count ); for I := 0 to count - 1 do begin Result[ I ].Position := aPositions[ I ]; Result[ I ].Value := aFactors[ I ]; end; end; function TGPPathGradientBrush.SetBlendArrays( blendFactors : array of Single; blendPositions : array of Single ) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientBlend( GpPathGradient(GetNativeBrush()), @blendFactors[ 0 ], @blendPositions[ 0 ], Min( Length( blendFactors ), Length( blendPositions )) )); Result := Self; end; function TGPPathGradientBrush.SetBlend( blendFactors : array of TGPBlend ) : TGPPathGradientBrush; var I : Integer; count : Integer; aFactors : array of Single; aPositions : array of Single; begin count := Length( blendFactors ); SetLength( aFactors, count ); SetLength( aPositions, count ); for I := 0 to count - 1 do begin aFactors[ I ] := blendFactors[ I ].Value; aPositions[ I ] := blendFactors[ I ].Position; end; SetBlendArrays( aFactors, aPositions ); Result := Self; end; procedure TGPPathGradientBrush.SetBlendProp( blendFactors : TGPBlendArray ); begin SetBlend( blendFactors ); end; function TGPPathGradientBrush.GetInterpolationColorCount() : Integer; begin ErrorCheck( GdipGetPathGradientPresetBlendCount(GpPathGradient(GetNativeBrush()), Result)); end; function TGPPathGradientBrush.SetInterpolationColors( Colors : array of TGPInterpolationColor ) : TGPPathGradientBrush; var presetColors : array of TGPColor; blendPositions : array of Single; count : Integer; I : Integer; begin count := Length( Colors ); SetLength( presetColors, count ); SetLength( blendPositions, count ); for I := 0 to count - 1 do begin presetColors[ I ] := Colors[ I ].Color; blendPositions[ I ] := Colors[ I ].Position; end; ErrorCheck( GdipSetPathGradientPresetBlend(GpPathGradient(GetNativeBrush()), PGPColor( @presetColors[ 0 ]), @blendPositions[ 0 ], count )); Result := Self; end; procedure TGPPathGradientBrush.SetInterpolationColorsProp( Colors : TGPInterpolationColorArray ); begin SetInterpolationColors( Colors ); end; function TGPPathGradientBrush.SetInterpolationColorArrays( presetColors: array of TGPColor; blendPositions: array of Single ) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientPresetBlend(GpPathGradient(GetNativeBrush()), PGPColor( @presetColors[ 0 ]), @blendPositions[ 0 ], Min( Length( presetColors ), Length( blendPositions )))); Result := Self; end; function TGPPathGradientBrush.GetInterpolationColors() : TGPInterpolationColorArray; var presetColors : array of TGPColor; blendPositions : array of Single; count : Integer; I : Integer; begin ErrorCheck( GdipGetPathGradientPresetBlendCount( GetNativeBrush(), count )); SetLength( presetColors, count ); SetLength( blendPositions, count ); ErrorCheck( GdipGetPathGradientPresetBlend(GetNativeBrush(), PGPColor(@presetColors[ 0 ]), @blendPositions[ 0 ], count)); for I := 0 to count - 1 do begin Result[ I ].Color := presetColors[ I ]; Result[ I ].Position := blendPositions[ I ]; end; end; function TGPPathGradientBrush.SetBlendBellShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientSigmaBlend(GpPathGradient(GetNativeBrush()), focus, scale)); Result := Self; end; function TGPPathGradientBrush.SetBlendTriangularShape(focus: Single; scale: Single = 1.0) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientLinearBlend(GpPathGradient(GetNativeBrush()), focus, scale)); Result := Self; end; function TGPPathGradientBrush.GetTransform() : IGPMatrix; begin Result := TGPMatrix.Create(); ErrorCheck( GdipGetPathGradientTransform(GpPathGradient(GetNativeBrush()), Result.GetNativeMatrix())); end; function TGPPathGradientBrush.SetTransform(matrix: IGPMatrix) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientTransform( GpPathGradient(GetNativeBrush()), matrix.GetNativeMatrix())); Result := Self; end; procedure TGPPathGradientBrush.SetTransformProp(matrix: IGPMatrix); begin ErrorCheck( GdipSetPathGradientTransform( GpPathGradient(GetNativeBrush()), matrix.GetNativeMatrix())); end; function TGPPathGradientBrush.ResetTransform() : TGPPathGradientBrush; begin ErrorCheck( GdipResetPathGradientTransform( GpPathGradient(GetNativeBrush()))); Result := Self; end; function TGPPathGradientBrush.MultiplyTransform(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; begin ErrorCheck( GdipMultiplyPathGradientTransform( GpPathGradient(GetNativeBrush()), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPPathGradientBrush.TranslateTransform(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; begin ErrorCheck( GdipTranslatePathGradientTransform( GpPathGradient(GetNativeBrush()), dx, dy, order)); Result := Self; end; function TGPPathGradientBrush.ScaleTransform(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; begin ErrorCheck( GdipScalePathGradientTransform( GpPathGradient(GetNativeBrush()), sx, sy, order)); Result := Self; end; function TGPPathGradientBrush.RotateTransform(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : TGPPathGradientBrush; begin ErrorCheck( GdipRotatePathGradientTransform( GpPathGradient(GetNativeBrush()), angle, order)); Result := Self; end; function TGPPathGradientBrush.SetTransformT(matrix: IGPMatrix) : IGPTransformable; begin ErrorCheck( GdipSetPathGradientTransform( GpPathGradient(GetNativeBrush()), matrix.GetNativeMatrix())); Result := Self; end; function TGPPathGradientBrush.ResetTransformT() : IGPTransformable; begin ErrorCheck( GdipResetPathGradientTransform( GpPathGradient(GetNativeBrush()))); Result := Self; end; function TGPPathGradientBrush.MultiplyTransformT(matrix: IGPMatrix; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipMultiplyPathGradientTransform( GpPathGradient(GetNativeBrush()), matrix.GetNativeMatrix(), order)); Result := Self; end; function TGPPathGradientBrush.TranslateTransformT(dx, dy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipTranslatePathGradientTransform( GpPathGradient(GetNativeBrush()), dx, dy, order)); Result := Self; end; function TGPPathGradientBrush.ScaleTransformT(sx, sy: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipScalePathGradientTransform( GpPathGradient(GetNativeBrush()), sx, sy, order)); Result := Self; end; function TGPPathGradientBrush.RotateTransformT(angle: Single; order: TGPMatrixOrder = MatrixOrderPrepend) : IGPTransformable; begin ErrorCheck( GdipRotatePathGradientTransform( GpPathGradient(GetNativeBrush()), angle, order)); Result := Self; end; function TGPPathGradientBrush.GetFocusScales(out xScale, yScale: Single) : TGPPathGradientBrush; begin ErrorCheck( GdipGetPathGradientFocusScales( GpPathGradient(GetNativeBrush()), xScale, yScale)); Result := Self; end; function TGPPathGradientBrush.SetFocusScales(xScale, yScale: Single) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientFocusScales( GpPathGradient(GetNativeBrush()), xScale, yScale)); Result := Self; end; function TGPPathGradientBrush.GetWrapMode() : TGPWrapMode; begin ErrorCheck( GdipGetPathGradientWrapMode(GpPathGradient(GetNativeBrush()), Result)); end; function TGPPathGradientBrush.SetWrapMode(wrapMode: TGPWrapMode) : TGPPathGradientBrush; begin ErrorCheck( GdipSetPathGradientWrapMode( GpPathGradient(GetNativeBrush()), wrapMode)); Result := Self; end; procedure TGPPathGradientBrush.SetWrapModeProp(wrapMode: TGPWrapMode); begin SetWrapMode( wrapMode ); end; // ----------------------------------------------------------------------------- // TGPBase class // ----------------------------------------------------------------------------- class function TGPBase.NewInstance() : TObject; begin Result := InitInstance(GdipAlloc(ULONG(instanceSize))); TGPBase(Result).FRefCount := 1; end; procedure TGPBase.FreeInstance(); begin CleanupInstance(); GdipFree(Self); end; class procedure TGPBase.ErrorCheck( AStatus : TGPStatus ); begin if( AStatus <> Ok ) then raise EGPLoadError.Create( GetStatus( AStatus )); end; // ----------------------------------------------------------------------------- // macros // ----------------------------------------------------------------------------- function ObjectTypeIsValid(type_: TGPObjectType) : Boolean; begin Result := ((type_ >= ObjectTypeMin) and (type_ <= ObjectTypeMax)); end; function GDIP_WMF_RECORD_TO_EMFPLUS(n: Integer) : Integer; begin Result := (n or GDIP_WMF_RECORD_BASE); end; function GDIP_EMFPLUS_RECORD_TO_WMF(n: Integer) : Integer; begin Result := n and (not GDIP_WMF_RECORD_BASE); end; function GDIP_IS_WMF_RECORDTYPE(n: Integer) : Boolean; begin Result := ((n and GDIP_WMF_RECORD_BASE) <> 0); end; //-------------------------------------------------------------------------- // TGPPoint Util //-------------------------------------------------------------------------- function MakePoint( X, Y: Integer ) : TGPPoint; begin Result.X := X; Result.Y := Y; end; function MakePoint( XY: Integer ) : TGPPoint; begin Result.X := XY; Result.Y := XY; end; function MakePoint( APoint : TPoint ) : TGPPoint; begin Result.X := APoint.X; Result.Y := APoint.Y; end; function MakePointF( X, Y: Single ) : TGPPointF; begin Result.X := X; Result.Y := Y; end; function MakePointF( XY: Single ) : TGPPointF; begin Result.X := XY; Result.Y := XY; end; function MakePointF( APoint : TGPPoint ) : TGPPointF; begin Result.X := APoint.X; Result.Y := APoint.Y; end; //-------------------------------------------------------------------------- // TGPSize Util //-------------------------------------------------------------------------- function MakeSizeF(Width, Height: Single) : TGPSizeF; begin Result.Width := Width; Result.Height := Height; end; function MakeSizeF( ASize : Single) : TGPSizeF; overload; begin Result.Width := ASize; Result.Height := ASize; end; function MakeSize( Width, Height: Integer ) : TGPSize; begin Result.Width := Width; Result.Height := Height; end; function MakeSize( ASize : Integer ) : TGPSize; begin Result.Width := ASize; Result.Height := ASize; end; //-------------------------------------------------------------------------- // TCharacterRange Util //-------------------------------------------------------------------------- function MakeCharacterRange(First, Length: Integer) : TGPCharacterRange; begin Result.First := First; Result.Length := Length; end; // ----------------------------------------------------------------------------- // RectF class // ----------------------------------------------------------------------------- function MakeRectF(x, y, width, height: Single) : TGPRectF; overload; begin Result.X := x; Result.Y := y; Result.Width := width; Result.Height := height; end; function MakeRectF(location: TGPPointF; size: TGPSizeF) : TGPRectF; overload; begin Result.X := location.X; Result.Y := location.Y; Result.Width := size.Width; Result.Height := size.Height; end; function MakeRectF( const Rect: TRect ) : TGPRectF; overload; begin Result.X := Rect.Left; Result.Y := Rect.Top; Result.Width := Rect.Right - Rect.Left - 1; Result.Height:= Rect.Bottom - Rect.Top - 1; end; function MakeRectF( const Rect: TGPRect ) : TGPRectF; overload; begin Result.X := Rect.X; Result.Y := Rect.Y; Result.Width := Rect.Width; Result.Height:= Rect.Height; end; // ----------------------------------------------------------------------------- // Rect class // ----------------------------------------------------------------------------- function MakeRect(x, y, width, height: Integer) : TGPRect; overload; begin Result.X := x; Result.Y := y; Result.Width := width; Result.Height := height; end; function MakeRect(location: TGPPoint; size: TGPSize) : TGPRect; overload; begin Result.X := location.X; Result.Y := location.Y; Result.Width := size.Width; Result.Height := size.Height; end; function MakeRect(const Rect: TRect) : TGPRect; begin Result.X := rect.Left; Result.Y := Rect.Top; Result.Width := Rect.Right-Rect.Left; Result.Height:= Rect.Bottom-Rect.Top; end; function RectFrom( const Rect: TGPRect ) : TRect; begin Result.Left := Rect.X; Result.Top := Rect.Y; Result.Right := Rect.X + Rect.Width; Result.Bottom := Rect.Y + Rect.Height; end; function GPInflateRect( ARect: TGPRect; CX, CY: Integer ) : TGPRect; begin Dec( ARect.X, CX ); Dec( ARect.Y, CY ); Inc( ARect.Width, CX * 2 ); Inc( ARect.Height, CY * 2 ); Result := ARect; end; function GPInflateRect( ARect: TGPRect; Change : Integer ) : TGPRect; begin Dec( ARect.X, Change ); Dec( ARect.Y, Change ); Inc( ARect.Width, Change * 2 ); Inc( ARect.Height, Change * 2 ); Result := ARect; end; function GPInflateRectF( ARect: TGPRectF; CX, CY: Single ) : TGPRectF; begin Result.X := ARect.X - CX; Result.Y := ARect.Y - CY; Result.Width := ARect.Width + CX * 2; Result.Height := ARect.Height + CY * 2; end; function GPInflateRectF( ARect: TGPRectF; Change : Single ) : TGPRectF; begin Result.X := ARect.X - Change; Result.Y := ARect.Y - Change; Result.Width := ARect.Width + Change * 2; Result.Height := ARect.Height + Change * 2; end; function GPIntersectRect( ARect1 : TGPRect; ARect2 : TGPRect ) : TGPRect; var AIntersectRect : TRect; begin IntersectRect( AIntersectRect, RectFrom( ARect1 ), RectFrom( ARect2 )); Result := MakeRect( AIntersectRect ); end; function GPCheckIntersectRect( ARect1 : TGPRect; ARect2 : TGPRect ) : Boolean; var AIntersectRect : TRect; begin Result := IntersectRect( AIntersectRect, RectFrom( ARect1 ), RectFrom( ARect2 )); end; function GPEqualRect( ARect1 : TGPRect; ARect2 : TGPRect ) : Boolean; begin Result := ( ARect1.X = ARect2.X ) and ( ARect1.Y = ARect2.Y ) and ( ARect1.Width = ARect2.Width ) and ( ARect1.Height = ARect2.Height ); end; // ----------------------------------------------------------------------------- // PathData class // ----------------------------------------------------------------------------- constructor TGPPathData.Create(); begin FCount := 0; FPoints := NIL; FTypes := NIL; end; destructor TGPPathData.Destroy(); begin if( FPoints <> NIL ) then FreeMem(FPoints); if( FTypes <> NIL ) then FreeMem(FTypes); end; function TGPPathData.GetCount() : Integer; begin Result := FCount; end; function TGPPathData.GetPoints( Index : Integer ) : TGPPointF; begin Result := PGPPointF( PChar( FPoints ) + Index * SizeOf( TGPPointF ) )^; end; function TGPPathData.GetTypes( Index : Integer ) : TGPPathPointType; begin Result := TGPPathPointType( PByte( PChar( FTypes ) + Index )^ ); end; function GetPixelFormatSize(pixfmt: TGPPixelFormat) : Cardinal; begin Result := (pixfmt shr 8) and $ff; end; function IsIndexedPixelFormat(pixfmt: TGPPixelFormat) : Boolean; begin Result := (pixfmt and PixelFormatIndexed) <> 0; end; function IsAlphaPixelFormat(pixfmt: TGPPixelFormat) : Boolean; begin Result := (pixfmt and PixelFormatAlpha) <> 0; end; function IsExtendedPixelFormat(pixfmt: TGPPixelFormat) : Boolean; begin Result := (pixfmt and PixelFormatExtended) <> 0; end; function IsCanonicalPixelFormat(pixfmt: TGPPixelFormat) : Boolean; begin Result := (pixfmt and PixelFormatCanonical) <> 0; end; {$IFDEF DELPHI16_UP} // Delphi 16.0 function ColorToRGB(Color: TColor): Longint; begin if Color < 0 then Result := GetSysColor(Color and $000000FF) else Result := Color; end; {$ENDIF} // Delphi 16.0 function MakeARGBColor( AAlpha : Byte; AColor : TGPColor ) : TGPColor; overload; begin Result := ( AColor and not AlphaMask ) or (DWORD(AAlpha) shl AlphaShift); end; function MakeColor( AColor : TColor ) : TGPColor; overload; begin Result := MakeColor( 255, AColor ); end; function MakeColor( AAlpha : Byte; AColor : TColor ) : TGPColor; overload; begin AColor := ColorToRGB( AColor ); Result := MakeColor( AAlpha, GetRValue( AColor ), GetGValue( AColor ), GetBValue( AColor )); end; function GPGetColor( AColor : TGPColor ) : TColor; begin Result := RGB( GetRed( AColor ), GetGreen( AColor ), GetBlue( AColor )); end; function MakeColor(r, g, b: Byte) : TGPColor; overload; begin Result := GPMakeColor(255, r, g, b); end; function MakeColor(a, r, g, b: Byte) : TGPColor; overload; begin Result := ((DWORD(b) shl BlueShift) or (DWORD(g) shl GreenShift) or (DWORD(r) shl RedShift) or (DWORD(a) shl AlphaShift)); end; function GPMakeColor( AColor : TColor ) : TGPColor; overload; begin Result := GPMakeColor( 255, AColor ); end; function GPMakeColor( AAlpha : Byte; AColor : TColor ) : TGPColor; overload; begin AColor := ColorToRGB( AColor ); Result := MakeColor( AAlpha, GetRValue( AColor ), GetGValue( AColor ), GetBValue( AColor )); end; function GPMakeColor(r, g, b: Byte) : TGPColor; overload; begin Result := GPMakeColor(255, r, g, b); end; function GPMakeColor(a, r, g, b: Byte) : TGPColor; overload; begin Result := ((DWORD(b) shl BlueShift) or (DWORD(g) shl GreenShift) or (DWORD(r) shl RedShift) or (DWORD(a) shl AlphaShift)); end; function GetAlpha(color: TGPColor) : BYTE; begin Result := BYTE(color shr AlphaShift); end; function GetRed(color: TGPColor) : BYTE; begin Result := BYTE(color shr RedShift); end; function GetGreen(color: TGPColor) : BYTE; begin Result := BYTE(color shr GreenShift); end; function GetBlue(color: TGPColor) : BYTE; begin Result := BYTE(color shr BlueShift); end; function ColorRefToARGB(rgb: COLORREF) : TGPColor; begin Result := GPMakeColor(255, GetRValue(rgb), GetGValue(rgb), GetBValue(rgb)); end; function ARGBToColorRef(Color: TGPColor) : COLORREF; begin Result := RGB(GetRed(Color), GetGreen(Color), GetBlue(Color)); end; function RGBToBGR(color: TGPColor) : TGPColor; begin Result := GPMakeColor( GetAlpha( color ), GetRValue(color), GetGValue(color), GetBValue(color) ); end; function MakeBlend( APosition : Single; AValue : Single ) : TGPBlend; begin Result.Position := APosition; Result.Value := AValue; end; function MakeInterpolationColor( APosition : Single; AColor : TGPColor ) : TGPInterpolationColor; begin Result.Position := APosition; Result.Color := AColor; end; // ----------------------------------------------------------------------------- // MetafileHeader class // ----------------------------------------------------------------------------- function TGPMetafileHeader.GetType() : TGPMetafileType; begin Result := FType; end; function TGPMetafileHeader.GetMetafileSize() : UINT; begin Result := FSize; end; function TGPMetafileHeader.GetVersion() : UINT; begin Result := FVersion; end; function TGPMetafileHeader.GetEmfPlusFlags() : UINT; begin Result := FEmfPlusFlags; end; function TGPMetafileHeader.GetDpiX() : Single; begin Result := FDpiX; end; function TGPMetafileHeader.GetDpiY() : Single; begin Result := FDpiY; end; function TGPMetafileHeader.GetBounds() : TGPRect; begin Result.X := FX; Result.Y := FY; Result.Width := FWidth; Result.Height := FHeight; end; function TGPMetafileHeader.IsWmf() : Boolean; begin Result := ((FType = MetafileTypeWmf) or (FType = MetafileTypeWmfPlaceable)); end; function TGPMetafileHeader.IsWmfPlaceable() : Boolean; begin Result := (FType = MetafileTypeWmfPlaceable); end; function TGPMetafileHeader.IsEmf() : Boolean; begin Result := (FType = MetafileTypeEmf); end; function TGPMetafileHeader.IsEmfOrEmfPlus() : Boolean; begin Result := (FType >= MetafileTypeEmf); end; function TGPMetafileHeader.IsEmfPlus() : Boolean; begin Result := (FType >= MetafileTypeEmfPlusOnly) end; function TGPMetafileHeader.IsEmfPlusDual() : Boolean; begin Result := (FType = MetafileTypeEmfPlusDual) end; function TGPMetafileHeader.IsEmfPlusOnly() : Boolean; begin Result := (FType = MetafileTypeEmfPlusOnly) end; function TGPMetafileHeader.IsDisplay() : Boolean; begin Result := (IsEmfPlus and ((FEmfPlusFlags and GDIP_EMFPLUSFLAGS_DISPLAY) <> 0)); end; function TGPMetafileHeader.GetWmfHeader() : PMetaHeader; begin if( IsWmf ) then Result := @FHeader.FWmfHeader else Result := NIL; end; function TGPMetafileHeader.GetEmfHeader() : PENHMETAHEADER3; begin if( IsEmfOrEmfPlus ) then Result := @FHeader.FEmfHeader else Result := NIL; end; function GetStatus(Stat: TGPStatus) : String; begin case Stat of Ok : Result := 'Ok'; GenericError : Result := 'GenericError'; InvalidParameter : Result := 'InvalidParameter'; OutOfMemory : Result := 'OutOfMemory'; ObjectBusy : Result := 'ObjectBusy'; InsufficientBuffer : Result := 'InsufficientBuffer'; NotImplemented : Result := 'NotImplemented'; Win32Error : Result := 'Win32Error'; WrongState : Result := 'WrongState'; Aborted : Result := 'Aborted'; FileNotFound : Result := 'FileNotFound'; ValueOverflow : Result := 'ValueOverflow'; AccessDenied : Result := 'AccessDenied'; UnknownImageFormat : Result := 'UnknownImageFormat'; FontFamilyNotFound : Result := 'FontFamilyNotFound'; FontStyleNotFound : Result := 'FontStyleNotFound'; NotTrueTypeFont : Result := 'NotTrueTypeFont'; UnsupportedGdiplusVersion : Result := 'UnsupportedGdiplusVersion'; GdiplusNotInitialized : Result := 'GdiplusNotInitialized'; PropertyNotFound : Result := 'PropertyNotFound'; PropertyNotSupported : Result := 'PropertyNotSupported'; ProfileNotFound : Result := 'ProfileNotFound'; else Result := '<UnKnown>'; end; end; type TGPColorNamePair = record Color : TGPColor; Name : String; end; const GPColorNames : array [ 0..140 ] of TGPColorNamePair = ( (Color:$FFF0F8FF; Name:'aclAliceBlue' ), (Color:$FFFAEBD7; Name:'aclAntiqueWhite' ), (Color:$FF00FFFF; Name:'aclAqua' ), (Color:$FF7FFFD4; Name:'aclAquamarine' ), (Color:$FFF0FFFF; Name:'aclAzure' ), (Color:$FFF5F5DC; Name:'aclBeige' ), (Color:$FFFFE4C4; Name:'aclBisque' ), (Color:$FF000000; Name:'aclBlack' ), (Color:$FFFFEBCD; Name:'aclBlanchedAlmond' ), (Color:$FF0000FF; Name:'aclBlue' ), (Color:$FF8A2BE2; Name:'aclBlueViolet' ), (Color:$FFA52A2A; Name:'aclBrown' ), (Color:$FFDEB887; Name:'aclBurlyWood' ), (Color:$FF5F9EA0; Name:'aclCadetBlue' ), (Color:$FF7FFF00; Name:'aclChartreuse' ), (Color:$FFD2691E; Name:'aclChocolate' ), (Color:$FFFF7F50; Name:'aclCoral' ), (Color:$FF6495ED; Name:'aclCornflowerBlue' ), (Color:$FFFFF8DC; Name:'aclCornsilk' ), (Color:$FFDC143C; Name:'aclCrimson' ), (Color:$FF00FFFF; Name:'aclCyan' ), (Color:$FF00008B; Name:'aclDarkBlue' ), (Color:$FF008B8B; Name:'aclDarkCyan' ), (Color:$FFB8860B; Name:'aclDarkGoldenrod' ), (Color:$FFA9A9A9; Name:'aclDarkGray' ), (Color:$FF006400; Name:'aclDarkGreen' ), (Color:$FFBDB76B; Name:'aclDarkKhaki' ), (Color:$FF8B008B; Name:'aclDarkMagenta' ), (Color:$FF556B2F; Name:'aclDarkOliveGreen' ), (Color:$FFFF8C00; Name:'aclDarkOrange' ), (Color:$FF9932CC; Name:'aclDarkOrchid' ), (Color:$FF8B0000; Name:'aclDarkRed' ), (Color:$FFE9967A; Name:'aclDarkSalmon' ), (Color:$FF8FBC8B; Name:'aclDarkSeaGreen' ), (Color:$FF483D8B; Name:'aclDarkSlateBlue' ), (Color:$FF2F4F4F; Name:'aclDarkSlateGray' ), (Color:$FF00CED1; Name:'aclDarkTurquoise' ), (Color:$FF9400D3; Name:'aclDarkViolet' ), (Color:$FFFF1493; Name:'aclDeepPink' ), (Color:$FF00BFFF; Name:'aclDeepSkyBlue' ), (Color:$FF696969; Name:'aclDimGray' ), (Color:$FF1E90FF; Name:'aclDodgerBlue' ), (Color:$FFB22222; Name:'aclFirebrick' ), (Color:$FFFFFAF0; Name:'aclFloralWhite' ), (Color:$FF228B22; Name:'aclForestGreen' ), (Color:$FFFF00FF; Name:'aclFuchsia' ), (Color:$FFDCDCDC; Name:'aclGainsboro' ), (Color:$FFF8F8FF; Name:'aclGhostWhite' ), (Color:$FFFFD700; Name:'aclGold' ), (Color:$FFDAA520; Name:'aclGoldenrod' ), (Color:$FF808080; Name:'aclGray' ), (Color:$FF008000; Name:'aclGreen' ), (Color:$FFADFF2F; Name:'aclGreenYellow' ), (Color:$FFF0FFF0; Name:'aclHoneydew' ), (Color:$FFFF69B4; Name:'aclHotPink' ), (Color:$FFCD5C5C; Name:'aclIndianRed' ), (Color:$FF4B0082; Name:'aclIndigo' ), (Color:$FFFFFFF0; Name:'aclIvory' ), (Color:$FFF0E68C; Name:'aclKhaki' ), (Color:$FFE6E6FA; Name:'aclLavender' ), (Color:$FFFFF0F5; Name:'aclLavenderBlush' ), (Color:$FF7CFC00; Name:'aclLawnGreen' ), (Color:$FFFFFACD; Name:'aclLemonChiffon' ), (Color:$FFADD8E6; Name:'aclLightBlue' ), (Color:$FFF08080; Name:'aclLightCoral' ), (Color:$FFE0FFFF; Name:'aclLightCyan' ), (Color:$FFFAFAD2; Name:'aclLightGoldenrodYellow' ), (Color:$FFD3D3D3; Name:'aclLightGray' ), (Color:$FF90EE90; Name:'aclLightGreen' ), (Color:$FFFFB6C1; Name:'aclLightPink' ), (Color:$FFFFA07A; Name:'aclLightSalmon' ), (Color:$FF20B2AA; Name:'aclLightSeaGreen' ), (Color:$FF87CEFA; Name:'aclLightSkyBlue' ), (Color:$FF778899; Name:'aclLightSlateGray' ), (Color:$FFB0C4DE; Name:'aclLightSteelBlue' ), (Color:$FFFFFFE0; Name:'aclLightYellow' ), (Color:$FF00FF00; Name:'aclLime' ), (Color:$FF32CD32; Name:'aclLimeGreen' ), (Color:$FFFAF0E6; Name:'aclLinen' ), (Color:$FFFF00FF; Name:'aclMagenta' ), (Color:$FF800000; Name:'aclMaroon' ), (Color:$FF66CDAA; Name:'aclMediumAquamarine' ), (Color:$FF0000CD; Name:'aclMediumBlue' ), (Color:$FFBA55D3; Name:'aclMediumOrchid' ), (Color:$FF9370DB; Name:'aclMediumPurple' ), (Color:$FF3CB371; Name:'aclMediumSeaGreen' ), (Color:$FF7B68EE; Name:'aclMediumSlateBlue' ), (Color:$FF00FA9A; Name:'aclMediumSpringGreen' ), (Color:$FF48D1CC; Name:'aclMediumTurquoise' ), (Color:$FFC71585; Name:'aclMediumVioletRed' ), (Color:$FF191970; Name:'aclMidnightBlue' ), (Color:$FFF5FFFA; Name:'aclMintCream' ), (Color:$FFFFE4E1; Name:'aclMistyRose' ), (Color:$FFFFE4B5; Name:'aclMoccasin' ), (Color:$FFFFDEAD; Name:'aclNavajoWhite' ), (Color:$FF000080; Name:'aclNavy' ), (Color:$FFFDF5E6; Name:'aclOldLace' ), (Color:$FF808000; Name:'aclOlive' ), (Color:$FF6B8E23; Name:'aclOliveDrab' ), (Color:$FFFFA500; Name:'aclOrange' ), (Color:$FFFF4500; Name:'aclOrangeRed' ), (Color:$FFDA70D6; Name:'aclOrchid' ), (Color:$FFEEE8AA; Name:'aclPaleGoldenrod' ), (Color:$FF98FB98; Name:'aclPaleGreen' ), (Color:$FFAFEEEE; Name:'aclPaleTurquoise' ), (Color:$FFDB7093; Name:'aclPaleVioletRed' ), (Color:$FFFFEFD5; Name:'aclPapayaWhip' ), (Color:$FFFFDAB9; Name:'aclPeachPuff' ), (Color:$FFCD853F; Name:'aclPeru' ), (Color:$FFFFC0CB; Name:'aclPink' ), (Color:$FFDDA0DD; Name:'aclPlum' ), (Color:$FFB0E0E6; Name:'aclPowderBlue' ), (Color:$FF800080; Name:'aclPurple' ), (Color:$FFFF0000; Name:'aclRed' ), (Color:$FFBC8F8F; Name:'aclRosyBrown' ), (Color:$FF4169E1; Name:'aclRoyalBlue' ), (Color:$FF8B4513; Name:'aclSaddleBrown' ), (Color:$FFFA8072; Name:'aclSalmon' ), (Color:$FFF4A460; Name:'aclSandyBrown' ), (Color:$FF2E8B57; Name:'aclSeaGreen' ), (Color:$FFFFF5EE; Name:'aclSeaShell' ), (Color:$FFA0522D; Name:'aclSienna' ), (Color:$FFC0C0C0; Name:'aclSilver' ), (Color:$FF87CEEB; Name:'aclSkyBlue' ), (Color:$FF6A5ACD; Name:'aclSlateBlue' ), (Color:$FF708090; Name:'aclSlateGray' ), (Color:$FFFFFAFA; Name:'aclSnow' ), (Color:$FF00FF7F; Name:'aclSpringGreen' ), (Color:$FF4682B4; Name:'aclSteelBlue' ), (Color:$FFD2B48C; Name:'aclTan' ), (Color:$FF008080; Name:'aclTeal' ), (Color:$FFD8BFD8; Name:'aclThistle' ), (Color:$FFFF6347; Name:'aclTomato' ), (Color:$00FFFFFF; Name:'aclTransparent' ), (Color:$FF40E0D0; Name:'aclTurquoise' ), (Color:$FFEE82EE; Name:'aclViolet' ), (Color:$FFF5DEB3; Name:'aclWheat' ), (Color:$FFFFFFFF; Name:'aclWhite' ), (Color:$FFF5F5F5; Name:'aclWhiteSmoke' ), (Color:$FFFFFF00; Name:'aclYellow' ), (Color:$FF9ACD32; Name:'aclYellowGreen' ) ); procedure GetStandardRGBAColorNames( ANames : TStrings ); var I : Integer; begin for I := 0 to Sizeof( GPColorNames ) div Sizeof( GPColorNames[ 0 ] ) - 1 do ANames.Add( GPColorNames[ I ].Name ); end; function HexToUInt( AValue : String ) : Cardinal; var I : Integer; Tmp : Byte; begin Result := 0; AValue := UpperCase( AValue ); Tmp := 0; for I := 1 to Length( AValue ) do begin if(( I = 1 ) and ( AValue[ 1 ] = '$' )) then Continue; case( AValue[ I ] ) of '0' : Tmp := 0; '1' : Tmp := 1; '2' : Tmp := 2; '3' : Tmp := 3; '4' : Tmp := 4; '5' : Tmp := 5; '6' : Tmp := 6; '7' : Tmp := 7; '8' : Tmp := 8; '9' : Tmp := 9; 'A' : Tmp := 10; 'B' : Tmp := 11; 'C' : Tmp := 12; 'D' : Tmp := 13; 'E' : Tmp := 14; 'F' : Tmp := 15; else Break; end; Result := Result * 16; Result := Result + Tmp; end; end; function StringToRGBAColor( AValue : String ) : TGPColor; var I : Integer; begin AValue := Trim( AValue ); Result := aclBlack; if( Length( AValue ) < 1 ) then Exit; if( AValue[ 1 ] = '$' ) then begin Result := HexToUInt( AValue ); // HexToInt( PChar( @AValue[ 2 ] ), PAnsiChar( @Result ), 8 ); Exit; end else for I := 0 to Sizeof( GPColorNames ) div Sizeof( GPColorNames[ 0 ] ) - 1 do if( GPColorNames[ I ].Name = AValue ) then begin Result := GPColorNames[ I ].Color; Exit; end; Result := StrToIntDef( AValue, Integer( aclBlack )); end; function RGBAColorToString( AValue : TGPColor ) : String; var I : Integer; begin for I := 0 to Sizeof( GPColorNames ) div Sizeof( GPColorNames[ 0 ] ) - 1 do if( GPColorNames[ I ].Color = AValue ) then begin Result := GPColorNames[ I ].Name; Exit; end; Result := '$' + IntToHex( AValue, 8 ); end; procedure StartIGDIPlus(); begin if( GInitialized ) then Exit; GInitialized := True; // Initialize StartupInput structure StartupInput.DebugEventCallback := NIL; StartupInput.SuppressBackgroundThread := True; StartupInput.SuppressExternalCodecs := False; StartupInput.GdiplusVersion := 1; // Initialize GDI+ GdiplusStartup( gdiplusToken, @StartupInput, @StartupOutput); if( Assigned( StartupOutput.NotificationHook )) then StartupOutput.NotificationHook( gdiplusBGThreadToken ); end; procedure StopIGDIPlus(); begin if( not GInitialized ) then Exit; GInitialized := False; if( Assigned(GenericSansSerifFontFamily)) then GenericSansSerifFontFamily.Free(); if( Assigned(GenericSerifFontFamily)) then GenericSerifFontFamily.Free(); if( Assigned(GenericMonospaceFontFamily)) then GenericMonospaceFontFamily.Free(); if( Assigned(GenericTypographicStringFormatBuffer)) then GenericTypographicStringFormatBuffer.Free(); if( Assigned(GenericDefaultStringFormatBuffer)) then GenericDefaultStringFormatBuffer.Free(); // Close GDI + if( Assigned( StartupOutput.NotificationUnhook )) then StartupOutput.NotificationUnhook( gdiplusBGThreadToken ); GdiplusShutdown(gdiplusToken); end; {$IFNDEF NO_IGDI_SELFINIT} initialization StartIGDIPlus(); finalization StopIGDIPlus(); {$ENDIF} end.
unit User; interface uses XMLDoc, Logger, ComObj, MSXML2_TLB, SysUtils, ExtCtrls, Graphics, Classes, FileSystemUtils, Windows, Contnrs, StringUtils, Forms, VersionInformation, ShellApi; type TFolderItem = class private pSmallIcon: TIcon; pFilePath: String; class var pUniqueID : Integer; function GetSmallIcon(): TIcon; function GetResolvedFilePath(): String; procedure SetFilePath(const value:String); public WasAutomaticallyAdded: Boolean; ID: Integer; Name: String; IsSeparator: Boolean; QuickLaunch: Boolean; property SmallIcon:TIcon read GetSmallIcon; property ResolvedFilePath:String read GetResolvedFilePath; property FilePath:String read pFilePath write SetFilePath; procedure AutoSetName(); procedure Launch(const silentErrors: Boolean = false); procedure ClearCachedIcons(); procedure AppendToXML(const xmlDoc:IXMLDomDocument; const parentElement:IXMLDOMElement); procedure LoadFromXML(const xmlElement:IXMLDOMElement); class function ResolveFilePath(const filePath: String):String; class function ConvertToRelativePath(const filePath: String): String; constructor Create(); end; TSpecialFolderNames = record Music: String; Pictures: String; Videos: String; Documents: String; end; TUser = class(TObject) private pFilePath: String; pXML: IXMLDomDocument; pSaveTimer: TTimer; pFolderItems: TObjectList; pSpecialFolderNames: TSpecialFolderNames; pSaveFolderItemsFlag: Boolean; pEditFolderItemForm: TObject; procedure ScheduleSave(); procedure ScheduleSave_Timer(Sender: TObject); procedure SetExclusions(const value: TStringList); function GetAutoAddExclusions(): TStringList; public procedure Save(); procedure DoQuickLaunch(); function GetUserSetting(const name: String): String; procedure SetUserSetting(const name: String; const value: String); procedure AutomaticallyAddNewApps(); procedure AddFolderItem(const folderItem: TFolderItem); function GetFolderItemAt(const iIndex: Word): TFolderItem; function GetFolderItemByID(const iFolderItemID: Integer): TFolderItem; function FolderItemCount(): Word; procedure ReorderAndDeleteFolderItems(const folderItemIDs: Array of Integer); constructor Create(const filePath: String); function EditNewFolderItem(): TFolderItem; function EditFolderItem(const folderItem: TFolderItem): Boolean; procedure InvalidateFolderItems(); procedure RemoveFolderItem(const folderItem: TFolderItem); procedure AddAutoAddExclusion(const filePath: String); procedure RemoveAutoAddExclusion(const filePath: String); property Exclusions: TStringList read GetAutoAddExclusions write SetExclusions; end; const DEFAULT_SETTINGS: Array[0..6] of Array[0..1] of String = ( ('PortableAppsPath', '%DRIVE%\PortableApps'), ('DocumentsPath', '%DRIVE%\Documents'), ('Locale', 'en'), ('IsFirstFolderItemRefresh', 'true'), ('AutoAddExclusions', ''), ('AnimationsEnabled', 'false'), ('LastWindowSettings', '') ); implementation uses Main, EditFolderItemUnit; // ***************************************************************************** // // TFolderItem Class // // ***************************************************************************** constructor TFolderItem.Create(); begin { TODO: Clear icon cache when changing file path } IsSeparator := false; pUniqueID := pUniqueID + 1; ID := pUniqueID; WasAutomaticallyAdded := false; QuickLaunch := false; end; procedure TFolderItem.ClearCachedIcons(); begin if pSmallIcon = nil then Exit; FreeAndNil(pSmallIcon); end; class function TFolderItem.ConvertToRelativePath; begin result := Trim(filePath); if UpperCase(Copy(result, 1, 2)) = UpperCase(GetApplicationDrive()) then begin result := '%DRIVE%' + Copy(result, 3, Length(result)); end; end; procedure TFolderItem.AutoSetName; begin Name := ExtractFileName(ResolvedFilePath); try versionInfo := TVersionInfo.CreateFile(ResolvedFilePath); if versionInfo.FileDescription <> '' then begin Name := versionInfo.FileDescription; end; finally FreeAndNil(versionInfo); end; end; procedure TFolderItem.SetFilePath; begin if pFilePath = value then Exit; pFilePath := value; ClearCachedIcons(); end; function TFolderItem.GetSmallIcon(): TIcon; begin result := nil; if IsSeparator then Exit; if pSmallIcon <> nil then begin result := pSmallIcon; Exit; end; result := GetFolderItemIcon(ResolvedFilePath, true); end; class function TFolderItem.ResolveFilePath(const filePath: String):String; begin result := filePath; result := SearchAndReplace(filePath, '%DRIVE%', GetApplicationDrive()); end; function TFolderItem.GetResolvedFilePath():String; begin result := ResolveFilePath(FilePath); end; procedure TFolderItem.AppendToXML; var eFolderItem: IXMLDOMElement; begin eFolderItem := xmlDoc.createElement('FolderItem'); parentElement.appendChild(eFolderItem); eFolderItem.setAttribute('name', Name); eFolderItem.setAttribute('filePath', FilePath); eFolderItem.setAttribute('isSeparator', StringConv(IsSeparator)); eFolderItem.setAttribute('wasAutomaticallyAdded', StringConv(WasAutomaticallyAdded)); eFolderItem.setAttribute('quickLaunch', StringConv(QuickLaunch)); end; procedure TFolderItem.Launch; var r: Cardinal; fileDirectory: String; begin fileDirectory := ResolveFilePath(ExtractFilePath(FilePath)); ilog('Launching: ' + ExtractFileName(FilePath)); ilog('In directory: ' + fileDirectory); r := ShellExecute(Application.Handle, 'open', PChar(ResolvedFilePath), nil, PChar(fileDirectory), SW_SHOWNORMAL); if Integer(r) <= 32 then begin if not silentErrors then TMain.Instance.ErrorMessage(TMain.Instance.Loc.GetString('FolderItem.LaunchFileError', IntToStr(r))); elog('#' + IntToStr(r) + ': Couldn''t launch: ' + FilePath); end; end; procedure TFolderItem.LoadFromXML; begin Name := xmlElement.getAttribute('name'); FilePath := xmlElement.getAttribute('filePath'); IsSeparator := xmlElement.getAttribute('isSeparator') = 'true'; WasAutomaticallyAdded := xmlElement.getAttribute('wasAutomaticallyAdded') = 'true'; QuickLaunch := xmlElement.getAttribute('quickLaunch') = 'true'; end; // ***************************************************************************** // // TUser Class // // ***************************************************************************** constructor TUser.Create(const filePath: String); var eRoot: IXMLDOMElement; success: Boolean; eFolderItems, eFolderItem: IXMLDOMElement; i, j: Integer; folderItem: TFolderItem; begin pFolderItems := TObjectList.Create(false); pSaveFolderItemsFlag := false; pSpecialFolderNames.Music := 'Music'; pSpecialFolderNames.Videos := 'Videos'; pSpecialFolderNames.Pictures := 'Pictures'; pSpecialFolderNames.Documents := 'Documents'; pFilePath := filePath; success := false; pXML := CreateOleObject('Microsoft.XMLDOM') as IXMLDomDocument; if FileExists(filePath) then begin success := pXML.Load(filePath); if success then begin ilog('Settings loaded successfully from: ' + pFilePath); ilog('Creating folder items...'); for i := 0 to pXML.documentElement.childNodes.length - 1 do begin eFolderItems := pXML.documentElement.childNodes.item[i] as IXMLDOMElement; if eFolderItems.nodeName <> 'FolderItems' then continue; for j := 0 to eFolderItems.childNodes.length - 1 do begin eFolderItem := eFolderItems.childNodes.item[j] as IXMLDOMElement; if eFolderItem.nodeName <> 'FolderItem' then continue; folderItem := TFolderItem.Create(); folderItem.LoadFromXML(eFolderItem); pFolderItems.Add(TObject(folderItem)); end; break; end; end else begin elog('Coulnd''t load settings from: ' + pFilePath); end; end; if not success then begin ilog('Creating new setting file...'); eRoot := pXML.createElement('MiniLaunchBar'); eRoot.setAttribute('version', '1.0'); pXML.appendChild(eRoot); end; end; procedure TUser.DoQuickLaunch; var i: Integer; folderItem: TFolderItem; begin for i := 0 to pFolderItems.Count - 1 do begin folderItem := TFolderItem(pFolderItems[i]); if folderItem.QuickLaunch then begin folderItem.Launch(); end; end; end; procedure TUser.AddFolderItem; begin pFolderItems.Add(TObject(folderItem)); InvalidateFolderItems(); end; procedure TUser.RemoveFolderItem; begin if folderItem.WasAutomaticallyAdded then begin AddAutoAddExclusion(folderItem.FilePath); end; pFolderItems.Remove(TObject(folderItem)); folderItem.Free(); end; procedure TUser.InvalidateFolderItems(); begin pSaveFolderItemsFlag := true; ScheduleSave(); end; procedure TUser.SetExclusions(const value: TStringList); var s: String; i: Integer; begin s := ''; for i := 0 to value.Count - 1 do begin if s <> '' then s := s + ','; s := s + value[i]; end; SetUserSetting('AutoAddExclusions', s); end; function TUser.GetAutoAddExclusions; begin result := SplitString(',', GetUserSetting('AutoAddExclusions')); end; procedure TUser.AddAutoAddExclusion; var exclusions: TStringList; i: Integer; begin exclusions := GetAutoAddExclusions(); for i := 0 to exclusions.Count - 1 do begin if TFolderItem.ResolveFilePath(exclusions[i]) = TFolderItem.ResolveFilePath(filePath) then begin ilog('This file path is already in the exclusion list: ' + filePath); Exit; end; end; exclusions.Add(filePath); SetExclusions(exclusions); end; procedure TUser.RemoveAutoAddExclusion; var exclusions: TStringList; i: Integer; modified: Boolean; begin exclusions := GetAutoAddExclusions(); modified := false; for i := exclusions.Count - 1 downto 0 do begin if TFolderItem.ResolveFilePath(exclusions[i]) = TFolderItem.ResolveFilePath(filePath) then begin exclusions.Delete(i); modified := true; end; end; if modified then SetExclusions(exclusions); end; procedure TUser.ReorderAndDeleteFolderItems(const folderItemIDs: Array of Integer); var newFolderItems: TObjectList; i, j: Integer; folderItem: TFolderItem; doIt, foundIt: Boolean; begin doIt := false; // --------------------------------------------------------------------------- // Check if something needs to be updated // --------------------------------------------------------------------------- if Length(folderItemIDs) <> pFolderItems.Count then begin // If the number of folder items is different from the number of // provided IDs - do the update doIt := true; end else begin // If the order of the folder items is different from the order // of the provided folder IDs - do the update for i := 0 to Length(folderItemIDs) - 1 do begin if folderItemIDs[i] <> TFolderItem(pFolderItems[i]).ID then begin doIt := true; break; end; end; end; // Quick exit if there's nothing to do if not doIt then Exit; // Create the list that is going to hold the new folder items newFolderItems := TObjectList.Create(false); // --------------------------------------------------------------------------- // Check if we need to delete some of the folder items (i.e. those that // are missing from the list of IDs) // --------------------------------------------------------------------------- for i := pFolderItems.Count - 1 downto 0 do begin folderItem := TFolderItem(pFolderItems[i]); foundIt := false; for j := 0 to Length(folderItemIDs) - 1 do begin if folderItem.ID = folderItemIDs[j] then begin foundIt := true; break; end; end; if not foundIt then begin // If we couldn't find it, remove the folder item from the list RemoveFolderItem(folderItem); //folderItem.Free(); //pFolderItems.Remove(TObject(folderItem)); end; end; // --------------------------------------------------------------------------- // Update the order of the folder items // --------------------------------------------------------------------------- for i := 0 to Length(folderItemIDs) - 1 do begin folderItem := GetFolderItemByID(folderItemIDs[i]); if folderItem = nil then begin wlog('TUser.SetFolderItemsOrder: Unknown folder item ID: ' + IntToStr(folderItemIDs[i])); continue; end; newFolderItems.Add(TObject(folderItem)); end; pFolderItems.Clear(); pFolderItems := newFolderItems; pSaveFolderItemsFlag := true; ScheduleSave(); end; function TUser.EditNewFolderItem(): TFolderItem; var folderItem: TFolderItem; begin result := nil; folderItem := TFolderItem.Create(); if EditFolderItem(folderItem) then begin AddFolderItem(folderItem); result := folderItem; end else begin FreeAndNil(folderItem); end; end; function TUser.EditFolderItem(const folderItem: TFolderItem): Boolean; var form: TEditFolderItemForm; begin if pEditFolderItemForm = nil then begin pEditFolderItemForm := TObject(TEditFolderItemForm.Create(TMain.Instance.mainForm)); end; form := TEditFolderItemForm(pEditFolderItemForm); form.Left := Round(Screen.Width / 2 - form.Width / 2); form.Top := Round(Screen.Height / 2 - form.Height / 2); form.LoadFolderItem(folderItem); form.ShowModal(); if form.SaveButtonClicked then begin folderItem.ClearCachedIcons(); InvalidateFolderItems(); end; result := form.SaveButtonClicked; end; function TUser.GetFolderItemAt(const iIndex: Word): TFolderItem; begin result := TFolderItem(pFolderItems[iIndex]); end; function TUser.GetFolderItemByID(const iFolderItemID: Integer): TFolderItem; var i: Word; folderItem: TFolderItem; begin result := nil; for i := 0 to pFolderItems.Count - 1 do begin folderItem := TFolderItem(pFolderItems[i]); if folderItem.ID = iFolderItemID then begin result := folderItem; break; end; end; end; function TUser.FolderItemCount(): Word; begin result := pFolderItems.Count; end; procedure TUser.AutomaticallyAddNewApps(); var directoryContents: TStringList; i, j: Integer; filePath: String; fileExtension: String; folderItem: TFolderItem; exclusions: TStringList; skipIt: Boolean; changeFlag: Boolean; documentFolderContent: TStringList; isFirstFolderItemRefresh: Boolean; documentPath: String; begin ilog('Looking for new applications..'); // Set this flag to true whenever the FolderItems list is modified changeFlag := false; // --------------------------------------------------------------------------- // Get the list of excluded folder items // --------------------------------------------------------------------------- //SetUserSetting('FolderItemExclusions', ''); exclusions := SplitString(',', GetUserSetting('AutoAddExclusions')); // --------------------------------------------------------------------------- // Check if it's the first time that the application is launched // --------------------------------------------------------------------------- isFirstFolderItemRefresh := GetUserSetting('IsFirstFolderItemRefresh') = 'true'; if isFirstFolderItemRefresh then SetUserSetting('IsFirstFolderItemRefresh', 'false'); // --------------------------------------------------------------------------- // Remove files that no longer exist // --------------------------------------------------------------------------- // for i := pFolderItems.Count - 1 downto 0 do begin // folderItem := TFolderItem(pFolderItems[i]); // if folderItem.IsSeparator then continue; // if (not FileExists(folderItem.FilePath)) and (not DirectoryExists(folderItem.FilePath)) then begin // wlog('Folder item doesn''t exist - removing it from the list: ' + folderItem.FilePath); // pFolderItems.Remove(TObject(folderItem)); // changeFlag := true; // end; // end; // --------------------------------------------------------------------------- // Get content of PortableApps folder. We only lookup for executable files // in the subfolders of the PortableApps folder // --------------------------------------------------------------------------- directoryContents := GetDirectoryContents(TFolderItem.ResolveFilePath(GetUserSetting('PortableAppsPath')), 1, 'exe'); // --------------------------------------------------------------------------- // Check if the document folder exists and if so, gets its subfolders // and add them to the list of folder items to process // --------------------------------------------------------------------------- documentPath := TFolderItem.ResolveFilePath(GetUserSetting('DocumentsPath')); if DirectoryExists(documentPath) then begin documentFolderContent := GetDirectoryContents(documentPath, 0, '*'); directoryContents.Add(documentPath); for i := 0 to documentFolderContent.Count - 1 do begin if not DirectoryExists(documentFolderContent[i]) then continue; directoryContents.Add(documentFolderContent[i]); end; end; // --------------------------------------------------------------------------- // Automatically add new applications. // Process the list of folders and files, creating FolderItems objects // as needed. // --------------------------------------------------------------------------- for i := 0 to directoryContents.Count - 1 do begin filePath := directoryContents[i]; fileExtension := ExtractFileExt(filePath); if (isFirstFolderItemRefresh) and (filePath = documentPath) then begin // The first time the application is launched, we add a separator between // the executables and the document folders. The separator can be removed // and won't be added. ilog('First launch - adding document separator...'); folderItem := TFolderItem.Create(); folderItem.IsSeparator := true; pFolderItems.Add(TObject(folderItem)); changeFlag := true; end; // Set this to true to prevent a folder item from being created // for the current file or folder skipIt := false; // Check if the file or folder is already in the FolderItems list for j := 0 to pFolderItems.Count - 1 do begin folderItem := TFolderItem(pFolderItems[j]); if folderItem.ResolvedFilePath = TFolderItem.ResolveFilePath(filePath) then begin skipIt := true; break; end; end; // Check if the file or folder is in the exclusion list for j := 0 to exclusions.Count - 1 do begin if TFolderItem.ResolveFilePath(exclusions[j]) = TFolderItem.ResolveFilePath(filePath) then begin skipIt := true; break; end; end; if not skipIt then begin // Create the folder item and add it to the list ilog('Adding new folder item: ' + filePath); folderItem := TFolderItem.Create(); folderItem.WasAutomaticallyAdded := true; folderItem.FilePath := TFolderItem.ConvertToRelativePath(filePath); folderItem.AutoSetName(); pFolderItems.Add(TObject(folderItem)); changeFlag := true; end; end; // --------------------------------------------------------------------------- // Loop through all the folder items and remove those that are in the // exclusion list. // --------------------------------------------------------------------------- // for i := pFolderItems.Count - 1 downto 0 do begin // folderItem := TFolderItem(pFolderItems[i]); // if folderItem.IsSeparator then continue; // // for j := 0 to exclusions.Count - 1 do begin // if AnsiPos(exclusions[j], folderItem.FilePath) >= 1 then begin // ilog('Folder item in exclusion list, so removing it: ' + folderItem.FilePath); // pFolderItems.Remove(TObject(folderItem)); // changeFlag := true; // end; // end; // // end; // --------------------------------------------------------------------------- // If the FolderItems list has been changed, schedule a save operation // --------------------------------------------------------------------------- if changeFlag then begin pSaveFolderItemsFlag := true; ScheduleSave(); end; end; procedure TUser.ScheduleSave_Timer(Sender: TObject); begin Save(); end; procedure TUser.ScheduleSave(); begin if pSaveTimer = nil then begin pSaveTimer := TTimer.Create(nil); pSaveTimer.Interval := 1000; pSaveTimer.OnTimer := ScheduleSave_Timer; end; pSaveTimer.Enabled := true; end; procedure TUser.Save(); var eFolderItems: IXMLDOMElement; i: Integer; folderItem: TFolderItem; begin ilog('Saving user settings to: ' + pFilePath); if pSaveTimer <> nil then pSaveTimer.Enabled := false; if pSaveFolderItemsFlag then begin ilog('Updating XML for folder items...'); for i := pXML.documentElement.childNodes.length - 1 downto 0 do begin eFolderItems := pXML.documentElement.childNodes.item[i] as IXMLDOMElement; if eFolderItems.nodeName = 'FolderItems' then begin pXML.documentElement.removeChild(eFolderItems); end; end; eFolderItems := pXML.createElement('FolderItems'); pXML.documentElement.appendChild(eFolderItems); for i := 0 to pFolderItems.Count - 1 do begin folderItem := TFolderItem(pFolderItems[i]); folderItem.AppendToXML(pXML, eFolderItems); end; pSaveFolderItemsFlag := false; end; pXML.save(pFilePath); end; function TUser.GetUserSetting(const name: String): String; var eSetting, eSettings: IXMLDOMElement; i, j: Integer; begin for i := 0 to pXML.documentElement.childNodes.length - 1 do begin eSettings := pXML.documentElement.childNodes.item[i] as IXMLDOMElement; if eSettings.nodeName = 'Settings' then begin for j := 0 to eSettings.childNodes.length - 1 do begin eSetting := eSettings.childNodes.item[j] as IXMLDOMElement; if eSetting.getAttribute('name') = name then begin result := eSetting.text; Exit; end; end; break; end; end; for i := 0 to Length(DEFAULT_SETTINGS) - 1 do begin if DEFAULT_SETTINGS[i][0] = name then begin result := DEFAULT_SETTINGS[i][1]; Exit; end; end; result := ''; end; procedure TUser.SetUserSetting(const name: String; const value: String); var eSetting, eSettings, eElement: IXMLDOMElement; i, j: Integer; done: Boolean; begin done := false; eSettings := nil; for i := 0 to pXML.documentElement.childNodes.length - 1 do begin eElement := pXML.documentElement.childNodes.item[i] as IXMLDOMElement; if eElement.nodeName = 'Settings' then begin eSettings := eElement; for j := 0 to eSettings.childNodes.length - 1 do begin eSetting := eSettings.childNodes.item[j] as IXMLDOMElement; if eSetting.getAttribute('name') = name then begin if eSetting.text = value then Exit; eSetting.text := value; done := true; break; end; end; break; end; end; if not done then begin if eSettings = nil then begin eSettings := pXML.createElement('Settings'); pXML.documentElement.appendChild(eSettings); end; eSetting := pXML.createElement('Setting'); eSetting.setAttribute('name', name); eSetting.text := value; eSettings.appendChild(eSetting); end; ScheduleSave(); end; end.
unit uDocDescription; interface uses SysUtils, Classes, Rtti, Db, Variants, TypInfo, dateVk, Dialogs, vkvariable, Windows, Controls, VkVariableBinding, fmVkDocDialog; type TBindingDescription = class(TObject) private FTypeClassItemBinding: TVkVariableBindingClass; public property TypeClassItemBinding: TVkVariableBindingClass read FTypeClassItemBinding write FTypeClassItemBinding; class function GetBindingDescription(ABindingClass:TVkVariableBindingClass):TBindingDescription; end; PDocStruDescriptionItem = ^RDocStruDescriptionItem; RDocStruDescriptionItem = record name: String; name_owner: String; // Если поле есть наименоваие объекта из owner GridLabel: String; DialogLabel: String; DisplayWidth: Integer; DisplayFormat: String; EditWidth: Integer; bEditInGrid: boolean; bNotInGrid: boolean; bNotEmpty: boolean; bHide: Boolean; BindingDescription: TBindingDescription; PageName: String; IsVariable: Boolean; end; TDocStruDescriptionList = class(TObject) private FList: TList; FPageCaptionList: TStringList; FOnInitialize: TNotifyEvent; procedure CheckIndexOf(AItem: PDocStruDescriptionItem); procedure SetOnInitialize(const Value: TNotifyEvent); public constructor Create; destructor Destroy;override; function GetDocStruDescriptionItem(AIndex:Integer):PDocStruDescriptionItem;overload; function GetDocStruDescriptionItem(const Aname: String):PDocStruDescriptionItem;overload; function IndexOfName(const Aname:String): Integer; procedure Add(const AName,AName_owner, AGridLabel, ADialogLabel: String; ADisplayWidth: Integer; const ADisplayFormat: String; AEditWidth:Integer; AEditInGrid, ANotInGrid:Boolean; ABindingDescription:TBindingDescription;const APageName: String = ''; AIsVariable:Boolean = false); procedure AddField(AField: TField); procedure FillFields(ADataSet: TDataSet); // const AName,AName_owner, AGridLabel, ADialogLabel: String; ADisplayWidth: Integer; // const ADisplayFormat: String; AEditWidth:Integer; AEditInGrid, ANotInGrid:Boolean; // ATypeClassItemBinding: TVkVariableBindingClass); procedure Clear; function Count: Integer; procedure Delete(AIndex:Integer); procedure Initialize(AObject: TObject); property OnInitialize: TNotifyEvent read FOnInitialize write SetOnInitialize; property PageCaptionList: TStringList read FPageCaptionList; end; implementation { TDocStruDescriptionList } procedure TDocStruDescriptionList.Add(const AName, AName_owner, AGridLabel, ADialogLabel: String; ADisplayWidth: Integer; const ADisplayFormat: String; AEditWidth: Integer; AEditInGrid, ANotInGrid: Boolean; ABindingDescription: TBindingDescription;const APageName: String = ''; AIsVariable: Boolean = false); var _p: PDocStruDescriptionItem; begin New(_p); _p.name := Aname; _p.name_owner := AName_owner; _p.GridLabel := AGridLabel; _p.DialogLabel := ADialogLabel; _p.DisplayWidth := ADisplayWidth; _p.DisplayFormat := ADisplayFormat; _p.EditWidth :=AEditWidth; _p.bEditInGrid := AEditInGrid; _p.bNotInGrid := ANotInGrid; _p.BindingDescription := ABindingDescription; _p.PageName := APageName; _p.IsVariable := AIsVariable; CheckIndexOf(_p); FList.Add(_p); if FPageCaptionList.IndexOf(_p.PageName)=-1 then FPageCaptionList.AddObject(_p.PageName,Pointer(1)); end; procedure TDocStruDescriptionList.AddField(AField: TField); var _p: PDocStruDescriptionItem; begin if IndexOfName(AField.FieldName)=-1 then begin New(_p); _p.name := AField.FieldName; _p.name_owner := ''; _p.GridLabel := AField.FieldName; _p.DialogLabel := AField.FieldName; _p.DisplayWidth := AField.DisplayWidth; _p.DisplayFormat := ''; _p.EditWidth := AField.DisplayWidth; _p.bEditInGrid := False; _p.bNotInGrid := True; _p.BindingDescription := nil; FList.Add(_p); end; end; procedure TDocStruDescriptionList.CheckIndexOf(AItem: PDocStruDescriptionItem); begin if IndexOfName(AItem.name)>-1 then raise Exception.CreateFmt('Dublicate name %s',[AItem.name]); end; procedure TDocStruDescriptionList.Clear; begin while FList.Count>0 do Delete(0); end; function TDocStruDescriptionList.Count: Integer; begin Result := FList.Count; end; constructor TDocStruDescriptionList.Create; begin FList := TList.Create; FPageCaptionList:= TStringList.Create; end; procedure TDocStruDescriptionList.Delete(AIndex: Integer); var _p: PDocStruDescriptionItem; begin _p := GetDocStruDescriptionItem(AIndex); _p.BindingDescription.Free; Dispose(_p); FList.Delete(AIndex); end; destructor TDocStruDescriptionList.Destroy; begin Clear; FreeAndNil(FList); FreeAndNil(FPageCaptionList); inherited; end; procedure TDocStruDescriptionList.FillFields(ADataSet: TDataSet); var fld: TField; begin for fld in ADataSet.Fields do AddField(fld); end; function TDocStruDescriptionList.GetDocStruDescriptionItem(const Aname: String): PDocStruDescriptionItem; var I: Integer; begin Result := nil; i := IndexOfname(Aname); if i>-1 then Result := GetDocStruDescriptionItem(i); end; function TDocStruDescriptionList.GetDocStruDescriptionItem(AIndex: Integer): PDocStruDescriptionItem; begin Result := PDocStruDescriptionItem(FList[AIndex]); end; function TDocStruDescriptionList.IndexOfName(const Aname: String): Integer; var I : Integer; _p: PDocStruDescriptionItem; begin Result := -1; for I := 0 to FList.Count-1 do begin _p := GetDocStruDescriptionItem(i); if SameText(_p.name,Aname) then begin Result := i; Break; end; end; end; procedure TDocStruDescriptionList.Initialize(AObject: TObject); var _Item: TVkVariableBinding; i: Integer; begin if Assigned(FOnInitialize) then if AObject is TVkVariableBindingCollection then begin for i:=0 to TVkVariableBindingCollection(AObject).Count-1 do begin _Item := TVkVariableBindingCollection(AObject).Items[i]; FOnInitialize(_Item); end; end else FOnInitialize(AObject); end; procedure TDocStruDescriptionList.SetOnInitialize(const Value: TNotifyEvent); begin FOnInitialize := Value; end; { TBindingDescription } class function TBindingDescription.GetBindingDescription( ABindingClass: TVkVariableBindingClass): TBindingDescription; begin Result := self.Create; Result.FTypeClassItemBinding := ABindingClass; end; end.
unit rsdat_pack; {$mode objfpc}{$H+} interface uses Classes, SysUtils, rsdat_common; type { TRSDatPacker } TRSDatPacker = class private Sections: array of TSection; Data: TMemoryStream; procedure FreeSections; procedure ReadSectionFiles(const basepath: string); procedure WriteData(path: string); procedure WriteHeader(path: string); procedure WriteNodeData(node: PFileNode); procedure WriteFileEntries(node: PFileNode; const base_offset: integer); public procedure PackDirectory(const path: string); constructor Create; destructor Destroy; override; end; //************************************************************************************************** implementation procedure ReadFileNodes(parent: PFileNode; path: string); var node: PFileNode; info: TSearchRec; n: integer; f: file; subdir_path: string; begin path := IncludeTrailingPathDelimiter(path); n := 0; if FindFirst(path + '*', faDirectory, Info) = 0 then begin repeat if (info.Name <> '.') and (info.name <> '..') then begin new(node); node^.name := info.Name; node^.is_directory := false; node^.data := nil; node^.size := 0; node^.subentries_count := 0; node^.offset := 0; //traverse subdirectory or load file if (info.Attr and faDirectory) > 0 then begin node^.is_directory := true; subdir_path := path + node^.name; Writeln('reading dir ', subdir_path); ReadFileNodes(node, subdir_path); node^.subentries_count := CountSubNodes(node) - 1; Writeln('dir subentries: ', node^.subentries_count); end else begin Writeln('reading file ', path + node^.name); AssignFile(f, path + node^.name); Reset(f, 1); node^.size := FileSize(f); node^.Data := Getmem(node^.size); BlockRead(f, node^.Data^, node^.size); CloseFile(f); end; n += 1; SetLength(parent^.nodes, n); parent^.nodes[n-1] := node; end; until FindNext(info) <> 0; end; end; procedure FreeFileNodes(node: PFileNode; const no_disposing: boolean = false); var i: integer; begin for i := 0 to Length(node^.nodes) - 1 do FreeFileNodes(node^.nodes[i]); node^.nodes := nil; if (not node^.is_directory) and (node^.Data <> nil) then freemem(node^.Data); if not no_disposing then dispose(node); end; { TRSDatPacker } procedure TRSDatPacker.ReadSectionFiles(const basepath: string); var n: integer; info: TSearchRec; section: TSection; node: TFileNode; begin n := 0; if FindFirst(basepath + '*', faDirectory, Info) = 0 then begin repeat if (info.Name <> '.') and (info.name <> '..') and ((info.Attr and faDirectory) > 0) then begin Writeln('reading section: ', info.name); ReadFileNodes(@node, basepath + info.name); node.name := info.Name; node.is_directory := true; node.data := nil; node.offset := 0; node.subentries_count := CountSubNodes(@node) - 1; section.name := info.name; section.root := node; n += 1; SetLength(Sections, n); Sections[n - 1] := section; end; until FindNext(info) <> 0; end; FindClose(Info); end; procedure TRSDatPacker.FreeSections; var i: integer; begin for i := 0 to Length(Sections) - 1 do FreeFileNodes(@Sections[i].root, true); Sections := nil; end; procedure TRSDatPacker.WriteNodeData(node: PFileNode); var i: integer; begin if node^.is_directory then begin for i := 0 to Length(node^.nodes) - 1 do begin WriteNodeData(node^.nodes[i]); end; end else begin node^.offset := Data.Position; Data.WriteBuffer(node^.Data^, node^.size); for i := 1 to 4 - (node^.size mod 4) do Data.WriteByte(0); end; end; { TFileEntry = packed record offset: longword; length: longword; padding: longword; type_flag: word; sub_entry_size: word; filename: array[0..15] of char; end; } procedure TRSDatPacker.WriteFileEntries(node: PFileNode; const base_offset: integer); var entry: TFileEntry; name: string; i: integer; begin entry.offset := node^.offset - base_offset; entry.length := CountSubNodeSizes(node); entry.padding := $ffffffff; entry.sub_entry_size := 0; if node^.is_directory then entry.sub_entry_size := (node^.subentries_count + 1) * 32; if node^.is_directory then entry.type_flag := FEDirectoryFlag else entry.type_flag := %00000010; writeln(stderr, format('name: %s size: %d dir: %s subsize: %d', [node^.Name, entry.length, BoolToStr(node^.is_directory), entry.sub_entry_size])); name := node^.Name; FillByte(entry.filename, 16, 0); for i := 0 to Length(name) - 1 do entry.filename[i] := name[i + 1]; Data.WriteBuffer(entry, 32); if node^.is_directory then begin for i := 0 to Length(node^.nodes) - 1 do begin WriteFileEntries(node^.nodes[i], base_offset); end; end; end; procedure TRSDatPacker.WriteData(path: string); var i, k: integer; head: pinteger; entries: integer; section: TSection; begin Data := TMemoryStream.Create; Data.Size := 1 shl 20; for i := 0 to Length(Sections) - 1 do begin section := Sections[i]; Writeln('writing section: ', section.name); section.offset := Data.Position; Data.WriteQWord(0); //offset + size placeholder Writeln('writing file data'); for k := 0 to Length(section.root.nodes) - 1 do WriteNodeData(section.root.nodes[k]); entries := section.root.subentries_count; head := pinteger (pbyte(Data.Memory) + section.offset); head^ := Data.Position - section.offset; head += 1; head^ := entries * 32; Writeln('writing file entries: ', entries); for k := 0 to Length(section.root.nodes) - 1 do WriteFileEntries(section.root.nodes[k], section.offset); //align? for k := 1 to 4 - (Data.Position mod 4) do Data.WriteByte(0); Sections[i] := section; end; Data.SaveToFile(path + 'DATA.DAT'); end; procedure TRSDatPacker.WriteHeader(path: string); var i, k: integer; f: file; section_name: string; name: array[1..28] of byte; begin AssignFile(f, path + 'DATA.HDR'); Rewrite(f, 1); for i := 0 to Length(Sections) - 1 do begin section_name := Sections[i].Name; Fillbyte(name, 28, 0); for k := 1 to Length(section_name) do name[k] := byte( section_name[k] ); Blockwrite(f, name, 28); Blockwrite(f, Sections[i].offset, 4); end; CloseFile(f); end; procedure TRSDatPacker.PackDirectory(const path: string); var basepath: string; begin basepath := IncludeTrailingPathDelimiter(path); ReadSectionFiles(basepath); WriteData(basepath); WriteHeader(basepath); FreeSections; end; constructor TRSDatPacker.Create; begin end; destructor TRSDatPacker.Destroy; begin inherited Destroy; end; end.
unit DIPXSnd; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Die Unit enthaelt die IPX-Sender-Task, die Nachrichten per IPX an den Anzeigerechner sendet. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface uses ProcMB; var Mailbox: ProcMB.Mailbox; procedure IPXSenderTask; implementation uses RTKernel, RTIPX, Tools, Types, PIPX; {$F+} procedure IPXSenderTask; (***************************************************************************** Beschreibung: IPX-Sender-Task In: - Out: - *****************************************************************************) var IPXConnection: PIPX.IPXConnection; Connected, Sent: boolean; Message: TProcessMessage; begin Debug('Wurde erzeugt'); { Mailbox initialisieren } Debug('Initialisiere IPX Mailbox'); ProcMB.InitMailbox(Mailbox, cIPXMailboxSlots, 'IPX mailbox'); Debug('IPX Mailbox initialisiert'); { IPX-Kanal oeffnen } Debug('Oeffne Kanal zum Prozessrechner'); PIPX.OpenChannel(cIPXSendBuffers); Debug('Kanal zum Prozessrechner geoeffnet'); { Variablen initialisieren } Connected := false; Sent := true; while true do begin { Pruefen, ob Verbindung zum Anzeigerechner besteht } if not Connected then begin { Verbindung zum Anzeigerechner herstellen } Debug('Stelle Verbindung zum Prozessrechner her'); PIPX.Connect(IPXConnection, cProcessComputerNodeName, cIPXConnectRetries, cIPXConnectTimeout, Connected); { Pruefen, ob Verbindung herstellen geklappt hat } if Connected then begin { Fehlermeldung } Debug('Verbindung zum Prozessrechner hergestellt'); ShowSystemStatus('Verbindung zum Prozessrechner hergestellt'); end else begin { Info ausgebene } Debug('Keine Verbindung zum Prozessrechner'); ShowSystemStatus('Keine Verbindung zum Prozessrechner'); end; end else begin { Pruefen, ob letzte Nachricht gesendet werden konnte } if Sent then begin { Auf Nachrichten warten } Debug('Warte auf Nachrichten fuer den Prozessrechner'); ProcMB.Get(Mailbox, Message); Debug('Nachricht empfangen'); end; { Nachricht senden } Debug('Sende Nachricht an Prozessrechner'); PIPX.IPXSend(IPXConnection, Addr(Message), Sent); { Pruefen, ob Nachricht gesendet wurde } if Sent then { Info ausgeben } Debug('Nachricht an Prozessrechner gesendet') else begin { Fehlermedlung } Debug('Nachricht konnte nicht an den Prozessrechner gesendet werden'); ShowSystemStatus('Nachricht konnte nicht an den Prozessrechner ' + 'gesendet werden'); end; end; { Taskwechsel } RTKernel.Delay(0); end; end; end.
{$include kode.inc} unit fx_eventhorizon; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_const, kode_types, kode_plugin, kode_parameter; type myPlugin = class(KPlugin) private _log2db, _db2log, slider1,slider2,slider3,slider4, thresh,threshdb, ceiling,ceildb,makeup,makeupdb, sc,scv,sccomp,peakdb,peaklvl, scratio,scmult : single; private procedure recalcAll; public procedure on_create; override; procedure on_parameterChange(AIndex:LongWord; AValue:Single); override; procedure on_processSample(AInputs,AOutputs:PPSingle); override; end; KPluginClass = myPLugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, //z_math, Math, kode_flags, kode_utils; //---------------------------------------------------------------------- // [internal] procedure myPlugin.recalcAll; begin // thresh := Exp(slider1 * _db2log); threshdb := slider1; ceiling := Exp(slider2 * _db2log); ceildb := slider2; makeup := Exp((ceildb-threshdb) * _db2log); makeupdb := ceildb - threshdb; sc := -slider3; scv := Exp( sc * _db2log); sccomp := Exp(-sc * _db2log); peakdb := ceildb + 25; peaklvl := Exp(peakdb * _db2log); scratio := slider4; scmult := Abs((ceildb - sc) / (peakdb - sc)); end; //---------- procedure myPlugin.on_create; begin FName := 'fx_eventhorizon'; FAuthor := 'skei.audio'; // thomas scott stillwell FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + fx_eventhorizon_id; KSetFlag(FFlags,kpf_perSample); FNumInputs := 2; FNumOutputs := 2; appendParameter( KParamFloat.create('threshold', 0, -30, 0, 0.1 )); appendParameter( KParamFloat.create('ceiling', -0.1, -20, 0, 0.1 ) ); appendParameter( KParamFloat.create('soft clip', 2, 0, 6, 0.01 ) ); //appendParameter( new parFloat("soft clip ratio","", 10.0, 3.0, 20.0, 0.1 ) ); // _log2db := 8.6858896380650365530225783783321; // 20 / ln(10) _db2log := 0.11512925464970228420089957273422; // ln(10) / 20 slider1 := 0; slider2 := 0; slider3 := 0; slider4 := 0; end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); var //p : ZParameter; v : Single; begin //p := FParameters[AIndex]; v := AValue;//p.from01(AValue); case AIndex of 0 : slider1 := v; 1 : slider2 := v; 2 : slider3 := v; //3 : slider4 := v; end; recalcAll; end; //---------- procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle); var spl0,spl1 : single; sign0,sign1,abs0,abs1,overdb0,overdb1 : single; begin spl0 := AInputs[0]^; spl1 := AInputs[1]^; //float peak = axMax(axAbs(spl0),axAbs(spl1)); spl0 := spl0 * makeup; spl1 := spl1 * makeup; sign0 := Sign(spl0); sign1 := Sign(spl1); abs0 := Abs(spl0); abs1 := Abs(spl1); overdb0 := 2.08136898 * Ln(abs0) * _log2db - ceildb; // c++ Log = pascal Ln ????? overdb1 := 2.08136898 * Ln(abs1) * _log2db - ceildb; if abs0 > scv then spl0 := sign0 * (scv + Exp(overdb0*scmult)*_db2log); if abs1 > scv then spl1 := sign1 * (scv + Exp(overdb1*scmult)*_db2log); spl0 := Min(ceiling,Abs(spl0)) * Sign(spl0); spl1 := Min(ceiling,Abs(spl1)) * Sign(spl1); AOutputs[0]^ := spl0; AOutputs[1]^ := spl1; end; //---------------------------------------------------------------------- end. (* /* // Copyright 2006, Thomas Scott Stillwell // 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. // //Redistributions in binary form must reproduce the above copyright notice, this list of conditions //and the following disclaimer in the documentation and/or other materials provided with the distribution. // //The name of Thomas Scott Stillwell may not be used to endorse or //promote products derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR //IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND //FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS //BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR //PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, //STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF //THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. desc:peak-eating limiter slider1:0.0<-30.0,0.0,0.1>Threshold slider2:-0.1<-20.0,0.0,0.1>Ceiling slider3:2.0<0,6.0,0.01>Soft clip (dB) //slider4:10<3,20,0.1>Soft clip ratio @init pi = 3.1415926535; log2db = 8.6858896380650365530225783783321; // 20 / ln(10) db2log = 0.11512925464970228420089957273422; // ln(10) / 20 @slider thresh=exp(slider1 * db2log); threshdb=slider1; ceiling=exp(slider2 * db2log); ceildb=slider2; makeup=exp((ceildb-threshdb) * db2log); makeupdb=ceildb-threshdb; sc = -slider3; scv = exp(sc * db2log); sccomp = exp(-sc * db2log); peakdb = ceildb+25; peaklvl = exp(peakdb * db2log); scratio = slider4; scmult = abs((ceildb - sc) / (peakdb - sc)); @sample peak=max(abs(spl0),abs(spl1)); spl0=spl0*makeup; spl1=spl1*makeup; sign0 = sign(spl0); sign1 = sign(spl1); abs0=abs(spl0); abs1=abs(spl1); overdb0 = 2.08136898 * log(abs0) * log2db - ceildb; overdb1 = 2.08136898 * log(abs1) * log2db - ceildb; abs0 > scv ? ( spl0=sign0*(scv + exp(overdb0*scmult)*db2log); ); abs1 > scv ? ( spl1=sign1*(scv + exp(overdb1*scmult)*db2log); ); spl0=min(ceiling,abs(spl0))*sign(spl0); spl1=min(ceiling,abs(spl1))*sign(spl1); */ *)
unit Unit5; interface uses Forms, Classes, ExtCtrls,Generics.Collections; Type TPilha = class private Index : Integer; FAowner : TPanel; List : TList; procedure AdicionandoImagemPilha(Valor : String); public procedure ReorganizarIndex; procedure AddProcesso(Valor : String); procedure RetiraProcesso; constructor Create(Aowner : TPanel); end; implementation uses Dialogs, Controls, SysUtils, Graphics; { TPilha } procedure TPilha.AddProcesso(Valor : String); begin If List.Count < 10 then begin if Trim(Valor) = '' then ShowMessage('Preencha o VALOR') else AdicionandoImagemPilha(Valor) end else end; procedure TPilha.AdicionandoImagemPilha(Valor : String); var FPanel : TPanel; begin FPanel := TPanel.Create(FAowner); FPanel.Parent := FAowner; FPanel.BorderStyle := bsNone; FPanel.BevelOuter := bvNone; FPanel.Height := 65; FPanel.Width := 40; FPanel.Color := Clred; FPanel.Align := alRight; FPanel.Caption := Valor; Inc(Index); List.Add(FPanel); end; constructor TPilha.Create(Aowner: TPanel); begin Self.FAowner := aowner; List := TList.Create; Index := 1; end; procedure TPilha.ReorganizarIndex; begin end; procedure TPilha.RetiraProcesso; var ObjTemp : TPanel; begin if List.Count <> 0 then begin ObjTemp := TPanel(List.Last); List.Remove(ObjTemp); FreeAndNil(ObjTemp); end else showmessage('PILHA VAZIA'); end; end.
unit Intfs; interface uses Classes, SysUtils, System.JSON; type TServerData = record FAddress: string; FPort: Integer; end; TRequestKind = (rkGet=0, rkPost); ISession = interface ['{A520DD7D-65CA-43D9-AB82-407D4BE83CFC}'] function IsValid() : Boolean; function GetLastError() : string; function Execute(const AReqUrl : string) : TJSONValue; overload; function Execute(const AReqUrl : string; const APayload : string) : TJSONValue; overload; function Delete(const AReqUrl : string) : Boolean; property Valid : Boolean read IsValid; property LastError : string read GetLastError; end; function _ToDate(const AVal : string) : TDateTime; function _ToDateTime(const AVal : string) : TDateTime; function _FromDateTime(const ADT : TDateTime) : string; implementation function _ToDate(const AVal: string): TDateTime; var y, m, d : Word; str : string; begin //"2018-05-18T19:00:00.000Z" str := Copy(Aval, 1, 4); y := StrToInt(str); str := Copy(AVal, 6, 2); m := StrToInt(str); str := Copy(AVal, 9, 2); d := StrToInt(str); Result := EncodeDate(y, m, d); end; function _ToDateTime(const AVal : string) : TDateTime; var y, m, d, hh, mm : Word; str : string; begin //"2018-05-18T19:00:00.000Z" str := Copy(Aval, 1, 4); y := StrToInt(str); str := Copy(AVal, 6, 2); m := StrToInt(str); str := Copy(AVal, 9, 2); d := StrToInt(str); str := Copy(AVal, 12, 2); hh := StrToInt(str); str := Copy(AVal, 15, 2); mm := StrToInt(str); Result := EncodeDate(y, m, d) + EncodeTime(hh, mm, 0, 0); end; function _FromDateTime(const ADT : TDateTime) : string; var y, m, d, hh, mm, ss, ms : Word; begin DecodeDate(ADT, y, m, d); DecodeTime(ADT, hh, mm, ss, ms); Result := Format('%d-%d-%d %d:%d:%d', [y, m, d, hh, mm, ss]); end; end.
unit TupleTests; interface procedure RunTests; implementation uses Commons, DelphiExt, System.SysUtils; function GetTupleOf2_1: Tuple<String, Integer>; begin Result := ['Hello World', 42]; //not checked at compile time end; function GetTupleOf2_2: Tuple<String, Boolean>; begin Result := [1234, True]; //not checked at compile time end; function GetTupleOf2_3: Tuple<String, TDateTime>; begin // compile time checked Result := Tuple<String, TDateTime>.MakeTuple('mystring', EncodeDate(2021, 9, 15)); end; function GetTupleOf3_1: Tuple<String, Integer, TDate>; begin Result := ['Hello World', 42, EncodeDate(2021, 9, 15)]; //not checked at compile time end; function GetTupleOf3_2: Tuple<String, Boolean, Extended>; begin Result := [1234, True, 1234.5678]; //not checked at compile time end; function GetTupleOf3_3: Tuple<String, TDateTime, Boolean>; begin // compile time checked Result := Tuple<String, TDateTime, Boolean> .MakeTuple('mystring', EncodeDate(2021, 9, 15), True); end; procedure TestInitFromArray_Int_Int; begin var t: Tuple<Integer, Integer> := [1, 2]; Assert(t.First = 1); Assert(t.Second = 2); var t1: Tuple<Int8, UInt8> := [1, 2]; Assert(t.First = 1); Assert(t.Second = 2); var t2: Tuple<Int16, UInt16> := [1, 2]; Assert(t.First = 1); Assert(t.Second = 2); var t3: Tuple<Int32, UInt32> := [1, 2]; Assert(t.First = 1); Assert(t.Second = 2); var t4: Tuple<Int64, UInt64> := [1, 2]; Assert(t.First = 1); Assert(t.Second = 2); end; procedure TestInitFromArray_String_Boolean; begin var t: Tuple<String, Boolean> := ['test', True]; Assert(t.First = 'test'); Assert(t.Second); var t1: Tuple<String, Boolean> := ['test', false]; Assert(t1.First = 'test'); Assert(not t1.Second); end; procedure RunTests; begin WriteLn(StringOfChar('~', 5) + ' TupleTests '.PadRight(30, '~')); Run('TestInitFromArray_Int_Int', TestInitFromArray_Int_Int); Run('TestInitFromArray_String_Boolean', TestInitFromArray_String_Boolean); end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [CONTABIL_INDICE] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ContabilIndiceController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, Generics.Collections, ContabilIndiceVO, ContabilIndiceValorVO; type TContabilIndiceController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TContabilIndiceVO>; class function ConsultaObjeto(pFiltro: String): TContabilIndiceVO; class procedure Insere(pObjeto: TContabilIndiceVO); class function Altera(pObjeto: TContabilIndiceVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses UDataModule, T2TiORM; class procedure TContabilIndiceController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TContabilIndiceVO>; begin try Retorno := TT2TiORM.Consultar<TContabilIndiceVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TContabilIndiceVO>(Retorno); finally end; end; class function TContabilIndiceController.ConsultaLista(pFiltro: String): TObjectList<TContabilIndiceVO>; begin try Result := TT2TiORM.Consultar<TContabilIndiceVO>(pFiltro, '-1', True); finally end; end; class function TContabilIndiceController.ConsultaObjeto(pFiltro: String): TContabilIndiceVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TContabilIndiceVO>(pFiltro, True); finally end; end; class procedure TContabilIndiceController.Insere(pObjeto: TContabilIndiceVO); var UltimoID: Integer; ContabilIndiceValorEnumerator: TEnumerator<TContabilIndiceValorVO>; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // Detalhes ContabilIndiceValorEnumerator := pObjeto.ListaContabilIndiceValorVO.GetEnumerator; try with ContabilIndiceValorEnumerator do begin while MoveNext do begin Current.IdContabilIndice := UltimoID; TT2TiORM.Inserir(Current); end; end; finally ContabilIndiceValorEnumerator.Free; end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TContabilIndiceController.Altera(pObjeto: TContabilIndiceVO): Boolean; var ContabilIndiceValorEnumerator: TEnumerator<TContabilIndiceValorVO>; begin try Result := TT2TiORM.Alterar(pObjeto); // Detalhes try ContabilIndiceValorEnumerator := pObjeto.ListaContabilIndiceValorVO.GetEnumerator; with ContabilIndiceValorEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdContabilIndice := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(ContabilIndiceValorEnumerator); end; finally end; end; class function TContabilIndiceController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TContabilIndiceVO; begin try ObjetoLocal := TContabilIndiceVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); TratarRetorno(Result); finally FreeAndNil(ObjetoLocal) end; end; class function TContabilIndiceController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TContabilIndiceController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TContabilIndiceController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TContabilIndiceVO>(TObjectList<TContabilIndiceVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TContabilIndiceController); finalization Classes.UnRegisterClass(TContabilIndiceController); end.
Program prMatriz6x6; type TMatriz = array[1..6,1..6] of integer; //função para retornar o valor a ser preenchido em uma celila da matriz function getValorCelula(i,j:integer): integer; var vl:integer; begin writeln('Valor para celula [', i, ',',j, ']'); readln(vl); getValorCelula := vl; end; procedure carregarMatriz(var mat:TMatriz); var l,c:integer; begin for l := 1 to 6 do for c := 1 to 6 do mat[l,c] := getValorCelula(l,c); end; function getSomaDiagonalPrincipal(mat:TMatriz): integer; var l, soma:integer; begin soma := 0; for l := 1 to 6 do soma := soma + mat[l,l]; getSomaDiagonalPrincipal := soma; end; function getMenorValorPar(mat:TMatriz): integer; var l, c, menor:integer; achou:boolean; begin achou := false; for l := 1 to 6 do begin if (achou) then break; for c := 1 to 6 do if (mat[l,c] mod 2 = 0) then begin menor := mat[l,c]; achou := true; break; end; end; if (not achou) then getMenorValorPar := -1 else begin for l := 1 to 6 do for c := 1 to 6 do if (mat[l,c] mod 2 = 0) then if (mat[l,c] < menor) then menor := mat[l,c]; getMenorValorPar := menor; end; end; function isPrimo(Valor: Integer):boolean; var i, cnt: integer; begin isPrimo := false; if Valor = 0 then exit; cnt := 0; for i:= 1 to Valor do begin if (Valor mod i) = 0 then cnt := cnt + 1; end; if cnt = 2 then isPrimo := true; end; procedure listarPrimos(mat:TMatriz); var l,c:integer; begin for l := 1 to 6 do for c := 1 to 6 do if (isPrimo(mat[l,c])) then writeln(mat[l,c]); end; procedure listarMatriz(mat:TMatriz); var l,c:integer; begin for l := 1 to 6 do begin for c:= 1 to 6 do write(mat[l,c], ' '); writeln(''); end; end; function getMatrizTransposta(mat:TMatriz): TMatriz; var l,c:integer; matAux:TMatriz; begin for l := 1 to 6 do for c := 1 to 6 do matAux[l,c] := mat[c,l]; getMatrizTransposta := matAux; end; procedure menu; var op, ret:integer; mat6x6, matTrasp: TMatriz; begin repeat writeln(''); writeln('---------------------------------------'); writeln('0 - Sair'); writeln('1 - Carregar matriz'); writeln('2 - Soma da diagonal principal'); writeln('3 - Menor valor par'); writeln('4 - Mostrar numeros primos da matriz'); writeln('5 - Matriz transposta'); readln(op); case (op) of 1: carregarMatriz(mat6x6); 2: writeln('Soma diagonal principal = ', getSomaDiagonalPrincipal(mat6x6)); 3: begin ret := getMenorValorPar(mat6x6); if (ret > 0) then writeln('Menor valor par = ', ret) else writeln('Nao ha valores pares!!'); end; 4: listarPrimos(mat6x6); 5: begin listarMatriz(mat6x6); matTrasp := getMatrizTransposta(mat6x6); listarMatriz(matTrasp); end; end; until(op = 0); end; //main Begin menu; End.
unit UKeyInfo; interface uses Classes, SysUtils, ComObj, Windows, ActiveX, ExtCtrls, Math, SenseUK, UFrmUkLogin, Sense4Dev; type TUKeyInfo = class Private FKeyInfo: TStringList; FMaxSize: Integer; //输入密码次数记录 FInputAccount: Integer; //记录是否密码验证通过 FUKConnect: Boolean; //记录是否需要输入密码验证登陆 FUKPasswordLogin: Boolean; FPassword: string; FKeyID: string; FError:String; function CheckUK: WideString; procedure SetPassword(const Key, Value: string); function ReadUKeyCode: string; procedure SetUkeyCode(const Value: string); procedure SetUKPasswordLogin(const Value: Boolean); procedure CheckUKeyConnect(Sender: Tobject); procedure InputPasswordLogin(Sender: Tobject); procedure SetError(const Value: String); Public //可用于Delphi与Com方法调用 constructor create; destructor detroy; //读U盘锁信息 function ReadUKInfo: String; Virtual; Stdcall; function Get_KeyName(i: SYSINT): WideString; Stdcall; function Get_Key(const name: WideString): WideString; Stdcall; procedure Set_Key(const name: WideString; const value: WideString); Stdcall; //删除U盘锁对应名称的信息值 function DelKey(const Name: WideString): WordBool; Stdcall; //获得U盘锁的信息数量 function KeyCount: SYSINT; Stdcall; //读取UK所有字符信息 function KeyAllText: WideString; Stdcall; //将信息保存到U盘锁 function Save: String; Virtual; Stdcall; //清除U盘锁信息 function Clear: String; Virtual; Stdcall; //变更密码 function ChangPass(const Key, OldName, NewName: WideString): WordBool; Stdcall; //UK密码验证登陆方法 function LoginUK(const Key, PassWord: WideString): WordBool; Stdcall; //UK退出方法 function LoginOutUK: WordBool; Stdcall; function UKIsExists(var Letter: Char): Boolean; procedure KeyClear; //下面方法用于delphi调用 //获得Key的名称 property KeyName[i: integer]: WideString Read Get_KeyName; //保存U盘锁对应名称的信息值 property Key[const name: WideString]: WideString Read Get_Key Write Set_Key; //是否进行UK加密验证 property UKPasswordLogin: Boolean Read FUKPasswordLogin Write SetUKPasswordLogin; //property Password :String read FPassword write SetPassword; property UKConnect: Boolean Read FUKConnect; property InputAccount: Integer Read FInputAccount; //获得U盾唯一序列号 property UKeyCode: string Read ReadUKeyCode Write SetUkeyCode; //主键ID号 property UKeyID: string Read FKeyID Write FKeyID; //获得UKey实例 class function InitUKeyInstance: TUKeyInfo; property Error:String read FError write SetError; end; TSense_UKeyInfo = class(TUKeyInfo) Public //读U盘锁信息 function ReadUKInfo: String; Override; function Save: String; Override; function Clear: String; Override; end; TSense4_UKeyInfo = class(TUKeyInfo) private function ReadLock(fileID, offset: ushort; len: byte; var readBuff: array of byte): boolean; function UpdateLock(fileID, offset: ushort; len: byte; var updateBuff: array of byte): boolean; Public //读U盘锁信息 function ReadUKInfo: String; Override; function Save: String; Override; function Clear: String; Override; end; implementation { TKeyInfo } uses Pub_Function; function TUKeyInfo.Clear: String; begin Result := ''; end; constructor TUKeyInfo.create; begin inherited; FKeyInfo := TStringList.Create; FInputAccount := 0; FMaxSize := 20; //最大5M FUKPasswordLogin := false; FUKConnect := False; {FTimer := TTimer.Create(nil); FTimer.Enabled := false; FTimer.OnTimer := CheckUKeyConnect; FTimer.Interval := 500; } try ReadUKInfo; except end; end; function TUKeyInfo.DelKey(const Name: WideString): WordBool; Stdcall; var iIndex: Integer; begin Result := False; //讯信息 if Trim(ReadUKInfo) <> '' then Exit; iIndex := FKeyInfo.IndexOfName(Name); if iIndex >= 0 then FKeyInfo.Delete(iIndex); //保存信息 if Trim(Save) <> '' then Exit; Result := true; end; destructor TUKeyInfo.detroy; begin { if Assigned(FTimer) then begin FTimer.Enabled := False; FreeAndNil(FTimer); end; } if Assigned(FKeyInfo) then FreeAndNil(FKeyInfo); FMaxSize := 0; inherited Destroy; end; function TUKeyInfo.KeyAllText: widestring; begin Result := ''; if Trim(ReadUKInfo) <> '' then exit; Result := FKeyInfo.Text; end; function TUKeyInfo.KeyCount: SYSINT; begin Result := 0; if Trim(ReadUKInfo) <> '' then exit; Result := FKeyInfo.Count; end; function TUKeyInfo.Get_KeyName(i: SYSINT): WideString; begin result := ''; if FKeyInfo.Count >= i + 1 then Result := FKeyInfo.Names[i]; end; function TUKeyInfo.ReadUKInfo: String; begin result := ''; end; function TUKeyInfo.Get_Key(const name: WideString): WideString; begin Result := ''; //if FKeyInfo.Text = '' then //ReadUKInfo; Result := FKeyInfo.Values[name]; end; function TUKeyInfo.Save: String; begin result := ''; end; procedure TUKeyInfo.Set_Key(const name: WideString; const value: WideString); begin //if FKeyInfo.Text = '' then //ReadUKInfo; FKeyInfo.Values[Name] := Value; if Trim(Save) <> '' then exit; end; function TUKeyInfo.ChangPass(const Key, OldName, NewName: WideString): WordBool; var Ret: string; sOldName, sNewName: string; begin Result := False; if not LoginUK(Key, OldName) then begin result := False; exit; end; SetPassword(Key, NewName); Ret := Save; if Ret <> '' then Result := false else result := true; end; function TUKeyInfo.LoginOutUK: WordBool; var Letter: Char; Buffer: array of char; begin Result := False; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); try if not UKGetRemovalLetter(@Letter) then begin Result := False; Exit; end; if not UKPassAreaLogout then Result := False else Result := true; finally Buffer := nil; end; end; function TUKeyInfo.LoginUK(const Key, PassWord: WideString): WordBool; var Letter: Char; Buffer: array of char; sPassword: string; begin Result := False; if Key = '' then exit; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); try sPassword := Password; if Trim(FKeyInfo.Values[Key]) <> Trim(sPassword) then Result := False else Result := true; finally Buffer := nil; end; end; procedure TUKeyInfo.InputPasswordLogin(Sender: Tobject); var sPassword: string; Letter: char; begin if not Assigned(FKeyInfo) then exit; //密内容 if FKeyInfo.Text = '' then ReadUKInfo; //不输入密码验证登陆 if not FUKPasswordLogin then begin FUKConnect := true; exit; end; //未读到UK if not UKIsExists(Letter) then begin FUKConnect := False; FInputAccount := 0; exit; end; while (not FUKConnect) and (FInputAccount < 3) do begin sPassword := InputPassword; if sPassword = '@@@取消@@@' then begin FInputAccount := 3; FUKConnect := False; end else if LoginUK(FKeyID, sPassword) then begin FInputAccount := 0; FUKConnect := true; end else begin inc(FInputAccount); FUKConnect := False; end; end; end; function TUKeyInfo.UKIsExists(var Letter: Char): Boolean; var Buffer: array of char; sOldName, sNewName: string; begin Result := False; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); if not UKGetRemovalLetter(@Letter) then Result := False else result := true; end; { TSense_UKeyInfo } { TSense_UKeyInfo } function TSense_UKeyInfo.Clear: String; var Letter: Char; Buffer: array of char; begin Result := ''; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); try if not UKIsExists(Letter) then begin Result := 'U盘锁末插入或末读到U盘锁信息错误!'; Exit; end; FKeyInfo.Clear; StrPCopy(@Buffer[0], FKeyInfo.Text); if not UKHiddenAreaWrite(Letter, 0, @Buffer[0], Length(Buffer)) then Result := '写U盘锁数据失败!'; finally Buffer := nil; end; end; function TSense_UKeyInfo.ReadUKInfo: String; var Letter: char; Buffer: array of char; begin Result := ''; Letter := ' '; SetLength(Buffer, FMaxSize); try if not UKIsExists(Letter) then begin Result := '错误:U盘锁未插入或未读到U盘锁信息!'; Exit; end; if not UKHiddenAreaRead(Letter, 0, @Buffer[0], Length(Buffer)) then Result := '错误:写U盘锁数据失败!'; FKeyInfo.Text := StrPas(@Buffer[0]); //FPassword :=FKeyInfo.Values['UserPassword']; finally Buffer := nil; end; end; function TSense_UKeyInfo.Save: String; var Letter: Char; Buffer: array of char; begin inherited Save; Result := ''; //大于隐藏区大小,则不允许保存 if Length(FKeyInfo.Text) > FMaxSize then begin Result := '错误:超出保存的最大值' + IntToStr(FMaxSize div 1024) + 'M'; Exit; end; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); try if not UKIsExists(Letter) then begin Result := '错误:U盘锁未插入或未读到U盘锁信息!'; Exit; end; //增加密码 //FKeyInfo.Values['UserPassword']:=FPassword; StrPCopy(@Buffer[0], FKeyInfo.Text); if not UKHiddenAreaWrite(Letter, 0, @Buffer[0], Length(Buffer)) then Result := '错误:写U盘锁数据失败!'; finally Buffer := nil; end; end; function TUKeyInfo.CheckUK: WideString; begin Result := ''; if FUKPasswordLogin and not FUKConnect then result := 'UK密码验证失败,不允许操作!'; end; procedure TUKeyInfo.SetPassword(const Key, Value: string); begin FKeyInfo.Values[Key] := Value; end; function TUKeyInfo.ReadUKeyCode: string; begin if FKeyInfo.Values['UFGOV-UKEYCODE'] = '' then begin FKeyInfo.Values['UFGOV-UKEYCODE'] := GetGuid; SetUkeyCode(FKeyInfo.Values['UFGOV-UKEYCODE']); Result := FKeyInfo.Values['UFGOV-UKEYCODE']; end else begin Result := FKeyInfo.Values['UFGOV-UKEYCODE']; end; end; procedure TUKeyInfo.SetUkeyCode(const Value: string); begin FKeyInfo.Values['UFGOV-UKEYCODE'] := value; if Save <> '' then FKeyInfo.Values['UFGOV-UKEYCODE'] := ''; end; class function TUKeyInfo.InitUKeyInstance: TUKeyInfo; var sUKeyName: string; begin //获得UKey实例,后期用于扩展,通过配置文件读取具体实例化UKey的厂商 sUKeyName := 'SENSE4'; //默认深思,可以读配置文件或数据库 if sUKeyName = 'SENSE' then Result := TSense_UKeyInfo.create; if sUKeyName = 'SENSE4' then Result := TSense4_UKeyInfo.create; end; procedure TUKeyInfo.SetUKPasswordLogin(const Value: Boolean); begin FUKPasswordLogin := Value; end; procedure TUKeyInfo.CheckUKeyConnect(Sender: Tobject); var sPassword: string; Letter: char; begin if not FUKConnect then Exit; //未读到UK if not UKIsExists(Letter) then begin FUKConnect := False; FInputAccount := 0; exit; end; end; { TSense4_UKeyInfo } function TSense4_UKeyInfo.Clear: String; var Letter: Char; Buffer: array of char; begin Result := ''; //获得U盘盘符 Letter := ' '; SetLength(Buffer, FMaxSize); try if not UKIsExists(Letter) then begin Result := 'U盘锁末插入或末读到U盘锁信息错误!'; Exit; end; FKeyInfo.Clear; StrPCopy(@Buffer[0], FKeyInfo.Text); if not UKHiddenAreaWrite(Letter, 0, @Buffer[0], Length(Buffer)) then Result := '写U盘锁数据失败!'; finally Buffer := nil; end; end;//************************************************* // 结构体定义 //************************************************* Type Input_Package = record // 读写文件指令结构定义 tag: byte; // 标志位,表示读/写 pktLen: byte; // 保留 fid: ushort; // 文件id offset: ushort; // 读写偏移量 len: byte; // 数据buff的长度 buff: array[0..242] of byte; end; Output_Package = record // 加密锁返回数据格式定义 tag: byte; // 标志位,表示读/写 len: byte; // 数据buff的长度 buff: array[0..247] of byte;// 若为读取指令则包含读取数据内容 end; //************************************************* // 常量定义 //************************************************* const devID = '123'; // 设备ID,用于在同时存在多把锁时,寻找指定设备ID的加密锁 S4_EXE_FILE_ID = 'ef21'; // 锁内读写文件程序ID S4_OBJ_FILE_ID = 'bf21'; // 锁内被读写数据文件ID S4_OBJ_FILE_ID_HEX = $bf21; // 数据文件ID,16进制数格式 CMD_UPDATE = 01; // 写 CMD_READ = 02; // 读 //************************************************* // 写数据文件 //************************************************* function TSense4_UKeyInfo.UpdateLock(fileID:ushort; offset:ushort; len:byte; var updateBuff: array of byte) : boolean; var ctxList: array of SENSE4_CONTEXT; ctxIndex:integer; size: DWORD; ret : DWORD; count: integer; i: integer; j: integer; userPin: string; bID: string; hasFound: boolean; input: Input_Package; output: Output_Package; begin if (Length(updateBuff) < len) or (Length(updateBuff) > Length(output.buff)) then begin result := false; exit; end; //------------------------------- // 列举锁 //------------------------------- // 获取设备数量 S4Enum(nil, size); if (size = 0) then // if begin FError := '没有找到锁'; result := false; exit; end; // if end count := floor(Integer(size) / SizeOf(SENSE4_CONTEXT)); SetLength(ctxList, count); ret := S4Enum(@ctxList[0], size); if (ret <> S4_SUCCESS) then // if begin FError := '列举锁失败 ' + IntToHex(ret, 8); result := false; exit; end; // if end //------------------------------- // 遍历各个加密锁 // 寻找设备ID为 bID 的加密锁 //------------------------------- hasFound := false; bID := devID; for ctxIndex := 0 to count - 1 do if CompareMem(@ctxList[ctxIndex].bID[0], PByte(bID), Length(bID)) then // 将bID静态类型转换为Byte指针,用以Memory Compare begin hasFound := true; break; end; if not hasFound then begin FError := '没有找到指定设备ID的加密锁'; result := false; exit; end; //------------------------------- // 打开找到的指定设备ID锁 //------------------------------- ret := S4Open(@ctxList[ctxIndex]); if (ret <> S4_SUCCESS) then begin FError := '打开锁失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 切换当前操作目录 //------------------------------- ret := S4ChangeDir(@ctxList[ctxIndex], '\'); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError := '切换目录失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 验证用户PIN码 //------------------------------- userPin := '12345678'; ret := S4VerifyPin(@ctxList[ctxIndex], PChar(userPin), 8, S4_USER_PIN); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError := '验证PIN码失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 执行锁内程序 //------------------------------- input.tag := CMD_UPDATE; input.pktLen := len + 5; // 5 为 input->,fileID,offset,len5个字段的长度,len + 7为pktLen之后个字段长度,即包括input->buff中的有效部分 input.fid := S4_OBJ_FILE_ID_HEX; input.offset := offset; input.len := len; for i := 0 to len do input.buff[i] := updateBuff[i]; ret := S4Execute(@ctxList[ctxIndex], S4_EXE_FILE_ID, PChar(@input), SizeOf(input), PChar(@output), SizeOf(output), size); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError := '执行失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 关闭锁 //------------------------------- S4Close(@ctxList[ctxIndex]); result := true; end; //************************************************* // 读数据文件 //************************************************* function TSense4_UKeyInfo.ReadLock(fileID:ushort; offset:ushort; len:byte; var readBuff: array of byte) : boolean; var ctxList: array of SENSE4_CONTEXT; ctxIndex: integer; size: DWORD; ret : DWORD; count: integer; i: integer; j: integer; userPin: string; bID: string; hasFound: boolean; input: Input_Package; output: Output_Package; begin if Length(readBuff) < len then begin result := false; exit; end; //------------------------------- // 列举锁 //------------------------------- // 获取设备数量 S4Enum(nil, size); if (size = 0) then // if begin FError:='没有找到锁'; result := false; exit; end; // if end count := floor(Integer(size) / SizeOf(SENSE4_CONTEXT)); SetLength(ctxList, count); ret := S4Enum(@ctxList[0], size); if (ret <> S4_SUCCESS) then // if begin FError:='列举锁失败 ' + IntToHex(ret, 8); result := false; exit; end; // if end //------------------------------- // 遍历各个加密锁 // 寻找设备ID为 '123' 的加密锁 //------------------------------- hasFound := false; bID := devID; for ctxIndex := 0 to count - 1 do if CompareMem(@ctxList[ctxIndex].bID[0], PByte(bID), Length(bID)) then // 将bID静态类型转换为Byte指针,用以Memory Compare begin hasFound := true; break; end; if not hasFound then begin FError:='没有找到指定设备ID的加密锁'; result := false; exit; end; //------------------------------- // 打开找到的指定设备ID锁 //------------------------------- ret := S4Open(@ctxList[ctxIndex]); if (ret <> S4_SUCCESS) then begin FError:='打开锁失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 切换当前操作目录 //------------------------------- ret := S4ChangeDir(@ctxList[ctxIndex], '\'); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError:='切换目录失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 验证用户PIN码 //------------------------------- userPin := '12345678'; ret := S4VerifyPin(@ctxList[ctxIndex], PChar(userPin), 8, S4_USER_PIN); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError:='验证PIN码失败 ' + IntToHex(ret, 8); result := false; exit; end; //------------------------------- // 执行锁内程序 //------------------------------- input.tag := CMD_READ; input.pktLen := 7; input.fid := S4_OBJ_FILE_ID_HEX; input.offset := offset; input.len := len; ret := S4Execute(@ctxList[ctxIndex], S4_EXE_FILE_ID, PChar(@input), SizeOf(input), PChar(@output), SizeOf(output), size); if (ret <> S4_SUCCESS) then begin S4Close(@ctxList[ctxIndex]); FError:='执行失败 ' + IntToHex(ret, 8); result := false; exit; end; //SetLength(readBuff, 250); for i := 0 to len-1 do readBuff[i] := output.buff[i]; //------------------------------- // 关闭锁 //------------------------------- S4Close(@ctxList[ctxIndex]); result := true; end; function TSense4_UKeyInfo.ReadUKInfo: String; var Buffer: array of byte; offset:integer; Len:integer; i:integer; S:String; R:Boolean; begin try offset := 0; len := 20; SetLength(Buffer, len); FError := ''; try R := ReadLock(S4_OBJ_FILE_ID_HEX, offset, len, Buffer); except end; if R then begin FKeyInfo.Clear; for i :=0 to Len-1 do begin S := S + chr(Buffer[i]); end; FKeyInfo.Text := S; end else Result := '错误:' + FError; finally end; end; function TSense4_UKeyInfo.Save: String; var Buffer: array of byte; S:String; iCount:integer; begin inherited Save; Result := ''; //大于隐藏区大小,则不允许保存 if Length(FKeyInfo.Text) > FMaxSize then begin Result := '错误:超出保存的最大值' + IntToStr(FMaxSize div 1024) + 'M'; Exit; end; SetLength(Buffer, 20); S := FKeyInfo.Text; for iCount := 1 to length(S) do begin Buffer[iCount-1] := ord(S[iCount]); end; try UpdateLock(S4_OBJ_FILE_ID_HEX, 0, 20, Buffer); Result := FError; finally end; end; procedure TUKeyInfo.KeyClear; begin FKeyInfo.Clear; end; procedure TUKeyInfo.SetError(const Value: String); begin FError := Value; end; end.
{ Version 11.9 Copyright (c) 2016-2018 by HtmlViewer Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Note that the source modules HTMLGIF1.PAS, DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } { Inspired by former UrlConId10.PAS written by Yves Urbain } {$I htmlcons.inc} unit UrlConn; interface uses {$ifdef VCL} Windows, {$endif} Classes, Types, Contnrs, SysUtils, Forms, URLSubs, HtmlGlobals; const ChtMaxRunningThreadCount = 20; type EhtUrlConnException = class(Exception); ThtUrlDocStatus = (ucsInitial, ucsInProgress, ucsLoaded, ucsError); ThtConnector = class; ThtConnection = class; ThtUrlDoc = class; ThtGetAuthorizationEvent = function (Sender: ThtConnection; TryRealm: Boolean): Boolean of object; //------------------------------------------------------------------------------ // A ThtConnectionManager gets a connection for a given transport protocol. // // Place a ThtConnectionManager component on your form and also place // transport protocol specific ThtConnector components like ThtFileConnector // and ThtResourceConnector on your form. They automatically register // themselves at the ThtConnectionManager and offer creating connections for // one or more protocols. // // Now the ThtConnectionManager is ready to support TFrameBrowser events like // OnGetPostRequest() and OnGetImageRequest() by creating the appropriate // ThtConnection descendant that can get the requested document resp. image. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtConnectionManager = class(TComponent) private FConnectors: TList; function GetCount: Integer; function GetConnector(Index: Integer): ThtConnector; function GetConnectorForProtocol(const Protocol: ThtString): ThtConnector; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegisterConnector(Connector: ThtConnector); procedure UnregisterConnector(Connector: ThtConnector); function GetAllProtocols: ThtString; function CreateConnection(const Protocol: ThtString): ThtConnection; function TryCreateConnection(const Protocol: ThtString; var Connection: ThtConnection): Boolean; function IndexOfProtocol(const Protocol: ThtString): Integer; property Count: Integer read GetCount; property Items[Index: Integer]: ThtConnector read GetConnector; default; published property AllProtocols: ThtString read GetAllProtocols; end; //------------------------------------------------------------------------------ // A ThtConnector descendant knows how to create connections for one or more // protocols. // // To implement a new protocol derive one descendant from ThtConnector and // another from ThtConnection. // // The ThtConnector descendant must override the following functions: // // - GetDefaultProtocols() // to tell the ThtConnectionManager which protocols it supports, // // - GetVersion() // to tell the application the ThtConnector's implementor and version and // // - CreateConnection(const Protocol: ThtString) // which actually creates the connection for the given protocol. // // In case the connection may need authorization publish OnGetAuthorization // rather than implementing another login/authorization dialog. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtConnector = class(TComponent) private FProtocols: ThtString; FOnGetAuthorization: ThtGetAuthorizationEvent; FConnectionManager: ThtConnectionManager; procedure SetProtocols(const Value: ThtString); function StoreProtocols: Boolean; procedure SetConnectionManger(const Value: ThtConnectionManager); protected class function GetDefaultProtocols: ThtString; virtual; abstract; class function GetVersion: string; virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetAuthorization(Connection: ThtConnection; TryRealm: Boolean): Boolean; virtual; property OnGetAuthorization: ThtGetAuthorizationEvent read FOnGetAuthorization write FOnGetAuthorization; public constructor Create(AOwner: TComponent); override; function CreateConnection(const Protocol: ThtString): ThtConnection; virtual; abstract; function SupportsProtocol(const Protocol: ThtString): Boolean; published property Version: string read GetVersion; property Protocols: ThtString read FProtocols write SetProtocols stored StoreProtocols; property ConnectionManager: ThtConnectionManager read FConnectionManager write SetConnectionManger; end; //---------------------------------------------------------------------------- // A ThtConnection gets a document via LoadDoc(Doc: ThtUrlDoc) // // LoadDoc(): // When called at least Doc.Url must be filled. // On return if Doc.Status is ucsLoaded Doc.Stream is filled with the loaded document. // On return if Doc.Status is ucsInProgress the connection is loading the document asynchronously. // // The ThtConnection descendant must override the following function: // // - Get() // to load document Doc.Url into Doc.Stream // // The ThtConnection descendant may override the following function: // // - CreateUrlDoc() // to create an appropriate descendant of ThtUrlDoc. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtConnection = class private FDoc: ThtUrlDoc; FOnDocBegin: TNotifyEvent; FOnDocData: TNotifyEvent; FOnDocEnd: TNotifyEvent; FSessionId: Integer; FAborted: Boolean; FRealm: ThtString; FPassword: ThtString; FUsername: ThtString; FBasicAuthentication: Boolean; FReasonPhrase: ThtString; FReceivedSize: Int64; FExpectedSize: Int64; protected function GetAuthorization(TryRealm: Boolean): Boolean; function GetConnector: ThtConnector; virtual; procedure Get(Doc: ThtUrlDoc); virtual; abstract; public constructor Create; function CreateUrlDoc(PostIt: Boolean; const URL, Query, QueryEncType, Referer: ThtString): ThtUrlDoc; virtual; procedure LoadDoc(Doc: ThtUrlDoc); procedure Abort; virtual; property Aborted: Boolean read FAborted write FAborted; property Realm: ThtString read FRealm write FRealm; property Password: ThtString read FPassword write FPassword; property Username: ThtString read FUsername write FUsername; property BasicAuthentication: Boolean read FBasicAuthentication write FBasicAuthentication; function IsProcessing: Boolean; // Must not be virtual! Checks Self just like Free does. function ReasonPhrase: ThtString; virtual; property SessionId : Integer read FSessionId; property Doc : ThtUrlDoc read FDoc; property Processing : Boolean read IsProcessing; property ReceivedSize: Int64 read FReceivedSize write FReceivedSize; property ExpectedSize: Int64 read FExpectedSize write FExpectedSize; property OnDocBegin : TNotifyEvent read FOnDocBegin write FOnDocBegin; property OnDocData : TNotifyEvent read FOnDocData write FOnDocData; property OnDocEnd : TNotifyEvent read FOnDocEnd write FOnDocEnd; end; //------------------------------------------------------------------------------ // ThtUrlDoc holds the document specific data required for a document request. // // A ThtUrlDoc object is passed to ThtConnection.LoadDoc(Doc: ThtUrlDoc). // When called at least Doc.Url must be filled. // On return if Doc.Status is ucsLoaded Doc.Stream is filled with the loaded document. // On return if Doc.Status is ucsInProgress the connection is loading the document asynchronously. // // ThtUrlDoc objects are designed to be kept in a first level cache in memory. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtUrlDoc = class(TObject) private FUrl: ThtString; FNewUrl: ThtString; FReferer: ThtString; FQuery: ThtString; FQueryEncType: ThtString; FStream: TStream; FPostIt: Boolean; FStatus: ThtUrlDocStatus; FDocType: ThtDocType; function GetStream: TStream; procedure SetNewUrl(const Value: ThtString); procedure SetStream(const Value: TStream); function GetStreamSize: Int64; public destructor Destroy; override; procedure Clear; procedure SaveToFile(FileName: ThtString); property Url: ThtString read FUrl write FUrl; property Status: ThtUrlDocStatus read FStatus write FStatus; property DocType: ThtDocType read FDocType write FDocType; property Stream: TStream read GetStream write SetStream; property StreamSize: Int64 read GetStreamSize; property NewUrl: ThtString read FNewUrl write SetNewUrl; property PostIt: Boolean read FPostIt write FPostIt; property Referer: ThtString read FReferer write FReferer; property Query: ThtString read FQuery write FQuery; property QueryEncType: ThtString read FQueryEncType write FQueryEncType; end; //------------------------------------------------------------------------------ // Use ThtProxyConnector as base class for protocols like http, ftp, etc. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtProxyConnector = class(ThtConnector) private FProxyServer: ThtString; FProxyPort: ThtString; FProxyUsername: ThtString; FProxyPassword: ThtString; published property ProxyServer : ThtString read FProxyServer write FProxyServer; property ProxyPort : ThtString read FProxyPort write FProxyPort; property ProxyUsername: ThtString read FProxyUsername write FProxyUsername; property ProxyPassword: ThtString read FProxyPassword write FProxyPassword; end; //------------------------------------------------------------------------------ // ThtFileConnection and ThtFileConnector implement the protocol 'file' // that gets files from a file system. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtFileConnection = class(ThtConnection) private procedure MakeDirOutput(AStream : TStream; const ADirName : ThtString); protected procedure Get(ADoc: ThtUrlDoc); override; end; //-- BG -------------------------------------------------------- 18.05.2016 -- ThtFileConnector = class(ThtConnector) protected class function GetDefaultProtocols: ThtString; override; class function GetVersion: string; override; public function CreateConnection(const Protocol: ThtString): ThtConnection; override; end; //------------------------------------------------------------------------------ // ThtResourceConnection and ThtResourceConnector implement the protocol 'res' // that gets files from the application's resources. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 18.05.2016 -- ThtResourceConnection = class(ThtConnection) protected procedure Get(ADoc: ThtUrlDoc); override; public class function CreateResourceStream(Instance: THandle; const ResourceName: ThtString; DocType: ThtDocType): TResourceStream; end; //-- BG -------------------------------------------------------- 18.05.2016 -- ThtResourceConnector = class(ThtConnector) protected class function GetDefaultProtocols: ThtString; override; class function GetVersion: string; override; public function CreateConnection(const Protocol: ThtString): ThtConnection; override; end; //------------------------------------------------------------------------------ // ThtUrlDocLoaderThread can load a document asynchronously. // // Given document is loaded via given connection. After having loaded the document // the OnLoaded event is fired. // // ThtUrlDocLoaderThread frees the connection but not the document as you might // want to keep it in a cache. If not you must free the document. //------------------------------------------------------------------------------ ThtUrlDocLoadedEvent = procedure(Sender: ThtUrlDoc; Receiver: TObject) of object; //-- BG -------------------------------------------------------- 19.05.2016 -- ThtUrlDocLoaderThread = class(TThread) private FConnection: ThtConnection; FUrlDoc: ThtUrlDoc; FOnLoaded: ThtUrlDocLoadedEvent; FReceiver: TObject; protected procedure DoTerminate; override; procedure Execute; override; procedure FreeConnection; public constructor Create( Connection: ThtConnection; UrlDoc: ThtUrlDoc; OnLoaded: ThtUrlDocLoadedEvent; Receiver: TObject); procedure Loaded; property Connection: ThtConnection read FConnection; property UrlDoc: ThtUrlDoc read FUrlDoc; property OnLoaded: ThtUrlDocLoadedEvent read FOnLoaded; property Receiver: TObject read FReceiver; end; ThtOnProgressEvent = procedure(Sender: TObject; Done, Total: Integer) of object; //------------------------------------------------------------------------------ // ThtUrlDocLoaderThreadList can load documents asynchronously using // ThtUrlDocLoaderThreads. // // Not to overcharge the systems ThtUrlDocLoaderThreadList runs at most // FMaxRunningThreadCount threads at a time. If one thread terminates the next // thread is started automatically until all documents are loaded. //------------------------------------------------------------------------------ //-- BG -------------------------------------------------------- 19.05.2016 -- ThtUrlDocLoaderThreadList = class(TComponent) private FWaiting: TList; FRunning: TList; FDone: Integer; FFailed: Integer; FTotal: Integer; FMaxRunningThreadCount: Integer; FOnProgress: ThtOnProgressEvent; procedure Terminated(Sender: TObject); procedure StartNext; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RunningCount: Integer; function WaitingCount: Integer; procedure AddLoader(Thread: ThtUrlDocLoaderThread); property FailureCount: Integer read FFailed; published property MaxRunningThreadCount: Integer read FMaxRunningThreadCount default ChtMaxRunningThreadCount; property OnProgress: ThtOnProgressEvent read FOnProgress write FOnProgress; end; //------------------------------------------------------------------------------ function ContentType2DocType(const AContentType: ThtString): ThtDocType; function FileExt2DocType(const AExt: ThtString): ThtDocType; //------------------------------------------------------------------------------ implementation uses HtmlUn2; var GNextSessionId: Integer; //-- BG ---------------------------------------------------------- 29.08.2007 -- function ContentType2DocType(const AContentType: ThtString): ThtDocType; var ContentType: ThtString; begin ContentType := LowerCase(AContentType); if (Pos('text/html', ContentType) > 0) or (Pos('text/css', ContentType) > 0) then Result := HTMLType else if Pos('application/xhtml+xml', ContentType) > 0 then Result := XHtmlType else if Pos('image/', ContentType) > 0 then Result := ImgType else if Pos('text/plain', ContentType) > 0 then Result := TextType else Result := OtherType; end; //-- BG ---------------------------------------------------------- 25.08.2007 -- function FileExt2DocType(const AExt: ThtString): ThtDocType; var Ext: ThtString; begin Ext := ',' + LowerCase(AExt) +','; // get type if Pos(Ext, ',htm,html,css,php,asp,shtml,') > 0 then Result := HTMLType else if Pos(Ext, ',xht,xhtml,') > 0 then Result := XHtmlType else if Pos(Ext, ',gif,tiff,tif,jpg,jpeg,png,bmp,rle,dib,jpe,jfif,emf,wmf,') > 0 then Result := ImgType else if Pos(Ext, ',txt,ini,sql,') > 0 then Result := TextType else Result := OtherType; end; { ThtUrlDoc } //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtUrlDoc.Clear; begin FreeAndNil(FStream); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- destructor ThtUrlDoc.Destroy; begin FStream.Free; inherited; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtUrlDoc.GetStream: TStream; begin if FStream = nil then FStream := TMemoryStream.Create; Result := FStream; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtUrlDoc.GetStreamSize: Int64; begin if FStream <> nil then Result := FStream.Size else Result := 0; end; ////-- BG ---------------------------------------------------------- 18.05.2016 -- //procedure ThtUrlDoc.SetName(const Value: ThtString); //begin // FName := Value; // if Length(FUrl) = 0 then // FUrl := Value; //end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtUrlDoc.SetNewUrl(const Value: ThtString); begin FNewUrl := Value; if Length(FNewUrl) = 0 then FNewUrl := FUrl; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDoc.SetStream(const Value: TStream); begin if FStream <> Value then begin FStream.Free; FStream := Value; end; end; ////-- BG ---------------------------------------------------------- 18.05.2016 -- //procedure ThtUrlDoc.SetUrl(const Value: ThtString); //begin // FUrl := Value; // if Length(FName) = 0 then // FName := Value; //end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtUrlDoc.SaveToFile(FileName: ThtString); var FileStream: TFileStream; begin if (Status = ucsLoaded) and (FStream <> nil) then begin FileStream := TFileStream.Create( htStringToString(Filename), fmCreate); try FileStream.CopyFrom(Stream, 0); finally FileStream.free; end; end; end; { ThtConnection } //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtConnection.Abort; begin FAborted := True; end; constructor ThtConnection.Create; begin inherited; FSessionId := GNextSessionId; Inc(GNextSessionId); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnection.CreateUrlDoc(PostIt: Boolean; const URL, Query, QueryEncType, Referer: ThtString): ThtUrlDoc; begin Result := ThtUrlDoc.Create; Result.PostIt := PostIt; Result.Url := URL; Result.Query := Query; Result.QueryEncType := QueryEncType; Result.Referer := Referer; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtConnection.LoadDoc(Doc: ThtUrlDoc); begin FDoc := Doc; try Get(Doc); finally FDoc := nil; end; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtConnection.GetAuthorization(TryRealm: Boolean): Boolean; var Connector: ThtConnector; begin Connector := GetConnector; Result := (Connector <> nil) and Connector.GetAuthorization(Self, TryRealm); end; //-- BG ---------------------------------------------------------- 22.05.2016 -- function ThtConnection.GetConnector: ThtConnector; begin Result := nil; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtConnection.IsProcessing: Boolean; begin Result := (Self <> nil) and (FDoc <> nil) and (FDoc.Status = ucsInProgress); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnection.ReasonPhrase: ThtString; begin Result := FReasonPhrase; end; { ThtConnector } //-- BG ---------------------------------------------------------- 18.05.2016 -- constructor ThtConnector.Create(AOwner: TComponent); begin inherited; Protocols := GetDefaultProtocols; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtConnector.GetAuthorization(Connection: ThtConnection; TryRealm: Boolean): Boolean; begin Result := Assigned(FOnGetAuthorization) and FOnGetAuthorization(Connection, TryRealm); end; //-- BG ---------------------------------------------------------- 22.05.2016 -- procedure ThtConnector.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; case Operation of // cannot register myself as ConnectionManager.FConnectors not yet created. // opInsert: // if not (csLoading in ComponentState) then // if (AComponent is ThtConnectionManager) and (FConnectionManager = nil) then // ConnectionManager := AComponent as ThtConnectionManager; opRemove: if AComponent = FConnectionManager then FConnectionManager := nil; end; end; //-- BG ---------------------------------------------------------- 22.05.2016 -- procedure ThtConnector.SetConnectionManger(const Value: ThtConnectionManager); begin if FConnectionManager <> Value then begin if FConnectionManager <> nil then FConnectionManager.UnregisterConnector(Self); FConnectionManager := Value; if FConnectionManager <> nil then FConnectionManager.RegisterConnector(Self); end; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtConnector.SetProtocols(const Value: ThtString); begin FProtocols := LowerCase(Value); end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtConnector.StoreProtocols: Boolean; begin Result := FProtocols <> GetDefaultProtocols; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnector.SupportsProtocol(const Protocol: ThtString): Boolean; begin // enclosed in ',' to exactly (and not partially) match single protocol entry // and an item of a comma separated list. Result := Pos(',' + Protocol + ',', ',' + FProtocols + ',') > 0; end; { ThtConnectionManager } //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.GetAllProtocols: ThtString; var Index: Integer; begin Result := ''; for Index := 0 to Count - 1 do begin if Length(Result) > 0 then Result := Result + ','; Result := Result + Items[Index].Protocols; end; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- constructor ThtConnectionManager.Create(AOwner: TComponent); begin inherited; FConnectors := TList.Create; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.CreateConnection(const Protocol: ThtString): ThtConnection; begin Result := GetConnectorForProtocol(Protocol).CreateConnection(Protocol); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- destructor ThtConnectionManager.Destroy; var I: Integer; begin for I := 0 to FConnectors.Count - 1 do GetConnector(I).FConnectionManager := nil; FConnectors.Free; inherited; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.GetConnector(Index: Integer): ThtConnector; begin Result := ThtConnector(FConnectors[Index]); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.GetConnectorForProtocol(const Protocol: ThtString): ThtConnector; var Index: Integer; begin Index := IndexOfProtocol(Protocol); if Index < 0 then raise EhtUrlConnException.CreateFmt( 'Unsupported protocol ''%s''. Supported protocols are %s.', [Protocol, AllProtocols]); Result := Items[Index]; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.GetCount: Integer; begin if FConnectors <> nil then Result := FConnectors.Count else Result := 0; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.IndexOfProtocol(const Protocol: ThtString): Integer; begin Result := Count - 1; while Result >= 0 do if Items[Result].SupportsProtocol(Protocol) then Exit else Dec(Result); end; //-- BG ---------------------------------------------------------- 22.05.2016 -- procedure ThtConnectionManager.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; case Operation of opInsert: if not (csLoading in ComponentState) then if AComponent is ThtConnector then (AComponent as ThtConnector).ConnectionManager := Self; opRemove: if AComponent <> Self then FConnectors.Remove(AComponent); end; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtConnectionManager.RegisterConnector(Connector: ThtConnector); begin if FConnectors.IndexOf(Connector) < 0 then FConnectors.Add(Connector); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtConnectionManager.TryCreateConnection(const Protocol: ThtString; var Connection: ThtConnection): Boolean; var Index: Integer; begin Index := IndexOfProtocol(Protocol); Result := Index >= 0; if Result then Connection := Items[Index].CreateConnection(Protocol); end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtConnectionManager.UnregisterConnector(Connector: ThtConnector); begin FConnectors.Remove(Connector); end; { ThtFileConnection } //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtFileConnection.MakeDirOutput(AStream: TStream; const ADirName: ThtString); {This is for generating HTML from a directory listing including special dir entries. Note that I realize a lot of the markup is probably unnecessary but it's a good idea to include it anyway to encourage good HTML habits.} var F : TSearchRec; TimeStamp: TDateTime; Name: ThtString; Size: ThtString; Text: ThtStringList; begin Text := ThtStringList.Create; try Text.Add('<!DOCTYPE html>'); Text.Add('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'); Text.Add('<head>'); Text.Add('<meta charset="utf-16le" />'); Text.Add('<base href="file://'+ EncodeUrl(DosToHTML(ADirName)) +'" />'); Text.Add('<title>' + ADirName + '</title>'); Text.Add('<style type="text/css">'); Text.Add(' .fn {text-align:left; font-weight:normal;}'); Text.Add(' .tm {text-align:center;}'); Text.Add(' .sz {text-align:right;}'); Text.Add(' table {width: 100%}'); Text.Add('</style>'); Text.Add('</head>'); Text.Add('<body>'); Text.Add('<h1>' + ADirName + '</h1>'); if (FindFirst( IncludeTrailingPathDelimiter( htStringToString(ADirName)) + '*.*', faAnyFile, F) = 0) then begin try Text.Add('<table>'); Text.Add('<thead>'); Text.Add('<tr><th scope="col">File Name</th><th scope="col">Last Modified</th><th scope="col">Size</th></tr>'); Text.Add('</thead>'); Text.Add('<tbody>'); repeat {$ifdef TSearchRecHasNoTimestamp} TimeStamp := FileDateToDateTime(F.Time); {$else} TimeStamp := F.TimeStamp; {$endif} if F.Attr and faDirectory <> 0 then begin if F.Name = '.' then Name := ADirName else if F.Name = '..' then Name := ExtractFileDir(ADirName) else Name := htString(F.Name); Size := 'DIR'; end else begin Name := htString(F.Name); Size := htString(IntToStr(F.Size)); end; Text.Add( '<tr><th class="fn" scope="row"><a href="' + EncodeUrl(DosToHtml(Name))+'">' + Name + '</a></th>' + '<td class="tm">' + htString( DateTimeToStr( TimeStamp )) + '</td><td class="sz">' + Size + '</td></tr>'); until FindNext(F) <> 0; Text.Add('</tbody>'); Text.Add('</table>'); finally FindClose(F); end; end; Text.Add('</body>'); Text.Add('</html>'); Text.SaveToStream(AStream); finally Text.Free; end; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtFileConnection.Get(ADoc: ThtUrlDoc); var FileName, Ext : ThtString; I : integer; begin FileName := ADoc.Url; {remove any query string as it's not certain how to respond to a Form submit with a file protocol. The user can add a response if desired.} SplitQuery(FileName); I := Pos('file://', LowerCase(FileName)); if I > 0 then begin Delete(FileName, 1,5+2); { remove file:// } { We suppose that windows accepts c:/test/test2 } if FileName[1] = '/' then Delete(FileName, 1, 1); end; FileName := HTMLtoDOS(FileName); if DirectoryExists(FileName) then begin MakeDirOutput(ADoc.Stream, FileName); ADoc.DocType := HTMLType; end else begin ADoc.Stream := TFileStream.Create( htStringToString(FileName), fmOpenRead or fmShareDenyWrite); Ext := htLowerCase(ExtractFileExt(FileName)); if Length(Ext) > 0 then Delete(Ext, 1, 1); ADoc.DocType := FileExt2DocType(Ext); end; ADoc.Status := ucsLoaded; end; { ThtFileConnector } //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtFileConnector.CreateConnection(const Protocol: ThtString): ThtConnection; begin Result := ThtFileConnection.Create; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- class function ThtFileConnector.GetDefaultProtocols: ThtString; begin Result := 'file'; end; //-- BG ---------------------------------------------------------- 22.05.2016 -- class function ThtFileConnector.GetVersion: string; begin Result := 'HtmlViewer ' + VersionNo; end; { ThtResourceConnection } function htFindResource(HInstance: HModule; const FileName, GoodType: ThtString): HRSRC; {$ifdef UseInline} inline; {$endif} begin {$ifdef LCL} Result := FindResource(HInstance, string(FileName), string(GoodType)); {$else} Result := FindResource(HInstance, PChar(FileName), PChar(GoodType)); {$endif} end; //-- BG ---------------------------------------------------------- 18.05.2016 -- procedure ThtResourceConnection.Get(ADoc: ThtUrlDoc); var FileName, Ext: ThtString; I: Integer; begin FileName := ADoc.Url; {remove any query string as it's not certain how to respond to a Form submit with a file protocol. The user can add a response if desired.} SplitQuery(FileName); { skip protocol: accept both res:// and res:/// } I := Pos('res://', htLowerCase(FileName)); if I > 0 then begin Delete(FileName, I, 4+2); if FileName[1] = '/' then Delete(FileName, 1, 1); end; Ext := htLowerCase(GetURLExtension(FileName)); ADoc.DocType := FileExt2DocType(Ext); ADoc.Stream := CreateResourceStream(HInstance, FileName, ADoc.DocType); end; //-- BG ---------------------------------------------------------- 10.03.2019 -- class function ThtResourceConnection.CreateResourceStream(Instance: THandle; const ResourceName: ThtString; DocType: ThtDocType): TResourceStream; var I: Integer; GoodType: ThtString; HResInfo: HRSRC; FileName, Ext, S: ThtString; begin Result := nil; FileName := ResourceName; case DocType of XHTMLType, HTMLType: GoodType := 'HTML'; ImgType: GoodType := htUpperCase(GetURLExtension(FileName)); TextType: GoodType := 'TEXT'; else GoodType := ''; end; HResInfo := htFindResource(HInstance, FileName, GoodType); if HResInfo = 0 then begin {try without the extension if can't find it with extension} Ext := htLowerCase(GetURLExtension(FileName)); I := Pos('.' + Ext, htLowerCase(FileName)); if I > 0 then begin S := FileName; SetLength(S, I - 1); HResInfo := htFindResource(HInstance, S, GoodType); if HResInfo <> 0 then FileName := S; end; end; if HResInfo <> 0 then Result := TResourceStream.Create(Instance, htStringToString(FileName), PChar({$ifdef LCL}string(GoodType){$else}GoodType{$endif})); end; { ThtResourceConnector } //-- BG ---------------------------------------------------------- 18.05.2016 -- function ThtResourceConnector.CreateConnection(const Protocol: ThtString): ThtConnection; begin Result := ThtResourceConnection.Create; end; //-- BG ---------------------------------------------------------- 18.05.2016 -- class function ThtResourceConnector.GetDefaultProtocols: ThtString; begin Result := 'res'; end; //-- BG ---------------------------------------------------------- 22.05.2016 -- class function ThtResourceConnector.GetVersion: string; begin Result := 'HtmlViewer ' + VersionNo; end; { ThtUrlDocLoaderThread } //-- BG ---------------------------------------------------------- 19.05.2016 -- constructor ThtUrlDocLoaderThread.Create(Connection: ThtConnection; UrlDoc: ThtUrlDoc; OnLoaded: ThtUrlDocLoadedEvent; Receiver: TObject); begin inherited Create(False); FConnection := Connection; FUrlDoc := UrlDoc; FOnLoaded := OnLoaded; FReceiver := Receiver; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThread.DoTerminate; begin inherited; Synchronize(FreeConnection); end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThread.Execute; begin if Terminated then Exit; UrlDoc.Status := ucsInProgress; try Connection.LoadDoc(UrlDoc); UrlDoc.Status := ucsLoaded; except UrlDoc.Status := ucsError; end; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThread.FreeConnection; begin FreeAndNil(FConnection); end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThread.Loaded; begin if Assigned(FOnLoaded) then FOnLoaded(FUrlDoc, FReceiver); end; { ThtUrlDocLoaderThreadList } //-- BG ---------------------------------------------------------- 19.05.2016 -- constructor ThtUrlDocLoaderThreadList.Create(AOwner: TComponent); begin inherited; FWaiting := TList.Create; FRunning := TList.Create; FMaxRunningThreadCount := ChtMaxRunningThreadCount; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- destructor ThtUrlDocLoaderThreadList.Destroy; var Thread: ThtUrlDocLoaderThread; Index: Integer; begin for Index := FWaiting.Count - 1 downto 0 do begin Thread := FWaiting[Index]; Thread.Terminate; if Thread.Suspended then Thread.Suspended := False; end; for Index := FRunning.Count - 1 downto 0 do begin Thread := FRunning[Index]; Thread.Terminate; if Thread.Suspended then Thread.Suspended := False end; while (FWaiting.Count > 0) or (FRunning.Count > 0) do Application.ProcessMessages; // let the threads come to an end... FWaiting.Free; FRunning.Free; inherited; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtUrlDocLoaderThreadList.RunningCount: Integer; begin Result := FRunning.Count; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThreadList.AddLoader(Thread: ThtUrlDocLoaderThread); begin if FWaiting.Count + FRunning.Count = 0 then begin FDone := 0; FTotal := 0; FFailed := 0; end; Thread.OnTerminate := Terminated; Thread.Priority := tpLower; FWaiting.add(Thread); Inc(FTotal); StartNext; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThreadList.Terminated(Sender: TObject); var Thread: ThtUrlDocLoaderThread absolute Sender; begin Assert(Sender is ThtUrlDocLoaderThread, Sender.ClassName + ' is not a ThtUrlDocLoaderThread'); try Thread.Loaded; except // must continue, no matter what happened. Inc(FFailed); end; FWaiting.Remove(Sender); // paranoia or needed for termination? FRunning.Remove(Sender); Inc(FDone); if FWaiting.Count + FRunning.Count = 0 then begin FDone := 0; FTotal := 0; end; StartNext; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- procedure ThtUrlDocLoaderThreadList.StartNext; var Thread: TThread; begin if Assigned(FOnProgress) then FOnProgress(self, FDone, FTotal); if (FWaiting.Count > 0) and (FRunning.Count < MaxRunningThreadCount) then begin Thread := FWaiting[0]; FWaiting.Delete(0); FRunning.Add(Thread); Thread.Suspended := False end; end; //-- BG ---------------------------------------------------------- 19.05.2016 -- function ThtUrlDocLoaderThreadList.WaitingCount: Integer; begin Result := FWaiting.Count; end; end.
UNIT TreeWorking; INTERFACE CONST WordLength = 60; TYPE Tree = ^NodeType; NodeType = RECORD Wd: STRING; Amount: INTEGER; LLink, RLink: Tree; END; PROCEDURE InsertWord(VAR Data: STRING; VAR Ptr: Tree); //Добавление нового слова в узел дерева PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); //Вывод отсортированного дерева в выходной файл PROCEDURE ClearTree(VAR Ptr: Tree); //Очистка дерева IMPLEMENTATION PROCEDURE InsertWord(VAR Data: STRING; VAR Ptr: Tree); BEGIN {InsertWord} IF Ptr = NIL THEN BEGIN NEW(Ptr); Ptr^.Wd := Data; Ptr^.Amount := 1; Ptr^.LLink := NIL; Ptr^.RLink := NIL; END ELSE IF Ptr^.Wd = Data THEN Ptr^.Amount := Ptr^.Amount + 1 ELSE IF Data <= Ptr^.Wd THEN InsertWord(Data, Ptr^.LLink) ELSE InsertWord(Data, Ptr^.RLink) END; {InsertWord} PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); BEGIN {PrintTree} IF Ptr <> NIL THEN BEGIN PrintTree(Ptr^.LLink, FOut); WRITELN(FOut, Ptr^.Wd, ' ', Ptr^.Amount); PrintTree(Ptr^.RLink, FOut); END; END; {PrintTree} PROCEDURE ClearTree(VAR Ptr: Tree); BEGIN {ClearTree} IF Ptr <> NIL THEN BEGIN ClearTree(Ptr^.LLink); ClearTree(Ptr^.RLink); DISPOSE(Ptr); Ptr := NIL; END; END; {ClearTree} BEGIN END.
{******************************************************************************} { } { EasyIp communication Library } { Common helpers unit } { } { Copyright 2017-2018 Artem Rudenko } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit eiHelpers; interface uses Windows, SysUtils, eiTypes, eiConstants; type TPacketFactory = class public class function GetReadPacket(const offset: short; const dataType: DataTypeEnum; const length: byte): EasyIpPacket; class function GetWritePacket(const offset: short; const dataType: DataTypeEnum; const length: byte): EasyIpPacket; end; TPacketAdapter = class public class function ToByteArray(const packet: EasyIpPacket; const infoPacket: EasyIpInfoPacket): DynamicByteArray; overload; class function ToByteArray(const packet: EasyIpPacket): DynamicByteArray; overload; class function ToEasyIpInfoPacket(const packet: EasyIpPacket): EasyIpInfoPacket; class function ToEasyIpPacket(const buffer: DynamicByteArray): EasyIpPacket; end; implementation class function TPacketFactory.GetReadPacket(const offset: short; const dataType: DataTypeEnum; const length: byte): EasyIpPacket; var packet: EasyIpPacket; begin ZeroMemory(@packet, SizeOf(EasyIpPacket)); with packet do begin Flags := 0; Error := 0; Counter := 0; Spare1 := 0; SendDataType := 0; SendDataSize := 0; SendDataOffset := offset; Spare2 := 0; RequestDataType := byte(dataType); RequestDataSize := length; RequestDataOffsetServer := offset; RequestDataOffsetClient := 0; end; Result := packet; end; class function TPacketFactory.GetWritePacket(const offset: short; const dataType: DataTypeEnum; const length: byte): EasyIpPacket; var packet: EasyIpPacket; begin ZeroMemory(@packet, SizeOf(EasyIpPacket)); with packet do begin Flags := 0; Error := 0; Counter := 0; Spare1 := 0; SendDataType := byte(dataType); SendDataSize := length; SendDataOffset := offset; Spare2 := 0; RequestDataType := 0; //!!! RequestDataSize := 0; RequestDataOffsetServer := offset; RequestDataOffsetClient := 0; end; Result := packet; end; class function TPacketAdapter.ToByteArray(const packet: EasyIpPacket; const infoPacket: EasyIpInfoPacket): DynamicByteArray; var returnBuffer: DynamicByteArray; bufferLength: int; begin bufferLength := EASYIP_HEADERSIZE + packet.RequestDataSize * SHORT_SIZE; SetLength(returnBuffer, bufferLength); CopyMemory(@packet.Data, @infoPacket, SizeOf(infoPacket)); CopyMemory(returnBuffer, @packet, Length(returnBuffer)); Result := returnBuffer; end; class function TPacketAdapter.ToByteArray(const packet: EasyIpPacket): DynamicByteArray; var tBuffer: DynamicByteArray; bufferLength: int; begin bufferLength := EASYIP_HEADERSIZE + packet.RequestDataSize * SHORT_SIZE + packet.SendDataSize * SHORT_SIZE; // if packet.SendDataSize > 0 then // bufferLength := bufferLength + packet.SendDataSize * SHORT_SIZE; SetLength(tBuffer, bufferLength); CopyMemory(tBuffer, @packet, bufferLength); Result := tBuffer; end; //For application using, not for exchange data between PC<->PLC class function TPacketAdapter.ToEasyIpInfoPacket(const packet: EasyIpPacket): EasyIpInfoPacket; var infoPacket: EasyIpInfoPacket; dataLength: int; begin dataLength := SizeOf(EasyIpInfoPacket); ZeroMemory(@infoPacket, dataLength); CopyMemory(@infoPacket, @packet.Data, dataLength); Result := infoPacket; end; class function TPacketAdapter.ToEasyIpPacket(const buffer: DynamicByteArray): EasyIpPacket; var tPacket: EasyIpPacket; begin ZeroMemory(@tPacket, SizeOf(EasyIpPacket)); CopyMemory(@tPacket, buffer, Length(buffer)); Result := tPacket; end; end.
unit uFormPrinciapalCliente; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, IdThreadSafe, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, uBiblioteca, Vcl.Buttons, IdAntiFreezeBase, Vcl.IdAntiFreeze, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdIOHandlerStream; type TEnvioDesktop = class(TThread) private FTCPDesktop: TIdTCPClient; FPrimeiroBMP : TMemoryStream; FSegundoBMP : TMemoryStream; FDiferencaoBMP : TMemoryStream; public constructor Create( pTCPCliente: TIdTCPClient); procedure Execute; override; end; TReceberMouse = class(TThread) private FTCPMouse: TIdTCPClient; FComandoMouse: TComandoMouse; procedure ProcesarComandoMouse; procedure Terminar(sender: TObject); public constructor Create( pMouse: TIdTCPClient); procedure Execute; override; end; TReberTeclado = class(TThread) private FTCPTeclado2: TIdTCPClient; FComandoTeclado: TComandoTeclado; procedure ProcessarComandoTeclado; public procedure Execute; override; constructor Create( pTeclado: TIdTCPClient); end; TFormPrincipalCliente = class(TForm) mmo1: TMemo; pnl1: TPanel; btnConectar: TButton; edtIP: TEdit; edtPorta: TEdit; idtcpclntDesktop: TIdTCPClient; btnInicial: TBitBtn; idtcpclntTeclado: TIdTCPClient; idtcpclntMouse: TIdTCPClient; procedure btnConectarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnInicialClick(Sender: TObject); procedure idhndlrstck1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure idtcpclntDesktopDisconnected(Sender: TObject); procedure idtcpclntMouseDisconnected(Sender: TObject); procedure idtcpclntTecladoDisconnected(Sender: TObject); private { Private declarations } FId: Integer; FEnviaoDesktop: TEnvioDesktop; FReceberMouse: TReceberMouse; FReceberTeclado: TReberTeclado; function Comprimir(pDados: TMemoryStream):boolean; public { Public declarations } end; var FormPrincipalCliente: TFormPrincipalCliente; implementation uses IdGlobal, ZLib; {$R *.dfm} procedure TFormPrincipalCliente.btnInicialClick(Sender: TObject); begin if not FEnviaoDesktop.Started then FEnviaoDesktop.Start; FReceberMouse.Start; FReceberTeclado.Start; end; procedure TFormPrincipalCliente.btnConectarClick(Sender: TObject); var linha: string; lpBuffer : PChar; nSize : DWord; const Buff_Size = MAX_COMPUTERNAME_LENGTH + 1; begin try nSize := Buff_Size; lpBuffer := StrAlloc(Buff_Size); GetComputerName(lpBuffer,nSize); idtcpclntDesktop.Host := edtIP.Text; //idtcpclntDesktop.Host := '127.0.0.1'; idtcpclntDesktop.Port := StrToInt(edtPorta.Text); idtcpclntDesktop.Connect; idtcpclntDesktop.Socket.WriteLn('Desktop|' +String(lpBuffer)); linha := idtcpclntDesktop.IOHandler.ReadLn(); FId := StrToIntDef(linha,0); StrDispose(lpBuffer); idtcpclntTeclado.Host := idtcpclntDesktop.Host; idtcpclntTeclado.port := idtcpclntDesktop.Port; idtcpclntTeclado.Connect; idtcpclntTeclado.Socket.WriteLn('Teclado|'+InttoSTR(FId)); idtcpclntMouse.Host := idtcpclntDesktop.Host; idtcpclntMouse.port := idtcpclntDesktop.Port; idtcpclntMouse.Connect; idtcpclntMouse.Socket.WriteLn('Mouse|'+InttoSTR(FId)); except on e : Exception do raise Exception.Create('Não foi possível estabelecer conmunicação com o servidor' + sLineBreak + e.Message); end end; function TFormPrincipalCliente.Comprimir(pDados: TMemoryStream): boolean; var InputStream,OutputStream :TMemoryStream; inbuffer,outbuffer :Pointer; count,outcount :longint; begin try result := false; if not assigned(pDados) then exit; InputStream := TMemoryStream.Create; OutputStream := TMemoryStream.Create; try InputStream.LoadFromStream(pDados); count := inputstream.Size; getmem(inbuffer,count); Inputstream.ReadBuffer(inbuffer^,count); zcompress(inbuffer,count,outbuffer,outcount,zcMax); outputstream.Write(outbuffer^,outcount); pDados.Clear; pDados.LoadFromStream(OutputStream); result :=true; finally InputStream.Free; OutputStream.Free; FreeMem(inbuffer, count); FreeMem(outbuffer, outcount); end; except raise Exception.Create('Erro a compactar'); end end; procedure TFormPrincipalCliente.FormCreate(Sender: TObject); begin FEnviaoDesktop := TEnvioDesktop.Create(idtcpclntDesktop); FReceberMouse := TReceberMouse.Create( idtcpclntMouse); FReceberTeclado := TReberTeclado.Create(idtcpclntTeclado); end; procedure TFormPrincipalCliente.idhndlrstck1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin mmo1.Lines.Add(AStatusText) ; end; procedure TFormPrincipalCliente.idtcpclntDesktopDisconnected(Sender: TObject); begin FEnviaoDesktop.Terminate; FEnviaoDesktop.WaitFor; FEnviaoDesktop.Free; end; procedure TFormPrincipalCliente.idtcpclntMouseDisconnected(Sender: TObject); begin FReceberMouse.Terminate; FReceberMouse.WaitFor; FReceberMouse.Free; end; procedure TFormPrincipalCliente.idtcpclntTecladoDisconnected(Sender: TObject); begin FReceberTeclado.Terminate; FReceberTeclado.WaitFor; FReceberTeclado.Free; end; { TManipulador } constructor TEnvioDesktop.Create(pTCPCliente: TIdTCPClient); begin inherited Create(True); FTCPDesktop := pTCPCliente; FreeOnTerminate := False; FPrimeiroBMP := TMemoryStream.Create; FSegundoBMP := TMemoryStream.Create; FDiferencaoBMP := TMemoryStream.Create; end; procedure TEnvioDesktop.Execute; begin inherited; try while not Self.Terminated and FTCPDesktop.Connected do begin try if FPrimeiroBMP.Size > 0 then begin try Synchronize( procedure begin FSegundoBMP := TBliblioteca.PegarBMP(True); TBliblioteca.CompareStream(FPrimeiroBMP, FSegundoBMP, FDiferencaoBMP); FormPrincipalCliente.Comprimir(FDiferencaoBMP); TBliblioteca.SendStream(FTCPDesktop,TStream(FDiferencaoBMP)); FSegundoBMP.Position :=0; FPrimeiroBMP.Clear; FPrimeiroBMP.CopyFrom(FSegundoBMP,0) ; FDiferencaoBMP.Clear; FSegundoBMP.Free; end); finally end; end else begin Synchronize( procedure begin FPrimeiroBMP := TBliblioteca.PegarBMP(false); FDiferencaoBMP.CopyFrom(FPrimeiroBMP,0); FormPrincipalCliente.Comprimir(FDiferencaoBMP); TBliblioteca.SendStream(FTCPDesktop,TStream(FDiferencaoBMP)); FDiferencaoBMP.Clear; end); end; except on e : Exception do ShowMessage(e.Message); end; Sleep(3); end; except raise Exception.Create('Eerro a executar thread'); end; end; { TRecebeTecladoMousep } constructor TReceberMouse.Create( pMouse: TIdTCPClient); begin inherited Create(True); FTCPMouse := pMouse; FreeOnTerminate := False; OnTerminate := Terminar; end; procedure TReceberMouse.Execute; var LBuffer: TIdBytes; comando: TComandoMouse; begin inherited; while not Self.Terminated and FTCPMouse.Connected do begin try if not FTCPMouse.IOHandler.InputBufferIsEmpty then begin if TBliblioteca.ReceiveBuffer(FTCPMouse, LBuffer) then begin BytesToRaw(LBuffer, comando, SizeOf(comando)); FComandoMouse := comando; if comando.Alterado then Synchronize(ProcesarComandoMouse); end; end; except on e:Exception do raise Exception.Create(e.Message); end; Sleep(2); end; end; procedure TReceberMouse.ProcesarComandoMouse; begin try case FComandoMouse.TipoEvento of mDown: begin SetCursorPos(FComandoMouse.x, FComandoMouse.y); if FComandoMouse.BotaoDireito then mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) else mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); end; mUp: begin SetCursorPos(FComandoMouse.x, FComandoMouse.y); if FComandoMouse.BotaoDireito then mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0) else mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; mMove: SetCursorPos(FComandoMouse.x, FComandoMouse.y); mCliqueDuplo: begin mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(10); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); Sleep(10); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(10); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; mClique : begin mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(10); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); Sleep(10); end; end; except raise Exception.Create('Erro ao processar comando mouse'); end; end; procedure TReceberMouse.Terminar(sender: TObject); begin ShowMessage('TErminando'); end; { TReberTeclado } constructor TReberTeclado.Create(pTeclado: TIdTCPClient); begin inherited Create(True); FTCPTeclado2 := pTeclado; end; procedure TReberTeclado.Execute; var LBuffer: TIdBytes; comando: TComandoTeclado; begin inherited; while not Self.Terminated and FTCPTeclado2.Connected do begin try if not FTCPTeclado2.IOHandler.InputBufferIsEmpty then begin if TBliblioteca.ReceiveBuffer(FTCPTeclado2, LBuffer) then begin BytesToRaw(LBuffer, comando, SizeOf(comando)); FComandoTeclado := comando; Synchronize( ProcessarComandoTeclado ); end; end; except on e:Exception do raise Exception.Create(e.Message); end; Sleep(2); end; end; procedure TReberTeclado.ProcessarComandoTeclado; begin if ssShift in FComandoTeclado.TeclaAuxiliar then begin keybd_event(VK_SHIFT,0,0,0 ); keybd_event(FComandoTeclado.CodigoTecla,0,0,0 ); keybd_event(FComandoTeclado.CodigoTecla,0,KEYEVENTF_KEYUP,0 ); keybd_event(VK_SHIFT,0,KEYEVENTF_KEYUP,0 ); end else begin keybd_event(FComandoTeclado.CodigoTecla,0,0,0 ); keybd_event(FComandoTeclado.CodigoTecla,0,KEYEVENTF_KEYUP,0 ); end; end; end.
{*******************************************************} { } { Gospel Compiler System } { } { Copyright (C) 1999 Voltus Corporation } { } {*******************************************************} unit Constants; interface {*******************************************************} { } { Error Message } { } {*******************************************************} resourcestring emSemicolonNotAllowedBeforeELSE = ''';'' not allowed before ''ELSE'''; emClause1ExpectedButClause2Found = '''%s'' clause expected, but ''%s'' found'; // todavia emNameIsNotTypeIdentifier = '''%s'' is not a type identifier'; emToken1ExpectedButToken2Found = '''%s'' expected but ''%s'' found'; emElementExpectedButToken2Found = '%s expected but ''%s'' found'; emArrayTypeRequired = 'Array type required'; emAssignmentToFORLoopVariable = 'Assignment to FOR-Loop variable ''%s'''; emCannotUseReservedUnitName = 'Cannot use reserved unit name ''%s'''; // todavia emCaseLabelOutsideOfRangeOfCaseExpression = 'Case label outside of range of case expression'; // todavia emCircularUnitReferenceTo = 'Circular unit reference to ''%s'''; // todavia emCompileTerminatedByUser = 'Compile terminated by user'; // todavia emConstantExpressionExpected = 'Constant expression expected'; // ver esto emConstantExpressionViolatesSubrangeBounds = 'Constant expression violates subrange bounds'; // y esto emConstantObjectCannotBePassedAsVarParameter = 'Constant object cannot be passed as var parameter'; emConstantOrTypeIdentifierExpected = 'Constant or type identifier expected'; emCouldNotCompileUsedUnit = 'Could not compile used unit ''%s'''; // todavia emDeclarationOfNameDiffersFromPreviousDeclaration = 'Declaration of ''%s'' differs from previous declaration'; // todavia emExpressionHasNoValue = 'Expression has no value'; // todavia ( y ver) emExpressionTooComplicated = 'Expression too complicated'; // todavia ( y ver) emFileNotFound = 'File not found: ''%s'''; // todavia emFileTypeNotAllowedHere = 'File type not allowed here'; // todavia emForLoopControlVariableMustBeSimpleLocalVariable = 'For loop control variable must be simple local variable'; emForLoopControlVariableMustHaveOrdinalType = 'For loop control variable must have ordinal type'; emFOROrWHILELoopExecutesZeroTimes = 'FOR or WHILE loop executes zero times - deleted'; // Esto es un warning emFORLoopVariableCannotBePassedAsVarParameter = 'FOR-Loop variable ''%s'' cannot be passed as var parameter'; emFunctionNeedsResultType = 'Function needs result type'; emIdentifierRedeclared = 'Identifier redeclared: ''%s'''; emIllegalCharacterInInputFile = 'Illegal character in input file: ''%s'''; // ya veremos donde va emIncompatibleTypes = 'Incompatible types'; // todavia (hay que ver donde va) emIncompatibleTypesName1AndName2 = 'Incompatible types: ''%s'' and ''%s'''; emIntegerConstantTooLarge = 'Integer constant too large'; // todavia emInternalError = 'Internal error: %d'; // todavia emInvalidFunctionResultType = 'Invalid function result type'; // todavia (faltan los files) emInvalidTypecast = 'Invalid typecast'; // todavia (faltan los typecast) emInvalidVectorIndexed = 'Invalid vector indexed'; emLeftSideCannotBeAssignedTo = 'Left side cannot be assigned to'; emLineTooLong = 'Line too long (more than 255 characters)'; // todavia emLowBoundExceedsHighBound = 'Low bound exceeds high bound'; emMatrixTypeMismatch = 'Matrix type mismatch'; emMatrixMustBeNoSingular = 'Matrix must be no singular'; emMissingOperatorOrSemicolon = 'Missing operator or semicolon'; emMissingParameterType = 'Missing parameter type'; emNotEnoughActualParameters = 'Not enough actual parameters'; emNumberOfElementsDiffersFromDeclaration = 'Number of elements differs from declaration'; // todavia (no existe inicializacion de variables o constantes con tipo) emOperatorNotApplicableToThisOperandType = 'Operator not applicable to this operand type'; emOrdinalTypeRequired = 'Ordinal type required'; emProcedureCannotHaveResultType = 'Procedure cannot have a result type'; emProgramOrUnitRecursivelyUsesItself = 'Program or unit ''%s'' recursively uses itself'; // todavia emRecordTypeRequired = 'Record type required'; emReturnValueOfFunctionMightBeUndefined = 'Return value of function ''%s'' might be undefined'; // todavia emStatementExpectedButExpressionFound = 'Statement expected, but expression of type ''%s'' found'; emSquareMatrixRequired = 'Square matrix requared'; emSyntaxErrorInRealNumber = 'Syntax error in real number'; emTextAfterFinalEND = 'Text after final ''END.'''; // Esto es un Warning emTooManyActualParameters = 'Too many actual parameters'; emTypeNameIsNotYetCompletelyDefined = 'Type ''%s'' is not yet completely defined'; // todavia emTypeOfExpressionMustBeBOOLEAN = 'Type of expression must be BOOLEAN'; emTypeOfExpressionMustBeINTEGER = 'Type of expression must be INTEGER'; emTypesOfActualAndFormalVarParametersMustBeIdentical = 'Types of actual and formal var parameters must be identical'; emUndeclaredIdentifier = 'Undeclared identifier: ''%s'''; emUnexpectedEndOfFileInComment = 'Unexpected end of file in comment started on line %d'; // Todavia (coments {} ) emUnknownDirective = 'Unknown directive: ''%s'''; // todavia emUnsatisfiedForwardDeclaration = 'Unsatisfied forward declaration: ''%s'''; // todavia emUnterminatedString = 'Unterminated string'; emValueAssignedToNameNeverUsed = 'Value assigned to ''%s'' never used'; // todavia emVariableNameIsDeclaredButNeverUsed = 'Variable ''%s'' is declared but never used in ''%s'''; // todavia emVariableNameMightNotHaveBeenInitialized = 'Variable ''%s'' might not have been initialized'; // todavia lsConstant = 'Constant'; lsVariable = 'Variable'; lsType = 'Type'; lsIdentifier = 'Identifier'; lsStatement = 'Statement'; lsDirective = 'Directive'; lsExpression = 'Expression'; implementation end.
PROGRAM Stat(INPUT, OUTPUT); VAR N, Min, Max, Sum, Counter, D: INTEGER; Ch: CHAR; OverFlow: BOOLEAN; PROCEDURE ReadDigitOrMinus(VAR F: TEXT; VAR D: INTEGER; VAR Minus: BOOLEAN); VAR Ch: CHAR; BEGIN {ReadDigitOrMinus} D := -1; IF (NOT EOLN(F)) THEN BEGIN Minus := FALSE; READ(F, Ch); IF (Ch = '0') THEN D := 0 ELSE IF (Ch = '1') THEN D := 1 ELSE IF (Ch = '2') THEN D := 2 ELSE IF (Ch = '3') THEN D := 3 ELSE IF (Ch = '4') THEN D := 4 ELSE IF (Ch = '5') THEN D := 5 ELSE IF (Ch = '6') THEN D := 6 ELSE IF (Ch = '7') THEN D := 7 ELSE IF (Ch = '8') THEN D := 8 ELSE IF (Ch = '9') THEN D := 9 ELSE IF (Ch = '-') THEN Minus := TRUE END END; {ReadDigitOrMinus} PROCEDURE ReadNumber(VAR F: TEXT; VAR N: INTEGER); VAR D: INTEGER; OverFlow: BOOLEAN; Minus: BOOLEAN; Void: BOOLEAN; BEGIN {ReadNumber} OverFlow := FALSE; N := 0; ReadDigitOrMinus(INPUT, D, Minus); IF Minus THEN D := 0; WHILE (D <> -1) AND NOT (OverFlow) DO BEGIN IF (N * 10 + D > MAXINT) OR (N * 10 + D < 0) OR (N > (MAXINT DIV 10) +1) THEN BEGIN Overflow := TRUE; N := -1; END ELSE N := N * 10 + D; ReadDigitOrminus(INPUT, D, Void) END; IF Minus AND NOT (OverFlow) THEN N := -N END; {ReadNumber} BEGIN {Stat} OverFlow := FALSE; WRITELN('Enter numbers with a space, for example:'); WRITELN('-5 100 0'); WRITELN('WARNING: Incorrect characters the program takes as 0'); WRITELN('WARNING: There is a limitation ', MaxInt, ', so value more then ', MaxInt, ' and value less then ', -MaxInt, ' the program takes as -1'); ReadNumber(INPUT, N); WRITE('You entered: ', N); Sum := N; Counter := 1; Min := N; Max := N; WHILE (NOT EOLN(INPUT)) DO BEGIN ReadNumber(INPUT, N); WRITE(' ', N); IF (N < Min) THEN Min := N; IF (N > Max) THEN Max := N; IF (Sum + N > MAXINT) OR (Sum + N < -MAXINT) OR ((Sum > 0) AND (N > 0) AND (Sum + N < 0)) OR ((Sum < 0) AND (N < 0) AND (Sum + N > 0)) THEN OverFlow := TRUE ELSE IF NOT OverFlow THEN BEGIN Sum := Sum + N; Counter := Counter + 1; END END; WRITELN; WRITELN('Smallest number: ', Min); 100/3 WRITELN('Highest number: ', Max); IF OverFlow THEN WRITELN('Average: OverFlow') ELSE WRITELN('Average: ', (Sum DIV Counter), ',', ((ABS(Sum MOD Counter)) * 100 DIV Counter)); END. {Stat} 1
unit AspectModelIntf; interface uses Classes, InfraValueTypeIntf; type IClassA = interface(IInfraObject) ['{6DF4A628-EC6B-4237-9D6E-CE3EAB85836B}'] procedure NotIntercepted; procedure ProcSemPar; procedure Proc1Par(const x: IInfraInteger); procedure Proc2Par(const x, y: IInfraInteger); procedure Proc3Par(const x, y, z: IInfraInteger); procedure Proc4Par(const x, y, z, w: IInfraInteger); procedure Proc5Par(const x, y, z, w, k: IInfraInteger); end; IClassB = interface(IInfraObject) ['{35B89064-540B-457A-9C0C-C16F05B0FF6B}'] function FuncSemPar: IInfraInteger; function FuncSemParWithoutProceed: IInfraInteger; function FuncSemParWithProceed: IInfraInteger; function Func1Par(const x: IInfraInteger): IInfraInteger; function Func2Par(const x, y: IInfraInteger): IInfraInteger; function Func3Par(const x, y, z: IInfraInteger): IInfraInteger; function Func4Par(const x, y, z, w: IInfraInteger): IInfraInteger; function Func5Par(const x, y, z, w, k: IInfraInteger): IInfraInteger; end; const cMsgAdviceCalled = '%s.%s(%s, [%s]) called'; cMsgAdviceAroundCalled = '%s.%s(%s, [%s]):%s %scalled'; cMsgProcedureCalled = '%s.%s(%s) called'; cMsgFunctionCalled = '%s.%s(%s):%s called'; cMsgAdviceOutOfOrder = '%s out of order'; function GlobalTestList: TStrings; implementation var _GlobalTestList: TStrings; function GlobalTestList: TStrings; begin if not Assigned(_GlobalTestList) then _GlobalTestList := TStringList.Create; Result := _GlobalTestList; end; initialization finalization if Assigned(_GlobalTestList) then _GlobalTestList.Free; end.
unit UxlImageList; interface uses windows, commctrl, UxlClasses, UxlList; type TxlImageList = class private Fhandle: HImageList; FIconList: TxlIntList; FOverlayNum: integer; function GetIconByIndex (index: integer): integer; public constructor Create (width: integer = 0; height: integer = 0; imgnum: integer = 0); destructor Destroy (); override; procedure Clear (); function Count (): integer; function AddIcon (id_icon: integer): integer; // returns index function AddIconGrayed (id_icon: integer; id_target: integer = 0): integer; function CreateOverlayedIcon (i_icon, i_overlay: integer; id_target: integer = 0): integer; procedure AddIcons (IconArray: array of cardinal); function AddHIcon (h_icon: HIcon): integer; function FindIcon (id_icon: integer): integer; function DeleteIcon (id_icon: integer): boolean; function AddOverlay (id_icon: integer): integer; property handle: HImageList read Fhandle; property Icons[index: integer]: integer read GetIconByIndex; // return resource id end; implementation uses UxlWindow, UxlFunctions; function GetGrayedIcon (h_icon: HIcon): HIcon; forward; constructor TxlImageList.Create (width: integer = 0; height: integer = 0; imgnum: integer = 0); var i_style: DWord; begin if width <= 0 then width := GetSystemMetrics (SM_CXSMICON); if height <= 0 then height := GetSystemMetrics (SM_CXSMICON); InitCommonControls (); i_style := ILC_COLOR32 or ILC_MASK; // 必须加上 ILC_MASK,否则透明背景显示黑色 if imgnum <= 0 then Fhandle := ImageList_Create (width, height, i_style, 0, 200) else Fhandle := ImageList_Create (width, height, i_style, imgnum, 0); FIconList := TxlIntList.create; FOverlayNum := 0; end; destructor TxlImageList.Destroy (); begin Clear; FIconList.free; ImageList_Destroy (Fhandle); inherited; end; procedure TxlImageList.Clear (); var i: integer; begin ImageList_RemoveAll (Fhandle); for i := FIconList.Low to FIconList.High do if FIconList[i] > 0 then DestroyIcon (FIconList[i]); FIconList.clear; FOverlaynum := 0; end; function TxlImageList.Count (): integer; begin result := ImageList_GetImageCount (Fhandle); end; //---------------------- function TxlImageList.AddIcon(id_icon: integer): integer; var h_Icon: HIcon; begin // result := FIconList.FindByIndex(id_icon); // if result >= 0 then exit; h_icon := LoadIconFromResource (id_icon); if h_icon = 0 then result := -1 else begin result := AddHIcon (h_icon); FIconList.addByIndex (id_icon, 0); end; end; function TxlImageList.AddIconGrayed (id_icon: integer; id_target: integer = 0): integer; var h_Icon: HIcon; begin if id_target = 0 then id_target := FIconList.GetNewIndex; // result := FIconList.FindByIndex(id_target); // if result >= 0 then exit; h_icon := LoadIconFromResource (id_icon); if h_icon = 0 then result := -1 else begin h_icon := GetGrayedIcon (h_icon); result := AddHIcon (h_icon); FIconList.AddByIndex(id_target, h_icon); end; end; function TxlImageList.CreateOverlayedIcon (i_icon, i_overlay: integer; id_target: integer = 0): integer; var h_icon: HIcon; begin if id_target = 0 then id_target := FIconList.GetNewIndex; // result := FIconList.FindByIndex(id_target); // if result >= 0 then exit; h_icon := ImageList_GetIcon (Fhandle, i_icon, INDEXTOOVERLAYMASK (i_overlay) or ILD_TRANSPARENT); result := AddHIcon (h_icon); FIconList.AddByIndex (id_target, h_icon); end; procedure TxlImageList.AddIcons (IconArray: array of cardinal); var i: integer; begin for i := Low(IconArray) to High(IconArray) do AddIcon (IconArray[i]); end; function TxlImageList.AddHIcon (h_icon: HIcon): integer; begin ImageList_AddIcon (Fhandle, h_icon); result := Count() - 1; end; function TxlImageList.AddOverlay (id_icon: integer): integer; var i: integer; begin i := AddIcon(id_icon); if i >= 0 then begin inc (Foverlaynum); ImageList_SetOverlayImage (Fhandle, i, Foverlaynum); result := Foverlaynum; end; end; function TxlImageList.FindIcon (id_icon: integer): integer; begin result := FIconList.FindByIndex (id_icon); end; function TxlImageList.DeleteIcon (id_icon: integer): boolean; var i_pos: integer; begin i_pos := FindIcon(id_icon); if i_pos < 0 then exit; result := ImageList_Remove (Fhandle, i_pos); if result then begin if FIconList[i_pos] > 0 then DestroyIcon (FIconList[i_pos]); FIconList.delete (i_pos); end; end; function TxlImageList.GetIconByIndex (index: integer): integer; begin result := FIconList.Indexes[index]; end; //------------- function GetGrayedIcon (h_icon: HIcon): HIcon; var iconinfo: TIconInfo; h_dc, hdcmem: HDC; i, j: integer; h_bitmap: HBitMap; cl: TColor; lt: byte; d: double; h_handle: HWND; begin h_handle := MainWinHandle; GetIconInfo (h_icon, iconinfo); h_bitmap := iconinfo.hbmColor; h_dc := GetDC (h_handle); hdcmem := CreateCompatibleDC (h_dc); SelectObject (hdcmem, h_bitmap); for i := 0 to 31 do // 不能是 i_width - 1 ! for j := 0 to 31 do begin cl := GetPixel (hdcmem, i, j); d := GetRValue(cl) * 0.299 + GetGValue(cl) * 0.587 + GetBValue(cl) * 0.114; lt := Round(d); SetPixel (hdcmem, i, j, rgb(lt,lt,lt)); end; DeleteDC (hdcmem); ReleaseDC (h_handle, h_dc); result := CreateIconIndirect (iconinfo); end; var ComCtl32Dll: HMODULE; initialization Comctl32Dll := LoadLibraryW ('comctl32.dll'); finalization FreeLibrary (Comctl32dll); end.
program Exercicio_11; procedure troca_variaveis(var a, b:integer); var temp : integer; begin temp := a; a := b; b := temp; end; var a, b: integer; begin write('Digite o A: '); readln(a); write('Digite o B: '); readln(b); troca_variaveis(a, b); writeln('Valor de A: ', a); writeln('Valor de B: ', b); end.
unit HTTPServer; interface uses Classes, SysUtils, IdContext, IdCustomHTTPServer, IdHTTPServer, IdGlobal, HTTPURI, HTTPRequest, HTTPResponse, HTTPRoute; type IHTTPServer = interface ['{DFCCE323-D799-4136-B891-83471EE996BB}'] function Start: boolean; function RouteList: THTTPRouteList; end; TOnHTTPServerLog = procedure(const Text: String); THTTPServer = class sealed(TInterfacedObject, IHTTPServer) strict private _IdHTTPServer: TIdHTTPServer; _RouteList: THTTPRouteList; _OnServerLog: TOnHTTPServerLog; private procedure IdHTTPServer1CommandGet(Context: TIdContext; RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo); procedure FailRoute(const RequestInfo: TIdHTTPRequestInfo; var ResponseInfo: TIdHTTPResponseInfo; const E: Exception); procedure ResponseToIndy(const Response: IHTTPResponse; var ResponseInfo: TIdHTTPResponseInfo); function CommandToHTTPMethod(const Command: String): THTTPMethod; function ContentTypeToText(const Value: THTTPContentType): String; function EncodingToText(const Value: THTTPEncoding): String; procedure DoLog(const Text: String); function FindRoute(const RequestInfo: TIdHTTPRequestInfo): IHTTPRoute; function ResolveRequestURL(const RequestInfo: TIdHTTPRequestInfo): String; function BuildRequest(const RequestInfo: TIdHTTPRequestInfo): IHTTPRequest; function RequestInfoToText(const RequestInfo: TIdHTTPRequestInfo): String; public function Start: boolean; function RouteList: THTTPRouteList; constructor Create(const Port: Word; const OnServerLog: TOnHTTPServerLog); destructor Destroy; override; class function New(const Port: Word; const OnServerLog: TOnHTTPServerLog): IHTTPServer; end; implementation function THTTPServer.Start: boolean; begin _IdHTTPServer.Active := true; Result := _IdHTTPServer.Active; end; function THTTPServer.RouteList: THTTPRouteList; begin Result := _RouteList; end; function THTTPServer.CommandToHTTPMethod(const Command: String): THTTPMethod; begin if SameText('GET', Command) then Result := THTTPMethod.Get else if SameText('POST', Command) then Result := THTTPMethod.Post else if SameText('PUT', Command) then Result := THTTPMethod.Put else if SameText('DELETE', Command) then Result := THTTPMethod.Delete else raise Exception.Create('Unrecognized HTTP command'); end; function THTTPServer.ContentTypeToText(const Value: THTTPContentType): String; const Text: array [THTTPContentType] of string = ('text/plain', 'text/html', 'application/json'); begin Result := Text[Value]; end; function THTTPServer.EncodingToText(const Value: THTTPEncoding): String; const Text: array [THTTPEncoding] of string = ('ansi', 'utf-8'); begin Result := Text[Value]; end; function THTTPServer.RequestInfoToText(const RequestInfo: TIdHTTPRequestInfo): String; begin Result := Format('Date=%s|Accept=%s|RemoteIP=%s|UserAgent=%s|RawHTTPCommand=%s|Version=%s', [ DateTimeToStr(RequestInfo.Date), RequestInfo.Accept, RequestInfo.RemoteIP, RequestInfo.UserAgent, RequestInfo.RawHTTPCommand, RequestInfo.Version]); end; procedure THTTPServer.FailRoute(const RequestInfo: TIdHTTPRequestInfo; var ResponseInfo: TIdHTTPResponseInfo; const E: Exception); var Route: IHTTPRoute; Response: IHTTPResponse; begin Route := RouteList.FindRoute('FailRoute', CommandToHTTPMethod(RequestInfo.Command)); if Assigned(Route) then begin RequestInfo.PostStream.Free; RequestInfo.PostStream := TStringStream.Create(Format('ClassName=%s|Message=%s|%s', [E.ClassName, E.Message, RequestInfoToText(RequestInfo)])); Response := Route.Execute(BuildRequest(RequestInfo)); ResponseToIndy(Response, ResponseInfo); end else begin ResponseInfo.ResponseNo := Ord(THTTPStatusCode.BadRequest); ResponseInfo.ContentText := Format('<HTTP><body>Critical error<br>Command: %s => %s. Error: %s</body></HTTP>', [RequestInfo.Command, RequestInfo.URI, E.Message]); end; end; procedure THTTPServer.ResponseToIndy(const Response: IHTTPResponse; var ResponseInfo: TIdHTTPResponseInfo); begin ResponseInfo.ResponseNo := Ord(Response.StatusCode); ResponseInfo.ContentText := Response.Content; ResponseInfo.ContentEncoding := EncodingToText(Response.Encoding); ResponseInfo.CharSet := EncodingToText(Response.Encoding); ResponseInfo.ContentType := ContentTypeToText(Response.ContentType); end; procedure THTTPServer.DoLog(const Text: String); begin if Assigned(_OnServerLog) then _OnServerLog(Text); end; function THTTPServer.ResolveRequestURL(const RequestInfo: TIdHTTPRequestInfo): String; begin Result := RequestInfo.URI; if Length(RequestInfo.QueryParams) > 0 then Result := Result + '?' + RequestInfo.QueryParams; end; function THTTPServer.FindRoute(const RequestInfo: TIdHTTPRequestInfo): IHTTPRoute; var URL: String; begin URL := ResolveRequestURL(RequestInfo); Result := RouteList.FindRoute(URL, CommandToHTTPMethod(RequestInfo.Command)); if not Assigned(Result) then raise EHTTPRoute.Create('URL not found'); end; function THTTPServer.BuildRequest(const RequestInfo: TIdHTTPRequestInfo): IHTTPRequest; var Stream: TStream; URI: IURI; Body: String; begin Stream := RequestInfo.PostStream; if Assigned(Stream) then begin Stream.Position := 0; Body := ReadStringFromStream(Stream); end else Body := EmptyStr; URI := TURI.New(ResolveRequestURL(RequestInfo)); Result := THTTPRequest.New(URI, Body); end; procedure THTTPServer.IdHTTPServer1CommandGet(Context: TIdContext; RequestInfo: TIdHTTPRequestInfo; ResponseInfo: TIdHTTPResponseInfo); var Route: IHTTPRoute; Response: IHTTPResponse; begin DoLog(Format('%s|%s|%s|%s|%s', [RequestInfo.RemoteIP, RequestInfo.UserAgent, RequestInfo.Version, RequestInfo.Command, RequestInfo.RawHTTPCommand])); try Route := FindRoute(RequestInfo); Response := Route.Execute(BuildRequest(RequestInfo)); ResponseToIndy(Response, ResponseInfo); DoLog(Format('%s|%s|%s|%s|%s|%d|%s', [RequestInfo.RemoteIP, RequestInfo.UserAgent, RequestInfo.Version, RequestInfo.Command, RequestInfo.RawHTTPCommand, ResponseInfo.ResponseNo, ResponseInfo.ContentText])); except on E: Exception do begin DoLog(Format('%s|%s|%s|%s|%s|%s', [RequestInfo.RemoteIP, RequestInfo.UserAgent, RequestInfo.Version, 'ERROR', RequestInfo.RawHTTPCommand, E.Message])); FailRoute(RequestInfo, ResponseInfo, E); end; end; end; constructor THTTPServer.Create(const Port: Word; const OnServerLog: TOnHTTPServerLog); begin _OnServerLog := OnServerLog; _RouteList := THTTPRouteList.New; _IdHTTPServer := TIdHTTPServer.Create(nil); _IdHTTPServer.DefaultPort := Port; _IdHTTPServer.AutoStartSession := true; _IdHTTPServer.OnCommandGet := IdHTTPServer1CommandGet; _IdHTTPServer.OnCommandOther := IdHTTPServer1CommandGet; end; destructor THTTPServer.Destroy; begin _RouteList.Free; _IdHTTPServer.Free; inherited; end; class function THTTPServer.New(const Port: Word; const OnServerLog: TOnHTTPServerLog): IHTTPServer; begin Result := THTTPServer.Create(Port, OnServerLog); end; end.
unit UserBrowser; interface uses Winapi.Windows, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Ora, Vcl.Dialogs, BCControls.DBGrid, Vcl.ComCtrls, JvExComCtrls, JvComCtrls, DBAccess, MemDS, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Buttons, Vcl.ActnList, BCControls.PageControl, Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, SynEdit, Vcl.AppEvnts, Vcl.Menus, VirtualTrees, Vcl.ToolWin, BCControls.ToolBar, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Data.DB, System.Actions, GridsEh, DBAxisGridsEh, DBGridEh, DBGridEhToolCtrls, DBGridEhGrouping, ToolCtrlsEh, BCCommon.Images, DynVarsEh; type TUserBrowserFrame = class(TFrame) UserPageControl: TBCPageControl; InfoTabSheet: TTabSheet; UserPanel: TPanel; UserQuery: TOraQuery; UserDataSource: TOraDataSource; UsersDBGrid: TBCDBGrid; ActionList: TActionList; CustomizeAction: TAction; PageControlPopupActionBar: TPopupActionBar; CustomizePageControl1: TMenuItem; RolesTabSheet: TTabSheet; RolesQuery: TOraQuery; RolesPanel: TPanel; VirtualDrawTree: TVirtualDrawTree; SourceTabSheet: TTabSheet; SourcePanel: TPanel; SourceSynEdit: TSynEdit; SQLEditorAction: TAction; SynSQLSyn: TSynSQLSyn; PrivilegesQuery: TOraQuery; CopyToClipboardAction: TAction; SaveToFileAction: TAction; InfoButtonPanel: TPanel; InfoToolBar: TBCToolBar; ToolButton41: TToolButton; RefreshAction: TAction; RolesButtonPanel: TPanel; RolesToolBar: TBCToolBar; ToolButton3: TToolButton; SourceButtonPanel: TPanel; SourceToolBar: TBCToolBar; SQLEditorToolButton: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; procedure UserPageControlChange(Sender: TObject); procedure CustomizeActionExecute(Sender: TObject); procedure RolesQueryAfterOpen(DataSet: TDataSet); procedure VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure VirtualDrawTreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer); procedure VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo); procedure SQLEditorActionExecute(Sender: TObject); procedure VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure VirtualDrawTreeInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure CopyToClipboardActionExecute(Sender: TObject); procedure SaveToFileActionExecute(Sender: TObject); procedure RefreshActionExecute(Sender: TObject); private { Private declarations } FSession: TOraSession; FObjectName: string; FSchemaParam: string; procedure SetSession(OraSession: TOraSession); function GetActivePageQuery: TOraQuery; procedure SetObjectFrameAlign(Value: TAlign); public { Public declarations } constructor Create(AOwner: TComponent; ParentPanel: TPanel; OraSession: TOraSession; SchemaParam: string); reintroduce; overload; procedure OpenQuery(RefreshQuery: Boolean); property ObjectName: string write FObjectName; property SchemaParam: string read FSchemaParam write FSchemaParam; property ObjectFrameAlign: TAlign write SetObjectFrameAlign; procedure CopyToClipboard; end; implementation uses Main, CustomizePages, Lib, Vcl.Themes, BCCommon.Lib; type PRoleRec = ^TRoleRec; TRoleRec = record Grantee: string; Grantor: string; Owner: string; ObjectName: string; GrantedRole: string; AdminOption: string; DefaultRole: string; ImageIndex: Byte; end; {$R *.dfm} constructor TUserBrowserFrame.Create(AOwner: TComponent; ParentPanel: TPanel; OraSession: TOraSession; SchemaParam: string); begin inherited Create(AOwner); Visible := False; UserPageControl.TabIndex := 0; Parent := ParentPanel; SetSession(OraSession); FSchemaParam := SchemaParam; end; procedure TUserBrowserFrame.UserPageControlChange(Sender: TObject); begin OpenQuery(False); end; procedure TUserBrowserFrame.VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo); var Data: PRoleRec; S: UnicodeString; R: TRect; Format: Cardinal; LStyles: TCustomStyleServices; LColor: TColor; begin LStyles := StyleServices; with Sender as TVirtualDrawTree, PaintInfo do begin Data := Sender.GetNodeData(Node); if not Assigned(Data) then Exit; if not LStyles.GetElementColor(LStyles.GetElementDetails(tgCellNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); //get and set the background color Canvas.Brush.Color := LStyles.GetStyleColor(scEdit); Canvas.Font.Color := LColor; if LStyles.Enabled and (vsSelected in PaintInfo.Node.States) then begin Colors.FocusedSelectionColor := LStyles.GetSystemColor(clHighlight); Colors.FocusedSelectionBorderColor := LStyles.GetSystemColor(clHighlight); Colors.UnfocusedSelectionColor := LStyles.GetSystemColor(clHighlight); Colors.UnfocusedSelectionBorderColor := LStyles.GetSystemColor(clHighlight); Canvas.Brush.Color := LStyles.GetSystemColor(clHighlight); Canvas.Font.Color := LStyles.GetStyleFontColor(sfMenuItemTextSelected);// GetSystemColor(clHighlightText); end else if not LStyles.Enabled and (vsSelected in PaintInfo.Node.States) then begin Canvas.Brush.Color := clHighlight; Canvas.Font.Color := clHighlightText; end; SetBKMode(Canvas.Handle, TRANSPARENT); R := ContentRect; InflateRect(R, -TextMargin, 0); Dec(R.Right); Dec(R.Bottom); S := ''; case Column of 0: S := Data.GrantedRole; 1: S := Data.AdminOption; 2: S := Data.DefaultRole; 3: S := Data.Grantee; 4: S := Data.Grantor; 5: S := Data.Owner; 6: S := Data.ObjectName; end; if Length(S) > 0 then begin with R do begin if (NodeWidth - 2 * Margin) > (Right - Left) then S := ShortenString(Canvas.Handle, S, Right - Left); end; if (Column = 0) or ((Column >= 3) and (Column <= 6)) then Format := DT_TOP or DT_LEFT or DT_VCENTER or DT_SINGLELINE else Format := DT_TOP or DT_LEFT or DT_VCENTER or DT_CENTER or DT_SINGLELINE; DrawTextW(Canvas.Handle, PWideChar(S), Length(S), R, Format); end; end; end; procedure TUserBrowserFrame.VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PRoleRec; begin Data := Sender.GetNodeData(Node); Finalize(Data^); end; procedure TUserBrowserFrame.VirtualDrawTreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PRoleRec; begin if Kind in [ikNormal, ikSelected] then begin Data := VirtualDrawTree.GetNodeData(Node); if Column = 0 then ImageIndex := Data.ImageIndex; end; end; procedure TUserBrowserFrame.VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer); var Data: PRoleRec; AMargin: Integer; begin with Sender as TVirtualDrawTree do begin AMargin := TextMargin; Data := Sender.GetNodeData(Node); if Assigned(Data) then case Column of 0: NodeWidth := Canvas.TextWidth(Data.GrantedRole) + 2 * AMargin; 1: NodeWidth := Canvas.TextWidth(Data.AdminOption) + 2 * AMargin; 2: NodeWidth := Canvas.TextWidth(Data.DefaultRole) + 2 * AMargin; 3: NodeWidth := Canvas.TextWidth(Data.Grantee) + 2 * AMargin; 4: NodeWidth := Canvas.TextWidth(Data.Grantor) + 2 * AMargin; 5: NodeWidth := Canvas.TextWidth(Data.Owner) + 2 * AMargin; 6: NodeWidth := Canvas.TextWidth(Data.ObjectName) + 2 * AMargin; end; end; end; procedure TUserBrowserFrame.VirtualDrawTreeInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var Data, ChildData: PRoleRec; ChildNode: PVirtualNode; begin Data := VirtualDrawTree.GetNodeData(Node); if PrivilegesQuery.Locate('GRANTEE', Data.GrantedRole, []) then begin while not PrivilegesQuery.Eof and (PrivilegesQuery.FieldByName('GRANTEE').AsString = Data.GrantedRole) do begin ChildNode := VirtualDrawTree.AddChild(Node); ChildData := VirtualDrawTree.GetNodeData(ChildNode); ChildData.Grantee := PrivilegesQuery.FieldByName('GRANTEE').AsString; ChildData.GrantedRole := PrivilegesQuery.FieldByName('PRIVILEGE').AsString; ChildData.Grantor := PrivilegesQuery.FieldByName('GRANTOR').AsString; ChildData.Owner := PrivilegesQuery.FieldByName('OWNER').AsString; ChildData.ObjectName := PrivilegesQuery.FieldByName('TABLE_NAME').AsString; ChildData.ImageIndex := IMG_IDX_KEY; PrivilegesQuery.Next; end; ChildCount := VirtualDrawTree.ChildCount[Node]; end; end; procedure TUserBrowserFrame.VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var Data: PRoleRec; begin inherited; Data := VirtualDrawTree.GetNodeData(Node); if PrivilegesQuery.Active and PrivilegesQuery.Locate('GRANTEE', Data.GrantedRole, []) then Include(InitialStates, ivsHasChildren); end; procedure TUserBrowserFrame.SaveToFileActionExecute(Sender: TObject); begin Lib.SaveSQL(Handle, SourceSynEdit); end; procedure TUserBrowserFrame.SetSession(OraSession: TOraSession); var i: Integer; begin FSession := OraSession; for i := 0 to ComponentCount - 1 do if Components[i] is TOraQuery then TOraQuery(Components[i]).Session := OraSession; end; procedure TUserBrowserFrame.SQLEditorActionExecute(Sender: TObject); begin MainForm.LoadSQLIntoEditor(Format('%s@%s', [UserQuery.Session.Schema, UserQuery.Session.Server]), SourceSynEdit.Text); end; procedure TUserBrowserFrame.CopyToClipboardActionExecute(Sender: TObject); begin CopyAllToClipboard(SourceSynEdit); end; procedure TUserBrowserFrame.CustomizeActionExecute(Sender: TObject); begin CustomizePageControlDialog.Open(UserPageControl); end; function TUserBrowserFrame.GetActivePageQuery: TOraQuery; begin Result := nil; if UserPageControl.ActivePage = InfoTabSheet then Result := UserQuery else if UserPageControl.ActivePage = RolesTabSheet then Result := RolesQuery else if UserPageControl.ActivePage = SourceTabSheet then Result := RolesQuery end; procedure TUserBrowserFrame.OpenQuery(RefreshQuery: Boolean); var OraQuery: TOraQuery; begin OraQuery := GetActivePageQuery; if Assigned(OraQuery) then begin if (not RefreshQuery) and OraQuery.Active and (OraQuery.ParamByName('P_OBJECT_NAME').AsWideString = FObjectName) then Exit; with OraQuery do begin Close; UnPrepare; ParamByName('P_OBJECT_NAME').AsWideString := FObjectName; Prepare; Open; Application.ProcessMessages; SetGridColumnWidths(UsersDBGrid) end; end; end; procedure TUserBrowserFrame.RefreshActionExecute(Sender: TObject); begin OpenQuery(True); end; procedure TUserBrowserFrame.RolesQueryAfterOpen(DataSet: TDataSet); var // Node: TTreeNode; GrantedRole, AdminOption: string; Parent: TList; Node: PVirtualNode; NodeData: PRoleRec; begin with PrivilegesQuery do begin Close; UnPrepare; ParamByName('P_OBJECT_NAME').AsWideString := FObjectName; Prepare; Open; end; VirtualDrawTree.Clear; VirtualDrawTree.NodeDataSize := SizeOf(TRoleRec); VirtualDrawTree.BeginUpdate; SourceSynEdit.Lines.Clear; SourceSynEdit.Lines.BeginUpdate; SourceSynEdit.Lines.Text := 'CREATE USER ' + FObjectName + ' IDENTIFIED BY "<password>";' + CHR_ENTER + CHR_ENTER; Parent := TList.Create; try with RolesQuery do begin First; Parent.Add(nil); GrantedRole := ''; while not Eof do begin { Role } Node := VirtualDrawTree.AddChild(Parent.Items[Parent.Count - 1]); NodeData := VirtualDrawTree.GetNodeData(Node); NodeData.Grantee := FieldByName('GRANTEE').AsString; NodeData.GrantedRole := FieldByName('GRANTED_ROLE').AsString; NodeData.AdminOption := FieldByName('ADMIN_OPTION').AsString; NodeData.DefaultRole := FieldByName('DEFAULT_ROLE').AsString; NodeData.ImageIndex := IMG_IDX_USER_CHILD; // role { Privilege } (* Grantee := NodeData.Grantee; if PrivilegesQuery.Locate('GRANTEE', Grantee, []) then begin while PrivilegesQuery.FieldByName('GRANTEE').AsString = Grantee do begin Node := VirtualDrawTree.AddChild(Parent.Items[Parent.Count - 1]); NodeData := VirtualDrawTree.GetNodeData(Node); NodeData.Grantee := PrivilegesQuery.FieldByName('PRIVILEGE').AsString; Next; end; end; *) AdminOption := ''; if FieldByName('ADMIN_OPTION').AsString = 'YES' then AdminOption := ' WITH ADMIN OPTION'; if FieldByName('GRANTEE').AsString = FObjectName then SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + 'GRANT ' + FieldByName('GRANTED_ROLE').AsString + ' TO ' + FObjectName + AdminOption + ';' + CHR_ENTER; GrantedRole := FieldByName('GRANTED_ROLE').AsString; Next; if GrantedRole = FieldByName('GRANTEE').AsString then Parent.Add(Node) else begin NodeData := VirtualDrawTree.GetNodeData(Parent.Items[Parent.Count - 1]); if Assigned(NodeData) then GrantedRole := NodeData.GrantedRole else GrantedRole := ''; while (Parent.Count > 1) and (GrantedRole <> '') and (GrantedRole <> FieldByName('GRANTEE').AsString) do begin Parent.Delete(Parent.Count - 1); NodeData := VirtualDrawTree.GetNodeData(Parent.Items[Parent.Count - 1]); if Assigned(NodeData) then GrantedRole := NodeData.GrantedRole else GrantedRole := ''; end; end; end; SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + 'ALTER USER ' + FObjectName + ' DEFAULT ROLE ALL;'; First; end; finally Parent.Free; VirtualDrawTree.EndUpdate; SourceSynEdit.Lines.Text := Trim(SourceSynEdit.Lines.Text); SourceSynEdit.Lines.EndUpdate; end; end; procedure TUserBrowserFrame.SetObjectFrameAlign(Value: TAlign); begin InfoButtonPanel.Align := Value; RolesButtonPanel.Align := Value; SourceButtonPanel.Align := Value; end; procedure TUserBrowserFrame.CopyToClipboard; begin SourceSynEdit.CopyToClipboard end; end.
{ Subroutine PICPRG_INIT (PR) * * Initialize the library use state PR. This call allocates no resources, * but after this call PR can be passed to PICPRG_OPEN to open a new use * of the library. The application may change some of the fields in PR * before the OPEN call to chose non-default settings. See the PICPRG_OPEN * documentations for details. } module picprg_init; define picprg_init; %include 'picprg2.ins.pas'; procedure picprg_init ( {initialize library state to defaults} out pr: picprg_t); {returned ready to pass to OPEN} val_param; begin pr.devconn := picprg_devconn_unk_k; {init to device connection type unknown} pr.sio := 1; {system serial line 1} pr.prgname.max := size_char(pr.prgname.str); {user name of programmer not specified} pr.prgname.len := 0; pr.debug := 1; {set to default debug output information} pr.flags := []; {init all general control flags to off} pr.lvpenab := true; {init to allow low voltage prog entry mode} pr.hvpenab := true; {init to allow high voltage prog entry mode} end;
unit RRManagerQuickMapViewFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerObjects, OleCtrls, ComCtrls, ActnList, ToolWin, DB, ADODB, ImgList, StdCtrls, Menus, RRManagerBaseGUI, RRManagerBaseObjects, BaseObjects; type TFoundType = (ftByUIN, ftByName, ftNotFound); TfrmQuickViewMap = class(TFrame, IConcreteVisitor) tlbr: TToolBar; actnLst: TActionList; actnUIN: TAction; tlbtnUIN: TToolButton; ToolButton2: TToolButton; actnFund: TAction; actnComment: TAction; imgLst: TImageList; ToolButton3: TToolButton; actnSave: TAction; actnUndo: TAction; tlbrEdit: TToolBar; edtComment: TEdit; ToolButton4: TToolButton; ToolButton5: TToolButton; pmnStructs: TPopupMenu; procedure actnUINExecute(Sender: TObject); procedure actnUINUpdate(Sender: TObject); procedure mgmFundMaponSelectionChanged(ASender: TObject; const Map: IDispatch); procedure actnFundExecute(Sender: TObject); procedure actnCommentExecute(Sender: TObject); procedure actnFundUpdate(Sender: TObject); procedure actnCommentUpdate(Sender: TObject); procedure actnSaveExecute(Sender: TObject); procedure actnUndoExecute(Sender: TObject); private { Private declarations } //FLayer: IMapLayer3; FLayerName: string; FUpdateByName, FUpdateByObjectID, FSelectQry, FUpdateUINed, FSelectUINed: string; FFoundType: TFoundType; FSelItemName: string; FConnString: string; FLastNote, FLastKlass: string; FQuickViewObject: TBaseObject; FMapPath: string; FZoomGoToUINed: string; FZoomGotoNamed: string; function GetMapObject(AUIN: string; ForceZoom: boolean): integer; function GetMapNamedObject(AName: string): integer; procedure SetQuickViewObject(const Value: TBaseObject); procedure SetMapPath(const Value: string); // procedure PrepareForDuplicatesArranging; // procedure UnprepareForDuplicatesArranging; protected function GetActiveObject: TIDObject; procedure SetActiveObject(const Value: TIDObject); public { Public declarations } procedure VisitVersion(AVersion: TOldVersion); procedure VisitStructure(AStructure: TOldStructure); procedure VisitDiscoveredStructure(ADiscoveredStructure: TOldDiscoveredStructure); procedure VisitPreparedStructure(APreparedStructure: TOldPreparedStructure); procedure VisitDrilledStructure(ADrilledStructure: TOldDrilledStructure); procedure VisitField(AField: RRManagerObjects.TOldField); procedure VisitHorizon(AHorizon: TOldHorizon); procedure VisitSubstructure(ASubstructure: TOldSubstructure); procedure VisitLayer(ALayer: TOldLayer); procedure VisitBed(ABed: TOldBed); procedure VisitAccountVersion(AAccountVersion: TOldAccountVersion); procedure VisitStructureHistoryElement(AHistoryElement: TOldStructureHistoryElement); procedure VisitOldLicenseZone(ALicenseZone: TOldLicenseZone); procedure Clear; property QuickViewObject: TBaseObject read FQuickViewObject write SetQuickViewObject; property LayerName: string read FLayerName write FLayerName; property UpdateByName: string read FUpdateByName write FUpdateByName; property UpdateByObjectID: string read FUpdateByObjectID write FUpdateByObjectID; property SelectQry: string read FSelectQry write FSelectQry; property SelectUINed: string read FSelectUINed write FSelectUINed; property UpdateUINed: string read FUpdateUINed write FUpdateUINed; property ZoomGoToUINed: string read FZoomGoToUINed write FZoomGoToUINed; property ZoomGoToNamed: string read FZoomGotoNamed write FZoomGotoNamed; property MapPath: string read FMapPath write SetMapPath; procedure VisitWell(AWell: TIDObject); procedure VisitTestInterval(ATestInterval: TIDObject); procedure VisitLicenseZone(ALicenseZone: TIDObject); procedure VisitSlotting(ASlotting: TIDObject); procedure VisitCollectionWell(AWell: TIDObject); procedure VisitCollectionSample(ACollectionSample: TIDObject); procedure VisitDenudation(ADenudation: TIDObject); procedure VisitWellCandidate(AWellCandidate: TIDObject); constructor Create(AOwner: TComponent); override; end; implementation uses ClientCommon, Facade; {$R *.dfm} type TPutUINByObjectID = class(TBaseAction) public function Execute: boolean; override; end; { TfrmQuickViewMap } procedure TfrmQuickViewMap.Clear; //var sel: ISelection; begin // FStructure := nil; {sel := mgmFundMap.getSelection; if Assigned(Sel) then begin sel.clear; if not mgmFundMap.isBusy then mgmFundMap.zoomOut; actnComment.Checked := false; edtComment.Clear; end;} end; constructor TfrmQuickViewMap.Create(AOwner: TComponent); begin inherited; FSelItemName := 'empty'; FConnString := 'Provider=MSDASQL.1;Persist Security Info=False;Data Source=FundStruct'; FFoundType := ftNotFound; end; function TfrmQuickViewMap.GetMapNamedObject(AName: string): integer; //var mObjs: ICollection; // qry: TADOQuery; begin (* Result := 0; //if not mgmFundMap.isBusy then begin if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); {if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName);} if Assigned(FLayer) then begin FLayer.setVisibility(true); mObjs := FLayer.getMapObjects; // вычищаем ое, ая и скобки AName := trim(StringReplace(AName, '(ОЕ)', '', [])); AName := trim(StringReplace(AName, '(-ОЕ)', '', [])); // отрезаем 4 последних AName := copy(AName, 1, Length(AName) - 4); // проверяем есть ли такое имя qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; qry.SQL.Text := Format(FSelectQry , [QuickViewObject.List(loMapAttributes, false, false)]); qry.Open; Result := qry.RecordCount; qry.Close; qry.Free; if Result > 0 then mgmFundMap.zoomGotoLocation('Структуры', AName, 2000); end; end; *) end; function TfrmQuickViewMap.GetMapObject(AUIN: string; ForceZoom: boolean): integer; var qry: TADOQuery; begin Result := 0; (* if not mgmFundMap.isBusy then begin if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); {if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName)}; if Assigned(FLayer) then begin FLayer.setVisibility(true); // сразу готовим qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; qry.SQL.Text := Format(FSelectUINed, [IntToStr(QuickViewObject.ID)]); qry.Prepared := true; qry.Open; qry.First; if qry.Recordset.RecordCount > 0 then begin Result := qry.RecordCount; mgmFundMap.zoomGotoLocation(ZoomGoToUINed, AUIN, 2000); FLastNote := trim(qry.Fields[0].AsString); FLastKlass := trim(qry.Fields[1].AsString); end else if ForceZoom then begin mgmFundMap.zoomGotoLocation(ZoomGoToUINed, AUIN, 2000); Result := 0; end; qry.Close; qry.Free; end; end; *) end; procedure TfrmQuickViewMap.VisitBed(ABed: TOldBed); begin QuickViewObject := ABed; end; procedure TfrmQuickViewMap.VisitDiscoveredStructure( ADiscoveredStructure: TOldDiscoveredStructure); begin QuickViewObject := ADiscoveredStructure; end; procedure TfrmQuickViewMap.VisitDrilledStructure( ADrilledStructure: TOldDrilledStructure); begin QuickViewObject := ADrilledStructure; end; procedure TfrmQuickViewMap.VisitField(AField: RRManagerObjects.TOldField); begin QuickViewObject := AField; end; procedure TfrmQuickViewMap.VisitHorizon(AHorizon: TOldHorizon); begin QuickViewObject := AHorizon.Structure; end; procedure TfrmQuickViewMap.VisitLayer(ALayer: TOldLayer); begin if Assigned(ALayer.Substructure) then QuickViewObject := ALayer.Substructure.Horizon.Structure else if Assigned(ALayer.Bed) then QuickViewObject := ALayer.Bed.Structure; end; procedure TfrmQuickViewMap.VisitPreparedStructure( APreparedStructure: TOldPreparedStructure); begin QuickViewObject := APreparedStructure; end; procedure TfrmQuickViewMap.VisitStructure(AStructure: TOldStructure); begin QuickViewObject := AStructure; end; procedure TfrmQuickViewMap.VisitSubstructure(ASubstructure: TOldSubstructure); begin QuickViewObject := ASubstructure.Horizon.Structure; end; procedure TfrmQuickViewMap.actnUINExecute(Sender: TObject); var qry: TADOQuery; begin qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; if FSelItemName = 'empty' then qry.SQL.Text := Format(FUpdateByName, [IntToStr(QuickViewObject.ID), QuickViewObject.List(loMapAttributes, false, false), QuickViewObject.List(loMapAttributes, false, false) + '\n' + IntToStr(QuickViewObject.ID), QuickViewObject.List(loMapAttributes, false, false)]) else begin FSelItemName := copy(FSelItemName, 1, pos('\n', FSelItemName)-1); qry.SQL.Text := Format(FUpdateByName, [IntToStr(QuickViewObject.ID), QuickViewObject.List(loMapAttributes, false, false), QuickViewObject.List(loMapAttributes, false, false) + '\n' + IntToStr(QuickViewObject.ID), FSelItemName]); end; qry.Prepared := true; qry.ExecSQL; qry.Close; qry.Free; //FLayer.Rebuild := true; if GetMapObject(IntToStr(QuickViewObject.ID), true) > 0 then FFoundType := ftByUIN; end; procedure TfrmQuickViewMap.actnUINUpdate(Sender: TObject); begin // actnUIN.Enabled := Assigned(QuickViewObject) and ((FFoundType <> ftNotFound) or (FSelItemName <> 'empty')); end; procedure TfrmQuickViewMap.mgmFundMaponSelectionChanged(ASender: TObject; const Map: IDispatch); var sel: OleVariant; selObjs: OleVariant; begin (* sel := mgmFundMap.getSelection; if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); {if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName){}; SelObjs := Sel.getMapObjects(FLayer); {if SelObjs.Count = 0 then SelObjs := Sel.getMapObjects(FFieldLayer);} if SelObjs.Count > 0 then begin FSelItemName := SelObjs.Item(0).getName; // if SelObjs.Count > 1 then // PrepareForDuplicatesArranging // else UnPrepareForDuplicatesArranging; end else FSelItemName := 'empty'; *) end; procedure TfrmQuickViewMap.actnFundExecute(Sender: TObject); var qry: TADOQuery; sNewKlass: string; begin sNewKlass := varAsType(GetObjectName((TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName['TBL_STRUCTURE_FUND_TYPE_DICT'].Dict, (QuickViewObject as TOldStructure).StructureTypeID, 2), varOleStr); if sNewKlass <> '' then begin qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; qry.SQL.Text := Format(FUpdateUINed, ['klass', sNewKlass, IntToStr(QuickViewObject.ID)]); qry.Prepared := true; qry.ExecSQL; qry.Close; qry.Free; //FLayer.Rebuild := true; end; end; procedure TfrmQuickViewMap.actnCommentExecute(Sender: TObject); begin actnComment.Checked := not actnComment.Checked; tlbrEdit.Visible := actnComment.Checked; if tlbrEdit.Visible then begin // загружаем edtComment.Text := FLastNote; edtComment.SetFocus; edtComment.SelectAll; end; end; procedure TfrmQuickViewMap.actnFundUpdate(Sender: TObject); var s: string; begin if Assigned(QuickViewObject) and (QuickViewObject is TOldStructure) and (not(QuickViewObject is RRManagerObjects.TOldField)) then begin s := varAsType(GetObjectName((TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName['TBL_STRUCTURE_FUND_TYPE_DICT'].Dict, (QuickViewObject as TOldStructure).StructureTypeID, 2), varOleStr); actnFund.Enabled := (FFoundType = ftByUIN) and (FLastKlass <> s) and (FLastKlass <> ''); end else actnFund.Enabled := false; end; procedure TfrmQuickViewMap.actnCommentUpdate(Sender: TObject); begin actnComment.Enabled := (FFoundType = ftByUIN) end; procedure TfrmQuickViewMap.actnSaveExecute(Sender: TObject); var qry: TADOQuery; begin qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; qry.SQL.Text := Format(FUpdateUINed, ['note', edtComment.Text, IntToStr(QuickViewObject.ID)]); qry.Prepared := true; qry.ExecSQL; qry.Close; qry.Free; //FLayer.Rebuild := true; end; procedure TfrmQuickViewMap.actnUndoExecute(Sender: TObject); begin edtComment.Text := FLastNote; end; {procedure TfrmQuickViewMap.PrepareForDuplicatesArranging; var qry: TADOQuery; actn: TBaseAction; pmi: TMenuItem; begin pmnStructs.Items.Clear; pmi := TMenuItem.Create(pmnStructs); pmi.Action := actnUIN; pmi.Caption := actnUIN.Caption + '(все)'; pmnStructs.Items.Add(pmi); // выбираем дублированные // создаём пункты меню // привязываем их ID к пунктам меню qry := TADOQuery.Create(nil); qry.ConnectionString := FConnString; qry.SQL.Text := Format(FSelectQry , [Structure.Name]); qry.Open; qry.First; while not qry.Eof do begin actn := TPutUINByObjectID.Create(Self); actn.Tag := qry.Fields[0].AsInteger; actn.Caption := FSelItemName + '(' + IntToStr(actn.Tag) + ')'; pmi := TMenuItem.Create(pmnStructs); pmnStructs.Items.Add(pmi); pmi.Action := actn; qry.Next; end; qry.Close; qry.Free; tlbtnUIN.Action := nil; tlbtnUIN.Style := tbsDropDown; tlbtnUIN.DropdownMenu := pmnStructs; tlbtnUIN.Enabled := true; end; procedure TfrmQuickViewMap.UnprepareForDuplicatesArranging; begin tlbtnUIN.Action := actnUIN; tlbtnUIN.Style := tbsButton; tlbtnUIN.DropdownMenu := nil; end;} procedure TfrmQuickViewMap.VisitAccountVersion( AAccountVersion: TOldAccountVersion); begin QuickViewObject := AAccountVersion.Structure; end; procedure TfrmQuickViewMap.VisitStructureHistoryElement( AHistoryElement: TOldStructureHistoryElement); begin QuickViewObject := AHistoryElement.HistoryStructure; end; procedure TfrmQuickViewMap.VisitVersion(AVersion: TOldVersion); begin { TODO : может быть тоже - подключение слоя в зависимости от версии } end; procedure TfrmQuickViewMap.SetQuickViewObject(const Value: TBaseObject); var iObjectsFound: integer; begin iObjectsFound := 0; FSelItemName := 'empty'; if FQuickViewObject <> Value then begin FLastNote := ''; FLastKlass := ''; actnComment.Checked := false; tlbrEdit.Visible := false; edtComment.Clear; FQuickViewObject := Value; if Assigned(FQuickViewObject) then begin iObjectsFound := GetMapObject(IntToStr(FQuickViewObject.ID), false); FFoundType := ftByUIN; if iObjectsFound = 0 then begin iObjectsFound := GetMapNamedObject(FQuickViewObject.List(loMapAttributes, false, false)); FFoundType := ftByName; end; end; if iObjectsFound = 0 then begin Clear; // UnprepareForDuplicatesArranging; FFoundType := ftNotFound; end // else PrepareForDuplicatesArranging; end; end; procedure TfrmQuickViewMap.SetMapPath(const Value: string); begin FMapPath := Value; //mgmFundMap.URL := FMapPath; //mgmFundMap.refresh; //mgmFundMap. end; procedure TfrmQuickViewMap.VisitOldLicenseZone(ALicenseZone: TOldLicenseZone); begin QuickViewObject := ALicenseZone; end; function TfrmQuickViewMap.GetActiveObject: TIDObject; begin Result := nil; end; procedure TfrmQuickViewMap.SetActiveObject(const Value: TIDObject); begin end; procedure TfrmQuickViewMap.VisitSlotting(ASlotting: TIDObject); begin end; procedure TfrmQuickViewMap.VisitTestInterval(ATestInterval: TIDObject); begin end; procedure TfrmQuickViewMap.VisitWell(AWell: TIDObject); begin end; procedure TfrmQuickViewMap.VisitLicenseZone(ALicenseZone: TIDObject); begin end; procedure TfrmQuickViewMap.VisitCollectionSample( ACollectionSample: TIDObject); begin end; procedure TfrmQuickViewMap.VisitCollectionWell(AWell: TIDObject); begin end; procedure TfrmQuickViewMap.VisitDenudation(ADenudation: TIDObject); begin end; procedure TfrmQuickViewMap.VisitWellCandidate(AWellCandidate: TIDObject); begin end; { TPutUINByObjectID } function TPutUINByObjectID.Execute: boolean; var qry: TADOQuery; frm: TfrmQuickViewMap; begin Result := true; qry := TADOQuery.Create(nil); frm := Owner as TfrmQuickViewMap; qry.ConnectionString := frm.FConnString; qry.SQL.Text := Format(frm.FUpdateByObjectID, [IntToStr(frm.QuickViewObject.ID), frm.QuickViewObject.List(loMapAttributes, false, false), frm.QuickViewObject.List(loMapAttributes, false, false) + '\n' + IntToStr(frm.QuickViewObject.ID), IntToStr(Tag)]); qry.Prepared := true; qry.ExecSQL; qry.Close; qry.Free; //frm.FLayer.Rebuild := true; if frm.GetMapObject(IntToStr(frm.QuickViewObject.ID), true) > 0 then frm.FFoundType := ftByUIN; end; end.
unit PageMangerPlugin; interface uses PluginManagerIntf, PluginIntf, DataModuleIntf, ControlPanelElementIntf, Graphics, LinkBrowserIntf; type TPageMangerPlugin = class(TPlugin, IPlugin, IDataModule, IControlPanelElement, ILinkBrowser) private FDataPath: String; FDescription: String; FDisplayName: string; FBitmap: TBitmap; public constructor Create(Module: HMODULE; PluginManager: IPluginManager); destructor Destroy; override; { IPlugin } function GetName: string; function Load: Boolean; function UnLoad: Boolean; { IDataModule } function GetDataPath: String; procedure SetDataPath(const Value: String); { IControlPanelElement } function Execute: Boolean; function GetDescription: string; function GetDisplayName: string; function GetBitmap: TBitmap; { ILinkBrowser } function ILinkBrowser.Execute = ExecuteBrowser; function ExecuteBrowser(var S: String): Boolean; function ILinkBrowser.GetName = GetBrowserName; function GetBrowserName: string; end; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; exports RegisterPlugin; implementation uses SysUtils, Windows, PageMangerMainForm, PageTreeForm; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; var Plugin: IInterface; begin Plugin := TPageMangerPlugin.Create(Module, PluginManager); Result := PluginManager.RegisterPlugin(Plugin); end; { TPageMangerPlugin } constructor TPageMangerPlugin.Create(Module: HMODULE; PluginManager: IPluginManager); begin inherited; FBitmap := Graphics.TBitmap.Create; FDisplayName := 'Редактор страниц'; FDescription := 'Редактор разделов для страниц'; FBitmap.Handle := LoadBitmap(Module, 'PLUGIN_ICON'); end; destructor TPageMangerPlugin.Destroy; begin FBitmap.Free; inherited; end; function TPageMangerPlugin.Execute: Boolean; begin Result := (GetMainForm(FPluginManager, FDataPath) = IDOK); end; function TPageMangerPlugin.ExecuteBrowser(var S: String): Boolean; begin Result := (GetTreeForm(FPluginManager, FDataPath, S) = IDOK); end; function TPageMangerPlugin.GetBitmap: Graphics.TBitmap; begin Result := FBitmap; end; function TPageMangerPlugin.GetBrowserName: string; begin Result := 'Карта сайта'; end; function TPageMangerPlugin.GetDataPath: String; begin Result := FDataPath; end; function TPageMangerPlugin.GetDescription: string; begin Result := FDescription; end; function TPageMangerPlugin.GetDisplayName: string; begin Result := FDisplayName; end; function TPageMangerPlugin.GetName: string; begin Result := 'PageMangerPlugin'; end; function TPageMangerPlugin.Load: Boolean; begin Result := True; end; procedure TPageMangerPlugin.SetDataPath(const Value: String); begin FDataPath := IncludeTrailingPathDelimiter(Value); end; function TPageMangerPlugin.UnLoad: Boolean; begin Result := True; end; end.
unit SetEcho; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface procedure SetupFileEchoProcessor; procedure SetupFileEchoLinks; procedure SetupForwardReq; { =================================================================== } implementation uses Objects, MyLib, SysUtils, Views, Dialogs, Drivers, App, _CFG, _RES, _LOG, MsgBox, MyViews, MsgAPI, _FAreas, Setup, HifiHelp, Import, _fopen; { --------------------------------------------------------- } { TOptionsDialog } { --------------------------------------------------------- } type POptionsDialog = ^TOptionsDialog; TOptionsDialog = object (TDialog) procedure HandleEvent( var Event: TEvent ); virtual; private procedure SetupAreafixRobots; end; { TOptionsDialog } { HandleEvent --------------------------------------------- } procedure TOptionsDialog.HandleEvent( var Event: TEvent ); const cmSetupRobots = 200; begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmSetupRobots: SetupAreafixRobots; else Exit; end; ClearEvent( Event ); end; end; end; { HandleEvent } { SetupAreaFixRobots -------------------------------------- } procedure TOptionsDialog.SetupAreaFixRobots; begin EditStrList( LoadString(_SAfixRobots), CFG^.AfixRobots, hcSetupAfixRobots ); CFG^.Modified := True; end; { SetupFinderRobots } { --------------------------------------------------------- } { SetupFileEchoProcessor } { --------------------------------------------------------- } procedure SetupFileEchoProcessor; var R: TRect; D: PDialog; E: POptionsDialog; Q: record OutTicPath : LongStr; BadTicPath : LongStr; Autocreate : LongStr; Passthrough: LongStr; FileBoxes : LongStr; HatchPw : LongStr; AfixHelp : LongStr; KillAfixReq: Longint; end; begin FillChar( Q, SizeOf(Q), 0 ); with CFG^ do begin Q.OutTicPath := OutTicPath; Q.BadTicPath := BadTicPath; Q.Autocreate := Autocreate; Q.Passthrough := Passthrough; Q.FileBoxes := FileBoxes; Q.HatchPw := HatchPw; Q.AfixHelp := AllFixHelp; SetBit( Q.KillAfixReq, $0001, KillAfixReq ); end; D := PDialog( Res^.Get( 'SETUP_EPROC' ) ); D^.HelpCtx := hcSetupEchoProc; R.Assign( 0, 0, 0, 0 ); E := New( POptionsDialog, Init(R, '') ); SwapDlg( D, E ); if Application^.ExecuteDialog( E, @Q ) = cmOk then begin with CFG^ do try OutTicPath := ExistingDir( Q.OutTicPath, True ); BadTicPath := ExistingDir( Q.BadTicPath, True ); Autocreate := ExistingDir( Q.Autocreate, True ); Passthrough := ExistingDir( Q.Passthrough, True ); FileBoxes := ExistingDir( Q.FileBoxes, True ); HatchPw := Q.HatchPw; AllfixHelp := ExistingFile( Q.AfixHelp ); KillAfixReq := TestBit( Q.KillAfixReq, $0001 ); except on E: Exception do ShowError( E.Message ); end; CFG^.Modified := True; end; end; { SetupFileEchoProcessor } { --------------------------------------------------------- } { TAccessBox } { --------------------------------------------------------- } type PAccessBox = ^TAccessBox; TAccessBox = object (TMyListBox) LinkAddr: PAddress; destructor Done; virtual; function GetText( Item, MaxLen: Integer ) : String; virtual; end; { TAccessBox } { Done ---------------------------------------------------- } destructor TAccessBox.Done; begin List^.DeleteAll; // Sic! Dont use FreeAll. Destroy( List ); inherited Done; end; { Done } { GetText ------------------------------------------------- } function TAccessBox.GetText( Item, MaxLen: Integer ) : String; var E: PFileEcho; S: String[2]; j: Integer; begin E := List^.At(Item); S := '--'; if E^.Downlinks^.Search( LinkAddr, j ) then S[1] := 'R'; if E^.Uplinks^.Search( LinkAddr, j ) then S[2] := 'W'; Result := S + ' │ ' + E^.Name^; end; { GetText } { --------------------------------------------------------- } { LinkedEchosEditor } { --------------------------------------------------------- } type PLinkedEchosEditor = ^TLinkedEchosEditor; TLinkedEchosEditor = object (TDialog) ListBox: PAccessBox; Access : PCheckBoxes; procedure SetupDialog( Link: PEchoLink ); procedure HandleEvent( var Event: TEvent ); virtual; end; { TLinkedEchosEditor } { SetupDialog ---------------------------------------------- } procedure TLinkedEchosEditor.SetupDialog( Link: PEchoLink ); var R: TRect; S: String; List: PEchoList; procedure CopyAllowedEcho( Echo: PFileEcho ); far; begin if not Link^.Deny^.Match(Echo^.Name^) then List^.Insert( Echo ); end; { CopyAllowedEcho } begin R.Assign( 0, 0, 0, 0 ); Access := PCheckBoxes( ShoeHorn(@Self, New(PCheckBoxes, Init(R, nil) ))); ListBox := PAccessBox ( ShoeHorn(@Self, New(PAccessBox, Init(R, 1, nil) ))); OpenFileBase; // This list MUST be destroyed but it's items MUST NOT be freed! List := New( PEchoList, Init(50, 10) ); FileBase^.EchoList^.ForEach( @CopyAllowedEcho ); ListBox^.SetMode( [] ); ListBox^.LinkAddr := @Link^.Addr; ListBox^.NewList( List ); S := ''; if elo_pause in Link^.Opt then S := ' (passive)'; // MyLib.ReplaceStr вызывать нельзя: // TDialog.Done вызывает DisposeStr, а не FreeStr :( FreeStr( Title ); Title := Objects.NewStr(AddrToStr(Link^.Addr) + S); end; { SetupDialog } { --------------------------------------------------------- } { HandleEvent } { --------------------------------------------------------- } procedure TLinkedEchosEditor.HandleEvent( var Event: TEvent ); const cmSet = 300; cmClearAll = 301; cmClearWA = 302; bDL = $0001; bUL = $0002; procedure UpdateCheckBoxes; var E: PFileEcho; j: Integer; Q: Longint; begin E := ListBox^.SelectedItem; if E = nil then begin if not Access^.GetState( sfDisabled ) then Access^.SetState( sfDisabled, True ); end else begin if Access^.GetState( sfDisabled ) then Access^.SetState( sfDisabled, False); Q := 0; SetBit(Q, bDL, E^.Downlinks^.Search(ListBox^.LinkAddr, j )); SetBit(Q, bUL, E^.Uplinks^.Search(ListBox^.LinkAddr, j)); Access^.SetData( Q ); end; end; { UpdateCheckBoxes } procedure SetRights; var E: PFileEcho; j: Integer; Q: Longint; begin E := ListBox^.SelectedItem; if E = nil then Exit; Access^.GetData( Q ); if TestBit( Q, bDL ) <> E^.Downlinks^.Search( ListBox^.LinkAddr, j ) then begin if TestBit( Q, bDL ) then E^.Downlinks^.Insert( NewAddr(ListBox^.LinkAddr^) ) else E^.Downlinks^.AtFree(j); FileBase^.Modified := True; end; if TestBit( Q, bUL ) <> E^.Uplinks^.Search( ListBox^.LinkAddr, j ) then begin if TestBit( Q, bUL ) then E^.Uplinks^.Insert( NewAddr(ListBox^.LinkAddr^) ) else E^.Uplinks^.AtFree(j); FileBase^.Modified := True; end; ListBox^.DrawView; end; { SetRights } procedure DoClearUL( E: PFileEcho ); far; var j: Integer; begin if E^.Uplinks^.Search(ListBox^.LinkAddr, j) then begin E^.Uplinks^.AtFree(j); FileBase^.Modified := True; end; end; { DoCleaUL } procedure DoClearDL( E: PFileEcho ); far; var j: Integer; begin if E^.Downlinks^.Search(ListBox^.LinkAddr, j) then begin E^.Downlinks^.AtFree(j); FileBase^.Modified := True; end; end; { DoClearDL } procedure ClearAllRights; begin if (ListBox^.Range > 0) and (MessageBox(LoadString(_SCfmClrAllRights), nil, mfConfirmation + mfYesNoCancel) = cmYes) then begin ListBox^.List^.ForEach( @DoClearUL ); ListBox^.List^.ForEach( @DoClearDL ); ListBox^.DrawView; end; end; { ClearAllRights } procedure ClearWriteAccess; begin if (ListBox^.Range > 0) and (MessageBox(LoadString(_SCfmClrWriteRights), nil, mfConfirmation + mfYesNoCancel) = cmYes) then begin ListBox^.List^.ForEach( @DoClearUL ); ListBox^.DrawView; end; end; { ClearWriteAccess } begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmSet : SetRights; cmClearAll: ClearAllRights; cmClearWA : ClearWriteAccess; else Exit; end; ClearEvent( Event ); end; evBroadcast: case Event.Command of cmFocusMoved: UpdateCheckBoxes; end; end; end; { HandleEvent } { --------------------------------------------------------- } { TAddrListBox } { --------------------------------------------------------- } type PAddrListBox = ^TAddrListBox; TAddrListBox = object (TMyListBox) function GetText( Item, MaxLen: Integer ) : String; virtual; end; { TAddrListBox } { GetText ------------------------------------------------- } function TAddrListBox.GetText( Item, MaxLen: Integer ) : String; begin Result := AddrToStr( PEchoLink(List^.At(Item))^.Addr ); end; { GetText } { --------------------------------------------------------- } { TLinkEditor } { --------------------------------------------------------- } type PLinkEditor = ^TLinkEditor; TLinkEditor = object (TDialog) ListBox: PAddrListBox; procedure SetupDialog; procedure HandleEvent( var Event: TEvent ); virtual; private procedure Refresh; procedure EditLinkedAreas( Link: PEchoLink ); end; { TLinkEditor } { SetupDialog --------------------------------------------- } procedure TLinkEditor.SetupDialog; var R: TRect; begin R.Assign( 0, 0, 0, 0 ); ListBox := PAddrListBox( ShoeHorn( @Self, New( PAddrListBox, Init(R, 1, nil)))); ListBox^.NewList( CFG^.Links ); end; { SetupDialog } { HandleEvent --------------------------------------------- } procedure TLinkEditor.HandleEvent( var Event: TEvent ); const cmImport = 200; cmDeny = 201; cmAreas = 202; const bAutoCreate = $0001; bAutoLink = $0002; bNotify = $0004; bPause = $0008; bFileBox = $0010; var Link: PEchoLink; Q: record Addr: LongStr; Pass: LongStr; Aka : LongStr; Opt : Longint; Fla : Longint; end; { TLinkEditorData } procedure RefreshData( Link: PEchoLink ); begin FillChar( Q, SizeOf(Q), 0 ); if Link <> nil then begin with Link^ do begin Q.Addr := AddrToStr(Addr); Q.Pass := Password^; Q.Aka := AddrToStr(OurAka); SetBit( Q.Opt, bAutoCreate, elo_AutoCreate in Opt ); SetBit( Q.Opt, bAutoLink, elo_AutoLink in Opt ); SetBit( Q.Opt, bNotify, elo_Notify in Opt ); SetBit( Q.Opt, bPause, elo_Pause in Opt ); SetBit( Q.Opt, bFileBox, elo_FileBox in Opt ); Q.Fla := Ord( Flavor ); end; end; SetData( Q ); end; { RefreshData } procedure UpdateLink; begin ReplaceStr( Link^.Password, Q.Pass ); Link^.Opt := []; if TestBit( Q.Opt, bAutoCreate ) then Include( Link^.Opt, elo_AutoCreate ); if TestBit( Q.Opt, bAutoLink ) then Include( Link^.Opt, elo_AutoLink ); if TestBit( Q.Opt, bNotify ) then Include( Link^.Opt, elo_Notify ); if TestBit( Q.Opt, bPause ) then Include( Link^.Opt, elo_Pause ); if TestBit( Q.Opt, bFileBox ) then Include( Link^.Opt, elo_FileBox ); Link^.Flavor := TFlavor( Q.Fla ); if not SafeAddr( Q.Aka, Link^.OurAka ) then MessageBox( Format(LoadString(_SBadAddr), [Q.Aka]), nil, mfError + mfOkButton ); end; { UpdateLink } procedure ChangeItem; var A: TAddress; j: Integer; begin with ListBox^ do begin if Focused < Range then begin Self.GetData( Q ); Q.Pass := Trim( Q.Pass ); if SafeAddr( Q.Addr, A ) then begin if CFG^.Links^.Search( @A, j ) and (j <> Focused) then begin MessageBox( LoadString(_SCantChgAddrDupe), nil, mfWarning + mfOkButton ); Exit; end; end else begin MessageBox( Format(LoadString(_SBadAddr), [Q.Addr]), nil, mfError + mfOkButton ); Exit; end; if Q.Pass = '' then begin MessageBox( LoadString(_SEmptyPwd), nil, mfWarning + mfOkButton ); Exit; end; Link := CFG^.Links^.At( Focused ); if CompAddr( Link^.Addr, A ) <> 0 then with CFG^.Links^ do begin AtDelete( Focused ); if j >= Focused then Dec(j); Link^.Addr := A; AtInsert( j, Link ); end; UpdateLink; FocusItem( j ); CFG^.Modified := True; end; end; end; { ChangeItem } procedure AppendItem; var A: TAddress; j: Integer; begin GetData( Q ); Q.Pass := Trim( Q.Pass ); if SafeAddr( Q.Addr, A ) then begin if CFG^.Links^.Search( @A, j ) then begin MessageBox( LoadString(_SCantAddLinkDupe), nil, mfWarning + mfOkButton ); Exit; end; if Q.Pass = '' then begin MessageBox( LoadString(_SCantAddLinkEmptyPwd), nil, mfWarning + mfOkButton ); Exit; end; New( Link, Init(A) ); CFG^.Links^.AtInsert( j, Link ); UpdateLink; with ListBox^ do begin SetRange( Succ(Range) ); FocusItem( j ); end; CFG^.Modified := True; end else MessageBox( Format(LoadString(_SBadAddr), [Q.Addr]), nil, mfError + mfOkButton ); end; { AppendItem } procedure DeleteItem; var Link: PEchoLink; begin with ListBox^ do begin if Focused < Range then begin Link := CFG^.Links^.At( Focused ); if MessageBox( Format(LoadString(_SAskKillLink), [AddrToStr(Link^.Addr)]), nil, mfConfirmation + mfYesNoCancel ) <> cmYes then Exit; CFG^.Links^.AtFree( Focused ); SetRange( Pred(Range) ); FocusItem( Focused ); OpenFileBase; FileBase^.EchoList^.RefineLinks; CFG^.Modified := True; end; end; end; { DeleteItem } procedure FocusMoved; begin RefreshData( ListBox^.SelectedItem ); end; { FocusMoved } procedure EditDenyList; var Link: PEchoLink; begin Link := ListBox^.SelectedItem; if Link <> nil then begin EditStrList( LoadString(_SEditDenyCaption), Link^.Deny, hcEditDenyList ); CFG^.Modified := True; end; end; { EditDenyList } begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmChgItem: ChangeItem; cmAppItem: AppendItem; cmDelItem: DeleteItem; cmDeny : EditDenyList; cmAreas : EditLinkedAreas( ListBox^.SelectedItem ); cmImport : if ImportLinks then Refresh; else Exit; end; ClearEvent( Event ); end; evBroadcast: case Event.Command of cmFocusMoved: FocusMoved; end; end; end; { HandleEvent } { Refresh ------------------------------------------------- } procedure TLinkEditor.Refresh; begin with ListBox^ do begin List := nil; NewList( CFG^.Links ); end; end; { Refresh } { EditLinkedAreas ----------------------------------------- } procedure TLinkEditor.EditLinkedAreas( Link: PEchoLink ); var R: TRect; D: PDialog; E: PLinkedEchosEditor; begin if Link = nil then Exit; R.Assign( 0, 0, 0, 0 ); D := PDialog( Res^.Get('LINKED_ECHOS') ); D^.HelpCtx := hcEditLinkedAreas; E := New( PLinkedEchosEditor, Init(R, '') ); SwapDlg( D, E ); E^.SetupDialog( Link ); Application^.ExecuteDialog( E, nil ); end; { EditLinkedAreas } { --------------------------------------------------------- } { SetupFileEchoLinks } { --------------------------------------------------------- } procedure SetupFileEchoLinks; var R: TRect; D: PDialog; E: PLinkEditor; begin R.Assign( 0, 0, 0, 0 ); D := PDialog( Res^.Get('SETUP_LINK') ); D^.HelpCtx := hcSetupLink; E := New( PLinkEditor, Init(R, '') ); SwapDlg( D, E ); E^.SetupDialog; Application^.ExecuteDialog( E, nil ); end; { SetupFileEchoLinks } { --------------------------------------------------------- } { PAvailListBox } { --------------------------------------------------------- } type PAvailListBox = ^TAvailListBox; TAvailListBox = object (TMyListBox) function GetText( Item, MaxLen: Integer ) : String; virtual; end; { TAvailListBox } { GetText ------------------------------------------------- } function TAvailListBox.GetText( Item, MaxLen: Integer ) : String; begin Result := AddrToStr( PAvailRec(List^.At(Item))^.Addr ); end; { TAvailListBox } { --------------------------------------------------------- } { TReqEditor } { --------------------------------------------------------- } type PReqEditor = ^TReqEditor; TReqEditor = object (TDialog) ListBox: PAvailListBox; Avail : PInputLine; procedure SetupDialog; procedure HandleEvent( var Event: TEvent ); virtual; end; { TReqEditor } { SetupDialog --------------------------------------------- } procedure TReqEditor.SetupDialog; var R: TRect; begin R.Assign( 0, 0, 0, 0 ); Avail := PInputLine( ShoeHorn( @Self, New( PInputLine, Init(R, Pred(SizeOf(LongStr)))))); ListBox := PAvailListBox( ShoeHorn( @Self, New( PAvailListBox, Init(R, 1, nil)))); ListBox^.SetMode([lb_speedsearch, lb_reorder]); ListBox^.NewList( CFG^.Avail ); end; { SetupDialog } { HandleEvent --------------------------------------------- } procedure TReqEditor.HandleEvent( var Event: TEvent ); const cmBrowse = 200; bInactive = $0001; var Q: record Name: LongStr; Addr: LongStr; Opt : Longint; end; procedure InsertItem; var AR: PAvailRec; begin if CFG^.Avail^.Find( ZERO_ADDR ) <> nil then Exit; New( AR ); FillChar( AR^, SizeOf(TAvailRec), 0 ); with ListBox^ do begin List^.AtInsert( Focused, AR ); SetRange( Succ(Range) ); FocusItem( Focused ); CFG^.Modified := True; end; end; { InsertItem } procedure DeleteItem; begin with ListBox^ do begin if Focused >= Range then Exit; if MessageBox( Format(LoadString(_SCfmDelAvailRec), [AddrToStr(PAvailRec(List^.At(Focused))^.Addr)]), nil, mfConfirmation + mfYesNoCancel ) = cmYes then begin List^.AtFree( Focused ); SetRange( Pred(Range) ); FocusItem( Focused ); CFG^.Modified := True; end; end; end; { DeleteItem } procedure ReplaceItem; var A : TAddress; AR: PAvailRec; begin with ListBox^ do begin if Focused >= Range then Exit; Self.GetData( Q ); if not SafeAddr( Q.Addr, A ) then begin ShowError( Format(LoadString(_SBadAddr), [Q.Addr]) ); Exit; end; if CFG^.Links^.Find( A ) = nil then ShowError( Format(LoadString(_SUnknownAvailLink), [AddrToStr(A)] ) ); if not FileExists( Q.Name ) then begin ShowError( Format(LoadString(_SFileNotFound), [Q.Name]) ); Exit; end; AR := List^.At( Focused ); if (CompAddr(AR^.Addr, A) <> 0) and (CFG^.Avail^.Find(A) <> nil) then begin ShowError( Format(LoadString(_SAvailAddrDupe), [Q.Addr]) ); Exit; end; AR^.Addr := A; AR^.Name := Q.Name; AR^.Opt := []; if TestBit( Q.Opt, bInactive ) then Include( AR^.Opt, ao_Inactive ); FocusItem( Focused ); CFG^.Modified := True; end; end; { ReplaceItem } procedure Refresh( AR: PAvailRec ); begin FillChar( Q, SizeOf(Q), 0 ); if AR <> nil then begin Q.Addr := AddrToStr( AR^.Addr ); Q.Name := AR^.Name; SetBit( Q.Opt, bInactive, ao_Inactive in AR^.Opt ); end; SetData( Q ); end; { Refresh } procedure Browse; begin Avail^.GetData( Q.Name ); Q.Name := '*.*'; if ExecFileOpenDlg(LoadString(_SBrowseAvailCaption), Q.Name, Q.Name) then Avail^.SetData( Q.Name ); end; { Browse } begin inherited HandleEvent( Event ); case Event.What of evCommand: begin case Event.Command of cmInsItem: InsertItem; cmDelItem: DeleteItem; cmChgItem: ReplaceItem; cmBrowse : Browse; else Exit; end; ClearEvent( Event ); end; evBroadcast: case Event.Command of cmFocusMoved: Refresh( ListBox^.SelectedItem ); end; end; end; { HandleEvent } { --------------------------------------------------------- } { SetupForwardReq } { --------------------------------------------------------- } procedure SetupForwardReq; var R: TRect; D: PDialog; E: PReqEditor; begin R.Assign( 0, 0, 0, 0 ); D := PDialog( Res^.Get( 'SETUP_AVAIL' ) ); D^.HelpCtx := hcSetupForwardReq; E := New( PReqEditor, Init(R, '') ); SwapDlg( D, E ); E^.SetupDialog; Application^.ExecuteDialog( E, nil ); end; { SetupForwardReq } end.
{------------------------------------ 功能说明:菜单管理... 创建日期:2010/04/23 作者:wzw 版权:wzw -------------------------------------} unit MenuDispatcher; interface uses SysUtils, Classes, Graphics, ComCtrls, Menus, Contnrs, MenuEventBinderIntf, SvcInfoIntf, RegIntf, MainFormIntf; type TItem = class(TObject) Key: string; Obj: TObject; Event: TNotifyEvent; end; TMenuDispatcher = class(TObject, IMenuEventBinder, ISvcInfo) private FList: TObjectList; procedure CreateMenu; procedure CreateTool; procedure OnClick(Sender: TObject); protected {IInterface} function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; {IMenuEventBinder} procedure RegMenuEvent(const Key: string; MenuClick: TNotifyEvent); procedure RegToolEvent(const Key: string; ToolClick: TNotifyEvent; Img: TGraphic); {ISvcInfo} function GetModuleName: string; function GetTitle: string; function GetVersion: string; function GetComments: string; public constructor Create; destructor Destroy; override; end; implementation uses SysSvc, SysFactory; //SplashFormIntf const MenuKey = 'SYSTEM\MENU'; ToolKey = 'SYSTEM\TOOL'; { TMenuDispatcher } function TMenuDispatcher.GetComments: string; begin Result := '可以给菜单或工具栏按扭绑定事件。'; end; function TMenuDispatcher.GetModuleName: string; begin Result := ExtractFileName(SysUtils.GetModuleName(HInstance)); end; function TMenuDispatcher.GetTitle: string; begin Result := '菜单事件绑定接口(IMenuEventBinder)'; end; function TMenuDispatcher.GetVersion: string; begin Result := '20100423.001'; end; procedure TMenuDispatcher.RegMenuEvent(const Key: string; MenuClick: TNotifyEvent); var i: Integer; aItem: TItem; begin for i := 0 to FList.Count - 1 do begin aItem := TItem(FList[i]); if CompareText(aItem.key, Key) = 0 then begin aItem.Event := MenuClick; TMenuItem(aItem.Obj).Visible := True; exit; end; end; end; constructor TMenuDispatcher.Create; begin FList := TObjectList.Create(True); self.CreateMenu; self.CreateTool; inherited; end; destructor TMenuDispatcher.Destroy; begin FList.Free; inherited; end; procedure TMenuDispatcher.CreateMenu; var Reg: IRegistry; aList: TStrings; i: Integer; aItem: TItem; vName: string; vStr: WideString; MainForm: IMainForm; begin if SysService.QueryInterface(IRegistry, Reg) = S_OK then begin if Reg.OpenKey(MenuKey) then begin MainForm := SysService as IMainForm; aList := TStringList.Create; try Reg.GetValueNames(aList); for i := 0 to aList.Count - 1 do begin vName := aList[i]; if Reg.ReadString(vName, vStr) then begin aItem := TItem.Create; aItem.Key := vName; aItem.Obj := MainForm.CreateMenu(vStr, self.OnClick); TMenuItem(aItem.Obj).Visible := False; aItem.Event := nil; FList.Add(aItem); end; end; finally aList.Free; end; end; end; end; procedure TMenuDispatcher.OnClick(Sender: TObject); var i: Integer; aItem: TItem; begin for i := 0 to FList.Count - 1 do begin aItem := TItem(FList[i]); if aItem.Obj = Sender then begin if Assigned(aItem.Event) then aItem.Event(Sender); end; end; end; procedure TMenuDispatcher.RegToolEvent(const Key: string; ToolClick: TNotifyEvent; Img: TGraphic); var i: Integer; aItem: TItem; ImgIndex: Integer; begin for i := 0 to FList.Count - 1 do begin aItem := TItem(FList[i]); if CompareText(aItem.key, Key) = 0 then begin aItem.Event := ToolClick; if aItem.Obj is TToolButton then begin ImgIndex := (SysService as IMainForm).AddImage(Img); TToolButton(aItem.Obj).ImageIndex := ImgIndex; //TToolButton(aItem.Obj).Visible:=True; end; exit; end; end; end; procedure TMenuDispatcher.CreateTool; var Reg: IRegistry; aList, vList: TStrings; i: Integer; aItem: TItem; vName, aStr: string; vStr: WideString; MainForm: IMainForm; begin if SysService.QueryInterface(IRegistry, Reg) = S_OK then begin if Reg.OpenKey(ToolKey) then begin MainForm := SysService as IMainForm; aList := TStringList.Create; vList := TStringList.Create; try Reg.GetValueNames(aList); for i := 0 to aList.Count - 1 do begin vName := aList[i]; if Reg.ReadString(vName, vStr) then begin aStr := vStr; vList.Clear; ExtractStrings([','], [], pchar(aStr), vList); aItem := TItem.Create; aItem.Key := vName; aItem.Obj := MainForm.CreateToolButton(vList.Values['Caption'], self.OnClick, vList.Values['Hint']); //if TToolButton(aItem.Obj).Caption<>'' then//不是分隔线就先不显示,等绑定事件再显示 // TToolButton(aItem.Obj).Visible:=False //else TToolButton(aItem.Obj).Width:=8; aItem.Event := nil; FList.Add(aItem); end; end; finally aList.Free; vList.Free; end; end; end; end; function TMenuDispatcher._AddRef: Integer; begin Result := -1; end; function TMenuDispatcher._Release: Integer; begin Result := -1; end; function TMenuDispatcher.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; initialization finalization end.
unit xe_DwmUtils; interface uses Windows, Messages, SysUtils, Classes, Graphics, ImgList, Controls, Forms, StdCtrls, ExtCtrls, ComCtrls; type {$IF not Declared(UnicodeString)} UnicodeString = WideString; {$IFEND} TImageListAddIconFixer = class helper for TCustomImageList public function AddIcon(Image: TIcon): Integer; //remove the size checking, given TIcon isn't end; //necessarily accurate, and the API will resize anyway procedure AddFormIconToImageList(Form: TForm; ImageList: TCustomImageList); function Create32BitImageList(Owner: TComponent; Width, Height: Integer; AllocBy: Integer = 4): TImageList; procedure DrawGlassCaption(Form: TForm; const Text: UnicodeString; var R: TRect; UseStdFont: Boolean; HorzAlignment: TAlignment = taLeftJustify; VertAlignment: TTextLayout = tlCenter; ShowAccel: Boolean = False); overload; procedure DrawGlassCaption(Form: TForm; var R: TRect; UseStdFont: Boolean = True; HorzAlignment: TAlignment = taLeftJustify; VertAlignment: TTextLayout = tlCenter; ShowAccel: Boolean = False); overload; procedure EnableAppropriateDoubleBuffering(Control: TWinControl); function IsVista: Boolean; inline; //useful for deciding what caption colour to use when maximised function FormsHaveCompatibilityCoords: Boolean; function GetDwmBorderIconsRect(Form: TForm): TRect; function GetRealWindowRect(Handle: HWND; var R: TRect): Boolean; procedure ShowSystemMenu(Form: TForm; const Message: TWMNCRButtonUp); implementation {$J+} uses CommCtrl, DwmApi, ImageHlp, UxTheme, Math, Themes; type TImageListAccess = class(TCustomImageList); procedure AddFormIconToImageList(Form: TForm; ImageList: TCustomImageList); var IconHandle: HICON; begin if not Form.Icon.Empty then IconHandle := Form.Icon.Handle else IconHandle := Application.Icon.Handle; IconHandle := CopyImage(IconHandle, IMAGE_ICON, ImageList.Width, ImageList.Height, LR_COPYFROMRESOURCE); ImageList_AddIcon(ImageList.Handle, IconHandle); //avoid VCL verifying the icon size DestroyIcon(IconHandle); TImageListAccess(ImageList).Change; end; function Create32BitImageList(Owner: TComponent; Width, Height: Integer; AllocBy: Integer = 4): TImageList; begin Result := TImageList.Create(Owner); Result.AllocBy := AllocBy; Result.Width := Width; Result.Height := Height; if GetComCtlVersion < ComCtlVersionIE6 then Exit; {$IF DECLARED(cd32Bit)} Result.ColorDepth := cd32Bit; {$ELSE} Result.Handle := ImageList_Create(Width, Height, ILC_COLOR32 or ILC_MASK, AllocBy, AllocBy) {$IFEND} end; procedure DrawGlassCaption(Form: TForm; const Text: UnicodeString; var R: TRect; UseStdFont: Boolean; HorzAlignment: TAlignment; VertAlignment: TTextLayout; ShowAccel: Boolean); const BasicFormat = DT_SINGLELINE or DT_END_ELLIPSIS; HorzFormat: array[TAlignment] of UINT = (DT_LEFT, DT_RIGHT, DT_CENTER); VertFormat: array[TTextLayout] of UINT = (DT_TOP, DT_VCENTER, DT_BOTTOM); AccelFormat: array[Boolean] of UINT = (DT_NOPREFIX, 0); var DTTOpts: TDTTOpts; { This routine doesn't use GetThemeSysFont and } Element: TThemedWindow; { GetThemeSysColor because they just return theme } IsVistaAndMaximized: Boolean; { defaults that will be overridden by the 'traditional' } NCM: TNonClientMetrics; { settings as and when the latter are set by the user. } ThemeData: HTHEME; procedure DoTextOut; begin with ThemeServices.GetElementDetails(Element) do DrawThemeTextEx(ThemeData, Form.Canvas.Handle, Part, State, PWideChar(Text), Length(Text), BasicFormat or AccelFormat[ShowAccel] or HorzFormat[HorzAlignment] or VertFormat[VertAlignment], @R, DTTOpts); end; begin IsVistaAndMaximized := IsVista and (Form.WindowState = wsMaximized); ThemeData := OpenThemeData(0, 'CompositedWindow::Window'); Assert(ThemeData <> 0, SysErrorMessage(GetLastError)); try if UseStdFont then begin NCM.cbSize := SizeOf(NCM); if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NCM, 0) then if Form.BorderStyle in [bsToolWindow, bsSizeToolWin] then Form.Canvas.Font.Handle := CreateFontIndirect(NCM.lfSmCaptionFont) else Form.Canvas.Font.Handle := CreateFontIndirect(NCM.lfCaptionFont); end; ZeroMemory(@DTTOpts, SizeOf(DTTOpts)); DTTOpts.dwSize := SizeOf(DTTOpts); DTTOpts.dwFlags := DTT_COMPOSITED or DTT_TEXTCOLOR; if not UseStdFont then DTTOpts.crText := ColorToRGB(Form.Canvas.Font.Color) else if IsVistaAndMaximized then DTTOpts.dwFlags := DTTOpts.dwFlags and not DTT_TEXTCOLOR else if Form.Active then DTTOpts.crText := GetSysColor(COLOR_CAPTIONTEXT) else DTTOpts.crText := GetSysColor(COLOR_INACTIVECAPTIONTEXT); if not IsVistaAndMaximized then begin DTTOpts.dwFlags := DTTOpts.dwFlags or DTT_GLOWSIZE; DTTOpts.iGlowSize := 15; end; if Form.WindowState = wsMaximized then if Form.Active then Element := twMaxCaptionActive else Element := twMaxCaptionInactive else if Form.BorderStyle in [bsToolWindow, bsSizeToolWin] then if Form.Active then Element := twSmallCaptionActive else Element := twSmallCaptionInactive else if Form.Active then Element := twCaptionActive else Element := twCaptionInactive; DoTextOut; if IsVistaAndMaximized then DoTextOut; finally CloseThemeData(ThemeData); end; end; procedure DrawGlassCaption(Form: TForm; var R: TRect; UseStdFont: Boolean; HorzAlignment: TAlignment; VertAlignment: TTextLayout; ShowAccel: Boolean); begin DrawGlassCaption(Form, Form.Caption, R, UseStdFont, HorzAlignment, VertAlignment, ShowAccel); end; type TWinControlAccess = class(TWinControl); TToolBarFixer = class strict private class procedure CustomDrawHandler(ToolBar: TToolBar; const ARect: TRect; var DefaultDraw: Boolean); public class procedure Fix(ToolBar: TToolBar); static; end; class procedure TToolBarFixer.CustomDrawHandler(ToolBar: TToolBar; const ARect: TRect; var DefaultDraw: Boolean); begin ToolBar.Canvas.FillRect(ARect); end; class procedure TToolBarFixer.Fix(ToolBar: TToolBar); begin if not (ToolBar.Parent is TPanel) and not Assigned(ToolBar.OnCustomDraw) and ((ToolBar.DrawingStyle = dsNormal) or not (gdoGradient in ToolBar.GradientDrawingOptions)) then ToolBar.OnCustomDraw := TToolBarFixer.CustomDrawHandler; end; function IsAppropriateToDoubleBuffer(Control: TWinControl): Boolean; function WithinGlassRange: Boolean; var R: TRect; begin if not (Control.Parent is TCustomForm) then Result := False else begin R := Control.Parent.ClientRect; with TCustomForm(Control.Parent).GlassFrame do begin Inc(R.Left, Left); Inc(R.Top, Top); Dec(R.Right, Right); Dec(R.Bottom, Bottom); end; Result := (Control.Left < R.Left) or (Control.Top < R.Top) or (Control.Left + Control.Width > R.Right) or (Control.Top + Control.Height > R.Bottom); end; end; begin if (Control is TCustomRichEdit) then Result := False else if Control is TButtonControl then Result := WithinGlassRange //double buffering kills the fade in/out animation, so only enable it if we have to else if Control is TToolBar then begin TToolBarFixer.Fix(TToolBar(Control)); Result := WithinGlassRange; end else begin Result := True; if Control is TCustomGroupBox then begin TWinControlAccess(Control).ParentBackground := False; if not (csAcceptsControls in Control.ControlStyle) then begin //get WS_CLIPCHILDREN window style set to avoid flicker Control.ControlStyle := Control.ControlStyle + [csAcceptsControls]; if Control.HandleAllocated then Control.Perform(CM_RECREATEWND, 0, 0) end; end; end; end; procedure EnableAppropriateDoubleBuffering(Control: TWinControl); {$IF CompilerVersion = 18.5} var I: Integer; begin if not IsAppropriateToDoubleBuffer(Control) then Exit; Control.DoubleBuffered := True; for I := Control.ControlCount - 1 downto 0 do if Control.Controls[I] is TWinControl then EnableAppropriateDoubleBuffering(TWinControl(Control.Controls[I])); end; {$ELSE} procedure CheckChildControls(Parent: TWinControl); var I: Integer; Child: TWinControl; begin for I := Parent.ControlCount - 1 downto 0 do if Parent.Controls[I] is TWinControl then begin Child := TWinControl(Parent.Controls[I]); if Child.ParentDoubleBuffered then if IsAppropriateToDoubleBuffer(Child) then CheckChildControls(Child) else Child.DoubleBuffered := False; end; end; begin Control.DoubleBuffered := IsAppropriateToDoubleBuffer(Control); if Control.DoubleBuffered then CheckChildControls(Control); end; {$IFEND} function FormsHaveCompatibilityCoords: Boolean; const Value: (DontKnow, No, Yes) = DontKnow; var Image: PloadedImage; begin if Value = DontKnow then if Win32MajorVersion < 6 then Value := No else begin Image := ImageLoad(PAnsiChar(AnsiString(GetModuleName(MainInstance))), ''); if Image = nil then RaiseLastOSError; if Image.FileHeader.OptionalHeader.MajorSubsystemVersion >= 6 then Value := No else Value := Yes; ImageUnload(Image); end; Result := (Value = Yes) and DwmCompositionEnabled; end; function InternalGetDwmBorderIconsRect(Form: TForm): TRect; inline begin if DwmGetWindowAttribute(Form.Handle, DWMWA_CAPTION_BUTTON_BOUNDS, @Result, SizeOf(Result)) <> S_OK then SetRectEmpty(Result); end; function GetDwmBorderIconsRect(Form: TForm): TRect; begin if Win32MajorVersion >= 6 then Result := InternalGetDwmBorderIconsRect(Form) else SetRectEmpty(Result); end; function GetRealWindowRect(Handle: HWND; var R: TRect): Boolean; begin Result := (GetParent(Handle) = 0) and DwmCompositionEnabled and (DwmGetWindowAttribute(Handle, DWMWA_EXTENDED_FRAME_BOUNDS, @R, SizeOf(R)) = S_OK); if not Result then Result := GetWindowRect(Handle, R); end; function IsVista: Boolean; inline; begin Result := (Win32MajorVersion = 6) and (Win32MinorVersion = 0); end; { No idea why we have to initialise the menu ourselves, or indeed, why we have to show the thing manually in the first place, given WM_NCHITTEST is properly handled. That said, this routine also sets the correct 'default' (i.e., bold) item, which Vista doesn't bother doing properly even with standard window frames. } procedure ShowSystemMenu(Form: TForm; const Message: TWMNCRButtonUp); var Cmd: WPARAM; Menu: HMENU; procedure UpdateItem(ID: UINT; Enable: Boolean; MakeDefaultIfEnabled: Boolean = False); const Flags: array[Boolean] of UINT = (MF_GRAYED, MF_ENABLED); begin EnableMenuItem(Menu, ID, MF_BYCOMMAND or Flags[Enable]); if MakeDefaultIfEnabled and Enable then SetMenuDefaultItem(Menu, ID, MF_BYCOMMAND); end; begin Menu := GetSystemMenu(Form.Handle, False); if Form.BorderStyle in [bsSingle, bsSizeable, bsToolWindow, bsSizeToolWin] then begin SetMenuDefaultItem(Menu, UINT(-1), 0); UpdateItem(SC_RESTORE, Form.WindowState <> wsNormal, True); UpdateItem(SC_MOVE, Form.WindowState <> wsMaximized); UpdateItem(SC_SIZE, (Form.WindowState <> wsMaximized) and (Form.BorderStyle in [bsSizeable, bsSizeToolWin])); UpdateItem(SC_MINIMIZE, (biMinimize in Form.BorderIcons) and (Form.BorderStyle in [bsSingle, bsSizeable])); UpdateItem(SC_MAXIMIZE, (biMaximize in Form.BorderIcons) and (Form.BorderStyle in [bsSingle, bsSizeable]) and (Form.WindowState <> wsMaximized), True); end; if Message.HitTest = HTSYSMENU then SetMenuDefaultItem(Menu, SC_CLOSE, MF_BYCOMMAND); Cmd := WPARAM(TrackPopupMenu(Menu, TPM_RETURNCMD or GetSystemMetrics(SM_MENUDROPALIGNMENT), Message.XCursor, Message.YCursor, 0, Form.Handle, nil)); PostMessage(Form.Handle, WM_SYSCOMMAND, Cmd, 0) end; { TImageListAddIconFixer } function TImageListAddIconFixer.AddIcon(Image: TIcon): Integer; begin if Image = nil then Result := Add(nil, nil) else begin Result := ImageList_AddIcon(Handle, Image.Handle); Change; end; end; end.
unit CatUI; { Catarinka - User Interface related functions Copyright (c) 2003-2015 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details ForceForegroundWindow function by Ray Lischner, based on code from Karl E. Peterson, with portions from Daniel P. Stasinski } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} Winapi.Windows, Vcl.Forms, Vcl.Menus, Vcl.ExtCtrls, System.SysUtils, System.Classes, Vcl.Controls, Vcl.ComCtrls, Vcl.Clipbrd, Winapi.CommCtrl, Winapi.Messages, Winapi.ShlObj, System.TypInfo; {$ELSE} Windows, Forms, Menus, ExtCtrls, SysUtils, Classes, Controls, ComCtrls, CommCtrl, Messages, ShlObj, TypInfo, Clipbrd; {$ENDIF} function AskYN(const question: string): Boolean; function GetLVItemAsString(lv: TListView; li: TListItem; copytoclipboard: Boolean = false): string; function GetWindowState: integer; function ForceForegroundWindow(hwnd: THandle): Boolean; function GetWindowClassHandle(const Title: string): integer; function GetFullPath(N: TTreeNode; Sep: string = '\'): string; function GetFullPathData(N: TTreeNode): string; function GetLVCheckedItems(lvcomp: TListView): string; function GetLVCheckedItemsSingleLn(lvcomp: TListView): string; function GetPercentage(const percent, Value: integer): Int64; function GetSpecialFolderPath(const Folder: integer; const CanCreate: Boolean): string; function MakeNotifyEvent(forObject: TObject; const procname: string) : TNotifyEvent; function TreeItemSearch(tv: ttreeview; const SearchItem: string): TTreeNode; procedure AddListViewItem(lv: TListView; const capt: string; const ii: integer; const mv: Boolean); procedure AddMultipleListViewItems(lv: TListView; const captlist: string; const ii: integer; const mv: Boolean); procedure ApplyWindowState(const i: integer); procedure CommaToLVItems(lvcomp: TListView; const commastring: string); procedure CloseWindowByClass(const classname: string); procedure DisableLVToolTips(H: THandle); procedure ExpandTreeViewItems(tv: ttreeview); procedure FlashUI(const times: integer = 2; const delay: integer = 500); procedure LoadListviewStrings(listview: TListView; const filename: string); procedure NilComponentMethods(Component: TComponent); procedure QuickSortTreeViewItems(tv: ttreeview); procedure ShowPopupMenu(PopupMenu: TPopupMenu; const AppHandle: integer); procedure SaveListviewStrings(listview: TListView; const filename: string); procedure SaveMemStreamToStrings(Stream: TMemoryStream; List: TStrings); procedure SetNodeBoldState(Node: TTreeNode; const Value: Boolean); type TCanvasPanel = class(TPanel) public property Canvas; end; { CSIDL_DESKTOPDIRECTORY returns the path to the current desktop CSIDL_PERSONAL is the My Documents directory CSIDL___LOCAL_APPDATA is the (user name)\Local Settings\Application Data directory } const CSIDL_DESKTOP = $0000; { <desktop> } CSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) } CSIDL_PROGRAMS = $0002; { Start Menu\Programs } CSIDL_CONTROLS = $0003; { My Computer\Control Panel } CSIDL_PRINTERS = $0004; { My Computer\Printers } CSIDL_PERSONAL = $0005; { My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above } CSIDL_FAVORITES = $0006; { <user name>\Favorites } CSIDL_STARTUP = $0007; { Start Menu\Programs\Startup } CSIDL_RECENT = $0008; { <user name>\Recent } CSIDL_SENDTO = $0009; { <user name>\SendTo } CSIDL_BITBUCKET = $000A; { <desktop>\Recycle Bin } CSIDL_STARTMENU = $000B; { <user name>\Start Menu } CSIDL_MYDOCUMENTS = $000C; { logical "My Documents" desktop icon } CSIDL_MYMUSIC = $000D; { "My Music" folder } CSIDL_MYVIDEO = $000E; { "My Video" folder } CSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop } CSIDL_DRIVES = $0011; { My Computer } CSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) } CSIDL_NETHOOD = $0013; { <user name>\nethood } CSIDL_FONTS = $0014; { windows\fonts } CSIDL_TEMPLATES = $0015; CSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu } CSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs } CSIDL_COMMON_STARTUP = $0018; { All Users\Startup } CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop } CSIDL_APPDATA = $001A; { <user name>\Application Data } CSIDL_PRINTHOOD = $001B; { <user name>\PrintHood } CSIDL_LOCAL_APPDATA = $001C; { <user name>\Local Settings\Application Data (non roaming) } CSIDL_ALTSTARTUP = $001D; { non localized startup } CSIDL_COMMON_ALTSTARTUP = $001E; { non localized common startup } CSIDL_COMMON_FAVORITES = $001F; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data } CSIDL_WINDOWS = $0024; { GetWindowsDirectory() } CSIDL_SYSTEM = $0025; { GetSystemDirectory() } CSIDL_PROGRAM_FILES = $0026; { C:\Program Files } CSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures } CSIDL_PROFILE = $0028; { USERPROFILE } CSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC } CSIDL_PROGRAM_FILESX86 = $002A; { x86 C:\Program Files on RISC } CSIDL_PROGRAM_FILES_COMMON = $002B; { C:\Program Files\Common } CSIDL_PROGRAM_FILES_COMMONX86 = $002C; { x86 C:\Program Files\Common on RISC } CSIDL_COMMON_TEMPLATES = $002D; { All Users\Templates } CSIDL_COMMON_DOCUMENTS = $002E; { All Users\Documents } CSIDL_COMMON_ADMINTOOLS = $002F; { All Users\Start Menu\Programs\Administrative Tools } CSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\Administrative Tools } CSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections } CSIDL_COMMON_MUSIC = $0035; { All Users\My Music } CSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures } CSIDL_COMMON_VIDEO = $0037; { All Users\My Video } CSIDL_RESOURCES = $0038; { Resource Directory } CSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory } CSIDL_COMMON_OEM_LINKS = $003A; { Links to All Users OEM specific apps } CSIDL_CDBURN_AREA = $003B; { USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning } CSIDL_COMPUTERSNEARME = $003D; { Computers Near Me (computered from Workgroup membership) } CSIDL_PROFILES = $003E; implementation uses CatPointer, CatStrings; procedure AddListViewItem(lv: TListView; const capt: string; const ii: integer; const mv: Boolean); begin with lv.Items.Add do begin Caption := capt; imageindex := ii; makevisible(mv); end; end; procedure AddMultipleListViewItems(lv: TListView; const captlist: string; const ii: integer; const mv: Boolean); var c, i: integer; List: TStringlist; begin List := TStringlist.Create; List.text := captlist; c := List.count; for i := 0 to c do begin if i < c then AddListViewItem(lv, List[i], ii, mv); end; List.free; end; procedure ApplyWindowState(const i: integer); begin case i of 0: Application.MainForm.WindowState := WsMaximized; 1: Application.MainForm.WindowState := WsMinimized; 2: Application.MainForm.WindowState := WsNormal; end; end; function AskYN(const question: string): Boolean; begin result := false; case Application.MessageBox({$IFDEF UNICODE}pwidechar{$ELSE}pchar{$ENDIF}(question), {$IFDEF UNICODE}pwidechar{$ELSE}pchar{$ENDIF}(Application.Title), mb_YesNo + mb_DefButton1) of IDYes: result := true; IDNo: result := false; end; end; // Usage example CloseWindowByClass('TSomeForm') procedure CloseWindowByClass(const classname: string); var winHandle: THandle; winClass: array [0 .. 63] of char; begin winHandle := Application.Handle; repeat winHandle := GetNextWindow(winHandle, GW_HWNDNEXT); GetClassName(winHandle, winClass, sizeof(winClass)); if (winHandle <> 0) and (StrComp(winClass, pchar(classname)) = 0) then PostMessage(winHandle, WM_CLOSE, 0, 0); until (winHandle = 0); end; procedure CommaToLVItems(lvcomp: TListView; const commastring: string); var i: integer; sl: TStringlist; begin sl := TStringlist.Create; sl.CommaText := commastring; for i := 0 to sl.count - 1 do begin if (before(sl[i], '=') <> emptystr) then begin with lvcomp.Items.Add do begin Caption := before(sl[i], '='); if after(sl[i], '=') = '1' then checked := true else checked := false; end; end; end; sl.free; end; // Needs testing procedure DisableLVToolTips(H: THandle); var styles: dword; begin styles := ListView_GetExtendedListViewStyle(H); styles := styles and not LVS_EX_INFOTIP; ListView_SetExtendedListViewStyle(H, styles); end; procedure ExpandTreeViewItems(tv: ttreeview); var i, c: integer; begin tv.Items.BeginUpdate; c := tv.Items.count; for i := 0 to c do begin if i < c then begin tv.Items[i].Expand(false); end; end; tv.Items.EndUpdate; try tv.Items[0].Selected := true; except end; end; procedure FlashUI(const times: integer = 2; const delay: integer = 500); var i: integer; procedure doflash(b: Boolean); begin FlashWindow(Application.MainForm.Handle, b); FlashWindow(Application.Handle, b); end; begin for i := 0 to times do begin doflash(true); sleep(delay); doflash(false); sleep(delay); end; end; function GetFullPath(N: TTreeNode; Sep: string = '\'): string; begin result := N.text; N := N.Parent; while (N <> nil) do begin result := N.text + Sep + result; N := N.Parent; end; end; function GetFullPathData(N: TTreeNode): string; begin result := PointerToStr(N.data); N := N.Parent; while (N <> nil) do begin result := PointerToStr(N.data) + '/' + result; N := N.Parent; end; end; function GetLVCheckedItems(lvcomp: TListView): string; var i: integer; sl: TStringlist; begin sl := TStringlist.Create; for i := 0 to lvcomp.Items.count - 1 do begin if lvcomp.Items[i].checked then sl.Add(lvcomp.Items[i].Caption + '=1') else sl.Add(lvcomp.Items[i].Caption + '=0'); end; result := sl.CommaText; sl.free; end; function GetLVCheckedItemsSingleLn(lvcomp: TListView): string; var i: integer; begin for i := 0 to lvcomp.Items.count - 1 do begin if lvcomp.Items[i].checked then result := result + inttostr(i) + ';'; end; result := result; end; // Returns the caption of a listview item along with the caption of its subitems // (if any) function GetLVItemAsString(lv: TListView; li: TListItem; copytoclipboard: Boolean = false): string; var s, t: String; i: integer; begin t := emptystr; s := li.Caption; for i := 0 to li.SubItems.count - 1 do begin if i < lv.Columns.count - 1 then // ignore subitems that are not visible s := s + ' ' + li.SubItems[i]; end; t := t + s + sLineBreak; if copytoclipboard = true then Clipboard.AsText := t; end; function GetPercentage(const percent, Value: integer): Int64; var p: Real; begin p := ((percent / Value) * 100); result := Round(p); end; // Gets the path of special system folders // Usage example: GetSpecialFolderPath (CSIDL_PERSONAL, false); function GetSpecialFolderPath(const Folder: integer; const CanCreate: Boolean): string; var FilePath: array [0 .. 255] of char; begin SHGetSpecialFolderPath(0, @FilePath[0], Folder, CanCreate); result := FilePath; end; function GetWindowClassHandle(const Title: string): integer; begin result := FindWindow(pchar(Title), nil); end; function GetWindowState: integer; begin result := 2; case Application.MainForm.WindowState of WsMaximized: result := 0; WsMinimized: result := 1; WsNormal: result := 2; end; end; procedure LoadListviewStrings(listview: TListView; const filename: string); var sl, lineelements: TStringlist; i: integer; item: TListItem; begin Assert(Assigned(listview)); sl := TStringlist.Create; try sl.LoadFromFile(filename); lineelements := TStringlist.Create; try for i := 0 to sl.count - 1 do begin lineelements.Clear; SplitString(sl[i], #9, lineelements); if lineelements.count > 0 then begin item := listview.Items.Add; item.Caption := lineelements[0]; lineelements.Delete(0); item.SubItems.Assign(lineelements); end; end; finally lineelements.free; end; finally sl.free end; end; function MakeNotifyEvent(forObject: TObject; const procname: String) : TNotifyEvent; begin TMethod(result).data := forObject; TMethod(result).code := forObject.methodAddress(procname); end; procedure NilComponentMethods(Component: TComponent); var count, Size, i: integer; List: PPropList; PropInfo: PPropInfo; NilMethod: TMethod; begin count := GetPropList(Component.ClassInfo, tkAny, nil); Size := count * sizeof(Pointer); GetMem(List, Size); NilMethod.data := nil; NilMethod.code := nil; try count := GetPropList(Component.ClassInfo, tkAny, List); for i := 0 to count - 1 do begin PropInfo := List^[i]; if PropInfo^.PropType^.Kind in tkMethods then SetMethodProp(Component, string(PropInfo.Name), NilMethod); end; finally FreeMem(List); end; end; procedure QuickSortTreeViewItems(tv: ttreeview); begin tv.Items.BeginUpdate; tv.sorttype := stnone; tv.sorttype := sttext; tv.Items.EndUpdate; end; procedure SaveListviewStrings(listview: TListView; const filename: string); var sl: TStringlist; s: string; i, si: integer; item: TListItem; begin Assert(Assigned(listview)); sl := TStringlist.Create; try for i := 0 to listview.Items.count - 1 do begin item := listview.Items[i]; s := item.Caption; for si := 0 to item.SubItems.count - 1 do s := s + #9 + item.SubItems[si]; sl.Add(s); end; sl.SaveToFile(filename); finally sl.free end; end; procedure SaveMemStreamToStrings(Stream: TMemoryStream; List: TStrings); var p, q, r: pchar; begin p := Stream.Memory; q := p + Stream.Size - 1; r := p; while (p <> nil) and (p < q) do begin while (p < q) and (p^ <> #13) and (p^ <> #10) do Inc(p); List.Add(Copy(StrPas(r), 1, p - r)); if (p[0] = #13) and (p[1] = #10) then Inc(p, 2) else Inc(p); r := p; end; end; procedure ShowPopupMenu(PopupMenu: TPopupMenu; const AppHandle: integer); var p: TPoint; begin SetForegroundWindow(AppHandle); GetCursorPos(p); PopupMenu.Popup(p.x, p.y); PostMessage(AppHandle, WM_NULL, 0, 0); end; procedure SetNodeBoldState(Node: TTreeNode; const Value: Boolean); var TVItem: TTVItem; begin if not Assigned(Node) then Exit; with TVItem do begin mask := TVIF_STATE or TVIF_HANDLE; hItem := Node.ItemId; stateMask := TVIS_BOLD; if Value then state := TVIS_BOLD else state := 0; TreeView_SetItem(Node.Handle, TVItem); end; end; function TreeItemSearch(tv: ttreeview; const SearchItem: string): TTreeNode; var i: integer; sitem: string; begin result := nil; if (tv = nil) or (SearchItem = emptystr) then Exit; for i := 0 to tv.Items.count - 1 do begin sitem := tv.Items[i].text; if SearchItem = sitem then begin result := tv.Items[i]; Exit; end else result := nil; end; end; function ForceForegroundWindow(hwnd: THandle): Boolean; const SPI_GETFOREGROUNDLOCKTIMEOUT = $2000; SPI_SETFOREGROUNDLOCKTIMEOUT = $2001; var ForegroundThreadID, ThisThreadID, timeout: dword; begin if IsIconic(hwnd) then ShowWindow(hwnd, SW_RESTORE); if GetForegroundWindow = hwnd then result := true else begin // Windows 98/2000 doesn't want to foreground a window when some other // window has keyboard focus if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and (Win32MinorVersion > 0)))) then begin // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm // Converted to Delphi by Ray Lischner // Published in The Delphi Magazine 55, page 16 result := false; ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow, nil); ThisThreadID := GetWindowThreadProcessID(hwnd, nil); if AttachThreadInput(ThisThreadID, ForegroundThreadID, true) then begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); AttachThreadInput(ThisThreadID, ForegroundThreadID, false); result := (GetForegroundWindow = hwnd); end; if not result then begin // Code by Daniel P. Stasinski SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE); BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE); end; end else begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); end; result := (GetForegroundWindow = hwnd); end; end; // ------------------------------------------------------------------------// end.
unit RRManagerLicenseZoneListFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerObjects, StdCtrls, ComCtrls, RRManagerBaseGUI, RRManagerBaseObjects, ExtCtrls, ToolWin, RRManagerLicenseZoneInfoForm, RRManagerPersistentObjects, RRManagerDataPosters, ImgList, Menus; type TfrmLicenseZoneList = class(TFrame) gbxAll: TGroupBox; lwLicenseZone: TListView; pnlFilter: TPanel; cmbxLicenseZoneType: TComboBox; Label1: TLabel; Label2: TLabel; cmbxLicenseType: TComboBox; tlbrActions: TToolBar; imgList: TImageList; procedure lwLicenseZoneColumnClick(Sender: TObject; Column: TListColumn); procedure lwLicenseZoneChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure cmbxLicenseZoneTypeChange(Sender: TObject); procedure cmbxLicenseTypeChange(Sender: TObject); procedure lwLicenseZoneDblClick(Sender: TObject); procedure lwLicenseZoneAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure cmbxLicenseTypeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cmbxLicenseTypeDropDown(Sender: TObject); private { Private declarations } actnList: TBaseActionList; FLicenseZones: TOldLicenseZones; FFilterID: integer; FFilterValues: OleVariant; FOnChangeItem: TNotifyEvent; FZoneFilters, FZoneTypeFilters: TAdditionalFilters; FMenus: TMenuList; FFilterList: TStringList; procedure RefreshStructs; procedure SetLicenseZones(const Value: TOldLicenseZones); function GetDeselectAllAction: TBaseAction; function GetLicenseZoneLoadAction: TBaseAction; function GetMenus(AItemName: string): TMenu; function GetActiveLicenseZone: TOldLicenseZone; public { Public declarations } property Menus[AItemName: string]: TMenu read GetMenus; property LicenseZoneLoadAction: TBaseAction read GetLicenseZoneLoadAction; property DeselectAllAction: TBaseAction read GetDeselectAllAction; property LicenseZones: TOldLicenseZones read FLicenseZones write SetLicenseZones; property FilterID: integer read FFilterID write FFilterID; property FilterValues: OleVariant read FFilterValues write FFilterValues; property ActiveLivenseZone: TOldLicenseZone read GetActiveLicenseZone; property OnChangeItem: TNotifyEvent read FOnChangeItem write FOnChangeItem; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses RRManagerLoaderCommands, RRManagerHorizonInfoForm, RRManagerEditCommands, ActnList, RRManagerBasicLicenseZoneInfoForm, RRManagerChangeLicenseZoneFundForm, Facade, CommonIDObjectListForm, IDObjectBaseActions, RRManagerLicenseConditionTypeEditForm; {$R *.dfm} type TFilterList = class(TStringList) public constructor Create; end; TLicenseTypeAdditionalFilters = class(TAdditionalFilters) public constructor Create; override; end; TLicenseZoneTypeFilters = class(TAdditionalFilters) public constructor Create; override; end; TDeselectAllAction = class(TBaseAction) public function Execute: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseZoneLoadAction = class(TLicenseZoneBaseLoadAction) public function Execute: boolean; overload; override; function Execute(AFilter: string): boolean; override; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseZoneFrameActionList = class(TBaseActionList) private FFilter: string; FLicenseZone: TOldLicenseZone; procedure SetFilter(const Value: string); procedure SetLicenseZone(const Value: TOldLicenseZone); public property LicenseZone: TOldLicenseZone read FLicenseZone write SetLicenseZone; property Filter: string read FFilter write SetFilter; constructor Create(AOwner: TComponent); override; end; TLicenseZoneEditAction = class(TBaseAction) protected procedure DoAfterExecute(ABaseObject: TBaseObject); virtual; public function Execute(ABaseObject: TBaseObject): boolean; override; function Execute: boolean; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseZoneChangeStateAction = class(TLicenseZoneEditAction) public function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseZoneAddAction = class(TLicenseZoneEditAction) protected procedure DoAfterExecute(ABaseObject: TBaseObject); override; public function Execute: boolean; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TBasicLicenseZoneEditAction = class(TBaseAction) protected procedure DoAfterExecute(ABaseObject: TBaseObject); virtual; public function Execute(ABaseObject: TBaseObject): boolean; override; function Execute: boolean; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TBasicLicenseZoneAddAction = class(TBasicLicenseZoneEditAction) protected procedure DoAfterExecute(ABaseObject: TBaseObject); override; public function Execute: boolean; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseZoneDeleteAction = class(TBaseAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseKindShowDictAction = class(TBaseAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseConditionTypeShowDictAction = class(TBaseAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TLicenseConditionTypeEditAction = class(TIDObjectEditAction) public constructor Create(AOwner: TComponent); override; end; TLicenseConditionTypeAddAction = class(TIDObjectAddAction) public constructor Create(AOwner: TComponent); override; end; { TfrmLicenseZoneList } constructor TfrmLicenseZoneList.Create(AOwner: TComponent); var mn: TMenu; mi: TMenuItem; actn: TBaseAction; begin inherited; FFilterList := TFilterList.Create; actnList := TLicenseZoneFrameActionList.Create(Self); actnList.Images := imgList; FZoneFilters := TLicenseZoneTypeFilters.Create; FZoneFilters.MakeList(cmbxLicenseZoneType.Items); cmbxLicenseZoneType.ItemIndex := 0; FZoneTypeFilters := TLicenseTypeAdditionalFilters.Create; FZoneTypeFilters.MakeList(cmbxLicenseType.Items); cmbxLicenseType.ItemIndex := 0; FMenus := TMenuList.Create(imgList); mn := FMenus.AddMenu(TMainMenu, AOwner); mn.Name := 'mnLicenseActions'; mi := FMenus.AddMenuItem(mn, nil); mi.Caption := 'Лицензионные участки'; mi.GroupIndex := 4; actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseConditionTypeShowDictAction]; FMenus.AddMenuItem(0, mi, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseKindShowDictAction]; FMenus.AddMenuItem(0, mi, actn); FMenus.AddMenuItem(0, mi, nil); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneDeleteAction]; FMenus.AddMenuItem(0, mi, actn); FMenus.AddMenuItem(0, mi, nil); AddToolButton(tlbrActions, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneChangeStateAction]; FMenus.AddMenuItem(0, mi, actn); FMenus.AddMenuItem(0, mi, nil); AddToolButton(tlbrActions, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TBasicLicenseZoneAddAction]; FMenus.AddMenuItem(0, mi, actn); AddToolButton(tlbrActions, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneAddAction]; FMenus.AddMenuItem(0, mi, actn); AddToolButton(tlbrActions, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TBasicLicenseZoneEditAction]; FMenus.AddMenuItem(0, mi, actn); AddToolButton(tlbrActions, actn); actn := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneEditAction]; FMenus.AddMenuItem(0, mi, actn); FMenus.AddMenuItem(0, mi, nil); AddToolButton(tlbrActions, actn); mn := FMenus.AddMenu(TPopupMenu, AOwner); mn.Name := 'mnLicensePopup'; FMenus.AddMenuItem(mn, (actnList as TLicenseZoneFrameActionList).ActionByClassType[TDeselectAllAction]); FMenus.AddMenuItem(mn, nil); FMenus.AddMenuItem(mn, (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneAddAction]); FMenus.AddMenuItem(mn, (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneEditAction]); end; function TfrmLicenseZoneList.GetDeselectAllAction: TBaseAction; begin Result := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TDeselectAllAction]; end; function TfrmLicenseZoneList.GetLicenseZoneLoadAction: TBaseAction; begin Result := (actnList as TLicenseZoneFrameActionList).ActionByClassType[TLicenseZoneLoadAction]; end; procedure TfrmLicenseZoneList.SetLicenseZones(const Value: TOldLicenseZones); var i: integer; li: TListItem; begin if FLicenseZones <> Value then begin FLicenseZones := Value; lwLicenseZone.Items.Clear; for i := 0 to FLicenseZones.Count - 1 do begin li := lwLicenseZone.Items.Add; li.Data := FLicenseZones.Items[i]; li.Caption := FLicenseZones.Items[i].LicenseZoneName; li.SubItems.Add(FLicenseZones.Items[i].LicenseZoneNum); end; end; end; procedure TfrmLicenseZoneList.RefreshStructs; begin end; destructor TfrmLicenseZoneList.Destroy; begin FFilterList.Free; FZoneFilters.Free; FZoneTypeFilters.Free; FMenus.Free; inherited; end; function TfrmLicenseZoneList.GetMenus(AItemName: string): TMenu; var i: integer; mns: TMenuList; begin Result := nil; mns := FMenus as TMenuList; for i := 0 to mns.Count - 1 do if mns.Items[i].Name = AItemName then begin Result := mns.Items[i] as TMenu; break; end; end; function TfrmLicenseZoneList.GetActiveLicenseZone: TOldLicenseZone; begin if Assigned(lwLicenseZone.Selected) then Result := TOldLicenseZone(lwLicenseZone.Selected.Data) else Result := nil; end; { TDeselectAllAction } constructor TDeselectAllAction.Create(AOwner: TComponent); begin inherited; Caption := 'Снять выделение'; Visible := true; CanUndo := false; end; function TDeselectAllAction.Execute: boolean; begin Result := true; with ActionList.Owner as TfrmLicenseZoneList do lwLicenseZone.Selected := nil; end; { TLicenseZoneFrameActionList } constructor TLicenseZoneFrameActionList.Create(AOwner: TComponent); var actn: TBaseAction; begin inherited; actn := TDeselectAllAction.Create(Self); actn.ActionList := Self; actn := TLicenseZoneLoadAction.Create(Self); actn.ActionList := Self; actn := TLicenseZoneAddAction.Create(Self); actn.ActionList := Self; actn := TBasicLicenseZoneAddAction.Create(Self); actn.ActionList := Self; actn := TLicenseZoneEditAction.Create(Self); actn.ActionList := Self; actn := TBasicLicenseZoneEditAction.Create(Self); actn.ActionList := Self; actn := TLicenseZoneChangeStateAction.Create(Self); actn.ActionList := Self; actn := TLicenseZoneDeleteAction.Create(Self); actn.ActionList := Self; end; procedure TLicenseZoneFrameActionList.SetFilter(const Value: string); begin FFilter := Value; end; procedure TLicenseZoneFrameActionList.SetLicenseZone( const Value: TOldLicenseZone); begin FLicenseZone := Value; end; { TLicenseZoneLoadAction } constructor TLicenseZoneLoadAction.Create(AOwner: TComponent); begin inherited Create(AOwner); CanUndo := false; Visible := false; end; function TLicenseZoneLoadAction.Execute: boolean; begin Result := Execute((ActionList as TLicenseZoneFrameActionList).Filter); end; function TLicenseZoneLoadAction.Execute(AFilter: string): boolean; var li: TListItem; i: integer; lz: TOldLicenseZone; begin (ActionList as TLicenseZoneFrameActionList).Filter := AFilter; Result := false; LastCollection := (ActionList.Owner as TfrmLicenseZoneList).LicenseZones; LastCollection.NeedsUpdate := AFilter <> LastFilter; LastFilter := AFilter; if LastCollection.NeedsUpdate then with ActionList.Owner as TfrmLicenseZoneList do begin lwLicenseZone.Items.BeginUpdate; lwLicenseZone.Items.Clear; Result := inherited Execute(AFilter); if Result then begin // загружаем в интерфейс if Assigned(LastCollection) then begin for i := 0 to LastCollection.Count - 1 do begin li := lwLicenseZone.Items.Add; lz := LastCollection.Items[i] as TOldLicenseZone; if lz.LicenseZoneStateID > 0 then li.ImageIndex := lz.LicenseZoneStateID + 1 else li.ImageIndex := -1; li.Caption := lz.LicenseZoneName; li.SubItems.Add(lz.LicenseZoneNum); li.SubItems.Add(lz.License.LicenseTypeShortName); li.SubItems.Add(lz.License.OwnerOrganizationName); li.Data := LastCollection.Items[i]; end; end end; lwLicenseZone.Items.EndUpdate; end; end; function TLicenseZoneLoadAction.Execute(ABaseObject: TBaseObject): boolean; begin Result := true; if ABaseObject is TOldLicenseZone then Result := Execute('License_Zone_ID = ' + IntToStr(ABaseObject.ID)); end; procedure TfrmLicenseZoneList.lwLicenseZoneColumnClick(Sender: TObject; Column: TListColumn); var sFilterSQL: string; begin sFilterSQL := (LicenseZoneLoadAction as TLicenseZoneLoadAction).LastFilter; if Pos('order by', sFilterSQL) > 0 then sFilterSQL := Copy(sFilterSQL, 1, Pos('order by', sFilterSQL) - 1); if sFilterSQL <> '' then LicenseZoneLoadAction.Execute(sFilterSQL + ' order by ' + FFilterList.Strings[Column.Index]) else LicenseZoneLoadAction.Execute(''); end; procedure TfrmLicenseZoneList.lwLicenseZoneChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if Assigned(Item) and (not Item.Deleting) then begin (actnList as TLicenseZoneFrameActionList).LicenseZone := TOldLicenseZone(Item.Data); if Assigned(FOnChangeItem) then FOnChangeItem(TObject(Item.Data)); end; end; procedure TfrmLicenseZoneList.cmbxLicenseZoneTypeChange(Sender: TObject); var sFilter, sAddedFilter, sLastFilter, sOrder: string; iPos: integer; begin sFilter := (actnList as TLicenseZoneFrameActionList).Filter; sLastFilter := sFilter; sAddedFilter := TAdditionalFilter(cmbxLicenseZoneType.Items.Objects[cmbxLicenseZoneType.ItemIndex]).Query; if (trim(sFilter) <> '') and (trim(sAddedFilter) <> '') then if pos('order by', sFilter) = 0 then sFilter := sFilter + ' and ' + '(' + sAddedFilter + ')' else begin iPos := pos('order by', sFilter) ; sOrder := trim(Copy(sFilter, iPos, Length(sFilter))); sFilter := Copy(sFilter, 1, iPos - 1); sFilter := sFilter + ' and ' + '(' + sAddedFilter + ')'; sFilter := sFilter + ' ' + sOrder; end else if trim(sFilter) = '' then sFilter := sAddedFilter; DeselectAllAction.Execute; LicenseZoneLoadAction.Execute(sFilter); (actnList as TLicenseZoneFrameActionList).Filter := sLastFilter; cmbxLicenseType.ItemIndex := 0; if Assigned(FOnChangeItem) then FOnChangeItem(nil); end; procedure TfrmLicenseZoneList.cmbxLicenseTypeChange(Sender: TObject); var sFilter, sAddedFilter, sLastFilter, sOrder: string; iPos: integer; begin //cmbxLicenseType.Style := csOwnerDrawFixed; sFilter := (actnList as TLicenseZoneFrameActionList).Filter; sLastFilter := sFilter; sAddedFilter := TAdditionalFilter(cmbxLicenseType.Items.Objects[cmbxLicenseType.ItemIndex]).Query; if (trim(sFilter) <> '') and (trim(sAddedFilter) <> '') then if pos('order by', sFilter) = 0 then sFilter := sFilter + ' and ' + '(' + sAddedFilter + ')' else begin iPos := pos('order by', sFilter) ; sOrder := trim(Copy(sFilter, iPos, Length(sFilter))); sFilter := Copy(sFilter, 1, iPos - 1); sFilter := sFilter + ' and ' + '(' + sAddedFilter + ')'; sFilter := sFilter + ' ' + sOrder; end else if trim(sFilter) = '' then sFilter := sAddedFilter; DeselectAllAction.Execute; LicenseZoneLoadAction.Execute(sFilter); (actnList as TLicenseZoneFrameActionList).Filter := sLastFilter; cmbxLicenseZoneType.ItemIndex := 0; if Assigned(FOnChangeItem) then FOnChangeItem(nil); end; { TLicenseTypeAdditionalFilters } constructor TLicenseTypeAdditionalFilters.Create; begin inherited; Add('<нет>', '', 0); Add('НР (поисковые и разведочные работы на нефть, газ, конденсат)', 'LICENSE_TYPE_ID = 1', 0); Add('НЭ (эксплуатационные работы на нефть, газ, конденсат)', 'LICENSE_TYPE_ID = 2', 0); Add('НП (геологическое изучение)', 'LICENSE_TYPE_ID = 3', 0); end; { TLicenseZoneTypeFilters } constructor TLicenseZoneTypeFilters.Create; begin inherited; Add('<нет>', '', 0); Add('действующий', 'LICENSE_ZONE_STATE_ID = 1', 0); Add('перспективный', 'LICENSE_ZONE_STATE_ID = 2', 0); Add('выведенный', 'LICENSE_ZONE_STATE_ID = 3', 0); end; { TLicenseZoneAddAction } constructor TLicenseZoneAddAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Caption := 'Редактировать лицензионный участок'; ImageIndex := 0; end; procedure TLicenseZoneAddAction.DoAfterExecute(ABaseObject: TBaseObject); var lv: TListView; li: TListItem; lz: TOldLicenseZone; begin lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; li := lv.Items.Add; lz := ABaseObject as TOldLicenseZone; li.Caption := lz.LicenseZoneName; li.SubItems.Add(lz.LicenseZoneNum); li.Data := ABaseObject; end; function TLicenseZoneAddAction.Execute: boolean; begin Result := inherited Execute(nil); end; function TLicenseZoneAddAction.Update: boolean; begin Result := inherited Update; Enabled := Result; end; { TLicenseZoneEditAction } constructor TLicenseZoneEditAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Visible := true; Caption := 'Редактировать лицензионный участок'; ImageIndex := 2; end; procedure TLicenseZoneEditAction.DoAfterExecute(ABaseObject: TBaseObject); var lv: TListView; begin lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; if TObject(lv.Selected.Data) is TOldLicenseZone then begin lv.Selected.SubItems.Clear; lv.Selected.Caption := (ABaseObject as TOldLicenseZone).LicenseZoneName; lv.Selected.SubItems.Add((TObject(lv.Selected.Data) as TOldLicenseZone).LicenseZoneNum); lv.Selected.SubItems.Add((TObject(lv.Selected.Data) as TOldLicenseZone).License.LicenseTypeShortName); lv.Selected.ImageIndex := (TObject(lv.Selected.Data) as TOldLicenseZone).LicenseZoneStateID + 1; lv.Selected.MakeVisible(false); end; end; function TLicenseZoneEditAction.Execute: boolean; begin if Assigned((ActionList as TLicenseZoneFrameActionList).LicenseZone) then Result := Execute((ActionList as TLicenseZoneFrameActionList).LicenseZone) else Result := false; end; function TLicenseZoneEditAction.Execute(ABaseObject: TBaseObject): boolean; var actn: TLicenseZoneBaseSaveAction; qResult: integer; begin Result := true; if not Assigned(frmLicenseZoneInfo) then frmLicenseZoneInfo := TfrmLicenseZoneInfo.Create(Self); frmLicenseZoneInfo.EditingObject := ABaseObject; frmLicenseZoneInfo.dlg.ActiveFrameIndex := 0; if Assigned(ABaseObject) and ((ABaseObject as TOldLicenseZone).LicenseZoneStateID = 2) then qResult := Application.MessageBox(PChar('Вы действительно хотите перевести участок из перспективных в действующие?'), PChar('Вопрос'), MB_YESNO) else qResult := ID_YES; if (qResult = ID_Yes) and (frmLicenseZoneInfo.ShowModal = mrOK) then begin frmLicenseZoneInfo.Save; ABaseObject := (frmLicenseZoneInfo.Dlg.Frames[0] as TbaseFrame).EditingObject; actn := TLicenseZoneBaseSaveAction.Create(nil); actn.Execute(ABaseObject); actn.Free; // обновляем представление DoAfterExecute(ABaseObject); end; end; function TLicenseZoneEditAction.Update: boolean; var lv: TListView; begin inherited Update; lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; Result := (Assigned(lv.Selected) and (TObject(lv.Selected.Data) is TOldLicenseZone)); Enabled := Result; end; { TLicenseZoneDeleteAction } constructor TLicenseZoneDeleteAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Caption := 'Удалить лицензионный участок'; ImageIndex := 4; end; function TLicenseZoneDeleteAction.Execute: boolean; begin Result := Execute((ActionList as TLicenseZoneFrameActionList).LicenseZone) end; function TLicenseZoneDeleteAction.Execute( ABaseObject: TBaseObject): boolean; var dp: TDataPoster; begin Result := true; if MessageBox(0, PChar('Вы действительно хотите удалить лицензионный участок ' + #13#10 + ABaseObject.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false) + '?'), 'Вопрос', MB_YESNO+MB_APPLMODAL+MB_DEFBUTTON2+MB_ICONQUESTION) = ID_YES then begin dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TLicenseZoneDataPoster]; dp.DeleteFromDB(ABaseObject); (actionList as TLicenseZoneFrameActionList).LicenseZone := nil; (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone.Selected.Delete; end; end; function TLicenseZoneDeleteAction.Update: boolean; var lv: TListView; begin inherited Update; lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; Result := Assigned(lv.Selected) and (TObject(lv.Selected.Data) is TOldLicenseZone); Enabled := Result; end; { TBasicLicenseZoneAddAction } constructor TBasicLicenseZoneAddAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Visible := true; Caption := 'Добавить перспективный лицензионный участок'; ImageIndex := 1; end; procedure TBasicLicenseZoneAddAction.DoAfterExecute( ABaseObject: TBaseObject); var lv: TListView; li: TListItem; begin lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; if (not Assigned(lv.Selected)) or ((TObject(lv.Selected.Data) is TOldLicenseZone) and ((TBaseObject(lv.Selected.Data) as TOldLicenseZone).ID <> ABaseObject.ID)) then begin li := lv.Items.Add; li.Selected := true; li.Data := ABaseObject; li.MakeVisible(false); end; if (TObject(lv.Selected.Data) is TOldLicenseZone) then begin lv.Selected.SubItems.Clear; lv.Selected.Caption := (ABaseObject as TOldLicenseZone).LicenseZoneName; lv.Selected.SubItems.Add((TObject(lv.Selected.Data) as TOldLicenseZone).LicenseZoneNum); end; end; function TBasicLicenseZoneAddAction.Execute: boolean; begin Result := inherited Execute(nil); end; function TBasicLicenseZoneAddAction.Update: boolean; begin Result := inherited Update; Enabled := Result; end; { TBasicLicenseZoneEditAction } constructor TBasicLicenseZoneEditAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Visible := true; Caption := 'Редактировать перспективный лицензионный участок'; ImageIndex := 3; end; procedure TBasicLicenseZoneEditAction.DoAfterExecute( ABaseObject: TBaseObject); var lv: TListView; begin lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; if TObject(lv.Selected.Data) is TOldLicenseZone then begin lv.Selected.SubItems.Clear; lv.Selected.Caption := (ABaseObject as TOldLicenseZone).LicenseZoneName; lv.Selected.SubItems.Add((TObject(lv.Selected.Data) as TOldLicenseZone).LicenseZoneNum); lv.Selected.MakeVisible(false); end; end; function TBasicLicenseZoneEditAction.Execute( ABaseObject: TBaseObject): boolean; var actn: TLicenseZoneBaseSaveAction; begin Result := true; if not Assigned(frmBasicLicenseZone) then frmBasicLicenseZone := TfrmBasicLicenseZone.Create(Self); frmBasicLicenseZone.EditingObject := ABaseObject; frmBasicLicenseZone.dlg.ActiveFrameIndex := 0; if frmBasicLicenseZone.ShowModal = mrOK then begin frmBasicLicenseZone.Save; ABaseObject := (frmBasicLicenseZone.Dlg.Frames[0] as TbaseFrame).EditingObject; actn := TLicenseZoneBaseSaveAction.Create(nil); actn.Execute(ABaseObject); actn.Free; // обновляем представление DoAfterExecute(ABaseObject); end; end; function TBasicLicenseZoneEditAction.Execute: boolean; begin if Assigned((ActionList as TLicenseZoneFrameActionList).LicenseZone) then Result := Execute((ActionList as TLicenseZoneFrameActionList).LicenseZone) else Result := false; end; function TBasicLicenseZoneEditAction.Update: boolean; var lv: TListView; begin inherited Update; lv := (ActionList.Owner as TfrmLicenseZoneList).lwLicenseZone; Result := (Assigned(lv.Selected) and (TObject(lv.Selected.Data) is TOldLicenseZone) // редактируем редактором перспективных участков только перспективные and (TOldLicenseZone(lv.Selected.Data).LicenseZoneStateID = 2)); Enabled := Result; end; { TFilterList } constructor TFilterList.Create; begin Add('vch_License_Zone_Name'); Add('vch_License_Num'); Add('vch_lic_type_short_name'); Add('vch_org_full_name'); end; procedure TfrmLicenseZoneList.lwLicenseZoneDblClick(Sender: TObject); begin if Assigned(ActiveLivenseZone) then if ActiveLivenseZone.LicenseZoneStateID = 1 then actnList.ActionByClassType[TLicenseZoneEditAction].Execute else actnList.ActionByClassType[TBasicLicenseZoneEditAction].Execute; end; procedure TfrmLicenseZoneList.lwLicenseZoneAdvancedCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); begin if not Item.Deleting then case TOldLicenseZone(Item.Data).License.LicenseTypeID of 1: lwLicenseZone.Canvas.Font.Color := clBlack; 2: lwLicenseZone.Canvas.Font.Color := clPurple; 3: lwLicenseZone.Canvas.Font.Color := clGreen; end; end; procedure TfrmLicenseZoneList.cmbxLicenseTypeDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin if cmbxLicenseType.ItemIndex > -1 then begin case Index of 1: cmbxLicenseType.Canvas.Font.Color := clBlack;//cmbxLicenseType.Canvas.Brush.Color := clBlack; // 2: cmbxLicenseType.Canvas.Font.Color := clPurple;//cmbxLicenseType.Canvas.Brush.Color := clPurple;// 3: cmbxLicenseType.Canvas.Font.Color := clGreen;//cmbxLicenseType.Canvas.Brush.Color := clGreen;// end; //cmbxLicenseType.Canvas.Brush.Color := clWhite; //cmbxLicenseType.Canvas.FillRect(Rect); cmbxLicenseType.Canvas.TextOut(Rect.Left + 1, Rect.Top + 1, cmbxLicenseType.Items[cmbxLicenseType.ItemIndex]); end; end; procedure TfrmLicenseZoneList.cmbxLicenseTypeDropDown(Sender: TObject); var i: integer; begin //cmbxLicenseType.Style := csDropDownList; { TODO : Криво отрисовывается - не обновляется при выпадении } { for i := 0 to cmbxLicenseType.Items.Count - 1 do begin cmbxLicenseType.ItemIndex := i; cmbxLicenseTypeDrawItem(cmbxLicenseType, i, Rect(0, 0, cmbxLicenseType.Width, cmbxLicenseType.ItemHeight * (i + 1)), [odSelected]); end;} end; { TLicenseZoneChangeStateAction } constructor TLicenseZoneChangeStateAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Visible := true; Caption := 'Сменить статус лицензионного участка'; ImageIndex := 5; end; function TLicenseZoneChangeStateAction.Execute( ABaseObject: TBaseObject): boolean; var actn: TBaseAction; begin Result := true; if not Assigned(frmChangeState) then frmChangeState := TfrmChangeState.Create(Self); frmChangeState.EditingObject := ABaseObject; frmChangeState.dlg.ActiveFrameIndex := 0; if (frmChangeState.ShowModal = mrOK) then begin frmChangeState.Save; ABaseObject := (frmChangeState.Dlg.Frames[0] as TbaseFrame).EditingObject; actn := TLicenseZoneBaseSaveAction.Create(nil); actn.Execute(ABaseObject); actn.Free; // обновляем представление DoAfterExecute(ABaseObject); end; end; { TLicenseKindShowDictAction } constructor TLicenseKindShowDictAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Caption := 'Справочник видов условий лицензионного соглашения'; ImageIndex := 6; end; function TLicenseKindShowDictAction.Execute: boolean; begin Result := Execute(nil); end; function TLicenseKindShowDictAction.Execute( ABaseObject: TBaseObject): boolean; begin if not Assigned(frmIDObjectList) then frmIDObjectList := TfrmIDObjectList.Create(Self); frmIDObjectList.IDObjects := (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionKinds; frmIDObjectList.Caption := 'Вид условия лицензионного соглашения'; frmIDObjectList.AddActionClass := TIDObjectAddAction; frmIDObjectList.EditActionClass := TIDObjectEditAction; frmIDObjectList.ShowShortName := false; frmIDObjectList.ShowModal; end; function TLicenseKindShowDictAction.Update: boolean; begin Result := true; end; { TLicenseConditionTypeShowDictAction } constructor TLicenseConditionTypeShowDictAction.Create(AOwner: TComponent); begin inherited; CanUndo := false; Caption := 'Справочник видов условий лицензионного соглашения'; ImageIndex := 6; end; function TLicenseConditionTypeShowDictAction.Execute: boolean; begin Result := Execute(nil); end; function TLicenseConditionTypeShowDictAction.Execute( ABaseObject: TBaseObject): boolean; begin if not Assigned(frmIDObjectList) then frmIDObjectList := TfrmIDObjectList.Create(Self); frmIDObjectList.IDObjects := (TMainFacade.GetInstance as TMainFacade).AllLicenseConditionTypes; frmIDObjectList.Caption := 'Тип условия лицензионного соглашения'; frmIDObjectList.AddActionClass := TLicenseConditionTypeAddAction; frmIDObjectList.EditActionClass := TLicenseConditionTypeEditAction; frmIDObjectList.ShowShortName := false; frmIDObjectList.ShowModal; end; function TLicenseConditionTypeShowDictAction.Update: boolean; begin Result := true; end; { TLicenseConditionKindEditAction } constructor TLicenseConditionTypeEditAction.Create(AOwner: TComponent); begin inherited; frmIDObjectEditClass := TfrmLicenseConditionTypeEdit; end; { TLicenseConditionKindAddAction } constructor TLicenseConditionTypeAddAction.Create(AOwner: TComponent); begin inherited; frmIDObjectEditClass := TfrmLicenseConditionTypeEdit; end; end.
{ Subroutine RAY_CLOSE * * Close this use of the ray tracer library. All resources will be * deallocated. RAY_INIT must be called before the ray tracer library can be * used again. } module ray_close; define ray_close; %include 'ray2.ins.pas'; procedure ray_close; {close use of ray tracer, release resources} val_param; begin util_mem_context_del (ray_mem_p); {deallocate all ray library dynamic memory} end;
unit bip0122uritestcase; {$ifdef fpc}{$mode delphi}{$endif}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, Generics.Collections, bip0122uriparser; type TBIP0122URITestCase = class(TTestCase) published procedure TestTryParse; end; implementation procedure TBIP0122URITestCase.TestTryParse; var InputUri: string; ExpectedUri: TBIP0122URI; ChainExpectedUri: TBIP0122URI; AddressExpectedUri: TBIP0122URI; BlockExpectedUri: TBIP0122URI; ActualUri: TBIP0122URI; TestCases: TDictionary<string, TBIP0122URI>; TestCaseUri: TBIP0122URI; Key: string; begin TestCases := TDictionary<string, TBIP0122URI>.Create; ExpectedUri := TBIP0122URI.Create; ExpectedUri.Chain := ''; ExpectedUri.UriType := 'tx'; ExpectedUri.Argument := 'b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da'; ChainExpectedUri := TBIP0122URI.Create; ChainExpectedUri.Chain := '000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943'; ChainExpectedUri.UriType := 'tx'; ChainExpectedUri.Argument := '3b95a766d7a99b87188d6875c8484cb2b310b78459b7816d4dfc3f0f7e04281a'; AddressExpectedUri := TBIP0122URI.Create; AddressExpectedUri.Chain := ''; AddressExpectedUri.UriType := 'address'; AddressExpectedUri.Argument := '16EW6Rv9P9AxFDBrZV816dD4sj1EAYUX3f'; BlockExpectedUri := TBIP0122URI.Create; BlockExpectedUri.Chain := ''; BlockExpectedUri.UriType := 'block'; BlockExpectedUri.Argument := '00000000000000000119af5bcae2926df54ae262e9071a94a99c913cc217cc72'; TestCases.Add('blockchain:/tx/b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da', ExpectedUri); // A transaction on Bitcoin main net TestCases.Add('BLOCKCHAIN:/tx/b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da', ExpectedUri); // Protocol is case insensitive TestCases.Add('blockchain:/TX/b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da', ExpectedUri); // UriType is case insensitive TestCases.Add('blockchain://000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943/tx/3b95a766d7a99b87188d6875c8484cb2b310b78459b7816d4dfc3f0f7e04281a', ChainExpectedUri); // A transaction on Bitcoin test net TestCases.Add('blockchain:/address/16EW6Rv9P9AxFDBrZV816dD4sj1EAYUX3f', AddressExpectedUri); // An address on Bitcoin main net TestCases.Add('blockchain:/aDdReSs/16EW6Rv9P9AxFDBrZV816dD4sj1EAYUX3f', AddressExpectedUri); // An address on Bitcoin main net, case insensitive TestCases.Add('blockchain:/block/00000000000000000119af5bcae2926df54ae262e9071a94a99c913cc217cc72', BlockExpectedUri); // A block on Bitcoin main net TestCases.Add('bitcoin:/tx/b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da', nil); // Fails, does not start with blockchain:/ TestCases.Add('blockchain:/unknown/b462ae6eb8bdae2e060239a2a3ea5d9c3e0f9ef34d9717beb2dcf0ed42cee7da', nil); // Fails, doesn't contain a known UriType for Key in TestCases.Keys do begin InputUri := Key; TestCaseUri := TestCases[Key]; if TBIP0122URI.TryParse(InputUri, ActualUri) then begin AssertEquals('Chain for ' + Key + ': ', TestCaseUri.Chain, ActualUri.Chain); AssertEquals('UriType for ' + Key + ': ', TestCaseUri.UriType, ActualUri.UriType); AssertEquals('Argument for ' + Key + ': ', TestCaseUri.Argument, ActualUri.Argument); end else if TestCaseUri = nil then begin AssertTrue(ActualUri = nil); end else Fail('Test case for ' + InputUri + ' failed'); end; end; initialization RegisterTest(TBIP0122URITestCase); end.
{$A+} { Align Data Switch } {$B-} { Boolean Evaluation Switch } {$D-} { Debug Information Switch } {$E-} { Emulation Switch - this doesn't affect a unit only a program } {$F-} { Force Far Calls Switch } {$G+} { Generate 80286 Code Switch } {$I-} { Input/Output-Checking Switch } {$I Defines.INC} { This file is used to define some conditionals according } { with user preferences. } {$L-} { Local Symbol Information Switch } {$N+} { Numeric Coprocessor Switch } {$Q-} { Overflow Checking Switch } {$R-} { Range-Checking Switch } {$S-} { Stack-Overflow Checking Switch } {$V-} { Var-String Checking Switch } {$Y+} { Symbol Reference Information Switch - just afect the Unit size, and } { it's very good when you run BP, because you can go directly to the } { line where the source begins! Study, to know more!!! } Program Vesa_Demo_2; { Testing Modes Colors Demo } Uses Crt, Math, Screen, Vesa, Keyboard; Var Mode : Word; PROCEDURE TestingBanks; Var A : Byte; ch : word; Begin FOR A := 0 TO VesaInfo.TotalMemory DO Begin SetBank(A); Fillchar(Mem[VesaMode.SegA:0000], $FFFF, 15+A*2); End; Repeat Ch := getscancodew; Until ch=kb_esc; CloseVesaMode; End; PROCEDURE Show256Colors; Var X,Y : Integer; Ch : Word; Begin clrscr; writeln('Testing VESA mode 640x480 256 colors'); writeln('Press a key ...'); repeat until keypressed; mode := $101; { 101 640*480 8 bits } { 103 800*600 8 bits } { 105 1024*768 8 bits } SetMode(mode); delay(2000); for x:=0 to 255 do for y:=0 to 255 do Drawpixel(x,y,x); CloseVesaMode; system.writeln('Mode VESA 101h OK : Press Esc key to quit ...'); repeat ch := getscancodew; until ch=kb_esc; End; var ch : word; Begin Mode := $110; Setmode(Mode); TestingBanks; Show256Colors; End.
unit unitPEModuleRW; interface uses Windows, Classes, SysUtils, unitPEFile; type TImportFunction = class private fFixups : TList; fFunctionName : string; public constructor Create (const AFunctionName : string); destructor Destroy; override; end; TImportDLL = class private fImportFunctions : TStrings; fDLLname : string; public constructor Create (const ADLLName : string); destructor Destroy; override; end; TImportSection = class (TImageSection) private fImportDLLS : TStrings; public destructor Destroy; override; procedure Initialize; override; procedure Fixup; override; end; TRelocSection = class (TImageSection) private fRelocs : TList; public destructor Destroy; override; procedure Initialize; override; procedure Fixup; override; end; TFixup = record OffsetInCode : DWORD; Section : TImageSection; end; PFixup = ^TFixup; TPEModuleRW = class (TPEResourceModule) private fFixups : array of TFixup; fFixupsCount : DWORD; fCodeSectionIdx : Integer; fDataSectionIdx : Integer; fUDataSectionIdx : Integer; protected procedure Decode (memory : pointer; exeSize : Integer); override; procedure AddFixup (ACodeOffset : DWORD; ASection : TImageSection); procedure AddReloc (ACodeOffset : DWORD); procedure ApplyGlobalFixups; override; public constructor Create; procedure Initialize (IsExe, IsGUI : boolean); function GetCodeSection : TImageSection; function GetDataSection : TImageSection; function GetUDataSection : TImageSection; function Emit (section : TImageSection; data : array of byte) : DWORD; overload; function Emit (section : TImageSection; const data : string) : DWORD; overload; procedure EmitRelocPtr (section : TImageSection; ptr : DWORD; destSection : TImageSection); procedure EmitAPICall (section : TImageSection; const dllName, functionName : string); function AddOrGetImportFunction (const dllName, functionName : string) : TImportFunction; end; implementation uses DateUtils; const DOSStubInit : array [0..255] of byte = ($4D,$5A,$50,$00,$02,$00,$00,$00,$04,$00,$0F,$00,$FF,$FF,$00,$00, // MZP............. $B8,$00,$00,$00,$00,$00,$00,$00,$40,$00,$1A,$00,$00,$00,$00,$00, // ........@....... $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00, // ................ $BA,$10,$00,$0E,$1F,$B4,$09,$CD,$21,$B8,$01,$4C,$CD,$21,$90,$90, // ........!..L.!.. $54,$68,$69,$73,$20,$70,$72,$6F,$67,$72,$61,$6D,$20,$6D,$75,$73, // This program mus $74,$20,$62,$65,$20,$72,$75,$6E,$20,$75,$6E,$64,$65,$72,$20,$57, // t be run under W $69,$6E,$33,$32,$0D,$0A,$24,$37,$00,$00,$00,$00,$00,$00,$00,$00, // in32..$7........ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, // ................ $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); // ................ EXECharacteristics : array [boolean] of DWORD = (IMAGE_FILE_DLL, 0); DefaultImageBase : array [boolean] of DWORD = ($10000000, $400000); Subsystems : array [boolean, boolean] of DWORD = ((IMAGE_SUBSYSTEM_NATIVE, IMAGE_SUBSYSTEM_NATIVE), (IMAGE_SUBSYSTEM_WINDOWS_CUI, IMAGE_SUBSYSTEM_WINDOWS_GUI)); { TPEModuleRW } function TPEModuleRW.Emit(section: TImageSection; data: array of byte): DWORD; begin result := section.RawData.Position; section.RawData.Write(data [0], length (data)) end; procedure TPEModuleRW.AddFixup(ACodeOffset: DWORD; ASection: TImageSection); var fixupLen : DWORD; begin fixupLen := Length (fFixups); if fixupLen = fFixupsCount then SetLength (fFixups, fixupLen + 1024); with fFixups [fFixupsCount] do begin OffsetInCode := ACodeOffset; Section := ASection; end; Inc (fFixupsCount); AddReloc (ACodeOffset) end; function TPEModuleRW.AddOrGetImportFunction(const dllName, functionName: string): TImportFunction; var isection : TImportSection; dll : TImportDLL; func : TImportFunction; i : Integer; begin result := Nil; iSection := GetSectionByName ('.idata') as TImportSection; if iSection = Nil then Exit; i := iSection.fImportDLLS.IndexOf(dllName); if i >= 0 then dll := TImportDll (iSection.fImportDlls.Objects [i]) else begin dll := TImportDll.Create(dllName); iSection.fImportDLLS.AddObject(dllName, dll) end; i := dll.fImportFunctions.IndexOf(functionName); if i >= 0 then func := TImportFunction (dll.fImportFunctions.Objects [i]) else begin func := TImportFunction.Create(functionName); dll.fImportFunctions.AddObject(functionName, func) end; result := func end; procedure TPEModuleRW.AddReloc(ACodeOffset: DWORD); var rSection : TRelocSection; begin rSection := GetSectionByName ('.reloc') as TRelocSection; if rSection = Nil then Exit; rSection.fRelocs.Add (Pointer (ACodeOffset)); end; procedure TPEModuleRW.ApplyGlobalFixups; var i : Integer; codeSection : TImageSection; fixup : PFixup; fcs : PDWORD; begin if fFixupsCount = 0 then Exit; codeSection := GetCodeSection; for i := 0 to fFixupsCount - 1 do begin fixup := @fFixups [i]; fcs := PDWORD (PByte (codeSection.RawData.Memory) + fixup^.OffsetInCode); Inc (fcs^, fixup^.Section.SectionHeader.VirtualAddress + fOptionalHeader.ImageBase); end end; constructor TPEModuleRW.Create; begin inherited; fCodeSectionIDx := -1; fDataSectionIdx := -1; end; procedure TPEModuleRW.Decode(memory: pointer; exeSize: Integer); const IDATA = IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE; UDATA = IMAGE_SCN_CNT_UNINITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE; var s : TImageSection; i : Integer; begin inherited; for i := 0 to ImageSectionCount - 1 do begin s := ImageSection [i]; if (fCodeSectionIdx = -1) and ((s.SectionHeader.Characteristics and IMAGE_SCN_CNT_CODE) = IMAGE_SCN_CNT_CODE) then fCodeSectionIdx := i; if (fDataSectionIdx = -1) and ((s.SectionHeader.Characteristics and IDATA) = IDATA) then fDataSectionIdx := i; if (fUDataSectionIdx = -1) and ((s.SectionHeader.Characteristics and UDATA) = UDATA) then fUDataSectionIdx := i end end; function TPEModuleRW.Emit(section: TImageSection; const data: string): DWORD; begin result := section.RawData.Position; section.RawData.Write(data [1], length (data)) end; procedure TPEModuleRW.EmitAPICall(section: TImageSection; const dllName, functionName: string); var func : TImportFunction; offset : DWORD; begin func := AddOrGetImportFunction (dllName, functionName); Emit (section, [$ff, $15]); // opcode for CALL DWORD PTR offset := section.RawData.Position; Emit (section, [$00, $00, $00, $00]); // ^ ^ ^ ^ // Address of the entry for this function in the IAT = // module base address (eg. 400000) + // rva of import section + // offset (in import section) of this function's IAT entry. // // Because we don't know the RVA of the import section or the offset of // the IAT within the import section yet we have to fix this up later. // // TODO: // // Maybe make the import section the first section (so it's RVA would always // be $1000), and move the IAT to the beginning of the import section. That // way we could generate the address here, rather than resort to fixups func.fFixups.Add(Pointer (offset)); end; procedure TPEModuleRW.EmitRelocPtr(section: TImageSection; ptr: DWORD; destSection: TImageSection); var b : array [0..3] of byte absolute ptr; co : DWORD; begin co := section.RawData.Position; Emit (section, b); AddFixup (co, destSection); end; function TPEModuleRW.GetCodeSection: TImageSection; begin result := ImageSection [fCodeSectionIdx]; end; function TPEModuleRW.GetDataSection: TImageSection; begin result := ImageSection [fDataSectionIdx]; end; function TPEModuleRW.GetUDataSection: TImageSection; begin result := ImageSection [fUDataSectionIdx]; end; procedure TPEModuleRW.Initialize(IsExe, IsGUI: boolean); var dt : TDateTime; st : TSystemTime; optionalHeaderSize : DWORD; begin Move (DOSStubInit [0], fDOSHeader, sizeof (fDOSHeader)); DOSStub.Clear; DOSStub.Write(DOSStubInit [sizeof (fDOSHeader)], sizeof (DOSStub) - sizeof (fDOSHeader)); FillChar (fCOFFHeader, sizeof (fCOFFHeader), 0); fCOFFHeader.Machine := IMAGE_FILE_MACHINE_I386; GetSystemTime (st); with st do dt := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliseconds); fSectionList.Clear; optionalHeaderSize := Integer (@(PImageOptionalHeader (0)^.DataDirectory)); Inc (optionalHeaderSize, NUM_DATA_DIRECTORIES * sizeof (TImageDataDirectory)); fCOFFHeader.TimeDateStamp := SecondsBetween (dt, UnixDateDelta); fCOFFHeader.NumberOfSections := fSectionList.Count; fCOFFHeader.Characteristics := IMAGE_FILE_BYTES_REVERSED_HI or IMAGE_FILE_BYTES_REVERSED_LO or IMAGE_FILE_32BIT_MACHINE or IMAGE_FILE_EXECUTABLE_IMAGE or IMAGE_FILE_LOCAL_SYMS_STRIPPED or IMAGE_FILE_LINE_NUMS_STRIPPED or EXECharacteristics [IsExe]; fCOFFHeader.PointerToSymbolTable := 0; // Symbol table rarely used these days (Pietrick) fCOFFHeader.NumberOfSymbols := 0; fCOFFHeader.SizeOfOptionalHeader := optionalHeaderSize; ReallocMem (fOptionalHeader, optionalHeaderSize); ZeroMemory (fOptionalHeader, optionalHeaderSize); fOptionalHeader^.Magic := IMAGE_NT_OPTIONAL_HDR32_MAGIC; fOptionalHeader^.MajorLinkerVersion := PE_LINKER_VERSION_HI; fOptionalHeader^.MinorLinkerVersion := PE_LINKER_VERSION_LO; fOptionalHeader^.SizeOfCode := 0; // Filled in by encode fOptionalHeader^.SizeOfInitializedData := 0; // " " " " fOptionalHeader^.SizeOfUninitializedData := 0; // " " " " fOptionalHeader^.AddressOfEntryPoint := 0; fOptionalHeader.BaseOfCode := 0; // " " " " fOptionalHeader.BaseOfData := 0; // " " " " fOptionalHeader.ImageBase := DefaultImageBase [IsExe]; fOptionalHeader.SectionAlignment := $1000; fOptionalHeader.FileAlignment := $200; // Pietrek fOptionalHeader^.MajorOperatingSystemVersion := 5; fOptionalHeader^.MinorOperatingSystemVersion := 0; fOptionalHeader^.MajorImageVersion := 0; fOptionalHeader^.MinorImageVersion := 0; fOptionalHeader^.MajorSubsystemVersion := 4; fOptionalHeader^.MinorSubsystemVersion := 0; fOptionalHeader^.Win32VersionValue := 0; fOptionalHeader^.SizeOfImage := 0; // Filled in by Encode fOptionalHeader^.SizeOfHeaders := 0; // " " " " fOptionalHeader^.CheckSum := 0; // " " " " fOptionalHeader^.Subsystem := Subsystems [IsExe, IsGUI]; fOptionalHeader^.DllCharacteristics := 0; fOptionalHeader^.SizeOfStackReserve := $00100000; fOptionalHeader^.SizeOfStackCommit := $00004000; fOptionalHeader^.SizeOfHeapReserve := $00100000; fOptionalHeader^.SizeOfHeapCommit := $00004000; fOptionalHeader^.LoaderFlags := 0; fOptionalHeader^.NumberOfRvaAndSizes := NUM_DATA_DIRECTORIES; fSectionList.Add(TImportSection.CreateEmpty(self, '.idata', IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE, IMAGE_DIRECTORY_ENTRY_IMPORT)); fCodeSectionIdx := fSectionList.Add(TImageSection.CreateEmpty(self, '.text', IMAGE_SCN_CNT_CODE or IMAGE_SCN_MEM_EXECUTE or IMAGE_SCN_MEM_READ, $ffffffff)); fDataSectionIdx := fSectionList.Add(TImageSection.CreateEmpty(self, '.data', IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE, $ffffffff)); fUDataSectionIdx := fSectionList.Add(TImageSection.CreateEmpty(self, '.udata', IMAGE_SCN_CNT_UNINITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE, $ffffffff)); fSectionList.Add(TImageSection.CreateEmpty(self, '.tls', IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE, IMAGE_DIRECTORY_ENTRY_TLS)); fSectionList.Add(TRelocSection.CreateEmpty(self, '.reloc', IMAGE_SCN_MEM_DISCARDABLE or IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ, IMAGE_DIRECTORY_ENTRY_BASERELOC)); fSectionList.Add(TImageSection.CreateEmpty(self, '.rsrc', IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ, IMAGE_DIRECTORY_ENTRY_RESOURCE)); end; { TImportFunction } constructor TImportFunction.Create(const AFunctionName: string); begin fFixups := TList.Create; fFunctionName := AFunctionName end; destructor TImportFunction.Destroy; begin fFixups.Free; inherited; end; { TImportDLL } constructor TImportDLL.Create(const ADLLName: string); begin fDLLName := ADLLName; fImportFunctions := TStringList.Create; TStringList (fImportFunctions).CaseSensitive := False end; destructor TImportDLL.Destroy; var i : Integer; begin for i := 0 to fImportFunctions.Count - 1 do fImportFunctions.Objects [i].Free; fImportFunctions.Free; inherited; end; { TImportSection } destructor TImportSection.Destroy; var i : Integer; begin for i := 0 to fImportDlls.Count - 1 do fImportDlls.Objects [i].Free; fImportDLLs.Free; inherited; end; procedure TImportSection.Fixup; var size, nameOffset, iatOffset, iatSize, i, j, k, base, fNameOffset, rva : Integer; pd : PImageImportDescriptor; piat, prevPiat : PDWORD; fn : TImportFunction; dll : TImportDll; pNames : PAnsiChar; adllname : AnsiString; codeOffset : Integer; codeSection : TImageSection; parentImage : TPEModule; begin parentImage := parent as TPEModule; codeSection := TPEModuleRW (Parent).GetCodeSection; rva := SectionHeader.VirtualAddress; size := sizeof (TImageImportDescriptor) * (fImportDlls.Count+1); iatOffset := size; iatSize := 0; for i := 0 to fImportDlls.Count - 1 do begin dll := TImportDll (fImportDlls.Objects [i]); Inc (size, (dll.fImportFunctions.Count + 1) * 2 * sizeof (DWORD)); Inc (iatSize, (dll.fImportFunctions.Count + 1) * sizeof (DWORD)); end; nameOffset := size; fnameOffset := nameOffset; for i := 0 to fImportDlls.Count - 1 do begin dll := TImportDll (fImportDlls.Objects [i]); Inc (size, Length (dll.fDLLname) + 1); Inc (fNameOffset, Length (dll.fDllName) + 1); for j := 0 to dll.fImportFunctions.Count - 1 do begin fn := TImportFunction (dll.fImportFunctions.Objects [j]); Inc (size, sizeof (word) + Length (fn.fFunctionName) + 1); end end; fRawData.Size := size; base := Integer (fRawData.Memory); pd := PImageImportDescriptor (base); piat := PDWORD (base + iatOffset); pnames := PAnsiChar (base + nameOffset); for i := 0 to fImportDlls.Count - 1 do begin dll := TImportDll (fImportDlls.Objects [i]); pd^.TimeDateStamp := 0; pd^.ForwarderChain := 0; pd^.Name := Integer (pnames) - base + rva; adllname := AnsiString (dll.fDLLname); Move (adllname [1], pnames^, Length (dll.fDllName) + 1); Inc (pNames, Length (dll.fDllName) + 1); prevPiat := piat; pd^.FirstThunk := Integer (piat) - base + rva; for j := 0 to dll.fImportFunctions.Count - 1 do begin fn := TImportFunction (dll.fImportFunctions.Objects [j]); piat^ := fnameOffset+rva; for k := 0 to fn.fFixups.Count - 1 do begin codeOffset := Integer (fn.fFixups [k]); PDWORD (PByte (codeSection.RawData.Memory) + codeOffset)^ := Integer (piat) - base + rva + Integer (parentImage.OptionalHeader.ImageBase); TPEModuleRW (Parent).AddReloc (codeOffset); end; Inc (fNameOffset, sizeof (word)); adllname := AnsiString (fn.fFunctionName); Move (adllname [1], PAnsiChar (base + fNameOffset)^, Length (fn.fFunctionName) + 1); Inc (fNameOffset, Length (fn.fFunctionName) + 1); Inc (piat); end; piat^ := 0; Inc (piat); pd^.Characteristics := Integer (piat) - base + rva; for j := 0 to dll.fImportFunctions.Count - 1 do begin piat^ := prevPiat^; Inc (prevPiat); Inc (piat); end; piat^ := 0; Inc (piat); Inc (pd); end; FillChar (pd^, sizeof (pd^), 0); ParentImage.DataDirectory [IMAGE_DIRECTORY_ENTRY_IAT]^.VirtualAddress := iatOffset + rva; ParentImage.DataDirectory [IMAGE_DIRECTORY_ENTRY_IAT]^.Size := iatSize; end; procedure TImportSection.Initialize; begin fImportDLLs := TStringList.Create; TStringList (fImportDlls).CaseSensitive := False end; { TRelocSection } destructor TRelocSection.Destroy; begin fRelocs.Free; inherited; end; function CompareRelocs (p1, p2 : Pointer) : Integer; begin result := DWORD (p1) - DWORD (p2); end; const IMAGE_REL_BASED_ABSOLUTE = 0; IMAGE_REL_BASED_HIGHLOW = 3; type TImageBaseRelocation = record RVA : DWORD; Size : DWORD; end; PImageBaseRelocation = ^TImageBaseRelocation; procedure TRelocSection.Fixup; var reloc, block, ofs, csrva : DWORD; i : Integer; pHdr : PImageBaseRelocation; hdr : TImageBaseRelocation; w : word; begin fRelocs.Sort(CompareRelocs); fRawData.Clear; pHdr := Nil; csrva := TPEModuleRW (Parent).GetCodeSection.SectionHeader.VirtualAddress; for i := 0 to fRelocs.Count - 1 do begin reloc := DWORD (fRelocs [i]) + csrva; block := reloc shr 4; ofs := reloc and $fff; if (pHdr = Nil) or (pHdr^.RVA <> block) then begin if pHdr <> Nil then begin if hdr.Size mod sizeof (DWORD) <> 0 then begin w := IMAGE_REL_BASED_ABSOLUTE shl 12 + 0; fRawData.Write (w, sizeof (w)); Inc (pHdr^.Size, sizeof (w)); end end; hdr.RVA := block; hdr.Size := sizeof (TImageBaseRelocation); fRawData.Write(hdr, sizeof (hdr)); pHdr := PImageBaseRelocation (PByte (fRawData.Memory) + fRawData.Position - sizeof (hdr)); end; w := IMAGE_REL_BASED_HIGHLOW shl 12 + ofs; fRawData.Write (w, sizeof (w)); Inc (pHdr^.Size, sizeof (w)); end end; procedure TRelocSection.Initialize; begin inherited; fRelocs := TList.Create; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_EMPRESA] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit EcfEmpresaVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('ECF_EMPRESA')] TEcfEmpresaVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FRAZAO_SOCIAL: String; FNOME_FANTASIA: String; FCNPJ: String; FINSCRICAO_ESTADUAL: String; FINSCRICAO_ESTADUAL_ST: String; FINSCRICAO_MUNICIPAL: String; FINSCRICAO_JUNTA_COMERCIAL: String; FDATA_INSC_JUNTA_COMERCIAL: TDateTime; FMATRIZ_FILIAL: String; FDATA_CADASTRO: TDateTime; FDATA_INICIO_ATIVIDADES: TDateTime; FSUFRAMA: String; FEMAIL: String; FIMAGEM_LOGOTIPO: String; FCRT: String; FTIPO_REGIME: String; FALIQUOTA_PIS: Extended; FALIQUOTA_COFINS: Extended; FLOGRADOURO: String; FNUMERO: String; FCOMPLEMENTO: String; FCEP: String; FBAIRRO: String; FCIDADE: String; FUF: String; FFONE: String; FFAX: String; FCONTATO: String; FCODIGO_IBGE_CIDADE: Integer; FCODIGO_IBGE_UF: Integer; public [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('RAZAO_SOCIAL', 'Razao Social', 450, [ldGrid, ldLookup, ldCombobox], False)] property RazaoSocial: String read FRAZAO_SOCIAL write FRAZAO_SOCIAL; [TColumn('NOME_FANTASIA', 'Nome Fantasia', 450, [ldGrid, ldLookup, ldCombobox], False)] property NomeFantasia: String read FNOME_FANTASIA write FNOME_FANTASIA; [TColumn('CNPJ', 'Cnpj', 112, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftCnpj, taLeftJustify)] property Cnpj: String read FCNPJ write FCNPJ; [TColumn('INSCRICAO_ESTADUAL', 'Inscricao Estadual', 240, [ldGrid, ldLookup, ldCombobox], False)] property InscricaoEstadual: String read FINSCRICAO_ESTADUAL write FINSCRICAO_ESTADUAL; [TColumn('INSCRICAO_ESTADUAL_ST', 'Inscricao Estadual St', 240, [ldGrid, ldLookup, ldCombobox], False)] property InscricaoEstadualSt: String read FINSCRICAO_ESTADUAL_ST write FINSCRICAO_ESTADUAL_ST; [TColumn('INSCRICAO_MUNICIPAL', 'Inscricao Municipal', 240, [ldGrid, ldLookup, ldCombobox], False)] property InscricaoMunicipal: String read FINSCRICAO_MUNICIPAL write FINSCRICAO_MUNICIPAL; [TColumn('INSCRICAO_JUNTA_COMERCIAL', 'Inscricao Junta Comercial', 240, [ldGrid, ldLookup, ldCombobox], False)] property InscricaoJuntaComercial: String read FINSCRICAO_JUNTA_COMERCIAL write FINSCRICAO_JUNTA_COMERCIAL; [TColumn('DATA_INSC_JUNTA_COMERCIAL', 'Data Insc Junta Comercial', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInscJuntaComercial: TDateTime read FDATA_INSC_JUNTA_COMERCIAL write FDATA_INSC_JUNTA_COMERCIAL; [TColumn('MATRIZ_FILIAL', 'Matriz Filial', 8, [ldGrid, ldLookup, ldCombobox], False)] property MatrizFilial: String read FMATRIZ_FILIAL write FMATRIZ_FILIAL; [TColumn('DATA_CADASTRO', 'Data Cadastro', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO; [TColumn('DATA_INICIO_ATIVIDADES', 'Data Inicio Atividades', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInicioAtividades: TDateTime read FDATA_INICIO_ATIVIDADES write FDATA_INICIO_ATIVIDADES; [TColumn('SUFRAMA', 'Suframa', 72, [ldGrid, ldLookup, ldCombobox], False)] property Suframa: String read FSUFRAMA write FSUFRAMA; [TColumn('EMAIL', 'Email', 450, [ldGrid, ldLookup, ldCombobox], False)] property Email: String read FEMAIL write FEMAIL; [TColumn('IMAGEM_LOGOTIPO', 'Imagem Logotipo', 450, [ldGrid, ldLookup, ldCombobox], False)] property ImagemLogotipo: String read FIMAGEM_LOGOTIPO write FIMAGEM_LOGOTIPO; [TColumn('CRT', 'Crt', 8, [ldGrid, ldLookup, ldCombobox], False)] property Crt: String read FCRT write FCRT; [TColumn('TIPO_REGIME', 'Tipo Regime', 8, [ldGrid, ldLookup, ldCombobox], False)] property TipoRegime: String read FTIPO_REGIME write FTIPO_REGIME; [TColumn('ALIQUOTA_PIS', 'Aliquota Pis', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaPis: Extended read FALIQUOTA_PIS write FALIQUOTA_PIS; [TColumn('ALIQUOTA_COFINS', 'Aliquota Cofins', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaCofins: Extended read FALIQUOTA_COFINS write FALIQUOTA_COFINS; [TColumn('LOGRADOURO', 'Logradouro', 450, [ldGrid, ldLookup, ldCombobox], False)] property Logradouro: String read FLOGRADOURO write FLOGRADOURO; [TColumn('NUMERO', 'Numero', 48, [ldGrid, ldLookup, ldCombobox], False)] property Numero: String read FNUMERO write FNUMERO; [TColumn('COMPLEMENTO', 'Complemento', 450, [ldGrid, ldLookup, ldCombobox], False)] property Complemento: String read FCOMPLEMENTO write FCOMPLEMENTO; [TColumn('CEP', 'Cep', 64, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftCep, taLeftJustify)] property Cep: String read FCEP write FCEP; [TColumn('BAIRRO', 'Bairro', 450, [ldGrid, ldLookup, ldCombobox], False)] property Bairro: String read FBAIRRO write FBAIRRO; [TColumn('CIDADE', 'Cidade', 450, [ldGrid, ldLookup, ldCombobox], False)] property Cidade: String read FCIDADE write FCIDADE; [TColumn('UF', 'Uf', 16, [ldGrid, ldLookup, ldCombobox], False)] property Uf: String read FUF write FUF; [TColumn('FONE', 'Fone', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Fone: String read FFONE write FFONE; [TColumn('FAX', 'Fax', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftTelefone, taLeftJustify)] property Fax: String read FFAX write FFAX; [TColumn('CONTATO', 'Contato', 240, [ldGrid, ldLookup, ldCombobox], False)] property Contato: String read FCONTATO write FCONTATO; [TColumn('CODIGO_IBGE_CIDADE', 'Codigo Ibge Cidade', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CodigoIbgeCidade: Integer read FCODIGO_IBGE_CIDADE write FCODIGO_IBGE_CIDADE; [TColumn('CODIGO_IBGE_UF', 'Codigo Ibge Uf', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CodigoIbgeUf: Integer read FCODIGO_IBGE_UF write FCODIGO_IBGE_UF; end; implementation initialization Classes.RegisterClass(TEcfEmpresaVO); finalization Classes.UnRegisterClass(TEcfEmpresaVO); end.
unit VSEFormManager; interface uses Windows, AvL, avlUtils, OpenGL, VSEOpenGLExt, oglExtensions, VSECore, VSEGUI; type TFormAlignment = (faLeft, faCenter, faRight, faTop, faMiddle, faBottom); TFormAlignmentSet = set of TFormAlignment; TAlignedForm = class(TGUIForm) //Alignable form protected FAlignment: TFormAlignmentSet; procedure SetAlignment(Value: TFormAlignmentSet); public constructor Create(X, Y, Width, Height: Integer); procedure Align; //Align form property Alignment: TFormAlignmentSet read FAlignment write SetAlignment; //Desired alignment end; TFormManager = class(TModule) private FFormsSet: TGUIFormsSet; FCapturedMouse: TGUIForm; FAlignedSets: TList; {$IFDEF VSE_CONSOLE} function UIColorHandler(Sender: TObject; Args: array of const): Boolean; function UIFontHandler(Sender: TObject; Args: array of const): Boolean; {$ENDIF} function GetForm(const Name: string): TGUIForm; procedure SetFormsSet(Value: TGUIFormsSet); function GetVisible(const Name: string): Boolean; procedure SetVisible(const Name: string; const Value: Boolean); public constructor Create; override; destructor Destroy; override; class function Name: string; override; procedure Draw; override; procedure Update; override; procedure OnEvent(var Event: TCoreEvent); override; procedure Show(const Name: string); //Show and pop form procedure Hide(const Name: string); //Hide form procedure Pop(const Name: string); //Pop form to front procedure AlignForms; //Align alignable forms function MouseOnForm(X, Y: Integer): Boolean; //Returns true if mouse on form or captured function Top: TGUIForm; //Topmost form property FormsSet: TGUIFormsSet read FFormsSet write SetFormsSet; //Current forms set property Forms[const Name: string]: TGUIForm read GetForm; default; //Forms property Visible[const Name: string]: Boolean read GetVisible write SetVisible; //Form visibility end; var FormManager: TFormManager; implementation uses VSECollisionCheck, VSERender2D{$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}; const ColorNames = 'btnbg:btnbd:btntxt:frmcpt:frmbg:frmbd:frmcptxt:text:tabstop'; { TAlignedForm } constructor TAlignedForm.Create(X, Y, Width, Height: Integer); begin inherited; Movable := true; FAlignment := []; end; procedure TAlignedForm.Align; begin if faLeft in FAlignment then Left := Round(Render2D.VSBounds.Left) else if faCenter in FAlignment then Left := (Render2D.VSWidth - Width) div 2 else if faRight in FAlignment then Left := Round(Render2D.VSBounds.Right) - Width; if faTop in FAlignment then Top := Round(Render2D.VSBounds.Top) else if faMiddle in FAlignment then Top := (Render2D.VSHeight - Height) div 2 else if faBottom in FAlignment then Top := Round(Render2D.VSBounds.Bottom) - Height; end; procedure TAlignedForm.SetAlignment(Value: TFormAlignmentSet); begin FAlignment := Value; Align; end; { TFormManager } constructor TFormManager.Create; begin inherited; FormManager := Self; FAlignedSets := TList.Create; SetGUIFont; {$IFDEF VSE_CONSOLE} Console['uicolor ?clr=e' + ColorNames + ' ?def=i ?hl=i ?act=i ?dis=i'] := UIColorHandler; Console['uifont name=s ?size=i8:24 ?weight=en:b'] := UIFontHandler; {$ENDIF} end; destructor TFormManager.Destroy; begin FormManager := nil; FAN(FAlignedSets); inherited; end; class function TFormManager.Name: string; begin Result := 'FormManager'; end; procedure TFormManager.Draw; var Form: PFormRec; begin if not Assigned(FFormsSet) then Exit; Form := FFormsSet.LastForm; while Assigned(Form) do begin if Form.Visible then Form.Form.Draw; Form := Form.Prev; end; end; procedure TFormManager.Update; var Form, NextForm: PFormRec; begin if not Assigned(FFormsSet) then Exit; Form := FFormsSet.FirstForm; while Assigned(Form) do begin NextForm := Form.Next; if Form.Visible then Form.Form.Update; Form := NextForm; end; end; procedure TFormManager.OnEvent(var Event: TCoreEvent); var Form: PFormRec; begin if Event is TMouseEvent then with Event as TMouseEvent do begin if Core.MouseCapture then Exit; if Assigned(FCapturedMouse) then begin FCapturedMouse.MouseEvent(Button, EvType, Cursor); if EvType = meUp then FCapturedMouse := nil; FreeAndNil(Event); Exit; end; if not Assigned(FFormsSet) then Exit; Form := FFormsSet.FormAt(Cursor.X, Cursor.Y); if Assigned(Form) and not Form.Locked then with Form^ do begin if EvType = meDown then begin FCapturedMouse := Form; Pop(Name); end; if Form.MouseEvent(Button, EvType, Cursor) then FreeAndNil(Event); end; end else if Event is TKeyEvent then with Event as TKeyEvent do begin if not Assigned(FFormsSet) or not Assigned(FFormsSet.FirstForm) then Exit; if (EvType = keDown) and (Key = VK_TAB) and Core.KeyPressed[VK_CONTROL] then begin FFormsSet.Pop(FFormsSet.LastForm); FreeAndNil(Event); end else with FFormsSet.FirstForm^ do if Visible and not Locked then if Form.KeyEvent(Key, EvType) then FreeAndNil(Event); end else if Event is TCharEvent then begin if not Assigned(FFormsSet) or not Assigned(FFormsSet.FirstForm) then Exit; with FFormsSet.FirstForm^ do if Visible and not Locked then if Form.CharEvent((Event as TCharEvent).Chr) then FreeAndNil(Event); end else if (Event is TSysNotify) and ((Event as TSysNotify).Notify = snResolutionChanged) then begin FAlignedSets.Clear; AlignForms; end else inherited; end; procedure TFormManager.Show(const Name: string); begin Visible[Name] := true; Pop(Name); end; procedure TFormManager.Hide(const Name: string); begin Visible[Name] := false; end; procedure TFormManager.Pop(const Name: string); begin if not Assigned(FFormsSet) then Exit; FFormsSet.Pop(FFormsSet.FindForm(Name)); end; procedure TFormManager.AlignForms; procedure RealignForm(Self: TObject; Form: TGUIForm); begin if Form is TAlignedForm then (Form as TAlignedForm).Align; end; begin if Assigned(FFormsSet) then begin FFormsSet.IterateForms(TOnForm(MakeMethod(@RealignForm))); if FAlignedSets.IndexOf(FFormsSet) < 0 then FAlignedSets.Add(FFormsSet); end; end; function TFormManager.MouseOnForm(X, Y: Integer): Boolean; begin Result := Assigned(FCapturedMouse) or (Assigned(FFormsSet) and Assigned(FFormsSet.FormAt(X, Y))); end; function TFormManager.Top: TGUIForm; begin Result := nil; if Assigned(FFormsSet) and Assigned(FFormsSet.FirstForm) then Result := FFormsSet.FirstForm.Form; end; function TFormManager.GetForm(const Name: string): TGUIForm; begin Result := FFormsSet[Name]; end; procedure TFormManager.SetFormsSet(Value: TGUIFormsSet); begin FFormsSet := Value; if FAlignedSets.IndexOf(FFormsSet) < 0 then AlignForms; end; function TFormManager.GetVisible(const Name: string): Boolean; begin Result := false; if Assigned(FFormsSet) then Result := FFormsSet.Visible[Name]; end; procedure TFormManager.SetVisible(const Name: string; const Value: Boolean); begin if Assigned(FFormsSet) then FFormsSet.Visible[Name] := Value; end; {$IFDEF VSE_CONSOLE} type TColorRec = record Name: string; case IsColorSet: Boolean of true: (ColorSet: ^TColorSet); false: (Color: ^TColor); end; function TFormManager.UIColorHandler(Sender: TObject; Args: array of const): Boolean; const Colors: array[0..8] of TColorRec = ( (IsColorSet: true; ColorSet: @BtnBackground), (IsColorSet: true; ColorSet: @BtnBorder), (IsColorSet: true; ColorSet: @BtnText), (IsColorSet: true; ColorSet: @FormCapt), (IsColorSet: false; Color: @clFormBackground), (IsColorSet: false; Color: @clFormBorder), (IsColorSet: false; Color: @clFormCaptText), (IsColorSet: false; Color: @clText), (IsColorSet: false; Color: @clTabStop)); begin Result := true; if Length(Args) = 1 then Console.WriteLn('Colors: ' + ColorNames) else with Colors[Args[1].VInteger] do if Length(Args) = 2 then if IsColorSet then Console.WriteLn(Format('def=$%X hl=$%X act=$%X dis=$%X', [ColorSet.Default, ColorSet.Highlighted, ColorSet.Activated, ColorSet.Disabled])) else Console.WriteLn('$' + IntToHex(Color^, 8)) else if IsColorSet then if Length(Args) = 6 then begin ColorSet.Default := Args[2].VInteger; ColorSet.Highlighted := Args[3].VInteger; ColorSet.Activated := Args[4].VInteger; ColorSet.Disabled := Args[5].VInteger; end else begin Console.WriteLn('Error: 4 values needed for color set' + PostfixError); Result := false; end else Color^ := Args[2].VInteger; end; function TFormManager.UIFontHandler(Sender: TObject; Args: array of const): Boolean; begin Result := true; if Length(Args) = 4 then SetGUIFont(string(Args[1].VAnsiString), Args[2].VInteger, Boolean(Args[3].VInteger)) else if Length(Args) = 3 then SetGUIFont(string(Args[1].VAnsiString), Args[2].VInteger) else SetGUIFont(string(Args[1].VAnsiString)); end; {$ENDIF} initialization RegisterModule(TFormManager); end.
unit Config; interface uses IdFTP, ADODB; //ftp config type TFTPConfig = class public server: String; port: String; user: string; password: string; passive: string; end; //db config type TDBConfig = class public server: String; db: String; user: string; password: string; end; type TConfig = class public dbconfig: TDBConfig; ftpconfig: TFTPConfig; constructor create(httpAddr:String); destructor destroy(); override; procedure InitFTP(var ftp: TIdFTP); procedure InitDBConn(var conn: TADOConnection); end; implementation uses IdHTTP,XMLMarkup,sysutils; constructor TConfig.Create(httpAddr:String); var idhttp1:TIdHTTP ; xmlstring:String; xml:TXMLMarkup; begin //inherited; //init member self.dbconfig:=TDBConfig.Create; self.ftpconfig:=TFTPConfig.Create; //read ini xml file idhttp1:= TIdHTTP.Create(nil); xmlstring := IDhttp1.Get(httpAddr); idhttp1.Destroy; //parse xml string xml:= TXMLMarkup.Create; xml.SetDoc(xmlstring); xml.FindElem;//ini xml.FindChildElem('db'); //db self.dbconfig.server:= xml.getchildattrib('server'); self.dbconfig.db:= xml.getchildattrib('dbname'); self.dbconfig.user:= xml.getchildattrib('user'); self.dbconfig.password:= xml.getchildattrib('password'); xml.FindChildElem('ftp'); //ftp self.ftpconfig.server:= xml.getchildattrib('server'); self.ftpconfig.port:= xml.getchildattrib('port'); self.ftpconfig.user:= xml.getchildattrib('user'); self.ftpconfig.password:= xml.getchildattrib('password'); self.ftpconfig.passive:= xml.getchildattrib('passive'); xml.Destroy; end; destructor TConfig.Destroy; begin self.dbconfig.Free; self.ftpconfig.Free; inherited; end; procedure TConfig.InitDBConn(var conn: TADOConnection); var connString:WideString; begin conn.Close; connString:='Provider=SQLOLEDB.1;' +'Password='+self.dbconfig.password+';' +'Persist Security Info=True;' +'User ID='+self.dbconfig.user+';' +'Initial Catalog='+self.dbconfig.db+';' +'Data Source='+self.dbconfig.server+';' +'Use Procedure for Prepare=1;' +'Auto Translate=True;' +'Packet Size=4096;' //+'Workstation ID=XUEGUOSONG;' +'Use Encryption for Data=False;' +'Tag with column collation when possible=False'; conn.ConnectionString:=connString; end; procedure TConfig.InitFTP(var ftp: TIdFTP); var passive:boolean; begin ftp.Host:=self.ftpconfig.server; ftp.Port:=strtoint(self.ftpconfig.port); ftp.Username:=self.ftpconfig.user; ftp.Password:=self.ftpconfig.password; if self.ftpconfig.passive = '1' then passive := true else passive := false; ftp.Passive:=passive; end; end.
{***************************************************************************} { } { DMemCached - Copyright (C) 2014 - Víctor de Souza Faria } { } { victor@victorfaria.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DMemcached.Message; interface uses System.Classes, System.SysUtils, DMemcached.Trasncoder; type opMagic = (Request = $80, Response = $81); opCodes = (opGet = $00, opSet = $01, opAdd = $02, opReplace = $03, opDelete = $04, opIncrement = $05, opDecrement = $06, opQuit = $07, opFlush = $08, opGetQ = $09, opNoop = $0A, opVersion = $0B , opGetK = $0C, opGetKQ = $0D, opAppend = $0E, opPrepend = $0F, opStat = $10, opSetQ = $11, opAddQ = $12, opReplaceQ = $13, opDeleteQ = $14, opIncrementQ = $15, opDecrementQ = $16, opQuitQ = $17, opFlushQ = $18, opAppendQ = $19, opPrependQ = $1A); respStatus = (NoError = $00, KeyNotFound = $01, KeyExists = $02, ValueTooLarge = $03, InvalidArguments = $04, ItemNotStored = $05, NonNumericValue = $06); TMemcaheHeader = class strict private FOpcode: opCodes; FKeyLength: UInt16; FExtraLength: Byte; FBodyLength: UInt32; FOpaque: TBytes; FCAS: UInt64; protected FMagic: opMagic; function Reserved: TBytes; virtual; abstract; public constructor Create; property Magic: opMagic read FMagic; property OpCode: opCodes read FOpcode write FOpcode; property KeyLength: UInt16 read FKeyLength write FKeyLength; property ExtraLength: Byte read FExtraLength write FExtraLength; property BodyLength: UInt32 read FBodyLength write FBodyLength; property Opaque: TBytes read FOpaque write FOpaque; property CAS: UInt64 read FCAS write FCAS; function Pack: TBytes; procedure Unpack(data: TBytes); virtual; end; TMemcaheResponseHeader = class(TMemcaheHeader) strict private FStatus: respStatus; protected function Reserved: TBytes; override; public constructor Create; property Status: respStatus read FStatus write FStatus; procedure Unpack(data: TBytes); override; end; TMemcaheRequestHeader = class(TMemcaheHeader) protected function Reserved: TBytes; override; public constructor Create; end; TMemcachedBaseMessage<T> = class private FHeader: TMemcaheHeader; FKey: String; FTranscoder: ITranscoder<T>; FValue: T; function KeyBytes: TBytes; protected function Extra: TBytes; virtual; procedure SetExtra(extra : TBytes); virtual; function ValueLength: UInt32; public constructor Create(opcode: opCodes; key: String; transcoder: ITranscoder<T>); overload; virtual; constructor Create(data: TBytes; transcoder: ITranscoder<T>); overload; virtual; property Key: String read FKey write FKey; property Value: T read FValue write FValue; property Header: TMemcaheHeader read FHeader; function Pack: TBytes; procedure Unpack(data: TBytes); virtual; end; TMemcachedSetMessage<T> = class(TMemcachedBaseMessage<T>) private FFlags: UInt32; FExpire: UInt32; protected function Extra: TBytes; override; procedure SetExtra(extra : TBytes); override; public constructor Create(opcode: opCodes; key: String; value: T; flags: UInt32; expire: UInt32; transcoder: ITranscoder<T>); end; TMemcachedGetMessage<T> = class(TMemcachedBaseMessage<T>) public constructor Create(opcode: opCodes; key: String; transcoder: ITranscoder<T>); override; end; TMemcachedResponseMessage<T> = class(TMemcachedBaseMessage<T>) public constructor Create(responseHeader: TBytes; transcoder: ITranscoder<T>); override; end; implementation uses DMemcached.Util; const headerSize = 24; magicOffset = 0; opcodOffset = 1; keyLengthOffset = 2; extraLengthOffset = 4; dataTypaOffset = 5; reservedOffset = 6; bodyLengthOffset = 8; opaqueOffset = 12; casOffset = 16; { TMemcachedBaseMessage } constructor TMemcachedBaseMessage<T>.Create(opcode: opCodes; key: String; transcoder: ITranscoder<T>); begin FHeader := TMemcaheRequestHeader.Create; FHeader.OpCode := opcode; FKey := key; FHeader.KeyLength := Length(key) * SizeOf(Char); FTranscoder := transcoder; end; constructor TMemcachedBaseMessage<T>.Create(data: TBytes; transcoder: ITranscoder<T>); begin FHeader := TMemcaheRequestHeader.Create; Unpack(data); end; function TMemcachedBaseMessage<T>.Extra: TBytes; begin SetLength(Result, 0); end; function TMemcachedBaseMessage<T>.KeyBytes: TBytes; begin Result := WideBytesOf(FKey); end; function TMemcachedBaseMessage<T>.Pack: TBytes; var index: NativeInt; extra: TBytes; value: TBytes; key: TBytes; begin Result := FHeader.Pack; SetLength(Result, headerSize + FHeader.BodyLength); index := headerSize; extra := self.Extra; Move(extra[0], Result[index], Length(extra)); index := index + Length(extra); key := KeyBytes; Move(key[0], Result[index], Length(key)); index := index + Length(key); value := FTranscoder.ToBytes(FValue); Move(value[0], Result[index], Length(value)); end; procedure TMemcachedBaseMessage<T>.SetExtra(extra: TBytes); begin end; procedure TMemcachedBaseMessage<T>.Unpack(data: TBytes); var index: NativeInt; begin FHeader.Unpack(data); if NativeInt(Length(data)) >= NativeInt(headerSize + FHeader.BodyLength) then begin index := headerSize; if (FHeader.ExtraLength > 0) then begin SetExtra(Copy(data, index, FHeader.ExtraLength)); index := index + FHeader.ExtraLength; end; if (FHeader.KeyLength > 0) then begin FKey := TEncoding.Unicode.GetString(Copy(data, index, FHeader.KeyLength)); index := index + FHeader.KeyLength; end; if (FHeader.BodyLength > FHeader.ExtraLength + FHeader.KeyLength) then begin FValue := FTranscoder.ToObject(Copy(data, index, FHeader.BodyLength - (FHeader.ExtraLength + FHeader.KeyLength))); end; end; end; function TMemcachedBaseMessage<T>.ValueLength: UInt32; begin Result := FTranscoder.BytesSize(FValue); end; { TMemcaheHeader } constructor TMemcaheHeader.Create; begin SetLength(FOpaque, 4); FCAS := 0; end; { TMemcachedSetMessage<T> } constructor TMemcachedSetMessage<T>.Create(opcode: opCodes; key: String; value: T; flags: UInt32; expire: UInt32; transcoder: ITranscoder<T>); begin inherited Create(opcode, key, transcoder); FValue := value; FHeader.ExtraLength := 8; FFlags := flags; FExpire := expire; FHeader.BodyLength := FHeader.ExtraLength + FHeader.KeyLength + ValueLength; end; function TMemcachedSetMessage<T>.Extra: TBytes; var flagsBytes: TBytes; expireBytes: TBytes; begin SetLength(Result, 8); flagsBytes := UInt32ToByte(FFlags); Move(flagsBytes[0], Result[0], 4); expireBytes := UInt32ToByte(FExpire); Move(expireBytes[0], Result[4], 4); end; procedure TMemcachedSetMessage<T>.SetExtra(extra: TBytes); begin if Length(extra) = 8 then begin FFlags := ByteToUInt32(Copy(extra, 0, 4)); FExpire := ByteToUInt32(Copy(extra, 4, 4)); end; end; function TMemcaheHeader.Pack: TBytes; var emptyValue: NativeInt; reserved: TBytes; begin emptyValue := 0; SetLength(Result, headerSize); Move(Magic, Result[magicOffset], 1); Move(Opcode, Result[opcodOffset], 1); Move(WordToByte(KeyLength)[0], Result[keyLengthOffset], SizeOf(KeyLength)); // Extras Move(ExtraLength, Result[extraLengthOffset], SizeOf(ExtraLength)); // DataType Move(emptyValue, Result[dataTypaOffset], 1); // Reserved reserved := self.Reserved; Move(reserved[0], Result[reservedOffset], 2); // BodyLength Move(UInt32ToByte(BodyLength)[0], Result[bodyLengthOffset], SizeOf(BodyLength)); // Opaque Move(Opaque[0], Result[opaqueOffset], 4); // CAS Move(UInt64ToByte(CAS)[0], Result[casOffset], SizeOf(CAS)); end; procedure TMemcaheHeader.Unpack(data: TBytes); begin if Length(data) >= headerSize then begin FMagic := opMagic(data[magicOffset]); Opcode := opCodes(data[opcodOffset]); KeyLength := ByteToWord(Copy(data, keyLengthOffset, SizeOf(KeyLength))); ExtraLength := data[extraLengthOffset]; BodyLength := ByteToUInt32(Copy(data, bodyLengthOffset, SizeOf(BodyLength))); FOpaque := Copy(data, opaqueOffset, 4); CAS := ByteToUInt64(Copy(data, casOffset, SizeOf(CAS))); end; end; { TMemcaheRequestHeader } constructor TMemcaheRequestHeader.Create; begin inherited Create; FMagic := Request; end; function TMemcaheRequestHeader.Reserved: TBytes; begin SetLength(Result, 2); end; { TMemcaheResponseHeader } constructor TMemcaheResponseHeader.Create; begin inherited Create; FMagic := Response; end; function TMemcaheResponseHeader.Reserved: TBytes; var status: TBytes; begin SetLength(Result, 2); status := WordToByte(Word(FStatus)); Move(status[0], Result[0], 2); end; procedure TMemcaheResponseHeader.Unpack(data: TBytes); begin inherited Unpack(data); FStatus := respStatus(ByteToWord(Copy(data, reservedOffset, 2))); end; { TMemcachedResponseMessage<T> } constructor TMemcachedResponseMessage<T>.Create(responseHeader: TBytes; transcoder: ITranscoder<T>); begin FHeader := TMemcaheResponseHeader.Create; FTranscoder := transcoder; FHeader.Unpack(responseHeader); end; { TMemcachedGetMessage<T> } constructor TMemcachedGetMessage<T>.Create(opcode: opCodes; key: String; transcoder: ITranscoder<T>); begin inherited Create(opcode, key, transcoder); FValue := value; FHeader.ExtraLength := 0; FHeader.BodyLength := FHeader.ExtraLength + FHeader.KeyLength + ValueLength; end; end.
unit ValuesetSelectDialog; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.StdCtrls, FMX.DateTimeCtrls, FMX.ListBox, FMX.Edit, FMX.Controls.Presentation, GuidSupport, FHIRTypes, FHIRResources, FHIRUtilities, FHIRClient, SettingsDialog, FMX.ComboEdit, ToolkitSettings; type TValuesetSelectForm = class(TForm) Panel1: TPanel; Button2: TButton; Panel2: TPanel; Label1: TLabel; Go: TButton; Label2: TLabel; Label3: TLabel; Label6: TLabel; edtValue: TEdit; gridContains: TGrid; cbxServer: TComboBox; btnSettings: TButton; cbxOperation: TComboBox; CheckColumn1: TCheckColumn; StringColumn1: TStringColumn; StringColumn2: TStringColumn; CheckColumn2: TCheckColumn; btnAppend: TButton; btnReplace: TButton; CheckColumn3: TCheckColumn; Label4: TLabel; btnAll: TButton; btnActive: TButton; btnSelectable: TButton; btnNone: TButton; cbUseDisplays: TCheckBox; cbeProperty: TComboEdit; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure GoClick(Sender: TObject); procedure gridContainsGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); procedure btnSettingsClick(Sender: TObject); procedure btnAllClick(Sender: TObject); procedure btnNoneClick(Sender: TObject); procedure btnActiveClick(Sender: TObject); procedure btnSelectableClick(Sender: TObject); procedure btnAppendClick(Sender: TObject); procedure btnReplaceClick(Sender: TObject); procedure gridContainsSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); private FExpansion : TFHIRValueSet; FSettings: TFHIRToolkitSettings; FClient : TFhirClient; FVersion: String; FSystem: String; FHasConcepts: boolean; FReplace: boolean; function selectedCount : integer; procedure SetExpansion(const Value: TFHIRValueSet); procedure SetSettings(const Value: TFHIRToolkitSettings); public destructor Destroy; override; property Settings : TFHIRToolkitSettings read FSettings write SetSettings; property system : String read FSystem write FSystem; property version : String read FVersion write FVersion; property hasConcepts : boolean read FHasConcepts write FHasConcepts; property replace : boolean read FReplace write FReplace; property expansion : TFHIRValueSet read FExpansion; end; var ValuesetSelectForm: TValuesetSelectForm; implementation {$R *.fmx} Uses FHIRToolkitForm; { TValuesetExpansionForm } procedure TValuesetSelectForm.btnSelectableClick(Sender: TObject); var contains : TFhirValueSetExpansionContains; begin for contains in FExpansion.expansion.containsList do if contains.abstract then contains.TagInt := 0 else contains.TagInt := 1; gridContains.RowCount := 0; gridContains.RowCount := FExpansion.expansion.containsList.Count; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); end; procedure TValuesetSelectForm.btnSettingsClick(Sender: TObject); var form : TSettingsForm; begin form := TSettingsForm.create(self); try form.Settings := FSettings.link; form.TabControl1.TabIndex := 1; if form.showmodal = mrOk then begin FSettings.ListServers('Terminology', cbxServer.Items); cbxServer.ItemIndex := 0; end; finally form.free; end; end; procedure TValuesetSelectForm.btnActiveClick(Sender: TObject); var contains : TFhirValueSetExpansionContains; begin for contains in FExpansion.expansion.containsList do if contains.inactive then contains.TagInt := 0 else contains.TagInt := 1; gridContains.RowCount := 0; gridContains.RowCount := FExpansion.expansion.containsList.Count; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); end; procedure TValuesetSelectForm.btnNoneClick(Sender: TObject); var contains : TFhirValueSetExpansionContains; begin for contains in FExpansion.expansion.containsList do contains.TagInt := 0; gridContains.RowCount := 0; gridContains.RowCount := FExpansion.expansion.containsList.Count; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); end; procedure TValuesetSelectForm.btnReplaceClick(Sender: TObject); begin if selectedCount > 0 then begin replace := true; ModalResult := mrOk; end; end; procedure TValuesetSelectForm.btnAllClick(Sender: TObject); var contains : TFhirValueSetExpansionContains; begin for contains in FExpansion.expansion.containsList do contains.TagInt := 1; gridContains.RowCount := 0; gridContains.RowCount := FExpansion.expansion.containsList.Count; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); end; procedure TValuesetSelectForm.btnAppendClick(Sender: TObject); begin if selectedCount > 0 then begin replace := false; ModalResult := mrOk; end; end; destructor TValuesetSelectForm.Destroy; begin FSettings.Free; FExpansion.Free; FClient.Free; inherited; end; procedure TValuesetSelectForm.FormClose(Sender: TObject; var Action: TCloseAction); var s : String; begin try FSettings.storeValue('ValueSet.Select.Window', 'left', left); FSettings.storeValue('ValueSet.Select.Window', 'top', top); FSettings.storeValue('ValueSet.Select.Window', 'width', width); FSettings.storeValue('ValueSet.Select.Window', 'height', height); FSettings.storeValue('ValueSet.Select', 'Property', cbeProperty.Text); FSettings.storeValue('ValueSet.Select', 'Operation', cbxOperation.ItemIndex); FSettings.storeValue('ValueSet.Select', 'Value', edtValue.Text); FSettings.save; except end; end; procedure TValuesetSelectForm.FormShow(Sender: TObject); begin Left := FSettings.getValue('ValueSet.Select.Window', 'left', left); Top := FSettings.getValue('ValueSet.Select.Window', 'top', top); Width := FSettings.getValue('ValueSet.Select.Window', 'width', width); Height := FSettings.getValue('ValueSet.Select.Window', 'height', height); FSettings.ListServers('Terminology', cbxServer.Items); cbxServer.ItemIndex := 0; cbeProperty.Text := FSettings.getValue('ValueSet.Select', 'Property', ''); cbxOperation.ItemIndex := FSettings.getValue('ValueSet.Select', 'Operation', 0); edtValue.Text := FSettings.getValue('ValueSet.Select', 'Value', ''); end; procedure TValuesetSelectForm.GoClick(Sender: TObject); var params : TFHIRParameters; vs : TFHIRValueSet; inc : TFhirValueSetComposeInclude; filter : TFhirValueSetComposeIncludeFilter; begin vs := TFHIRValueSet.create; try vs.url := NewGuidURN; vs.compose := TFhirValueSetCompose.create; inc := vs.compose.includeList.Append; inc.system := system; inc.version := version; filter := inc.filterList.Append; filter.property_ := cbeProperty.Text; filter.op := TFhirFilterOperatorEnum(cbxOperation.ItemIndex); filter.value := edtValue.Text; FExpansion.Free; FExpansion := nil; gridContains.RowCount := 0; btnAppend.Enabled := false; btnReplace.Enabled := false; if FClient = nil then FClient := TFhirThreadedClient.Create(TFhirHTTPClient.Create(nil, FSettings.serverAddress('Terminology', cbxServer.itemIndex), false, FSettings.timeout * 1000, FSettings.proxy), MasterToolsForm.threadMonitorProc); MasterToolsForm.dowork(self, 'Searching', true, procedure var params : TFHIRParameters; begin params := TFhirParameters.Create; try params.AddParameter('valueSet', vs.Link); FExpansion := FClient.operation(frtValueSet, 'expand', params) as TFHIRValueSet; gridContains.RowCount := FExpansion.expansion.containsList.Count; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); finally params.Free; end; end); finally vs.Free; end; end; procedure TValuesetSelectForm.gridContainsGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); var contains : TFhirValueSetExpansionContains; begin contains := FExpansion.expansion.containsList[ARow]; case ACol of 0: value := contains.TagInt > 0; 1: value := contains.code; 2: value := contains.display; 3: value := not contains.abstract; 4: value := not contains.inactive; end; end; procedure TValuesetSelectForm.gridContainsSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); var contains : TFhirValueSetExpansionContains; begin contains := FExpansion.expansion.containsList[ARow]; if ACol = 0 then if value.AsBoolean then contains.TagInt := 1 else contains.TagInt := 0; btnAppend.Enabled := selectedCount > 0; btnReplace.Enabled := HasConcepts and (selectedCount > 0); end; function TValuesetSelectForm.selectedCount: integer; var contains : TFhirValueSetExpansionContains; begin result := 0; for contains in FExpansion.expansion.containsList do if contains.TagInt > 0 then inc(result); end; procedure TValuesetSelectForm.SetExpansion(const Value: TFHIRValueSet); begin FExpansion.Free; FExpansion := Value; end; procedure TValuesetSelectForm.SetSettings(const Value: TFHIRToolkitSettings); begin FSettings.Free; FSettings := Value; end; end.
unit CoreMechanicalState; interface uses BaseObjects, Registrator, Classes; type TCoreMechanicalState = class(TRegisteredIdObject) private FIsVisible: boolean; protected procedure AssignTo(Dest: TPersistent); override; public property IsVisible: boolean read FIsVisible write FIsVisible; function List(AListOption: TListOption = loBrief): string; override; constructor Create(ACollection: TIDObjects); override; end; TCoreMechanicalStates = class(TRegisteredIDObjects) private function GetItems(Index: integer): TCoreMechanicalState; public property Items[Index: integer]: TCoreMechanicalState read GetItems; constructor Create; override; end; TSlottingCoreMechanicalState = class(TRegisteredIDObject) private FMechanicalState: TCoreMechanicalState; protected procedure AssignTo(Dest: TPersistent); override; public property MechanicalState: TCoreMechanicalState read FMechanicalState write FMechanicalState; function List(AListOption: TListOption = loBrief): string; override; constructor Create(ACollection: TIDObjects); override; end; TSlottingCoreMechanicalStates = class(TRegisteredIDObjects) private function GetItems(Index: integer): TSlottingCoreMechanicalState; public property Items[Index: integer]: TSlottingCoreMechanicalState read GetItems; function AddCoreMechanicalState(ACoreMechanicalState: TCoreMechanicalState): TSlottingCoreMechanicalState; function GetCoreMechanicalState(ACoreMechanicalState: TCoreMechanicalState): TSlottingCoreMechanicalState; procedure RemoveCoreMechanicalState(ACoreMechanicalState: TCoreMechanicalState); function List(AListOption: TListOption = loBrief): string; override; constructor Create; override; end; implementation uses Facade, CoreMechanicalStatePoster, Contnrs, SysUtils; { TCoreMechanicalState } procedure TCoreMechanicalState.AssignTo(Dest: TPersistent); begin inherited; (Dest as TCoreMechanicalState).IsVisible := IsVisible; end; constructor TCoreMechanicalState.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Механическое состояние керна'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TCoreMechanicalStateDataPoster]; end; function TCoreMechanicalState.List(AListOption: TListOption): string; begin if AListOption = loBrief then Result := ShortName else Result := Name; end; { TCoreMechanicalStates } constructor TCoreMechanicalStates.Create; begin inherited; FObjectClass := TCoreMechanicalState; Poster := TMainFacade.GetInstance.DataPosterByClassType[TCoreMechanicalStateDataPoster]; end; function TCoreMechanicalStates.GetItems( Index: integer): TCoreMechanicalState; begin Result := inherited Items[Index] as TCoreMechanicalState; end; { TSlottingCoreMechanicalStates } function TSlottingCoreMechanicalStates.AddCoreMechanicalState( ACoreMechanicalState: TCoreMechanicalState): TSlottingCoreMechanicalState; begin Result := GetCoreMechanicalState(ACoreMechanicalState); if not Assigned(Result) then Result := inherited Add as TSlottingCoreMechanicalState; Result.MechanicalState := ACoreMechanicalState; Result.ID := ACoreMechanicalState.ID; end; constructor TSlottingCoreMechanicalStates.Create; begin inherited; FObjectClass := TSlottingCoreMechanicalState; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSlottingCoreMechanicalStateDataPoster]; OwnsObjects := true; end; function TSlottingCoreMechanicalStates.GetCoreMechanicalState( ACoreMechanicalState: TCoreMechanicalState): TSlottingCoreMechanicalState; var i: integer; begin Result := nil; for i := 0 to Count - 1 do if Items[i].MechanicalState = ACoreMechanicalState then begin Result := Items[i]; break; end; end; function TSlottingCoreMechanicalStates.GetItems( Index: integer): TSlottingCoreMechanicalState; begin Result := inherited Items[Index] as TSlottingCoreMechanicalState; end; function TSlottingCoreMechanicalStates.List( AListOption: TListOption): string; var i: integer; begin Result := ''; if Count > 1 then begin for i := 0 to Count - 1 do Result := Result + '; ' + Items[i].MechanicalState.List(AListOption); Result := trim(copy(Result, 2, Length(Result))); end else begin if Count = 1 then begin if Items[0].MechanicalState.IsVisible then Result := Items[0].List(); end; end; end; procedure TSlottingCoreMechanicalStates.RemoveCoreMechanicalState( ACoreMechanicalState: TCoreMechanicalState); var s: TSlottingCoreMechanicalState; begin s := GetCoreMechanicalState(ACoreMechanicalState); if Assigned(s) then MarkDeleted(s); end; { TSlottingCoreMechanicalState } procedure TSlottingCoreMechanicalState.AssignTo(Dest: TPersistent); var o: TSlottingCoreMechanicalState; begin inherited; o := Dest as TSlottingCoreMechanicalState; o.MechanicalState := MechanicalState; end; constructor TSlottingCoreMechanicalState.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Механическое состояние керна для долбления'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSlottingCoreMechanicalStateDataPoster]; end; function TSlottingCoreMechanicalState.List( AListOption: TListOption): string; begin Result := MechanicalState.List(AListOption) end; end.
unit Metrics.UnitM; interface uses System.SysUtils, System.Generics.Collections, System.Generics.Defaults, {--} Utils.IntegerArray, Metrics.UnitMethod; type TUnitMetrics = class private fName: string; fMethods: TObjectList<TUnitMethodMetrics>; public constructor Create(const aUnitName: string); destructor Destroy; override; property Name: string read fName; function MethodsCount(): Integer; function GetMethod(aIdx: Integer): TUnitMethodMetrics; function GetMethods: TList<TUnitMethodMetrics>; function GetMethodsSorted(const aNameofClass: string = '') : TArray<TUnitMethodMetrics>; procedure AddMethod(const aMethodMetics: TUnitMethodMetrics); end; implementation constructor TUnitMetrics.Create(const aUnitName: string); begin self.fName := aUnitName; fMethods := TObjectList<TUnitMethodMetrics>.Create(); end; destructor TUnitMetrics.Destroy; begin fMethods.Free; inherited; end; function TUnitMetrics.GetMethod(aIdx: Integer): TUnitMethodMetrics; begin Result := fMethods[aIdx]; end; function TUnitMetrics.GetMethods: TList<TUnitMethodMetrics>; begin Result := fMethods; end; function TUnitMetrics.GetMethodsSorted(const aNameofClass: string) : TArray<TUnitMethodMetrics>; var sorted: TList<TUnitMethodMetrics>; method: TUnitMethodMetrics; begin sorted := TList<TUnitMethodMetrics>.Create(); try if aNameofClass <> '' then begin for method in fMethods do if method.Name.StartsWith(aNameofClass + '.') then sorted.Add(method); end else sorted.AddRange(fMethods); sorted.Sort(TComparer<TUnitMethodMetrics>.Construct( function(const Left, Right: TUnitMethodMetrics): Integer begin Result := TComparer<string>.Default.Compare(Left.Name.ToUpper, Right.Name.ToUpper) end)); Result := sorted.ToArray; finally sorted.Free; end; end; function TUnitMetrics.MethodsCount: Integer; begin Result := fMethods.Count; end; procedure TUnitMetrics.AddMethod(const aMethodMetics: TUnitMethodMetrics); begin fMethods.Add(aMethodMetics); end; end.
unit UDAOPublicacion; interface uses SysUtils,StrUtils,Classes,DB,DBClient, zdataset, ZDbcIntfs, UDMConexion, UFolio, UImagen; type TDAOPublicacion = class private FQuery : TZquery; public constructor create; destructor destroy; Function AgregarFolio(P_DatoFolio: TFolio; P_CodPreimpreso: string): TClientDataSet; Procedure AgregarImagen(P_DatoImag: TImagen); Procedure CambiarEstadoCarpeta(P_IdenCarp: integer); procedure CancelarTransaccion; procedure FinalizarTransaccion; procedure InicarTransaccion; function ObtenerCantidadesCarpeta(P_IdenCarp: Integer; P_CodiCarp: string): TClientDataSet; function ObtenerDatosEstado(P_CodiCarp: string): TClientDataSet; //Sebastian Camacho 02/10/2018 function GetCodigoFolio(P_CodPreimpreso :string) :string; end; implementation {$REGION 'METODOS PROPIOS'} Function TDAOPublicacion.AgregarFolio(P_DatoFolio: TFolio; P_CodPreimpreso: string): TClientDataSet; begin try Result := TClientDataSet.Create(nil); with Result do begin FieldDefs.Add('IDFOLIO',ftLargeint, 0); FieldDefs.Add('CODIGOFOLIO',ftString, 15); CreateDataSet; end; with FQuery do begin Close; SQL.Clear; //Sebastian Camacho 03/10/2018 P_CodPreimpreso := ansileftstr(P_CodPreimpreso,Length(P_CodPreimpreso) - Length(ExtractFileExt(P_CodPreimpreso))); SQL.Add(Format('UPDATE %s.FOLIO SET TIPOFOLIO = :TIPOFOLIO WHERE CODPREIMPRESO = '+QuotedStr(P_CodPreimpreso), [DMConexion.esquema])); SQL.Add(' RETURNING idfolio, codigofolio'); ParamByName('TIPOFOLIO').AsString := P_DatoFolio.TipoFolio; Open; if not IsEmpty then begin First; while not Eof do begin Result.Append; Result.FieldByName('IDFOLIO').Value := FieldByName('IDFOLIO').Value; Result.FieldByName('CODIGOFOLIO').value := FieldByName('CODIGOFOLIO').AsString; Next end; end; end; except on E:exception do raise Exception.Create('No es posible indexar el Folio [' + P_DatoFolio.CodigoFolio + ']. ' + #10#13 + '* '+ e.Message); end; end; Procedure TDAOPublicacion.AgregarImagen(P_DatoImag: TImagen); begin try with FQuery do begin Close; SQL.Clear; SQL.Add(Format('INSERT INTO %s.IMAGEN (idfolio, version, rutalocal, rutaftp, nombreimagen, ' + 'servidorftp, ippublicacion, tamanobytes, ancho, alto, densidad, ' + 'usuario)',[DMConexion.esquema])); SQL.Add(Format(' VALUES (%d,%d,''%s'',''%s'',''%s'',''%s'', ''%s'', %d, %d, %d, %d, ''%s'' )', [P_DatoImag.IdFolio, P_DatoImag.Version, P_DatoImag.RutaLocal, P_DatoImag.RutaFTP, P_DatoImag.NombreImagen, P_DatoImag.ServidorFTP, P_DatoImag.IpPublicacion, P_DatoImag.TamanoBytes, P_DatoImag.Ancho, P_DatoImag.Alto, P_DatoImag.Densidad, Paramstr(1)])); ExecSQL; end; except on E:exception do raise Exception.Create('No es posible insertar la Imagen [' + P_DatoImag.NombreImagen + ']. ' + #10#13 + '* ' + e.Message); end; end; function TDAOPublicacion.GetCodigoFolio(P_CodPreimpreso :string):string; begin try with FQuery do begin Close; SQL.Clear; SQL.Add(Format('SELECT CODIGOFOLIO FROM %S.FOLIO WHERE CODPREIMPRESO = '+QuotedStr(P_CodPreimpreso),[DMConexion.esquema])); Open; First; Result := FieldByName('CODIGOFOLIO').AsString end; except on E:exception do raise Exception.Create('No es posible consultar el codigo del folio [' + P_CodPreimpreso + ']. ' + #10#13 + '* ' + e.Message); end; end; Procedure TDAOPublicacion.CambiarEstadoCarpeta(P_IdenCarp: integer); begin try with FQuery do begin Close; SQL.Clear; SQL.Add('SELECT p_idenflujnuev '); SQL.Add(Format('FROM %s.FNC_ASIGNARFLUJOCARPETA (%d,''%s'')', [DMConexion.esquema, p_IdenCarp, 'GUARDADO SATISFACTORIO'])); Open; end; except on E:exception do raise Exception.Create('No es posible actualizar el estado de la Carpeta ID [' + IntToStr(P_IdenCarp) + ']. ' + #10#13 + '* ' + e.Message); end; end; function TDAOPublicacion.ObtenerCantidadesCarpeta(P_IdenCarp: Integer; P_CodiCarp: string): TClientDataSet; begin try Result:= TClientDataSet.Create(nil); with Result do begin FieldDefs.Add('CODIGOCARPETA',ftString, 30); FieldDefs.Add('CLASECARPETA',ftString, 1); FieldDefs.Add('IDCARPETAALETA',ftLargeint, 0); FieldDefs.Add('CODIGOCARPETAALETA',ftString, 30); FieldDefs.Add('CANTIDADFOLIOS',ftInteger, 0); FieldDefs.Add('RUTAFTP',ftString, 150); CreateDataSet; end; with FQuery do begin Close; SQL.Clear; SQL.Add('SELECT CARP.CODIGOCARPETA, CARP.CLASECARPETA, CAAL.IDCARPETAALETA, '); SQL.Add(' CAAL.CODIGOCARPETAALETA, CAAL.CANTIDADFOLIOS,'); SQL.Add(' (SELECT IMAG1.RUTAFTP '); SQL.Add(Format(' FROM %s.CARPETAALETA CAAL1',[DMConexion.esquema])); SQL.Add(Format(' INNER JOIN %s.FOLIO FOLI1 ON (FOLI1.IDCARPETAALETA = CAAL1.IDCARPETAALETA)', [DMConexion.esquema])); SQL.Add(Format(' INNER JOIN %s.IMAGEN IMAG1 ON (IMAG1.IDFOLIO = FOLI1.IDFOLIO)', [DMConexion.esquema])); SQL.Add(' WHERE CAAL1.IDCARPETA = CARP.IDCARPETACREA' ); SQL.Add(' LIMIT 1) AS RUTAFTP' ); SQL.Add(Format('FROM %s.CARPETA CARP',[DMConexion.esquema])); SQL.Add(Format('INNER JOIN %s.CARPETAALETA CAAL ON CAAL.IDCARPETA=CARP.IDCARPETA',[DMConexion.esquema])); SQL.Add(' WHERE CARP.IDCARPETA = ' + IntToStr(P_IdenCarp)); SQL.Add(' AND CARP.HABILITADO AND CAAL.HABILITADO'); SQL.Add(' ORDER BY 1,4'); open; first; while (not Eof) do begin Result.Append; Result.FieldByName('CODIGOCARPETA').Value := FieldByName('CODIGOCARPETA').AsString; Result.FieldByName('CLASECARPETA').Value := FieldByName('CLASECARPETA').AsString; Result.FieldByName('IDCARPETAALETA').Value := FieldByName('IDCARPETAALETA').AsString; Result.FieldByName('CODIGOCARPETAALETA').Value := FieldByName('CODIGOCARPETAALETA').AsString; Result.FieldByName('CANTIDADFOLIOS').Value := FieldByName('CANTIDADFOLIOS').AsString; Result.FieldByName('RUTAFTP').Value := FieldByName('RUTAFTP').AsString; next; end; end; except on E:exception do raise Exception.Create('No es posible consultar cantidad de folios de la Carpeta (' + P_CodiCarp + ') [' + ParamStr(2) + '].' + #10#13 + '* '+ e.Message); end; end; function TDAOPublicacion.ObtenerDatosEstado(P_CodiCarp: string): TClientDataSet; begin try Result:= TClientDataSet.Create(nil); with Result do begin FieldDefs.Add('DESCRIPCIONTAREA',ftString, 50); FieldDefs.Add('IDCARPETA',ftInteger, 0); CreateDataSet; end; with FQuery do begin Close; SQL.Clear; SQL.Add('SELECT DISTINCT CASE WHEN TARE.DESCRIPCIONTAREA NOT IN (''PUBLICACIÓN'',''FIRMA Y ESTAMPA'') '); SQL.Add(' THEN ''OTRO'' ELSE TARE.DESCRIPCIONTAREA END AS DESCRIPCIONTAREA, '); SQL.Add(' CASE WHEN TARE.DESCRIPCIONTAREA = ''PUBLICACIÓN'' AND COUNT(*) = 1 '); SQL.Add(' THEN MAX(CARP.IDCARPETA) ELSE NULL END AS IDCARPETA '); SQL.Add(Format('FROM %s.CARPETA CARP',[DMConexion.esquema])); SQL.Add(Format('INNER JOIN %s.FLUJO FLUJ ON FLUJ.IDFLUJO = CARP.IDFLUJO',[DMConexion.esquema])); SQL.Add(Format('INNER JOIN %s.TAREA TARE ON TARE.IDTAREA = FLUJ.IDTAREAPROXIMA',[DMConexion.esquema])); SQL.Add(' WHERE CARP.CODIGOCARPETA = ' + QuotedStr(P_CodiCarp)); SQL.Add(' AND CARP.HABILITADO AND FLUJ.HABILITADO AND TARE.HABILITADO'); SQL.Add(' GROUP BY TARE.DESCRIPCIONTAREA'); open; first; while (not Eof) do begin Result.Append; Result.FieldByName('DESCRIPCIONTAREA').Value := FieldByName('DESCRIPCIONTAREA').AsString; Result.FieldByName('IDCARPETA').Value := FieldByName('IDCARPETA').value; next; end; end; except on E:exception do raise Exception.Create('No es posible consultar Estados de Carpetas de Creación e Inseciones del ' + 'código [' + P_CodiCarp + '] [' + ParamStr(2) + '].' + #10#13 + '* '+ e.Message); end; end; {$ENDREGION} {$REGION 'CONTROL DE TRANSACCIONES'} procedure TDAOPublicacion.CancelarTransaccion; begin try with FQuery do begin if Connection.InTransaction then Connection.Rollback; Connection.TransactIsolationLevel:= TZTransactIsolationLevel.tinone; end; finally end; end; procedure TDAOPublicacion.InicarTransaccion; begin try with FQuery do begin Connection.TransactIsolationLevel := TZTransactIsolationLevel.tiReadCommitted; Connection.StartTransaction; end; except on E:exception do raise Exception.Create('No es posible inicializar Administrador de Transacciones. ' + #10#13 + '* ' + e.Message); end; end; procedure TDAOPublicacion.FinalizarTransaccion; begin try with FQuery do begin Connection.commit; Connection.TransactIsolationLevel:= TZTransactIsolationLevel.tinone; end; except on E:exception do raise Exception.Create('No es posible finalizar el Administrador de Transacciones. ' + #10#13 + '* ' + e.Message); end; end; {$ENDREGION} {$REGION 'CONSTRUCTOR Y DESTRUCTOR'} constructor TDAOPublicacion.create; begin FQuery:= TZQuery.create(nil); FQuery.Connection:= DMConexion.ZConexion; end; destructor TDAOPublicacion.destroy; begin FQuery.Close; FQuery.Connection.Disconnect; FQuery.free; end; {$ENDREGION} end.
unit liste; {****************************** ****************************** ****** ****** ***** Verkettete Liste ***** ****** ****** ****************************** ****************************** } INTERFACE type nodep =^nodet; nodet = object number:longint; next,prev:nodep; constructor init; destructor done; end; listp =^listt; listt = object anzahl,laufende_nr:longint; actual,first,last:nodep; constructor init; destructor done; procedure insert(insnode:nodep); procedure delete; procedure next; procedure prev; procedure setfirst; procedure setlast; function get:nodep; function is_last:boolean; function is_first:boolean; end; IMPLEMENTATION constructor nodet.init; begin number:=0; next:=nil; prev:=nil; end; destructor nodet.done; begin end; constructor listt.init; begin new(actual, init); actual^.next:=actual; actual^.prev:=actual; first:=actual; last:=actual; anzahl:=1; laufende_nr:=1; actual^.number:=laufende_nr; end; destructor listt.done; var temp:nodep; begin actual:=last; while not (last=first) do begin temp:=actual^.prev; temp^.next:=temp; actual^.done; dispose(actual); actual:=temp; last:=actual; end; first^.done; dispose(first); end; procedure listt.delete; var temp:nodep; begin if actual<>first then begin temp:=actual^.next; actual^.prev^.next:=temp; temp^.prev:=actual^.prev; actual^.done; dispose(actual); actual:=temp; end; dec(anzahl); end; procedure listt.insert(insnode:nodep); begin if first=last then begin end else if last=actual then begin writelN('oink'); last:=insnode; actual^.next:=insnode; insnode^.prev:=actual; insnode^.next:=insnode; end else begin insnode^.prev:=actual; insnode^.next:=actual^.next; insnode^.next^.prev:=insnode; actual^.next:=insnode; end; inc(anzahl); inc(laufende_nr); actual^.number:=laufende_nr; actual:=insnode; end; procedure listt.next; begin actual:=actual^.next end; procedure listt.prev; begin actual:=actual^.prev end; procedure listt.setfirst; begin actual:=first end; procedure listt.setlast; begin actual:=last end; function listt.get:nodep; begin get:=actual end; function listt.is_first:boolean; begin is_first:=first=actual end; function listt.is_last:boolean; begin is_last:=last=actual end; begin end.
{***************************************************************************} { TIdSmtpEx component } { for Delphi base Indy9 } { } { 继承TIdSMTP组件用于解决以下问题: } { 1、SendBody方法同时发送TIdText和TIdAttachment时TIdText不发送的问题 } { 2、SendHeader主题长度被截断问题 } { written by mini188 } { Email : mini188.com@qq.com } { } {***************************************************************************} unit IdSMTPEx; interface uses SysUtils, IdComponent, IdSMTP, IdMessage, IdTCPConnection, IdTCPClient, IdMessageClient, IdBaseComponent; type TIdSmtpEx = class(TIdSMTP) protected procedure SendHeader(AMsg: TIdMessage); override; procedure SendBody(AMsg: TIdMessage); override; end; implementation uses IdTCPStream, IdCoderHeader, IdCoderQuotedPrintable, IdGlobal, IdMessageCoderMIME, IdResourceStrings, IdHeaderList; { TIdSmtpEx } /// <summary> /// 发送内容 /// 此方法是为了解决发送TIdText 的bug /// </summary> /// <param name="AMsg"></param> procedure TIdSmtpEx.SendBody(AMsg: TIdMessage); var i: Integer; LAttachment: TIdAttachment; LBoundary: string; LDestStream: TIdTCPStream; LMIMEAttachments: boolean; ISOCharset: string; HeaderEncoding: Char; { B | Q } TransferEncoding: TTransfer; procedure WriteTextPart(ATextPart: TIdText); var Data: string; i: Integer; begin if Length(ATextPart.ContentType) = 0 then ATextPart.ContentType := 'text/plain'; {do not localize} if Length(ATextPart.ContentTransfer) = 0 then ATextPart.ContentTransfer := 'quoted-printable'; {do not localize} WriteLn('Content-Type: ' + ATextPart.ContentType); {do not localize} WriteLn('Content-Transfer-Encoding: ' + ATextPart.ContentTransfer); {do not localize} WriteStrings(ATextPart.ExtraHeaders); WriteLn(''); // TODO: Provide B64 encoding later // if AnsiSameText(ATextPart.ContentTransfer, 'base64') then begin // LEncoder := TIdEncoder3to4.Create(nil); if AnsiSameText(ATextPart.ContentTransfer, 'quoted-printable') then begin for i := 0 to ATextPart.Body.Count - 1 do begin if Copy(ATextPart.Body[i], 1, 1) = '.' then begin ATextPart.Body[i] := '.' + ATextPart.Body[i]; end; Data := TIdEncoderQuotedPrintable.EncodeString(ATextPart.Body[i] + EOL); if TransferEncoding = iso2022jp then Write(Encode2022JP(Data)) else Write(Data); end; end else begin WriteStrings(ATextPart.Body); end; WriteLn(''); end; begin LMIMEAttachments := AMsg.Encoding = meMIME; LBoundary := ''; InitializeISO(TransferEncoding, HeaderEncoding, ISOCharSet); BeginWork(wmWrite); try if AMsg.MessageParts.AttachmentCount > 0 then begin if LMIMEAttachments then begin WriteLn('This is a multi-part message in MIME format'); {do not localize} WriteLn(''); if AMsg.MessageParts.RelatedPartCount > 0 then begin LBoundary := IndyMultiPartRelatedBoundary; end else begin LBoundary := IndyMIMEBoundary; end; WriteLn('--' + LBoundary); end else begin // It's UU, write the body WriteBodyText(AMsg); WriteLn(''); end; if AMsg.MessageParts.TextPartCount >= 1 then//原先是'>'修改为'>='用于支持 TIdText的发送 begin WriteLn('Content-Type: multipart/alternative; '); {do not localize} WriteLn(' boundary="' + IndyMultiPartAlternativeBoundary + '"'); {do not localize} WriteLn(''); for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts.Items[i] is TIdText then begin WriteLn('--' + IndyMultiPartAlternativeBoundary); DoStatus(hsStatusText, [RSMsgClientEncodingText]); WriteTextPart(AMsg.MessageParts.Items[i] as TIdText); WriteLn(''); end; end; WriteLn('--' + IndyMultiPartAlternativeBoundary + '--'); end else begin if LMIMEAttachments then begin WriteLn('Content-Type: text/plain'); {do not localize} WriteLn('Content-Transfer-Encoding: 7bit'); {do not localize} WriteLn(''); WriteBodyText(AMsg); end; end; // Send the attachments for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts[i] is TIdAttachment then begin LAttachment := TIdAttachment(AMsg.MessageParts[i]); DoStatus(hsStatusText, [RSMsgClientEncodingAttachment]); if LMIMEAttachments then begin WriteLn(''); WriteLn('--' + LBoundary); if Length(LAttachment.ContentTransfer) = 0 then begin LAttachment.ContentTransfer := 'base64'; {do not localize} end; if Length(LAttachment.ContentDisposition) = 0 then begin LAttachment.ContentDisposition := 'attachment'; {do not localize} end; if (LAttachment.ContentTransfer = 'base64') {do not localize} and (Length(LAttachment.ContentType) = 0) then begin LAttachment.ContentType := 'application/octet-stream'; {do not localize} end; WriteLn('Content-Type: ' + LAttachment.ContentType + ';'); {do not localize} WriteLn(' name="' + ExtractFileName(LAttachment.FileName) + '"'); {do not localize} WriteLn('Content-Transfer-Encoding: ' + LAttachment.ContentTransfer); {do not localize} WriteLn('Content-Disposition: ' + LAttachment.ContentDisposition +';'); {do not localize} WriteLn(' filename="' + ExtractFileName(LAttachment.FileName) + '"'); {do not localize} WriteStrings(LAttachment.ExtraHeaders); WriteLn(''); end; LDestStream := TIdTCPStream.Create(Self); try TIdAttachment(AMsg.MessageParts[i]).Encode(LDestStream); finally FreeAndNil(LDestStream); end; WriteLn(''); end; end; if LMIMEAttachments then begin WriteLn('--' + LBoundary + '--'); end; end // S.G. 21/2/2003: If the user added a single texpart message without filling the body // S.G. 21/2/2003: we still need to send that out else if (AMsg.MessageParts.TextPartCount > 1) or ((AMsg.MessageParts.TextPartCount = 1) and (AMsg.Body.Count = 0)) then begin WriteLn('This is a multi-part message in MIME format'); {do not localize} WriteLn(''); for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts.Items[i] is TIdText then begin WriteLn('--' + IndyMIMEBoundary); DoStatus(hsStatusText, [RSMsgClientEncodingText]); WriteTextPart(AMsg.MessageParts.Items[i] as TIdText); end; end; WriteLn('--' + IndyMIMEBoundary + '--'); end else begin DoStatus(hsStatusText, [RSMsgClientEncodingText]); // Write out Body //TODO: Why just iso2022jp? Why not someting generic for all MBCS? Or is iso2022jp special? if TransferEncoding = iso2022jp then begin for i := 0 to AMsg.Body.Count - 1 do begin if Copy(AMsg.Body[i], 1, 1) = '.' then begin WriteLn('.' + Encode2022JP(AMsg.Body[i])); end else begin WriteLn(Encode2022JP(AMsg.Body[i])); end; end; end else begin WriteBodyText(AMsg); end; end; finally EndWork(wmWrite); end; end; procedure TIdSmtpEx.SendHeader(AMsg: TIdMessage); var LHeaders: TIdHeaderList; begin LHeaders := AMsg.GenerateHeader; try //解决标题过长时导致的收件方解码错误问题 LHeaders.Text := StringReplace(LHeaders.Text, #13#10#13#10, #13#10, [rfReplaceAll]); WriteStrings(LHeaders); finally FreeAndNil(LHeaders); end; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.metadata.db.factory; interface uses SysUtils, Rtti, Generics.Collections, dbebr.factory.interfaces, dbcbr.metadata.register, dbcbr.metadata.extract, dbcbr.database.mapping, dbcbr.database.abstract; type TMetadataDBAbstract = class abstract protected FOwner: TDatabaseAbstract; FConnection: IDBConnection; FDatabaseMetadata: TCatalogMetadataAbstract; procedure ExtractCatalogs; virtual; abstract; procedure ExtractSchemas; virtual; abstract; procedure ExtractTables; virtual; abstract; public constructor Create(AOwner: TDatabaseAbstract; AConnection: IDBConnection); virtual; destructor Destroy; override; procedure ExtractMetadata(ACatalogMetadata: TCatalogMetadataMIK); virtual; abstract; property DatabaseMetadata: TCatalogMetadataAbstract read FDatabaseMetadata; end; TMetadataDBFactory = class(TMetadataDBAbstract) public procedure ExtractMetadata(ACatalogMetadata: TCatalogMetadataMIK); override; end; implementation { TMetadataDBAbstract } constructor TMetadataDBAbstract.Create(AOwner: TDatabaseAbstract; AConnection: IDBConnection); begin FOwner := AOwner; FConnection := AConnection; end; destructor TMetadataDBAbstract.Destroy; begin inherited; end; { TMetadataFactory } procedure TMetadataDBFactory.ExtractMetadata(ACatalogMetadata: TCatalogMetadataMIK); begin inherited; if ACatalogMetadata = nil then raise Exception.Create('Antes de executar a extração do metadata, atribua a propriedade o catalogue a set preenchido em "DatabaseMetadata.CatalogMetadata"'); // Extrair database metadata FDatabaseMetadata := TMetadataRegister.GetInstance.GetMetadata(FConnection.GetDriverName); FDatabaseMetadata.Connection := FConnection; FDatabaseMetadata.CatalogMetadata := ACatalogMetadata; if FOwner <> nil then FDatabaseMetadata.ModelForDatabase := FOwner.ModelForDatabase; try FDatabaseMetadata.GetDatabaseMetadata; finally FDatabaseMetadata.CatalogMetadata := nil; FDatabaseMetadata.Connection := nil; end; end; end.
unit AsyncIO.Detail; interface uses WinAPI.Windows, System.SysUtils, System.Classes, AsyncIO, AsyncIO.OpResults; type IOCPContext = class strict private FOverlapped: TOverlapped; function GetOverlapped: POverlapped; function GetOverlappedOffset: UInt64; procedure SetOverlappedOffset(const Value: UInt64); public constructor Create; destructor Destroy; override; property Overlapped: POverlapped read GetOverlapped; property OverlappedOffset: UInt64 read GetOverlappedOffset write SetOverlappedOffset; procedure ExecHandler(const res: OpResult; const transferred: Int64); virtual; class function FromOverlapped(const Overlapped: POverlapped): IOCPContext; end; HandlerContext = class(IOCPContext) strict private FHandler: CompletionHandler; public constructor Create(const Handler: CompletionHandler); procedure ExecHandler(const res: OpResult; const transferred: Int64); override; property Handler: CompletionHandler read FHandler; end; OpHandlerContext = class(IOCPContext) strict private FHandler: OpHandler; public constructor Create(const Handler: OpHandler); procedure ExecHandler(const res: OpResult; const transferred: Int64); override; property Handler: OpHandler read FHandler; end; IOHandlerContext = class(IOCPContext) strict private FHandler: IOHandler; public constructor Create(const Handler: IOHandler); procedure ExecHandler(const res: OpResult; const transferred: Int64); override; property Handler: IOHandler read FHandler; end; procedure IOServicePostCompletion(const Service: IOService; const BytesTransferred: DWORD; const Ctx: IOCPContext); procedure IOServiceAssociateHandle(const Service: IOService; const Handle: THandle); type IOServiceIOCP = interface ['{B26EA70A-4501-4232-B07F-1495FD945979}'] procedure AssociateHandle(const Handle: THandle); procedure PostCompletion(const BytesTransferred: DWORD; const Ctx: IOCPContext); end; IOServiceImpl = class(TInterfacedObject, IOService, IOServiceIOCP) strict private FIOCP: THandle; FStopped: integer; function GetStopped: boolean; function DoPollOne(const Timeout: DWORD): integer; procedure DoDequeueStoppedHandlers; protected property IOCP: THandle read FIOCP; public constructor Create(const MaxConcurrentThreads: Cardinal); destructor Destroy; override; procedure AssociateHandle(const Handle: THandle); procedure PostCompletion(const BytesTransferred: DWORD; const Ctx: IOCPContext); function Poll: Int64; function PollOne: Int64; function Run: Int64; function RunOne: Int64; procedure Post(const Handler: CompletionHandler); procedure Stop; property Stopped: boolean read GetStopped; end; AsyncStreamImplBase = class(TInterfacedObject, AsyncStream) strict private FService: IOService; public constructor Create(const Service: IOService); function GetService: IOService; procedure AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler); virtual; abstract; procedure AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler); virtual; abstract; property Service: IOService read FService; end; AsyncMemoryStreamImpl = class(AsyncStreamImplBase, AsyncMemoryStream) strict private FData: TBytes; FOffset: UInt64; public constructor Create(const Service: IOService; const Data: TBytes); destructor Destroy; override; function GetData: TBytes; procedure AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler); override; procedure AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler); override; property Data: TBytes read FData; end; AsyncHandleStreamImpl = class(AsyncStreamImplBase, AsyncHandleStream) strict private FHandle: THandle; FOffset: UInt64; public constructor Create(const Service: IOService; const Handle: THandle); destructor Destroy; override; function GetHandle: THandle; procedure AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler); override; procedure AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler); override; property Handle: THandle read FHandle; end; implementation uses System.Math; {$POINTERMATH ON} const COMPLETION_KEY_EXIT = 0; COMPLETION_KEY_OPERATION = 1; COMPLETION_KEY_OPERATION_DIR = 2; procedure IOServicePostCompletion(const Service: IOService; const BytesTransferred: DWORD; const Ctx: IOCPContext); var iocpService: IOServiceIOCP; begin iocpService := Service as IOServiceIOCP; iocpService.PostCompletion(BytesTransferred, Ctx); end; procedure IOServiceAssociateHandle(const Service: IOService; const Handle: THandle); var iocpService: IOServiceIOCP; begin iocpService := Service as IOServiceIOCP; iocpService.AssociateHandle(Handle); end; { IOCPContext } constructor IOCPContext.Create; begin inherited Create; // WriteLn(Format('DEBUG overlapped created: %.8x', [NativeUInt(Self.Overlapped)])); end; destructor IOCPContext.Destroy; begin // WriteLn(Format('DEBUG overlapped destroyed: %.8x', [NativeUInt(Self.Overlapped)])); inherited; end; procedure IOCPContext.ExecHandler(const res: OpResult; const transferred: Int64); begin raise ENotImplemented.Create('Invalid context handler'); end; class function IOCPContext.FromOverlapped(const Overlapped: POverlapped): IOCPContext; type PUInt8 = ^UInt8; begin result := TObject(PUInt8(Overlapped) - SizeOf(pointer)) as IOCPContext; end; function IOCPContext.GetOverlapped: POverlapped; begin result := @FOverlapped; end; function IOCPContext.GetOverlappedOffset: UInt64; begin result := FOverlapped.Offset + (UInt64(FOverlapped.OffsetHigh) shl 32); end; procedure IOCPContext.SetOverlappedOffset(const Value: UInt64); begin FOverlapped.Offset := UInt32(Value and $ffffffff); FOverlapped.OffsetHigh := UInt32((Value shr 32) and $ffffffff); end; { HandlerContext } constructor HandlerContext.Create(const Handler: CompletionHandler); begin inherited Create; FHandler := Handler; end; procedure HandlerContext.ExecHandler(const res: OpResult; const transferred: Int64); begin Handler(); end; { OpHandlerContext } constructor OpHandlerContext.Create(const Handler: OpHandler); begin inherited Create; FHandler := Handler; end; procedure OpHandlerContext.ExecHandler(const res: OpResult; const transferred: Int64); begin Handler(res); end; { IOHandlerContext } constructor IOHandlerContext.Create(const Handler: IOHandler); begin inherited Create; FHandler := Handler; end; procedure IOHandlerContext.ExecHandler(const res: OpResult; const transferred: Int64); begin Handler(res, transferred); end; { IOServiceImpl } procedure IOServiceImpl.AssociateHandle(const Handle: THandle); var cph: THandle; begin // Associate with IOCP cph := CreateIoCompletionPort(Handle, IOCP, COMPLETION_KEY_OPERATION, 0); if (cph = 0) then RaiseLastOSError; end; constructor IOServiceImpl.Create(const MaxConcurrentThreads: Cardinal); begin inherited Create; FIOCP := CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, MaxConcurrentThreads); if (FIOCP = 0) then begin FIOCP := INVALID_HANDLE_VALUE; RaiseLastOSError; end; end; destructor IOServiceImpl.Destroy; begin if (not Stopped) then begin Stop; DoDequeueStoppedHandlers; end; if (IOCP <> INVALID_HANDLE_VALUE) then CloseHandle(IOCP); inherited; end; procedure IOServiceImpl.DoDequeueStoppedHandlers; var r: integer; begin if not Stopped then exit; // dequeue all pending handlers while True do begin r := DoPollOne(0); if (r = 0) then break; end; end; function IOServiceImpl.DoPollOne(const Timeout: DWORD): integer; var success: boolean; overlapped: POverlapped; completionKey: ULONG_PTR; transferred: DWORD; res: OpResult; ctx: IOCPContext; begin result := 0; ctx := nil; overlapped := nil; success := GetQueuedCompletionStatus(IOCP, transferred, completionKey, overlapped, Timeout); // WriteLn('DEBUG completion key: ', completionKey); // WriteLn(Format('DEBUG completion overlapped: %.8x', [NativeUInt(overlapped)])); if success then begin res := SystemResults.Success; end else begin res := SystemResults.LastError; if Assigned(overlapped) then begin // failed IO operation, trigger handler end else if (res = SystemResults.WaitTimeout) then begin // nothing to do exit; end else res.RaiseException(); end; if completionKey = COMPLETION_KEY_EXIT then exit; Assert((completionKey = COMPLETION_KEY_OPERATION) or (completionKey = COMPLETION_KEY_OPERATION_DIR), 'Invalid completion key'); ctx := IOCPContext.FromOverlapped(overlapped); // WriteLn(Format('DEBUG exec context: %.8x', [NativeUInt(ctx)])); try result := 1; if not Stopped then ctx.ExecHandler(res, transferred); finally ctx.Free; end; end; function IOServiceImpl.GetStopped: boolean; begin result := FStopped <> 0; end; function IOServiceImpl.Poll: Int64; var r: Int64; begin result := 0; while True do begin r := PollOne(); if (r = 0) then break; result := result + 1; end; end; function IOServiceImpl.PollOne: Int64; begin result := 0; if Stopped then begin DoDequeueStoppedHandlers; exit; end; result := DoPollOne(0); end; procedure IOServiceImpl.Post(const Handler: CompletionHandler); var ctx: HandlerContext; begin if Stopped then raise EIOServiceStopped.Create('Cannot post to a stopped IOService'); ctx := HandlerContext.Create(Handler); PostQueuedCompletionStatus(IOCP, 0, COMPLETION_KEY_OPERATION, ctx.Overlapped); end; procedure IOServiceImpl.PostCompletion(const BytesTransferred: DWORD; const Ctx: IOCPContext); begin if Stopped then raise EIOServiceStopped.Create('Cannot post to a stopped IOService'); // WriteLn(Format('DEBUG post overlapped: %.8x', [NativeUInt(ctx.Overlapped)])); PostQueuedCompletionStatus(IOCP, BytesTransferred, COMPLETION_KEY_OPERATION_DIR, Ctx.Overlapped); end; function IOServiceImpl.Run: Int64; var r: Int64; begin result := 0; while True do begin r := RunOne(); if (r = 0) and (Stopped) then break; result := result + 1; end; end; function IOServiceImpl.RunOne: Int64; begin result := 0; if Stopped then begin DoDequeueStoppedHandlers; exit; end; while (result <= 0) and (not Stopped) do begin // From Boost.ASIO: // Timeout to use with GetQueuedCompletionStatus. Some versions of windows // have a "bug" where a call to GetQueuedCompletionStatus can appear stuck // even though there are events waiting on the queue. Using a timeout helps // to work around the issue. result := DoPollOne(500); end; end; procedure IOServiceImpl.Stop; begin InterlockedExchange(FStopped, 1); CancelIo(IOCP); PostQueuedCompletionStatus(IOCP, 0, COMPLETION_KEY_EXIT, nil); end; { AsyncStreamImplBase } constructor AsyncStreamImplBase.Create(const Service: IOService); begin inherited Create; FService := Service; end; function AsyncStreamImplBase.GetService: IOService; begin result := FService; end; { AsyncMemoryStreamImpl } procedure AsyncMemoryStreamImpl.AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler); var ctx: IOHandlerContext; remainingData: Int64; bytesRead: UInt32; begin ctx := IOHandlerContext.Create(Handler); if (Length(Data) > 0) then begin remainingData := Length(Data) - FOffset; bytesRead := Min(Buffer.Size, remainingData); end else begin bytesRead := 0; end; Move(Data[FOffset], Buffer.Data^, bytesRead); FOffset := FOffset + bytesRead; IOServicePostCompletion(Service, bytesRead, ctx); end; procedure AsyncMemoryStreamImpl.AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler); var ctx: IOHandlerContext; bytesWritten: UInt32; newSize: Int64; begin ctx := IOHandlerContext.Create(Handler); bytesWritten := Buffer.Size; newSize := bytesWritten + FOffset; if (newSize > Length(Data)) then begin try SetLength(FData, newSize); except on E: EOutOfMemory do bytesWritten := 0; end; end; Move(Buffer.Data^, Data[FOffset], bytesWritten); FOffset := FOffset + bytesWritten; IOServicePostCompletion(Service, bytesWritten, ctx); end; constructor AsyncMemoryStreamImpl.Create(const Service: IOService; const Data: TBytes); begin inherited Create(Service); FData := Data; end; destructor AsyncMemoryStreamImpl.Destroy; begin FData := nil; inherited; end; function AsyncMemoryStreamImpl.GetData: TBytes; begin result := FData; end; { AsyncHandleStreamImpl } procedure AsyncHandleStreamImpl.AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler); var bytesRead: DWORD; ctx: IOHandlerContext; res: boolean; ec: DWORD; begin ctx := IOHandlerContext.Create( procedure(const Res: OpResult; const BytesTransferred: UInt64) begin FOffset := FOffset + BytesTransferred; Handler(Res, BytesTransferred); end ); // offset is ignored if handle does not support it ctx.OverlappedOffset := FOffset; bytesRead := 0; res := ReadFile(Handle, Buffer.Data^, Buffer.Size, bytesRead, ctx.Overlapped); if (not res) then begin ec := GetLastError; if (ec <> ERROR_IO_PENDING) then RaiseLastOSError(ec); end else begin // completed directly, but completion entry is queued by manager // no async action, call handler directly // IOServicePostCompletion(Service, bytesRead, ctx); end; end; procedure AsyncHandleStreamImpl.AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler); var bytesWritten: DWORD; ctx: IOHandlerContext; res: boolean; ec: DWORD; begin ctx := IOHandlerContext.Create( procedure(const Res: OpResult; const BytesTransferred: UInt64) begin FOffset := FOffset + BytesTransferred; Handler(Res, BytesTransferred); end ); // offset is ignored if handle does not support it ctx.OverlappedOffset := FOffset; res := WriteFile(Handle, Buffer.Data^, Buffer.Size, bytesWritten, ctx.Overlapped); if (not res) then begin ec := GetLastError; if (ec <> ERROR_IO_PENDING) then RaiseLastOSError(ec); end else begin // completed directly, but completion entry is queued by manager // no async action, call handler directly // IOServicePostCompletion(Service, bytesWritten, ctx); end; end; constructor AsyncHandleStreamImpl.Create(const Service: IOService; const Handle: THandle); begin inherited Create(Service); FHandle := Handle; end; destructor AsyncHandleStreamImpl.Destroy; begin CloseHandle(FHandle); inherited; end; function AsyncHandleStreamImpl.GetHandle: THandle; begin result := FHandle; end; end.
{*******************************************************} { } { AddListViewGroup.pas { Copyright @2014/5/15 10:26:32 by 姜梁 { } { 功能描述:对list动态添加group。基于win消息提高效率 { 函数说明: {*******************************************************} unit AddListViewGroup; interface uses CommCtrl, Windows; type TLVGROUP = record cbSize: UINT; mask: UINT; pszHeader: LPWSTR; cchHeader: Integer; pszFooter: LPWSTR; cchFooter: Integer; iGroupIdL: Integer; stateMask: UINT; state: UINT; uAlign: UINT; end; type tagLVITEMA = packed record mask: UINT; iItem: Integer; iSubItem: Integer; state: UINT; stateMask: UINT; pszText: PAnsiChar; cchTextMax: Integer; iImage: Integer; lParam: lParam; iIndent: Integer; iGroupId: Integer; cColumns: UINT; puColumns: PUINT; end; const LVM_ENABLEGROUPVIEW = LVM_FIRST + 157; LVM_MOVEITEMTOGROUP = LVM_FIRST + 154; LVM_INSERTGROUP = LVM_FIRST + 145; function HelperAddNewGroup(fileName:string;groupIndex:Integer;ListHandle:Cardinal):Boolean; function HelperAddNewIteToGroup(ItemIndex,groupIndex:Integer;ListHandle:Cardinal):Boolean; implementation /// <summary> /// 新加一个group /// </summary> /// <param name="filename">文件名</param> /// <param name="groupIndex">添加的组号</param> /// <param name="listviewhandle">list的hanlde</param> function HelperAddNewGroup(fileName:string;groupIndex:Integer;ListHandle:Cardinal):Boolean; var LvGroup:TLVGROUP; begin FillChar(LvGroup, SizeOf(TLVGROUP), 0); with LvGroup do begin cbSize := SizeOf(TLVGROUP); mask := LVGF_HEADER or LVGF_ALIGN or LVGF_GROUPID; pszHeader := PChar(fileName); cchHeader := Length(LvGroup.pszHeader); iGroupIdL := groupIndex; uAlign := LVGA_HEADER_CENTER; end; SendMessage(ListHandle, LVM_INSERTGROUP, 0, Longint(@LvGroup)); end; /// <summary> /// 新加一个item到group /// </summary> /// <param name="ItemIndex">item的序号</param> /// <param name="groupIndex">需要添加到的组号</param> /// <param name="listviewhandle">list的hanlde</param> function HelperAddNewIteToGroup(ItemIndex,groupIndex:Integer;ListHandle:Cardinal):Boolean; var LvItemA:tagLVITEMA; begin with LvItemA do begin FillChar(LvItemA, SizeOf(TLvItemA), 0); mask := LVIF_GROUPID; iItem := ItemIndex; iGroupId := groupIndex; end; SendMessage(ListHandle, LVM_SETITEM, 0, Longint(@LvItemA)); end; end.
{ Catarinka TStringLoop, TSepStringLoop Loops through a string list or a separated string Copyright (c) 2003-2014 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } unit CatStringLoop; interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils; {$ELSE} Classes, SysUtils; {$ENDIF} type TStringLoop = class protected fCSV: TStringList; fCurrent: string; fIsCSV: boolean; fList: TStringList; fPosition: integer; function GetCount: integer; function GetCountAsStr: string; function GetCurrentLower: string; function GetCurrentUpper: string; function GetLine(const l: integer): string; procedure SetCurrent(const s: string); procedure SetLine(const l: integer; const v: string); public constructor Create(const sl: tstrings = nil); destructor Destroy; override; procedure Load(const sl: tstrings); procedure LoadFromString(const s: string); procedure LoadFromFile(const filename: string); procedure Reset; procedure Stop; procedure Clear; function Found: boolean; function GetValue(const s: string): string; procedure SetValue(const s: string; const v: string); function Index(const zerostart: boolean = true): integer; function IndexAsStr: string; function IndexOf(const s: string): integer; function Contains(const s: string; const casesensitive: boolean = true): boolean; procedure Delete; property Lines[const l: integer]: string read GetLine write SetLine; property Values[const s: string]: string read GetValue write SetValue; default; // properties property Count: integer read GetCount; property CountAsStr:string read GetCountAsStr; property Current: string read fCurrent write SetCurrent; property CurrentLower: string read GetCurrentLower; property CurrentUpper: string read GetCurrentUpper; property IsCSV: boolean read fIsCSV write fIsCSV; property List: TStringList read FList; end; type TSepStringLoop = class protected fCount: integer; fCurrent: string; fPos: integer; fTags: string; // a separated string fSeparator: string; public constructor Create(const tags: string = ''; const asep: string = '|'); destructor Destroy; override; function Found: boolean; property Count: integer read fCount; property Current: string read fCurrent; property Position: integer read fPos; property Separator: string read fSeparator write fSeparator; property tags: string read fTags write fTags; end; implementation uses CatStrings; function TStringLoop.GetCount: integer; begin result := fList.Count; end; procedure TStringLoop.Delete; begin fList.Delete(FPosition - 1); end; function TStringLoop.Contains(const s: string; const casesensitive: boolean = true): boolean; procedure check(substr, str: string); begin if pos(substr, str) <> 0 then result := true; end; begin result := false; case casesensitive of false: check(uppercase(s), uppercase(FCurrent)); true: check(s, FCurrent); end; end; procedure TStringLoop.Stop; begin FPosition := fList.Count; end; function TStringLoop.GetCurrentUpper: string; begin result := uppercase(FCurrent); end; function TStringLoop.GetCurrentLower: string; begin result := lowercase(FCurrent); end; function TStringLoop.IndexAsStr: string; begin result := inttostr(FPosition); end; function TStringLoop.GetCountAsStr: string; begin result := inttostr(fList.Count); end; function TStringLoop.IndexOf(const s: string): integer; begin result := fList.IndexOf(s); end; function TStringLoop.Index(const zerostart: boolean = true): integer; begin result := FPosition; if zerostart then result := FPosition - 1; end; procedure TStringLoop.Clear; begin fList.Clear; Reset; end; function TStringLoop.GetValue(const s: string): string; begin if isCSV = false then fcsv.commatext := FCurrent; result := fcsv.Values[s]; end; procedure TStringLoop.SetValue(const s, v: string); begin if isCSV = false then fcsv.commatext := FCurrent; fcsv.Values[s] := v; SetCurrent(fcsv.commatext); end; function TStringLoop.GetLine(const l: integer): string; begin if isCSV = false then fcsv.commatext := FCurrent; try result := fcsv[l]; except end; end; procedure TStringLoop.SetLine(const l: integer; const v: string); begin if isCSV = false then fcsv.commatext := FCurrent; try fcsv[l] := v; except end; SetCurrent(fcsv.commatext); end; procedure TStringLoop.SetCurrent(const s: string); begin FCurrent := s; fList[FPosition - 1] := s; end; function TStringLoop.Found: boolean; var i: integer; begin result := false; i := FPosition; if i < fList.Count then begin result := true; FCurrent := fList[i]; // If each line is a CSV string and the IsCSV property is set // to true, it should be faster to retrive a value (via GetValue). if isCSV then fcsv.commatext := FCurrent; FPosition := FPosition + 1; end; end; procedure TStringLoop.Reset; begin FPosition := 0; FCurrent := emptystr; fcsv.Clear; end; procedure TStringLoop.LoadFromFile(const filename: string); begin fList.LoadFromFile(filename); Reset; end; procedure TStringLoop.LoadFromString(const s: string); begin fList.text := s; Reset; end; procedure TStringLoop.Load(const sl: tstrings); begin LoadFromString(sl.text); end; constructor TStringLoop.Create(const sl: tstrings = nil); begin isCSV := false; fList := tstringlist.Create; fcsv := tstringlist.Create; if sl <> nil then Load(sl); Reset; end; destructor TStringLoop.Destroy; begin fList.free; fcsv.free; inherited; end; {------------------------------------------------------------------------------} function TSepStringLoop.Found: boolean; begin result := false; if fTags = emptystr then exit; fCount := occurs(fSeparator, fTags) + 1; if fPos < fCount then begin fPos := fPos + 1; fCurrent := gettoken(fTags, fSeparator, fPos); result := true; end; end; constructor TSepStringLoop.Create(const tags: string = ''; const asep: string = '|'); begin fTags := tags; fCurrent := emptystr; fPos := 0; fSeparator := asep; end; destructor TSepStringLoop.Destroy; begin inherited; end; end.
unit VectorHelperTimingTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, BaseTimingTest, native, BZVectorMath, BZProfiler; type TVectorHelperTimingTest = class(TVectorBaseTimingTest) protected {$CODEALIGN RECORDMIN=16} nt4,nt5 : TNativeBZVector; vt5 : TBZVector; {$CODEALIGN RECORDMIN=4} alpha: Single; procedure Setup; override; published procedure TestTimeRotate; procedure TestTimeRotateAroundX; procedure TestTimeRotateAroundY; procedure TestTimeRotateAroundZ; procedure TestTimeRotateWithMatrixAroundX; procedure TestTimeRotateWithMatrixAroundY; procedure TestTimeRotateWithMatrixAroundZ; procedure TestTimeAverageNormal4; procedure TestTimePointProject; procedure TestTimeMoveAround; procedure TestTimeShiftObjectFromCenter; procedure TestTimeExtendClipRect; procedure TestTimeStep; procedure TestTimeFaceForward; procedure TestTimeSaturate; procedure TestTimeSmoothStep; end; implementation procedure TVectorHelperTimingTest.Setup; begin inherited Setup; Group := rgVector4f; nt3.Create(10.350,10.470,2.482,0.0); nt4.Create(20.350,18.470,8.482,0.0); vt3.V := nt3.V; vt4.V := nt4.V; alpha := pi / 6; end; procedure TVectorHelperTimingTest.TestTimeRotate; begin TestDispName := 'VectorH Rotate'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.Rotate(NativeYHmgVector,alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.Rotate(YHmgVector,alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateAroundX; begin TestDispName := 'VectorH Rotate Around X'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateAroundX(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateAroundX(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateAroundY; begin TestDispName := 'VectorH Rotate Around Y'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateAroundY(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateAroundY(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateAroundZ; begin TestDispName := 'VectorH Rotate Around Z'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateAroundZ(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateAroundZ(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateWithMatrixAroundX; begin TestDispName := 'VectorH Rotate with Matrix Around X'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateWithMatrixAroundX(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateWithMatrixAroundX(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateWithMatrixAroundY; begin TestDispName := 'VectorH Rotate with Matrix Around Y'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateWithMatrixAroundY(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateWithMatrixAroundY(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeRotateWithMatrixAroundZ; begin TestDispName := 'VectorH Rotate with Matrix Around Z'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.RotateWithMatrixAroundZ(alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.RotateWithMatrixAroundZ(alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeAverageNormal4; begin TestDispName := 'VectorH AverageNormal4'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt5 := nt1.AverageNormal4(nt1,nt2,nt3,nt4); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt5 := vt1.AverageNormal4(vt1,vt2,vt3,vt4); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimePointProject; begin TestDispName := 'VectorH Point Project'; GlobalProfiler[0].Clear; cnt:=0; GlobalProfiler[0].Start; //for cnt := 1 to Iterations do begin Fs1 := nt1.PointProject(nt2,nt3); end; while cnt<Iterations do begin Fs1 := nt1.PointProject(nt2,nt3); inc(cnt); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; cnt:=0; GlobalProfiler[1].Start; while cnt<Iterations do begin Fs2 := vt1.PointProject(vt2,vt3); inc(cnt); end; //for cnt := 1 to Iterations do begin Fs2 := vt1.PointProject(vt2,vt3); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeMoveAround; begin TestDispName := 'VectorH MoveAround'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.MoveAround(NativeYHmgVector,nt2, alpha, alpha); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.MoveAround(YHmgVector,vt2, alpha, alpha); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeShiftObjectFromCenter; begin TestDispName := 'VectorH ShiftObjectFromCenter'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt3 := nt1.ShiftObjectFromCenter(nt2, Fs1, True); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to IterationsQuarter do begin vt3 := vt1.ShiftObjectFromCenter(vt2, Fs1, True); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeExtendClipRect; var nCr: TNativeBZClipRect; aCr: TBZClipRect; begin //nCr.V := nt1.V; //aCr.V := vt1.V; //TestDispName := 'VectorH ExtendClipRect'; //GlobalProfiler[0].Clear; //GlobalProfiler[0].Start; //for cnt := 1 to Iterations do begin nCr.ExtendClipRect(Fs1,Fs2); end; //GlobalProfiler[0].Stop; //GlobalProfiler[1].Clear; //GlobalProfiler[1].Start; //for cnt := 1 to Iterations do begin aCr.ExtendClipRect(Fs1,Fs2); end; //GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeStep; begin TestDispName := 'VectorH Step'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt3 := nt1.Step(nt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to Iterations do begin vt3 := vt1.Step(vt2); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeFaceForward; begin TestDispName := 'VectorH FaceForward'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt4 := nt1.FaceForward(nt2,nt3); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to Iterations do begin vt4 := vt1.FaceForward(vt2,vt3); end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeSaturate; begin TestDispName := 'VectorH Saturate'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt4 := nt1.Saturate; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to Iterations do begin vt4 := vt1.Saturate; end; GlobalProfiler[1].Stop; end; procedure TVectorHelperTimingTest.TestTimeSmoothStep; begin vt1.Create(1,1,1,1); // self vt2.Create(0,0,0,0); // A vt3.Create(2,2,2,2); // B TestDispName := 'VectorH SmoothStep'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt4 := nt1.SmoothStep(nt2,nt3); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; for cnt := 1 to Iterations do begin vt4 := vt1.SmoothStep(vt2,vt3); end; GlobalProfiler[1].Stop; end; initialization RegisterTest(REPORT_GROUP_VECTOR4F, TVectorHelperTimingTest); end.
unit VectorHelperTestCase; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type { TVectorHelperTestCase } TVectorHelperTestCase = class(TVectorBaseTestCase) protected procedure Setup; override; public {$CODEALIGN RECORDMIN=16} nph1, nph2,nph3 : TNativeBZHmgPlane; nt4,nt5 : TNativeBZVector; vt5 : TBZVector; ph1,ph2,ph3 : TBZHmgPlane; {$CODEALIGN RECORDMIN=4} alpha: Single; published procedure TestRotate; procedure TestRotateAroundX; procedure TestRotateAroundY; procedure TestRotateAroundZ; procedure TestRotateWithMatrixAroundX; procedure TestRotateWithMatrixAroundY; procedure TestRotateWithMatrixAroundZ; procedure TestAverageNormal4; procedure TestPointProject; procedure TestMoveAround; procedure TestShiftObjectFromCenter; procedure TestExtendClipRect; procedure TestStep; procedure TestFaceForward; procedure TestSaturate; procedure TestSmoothStep; end; implementation { TVectorHelperTestCase } procedure TVectorHelperTestCase.Setup; begin inherited Setup; nt3.Create(10.350,10.470,2.482,0.0); nt4.Create(20.350,18.470,8.482,0.0); nph1.Create(nt1,nt2,nt3); ph1.V := nph1.V; vt3.V := nt3.V; vt4.V := nt4.V; alpha := pi / 6; end; {%region%====[ TVectorHelperTestCase ]========================================} procedure TVectorHelperTestCase.TestRotate; begin nt3 := nt1.Rotate(NativeYHmgVector,alpha); vt3 := vt1.Rotate(YHmgVector,alpha); AssertTrue('VectorHelper Rotate do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); vt1.Create(1,1,1,1); // unit point vt4 := vt1.Rotate(ZHmgVector, pi/2); AssertEquals('Rotate:Sub1 X failed ', -1.0, vt4.X); AssertEquals('Rotate:Sub2 Y failed ', 1.0, vt4.Y); AssertEquals('Rotate:Sub3 Z failed ', 1.0, vt4.Z); AssertEquals('Rotate:Sub4 W failed ', 1.0, vt4.W); vt4 := vt1.Rotate(ZHmgVector, -pi/2); AssertEquals('Rotate:Sub5 X failed ', 1.0, vt4.X); AssertEquals('Rotate:Sub6 Y failed ', -1.0, vt4.Y); AssertEquals('Rotate:Sub7 Z failed ', 1.0, vt4.Z); AssertEquals('Rotate:Sub8 W failed ', 1.0, vt4.W); // inverted axis vector result should be opposite from above vt4 := vt1.Rotate(-ZHmgVector, pi/2); AssertEquals('Rotate:Sub9 X failed ', 1.0, vt4.X); AssertEquals('Rotate:Sub10 Y failed ', -1.0, vt4.Y); AssertEquals('Rotate:Sub11 Z failed ', 1.0, vt4.Z); AssertEquals('Rotate:Sub12 W failed ', 1.0, vt4.W); vt4 := vt1.Rotate(-ZHmgVector, -pi/2); AssertEquals('Rotate:Sub13 X failed ', -1.0, vt4.X); AssertEquals('Rotate:Sub14 Y failed ', 1.0, vt4.Y); AssertEquals('Rotate:Sub15 Z failed ', 1.0, vt4.Z); AssertEquals('Rotate:Sub16 W failed ', 1.0, vt4.W); end; procedure TVectorHelperTestCase.TestRotateWithMatrixAroundX; begin nt3 := nt1.RotateWithMatrixAroundX(alpha); vt3 := vt1.RotateWithMatrixAroundX(alpha); AssertTrue('VectorHelper Rotate WithMatrix Around X do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestRotateWithMatrixAroundY; begin nt3 := nt1.RotateWithMatrixAroundY(alpha); vt3 := vt1.RotateWithMatrixAroundY(alpha); AssertTrue('VectorHelper Rotate WithMatrix Around Y do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestRotateWithMatrixAroundZ; begin nt3 := nt1.RotateWithMatrixAroundZ(alpha); vt3 := vt1.RotateWithMatrixAroundZ(alpha); AssertTrue('VectorHelper Rotate WithMatrix Around Z do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestRotateAroundX; begin nt3 := nt1.RotateAroundX(alpha); vt3 := vt1.RotateAroundX(alpha); AssertTrue('VectorHelper Rotate Around X do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestRotateAroundY; begin nt3 := nt1.RotateAroundY(alpha); vt3 := vt1.RotateAroundY(alpha); AssertTrue('VectorHelper Rotate Around Y do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestRotateAroundZ; begin nt3 := nt1.RotateAroundZ(alpha); vt3 := vt1.RotateAroundZ(alpha); AssertTrue('VectorHelper Rotate Around Z do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestAverageNormal4; begin nt5 := nt1.AverageNormal4(nt1,nt2,nt3,nt4); vt5 := vt1.AverageNormal4(vt1,vt2,vt3,vt4); AssertTrue('VectorHelper AverageNormal4 no match'+nt5.ToString+' --> '+vt5.ToString, Compare(nt5,vt5, 1e-5)); end; procedure TVectorHelperTestCase.TestPointProject; begin Fs1 := nt1.PointProject(nt2,nt3); Fs2 := vt1.PointProject(vt2,vt3); AssertTrue('VectorHelper PointProject do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2)); end; procedure TVectorHelperTestCase.TestMoveAround; begin nt3 := nt1.MoveAround(NativeYHmgVector,nt2, alpha, alpha); vt3 := vt1.MoveAround(YHmgVector,vt2, alpha, alpha); AssertTrue('VectorHelper Move Z does not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3,1e-5)); end; procedure TVectorHelperTestCase.TestShiftObjectFromCenter; begin nt3 := nt1.ShiftObjectFromCenter(nt2, Fs1, True); vt3 := vt1.ShiftObjectFromCenter(vt2, Fs1, True); AssertTrue('VectorHelper ShiftObjectFromCenter does not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestExtendClipRect; var nCr: TNativeBZClipRect; aCr: TBZClipRect; begin //nCr.V := nt1.V; //aCr.V := vt1.V; //nCr.ExtendClipRect(Fs1,Fs2); //aCr.ExtendClipRect(Fs1,Fs2); //AssertTrue('VectorHelper ExtendClipRect does not match : '+nCr.ToString+' --> '+nCr.ToString, Compare(nCr,aCr)); end; procedure TVectorHelperTestCase.TestStep; begin nt3 := nt1.Step(nt2); vt3 := vt1.Step(vt2); AssertTrue('VectorHelper Step does not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestFaceForward; begin //nt3 := nt1.Step(nt2); //vt3 := vt1.Step(vt2); //AssertTrue('VectorHelper Step does not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestSaturate; begin nt3 := nt1.Saturate; vt3 := vt1.Saturate; AssertTrue('VectorHelper Saturate does not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorHelperTestCase.TestSmoothStep; begin end; {%endregion%} initialization RegisterTest(REPORT_GROUP_VECTOR4F, TVectorHelperTestCase); end.
unit UMetaData; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TTableField = record FRealName: string; FDisplayName: string; FRefTableName: string; FRefFieldName: string; FRefTableInd: integer; FPermittedToShow: Boolean; end; TTable = record FRealName: string; FDisplayName: string; FFields: array of TTableField; FFieldCount: Integer; end; { TMetaData } TMetaData = class procedure AddTable(ARealTableName, ADisplayTableName: string); procedure AddField(var ATable: TTable; ARealFieldName, ADisplayFieldName, ARefTableName, ARefFieldName: string; ARefTableInd: integer); procedure AddField(var ATable: TTable; ARealFieldName, ADisplayFieldName: string; APermittedToShow: Boolean); public FTables: array of TTable; end; var MetaData: TMetaData; implementation { TMetaData } procedure TMetaData.AddTable(ARealTableName, ADisplayTableName: string); begin SetLength(FTables, Length(FTables) + 1); FTables[High(FTables)].FRealName := ARealTableName; FTables[High(FTables)].FDisplayName := ADisplayTableName; FTables[High(FTables)].FFieldCount := 0; end; procedure TMetaData.AddField(var ATable: TTable; ARealFieldName, ADisplayFieldName, ARefTableName, ARefFieldName: string; ARefTableInd: integer ); begin SetLength(ATable.FFields, Length(ATable.FFields) + 1); ATable.FFieldCount += 1; with ATable.FFields[High(ATable.FFields)] do begin FRealName := ARealFieldName; FDisplayName := ADisplayFieldName; FRefTableName := ARefTableName; FRefFieldName := ARefFieldName; FRefTableInd := ARefTableInd; FPermittedToShow := True; end; end; procedure TMetaData.AddField(var ATable: TTable; ARealFieldName, ADisplayFieldName: string; APermittedToShow: Boolean); begin SetLength(ATable.FFields, Length(ATable.FFields) + 1); ATable.FFieldCount += 1; with ATable.FFields[High(ATable.FFields)] do begin FRealName := ARealFieldName; FDisplayName := ADisplayFieldName; FRefTableName := ''; FRefFieldName := ''; FRefTableInd := -1; FPermittedToShow := APermittedToShow; end; end; initialization MetaData := TMetaData.Create; with MetaData do begin AddTable('GROUPS','Группы'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'NAME', 'Имя Группы', True); AddField(FTables[High(FTables)], 'STUDENT_NUMBER', 'Кол-во Учащихся', True); AddTable('LESSONS','Предметы'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'NAME', 'Название Предмета', True); AddTable('TEACHERS','Преподаватели'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'LAST_NAME', 'Фамилия', True); AddField(FTables[High(FTables)], 'FIRST_NAME', 'Имя', False); AddField(FTables[High(FTables)], 'MIDDLE_NAME', 'Отчество', False); AddTable('CLASSROOMS','Аудитории'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'NAME', 'Номер Аудитории', True); AddField(FTables[High(FTables)], 'CAPACITY', 'Вместимость Аудитории', True); AddTable('LESSON_TIMES','Время занятий'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'BEGIN_', 'Начало', True); AddField(FTables[High(FTables)], 'END_', 'Конец', True); AddTable('WEEKDAYS','Дни недели'); AddField(FTables[High(FTables)], 'ID','ID', True); AddField(FTables[High(FTables)], 'NAME', 'День Недели', True); AddTable('LESSON_TYPES','Тип предмета'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'NAME', 'Тип', True); AddTable('TIMETABLE', 'Расписание'); AddField(FTables[High(FTables)], 'ID', 'ID', True); AddField(FTables[High(FTables)], 'LESSON_ID', 'LESSON_ID', 'LESSONS', 'ID', 1); AddField(FTables[High(FTables)], 'LESSON_TYPE_ID', 'LESSON_TYPE_ID', 'LESSON_TYPES', 'ID', 6); AddField(FTables[High(FTables)], 'TEACHER_ID', 'TEACHER_ID', 'TEACHERS', 'ID', 2); AddField(FTables[High(FTables)], 'GROUP_ID', 'GROUP_ID', 'GROUPS', 'ID', 0 ); AddField(FTables[High(FTables)], 'CLASSROOM_ID', 'CLASSROOM_ID', 'CLASSROOMS', 'ID', 3); AddField(FTables[High(FTables)], 'WEEKDAY_ID', 'WEEKDAY_ID', 'WEEKDAYS', 'ID', 5); AddField(FTables[High(FTables)], 'LESSON_TIME_ID', 'LESSON_TIME_ID', 'LESSON_TIMES', 'ID', 4); end; end.
unit DebugUnit; interface uses SysUtils; procedure IgnoreException(ExClass: ExceptClass); implementation uses Classes, JclDebug, JclHookExcept; var IgnoreList: TList; procedure IgnoreException(ExClass: ExceptClass); begin if IgnoreList = nil then IgnoreList := TList.Create; IgnoreList.Add(Pointer(ExClass)); end; procedure AddToLog(const S: string); var FileName: string; FS: TFileStream; begin try FileName := ChangeFileExt(ParamStr(0), '.dbg'); if not FileExists(FileName) then TFileStream.Create(FileName, fmCreate).Free; FS := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyWrite); try FS.Position := FS.Size; FS.WriteBuffer(PChar(S)^, Length(S)); finally FS.Free; end; except { suppress any exception } end; end; procedure DoExceptNotify(ExceptObj: TObject; ExceptAddr: Pointer; OSException: Boolean); var Strings: TStrings; S: string; begin if JclExceptionTrackingActive then begin if (IgnoreList <> nil) and (IgnoreList.IndexOf(Pointer(ExceptObj.ClassType)) <> -1) then Exit; Strings := TStringList.Create; try S := '**************** [' + DateTimeToStr(Now) + ']'; if ExceptObj is Exception then S := S + ' ' + Exception(ExceptObj).Message; S := S + #13#10; AddToLog(S); if JclLastExceptStackListToStrings(Strings, True, True, True) then begin AddToLog(Strings.Text); end; finally Strings.Free; end; end; end; initialization JclStackTrackingOptions := [stStack, stExceptFrame, stRawMode]; if JclStartExceptionTracking then JclAddExceptNotifier(DoExceptNotify, npNormal); finalization JclRemoveExceptNotifier(DoExceptNotify); JclStopExceptionTracking; IgnoreList.Free; IgnoreList := nil; end.
Unit Pas2LAM; INTERFACE Uses Systex; Function Pascal2Lam(Const Path:String):Int; IMPLEMENTATION Uses Systems,Lamtex; Const psAbsolute={$IFDEF FRENCHCODE}'ABSOLUE'{$ELSE}'ABSOLUTE'{$ENDIF}; psAnd={$IFDEF FRENCHCODE}'ET'{$ELSE}'AND'{$ENDIF}; psArray={$IFDEF FRENCHCODE}'RANGE'{$ELSE}'ARRAY'{$ENDIF}; psASM={$IFDEF FRENCHCODE}'ASM'{$ELSE}'ASM'{$ENDIF}; psAssembler={$IFDEF FRENCHCODE}'ASSEMBLEUR'{$ELSE}'ASSEMBLER'{$ENDIF}; psBegin={$IFDEF FRENCHCODE}'DBUT'{$ELSE}'BEGIN'{$ENDIF}; psBoolean={$IFDEF FRENCHCODE}'BOOLEN'{$ELSE}'BOOLEAN'{$ENDIF}; psByte={$IFDEF FRENCHCODE}'OCTET'{$ELSE}'BYTE'{$ENDIF}; psCase={$IFDEF FRENCHCODE}'CAS'{$ELSE}'CASE'{$ENDIF}; psChar={$IFDEF FRENCHCODE}'CAR'{$ELSE}'CHAR'{$ENDIF}; psConst={$IFDEF FRENCHCODE}'CONST'{$ELSE}'CONST'{$ENDIF}; psConstructor={$IFDEF FRENCHCODE}'CONSTRUCTEUR'{$ELSE}'CONSTRUCTOR'{$ENDIF}; psCString={$IFDEF FRENCHCODE}'CHAINEC'{$ELSE}'CSTRING'{$ENDIF}; psDestructor={$IFDEF FRENCHCODE}'DESTRUCTEUR'{$ELSE}'DESTRUCTOR'{$ENDIF}; psDiv={$IFDEF FRENCHCODE}'DIV'{$ELSE}'DIV'{$ENDIF}; psDo={$IFDEF FRENCHCODE}'FAIT'{$ELSE}'DO'{$ENDIF}; psDownTo={$IFDEF FRENCHCODE}'ABAISSERA'{$ELSE}'DOWNTO'{$ENDIF}; psElse={$IFDEF FRENCHCODE}'SINON'{$ELSE}'ELSE'{$ENDIF}; psEnd={$IFDEF FRENCHCODE}'FIN'{$ELSE}'END'{$ENDIF}; psExit={$IFDEF FRENCHCODE}'SORTIR'{$ELSE}'EXIT'{$ENDIF}; psExport={$IFDEF FRENCHCODE}'EXPORTE'{$ELSE}'EXPORT'{$ENDIF}; psExports={$IFDEF FRENCHCODE}'EXPORTES'{$ELSE}'EXPORTS'{$ENDIF}; psExternal={$IFDEF FRENCHCODE}'EXTERNE'{$ELSE}'EXTERNAL'{$ENDIF}; psFalse={$IFDEF FRENCHCODE}'FAUX'{$ELSE}'FALSE'{$ENDIF}; psFar={$IFDEF FRENCHCODE}'LOIN'{$ELSE}'FAR'{$ENDIF}; psFile={$IFDEF FRENCHCODE}'FICHIER'{$ELSE}'FILE'{$ENDIF}; psFor={$IFDEF FRENCHCODE}'POUR'{$ELSE}'FOR'{$ENDIF}; psFunc={$IFDEF FRENCHCODE}'FONCTION'{$ELSE}'FUNCTION'{$ENDIF}; psGoto={$IFDEF FRENCHCODE}'ALLERA'{$ELSE}'GOTO'{$ENDIF}; psIf={$IFDEF FRENCHCODE}'SI'{$ELSE}'IF'{$ENDIF}; psImplementation={$IFDEF FRENCHCODE}'IMPLMENTATION'{$ELSE}'IMPLEMENTATION'{$ENDIF}; psIn={$IFDEF FRENCHCODE}'DANS'{$ELSE}'IN'{$ENDIF}; psInherited={$IFDEF FRENCHCODE}'HRITIER'{$ELSE}'INHERITED'{$ENDIF}; psInline={$IFDEF FRENCHCODE}'ENLIGNE'{$ELSE}'INLINE'{$ENDIF}; psInput={$IFDEF FRENCHCODE}'ENTRE'{$ELSE}'INPUT'{$ENDIF}; psInterface={$IFDEF FRENCHCODE}'INTERFACE'{$ELSE}'INTERFACE'{$ENDIF}; psInteger={$IFDEF FRENCHCODE}'ENTIER'{$ELSE}'INTEGER'{$ENDIF}; psLabel={$IFDEF FRENCHCODE}'TIQUETTE'{$ELSE}'LABEL'{$ENDIF}; psLibrary={$IFDEF FRENCHCODE}'BIBLIOTHEQUE'{$ELSE}'LIBRARY'{$ENDIF}; psLongInt={$IFDEF FRENCHCODE}'ENTLONG'{$ELSE}'LONGINT'{$ENDIF}; psMem={$IFDEF FRENCHCODE}'MM'{$ELSE}'MEM'{$ENDIF}; psMemW={$IFDEF FRENCHCODE}'MMM'{$ELSE}'MEMW'{$ENDIF}; psMemL={$IFDEF FRENCHCODE}'MML'{$ELSE}'MEML'{$ENDIF}; psMod={$IFDEF FRENCHCODE}'MOD'{$ELSE}'MOD'{$ENDIF}; psNear={$IFDEF FRENCHCODE}'PROCHE'{$ELSE}'NEAR'{$ENDIF}; psNil={$IFDEF FRENCHCODE}'NIL'{$ELSE}'NIL'{$ENDIF}; psNot={$IFDEF FRENCHCODE}'NG'{$ELSE}'NOT'{$ENDIF}; psObject={$IFDEF FRENCHCODE}'OBJET'{$ELSE}'OBJECT'{$ENDIF}; psOf={$IFDEF FRENCHCODE}'DE'{$ELSE}'OF'{$ENDIF}; psOr={$IFDEF FRENCHCODE}'OU'{$ELSE}'OR'{$ENDIF}; psOutput={$IFDEF FRENCHCODE}'SORTIE'{$ELSE}'OUTPUT'{$ENDIF}; psPacked={$IFDEF FRENCHCODE}'PAQUET'{$ELSE}'PACKED'{$ENDIF}; psPointer={$IFDEF FRENCHCODE}'POINTER'{$ELSE}'POINTEUR'{$ENDIF}; psPort={$IFDEF FRENCHCODE}'PORT'{$ELSE}'PORT'{$ENDIF}; psPortW={$IFDEF FRENCHCODE}'PORTM'{$ELSE}'PORTW'{$ENDIF}; psPrivate={$IFDEF FRENCHCODE}'PRIVE'{$ELSE}'PRIVATE'{$ENDIF}; psProgram={$IFDEF FRENCHCODE}'PROGRAMME'{$ELSE}'PROGRAM'{$ENDIF}; psProc={$IFDEF FRENCHCODE}'PROCDURE'{$ELSE}'PROCEDURE'{$ENDIF}; psRandom={$IFDEF FRENCHCODE}'HASARD'{$ELSE}'RANDOM'{$ENDIF}; psReal={$IFDEF FRENCHCODE}'REL'{$ELSE}'REAL'{$ENDIF}; psRecord={$IFDEF FRENCHCODE}'ENREGISTREMENT'{$ELSE}'RECORD'{$ENDIF}; psRepeat={$IFDEF FRENCHCODE}'FAIRE'{$ELSE}'REPEAT'{$ENDIF}; psSet={$IFDEF FRENCHCODE}'ENSEMBLE'{$ELSE}'SET'{$ENDIF}; psShl={$IFDEF FRENCHCODE}'DCALG'{$ELSE}'SHL'{$ENDIF}; psShr={$IFDEF FRENCHCODE}'DCALD'{$ELSE}'SHR'{$ENDIF}; psShortInt={$IFDEF FRENCHCODE}'ENTCOURT'{$ELSE}'SHORTINT'{$ENDIF}; psString={$IFDEF FRENCHCODE}'CHAINE'{$ELSE}'STRING'{$ENDIF}; psThen={$IFDEF FRENCHCODE}'ALORS'{$ELSE}'THEN'{$ENDIF}; psTo={$IFDEF FRENCHCODE}'A'{$ELSE}'TO'{$ENDIF}; psTrue={$IFDEF FRENCHCODE}'VRAI'{$ELSE}'TRUE'{$ENDIF}; psType={$IFDEF FRENCHCODE}'TYPE'{$ELSE}'TYPE'{$ENDIF}; psUnit={$IFDEF FRENCHCODE}'UNIT'{$ELSE}'UNIT'{$ENDIF}; psUntil={$IFDEF FRENCHCODE}'TANTQUE'{$ELSE}'UNTIL'{$ENDIF}; psUses={$IFDEF FRENCHCODE}'UTILISES'{$ELSE}'USES'{$ENDIF}; psVar={$IFDEF FRENCHCODE}'VAR'{$ELSE}'VAR'{$ENDIF}; psVirtual={$IFDEF FRENCHCODE}'VIRTUEL'{$ELSE}'VIRTUAL'{$ENDIF}; psWhile={$IFDEF FRENCHCODE}'TANTQUE'{$ELSE}'WHILE'{$ENDIF}; psWith={$IFDEF FRENCHCODE}'AVEC'{$ELSE}'WITH'{$ENDIF}; psWord={$IFDEF FRENCHCODE}'MOT'{$ELSE}'WORD'{$ENDIF}; psWrite={$IFDEF FRENCHCODE}'CRIRE'{$ELSE}'WRITE'{$ENDIF}; psWriteLn={$IFDEF FRENCHCODE}'CRITLN'{$ELSE}'WRITELN'{$ENDIF}; psXor={$IFDEF FRENCHCODE}'OUEX'{$ELSE}'XOR'{$ENDIF}; {Indicateur de d‚but} lamEnd=$0; {Marqueur de fin} lamRem=$1; {Remarque(s) du compilateur (voir rem???)} lamDeb=$2; {Information de d‚boguage: X:BYTE;Y:WORD} lamLongDeb=$3; {Information de d‚boguage: X:BYTE;Y:LONG} lamProc=$4; {Indicateur de Proc‚dure: ASCIIZ} lamFuncBool=$5; {Fonction ?:VRAI|FAUX ASCIIZ} lamFuncByte=$6; {Fonction ?:0 … 255: ASCIIZ} lamFuncShortByte=$7; {Fonction ?:-128 … 127: ASCIIZ} lamFuncChar=$8; {Fonction ?:CaractŠre ASCIIZ} lamFuncUntypedByte=$9; {Fonction ?:CaractŠre|0 … 255: ASCIIZ} lamFuncUntypedShortByte=$A; {Fonction ?:CaractŠre|-128 … 127: ASCIIZ} lamFuncInteger=$B; {Fonction ?:-32768 … 32767: ASCIIZ} lamFuncUntypedInt=$C; {Fonction ?:CaractŠre|-32768 … 32767: ASCIIZ} lamFuncWord=$D; {Fonction ?:0 … 65535: ASCIIZ} lamFuncUntypedWord=$E; {Fonction ?:CaractŠre|0 … 65535: ASCIIZ} lamFuncPointerFar=$F; {Fonction ?:PointerFar: ASCIIZ} lamFuncLongInt=$10; {Fonction ?:LongInt: ASCIIZ} lamFuncDWord=$11; {Fonction ?:LongWord: ASCIIZ} lamFuncQWord=$12; {Fonction ?:QuadrupleMot ASCIIZ} lamFuncQInt=$13; {Fonction ?:QuadrupleEntier ASCIIZ} lamConstBool=$14; {Constante VRAI|FAUX: BYTE;ASCIIZ} lamLetEqual=$15; {Variable= ASCIIZ} lamAsm=$16; {Instruction Assembleur (voir asm???)} {Commence par ®lamRem¯ et suivit par un de ces codes:} remCompilerName=$0; {Nom du compilateur: ASCIIZ} remCompilerVer=$1; {Version du compilateur: Ver:WORD;Sub:WORD} remCompilerCopyright=$2; {Droits d'auteur du compilateur: ASCIIZ} remProgram=$3; {Nom du programme compiler: ASCIIZ} {Commence par ®lamAsm¯ et suivit par un de ces codes:} asmAAA=$01; {Famille 86: AAA} asmAAD=$02; {Famille 86: AAD} asmABA=$03; {6800: ABA} asmAAM=$04; {Famille 86: AAM} asmAAS=$05; {Famille 86: AAS} asmACI=$06; {8080: ACI (Addition Immediate to A with carry)} asmADC=$07; {6502, 6800, 8080 & Famille 86: ADC (Addition & Carry)} asmADD=$08; {6800, 8080 & Famille 86: ADD (Addition)} asmADI=$09; {8080: ADI (Addition immediat with A)} asmANA=$0A; {8080: ANA (AND memory with A)} asmAND=$0B; {6502 & Famille 86: AND} asmANI=$0C; {8080: ANI} asmASL=$0D; {6502 & 6800: ASL (Shift Left One Bit Memory of Accumulator)} asmASR=$0E; {6800: ASR} asmBCC=$0F; {6502 & 6800: BCC (Branch on Carry Clear)} asmBCS=$10; {6502 & 6800: BCS (Branch on Carry Set)} asmBEQ=$11; {6502 & 6800: BEQ {Branch on Result Zero)} asmBHI=$12; {6800: BHI} asmBIT=$13; {6502 & 6800: BIT (Test Bits in Memory with Accumulator)} asmBLE=$14; {6800: BLE} asmBLS=$15; {6800: BLS} asmBMI=$16; {6502 & 6800: Branch on Result Minus)} asmBNE=$17; {6502 & 6800: Branch on Result Not Zero} asmBPL=$18; {6502 & 6800: Branch on Result Plus} asmBRA=$19; {6800: BRA} asmBRK=$1A; {6502: Force Break} asmBSF=$1B; {386+: BSF} asmBSR=$1C; {6800: BSR} asmBSWAP=$1D; {486+: BSWAP} asmBT=$1E; {386+: BT} asmBTC=$1F; {386+: BTC} asmBTR=$20; {386+: BTR} asmBTS=$21; {386+: BTS} asmBVC=$22; {6502 & 6800: BVC (Branch On Overflow Clear)} asmBVS=$23; {6800: BVS} asmCALL=$24; {8080 & Famille 86: CALL} asmCBA=$25; {6800: CBA} asmCBW=$26; {Famille 86: CBW} asmCC=$27; {8080: CC (Call on carry)} asmCDQ=$28; {Famille 86: CDQ} asmCLC=$29; {6502, 6800 & Famille 86: CLC (Clear Carry)} asmCLD=$2A; {6502 & Famille 86: CLD (Clear Decimal Flag/Clear Direction Flag)} asmCLI=$2B; {6502, 6800 & Famille 86: CLI (Clear Interrupt Disable Bit)} asmCLR=$2C; {6800: CLR} asmCLV=$2D; {6502 & 6800: CLV (Clear Overflow Flag))} asmCM=$2E; {8080: CM (Call on minus)} asmCMA=$2F; {8080: CMA (Compliment A)} asmCMC=$30; {8080 & Famille 86: CMC (Compliment Carry)} asmCMP=$31; {6502, 6800, 8080 & Famille 86: CMP (Compare)} asmCMPS=$32; {Famille 86: CMPS} asmCMPSB=$33; {Famille 86: CMPSB} asmCMPSD=$34; {386+: CMPSD} asmCMPSW=$35; {Famille 86: CMPSW} asmCMPXCHG=$36; {486+: CMPXCHG} asmCNC=$37; {8080: CNC (Call on no carry)} asmCNZ=$38; {8080: CNZ (Call on no zero)} asmCOM=$39; {6800: COM} asmCP=$3A; {8080: CP (Call on positive)} asmCPE=$3B; {8080: CPE (Call on parity even)} asmCPI=$3C; {8080: CPI (Call immediate with A)} asmCPO=$3D; {8080: CPO (Call on parity odd)} asmCPX=$3E; {6502 & 6800: Compare Memory and Index X} asmCPY=$3F; {6502: Compare Memory and Index Y} asmCWD=$40; {Famille 86: CWD} asmCWDE=$41; {386+: CWDE} asmCZ=$42; {8080: CZ (Call on zero)} asmDAA=$43; {6800, 8080 & Famille 86: DAA (Decimal adjust A)} asmDAD=$44; {8080: DAD (Addition)} asmDAS=$45; {Famille 86: DAS} asmDCR=$46; {8080: DCR (Decrement)} asmDCX=$47; {8080: DCX (Decrement ?X)} asmDEC=$48; {6502, 6800 & Famille 86: DEC (Decrement)} asmDES=$49; {6800: DES} asmDEX=$4A; {6502, 6800: DEX (Decrement Index X by One)} asmDEY=$4B; {6502: DEY (Decrement Index Y by One)} asmDI=$4C; {8080: DI (Disable Interruption)} asmDIV=$4D; {Famille 86: DIV} asmEI=$4E; {8080: EI (Enable Interruption)} asmENTER=$4F; {Famille 86: ENTER} asmEOR=$50; {6502 & 6800: "Exclusive-Or" Memory with accumulator} asmESC=$51; {Famille 86: ESC} asmF2XM=$52; {Famille MPU 87: F2XM} asmFABS=$53; {Famille MPU 87: FABS} asmFADD=$54; {Famille MPU 87: FADD} asmFADDC=$55; {Famille MPU 87: FADDC} asmFBLD=$56; {Famille MPU 87: FBLD} asmFBSTP=$57; {Famille MPU 87: FBSTP} asmFCHS=$58; {Famille MPU 87: FCHS} asmFCLEX=$59; {Famille MPU 87: FCLEX} asmFCOM=$5A; {Famille MPU 87: FCOM} asmFCOMP=$5B; {Famille MPU 87: FCOMP} asmFCOMPP=$5C; {Famille MPU 87: FCOMPP} asmFCOS=$5D; {Famille MPU 87: FCOS} asmFDECSTP=$5E; {Famille MPU 87: FDECSTP} asmFDISI=$5F; {Famille MPU 87: FDISI} asmFDIV=$60; {Famille MPU 87: FDIV} asmFDIVP=$61; {Famille MPU 87: FDIVP} asmFDIVR=$62; {Famille MPU 87: FDIVR} asmFDIVRP=$63; {Famille MPU 87: FDIVRP} asmFENI=$64; {Famille MPU 87: FENI} asmFFREE=$65; {Famille MPU 87: FFREE} asmFIADD=$66; {Famille MPU 87: FIADD} asmFICOM=$67; {Famille MPU 87: FICOM} asmFICOMP=$68; {Famille MPU 87: FICOMP} asmFIDIV=$69; {Famille MPU 87: FIDIV} asmFIDIVR=$6A; {Famille MPU 87: FIDIVR} asmFILD=$6B; {Famille MPU 87: FILD} asmFIMUL=$6C; {Famille MPU 87: FIMUL} asmFINCSTP=$6D; {Famille MPU 87: FINCSTP} asmFINIT=$6E; {Famille MPU 87: FINIT} asmFISTP=$6F; {Famille MPU 87: FISTP} asmFISUB=$70; {Famille MPU 87: FISUB} asmFISUBR=$71; {Famille MPU 87: FISUBR} asmFLD=$72; {Famille MPU 87: FLD} asmFLD1=$73; {Famille MPU 87: FLD1} asmFLDCW=$74; {Famille MPU 87: FLDCW} asmFLDENV=$75; {Famille MPU 87: FLDENV} asmFLDL2E=$76; {Famille MPU 87: FLDL2E} asmFLDL2T=$77; {Famille MPU 87: FLDL2T} asmFLDLG2=$78; {Famille MPU 87: FLDLG2} asmFLDLN2=$79; {Famille MPU 87: FLDLN2} asmFLDPI=$7A; {Famille MPU 87: FLDPI} asmFLDZ=$7B; {Famille MPU 87: FLDZ} asmFMUL=$7C; {Famille MPU 87: FMUL} asmFMULP=$7D; {Famille MPU 87: FMULP} asmFNCLEX=$7E; {Famille MPU 87: FNCLEX} asmFNDISI=$7F; {Famille MPU 87: FNDISI} asmFNENI=$80; {Famille MPU 87: FNENI} asmFNINIT=$81; {Famille MPU 87: FNINIT} asmFNOP=$82; {Famille MPU 87: FNOP} asmFNSAVE=$83; {Famille MPU 87: FNSAVE} asmFNSTCW=$84; {Famille MPU 87: FNSTCW} asmFPATAN=$85; {Famille MPU 87: FPATAN} asmFPREM=$86; {Famille MPU 87: FPREM} asmFPTAN=$87; {Famille MPU 87: FPTAN} asmFRNDINT=$88; {Famille MPU 87: FRNDINT} asmFRSTOR=$89; {Famille MPU 87: FRSTOR} asmFSAVE=$8A; {Famille MPU 87: FSAVE} asmFSCALE=$8B; {Famille MPU 87: FSCALE} asmFSETPM=$8C; {MPU 287+: FSETPM} asmFSIN=$8D; {Famille MPU 87: FSIN} asmFSINCOS=$8E; {Famille MPU 87: FSINCOS} asmFSQRT=$8F; {Famille MPU 87: FSQRT} asmFST=$90; {Famille MPU 87: FST} asmFSTCW=$91; {Famille MPU 87: FSTCW} asmFSTENV=$92; {Famille MPU 87: FSTENV} asmFSTP=$93; {Famille MPU 87: FSTP} asmFSTSW=$94; {Famille MPU 87: FSTSW} asmFSUB=$95; {Famille MPU 87: FSUB} asmFSUBPP=$96; {Famille MPU 87: FSUBPP} asmFSUBR=$97; {Famille MPU 87: FSUBR} asmFSUBRP=$98; {Famille MPU 87: FSUBRP} asmFTST=$99; {Famille MPU 87: FTST} asmFWAIT=$9A; {Famille MPU 87: FWAIT} asmFXAM=$9B; {Famille MPU 87: FXAM} asmFXCH=$9C; {Famille MPU 87: FXCH} asmFXTRACT=$9D; {Famille MPU 87: FXTRACT} asmFYL2X=$9E; {Famille MPU 87: FYL2X} asmFYL2XP1=$9F; {Famille MPU 87: FYl2XP1} asmHLT=$A0; {8080 & Famille 86: HLT (Halt)} asmIDIV=$A1; {Famille 86: IDIV} asmIMUL=$A2; {Famille 86: IMUL} asmIN=$A3; {8080 & Famille 86: IN (Input) } asmINC=$A4; {6502, 6800 & Famille 86: INC (Increment)} asmINR=$A5; {8080: INR (Increment)} asmINS=$A6; {6800 & Famille 86: INS} asmINSB=$A7; {Famille 86: INSB} asmINSD=$A8; {Famille 86: INSD} asmINSW=$A9; {Famille 86: INSW} asmINT=$AA; {Famille 86: INT} asmINTO=$AB; {Famille 86: INTO} asmINX=$AC; {6502, 6800 & 8080: INX (Increment/Increment Index X by One)} asmINY=$AD; {6502: INY (Incremnet Index Y by One)} asmIRET=$AE; {Famille 86: IRET} asmJA=$AF; {Famille 86: JA} asmJAE=$B0; {Famille 86: JAE} asmJB=$B1; {Famille 86: JB} asmJBE=$B2; {Famille 86: JBE} asmJC=asmJB; {8080 & Famille 86: JC (Jump on carry)} asmJE=$B3; {Famille 86: JE} asmJG=$B4; {Famille 86: JG} asmJGE=$B5; {Famille 86: JGE} asmJL=$B6; {Famille 86: JL} asmJLE=$B7; {Famille 86: JLE} asmJM=$B8; {8080: JM (Jump on minus)} asmJMP=$B9; {6502, 6800, 8080 & Famille 86: JMP (Jump unconditionnel)} asmJNA=asmJBE; {Famille 86: JNA} asmJNAE=asmJB; {Famille 86: JNAE} asmJNB=asmJAE; {Famille 86: JNB} asmJNBE=asmJA; {Famille 86: JNBE} asmJNC=asmJAE; {8080 & Famille 86: JNC (Jump on no carry)} asmJNE=$BA; {Famille 86: JNE} asmJNG=asmJLE; {Famille 86: JNG} asmJNGE=asmJL; {Famille 86: JNGE} asmJNL=asmJGE; {Famille 86: JNL} asmJNLE=asmJG; {Famille 86: JNLE} asmJNO=$BB; {Famille 86: JNO} asmJNP=$BC; {Famille 86: JNP} asmJNS=$BD; {Famille 86: JNS} asmJNZ=asmJNE; {8080 & Famille 86: JNZ (Jump on no zero)} asmJO=$BE; {Famille 86: JO} asmJP=$BF; {8080 & Famille 86: JP (Jump on parity)} asmJPE=$C0; {8080 & Famille 86: JPE (Jump on parity even)} asmJPO=$C1; {Famille 86: JPO} asmJS=$C2; {Famille 86: JS} asmJSR=$C3; {6502, 6800: JSR (Jump to New Location Saving Return Address)} asmJZ=asmJE; {8080 & Famille 86: JZ (Jump on zero)} asmLAHF=$C4; {Famille 86: LAHF} asmLAR=$C5; {Famille 86: LAR} asmLDA=$C6; {6502, 6800 & 8080: LDA (Load Accumulator with Memory/Load A direct)} asmLDAX=$C7; {8080: LDAX (Load A indirect) } asmLDS=$C8; {Famille 86: LDS} asmLDX=$C9; {6502 & 6800: LDX (Load Index X with Memory)} asmLDY=$CA; {6502: LDY (Load Index Y with Memory)} asmLEA=$CB; {Famille 86: LEA} asmLEAVE=$CC; {Famille 86: LEAVE} asmLES=$CD; {Famille 86: LES} asmLFS=$CE; {386+: LFS} asmLGS=$CF; {386+: LGS} asmLHLD=$D0; {8080: LHLD (Load H & L direct)} asmLOCK=$D1; {Famille 86: LOCK} asmLODS=$D2; {Famille 86: LODS} asmLODSB=$D3; {Famille 86: LODSB} asmLODSD=$D4; {386+: LODSD} asmLODSW=$D5; {Famille 86: LODSW} asmLOOP=$D6; {Famille 86: LOOP} asmLOOPE=$D7; {Famille 86: LOOPE} asmLOOPNE=$D8; {Famille 86: LOOPNE} asmLOOPNZ=asmLOOPNE; {Famille 86: LOOPNZ} asmLOOPZ=asmLOOPE; {Famille 86: LOOPZ} asmLSR=$D9; {6502 & 6800: LSR (Shift Right One bit Memory or Accumulator)} asmLXI=$DA; {8080: LXI (Load immediate register Pair)} asmMOV=$DB; {8080 & Famille 86: MOV (Move)} asmMOVS=$DC; {Famille 86: MOVS} asmMOVSB=$DD; {Famille 86: MOVSB} asmMOVSD=$DE; {386+: MOVSD} asmMOVSW=$DF; {Famille 86: MOVSW} asmMUL=$E0; {Famille 86: MUL} asmMVI=$E1; {8080: MVI (Move immediate)} asmNEG=$E2; {6800 & Famille 86: NEG} asmNOP=$E3; {6502, 6800, 8080 & Famille 86: NOP (No Operation)} asmNOT=$E4; {Famille 86: NOT} asmOR=$E5; {Famille 86: OR} asmORA=$E6; {6502, 6800 & 8080: ORA (Or memory with A(ccumulator))} asmORI=$E7; {8080: ORI (Or register with A)} asmOUT=$E8; {8080 & Famille 86: OUT (Output)} asmOUTS=$E9; {Famille 86: OUTS} asmOUTSB=$EA; {286+: OUTSB} asmOUTSD=$EB; {386+: OUTSD} asmOUTSW=$EC; {286+: OUTSW} asmPCHL=$ED; {8080: PCHL (H & L to program counter)} asmPHA=$EE; {6502: PHA (Push Accumalator on Stack)} asmPHP=$EF; {6502: PHP (Push Processor Status on Stack)} { F0h ??h: ÄÄÄ Code Double ÄÄÄ } asmPLA=$00; {6502: PLA (Pull Accumulator on Stack)} asmPLP=$01; {6502: PLP (Pull Processor on Stack)} asmPOP=$02; {8080 & Famille 86: POP} asmPOPA=$03; {286+: POPA} asmPOPAD=$04; {386+: POPAD} asmPSH=$05; {6800: PSH} asmPUL=$06; {6800: PUL} asmPUSH=$07; {8080 & Famille 86: PUSH} asmPUSHA=$08; {286+: PUSHA} asmPUSHAD=$09; {386+: PUSHAD} asmPUSHF=$0A; {Famille 86: PUSHF} asmRAL=$0B; {8080: RAL (Rotate A left troug carry)} asmRAR=$0C; {8080: RAR (Rotate A righe troug carry)} asmRC=$0D; {8080: RC (Return on carry)} asmRCL=$0E; {Famille 86: RCL} asmRCR=$0F; {Famille 86: RCR} asmREP=$10; {Famille 86: REP} asmREPE=$11; {Famille 86: REPE} asmREPNE=$12; {Famille 86: REPNE} asmREPNZ=$13; {Famille 86: REPNZ} asmRET=$14; {8080 & Famille 86: RET (Return)} asmRETF=$15; {Famille 86: RETF} asmRETN=$16; {Famille 86: RETN} asmRM=$17; {8080: RM (Return on minus)} asmRNC=$18; {8080: RNC (Return on no carry)} asmRNZ=$19; {8080: RNZ (Return on no zero)} asmROL=$1A; {6502, 6800 & Famille 86: ROL (Rotate 1 Bit Left)} asmROR=$1B; {6502, 6800 & Famille 86: ROR (Rotate 1 Bit Right)} asmRP=$1C; {8080: RP (Return on positive)} asmRPE=$1D; {8080: RPE (Return on parity even)} asmRPO=$1E; {8080: RPO (Return on parity odd)} asmRRC=$1F; {8080: RRC (Rotate A right)} asmRST=$20; {8080: RST (Restart)} asmRTI=$21; {6502 & 6800: RTI (Return from Interrupt)} asmRTS=$22; {6502 & 6800: RTS (Retour from subroutine)} asmRZ=$23; {8080: RZ (Return on zero)} asmSAHF=$24; {Famille 86: SAHF} asmSAL=$25; {Famille 86: SAL} asmSAR=$26; {Famille 86: SAR} asmSBA=$27; {6800: SBA} asmSBB=$28; {8080 & Famille 86: SBB (Subtract with borrow)} asmSBC=$29; {6502 & 6800: SBC (Subtract Memory from Accumulator with borrow)} asmSBI=$2A; {8080: SBI (Subtract immediate from A with borrow)} asmSCAS=$2B; {Famille 86: SCAS} asmSCASB=$2C; {Famille 86: SCASB} asmSCASD=$2D; {386+: SCASD} asmSCASW=$2E; {Famille 86: SCASW} asmSEC=$2F; {6502 & 6800: SEC (Set Carry Flag)} asmSED=$30; {6502: SED (Set Decimal Mode)} asmSEI=$31; {6502 & 6800: SEI (Set Interrupt Enable Status)} asmSETA=$32; {386+: SETA} asmSETAE=$33; {386+: SETAE} asmSETALC=$34; {Famille 86 INTEL: SETALC (Set AL equal Carry)} asmSETB=$35; {386+: SETB} asmSETBE=$36; {386+: SETBE} asmSETC=asmSETB; {386+: SETC} asmSETE=$37; {386+: SETE} asmSETG=$38; {386+: SETG} asmSETGE=$39; {386+: SETGE} asmSETL=$3A; {386+: SETL} asmSETLE=$3B; {386+: SETLE} asmSETNA=asmSETBE; {386+: SETNA} asmSETNAE=asmSETB; {386+: SETNAE} asmSETNB=asmSETAE; {386+: SETNB} asmSETNC=asmSETAE; {386+: SETNC} asmSETNE=$3C; {386+: SETNE} asmSETNG=asmSETLE; {386+: SETNG} asmSETNGE=asmSETL; {386+: SETNGE} asmSETNL=asmSETGE; {386+: SETNL} asmSETNLE=asmSETG; {386+: SETNLE} asmSETNO=$3D; {386+: SETNO} asmSETNP=$3E; {386+: SETNP} asmSETNS=$3F; {386+: SETNS} asmSETNZ=asmSETNE; {386+: SETNZ} asmSETO=$40; {386+: SETO} asmSETP=$41; {386+: SETP} asmSETPE=$42; {386+: SETPE} asmSETPO=$43; {386+: SETPO} asmSETS=$44; {386+: SETS} asmSETZ=asmSETE; {386+: SETZ} asmSEV=$45; {6800: SEV} asmSHL=$46; {Famille 86: SHL} asmSHLD=$47; {8080 & 386+: SHLD (Store H & L direct/Shift Left Double)} asmSHR=$48; {Famille 86: SHR} asmSHRD=$49; {386+: SHRD} asmSPHL=$4A; {8080: SPHL (Store H & L to stack)} asmSTA=$4C; {6502, 6800 & 8080: STA (Store A direct/Store accumulator in Memory)} asmSTAX=$4D; {8080: STAX (Store A indirect)} asmSTC=$4E; {8080 & Famille 86: STC (Set Carry)} asmSTD=$4F; {Famille 86: STD} asmSTI=$50; {Famille 86: STI} asmSTOS=$51; {Famille 86: STOS} asmSTOSB=$52; {Famille 86: STOSB} asmSTOSD=$53; {386+: STOSD} asmSTOSW=$54; {Famille 86: STOSW} asmSTS=$55; {6800: STS} asmSTX=$56; {6502 & 6800: STX (Store Index X in Memory)} asmSTY=$57; {6502: STY (Store Index Y in Memory)} asmSUB=$58; {6800, 8080 & Famille 86: SUB (Subtract)} asmSUI=$59; {8080: SUI (Subtract immediate)} asmSWI=$5A; {6800: SWI} asmTAB=$5B; {6800: TAB} asmTAP=$5C; {6800: TAP} asmTAX=$5D; {6502: TAX (Transfer Accumulator to Index X)} asmTAY=$5E; {6502: TAY (Transfer Accumulator to Index Y)} asmTBA=$5F; {6800: TBA} asmTEST=$60; {Famille 86: TEST} asmTPA=$61; {6800: TPA} asmTST=$62; {6800: TST} asmTSX=$63; {6502 & 6800: TSX (Transfer Stack Pointer to Index X)} asmTSY=$64; {6502: TSY (Transfer Stack Pointer to Index Y)} asmTXA=$65; {6502: TXA (Transfer Index X to Accumulator)} asmTXS=$66; {6502 & 6800: TXS (Transfer Index X to Stack Pointer)} asmTYA=$67; {6502: TYA (Transfer Index Y to Accumulator)} asmWAI=$68; {6800: WAI} asmWAIT=$69; {Famille 86: WAIT} asmXCHG=$6A; {8080 & Famille 86: XCHG (Exchange D & E, H & L, registers/Exchange x,y)} asmXLAT=$6B; {Famille 86: XLAT} asmXOR=$6C; {Famille 86: XOR} asmXRA=$6D; {8080: XRA (Exclusive Or memory with A)} asmXRI=$6E; {8080: XRI (Exclusive Or immediate with A)} asmXTHL=$6F; {8080: XTHL (Exchange top of stack, H & L)} Function Pascal2Lam;Label Got,Xit;Var HS,HT:Hdl;CL,FS,PS:Long; I:Byte;S,Name,Wd:String;Def:Bool; Procedure DebugInfo;Begin PutFileTxt(HT,Chr(lamDeb)+Chr(I)+Chr(Lo(CL))+Chr(Hi(CL))); End; Procedure SkipSpc;Begin SkipSpcInLn(I,S); If I>=Length(S)Then Begin I:=1;Inc(CL); __GetAbsFileTxtLn(HS,PS,S); SkipSpcInLn(I,S) End; End; Function Let:Bool;Begin Let:=No;Wd:=XtrkWord(I,S); SkipSpc; If StrI(I,S)<>'='Then Begin;Pascal2LAM:=EqualExpected;Exit;End; Inc(I); Let:=Ya; End; Function InlineAsm:Bool;Begin Repeat Wd:=StrUp(XtrkWord(I,S)); If(Wd=asAAA)Then PutFileTxt(HT,Chr(lamAsm)+Chr(asmAAA))Else If(Wd=asAAD)Then PutFileTxt(HT,Chr(lamAsm)+Chr(asmAAD))Else If(Wd=asAAM)Then PutFileTxt(HT,Chr(lamAsm)+Chr(asmAAM))Else If(Wd=asAAS)Then PutFileTxt(HT,Chr(lamAsm)+Chr(asmAAS)) Else If(Wd<>psEnd)Then Begin;Pascal2LAM:=SyntaxError;Exit;End; Until Wd=psEnd; End; Function Cortex:Bool;Begin Cortex:=No; Repeat SkipSpc; Wd:=StrUp(XtrkWord(I,S)); If(Wd=psAsm)Then Begin If Not(InlineAsm)Then Break; End Else If(Wd=psBegin)Then Begin If Not(Cortex)Then Break; End Else If(Wd=psFor)Then Begin If Not(Let)Then Break; End Else If(Wd=psIf)Then Begin Wd:=StrUp(XtrkWord(I,S)); If(Wd<>psThen)Then Begin;Pascal2LAM:=SyntaxError;Exit;End; End Else If(Wd=psWrite)Then Begin End Else If(Wd<>psEnd)Then Begin;Pascal2LAM:=SyntaxError;Exit;End; Until Wd=psEnd; Cortex:=Ya; End; Begin Pascal2Lam:=0;PS:=0;CL:=0;Def:=No;HS:=FileOpen(Path,fmRead); If(HS=errHdl)Then Begin;Pascal2Lam:=FileNotFound;Exit;End; FS:=FileSize(HS);HT:=FileCreate(Path2NoExt(Path)+'.LAM'); If(HS=errHdl)Then Pascal2Lam:=FileNotFound Else Begin PutFileTxt(HT,Chr(lamRem)+Chr(remCompilerName)+'OverCode'#0); PutFileTxt(HT,Chr(lamRem)+Chr(remCompilerVer)+#1#0#1#0); PutFileTxt(HT,Chr(lamRem)+Chr(remCompilerCopyright)+ 'Tous droits r‚serv‚s par les Chevaliers de Malte'#13#10+ 'Concepteur/Programmeur/Analyste: Gabriel Sylvain Maltais'#0); I:=1;Inc(CL); __GetAbsFileTxtLn(HS,PS,S); Repeat SkipSpcInLn(I,S); Wd:=StrUp(XtrkWord(I,S)); If(Wd=psBegin)Then Begin If Not(Cortex)Then Break; End Else If(Wd=psProgram)Then Begin If(Def)Then Begin;Pascal2LAM:=MisplacedProgram;Break;End; PutFileTxt(HT,Chr(lamRem)+Chr(remProgram)+Wd+#0); End Else If(Wd=psProc)Then Begin SkipSpc; Name:=StrUp(XtrkWord(I,S)); If Name=''Then Pascal2LAM:=NameExpected; PutFileTxt(HT,Chr(lamProc)+Name+#0); Goto Got; End Else If(Wd=psFunc)Then Begin SkipSpc; Name:=StrUp(XtrkWord(I,S)); If Name=''Then Begin;Pascal2LAM:=NameExpected;Break;End; SkipSpc; If StrI(I,S)<>':'Then Begin;Pascal2LAM:=ColonExpected;Break;End; Inc(I);Wd:=StrUp(XtrkWord(I,S)); If Wd=''Then Begin;Pascal2LAM:=NameExpected;Break;End; If(Wd=psBoolean)Then PutFileTxt(HT,Chr(lamFuncBool)+Name+#0)Else If(Wd=psByte)Then PutFileTxt(HT,Chr(lamFuncByte)+Name+#0)Else If(Wd=psChar)Then PutFileTxt(HT,Chr(lamFuncChar)+Name+#0)Else If(Wd=psShortInt)Then PutFileTxt(HT,Chr(lamFuncShortByte)+Name+#0)Else If(Wd=psInteger)Then PutFileTxt(HT,Chr(lamFuncInteger)+Name+#0)Else If(Wd=psWord)Then PutFileTxt(HT,Chr(lamFuncWord)+Name+#0)Else If(Wd=psLongInt)Then PutFileTxt(HT,Chr(lamFuncLongInt)+Name+#0)Else If(Wd=psPointer)or (Wd='PTR')Then PutFileTxt(HT,Chr(lamFuncPointerFar)+Name+#0) Else Begin;Pascal2LAM:=SyntaxError;Break;End; Got:Def:=Ya; SkipSpc; If StrI(I,S)<>';'Then Begin;Pascal2LAM:=PointCommaExpected;Break;End; Inc(I);Wd:=StrUp(XtrkWord(I,S)); If(Wd=psBegin)Then Begin If Not(Cortex)Then Break End Else Begin;Pascal2LAM:=SyntaxError;Break;End; End; Until PS>=FS; Xit: FileClose(HT); End; FileClose(HS); End; END.
// NAME: TUMAKOV KIRILL ALEKSANDROVICH, 203 // ASGN: N3 unit Recognition; interface uses Graphics,Classes; function Recognize(var BinBmp,Bmp:TBitmap):TStringList; implementation uses SysUtils,Math,Types,Filters,Forms; const NoiseObjectSquare=350; UnmarkedObject=-666; DeletedObject=-37131; elGray=0; elUndefined=0; elRed=1; elYellow=2; elBlue=3; elViolet=4; elGreen=5; typeUndefined=0; typeElephant=1; typeBamboo=2; type TConnectedObj=record Square:Integer; meanx,meany:Integer; m11,m02,m20,e,angle:Single; meanc:array[0..2] of Integer; Color:Byte; maxx,maxy,minx,miny:Single; Up:array[0..1] of Single; Processed:Boolean; ObjType:Integer; EatenBy:Integer; EatenN:Integer; end; TConnectedObjArray=array[1..32000] of TConnectedObj; PConnectedObjArray=^TConnectedObjArray; TXY=record x:Integer; y:Integer; end; TXYArray=array[0..32000] of TXY; PXYArray=^TXYArray; var a:array[0..1000000,0..2] of Byte; procedure PrepareBmp(var Bmp:TBitmap; var w,h: Integer; var P:PByteArray); begin; Bmp.PixelFormat:=pf24bit; w:=Bmp.Width*3; w:=w+(4-w mod 4)mod 4; h:=Bmp.Height-1; P:=Bmp.ScanLine[Bmp.Height-1]; end; function GetColor(r,g,b:Integer):Integer; var mean:Integer; begin; Result:=elGray; if max(max(abs(r-g),abs(b-g)),abs(r-b))>3 then begin; mean:=(max(max(r,g),b)+min(min(r,g),b)) div 2; if (r>mean) and (b>mean) then Result:=elViolet else if (r>mean) and (g>mean) then Result:=elYellow else if r>mean then Result:=elRed else if b>mean then Result:=elBlue else if g>mean then Result:=elGreen else Result:=elUndefined; end; end; function GetType(e: Single):Integer; begin; Result:=typeUndefined; if (e>1)and(e<2.7) then Result:=typeElephant else if e>14 then Result:=typeBamboo; end; function GetElongation(m02,m20,m11:Single):Single; begin; Result:=(m02+m20+sqrt(sqr(m20-m02)+4*sqr(m11))) / (m02+m20-sqrt(sqr(m20-m02)+4*sqr(m11))); end; //============================================================================// function FindConnectedObjects(var Bmp:TBitmap; var N:Integer):PIntegerArray; var bin:PIntegerArray; bw,bh:Integer; Filler:Integer; Borderer:Integer; function FillObj(const x,y:Integer):Integer; var i:Integer; w1,w2,w3:PXYArray; c1,c2:Integer; begin; GetMem(w1,Sizeof(TXY)*2*(bw+bh)); GetMem(w2,Sizeof(TXY)*2*(bw+bh)); c1:=1;c2:=0;w1[0].x:=x;w1[0].y:=y; Result:=1; bin[y*bw+x]:=Filler; repeat for i:=0 to c1-1 do begin; if (w1[i].x>0) and (bin[(w1[i].y)*bw+(w1[i].x-1)]=Borderer) then begin; bin[(w1[i].y)*bw+(w1[i].x-1)]:=Filler; w2[c2].x:=w1[i].x-1; w2[c2].y:=w1[i].y; c2:=c2+1; end; if (w1[i].y>0) and (bin[(w1[i].y-1)*bw+(w1[i].x)]=Borderer) then begin; bin[(w1[i].y-1)*bw+(w1[i].x)]:=Filler; w2[c2].x:=w1[i].x; w2[c2].y:=w1[i].y-1; c2:=c2+1; end; if (w1[i].x<bw-1) and (bin[(w1[i].y)*bw+(w1[i].x+1)]=Borderer) then begin; bin[(w1[i].y)*bw+(w1[i].x+1)]:=Filler; w2[c2].x:=w1[i].x+1; w2[c2].y:=w1[i].y; c2:=c2+1; end; if (w1[i].y<bh-1) and (bin[(w1[i].y+1)*bw+(w1[i].x)]=Borderer) then begin; bin[(w1[i].y+1)*bw+(w1[i].x)]:=Filler; w2[c2].x:=w1[i].x; w2[c2].y:=w1[i].y+1; c2:=c2+1; end; end; c1:=c2;c2:=0; Result:=Result+c1; w3:=w1;w1:=w2;w2:=w3; until (c1=0); FreeMem(w1); FreeMem(w2); end; procedure MarkObj(const x,y:Integer); begin; Filler:=N+1; Borderer:=UnmarkedObject; if FillObj(x,y)<NoiseObjectSquare then begin; Borderer:=Filler; Filler:=DeletedObject; FillObj(x,y); end else Inc(N); end; var P:PByteArray; w,h,x,y:Integer; begin; PrepareBmp(Bmp,w,h,P); bw:=Bmp.Width;bh:=Bmp.Height; GetMem(bin,Sizeof(Integer)*bw*bh); for x:=0 to bw-1 do for y:=0 to bh-1 do begin; if P^[(h-y)*w+x*3+0]=0 then bin[y*bw+x]:=0 else bin[y*bw+x]:=UnmarkedObject; end; N:=0; for x:=0 to bw-1 do for y:=0 to bh-1 do if bin[y*bw+x]=UnmarkedObject then MarkObj(x,y); for x:=0 to bw-1 do for y:=0 to bh-1 do if bin[y*bw+x]=DeletedObject then bin[y*bw+x]:=0; Result:=bin; end; //============================================================================// function Recognize(var BinBmp,Bmp:TBitmap):TStringList; var S:String; i,j,k,x,y,mindist,minj:Integer; w,h:Integer; bw,bh:Integer; P,P2:PByteArray; Obj,Elephants,Bamboos:PConnectedObjArray; N,eN,bN:Integer; bin:PIntegerArray; tmp:TConnectedObj; begin; Result:=TStringList.Create;Result.Clear; if (BinBmp=nil) or (Bmp=nil) or (BinBmp.Width=0) or (BinBmp.Height=0) or (Bmp.Width=0) or (Bmp.Height=0) then begin; Result.Add('Error: either Binary or Source image does not exist.'); exit; end; if (BinBmp.Width<>Bmp.Width) or (BinBmp.Height<>Bmp.Height) then begin; Result.Add('Error: the sizes of Binary and Source images aren''t equal.'); exit; end; PrepareBmp(BinBmp,w,h,P); PrepareBmp(Bmp,w,h,P2); bw:=BinBmp.Width;bh:=BinBmp.Height; Gauge.MaxValue:=11; Gauge.Progress:=1; bin:=FindConnectedObjects(BinBmp,N); Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; a[0][0]:=0;a[0][1]:=0;a[0][2]:=0; for i:=1 to N do begin; a[i][0]:=Random(256); a[i][1]:=Random(256); a[i][2]:=Random(256); end; for x:=0 to bw-1 do for y:=0 to bh-1 do begin; P^[(h-y)*w+x*3+0]:=a[bin[y*bw+x]][0]; P^[(h-y)*w+x*3+1]:=a[bin[y*bw+x]][1]; P^[(h-y)*w+x*3+2]:=a[bin[y*bw+x]][2]; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; GetMem(Obj,Sizeof(TConnectedObj)*N);FillChar(Obj^,Sizeof(TConnectedObj)*N,0); for x:=0 to bw-1 do for y:=0 to bh-1 do begin; i:=bin[y*bw+x]; if (i<>0) then begin; Inc(Obj^[i].Square); Obj^[i].meanx:=Obj^[i].meanx+x; Obj^[i].meany:=Obj^[i].meany+y; Obj^[i].meanc[0]:=Obj^[i].meanc[0]+P2^[(h-y)*w+x*3+0]; Obj^[i].meanc[1]:=Obj^[i].meanc[1]+P2^[(h-y)*w+x*3+1]; Obj^[i].meanc[2]:=Obj^[i].meanc[2]+P2^[(h-y)*w+x*3+2]; end; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for i:=1 to N do begin; Obj^[i].meanx:=Obj^[i].meanx div Obj^[i].Square; Obj^[i].meany:=Obj^[i].meany div Obj^[i].Square; Obj^[i].meanc[0]:=Obj^[i].meanc[0] div Obj^[i].Square; Obj^[i].meanc[1]:=Obj^[i].meanc[1] div Obj^[i].Square; Obj^[i].meanc[2]:=Obj^[i].meanc[2] div Obj^[i].Square; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for x:=0 to bw-1 do for y:=0 to bh-1 do begin; i:=bin[y*bw+x]; if (i<>0) then begin; Obj^[i].m02:=Obj^[i].m02+sqr(y-Obj^[i].meany); Obj^[i].m20:=Obj^[i].m20+sqr(x-Obj^[i].meanx); Obj^[i].m11:=Obj^[i].m11+(x-Obj^[i].meanx)*(y-Obj^[i].meany); end; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; eN:=0;bN:=0; for i:=1 to N do begin; Obj^[i].angle:=0.5*arctan2(2*Obj^[i].m11,Obj^[i].m20-Obj^[i].m02); Obj^[i].Up[0]:=cos(Obj^[i].angle); Obj^[i].Up[1]:=sin(Obj^[i].angle); Obj^[i].e:=GetElongation(Obj^[i].m02,Obj^[i].m20,Obj^[i].m11); Obj^[i].ObjType:=GetType(Obj^[i].e); if Obj^[i].ObjType=typeElephant then Inc(eN); if Obj^[i].ObjType=typeBamboo then Inc(bN); Obj^[i].Color:=GetColor(Obj^[i].meanc[2],Obj^[i].meanc[1],Obj^[i].meanc[0]); end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for x:=0 to bw-1 do for y:=0 to bh-1 do begin; k:=bin[y*bw+x]; if (k<>0) then begin; Obj^[k].maxy:=max(Obj^[k].maxy,(x-Obj^[k].meanx)*Obj^[k].Up[0]+(y-Obj^[k].meany)*Obj^[k].Up[1]); Obj^[k].maxx:=max(Obj^[k].maxx,(x-Obj^[k].meanx)*Obj^[k].Up[1]-(y-Obj^[k].meany)*Obj^[k].Up[0]); Obj^[k].miny:=min(Obj^[k].miny,(x-Obj^[k].meanx)*Obj^[k].Up[0]+(y-Obj^[k].meany)*Obj^[k].Up[1]); Obj^[k].minx:=min(Obj^[k].minx,(x-Obj^[k].meanx)*Obj^[k].Up[1]-(y-Obj^[k].meany)*Obj^[k].Up[0]); end; end; FreeMem(bin); GetMem(Elephants,Sizeof(TConnectedObj)*eN);FillChar(Elephants^,Sizeof(TConnectedObj)*eN,0); GetMem(Bamboos,Sizeof(TConnectedObj)*bN);FillChar(Bamboos^,Sizeof(TConnectedObj)*bN,0); eN:=0;bN:=0; for i:=1 to N do begin; if Obj^[i].ObjType=typeElephant then begin; Inc(eN); Elephants^[eN]:=Obj^[i]; end; if Obj^[i].ObjType=typeBamboo then begin; Inc(bN); Bamboos^[bN]:=Obj^[i]; end; end; FreeMem(Obj); Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for i:=1 to bN do begin; mindist:=1000000000; for j:=1 to eN do if ((Elephants^[j].Color=elGray) or (Bamboos^[i].Color=Elephants^[j].Color))and ((sqr(Bamboos^[i].meanx-Elephants^[j].meanx)+sqr(Bamboos^[i].meany-Elephants^[j].meany))<mindist) then begin; mindist:=sqr(Bamboos^[i].meanx-Elephants^[j].meanx)+sqr(Bamboos^[i].meany-Elephants^[j].meany); minj:=j; end; if mindist<1000000000 then begin; Bamboos^[i].EatenBy:=minj; Inc(Elephants^[minj].EatenN); end; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; Bmp.Canvas.Pen.Color:=255*256*256+255*256+0;Bmp.Canvas.Pen.Width:=3; for i:=1 to bN do begin; Bmp.Canvas.MoveTo(Bamboos^[i].meanx+Round(Bamboos^[i].Up[0]*Bamboos^[i].maxy+Bamboos^[i].Up[1]*Bamboos^[i].maxx),Bamboos^[i].meany+Round(Bamboos^[i].Up[1]*Bamboos^[i].maxy-Bamboos^[i].Up[0]*Bamboos^[i].maxx)); Bmp.Canvas.LineTo(Bamboos^[i].meanx+Round(Bamboos^[i].Up[0]*Bamboos^[i].maxy+Bamboos^[i].Up[1]*Bamboos^[i].minx),Bamboos^[i].meany+Round(Bamboos^[i].Up[1]*Bamboos^[i].maxy-Bamboos^[i].Up[0]*Bamboos^[i].minx)); Bmp.Canvas.LineTo(Bamboos^[i].meanx+Round(Bamboos^[i].Up[0]*Bamboos^[i].miny+Bamboos^[i].Up[1]*Bamboos^[i].minx),Bamboos^[i].meany+Round(Bamboos^[i].Up[1]*Bamboos^[i].miny-Bamboos^[i].Up[0]*Bamboos^[i].minx)); Bmp.Canvas.LineTo(Bamboos^[i].meanx+Round(Bamboos^[i].Up[0]*Bamboos^[i].miny+Bamboos^[i].Up[1]*Bamboos^[i].maxx),Bamboos^[i].meany+Round(Bamboos^[i].Up[1]*Bamboos^[i].miny-Bamboos^[i].Up[0]*Bamboos^[i].maxx)); Bmp.Canvas.LineTo(Bamboos^[i].meanx+Round(Bamboos^[i].Up[0]*Bamboos^[i].maxy+Bamboos^[i].Up[1]*Bamboos^[i].maxx),Bamboos^[i].meany+Round(Bamboos^[i].Up[1]*Bamboos^[i].maxy-Bamboos^[i].Up[0]*Bamboos^[i].maxx)); end; Bmp.Canvas.Pen.Color:=0*256*256+255*256+255;Bmp.Canvas.Pen.Width:=3; for i:=1 to eN do begin; Bmp.Canvas.MoveTo(Elephants^[i].meanx+Round(Elephants^[i].Up[0]*Elephants^[i].maxy+Elephants^[i].Up[1]*Elephants^[i].maxx),Elephants^[i].meany+Round(Elephants^[i].Up[1]*Elephants^[i].maxy-Elephants^[i].Up[0]*Elephants^[i].maxx)); Bmp.Canvas.LineTo(Elephants^[i].meanx+Round(Elephants^[i].Up[0]*Elephants^[i].maxy+Elephants^[i].Up[1]*Elephants^[i].minx),Elephants^[i].meany+Round(Elephants^[i].Up[1]*Elephants^[i].maxy-Elephants^[i].Up[0]*Elephants^[i].minx)); Bmp.Canvas.LineTo(Elephants^[i].meanx+Round(Elephants^[i].Up[0]*Elephants^[i].miny+Elephants^[i].Up[1]*Elephants^[i].minx),Elephants^[i].meany+Round(Elephants^[i].Up[1]*Elephants^[i].miny-Elephants^[i].Up[0]*Elephants^[i].minx)); Bmp.Canvas.LineTo(Elephants^[i].meanx+Round(Elephants^[i].Up[0]*Elephants^[i].miny+Elephants^[i].Up[1]*Elephants^[i].maxx),Elephants^[i].meany+Round(Elephants^[i].Up[1]*Elephants^[i].miny-Elephants^[i].Up[0]*Elephants^[i].maxx)); Bmp.Canvas.LineTo(Elephants^[i].meanx+Round(Elephants^[i].Up[0]*Elephants^[i].maxy+Elephants^[i].Up[1]*Elephants^[i].maxx),Elephants^[i].meany+Round(Elephants^[i].Up[1]*Elephants^[i].maxy-Elephants^[i].Up[0]*Elephants^[i].maxx)); end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for i:=1 to eN do begin; x:=Elephants^[i].meanx; y:=Elephants^[i].meany; while true do begin; mindist:=1000000000; for j:=1 to bN do if (Bamboos^[j].EatenBy=i) and (not Bamboos^[j].Processed) and (sqr(x-Bamboos^[j].meanx)+sqr(y-Bamboos^[j].meany)<mindist) then begin; mindist:=sqr(x-Bamboos^[j].meanx)+sqr(y-Bamboos^[j].meany); minj:=j; end; if mindist=1000000000 then break; Bmp.Canvas.Pen.Color:=0*256*256+0*256+255; Bmp.Canvas.Pen.Width:=3; Bmp.Canvas.MoveTo(x,y); Bmp.Canvas.LineTo(Bamboos^[minj].meanx,Bamboos^[minj].meany); x:=Bamboos^[minj].meanx; y:=Bamboos^[minj].meany; Bamboos^[minj].Processed:=true; end; end; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for i:=1 to eN do for j:=i+1 to eN do if(Elephants^[i].meany*bw+Elephants^[i].meanx>Elephants^[j].meany*bw+Elephants^[j].meanx) then begin; tmp:=Elephants^[i]; Elephants^[i]:=Elephants^[j]; Elephants^[j]:=tmp; end; for i:=1 to eN do begin; S:='Elephant '+IntToStr(i)+' - '+IntToStr(Elephants^[i].EatenN); if (Elephants^[i].EatenN=1)then S:=S+' bamboo' else S:=S+' bamboos'; Result.Add(S); end; Gauge.Progress:=0; end; end.
unit uRoedor; interface uses System.SysUtils, DBClient, uCustomAttImpl; type TRoedor = class [Audit] procedure Post; virtual; private FCds: TClientDataSet; FPeso: Extended; FAltura: Extended; FComprimento: Extended; FTipo: string; FId: Integer; public constructor CreateAltered(cds: TClientDataSet); property Id: Integer read FId write FId; property Tipo: string read FTipo write FTipo; property Peso: Extended read FPeso write FPeso; property Altura: Extended read FAltura write FAltura; property Comprimento: Extended read FComprimento write FComprimento; end; implementation { TRoedor } constructor TRoedor.CreateAltered(cds: TClientDataSet); begin FCds := cds; end; procedure TRoedor.Post; begin if Fcds.Locate('ID', Self.Id, []) then FCds.Edit else begin FCds.Append; FCds.FieldByName('ID').Value := Self.Id; end; FCds.FieldByName('ROEDOR').Value := Self.Tipo; FCds.FieldByName('PESO').Value := Self.Peso; FCds.FieldByName('ALTURA').Value := Self.Altura; FCds.FieldByName('COMPRIMENTO').Value := Self.Comprimento; FCds.Post; end; end.
unit UBackupInfoFace; interface uses UChangeInfo, SysUtils, Generics.Collections, ComCtrls, UMyUtil, UModelUtil, Classes, DateUtils, UIconUtil, StdCtrls, uDebug, SyncObjs, RzPanel, VirtualTrees, Math, IniFiles; type PathTypeIconUtil = class public class function getIcon( FullPath, PathType : string ) : Integer; end; {$Region ' 数据结构与辅助类 '} // 界面 VirtualString 路径信息 PVstBackupItemData = ^TVstBackupItemData; TVstBackupItemData = record public FolderName, PathType : WideString; IsEncrypt, IsExist : Boolean; IsDiable, IsAuctoSync: Boolean; SyncTimeType, SyncTimeValue : Integer; LastSyncTime, NextSyncTime : TDateTime; FileCount, CopyCount : Integer; ItemSize, CompletedSpace : Int64; FolderStatus : WideString; end; // 界面 ListView 文件信息 TBackupLvFaceData = class public FullPath : string; IsFolder : Boolean; public constructor Create( _FullPath : string ); procedure SetIsFolder( _IsFolder : Boolean ); end; TFindNodeIcon = class private PathType : string; IsExist, IsEmpty : Boolean; IsLoading, IsWaiting, IsRefreshing, IsAnalyzing : Boolean; IsFullBackup, IsEmptyBackup, IsDisable : Boolean; public constructor Create( Node : PVirtualNode ); function get : Integer; private function getFileIcon : Integer; function getFolderIcon : Integer; end; VstBackupItemUtil = class public class function getStatus( Node : PVirtualNode ): string; class function getStatusInt( Node : PVirtualNode ): Integer; class function getStatusIcon( Node : PVirtualNode ): Integer; class function getStatusHint( Node : PVirtualNode ): string; class function getBackupStatus( CompletedSpace, TotalSpace : Int64 ): string; public class function getNodeFullPath( Node : PVirtualNode ): string; class function getHintStr( Node : PVirtualNode ): string; public class function getNextSyncTimeStr( Node : PVirtualNode ): string; public class function getSelectPath: string; class function getSelectPathList : TStringList; public class function IsRootPath( FolderPath : string ): Boolean; end; LvBackupFileUtil = class public class function IsFolderShow( FolderPath : string ): Boolean; class function IsFileShow( FilePath : string ): Boolean; class function getBackupStatus( CompletedSpace, TotalSpace : Int64 ): string; public class function getSelectPath : string; end; {$EndRegion} {$Region ' 选择备份目录VirtualTree界面 写操作 ' } // 写信息 父类 TBackupVtWriteInfo = class( TChangeInfo ) public FullPath : string; public constructor Create( _FullPath : string ); end; // 添加 信息 TBackupVtAddInfo = class( TBackupVtWriteInfo ) public procedure Update;override; end; // 删除 信息 TBackupVtRemoveInfo = class( TBackupVtWriteInfo ) public procedure Update;override; end; {$EndRegion} {$Region ' 备份路径VirtualTree界面 写操作 '} // 添加 第一个 Backup Item 时 界面处理 TBackupItemFirstHandle = class public procedure Update; end; // 没有 Backup Item 时 界面处理 TBackupItemEmptyHandle = class public procedure Update; end; // 父类 TVstBackupPathChange = class( TChangeInfo ) public VstBackupItem : TVirtualStringTree; public procedure Update;override; end; {$Region ' 修改 备份路径 ' } // 修改 TVstBackupPathWrite = class( TVstBackupPathChange ) public FullPath : string; protected PathNode : PVirtualNode; PathData : PVstBackupItemData; public constructor Create( _FullPath : string ); protected function FindPathNode : Boolean; procedure RefreshPathNode; procedure RefreshNextSyncTime; end; // 添加 备份路径 TVstBackupPathAdd = class( TVstBackupPathWrite ) public PathType : string; IsEncrypt : Boolean; IsDisable, IsAuctoSync : Boolean; SyncTimeType, SyncTimeValue : Integer; LastSyncTime : TDateTime; CopyCount, FileCount : Integer; FileSize, CompletedSize : Int64; public procedure SetPathType( _PathType : string ); procedure SetBackupInfo( _IsDisable : Boolean ); procedure SetSyncTimeInfo( _IsAuctoSync : Boolean; _SyncTimeType, _SyncTimeValue : Integer; _LastSyncTime : TDateTime ); procedure SetIsEncrypt( _IsEncrypt : Boolean ); procedure SetCountInfo( _CopyCount, _FileCount : Integer ); procedure SetSpaceInfo( _FileSize, _CompletedSize : Int64 ); procedure Update;override; end; // 修改 备份 Copy 信息 TVstBackupPathSetCopyCount = class( TVstBackupPathWrite ) private CopyCount : Integer; public procedure SetCopyCount( _CopyCount : Integer ); procedure Update;override; private procedure ResetChildNode( ChildNode : PVirtualNode ); end; {$Region ' 修改 同步时间信息 ' } // 设置 上一次 同步时间 TVstBackupPathSetLastSyncTime = class( TVstBackupPathWrite ) private LastSyncTime : TDateTime; public procedure SetLastSyncTime( _LastSyncTime : TDateTime ); procedure Update;override; end; // 设置 同步周期 TVstBackupPathSetSyncTime = class( TVstBackupPathWrite ) private IsAutoSync : Boolean; SyncTimeType, SyncTimeValue : Integer; public procedure SetIsAutoSync( _IsAutoSync : Boolean ); procedure SetSyncTimeInfo( _SyncTimeType, _SyncTimeValue : Integer ); procedure Update;override; end; // 刷新 下一次 同步时间 TVstBackuppathRefreshNextSyncTime = class( TVstBackupPathWrite ) public procedure Update;override; end; {$EndRegion} {$Region ' 修改 状态信息 '} // 是修改 Path Exist 状态 TVstBackupPathIsExist = class( TVstBackupPathWrite ) public IsExist : Boolean; public procedure SetIsExist( _IsExist : Boolean ); procedure Update;override; end; // 是否 禁止备份 TVstBackupPathIsDisable = class( TVstBackupPathWrite ) public IsDisable : Boolean; public procedure SetIsDisable( _IsDisable : Boolean ); procedure Update;override; end; // 设置 备份路径状态 TVstBackupPathSetStatus = class( TVstBackupPathWrite ) private Status : string; public procedure SetStatus( _Status : string ); procedure Update;override; end; {$EndRegion} // 刷新 选择的 Node 信息 TVstBackupPathRefreshSelectNode = class( TVstBackupPathWrite ) public procedure Update;override; end; // 删除 根节点信息 TVstBackupPathRemove = class( TVstBackupPathWrite ) public procedure Update;override; end; {$EndRegion} {$Region ' 修改 备份目录 ' } // 修改 TVstBackupFolderChange = class( TVstBackupPathChange ) public FolderPath : string; protected FolderNode : PVirtualNode; FolderData : PVstBackupItemData; protected RootFolderNode : PVirtualNode; RootFolderData : PVstBackupItemData; public constructor Create( _FolderPath : string ); protected function FindRootFolderNode : Boolean; function FindFolderNode : Boolean; procedure ResetFolderNode; protected function FindChildNode( ParentNode : PVirtualNode; ChileName : string ): PVirtualNode; end; // 添加 备份目录 TVstBackupFolderAdd = class( TVstBackupFolderChange ) private FileCount : Integer; FileSize, CompletedSize : Int64; public procedure SetCountInfo( _FileCount : Integer ); procedure SetSpaceInfo( _FileSize, _CompletedSize : Int64 ); procedure Update;override; private procedure IniFolderNode( NewNode : PVirtualNode ); procedure AddFolderNode; end; // 设置 备份目录 空间信息 TVstBackupFolderSetSpace = class( TVstBackupFolderChange ) private FileCount : Integer; Size : Int64; public procedure SetFileCount( _FileCount : Integer ); procedure SetSize( _Size : Int64 ); procedure Update;override; end; {$Region ' 修改 已完成空间 信息 ' } // 修改 TVstBackupFolderChangeCompletedSpace = class( TVstBackupFolderChange ) public CompletedSpace : Int64; public procedure SetCompletedSpace( _CompletedSpace : Int64 ); protected procedure RefreshLvStatus( Node : PVirtualNode ); end; // 添加 已完成空间 TVstBackupFolderAddCompletedSpace = class( TVstBackupFolderChangeCompletedSpace ) public procedure Update;override; end; // 删除 已完成空间 TVstBackupFolderRemoveCompletedSpace = class( TVstBackupFolderChangeCompletedSpace ) public procedure Update;override; end; // 设置 已完成空间 TVstBackupFolderSetCompletedSpace = class( TVstBackupFolderChangeCompletedSpace ) private LastCompletedSpace : Int64; public procedure SetLastCompletedSpace( _LastCompletedSpace : Int64 ); procedure Update;override; end; {$EndRegion} // 设置 节点状态 TVstBackupFolderSetStatus = class( TVstBackupFolderChange ) private PathStatus : string; public procedure SetPathStatus( _PathStatus : string ); procedure Update;override; end; // 删除 子节点信息 TVstBackupItemRemoveChild = class( TVstBackupFolderChange ) public procedure Update;override; end; {$EndRegion} {$EndRegion} {$Region ' 备份信息ListView界面 写操作 ' } LvBackupFileStatusUtil = class public class function getSelectPath : string; class function getSelectPathList : TStringList; public class function getIsFolder( FilePath : string ): Boolean; end; // 父类 TLvBackupFileChangeInfo = class( TChangeInfo ) public LvBackupFile : TListView; public procedure Update;override; end; // 修改 TBackupLvWriteInfo = class( TLvBackupFileChangeInfo ) public FilePath : string; protected FileItem : TListItem; ItemIndex : Integer; ItemData : TBackupLvFaceData; public constructor Create( _FullPath : string ); protected function FindFileItem : Boolean; function getStatusIcon( BackupStatus : string ): Integer; end; // 添加 信息 TBackupLvAddInfo = class( TBackupLvWriteInfo ) public IsFolder : Boolean; FileSize : Int64; FileTime : TDateTime; public CopyCount : Integer; Status, StatusShow : string; public procedure SetIsFolder( _IsFolder : Boolean ); procedure SetFileInfo( _FileSize : Int64; _FileTime : TDateTime ); procedure SetCopyInfo( _CopyCount : Integer ); procedure SetStatusInfo( _Status, _StatusShow : string ); procedure Update;override; end; TBackupLvAddList = class( TObjectList<TBackupLvAddInfo> )end; // Backup Status 信息 TBackupLvStatusInfo = class( TBackupLvWriteInfo ) private CopyCountStatus : string; Status, StatusShow : string; public procedure SetCopyCountStatus( _BackupCopyCount : string ); procedure SetStatusInfo( _Status, _StatusShow : string ); procedure Update;override; end; // 删除 信息 TBackupLvRemoveInfo = class( TBackupLvWriteInfo ) public procedure Update;override; end; // 读取一个目录的信息 TBackupLvReadFolderInfo = class( TLvBackupFileChangeInfo ) public FullPath : string; BackupLvAddList : TBackupLvAddList; public constructor Create( _FullPath : string ); procedure AddBackupLv( BackupLvAddInfo : TBackupLvAddInfo ); procedure Update;override; destructor Destroy; override; end; // 清空 信息 TBackupLvClearInfo = class( TLvBackupFileChangeInfo ) public procedure Update;override; end; {$EndRegion} {$Region ' 备份信息 属性窗口界面 写操作 ' } {$Region ' 备份文件 详细信息 ' } TShowCopyInfo = class public OwnerID : string; OwnerStatus : string; public OwnerOnlineTime : string; public constructor Create( _OwnerID, _OwnerStatus : string ); procedure SetOwnerOnlineTime( _OwnerOnlineTime : string ); end; TShowCopyPair = TPair< string , TShowCopyInfo >; TShowCopyHash = class(TStringDictionary< TShowCopyInfo >); // 文件 Detail 信息 TBackupFrmDetailInfo = class( TChangeInfo ) public FullPath : string; FileSize : Int64; BackupStatus : string; FileCount : Integer; public ShowCopyHash : TShowCopyHash; public constructor Create; procedure Update;override; destructor Destroy; override; end; {$EndRegion} {$Region ' 备份路径 属性界面 ' } // 数据结构 TLvBackupPathProData = class public FullPath : string; public constructor Create( _FullPath : string ); end; // 父类 TLvBackupPathProChange = class( TChangeInfo ) public LvBackupPathPro : TListView; public procedure Update;override; end; // 修改 TLvBackupPathProWrite = class( TLvBackupPathProChange ) public FullPath : string; protected PathItem : TListItem; PathIndex : Integer; public constructor Create( _FullPath : string ); protected function FindPathItem : Boolean; end; // 添加 TLvBackupPathProAdd = class( TLvBackupPathProWrite ) public procedure Update;override; end; // 删除 TLvBackupPathProRemove = class( TLvBackupPathProWrite ) public procedure Update;override; end; {$EndRegion} {$EndRegion} {$Region ' 网络备份 Panel 公告信息 ' } // 显示 公告 TPlBackupBoardShow = class( TChangeInfo ) public ShowStr : string; public constructor Create( _ShowStr : string ); procedure Update;override; end; // 显示 公告图标 TPlBackupBoardIconShow = class( TChangeInfo ) public IsShow : Boolean; public constructor Create( _IsShow : Boolean ); procedure Update;override; end; // 公告栏的隐藏 TBackupBoardInvisibleThread = class( TThread ) private LastStr : string; LastTime : TDateTime; public constructor Create; procedure ResetLastStr( _LastStr : string ); destructor Destroy; override; protected procedure Execute; override; private procedure BackupBoardInvisible; end; {$EndRegion} {$Region ' 本地备份 Panel 公告信息 ' } // 本地备份信息 公告 TPlBackupDesBoardShowInfo = class( TChangeInfo ) public FilePath : string; ShowType : string; public constructor Create( _FilePath : string ); procedure SetShowType( _ShowType : string ); procedure Update;override; protected procedure ShowFileType; end; // 本地备份信息 + 空间 公告 TPlBackupDesBoardShowSizeInfo = class( TPlBackupDesBoardShowInfo ) private FileSize : Int64; public procedure SetFileSize( _FileSize : Int64 ); procedure Update;override; end; // 本地备份信息 可见性 TPlBackupDesBoardVisibleInfo = class( TChangeInfo ) private IsVisible : Boolean; public constructor Create( _IsVisible : Boolean ); procedure Update;override; end; // 本地备份进度 可见性 TPlBackupDesPercentVisibleInfo = class( TChangeInfo ) private IsVisible : Boolean; ExplorerPath : string; public constructor Create( _IsVisible : Boolean ); procedure SetExplorerPath( _ExplorerPath : string ); procedure Update;override; end; // 本地备份进度 公告 TPlBackupDesBoardPercentInfo = class( TChangeInfo ) public Percent : Integer; PercentCompareStr : string; public constructor Create( _Percent : Integer ); procedure SetPercentCompareStr( _PercentCompareStr : string ); procedure Update;override; end; {$EndRegion} {$Region ' 备份进度条 写操作 ' } TBackupPgWriteInfo = class( TChangeInfo ) end; // 刷新进度条 TBackupPgRefreshInfo = class( TBackupPgWriteInfo ) private CompletedSize : Int64; TotalSize : Int64; public constructor Create( _CompletedSize, _TotalSize : Int64 ); procedure Update;override; end; // 添加 已完成 TBackupPgAddCompletedInfo = class( TBackupPgWriteInfo ) private AddSize : Int64; public constructor Create( _AddSize : Int64 ); procedure Update;override; private procedure ShowProgress; end; // 移除 已完成 TBackupPgRemoveCompletedInfo = class( TBackupPgWriteInfo ) private RemoveSize : Int64; public constructor Create( _RemoveSize : Int64 ); procedure Update;override; end; // 显示进度条 TBackupPgShowInfo = class( TChangeInfo ) public procedure Update;override; end; // 隐藏备份 进度条 线程 TBackupProgressHideThread = class( TThread ) private LastShowTime : TDateTime; public constructor Create; procedure ShowBackupProgress; destructor Destroy; override; protected procedure Execute; override; private procedure HideProgress; end; {$EndRegion} {$Region ' 备份 界面控制 ' } // 备份扫描 完成 TBackupTvBackupStopInfo = class( TChangeInfo ) public procedure Update;override; end; {$EndRegion} LanguageUtil = class public class function getPercentageStr( Str : string ): string; class function getSyncTimeStr( Str : string ): string; end; const NodeIcon_FolderIncompleted = 0; NodeIcon_FolderPartCompleted = 1; NodeIcon_FolderCompleted = 2; NodeIcon_FolderNotExists = 3; NodeIcon_FolderEmpty = 4; NodeIcon_FolderLoading = 5; NodeIcon_FolderWaiting = 5; NodeIcon_FolderRefreshing = 6; NodeIcon_FolderAnalyzing = 7; NodeIcon_FolderDisable = 15; NodeIcon_FileIncompleted = 8; NodeIcon_FilePartCompleted = 9; NodeIcon_FileCompleted = 10; NodeIcon_FileNotExists = 11; NodeIcon_FileLoading = 12; NodeIcon_FileWaiting = 12; NodeIcon_FileRefreshing = 13; NodeIcon_FileAnalyzing = 14; NodeIcon_FileDisable = 16; const NodeStatusHint_Loading = 'The directory is loading...'; NodeStatusHint_Waiting = 'The directory is waiting...'; NodeStatusHint_Refreshing = 'The directory is refreshing...'; NodeStatusHint_Analyzing = 'The directory is analyzing...'; NodeStatusHint_NotExists = 'No backup directory exists'; NodeStatusHint_Disable = 'The directory is Disable'; NodeStatus_Disable = 'Disable'; NodeStatus_Loading = 'Loading...'; NodeStatus_Waiting = 'Waiting...'; NodeStatus_Refreshing = 'Refreshing...'; NodeStatus_Analyzing = 'Analyzing...'; NodeStatus_NotExists = 'Not exists'; NodeStatus_Empty = 'Empty directory'; NodeStatus_Incompleted = 'Incompleted'; NodeStatus_PartCompleted = 'Partially completed'; NodeStatus_Completed = 'Completed'; LvFileStatus_FileSize = 0; LvFileStatus_FileTime = 1; LvFileStatus_CopyCount = 2; LvFileStatus_BackupStatus = 3; BackupPriorityIcon_Offline = 0; BackupPriorityIcon_Online = 1; BackupPriorityIcon_Alway = 2; BackupPriorityIcon_Never = 3; BackupPriorityIcon_High = 4; BackupPriorityIcon_Normal = 5; BackupPriorityIcon_Low = 6; BackupStatus_Disable = 'Disable'; LvBackupDes_Status = 0; Label_SyncTime : string = 'Synchronize Every %d Minutes'; Label_CopyCount : string = 'Pre-set Copy Quantity : %d'; SbRemainTime_Min : string = '%d Min'; NodeStatus_Encrypted = ' (Encrypted)'; BackupDesBroadType_Copy = 'Copying'; BackupDesBroadType_Removing = 'Removing'; BackupDesBroadType_Recycling = 'Recycling'; PlLocalBackupDesProgress_Heigh = 28; FolderStatus_Loading = 'Loading'; FolderStatus_Waiting = 'Waiting'; FolderStatus_Refreshing = 'Refreshing'; FolderStatus_Analyzing = 'Analyzing'; FolderStatus_Stop = 'Stop'; const LocalBackupStatus_Copying = 'Copying'; LocalBackupStatus_Removing = 'Removeing'; LocalBackupStatus_Disable = 'Disable'; LocalBackupStatus_NotExist = 'Not Exist'; LocalBackupStatus_Unmodifiable = 'Cannot Write'; LocalBackupStatus_LackSpace = 'Space Insufficient'; LocalBackupStatus_FreeLimit = 'Incompleted'; LocalBackupStatus_Completed = 'Completed'; LocalBackupStatus_InCompleted = 'Incompleted'; LocalBackupStatus_Recycled = 'Recycled'; LocalBackupStatus_Recycling = 'Recycling'; LocalBackupSourceStatus_Copy = 'Copying'; LocalBackupSourceStatus_Refresh = 'Analyzing'; const Ini_Sync = 'Sync'; Ini_LastSyncTime = 'LastSyncTime'; SyncTimeShow_LastSync = 'Last Synchronization: '; SyncTimeShow_SyncEvery = 'Synchronize Every: '; SyncTimeShow_SyncRemain = 'Sync Time Remain: '; var // Backup Progress BackupProgress_Completed : Int64 = 0; BackupProgress_Total : Int64 = 0; TvNodePath_Selected : string = ''; MyBackupFileFace : TMyChildFaceChange; BackupBoardInvisibleThread : TBackupBoardInvisibleThread; BackupProgressHideThread : TBackupProgressHideThread; Path_LocalCopyExplorer : string = ''; implementation uses UMainForm, UFormBackupPath, UFormFilestatusDetail, USettingInfo, UMainFormFace, UNetworkFace, UMyBackupInfo, UMyNetPcInfo, UFormUtil, UFormBackupProperties, URegisterInfo, UBackupInfoControl, ULocalBackupControl; { TBackupTvWriteInfo } constructor TVstBackupPathWrite.Create(_FullPath: string); begin FullPath := _FullPath; end; function TVstBackupPathWrite.FindPathNode: Boolean; var SelectNode : PVirtualNode; SelectData : PVstBackupItemData; FolderName : string; begin Result := False; // 遍历关联目录 SelectNode := vstBackupItem.RootNode.FirstChild; while Assigned( SelectNode ) do begin SelectData := vstBackupItem.GetNodeData( SelectNode ); FolderName := SelectData.FolderName; // 找到节点 if FolderName = FullPath then begin PathNode := SelectNode; PathData := VstBackupItem.GetNodeData( PathNode ); Result := True; Break; end; SelectNode := SelectNode.NextSibling; end; end; procedure TVstBackupPathWrite.RefreshNextSyncTime; var SyncMins : Integer; begin SyncMins := TimeTypeUtil.getMins( PathData.SyncTimeType, PathData.SyncTimeValue ); PathData.NextSyncTime := IncMinute( PathData.LastSyncTime, SyncMins ); end; procedure TVstBackupPathWrite.RefreshPathNode; begin VstBackupItem.RepaintNode( PathNode ); end; { TBackupVtWriteInfo } constructor TBackupVtWriteInfo.Create(_FullPath: string); begin FullPath := _FullPath; end; { TBackupLvAddInfo } procedure TBackupLvAddInfo.SetStatusInfo(_Status, _StatusShow: string); begin Status := _Status; StatusShow := _StatusShow; end; procedure TBackupLvAddInfo.SetCopyInfo(_CopyCount: Integer); begin CopyCount := _CopyCount; end; procedure TBackupLvAddInfo.SetFileInfo(_FileSize: Int64; _FileTime: TDateTime); begin FileSize := _FileSize; FileTime := _FileTime; end; procedure TBackupLvAddInfo.SetIsFolder(_IsFolder: Boolean); begin IsFolder := _IsFolder; end; procedure TBackupLvAddInfo.Update; var FileSizeStr, CopyCountStr : string; begin inherited; // 已存在 if FindFileItem then Exit; // 提取信息 FileSizeStr := MySize.getFileSizeStr( FileSize ); if IsFolder then CopyCountStr := '' else CopyCountStr := IntToStr( CopyCount ); if Status = BackupStatus_Empty then StatusShow := ''; // 添加 数据 ItemData := TBackupLvFaceData.Create( FilePath ); ItemData.SetIsFolder( IsFolder ); StatusShow := LanguageUtil.getPercentageStr( StatusShow ); // 添加 界面 with LvBackupFile.Items.Add do begin Caption := ExtractFileName( FilePath ); SubItems.Add( FileSizeStr ); SubItems.Add( DateTimeToStr( FileTime ) ); SubItems.Add( CopyCountStr ); SubItems.Add( StatusShow ); ImageIndex := MyIcon.getIconByFilePath( FilePath ); SubItemImages[ LvFileStatus_BackupStatus ] := getStatusIcon( Status ); Data := ItemData; end; end; { TBackupLvWriteInfo } constructor TBackupLvWriteInfo.Create(_FullPath: string); begin FilePath := _FullPath; end; { TBackupTvStatusInfo } function TBackupLvWriteInfo.FindFileItem: Boolean; var i : Integer; SelectData : TBackupLvFaceData; begin Result := False; for i := 0 to LvBackupFile.Items.Count - 1 do begin SelectData := LvBackupFile.Items[i].Data; if SelectData.FullPath = FilePath then begin FileItem := LvBackupFile.Items[i]; ItemIndex := i; ItemData := FileItem.Data; Result := True; Break; end; end; end; function TBackupLvWriteInfo.getStatusIcon( BackupStatus: string): Integer; begin Result := -1; if BackupStatus = BackupStatus_Incompleted then Result := MyShellBackupStatusIconUtil.getFileIncompleted else if BackupStatus = BackupStatus_PartCompleted then Result := MyShellBackupStatusIconUtil.getFilePartcompleted else if BackupStatus = BackupStatus_completed then Result := MyShellBackupStatusIconUtil.getFilecompleted; end; { TBackupTvAddRootInfo } procedure TVstBackupPathAdd.SetBackupInfo(_IsDisable: Boolean); begin IsDisable := _IsDisable; end; procedure TVstBackupPathAdd.SetCountInfo(_CopyCount, _FileCount: Integer); begin CopyCount := _CopyCount; FileCount := _FileCount; end; procedure TVstBackupPathAdd.SetIsEncrypt(_IsEncrypt: Boolean); begin IsEncrypt := _IsEncrypt; end; procedure TVstBackupPathAdd.SetPathType(_PathType: string); begin PathType := _PathType; end; procedure TVstBackupPathAdd.SetSpaceInfo(_FileSize, _CompletedSize: Int64); begin FileSize := _FileSize; CompletedSize := _CompletedSize; end; procedure TVstBackupPathAdd.SetSyncTimeInfo(_IsAuctoSync : Boolean; _SyncTimeType, _SyncTimeValue: Integer; _LastSyncTime: TDateTime); begin IsAuctoSync := _IsAuctoSync; SyncTimeType := _SyncTimeType; SyncTimeValue := _SyncTimeValue; LastSyncTime := _LastSyncTime; end; procedure TVstBackupPathAdd.Update; var BackupItemFirstHandle : TBackupItemFirstHandle; begin inherited; // 已存在 if FindPathNode then Exit; // 创建 根节点 PathNode := VstBackupItem.AddChild( VstBackupItem.RootNode ); PathData := vstBackupItem.GetNodeData( PathNode ); PathData.FolderName := FullPath; PathData.PathType := PathType; PathData.IsEncrypt := IsEncrypt; PathData.IsExist := True; PathData.IsDiable := IsDisable; PathData.IsAuctoSync := IsAuctoSync; PathData.SyncTimeType := SyncTimeType; PathData.SyncTimeValue := SyncTimeValue; PathData.LastSyncTime := LastSyncTime; PathData.CopyCount := CopyCount; PathData.FileCount := FileCount; PathData.ItemSize := FileSize; PathData.CompletedSpace := CompletedSize; PathData.FolderStatus := FolderStatus_Stop; // 计算下次同步时间 RefreshNextSyncTime; // 添加 第一个 BackupItem if vstBackupItem.RootNodeCount = 1 then begin BackupItemFirstHandle := TBackupItemFirstHandle.Create; BackupItemFirstHandle.Update; BackupItemFirstHandle.Free; end; end; { TBackupVtAddInfo } procedure TBackupVtAddInfo.Update; begin frmSelectBackupPath.AddBackupPath( FullPath ); end; { TBackupVtRemoveInfo } procedure TBackupVtRemoveInfo.Update; begin frmSelectBackupPath.RemoveBackupPath( FullPath ); end; { TBackupTvAddChildInfo } procedure TVstBackupFolderAdd.AddFolderNode; var ParentNode, ChildNode : PVirtualNode; ParentData, ChildData : PVstBackupItemData; RemainPath, FolderName : string; IsFindNext : Boolean; begin // 根路径 if RootFolderData.FolderName = FolderPath then begin FolderNode := RootFolderNode; FolderData := RootFolderData; Exit; end; // 从根目录向下寻找 ParentNode := RootFolderNode; RemainPath := MyString.CutStartStr( MyFilePath.getPath( RootFolderData.FolderName ), FolderPath ); IsFindNext := True; while IsFindNext do // 寻找子目录 begin FolderName := MyString.GetRootFolder( RemainPath ); if FolderName = '' then begin FolderName := RemainPath; IsFindNext := False; end; // 不存在目录, 则创建 ChildNode := FindChildNode( ParentNode, FolderName ); if ChildNode = nil then begin ChildNode := VstBackupItem.AddChild( ParentNode ); IniFolderNode( ChildNode ); ChildData := VstBackupItem.GetNodeData( ChildNode ); ChildData.FolderName := FolderName; ChildData.CopyCount := RootFolderData.CopyCount; end; // 下一层 ParentNode := ChildNode; RemainPath := MyString.CutRootFolder( RemainPath ); end; // 找到节点 FolderNode := ParentNode; FolderData := VstBackupItem.GetNodeData( FolderNode ); end; procedure TVstBackupFolderAdd.IniFolderNode(NewNode: PVirtualNode); var NewData : PVstBackupItemData; begin NewData := VstBackupItem.GetNodeData( NewNode ); NewData.ItemSize := 0; NewData.CompletedSpace := 0; NewData.FileCount := 0; NewData.CopyCount := 0; NewData.PathType := PathType_Folder; NewData.IsEncrypt := False; NewData.IsExist := True; NewData.IsDiable := False; NewData.FolderStatus := FolderStatus_Stop; end; procedure TVstBackupFolderAdd.SetCountInfo(_FileCount : Integer); begin FileCount := _FileCount; end; procedure TVstBackupFolderAdd.SetSpaceInfo(_FileSize, _CompletedSize: Int64); begin FileSize := _FileSize; CompletedSize := _CompletedSize; end; procedure TVstBackupFolderAdd.Update; begin inherited; // 不存在 根路径 if not FindRootFolderNode then Exit; // 添加节点 AddFolderNode; // 设置属性 FolderData.FileCount := FileCount; FolderData.ItemSize := FileSize; FolderData.CompletedSpace := CompletedSize; end; { TBackupTvRemoveInfo } procedure TVstBackupPathRemove.Update; var BackupItemEmptyHandle : TBackupItemEmptyHandle; begin inherited; // 不存在 if not FindPathNode then Exit; // 删除节点 VstBackupItem.DeleteNode( PathNode ); // ListView frmMainForm.lvFileStatus.Clear; frmMainForm.tbtnFsDetail.Enabled := False; frmMainForm.tbtnFsOpen.Enabled := False; frmMainForm.tbtnFsLvlExplorer.Enabled := False; frmMainForm.tbtnFsLvlRemove.Enabled := False; // VirtualTree frmMainForm.tbtnFsDelete.Enabled := False; frmMainForm.tbtnFsExplorer.Enabled := False; // 删除 最后一个 BackupItem if vstBackupItem.RootNodeCount <= 0 then begin BackupItemEmptyHandle := TBackupItemEmptyHandle.Create; BackupItemEmptyHandle.Update; BackupItemEmptyHandle.Free; end; end; { TBackupLvRemoveInfo } procedure TBackupLvRemoveInfo.Update; begin inherited; // 不存在 if not FindFileItem then Exit; // 删除 LvBackupFile.Items.Delete( ItemIndex ); end; { TBackupLvClearInfo } procedure TBackupLvClearInfo.Update; begin inherited; LvBackupFile.Clear; frmMainForm.tbtnFsDetail.Enabled := False; frmMainForm.tbtnFsOpen.Enabled := False; frmMainForm.tbtnFsLvlExplorer.Enabled := False; frmMainForm.tbtnFsLvlRemove.Enabled := False; end; { TBackupLvStatusInfo } procedure TBackupLvStatusInfo.SetCopyCountStatus(_BackupCopyCount: string); begin CopyCountStatus := _BackupCopyCount; end; procedure TBackupLvStatusInfo.SetStatusInfo(_Status, _StatusShow : string); begin Status := _Status; StatusShow := _StatusShow; end; procedure TBackupLvStatusInfo.Update; begin inherited; // 不存在 if not FindFileItem then Exit; StatusShow := LanguageUtil.getPercentageStr( StatusShow ); // 修改信息 FileItem.SubItems[ LvFileStatus_CopyCount ] := CopyCountStatus; FileItem.SubItems[ LvFileStatus_BackupStatus ] := StatusShow; FileItem.SubItemImages[ LvFileStatus_BackupStatus ] := getStatusIcon( Status ); end; { TBackupLvFaceData } constructor TBackupLvFaceData.Create(_FullPath: string); begin FullPath := _FullPath; end; procedure TBackupLvFaceData.SetIsFolder(_IsFolder: Boolean); begin IsFolder := _IsFolder; end; { TShowCopyInfo } constructor TShowCopyInfo.Create(_OwnerID, _OwnerStatus: string); begin OwnerID := _OwnerID; OwnerStatus := _OwnerStatus; end; procedure TShowCopyInfo.SetOwnerOnlineTime(_OwnerOnlineTime: string); begin OwnerOnlineTime := _OwnerOnlineTime; end; { TBackupFrmDetailInfo } constructor TBackupFrmDetailInfo.Create; begin ShowCopyHash := TShowCopyHash.Create; end; destructor TBackupFrmDetailInfo.Destroy; begin ShowCopyHash.Free; inherited; end; procedure TBackupFrmDetailInfo.Update; var LvCopyStatus : TListView; p : TShowCopyPair; PropertiesStr, BackupStatusStr, OnlineTimeStr, OwnerStr : string; begin BackupStatusStr := frmFileStatusDetail.siLang_frmFileStatusDetail.GetText( BackupStatus ); frmFileStatusDetail.edtFullPath.Text := FullPath; frmFileStatusDetail.lbFileSize.Caption := MySize.getFileSizeStr( FileSize ); frmFileStatusDetail.lbFileCount.Caption := IntToStr( FileCount ); frmFileStatusDetail.lbFileStatus.Caption := BackupStatusStr; LvCopyStatus := frmFileStatusDetail.lvFileOwners; LvCopyStatus.Clear; for p in ShowCopyHash do with LvCopyStatus.Items.Add do begin if p.Value.OwnerOnlineTime = Status_Online then OnlineTimeStr := frmFileStatusDetail.siLang_frmFileStatusDetail.GetText( 'StrOnline' ) else OnlineTimeStr := p.Value.OwnerOnlineTime; OwnerStr := frmFileStatusDetail.siLang_frmFileStatusDetail.GetText( p.Value.OwnerStatus ); Caption := p.Value.OwnerID; SubItems.Add( OnlineTimeStr ); SubItems.Add( OwnerStr ); if p.Value.OwnerOnlineTime = Status_Online then ImageIndex := CloudStatusIcon_Online else ImageIndex := CloudStatusIcon_Offline; end; PropertiesStr := frmFileStatusDetail.siLang_frmFileStatusDetail.GetText( 'StrProperties' ); frmFileStatusDetail.Caption := ExtractFileName( FullPath ) + ' ' + PropertiesStr; frmFileStatusDetail.tbtnFileLink.ImageIndex := MyIcon.getIconByFilePath( FullPath ); frmFileStatusDetail.Show; end; { TBackupTvBackupStopInfo } procedure TBackupTvBackupStopInfo.Update; begin // 开启 BackupNow 按钮 frmMainForm.tbtnBackupNow.Enabled := True; end; { TBackupItemEmptyHandle } procedure TBackupItemEmptyHandle.Update; begin // tb Treeview frmMainForm.tbtnBackupNow.Enabled := False; frmMainForm.tbtnBackupClear.Enabled := False; // tb Setting frmMainForm.plBackupProgress.Visible := False; // Backup Broad frmMainForm.plBackupBoard.Visible := False; frmMainForm.plBackupBoardMain.Visible := False; // Enable 背景图案 frmMainForm.vstBackupItem.TreeOptions.PaintOptions := frmMainForm.vstBackupItem.TreeOptions.PaintOptions + [toShowBackground]; end; { TBackupItemFirstHandle } procedure TBackupItemFirstHandle.Update; var stp : TStringTreeOptions; begin // tb Treeview frmMainForm.tbtnBackupNow.Enabled := True; frmMainForm.tbtnBackupClear.Enabled := True; // disable 背景图案 frmMainForm.vstBackupItem.TreeOptions.PaintOptions := frmMainForm.vstBackupItem.TreeOptions.PaintOptions - [toShowBackground]; end; { TPlBackupBoardShow } constructor TPlBackupBoardShow.Create(_ShowStr: string); begin ShowStr := _ShowStr; end; procedure TPlBackupBoardShow.Update; var plBackupBoard : TRzPanel; begin plBackupBoard := frmMainForm.plBackupBoard; if ( ShowStr = '' ) and ( plBackupBoard.Visible ) then BackupBoardInvisibleThread.ResetLastStr( plBackupBoard.Caption ) else begin plBackupBoard.Caption := ShowStr; if ( ShowStr <> '' ) and ( not plBackupBoard.Visible ) then begin plBackupBoard.Visible := True; frmMainForm.plBackupBoardMain.Visible := True; end; end; end; { TBackupBoardInvisibleThread } procedure TBackupBoardInvisibleThread.BackupBoardInvisible; begin if frmMainForm.plBackupBoard.Caption = LastStr then begin frmMainForm.plBackupBoard.Caption := ''; frmMainForm.plBackupBoard.Visible := False; frmMainForm.plBackupBoardMain.Visible := False; end; end; constructor TBackupBoardInvisibleThread.Create; begin inherited Create( True ); end; destructor TBackupBoardInvisibleThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TBackupBoardInvisibleThread.Execute; begin while not Terminated do begin while not Terminated and ( SecondsBetween( Now, LastTime ) < 2 ) do Sleep(100); if Terminated then Break; Synchronize( BackupBoardInvisible ); if not Terminated then Suspend; end; inherited; end; procedure TBackupBoardInvisibleThread.ResetLastStr(_LastStr: string); begin LastStr := _LastStr; LastTime := Now; Resume; end; { TBackupTvSpaceInfo } procedure TVstBackupFolderSetSpace.SetFileCount(_FileCount: Integer); begin FileCount := _FileCount; end; procedure TVstBackupFolderSetSpace.SetSize(_Size: Int64); begin Size := _Size; end; procedure TVstBackupFolderSetSpace.Update; begin inherited; // 不存在 if not FindFolderNode then Exit; // Vst FolderData.FileCount := FileCount; FolderData.ItemSize := Size; // 刷新节点 ResetFolderNode; end; { TBackupProgressInfo } constructor TBackupPgRefreshInfo.Create(_CompletedSize, _TotalSize: Int64); begin CompletedSize := _CompletedSize; TotalSize := _TotalSize; end; procedure TBackupPgRefreshInfo.Update; begin BackupProgress_Completed := CompletedSize; BackupProgress_Total := TotalSize; end; { TBackupPgAddCompletedInfo } constructor TBackupPgAddCompletedInfo.Create(_AddSize: Int64); begin AddSize := _AddSize; end; procedure TBackupPgAddCompletedInfo.ShowProgress; var ProgressStr : string; Percentage : Integer; begin // 空间 ProgressStr := MyPercentage.getCompareStr( BackupProgress_Completed, BackupProgress_Total ); frmMainForm.plBackupProgressPercent.Caption := ProgressStr; // 百分比 Percentage := MyPercentage.getPercent( BackupProgress_Completed, BackupProgress_Total ); frmMainForm.PbBackup.Percent := Percentage; // 显示进度条 if not frmMainForm.plBackupProgress.Visible then frmMainForm.plBackupProgress.Visible := True; // 隐藏进度条 BackupProgressHideThread.ShowBackupProgress; end; procedure TBackupPgAddCompletedInfo.Update; begin // 添加 BackupProgress_Completed := BackupProgress_Completed + AddSize; BackupProgress_Completed := Min( BackupProgress_Completed, BackupProgress_Total ); // 刷新显示 ShowProgress; end; { PathTypeIconUtil } class function PathTypeIconUtil.getIcon(FullPath, PathType: string): Integer; begin if PathType = PathType_File then Result := MyIcon.getIconByFileExt( FullPath ) else Result := MyShellIconUtil.getFolderIcon; end; { TBackupTvCopyCountInfo } procedure TVstBackupPathSetCopyCount.ResetChildNode(ChildNode: PVirtualNode); var SelectNode : PVirtualNode; ChildData : PVstBackupItemData; begin // 重设 Copy 数 ChildData := VstBackupItem.GetNodeData( ChildNode ); ChildData.CopyCount := CopyCount; VstBackupItem.RepaintNode( ChildNode ); // 刷新 子节点 SelectNode := ChildNode.FirstChild; while Assigned( SelectNode ) do begin ResetChildNode( SelectNode ); SelectNode := SelectNode.NextSibling; end; end; procedure TVstBackupPathSetCopyCount.SetCopyCount(_CopyCount: Integer); begin CopyCount := _CopyCount; end; procedure TVstBackupPathSetCopyCount.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // 设置 Copy 数 ResetChildNode( PathNode ); // 刷新节点 RefreshPathNode; end; { TBackupTvRemoveChildInfo } procedure TVstBackupItemRemoveChild.Update; begin inherited; // 不存在 if not FindFolderNode then Exit; // 删除 选中的节点 if VstBackupItem.Selected[ FolderNode ] then begin // ListView frmMainForm.lvFileStatus.Clear; frmMainForm.tbtnFsDetail.Enabled := False; frmMainForm.tbtnFsOpen.Enabled := False; frmMainForm.tbtnFsLvlExplorer.Enabled := False; frmMainForm.tbtnFsLvlRemove.Enabled := False; end; // 删除 界面 vstBackupItem.DeleteNode( FolderNode ); end; { TBackupPgRemoveCompletedInfo } constructor TBackupPgRemoveCompletedInfo.Create(_RemoveSize: Int64); begin RemoveSize := _RemoveSize; end; procedure TBackupPgRemoveCompletedInfo.Update; begin // 删除 BackupProgress_Completed := BackupProgress_Completed - RemoveSize; BackupProgress_Completed := Max( BackupProgress_Completed, 0 ); end; { TPlBackupDesBoardShowInfo } constructor TPlBackupDesBoardShowInfo.Create(_FilePath: string); begin FilePath := _FilePath; end; procedure TPlBackupDesBoardShowInfo.SetShowType(_ShowType: string); begin ShowType := _ShowType; end; procedure TPlBackupDesBoardShowInfo.ShowFileType; var ShowStr : string; begin if ShowType = BackupDesBroadType_Copy then ShowStr := 'Copying' else if ShowType = BackupDesBroadType_Removing then ShowStr := 'Removing' else if ShowType = BackupDesBroadType_Recycling then ShowStr := 'Recycling'; ShowStr := frmMainForm.siLang_frmMainForm.GetText( ShowStr ); ShowStr := ' ' + ShowStr; // 相同 则 跳过 if frmMainForm.plBackupDesType.Caption = ShowStr then Exit; frmMainForm.plBackupDesType.Caption := ShowStr; end; procedure TPlBackupDesBoardShowInfo.Update; begin ShowFileType; frmMainForm.plBackupDesShow.Caption := ExtractFileName( FilePath ); end; { TPlBackupDesBoardPercentInfo } constructor TPlBackupDesBoardPercentInfo.Create(_Percent: Integer); begin Percent := _Percent; end; procedure TPlBackupDesBoardPercentInfo.SetPercentCompareStr( _PercentCompareStr: string); begin PercentCompareStr := _PercentCompareStr; end; procedure TPlBackupDesBoardPercentInfo.Update; begin frmMainForm.PbLocalBackupCopy.Percent := Percent; frmMainForm.plLocalBackupCopyPercentShow.Caption := PercentCompareStr; end; { TPlBackupDesBoardShowSizeInfo } procedure TPlBackupDesBoardShowSizeInfo.SetFileSize(_FileSize: Int64); begin FileSize := _FileSize; end; procedure TPlBackupDesBoardShowSizeInfo.Update; var ShowStr : string; begin ShowFileType; ShowStr := ExtractFileName( FilePath ) + ' ' + MySize.getFileSizeStr( FileSize ); frmMainForm.plBackupDesShow.Caption := ShowStr; end; { TPlBackupDesPercentVisibleInfo } constructor TPlBackupDesPercentVisibleInfo.Create(_IsVisible: Boolean); begin IsVisible := _IsVisible; end; procedure TPlBackupDesPercentVisibleInfo.SetExplorerPath(_ExplorerPath: string); begin ExplorerPath := _ExplorerPath; end; procedure TPlBackupDesPercentVisibleInfo.Update; var PercentageHeigh, ChangeHeight : Integer; begin if IsVisible then begin frmMainForm.PbLocalBackupCopy.Percent := 0; Path_LocalCopyExplorer := ExplorerPath; end else Path_LocalCopyExplorer := ''; PercentageHeigh := frmMainForm.plLocalBackupPercentage.Height; if not IsVisible and ( PercentageHeigh = PlLocalBackupDesProgress_Heigh ) then ChangeHeight := -PlLocalBackupDesProgress_Heigh else if IsVisible and ( PercentageHeigh = 0 ) then ChangeHeight := PlLocalBackupDesProgress_Heigh else ChangeHeight := 0; frmMainForm.plBackupDesBoard.Height := frmMainForm.plBackupDesBoard.Height + ChangeHeight; frmMainForm.plLocalCopyExplorer.Visible := IsVisible; end; { TPlBackupDesBoardVisibleInfo } constructor TPlBackupDesBoardVisibleInfo.Create(_IsVisible: Boolean); begin IsVisible := _IsVisible; end; procedure TPlBackupDesBoardVisibleInfo.Update; begin frmMainForm.plBackupDesBoard.Visible := IsVisible; end; { TBackupLvReadFolderInfo } procedure TBackupLvReadFolderInfo.AddBackupLv( BackupLvAddInfo: TBackupLvAddInfo); begin BackupLvAddList.Add( BackupLvAddInfo ); end; constructor TBackupLvReadFolderInfo.Create(_FullPath: string); begin FullPath := _FullPath; BackupLvAddList := TBackupLvAddList.Create; end; destructor TBackupLvReadFolderInfo.Destroy; begin BackupLvAddList.Free; inherited; end; procedure TBackupLvReadFolderInfo.Update; var i : Integer; begin inherited; // 选择的已经发生变化 if FullPath <> TvNodePath_Selected then Exit; // 清空旧的 LvBackupFile.Clear; // 显示新的 for i := 0 to BackupLvAddList.Count - 1 do BackupLvAddList[i].Update; end; { TBackupProgressHideThread } constructor TBackupProgressHideThread.Create; begin inherited Create( True ); end; destructor TBackupProgressHideThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TBackupProgressHideThread.Execute; begin while not Terminated do begin while not Terminated and ( SecondsBetween( Now, LastShowTime ) < 2 ) do Sleep(100); if Terminated then Break; // 隐藏进度条 Synchronize( HideProgress ); // 挂起线程 if SecondsBetween( Now, LastShowTime ) >= 2 then Suspend; end; inherited; end; procedure TBackupProgressHideThread.HideProgress; begin if frmMainForm.plBackupProgress.Visible then frmMainForm.plBackupProgress.Visible := False; end; procedure TBackupProgressHideThread.ShowBackupProgress; begin LastShowTime := Now; Resume; end; { TBackupTvCompletedSpaceInfo } procedure TVstBackupFolderAddCompletedSpace.Update; var IsSelectNodeChild : Boolean; SelectNode : PVirtualNode; SelectData : PVstBackupItemData; begin inherited; // 不存在 if not FindFolderNode then Exit; // 是否需要更新 ListView IsSelectNodeChild := MyMatchMask.CheckChild( FolderPath, TvNodePath_Selected ); // 改变空间信息 SelectNode := FolderNode; while Assigned( SelectNode ) and ( SelectNode <> vstBackupItem.RootNode ) do begin SelectData := vstBackupItem.GetNodeData( SelectNode ); SelectData.CompletedSpace := SelectData.CompletedSpace + CompletedSpace; // 刷新节点 vstBackupItem.RepaintNode( SelectNode ); // 刷新 ListView if IsSelectNodeChild then RefreshLvStatus( SelectNode ); SelectNode := SelectNode.Parent; end; end; { TBackupTvSetCompletedSpaceInfo } procedure TVstBackupFolderSetCompletedSpace.SetLastCompletedSpace( _LastCompletedSpace: Int64); begin LastCompletedSpace := _LastCompletedSpace; end; procedure TVstBackupFolderSetCompletedSpace.Update; begin inherited; // 不存在 if not FindFolderNode then Exit; // 已发生变化 if FolderData.CompletedSpace <> LastCompletedSpace then Exit; // Vst FolderData.CompletedSpace := CompletedSpace; // 刷新节点 ResetFolderNode; end; { VstBackupItemUtil } class function VstBackupItemUtil.getBackupStatus(CompletedSpace, TotalSpace: Int64): string; var Percentage : Integer; begin if CompletedSpace >= TotalSpace then Result := NodeStatus_Completed else if CompletedSpace = 0 then Result := NodeStatus_Incompleted else begin Percentage := MyPercentage.getPercent( CompletedSpace, TotalSpace ); Result := MyPercentage.getPercentageStr( Percentage ) + ' ' + NodeStatus_Completed; end; end; class function VstBackupItemUtil.getHintStr(Node: PVirtualNode): string; var vstBackupItem : TVirtualStringTree; NodeData : PVstBackupItemData; TempStr, HintStr : string; FullPath, SyncTimeStr, LasSyncStr, NextSyncStr: string; begin vstBackupItem := frmMainForm.vstBackupItem; NodeData := vstBackupItem.GetNodeData( Node ); FullPath := VstBackupItemUtil.getNodeFullPath( Node ); LasSyncStr := DateTimeToStr( NodeData.LastSyncTime ); if NodeData.IsAuctoSync and not NodeData.IsDiable then begin SyncTimeStr := TimeTypeUtil.getTimeShow( NodeData.SyncTimeType, NodeData.SyncTimeValue ); NextSyncStr := DateTimeToStr( NodeData.NextSyncTime ); end else begin SyncTimeStr := Sign_NA; NextSyncStr := Sign_NA; end; TempStr := frmMainForm.siLang_frmMainForm.GetText( 'HintItemPath' ); HintStr := TempStr + FullPath + #13#10; TempStr := frmMainForm.siLang_frmMainForm.GetText( 'HintPersetCopy' ); HintStr := HintStr + TempStr + IntToStr( NodeData.CopyCount ) + #13#10; if Node.Parent = vstBackupItem.RootNode then begin TempStr := frmMainForm.siLang_frmMainForm.GetText( 'HintSyncTime' ); HintStr := HintStr + TempStr; TempStr := LanguageUtil.getSyncTimeStr( SyncTimeStr ); HintStr := HintStr + TempStr + #13#10; TempStr := frmMainForm.siLang_frmMainForm.GetText( 'HintLastSync' ); LasSyncStr := LanguageUtil.getSyncTimeStr( LasSyncStr ); HintStr := HintStr + TempStr + LasSyncStr + #13#10; TempStr := frmMainForm.siLang_frmMainForm.GetText( 'NextSync' ); HintStr := HintStr + TempStr + NextSyncStr + #13#10; end; TempStr := frmMainForm.siLang_frmMainForm.GetText( 'Status' ); HintStr := HintStr + TempStr; TempStr := VstBackupItemUtil.getStatusHint( Node ); TempStr := LanguageUtil.getPercentageStr( TempStr ); HintStr := HintStr + TempStr; Result := HintStr; end; class function VstBackupItemUtil.getNextSyncTimeStr(Node: PVirtualNode): string; var VstBackupitem : TVirtualStringTree; NodeData : PVstBackupItemData; ShowStr : string; ShowStrList : TStringList; begin VstBackupItem := frmMainForm.vstBackupItem; NodeData := VstBackupitem.GetNodeData( Node ); if not NodeData.IsAuctoSync or NodeData.IsDiable then Result := frmMainForm.siLang_frmMainForm.GetText( 'NA' )// Sign_NA else begin ShowStr := TimeTypeUtil.getMinShowStr( MinutesBetween( Now, NodeData.NextSyncTime ) ); Result := LanguageUtil.getSyncTimeStr( ShowStr ); end; end; class function VstBackupItemUtil.getNodeFullPath(Node: PVirtualNode): string; var VstBackupitem : TVirtualStringTree; NodeData : PVstBackupItemData; begin VstBackupItem := frmMainForm.vstBackupItem; Result := ''; while Assigned( Node ) and ( Node <> VstBackupitem.RootNode ) do begin NodeData := VstBackupitem.GetNodeData( Node ); if Result = '' then Result := NodeData.FolderName else Result := MyFilePath.getPath( NodeData.FolderName ) + Result; Node := Node.Parent; end; end; class function VstBackupItemUtil.getSelectPath: string; var vstBackupItem : TVirtualStringTree; begin Result := ''; vstBackupItem := frmMainForm.vstBackupItem; if not Assigned( vstBackupItem.FocusedNode ) then Exit; Result := getNodeFullPath( vstBackupItem.FocusedNode ); end; class function VstBackupItemUtil.getSelectPathList: TStringList; var vstBackupItem : TVirtualStringTree; SelectNode : PVirtualNode; FullPath : string; begin Result := TStringList.Create; vstBackupItem := frmMainForm.vstBackupItem; SelectNode := vstBackupItem.GetFirstSelected; while Assigned( SelectNode ) do begin FullPath := getNodeFullPath( SelectNode ); Result.Add( FullPath ); SelectNode := vstBackupItem.GetNextSelected( SelectNode ); end; end; class function VstBackupItemUtil.getStatus(Node: PVirtualNode): string; var NodeData: PVstBackupItemData; TotalSize : Int64; begin NodeData := frmMainForm.vstBackupItem.GetNodeData( Node ); if NodeData.IsDiable then Result := NodeStatus_Disable else if not NodeData.IsExist then Result := NodeStatus_NotExists else if NodeData.FolderStatus = FolderStatus_Loading then Result := NodeStatus_Loading else if NodeData.FolderStatus = FolderStatus_Waiting then Result := NodeStatus_Waiting else if NodeData.FolderStatus = FolderStatus_Refreshing then Result := NodeStatus_Refreshing else if NodeData.FolderStatus = FolderStatus_Analyzing then Result := NodeStatus_Analyzing else if NodeData.FileCount = 0 then Result := NodeStatus_Empty else begin TotalSize := NodeData.CopyCount * NodeData.ItemSize; Result := getBackupStatus( NodeData.CompletedSpace, TotalSize ); end; end; class function VstBackupItemUtil.getStatusHint(Node: PVirtualNode): string; var NodeData: PVstBackupItemData; Percentage : Integer; TotalSize : Int64; begin NodeData := frmMainForm.vstBackupItem.GetNodeData( Node ); if NodeData.IsDiable then Result := NodeStatusHint_Disable else if not NodeData.IsExist then Result := NodeStatusHint_NotExists else if NodeData.FolderStatus = FolderStatus_Loading then Result := NodeStatusHint_Loading else if NodeData.FolderStatus = FolderStatus_Waiting then Result := NodeStatusHint_Waiting else if NodeData.FolderStatus = FolderStatus_Refreshing then Result := NodeStatusHint_Refreshing else if NodeData.FolderStatus = FolderStatus_Analyzing then Result := NodeStatusHint_Analyzing else if NodeData.FileCount = 0 then Result := NodeStatus_Empty else begin TotalSize := NodeData.CopyCount * NodeData.ItemSize; Result := getBackupStatus( NodeData.CompletedSpace, TotalSize ); end; end; class function VstBackupItemUtil.getStatusIcon(Node: PVirtualNode): Integer; var FindNodeIcon : TFindNodeIcon; begin FindNodeIcon := TFindNodeIcon.Create( Node ); Result := FindNodeIcon.get; FindNodeIcon.Free; end; class function VstBackupItemUtil.getStatusInt(Node: PVirtualNode): Integer; var NodeData: PVstBackupItemData; Percentage : Integer; TotalSize : Int64; begin NodeData := frmMainForm.vstBackupItem.GetNodeData( Node ); if NodeData.IsDiable then Result := 0 else if not NodeData.IsExist then Result := 1 else if NodeData.FolderStatus = FolderStatus_Loading then Result := 2 else if NodeData.FolderStatus = FolderStatus_Waiting then Result := 3 else if NodeData.FolderStatus = FolderStatus_Refreshing then Result := 4 else if NodeData.FolderStatus = FolderStatus_Analyzing then Result := 5 else if NodeData.FileCount = 0 then Result := 6 else begin TotalSize := NodeData.CopyCount * NodeData.ItemSize; if TotalSize = NodeData.CompletedSpace then // Completed Result := 202 else if NodeData.CompletedSpace = 0 then // Incompleted Result := 7 else begin Percentage := MyPercentage.getPercent( NodeData.CompletedSpace, TotalSize ); if ( Percentage > 100 ) or ( Percentage < 0 ) then Result := 201 else Result := 100 + Percentage; end; end; end; class function VstBackupItemUtil.IsRootPath(FolderPath: string): Boolean; var vstBackupItem : TVirtualStringTree; SelectNode : PVirtualNode; NodeData : PVstBackupItemData; begin Result := False; vstBackupItem := frmMainForm.vstBackupItem; SelectNode := vstBackupItem.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstBackupItem.GetNodeData( SelectNode ); if NodeData.FolderName = FolderPath then begin Result := True; Break; end; SelectNode := SelectNode.NextSibling; end; end; { TBackupPgShowInfo } procedure TBackupPgShowInfo.Update; begin // 显示进度条 if not frmMainForm.plBackupProgress.Visible then frmMainForm.plBackupProgress.Visible := True; // 定时隐藏 BackupProgressHideThread.ShowBackupProgress; end; { TFindNodeIcon } constructor TFindNodeIcon.Create( Node : PVirtualNode ); var NodeData : PVstBackupItemData; begin NodeData := frmMainForm.vstBackupItem.GetNodeData( Node ); PathType := NodeData.PathType; IsDisable := NodeData.IsDiable; IsExist := NodeData.IsExist; IsEmpty := NodeData.FileCount = 0; IsLoading := NodeData.FolderStatus = FolderStatus_Loading; IsWaiting := NodeData.FolderStatus = FolderStatus_Waiting; IsRefreshing := NodeData.FolderStatus = FolderStatus_Refreshing; IsAnalyzing := NodeData.FolderStatus = FolderStatus_Analyzing; IsEmptyBackup := NodeData.CompletedSpace = 0; IsFullBackup := NodeData.CompletedSpace >= ( NodeData.CopyCount * NodeData.ItemSize ); end; function TFindNodeIcon.get: Integer; begin if PathType = PathType_Folder then Result := getFolderIcon else if PathType = PathType_File then Result := getFileIcon; end; function TFindNodeIcon.getFileIcon: Integer; begin if IsDisable then Result := NodeIcon_FileDisable else if not IsExist then Result := NodeIcon_FileNotExists else if IsLoading then Result := NodeIcon_FileLoading else if IsWaiting then Result := NodeIcon_FileWaiting else if IsRefreshing then Result := NodeIcon_FileRefreshing else if IsAnalyzing then Result := NodeIcon_FileAnalyzing else if IsFullBackup then Result := NodeIcon_FileCompleted else if IsEmptyBackup then Result := NodeIcon_FileIncompleted else Result := NodeIcon_FilePartCompleted; end; function TFindNodeIcon.getFolderIcon: Integer; begin if IsDisable then Result := NodeIcon_FolderDisable else if not IsExist then Result := NodeIcon_FolderNotExists else if IsLoading then Result := NodeIcon_FolderLoading else if IsWaiting then Result := NodeIcon_FolderWaiting else if IsRefreshing then Result := NodeIcon_FolderRefreshing else if IsAnalyzing then Result := NodeIcon_FolderAnalyzing else if IsEmpty then Result := NodeIcon_FolderEmpty else if IsFullBackup then Result := NodeIcon_FolderCompleted else if IsEmptyBackup then Result := NodeIcon_FolderIncompleted else Result := NodeIcon_FolderPartCompleted; end; { TVstBackupItemChange } procedure TVstBackupPathChange.Update; begin VstBackupItem := frmMainForm.vstBackupItem; end; { TVstBackupItemIsExist } procedure TVstBackupPathIsExist.SetIsExist(_IsExist: Boolean); begin IsExist := _IsExist; end; procedure TVstBackupPathIsExist.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // Vst PathData.IsExist := IsExist; // 刷新节点 RefreshPathNode; end; { TVstBackupItemResetStatus } procedure TVstBackupFolderSetStatus.SetPathStatus(_PathStatus: string); begin PathStatus := _PathStatus; end; procedure TVstBackupFolderSetStatus.Update; begin inherited; // 不存在 if not FindFolderNode then Exit; // Vst FolderData.FolderStatus := PathStatus; // 刷新节点 ResetFolderNode; end; { TLvBackupFileChangeInfo } procedure TLvBackupFileChangeInfo.Update; begin LvBackupFile := frmMainForm.lvFileStatus; end; { LvBackupFileUtil } class function LvBackupFileUtil.getBackupStatus(CompletedSpace, TotalSpace: Int64): string; begin if CompletedSpace >= TotalSpace then Result := BackupStatus_Completed else if CompletedSpace = 0 then Result := BackupStatus_Incompleted else Result := BackupStatus_PartCompleted end; class function LvBackupFileUtil.getSelectPath: string; var SelectItem: TListItem; SelectData: TBackupLvFaceData; begin Result := ''; SelectItem := frmMainForm.lvFileStatus.Selected; if SelectItem = nil then Exit; SelectData := SelectItem.Data; Result := SelectData.FullPath; end; class function LvBackupFileUtil.IsFileShow(FilePath: string): Boolean; begin Result := ( ExtractFileDir( FilePath ) = TvNodePath_Selected ) or ( FilePath = TvNodePath_Selected ); end; class function LvBackupFileUtil.IsFolderShow(FolderPath: string): Boolean; begin Result := ExtractFileDir( FolderPath ) = TvNodePath_Selected; end; { TVstBackupFolderChange } constructor TVstBackupFolderChange.Create(_FolderPath: string); begin FolderPath := _FolderPath; end; function TVstBackupFolderChange.FindChildNode(ParentNode: PVirtualNode; ChileName: string): PVirtualNode; var ChildNode : PVirtualNode; ChildData : PVstBackupItemData; begin Result := nil; ChildNode := ParentNode.FirstChild; while Assigned( ChildNode ) do begin ChildData := VstBackupItem.GetNodeData( ChildNode ); if ChildData.FolderName = ChileName then begin Result := ChildNode; Break; end; ChildNode := ChildNode.NextSibling; end; end; function TVstBackupFolderChange.FindFolderNode: Boolean; var ParentNode : PVirtualNode; ParentData : PVstBackupItemData; RemainPath, FolderName : string; IsFindNext : Boolean; begin Result := False; // 找不到 根节点 if not FindRootFolderNode then Exit; // 根节点 是 目标节点 if RootFolderData.FolderName = FolderPath then begin Result := True; FolderNode := RootFolderNode; FolderData := RootFolderData; Exit; end; // 从根目录向下寻找 ParentNode := RootFolderNode; RemainPath := MyString.CutStartStr( MyFilePath.getPath( RootFolderData.FolderName ), FolderPath ); IsFindNext := True; while IsFindNext do // 寻找子目录 begin FolderName := MyString.GetRootFolder( RemainPath ); if FolderName = '' then begin FolderName := RemainPath; IsFindNext := False; end; ParentNode := FindChildNode( ParentNode, FolderName ); if ParentNode = nil then // 不存在目录 Exit; // 下一层 RemainPath := MyString.CutRootFolder( RemainPath ); end; FolderNode := ParentNode; FolderData := VstBackupItem.GetNodeData( FolderNode ); Result := True; end; function TVstBackupFolderChange.FindRootFolderNode: Boolean; var SelectNode : PVirtualNode; SelectData : PVstBackupItemData; begin Result := False; SelectNode := VstBackupItem.RootNode.FirstChild; while Assigned( SelectNode ) do begin SelectData := VstBackupItem.GetNodeData( SelectNode ); if MyMatchMask.CheckEqualsOrChild( FolderPath, SelectData.FolderName ) then begin RootFolderNode := SelectNode; RootFolderData := SelectData; Result := True; Break; end; SelectNode := SelectNode.NextSibling; end; end; procedure TVstBackupFolderChange.ResetFolderNode; begin VstBackupItem.RepaintNode( FolderNode ); end; { TVstBackupPathSetStatus } procedure TVstBackupPathSetStatus.SetStatus(_Status: string); begin Status := _Status; end; procedure TVstBackupPathSetStatus.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // 设置目录状态 PathData.FolderStatus := Status; RefreshPathNode; end; { TVstBackupFolderChangeCompletedSpace } procedure TVstBackupFolderChangeCompletedSpace.RefreshLvStatus( Node: PVirtualNode); var SelectPath, Status, ShowStatus : string; SelectData : PVstBackupItemData; TotalSpace, CompletedSpace : Int64; BackupLvStatusInfo : TBackupLvStatusInfo; begin // 获取 节点完整路径,并判断是否需要更新 SelectPath := VstBackupItemUtil.getNodeFullPath( Node ); if not LvBackupFileUtil.IsFolderShow( SelectPath ) then Exit; // 提取 节点信息 SelectData := VstBackupItem.GetNodeData( Node ); TotalSpace := SelectData.CopyCount * SelectData.ItemSize; Status := LvBackupFileUtil.getBackupStatus( SelectData.CompletedSpace, TotalSpace ); ShowStatus := VstBackupItemUtil.getBackupStatus( SelectData.CompletedSpace, TotalSpace ); // 刷新 节点信息 BackupLvStatusInfo := TBackupLvStatusInfo.Create( SelectPath ); BackupLvStatusInfo.SetCopyCountStatus( '' ); BackupLvStatusInfo.SetStatusInfo( Status, ShowStatus ); MyBackupFileFace.AddChange( BackupLvStatusInfo ); end; procedure TVstBackupFolderChangeCompletedSpace.SetCompletedSpace( _CompletedSpace: Int64); begin CompletedSpace := _CompletedSpace; end; { TVstBackupFolderRemoveCompletedSpace } procedure TVstBackupFolderRemoveCompletedSpace.Update; var SelectNode : PVirtualNode; SelectData : PVstBackupItemData; begin inherited; // 不存在 if not FindFolderNode then Exit; // 改变空间信息 SelectNode := FolderNode; while Assigned( SelectNode ) and ( SelectNode <> vstBackupItem.RootNode ) do begin SelectData := vstBackupItem.GetNodeData( SelectNode ); SelectData.CompletedSpace := SelectData.CompletedSpace - CompletedSpace; // 刷新 节点 vstBackupItem.RepaintNode( SelectNode ); // 刷新 ListView 数据 RefreshLvStatus( SelectNode ); SelectNode := SelectNode.Parent; end; end; { TVstBackupPathRefreshSelectNode } procedure TVstBackupPathRefreshSelectNode.Update; var RefreshPath : string; begin inherited; // 没有选择 if TvNodePath_Selected = '' then Exit; // 刷新选择节点 RefreshPath := TvNodePath_Selected; // 刷新节点 与 更新节点存在 关系 if MyMatchMask.CheckEqualsOrChild( RefreshPath, FullPath ) or MyMatchMask.CheckChild( FullPath, RefreshPath ) then MyBackupFileControl.ShowBackupFileStatusNomal( RefreshPath ); end; { TLvBackupPathProData } constructor TLvBackupPathProData.Create(_FullPath: string); begin FullPath := _FullPath; end; { TLvBackupPathProChange } procedure TLvBackupPathProChange.Update; begin LvBackupPathPro := frmBackupProperties.LvBackupItem; end; { TLvBackupPathProWrite } constructor TLvBackupPathProWrite.Create(_FullPath: string); begin FullPath := _FullPath; end; function TLvBackupPathProWrite.FindPathItem: Boolean; var i : Integer; SelectData : TLvBackupPathProData; begin Result := False; for i := 0 to LvBackupPathPro.Items.Count - 1 do begin SelectData := LvBackupPathPro.Items[i].Data; if SelectData.FullPath = FullPath then begin PathItem := LvBackupPathPro.Items[i]; PathIndex := i; Result := True; Break; end; end; end; { TLvBackupPathProAdd } procedure TLvBackupPathProAdd.Update; var PathData : TLvBackupPathProData; begin inherited; // 已存在 if FindPathItem then Exit; // 创建 PathData := TLvBackupPathProData.Create( FullPath ); with LvBackupPathPro.Items.Add do begin Caption := ExtractFileName( FullPath ); SubItems.Add(''); ImageIndex := MyIcon.getIconByFilePath( FullPath ); Data := PathData; end; end; { TLvBackupPathProRemove } procedure TLvBackupPathProRemove.Update; begin inherited; // 不存在 if not FindPathItem then Exit; // 删除 LvBackupPathPro.Items.Delete( PathIndex ); end; { TVstBackupPathSetLastSyncTime } procedure TVstBackupPathSetLastSyncTime.SetLastSyncTime( _LastSyncTime: TDateTime); begin LastSyncTime := _LastSyncTime; end; procedure TVstBackupPathSetLastSyncTime.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // 设置 上一次 同步时间 PathData.LastSyncTime := LastSyncTime; // 计算下次同步时间 RefreshNextSyncTime; // 刷新节点 RefreshPathNode; end; { TVstBackupPathSetSyncMins } procedure TVstBackupPathSetSyncTime.SetIsAutoSync(_IsAutoSync: Boolean); begin IsAutoSync := _IsAutoSync; end; procedure TVstBackupPathSetSyncTime.SetSyncTimeInfo(_SyncTimeType, _SyncTimeValue : Integer); begin SyncTimeType := _SyncTimeType; SyncTimeValue := _SyncTimeValue; end; procedure TVstBackupPathSetSyncTime.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // 设置 上一次 同步时间 PathData.IsAuctoSync := IsAutoSync; PathData.SyncTimeType := SyncTimeType; PathData.SyncTimeValue := SyncTimeValue; // 计算下次同步时间 RefreshNextSyncTime; // 刷新节点 RefreshPathNode; end; { TVstBackuppathRefreshNextSyncTime } procedure TVstBackuppathRefreshNextSyncTime.Update; begin inherited; // 路径不存在 if not FindPathNode then Exit; // 刷新路径信息 RefreshPathNode; end; { TVstBackupPathIsDisable } procedure TVstBackupPathIsDisable.SetIsDisable(_IsDisable: Boolean); begin IsDisable := _IsDisable; end; procedure TVstBackupPathIsDisable.Update; begin inherited; // 不存在 if not FindPathNode then Exit; // Vst PathData.IsDiable := IsDisable; // 刷新节点 RefreshPathNode; end; { LvBackupFileStatusUtil } class function LvBackupFileStatusUtil.getIsFolder(FilePath: string): Boolean; var LvFileStatus : TListView; i : Integer; SelectData: TBackupLvFaceData; begin Result := False; LvFileStatus := frmMainForm.lvFileStatus; for i := 0 to LvFileStatus.Items.Count - 1 do begin SelectData := LvFileStatus.Items[i].Data; if SelectData.FullPath = FilePath then begin Result := SelectData.IsFolder; break; end; end; end; class function LvBackupFileStatusUtil.getSelectPath: string; var SelectItem: TListItem; SelectData: TBackupLvFaceData; begin Result := ''; SelectItem := frmMainForm.lvFileStatus.Selected; if SelectItem = nil then Exit; SelectData := SelectItem.Data; Result := SelectData.FullPath; end; class function LvBackupFileStatusUtil.getSelectPathList: TStringList; var LvFileStatus : TListView; i : Integer; SelectData: TBackupLvFaceData; begin Result := TStringList.Create; LvFileStatus := frmMainForm.lvFileStatus; for i := 0 to LvFileStatus.Items.Count - 1 do begin if LvFileStatus.Items[i].Selected then begin SelectData := LvFileStatus.Items[i].Data; Result.Add( SelectData.FullPath ); end; end; end; { TPlBackupBoardIconShow } constructor TPlBackupBoardIconShow.Create(_IsShow: Boolean); begin IsShow := _IsShow; end; procedure TPlBackupBoardIconShow.Update; begin inherited; frmMainForm.plBackupBoardIcon.Visible := IsShow; end; { LanguageUtil } class function LanguageUtil.getPercentageStr(Str: string): string; var ShowStrList : TStringList; begin ShowStrList := MySplitStr.getList( Str, ' ' ); if ShowStrList.Count = 3 then begin if ShowStrList[1] <> '%' then ShowStrList[0] := frmMainForm.siLang_frmMainForm.GetText( ShowStrList[0] ); ShowStrList[2] := frmMainForm.siLang_frmMainForm.GetText( ShowStrList[2] ); Result := ShowStrList[0] + ' ' + ShowStrList[1] + ' ' + ShowStrList[2]; end else Result := frmMainForm.siLang_frmMainForm.GetText( Str ); ShowStrList.Free; end; class function LanguageUtil.getSyncTimeStr(Str: string): string; var ShowStr : string; ShowStrList : TStringList; begin ShowStr := Str; ShowStrList := MySplitStr.getList( ShowStr, ' ' ); if ShowStrList.Count = 2 then begin ShowStrList[1] := frmMainForm.siLang_frmMainForm.GetText( ShowStrList[1] ); ShowStr := ShowStrList[0] + ' ' + ShowStrList[1]; end; ShowStrList.Free; Result := ShowStr; end; end.
unit Aurelius.Commands.Exceptions; {$I Aurelius.inc} interface uses Aurelius.Global.Exceptions; type ESelectAlreadyOpen = class(EOPFBaseException) public constructor Create; end; ESelectNotOpen = class(EOPFBaseException) constructor Create; end; ECursorNotFetching = class(EOPFBaseException) constructor Create; end; ENilObjectReturned = class(EOPFBaseException) constructor Create; end; implementation { ESelectAlreadyOpen } constructor ESelectAlreadyOpen.Create; begin inherited Create('Cannot start selecting objects. A select operation has been already started.'); end; { ESelectNotOpen } constructor ESelectNotOpen.Create; begin inherited Create('Cannot fetch object. A select operation has not been started.'); end; { ECursorNotFetching } constructor ECursorNotFetching.Create; begin inherited Create('Cannot fetch object, cursor fetching has not started.'); end; { ENilObjectReturned } constructor ENilObjectReturned.Create; begin inherited Create('No object returned from database. Check if id column in database has a valid value.'); end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.Core.CustomControl; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.UxTheme, Winapi.DwmApi, Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.GDIPUTIL, Vcl.Controls, Vcl.Graphics, Vcl.Themes, {$ELSE} SysUtils, Classes, Windows, Messages, Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.GDIPUTIL, UxTheme, DwmApi, Controls, Graphics, Themes, {$ENDIF} UI.Aero.Core.BaseControl, UI.Aero.Globals; type TCustomAeroControl = class(TAeroBaseControl) Private Function CreateRenderBuffer(const DrawDC: hDC;var PaintDC: hDC): hPaintBuffer; Protected function GetRenderState: TRenderConfig; Virtual; Abstract; procedure RenderProcedure_Vista(const ACanvas: TCanvas); override; procedure RenderProcedure_XP(const ACanvas: TCanvas); override; procedure RenderProcedure_Classic(const ACanvas: TCanvas); procedure ClassicRender(const ACanvas: TCanvas); Virtual; Abstract; procedure ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); Virtual; Abstract; procedure PostRender(const Surface: TCanvas;const RConfig: TRenderConfig); Virtual; Abstract; Public Constructor Create(AOwner: TComponent); OverRide; Destructor Destroy; OverRide; end; implementation { TCustomAeroControl } constructor TCustomAeroControl.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TCustomAeroControl.Destroy; begin inherited Destroy; end; function TCustomAeroControl.CreateRenderBuffer(const DrawDC: hDC; var PaintDC: hDC): hPaintBuffer; var rcClient: TRect; Params: TBPPaintParams; begin rcClient:= GetClientRect; ZeroMemory(@Params,SizeOf(TBPPaintParams)); Params.cbSize:= SizeOf(TBPPaintParams); Params.dwFlags:= BPPF_ERASE; Result:= BeginBufferedPaint(DrawDC, rcClient, BPBF_COMPOSITED, @params, PaintDC); if Result = 0 then PaintDC:= DrawDC else DrawAeroParentBackground(PaintDC,rcClient); end; procedure TCustomAeroControl.RenderProcedure_Classic(const ACanvas: TCanvas); begin CreateClassicBuffer; DrawClassicBG; ClassicRender(ClassicBuffer.Canvas); ACanvas.Draw(0, 0, ClassicBuffer); end; procedure TCustomAeroControl.RenderProcedure_Vista(const ACanvas: TCanvas); var RConfig: TRenderConfig; PaintDC: hDC; RenderBuffer: hPaintBuffer; GPSurface: TGPGraphics; begin PaintDC:= ACanvas.Handle; RenderBuffer:= 0; GPSurface:= nil; RConfig:= []; // if {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF} then begin if IsCompositionActive then RConfig:= GetRenderState+[rsComposited] else RConfig:= GetRenderState; if (rsBuffer in RConfig) then RenderBuffer:= CreateRenderBuffer(ACanvas.Handle,PaintDC); if (rsGDIP in RConfig) then GPSurface:= TGPGraphics.Create(PaintDC); ThemedRender(PaintDC, GPSurface, RConfig); if Assigned(GPSurface) then GPSurface.Free; if (rsBuffer in RConfig) and (RenderBuffer <> 0) then EndBufferedPaint(RenderBuffer, True); end else RenderProcedure_Classic(ACanvas); if rsPostDraw in RConfig then PostRender(ACanvas,RConfig); end; procedure TCustomAeroControl.RenderProcedure_XP(const ACanvas: TCanvas); var RConfig: TRenderConfig; PaintDC: hDC; GPSurface: TGPGraphics; begin PaintDC:= ACanvas.Handle; GPSurface:= nil; RConfig:= []; // if {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF} then begin RConfig:= GetRenderState; if (rsGDIP in RConfig) then GPSurface:= TGPGraphics.Create(PaintDC); ThemedRender(PaintDC,GPSurface,RConfig); if Assigned(GPSurface) then GPSurface.Free; end else RenderProcedure_Classic(ACanvas); if rsPostDraw in RConfig then PostRender(ACanvas,RConfig); end; end.
{$N+} UNIT AllMaths; INTERFACE CONST e = 2.7182818; Function Prime(N: LongInt): Boolean; {Determines if argument is prime} Function Whole(X: Real): Boolean; Function Deg2Rad(D: Real): Real; Function Grad2Rad(G: Real): Real; Function Deg2Grad(D: Real): Real; Function Rad2Deg(R: Real): Real; Function Rad2Grad(R: Real): Real; Function Grad2Deg(G: Real): Real; Function Csc(R: Real): Real; Function Sec(R: Real): Real; Function HypETr(S: Real): Real; { Hypotenuse_Equilateral_Triangle } Function Hypot(A, B: Real): Real; { Pythagoras } Function Triangle_Area(B, H: Real): Real; Function ETArea(S: Real): Real; { Equilateral_Triangle_Area } Function CrArea(R: Real): Real; { Circle_Area } Function ElArea(A, B: Real): Real; { Ellipse_Area } Function SqArea(S: Real): Real; { Square_Area } Function RecArea(X, Y: Real): Real; { Rectangle_Area } Function CbSfArea(S: Real): Real; { Cube_Surface_Area } Function RecPsmSfArea(H, W, L: Real): Real; { Rectangular_Prism_Surface_Area } Function SpSfArea(R: Real): Real; { Sphere_Surface_Area } Function ClSfArea(R, H: Real): Real; { Cylinder_Surface_Area } Function CnSfAreaNoBase(R, H: Real): Real; { Cone_Surface_Area_Without_Base } Function CnSfAreaAndBase(R, H: Real): Real; { Cone_Surface_Area_With_Base } Function ScArea(R, A: Real): Real; { Sector_Area } Function TzArea(A, B, H: Real): Real; { Trapezoid_Area } Function CrCfer(R: Real): Real; { Circle_Circumference } Function ElCfer(A, B: Real): Real; { Ellipse_Circumference } Function CbVol(S: Real): Real; { Cube_Volume } Function RecVol(X, Y, Z: Real): Real; { Rectangle_Volume } Function SpVol(R: Real): Real; { Sphere_Volume } Function ClVol(R, H: Real): Real; { Cylinder_Volume } Function CnVol(R, H: Real): Real; { Cone_Volume } Function PsmVol(B, H: Real): Real; { Prism_Volume } Function Distance(X1, X2, Y1, Y2: Real): Real; Function Factorial(n: word):longint; Function GCD(A, B: LongInt): LongInt; {finds the Greatest Common Divisor between 2 arguments} Function LCM(A, B: LongInt): LongInt; {finds the Least Common Multiple between 2 arguments} IMPLEMENTATION Function Whole; Begin Whole:=INT(X) = X; End; Function Deg2Rad; Begin Deg2Rad:=D*Pi/180; End; Function Grad2Rad; Begin Grad2Rad:=G*Pi/200; End; Function Deg2Grad; Begin Deg2Grad:=D/0.9; End; Function Rad2Deg; Begin Rad2Deg:=R*180/Pi; End; Function Rad2Grad; Begin Rad2Grad:=R*200/Pi; End; Function Grad2Deg; Begin Grad2Deg:=G*0.9; End; Function Csc; Begin Csc:=1 / Sin(R); End; Function Sec; Begin Sec:=1 / Cos(R); End; Function HypETr; Begin HypETr:=( SQRT(3) * S ) / 2; End; Function Hypot; Begin Hypot:=Sqrt((A*A)+(B*B)); End; Function Triangle_Area; Begin Triangle_Area:=0.5 * B * H; End; Function ETArea; Begin ETArea:=( SQRT(3) * (S*S) ) / 4; End; Function CrArea; Begin CrArea:=Pi*(R*R); End; Function ElArea; Begin ElArea:=Pi*A*B; End; Function SqArea; Begin SqArea:=(S*S); End; Function RecArea; Begin RecArea:=X*Y; End; Function CbSfArea; Begin CbSfArea:=6*(S*S); End; Function RecPsmSfArea; Begin RecPsmSfArea:=(2*H*W) + (2*H*L) + (2*L*W); End; Function SpSfArea; Begin SpSfArea:=4*Pi*(R*R); End; Function ClSfArea; Begin ClSfArea:=(2*Pi*R*H) + (2*Pi*(R*R)); End; Function CnSfAreaNoBase; Begin CnSfAreaNoBase:=Pi*R*Hypot(R,H); End; Function CnSfAreaAndBase; Begin CnSfAreaAndBase:=(Pi*R*Hypot(R,H)) + (Pi*(R*R)); End; Function ScArea; Begin ScArea:=0.5*(R*R)*A; End; Function TzArea; Begin TzArea:=(H / 2) * (A + B); End; Function CrCfer; Begin CrCfer:=2*Pi*R; End; Function ElCfer; Begin ElCfer := (2*Pi) * Hypot(A,B) / 2; End; Function CbVol; Begin CbVol:=S*S*S; End; Function RecVol; Begin RecVol:=X*Y*Z; End; Function SpVol; Begin SpVol:=(4/3)*Pi*(R*R*R); End; Function ClVol; Begin ClVol:=Pi*(R*R)*H; End; Function CnVol; Begin CnVol:=(Pi*(R*R)*H)/3; End; Function PsmVol; Begin PsmVol:=B*H; End; Function Distance; Begin Distance:=Sqrt(Sqr(Y2-Y1)+Sqr(X2-X1)); End; Function Factorial(n: word):longint; var X,F: word; Begin { if (n<2) then factorial:=1 else Factorial:=n*Factorial(n-1);} if (n<2) then Factorial:=1; F:=1; for X:=1 to N do F:=F*X; Factorial:=N; End; Function GCD; Var X, High: LongInt; Begin High:=1; For X:=2 to A do If (A MOD X = 0) AND (B MOD X = 0) then High:=X; GCD:=High; End; Function LCM; Var Itt, Low, High: LongInt; Begin High:=longMax(A,B); Low :=longMin(A,B); Itt:=High; While High MOD Low <> 0 do inc(High,itt); LCM:=High; End; Function Prime; var divisor:word; Begin if N = 2 then begin Prime:=TRUE; exit end; if (N and 1) = 0 then begin Prime:=FALSE; exit end; divisor:=3; while divisor<=sqrt(N) do begin if N mod divisor = 0 then begin Prime:=FALSE; exit end; inc(divisor,2); end; Prime:=TRUE; End; function pow10(P: byte): word; var p10: word; i: byte; begin p10:=1; if P=0 then pow10:=1 else begin for i:=1 to P do p10:=p10*10; pow10:=p10; end; end; END.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement 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. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.XML; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface uses SysUtils, Classes, Math, PUCU, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Collections, PasVulkan.Streams; const XMLMaxListSize=2147483647 div SizeOf(TpvPointer); type EpvXML=class(Exception); TpvXMLClass=class public Previous,Next:TpvXMLClass; Core:TpvPointer; constructor Create; overload; virtual; destructor Destroy; override; end; PpvXMLClasses=^TpvXMLClasses; TpvXMLClasses=array[0..XMLMaxListSize-1] of TpvXMLClass; TpvXMLClassList=class(TpvXMLClass) private InternalList:PpvXMLClasses; InternalCount,InternalCapacity:TpvInt32; function GetItem(Index:TpvInt32):TpvXMLClass; procedure SetItem(Index:TpvInt32;Value:TpvXMLClass); function GetItemPointer(Index:TpvInt32):TpvXMLClass; public ClearWithContentDestroying:boolean; CapacityMinimium:TpvInt32; constructor Create; override; destructor Destroy; override; procedure Clear; procedure ClearNoFree; procedure ClearWithFree; function Add(Item:TpvXMLClass):TpvInt32; function Append(Item:TpvXMLClass):TpvInt32; function AddList(List:TpvXMLClassList):TpvInt32; function AppendList(List:TpvXMLClassList):TpvInt32; function NewClass:TpvXMLClass; procedure Insert(Index:TpvInt32;Item:TpvXMLClass); procedure Delete(Index:TpvInt32); procedure DeleteClass(Index:TpvInt32); function Remove(Item:TpvXMLClass):TpvInt32; function RemoveClass(Item:TpvXMLClass):TpvInt32; function Find(Item:TpvXMLClass):TpvInt32; function IndexOf(Item:TpvXMLClass):TpvInt32; procedure Exchange(Index1,Index2:TpvInt32); procedure SetCapacity(NewCapacity:TpvInt32); procedure SetOptimalCapacity(TargetCapacity:TpvInt32); procedure SetCount(NewCount:TpvInt32); function Push(Item:TpvXMLClass):TpvInt32; function Pop(var Item:TpvXMLClass):boolean; overload; function Pop:TpvXMLClass; overload; function Last:TpvXMLClass; property Count:TpvInt32 read InternalCount; property Capacity:TpvInt32 read InternalCapacity write SetCapacity; property Item[Index:TpvInt32]:TpvXMLClass read GetItem write SetItem; default; property Items[Index:TpvInt32]:TpvXMLClass read GetItem write SetItem; property PItems[Index:TpvInt32]:TpvXMLClass read GetItemPointer; end; TpvXMLClassLinkedList=class(TpvXMLClass) public ClearWithContentDestroying:boolean; First,Last:TpvXMLClass; constructor Create; override; destructor Destroy; override; procedure Clear; procedure ClearNoFree; procedure ClearWithFree; procedure Add(Item:TpvXMLClass); procedure Append(Item:TpvXMLClass); procedure AddLinkedList(List:TpvXMLClassLinkedList); procedure AppendLinkedList(List:TpvXMLClassLinkedList); procedure Remove(Item:TpvXMLClass); procedure RemoveClass(Item:TpvXMLClass); procedure Push(Item:TpvXMLClass); function Pop(var Item:TpvXMLClass):boolean; overload; function Pop:TpvXMLClass; overload; function Count:TpvInt32; end; TpvXMLString={$ifdef XMLUnicode}{$if declared(UnicodeString)}UnicodeString{$else}WideString{$ifend}{$else}TpvRawByteString{$endif}; TpvXMLChar={$ifdef XMLUnicode}WideChar{$else}TpvRawByteChar{$endif}; TpvXMLParameter=class(TpvXMLClass) public Name:TpvRawByteString; Value:TpvXMLString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLParameter); virtual; end; TpvXMLItemList=class; TpvXMLTag=class; TpvXMLTags=array of TpvXMLTag; TpvXMLItem=class(TpvXMLClass) public Items:TpvXMLItemList; constructor Create; override; destructor Destroy; override; procedure Clear; virtual; procedure Add(Item:TpvXMLItem); procedure Assign(From:TpvXMLItem); virtual; function FindTag(const TagName:TpvRawByteString):TpvXMLTag; function FindTags(const TagName:TpvRawByteString):TpvXMLTags; end; TpvXMLItemList=class(TpvXMLClassList) private function GetItem(Index:TpvInt32):TpvXMLItem; procedure SetItem(Index:TpvInt32;Value:TpvXMLItem); public constructor Create; override; destructor Destroy; override; function NewClass:TpvXMLItem; function FindTag(const TagName:TpvRawByteString):TpvXMLTag; function FindTags(const TagName:TpvRawByteString):TpvXMLTags; property Item[Index:TpvInt32]:TpvXMLItem read GetItem write SetItem; default; property Items[Index:TpvInt32]:TpvXMLItem read GetItem write SetItem; end; TpvXMLText=class(TpvXMLItem) public Text:TpvXMLString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXMLCommentTag=class(TpvXMLItem) public Text:TpvRawByteString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXMLTagParameterHashMap=TpvStringHashMap<TpvXMLParameter>; TpvXMLTag=class(TpvXMLItem) public Name:TpvRawByteString; Parameter:array of TpvXMLParameter; ParameterHashMap:TpvXMLTagParameterHashMap; IsAloneTag:boolean; constructor Create; override; destructor Destroy; override; procedure Clear; override; procedure Assign(From:TpvXMLItem); override; function FindParameter(ParameterName:TpvRawByteString):TpvXMLParameter; function GetParameter(ParameterName:TpvRawByteString;default:TpvRawByteString=''):TpvRawByteString; function AddParameter(AParameter:TpvXMLParameter):boolean; overload; function AddParameter(Name:TpvRawByteString;Value:TpvXMLString):boolean; overload; function RemoveParameter(AParameter:TpvXMLParameter):boolean; overload; function RemoveParameter(ParameterName:TpvRawByteString):boolean; overload; end; TpvXMLProcessTag=class(TpvXMLTag) public constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; end; TpvXMLScriptTag=class(TpvXMLItem) public Text:TpvRawByteString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXMLCDataTag=class(TpvXMLItem) public Text:TpvRawByteString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXMLDOCTYPETag=class(TpvXMLItem) public Text:TpvRawByteString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXMLExtraTag=class(TpvXMLItem) public Text:TpvRawByteString; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXMLItem); override; procedure SetText(AText:TpvRawByteString); end; TpvXML=class(TpvXMLClass) private function ReadXMLText:TpvRawByteString; procedure WriteXMLText(Text:TpvRawByteString); function Read(Stream: TStream): boolean; public Root:TpvXMLItem; AutomaticAloneTagDetection:boolean; FormatIndent:boolean; FormatIndentText:boolean; constructor Create; override; destructor Destroy; override; procedure Assign(From:TpvXML); function Parse(Stream:TStream):boolean; function Write(Stream:TStream;IdentSize:TpvInt32=2):boolean; procedure LoadFromStream(const aStream:TStream); procedure LoadFromFile(const aFileName:string); procedure SaveToStream(const aStream:TStream); procedure SaveToFile(const aFileName:string); property Text:TpvRawByteString read ReadXMLText write WriteXMLText; end; implementation constructor TpvXMLClass.Create; begin inherited Create; Previous:=nil; Next:=nil; Core:=nil; end; destructor TpvXMLClass.Destroy; begin inherited Destroy; end; constructor TpvXMLClassList.Create; begin inherited Create; ClearWithContentDestroying:=false; InternalCount:=0; InternalCapacity:=0; InternalList:=nil; CapacityMinimium:=0; Clear; end; destructor TpvXMLClassList.Destroy; begin Clear; if assigned(InternalList) and (InternalCapacity<>0) then begin FreeMem(InternalList); end; inherited Destroy; end; procedure TpvXMLClassList.Clear; begin if ClearWithContentDestroying then begin ClearWithFree; end else begin ClearNoFree; end; end; procedure TpvXMLClassList.ClearNoFree; begin SetCount(0); end; procedure TpvXMLClassList.ClearWithFree; var Counter:TpvInt32; begin for Counter:=0 to InternalCount-1 do begin FreeAndNil(InternalList^[Counter]); end; SetCount(0); end; procedure TpvXMLClassList.SetCapacity(NewCapacity:TpvInt32); begin if (InternalCapacity<>NewCapacity) and ((NewCapacity>=0) and (NewCapacity<XMLMaxListSize)) then begin ReallocMem(InternalList,NewCapacity*SizeOf(TpvXMLClass)); if InternalCapacity<NewCapacity then begin FillChar(InternalList^[InternalCapacity],(NewCapacity-InternalCapacity)*SizeOf(TpvXMLClass),#0); end; InternalCapacity:=NewCapacity; end; end; procedure TpvXMLClassList.SetOptimalCapacity(TargetCapacity:TpvInt32); var CapacityMask:TpvInt32; begin if (TargetCapacity>=0) and (TargetCapacity<XMLMaxListSize) then begin if TargetCapacity<256 then begin CapacityMask:=15; end else if TargetCapacity<1024 then begin CapacityMask:=255; end else if TargetCapacity<4096 then begin CapacityMask:=1023; end else if TargetCapacity<16384 then begin CapacityMask:=4095; end else if TargetCapacity<65536 then begin CapacityMask:=16383; end else begin CapacityMask:=65535; end; SetCapacity((TargetCapacity+CapacityMask+CapacityMinimium) and not CapacityMask); end; end; procedure TpvXMLClassList.SetCount(NewCount:TpvInt32); begin if (NewCount>=0) and (NewCount<XMLMaxListSize) then begin SetOptimalCapacity(NewCount); if InternalCount<NewCount then begin FillChar(InternalList^[InternalCount],(NewCount-InternalCount)*SizeOf(TpvXMLClass),#0); end; InternalCount:=NewCount; end; end; function TpvXMLClassList.Add(Item:TpvXMLClass):TpvInt32; begin result:=InternalCount; SetCount(result+1); InternalList^[result]:=Item; end; function TpvXMLClassList.Append(Item:TpvXMLClass):TpvInt32; begin result:=Add(Item); end; function TpvXMLClassList.AddList(List:TpvXMLClassList):TpvInt32; var Counter,Index:TpvInt32; begin result:=-1; for Counter:=0 to List.Count-1 do begin Index:=Add(List[Counter]); if Counter=0 then begin result:=Index; end; end; end; function TpvXMLClassList.AppendList(List:TpvXMLClassList):TpvInt32; begin result:=AddList(List); end; function TpvXMLClassList.NewClass:TpvXMLClass; var Item:TpvXMLClass; begin Item:=TpvXMLClass.Create; Add(Item); result:=Item; end; procedure TpvXMLClassList.Insert(Index:TpvInt32;Item:TpvXMLClass); var Counter:TpvInt32; begin if (Index>=0) and (Index<InternalCount) then begin SetCount(InternalCount+1); for Counter:=InternalCount-1 downto Index do begin InternalList^[Counter+1]:=InternalList^[Counter]; end; InternalList^[Index]:=Item; end else if Index=InternalCount then begin Add(Item); end else if Index>InternalCount then begin SetCount(Index); Add(Item); end; end; procedure TpvXMLClassList.Delete(Index:TpvInt32); var i,j:TpvInt32; begin if (Index>=0) and (Index<InternalCount) then begin j:=InternalCount-1; i:=Index; Move(InternalList^[i+1],InternalList^[i],(j-i)*SizeOf(TpvXMLClass)); SetCount(j); end; end; procedure TpvXMLClassList.DeleteClass(Index:TpvInt32); var i,j:TpvInt32; begin if (Index>=0) and (Index<InternalCount) then begin j:=InternalCount-1; i:=Index; if assigned(InternalList^[i]) then begin InternalList^[i].Free; InternalList^[i]:=nil; end; Move(InternalList^[i+1],InternalList^[i],(j-i)*SizeOf(TpvXMLClass)); SetCount(j); end; end; function TpvXMLClassList.Remove(Item:TpvXMLClass):TpvInt32; var i,j,k:TpvInt32; begin result:=-1; k:=InternalCount; j:=-1; for i:=0 to k-1 do begin if InternalList^[i]=Item then begin j:=i; break; end; end; if j>=0 then begin dec(k); Move(InternalList^[j+1],InternalList^[j],(k-j)*SizeOf(TpvXMLClass)); SetCount(k); result:=j; end; end; function TpvXMLClassList.RemoveClass(Item:TpvXMLClass):TpvInt32; var i,j,k:TpvInt32; begin result:=-1; k:=InternalCount; j:=-1; for i:=0 to k-1 do begin if InternalList^[i]=Item then begin j:=i; break; end; end; if j>=0 then begin dec(k); Move(InternalList^[j+1],InternalList^[j],(k-j)*SizeOf(TpvXMLClass)); SetCount(k); Item.Free; result:=j; end; end; function TpvXMLClassList.Find(Item:TpvXMLClass):TpvInt32; var i:TpvInt32; begin result:=-1; for i:=0 to InternalCount-1 do begin if InternalList^[i]=Item then begin result:=i; exit; end; end; end; function TpvXMLClassList.IndexOf(Item:TpvXMLClass):TpvInt32; var i:TpvInt32; begin result:=-1; for i:=0 to InternalCount-1 do begin if InternalList^[i]=Item then begin result:=i; exit; end; end; end; procedure TpvXMLClassList.Exchange(Index1,Index2:TpvInt32); var TempPointer:TpvXMLClass; begin if (Index1>=0) and (Index1<InternalCount) and (Index2>=0) and (Index2<InternalCount) then begin TempPointer:=InternalList^[Index1]; InternalList^[Index1]:=InternalList^[Index2]; InternalList^[Index2]:=TempPointer; end; end; function TpvXMLClassList.Push(Item:TpvXMLClass):TpvInt32; begin result:=Add(Item); end; function TpvXMLClassList.Pop(var Item:TpvXMLClass):boolean; begin result:=InternalCount>0; if result then begin Item:=InternalList^[InternalCount-1]; Delete(InternalCount-1); end; end; function TpvXMLClassList.Pop:TpvXMLClass; begin if InternalCount>0 then begin result:=InternalList^[InternalCount-1]; Delete(InternalCount-1); end else begin result:=nil; end; end; function TpvXMLClassList.Last:TpvXMLClass; begin if InternalCount>0 then begin result:=InternalList^[InternalCount-1]; end else begin result:=nil; end; end; function TpvXMLClassList.GetItem(Index:TpvInt32):TpvXMLClass; begin if (Index>=0) and (Index<InternalCount) then begin result:=InternalList^[Index]; end else begin result:=nil; end; end; procedure TpvXMLClassList.SetItem(Index:TpvInt32;Value:TpvXMLClass); begin if (Index>=0) and (Index<InternalCount) then begin InternalList^[Index]:=Value; end; end; function TpvXMLClassList.GetItemPointer(Index:TpvInt32):TpvXMLClass; begin if (Index>=0) and (Index<InternalCount) then begin result:=@InternalList^[Index]; end else begin result:=nil; end; end; constructor TpvXMLClassLinkedList.Create; begin inherited Create; ClearWithContentDestroying:=false; ClearNoFree; end; destructor TpvXMLClassLinkedList.Destroy; begin Clear; inherited Destroy; end; procedure TpvXMLClassLinkedList.Clear; begin if ClearWithContentDestroying then begin ClearWithFree; end else begin ClearNoFree; end; end; procedure TpvXMLClassLinkedList.ClearNoFree; var Current,Next:TpvXMLClass; begin Current:=First; while assigned(Current) do begin Next:=Current.Next; Remove(Current); Current:=Next; end; First:=nil; Last:=nil; end; procedure TpvXMLClassLinkedList.ClearWithFree; var Current,Next:TpvXMLClass; begin Current:=First; while assigned(Current) do begin Next:=Current.Next; RemoveClass(Current); Current:=Next; end; First:=nil; Last:=nil; end; procedure TpvXMLClassLinkedList.Add(Item:TpvXMLClass); begin Item.Next:=nil; if assigned(Last) then begin Last.Next:=Item; Item.Previous:=Last; end else begin Item.Previous:=nil; First:=Item; end; Last:=Item; end; procedure TpvXMLClassLinkedList.Append(Item:TpvXMLClass); begin Add(Item); end; procedure TpvXMLClassLinkedList.AddLinkedList(List:TpvXMLClassLinkedList); begin Last.Next:=List.First; if assigned(List.First) then begin List.First.Previous:=Last; end; Last:=List.Last; List.First:=nil; List.Last:=nil; end; procedure TpvXMLClassLinkedList.AppendLinkedList(List:TpvXMLClassLinkedList); begin AddLinkedList(List); end; procedure TpvXMLClassLinkedList.Remove(Item:TpvXMLClass); begin if assigned(Item) then begin if assigned(Item.Next) then begin Item.Next.Previous:=Item.Previous; end else if Last=Item then begin Last:=Item.Previous; end; if assigned(Item.Previous) then begin Item.Previous.Next:=Item.Next; end else if First=Item then begin First:=Item.Next; end; Item.Previous:=nil; Item.Next:=nil; end; end; procedure TpvXMLClassLinkedList.RemoveClass(Item:TpvXMLClass); begin if assigned(Item) then begin Remove(Item); Item.Free; end; end; procedure TpvXMLClassLinkedList.Push(Item:TpvXMLClass); begin Add(Item); end; function TpvXMLClassLinkedList.Pop(var Item:TpvXMLClass):boolean; begin result:=assigned(Last); if result then begin Item:=Last; Remove(Last); end; end; function TpvXMLClassLinkedList.Pop:TpvXMLClass; begin result:=Last; if assigned(Last) then begin Remove(Last); end; end; function TpvXMLClassLinkedList.Count:TpvInt32; var Current:TpvXMLClass; begin result:=0; Current:=First; while assigned(Current) do begin inc(result); Current:=Current.Next; end; end; constructor TpvXMLItem.Create; begin inherited Create; Items:=TpvXMLItemList.Create; end; destructor TpvXMLItem.Destroy; begin Items.Free; inherited Destroy; end; procedure TpvXMLItem.Clear; begin Items.Clear; end; procedure TpvXMLItem.Add(Item:TpvXMLItem); begin Items.Add(Item); end; procedure TpvXMLItem.Assign(From:TpvXMLItem); var i:TpvInt32; NewItem:TpvXMLItem; begin Items.ClearWithFree; NewItem:=nil; for i:=0 to Items.Count-1 do begin if Items[i] is TpvXMLTag then begin NewItem:=TpvXMLTag.Create; end else if Items[i] is TpvXMLCommentTag then begin NewItem:=TpvXMLCommentTag.Create; end else if Items[i] is TpvXMLScriptTag then begin NewItem:=TpvXMLScriptTag.Create; end else if Items[i] is TpvXMLProcessTag then begin NewItem:=TpvXMLProcessTag.Create; end else if Items[i] is TpvXMLCDATATag then begin NewItem:=TpvXMLCDATATag.Create; end else if Items[i] is TpvXMLDOCTYPETag then begin NewItem:=TpvXMLDOCTYPETag.Create; end else if Items[i] is TpvXMLExtraTag then begin NewItem:=TpvXMLExtraTag.Create; end else if Items[i] is TpvXMLText then begin NewItem:=TpvXMLText.Create; end else if Items[i] is TpvXMLItem then begin NewItem:=Items[i].Create; end else begin continue; end; NewItem.Assign(Items[i]); Items.Add(NewItem); end; end; function TpvXMLItem.FindTag(const TagName:TpvRawByteString):TpvXMLTag; begin result:=Items.FindTag(TagName); end; function TpvXMLItem.FindTags(const TagName:TpvRawByteString):TpvXMLTags; begin result:=Items.FindTags(TagName); end; constructor TpvXMLItemList.Create; begin inherited Create; ClearWithContentDestroying:=true; //CapacityMask:=$f; CapacityMinimium:=0; end; destructor TpvXMLItemList.Destroy; begin ClearWithFree; inherited Destroy; end; function TpvXMLItemList.NewClass:TpvXMLItem; begin result:=TpvXMLItem.Create; Add(result); end; function TpvXMLItemList.GetItem(Index:TpvInt32):TpvXMLItem; begin result:=TpvXMLItem(inherited Items[Index]); end; procedure TpvXMLItemList.SetItem(Index:TpvInt32;Value:TpvXMLItem); begin inherited Items[Index]:=Value; end; function TpvXMLItemList.FindTag(const TagName:TpvRawByteString):TpvXMLTag; var i:TpvInt32; Item:TpvXMLItem; begin result:=nil; for i:=0 to Count-1 do begin Item:=TpvXMLItem(inherited Items[i]); if (assigned(Item) and (Item is TpvXMLTag)) and (TpvXMLTag(Item).Name=TagName) then begin result:=TpvXMLTag(Item); break; end; end; end; function TpvXMLItemList.FindTags(const TagName:TpvRawByteString):TpvXMLTags; var i,j:TpvInt32; Item:TpvXMLItem; begin result:=nil; j:=0; try for i:=0 to Count-1 do begin Item:=TpvXMLItem(inherited Items[i]); if (assigned(Item) and (Item is TpvXMLTag)) and (TpvXMLTag(Item).Name=TagName) then begin if length(result)<(j+1) then begin SetLength(result,(j+1)*2); end; result[j]:=Item as TpvXMLTag; inc(j); end; end; finally SetLength(result,j); end; end; constructor TpvXMLParameter.Create; begin inherited Create; Name:=''; Value:=''; end; destructor TpvXMLParameter.Destroy; begin Name:=''; Value:=''; inherited Destroy; end; procedure TpvXMLParameter.Assign(From:TpvXMLParameter); begin Name:=From.Name; Value:=From.Value; end; constructor TpvXMLText.Create; begin inherited Create; Text:=''; end; destructor TpvXMLText.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLText.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLText then begin Text:=TpvXMLText(From).Text; end; end; procedure TpvXMLText.SetText(AText:TpvRawByteString); begin Text:=AText; end; constructor TpvXMLCommentTag.Create; begin inherited Create; Text:=''; end; destructor TpvXMLCommentTag.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLCommentTag.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLCommentTag then begin Text:=TpvXMLCommentTag(From).Text; end; end; procedure TpvXMLCommentTag.SetText(AText:TpvRawByteString); begin Text:=AText; end; constructor TpvXMLTag.Create; begin inherited Create; Name:=''; Parameter:=nil; ParameterHashMap:=TpvXMLTagParameterHashMap.Create(nil); end; destructor TpvXMLTag.Destroy; begin Clear; FreeAndNil(ParameterHashMap); inherited Destroy; end; procedure TpvXMLTag.Clear; var Counter:TpvInt32; begin inherited Clear; ParameterHashMap.Clear; for Counter:=0 to length(Parameter)-1 do begin Parameter[Counter].Free; end; SetLength(Parameter,0); Name:=''; end; procedure TpvXMLTag.Assign(From:TpvXMLItem); var Counter:TpvInt32; begin inherited Assign(From); if From is TpvXMLTag then begin for Counter:=0 to length(Parameter)-1 do begin Parameter[Counter].Free; end; SetLength(Parameter,0); Name:=TpvXMLTag(From).Name; for Counter:=0 to length(TpvXMLTag(From).Parameter)-1 do begin AddParameter(TpvXMLTag(From).Parameter[Counter].Name,TpvXMLTag(From).Parameter[Counter].Value); end; end; end; function TpvXMLTag.FindParameter(ParameterName:TpvRawByteString):TpvXMLParameter; begin result:=ParameterHashMap[ParameterName]; end; function TpvXMLTag.GetParameter(ParameterName:TpvRawByteString;default:TpvRawByteString=''):TpvRawByteString; var Parameter:TpvXMLParameter; begin Parameter:=FindParameter(ParameterName); if assigned(Parameter) then begin result:=Parameter.Value; end else begin result:=Default; end; end; function TpvXMLTag.AddParameter(AParameter:TpvXMLParameter):boolean; var Index:TpvInt32; begin try Index:=length(Parameter); SetLength(Parameter,Index+1); Parameter[Index]:=AParameter; ParameterHashMap.Add(AParameter.Name,AParameter); result:=true; except result:=false; end; end; function TpvXMLTag.AddParameter(Name:TpvRawByteString;Value:TpvXMLString):boolean; var AParameter:TpvXMLParameter; begin AParameter:=TpvXMLParameter.Create; AParameter.Name:=Name; AParameter.Value:=Value; result:=AddParameter(AParameter); end; function TpvXMLTag.RemoveParameter(AParameter:TpvXMLParameter):boolean; var Found,Counter:TpvInt32; begin result:=false; Found:=-1; for Counter:=0 to length(Parameter)-1 do begin if Parameter[Counter]=AParameter then begin Found:=Counter; break; end; end; if Found>=0 then begin for Counter:=Found to length(Parameter)-2 do begin Parameter[Counter]:=Parameter[Counter+1]; end; SetLength(Parameter,length(Parameter)-1); ParameterHashMap.Delete(AParameter.Name); AParameter.Free; result:=true; end; end; function TpvXMLTag.RemoveParameter(ParameterName:TpvRawByteString):boolean; begin result:=RemoveParameter(FindParameter(ParameterName)); end; constructor TpvXMLProcessTag.Create; begin inherited Create; end; destructor TpvXMLProcessTag.Destroy; begin inherited Destroy; end; procedure TpvXMLProcessTag.Assign(From:TpvXMLItem); begin inherited Assign(From); end; constructor TpvXMLScriptTag.Create; begin inherited Create; Text:=''; end; destructor TpvXMLScriptTag.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLScriptTag.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLScriptTag then begin Text:=TpvXMLScriptTag(From).Text; end; end; procedure TpvXMLScriptTag.SetText(AText:TpvRawByteString); begin Text:=AText; end; constructor TpvXMLCDataTag.Create; begin inherited Create; Text:=''; end; destructor TpvXMLCDataTag.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLCDataTag.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLCDataTag then begin Text:=TpvXMLCDataTag(From).Text; end; end; procedure TpvXMLCDataTag.SetText(AText:TpvRawByteString); begin Text:=AText; end; constructor TpvXMLDOCTYPETag.Create; begin inherited Create; Text:=''; end; destructor TpvXMLDOCTYPETag.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLDOCTYPETag.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLDOCTYPETag then begin Text:=TpvXMLDOCTYPETag(From).Text; end; end; procedure TpvXMLDOCTYPETag.SetText(AText:TpvRawByteString); begin Text:=AText; end; constructor TpvXMLExtraTag.Create; begin inherited Create; Text:=''; end; destructor TpvXMLExtraTag.Destroy; begin Text:=''; inherited Destroy; end; procedure TpvXMLExtraTag.Assign(From:TpvXMLItem); begin inherited Assign(From); if From is TpvXMLExtraTag then begin Text:=TpvXMLExtraTag(From).Text; end; end; procedure TpvXMLExtraTag.SetText(AText:TpvRawByteString); begin Text:=AText; end; const EntityChars:array[1..102,1..2] of TpvXMLString=(('&quot;',#34),('&amp;',#38),('&apos;',''''), ('&lt;',#60),('&gt;',#62),('&euro;',#128),('&nbsp;',#160),('&iexcl;',#161), ('&cent;',#162),('&pound;',#163),('&curren;',#164),('&yen;',#165), ('&brvbar;',#166),('&sect;',#167),('&uml;',#168),('&copy;',#169), ('&ordf;',#170),('&laquo;',#171),('&not;',#172),('&shy;',#173), ('&reg;',#174),('&macr;',#175),('&deg;',#176),('&plusmn;',#177), ('&sup2;',#178),('&sup3;',#179),('&acute;',#180),('&micro;',#181), ('&para;',#182),('&middot;',#183),('&cedil;',#184),('&sup1;',#185), ('&ordm;',#186),('&raquo;',#187),('&frac14;',#188),('&frac12;',#189), ('&frac34;',#190),('&iquest;',#191),('&Agrave;',#192),('&Aacute;',#193), ('&Acirc;',#194),('&Atilde;',#195),('&Auml;',#196),('&Aring;',#197), ('&AElig;',#198),('&Ccedil;',#199),('&Egrave;',#200),('&Eacute;',#201), ('&Ecirc;',#202),('&Euml;',#203),('&Igrave;',#204),('&Iacute;',#205), ('&Icirc;',#206),('&Iuml;',#207),('&ETH;',#208),('&Ntilde;',#209), ('&Ograve;',#210),('&Oacute;',#211),('&Ocirc;',#212),('&Otilde;',#213), ('&Ouml;',#214),('&times;',#215),('&Oslash;',#216),('&Ugrave;',#217), ('&Uacute;',#218),('&Ucirc;',#219),('&Uuml;',#220),('&Yacute;',#221), ('&THORN;',#222),('&szlig;',#223),('&agrave;',#224),('&aacute;',#225), ('&acirc;',#226),('&atilde;',#227),('&auml;',#228),('&aring;',#229), ('&aelig;',#230),('&ccedil;',#231),('&egrave;',#232),('&eacute;',#233), ('&ecirc;',#234),('&euml;',#235),('&igrave;',#236),('&iacute;',#237), ('&icirc;',#238),('&iuml;',#239),('&eth;',#240),('&ntilde;',#241), ('&ograve;',#242),('&oacute;',#243),('&ocirc;',#244),('&otilde;',#245), ('&ouml;',#246),('&divide;',#247),('&oslash;',#248),('&ugrave;',#249), ('&uacute;',#250),('&ucirc;',#251),('&uuml;',#252),('&yacute;',#253), ('&thorn;',#254),('&yuml;',#255)); type TEntitiesCharLookUpItem=record IsEntity:boolean; Entity:TpvRawByteString; end; TEntitiesCharLookUpTable=array[0..{$ifdef XMLUnicode}65535{$else}255{$endif}] of TEntitiesCharLookUpItem; TEntityStringHashMap=class(TpvStringHashMap<TpvInt32>); var EntitiesCharLookUp:TEntitiesCharLookUpTable; EntityStringHashMap:TEntityStringHashMap; const EntityInitialized:boolean=false; procedure InitializeEntites; var EntityCounter:TpvInt32; begin if not EntityInitialized then begin EntityInitialized:=true; EntityStringHashMap:=TEntityStringHashMap.Create(-1); FillChar(EntitiesCharLookUp,SizeOf(TEntitiesCharLookUpTable),#0); for EntityCounter:=low(EntityChars) to high(EntityChars) do begin EntityStringHashMap.Add(EntityChars[EntityCounter,1],EntityCounter); with EntitiesCharLookUp[ord(EntityChars[EntityCounter,2][1])] do begin IsEntity:=true; Entity:=EntityChars[EntityCounter,1]; end; end; end; end; procedure FinalizeEntites; begin FreeAndNil(EntityStringHashMap); EntityInitialized:=false; end; function ConvertToEntities(AString:TpvXMLString;IdentLevel:TpvInt32=0):TpvRawByteString; var Counter,IdentCounter:TpvInt32; c:TpvXMLChar; begin result:=''; for Counter:=1 to length(AString) do begin c:=AString[Counter]; if c=#13 then begin if ((Counter+1)<=length(AString)) and (AString[Counter+1]=#10) then begin continue; end; c:=#10; end; if EntitiesCharLookUp[ord(c)].IsEntity then begin result:=result+EntitiesCharLookUp[ord(c)].Entity; end else if (c=#9) or (c=#10) or (c=#13) or ((c>=#32) and (c<=#127)) then begin result:=result+c; if c=#10 then begin for IdentCounter:=1 to IdentLevel do begin result:=result+' '; end; end; end else begin {$ifdef XMLUnicode} if c<#255 then begin result:=result+'&#'+TpvRawByteString(IntToStr(ord(c)))+';'; end else begin result:=result+'&#x'+TpvRawByteString(IntToHex(ord(c),4))+';'; end; {$else} result:=result+'&#'+TpvRawByteString(IntToStr(TpvUInt8(c)))+';'; {$endif} end; end; end; constructor TpvXML.Create; begin inherited Create; InitializeEntites; Root:=TpvXMLItem.Create; AutomaticAloneTagDetection:=true; FormatIndent:=true; FormatIndentText:=false; end; destructor TpvXML.Destroy; begin Root.Free; inherited Destroy; end; procedure TpvXML.Assign(From:TpvXML); begin Root.Assign(From.Root); AutomaticAloneTagDetection:=From.AutomaticAloneTagDetection; FormatIndent:=From.FormatIndent; FormatIndentText:=From.FormatIndentText; end; function TpvXML.Parse(Stream:TStream):boolean; const NameCanBeginWithCharSet:set of TpvRawByteChar=['A'..'Z','a'..'z','_']; NameCanContainCharSet:set of TpvRawByteChar=['A'..'Z','a'..'z','0'..'9','.',':','_','-']; BlankCharSet:set of TpvRawByteChar=[#0..#$20];//[#$9,#$A,#$D,#$20]; type TEncoding=(ASCII,UTF8,UTF16); var Errors:boolean; CurrentChar:TpvRawByteChar; StreamEOF:boolean; Encoding:TEncoding; function IsEOF:boolean; begin result:=StreamEOF or (Stream.Position>Stream.Size); end; function IsEOFOrErrors:boolean; begin result:=IsEOF or Errors; end; function NextChar:TpvRawByteChar; begin if Stream.Read(CurrentChar,SizeOf(TpvRawByteChar))<>SizeOf(TpvRawByteChar) then begin StreamEOF:=true; CurrentChar:=#0; end; result:=CurrentChar; //system.Write(result); end; procedure SkipBlank; begin while (CurrentChar in BlankCharSet) and not IsEOFOrErrors do begin NextChar; end; end; function GetName:TpvRawByteString; var i:TpvInt32; begin result:=''; i:=0; if (CurrentChar in NameCanBeginWithCharSet) and not IsEOFOrErrors then begin while (CurrentChar in NameCanContainCharSet) and not IsEOFOrErrors do begin inc(i); if (i+1)>length(result) then begin SetLength(result,RoundUpToPowerOfTwo(i+1)); end; result[i]:=CurrentChar; NextChar; end; end; SetLength(result,i); end; function ExpectToken(const s:TpvRawByteString):boolean; overload; var i:TpvInt32; begin result:=true; for i:=1 to length(s) do begin if s[i]<>CurrentChar then begin result:=false; break; end; NextChar; end; end; function ExpectToken(const c:TpvRawByteChar):boolean; overload; begin result:=false; if c=CurrentChar then begin result:=true; NextChar; end; end; function GetUntil(var Content:TpvRawByteString;const TerminateToken:TpvRawByteString):boolean; var i,j,OldPosition:TpvInt32; OldEOF:boolean; OldChar:TpvRawByteChar; begin result:=false; j:=0; Content:=''; while not IsEOFOrErrors do begin if (length(TerminateToken)>0) and (TerminateToken[1]=CurrentChar) and (((Stream.Size-Stream.Position)+1)>=length(TerminateToken)) then begin OldPosition:=Stream.Position; OldEOF:=StreamEOF; OldChar:=CurrentChar; for i:=1 to length(TerminateToken) do begin if TerminateToken[i]=CurrentChar then begin if i=length(TerminateToken) then begin NextChar; SetLength(Content,j); result:=true; exit; end; end else begin break; end; NextChar; end; Stream.Seek(OldPosition,soFromBeginning); StreamEOF:=OldEOF; CurrentChar:=OldChar; end; inc(j); if (j+1)>length(Content) then begin SetLength(Content,RoundUpToPowerOfTwo(j+1)); end; Content[j]:=CurrentChar; NextChar; end; SetLength(Content,j); end; function GetDecimalValue:TpvInt32; var Negitive:boolean; begin Negitive:=CurrentChar='-'; if Negitive then begin NextChar; end else if CurrentChar='+' then begin NextChar; end; result:=0; while (CurrentChar in ['0'..'9']) and not IsEOFOrErrors do begin result:=(result*10)+(ord(CurrentChar)-ord('0')); NextChar; end; if Negitive then begin result:=-result; end; end; function GetHeximalValue:TpvInt32; var Negitive:boolean; Value:TpvInt32; begin Negitive:=CurrentChar='-'; if Negitive then begin NextChar; end else if CurrentChar='+' then begin NextChar; end; result:=0; Value:=0; while not IsEOFOrErrors do begin case CurrentChar of '0'..'9':begin Value:=TpvUInt8(CurrentChar)-ord('0'); end; 'A'..'F':begin Value:=(TpvUInt8(CurrentChar)-ord('A'))+$a; end; 'a'..'f':begin Value:=(TpvUInt8(CurrentChar)-ord('a'))+$a; end; else begin break; end; end; result:=(result shl 4) or Value; NextChar; end; if Negitive then begin result:=-result; end; end; function GetEntity:TpvXMLString; var Value:TpvInt32; Entity:TpvRawByteString; c:TpvXMLChar; begin result:=''; if CurrentChar='&' then begin NextChar; if not IsEOF then begin if CurrentChar='#' then begin NextChar; if IsEOF then begin Errors:=true; end else begin if CurrentChar='x' then begin NextChar; Value:=GetHeximalValue; end else begin Value:=GetDecimalValue; end; if CurrentChar=';' then begin NextChar; {$ifdef XMLUnicode} c:=WideChar(TpvUInt16(Value)); {$else} c:=TpvRawByteChar(TpvUInt8(Value)); {$endif} result:=c; end else begin Errors:=true; end; end; end else begin Entity:='&'; while (CurrentChar in ['a'..'z','A'..'Z','0'..'9','_']) and not IsEOFOrErrors do begin Entity:=Entity+CurrentChar; NextChar; end; if CurrentChar=';' then begin Entity:=Entity+CurrentChar; NextChar; if EntityStringHashMap.TryGet(Entity,Value) then begin result:=EntityChars[Value,2]; end else begin result:=Entity; end; end else begin Errors:=true; end; end; end; end; end; function ParseTagParameterValue(TerminateChar:TpvRawByteChar):TpvXMLString; var i,wc,c:TpvInt32; begin result:=''; SkipBlank; i:=0; while (CurrentChar<>TerminateChar) and not IsEOFOrErrors do begin if (Encoding=TEncoding.UTF8) and (ord(CurrentChar)>=$80) then begin wc:=ord(CurrentChar) and $3f; if (wc and $20)<>0 then begin NextChar; c:=ord(CurrentChar); if (c and $c0)<>$80 then begin break; end; wc:=(wc shl 6) or (c and $3f); end; NextChar; c:=ord(CurrentChar); if (c and $c0)<>$80 then begin break; end; wc:=(wc shl 6) or (c and $3f); NextChar; inc(i); if (i+1)>length(result) then begin SetLength(result,RoundUpToPowerOfTwo(i+1)); end; {$ifdef XMLUnicode} result[i]:=WideChar(wc); {$else} result[i]:=TpvRawByteChar(wc); {$endif} end else if CurrentChar='&' then begin SetLength(result,i); result:=result+GetEntity; i:=length(result); end else begin inc(i); if (i+1)>length(result) then begin SetLength(result,RoundUpToPowerOfTwo(i+1)); end; {$ifdef XMLUnicode} result[i]:=WideChar(TpvUInt16(TpvUInt8(CurrentChar)+0)); {$else} result[i]:=CurrentChar; {$endif} NextChar; end; end; SetLength(result,i); NextChar; end; procedure ParseTagParameter(XMLTag:TpvXMLTag); var ParameterName,ParameterValue:TpvRawByteString; TerminateChar:TpvRawByteChar; begin SkipBlank; while (CurrentChar in NameCanBeginWithCharSet) and not IsEOFOrErrors do begin ParameterName:=GetName; SkipBlank; if CurrentChar='=' then begin NextChar; if IsEOFOrErrors then begin Errors:=true; break; end; end else begin Errors:=true; break; end; SkipBlank; if CurrentChar in ['''','"'] then begin TerminateChar:=CurrentChar; NextChar; if IsEOFOrErrors then begin Errors:=true; break; end; ParameterValue:=ParseTagParameterValue(TerminateChar); if Errors then begin break; end else begin XMLTag.AddParameter(ParameterName,ParameterValue); SkipBlank; end; end else begin Errors:=true; break; end; end; end; procedure Process(ParentItem:TpvXMLItem;Closed:boolean); var FinishLevel:boolean; procedure ParseText; var Text:TpvXMLString; XMLText:TpvXMLText; i,wc,c:TpvInt32; {$ifndef XMLUnicode} w:TpvRawByteString; {$endif} begin SkipBlank; if CurrentChar='<' then begin exit; end; i:=0; Text:=''; SetLength(Text,16); while (CurrentChar<>'<') and not IsEOFOrErrors do begin if (Encoding=TEncoding.UTF8) and (ord(CurrentChar)>=$80) then begin wc:=ord(CurrentChar) and $3f; if (wc and $20)<>0 then begin NextChar; c:=ord(CurrentChar); if (c and $c0)<>$80 then begin break; end; wc:=(wc shl 6) or (c and $3f); end; NextChar; c:=ord(CurrentChar); if (c and $c0)<>$80 then begin break; end; wc:=(wc shl 6) or (c and $3f); NextChar; {$ifdef XMLUnicode} if wc<=$d7ff then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16(wc)); end else if wc<=$dfff then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=#$fffd; end else if wc<=$fffd then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16(wc)); end else if wc<=$ffff then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=#$fffd; end else if wc<=$10ffff then begin dec(wc,$10000); inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16((wc shr 10) or $d800)); inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16((wc and $3ff) or $dc00)); end else begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=#$fffd; end; {$else} if wc<$80 then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+1)); end; Text[i]:=TpvRawByteChar(TpvUInt8(wc)); end else begin w:=PUCUUTF32CharToUTF8(wc); if length(w)>0 then begin inc(i); if (i+length(w)+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+length(w)+1)); end; Move(w[1],Text[i],length(w)); inc(i,length(w)-1); end; end; {$endif} end else if CurrentChar='&' then begin SetLength(Text,i); Text:=Text+GetEntity; i:=length(Text); end else if CurrentChar in BlankCharSet then begin {$ifdef XMLUnicode} inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16(TpvUInt8(CurrentChar)+0)); {$else} wc:=ord(CurrentChar); if wc<$80 then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+1)); end; Text[i]:=TpvRawByteChar(TpvUInt8(wc)); end else begin w:=PUCUUTF32CharToUTF8(wc); if length(w)>0 then begin inc(i); if (i+length(w)+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+length(w)+1)); end; Move(w[1],Text[i],length(w)); inc(i,length(w)-1); end; end; {$endif} SkipBlank; end else begin {$ifdef XMLUnicode} inc(i); if (i+1)>length(Text) then begin SetLength(Text,VulkanRoundUpToPowerOfTwo(i+1)); end; Text[i]:=WideChar(TpvUInt16(TpvUInt8(CurrentChar)+0)); {$else} wc:=ord(CurrentChar); if wc<$80 then begin inc(i); if (i+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+1)); end; Text[i]:=TpvRawByteChar(TpvUInt8(wc)); end else begin w:=PUCUUTF32CharToUTF8(wc); if length(w)>0 then begin inc(i); if (i+length(w)+1)>length(Text) then begin SetLength(Text,RoundUpToPowerOfTwo(i+length(w)+1)); end; Move(w[1],Text[i],length(w)); inc(i,length(w)-1); end; end; {$endif} NextChar; end; end; SetLength(Text,i); if length(Text)<>0 then begin XMLText:=TpvXMLText.Create; XMLText.Text:=Text; ParentItem.Add(XMLText); end; end; procedure ParseProcessTag; var TagName,EncodingName:TpvRawByteString; XMLProcessTag:TpvXMLProcessTag; begin if not ExpectToken('?') then begin Errors:=true; exit; end; TagName:=GetName; if IsEOF or Errors then begin Errors:=true; exit; end; XMLProcessTag:=TpvXMLProcessTag.Create; XMLProcessTag.Name:=TagName; ParentItem.Add(XMLProcessTag); ParseTagParameter(XMLProcessTag); if not ExpectToken('?>') then begin Errors:=true; exit; end; if XMLProcessTag.Name='xml' then begin EncodingName:=TpvRawByteString(UpperCase(String(XMLProcessTag.GetParameter('encoding','ascii')))); if EncodingName='UTF-8' then begin Encoding:=TEncoding.UTF8; end else if EncodingName='UTF-16' then begin Encoding:=TEncoding.UTF16; end else begin Encoding:=TEncoding.ASCII; end; end; end; procedure ParseScriptTag; var XMLScriptTag:TpvXMLScriptTag; begin if not ExpectToken('%') then begin Errors:=true; exit; end; if IsEOFOrErrors then begin Errors:=true; exit; end; XMLScriptTag:=TpvXMLScriptTag.Create; ParentItem.Add(XMLScriptTag); if not GetUntil(XMLScriptTag.Text,'%>') then begin Errors:=true; end; end; procedure ParseCommentTag; var XMLCommentTag:TpvXMLCommentTag; begin if not ExpectToken('--') then begin Errors:=true; exit; end; if IsEOFOrErrors then begin Errors:=true; exit; end; XMLCommentTag:=TpvXMLCommentTag.Create; ParentItem.Add(XMLCommentTag); if not GetUntil(XMLCommentTag.Text,'-->') then begin Errors:=true; end; end; procedure ParseCDATATag; var XMLCDataTag:TpvXMLCDataTag; begin if not ExpectToken('[CDATA[') then begin Errors:=true; exit; end; if IsEOFOrErrors then begin Errors:=true; exit; end; XMLCDataTag:=TpvXMLCDataTag.Create; ParentItem.Add(XMLCDataTag); if not GetUntil(XMLCDataTag.Text,']]>') then begin Errors:=true; end; end; procedure ParseDOCTYPEOrExtraTag; var Content:TpvRawByteString; XMLDOCTYPETag:TpvXMLDOCTYPETag; XMLExtraTag:TpvXMLExtraTag; begin Content:=''; if not GetUntil(Content,'>') then begin Errors:=true; exit; end; if pos('DOCTYPE',String(Content))=1 then begin XMLDOCTYPETag:=TpvXMLDOCTYPETag.Create; ParentItem.Add(XMLDOCTYPETag); XMLDOCTYPETag.Text:=TpvRawByteString(TrimLeft(Copy(String(Content),8,length(String(Content))-7))); end else begin XMLExtraTag:=TpvXMLExtraTag.Create; ParentItem.Add(XMLExtraTag); XMLExtraTag.Text:=Content; end; end; procedure ParseTag; var TagName:TpvRawByteString; XMLTag:TpvXMLTag; IsAloneTag:boolean; begin if CurrentChar='/' then begin NextChar; if IsEOFOrErrors then begin Errors:=true; exit; end; TagName:='/'+GetName; end else begin TagName:=GetName; end; if IsEOFOrErrors then begin Errors:=true; exit; end; XMLTag:=TpvXMLTag.Create; XMLTag.Name:=TagName; ParseTagParameter(XMLTag); IsAloneTag:=CurrentChar='/'; if IsAloneTag then begin NextChar; if IsEOFOrErrors then begin Errors:=true; exit; end; end; if CurrentChar<>'>' then begin Errors:=true; exit; end; NextChar; if (ParentItem<>Root) and (ParentItem is TpvXMLTag) and (XMLTag.Name='/'+TpvXMLTag(ParentItem).Name) then begin XMLTag.Free; FinishLevel:=true; Closed:=true; end else begin ParentItem.Add(XMLTag); if not IsAloneTag then begin Process(XMLTag,false); end; end; // IsAloneTag:=false; end; begin FinishLevel:=false; while not (IsEOFOrErrors or FinishLevel) do begin ParseText; if CurrentChar='<' then begin NextChar; if not IsEOFOrErrors then begin if CurrentChar='/' then begin ParseTag; end else if CurrentChar='?' then begin ParseProcessTag; end else if CurrentChar='%' then begin ParseScriptTag; end else if CurrentChar='!' then begin NextChar; if not IsEOFOrErrors then begin if CurrentChar='-' then begin ParseCommentTag; end else if CurrentChar='[' then begin ParseCDATATag; end else begin ParseDOCTYPEOrExtraTag; end; end; end else begin ParseTag; end; end; end; end; if not Closed then begin Errors:=true; end; end; begin Encoding:=TEncoding.ASCII; Errors:=false; CurrentChar:=#0; Root.Clear; StreamEOF:=false; Stream.Seek(0,soFromBeginning); NextChar; Process(Root,true); if Errors then begin Root.Clear; end; result:=not Errors; end; function TpvXML.Read(Stream:TStream):boolean; var BufferedStream:TStream; begin BufferedStream:=TpvSimpleBufferedStream.Create(Stream,false,4096); try result:=Parse(BufferedStream); finally BufferedStream.Free; end; end; function TpvXML.Write(Stream:TStream;IdentSize:TpvInt32=2):boolean; var IdentLevel:TpvInt32; Errors:boolean; BufferedStream:TStream; procedure Process(Item:TpvXMLItem;DoIndent:boolean); var Line:TpvRawByteString; Counter:TpvInt32; TagWithSingleLineText,ItemsText:boolean; procedure WriteLineEx(Line:TpvRawByteString); begin if length(Line)>0 then begin if BufferedStream.Write(Line[1],length(Line))<>length(Line) then begin Errors:=true; end; end; end; procedure WriteLine(Line:TpvRawByteString); begin if FormatIndent and DoIndent then begin Line:=Line+#10; end; if length(Line)>0 then begin if BufferedStream.Write(Line[1],length(Line))<>length(Line) then begin Errors:=true; end; end; end; begin if not Errors then begin if assigned(Item) then begin inc(IdentLevel,IdentSize); Line:=''; if FormatIndent and DoIndent then begin for Counter:=1 to IdentLevel do begin Line:=Line+' '; end; end; if Item is TpvXMLText then begin if FormatIndentText then begin Line:=Line+ConvertToEntities(TpvXMLText(Item).Text,IdentLevel); end else begin Line:=ConvertToEntities(TpvXMLText(Item).Text); end; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLCommentTag then begin Line:=Line+'<!--'+TpvXMLCommentTag(Item).Text+'-->'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLProcessTag then begin Line:=Line+'<?'+TpvXMLProcessTag(Item).Name; for Counter:=0 to length(TpvXMLProcessTag(Item).Parameter)-1 do begin if assigned(TpvXMLProcessTag(Item).Parameter[Counter]) then begin Line:=Line+' '+TpvXMLProcessTag(Item).Parameter[Counter].Name+'="'+ConvertToEntities(TpvXMLProcessTag(Item).Parameter[Counter].Value)+'"'; end; end; Line:=Line+'?>'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLScriptTag then begin Line:=Line+'<%'+TpvXMLScriptTag(Item).Text+'%>'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLCDataTag then begin Line:=Line+'<![CDATA['+TpvXMLCDataTag(Item).Text+']]>'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLDOCTYPETag then begin Line:=Line+'<!DOCTYPE '+TpvXMLDOCTYPETag(Item).Text+'>'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLExtraTag then begin Line:=Line+'<!'+TpvXMLExtraTag(Item).Text+'>'; WriteLine(Line); for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end else if Item is TpvXMLTag then begin if AutomaticAloneTagDetection then begin TpvXMLTag(Item).IsAloneTag:=TpvXMLTag(Item).Items.Count=0; end; Line:=Line+'<'+TpvXMLTag(Item).Name; for Counter:=0 to length(TpvXMLTag(Item).Parameter)-1 do begin if assigned(TpvXMLTag(Item).Parameter[Counter]) then begin Line:=Line+' '+TpvXMLTag(Item).Parameter[Counter].Name+'="'+ConvertToEntities(TpvXMLTag(Item).Parameter[Counter].Value)+'"'; end; end; if TpvXMLTag(Item).IsAloneTag then begin Line:=Line+' />'; WriteLine(Line); end else begin TagWithSingleLineText:=false; if Item.Items.Count=1 then begin if assigned(Item.Items[0]) then begin if Item.Items[0] is TpvXMLText then begin if ((Pos(#13,String(TpvXMLText(Item.Items[0]).Text))=0) and (Pos(#10,String(TpvXMLText(Item.Items[0]).Text))=0)) or not FormatIndentText then begin TagWithSingleLineText:=true; end; end; end; end; ItemsText:=false; for Counter:=0 to Item.Items.Count-1 do begin if assigned(Item.Items[Counter]) then begin if Item.Items[Counter] is TpvXMLText then begin ItemsText:=true; end; end; end; if TagWithSingleLineText then begin Line:=Line+'>'+ConvertToEntities(TpvXMLText(Item.Items[0]).Text)+'</'+TpvXMLTag(Item).Name+'>'; WriteLine(Line); end else if Item.Items.Count<>0 then begin Line:=Line+'>'; if assigned(Item.Items[0]) and (Item.Items[0] is TpvXMLText) and not FormatIndentText then begin WriteLineEx(Line); end else begin WriteLine(Line); end; for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent and ((not ItemsText) or (FormatIndent and FormatIndentText))); end; Line:=''; if DoIndent and ((not ItemsText) or (FormatIndent and FormatIndentText)) then begin for Counter:=1 to IdentLevel do begin Line:=Line+' '; end; end; Line:=Line+'</'+TpvXMLTag(Item).Name+'>'; WriteLine(Line); end else begin Line:=Line+'></'+TpvXMLTag(Item).Name+'>'; WriteLine(Line); end; end; end else begin for Counter:=0 to Item.Items.Count-1 do begin Process(Item.Items[Counter],DoIndent); end; end; dec(IdentLevel,IdentSize); end; end; end; begin IdentLevel:=-(2*IdentSize); if Stream is TMemoryStream then begin TMemoryStream(Stream).Clear; end; Errors:=false; BufferedStream:=TpvSimpleBufferedStream.Create(Stream,false,4096); try Process(Root,FormatIndent); finally BufferedStream.Free; end; result:=not Errors; end; function TpvXML.ReadXMLText:TpvRawByteString; var Stream:TMemoryStream; begin Stream:=TMemoryStream.Create; try Write(Stream); if Stream.Size>0 then begin SetLength(result,Stream.Size); Stream.Seek(0,soFromBeginning); Stream.Read(result[1],Stream.Size); end else begin result:=''; end; finally Stream.Free; end; end; procedure TpvXML.WriteXMLText(Text:TpvRawByteString); var Stream:TMemoryStream; begin Stream:=TMemoryStream.Create; try if length(Text)>0 then begin Stream.Write(Text[1],length(Text)); Stream.Seek(0,soFromBeginning); end; Parse(Stream); finally Stream.Free; end; end; procedure TpvXML.LoadFromStream(const aStream:TStream); begin if not Parse(aStream) then begin raise EpvXML.Create('XML parsing error'); end; end; procedure TpvXML.LoadFromFile(const aFileName:string); var Stream:TStream; begin Stream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TpvXML.SaveToStream(const aStream:TStream); begin if not Write(aStream) then begin raise EpvXML.Create('XML writing error'); end; end; procedure TpvXML.SaveToFile(const aFileName:string); var Stream:TStream; begin Stream:=TFileStream.Create(aFileName,fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; initialization InitializeEntites; finalization FinalizeEntites; end.
program stringsAndUtils; uses sysutils; { <- string utilities live here } var s : ANSIString; begin s := 'The Quick Brown Fox Jumps Over the Lazy Dog.'; writeln('Using bunch of string functions: '); appendstr(s, ' (appended) '); writeln(s); writeln; writeln(' -- compareSTR is case sentitive, compareTEXT is not. '); writeln('comparstr abc = ABC ? ', comparestr('abc', 'ABC')); writeln('comparetext abc = ABC ? ', comparetext('abc', 'ABC')); { apparently the result is just getings ascii of character a and subtracting the ascii number of character b. if the result is 0, then they are the same. } writeln; writeln(' -- isValidIdent means "is this a valid pascal identifier?"'); writeln('is 00var valid? ', isValidIdent('00var')); { i wonder if there's } writeln('is Death valid? ', isValidIdent('Death')); { an eval in Pascal } writeln('is _ valid? ', isValidIdent('_')); { lodash.pas? hmmmm } writeln('is $ valid? ', isValidIdent('$')); { no jquery.pas tho } writeln; { lastDelimiter(text, otherText) -> "text".lastIndexOf('char') } writeln(' -- index of last occurence of character in string'); writeln(' last x in the example sentence: '); writeln(' -> ', lastDelimiter('x', s)); writeln; writeln(' -- get first n characters of text'); writeln(' n=9 -> ', leftStr(s, 9)); writeln(' -- get last n characters of text'); writeln(' n=9 -> ', rightStr(s, 9)); writeln; writeln(' LowerCase and UpperCase '); writeln( lowerCase(s) ); writeln( upperCase(s) ); writeln; writeln(' other functions: '); writeln(' https://www.freepascal.org/docs-html/rtl/sysutils/stringfunctions.html '); writeln; end.
unit PluginSupport; {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$IFEND} interface uses SysUtils, PluginAPI; type // Переопределяем TNotifyEvent, чтобы не тащить Classes ради одного определения TNotifyEvent = procedure(Sender: TObject) of object; TPluginMenuItem = class(TObject, IUnknown, INotifyEvent) private FManager: IMenuManager; FItem: IMenuItem; FClick: TNotifyEvent; protected // IUnknown function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; // INotifyEvent procedure Execute(Sender: IInterface); safecall; public constructor Create(const ACore: ICore); destructor Destroy; override; property Item: IMenuItem read FItem; procedure Click; virtual; property OnClick: TNotifyEvent read FClick write FClick; function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override; end; implementation uses Helpers; { TPluginMenuItem } constructor TPluginMenuItem.Create(const ACore: ICore); begin inherited Create; if not Supports(ACore, IMenuManager, FManager) then Assert(False); FItem := FManager.CreateMenuItem; FItem.Caption := 'PluginMenuItem'; FItem.Hint := ''; FItem.Enabled := True; FItem.Checked := False; FItem.RegisterExecuteHandler(Self); end; destructor TPluginMenuItem.Destroy; begin FManager.DeleteMenuItem(FItem); FManager := nil; inherited; end; procedure TPluginMenuItem.Execute(Sender: IInterface); begin Click; end; procedure TPluginMenuItem.Click; begin if FItem.Enabled then begin if Assigned(FClick) then FClick(Self); end; end; function TPluginMenuItem.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TPluginMenuItem._AddRef: Integer; begin Result := -1; // -1 indicates no reference counting is taking place end; function TPluginMenuItem._Release: Integer; begin Result := -1; // -1 indicates no reference counting is taking place end; function TPluginMenuItem.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; begin Result := HandleSafeCallException(Self, ExceptObject, ExceptAddr); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Livros Contábeis The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit UContabilLivrosContabeis; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ActnList, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, DBXJSON, ACBrPonto_AFD_Class, Mask, JvExMask, JvToolEdit, LabeledCtrls, ACBrPonto_AFDT_Class, ComCtrls, JvBaseEdits, SessaoUsuario, System.Actions, Controller, Vcl.Imaging.pngimage, COMObj; type TFContabilLivrosContabeis = class(TForm) PanelCabecalho: TPanel; Bevel1: TBevel; Image1: TImage; Label2: TLabel; ActionToolBarPrincipal: TActionToolBar; ActionManagerLocal: TActionManager; ActionCancelar: TAction; ActionLivroDiario: TAction; PageControlItens: TPageControl; tsDados: TTabSheet; PanelDados: TPanel; ActionSair: TAction; PanelMestre: TPanel; EditPeriodo: TLabeledMaskEdit; ActionLivroRazao: TAction; ActionLivroBalancete: TAction; ActionLivroCaixa: TAction; procedure ActionCancelarExecute(Sender: TObject); procedure ActionSairExecute(Sender: TObject); procedure ActionLivroDiarioExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure ActionLivroCaixaExecute(Sender: TObject); procedure ActionLivroBalanceteExecute(Sender: TObject); procedure ActionLivroRazaoExecute(Sender: TObject); class function Sessao: TSessaoUsuario; private { Private declarations } public { Public declarations } end; var FContabilLivrosContabeis: TFContabilLivrosContabeis; implementation uses UDataModule; {$R *.dfm} class function TFContabilLivrosContabeis.Sessao: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; procedure TFContabilLivrosContabeis.ActionCancelarExecute(Sender: TObject); begin Close; end; procedure TFContabilLivrosContabeis.ActionSairExecute(Sender: TObject); begin Close; end; procedure TFContabilLivrosContabeis.FormShow(Sender: TObject); begin EditPeriodo.Clear; EditPeriodo.SetFocus; end; procedure TFContabilLivrosContabeis.ActionLivroBalanceteExecute(Sender: TObject); begin Application.MessageBox('Emitido no SPED Contábil.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFContabilLivrosContabeis.ActionLivroDiarioExecute(Sender: TObject); begin Application.MessageBox('Emitido no SPED Contábil.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFContabilLivrosContabeis.ActionLivroRazaoExecute(Sender: TObject); begin Application.MessageBox('Emitido no SPED Contábil.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFContabilLivrosContabeis.ActionLivroCaixaExecute(Sender: TObject); var (* RemoteDataInfo: TStringList; ConsultaSQL, NomeArquivo: String; i: Integer; *) ReportManager: Variant; begin (* try try NomeArquivo := 'LivroCaixa.rep'; FDataModule.VCLReport.GetRemoteParams(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo); FDataModule.VCLReport.Report.Params.ParamByName('PERIODO').Value := EditPeriodo.Text; // FDataModule.VCLReport.GetRemoteDataInfo(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo); RemoteDataInfo := FDataModule.VCLReport.Report.RemoteDataInfo; // ConsultaSQL := ''; FDataModule.VCLReport.ExecuteRemote(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo, ConsultaSQL); except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro na construção do relatório. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally end; *) try ReportManager := CreateOleObject('ReportMan.ReportManX'); ReportManager.Preview := True; ReportManager.ShowProgress := True; ReportManager.ShowPrintDialog := False; ReportManager.Filename := 'C:\T2Ti\Relatorios\LivroCaixa.rep'; ReportManager.SetParamValue('PERIODO', EditPeriodo.Text); ReportManager.execute; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a impressão. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.manager.dataset; interface uses DB, SysUtils, Variants, Generics.Collections, {$IFDEF USEFDMEMTABLE} FireDAC.Comp.Client, {$IFDEF DRIVERRESTFUL}ormbr.restdataset.fdmemtable{$ELSE}ormbr.dataset.fdmemtable{$ENDIF}, {$ENDIF} {$IFDEF USECLIENTDATASET} DBClient, {$IFDEF DRIVERRESTFUL}ormbr.restdataset.clientdataset{$ELSE}ormbr.dataset.clientdataset{$ENDIF}, {$ENDIF} // ORMBr Interface {$IFDEF DRIVERRESTFUL} ormbr.client.interfaces {$ELSE} dbebr.factory.interfaces {$ENDIF}, ormbr.dataset.base.adapter; type IMDConnection = {$IFDEF DRIVERRESTFUL}IRESTConnection{$ELSE}IDBConnection{$ENDIF}; TManagerDataSet = class private FConnection: IMDConnection; FRepository: TDictionary<string, TObject>; FNestedList: TDictionary<string, TObjectList<TObject>>; FOwnerNestedList: Boolean; function Resolver<T: class, constructor>: TDataSetBaseAdapter<T>; procedure ResolverDataSetType(const ADataSet: TDataSet); public constructor Create(const AConnection: IMDConnection); destructor Destroy; override; {$IFNDEF DRIVERRESTFUL} procedure NextPacket<T: class, constructor>; function GetAutoNextPacket<T: class, constructor>: Boolean; procedure SetAutoNextPacket<T: class, constructor>(const AValue: Boolean); {$ENDIF} procedure RemoveAdapter<T: class>; function AddAdapter<T: class, constructor>(const ADataSet: TDataSet; const APageSize: Integer = -1): TManagerDataSet; overload; function AddAdapter<T, M: class, constructor>(const ADataSet: TDataSet): TManagerDataSet; overload; function AddLookupField<T, M: class, constructor>(const AFieldName: string; const AKeyFields: string; const ALookupKeyFields: string; const ALookupResultField: string; const ADisplayLabel: string = ''): TManagerDataSet; procedure Open<T: class, constructor>; overload; procedure Open<T: class, constructor>(const AID: Integer); overload; procedure Open<T: class, constructor>(const AID: String); overload; procedure OpenWhere<T: class, constructor>(const AWhere: string; const AOrderBy: string = ''); procedure Close<T: class, constructor>; procedure LoadLazy<T: class, constructor>(const AOwner: T); procedure RefreshRecord<T: class, constructor>; procedure EmptyDataSet<T: class, constructor>; procedure CancelUpdates<T: class, constructor>; procedure ApplyUpdates<T: class, constructor>(const MaxErros: Integer); procedure Save<T: class, constructor>(AObject: T); function Current<T: class, constructor>: T; function DataSet<T: class, constructor>: TDataSet; // ObjectSet function Find<T: class, constructor>: TObjectList<T>; overload; function Find<T: class, constructor>(const AID: Variant): T; overload; function FindWhere<T: class, constructor>(const AWhere: string; const AOrderBy: string = ''): TObjectList<T>; function NestedList<T: class>: TObjectList<T>; function AutoNextPacket<T: class, constructor>(const AValue: Boolean): TManagerDataSet; property OwnerNestedList: Boolean read FOwnerNestedList write FOwnerNestedList; end; implementation { TManagerDataSet } constructor TManagerDataSet.Create(const AConnection: IMDConnection); begin FConnection := AConnection; FRepository := TObjectDictionary<string, TObject>.Create([doOwnsValues]); FNestedList := TObjectDictionary<string, TObjectList<TObject>>.Create([doOwnsValues]); FOwnerNestedList := False; end; destructor TManagerDataSet.Destroy; begin FNestedList.Free; FRepository.Free; inherited; end; function TManagerDataSet.Current<T>: T; begin Result := Resolver<T>.Current; end; function TManagerDataSet.NestedList<T>: TObjectList<T>; var LClassName: String; begin Result := nil; LClassName := TClass(T).ClassName; if FNestedList.ContainsKey(LClassName) then Result := TObjectList<T>(FNestedList.Items[LClassName]); end; function TManagerDataSet.DataSet<T>: TDataSet; begin Result := Resolver<T>.FOrmDataSet; end; procedure TManagerDataSet.EmptyDataSet<T>; begin Resolver<T>.EmptyDataSet; end; function TManagerDataSet.Find<T>(const AID: Variant): T; begin if TVarData(AID).VType = varInteger then Result := Resolver<T>.Find(Integer(AID)) else if TVarData(AID).VType = varString then Result := Resolver<T>.Find(VarToStr(AID)) end; function TManagerDataSet.Find<T>: TObjectList<T>; var LObjectList: TObjectList<T>; begin Result := nil; if not FOwnerNestedList then begin Result := Resolver<T>.Find; Exit; end; LObjectList := Resolver<T>.Find; // Limpa a lista de objectos FNestedList.AddOrSetValue(TClass(T).ClassName, TObjectList<TObject>(LObjectList)); end; procedure TManagerDataSet.CancelUpdates<T>; begin Resolver<T>.CancelUpdates; end; procedure TManagerDataSet.Close<T>; begin Resolver<T>.EmptyDataSet; end; procedure TManagerDataSet.LoadLazy<T>(const AOwner: T); begin Resolver<T>.LoadLazy(AOwner); end; function TManagerDataSet.AddAdapter<T, M>(const ADataSet: TDataSet): TManagerDataSet; var LDataSetAdapter: TDataSetBaseAdapter<T>; LMaster: TDataSetBaseAdapter<T>; LClassName: String; LMasterName: String; begin Result := Self; LClassName := TClass(T).ClassName; LMasterName := TClass(M).ClassName; if FRepository.ContainsKey(LClassName) then Exit; if not FRepository.ContainsKey(LMasterName) then Exit; LMaster := TDataSetBaseAdapter<T>(FRepository.Items[LMasterName]); if LMaster = nil then Exit; // Checagem do tipo do dataset definido para uso ResolverDataSetType(ADataSet); {$IFDEF DRIVERRESTFUL} {$IFDEF USEFDMEMTABLE} LDataSetAdapter := TRESTFDMemTableAdapter<T>.Create(FConnection, ADataSet, -1, LMaster); {$ELSE} LDataSetAdapter := TRESTClientDataSetAdapter<T>.Create(FConnection, ADataSet, -1, LMaster); {$ENDIF} {$ELSE} {$IFDEF USEFDMEMTABLE} LDataSetAdapter := TFDMemTableAdapter<T>.Create(FConnection, ADataSet, -1, LMaster); {$ELSE} LDataSetAdapter := TClientDataSetAdapter<T>.Create(FConnection, ADataSet, -1, LMaster); {$ENDIF} {$ENDIF} // Adiciona o container ao repositório FRepository.Add(LClassName, LDataSetAdapter); end; function TManagerDataSet.AddAdapter<T>(const ADataSet: TDataSet; const APageSize: Integer): TManagerDataSet; var LDataSetAdapter: TDataSetBaseAdapter<T>; LClassName: String; begin Result := Self; LClassName := TClass(T).ClassName; if FRepository.ContainsKey(LClassName) then Exit; // Checagem do tipo do dataset definido para uso ResolverDataSetType(ADataSet); {$IFDEF DRIVERRESTFUL} {$IFDEF USEFDMEMTABLE} LDataSetAdapter := TRESTFDMemTableAdapter<T>.Create(FConnection, ADataSet, APageSize, nil); {$ELSE} LDataSetAdapter := TRESTClientDataSetAdapter<T>.Create(FConnection, ADataSet, APageSize, nil); {$ENDIF} {$ELSE} {$IFDEF USEFDMEMTABLE} LDataSetAdapter := TFDMemTableAdapter<T>.Create(FConnection, ADataSet, APageSize, nil); {$ELSE} LDataSetAdapter := TClientDataSetAdapter<T>.Create(FConnection, ADataSet, APageSize, nil); {$ENDIF} {$ENDIF} // Adiciona o container ao repositório FRepository.Add(LClassName, LDataSetAdapter); end; function TManagerDataSet.AddLookupField<T, M>(const AFieldName, AKeyFields: string; const ALookupKeyFields, ALookupResultField, ADisplayLabel: string): TManagerDataSet; var LObject: TDataSetBaseAdapter<M>; begin Result := Self; LObject := Resolver<M>; if LObject = nil then Exit; Resolver<T>.AddLookupField(AFieldName, AKeyFields, LObject, ALookupKeyFields, ALookupResultField, ADisplayLabel); end; procedure TManagerDataSet.ApplyUpdates<T>(const MaxErros: Integer); begin Resolver<T>.ApplyUpdates(MaxErros); end; function TManagerDataSet.AutoNextPacket<T>(const AValue: Boolean): TManagerDataSet; begin Resolver<T>.AutoNextPacket := AValue; end; procedure TManagerDataSet.Open<T>(const AID: String); begin Resolver<T>.OpenIDInternal(AID); end; procedure TManagerDataSet.OpenWhere<T>(const AWhere, AOrderBy: string); begin Resolver<T>.OpenWhereInternal(AWhere, AOrderBy); end; procedure TManagerDataSet.Open<T>(const AID: Integer); begin Resolver<T>.OpenIDInternal(AID); end; procedure TManagerDataSet.Open<T>; begin Resolver<T>.OpenSQLInternal(''); end; procedure TManagerDataSet.RefreshRecord<T>; begin Resolver<T>.RefreshRecord; end; procedure TManagerDataSet.RemoveAdapter<T>; var LClassName: String; begin LClassName := TClass(T).ClassName; if not FRepository.ContainsKey(LClassName) then Exit; FRepository.Remove(LClassName); FRepository.TrimExcess; end; function TManagerDataSet.Resolver<T>: TDataSetBaseAdapter<T>; var LClassName: String; begin Result := nil; LClassName := TClass(T).ClassName; if FRepository.ContainsKey(LClassName) then Result := TDataSetBaseAdapter<T>(FRepository.Items[LClassName]); end; procedure TManagerDataSet.ResolverDataSetType(const ADataSet: TDataSet); begin {$IFDEF USEFDMEMTABLE} if not (ADataSet is TFDMemTable) then raise Exception.Create('Is not TFDMemTable type'); {$ENDIF} {$IFDEF USECLIENTDATASET} if not (ADataSet is TClientDataSet) then raise Exception.Create('Is not TClientDataSet type'); {$ENDIF} {$IFNDEF USEMEMDATASET} raise Exception.Create('Enable the directive "USEFDMEMTABLE" or "USECLIENTDATASET" in file ormbr.inc'); {$ENDIF} end; procedure TManagerDataSet.Save<T>(AObject: T); begin Resolver<T>.Save(AObject); end; function TManagerDataSet.FindWhere<T>(const AWhere, AOrderBy: string): TObjectList<T>; var LObjectList: TObjectList<T>; begin Result := nil; if not FOwnerNestedList then begin Result := Resolver<T>.FindWhere(AWhere, AOrderBy); Exit; end; LObjectList := Resolver<T>.FindWhere(AWhere, AOrderBy); // Limpa a lista de objectos FNestedList.AddOrSetValue(TClass(T).ClassName, TObjectList<TObject>(LObjectList)); end; {$IFNDEF DRIVERRESTFUL} procedure TManagerDataSet.NextPacket<T>; begin Resolver<T>.NextPacket; end; function TManagerDataSet.GetAutoNextPacket<T>: Boolean; begin Result := Resolver<T>.AutoNextPacket; end; procedure TManagerDataSet.SetAutoNextPacket<T>(const AValue: Boolean); begin Resolver<T>.AutoNextPacket := AValue; end; {$ENDIF} end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CTE_INFORMACAO_NF_OUTROS] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CteInformacaoNfOutrosVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('CTE_INFORMACAO_NF_OUTROS')] TCteInformacaoNfOutrosVO = class(TVO) private FID: Integer; FID_CTE_CABECALHO: Integer; FNUMERO_ROMANEIO: String; FNUMERO_PEDIDO: String; FCHAVE_ACESSO_NFE: String; FCODIGO_MODELO: String; FSERIE: String; FNUMERO: String; FDATA_EMISSAO: TDateTime; FUF_EMITENTE: Integer; FBASE_CALCULO_ICMS: Extended; FVALOR_ICMS: Extended; FBASE_CALCULO_ICMS_ST: Extended; FVALOR_ICMS_ST: Extended; FVALOR_TOTAL_PRODUTOS: Extended; FVALOR_TOTAL: Extended; FCFOP_PREDOMINANTE: Integer; FPESO_TOTAL_KG: Extended; FPIN_SUFRAMA: Integer; FDATA_PREVISTA_ENTREGA: TDateTime; FOUTRO_TIPO_DOC_ORIG: String; FOUTRO_DESCRICAO: String; FOUTRO_VALOR_DOCUMENTO: Extended; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CTE_CABECALHO', 'Id Cte Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCteCabecalho: Integer read FID_CTE_CABECALHO write FID_CTE_CABECALHO; [TColumn('NUMERO_ROMANEIO', 'Numero Romaneio', 160, [ldGrid, ldLookup, ldCombobox], False)] property NumeroRomaneio: String read FNUMERO_ROMANEIO write FNUMERO_ROMANEIO; [TColumn('NUMERO_PEDIDO', 'Numero Pedido', 160, [ldGrid, ldLookup, ldCombobox], False)] property NumeroPedido: String read FNUMERO_PEDIDO write FNUMERO_PEDIDO; [TColumn('CHAVE_ACESSO_NFE', 'Chave Acesso Nfe', 352, [ldGrid, ldLookup, ldCombobox], False)] property ChaveAcessoNfe: String read FCHAVE_ACESSO_NFE write FCHAVE_ACESSO_NFE; [TColumn('CODIGO_MODELO', 'Codigo Modelo', 16, [ldGrid, ldLookup, ldCombobox], False)] property CodigoModelo: String read FCODIGO_MODELO write FCODIGO_MODELO; [TColumn('SERIE', 'Serie', 24, [ldGrid, ldLookup, ldCombobox], False)] property Serie: String read FSERIE write FSERIE; [TColumn('NUMERO', 'Numero', 160, [ldGrid, ldLookup, ldCombobox], False)] property Numero: String read FNUMERO write FNUMERO; [TColumn('DATA_EMISSAO', 'Data Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO; [TColumn('UF_EMITENTE', 'Uf Emitente', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property UfEmitente: Integer read FUF_EMITENTE write FUF_EMITENTE; [TColumn('BASE_CALCULO_ICMS', 'Base Calculo Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS; [TColumn('VALOR_ICMS', 'Valor Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS; [TColumn('BASE_CALCULO_ICMS_ST', 'Base Calculo Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST; [TColumn('VALOR_ICMS_ST', 'Valor Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST; [TColumn('VALOR_TOTAL_PRODUTOS', 'Valor Total Produtos', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS; [TColumn('VALOR_TOTAL', 'Valor Total', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; [TColumn('CFOP_PREDOMINANTE', 'Cfop Predominante', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CfopPredominante: Integer read FCFOP_PREDOMINANTE write FCFOP_PREDOMINANTE; [TColumn('PESO_TOTAL_KG', 'Peso Total Kg', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property PesoTotalKg: Extended read FPESO_TOTAL_KG write FPESO_TOTAL_KG; [TColumn('PIN_SUFRAMA', 'Pin Suframa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property PinSuframa: Integer read FPIN_SUFRAMA write FPIN_SUFRAMA; [TColumn('DATA_PREVISTA_ENTREGA', 'Data Prevista Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA; [TColumn('OUTRO_TIPO_DOC_ORIG', 'Outro Tipo Doc Orig', 16, [ldGrid, ldLookup, ldCombobox], False)] property OutroTipoDocOrig: String read FOUTRO_TIPO_DOC_ORIG write FOUTRO_TIPO_DOC_ORIG; [TColumn('OUTRO_DESCRICAO', 'Outro Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)] property OutroDescricao: String read FOUTRO_DESCRICAO write FOUTRO_DESCRICAO; [TColumn('OUTRO_VALOR_DOCUMENTO', 'Outro Valor Documento', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property OutroValorDocumento: Extended read FOUTRO_VALOR_DOCUMENTO write FOUTRO_VALOR_DOCUMENTO; //Transientes end; implementation initialization Classes.RegisterClass(TCteInformacaoNfOutrosVO); finalization Classes.UnRegisterClass(TCteInformacaoNfOutrosVO); end.
unit Dao.Atributo; interface type Tabela = class(TCustomAttribute) strict private FNome: string; public property Nome: string read FNome write FNome; constructor Create(const ANome: string); end; Campo = class(TCustomAttribute) strict private FNome: string; FChavePrimaria: Boolean; public property Nome: string read FNome write FNome; property ChavePrimaria: Boolean read FChavePrimaria write FChavePrimaria; constructor Create(ANome: string; AChavePrimaria: Boolean = False); end; implementation constructor Tabela.Create(const ANome: string); begin FNome := ANome; end; constructor Campo.Create(ANome: string; AChavePrimaria: Boolean = False); begin FNome := ANome; FChavePrimaria := AChavePrimaria; end; end.
unit Kernel; interface uses Random, Array2D, ArrayInline2D, Stopwatch, MonteCarlo, SOR, SparseCompRow, FFT, LU; {$IFDEF WIN64} {$DEFINE DOINLINE} {$ENDIF} {$IFDEF DOINLINE} {$DEFINE INLINE} {$ENDIF} function kernel_measureFFT(N: integer; min_time: double; R: PRandom): double; function kernel_measureSOR(N: integer; min_time: double; R: PRandom): double; {$IFDEF INLINE} inline; {$ENDIF} function kernel_measureMonteCarlo(min_time: double; R: PRandom): double; function kernel_measureSparseMatMult(N: integer; nz: integer; min_time: double; R: PRandom): double; {$IFDEF INLINE} inline; {$ENDIF} function kernel_measureLU(N: integer; min_time: double; R: PRandom): double; implementation function kernel_measureFFT(N: integer; min_time: double; R: PRandom): double; var twoN: integer; x: PDoubleArray; cycles: integer; Q: PStopWatch; i: integer; begin { initialize FFT data as complex (N real/img pairs) } twoN := 2*N; x := RandomVector(twoN, R); cycles := 1; Q := new_Stopwatch(); while(true) do begin Stopwatch_start(Q); for i:=0 to cycles-1 do begin FFT_transform(twoN, x); { forward transform } FFT_inverse(twoN, x); { backward transform } end; Stopwatch_stop(Q); if (Stopwatch_read(Q) >= min_time) then break; cycles := cycles*2; end; { approx Mflops } result := FFT_num_flops(N)*cycles/ Stopwatch_read(Q) * 1.0e-6; Stopwatch_delete(Q); FreeMem(x); end; function kernel_measureSparseMatMult(N: integer; nz: integer; min_time: double; R: PRandom): double; {$IFDEF INLINE} inline; {$ENDIF} Var x, y, val: PDoubleArrayInline; col, row: PIntegerArrayInline; nr, anz, _r, cycles, rowr, step, i: integer; Q: PStopwatch; Begin { initialize vector multipliers and storage for result } { y = A*y; } x := RandomVectorInline(N, R); GetMem(y, sizeof(double)*N); // initialize square sparse matrix // // for this test, we create a sparse matrix with M/nz nonzeros // per row, with spaced-out evenly between the begining of the // row to the main diagonal. Thus, the resulting pattern looks // like // +-----------------+ // +* + // +*** + // +* * * + // +** * * + // +** * * + // +* * * * + // +* * * * + // +* * * * + // +-----------------+ // // (as best reproducible with integer artihmetic) // Note that the first nr rows will have elements past // the diagonal. nr := nz div N; { average number of nonzeros per row } anz := nr *N; { _actual_ number of nonzeros } val := RandomVectorInline(anz, R); GetMem(col, sizeof(integer)*nz); GetMem(row, sizeof(integer)*(N+1)); cycles:=1; Q := new_Stopwatch(); row[0] := 0; for _r:=0 to N-1 do Begin { initialize elements for row r } rowr := row[_r]; step := _r div nr; row[_r+1] := rowr + nr; if (step < 1) then step := 1; { take at least unit steps } for i:=0 to nr-1 do col[rowr+i] := i*step; end; while(true) do Begin Stopwatch_start(Q); SparseCompRow_matmult(N, y, val, row, col, x, cycles); Stopwatch_stop(Q); if (Stopwatch_read(Q) >= min_time) then break; cycles := cycles*2; end; { approx Mflops } result := SparseCompRow_num_flops(N, nz, cycles) / Stopwatch_read(Q) * 1.0e-6; Stopwatch_delete(Q); FreeMem(row); FreeMem(col); FreeMem(val); FreeMem(y); FreeMem(x); end; function kernel_measureSOR(N: integer; min_time: double; R: PRandom): double; {$IFDEF INLINE} inline; {$ENDIF} var cycles: integer; Q: PStopwatch; G: PArrayofDoubleArrayInline; begin G := RandomMatrixInline(N, N, R); Q := new_Stopwatch(); cycles :=1; while(true) do begin Stopwatch_start(Q); SOR_execute(N, N, 1.25, G, cycles); Stopwatch_stop(Q); if (Stopwatch_read(Q) >= min_time) then break; cycles := cycles*2; end; { approx Mflops } result := SOR_num_flops(N, N, cycles) / Stopwatch_read(Q) * 1.0e-6; Stopwatch_delete(Q); Array2D_double_delete_Inline(N, N, G); end; function kernel_measureMonteCarlo(min_time: double; R: PRandom): double; var Q: PStopWatch; cycles: integer; begin Q := new_Stopwatch(); cycles:=1; while true do begin Stopwatch_start(Q); MonteCarlo_integrate(cycles); Stopwatch_stop(Q); if (Stopwatch_read(Q) >= min_time) then break; cycles := cycles*2; end; { approx Mflops } result := MonteCarlo_num_flops(cycles) / Stopwatch_read(Q) * 1.0e-6; Stopwatch_delete(Q); end; function kernel_measureLU(N: integer; min_time: double; R: PRandom): double; Var i, cycles: Integer; Q: PStopwatch; A, lu: PArrayofDoubleArray; pivot: PIntegerArray; begin Q := new_Stopwatch(); cycles:=1; A := RandomMatrix(N, N, R); if (A = nil) then exit(1); lu := new_Array2D_double(N, N); if (lu = nil) then exit(1); GetMem(pivot, N * sizeof(integer)); if (pivot = nil) then exit(1); while true do begin Stopwatch_start(Q); for i:=0 to cycles-1 do begin Array2D_double_copy(N, N, lu, A); LU_factor(N, N, lu, pivot); end; Stopwatch_stop(Q); if (Stopwatch_read(Q) >= min_time) then break; cycles := cycles*2; end; { approx Mflops } result := LU_num_flops(N) * cycles / Stopwatch_read(Q) * 1.0e-6; Stopwatch_delete(Q); FreeMem(pivot); Array2D_double_delete(N, N, lu); Array2D_double_delete(N, N, A); end; end.
unit FrmPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ImgList, Vcl.Menus, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Data.Win.ADODB; type TFormPrincipal = class(TForm) MainMenu1: TMainMenu; Cadastros1: TMenuItem; Pacientes1: TMenuItem; Imagens: TImageList; ToolBar1: TToolBar; btnProdutos: TToolButton; btnAjuda: TToolButton; btnSobre: TToolButton; btnSair: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; pnlPrincipal: TPanel; DBGrid1: TDBGrid; Panel1: TPanel; btnIncluirProduto: TBitBtn; btnAlterarProduto: TBitBtn; btnExcluirProduto: TBitBtn; conexao: TADOConnection; dsProdutos: TDataSource; qrProdutos: TADOQuery; procedure btnSairClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btnProdutosClick(Sender: TObject); procedure dsProdutosDataChange(Sender: TObject; Field: TField); procedure btnExcluirProdutoClick(Sender: TObject); procedure btnAlterarProdutoClick(Sender: TObject); procedure btnIncluirProdutoClick(Sender: TObject); private procedure CriarArquivoINI; function GetDiretorioAplicacao: String; public { Public declarations } end; var FormPrincipal: TFormPrincipal; implementation {$R *.dfm} uses System.IniFiles, Produto, FrmProduto; procedure TFormPrincipal.btnAlterarProdutoClick(Sender: TObject); var produto : TProduto; begin produto := TProduto.Create; produto.SetCodigo( dsProdutos.DataSet.FieldByName( 'codigo' ).AsString ); produto.SetDescricao( dsProdutos.DataSet.FieldByName( 'descricao' ).AsString ); produto.SetFornecedor( dsProdutos.DataSet.FieldByName( 'fornecedor' ).AsString ); if CriarProduto( produto ) then btnProdutosClick( nil ); FreeAndNil( produto ); end; procedure TFormPrincipal.btnExcluirProdutoClick(Sender: TObject); var produto : TProduto; begin if Application.MessageBox( 'Deseja realmente excluir o produto?', 'Confirmação', MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = ID_YES then begin produto := TProduto.Create; produto.SetCodigo( dsProdutos.DataSet.FieldByName( 'codigo' ).AsString ); if produto.Excluir then begin Application.MessageBox( 'Produto excluído com sucesso!', 'Informação', MB_ICONINFORMATION ); btnProdutosClick( Nil ); end else Application.MessageBox( 'Ocorreu um erro ao excluir o produto!', 'Erro', MB_ICONERROR ); FreeAndNil( produto ); end; end; procedure TFormPrincipal.btnIncluirProdutoClick(Sender: TObject); var produto : TProduto; begin produto := TProduto.Create; if CriarProduto( produto, True ) then btnProdutosClick( nil ); FreeAndNil( produto ); end; procedure TFormPrincipal.btnProdutosClick(Sender: TObject); begin if qrProdutos.Active then qrProdutos.Close; qrProdutos.SQL.Text := 'select * from produtos order by codigo'; qrProdutos.Open; end; procedure TFormPrincipal.btnSairClick(Sender: TObject); begin Close; end; procedure TFormPrincipal.FormClose(Sender: TObject; var Action: TCloseAction); begin // Verificando se o usuário deseja realmente finalizar a aplicação. if Application.MessageBox( 'Deseja realmente sair do sistema?', 'Confirmação', MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2) = ID_YES then Action := caFree else Action:= caNone; end; procedure TFormPrincipal.FormCreate(Sender: TObject); var arquivo : TIniFile; instancia : String; usuario : String; senha : String; strConn : String; begin // Criando o arquivo de configuração do sistema, se não existir. CriarArquivoINI; try // Lendo o conteúdo do arquivo de configuração. arquivo := TIniFile.Create( GetDiretorioAplicacao + 'config.ini' ); instancia := arquivo.ReadString( 'CONEXAO' , 'instancia' , EmptyStr ); usuario := arquivo.ReadString( 'CONEXAO' , 'usuario' , EmptyStr ); senha := arquivo.ReadString( 'CONEXAO' , 'senha' , EmptyStr ); strConn := arquivo.ReadString( 'CONEXAO' , 'strConn' , EmptyStr ); FreeAndNil( arquivo ); except on e : Exception do begin Application.MessageBox( PWideChar( 'Erro ao ler o arquivo de configuração: ' + e.Message ), 'Erro', MB_ICONERROR ); Application.Terminate; end; end; // Conectando a aplicação com o banco de dados. try with conexao do begin ConnectionString := Format( strConn, [ senha, usuario, instancia ] ); LoginPrompt := False; Connected := True; end; except on e : Exception do begin Application.MessageBox( PWideChar( 'Erro ao conectar com o banco de dados: ' + e.Message ), 'Erro', MB_ICONERROR ); Application.Terminate; end; end; end; procedure TFormPrincipal.CriarArquivoINI; var arquivo : TIniFile; begin try if ( not FileExists( GetDiretorioAplicacao + 'config.ini' ) ) then begin arquivo := TIniFile.Create( GetDiretorioAplicacao + 'config.ini' ); // Parâmetros da tela de configurações. arquivo.WriteString( 'CONEXAO' , 'instancia' , 'rhdev' ); arquivo.WriteString( 'CONEXAO' , 'usuario' , 'caerd_david' ); arquivo.WriteString( 'CONEXAO' , 'senha' , 'caerd_david' ); arquivo.WriteString( 'CONEXAO' , 'strConn' , 'Provider=OraOLEDB.Oracle.1;' + 'Password=%s;' + 'Persist Security Info=True;' + 'User ID=%s;' + 'Data Source=%s' ); FreeAndNil( arquivo ); end; except on e : Exception do begin raise Exception.Create( 'Erro durante a criação do arquivo de configurações: ' + e.message ); Abort; end; end; end; procedure TFormPrincipal.dsProdutosDataChange(Sender: TObject; Field: TField); begin btnIncluirProduto.Enabled := ( dsProdutos.DataSet.RecordCount > 0 ); btnAlterarProduto.Enabled := ( dsProdutos.DataSet.RecordCount > 0 ); btnExcluirProduto.Enabled := ( dsProdutos.DataSet.RecordCount > 0 ); end; function TFormPrincipal.GetDiretorioAplicacao : String; begin Result := ExtractFilePath( Application.ExeName ); end; end.
unit uView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, CheckLst; type TfrmView = class(TfrmBase) cbView: TCheckListBox; cbSelAll: TCheckBox; procedure cbSelAllClick(Sender: TObject); procedure cbViewClickCheck(Sender: TObject); procedure btnOkClick(Sender: TObject); private { Private declarations } FOriStr: string; function GetCheckStr: string; protected //数据操作过程... procedure InitData; override; procedure SaveData; override; public { Public declarations } end; var frmView: TfrmView; function ShowView(): Boolean; implementation uses uGlobal; {$R *.dfm} function ShowView(): Boolean; begin with TfrmView.Create(Application.MainForm) do begin imgHelp.Visible := False; try InitData(); Result := ShowModal() = mrOk; if Result then Log.Write(App.UserID + '对类别显示做过改动'); finally Free; end; end; end; function TfrmView.GetCheckStr: string; var i: Integer; begin Result := ''; for i := 0 to cbView.Items.Count - 1 do if cbView.Checked[i] then Result := Result + '1' else Result := Result + '0'; end; procedure TfrmView.InitData; begin cbView.Items.Clear; with cbView.Items, App.ViewSet do begin Append(DeptStr); Append(DutyStr); Append(TypeStr); Append(TechnicStr); Append(SexStr); Append(FolkStr); Append(MarriageStr); Append(PolityStr); Append(CultureStr); Append(SpecialStr); end; with cbView, App.ViewSet do begin Checked[0] := ShowDept; Checked[1] := ShowDuty; Checked[2] := ShowType; Checked[3] := ShowTechnic; Checked[4] := ShowSex; Checked[5] := ShowFolk; Checked[6] := ShowMarriage; Checked[7] := ShowPolity; Checked[8] := ShowCulture; Checked[9] := ShowSpecial; end; cbView.OnClickCheck(cbView); FOriStr := GetCheckStr(); end; procedure TfrmView.SaveData; begin with cbView, App.ViewSet do begin ShowDept := Checked[0]; ShowDuty := Checked[1]; ShowType := Checked[2]; ShowTechnic := Checked[3]; ShowSex := Checked[4]; ShowFolk := Checked[5]; ShowMarriage := Checked[6]; ShowPolity := Checked[7]; ShowCulture := Checked[8]; ShowSpecial := Checked[9]; end; Log.Write(App.UserID + '进行类别显示设置操作'); end; procedure TfrmView.cbSelAllClick(Sender: TObject); var i: Integer; begin for i := 0 to cbView.Count - 1 do cbView.Checked[i] := cbSelAll.Checked; end; procedure TfrmView.cbViewClickCheck(Sender: TObject); var i: Integer; AllChecked: Boolean; begin AllChecked := True; for i := 0 to cbView.Count - 1 do if not cbView.Checked[i] then begin AllChecked := False; Break; end; //反判断 if AllChecked and not cbSelAll.Checked then begin cbSelAll.OnClick := nil; cbSelAll.Checked := True; cbSelAll.OnClick := cbSelAllClick; end; if cbSelAll.Checked and not AllChecked then begin cbSelAll.OnClick := nil; cbSelAll.Checked := False; cbSelAll.OnClick := cbSelAllClick; end; end; procedure TfrmView.btnOkClick(Sender: TObject); begin if GetCheckStr() <> FOriStr then inherited else ModalResult := mrCancel; end; end.
unit unConfiguracaoGlobal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, unPadrao, Menus, DB, ActnList, StdCtrls, Buttons, ExtCtrls, ComCtrls, DBClient, Provider, SqlExpr, DBCtrls, Mask, FMTBcd, System.Actions, uniLabel, uniButton, uniBitBtn, uniSpeedButton, uniGUIClasses, uniPanel, uniGUIBaseClasses, uniStatusBar, uniEdit, uniDBEdit, uniCheckBox, uniDBCheckBox, uniMemo, uniDBMemo, uniPageControl; type TfrmConfigGlobal = class(TfrmPadrao) sqldPadrao: TSQLDataSet; dspPadrao: TDataSetProvider; cdsPadrao: TClientDataSet; pgcConfigGlobal: TUniPageControl; tsCrediario: TUniTabSheet; tsCliente: TUniTabSheet; tsOrcamento: TUniTabSheet; tsVenda: TUniTabSheet; tsFTP: TUniTabSheet; sqldPadraoTAXAJURO: TFMTBCDField; sqldPadraoINTERVALO: TIntegerField; sqldPadraoPRAZOINICIAL: TIntegerField; sqldPadraoPARCELAS: TIntegerField; sqldPadraoLIMITECLIENTE: TFMTBCDField; sqldPadraoTITULOORCAM: TStringField; sqldPadraoCOLUNAORCAMBOBINA: TIntegerField; sqldPadraoMSGRODAPEORCAM: TStringField; sqldPadraoTITULOVENDA: TStringField; sqldPadraoCOLUNAVENDABOBINA: TIntegerField; sqldPadraoMSGRODAPEVENDA: TStringField; sqldPadraoLINHAPULARBOBINAVENDA: TIntegerField; sqldPadraoLINHAPULARBOBINAORCAM: TIntegerField; sqldPadraoPORTAIMPVENDA: TStringField; sqldPadraoFTP_HOST: TStringField; sqldPadraoFTP_USER_NAME: TStringField; sqldPadraoFTP_PASSWORD: TStringField; sqldPadraoFTP_TIMEOUT: TIntegerField; sqldPadraoFTP_PASSIVE: TStringField; sqldPadraoFTP_DIR: TStringField; sqldPadraoIDADECADASTROCLIENTE: TIntegerField; sqldPadraoIDCONFIGGLOBAL: TIntegerField; cdsPadraoTAXAJURO: TFMTBCDField; cdsPadraoINTERVALO: TIntegerField; cdsPadraoPRAZOINICIAL: TIntegerField; cdsPadraoPARCELAS: TIntegerField; cdsPadraoLIMITECLIENTE: TFMTBCDField; cdsPadraoTITULOORCAM: TStringField; cdsPadraoCOLUNAORCAMBOBINA: TIntegerField; cdsPadraoMSGRODAPEORCAM: TStringField; cdsPadraoTITULOVENDA: TStringField; cdsPadraoCOLUNAVENDABOBINA: TIntegerField; cdsPadraoMSGRODAPEVENDA: TStringField; cdsPadraoLINHAPULARBOBINAVENDA: TIntegerField; cdsPadraoLINHAPULARBOBINAORCAM: TIntegerField; cdsPadraoPORTAIMPVENDA: TStringField; cdsPadraoFTP_HOST: TStringField; cdsPadraoFTP_USER_NAME: TStringField; cdsPadraoFTP_PASSWORD: TStringField; cdsPadraoFTP_TIMEOUT: TIntegerField; cdsPadraoFTP_PASSIVE: TStringField; cdsPadraoFTP_DIR: TStringField; cdsPadraoIDADECADASTROCLIENTE: TIntegerField; cdsPadraoIDCONFIGGLOBAL: TIntegerField; lbMsgOrcamRodape: TUniLabel; lbMsgRodapeVenda: TUniLabel; dbeJuro: TUniDBEdit; dbeIntervalo: TUniDBEdit; dbePrazoInicial: TUniDBEdit; dbeParcelas: TUniDBEdit; dbeLimiteCliente: TUniDBEdit; dbeIdadeCliente: TUniDBEdit; dbeTituloOrcam: TUniDBEdit; dbeColunaBobina: TUniDBEdit; dbeLinhaPularOrcam: TUniDBEdit; dbeTituloVenda: TUniDBEdit; dbeColunaBobinaVenda: TUniDBEdit; dbeLinhaPularVenda: TUniDBEdit; dbePortaImpVenda: TUniDBEdit; dbeHost: TUniDBEdit; dbeUserName: TUniDBEdit; dbePassWord: TUniDBEdit; dbeDiretorio: TUniDBEdit; dbeTimeOut: TUniDBEdit; dbckbPassive: TUniDBCheckBox; dbmmMsgRodape: TUniDBMemo; dbmmMsgRodapeVenda: TUniDBMemo; procedure FormCreate(Sender: TObject); procedure cdsPadraoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure dbeJuroKeyPress(Sender: TObject; var Key: Char); procedure cdsPadraoCOLUNAORCAMBOBINAChange(Sender: TField); procedure cdsPadraoCOLUNAVENDABOBINAChange(Sender: TField); private public end; var frmConfigGlobal: TfrmConfigGlobal; implementation uses Funcoes, ConstPadrao; {$R *.dfm} procedure TfrmConfigGlobal.FormCreate(Sender: TObject); begin inherited; actInsert.Visible := False; actPrint.Visible := False; actDelete.Visible := False; actSearch.Visible := False; // actPrimeiro.Visible := False; // actAnterior.Visible := False; // actProximo.Visible := False; // actUltimo.Visible := False; // miRelatorios.Visible := False; // miOpcoes.Visible := False; ReordenaBotoes([btnAlterar, btnSalvar, btnCancelar, btnSair]); pgcConfigGlobal.ActivePageIndex := 0; end; procedure TfrmConfigGlobal.cdsPadraoAfterApplyUpdates( Sender: TObject; var OwnerData: OleVariant); begin inherited; PostMessageAllForms(WM_CONFIG_GLOBAL_ALTERADO); end; procedure TfrmConfigGlobal.dbeJuroKeyPress(Sender: TObject; var Key: Char); begin inherited; if not (Key in ['0'..'9', ',', #8]) then Key := #0; end; procedure TfrmConfigGlobal.cdsPadraoCOLUNAORCAMBOBINAChange( Sender: TField); begin inherited; if Sender.AsInteger > 40 then begin MsgAviso('O número de colunas não deve ser maior que 40.'); Sender.AsInteger := 40; end; end; procedure TfrmConfigGlobal.cdsPadraoCOLUNAVENDABOBINAChange( Sender: TField); begin inherited; if Sender.AsInteger > 40 then begin MsgAviso('O número de colunas não deve ser maior que 40.'); Sender.AsInteger := 40; end; end; initialization RegisterClass(TfrmConfigGlobal); finalization UnRegisterClass(TfrmConfigGlobal); end.
unit UTDMSLeadInfo; interface uses System.Classes,System.SysUtils; type LeadInfo = class private startName:array [0..4] of AnsiChar; toc:Integer; versionInfo:Integer; nextSeg:LongInt; metaDataSize:LongInt; public constructor Create(buffer:TFileStream); procedure type_Info(); function hasMetaData():Boolean; function hasRawData():Boolean; function isDAQmxRawData():Boolean; function hasIterleavedData():Boolean; function isToBigEndian():Boolean; function isTocNewObjlist():Boolean; function getFileze():LongInt; function getRawSize():LongInt; end; implementation { LeadInfo } constructor LeadInfo.Create(buffer:TFileStream); var bytes:array [0..4] of Byte; byt:array [0..8] of Byte; begin inherited create; startName:=' '; buffer.Read(startName[0],4); buffer.Read(bytes,4); toc := Pinteger(@bytes)^; buffer.Read(bytes,4); versionInfo := Pinteger(@bytes)^; buffer.Read(byt,8); nextSeg := Pint64(@byt)^; buffer.Read(byt,8); metaDataSize := Pint64(@byt)^; end; function LeadInfo.getFileze: LongInt; begin result := Self.metaDataSize; end; function LeadInfo.getRawSize: LongInt; begin result:= self.nextSeg-self.metaDataSize; end; function LeadInfo.hasIterleavedData: Boolean; begin Result:= ((toc and (1 shl 5)) <> 0); end; function LeadInfo.hasMetaData: Boolean; begin Result:= ((toc and (1 shl 1)) <> 0); end; function LeadInfo.hasRawData: Boolean; begin Result:= ((toc and (1 shl 3)) <> 0); end; function LeadInfo.isDAQmxRawData: Boolean; begin Result:= ((toc and (1 shl 7)) <> 0); end; function LeadInfo.isToBigEndian: Boolean; begin Result:= ((toc and (1 shl 6)) <> 0); end; function LeadInfo.isTocNewObjlist: Boolean; begin Result:= ((toc and (1 shl 2)) <> 0); end; procedure LeadInfo.type_Info; begin Writeln('segMent Name: ' + startName ); Writeln('toc Size: ' + IntToStr(toc) ); Writeln('version_Num: ' + IntToStr(versionInfo) ); Writeln('Next seg: ' + IntToStr(nextSeg) ); Writeln('metaSize : ' + IntToStr(metaDataSize) ); end; end.
// ---------------------------------------------------------------------------- // Unit : PxService.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2004-10-27 // Version : 1.0 // Description : Service applications facilities. This should be independent // from the platform (Delphi/Kylix). // // To create a simple or event more advanced service create a new // console application project, create a class that inherits from // TPxService class and override this methods to create the // service functionality: // // OnInitialize - in this method implement all initialization // required by service // OnFinalize - in this method implement all finalization // required by service and cleanup any resources // allocated by service // ReadSettings - in this method read all service-specific settings // Main - in this method implement the main service // functionality. A basic implementation of Main // method would look like this: // // // service's thread main loop // repeat // // give other threads some time to breath // Sleep(1); // until Terminated; // // Depending on the value passed to Sleep the thread // is more time-consuming (smaller value) or less // time-consuming (greater value). // // Changes log ; 2004-10-27 - Initial version (based on an old version of // ServiceConf and TestSvc project). // 2004-12-21 - Fixed bug when setting the service description. // 2005-03-23 - Compatibility with FPC achieved // - JwaWinSvc references removed // 2005-04-17 - Added a possibility to create a service application // that works like standard window-less user-mode app // ToDo : - Testing. // ---------------------------------------------------------------------------- unit PxService; {$I PxDefines.inc} interface uses Windows, ActiveX, Classes, SysUtils, IniFiles, {$IFDEF DELPHI} WinSvc, {$ENDIF} PxLog, PxThread, PxSettings; type TPxService = class (TPxThread) private FClosed: Boolean; FDebugMode: Boolean; {$IFDEF WIN32} FServiceName: String; FServiceDescription: String; {$ENDIF} protected // override this to initialize the service procedure OnInitialize; virtual; // override this to cleanup after the main service loop ends procedure OnFinalize; virtual; // override this to read additional application settings // do not forget to call the inherited method ! procedure ReadSettings(IniFile: TIniFile); virtual; // override this to implement the main service functionality procedure Main; virtual; // do NOT override this - use Main procedure to implement the service functionality procedure Execute; override; public constructor Create; destructor Destroy; override; // call this to initialize procedure Initialize; // call this to start the service procedure Run(AppMode: Boolean = False); property Closed: Boolean read FClosed; property DebugMode: Boolean read FDebugMode write FDebugMode; {$IFDEF WIN32} property ServiceName: String read FServiceName; property ServiceDescription: String read FServiceDescription; {$ENDIF} end; implementation uses {$IFDEF FPC} PxFPC, {$ENDIF} {$IFDEF VER130} Consts; {$ENDIF} {$IFDEF VER150} RtlConsts; {$ENDIF} // // Additional import and constants to set service description // const SERVICE_CONFIG_DESCRIPTION = 1; function ChangeServiceConfig2(hService: SC_HANDLE; dwInfoLevel: DWORD; lpInfo: Pointer): BOOL; external 'advapi32.dll' name 'ChangeServiceConfig2A'; var ServiceStatus : SERVICE_STATUS; ServiceStatusHandle: SERVICE_STATUS_HANDLE; ServiceControlEvent: THandle; Service : TPxService; procedure ServiceControlHandler(ControlCode: DWORD); stdcall; forward; procedure ServiceProc(argc: DWORD; argv: PLPSTR); stdcall; forward; procedure InstallService; forward; procedure UninstallService; forward; procedure RunService; forward; procedure DebugService; forward; procedure ServiceMain(Thread: TPxService); forward; function ConsoleHandler(dwCtrlType: DWORD): BOOL; forward; { TPxService } { Private declarations } { Protected declarations } procedure TPxService.ReadSettings(IniFile: TIniFile); begin {$IFDEF WIN32} FServiceName := IniFile.ReadString('Service', 'Name', ExtractFileName(ParamStr(0))); FServiceDescription := IniFile.ReadString('Service', 'Description', 'Description of ' + ExtractFileName(ParamStr(0))); {$ENDIF} end; procedure TPxService.OnInitialize; begin end; procedure TPxService.OnFinalize; begin end; procedure TPxService.Main; begin end; procedure TPxService.Execute; begin OleInitialize(nil); FClosed := False; Main; FClosed := True; SetEvent(ServiceControlEvent); // OleUninitialize; end; { Public declarations } constructor TPxService.Create; begin inherited Create(True); FreeOnTerminate := False; FClosed := True; OnInitialize; end; destructor TPxService.Destroy; begin OnFinalize; inherited Destroy; end; procedure TPxService.Initialize; var IniFile: TIniFile; begin inherited Create(True); FDebugMode := FindCmdLineSwitch('debug', ['-', '/'], True); IniFile := TIniFile.Create(SettingsFileName); ReadSettings(IniFile); FreeAndNil(IniFile); if (not FDebugMode) and LogToConsole then FDebugMode := True else if FDebugMode and (not LogToConsole) then SwitchLogToConsole; end; procedure TPxService.Run(AppMode: Boolean = False); begin if AppMode then begin Log('Running in application mode'); FDebugMode := True; end; ServiceMain(Self); end; { *** } procedure ServiceControlHandler(ControlCode: DWORD); stdcall; begin Log(LOGLEVEL_DEBUG, 'ServiceControlHandler(ControlCode=%d)', [ControlCode]); case ControlCode of SERVICE_CONTROL_INTERROGATE: begin end; SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_STOP: begin Service.Terminate; SetServiceStatus(ServiceStatusHandle, ServiceStatus); SetEvent(ServiceControlEvent); end; SERVICE_CONTROL_PAUSE: begin Service.Suspend; end; SERVICE_CONTROL_CONTINUE: begin Service.Resume; end; else if (ControlCode > 127) and (ControlCode < 256) then begin // user control codes end end; SetServiceStatus(ServiceStatusHandle, ServiceStatus); end; procedure ServiceProc(argc: DWORD; argv: PLPSTR); stdcall; var Msg: TMsg; OldMainThreadId: THandle; begin Log(LOGLEVEL_DEBUG, 'ServiceProc()'); ServiceStatus.dwServiceType := SERVICE_WIN32; ServiceStatus.dwCurrentState := SERVICE_STOPPED; ServiceStatus.dwControlsAccepted := 0; ServiceStatus.dwWin32ExitCode := NO_ERROR; ServiceStatus.dwServiceSpecificExitCode := NO_ERROR; ServiceStatus.dwCheckPoint := 0; ServiceStatus.dwWaitHint := 0; ServiceStatusHandle := RegisterServiceCtrlHandler(PAnsiChar(Service.ServiceName), @ServiceControlHandler); if ServiceStatusHandle <> 0 then begin // service is starting ServiceStatus.dwCurrentState := SERVICE_START_PENDING; SetServiceStatus(ServiceStatusHandle, ServiceStatus); // Create the Controlling Event here ServiceControlEvent := CreateEvent(nil, False, False, nil); // Service running ServiceStatus.dwControlsAccepted := ServiceStatus.dwControlsAccepted or (SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN); ServiceStatus.dwCurrentState := SERVICE_RUNNING; SetServiceStatus(ServiceStatusHandle, ServiceStatus); // log, that the service is running Log(LOGLEVEL_DEBUG, 'Starting main service thread'); // store MainThreadId and make current thread the main thread OldMainThreadID := MainThreadID; MainThreadID := GetCurrentThreadId; // start service thread here... Service.Resume; Log(LOGLEVEL_DEBUG, 'ServiceThread resumed'); // wait until the service has stopped repeat if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin TranslateMessage(Msg); DispatchMessage(Msg); end; if WaitForSingleObject(ServiceControlEvent, 100) = WAIT_OBJECT_0 then begin Log(LOGLEVEL_DEBUG, 'WaitForSingleObject() = WAIT_OBJECT_0 in ServiceProc'); Break; end; if GetCurrentThreadID = MainThreadID then begin {$IFDEF DELPHI} CheckSynchronize(1); {$ENDIF} {$IFDEF FPC} CheckSynchronize; Sleep(1); {$ENDIF} end else Log(LOGLEVEL_DEBUG, '!!! GetCurrentThreadID <> MainThreadID !!! NO SYNCHRONIZATION PERFORMED !!!'); until False; // restore main thread id MainThreadID := OldMainThreadID; // service was stopped ServiceStatus.dwCurrentState := SERVICE_STOP_PENDING; SetServiceStatus(ServiceStatusHandle, ServiceStatus); // log, that the service has stopped execution Log(LOGLEVEL_DEBUG, 'Service stopped'); // do cleanup here ServiceControlEvent := 0; // service is now stopped ServiceStatus.dwControlsAccepted := ServiceStatus.dwControlsAccepted and (not (SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN)); ServiceStatus.dwCurrentState := SERVICE_STOPPED; SetServiceStatus(ServiceStatusHandle, ServiceStatus); end; end; procedure InstallService; var ServiceControlManager, Service_: SC_HANDLE; Description: PAnsiChar; begin ServiceControlManager := OpenSCManager(nil, nil, SC_MANAGER_CREATE_SERVICE); if ServiceControlManager <> 0 then begin Service_ := CreateService( ServiceControlManager, PChar(Service.ServiceName), PChar(Service.ServiceName), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, PChar(ParamStr(0)), nil, nil, nil, nil, nil); if Service_ <> 0 then begin Description := PAnsiChar(Service.ServiceDescription); ChangeServiceConfig2( Service_, SERVICE_CONFIG_DESCRIPTION, @Description ); CloseServiceHandle(Service_); Log('Service %s installed successfully', [Service.ServiceName]); end else if GetLastError = ERROR_SERVICE_EXISTS then Log('Error: Service %s already exists !', [Service.ServiceName]) else Log('Error while installing service %s. Error Code: %d', [Service.ServiceName, GetLastError]); end; CloseServiceHandle(ServiceControlManager); end; procedure UninstallService; var ServiceControlManager, Service_: SC_HANDLE; ServiceStatus: SERVICE_STATUS; Error: DWORD; begin ServiceControlManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if ServiceControlManager <> 0 then begin Service_ := OpenService(serviceControlManager, PChar(Service.ServiceName), SERVICE_QUERY_STATUS or $00010000); if Service_ <> 0 then begin if QueryServiceStatus(Service_, ServiceStatus) then begin if ServiceStatus.dwCurrentState = SERVICE_STOPPED then begin if DeleteService(Service_) then Log('Service %s removed successfully', [Service.ServiceName]) else begin Error := GetLastError; case Error of ERROR_ACCESS_DENIED: Log('Error: Access denied while trying to remove the service %s', [Service.ServiceName]); ERROR_INVALID_HANDLE: Log('Error: Handle invalid while trying to remove the service %s', [Service.ServiceName]); ERROR_SERVICE_MARKED_FOR_DELETE: Log('Error: Service % already marked for deletion', [Service.ServiceName]); else Log('Error: Unknown error code %d', [Error]); end; end; end else Log('Service %s is still running.', [Service.ServiceName]); end else begin Error := GetLastError; case Error of ERROR_ACCESS_DENIED: Log('Error: Access denied while trying to remove the service %s', [Service.ServiceName]); ERROR_INVALID_HANDLE: Log('Error: Handle invalid while trying to remove the service %s', [Service.ServiceName]); ERROR_SERVICE_MARKED_FOR_DELETE: Log('Error: Service %s already marked for deletion', [Service.ServiceName]); else Log('Error: Unknown error code %s', [Error]); end; end; CloseServiceHandle(Service_); end else Log('Error: Unknown error code %d', [GetLastError]); CloseServiceHandle(ServiceControlManager); end; end; procedure RunService; var ServiceTable: TServiceTableEntry; begin FillChar(ServiceTable, SizeOf(ServiceTable), 0); ServiceTable.lpServiceName := PChar(Service.FServiceName); ServiceTable.lpServiceProc := @ServiceProc; StartServiceCtrlDispatcher(ServiceTable); if GetCurrentThreadID = MainThreadID then Log(LOGLEVEL_DEBUG, 'GetCurrentThreadID = MainThreadID') ; end; procedure DebugService; var Msg: TMsg; begin ServiceControlEvent := CreateEvent(nil, False, False, nil); // bind console controls (to catch ctrl+XXX keyboard macros and exit) SetConsoleCtrlHandler(@ConsoleHandler, True); // start service thread here... Service.Resume; // wait until the service has stopped repeat if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin TranslateMessage(Msg); DispatchMessage(Msg); end; if WaitForSingleObject(ServiceControlEvent, 0) = WAIT_OBJECT_0 then Break; CheckSynchronize(1); until False; // do cleanup here ServiceControlEvent := 0; end; procedure ServiceMain(Thread: TPxService); begin Service := Thread; Log(LOGLEVEL_DEBUG, 'Started with CmdLine=%s', [CmdLine]); if FindCmdLineSwitch('install', ['-', '/'], True) then InstallService else if FindCmdLineSwitch('remove', ['-', '/'], True) then UninstallService else if FindCmdLineSwitch('debug', ['-', '/'], True) or Thread.FDebugMode then DebugService else if FindCmdLineSwitch('start', ['-', '/'], True) then begin Writeln('To start this service type'); Writeln('C:\>net start ', Service.ServiceName); Writeln; Writeln; end else if FindCmdLineSwitch('stop', ['-', '/'], True) then begin Writeln('To stop this service type'); Writeln('C:\>net stop ', Service.ServiceName); Writeln; Writeln; end else if FindCmdLineSwitch('help', ['-', '/'], True) or FindCmdLineSwitch('?', ['-', '/'], True) then begin Log(LOGLEVEL_DEBUG, 'Showing help'); Writeln(ExtractFileName(ParamStr(0)) + ' [-install] [-remove] [-start] [-stop] [-debug]'); Writeln; Writeln(' -install - to install this application as a Win32 service'); Writeln(' -remove - to remve the service installed with -install'); Writeln(' -start - to start the service if installed'); Writeln(' -stop - to stop the service if installed and running'); Writeln(' -debug - to run this application in debug mode'); Writeln; Writeln; end else begin Log(LOGLEVEL_DEBUG, 'GetCurrentProcessId = %d', [GetCurrentProcessId]); RunService; end; end; function ConsoleHandler(dwCtrlType: DWORD): BOOL; begin Log(LOGLEVEL_DEBUG, 'Closing...'); // terminate main service thread Service.Terminate; // wait until the main service thread terminates while not Service.Closed do Sleep(10); Result := True; end; end.
unit NovusIndyUtils; interface uses SysUtils, NovusNumUtils, Winsock, IdTCPClient, NovusUtilities; Type TNovusIndyUtils = class(tNovusUtilities) protected public class function UrlEncode(const DecodedStr: String; Pluses: Boolean): String; class function UrlDecode(const EncodedStr: String): String; class function IsTCPPortUsed(aPort : Word; aAddress:AnsiString) : boolean; end; implementation class function TNovusIndyUtils.UrlEncode(const DecodedStr: String; Pluses: Boolean): String; var I: Integer; begin Result := ''; if Length(DecodedStr) > 0 then for I := 1 to Length(DecodedStr) do begin if not (DecodedStr[I] in ['0'..'9', 'a'..'z', 'A'..'Z', ' ']) then Result := Result + '%' + IntToHex(Ord(DecodedStr[I]), 2) else if not (DecodedStr[I] = ' ') then Result := Result + DecodedStr[I] else begin if not Pluses then Result := Result + '%20' else Result := Result + '+'; end; end; end; class function TNovusIndyUtils.UrlDecode(const EncodedStr: String): String; var I: Integer; begin Result := ''; if Length(EncodedStr) > 0 then begin I := 1; while I <= Length(EncodedStr) do begin if EncodedStr[I] = '%' then begin Result := Result + Chr(TNovusNumUtils.HexToInt64(EncodedStr[I+1] + EncodedStr[I+2])); I := Succ(Succ(I)); end else if EncodedStr[I] = '+' then Result := Result + ' ' else Result := Result + EncodedStr[I]; I := Succ(I); end; end; end; class function TNovusIndyUtils.IsTCPPortUsed(aPort : Word; aAddress:AnsiString) : boolean; var LTcpClient: TIdTCPClient; begin LTcpClient := TIdTCPClient.Create(nil); try try LTcpClient.Host := AAddress; //which server to test LTcpClient.Port := APort; //which port to test LTcpClient.ConnectTimeout := 200; //assume a port to be clodes if it does not respond within 200ms (some ports will immediately reject, others are using a "stealth" mechnism) LTcpClient.Connect; //try to connect result := true; //port is open except result := false; end; finally freeAndNil(LTcpClient); end; end; end.
unit DAO.DestinosViagem; interface uses DAO.base, Model.DestinosViagem, Generics.Collections, System.Classes; type TDestinosViagemDAO = class(TDAO) public function Insert(aDestinos: TDestinosViagem): Boolean; function Update(aDestinos: TDestinosViagem): Boolean; function Delete(aParam: array of Variant): Boolean; function Find(aParam: array of Variant): TObjectList<TDestinosViagem>; end; const TABLENAME = 'trs_destinos_transporte'; implementation { TDestinosViagemDAO } Uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TDestinosViagemDAO.Delete(aParam: array of Variant): Boolean; var sSQL: String; sWhere: String; begin Result := False; if Length(aParam) <= 1 then Exit; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if aParam[0] = 'ID' then begin sSQL := 'WHERE ID_DESTINO = :ID'; Connection.ExecSQL(sSQL + sWhere,[aParam[1]], [ftInteger]); end; if aParam[0] = 'DESTINO' then begin sSQL := 'WHERE COD_DESTINO = :DESTINO'; Connection.ExecSQL(sSQL + sWhere,[aParam[1]], [ftInteger]); end; if aParam[0] = 'CONTROLE' then begin sSQL := 'WHERE ID_CONTROLE = :CONTROLE'; Connection.ExecSQL(sSQL + sWhere,[aParam[1]], [ftInteger]); end; Result := True; end; function TDestinosViagemDAO.Find(aParam: array of Variant): TObjectList<TDestinosViagem>; var FdQuery : TFDQuery; destinos : TObjectList<TDestinosViagem>; begin try if Length(aParam) <= 1 then Exit; FdQuery := TFDQuery.Create(nil); FdQuery.Connection := Connection; FdQuery.SQL.Add('SELECT * FROM ' + TABLENAME); destinos := TObjectList<TDestinosViagem>.Create; if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_DESTINO = :ID'); FDQuery.ParamByName('ID').AsInteger := aParam[1]; end; if aParam[0] = 'DESTINO' then begin FDQuery.SQL.Add('WHERE COD_DESTINO = :DESTINO'); FDQuery.ParamByName('DESTINO').AsInteger := aParam[1]; end; if aParam[0] = 'CONTROLE' then begin FDQuery.SQL.Add('WHERE ID_CONTROLE = :CONTROLE'); FDQuery.ParamByName('CONTROLE').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[2]); end; destinos := TObjectList<TDestinosViagem>.Create; FDQuery.Open(); while not FDQuery.Eof do begin destinos.Add(TDestinosViagem.Create(FDQuery.FieldByName('ID_DESTINO').AsInteger, FdQuery.FieldByName('COD_DESTINO').AsInteger, FdQuery.FieldByName('ID_CONTROLE').AsInteger)); FdQuery.Next; end; Result := destinos; finally FdQuery.Free; end; end; function TDestinosViagemDAO.Insert(aDestinos: TDestinosViagem): Boolean; var sSQL : String; begin Result := False; sSQL := 'INSERT INTO ' + TABLENAME + '(ID_DESTINO, COD_DESTINO, ID_CONTROLE) VALUES (:PID_DESTINO, :PCOD_DESTINO, :PID_CONTROLE)'; Connection.ExecSQL(sSQL,[aDestinos.Id, aDestinos.Destino, aDestinos.Controle], [ftInteger, ftInteger, ftInteger]); Result := True; end; function TDestinosViagemDAO.Update(aDestinos: TDestinosViagem): Boolean; var sSQL : String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + 'SET COD_DESTINO = :PCOD_DESTINO, ID_CONTROLE = :PID_CONTROLE WHERE ID_DESTINO = :PID_DESTINO'; Connection.ExecSQL(sSQL,[aDestinos.Destino, aDestinos.Controle, aDestinos.Id], [ftInteger, ftInteger, ftInteger]); Result := True; end; end.
unit SISVISA.Model.Artigos; interface uses FireDAC.Comp.Client, FMX.ListView.Appearances, System.Classes, FMX.Edit; type iModelArtigos = interface ['{EF50123E-EF1A-434B-993B-9377BA38289F}'] function CodArtigo(value: integer): iModelArtigos; function Fields(value: string): iModelArtigos; function PreencherArtigo: string; function Artigo(value: string): iModelArtigos; function Paragrafo(value: string): iModelArtigos; function Inciso(value: string): iModelArtigos; end; TModelArtigos = class(TInterfacedObject, iModelArtigos) private FCodArtigo: integer; FFields: string; FArtigo: string; FInciso: string; FParagrafo: string; public constructor create; destructor destroy; override; class function New: iModelArtigos; function CodArtigo(value: integer): iModelArtigos; function Fields(value: string): iModelArtigos; function Artigo(value: string): iModelArtigos; function Paragrafo(value: string): iModelArtigos; function Inciso(value: string): iModelArtigos; function PreencherArtigo: string; end; implementation uses U_dmSISVISA, System.SysUtils; { TModelCaminhoDb } { TModelArtigos } function TModelArtigos.Artigo(value: string): iModelArtigos; begin Result := Self; FArtigo := value; end; function TModelArtigos.CodArtigo(value: integer): iModelArtigos; begin Result := Self; FCodArtigo := value; end; constructor TModelArtigos.create; begin end; destructor TModelArtigos.destroy; begin inherited; end; function TModelArtigos.Fields(value: string): iModelArtigos; begin Result := Self; FFields := value; end; function TModelArtigos.Inciso(value: string): iModelArtigos; begin Result := Self; FInciso := value; end; class function TModelArtigos.New: iModelArtigos; begin Result := Self.create; end; function TModelArtigos.Paragrafo(value: string): iModelArtigos; begin Result := Self; FParagrafo := value; end; function TModelArtigos.PreencherArtigo: string; var qry: TFDQuery; begin qry := TFDQuery.create(nil); try qry.Close; qry.SQL.Clear; qry.Connection := dmSISVISA.FD_ConnSISVISA; qry.SQL.Text := 'select ' + FFields + ' from artigos where cod_artigo = ' + intToStr(FCodArtigo); qry.Prepared := true; qry.Open(); FArtigo := qry.FieldByName(FFields).AsString; finally qry.destroy; end; Result := FArtigo; end; end.
unit SessaoUsuario; interface uses Classes, DSHTTP, Biblioteca, Forms, Windows, IniFiles, SysUtils, Generics.Collections, DataSnap.DSHTTPClient, Tipos, ACBrDevice, DBClient, EcfOperadorVO, EcfConfiguracaoVO, EcfMovimentoVO, EcfTipoPagamentoVO, EcfImpressoraVO, R01VO, EcfVendaCabecalhoVO; type TSessaoUsuario = class private FHttp: TDSHTTP; FUrl: String; FIdSessao: String; FCamadas: Integer; FPathIntegracao: String; FStatusCaixa: TStatusCaixa; FMenuAberto: TSimNao; FServidor: String; FPorta: Integer; FUsuario: TEcfOperadorVO; FConfiguracao: TEcfConfiguracaoVO; FMovimento: TEcfMovimentoVO; FR01: TR01VO; FVendaAtual: TEcfVendaCabecalhoVO; FECFsAutorizados: TStringList; FListaTipoPagamento: TObjectList<TEcfTipoPagamentoVO>; FListaImpressora: TObjectList<TEcfImpressoraVO>; class var FInstance: TSessaoUsuario; public constructor Create; destructor Destroy; override; class function Instance: TSessaoUsuario; function AutenticaUsuario(pLogin, pSenha: String): Boolean; function Autenticado: Boolean; procedure PopulaObjetosPrincipais; procedure LiberaVendaAtual; property HTTP: TDSHTTP read FHttp; property URL: String read FUrl; property IdSessao: String read FIdSessao; property Camadas: Integer read FCamadas write FCamadas; property PathIntegracao: String read FPathIntegracao write FPathIntegracao; property StatusCaixa: TStatusCaixa read FStatusCaixa write FStatusCaixa; property MenuAberto: TSimNao read FMenuAberto write FMenuAberto; property Servidor: String read FServidor; property Porta: Integer read FPorta; property Usuario: TEcfOperadorVO read FUsuario; property Configuracao: TEcfConfiguracaoVO read FConfiguracao write FConfiguracao; property Movimento: TEcfMovimentoVO read FMovimento write FMovimento; property R01: TR01VO read FR01 write FR01; property VendaAtual: TEcfVendaCabecalhoVO read FVendaAtual write FVendaAtual; property ECFsAutorizados: TStringList read FECFsAutorizados write FECFsAutorizados; property ListaTipoPagamento: TObjectList<TEcfTipoPagamentoVO> read FListaTipoPagamento write FListaTipoPagamento; property ListaImpressora: TObjectList<TEcfImpressoraVO> read FListaImpressora write FListaImpressora; const Estados: array [TACBrECFEstado] of string = ('Não Inicializada', 'Desconhecido', 'Livre', 'Venda', 'Pagamento', 'Relatório', 'Bloqueada', 'Requer Z', 'Requer X', 'Nao Fiscal'); end; implementation uses Controller, EcfTipoPagamentoController, EcfImpressoraController; constructor TSessaoUsuario.Create; var ArquivoIni: TIniFile; I: Integer; begin inherited Create; FHttp := TDSHTTP.Create; // Conexão ArquivoIni := TIniFile.Create(CaminhoApp + 'Conexao.ini'); try with ArquivoIni do begin if not SectionExists('ServidorApp') then begin WriteString('ServidorApp', 'Servidor', 'localhost'); WriteInteger('ServidorApp', 'Porta', 8080); end; FServidor := ReadString('ServidorApp', 'Servidor', 'localhost'); FPorta := ReadInteger('ServidorApp', 'Porta', 8080); Camadas := ReadInteger('ServidorApp', 'Camadas', 3); PathIntegracao := ReadString('INTEGRACAO', 'REMOTEAPP', ''); end; finally ArquivoIni.Free; end; // Arquivo Auxiliar ArquivoIni := TIniFile.Create(CaminhoApp + 'ArquivoAuxiliar.ini'); try FECFsAutorizados := TStringList.Create; ArquivoIni.ReadSectionValues('SERIES', ECFsAutorizados); finally ArquivoIni.Free; end; FUrl := 'http://' + Servidor + ':' + IntToStr(Porta) + '/datasnap/restT2Ti/TController/ObjetoJson/'; end; destructor TSessaoUsuario.Destroy; begin FHttp.Free; FreeAndNil(FUsuario); FreeAndNil(FMovimento); FreeAndNil(FConfiguracao); FreeAndNil(FR01); FreeAndNil(FVendaAtual); FreeAndNil(FECFsAutorizados); FreeAndNil(FListaImpressora); FreeAndNil(FListaTipoPagamento); inherited; end; procedure TSessaoUsuario.LiberaVendaAtual; begin FreeAndNil(FVendaAtual); end; procedure TSessaoUsuario.PopulaObjetosPrincipais; var Filtro: String; I: Integer; begin Filtro := 'STATUS_MOVIMENTO=' + QuotedStr('A') + ' or STATUS_MOVIMENTO=' + QuotedStr('T'); FMovimento := TEcfMovimentoVO(TController.BuscarObjeto('EcfMovimentoController.TEcfMovimentoController', 'ConsultaObjeto', [Filtro], 'GET')); FConfiguracao := TEcfConfiguracaoVO(TController.BuscarObjeto('EcfConfiguracaoController.TEcfConfiguracaoController', 'ConsultaObjeto', ['ID=1'], 'GET')); FR01 := TR01VO(TController.BuscarObjeto('R01Controller.TR01Controller', 'ConsultaObjeto', ['ID=1'], 'GET')); FListaTipoPagamento := TObjectList<TEcfTipoPagamentoVO>(TController.BuscarLista('EcfTipoPagamentoController.TEcfTipoPagamentoController', 'ConsultaLista', ['ID>0'], 'GET')); FListaImpressora := TObjectList<TEcfImpressoraVO>(TController.BuscarLista('EcfImpressoraController.TEcfImpressoraController', 'ConsultaLista', ['ID>0'], 'GET')); end; class function TSessaoUsuario.Instance: TSessaoUsuario; begin if not Assigned(FInstance) then FInstance := TSessaoUsuario.Create; Result := FInstance; end; function TSessaoUsuario.Autenticado: Boolean; begin Result := Assigned(FUsuario); end; function TSessaoUsuario.AutenticaUsuario(pLogin, pSenha: String): Boolean; var SenhaCript: String; begin FIdSessao := CriaGuidStr; FIdSessao := MD5String(FIdSessao); try // Senha é criptografada com a senha digitada + login SenhaCript := MD5String(pLogin + pSenha); FHttp.SetBasicAuthentication(pLogin + '|' + FIdSessao, SenhaCript); FUsuario := TEcfOperadorVO(TController.BuscarObjeto('EcfFuncionarioController.TEcfFuncionarioController', 'Usuario', [pLogin, pSenha], 'GET')); if Assigned(FUsuario) then FUsuario.Senha := pSenha; Result := Assigned(FUsuario); except Application.MessageBox('Erro ao autenticar usuário.', 'Erro de Login', MB_OK + MB_ICONERROR); raise; end; end; end.
unit help_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JSON, ComCtrls, COMMONS, StdCtrls, ExtCtrls; type TfrmHelp = class(TForm) tvwHelp: TTreeView; redHelp: TRichEdit; edtSearch: TEdit; btnSearch: TButton; Panel1: TPanel; btnMainMain: TButton; Label1: TLabel; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure tvwHelpChange(Sender: TObject; Node: TTreeNode); procedure FormShow(Sender: TObject); procedure btnMainMainClick(Sender: TObject); private procedure Search(relevant:string); procedure AddToTree(Current : MArray<DictObject>; Parent : TTreeNode); var jsonHelp : DictObject; specialHelp : MDict<TTreeNode,string>; dicTree : MDict<string,TTreeNode>; public procedure Help(relevant:string); end; var frmHelp: TfrmHelp; implementation uses mainmenu_u; {$R *.dfm} procedure TfrmHelp.AddToTree(Current: MArray<DictObject>; Parent : TTreeNode); var tmpObj : DictObject; tmpParent : TTreeNode; begin for tmpObj in Current.container do begin tmpParent := tvwHelp.Items.AddChild(Parent,tmpObj['title'].toString); dicTree.append(tmpObj['title'].toString,tmpParent); if tmpObj['hasChildren'].toBool then begin AddToTree(tmpObj['content'].toArray,tmpParent); end else specialHelp.append(tmpParent,tmpObj['content'].toString) end; end; procedure TfrmHelp.btnMainMainClick(Sender: TObject); begin frmMainMenu.SHow; Hide; end; procedure TfrmHelp.btnSearchClick(Sender: TObject); begin if edtSearch.Text <> '' then Search(edtSearch.Text); end; procedure TfrmHelp.FormCreate(Sender: TObject); begin jsonHelp := JSONParser.FileParse('help.json'); specialHelp := MDict<TTreeNOde,string>.Create(); dicTree := MDict<string,TTreeNode>.Create(); AddToTree(jsonHelp['help'].toArray,nil); end; procedure TfrmHelp.FormShow(Sender: TObject); var tmpNode:TTreeNode; begin for tmpNode in dicTree.values.container do tmpNode.Expanded := false; redHelp.Text := ''; end; procedure TfrmHelp.Help(relevant: string); begin Show; Search(relevant); end; procedure TfrmHelp.Search(relevant: string); var searchIndex : integer; begin searchIndex := dicTree.keys.findIF(relevant,Strings.Equivalent); if searchIndex <> -1 then tvwHelp.Select(dicTree.values[searchIndex]); dicTree.values[searchIndex].Expanded:=true; tvwHelp.SetFocus; end; procedure TfrmHelp.tvwHelpChange(Sender: TObject; Node: TTreeNode); var specialIndex : integer; begin specialIndex := specialHelp.keys.find(tvwHelp.Selected); if specialIndex <> -1 then redHelp.Text := specialHelp.values[specialIndex]; end; end.
unit fmChild2_; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, EventBus, EventPacket, PacketListen ; type TfmChild2 = class(TForm) Memo1: TMemo; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } FPacketListen: TPacketListen; procedure log(s:String); procedure OnPacket(AEvent: TEventPacket); public { Public declarations } [Subscribe(TThreadMode.Main)] procedure OnRxClear(AEvent:TClearPacket); [Subscribe(TThreadMode.Main)] procedure OnRxEventPacket(AEvent:TEventPacket); [Subscribe(TThreadMode.Posting)] procedure OnRxEventPacketPosting(AEvent:TEventPacket); [Subscribe(TThreadMode.Async)] procedure OnRxEventPacketAsync(AEvent:TEventPacket); end; var fmChild2: TfmChild2; implementation {$R *.dfm} procedure TfmChild2.FormClose(Sender: TObject; var Action: TCloseAction); begin FPacketListen.Free; FPacketListen := nil; GlobalEventBus.Unregister(self); Action := caFree; Fmchild2 := nil; end; procedure TfmChild2.FormCreate(Sender: TObject); begin GlobalEventBus.RegisterSubscriber(self); FPacketListen := TPacketListen.Create; FPacketListen.OnPacket := OnPacket; end; procedure TfmChild2.log(s: String); begin if Memo1.Lines.Count > 20 then Memo1.Lines.Delete( Memo1.Lines.Count - 1 ); Memo1.Lines.Insert(0, s); end; procedure TfmChild2.OnPacket(AEvent: TEventPacket); var LObject:String; begin if AEvent.Data = nil then begin LObject := 'nil'; end else begin LObject := format('%-30s %s.%s ThreadID:%d',[ 'Thread.Background',TCustomForm(TButton(AEvent.Data).Owner).Name, TButton(AEvent.Data).Name, TThread.Current.ThreadID]); end; TThread.Queue(nil, procedure begin log( AEvent.Msg + ' : ' + LObject); AEvent.Free; end); end; procedure TfmChild2.OnRxClear(AEvent: TClearPacket); begin Memo1.Lines.Clear; AEvent.Free; end; procedure TfmChild2.OnRxEventPacket(AEvent: TEventPacket); var LObject:String; begin if AEvent.Data = nil then begin LObject := 'nil'; end else begin LObject := format('%-30s %s.%s ThreadID:%d',[ 'Thread.Main', TCustomForm(TButton(AEvent.Data).Owner).Name, TButton(AEvent.Data).Name, TThread.Current.ThreadID]); end; log( AEvent.Msg + ' : ' + LObject); AEvent.Free; end; procedure TfmChild2.OnRxEventPacketAsync(AEvent: TEventPacket); var LObject:String; begin if AEvent.Data = nil then begin LObject := 'nil'; end else begin LObject := format('%-30s %s.%s ThreadID:%d',[ 'Thread.Main.Async', TCustomForm(TButton(AEvent.Data).Owner).Name, TButton(AEvent.Data).Name, TThread.Current.ThreadID]); end; TThread.Queue(nil, procedure begin log( AEvent.Msg + ' : ' + LObject); AEvent.Free; end); end; procedure TfmChild2.OnRxEventPacketPosting(AEvent: TEventPacket); var LObject:String; begin if AEvent.Data = nil then begin LObject := 'nil'; end else begin LObject := format('%-30s %s.%s ThreadID:%d',[ 'Thread.Main.Posting', TCustomForm(TButton(AEvent.Data).Owner).Name, TButton(AEvent.Data).Name, TThread.Current.ThreadID]); end; TThread.Queue(nil, procedure begin log( AEvent.Msg + ' : ' + LObject); AEvent.Free; end); end; end.
unit ValueHolder; interface uses System.SysUtils, System.SyncObjs, Promise.Proto ; type IHolder<TResult> = interface function GetValue: TResult; procedure SetValue(const value: TResult); function GetReason: IFailureReason<Exception>; procedure SetReason(const value: IFailureReason<Exception>); function GetSuccessCount: integer; function GetFailureCount: integer; function GetAlwaysCount: integer; procedure Success; procedure Failed; procedure Increment; property Value: TResult read GetValue write SetValue; property Error: IFailureReason<Exception> read GetReason write SetReason; property SuccessCount: integer read GetSuccessCount; property FailureCount: integer read GetFailureCount; property AlwaysCount: integer read GetAlwaysCount; end; TValueHolder<TResult> = class (TInterfacedObject, IHolder<TResult>) private var FValue: TResult; FReason: IFailureReason<Exception>; FSuccessCount: integer; FFailureCount: integer; FAlwaysCount: integer; private function GetValue: TResult; procedure SetValue(const value: TResult); function GetReason: IFailureReason<Exception>; procedure SetReason(const value: IFailureReason<Exception>); function GetSuccessCount: integer; function GetFailureCount: integer; function GetAlwaysCount: integer; protected procedure Success; procedure Failed; procedure Increment; end; implementation { TValueHolder<TResult> } procedure TValueHolder<TResult>.Failed; begin TInterlocked.Increment(FFailureCount); end; function TValueHolder<TResult>.GetAlwaysCount: integer; begin Exit(FAlwaysCount); end; function TValueHolder<TResult>.GetFailureCount: integer; begin Exit(FFailureCount); end; function TValueHolder<TResult>.GetReason: IFailureReason<Exception>; begin Exit(FReason); end; function TValueHolder<TResult>.GetSuccessCount: integer; begin Exit(FSuccessCount); end; function TValueHolder<TResult>.GetValue: TResult; begin Exit(FValue); end; procedure TValueHolder<TResult>.Increment; begin TInterlocked.Increment(FAlwaysCount); end; procedure TValueHolder<TResult>.Success; begin TInterlocked.Increment(FSuccessCount); end; procedure TValueHolder<TResult>.SetReason(const value: IFailureReason<Exception>); begin FReason := value; end; procedure TValueHolder<TResult>.SetValue(const value: TResult); begin FValue := value; end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvActionsEngine.Pas, released on 2007-03-12. The Initial Developer of the Original Code is Jens Fudickar [jens dott fudicker att oratool dott de] Portions created by Jens Fudickar are Copyright (C) 2007 Jens Fudickar. All Rights Reserved. Contributor(s): - You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvActionsEngine.pas 13415 2012-09-10 09:51:54Z obones $ unit JvActionsEngine; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} {$IFDEF MSWINDOWS} Windows, ActnList, Graphics, ImgList, {$ENDIF MSWINDOWS} {$IFDEF HAS_UNIT_SYSTEM_UITYPES} System.UITypes, {$ENDIF HAS_UNIT_SYSTEM_UITYPES} Controls, Classes; type TJvActionEngineBaseAction = class; TJvChangeActionComponent = procedure(ActionComponent: TComponent) of object; TJvActionBaseEngine = class(TComponent) private protected public constructor Create(AOwner: TComponent); override; function SupportsComponent(AComponent: TComponent): Boolean; virtual; function SupportsAction(AAction: TJvActionEngineBaseAction): Boolean; virtual; published end; TJvActionBaseEngineClass = class of TJvActionBaseEngine; TJvActionEngineList = class(TList) private function GetEngine(Index: Integer): TJvActionBaseEngine; public destructor Destroy; override; procedure RegisterEngine(AEngineClass: TJvActionBaseEngineClass); function GetControlEngine(AComponent: TComponent; AAction: TJvActionEngineBaseAction): TJvActionBaseEngine; virtual; function Supports(AComponent: TComponent; AAction: TJvActionEngineBaseAction = nil): Boolean; property Engine[Index: Integer]: TJvActionBaseEngine read GetEngine; end; TJvActionEngineBaseAction = class(TAction) private FActionComponent: TComponent; FControlEngine: TJvActionBaseEngine; FLastTarget: TComponent; FOnChangeActionComponent: TJvChangeActionComponent; protected //1 This Procedure is called when the ActionComponent is changed procedure ChangeActionComponent(const AActionComponent: TComponent); virtual; procedure CheckChecked(var AChecked: Boolean); virtual; procedure CheckEnabled(var AEnabled: Boolean); virtual; procedure CheckVisible(var AVisible: Boolean); virtual; function DetectControlEngine(aActionComponent: TComponent): Boolean; virtual; function GetEngineList: TJvActionEngineList; virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetActionComponent(const Value: TComponent); virtual; property ControlEngine: TJvActionBaseEngine read FControlEngine; property EngineList: TJvActionEngineList read GetEngineList; property LastTarget: TComponent read FLastTarget; //1 Use this event to check the Enabled Flag depending on properties of the ActionComponent property OnChangeActionComponent: TJvChangeActionComponent read FOnChangeActionComponent write FOnChangeActionComponent; public constructor Create(AOwner: TComponent); override; function HandlesTarget(Target: TObject): Boolean; override; procedure SetChecked(Value: Boolean); {$IFDEF RTL240_UP}override;{$ENDIF RTL240_UP} procedure SetEnabled(Value: Boolean); {$IFDEF RTL240_UP}override;{$ENDIF RTL240_UP} procedure SetImageIndex(Value: TImageIndex); {$IFDEF RTL240_UP}override;{$ENDIF RTL240_UP} procedure SetParentComponent(AParent: TComponent); override; procedure SetVisible(Value: Boolean); {$IFDEF RTL240_UP}override;{$ENDIF RTL240_UP} procedure UpdateTarget(Target: TObject); override; property ActionComponent: TComponent read FActionComponent write SetActionComponent; end; type TJvActionBaseActionList = class(TActionList) //The idea of the Action Classes is to work different type of controls. // //Then we have a list of ActionEngines which have the availability to //validate find for a Component if it is supported or not. //For each new type of controls with specific need of handles a new Engine //must be created and registered. An example for these engines can be found //in "JvDBActionsEngineControlCxGrid.pas". // //When a ActionComponent is assigned the action tries to find the correct //engine based on the component and uses the engine for all further operations. // //There are two ways to assign a ActionComponent: //1. Assigning the component to the action list, then all actions in // this list (which are based on TJvActionEngineBaseAction class) // gets the ActionComponent assigned also. //2. Using the active control, like the normal action handling. private FActionComponent: TComponent; FOnChangeActionComponent: TJvChangeActionComponent; protected procedure SetActionComponent(Value: TComponent); property ActionComponent: TComponent read FActionComponent write SetActionComponent; property OnChangeActionComponent: TJvChangeActionComponent read FOnChangeActionComponent write FOnChangeActionComponent; public procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvActionsEngine.pas $'; Revision: '$Revision: 13415 $'; Date: '$Date: 2012-09-10 11:51:54 +0200 (lun. 10 sept. 2012) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses SysUtils, Variants, JvJVCLUtils; //=== { TJvActionEngineList } ======================================== destructor TJvActionEngineList.Destroy; var I: Integer; begin for I := Count - 1 downto 0 do begin TJvActionBaseEngine(Items[I]).Free; Items[I] := nil; Delete(I); end; inherited Destroy; end; procedure TJvActionEngineList.RegisterEngine(AEngineClass: TJvActionBaseEngineClass); begin Add(AEngineClass.Create(nil)); end; function TJvActionEngineList.GetControlEngine(AComponent: TComponent; AAction: TJvActionEngineBaseAction): TJvActionBaseEngine; var Ind: Integer; begin Result := nil; for Ind := 0 to Count - 1 do if Engine[Ind].SupportsComponent(AComponent) then if not Assigned(AAction) or Engine[Ind].SupportsAction(AAction) then begin Result := TJvActionBaseEngine(Items[Ind]); Break; end; end; function TJvActionEngineList.GetEngine(Index: Integer): TJvActionBaseEngine; begin Result := TJvActionBaseEngine(Items[Index]); end; function TJvActionEngineList.Supports(AComponent: TComponent; AAction: TJvActionEngineBaseAction = nil): Boolean; begin Result := Assigned(GetControlEngine(AComponent, AAction)); end; constructor TJvActionBaseEngine.Create(AOwner: TComponent); begin inherited Create(AOwner); end; function TJvActionBaseEngine.SupportsComponent(AComponent: TComponent): Boolean; begin Result := False; end; function TJvActionBaseEngine.SupportsAction(AAction: TJvActionEngineBaseAction): Boolean; begin Result := False; end; constructor TJvActionEngineBaseAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FLastTarget := nil; FControlEngine := nil; if Assigned(AOwner) and (AOwner is TJvActionBaseActionList) then ActionComponent := TJvActionBaseActionList(AOwner).ActionComponent else FActionComponent := nil; end; procedure TJvActionEngineBaseAction.ChangeActionComponent(const AActionComponent: TComponent); begin if Assigned(OnChangeActionComponent) then OnChangeActionComponent(AActionComponent); end; procedure TJvActionEngineBaseAction.CheckChecked(var AChecked: Boolean); begin end; procedure TJvActionEngineBaseAction.CheckEnabled(var AEnabled: Boolean); begin end; procedure TJvActionEngineBaseAction.CheckVisible(var AVisible: Boolean); begin end; function TJvActionEngineBaseAction.DetectControlEngine(aActionComponent: TComponent): Boolean; begin if Assigned(EngineList) and Assigned(aActionComponent) then FControlEngine := EngineList.GetControlEngine(aActionComponent, self) else FControlEngine := nil; Result := Assigned(FControlEngine); end; function TJvActionEngineBaseAction.HandlesTarget(Target: TObject): Boolean; begin if Target is TComponent then begin ActionComponent := TComponent(Target); Result := Assigned(ControlEngine); end else Result := False; end; procedure TJvActionEngineBaseAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FActionComponent) then ActionComponent := nil; end; //=== { TJvActionEngineBaseAction } ======================================== procedure TJvActionEngineBaseAction.SetActionComponent(const Value: TComponent); var intValue: TComponent; changed: Boolean; begin if FLastTarget <> Value then begin FLastTarget := Value; if DetectControlEngine(Value) then intValue := Value else intValue := nil; Changed := FActionComponent <> intValue; ReplaceComponentReference(Self, intValue, FActionComponent); if changed then ChangeActionComponent(FActionComponent); end; end; procedure TJvActionEngineBaseAction.SetChecked(Value: Boolean); begin CheckChecked (Value); if Checked <> Value then {$IFDEF RTL240_UP} inherited SetChecked (Value); {$ELSE} Checked := Value; {$ENDIF RTL240_UP} end; procedure TJvActionEngineBaseAction.SetEnabled(Value: Boolean); begin CheckEnabled (Value); if Enabled <> Value then {$IFDEF RTL240_UP} inherited SetEnabled (Value); {$ELSE} Enabled := Value; {$ENDIF RTL240_UP} end; procedure TJvActionEngineBaseAction.SetImageIndex(Value: TImageIndex); begin if ImageIndex <> Value then {$IFDEF RTL240_UP} inherited SetImageIndex (Value); {$ELSE} ImageIndex := Value; {$ENDIF RTL240_UP} end; procedure TJvActionEngineBaseAction.SetParentComponent(AParent: TComponent); begin Inherited SetParentComponent(AParent); if AParent is TJvActionBaseActionList then ActionComponent := TJvActionBaseActionList(AParent).ActionComponent; end; procedure TJvActionEngineBaseAction.SetVisible(Value: Boolean); begin CheckVisible(Value); if Visible <> Value then {$IFDEF RTL240_UP} inherited SetVisible (Value); {$ELSE} Visible := Value; {$ENDIF RTL240_UP} end; procedure TJvActionEngineBaseAction.UpdateTarget(Target: TObject); begin if Assigned(ControlEngine) then ControlEngine.UpdateAction(self) else inherited UpdateTarget(Target); end; //=== { TJvDatabaseActionList } ============================================== procedure TJvActionBaseActionList.SetActionComponent(Value: TComponent); var I: Integer; begin if ReplaceComponentReference(Self, Value, FActionComponent) then begin for I := 0 to ActionCount - 1 do if Actions[I] is TJvActionEngineBaseAction then TJvActionEngineBaseAction(Actions[I]).ActionComponent := Value; if Assigned(OnChangeActionComponent) then OnChangeActionComponent(Value); end; end; procedure TJvActionBaseActionList.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then if AComponent = FActionComponent then ActionComponent := nil; end; initialization {$IFDEF UNITVERSIONING} RegisterUnitVersion(HInstance, UnitVersioning); {$ENDIF UNITVERSIONING} finalization {$IFDEF UNITVERSIONING} UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit ExtraUnit; interface uses Classes, Controls, Graphics, SysUtils, Windows, DB, IBCustomDataSet, DbGridEh; function GetFileVersion(const AFileName: string; var MS, LS: DWORD): Boolean; function FormatVersion(MS, LS: DWORD): string; function FontHeight(Font: TFont): Integer; function ControlOffsetX(Control: TControl; DX: Integer = 0): Integer; function ControlOffsetY(Control: TControl; DY: Integer = 0): Integer; function TextWidth(WinControl: TWinControl; const Text: string): Integer; procedure ControlVAllign(Control: TControl; MainControl: TControl); //вертикальное выравнивание одного контрола относительно другого function LevenshteinSimilarity(const S, T: string): Double; function LevenshteinSimilarityEx(PS: PChar; NS: Integer; PB: PWordArray; PT: PChar; NT: Integer): Double; procedure FieldDateChanged(var Lock: Boolean; DateField, TimeField, DateTimeField: TField); procedure FieldTimeChanged(var Lock: Boolean; DateField, TimeField, DateTimeField: TField); procedure EnterAsTabKeyPress(Sender: TObject; var Key: Char); function SelectNextControl(Control: TWinControl): Boolean; function AddIntField(DataSet: TDataSet; const FieldName: string; Owner: TComponent = nil): TIntegerField; function AddNumField(DataSet: TDataSet; const FieldName: string; Precision, Size: Integer; Owner: TComponent = nil): TIBBCDField; function AddStrField(DataSet: TDataSet; const FieldName: string; Size: Integer; Owner: TComponent = nil): TIBStringField; function NullToEmpty(V: Variant): Variant; function FormatDb(const Format: string; DataSet: TDataSet): string; function ConfirmDelete(const CustomConfirmation: string; DataSet: TDataSet): Boolean; function ConfirmCascade(const CustomConfirmation: string; DataSet: TDataSet): Boolean; //добавлено из других библиотек procedure CheckRequiredFields( DataSet : TDataSet ); procedure TrimAndNullFields(DataSet: TDataSet); procedure PrepareLookUpColumnExtra(Grd: TDBGridEh; const FN: String; const LookUpTableName, LookUpKeyFld, LookUpDisplayFld : String; SQLTEXT : String = '' ); implementation uses Variants, Forms, Dialogs, JvDSADialogs, DataUnit, mnutils; function ConfirmDelete(const CustomConfirmation: string; DataSet: TDataSet): Boolean; var S: string; begin if DataSet = nil then S := CustomConfirmation else S := FormatDb(CustomConfirmation, DataSet); Result := JvDSADialogs.MessageDlg('Подтверждение удаления', S, mtConfirmation, [mbYes, mbNo], 0, dckScreen, 0, mbNo, mbNo) = mrYes; end; function ConfirmCascade(const CustomConfirmation: string; DataSet: TDataSet): Boolean; const Buttons: array [0..1] of string = ('Удалить', 'Отмена'); var S: string; begin if DataSet = nil then S := CustomConfirmation else S := FormatDb(CustomConfirmation, DataSet); Result := JvDSADialogs.MessageDlgEx('Каскадное удаление', S, mtConfirmation, Buttons, [mrOK, mrCancel], 0, dckScreen, 0, 1, 1) = mrOK; end; function FormatDb(const Format: string; DataSet: TDataSet): string; var P, P1: PChar; S: string; Field: TField; begin Result := ''; P := PChar(Format); while (P^ <> #0) do begin P1 := StrScan(P, '%'); if P1 = nil then begin Result := Result + string(P); Break; end; SetString(S, P, P1 - P); Result := Result + S; P := P1 + 1; if P^ = '%' then begin Result := Result + '%'; P := P + 1; Continue; end; P1 := StrScan(P, '%'); if P1 = nil then Break; SetString(S, P, P1 - P); Field := DataSet.FindField(S); if Field <> nil then Result := Result + Field.DisplayText; P := P1 + 1; end; end; function AddIntField(DataSet: TDataSet; const FieldName: string; Owner: TComponent): TIntegerField; begin if Owner = nil then Owner := DataSet.Owner; Result := TIntegerField.Create(Owner); Result.FieldName := FieldName; Result.DataSet := DataSet; end; function AddNumField(DataSet: TDataSet; const FieldName: string; Precision, Size: Integer; Owner: TComponent): TIBBCDField; begin if Owner = nil then Owner := DataSet.Owner; Result := TIBBCDField.Create(Owner); Result.FieldName := FieldName; Result.Precision := 9; Result.Size := 4; Result.DataSet := DataSet; end; function AddStrField(DataSet: TDataSet; const FieldName: string; Size: Integer; Owner: TComponent): TIBStringField; begin if Owner = nil then Owner := DataSet.Owner; Result := TIBStringField.Create(Owner); Result.FieldName := FieldName; Result.Size := Size; Result.DataSet := DataSet; end; type TXWinControl = class(TWinControl) end; procedure EnterAsTabKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) and SelectNextControl(Sender as TWinControl) then Key := #0; end; function SelectNextControl(Control: TWinControl): Boolean; var WinControl: TWinControl; ParentForm: TCustomForm; begin ParentForm := GetParentForm(Control); WinControl := TXWinControl(ParentForm).FindNextControl(Control, True, True, False); Result := WinControl <> nil; if Result then WinControl.SetFocus; end; function TextWidth(WinControl: TWinControl; const Text: string): Integer; var Canvas: TCanvas; begin Canvas := TCanvas.Create; try Canvas.Handle := GetDC(WinControl.Handle); try Canvas.Font := TXWinControl(WinControl).Font; Result := Canvas.TextWidth(Text); finally ReleaseDC(WinControl.Handle, Canvas.Handle); Canvas.Handle := 0; end; finally Canvas.Free; end; end; function ControlOffsetX(Control: TControl; DX: Integer): Integer; begin Result := Control.Left + Control.Width + DX; end; function ControlOffsetY(Control: TControl; DY: Integer): Integer; begin Result := Control.Top + Control.Height + DY; end; function FontHeight(Font: TFont): Integer; begin Result := Font.Height; if Result < 0 then Result := - Result; end; procedure ControlVAllign(Control: TControl; MainControl: TControl); begin Control.Top := MainControl.Top + Round((MainControl.Height - Control.Height) / 2); end; function GetFileVersion(const AFileName: string; var MS, LS: DWORD): Boolean; var VersionSize, SomeHandle: Cardinal; Data: Pointer; VersionInfo: PVSFixedFileInfo; L: Cardinal; FileName: string; begin Result := False; { from SysUtils.pas vvv } // GetFileVersionInfo modifies the filename parameter data while parsing. // Copy the string const into a local variable to create a writeable copy. FileName := AFileName; UniqueString(FileName); { from SysUtils.pas ^^^ } VersionSize := GetFileVersionInfoSize(PChar(FileName), SomeHandle); if VersionSize > 0 then begin Data := AllocMem(VersionSize); try if GetFileVersionInfo(PChar(FileName), SomeHandle, VersionSize, Data) then begin if VerQueryValue(Data, '\', Pointer(VersionInfo), L) then begin if (L = SizeOf(TVSFixedFileInfo)) and (VersionInfo.dwSignature = $FEEF04BD) then begin MS := VersionInfo.dwFileVersionMS; LS := VersionInfo.dwFileVersionLS; Result := True; end; end; end; finally FreeMem(Data); end; end; end; function FormatVersion(MS, LS: DWORD): string; begin Result := Format('Версия %d.%d.%d Сборка %d', [ HiWord(MS), LoWord(MS), HiWord(LS), LoWord(LS) ]); end; {$OPTIMIZATION ON} { MUST: NS >= NT } function LevenshteinSimilarityEx(PS: PChar; NS: Integer; PB: PWordArray; PT: PChar; NT: Integer): Double; var I, J: Integer; Prev, Next, B: Word; begin if NT = 0 then begin if NS = 0 then Result := 1 else Result := 0; end else begin for J := 0 to NS do PB[J] := J; for I := 1 to NT do begin Prev := PB[0]; PB[0] := I; for J := 1 to NS do begin if PS[J - 1] <> PT[I - 1] then Inc(Prev); Next := PB[J - 1] + 1; B := PB[J] + 1; if Next > B then Next := B; if Next > Prev then Next := Prev; Prev := PB[J]; PB[J] := Next; end; end; Result := 1 - (PB[NS] / NT); if Result < 0 then Result := 0; end; end; function Min3(A, B, C:Integer): Integer; begin Result := A; if Result > B then Result := B; if Result > C then Result := C; end; var LevBuffer: array [0..1023] of Word; function LevenshteinSimilarity(const S, T: string): Double; var Matrix: array of array of Integer; Dist, N, M, L: Integer; I, J: Integer; Si, Tj: Char; Cost: Integer; SS, TT: string; NN, MM: Integer; PB: PWordArray; begin N := Length(S); M := Length(T); if N <= M then begin SS := S; TT := T; NN := N; MM := M; end else begin SS := T; TT := S; NN := M; MM := N; end; if NN < 1024 then begin Result := LevenshteinSimilarityEx(PChar(SS), NN, @LevBuffer[0], PChar(TT), MM); Exit; end else begin PB := AllocMem(NN * SizeOf(Word)); try Result := LevenshteinSimilarityEx(PChar(SS), NN, @LevBuffer[0], PChar(TT), MM); Exit; finally FreeMem(PB); end; end; SetLength(Matrix, N + 1, M + 1); if N = 0 then Dist := M else if M = 0 then Dist := N else begin for I := 0 to N do Matrix[I, 0] := I; for J := 0 to M do Matrix[0, J] := J; for I := 1 to N do begin Si := S[I]; for J := 1 to M do begin Tj := T[J]; Cost := Ord(Si <> Tj); Matrix[I, J] := Min3(Matrix[I - 1, J] + 1, Matrix[I, J - 1] + 1, Matrix[I - 1, J - 1] + Cost); end; end; Dist := Matrix[N, M]; end; if M > N then L := M else L := N; Result := 1 - (Dist / L); if Result < 0 then Result := 0; end; procedure FieldDateChanged(var Lock: Boolean; DateField, TimeField, DateTimeField: TField); begin if not Lock then begin Lock := True; try if DateField.IsNull then begin TimeField.Clear; DateTimeField.Clear; end else begin if TimeField.IsNull then TimeField.AsDateTime := 0; DateTimeField.AsDateTime := DateField.AsDateTime + TimeField.AsDateTime; end; finally Lock := False; end; end; end; procedure FieldTimeChanged(var Lock: Boolean; DateField, TimeField, DateTimeField: TField); begin if not Lock then begin Lock := True; try if TimeField.IsNull then begin DateField.Clear; DateTimeField.Clear; end else begin if DateField.IsNull then DateField.AsDateTime := Date; DateTimeField.AsDateTime := DateField.AsDateTime + TimeField.AsDateTime; end; finally Lock := False; end; end; end; function NullToEmpty(V: Variant): Variant; begin if VarIsNull(V) then Result := Unassigned else Result := V; end; procedure CheckRequiredFields(DataSet: TDataSet); var I: Integer; begin with DataSet do for I := 0 to FieldCount-1 do with Fields[I] do if Required and not ReadOnly and (FieldKind = fkData) and (IsNull or (AsString = '')) then begin FocusControl; raise Exception.Create( Format('Поле ''%s'' не может оставаться пустым', [DisplayName]) ); end; end; procedure TrimAndNullFields(DataSet: TDataSet); var I: Integer; F: TField; begin with DataSet do for I := 0 to FieldCount-1 do begin F := Fields[I]; if not F.ReadOnly and not F.IsNull and (F.FieldKind = fkData) and ((F is TStringField) or (F is TMemoField)) then begin F.AsString := Trim(F.AsString); if (F.AsString = '') then F.Clear; end; end; end; procedure PrepareLookUpColumnExtra(Grd: TDBGridEh; const FN: String; const LookUpTableName, LookUpKeyFld, LookUpDisplayFld : String; SQLTEXT : String = '' ); var Col : TColumnEh; begin Col := Grd[FN]; if Col = nil then exit; Col.KeyList.Clear; Col.PickList.Clear; with CommonData.AnyQuery do begin if SQLTEXT = '' then SQLTEXT := GenerateSQLText(LookUpTableName, LookUpKeyFld + ';' + LookUpDisplayFld, '', skSelect); SQL.Text := SQLTEXT; Open; Col.ReadOnly := IsEmpty; while not Eof do begin Col.KeyList.Add(Fields[0].AsString); Col.PickList.Add(Fields[1].AsString); Next; end; end; end; end.
{ Windows 95 style progress bar } { Vitaly Monastirsky vitaly@vdl.t.u-tokyo.ac.jp } unit Gauge95; interface uses WinTypes, WinProcs, Messages, Classes, Graphics, Controls, ExtCtrls, Forms; type TBevelStyle = (bsNone, bsLowered, bsRaised); TGauge95 = class(TGraphicControl) private FMinValue : Longint; FMaxValue : Longint; FCurValue : Longint; FBevelStyle: TBevelStyle; FBoxColor : TColor; FBoxCount : Integer; FBoxWidth : Integer; procedure SetMinValue(Value: Longint); procedure SetMaxValue(Value: Longint); procedure SetBevelStyle(Value: TBevelStyle); procedure SetBoxColor(Value: TColor); procedure SetBoxCount(Value: Integer); procedure SetBoxWidth(Value: Integer); procedure SetProgress(Value: Longint); function GetPercentDone: Double; procedure AdjustSize (var W: Integer; var H: Integer); protected LastPercent : integer; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure AddProgress(Value: Longint); property PercentDone: Double read GetPercentDone; function GetFMax : Longint; published property Align; property BevelStyle: TBevelStyle read FBevelStyle write SetBevelStyle default bsLowered; property BoxColor : TColor read FBoxColor write SetBoxColor default clHighlight; property BoxCount : Integer read FBoxCount write SetBoxCount default 20; property BoxWidth : Integer read FBoxWidth write SetBoxWidth default 12; property Color; property Enabled; property MinValue: Longint read FMinValue write SetMinValue default 0; property MaxValue: Longint read FMaxValue write SetMaxValue default 100; property ParentColor; property ParentShowHint; property Progress: Longint read FCurValue write SetProgress; property ShowHint; property Visible; end; procedure Register; implementation const MinBoxSize = 3; DeltaSize: array[TBevelStyle] of Integer = (1,3,3); {--------------------------------------------------} constructor TGauge95.Create(AOwner: TComponent); {--------------------------------------------------} begin inherited Create(AOwner); ControlStyle := ControlStyle + [csFramed, csOpaque]; FMinValue := 0; FMaxValue := 100; FCurValue := 0; FBevelStyle := bsLowered; FBoxColor := clHighlight; FBoxCount := 20; FBoxWidth := 12; Width := (FBoxWidth * FBoxCount) + 3; Height := 24; LastPercent:=0; end; {-------------------------------------------------} procedure TGauge95.SetMinValue(Value: Longint); {-------------------------------------------------} begin if Value <> FMinValue then begin FMinValue := Value; Refresh; end; end; {-------------------------------------------------} procedure TGauge95.SetMaxValue(Value: Longint); {-------------------------------------------------} begin if Value <> FMaxValue then begin FMaxValue := Value; Refresh; end; end; {-------------------------------------------------------} procedure TGauge95.SetBevelStyle(Value: TBevelStyle); {-------------------------------------------------------} var W, H : Integer; begin if Value <> FBevelStyle then begin W := Width; H := Height; if FBevelStyle = bsNone then begin Inc(W, 2); Inc(H, 2); end else if Value = bsNone then begin Dec(W, 2); Dec(H, 2); end; FBevelStyle := Value; inherited SetBounds(Left, Top, W, H); Invalidate; end; end; {------------------------------------------------} procedure TGauge95.SetBoxCount(Value: Integer); {------------------------------------------------} var W: Integer; begin if FBoxCount <> Value then begin if Value < 1 then Value := 1; FBoxCount := Value; W := FBoxWidth * FBoxCount + 1; if FBevelStyle <> bsNone then Inc(W, 2); SetBounds(Left, Top, W, Height); Invalidate; end; end; {-----------------------------------------------} procedure TGauge95.SetBoxColor(Value: TColor); {-----------------------------------------------} begin if FBoxColor <> Value then begin FBoxColor := Value; Invalidate; end; end; {------------------------------------------------} procedure TGauge95.SetBoxWidth(Value: Integer); {------------------------------------------------} var W: Integer; begin if FBoxWidth <> Value then begin if Value < MinBoxSize then Value := MinBoxSize; FBoxWidth := Value; W := FBoxWidth * FBoxCount + 1; if FBevelStyle <> bsNone then Inc(W, 2); SetBounds(Left, Top, W, Height); Invalidate; end; end; {-------------------------------------------------} procedure TGauge95.SetProgress(Value: Longint); {-------------------------------------------------} var p2:longint; begin p2:=round((Value - FMinValue) / (FMaxValue - FMinValue) * 50); if (FCurValue <> Value) and (Value >= FMinValue) and (Value <= FMaxValue) then begin FCurValue := Value; if (LastPercent<>p2) then Refresh; LastPercent := p2; end; end; {-------------------------------------------} function TGauge95.GetPercentDone: Double; {-------------------------------------------} begin if FMaxValue = FMinValue then Result := 0 else Result := (FCurValue - FMinValue) / (FMaxValue - FMinValue) * 100; end; {-----------------------------------------------------------------} procedure TGauge95.AdjustSize (var W: Integer; var H: Integer); {-----------------------------------------------------------------} var TempW, TempH: Integer; begin if csLoading in ComponentState then Exit; TempW := W - DeltaSize[FBevelStyle]; TempH := H - DeltaSize[FBevelStyle] - 1; if TempW < FBoxWidth then TempW := FBoxWidth; if TempH < MinBoxSize then TempH := MinBoxSize; FBoxCount := TempW div FBoxWidth; if Align = alNone then TempW := FBoxCount * FBoxWidth; W := TempW + DeltaSize[FBevelStyle]; H := TempH + DeltaSize[FBevelStyle] + 1; end; {----------------------------------------------------------------------} procedure TGauge95.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); {----------------------------------------------------------------------} var W, H: Integer; begin W := AWidth; H := AHeight; AdjustSize (W, H); inherited SetBounds (ALeft, ATop, W, H); end; {---------------------------} procedure TGauge95.Paint; {---------------------------} var I, PaintBoxes: integer; BoxRect, BoundRect, TheRect : TRect; GaugeImage: TBitmap; begin GaugeImage := TBitmap.Create; try GaugeImage.Height := Height; GaugeImage.Width := Width; BoundRect := ClientRect; TheRect := BoundRect; if FBevelStyle = bsLowered then Frame3D(GaugeImage.Canvas, TheRect, clBtnShadow, clBtnHighlight, 1) else if FBevelStyle = bsRaised then Frame3D(GaugeImage.Canvas, TheRect, clBtnHighlight, clBtnShadow, 1); with GaugeImage.Canvas do begin if ParentColor then Brush.Color := Parent.Brush.Color else Brush.Color := Color; FillRect(TheRect); if Enabled then Brush.Color := FBoxColor else Brush.Color := clInactiveCaption; PaintBoxes := Round(PercentDone * FBoxCount * 0.01); if PaintBoxes > FBoxCount then PaintBoxes := FBoxCount; BoxRect := Bounds(TheRect.Left + 1, TheRect.Top + 1, FBoxWidth - 2 , Height - DeltaSize[FBevelStyle] - 1); for I := 1 to PaintBoxes do begin FillRect(BoxRect); OffsetRect(BoxRect, FBoxWidth, 0); end; end; Canvas.CopyRect(BoundRect, GaugeImage.Canvas, BoundRect); finally GaugeImage.Free; end; end; {-------------------------------------------------} procedure TGauge95.AddProgress(Value: Longint); {-------------------------------------------------} var NewValue:longint; begin NewValue:=FCurValue + Value; if (NewValue >= FMinValue) and (NewValue <= FMaxValue) then Progress := NewValue; end; {-------------------------------------------------} function TGauge95.GetFMax : Longint; {-------------------------------------------------} begin GetFMax:=FMaxValue; end; {---------------------} procedure Register; {---------------------} begin RegisterComponents('Samples', [TGauge95]); end; end.
{ Target driver routines that are specific to the PIC10 family. } module picprg_10; define picprg_erase_10; %include 'picprg2.ins.pas'; { ******************************************************************************* * * Subroutine PICPRG_ERASE_10 (PR, STAT) * * Erase all non-volatile memory in the target chip. * * This version is for 10Fxxx devices. The backup OSCCAL MOVLW instruction * in configuration space is preserved. The OSCCAL MOVLW instruction at the * reset vector (last location in program memory) is erased, since the * application may decide to write other information there. } procedure picprg_erase_10 ( {erase routine for generic 10Fxxx} in out pr: picprg_t; {state for this use of the library} out stat: sys_err_t); {completion status} val_param; const tera = 0.010; {erase wait time, seconds} max_msg_args = 1; {max arguments we can pass to a message} type cal_k_t = ( {indicates where OSCCAL value came from} cal_back_k, {backup OSCCAL location} cal_last_k, {from last instruction word} cal_def_k); {default value} var lastpgm: picprg_dat_t; {saved last location of program memory} osccal: picprg_dat_t; {saved backup oscillator calibration MOVLW} tk: string_var32_t; cal: cal_k_t; {indicates where OSCCAL value came from} msg_parm: {references arguments passed to a message} array[1..max_msg_args] of sys_parm_msg_t; begin tk.max := size_char(tk.str); picprg_vddlev (pr, picprg_vdd_norm_k, stat); {select normal Vdd} if sys_error(stat) then return; picprg_reset (pr, stat); {reset target to put it into known state} if sys_error(stat) then return; { * Read and save the backup OSCCAL data and the last instruction in memory. * These should both be MOVLW instruction, which are Cxxh. } picprg_read ( {read the last executable location} pr, {state for this use of the library} pr.id_p^.nprog - 1, {address to read} 1, {number of locations to read} pr.id_p^.maskprg, {mask for valid data bits} lastpgm, {returned data} stat); if sys_error(stat) then return; picprg_read ( {read the backup OSCCAL MOVLW instruction} pr, {state for this use of the library} pr.id_p^.nprog + pr.id_p^.ndat + 4, {address to read} 1, {number of locations to read} pr.id_p^.maskprg, {mask for valid data bits} osccal, {returned data} stat); if sys_error(stat) then return; { * Erase with PC at the configuration word. The config word is first set to 0, * which turns on code protection, which causes additional things to get erased * when the config word is erased. Erasing the config word disables code * protection. } { * Write 0 to the config word. } picprg_reset (pr, stat); {put the PC at the config word} if sys_error(stat) then return; picprg_send6 (pr, 2, stat); {LOAD DATA} if sys_error(stat) then return; picprg_send14ss (pr, 0, stat); {0 data word} if sys_error(stat) then return; picprg_send6 (pr, 8, stat); {BEGIN PROGRAMMING} if sys_error(stat) then return; picprg_cmdw_wait (pr, pr.id_p^.tprogp, stat); {wait the programming time} if sys_error(stat) then return; picprg_send6 (pr, 14, stat); {END PROGRAMMING} if sys_error(stat) then return; { * Erase. The PC is currently at the config word. } picprg_send6 (pr, 9, stat); {send BULK ERASE PROGRAM MEMORY command} if sys_error(stat) then return; picprg_cmdw_wait (pr, tera, stat); {insert wait for erase to finish} if sys_error(stat) then return; picprg_reset (pr, stat); {reset target after bulk erase} if sys_error(stat) then return; { * If the backup OSCCAL word was 0, then try reading it again because it might * have been reported as 0 due to code protection, which is now off. Code * protection doesn't actually cover the backup OSCCAL value, but on some PICs * it reads 0 anyway as long as code protection is on. } if osccal = 0 then begin {backup cal 0, could be read protected ?} picprg_read ( {read the backup OSCCAL MOVLW instruction} pr, {state for this use of the library} pr.id_p^.nprog + pr.id_p^.ndat + 4, {address to read} 1, {number of locations to read} pr.id_p^.maskprg, {mask for valid data bits} osccal, {returned data} stat); if sys_error(stat) then return; end; { * Determine what to consider the calibration value, and record where it came * from. Normally this comes from the backup OSCCAL location, but if that is * is not a valid MOVLW instruction (Cxxh), then we try to use what was read * from the last location of program memory. If that is not a valid MOVLW * instruction either, then the stored calibration value for this chip has been * lost, and we substitute the middle value of 0, which results in a MOVLW * instruction of C00h. } cal := cal_back_k; {init to using backup OSCCAL value} if (osccal & 16#F00) <> 16#C00 then begin {backup OSCCAL not MOVLW instruction ?} if (lastpgm & 16#F00) = 16#C00 then begin {last executable location contains MOVLW} osccal := lastpgm; {use value from last executable location} cal := cal_last_k; end else begin {last instruction not MOVLW either} osccal := 16#C00; {pick center value} cal := cal_def_k; end ; end; string_f_int_max_base ( {make HEX value string} tk, osccal, 16, 3, [string_fi_leadz_k, string_fi_unsig_k], stat); if sys_error(stat) then return; sys_msg_parm_vstr (msg_parm[1], tk); case cal of cal_last_k: sys_message_parms ('picprg', 'osccal_last', msg_parm, 1); cal_def_k: sys_message_parms ('picprg', 'osccal_default', msg_parm, 1); otherwise sys_message_parms ('picprg', 'osccal_backup', msg_parm, 1); end; sys_flush_stdout; {make sure all output sent to parent program} { * Erase the user ID locations. This is done with the PC at one of the user * ID locations. } picprg_reset (pr, stat); {reset target to put it into known state} if sys_error(stat) then return; picprg_cmdw_adr ( {set address to first user ID word} pr, {state for this use of the library} pr.id_p^.nprog + pr.id_p^.ndat, {address to set} stat); if sys_error(stat) then return; picprg_send6 (pr, 9, stat); {send BULK ERASE PROGRAM MEMORY command} if sys_error(stat) then return; picprg_cmdw_wait (pr, tera, stat); {insert wait for erase to finish} if sys_error(stat) then return; picprg_reset (pr, stat); if sys_error(stat) then return; { * Erase non-volatile data memory if this chip has any. This is done with the * PC in the non-volatile data space. } if pr.id_p^.ndat > 0 then begin {this chip has non-volatile data memory ?} picprg_reset (pr, stat); {reset target to put it into known state} if sys_error(stat) then return; picprg_cmdw_adr ( {set address to first data memory word} pr, {state for this use of the library} pr.id_p^.nprog, {address to set} stat); if sys_error(stat) then return; picprg_send6 (pr, 9, stat); {send BULK ERASE PROGRAM MEMORY command} if sys_error(stat) then return; picprg_cmdw_wait (pr, tera, stat); {insert wait for erase to finish} if sys_error(stat) then return; picprg_reset (pr, stat); if sys_error(stat) then return; end; { * Restore the backup OSCCAL MOVLW instruction. } picprg_write ( {write the backup OSCCAL MOVLW instruction} pr, {state for this use of the library} pr.id_p^.nprog + pr.id_p^.ndat + 4, {address to write} 1, {number of locations to write} osccal, {the data to write} pr.id_p^.maskprg, {mask for the valid data bits} stat); end;
unit frmOptions; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses //delphi & libs ExtCtrls, Forms, Classes, ComCtrls, StdCtrls, SysUtils, Windows, Graphics, Messages, Controls, Dialogs, //sdu & LibreCrypt utils CommonSettings, OTFEFreeOTFE_U, SDUStdCtrls, MainSettings, SDUFilenameEdit_U, // LibreCrypt forms fmeAutorunOptions, frmCommonOptions, // fmeAdvancedOptions, fmeSystemTrayOptions, // fmeLcOptions, // fmeBaseOptions, fmeVolumeSelect, SDUForms, SDUFrames, Spin64; type TLanguageTranslation = record Name: String; Code: String; Contact: String; end; PLanguageTranslation = ^TLanguageTranslation; TfrmOptions = class (TfrmCommonOptions) tsGeneral: TTabSheet; tsHotkeys: TTabSheet; tcSystemTray: TTabSheet; tsAutorun: TTabSheet; tsAdvanced: TTabSheet; fmeOptions_Autorun1: TfmeAutorunOptions; ckLaunchAtStartup: TSDUCheckBox; ckLaunchMinimisedAtStartup: TSDUCheckBox; gbHotkeys: TGroupBox; Label1: TLabel; Label2: TLabel; hkDismount: THotKey; ckHotkeyDismount: TSDUCheckBox; ckHotkeyDismountEmerg: TSDUCheckBox; hkDismountEmerg: THotKey; gbAdvanced: TGroupBox; lblDragDrop: TLabel; lblMRUMaxItemCountInst: TLabel; lblMRUMaxItemCount: TLabel; lblOnNormalDismountFail: TLabel; lblDefaultMountAs: TLabel; lblOnExitWhenMounted: TLabel; lblOnExitWhenPortableMode: TLabel; ckAllowMultipleInstances: TSDUCheckBox; cbDragDrop: TComboBox; ckAutoStartPortable: TSDUCheckBox; ckAdvancedMountDlg: TSDUCheckBox; ckRevertVolTimestamps: TSDUCheckBox; pnlVertSplit: TPanel; seMRUMaxItemCount: TSpinEdit64; ckWarnBeforeForcedDismount: TSDUCheckBox; cbOnNormalDismountFail: TComboBox; cbDefaultMountAs: TComboBox; cbOnExitWhenMounted: TComboBox; cbOnExitWhenPortableMode: TComboBox; ckAllowNewlinesInPasswords: TSDUCheckBox; ckAllowTabsInPasswords: TSDUCheckBox; gbGeneral: TGroupBox; lblDefaultDriveLetter: TLabel; lblLanguage: TLabel; lblChkUpdatesFreq: TLabel; ckDisplayToolbar: TSDUCheckBox; ckDisplayStatusbar: TSDUCheckBox; ckExploreAfterMount: TSDUCheckBox; Panel1: TPanel; cbDrive: TComboBox; ckShowPasswords: TSDUCheckBox; cbLanguage: TComboBox; pbLangDetails: TButton; ckPromptMountSuccessful: TSDUCheckBox; ckDisplayToolbarLarge: TSDUCheckBox; ckDisplayToolbarCaptions: TSDUCheckBox; cbChkUpdatesFreq: TComboBox; gbSystemTrayIcon: TGroupBox; ckUseSystemTrayIcon: TSDUCheckBox; ckMinToIcon: TSDUCheckBox; ckCloseToIcon: TSDUCheckBox; gbClickActions: TGroupBox; Label3: TLabel; Label4: TLabel; rbSingleClick: TRadioButton; rbDoubleClick: TRadioButton; cbClickAction: TComboBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ckLaunchAtStartupClick(Sender: TObject); procedure ControlChanged(Sender: TObject); procedure cbLanguageChange(Sender: TObject); procedure pbLangDetailsClick(Sender: TObject); private FLanguages: array of TLanguageTranslation; procedure _InitializeHotKeys; procedure _WriteSettingsHotKeys(config: TMainSettings); procedure _ReadSettingsHotKeys(config: TMainSettings); procedure _EnableDisableControlsHotKeys; procedure _InitializeAdvancedTab; procedure _ReadSettingsAdvanced(config: TMainSettings); procedure _WriteSettingsAdvanced(config: TMainSettings); function _LanguageControlLanguage(idx: Integer): TLanguageTranslation; function _SelectedLanguage: TLanguageTranslation; procedure _PopulateLanguages; procedure _SetLanguageSelection(langCode: String); procedure _EnableDisableControlsGeneral; procedure _InitializeGeneral; procedure _ReadSettingsGeneral(config: TMainSettings); procedure _WriteSettingsGeneral(config: TMainSettings); procedure _InitializeSystemTrayOptions; procedure _EnableDisableControlsSystemTray; procedure _ReadSettingsSystemTray(config: TMainSettings); procedure _WriteSettingsSystemTray(config: TMainSettings); procedure _PopulateAndSetClickAction(cbox: TComboBox; selectedAction: TSystemTrayClickAction); function _GetClickAction(cbox: TComboBox): TSystemTrayClickAction; protected FOrigLaunchAtStartup: Boolean; FOrigLaunchMinimisedAtStartup: Boolean; procedure EnableDisableControls(); override; procedure AllTabs_InitAndReadSettings(config: TCommonSettings); override; procedure AllTabs_WriteSettings(config: TCommonSettings); override; function DoOKClicked(): Boolean; override; public procedure ChangeLanguage(langCode: String); override; end; const CONTROL_MARGIN_LBL_TO_CONTROL = 5; implementation {$R *.DFM} uses // delphi Math, ShlObj, // Required for CSIDL_PROGRAMS StrUtils, // sdu /librecrypt OTFEFreeOTFEBase_U, SDUDialogs, SDUGeneral, lcTypes, CommonConsts,lcDialogs, lcConsts, SDUi18n, lcCommandLine // for CMDLINE_MINIMIZE //forms ; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} procedure TfrmOptions._WriteSettingsHotKeys(config: TMainSettings); begin // Hotkeys... config.OptHKeyEnableDismount := ckHotkeyDismount.Checked; config.OptHKeyKeyDismount := hkDismount.HotKey; config.OptHKeyEnableDismountEmerg := ckHotkeyDismountEmerg.Checked; config.OptHKeyKeyDismountEmerg := hkDismountEmerg.HotKey; end; function TfrmOptions._GetClickAction(cbox: TComboBox): TSystemTrayClickAction; var stca: TSystemTrayClickAction; begin Result := stcaDoNothing; // Decode click action... for stca := low(stca) to high(stca) do begin if (SystemTrayClickActionTitle(stca) = cbox.Items[cbox.ItemIndex]) then begin Result := stca; break; end; end; end; procedure TfrmOptions._WriteSettingsSystemTray(config: TMainSettings); begin // System tray icon related... config.OptSystemTrayIconDisplay := ckUseSystemTrayIcon.Checked; config.OptSystemTrayIconMinTo := ckMinToIcon.Checked; config.OptSystemTrayIconCloseTo := ckCloseToIcon.Checked; if rbSingleClick.Checked then begin config.OptSystemTrayIconActionSingleClick := _GetClickAction(cbClickAction); config.OptSystemTrayIconActionDoubleClick := stcaDoNothing; end else begin config.OptSystemTrayIconActionSingleClick := stcaDoNothing; config.OptSystemTrayIconActionDoubleClick := _GetClickAction(cbClickAction); end; end; procedure TfrmOptions._WriteSettingsAdvanced(config: TMainSettings); var owem: eOnExitWhenMounted; owrp: eOnExitWhenPortableMode; ondf: eOnNormalDismountFail; ma: TFreeOTFEMountAs; ft: TVolumeType; begin // Advanced... config.OptAllowMultipleInstances := ckAllowMultipleInstances.Checked; config.OptAutoStartPortable := ckAutoStartPortable.Checked; config.OptAdvancedMountDlg := ckAdvancedMountDlg.Checked; config.OptRevertVolTimestamps := ckRevertVolTimestamps.Checked; config.OptWarnBeforeForcedDismount := ckWarnBeforeForcedDismount.Checked; config.OptAllowNewlinesInPasswords := ckAllowNewlinesInPasswords.Checked; config.OptAllowTabsInPasswords := ckAllowTabsInPasswords.Checked; // Decode action on exiting when volumes mounted config.OptOnExitWhenMounted := oewmPromptUser; for owem := low(owem) to high(owem) do begin if (OnExitWhenMountedTitle(owem) = cbOnExitWhenMounted.Items[cbOnExitWhenMounted.ItemIndex]) then begin config.OptOnExitWhenMounted := owem; break; end; end; // Decode action on exiting when in portable mode config.OptOnExitWhenPortableMode := oewpPromptUser; for owrp := low(owrp) to high(owrp) do begin if (OnExitWhenPortableModeTitle(owrp) = cbOnExitWhenPortableMode.Items[cbOnExitWhenPortableMode.ItemIndex]) then begin config.OptOnExitWhenPortableMode := owrp; break; end; end; // Decode action when normal dismount fails config.OptOnNormalDismountFail := ondfPromptUser; for ondf := low(ondf) to high(ondf) do begin if (OnNormalDismountFailTitle(ondf) = cbOnNormalDismountFail.Items[cbOnNormalDismountFail.ItemIndex]) then begin config.OptOnNormalDismountFail := ondf; break; end; end; // Decode default mount type config.OptDefaultMountAs := fomaRemovableDisk; for ma := low(ma) to high(ma) do begin if (FreeOTFEMountAsTitle(ma) = cbDefaultMountAs.Items[cbDefaultMountAs.ItemIndex]) then begin config.OptDefaultMountAs := ma; break; end; end; // Decode drag drop filetype config.OptDragDropFileType := vtUnknown; for ft := low(ft) to high(ft) do begin if (DragDropFileTypeTitle(ft) = cbDragDrop.Items[cbDragDrop.ItemIndex]) then begin config.OptDragDropFileType := ft; break; end; end; config.OptMRUList.MaxItems := seMRUMaxItemCount.Value; end; procedure TfrmOptions.AllTabs_WriteSettings(config: TCommonSettings); begin inherited; _WriteSettingsGeneral(config as TMainSettings); _WriteSettingsHotKeys(config as TMainSettings); fmeOptions_Autorun1.WriteSettings(config); _WriteSettingsAdvanced(config as TMainSettings); _WriteSettingsSystemTray(config as TMainSettings); end; function TfrmOptions._SelectedLanguage(): TLanguageTranslation; begin Result := _LanguageControlLanguage(cbLanguage.ItemIndex); end; procedure TfrmOptions._PopulateLanguages(); var i: Integer; origLangCode: String; langCodes: TStringList; sortedList: TStringList; begin // Store language information for later use... langCodes := TStringList.Create(); try // Get all language codes... SDUGetLanguageCodes(langCodes); // +1 to include "Default" SetLength(FLanguages, langCodes.Count); // Spin though the languages, getting their corresponding human-readable // names origLangCode := SDUGetCurrentLanguageCode(); try for i := 0 to (langCodes.Count - 1) do begin SDUSetLanguage(langCodes[i]); FLanguages[i].Code := langCodes[i]; FLanguages[i].Name := _(CONST_LANGUAGE_ENGLISH); FLanguages[i].Contact := SDUGetTranslatorNameAndEmail(); // Force set contact details for English version; the dxgettext software sets // this to some stupid default if (langCodes[i] = ISO639_ALPHA2_ENGLISH) then begin FLanguages[i].Contact := ENGLISH_TRANSLATION_CONTACT; end; end; finally // Flip back to original language... SDUSetLanguage(origLangCode); end; finally langCodes.Free(); end; // Add "default" into the list SetLength(FLanguages, (length(FLanguages) + 1)); FLanguages[length(FLanguages) - 1].Code := ''; FLanguages[length(FLanguages) - 1].Name := _('(Default)'); FLanguages[length(FLanguages) - 1].Contact := ''; // Populate list sortedList := TStringList.Create(); try for i := 0 to (length(FLanguages) - 1) do begin sortedList.AddObject(FLanguages[i].Name, @(FLanguages[i])); end; sortedList.Sorted := True; sortedList.Sorted := False; cbLanguage.Items.Assign(sortedList) finally sortedList.Free(); end; end; procedure TfrmOptions._SetLanguageSelection(langCode: String); var useIdx: Integer; currLang: TLanguageTranslation; i: Integer; begin useIdx := 0; for i := 0 to (cbLanguage.items.Count - 1) do begin currLang := _LanguageControlLanguage(i); if (currLang.Code = langCode) then begin useIdx := i; break; end; end; cbLanguage.ItemIndex := useIdx; end; function TfrmOptions._LanguageControlLanguage(idx: Integer): TLanguageTranslation; begin Result := (PLanguageTranslation(cbLanguage.Items.Objects[idx]))^; end; procedure TfrmOptions.pbLangDetailsClick(Sender: TObject); var rcdLanguage: TLanguageTranslation; begin inherited; rcdLanguage := _SelectedLanguage(); SDUMessageDlg( Format(_('Language name: %s'), [rcdLanguage.Name]) + SDUCRLF + Format(_('Language code: %s'), [rcdLanguage.Code]) + SDUCRLF + Format(_('Translator: %s'), [rcdLanguage.Contact]) ); end; procedure TfrmOptions.cbLanguageChange(Sender: TObject); var useLang: TLanguageTranslation; langIdx: Integer; begin inherited; // Preserve selected language; the selected language gets change by the // PopulateLanguages() call langIdx := cbLanguage.ItemIndex; useLang := _SelectedLanguage(); TfrmCommonOptions(Owner).ChangeLanguage(useLang.Code); // Repopulate the languages list; translation would have translated them all _PopulateLanguages(); // Restore selected cbLanguage.ItemIndex := langIdx; EnableDisableControls(); end; procedure TfrmOptions.ChangeLanguage(langCode: String); var tmpConfig: TMainSettings; begin tmpConfig := TMainSettings.Create(); try tmpConfig.Assign(GetSettings()); AllTabs_WriteSettings(tmpConfig); SDUSetLanguage(langCode); try SDURetranslateComponent(self); except on E: Exception do begin SDUTranslateComponent(self); end; end; AllTabs_InitAndReadSettings(tmpConfig); finally tmpConfig.Free(); end; // Call EnableDisableControls() as this re-jigs the "Save above settings to:" // label EnableDisableControls(); end; procedure TfrmOptions.ckLaunchAtStartupClick(Sender: TObject); begin inherited; EnableDisableControls(); end; procedure TfrmOptions.ControlChanged(Sender: TObject); begin inherited; EnableDisableControls(); end; procedure TfrmOptions.FormCreate(Sender: TObject); begin inherited; // Set active page to the first one pcOptions.ActivePage := tsGeneral; end; procedure TfrmOptions.FormShow(Sender: TObject); begin inherited; FOrigLaunchAtStartup := SDUDoesShortcutExist(SDU_CSIDL_STARTUP, Application.Title); ckLaunchAtStartup.Checked := FOrigLaunchAtStartup; FOrigLaunchMinimisedAtStartup := False; if FOrigLaunchAtStartup then FOrigLaunchMinimisedAtStartup := AnsiContainsStr(SDUGetShortCutArguments(SDU_CSIDL_STARTUP, Application.Title), CMDLINE_MINIMIZE); ckLaunchMinimisedAtStartup.Checked := FOrigLaunchMinimisedAtStartup; // Push the "Advanced" tab to the far end; even after the "PKCS#11" tab tsAdvanced.PageIndex := (pcOptions.PageCount - 1); end; procedure TfrmOptions._EnableDisableControlsHotKeys(); begin inherited; SDUEnableControl(hkDismount, ckHotkeyDismount.Checked); SDUEnableControl(hkDismountEmerg, ckHotkeyDismountEmerg.Checked); end; procedure TfrmOptions._EnableDisableControlsSystemTray(); begin inherited; SDUEnableControl(ckMinToIcon, ckUseSystemTrayIcon.Checked); SDUEnableControl(ckCloseToIcon, ckUseSystemTrayIcon.Checked); SDUEnableControl(gbClickActions, ckUseSystemTrayIcon.Checked); end; procedure TfrmOptions._EnableDisableControlsGeneral(); begin inherited; // Language at index 0 is "(Default)" SDUEnableControl(pbLangDetails, (cbLanguage.ItemIndex > 0)); SDUEnableControl(ckDisplayToolbarLarge, ckDisplayToolbar.Checked); SDUEnableControl(ckDisplayToolbarCaptions, (ckDisplayToolbar.Checked and ckDisplayToolbarLarge.Checked)); // Only allow captions if the user has selected large icons if not (ckDisplayToolbarLarge.Checked) then begin ckDisplayToolbarCaptions.Checked := False; end; end; procedure TfrmOptions.EnableDisableControls(); begin inherited; _EnableDisableControlsHotKeys; _EnableDisableControlsGeneral; _EnableDisableControlsSystemTray; SDUEnableControl(ckLaunchMinimisedAtStartup, ckLaunchAtStartup.Checked); if not (ckLaunchMinimisedAtStartup.Enabled) then ckLaunchMinimisedAtStartup.Checked := False; end; procedure TfrmOptions._PopulateAndSetClickAction(cbox: TComboBox; selectedAction: TSystemTrayClickAction); var stca: TSystemTrayClickAction; idx: Integer; useIdx: Integer; begin // Populate and set default store op dropdown cbox.Items.Clear(); idx := -1; useIdx := -1; for stca := low(stca) to high(stca) do begin Inc(idx); cbox.Items.Add(SystemTrayClickActionTitle(stca)); if (selectedAction = stca) then begin useIdx := idx; end; end; cbox.ItemIndex := useIdx; end; procedure TfrmOptions._InitializeAdvancedTab(); const // Vertical spacing between checkboxes, and min horizontal spacing between // checkbox label and the vertical separator line // Set to 6 for now as that looks reasonable. 10 is excessive, 5 is a bit // cramped CHKBOX_CONTROL_MARGIN = 6; // Min horizontal spacing between label and control to the right of it LABEL_CONTROL_MARGIN = 10; // This adjusts the width of a checkbox, and resets it caption so it // autosizes. If it autosizes such that it's too wide, it'll drop the width // and repeat procedure NudgeCheckbox(chkBox: TCheckBox); var tmpCaption: String; maxWidth: Integer; useWidth: Integer; lastTriedWidth: Integer; begin tmpCaption := chkBox.Caption; maxWidth := (pnlVertSplit.left - CHKBOX_CONTROL_MARGIN) - chkBox.Left; useWidth := maxWidth; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; while ((chkBox.Width > maxWidth) and (lastTriedWidth > 0)) do begin // 5 used here; just needs to be something sensible to reduce the // width by; 1 would do pretty much just as well useWidth := useWidth - 5; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; end; end; procedure NudgeFocusControl(lbl: TLabel); begin if (lbl.FocusControl <> nil) then begin lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL; end; end; procedure NudgeLabel(lbl: TLabel); var maxWidth: Integer; begin if (pnlVertSplit.left > lbl.left) then begin maxWidth := (pnlVertSplit.left - LABEL_CONTROL_MARGIN) - lbl.left; end else begin maxWidth := (lbl.Parent.Width - LABEL_CONTROL_MARGIN) - lbl.left; end; lbl.Width := maxWidth; end; var stlChkBoxOrder: TStringList; YPos: Integer; i: Integer; currChkBox: TCheckBox; groupboxMargin: Integer; begin inherited; SDUCenterControl(gbAdvanced, ccHorizontal); SDUCenterControl(gbAdvanced, ccVertical, 25); // Re-jig label size to take cater for differences in translation lengths // Size so the max. right is flush with the max right of pbLangDetails // lblDragDrop.width := (pbLangDetails.left + pbLangDetails.width) - lblDragDrop.left; // lblMRUMaxItemCount.width := (pbLangDetails.left + pbLangDetails.width) - lblMRUMaxItemCount.left; groupboxMargin := ckAutoStartPortable.left; lblDragDrop.Width := (gbAdvanced.Width - groupboxMargin) - lblDragDrop.left; lblMRUMaxItemCount.Width := (gbAdvanced.Width - groupboxMargin) - lblMRUMaxItemCount.left; pnlVertSplit.Caption := ''; pnlVertSplit.bevelouter := bvLowered; pnlVertSplit.Width := 3; // Here we re-jig the checkboxes so that they are nicely spaced vertically. // This is needed as some language translation require the checkboxes to have // more than one line of text // // !! IMPORTANT !! // When adding a checkbox: // 1) Add it to stlChkBoxOrder below (doesn't matter in which order these // are added) // 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi // TCheckBox // 3) Make sure it's autosize property is TRUE // stlChkBoxOrder := TStringList.Create(); try // stlChkBoxOrder is used to order the checkboxes in their vertical order; // this allows checkboxes to be added into the list below in *any* order, // and it'll still work stlChkBoxOrder.Sorted := True; stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowMultipleInstances.Top]), ckAllowMultipleInstances); stlChkBoxOrder.AddObject(Format('%.5d', [ckAutoStartPortable.Top]), ckAutoStartPortable); stlChkBoxOrder.AddObject(Format('%.5d', [ckAdvancedMountDlg.Top]), ckAdvancedMountDlg); stlChkBoxOrder.AddObject(Format('%.5d', [ckRevertVolTimestamps.Top]), ckRevertVolTimestamps); stlChkBoxOrder.AddObject(Format('%.5d', [ckWarnBeforeForcedDismount.Top]), ckWarnBeforeForcedDismount); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowNewlinesInPasswords.Top]), ckAllowNewlinesInPasswords); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowTabsInPasswords.Top]), ckAllowTabsInPasswords); currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; for i := 1 to (stlChkBoxOrder.Count - 1) do begin currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]); currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN; // Sort out the checkbox's height NudgeCheckbox(currChkBox); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; end; finally stlChkBoxOrder.Free(); end; // Nudge labels so they're as wide as can be allowed NudgeLabel(lblOnExitWhenMounted); NudgeLabel(lblOnExitWhenPortableMode); NudgeLabel(lblOnNormalDismountFail); NudgeLabel(lblDragDrop); NudgeLabel(lblMRUMaxItemCount); NudgeLabel(lblMRUMaxItemCountInst); NudgeLabel(lblDefaultMountAs); // Here we move controls associated with labels, such that they appear // underneath the label // NudgeFocusControl(lblLanguage); NudgeFocusControl(lblDragDrop); // NudgeFocusControl(lblDefaultDriveLetter); // NudgeFocusControl(lblMRUMaxItemCount); end; procedure TfrmOptions._InitializeHotKeys(); var maxCkBoxWidth: Integer; begin // ckHotkeyDismount and ckHotkeyDismountEmerg have AutoSize := TRUE // Use the autosized controls to determine how big the groupbox needs to be maxCkBoxWidth := max(ckHotkeyDismount.Width, ckHotkeyDismountEmerg.Width); gbHotkeys.Width := max(((ckHotkeyDismount.left * 2) + maxCkBoxWidth), max( (hkDismount.left + hkDismount.Width + ckHotkeyDismount.left), (hkDismountEmerg.left + hkDismountEmerg.Width + ckHotkeyDismount.left))); SDUCenterControl(gbHotkeys, ccHorizontal); SDUCenterControl(gbHotkeys, ccVertical, 25); end; procedure TfrmOptions._InitializeSystemTrayOptions(); var maxToIconCkBoxWidth: Integer; maxgbWidth: Integer; begin // ckHotkeyDismount and ckHotkeyDismountEmerg have AutoSize := TRUE // Use the autosized controls to determine how big the groupbox needs to be maxToIconCkBoxWidth := max(ckMinToIcon.Width, ckCloseToIcon.Width); maxgbWidth := 0; maxgbWidth := max(maxgbWidth, (ckUseSystemTrayIcon.left * 2) + ckUseSystemTrayIcon.Width); maxgbWidth := max(maxgbWidth, (ckMinToIcon.left + maxToIconCkBoxWidth + ckUseSystemTrayIcon.left)); maxgbWidth := max(maxgbWidth, (gbClickActions.left + gbClickActions.Width + ckUseSystemTrayIcon.left)); gbSystemTrayIcon.Width := maxgbWidth; SDUCenterControl(gbSystemTrayIcon, ccHorizontal); SDUCenterControl(gbSystemTrayIcon, ccVertical, 25); end; procedure TfrmOptions._InitializeGeneral(); const // Vertical spacing between checkboxes, and min horizontal spacing between // checkbox label and the vertical separator line // Set to 6 for now as that looks reasonable. 10 is excessive, 5 is a bit // cramped CHKBOX_CONTROL_MARGIN = 6; // This adjusts the width of a checkbox, and resets it caption so it // autosizes. If it autosizes such that it's too wide, it'll drop the width // and repeat procedure NudgeCheckbox(chkBox: TCheckBox); var tmpCaption: String; maxWidth: Integer; useWidth: Integer; lastTriedWidth: Integer; begin tmpCaption := chkBox.Caption; maxWidth := (pnlVertSplit.left - CHKBOX_CONTROL_MARGIN) - chkBox.Left; useWidth := maxWidth; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; while ((chkBox.Width > maxWidth) and (lastTriedWidth > 0)) do begin // 5 used here; just needs to be something sensible to reduce the // width by; 1 would do pretty much just as well useWidth := useWidth - 5; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; end; end; procedure NudgeFocusControl(lbl: TLabel); begin if (lbl.FocusControl <> nil) then begin lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL; end; end; var driveLetter: Char; stlChkBoxOrder: TStringList; YPos: Integer; i: Integer; currChkBox: TCheckBox; begin inherited; SDUCenterControl(gbGeneral, ccHorizontal); SDUCenterControl(gbGeneral, ccVertical, 25); pnlVertSplit.Caption := ''; pnlVertSplit.bevelouter := bvLowered; pnlVertSplit.Width := 3; _PopulateLanguages(); cbDrive.Items.Clear(); cbDrive.Items.Add(USE_DEFAULT); // for driveLetter:='C' to 'Z' do for driveLetter := 'A' to 'Z' do begin cbDrive.Items.Add(driveLetter + ':'); end; // Here we re-jig the checkboxes so that they are nicely spaced vertically. // This is needed as some language translation require the checkboxes to have // more than one line of text // // !! IMPORTANT !! // When adding a checkbox: // 1) Add it to stlChkBoxOrder below (doesn't matter in which order these // are added) // 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi // TCheckBox // 3) Make sure it's autosize property is TRUE // stlChkBoxOrder := TStringList.Create(); try // stlChkBoxOrder is used to order the checkboxes in their vertical order; // this allows checkboxes to be added into the list below in *any* order, // and it'll still work stlChkBoxOrder.Sorted := True; stlChkBoxOrder.AddObject(Format('%.5d', [ckExploreAfterMount.Top]), ckExploreAfterMount); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbar.Top]), ckDisplayToolbar); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarLarge.Top]), ckDisplayToolbarLarge); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarCaptions.Top]), ckDisplayToolbarCaptions); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayStatusbar.Top]), ckDisplayStatusbar); stlChkBoxOrder.AddObject(Format('%.5d', [ckShowPasswords.Top]), ckShowPasswords); stlChkBoxOrder.AddObject(Format('%.5d', [ckPromptMountSuccessful.Top]), ckPromptMountSuccessful); currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; for i := 1 to (stlChkBoxOrder.Count - 1) do begin currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]); if currChkBox.Visible then begin currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN; // Sort out the checkbox's height NudgeCheckbox(currChkBox); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; end; end; finally stlChkBoxOrder.Free(); end; // Here we move controls associated with labels, such that they appear // underneath the label // NudgeFocusControl(lblLanguage); // NudgeFocusControl(lblDefaultDriveLetter); // NudgeFocusControl(lblMRUMaxItemCount); end; procedure TfrmOptions._ReadSettingsHotKeys(config: TMainSettings); begin // Hotkeys... ckHotkeyDismount.Checked := config.OptHKeyEnableDismount; hkDismount.HotKey := config.OptHKeyKeyDismount; ckHotkeyDismountEmerg.Checked := config.OptHKeyEnableDismountEmerg; hkDismountEmerg.HotKey := config.OptHKeyKeyDismountEmerg; end; procedure TfrmOptions._ReadSettingsSystemTray(config: TMainSettings); begin // System tray icon related... ckUseSystemTrayIcon.Checked := config.OptSystemTrayIconDisplay; ckMinToIcon.Checked := config.OptSystemTrayIconMinTo; ckCloseToIcon.Checked := config.OptSystemTrayIconCloseTo; if (config.OptSystemTrayIconActionSingleClick <> stcaDoNothing) then begin rbSingleClick.Checked := True; _PopulateAndSetClickAction(cbClickAction, config.OptSystemTrayIconActionSingleClick); end else begin rbDoubleClick.Checked := True; _PopulateAndSetClickAction(cbClickAction, config.OptSystemTrayIconActionDoubleClick); end; end; procedure TfrmOptions._ReadSettingsGeneral(config: TMainSettings); var uf: TUpdateFrequency; idx: Integer; useIdx: Integer; begin // General... ckExploreAfterMount.Checked := config.OptExploreAfterMount; ckDisplayToolbar.Checked := config.OptDisplayToolbar; ckDisplayToolbarLarge.Checked := config.OptDisplayToolbarLarge; ckDisplayToolbarCaptions.Checked := config.OptDisplayToolbarCaptions; ckDisplayStatusbar.Checked := config.OptDisplayStatusbar; ckShowPasswords.Checked := config.OptShowPasswords; ckPromptMountSuccessful.Checked := config.OptPromptMountSuccessful; // In case language code not found; reset to "(Default)" entry; at index 0 _SetLanguageSelection(config.OptLanguageCode); // Default drive letter if (config.OptDefaultDriveLetter = #0) then begin cbDrive.ItemIndex := 0; end else begin cbDrive.ItemIndex := cbDrive.Items.IndexOf(config.OptDefaultDriveLetter + ':'); end; // Populate and set update frequency dropdown cbChkUpdatesFreq.Items.Clear(); idx := -1; useIdx := -1; for uf := low(uf) to high(uf) do begin Inc(idx); cbChkUpdatesFreq.Items.Add(UpdateFrequencyTitle(uf)); if (config.OptUpdateChkFrequency = uf) then begin useIdx := idx; end; end; cbChkUpdatesFreq.ItemIndex := useIdx; end; procedure TfrmOptions._WriteSettingsGeneral(config: TMainSettings); var uf: TUpdateFrequency; useLang: TLanguageTranslation; begin // General... config.OptExploreAfterMount := ckExploreAfterMount.Checked; config.OptDisplayToolbar := ckDisplayToolbar.Checked; config.OptDisplayToolbarLarge := ckDisplayToolbarLarge.Checked; config.OptDisplayToolbarCaptions := ckDisplayToolbarCaptions.Checked; config.OptDisplayStatusbar := ckDisplayStatusbar.Checked; config.OptShowPasswords := ckShowPasswords.Checked; config.OptPromptMountSuccessful := ckPromptMountSuccessful.Checked; useLang := _SelectedLanguage(); config.OptLanguageCode := useLang.Code; // Default drive letter if (cbDrive.ItemIndex = 0) then begin config.OptDefaultDriveLetter := #0; end else begin config.OptDefaultDriveLetter := DriveLetterChar(cbDrive.Items[cbDrive.ItemIndex][1]); end; // Decode update frequency config.OptUpdateChkFrequency := ufNever; for uf := low(uf) to high(uf) do begin if (UpdateFrequencyTitle(uf) = cbChkUpdatesFreq.Items[cbChkUpdatesFreq.ItemIndex]) then begin config.OptUpdateChkFrequency := uf; break; end; end; end; procedure TfrmOptions._ReadSettingsAdvanced(config: TMainSettings); var owem: eOnExitWhenMounted; owrp: eOnExitWhenPortableMode; ondf: eOnNormalDismountFail; ma: TFreeOTFEMountAs; ft: TVolumeType; idx: Integer; useIdx: Integer; begin // Advanced... ckAllowMultipleInstances.Checked := config.OptAllowMultipleInstances; ckAutoStartPortable.Checked := config.OptAutoStartPortable; ckAdvancedMountDlg.Checked := config.OptAdvancedMountDlg; ckRevertVolTimestamps.Checked := config.OptRevertVolTimestamps; ckWarnBeforeForcedDismount.Checked := config.OptWarnBeforeForcedDismount; ckAllowNewlinesInPasswords.Checked := config.OptAllowNewlinesInPasswords; ckAllowTabsInPasswords.Checked := config.OptAllowTabsInPasswords; // Populate and set action on exiting when volumes mounted cbOnExitWhenMounted.Items.Clear(); idx := -1; useIdx := -1; for owem := low(owem) to high(owem) do begin Inc(idx); cbOnExitWhenMounted.Items.Add(OnExitWhenMountedTitle(owem)); if (config.OptOnExitWhenMounted = owem) then begin useIdx := idx; end; end; cbOnExitWhenMounted.ItemIndex := useIdx; // Populate and set action on exiting when in portable mode cbOnExitWhenPortableMode.Items.Clear(); idx := -1; useIdx := -1; for owrp := low(owrp) to high(owrp) do begin Inc(idx); cbOnExitWhenPortableMode.Items.Add(OnExitWhenPortableModeTitle(owrp)); if (config.OptOnExitWhenPortableMode = owrp) then begin useIdx := idx; end; end; cbOnExitWhenPortableMode.ItemIndex := useIdx; // Populate and set action when normal dismount fails cbOnNormalDismountFail.Items.Clear(); idx := -1; useIdx := -1; for ondf := low(ondf) to high(ondf) do begin Inc(idx); cbOnNormalDismountFail.Items.Add(OnNormalDismountFailTitle(ondf)); if (config.OptOnNormalDismountFail = ondf) then begin useIdx := idx; end; end; cbOnNormalDismountFail.ItemIndex := useIdx; // Populate and set default mount type cbDefaultMountAs.Items.Clear(); idx := -1; useIdx := -1; for ma := low(ma) to high(ma) do begin if (ma = fomaUnknown) then begin continue; end; Inc(idx); cbDefaultMountAs.Items.Add(FreeOTFEMountAsTitle(ma)); if (config.OptDefaultMountAs = ma) then begin useIdx := idx; end; end; cbDefaultMountAs.ItemIndex := useIdx; // Populate and set drag drop filetype dropdown cbDragDrop.Items.Clear(); idx := -1; for ft := low(ft) to high(ft) do begin //only add types that can't be deected - ie not luks if ft in sDragDropFileType then begin Inc(idx); cbDragDrop.Items.Add(DragDropFileTypeTitle(ft)); if (config.OptDragDropFileType = ft) then begin cbDragDrop.ItemIndex := idx; end; end; end; seMRUMaxItemCount.Value := config.OptMRUList.MaxItems; end; procedure TfrmOptions.AllTabs_InitAndReadSettings(config: TCommonSettings); //var // ckboxIndent: Integer; // maxCBoxWidth: Integer; begin inherited; ckLaunchAtStartup.Caption := Format(_('Start %s at system startup'), [Application.Title]); _InitializeGeneral; _ReadSettingsGeneral(config as TMainSettings); _InitializeHotKeys(); _ReadSettingsHotKeys(config as TMainSettings); fmeOptions_Autorun1.Initialize; fmeOptions_Autorun1.ReadSettings(config); _InitializeAdvancedTab; _ReadSettingsAdvanced(config as TMainSettings); _InitializeSystemTrayOptions(); _ReadSettingsSystemTray(config as TMainSettings); // ckboxIndent := ckLaunchMinimisedAtStartup.left - ckLaunchAtStartup.left; // maxCBoxWidth := max(ckAssociateFiles.Width, ckLaunchAtStartup.Width); // // ckAssociateFiles.Left := ((self.Width - maxCBoxWidth) div 2); // ckLaunchAtStartup.Left := ckAssociateFiles.Left; // ckLaunchMinimisedAtStartup.left := ckLaunchAtStartup.left + ckboxIndent; EnableDisableControls(); end; function TfrmOptions.DoOKClicked(): Boolean; var minimisedParam: String; begin Result := inherited DoOKClicked(); if Result then begin if ((ckLaunchAtStartup.Checked <> FOrigLaunchAtStartup) or (ckLaunchMinimisedAtStartup.Checked <> FOrigLaunchMinimisedAtStartup)) then begin // Purge any existing shortcut... SDUDeleteShortcut( SDU_CSIDL_STARTUP, Application.Title ); // ...and recreate if necessary if ckLaunchAtStartup.Checked then begin minimisedParam := Ifthen(ckLaunchMinimisedAtStartup.Checked, '/' + CMDLINE_MINIMIZE, ''); SDUCreateShortcut( SDU_CSIDL_STARTUP, Application.Title, ParamStr(0), minimisedParam, '', // ShortcutKey: TShortCut; - not yet implemented wsNormal, // for some reason wsMinimized doesnt work here - makes app hang. so use 'minimise' flag instead '' ); end; FOrigAssociateFiles := ckAssociateFiles.Checked; end; end; end; end.
unit ApplPro; interface uses Dos, App,Drivers,Memory,Dialogs, {$IFDEF ExeHelp} ExeStrm, {$ENDIF} HelpFile,StdDlg,Gadgets,Objects,Menus,MsgBox,Views; const cmHelp = 9100; cmHelpContents = 9101; cmHelpOnHelp = 9102; cmPreviousTopic = 9103; cmNextTopic = 9104; cmSwitchToTopic = 9109; hcHelp = 0; hcHelpWindow = 11111; { Popup help's HelpCtx (for status line) } hcContents = 0; hcHelpIntro = 1; hcHelpOnHelp = 2; hcUsingHelp = 3; hcPreviousTopic = 5; hcNextTopic = 6; PreviousTopic = $EEEE; { MaxOldTopics = 16;} type PApplPro=^TApplPro; TApplPro=object(TApplication) ExeFileName : PathStr; HelpFileName : PathStr; HelpInUse : Boolean; constructor Init; procedure Idle;virtual; procedure GetEvent(var Event:TEvent); virtual; function GetPalette:PPalette; virtual; function ExeDir:PathStr; procedure ShowHelp(aHelpCtx:word); end; function StdStatusHelp(Next:PStatusDef):PStatusDef; implementation var Heap:PHeapView; Clock:PClockView; function StdStatusHelp(Next:PStatusDef):PStatusDef; begin StdStatusHelp:= NewStatusDef(hcHelpWindow, hcHelpWindow, StdStatusKeys( NewStatusKey('~F1~ Help on Help', kbF1, cmHelpOnHelp, NewStatusKey('~Alt+B~ Back', kbAltB, cmPreviousTopic, NewStatusKey('~Alt+C~ Contents', kbAltC, cmHelpContents, NewStatusKey('~F5~ Zoom', kbF5, cmZoom, NewStatusKey('~Esc~ Close help', kbEsc, cmClose, Nil)))))), Next); end; function AddBackslash(const s:String):String; begin if (s<>'') and not (s[Length(s)] in ['\',':']) then AddBackslash:=s+'\' else AddBackslash:=s; end; constructor TApplPro.Init; var R:TRect; begin Inherited Init; GetExtent(R); R.A.X:= R.B.X-9; R.A.Y:= R.B.Y-1; Heap:=New(PHeapView,Init(R)); Insert(Heap); GetExtent(R); R.A.X:=R.B.X-9; R.B.Y:=R.A.Y+1; Clock:=New(PClockView,Init(R)); Insert(Clock); RegisterHelpFile; end; procedure TApplPro.Idle; var E:TEvent; begin Inherited Idle; Heap^.Update; Clock^.Update; end; procedure TApplPro.GetEvent; begin inherited GetEvent(Event); if Event.What=evCommand then begin case Event.Command of (* The usual TV help command *) cmHelp: ShowHelp(GetHelpCtx); (* These are status line commands and must reside in GetEvent, else won't work inside (modal) Help *) cmPreviousTopic: ShowHelp(PreviousTopic); cmHelpContents: ShowHelp(hcContents); cmHelpOnHelp: ShowHelp(hcHelpOnHelp); else Exit; end; ClearEvent(Event); end; end; function TApplPro.ExeDir:PathStr; var EXEName : PathStr; Dir : DirStr; Name : NameStr; Ext : ExtStr; begin if Lo(DosVersion)>=3 then EXEName:=ParamStr(0) else EXEName:=FSearch(ExeFileName, GetEnv('PATH')); FSplit(EXEName, Dir, Name, Ext); ExeDir:=AddBackslash(Dir); end; function TApplPro.GetPalette; const CNewColor = CAppColor + CHelpColor; CNewBlackWhite = CAppBlackWhite + CHelpBlackWhite; CNewMonochrome = CAppMonochrome + CHelpMonochrome; P : array [apColor..apMonochrome] of String[Length(CNewColor)] = (CNewColor, CNewBlackWhite, CNewMonochrome); begin GetPalette := PPalette(@P[AppPalette]); end; procedure TApplPro.ShowHelp; var W : PWindow; HFile : PHelpFile; HelpStrm : PDosStream; Event : TEvent; begin { HelpInUse moved into the Application object } if HelpInUse then begin Event.What:=evCommand; Event.Command:=cmSwitchToTopic; Event.InfoWord:=aHelpCtx; PutEvent(Event); end else begin HelpInUse:=True; {$IFDEF ExeHelp} HelpStrm:=New(PExeScanningStream, Init(ParamStr(0), stOpenRead, magicHelpFile)); {$ELSE} New(HelpStrm, Init(FSearch(HelpFileName, ExeDir), stOpenRead)); {$ENDIF} New(HFile, Init(HelpStrm)); if HelpStrm^.Status<>stOk then begin MessageBox(^C'Could not open help file', Nil, mfError+mfOkButton); Dispose(HFile, Done); end else begin W:=New(PHelpWindow, Init(HFile, aHelpCtx)); if ValidView(W)<>Nil then begin W^.HelpCtx:=hcHelpWindow; Application^.ExecView(W); Dispose(W, Done); end; end; HelpInUse:=False; end; end; end.
unit TemplateStore; {$IFDEF LINUX}{$INCLUDE ../FLXCOMPILER.INC}{$ELSE}{$INCLUDE ..\FLXCOMPILER.INC}{$ENDIF} interface {$R XlsTemplateStore.res} uses SysUtils, Classes, XlsMessages, UFlxMessages, XlsBaseTemplateStore, contnrs; type TXlsTemplate= class (TCollectionItem) private FFileName: TFileName; FCompress: boolean; FStorages: TXlsStorageList; FModifiedDate: TDateTime; procedure SetFileName(const Value: TFileName); procedure SetCompress(const Value: boolean); property Compress: boolean read FCompress write SetCompress; protected function GetDisplayName: string; override; procedure SetDisplayName(const Value: string); override; procedure WriteData(Stream: TStream); procedure ReadData(Stream: TStream); procedure WriteModifiedDate(Writer: TWriter); procedure ReadModifiedDate(Reader: TReader); procedure DefineProperties(Filer: TFiler); override; function Equal(aTemplate: TXlsTemplate): Boolean; public property Storages: TXlsStorageList read FStorages; constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure SaveAs(const aFileName: TFileName); property ModifiedDate: TDateTime read FModifiedDate; published property FileName: TFileName read FFileName write SetFileName stored false; end; TXlsTemplateList=class(TOwnedCollection) //Items are TXlsTemplate private FCompress: boolean; procedure SetCompress(const Value: boolean); property Compress: boolean read FCompress write SetCompress; function GetItems(Index: integer): TXlsTemplate; public property Items[Index: integer]: TXlsTemplate read GetItems; default; end; TXlsTemplateStore = class(TXlsBaseTemplateStore) private FCompress: boolean; FRefreshPath: string; procedure SetCompress(const Value: boolean); { Private declarations } protected FTemplates: TXlsTemplateList; function GetStorages(Name: String): TXlsStorageList; override; { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy;override; function IsUpToDate: boolean;override; procedure Refresh;override; published { Published declarations } property Templates: TXlsTemplateList read FTemplates write FTemplates; property Compress: boolean read FCompress write SetCompress; property RefreshPath: string read FRefreshPath write FRefreshPath; //PENDING:AssignTo end; procedure Register; implementation procedure Register; begin RegisterComponents('FlexCel', [TXlsTemplateStore]); end; { TXlsTemplate } constructor TXlsTemplate.Create(Collection: TCollection); begin inherited; FStorages:=TXlsStorageList.Create; end; procedure TXlsTemplate.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin if Filer.Ancestor <> nil then Result := not (Filer.Ancestor is TXlsTemplate) or not Equal(TXlsTemplate(Filer.Ancestor)) else Result := FFileName<>''; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('TemplateData', ReadData, WriteData, DoWrite); Filer.DefineProperty('ModifiedDate', ReadModifiedDate, WriteModifiedDate, DoWrite); end; destructor TXlsTemplate.Destroy; begin FreeAndNil(FStorages); inherited; end; function TXlsTemplate.Equal(aTemplate: TXlsTemplate): Boolean; begin Result:=FFileName=aTemplate.FFileName; end; function TXlsTemplate.GetDisplayName: string; begin Result:=FFileName; end; procedure TXlsTemplate.ReadData(Stream: TStream); var Version: SmallInt; Ln: integer; begin Stream.ReadBuffer(Version, SizeOf(Version)); Stream.ReadBuffer(Ln, SizeOF(Ln)); SetLength(FFileName, Ln); Stream.ReadBuffer(FFileName[1], Ln); FStorages.ReadData(Stream); end; procedure TXlsTemplate.ReadModifiedDate(Reader: TReader); begin FModifiedDate:=Reader.ReadDate; end; procedure TXlsTemplate.SaveAs(const aFileName: TFileName); begin FStorages.SaveAs(aFileName); end; procedure TXlsTemplate.SetCompress(const Value: boolean); var i:integer; begin FCompress := Value; for i:=0 to FStorages.Count-1 do FStorages[i].Compress:=Value; end; procedure TXlsTemplate.SetDisplayName(const Value: string); begin inherited; FileName:=Value; end; procedure TXlsTemplate.SetFileName(const Value: TFileName); begin FStorages.LoadFrom(Value); FFileName := ExtractFileName(Value); FModifiedDate:=FileDateToDateTime(FileAge(Value)); end; procedure TXlsTemplate.WriteData(Stream: TStream); var Version: SmallInt; Ln: integer; begin Version:=1; Stream.WriteBuffer(Version,SizeOf(Version)); Ln:=Length(FFileName); Stream.WriteBuffer(Ln, SizeOf(Ln)); Stream.WriteBuffer(FFileName[1], Ln); FStorages.WriteData(Stream); end; procedure TXlsTemplate.WriteModifiedDate(Writer: TWriter); begin Writer.WriteDate(FModifiedDate); end; { TXlsTemplateStore } constructor TXlsTemplateStore.Create(AOwner: TComponent); begin inherited; FTemplates:= TXlsTemplateList.Create(Self, TXlsTemplate); end; destructor TXlsTemplateStore.Destroy; begin FreeAndNil(FTemplates); inherited; end; function TXlsTemplateStore.GetStorages(Name: String): TXlsStorageList; var i: integer; begin Name:= ExtractFileName(Name); for i:=0 to Templates.Count -1 do if Templates[i].FileName=Name then begin Result:=Templates[i].Storages; exit; end; raise Exception.CreateFmt(ErrFileNotFound, [Name]); end; function TXlsTemplateStore.IsUpToDate: boolean; var FileName: string; i: integer; begin Result:=false; for i:=0 to Templates.Count-1 do begin FileName:=IncludeTrailingPathDelimiter(RefreshPath)+Templates[i].FileName; if not FileExists(FileName) then exit; if FileAge(FileName)<> DateTimeToFileDate(Templates[i].ModifiedDate) then //We compare integers, not doubles exit; end; Result:=true; end; procedure TXlsTemplateStore.Refresh; var i: integer; begin for i:=0 to Templates.Count-1 do begin Templates[i].FileName:=IncludeTrailingPathDelimiter(RefreshPath)+Templates[i].FileName; end; end; procedure TXlsTemplateStore.SetCompress(const Value: boolean); begin FCompress := Value; Templates.Compress:=Value; end; { TXlsTemplateList } function TXlsTemplateList.GetItems(Index: integer): TXlsTemplate; begin Result:= inherited Items[Index] as TXlsTemplate; end; procedure TXlsTemplateList.SetCompress(const Value: boolean); var i:integer; begin FCompress := Value; for i:=0 to Count-1 do Items[i].Compress:=true; end; end.
unit uServidor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, WinSock, Dialogs, StdCtrls, ComCtrls, Buttons, ExtCtrls, Spin, Sockets, ScktComp, ImgList, DateUtils, Math; function getIPs: Tstrings; type TformServidor = class(TForm) PageControl1: TPageControl; tabRede: TTabSheet; tabLog: TTabSheet; GroupBox1: TGroupBox; GroupBox3: TGroupBox; Panel1: TPanel; logServidor: TMemo; Label1: TLabel; Servidor_PortaTCP: TEdit; Panel2: TPanel; StopServidor: TBitBtn; PlayServidor: TBitBtn; Panel3: TPanel; GroupBox2: TGroupBox; TreeView1: TTreeView; Timer1: TTimer; Shape9: TShape; Label11: TLabel; Servidor_Status: TLabel; Button1: TButton; Button2: TButton; Timer2: TTimer; TCPServer1: TServerSocket; Label13: TLabel; nivelDet: TSpinEdit; saveLog: TCheckBox; Label12: TLabel; ultLinhas: TSpinEdit; Label14: TLabel; GroupBox4: TGroupBox; Label2: TLabel; lblDias: TLabel; Servidor_Tempo_Conex: TLabel; Shape1: TShape; Label15: TLabel; Servidor_Clientes_Conect: TLabel; Shape11: TShape; Shape12: TShape; Label3: TLabel; Label16: TLabel; Shape13: TShape; Label6: TLabel; Shape14: TShape; Label17: TLabel; Shape15: TShape; Label18: TLabel; Shape16: TShape; Label19: TLabel; Shape17: TShape; Label20: TLabel; Servidor_Bytes_Recebidos: TLabel; Servidor_Bytes_Enviados: TLabel; Servidor_Nome_Maquina: TLabel; Servidor_Endereco_IP: TLabel; Servidor_Executado_Em: TLabel; Servidor_Ativado_Em: TLabel; Servidor_Parado_Em: TLabel; tabThreads: TTabSheet; GroupBox5: TGroupBox; ImageList1: TImageList; Panel4: TPanel; Shape2: TShape; Button3: TButton; Panel5: TPanel; listaThreads: TListView; GroupBox6: TGroupBox; Label4: TLabel; Servidor_string_retorno: TEdit; btnOpcoes: TButton; Servidor_Arquivo_Log: TLabel; tabRetorno: TTabSheet; GroupBox7: TGroupBox; Label5: TLabel; edtChave: TEdit; edtValor: TEdit; Label7: TLabel; btnAddChave: TButton; lvChaves: TListView; btnRemoveChave: TButton; btnRemoveAll: TButton; procedure FormCreate(Sender: TObject); procedure PlayServidorClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure TreeView1Click(Sender: TObject); procedure StopServidorClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure TCPServer1ClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure TCPServer1ClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure TCPServer1ClientConnect(Sender: TObject; Socket: TCustomWinSocket); procedure TCPServer1ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure Button3Click(Sender: TObject); procedure listaThreadsColumnClick(Sender: TObject; Column: TListColumn); procedure btnOpcoesClick(Sender: TObject); procedure btnAddChaveClick(Sender: TObject); procedure btnRemoveAllClick(Sender: TObject); procedure btnRemoveChaveClick(Sender: TObject); procedure edtChaveKeyPress(Sender: TObject; var Key: Char); private { Private declarations } Hoje: TDate; procedure ProcessaBuffer(const Buffer: string; const Socket: TCustomWinSocket); procedure Detalhe(const nivel: integer; const detalhe: string); public { Public declarations } LogAGravar: TStrings; procedure MandaResposta(const Socket: TCustomWinSocket; const resposta: string); procedure AtualizaListaThreads(const SocketID: integer; const ThreadId: integer; const ImageID: integer; const Tempo: integer; const origem: string; const status: string); end; var formServidor: TformServidor; hora, minuto, segundo: word; dia: integer; implementation uses uLogs, uProcessosThreads, uPrincipal; {$R *.dfm} // Escreve as ocorrências no LOG procedure TformServidor.Detalhe(const nivel: integer; const detalhe: string); var s1: string; begin if (nivel > nivelDet.Value) then exit; s1 := detalhe; Apoio_Detalhe(logServidor, s1, ultLinhas.Value); LogAGravar.Add(s1); end; procedure TformServidor.FormCreate(Sender: TObject); var i: integer; begin Hoje := Date(); LogAGravar := TStringList.Create; with PageControl1 do begin for i := 0 to PageCount -1 do begin Pages[i].TabVisible := False; end; ActivePage := tabThreads; end; TreeView1.Items.Item[0].SelectedIndex := 2; Servidor_Parado_Em.Caption := 'Ainda não foi parado.'; Servidor_Executado_Em.Caption := FormatDateTime('dd/mm/yyyy hh:nn:ss', now); hora := 0; segundo := 0; minuto := 0; dia := 0; Detalhe(1,'Servidor Iniciado em: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', now)); Servidor_Arquivo_Log.Caption := ExtractFileDir(Application.ExeName) + '\Logs\logServidor_'+FormatDateTime('yyyymmdd', now) + '.txt'; lblDias.Caption := ''; Panel1.Height := 85; PlayServidor.Click; end; // Botão Parar Servidor procedure TformServidor.StopServidorClick(Sender: TObject); begin Servidor_Status.Caption := 'Parado'; Servidor_Status.Font.Color := clRed; TCPServer1.Active := False; Timer1.Enabled := False; stopServidor.Enabled := False; playServidor.Enabled := True; GroupBox1.Enabled := True; Servidor_Parado_Em.Caption := FormatDateTime('dd/mm/yyyy hh:nn:ss', now); Detalhe(1,'Servidor Parado em: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', now)); end; // Botão Ativar Servidor procedure TformServidor.PlayServidorClick(Sender: TObject); var lstIPs: TStrings; begin try TCPServer1.Port := StrToIntDef(Servidor_PortaTCP.Text, 16500); TCPServer1.Active := True; except on e: exception do begin Detalhe(1, 'Erro ao iniciar servidor de conexões: ' + e.Message); exit; end; end; Timer1.Enabled := True; stopServidor.Enabled := True; playServidor.Enabled := False; GroupBox1.Enabled := False; Servidor_Nome_Maquina.Caption := TCPServer1.Socket.LocalHost; lstIPs := TStringList.Create; lstIPs := getIPs; if (lstIPs.Count > 0) then Servidor_Endereco_IP.Caption := lstIps.Strings[0] else Servidor_Endereco_IP.Caption := TCPServer1.Socket.LocalAddress; lstIPs.Free; Servidor_Ativado_Em.Caption := FormatDateTime('dd/mm/yyyy hh:nn:ss', now); Servidor_Status.Caption := 'Ativado'; Servidor_Status.Font.Color := clNavy; Detalhe(1, 'Servidor Ativado em: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', now)); end; // Mostra quanto tempo tem de duração a conexão (não conta as paradas) procedure TformServidor.Timer1Timer(Sender: TObject); var tempo: TTime; begin inc(segundo); if (segundo = 60) then begin segundo := 0; inc(minuto); end; if (minuto = 60) then begin inc(hora); minuto := 0; segundo := 0; end; if (hora = 24) then begin inc(dia); hora := 0; minuto := 0; segundo := 0; if (dia = 1) then lblDias.Caption := '1 dia e' else lblDias.Caption := IntToStr(dia) + ' dias e '; end; try tempo := EncodeTime(hora, minuto, segundo, 0); Servidor_Tempo_Conex.Caption := TimeToStr(tempo); except on e: exception do begin Detalhe(10,'Erro ao mostrar tempo: hora=' + IntToStr(hora) + ', minuto=' + IntToStr(minuto) + ', segundo=' + IntToStr(segundo)); Detalhe(10,'Erro ao mostrar tempo, parando timer: ' + e.Message); timer1.Enabled := false; end; end; end; procedure TformServidor.TreeView1Click(Sender: TObject); begin if (TreeView1.Selected.Index < 0) then exit; PageControl1.ActivePageIndex := TreeView1.Selected.Index; end; // Limpar a tela de Logs procedure TformServidor.Button1Click(Sender: TObject); begin LimpaTelaDeLogs(logServidor); end; //Abrir log no bloco de notas procedure TformServidor.Button2Click(Sender: TObject); var fnTemp: string; begin fnTemp := ExtractFileDir(Application.ExeName) + '\Logs\logServidorTEMP_'+FormatDateTime('yyyymmdd', now) + '.txt'; AbreLogNoBlocoNotas(logServidor, fnTemp); end; procedure TformServidor.FormDestroy(Sender: TObject); begin Detalhe(1,'Encerrando o Autorizador com solicitação de usuário!'); if (SaveLog.Checked) then Grava_Log(LogAGravar, Servidor_Arquivo_Log.Caption); if (LogAGravar <> nil) then begin LogAGravar.Free; LogAGravar := nil; end; end; // Para gravar o Log em segundo plano para melhor performance procedure TformServidor.Timer2Timer(Sender: TObject); begin if (Hoje <> Date()) then begin Servidor_Arquivo_Log.Caption := ExtractFileDir(Application.ExeName) + '\Logs\logServidor_'+FormatDateTime('yyyymmdd', now) + '.txt'; Hoje := Date(); end; if (LogAGravar.Count = 0) then exit; if (SaveLog.Checked) then Grava_Log(LogAGravar, Servidor_Arquivo_Log.Caption); end; // Cria a Thread de Processo para processar o buffer recebido procedure TformServidor.ProcessaBuffer(const Buffer: string; const Socket: TCustomWinSocket); var thProcessos: TProcessos; begin thProcessos := TProcessos.Create(Buffer, socket, TCPServer1); AtualizaListaThreads(socket.SocketHandle, thProcessos.ThreadID, 1, 0, socket.RemoteAddress, 'criando thread'); thProcessos.FreeOnTerminate := True; thProcessos.Resume; end; procedure TformServidor.TCPServer1ClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin AtualizaListaThreads(socket.SocketHandle, 0, 2, 0, socket.RemoteAddress, 'erro de socket: ' + IntToStr(ErrorCode)); Detalhe(1,'(skt:' + IntToStr(Socket.SocketHandle) + ') Erro de conexão : ' + Socket.RemoteAddress + ',' + IntToStr(ErrorCode)); try Socket.Close; except end; ErrorCode := 0; end; //Recebendo buffer enviado pelo client procedure TformServidor.TCPServer1ClientRead(Sender: TObject; Socket: TCustomWinSocket); var bytesRecebidos: Word; strBuffer, strCommand: string; begin AtualizaListaThreads(socket.SocketHandle, 0, 4, 0, socket.RemoteAddress, 'recebendo...'); Servidor_Endereco_IP.Caption := Socket.LocalAddress; bytesRecebidos := StrToIntDef(Servidor_Bytes_Recebidos.Caption, 0); try strBuffer := Socket.ReceiveText; except on e: exception do begin Detalhe(5, '(skt:' + IntToStr(Socket.SocketHandle) + ') Erro de exception ao receber mensagem: ('+ e.Message); end; end; strCommand := trim(strBuffer); bytesRecebidos := bytesRecebidos + length(strCommand); Servidor_Bytes_Recebidos.Caption := FloatToStr(bytesRecebidos); Detalhe(5,'(skt:' + IntToStr(Socket.SocketHandle) + ') Recebendo buffer com : ' + IntToStr(length(strCommand)) + ' bytes.'); Detalhe(8,'(skt:' + IntToStr(Socket.SocketHandle) + ') Buffer Recebido : ' + strCommand); processaBuffer(strBuffer, Socket); end; //Cliente conectou via sockt procedure TformServidor.TCPServer1ClientConnect(Sender: TObject; Socket: TCustomWinSocket); begin AtualizaListaThreads(socket.SocketHandle, 0, 0, 0, socket.RemoteAddress, 'conectado.'); Servidor_Clientes_Conect.Caption := IntToStr(StrToIntDef(Servidor_Clientes_Conect.Caption, 0) +1); Servidor_Clientes_Conect.Refresh; Detalhe(5,'(skt:' + IntToStr(Socket.SocketHandle) + ') Conectado por : ' + Socket.RemoteAddress); end; procedure TformServidor.TCPServer1ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin AtualizaListaThreads(socket.SocketHandle, 0, 3, 0, socket.RemoteAddress, 'desconectado'); if (Servidor_Clientes_Conect.Caption <> '0') then Servidor_Clientes_Conect.Caption := IntToStr(StrToIntDef(Servidor_Clientes_Conect.Caption, 1) -1); Servidor_Clientes_Conect.Refresh; Detalhe(5, '(skt:' + IntToStr(Socket.SocketHandle) + ') Desconectado por : ' + Socket.RemoteAddress); end; procedure TformServidor.MandaResposta(const Socket: TCustomWinSocket; const resposta: string); var bytesEnviados: Word; strToSend: String; begin strToSend := resposta; if (Socket = nil) then exit; if (Socket.Connected) then begin bytesEnviados := Socket.SendText(strToSend); if (bytesEnviados = 0) then begin sleep(100); bytesEnviados := Socket.SendText(strToSend); end; if (bytesEnviados > 0) then begin Detalhe(5, '(skt:' + IntToStr(Socket.SocketHandle) + ') Enviando resposta ('+IntToStr(bytesEnviados)+') bytes: '+resposta); end else begin Detalhe(5, '(skt:' + IntToStr(Socket.SocketHandle) + ') Nao foi possivel enviar ('+IntToStr(bytesEnviados)+') bytes: '+resposta); end; end; socket.Close; bytesEnviados := StrToIntDef(Servidor_Bytes_Enviados.Caption, 0); bytesEnviados := bytesEnviados + length(strToSend); Servidor_Bytes_Enviados.Caption := FloatToStr(bytesEnviados); AtualizaListaThreads(socket.SocketHandle, 0, 1, 0, socket.RemoteAddress, 'respondendo:'+resposta); end; procedure TformServidor.AtualizaListaThreads(const SocketID: integer; const ThreadId: integer; const ImageID: integer; const Tempo: integer; const origem: string; const status: string); var item: TListItem; dif: integer; begin listaThreads.Canvas.Lock; if (ImageID = 0) then // cria nova conexao begin listaThreads.Items.BeginUpdate; item := listaThreads.Items.Insert(0); item.Caption := IntToStr(SocketID); item.ImageIndex := 4; item.SubItems.Add(IntToStr(ThreadID)); item.SubItems.Add(formatDateTime('dd/mm/yyyy hh:nn:ss:zz', now)); item.SubItems.Add(origem); item.SubItems.Add(' '); item.SubItems.Add('Conectado...'); item.SubItems.Add(' '); if (listaThreads.Items.Count > 200) then listaThreads.Items.Delete(200); listaThreads.Items.EndUpdate; listaThreads.Canvas.UnLock; exit; end; item := listaThreADS.FindCaption(0, IntToStr(SocketID), false, true, false); // encontra socket existente if (item = nil) then exit; // nao achou, entao vaza... listaThreads.Items.BeginUpdate; item.ImageIndex := ImageID; if (Tempo <> 0) then item.SubItems.Strings[3] := IntToStr(Tempo); if (ThreadID <> 0) then item.SubItems.Strings[0] := IntToStr(ThreadID); item.SubItems.Strings[4] := Status; if (status = 'desconectado') then begin dif := MilliSecondsBetween(now, StrToDateTime(item.SubItems.Strings[1])); item.SubItems.Strings[3] := IntToStr(dif);//+'ms'; end; if (imageId = 2) then item.SubItems.Strings[5] := status; listaThreads.Items.EndUpdate; listaThreads.Canvas.UnLock; end; procedure TformServidor.Button3Click(Sender: TObject); begin listaThreads.Items.BeginUpdate; listaThreads.Items.Clear; listaThreads.Items.EndUpdate; end; function SortByColumn(PItem1, PItem2: TListItem; PData: integer):integer; stdcall; var Ascending: Boolean; f1, f2: double; s1, s2: String; begin // Check out the Ascending or Descending property, this is embedded in the sign of PData Ascending := Sign(PData) = 1; // Get away the ascending or descending property PData := abs(PData); // Get the strings to compare if PData = 1 then begin s1 := PItem1.Caption; s2 := PItem2.Caption; end else begin s1 := PItem1.SubItems[PData-2]; s2 := PItem2.SubItems[PData-2]; end; try // Check out if the column contains numerical data f1 := StrToFloat(s1); f2 := StrToFloat(s2); // if code execution get's to this point, we have to deal with numerical values, and return -1, 0, 1 according to if f1 > f2 then result := 1 else if f1 < f2 then result := -1 else result := 0; except // Else the result is based upon string comparison Result := AnsiCompareText(s1, s2) end; if not Ascending then Result := -Result; end; procedure TformServidor.listaThreadsColumnClick(Sender: TObject; Column: TListColumn); var i: integer; begin for i := 0 to TListView(Sender).Columns.Count -1 do TListView(Sender).Columns.Items[i].ImageIndex := -1; // Check out if this is the first time the column is sorted if Column.Tag = 0 then // Default = Ascending Column.Tag := 1 else Column.Tag := -Column.Tag; if (Column.tag = -1) then Column.ImageIndex := 5 else Column.ImageIndex := 0; // Perform the sort // the second parameter has a part for the ascending property, the sign of the parameter and the // column index is increased by one, else the first column (index=0) is always sorted Descending // In the SortByCloumn function this assumption is taken into account TListView(Sender).CustomSort(@SortByColumn, Column.Tag * (Column.Index + 1)); end; procedure TformServidor.btnOpcoesClick(Sender: TObject); begin if (btnOpcoes.Tag = 0) then begin btnOpcoes.Caption := '<< Menos opções'; btnOpcoes.Tag := 1; Panel1.Height := 140; end else begin btnOpcoes.Caption := 'Mais opções >>'; btnOpcoes.Tag := 0; Panel1.Height := 85; end; end; function getIPs: Tstrings; type TaPInAddr = array[0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; Buffer: array[0..63] of Char; I: Integer; GInitData: TWSAData; begin WSAStartup($101, GInitData); Result := TstringList.Create; Result.Clear; GetHostName(Buffer, SizeOf(Buffer)); phe := GetHostByName(buffer); if phe = nil then Exit; pPtr := PaPInAddr(phe^.h_addr_list); I := 0; while pPtr^[I] <> nil do begin Result.Add(inet_ntoa(pptr^[I]^)); Inc(I); end; WSACleanup; end; procedure GravaChaves(const lvChaves: TListView); var i: integer; item: TListItem; sChave, sValor, sList: String; begin for i := 0 to lvChaves.Items.Count -1 do begin item := lvChaves.Items[i]; sChave := trim(item.Caption); sValor := trim(item.SubItems[0]); if (sChave <> '') and (sValor <> '') then begin sList := sList + '"' + sChave + '=' + sValor + '",'; end; end; formServidor.Servidor_string_retorno.Text := sList; formPrincipal.SalvarConfiguracoes; end; procedure TformServidor.btnAddChaveClick(Sender: TObject); var sChave, sValor: string; item: TListItem; begin sChave := trim(edtChave.Text); sValor := trim(edtValor.Text); if (sChave = '') or (sValor = '') then exit; item := lvChaves.FindCaption(0, sChave, false, true, true); if (item <> nil) then exit; item := lvChaves.Items.Add; item.Caption := edtChave.Text; item.SubItems.Add(edtValor.Text); GravaChaves(lvChaves); edtChave.SetFocus; end; procedure TformServidor.btnRemoveAllClick(Sender: TObject); begin with lvChaves.Items do begin BeginUpdate; Clear; EndUpdate; end; GravaChaves(lvChaves); end; procedure TformServidor.btnRemoveChaveClick(Sender: TObject); var item: TListItem; i: integer; begin item := lvChaves.Selected; if (item = nil) then exit; i := item.Index; with lvChaves.Items do begin BeginUpdate; lvChaves.DeleteSelected; EndUpdate; end; if (i > lvChaves.Items.Count -1) then i := lvChaves.Items.Count -1; lvChaves.ItemIndex := i; GravaChaves(lvChaves); end; procedure TformServidor.edtChaveKeyPress(Sender: TObject; var Key: Char); begin if (key = #13) then begin btnAddChave.Click; end; end; end.
unit Server.Models.Cadastros.PausasRealizadas; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('PAUSAS_REALIZADAS','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TPausasRealizadas = class(TTabelaBase) private fOBS: String; fEXCEDEU: String; fTEMPO_EXEDIDO: TTime; fCOD_PAUSA: Integer; fOPERADOR: Integer; fDATA_HORA: TDateTime; fTIPO: String; fDATA_HORA_FIM: TDateTime; fDataInicioPausa: Double; function Getid: Integer; procedure Setid(const Value: Integer); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('OPERADOR', ftInteger)] property OPERADOR: Integer read fOPERADOR write fOPERADOR; [Column('OBS', ftString, 50)] property OBS: String read fOBS write fOBS; [Column('COD_PAUSA', ftinteger)] property COD_PAUSA: Integer read fCOD_PAUSA write fCOD_PAUSA; [Column('EXCEDEU', ftString, 3)] property EXCEDEU: String read fEXCEDEU write fEXCEDEU; [Column('TIPO', ftString, 5)] property TIPO: String read fTIPO write fTIPO; [Column('TEMPO_EXEDIDO', ftTime)] property TEMPO_EXEDIDO: TTime read fTEMPO_EXEDIDO write fTEMPO_EXEDIDO; [Column('DATA_HORA', ftDateTime)] property DATA_HORA: TDateTime read fDATA_HORA write fDATA_HORA; [Column('DATA_HORA_FIM', ftDateTime)] property DATA_HORA_FIM: TDateTime read fDATA_HORA_FIM write fDATA_HORA_FIM; property DataInicioPausa: Double read fDataInicioPausa write fDataInicioPausa; end; implementation { TPausasRealizadas } constructor TPausasRealizadas.create; begin end; destructor TPausasRealizadas.destroy; begin inherited; end; function TPausasRealizadas.Getid: Integer; begin Result := fid; end; procedure TPausasRealizadas.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TPausasRealizadas); end.
unit UDbfCursor; interface uses classes,db, UDbfPagedFile,UDbfCommon; type //==================================================================== TVirtualCursor = class private _file:TPagedFile; public property PagedFile:TPagedFile read _file; constructor Create(pFile:TPagedFile); destructor destroy; override; function RecordSize : Integer; function Next:boolean; virtual; abstract; function Prev:boolean; virtual; abstract; procedure First; virtual; abstract; procedure Last; virtual; abstract; function GetPhysicalRecno:integer; virtual; abstract; procedure SetPhysicalRecno(Recno:integer); virtual; abstract; function GetSequentialRecordCount:integer; virtual; abstract; function GetSequentialRecno:integer; virtual; abstract; procedure SetSequentialRecno(Recno:integer); virtual; abstract; function GetBookMark:rBookmarkData; virtual; abstract; procedure GotoBookmark(Bookmark:rBookmarkData); virtual; abstract; procedure Insert(Recno:integer; Buffer:PChar); virtual; abstract; procedure Update(Recno: integer; PrevBuffer,NewBuffer: PChar); virtual; abstract; end; implementation function TVirtualCursor.RecordSize : Integer; begin if _file = nil then result:=0 else result:=_file.recordsize; end; constructor TVirtualCursor.Create(pFile:TPagedFile); begin _File:=pFile; end; destructor TVirtualCursor.destroy; {override;} begin end; end.
{********************************************************** Copyright (C) 2012-2016 Zeljko Cvijanovic www.zeljus.com (cvzeljko@gmail.com) & Miran Horjak usbdoo@gmail.com ***********************************************************} unit Dialogs; {$mode objfpc}{$H+} {$modeswitch unicodestrings} {$namespace zeljus.com.units.pascal} interface uses androidr15, DialogsView; type TOnClickEventDialog = procedure (para1: ACDialogInterface; para2: jint) of object; TTypeButton = (btNeutral, btNegative, btPositive); { TDialog } TDialog = class(AAAlertDialog, ACDialogInterface.InnerOnClickListener) private fID: integer; FOnClick: TOnClickEventDialog; public procedure onClick(para1: ACDialogInterface; para2: jint); overload; public constructor create(para1: ACContext); overload; virtual; procedure AddButton(aTypeButton: TTypeButton; aName: JLCharSequence); public property ID: integer read fID write fID; property OnClickListener: TOnClickEventDialog read FOnClick write FOnClick; end; { TTimePickerDialog } TTimePickerDialog = class(TDialog) private FTimePicker: AWTimePicker; public constructor create(para1: ACContext); override; public property TimePicker: AWTimePicker read FTimePicker; end; { TDatePickerDialog } TDatePickerDialog = class(TDialog) private FDatePicker: AWDatePicker; public constructor create(para1: ACContext); override; public property DatePicker: AWDatePicker read FDatePicker; end; { TUserNamePasswordDialog } TUserNamePasswordDialog = class(TDialog) private FUserPasswordView: TUserPasswordView; public constructor create(para1: ACContext); override; public property UserNamePassword: TUserPasswordView read FUserPasswordView; end; implementation { TDialog } procedure TDialog.onClick(para1: ACDialogInterface; para2: jint); begin if Assigned(FOnClick) then FOnClick(para1, para2); end; constructor TDialog.create(para1: ACContext); begin inherited Create(para1); setTitle(AAActivity(para1).getPackageManager.getApplicationLabel(AAActivity(para1).getApplicationInfo)); setIcon(AAActivity(para1).getPackageManager.getApplicationIcon(AAActivity(para1).getApplicationInfo)); end; procedure TDialog.AddButton(aTypeButton: TTypeButton; aName: JLCharSequence); begin setButton(ord(aTypeButton) - (Ord(High(TTypeButton)) + 1), aName, Self); end; { TTimePickerDialog } constructor TTimePickerDialog.create(para1: ACContext); begin inherited Create(para1); FTimePicker:= AWTimePicker.create(getContext); Self.setView(FTimePicker); end; { TDatePickerDialog } constructor TDatePickerDialog.create(para1: ACContext); begin inherited Create(para1); FDatePicker := AWDatePicker.create(getContext); Self.setView(FDatePicker); end; { TUserNamePasswordDialog } constructor TUserNamePasswordDialog.create(para1: ACContext); begin inherited Create(para1); FUserPasswordView := TUserPasswordView.create(getContext); FUserPasswordView.UserNameCaption := 'User name: '; FUserPasswordView.PasswordCaption := 'Password: '; Self.setView(FUserPasswordView); end; end.
/// <summary> /// 码型过滤插件模块 /// </summary> unit MaXingFltForm; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, Buttons, RzButton, ExtCtrls, Graphics; type /// <summary> /// 码型过滤条件设置窗口 /// </summary> TfrmMaXingFlt = class(TForm) Panel1: TPanel; Image1: TImage; Label1: TLabel; Label2: TLabel; Bevel2: TBevel; Label6: TLabel; Label7: TLabel; Label14: TLabel; lstAllMX: TListBox; btnAddMX: TBitBtn; btnAddAllMX: TBitBtn; btnMXDelete: TBitBtn; btnMXDeleteAll: TBitBtn; lstMXFilter: TListBox; Panel2: TPanel; btnCancel: TBitBtn; btnHelp: TBitBtn; btnOK: TBitBtn; Bevel1: TBevel; btnSave: TBitBtn; btnLoad: TBitBtn; GroupBox1: TGroupBox; Label3: TLabel; rdbDelete: TRadioButton; rdbKeep: TRadioButton; procedure btnAddMXClick(Sender: TObject); procedure btnAddAllMXClick(Sender: TObject); procedure btnMXDeleteClick(Sender: TObject); procedure btnMXDeleteAllClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure btnOKClick(Sender: TObject); { Private declarations } public bCancel: boolean; procedure SetFilter(str: String); function GetFilter(): String; end; var frmMaXingFlt: TfrmMaXingFlt; /// <summary> /// 足彩场次选择串 /// </summary> GZc9Select: string = 'YYYYYYYYYYYYYY'; /// <summary> /// 足彩任选场次数 /// </summary> GZc9SelCount: integer = 14; /// <summary> /// 计算码型 /// </summary> function GetMaXingD(sChip: String): String; implementation {$R *.dfm} function GetMaXingD(sChip: String): String; var i: integer; nNumCount: array [0 .. 3] of byte; begin for i := Low(nNumCount) to High(nNumCount) do nNumCount[i] := 0; for i := 1 to Length(sChip) do begin Inc(nNumCount[StrToInt(sChip[i])]); end; Result := Format('%2d-%2d-%2d', [nNumCount[3], nNumCount[1], nNumCount[0]]);; end; procedure TfrmMaXingFlt.btnAddMXClick(Sender: TObject); var i: integer; begin for i := lstAllMX.Items.Count - 1 downto 0 do begin if lstAllMX.Selected[i] then begin lstMXFilter.Items.Add(lstAllMX.Items[i]); lstAllMX.Items.Delete(i); end; end; end; procedure TfrmMaXingFlt.btnAddAllMXClick(Sender: TObject); var i: integer; begin for i := 0 to lstAllMX.Items.Count - 1 do begin lstMXFilter.Items.Add(lstAllMX.Items[i]); end; lstAllMX.Clear; end; procedure TfrmMaXingFlt.btnMXDeleteClick(Sender: TObject); var i: integer; begin for i := lstMXFilter.Items.Count - 1 downto 0 do begin if lstMXFilter.Selected[i] then begin lstAllMX.Items.Add(lstMXFilter.Items[i]); lstMXFilter.Items.Delete(i); end; end; end; procedure TfrmMaXingFlt.btnMXDeleteAllClick(Sender: TObject); var i: integer; begin for i := 0 to lstMXFilter.Items.Count - 1 do begin lstAllMX.Items.Add(lstMXFilter.Items[i]); end; lstMXFilter.Clear; end; procedure TfrmMaXingFlt.FormCreate(Sender: TObject); var i, j, k: integer; sTemp: String; begin // 添加所有可用的连型 lstAllMX.Sorted := False; for i := 0 to GZc9SelCount do for j := 0 to GZc9SelCount - i do begin sTemp := Format('%2d-%2d-%2d', [i, j, GZc9SelCount - i - j]); if lstMXFilter.Items.IndexOf(sTemp) < 0 then lstAllMX.Items.Add(sTemp); end; lstAllMX.Sorted := True; bCancel := True; end; procedure TfrmMaXingFlt.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmMaXingFlt.btnHelpClick(Sender: TObject); var msg: String; begin msg := '【码型过滤】' + #13#10#13#10 + '码型过滤是针对单注中胜(3)、平(1)、负(0)个数的组合形式进行过滤。' + #13#10 + '例如:33111031031031 的码型为 2- 3- 1' + #13#10 + '又如:33330313130031 的码型为 4- 1- 2'; Application.MessageBox(PChar(msg), '码型过滤'); end; procedure TfrmMaXingFlt.btnOKClick(Sender: TObject); begin bCancel := False; Close; end; function TfrmMaXingFlt.GetFilter: String; begin if rdbDelete.Checked then Result := 'D|' else Result := 'K|'; Result := Result + StringReplace(lstMXFilter.Items.Text, #13#10, ';', [rfReplaceAll]); end; procedure TfrmMaXingFlt.SetFilter(str: String); var i, nID: integer; begin if Copy(str, 2, 1) = '|' then begin rdbDelete.Checked := (str[1] in ['d', 'D']); str := Copy(str, 3, Length(str)); end; rdbKeep.Checked := not rdbDelete.Checked; lstMXFilter.Items.Text := StringReplace(str, ';', #13#10, [rfReplaceAll]); for i := 0 to lstMXFilter.Count - 1 do begin nID := lstAllMX.Items.IndexOf(lstMXFilter.Items[i]); if nID >= 0 then lstAllMX.Items.Delete(nID); end; end; end.
unit UBackupFileWatcher; interface uses UFileWatcher, UChangeInfo, SysUtils, Classes, UModelUtil, Generics.Collections, SyncObjs, DateUtils; type // 路径是否存在 监听 TBackupItemExistThread = class( TWatchPathExistThread ) protected procedure WatchPathNotEixst( WatchPath : string );override; procedure WatchPathExist( WatchPath : string );override; end; // 备份文件 变化检测器 TMyBackupFileWatcher = class public BackupItemExistThread : TBackupItemExistThread; public constructor Create; procedure StopWatch; public procedure AddWatchPath( WatchPath : string; IsExist : Boolean ); procedure RemoveWatchPath( WatchPath : string ); end; var MyBackupFileWatcher : TMyBackupFileWatcher; implementation uses UBackupInfoControl, UMyUtil, UBackupFileScan; { TMyBackupFileWatcher } procedure TMyBackupFileWatcher.AddWatchPath(WatchPath: string; IsExist : Boolean); begin BackupItemExistThread.AddWatchPath( WatchPath, IsExist ); end; constructor TMyBackupFileWatcher.Create; begin BackupItemExistThread := TBackupItemExistThread.Create; BackupItemExistThread.Resume; end; procedure TMyBackupFileWatcher.RemoveWatchPath(WatchPath: string); begin BackupItemExistThread.RemoveWatchPath( WatchPath ); end; procedure TMyBackupFileWatcher.StopWatch; begin // 停止检测 备份路径 BackupItemExistThread.Free; end; { TBackupItemExistThread } procedure TBackupItemExistThread.WatchPathExist(WatchPath: string); var BackupPathResetExistHandle : TBackupPathSetExistHandle; BackupScanPathInfo : TBackupScanPathInfo; begin BackupPathResetExistHandle := TBackupPathSetExistHandle.Create( WatchPath ); BackupPathResetExistHandle.SetIsExist( True ); BackupPathResetExistHandle.Update; BackupPathResetExistHandle.Free; end; procedure TBackupItemExistThread.WatchPathNotEixst(WatchPath: string); var BackupPathResetExistHandle : TBackupPathSetExistHandle; BackupScanPathInfo : TBackupScanPathInfo; begin BackupPathResetExistHandle := TBackupPathSetExistHandle.Create( WatchPath ); BackupPathResetExistHandle.SetIsExist( False ); BackupPathResetExistHandle.Update; BackupPathResetExistHandle.Free; end; end.
unit longpoll; {$mode objfpc}{$H+} interface uses Classes, SysUtils, vkcmobserver, fphttpclient, fpjson, vkdao, sqldb, entities, fgl; type { TLongPollServer } TLongPollServer = class private FTS: string; FKey: string; FServer: string; procedure SetTS(AValue: string); procedure SetKey(AValue: string); procedure SetServer(AValue: string); public property Key: string read FKey write SetKey; property Server: string read FServer write SetServer; property TS: string read FTS write SetTS; end; TLongPollServersObjectList = specialize TFPGObjectList<TLongpollServer>; { TLongPollWorker } TLongPollWorker = class(TThread) private Observable: TVKCMObservable; CommunitiesKeys: TStringList; procedure InitializeServerList(var ServersList: TLongPollServersObjectList); {Function returns first ts} function MakeFirstCall(AccessKey: string): TLongPollServer; {Function decides whether to send update notification} function ProcessServer(Server: TLongPollServer): boolean; procedure NotifyObserversThreadMethod; protected procedure Execute; override; public constructor Create(CreateSuspended: boolean; Communities: TCommunityList); procedure SubscribeForNotifications(Me: TVKCMObserver); destructor Destroy; override; end; implementation { TLongPollServer } procedure TLongPollServer.SetKey(AValue: string); begin if FKey = AValue then Exit; FKey := AValue; end; procedure TLongPollServer.SetTS(AValue: string); begin if FTS = AValue then Exit; FTS := AValue; end; procedure TLongPollServer.SetServer(AValue: string); begin if FServer = AValue then Exit; FServer := AValue; end; { TLongPollWorker } function TLongPollWorker.MakeFirstCall(AccessKey: string): TLongPollServer; var JSONResponse, Response: TJSONObject; var HTTPClient: TFPHTTPClient; begin HTTPClient := TFPHTTPClient.Create(nil); try JSONResponse := DAO.Messages.GetLongPollServer(HTTPClient, AccessKey); finally FreeAndNil(HTTPClient); end; Response := (JSONResponse['response'] as TJSONObject); Result := TLongPollServer.Create; Result.Key := Response['key'].AsString; Result.Server := Response['server'].AsString; Result.TS := Response['ts'].AsString; FreeAndNil(JSONResponse); end; function TLongPollWorker.ProcessServer(Server: TLongPollServer): boolean; var URL, Response: string; JSONResponse: TJSONObject; Updates: TJSONArray; Update: TJSONArray; i: integer; HTTPClient: TFPHTTPClient; begin URL := 'https://' + Server.Server + '?act=a_check&key=' + Server.Key + '&ts=' + Server.TS + '&wait=5&mode=2&version=1'; HTTPClient := TFPHTTPClient.Create(nil); try Response := DAO.ExecuteGetRequest(HTTPClient, URL); finally FreeAndNil(HTTPClient); end; JSONResponse := GetJSON(Response) as TJSONObject; Updates := JSONResponse['updates'] as TJSONArray; if Updates.Count > 0 then for i := 0 to Updates.Count - 1 do begin Update := (Updates[i] as TJSONArray); if Update.Items[0].AsInt64 = 4 then begin Result := True; Server.TS := JSONResponse['ts'].AsString; break; end else Result := False; end else Result := False; FreeAndNil(JSONResponse); end; procedure TLongPollWorker.NotifyObserversThreadMethod; begin Observable.NotifyObservers; end; procedure TLongPollWorker.InitializeServerList( var ServersList: TLongPollServersObjectList); var i: integer; begin for i := 0 to CommunitiesKeys.Count - 1 do begin ServersList.Add(MakeFirstCall(CommunitiesKeys[i])); end; end; procedure TLongPollWorker.Execute; var ServersList: TLongPollServersObjectList; i: integer; CurrentServer: TLongPollServer; begin ServersList := TLongPollServersObjectList.Create(True); InitializeServerList(ServersList); while not Terminated do begin try for i := 0 to ServersList.Count - 1 do begin CurrentServer := ServersList[i]; if ProcessServer(CurrentServer) then Synchronize(@NotifyObserversThreadMethod); if terminated then break; end; except end; end; FreeAndNil(ServersList); end; constructor TLongPollWorker.Create(CreateSuspended: boolean; Communities: TCommunityList); var i: integer; begin Observable := TVKCMObservable.Create; CommunitiesKeys := TStringList.Create; for i := 0 to Communities.Count - 1 do CommunitiesKeys.Add(Communities[i].AccessKey); FreeAndNil(Communities); inherited Create(CreateSuspended); end; procedure TLongPollWorker.SubscribeForNotifications(Me: TVKCMObserver); begin Me.Subscribe(Observable); end; destructor TLongPollWorker.Destroy; begin inherited Destroy; end; end.
unit xxmWebProject; interface uses Windows, SysUtils, Classes, MSXML2_TLB; type TXxmWebProjectOutput=procedure(Msg:string); TXxmWebProject=class(TObject) private Data:DOMDocument; DataStartSize:integer; DataFileName,FProjectName,FRootFolder,FSrcFolder,FProtoPathDef,FProtoPath:string; RootNode,DataFiles:IXMLDOMElement; Modified:boolean; Signatures:TStringList; FOnOutput:TXxmWebProjectOutput; function GetNode(element:IXMLDOMElement;xpath:string):IXMLDOMElement; function GetNodeText(element:IXMLDOMElement;xpath:string):string; function ForceNode(element:IXMLDOMElement;tagname:string):IXMLDOMElement; function ForceNodeID(element:IXMLDOMElement;tagname,id:string):IXMLDOMElement; function NodesText(element:IXMLDOMElement;xpath:string):string; function ReadString(FilePath:string):string; procedure BuildOutput(Msg:string); public constructor Create(SourcePath:string; OnOutput:TXxmWebProjectOutput; CanCreate:boolean); destructor Destroy; override; function CheckFiles(Rebuild:boolean):boolean; function GenerateProjectFiles(Rebuild: boolean):boolean; function Compile:boolean; procedure Update; property ProjectName:string read FProjectName; property RootFolder:string read FRootFolder; property ProjectFile:string read DataFileName; end; EXxmWebProjectNotFound=class(Exception); EXxmWebProjectLoad=class(Exception); implementation uses Variants, ComObj, xxmUtilities, xxmProtoParse, xxmPageParse, IniFiles; { TXxmWebProject } const SXxmWebProjectNotFound='Web Project File not found for "__"'; SXxmWebProjectLoad='Could not read "__"'; constructor TXxmWebProject.Create(SourcePath: string; OnOutput:TXxmWebProjectOutput; CanCreate:boolean); var x:IXMLDOMElement; i:integer; s:string; f:TFileStream; begin inherited Create; Modified:=false; FOnOutput:=OnOutput; FProjectName:=''; //assert full expanded path //SourcePath:=ExpandFileName(SourcePath); i:=Length(SourcePath); while not(i=0) and not(SourcePath[i]='.') do dec(i); if LowerCase(Copy(SourcePath,i,Length(SourcePath)-i+1))=XxmFileExtension[ftProject] then begin //project file specified while not(i=0) and not(SourcePath[i]=PathDelim) do dec(i); FRootFolder:=Copy(SourcePath,1,i); DataFileName:=Copy(SourcePath,i+1,Length(SourcePath)-i); end else begin //find DataFileName:=XxmProjectFileName; FRootFolder:=IncludeTrailingPathDelimiter(SourcePath); i:=Length(FRootFolder); while not(i=0) and not(FileExists(FRootFolder+DataFileName)) do begin dec(i); while not(i=0) and not(FRootFolder[i]=PathDelim) do dec(i); SetLength(FRootFolder,i); end; if i=0 then if CanCreate then begin //create empty project if DirectoryExists(SourcePath) then FRootFolder:=IncludeTrailingPathDelimiter(SourcePath) else begin i:=Length(SourcePath); while not(i=0) and not(SourcePath[i]=PathDelim) do dec(i); FRootFolder:=Copy(SourcePath,1,i); end; i:=Length(FRootFolder)-1; while not(i=0) and not(FRootFolder[i]=PathDelim) do dec(i); FProjectName:=Copy(FRootFolder,i+1,Length(FRootFolder)-i-1); s:='<XxmWebProject>'#13#10#9'<ProjectName></ProjectName>'#13#10#9+ '<CompileCommand>dcc32 -U..\..\public -Q [[ProjectName]].dpr</CompileCommand>'#13#10'</XxmWebProject>'; f:=TFileStream.Create(FRootFolder+DataFileName,fmCreate); try f.Write(s[1],Length(s)); finally f.Free; end; end else raise EXxmWebProjectNotFound.Create(StringReplace( SXxmWebProjectNotFound,'__',SourcePath,[])); end; FProtoPathDef:=GetSelfPath+ProtoDirectory+PathDelim; FSrcFolder:=FRootFolder+SourceDirectory+PathDelim; Signatures:=TStringList.Create; try Signatures.LoadFromFile(FRootFolder+DataFileName+SignaturesExtension); except //silent end; Data:=CoDOMDocument.Create; Data.async:=false; Data.preserveWhiteSpace:=true; if not(Data.load(FRootFolder+DataFileName)) then raise EXxmWebProjectLoad.Create(StringReplace( SXxmWebProjectLoad,'__',FRootFolder+DataFileName,[])+ #13#10+Data.parseError.reason); RootNode:=Data.documentElement; DataStartSize:=Length(Data.xml); x:=ForceNode(RootNode,' UUID'); if x.text='' then x.text:=CreateClassID;//other random info? x:=ForceNode(RootNode,' ProjectName'); if x.text='' then begin if FProjectName='' then begin i:=Length(DataFileName); while not(i=0) and not(DataFileName[i]='.') do dec(i); FProjectName:=Copy(DataFileName,1,Length(DataFileName)-i-1); end; x.text:=FProjectName; end else FProjectName:=x.text; DataFiles:=ForceNode(RootNode,' Files'); //TODO: setting protopath? if DirectoryExists(FRootFolder+ProtoDirectory) then FProtoPath:=FRootFolder+ProtoDirectory+PathDelim else FProtoPath:=FProtoPathDef; //TODO: setting sourcepath? //TODO: //Settings/@AutoAddFiles //Settings/@AutoRemoveFiles //TODO:delphi source in separate buildfolder? end; destructor TXxmWebProject.Destroy; begin //Update was here before Data:=nil; Signatures.Free; inherited; end; procedure TXxmWebProject.Update; var fn:string; begin if Modified then begin if not(DataStartSize=Length(Data.xml)) then begin ForceNode(RootNode,' LastModified').text:= FormatDateTime('yyyy-mm-dd"T"hh:nn:ss',Now);//timezone? Data.save(FRootFolder+DataFileName); Modified:=false; end; //save signatures try fn:=FRootFolder+DataFileName+SignaturesExtension; SetFileAttributes(PChar(fn),0); Signatures.SaveToFile(fn); SetFileAttributes(PChar(fn),FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM); except //silent? end; end; end; function TXxmWebProject.CheckFiles(Rebuild:boolean): boolean; var p:TXxmProtoParser; q:TXxmPageParser; xl:IXMLDOMNodeList; xFile,x:IXMLDOMElement; fn,fnu,s,cid,uname,upath,uext:string; sl,sl1:TStringList; sl_i,i,cPathIndex,fExtIndex,fPathIndex:integer; begin Result:=false; //TODO: setting autoaddfiles //TODO: autoremove files? p:=TXxmProtoParser.Create; q:=TXxmPageParser.Create; try sl:=TStringList.Create; sl1:=TStringList.Create; try xl:=DataFiles.selectNodes('File'); try x:=xl.nextNode as IXMLDOMElement; while not(x=nil) do begin sl1.Add(x.getAttribute('ID')); x:=xl.nextNode as IXMLDOMElement; end; finally xl:=nil; end; ListFilesInPath(sl,FRootFolder); for sl_i:=0 to sl.Count-1 do begin fn:=sl[sl_i]; cid:=GetInternalIdentifier(fn,cPathIndex,fExtIndex,fPathIndex); xFile:=ForceNodeID(DataFiles,' File',cid); i:=sl1.IndexOf(cid); if not(i=-1) then sl1.Delete(i); //fn fit for URL fnu:=StringReplace(fn,'\','/',[rfReplaceAll]); x:=ForceNode(xFile,'Path'); x.text:=fnu; //BuildFile(xFile,fn,cid,Rebuild); //pascal unit name upath:=VarToStr(xFile.getAttribute('UnitPath')); uname:=VarToStr(xFile.getAttribute('UnitName')); if fExtIndex=0 then uext:='' else uext:=Copy(fn,fExtIndex+1,Length(fn)-fExtIndex); if uname='' then begin //unique counter for project uname:=Copy(cid,cPathIndex,Length(cid)-cPathIndex+1); if not(uname[1] in ['A'..'Z','a'..'z']) then uname:='x'+uname; i:=0; repeat inc(i); s:=uname+IntToStr(i); x:=DataFiles.selectSingleNode('File[@UnitName="'+s+'"]') as IXMLDOMElement; until (x=nil); uname:=s; xFile.setAttribute('UnitName',uname); Modified:=true; end; if upath='' then begin upath:=Copy(fn,1,fPathIndex); xFile.setAttribute('UnitPath',upath); end; //TODO: setting no pas subdirs? //TODO: proto signature? (setting?) s:=Signature(FRootFolder+fn); if Rebuild or not(Signatures.Values[uname]=s) or not( FileExists(FSrcFolder+upath+uname+DelphiExtension)) then begin Signatures.Values[uname]:=s; Modified:=true; BuildOutput(':'+FProjectName+':'+fn+':'+uname+':'+cid+#13#10); //TODO: alternate proto? either XML tag or default file. s:=FRootFolder+fn+XxmProtoExtension; if not(FileExists(s)) then s:=FProtoPath+uext+DelphiExtension; if not(FileExists(s)) then s:=FProtoPathDef+uext+DelphiExtension; p.Parse(ReadString(s)); q.Parse(ReadString(FRootFolder+fn)); repeat case p.GetNext of ptProjectName:p.Output(FProjectName); ptProtoFile:p.Output(FProtoPath+uext+DelphiExtension); ptFragmentID:p.Output(cid); ptFragmentUnit:p.Output(uname); ptFragmentAddress:p.Output(fnu); ptUsesClause:p.Output(q.AllSections(psUses));//TODO: check comma's? ptFragmentDefinitions:p.Output(q.AllSections(psDefinitions)); ptFragmentHeader:p.Output(q.AllSections(psHeader)); ptFragmentBody:p.Output(q.BuildBody); ptFragmentFooter:p.Output(q.AllSections(psFooter)); //else raise? end; until p.Done; ForceDirectories(FSrcFolder+upath); p.Save(FSrcFolder+upath+uname+DelphiExtension); Result:=true; end; end; //delete missing files for sl_i:=0 to sl1.Count-1 do begin cid:=sl1[sl_i]; xFile:=ForceNodeID(DataFiles,'File',cid); //TODO: setting keep pas? uname:=VarToStr(xFile.getAttribute('UnitName')); upath:=VarToStr(xFile.getAttribute('UnitPath')); DeleteFile(FSrcFolder+upath+uname+DelphiExtension); xFile.parentNode.removeChild(xFile); Modified:=true; Result:=true; end; finally sl.Free; sl1.Free; end; //check units xl:=DataFiles.selectNodes('Unit'); try xFile:=xl.nextNode as IXMLDOMElement; while not(xFile=nil) and not(Result) do begin uname:=VarToStr(xFile.getAttribute('UnitName')); upath:=VarToStr(xFile.getAttribute('UnitPath')); fn:=upath+uname+DelphiExtension; s:=Signature(FRootFolder+fn); if not(Signatures.Values[uname]=s) then begin Signatures.Values[uname]:=s; Modified:=true; Result:=true; end; xFile:=xl.nextNode as IXMLDOMElement; end; finally xl:=nil; end; //missing? delete? GenerateProjectFiles(Rebuild); finally p.Free; q.Free; end; end; function TXxmWebProject.GenerateProjectFiles(Rebuild:boolean):boolean; var p:TXxmProtoParser; x:IXMLDOMElement; xl:IXMLDOMNodeList; fh:THandle; fd:TWin32FindData; fn1,fn2,s:string; i:integer; begin Result:=false; //project files fn1:=FSrcFolder+FProjectName+DelphiProjectExtension; fn2:=FRootFolder+ProtoProjectPas; if Modified or Rebuild or not(FileExists(fn1)) or not(FileExists(fn2)) then begin //TODO: flags from project XML? //TODO: signatures? p:=TXxmProtoParser.Create; try //[[ProjectName]].dpr BuildOutput(FProjectName+DelphiProjectExtension+#13#10); s:=FProtoPath+ProtoProjectDpr; if not(FileExists(s)) then s:=FProtoPathDef+ProtoProjectDpr; p.Parse(ReadString(s)); repeat case p.GetNext of ptProjectName:p.Output(FProjectName); ptProtoFile:p.Output(FProtoPath+ProtoProjectDpr); ptIterateFragment: begin xl:=DataFiles.selectNodes('File'); x:=xl.nextNode as IXMLDOMElement; p.IterateBegin(not(x=nil)); end; ptIterateInclude: begin xl:=DataFiles.selectNodes('Unit'); x:=xl.nextNode as IXMLDOMElement; p.IterateBegin(not(x=nil)); end; ptFragmentUnit:p.Output(VarToStr(x.getAttribute('UnitName'))); ptFragmentPath:p.Output(VarToStr(x.getAttribute('UnitPath'))); ptFragmentAddress:p.Output(GetNode(x,'Path').text); ptIncludeUnit:p.Output(VarToStr(x.getAttribute('UnitName'))); ptIncludePath:p.Output(VarToStr(x.getAttribute('UnitPath'))); ptIterateEnd: begin x:=xl.nextNode as IXMLDOMElement; p.IterateNext(not(x=nil)); end; ptUsesClause: p.Output(NodesText(RootNode,'UsesClause')); ptProjectHeader: p.Output(NodesText(RootNode,'Header')); ptProjectBody: p.Output(NodesText(RootNode,'Body')); //else raise? end; until p.Done; ForceDirectories(FSrcFolder); p.Save(fn1); //xxmp.pas if not(FileExists(fn2)) then begin BuildOutput(ProtoProjectPas+#13#10); s:=FProtoPath+ProtoProjectPas; if not(FileExists(s)) then s:=FProtoPathDef+ProtoProjectPas; p.Parse(ReadString(s)); repeat case p.GetNext of ptProjectName:p.Output(FProjectName); ptProtoFile:p.Output(FProtoPath+ProtoProjectPas); end; until p.Done; p.Save(fn2); end; //copy other files the first time (cfg,dof,res...) fh:=FindFirstFile(PChar(FProtoPath+ProtoProjectMask),fd); if not(fh=INVALID_HANDLE_VALUE) then begin repeat s:=fd.cFileName; if not(s=ProtoProjectDpr) then begin i:=Length(s); while not(i=0) and not(s[i]='.') do dec(i); fn1:=FSrcFolder+FProjectName+Copy(s,i,Length(s)-i+1); if not(FileExists(fn1)) then begin BuildOutput(fn1+#13#10); CopyFile(PChar(FProtoPath+s),PChar(fn1),false); end; end; until not(FindNextFile(fh,fd)); Windows.FindClose(fh); end; fh:=FindFirstFile(PChar(FProtoPathDef+ProtoProjectMask),fd); if not(fh=INVALID_HANDLE_VALUE) then begin repeat s:=fd.cFileName; if not(s=ProtoProjectDpr) then begin i:=Length(s); while not(i=0) and not(s[i]='.') do dec(i); fn1:=FSrcFolder+FProjectName+Copy(s,i,Length(s)-i+1); if not(FileExists(fn1)) then begin BuildOutput(fn1+#13#10); CopyFile(PChar(FProtoPathDef+s),PChar(fn1),false); end; end; until not(FindNextFile(fh,fd)); Windows.FindClose(fh); end; finally p.Free; end; Result:=true; end; end; function TXxmWebProject.GetNode(element: IXMLDOMElement; xpath: string): IXMLDOMElement; begin Result:=element.selectSingleNode(xpath) as IXMLDOMElement; end; function TXxmWebProject.GetNodeText(element: IXMLDOMElement; xpath: string): string; var x:IXMLDOMNode; begin x:=element.selectSingleNode(xpath); if x=nil then Result:='' else Result:=x.text; end; function TXxmWebProject.ForceNode(element:IXMLDOMElement;tagname:string): IXMLDOMElement; begin Result:=element.selectSingleNode(tagname) as IXMLDOMElement; if Result=nil then begin if tagname[1]=' ' then begin element.appendChild(element.ownerDocument.createTextNode(#13#10)); Result:=element.ownerDocument.createElement(Copy(tagname,2,Length(tagname)-1)); end else Result:=element.ownerDocument.createElement(tagname); element.appendChild(Result); Modified:=true; end; end; function TXxmWebProject.ForceNodeID(element: IXMLDOMElement; tagname, id: string): IXMLDOMElement; begin Result:=element.selectSingleNode(tagname+'[@ID="'+id+'"]') as IXMLDOMElement; if Result=nil then begin if tagname[1]=' ' then begin element.appendChild(element.ownerDocument.createTextNode(#13#10)); Result:=element.ownerDocument.createElement(Copy(tagname,2,Length(tagname)-1)); end else Result:=element.ownerDocument.createElement(tagname); Result.setAttribute('ID',id); element.appendChild(Result); Modified:=true; end; end; function TXxmWebProject.ReadString(FilePath: string): string; var f:TFileStream; l:int64; begin f:=TFileStream.Create(FilePath,fmOpenRead or fmShareDenyNone); try l:=f.Size; SetLength(Result,l); f.Read(Result[1],l); finally f.Free; end; end; function TXxmWebProject.NodesText(element: IXMLDOMElement;xpath:string): string; var xl:IXMLDOMNodeList; x:IXMLDOMElement; s:TStringStream; begin //CDATA? seems to work with .text xl:=element.selectNodes(xpath); x:=xl.nextNode as IXMLDOMElement; s:=TStringStream.Create(''); try while not(x=nil) do begin s.WriteString(x.text); x:=xl.nextNode as IXMLDOMElement; end; Result:= StringReplace( StringReplace( s.DataString, #13#10,#10,[rfReplaceAll]), #10,#13#10,[rfReplaceAll]); finally s.Free; end; end; function TXxmWebProject.Compile:boolean; var cl1,cl2,cl3:string; pi:TProcessInformation; si:TStartupInfo; h1,h2:THandle; sa:TSecurityAttributes; h:THandleStream; f:TFileStream; c:cardinal; d:array[0..$FFF] of char; function DoCommand(cmd:string):boolean; begin if not(CreateProcess(nil,PChar( StringReplace( cmd, '[[ProjectName]]',FProjectName,[rfReplaceAll]) //more? ), nil,nil,true,NORMAL_PRIORITY_CLASS,nil,PChar(FSrcFolder),si,pi)) then RaiseLastOSError; CloseHandle(pi.hThread); try while (WaitForSingleObject(pi.hProcess,50)=WAIT_TIMEOUT) or not(h.Size=0) do begin c:=h.Read(d[0],$1000); if not(c=0) then begin f.Write(d[0],c); d[c]:=#0; BuildOutput(d); end; end; Result:=GetExitCodeProcess(pi.hProcess,c) and (c=0); finally CloseHandle(pi.hProcess); end; end; begin cl1:=GetNodeText(RootNode,'PreCompileCommand'); cl2:=GetNodeText(RootNode,'CompileCommand'); cl3:=GetNodeText(RootNode,'PostCompileCommand'); if (cl1='') and (cl2='') and (cl3='') then Result:=true else begin //more? f:=TFileStream.Create(FRootFolder+FProjectName+ProjectLogExtension,fmCreate); try sa.nLength:=SizeOf(TSecurityAttributes); sa.lpSecurityDescriptor:=nil; sa.bInheritHandle:=true; if not(CreatePipe(h1,h2,@sa,$10000)) then RaiseLastOSError; ZeroMemory(@si,SizeOf(TStartupInfo)); si.cb:=SizeOf(TStartupInfo); si.dwFlags:=STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; si.wShowWindow:=SW_HIDE; si.hStdOutput:=h2; si.hStdError:=h2; Result:=true; h:=THandleStream.Create(h1); try if Result and not(cl1='') then Result:=DoCommand(cl1); if Result and not(cl2='') then Result:=DoCommand(cl2); if Result and not(cl3='') then Result:=DoCommand(cl3); finally h.Free; CloseHandle(h1); CloseHandle(h2); end; finally f.Free; end; end; end; procedure TXxmWebProject.BuildOutput(Msg: string); begin FOnOutput(Msg); end; end.
unit uReport; interface uses System.Generics.Collections, System.SysUtils; type ETCMStoredProcNameMissing = class(Exception); // Subreport(s) TCMSReportData = class; // Forward declaration TCMSReportsData = TList<TCMSReportData>; // Mainreport(s) TCMMReportData = class; // Forward declaration TCMMReportsData = TList<TCMMReportData>; // TODO!! Test this what happends if it exists same Parametername in two different subreports or mainreport. // An exception is likely - we want to know, in such case, what exception is thrown so that we can ignore that exception. TCMParams = TDictionary<string, variant>; TCMParamInfo = TPair<string, string>; TCMParamsInfo = TDictionary<string, string>; TCMReportData = class private FReportNo: integer; FdatasetUserName: string; FstoredProcName: string; Fname: string; Fdescription: string; FparamsInfo: TCMParamsInfo; FParams: TCMParams; FSubreportsData: TCMSReportsData; public constructor Create(aReportNo: integer; aDatasetName: string; aStoredProcName: string; aDescription: string; aname: string; aParamsInfo: TCMParamsInfo); destructor destroy; property ReportNo: integer read FReportNo write FReportNo; property datasetUserName: string read FdatasetUserName write FdatasetUserName; property storedProcName: string read FstoredProcName write FstoredProcName; property name: string read Fname write Fname; property description: string read Fdescription write Fdescription; property paramsInfo: TCMParamsInfo read FparamsInfo write FparamsInfo; property params: TCMParams read FParams write FParams; property subReportsData: TCMSReportsData read FSubreportsData write FSubreportsData; end; TCMSReportData = class(TCMReportData) end; TCMMReportData = class(TCMReportData) private FTemplate: string; FdocType: integer; FdocTypeName: string; public constructor Create(aReportNo: integer; aDatasetName: string; aStoredProcName: string; aDescription: string; aTemplate: string; adocType: integer; aParamsInfo: TCMParamsInfo); function getAllParameters: TCMParamsInfo; property Template: string read FTemplate write FTemplate; property docType: integer read FdocType write FdocType; property docTypeName: string read FdocTypeName write FdocTypeName; end; implementation function TCMMReportData.getAllParameters: TCMParamsInfo; var allPar, MainPar: TCMParamsInfo; SRName, parName, keys: string; i: integer; begin { Gather all parameters from mainreport and all subreports in this report } allPar := TCMParamsInfo.Create(); result := nil; if FparamsInfo <> nil then begin for parName in FparamsInfo.keys do begin allPar.add(parName, FparamsInfo.Items[parName]); end; end; try if FSubreportsData <> nil then begin for i := 0 to FSubreportsData.Count - 1 do begin with FSubreportsData[i] do begin if FparamsInfo <> nil then begin for parName in FparamsInfo.keys do begin allPar.add(parName, FparamsInfo.Items[parName]); end; end; end; end; end; except on E: EListError do end; result := allPar; end; constructor TCMReportData.Create(aReportNo: integer; aDatasetName, aStoredProcName, aDescription, aname: string; aParamsInfo: TCMParamsInfo); begin FReportNo := aReportNo; FdatasetUserName := aDatasetName; FstoredProcName := aStoredProcName; Fdescription := aDescription; Fname := aname; FparamsInfo := aParamsInfo; end; constructor TCMMReportData.Create(aReportNo: integer; aDatasetName, aStoredProcName, aDescription, aTemplate: string; adocType: integer; aParamsInfo: TCMParamsInfo); begin inherited Create(aReportNo, aDatasetName, aStoredProcName, aDescription, '', aParamsInfo); FdocType := adocType; FTemplate := aTemplate; end; destructor TCMReportData.destroy; var SRD: TCMSReportData; begin paramsInfo.Free; params.Free; for SRD in FSubreportsData do begin SRD.destroy; SRD.Free; end; end; end.
unit UEditor; interface uses Windows, Messages, UxlRichEdit, Resource, richedit, UCalcHandler, UxlStrUtils, UPageSuper, UxlRichEditClasses, UDialogs, UxlFunctions, UClientSuper, UxlWinControl, UxlClasses, UxlExtClasses, UxlList, UTypeDef, UFindHandler; type TSelMemo = class private FBookMarks: TxlStrList; FTempList: TxlIntList; public constructor Create (); destructor Destroy (); override; procedure SetSel (id: integer; i_start, i_len, i_line: integer); procedure GetSel (id: integer; var i_start, i_len, i_line: integer); end; THLTextHandler = class (TxlInterfacedObject, IOptionObserver, ICommandExecutor) private FEditor: TxlRichEdit; FULText: TxlRichEditHighlightTextBlock; FUL1, FUL2: widestring; public constructor Create (AEditor: TxlRichEdit); destructor Destroy (); override; function CheckCommand (opr: word): boolean; procedure ExecuteCommand (opr: word); procedure OptionChanged (); end; TEditorClient = class (TClientSuper, IOptionObserver, IMemorizer, IEventObserver, IMessageObserver) private FWndParent: TxlWinControl; FEditor: TxlRichEdit; FSelMemo: TSelMemo; FFindHandler: TFindHandler; FCalcHandler: TCalcHandler; FLineNumber: TxlRichEditLineNumber; FHLSelLine: TxlRichEditHighlightSelLine; FHLTextHandler: THLTextHandler; procedure f_OnChange (Sender: TObject); procedure SetStatus (); function f_OnContextmenu (Sender: TObject): boolean; procedure f_RestoreScrollPos (); procedure f_SaveScrollPos (); procedure f_OnLink (const s_link: widestring); protected procedure Load (value: TPageSuper); override; procedure UnLoad (); override; public constructor Create (WndParent: TxlWinContainer); destructor Destroy (); override; function Control (): TxlControl; override; procedure Save (); override; procedure OnPageEvent (pct: TPageEvent; id, id2: integer); override; function CheckCommand (opr: word): boolean; override; procedure ExecuteCommand (opr: word); override; procedure OptionChanged (); procedure RestoreMemory (); procedure SaveMemory (); procedure EventNotify (event, wparam, lparam: integer); function ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; end; implementation uses CommDlg, UxlCommDlgs, UxlMath, UxlWinClasses, UxlWinDef, UxlWindow, ShellAPI, UGlobalObj, UOptionManager, ULangManager, UExtFuncs, UxlListSuper, UPageStore, UPageFactory; constructor TSelMemo.Create (); begin FBookMarks := TxlStrList.Create (500); FBookMarks.IndexDeli := '='; FBookMarks.LoadFromFile (DataDir + 'minipad2.bmk'); FBookMarks.SortType := stByIndexNoDup; FTempList := TxlIntList.Create (3); FTempList.Separator := ','; end; destructor TSelMemo.Destroy (); begin FBookMarks.Free; FTempList.Free; inherited; end; procedure TSelMemo.SetSel (id: integer; i_start, i_len, i_line: integer); // 不要试图记录 FEditor.ScrollPos!!! var s: widestring; begin s := IntToStr(i_start) + ',' + IntToStr(i_len) + ',' + IntToStr (i_line); if s <> FBookMarks.ItemsByIndex[id] then begin FBookMarks.ItemsByIndex[id] := s; FBookMarks.SaveToFile (DataDir + 'minipad2.bmk'); end; end; procedure TSelMemo.GetSel (id: integer; var i_start, i_len, i_line: integer); begin FTempList.Text := FBookMarks.ItemsByIndex[id]; i_start := FTempList[0]; i_len := FTempList[1]; i_line := FTempList[2]; end; //---------------------- constructor THLTextHandler.Create (AEditor: TxlRichEdit); begin FEditor := AEditor; FULText := TxlRichEditHighlightTextBlock.Create (FEditor); FULText.Enabled := true; CommandMan.AddExecutor (self); OptionMan.AddObserver (self); end; destructor THLTextHandler.Destroy (); begin OptionMan.RemoveObserver (self); CommandMan.RemoveExecutor (self); FULText.free; inherited; end; procedure THLTextHandler.ExecuteCommand (opr: word); function f_IsRightChar (c2: widechar): boolean; var i: integer; begin result := false; for i := 0 to 3 do if c2 = FULText.Schemes[i].RightChar then begin result := true; exit; end; end; procedure f_RemoveUnderline (); var i_start, i_len, i, i_start1, i_count: integer; s1, s: widestring; i_pos1, i_pos2: integer; begin FEditor.GetSel (i_start, i_len); s := FEditor.SelText; i_pos1 := -1; i_pos2 := -1; // 寻找最近的一个 LeftChar if (i_start > 0) and (FEditor.GetTextBlock (i_start - 1, 1) = FULText.LeftChar) then i_pos1 := i_start - 1 else begin s1 := FEditor.GetTextBlock (i_start, i_len); for i := 1 to i_len do begin if (s1[i] = FULText.LeftChar) then begin i_pos1 := i + i_start - 1; break; end; end; end; if i_pos1 < 0 then begin i_start1 := max(i_start - 2000, 0); s1 := FEditor.GetTExtBlock (i_start1, i_start - i_start1); for i := length(s1) downto 1 do if (s1[i] = FULText.LeftChar) then begin i_pos1 := i + i_start1 - 1; break; end; end; if i_pos1 < 0 then exit; // 寻找匹配的 RightChar i_count := 1; s1 := FEditor.GetTextBlock (i_pos1 + 1, max(i_len + i_start - i_pos1, 2000)); for i := 1 to length(s1) do begin if s1[i] = FULText.LeftChar then inc (i_count) else if f_IsRightChar(s1[i]) then begin dec (i_count); if i_count = 0 then begin i_pos2 := i + i_pos1; if (i_pos1 < i_start) and (i_pos2 < i_start) then exit; break; end; end; end; if i_pos2 < 0 then exit; FEditor.SetSel (i_pos1, i_pos2 - i_pos1 + 1); s := FEditor.SelText; s := MidStr (s, 2, length(s) - 2); FEditor.SelTExt := s; FEditor.SetSel (i_pos1, i_pos2 - i_pos1 - 1); FEditor.Redraw; end; procedure f_RemoveList (); begin FEditor.Indent (false, FUL1); FEditor.Indent (false, FUL2); FEditor.Indent (false); end; procedure f_addcr (var pr: pwidechar); begin pr^ := #13; inc (pr); pr^ := #10; inc (pr); end; procedure f_FilterEmptyLine (var s: widestring; b_oneemptyline: boolean); var i, j, n: integer; p, p2: pwidechar; c: widechar; b_hasbreak: boolean; s2: widestring; begin n := Length(s); if n = 0 then exit; // s2 := ''; getmem (p, n*4+2); p2 := p; b_hasbreak := false; for i := 1 to n do begin c := s[i]; if (c = #13) then begin b_hasbreak := true; s2 := ''; end else if (c = #10) then begin end else if ((c = #9) or (c = #32)) and b_hasbreak then begin s2 := s2 + c; end else begin if b_hasbreak then begin f_addcr (p2); if b_oneemptyline then f_addcr (p2); if s2 <> '' then for j := 1 to length(s2) do begin p2^ := s2[j]; inc (p2); end; b_hasbreak := false; end; p2^ := c; inc (p2); end; end; if b_oneemptyline then f_addcr (p2); p2^ := #0; s := p; freemem (p); // for i := n downto 1 do // if (s[i] = #13) and ((i = n) or (s[i+1] <> #10)) then // Insert (s, i + 1, #10); // // n := Length(s); // for i := n - 3 downto 1 do // if (MidStr(s, i, 2) = #13#10) and (MidStr(s, i+2, 2) = #13#10) then // Delete (s, i+2, 2); // if LeftStr(s, 2) = #13#10 then // Delete (s, 1, 2); // // if b_oneemptyline then // begin // n := Length(s); // for i := n - 2 downto 1 do // if s[i] = #13 then // Insert (s, i+2, #13#10); // end; end; var i, i_start, i_len: integer; s: widestring; begin if not CheckCommand (opr) then exit; case opr of m_highlight1, m_highlight2, m_highlight3, m_highlight4: begin case opr of m_highlight1: i := 0; m_highlight2: i := 1; m_highlight3: i := 2; m_highlight4: i := 3; end; FEditor.GetSel (i_start, i_len); s := FEditor.SelText; if RightStr (s, 1) = #13 then begin dec (i_len, 1); FEditor.SetSel (i_start, i_len); end; FEditor.SelTExt := FULText.LeftChar + FEditor.SelTExt + FULText.Schemes[i].RightChar; FEditor.SetSel (i_start + 1, i_len); end; m_removehighlight: f_RemoveUnderline; m_ul1: begin f_RemoveList; FEditor.Indent (true, FUL1); end; m_ul2: begin f_RemoveList; FEditor.Indent (true, FUL2); end; m_ol: begin f_RemoveList; FEditor.Indent (true); end; m_removelist: f_RemoveList; m_noemptyline, m_oneemptyline: begin FEditor.GetSel (i_start, i_len); if i_len = 0 then FEditor.SelectAll; s := FEditor.SelText; f_FilterEmptyLine (s, opr = m_oneemptyline); FEditor.SelText := s; end; end; end; function THLTextHandler.CheckCommand (opr: word): boolean; begin case opr of m_highlight1, m_highlight2, m_highlight3, m_highlight4: result := FEditor.CanCut; m_ul1, m_ul2, m_ol, m_removelist: result := FEditor.CanIndent; // m_noemptyline, m_oneemptyline: // result := FEditor.TextCount > 0; else result := true; end; end; procedure THLTextHandler.OptionChanged (); var sc: TULScheme; i: integer; begin for i := 1 to 4 do // 共四套方案 begin if i = 4 then sc.RightChar := #127 else sc.RightChar := widechar (i + 28); sc.Color := OptionMan.Options.HLColor[i]; if OptionMan.Options.HLUnderline[i] then sc.Thickness := 2 else sc.Thickness := 0; FULText.Schemes[i - 1] := sc; end; FUL1 := OptionMan.Options.UL1; FUL2 := OptionMan.Options.UL2; end; //---------------------- constructor TEditorClient.Create (WndParent: TxlWinContainer); begin FWndParent := WndParent; FEditor := TxlRichEdit.Create (WndParent); FEditor.OnChange := f_OnChange; FEditor.OnContextMenu := f_OnContextMenu; FEditor.OnLink := f_OnLink; FLineNumber := TxlRichEditLineNumber.Create (FEditor); FLineNumber.Font := FEditor.Font; FHLSelLine := TxlRichEditHighlightSelLine.Create (FEditor); FHLtextHandler := THLTextHandler.Create (FEditor); FFindHandler := TFindHandler.Create (FEditor); FCalcHandler := TCalcHandler.Create (FEditor); FSelMemo := TSelMemo.Create; OptionMan.AddObserver(self); MemoryMan.AddObserver (self); EventMan.AddObserver (self); MainWindow.AddMessageObserver (self); end; destructor TEditorClient.Destroy (); begin MainWindow.RemoveMessageObserver (self); EventMan.RemoveObserver(self); MemoryMan.RemoveObserver (self); OptionMan.RemoveObserver(self); FHLtextHandler.Free; FHLSelLine.free; FLineNumber.free; FSelMemo.Free; FCalcHandler.Free; FFindHandler.Free; FEditor.Free; inherited; end; function TEditorClient.Control (): TxlControl; begin result := FEditor; end; procedure TEditorClient.f_OnChange (Sender: TObject); begin CommandMan.CheckCommands; end; //---------------------- procedure TEditorClient.Load (value: TPageSuper); begin if value = nil then exit; inherited Load (value); FEditor.Text := value.Text; SetStatus (); FCalcHandler.PageType := value.PageType; MainWindow.Post (WM_RESTORESCROLLPOS, 0, 0); if OptionMan.Options.AlwaysFocusEditor then MainWindow.Post (WM_FOCUSEDITOR, 0, 0); end; procedure TEditorClient.UnLoad (); begin FEditor.Text := ''; end; procedure TEditorClient.f_RestoreScrollPos (); var i_selstart, i_sellength, i_line: integer; i_start, i_end: cardinal; sc: TPoint; begin if not OptionMan.Options.RememberPageScroll then exit; FSelMemo.GetSel (FPage.id, i_selstart, i_sellength, i_line); // if OptionMan.Options.BmkRule = 0 then // 适合于绝大部分情况。尝试恢复 FEditor.ScrollPos 会导致大文本下无法恢复位置bug!!! FEditor.FirstVisibleLine := i_line; // else // begin // 3.1.6 的算法。可能适合于繁体中文版 // sc.x := 0; // sc.y := i_line; // FEditor.ScrollPos := sc; // end; // FEditor.ScrollPos := FEditor.ScrollPos; FEditor.GetVisibleTextRange (i_start, i_end); if InRange (i_selstart, i_start, i_end) and (i_selstart + i_sellength <= i_end) then FEditor.SetSel(i_SelStart, i_SelLength) else FEditor.SetSel (i_start, 0); end; procedure TEditorClient.f_SaveScrollPos (); var i_selstart, i_sellength, i_line: integer; begin if not OptionMan.Options.RememberPageScroll then exit; FEditor.GetSel (i_selstart, i_sellength); if OptionMan.Options.BmkRule = 0 then i_line := FEditor.FirstVisibleLine else i_line := FEditor.ScrollPos.y; FSelMemo.SetSel (FPage.id, i_selstart, i_sellength, i_line); end; procedure TEditorClient.Save (); begin FPage.Text := FEditor.Text; f_SaveScrollPos; inherited; end; procedure TEditorClient.SetStatus (); begin FEditor.Protected := (FPage.Status = psProtected); FEditor.ReadOnly := (FPage.Status = psReadOnly); end; procedure TEditorClient.OptionChanged (); begin with FEditor do begin UndoLimit := OptionMan.Options.undolimit; TabStops := OptionMan.Options.tabstops; AutoIndent := OptionMan.Options.autoindent; AutoEmptyLine := OptionMan.Options.autoemptyline; Font := OptionMan.Options.editorfont; Color := OptionMan.Options.editorcolor; LeftMargin := OptionMan.Options.Margins * 4 + 2; RightMargin := OptionMan.Options.Margins * 4 + 2; SmoothScroll := OptionMan.Options.SmoothScroll; OneClickOpenLink := OptionMan.Options.OneClickOpenLink; end; FLineNumber.Color := OptionMan.Options.LineNumberColor; FLineNumber.Enabled := OptionMan.Options.showlinenumber; FHLSelLine.Color := Optionman.Options.SelLineColor; FHLSelLine.Enabled := OptionMan.Options.HighLightSelLine; end; procedure TEditorClient.RestoreMemory (); begin FEditor.WordWrap := MemoryMan.WordWrap; CommandMan.ItemChecked [m_wordwrap] := FEditor.WordWrap; end; procedure TEditorClient.SaveMemory (); begin MemoryMan.WordWrap := FEditor.WordWrap; end; //--------------------- procedure TEditorClient.OnPageEvent (pct: TPageEvent; id, id2: integer); begin case pct of pctSwitchStatus: if id = FPage.id then SetStatus (); else inherited OnPageEvent (pct, id, id2); end; end; function TEditorClient.CheckCommand (opr: word): boolean; begin with FEditor do // 不要进行任何牵涉到 IsEmpty 的判断,包括 CanClear!否则严重降低大文本下的执行效率! begin case opr of m_undo: result := CanUndo (); m_redo: result := CanRedo (); m_cut, m_delete: result := CanCut (); m_copy: result := CanCopy (); m_paste: result := CanPaste (); m_wordwrap: result := true; m_find, m_subsequentfind, m_findnext, m_findprevious, m_replace, m_replace_p, m_replaceall, m_highlightmatch: result := FFindHandler.CheckCommand (opr); else result := true; end; end; end; procedure TEditorClient.ExecuteCommand (opr: word); var s: widestring; o_box: TInsertLinkBox; begin if not CheckCommand (opr) then exit; case opr of m_wordwrap: begin f_SaveScrollPos; FEditor.WordWrap := not FEditor.WordWrap; CommandMan.ItemChecked [m_wordwrap] := FEditor.WordWrap; f_RestoreScrollPos; end; m_clear: begin if OptionMan.Options.ConfirmClear and (ShowMessage (LangMan.GetItem(sr_clearprompt), mtQuestion, LangMan.GetItem(sr_prompt)) = mrCancel) then exit; FEditor.clear (); end; m_delete: FEditor.DeleteSel; m_undo: FEditor.undo (); m_redo: FEditor.redo (); m_selectall: FEditor.selectall (); m_cut: FEditor.cut(); m_copy: FEditor.copy (); m_paste: FEditor.paste (); m_find, m_subsequentfind, m_findnext, m_findprevious, m_replace, m_replace_p, m_replaceall, m_highlightmatch: FFindHandler.ExecuteCommand (opr); m_insertlink: begin o_box := TInsertLinkBox.Create; if o_box.Execute then begin FEditor.SetFocus; FEditor.SelText := o_box.LinkText; end; o_box.free; end; hk_selastitle: begin s := FEditor.SelText; if s = '' then exit; FPage.Name := MultiLineToSingleLine (LeftStr(s, 200)); end; else exit; end; f_onchange (self); end; function TEditorClient.ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; var pt: TPoint; begin if not FEditor.visible then b_processed := false else begin b_processed := true; case AMessage of WM_FOCUSEDITOR: begin FEditor.SetFocus; if FEditor.CursorInWindow and KeyPressed(VK_LBUTTON) then // 不可省略!否则不能立即选中文字! begin pt := FEditor.CursorPos; FEditor.Post (WM_LBUTTONDOWN, 0, Makelparam(pt.x, pt.y)); end; end; WM_RESTORESCROLLPOS: f_RestoreScrollPos; else b_processed := false; end; end; end; procedure TEditorClient.EventNotify (event, wparam, lparam: integer); var s: widestring; n: integer; {$J+}const cs_settings: widestring = ''; {$J-} begin if not FEditor.Visible then exit; case event of // e_WinStatusChanged: // if wparam in [p_maximized] then // FEditor.FirstVisibleLine := FEditor.FirstVisibleLine; // 防止出现最大化后滚动超过页面底部的现象。 e_GetEditorSelText: EventMan.Message := IfThen (FEditor.Visible, FEditor.SelText, ''); e_AppendEditorText: begin s := EventMan.Message; n := FEditor.TextCount; if n > 0 then s := #13#10 + DecodeTemplate(OptionMan.Options.SepLine) + #13#10 + s; FEditor.SetSel (n, 0); FEditor.SelText := s; FEditor.SetSel (FEditor.TextCount, 0); end; end; end; function TEditorClient.f_OnContextmenu (Sender: TObject): boolean; var i_start, i_len: integer; begin result := false; FEditor.GetSel (i_start, i_len); if i_len > 0 then EventMan.EventNOtify (e_ContextMenuDemand, EditorContext) else EventMan.EventNOtify (e_ContextMenuDemand, EditorNoSelContext); end; procedure TEditorClient.f_OnLink (const s_link: widestring); procedure f_OnUserLink (s_link: widestring); var p: TPageSuper; idroot: integer; pt: TPoint; begin if LeftStr (s_link, 1) = '\' then begin PageStore.GetFirstPageId (ptGroupRoot, idroot); s_link := PageStore[idroot].Name + s_link; end else if LeftStr (s_link, 3) = '..\' then s_link := PageStore.GetPagePath (FPage.Owner) + MidStr (s_link, 3) else if LeftStr (s_link, 1) = '@' then s_link := PageStore.GetPagePath (FPage.Owner) + '\' + MidStr (s_link, 2); if PageStore.FindPageByPath (s_link, p) then begin // 防止双击造成文字选中的结果 pt.x := -1; pt.y := -1; ClientToScreen (FEditor.handle, pt); SetCursorPos (pt.x, pt.y); PageCenter.ActivePage := p; end else ProgTip.ShowTip (LangMan.GetItem(sr_invalidnodelink) + ': ' + s_link); end; var s: widestring; begin s := Trim(s_link); if IsSameStr(LeftStr(s, 8), 'outlook:') then begin s := MidStr (s, 9); while (length(s) > 0) and (s[1] = '/') do s := MidStr(s, 2); s := ReplaceStr (s, '/', '\'); f_OnUserLink (s); end else begin if IsSameStr (LeftStr(s, 5), 'file:') then s := RelToFullPath (s, ProgDir); try ExecuteLink (s); except end; end; end; end.
unit URegraCRUDCliente; interface uses URegraCRUD , UEntidade , UCliente , URepositorioDB , URepositorioCliente ; type TRegraCRUDCliente = class(TRegraCRUD) private function ValidateEmail(const emailAddress: string): Boolean; function isCPF(CPF: string): boolean; protected procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; destructor Destroy; override; function RetornaCliente(const ciIdCliente: Integer): TCLIENTE; function RetornaClientes: TArray<TCLIENTE>; procedure ValidaEmail(const csEmail: String); procedure ValidaCPF(const CPF: String); procedure ValidaDataNascimento(Data: TDate); procedure ValidaNome(const csNome: String); procedure ValidaNomeDuplicidade(const csNome: String; const ciIdCLIENTE: Integer); end; implementation { TRegraCRUDCliente } uses Generics.Collections , SysUtils , UUtilitarios , UMensagens , UConstantes , RegularExpressions ; constructor TRegraCRUDCliente.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioCliente.Create); end; destructor TRegraCRUDCliente.Destroy; begin FreeAndNil(FRepositorioDB); inherited; end; function TRegraCRUDCliente.isCPF(CPF: string): boolean; var dig10, dig11: string; s, i, r, peso: integer; begin // length - retorna o tamanho da string (CPF é um número formado por 11 dígitos) if ((CPF = '00000000000') or (CPF = '11111111111') or (CPF = '22222222222') or (CPF = '33333333333') or (CPF = '44444444444') or (CPF = '55555555555') or (CPF = '66666666666') or (CPF = '77777777777') or (CPF = '88888888888') or (CPF = '99999999999') or (length(CPF) <> 11)) then begin isCPF := false; exit; end; // try - protege o código para eventuais erros de conversão de tipo na função StrToInt try { *-- Cálculo do 1o. Digito Verificador --* } s := 0; peso := 10; for i := 1 to 9 do begin // StrToInt converte o i-ésimo caractere do CPF em um número s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig10 := '0' else str(r:1, dig10); // converte um número no respectivo caractere numérico { *-- Cálculo do 2o. Digito Verificador --* } s := 0; peso := 11; for i := 1 to 10 do begin s := s + (StrToInt(CPF[i]) * peso); peso := peso - 1; end; r := 11 - (s mod 11); if ((r = 10) or (r = 11)) then dig11 := '0' else str(r:1, dig11); { Verifica se os digitos calculados conferem com os digitos informados. } if ((dig10 = CPF[10]) and (dig11 = CPF[11])) then isCPF := true else isCPF := false; except isCPF := false end; end; function TRegraCRUDCliente.RetornaCliente(const ciIdCliente: Integer): TCLIENTE; var loCLIENTE: TCLIENTE; begin Result:= nil; for loCLIENTE in TRepositorioCLIENTE(FRepositorioDB).RetornaTodos do begin if loCLIENTE.ID = ciIdCliente then begin Result:= loCLIENTE; end; end; end; function TRegraCRUDCliente.RetornaClientes: TArray<TCLIENTE>; begin Result:= TRepositorioCliente(FRepositorioDB).RetornaTodos.ToArray; end; procedure TRegraCRUDCliente.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin inherited; ValidaNome(TCLIENTE(coENTIDADE).NOME); ValidaNomeDuplicidade(TCLIENTE(coENTIDADE).NOME, TCLIENTE(coENTIDADE).ID); ValidaEmail(TCLIENTE(coENTIDADE).EMAIL); ValidaCPF(TCLIENTE(coENTIDADE).CPF); ValidaDataNascimento(TCLIENTE(coENTIDADE).DATA_NASCIMENTO); end; procedure TRegraCRUDCliente.ValidaCPF(const CPF: String); begin if not isCPF(CPF) then begin raise EValidacaoNegocio.Create(STR_CLIENTE_CPF_INVALIDO); end; end; procedure TRegraCRUDCliente.ValidaDataNascimento(Data: TDate); begin if (Data >= Now) then begin raise EValidacaoNegocio.Create(STR_CLIENTE_DATA_NASCIMENTO_INVALIDA); end; end; procedure TRegraCRUDCliente.ValidaEmail(const csEmail: String); begin if not ValidateEmail(csEmail) then begin raise EValidacaoNegocio.Create(STR_CLIENTE_EMAIL_INVALIDO); end; end; procedure TRegraCRUDCliente.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; ValidaNome(TCLIENTE(coENTIDADE).NOME); ValidaNomeDuplicidade(TCLIENTE(coENTIDADE).NOME, TCLIENTE(coENTIDADE).ID); ValidaEmail(TCLIENTE(coENTIDADE).EMAIL); ValidaCPF(TCLIENTE(coENTIDADE).CPF); ValidaDataNascimento(TCLIENTE(coENTIDADE).DATA_NASCIMENTO); end; procedure TRegraCRUDCliente.ValidaNome(const csNome: String); begin if Trim(csNome) = EmptyStr then begin raise EValidacaoNegocio.Create(STR_CLIENTE_NOME_NAO_INFORMADO); end; end; procedure TRegraCRUDCliente.ValidaNomeDuplicidade(const csNome: String; const ciIdCLIENTE: Integer); var loCLIENTE: TCLIENTE; begin for loCLIENTE in TRepositorioCLIENTE(FRepositorioDB).RetornaTodos do begin if (Trim(loCLIENTE.NOME) = Trim(csNome)) and (loCLIENTE.ID <> ciIdCLIENTE) then begin raise EValidacaoNegocio.Create(STR_CLIENTE_NOME_JA_EXISTE); end; end; end; function TRegraCRUDCliente.ValidateEmail(const emailAddress: string): Boolean; var RegEx: TRegEx; begin RegEx := TRegex.Create('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$'); Result := RegEx.Match(emailAddress).Success; end; end.
unit FreeOTFEExplorerfrmOverwritePrompt; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SDUForms, FreeOTFEExplorerSettings, // Required for TMoveDeletionMethod FreeOTFEExplorerfrmMain, ExtCtrls; // Required for TFExplOperation type TfrmOverwritePrompt = class(TSDUForm) Label1: TLabel; pbOK: TButton; pbCancel: TButton; gbMoveDeletionMethod: TRadioGroup; procedure rbLeaveAloneClick(Sender: TObject); procedure FormShow(Sender: TObject); private function GetSelected(): TMoveDeletionMethod; public procedure EnableDisableControls(); published property MoveDeletionMethod: TMoveDeletionMethod read GetSelected; end; implementation {$R *.dfm} uses SDUi18n, SDUGeneral, SDUDialogs; procedure TfrmOverwritePrompt.EnableDisableControls(); begin SDUEnableControl(pbOK, (MoveDeletionMethod <> mdmPrompt)); end; procedure TfrmOverwritePrompt.FormShow(Sender: TObject); const DEFAULT_METHOD = mdmDelete; var mdm: TMoveDeletionMethod; idx: integer; useIdx: integer; begin // Populate and set move deletion method gbMoveDeletionMethod.Items.Clear(); idx := -1; useIdx := -1; for mdm:=low(mdm) to high(mdm) do begin // Skip the obvious one! if (mdm = mdmPrompt) then begin continue; end; inc(idx); gbMoveDeletionMethod.Items.Add(MoveDeletionMethodTitle(mdm)); if (DEFAULT_METHOD = mdm) then begin useIdx := idx; end; end; gbMoveDeletionMethod.ItemIndex := useIdx; EnableDisableControls(); end; function TfrmOverwritePrompt.GetSelected(): TMoveDeletionMethod; var mdm: TMoveDeletionMethod; retval: TMoveDeletionMethod; begin // Decode move deletion method retval := mdmPrompt; for mdm:=low(mdm) to high(mdm) do begin if (MoveDeletionMethodTitle(mdm) = gbMoveDeletionMethod.Items[gbMoveDeletionMethod.ItemIndex]) then begin retval := mdm; break; end; end; Result := retval; end; procedure TfrmOverwritePrompt.rbLeaveAloneClick(Sender: TObject); begin EnableDisableControls(); end; END.